Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(plugins): 按 namespace 识别并隔离插件实例 (#5753)

fattycat93f1393143a5
diff --git a/apps/desktop/src/main/__tests__/githubSetupIpc.test.ts b/apps/desktop/src/main/__tests__/githubSetupIpc.test.ts
index 8b0160d906..80426d748e 100644
--- a/apps/desktop/src/main/__tests__/githubSetupIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/githubSetupIpc.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('../secrets/providerSecretStore', () => ({ readGhostSecret: vi.fn() }));
vi.mock('../maker-host/outbound-fetch', () => ({ outboundFetch: vi.fn() }));
vi.mock('../appSessionState', () => ({ activeOwnerScopeKey: () => 'test-owner' }));
@@ -8,10 +8,12 @@ const mocks = vi.hoisted(() => ({
start: vi.fn(),
invalidate: vi.fn(),
send: vi.fn(),
+ readToken: vi.fn(),
+ disposers: [] as Array<() => void>,
connected: undefined as undefined | (() => void),
}));
vi.mock('electron', () => ({
- app: { getPath: () => '/test/userData', once: vi.fn() },
+ app: { getPath: () => '/test/userData', once: (_event: string, dispose: () => void) => mocks.disposers.push(dispose) },
ipcMain: {
handle: (name: string, fn: (...args: any[]) => unknown) => mocks.handlers.set(name, fn),
},
@@ -22,7 +24,7 @@ vi.mock('electron', () => ({
vi.mock('../security/trustedAppRenderer', () => ({ assertTrustedAppRendererEvent: mocks.guard }));
vi.mock('../git-context/ghBinary', () => ({ configureManagedGhRoot: vi.fn() }));
vi.mock('../git-context/ghCliTokenSource', () => ({
- getSharedGhCliTokenSource: () => ({ invalidate: mocks.invalidate }),
+ getSharedGhCliTokenSource: () => ({ invalidate: mocks.invalidate, readToken: mocks.readToken }),
}));
vi.mock('../git-context/githubSetup', () => ({
createGithubSetup: (_root: string, connected: () => void) => {
@@ -31,8 +33,44 @@ vi.mock('../git-context/githubSetup', () => ({
},
}));
import { registerGithubSetupIpc } from '../git-context/githubSetupIpc';
+import { readGhostSecret } from '../secrets/providerSecretStore';
+import { outboundFetch } from '../maker-host/outbound-fetch';
+import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(readGhostSecret).mockReset();
+ vi.mocked(outboundFetch).mockReset();
+ mocks.readToken.mockResolvedValue(null);
+});
+afterEach(() => mocks.disposers.splice(0).forEach(dispose => dispose()));
describe('GitHub setup IPC boundary', () => {
+ it.each(['cindy-github', '_root__cindy-github'])(
+ 'verifies the PAT and refreshes connected windows for %s', async (instanceId) => {
+ const invalidate = vi.fn();
+ vi.mocked(readGhostSecret).mockImplementation((id) => id === instanceId ? 'synthetic-pat' : null);
+ vi.mocked(outboundFetch).mockResolvedValue(new Response('{"login":"test-user"}'));
+ registerGithubSetupIpc(invalidate);
+ const connection = mocks.handlers.get('git-context:github-setup:connection')!;
+ await expect(connection({})).resolves.toEqual({ status: 'connected', source: 'token', login: 'test-user' });
+ expect(outboundFetch).toHaveBeenCalledWith('https://api.github.com/user',
+ expect.objectContaining({ headers: expect.objectContaining({ Authorization: 'Bearer synthetic-pat' }) }));
+ getGhostSetupChangeBus().emit(instanceId, { source: 'secret', ref: 'github_pat' });
+ expect(invalidate).toHaveBeenCalledOnce();
+ expect(mocks.send).toHaveBeenCalledWith('git-context:github-connected');
+ },
+ );
+ it('does not verify or subscribe to a same-name enterprise credential', async () => {
+ const instanceId = '_ns__acme__cindy-github';
+ vi.mocked(readGhostSecret).mockImplementation((id) => id === instanceId ? 'synthetic-enterprise-pat' : null);
+ registerGithubSetupIpc(vi.fn());
+ const connection = mocks.handlers.get('git-context:github-setup:connection')!;
+ await expect(connection({})).resolves.toEqual({ status: 'missing' });
+ getGhostSetupChangeBus().emit(instanceId, { source: 'secret', ref: 'github_pat' });
+ expect(outboundFetch).not.toHaveBeenCalled();
+ expect(mocks.send).not.toHaveBeenCalled();
+ });
it('rejects untrusted callers and arbitrary payloads before invoking the installer', () => {
registerGithubSetupIpc(vi.fn());
const start = mocks.handlers.get('git-context:github-setup:start')!;
diff --git a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
index 2b7783d7cb..f2198672e3 100644
--- a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
+++ b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
@@ -200,6 +200,7 @@ describe('sidebarSettingsStore', () => {
});
afterEach(() => {
+ vi.restoreAllMocks();
fs.rmSync(harness.root, { recursive: true, force: true });
});
diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index d28ded90cc..5630860f42 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -38,6 +38,8 @@ import {
LOGIN_CAPTCHA_PARTITION,
} from '../../shared/webviewPartition';
import { getEffectiveAppShortcuts, type AppShortcutId } from '../../shared/appShortcuts';
+import * as appSessionState from '../appSessionState';
+import { resolveGhostMediaHandoverTarget } from '../cindy-brain/ghostMediaHandoverTargetTracker';
import {
BLANK_POPUP_WINDOW_WEB_PREFERENCES,
DEFERRED_POPUP_ROUTE_TIMEOUT_MS,
@@ -52,6 +54,7 @@ import {
authorizeGhostWebviewAttach,
hardenLoginCaptchaSession,
installGhostGuestNavigationHandlers,
+ installGhostMediaHandoverSource,
installBrowserGuestHandlers,
installDeferredPopupRouter,
installLoginCaptchaGuestHandlers,
@@ -338,7 +341,9 @@ describe('applyGhostWebviewHardening(意识面板 webview)', () => {
expect(authorizeGhostWebviewAttach(webPreferences, params, resolver)).toEqual({
id: 'same-ghost',
+ instanceId: 'same-ghost',
owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ isCurrent: expect.any(Function),
});
expect(resolver).toHaveBeenCalledWith(
'cindy-ghost-same-ghost',
@@ -352,6 +357,39 @@ describe('applyGhostWebviewHardening(意识面板 webview)', () => {
expect('allowpopups' in params).toBe(false);
});
+ it('retains the verified physical instance separately from the URL host', () => {
+ const resolver = vi.fn(() => ({
+ ghost: {
+ manifest: { id: 'helper' }, namespace: 'acme',
+ dir: '/plugins/_ns/acme/helper',
+ },
+ partition: 'cindy-ghost-owner:cloud:opaque-owner-a:_ns__acme__helper',
+ owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ })) as never;
+ expect(authorizeGhostWebviewAttach({}, {
+ partition: 'cindy-ghost-_ns__acme__helper',
+ src: 'cindy-ghost://helper/panel.html',
+ }, resolver)).toEqual({
+ id: 'helper', instanceId: '_ns__acme__helper',
+ owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ isCurrent: expect.any(Function),
+ });
+ });
+
+ it('keeps a stamped installation on its verified physical root key', () => {
+ const resolver = vi.fn(() => ({
+ ghost: { manifest: { id: 'helper' }, namespace: 'acme', dir: '/plugins/helper' },
+ partition: 'cindy-ghost-owner:cloud:opaque-owner-a:_ns__acme__helper',
+ owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ })) as never;
+ expect(authorizeGhostWebviewAttach({}, {
+ partition: 'cindy-ghost-_ns__acme__helper', src: 'cindy-ghost://helper/panel.html',
+ }, resolver)).toEqual({
+ id: 'helper', instanceId: 'helper', owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ isCurrent: expect.any(Function),
+ });
+ });
+
it('Main 解析或协议注册异常时不核准 attach', () => {
const params: Record<string, string> = {
src: 'cindy-ghost://same-ghost/panel.html',
@@ -529,8 +567,113 @@ describe('installLoginCaptchaGuestHandlers(captcha guest 导航闸)', () => {
});
});
+describe('Ghost handover attach lifetime', () => {
+ const uri = 'cindy-ghost://helper/preview/' + 'a'.repeat(64) + '.png';
+
+ afterEach(() => vi.restoreAllMocks());
+
+ function makeSource(instanceId = '_ns__acme__helper') {
+ const host = Object.assign(new EventEmitter(), { id: 10, isDestroyed: vi.fn(() => false) });
+ const guest = Object.assign(new EventEmitter(), {
+ id: 20, isDestroyed: vi.fn(() => false),
+ executeJavaScript: vi.fn().mockResolvedValue(undefined),
+ setWindowOpenHandler: vi.fn(),
+ });
+ let current = true;
+ installGhostGuestNavigationHandlers(
+ host as unknown as WebContents, guest as unknown as WebContents, 'helper', () => true,
+ { preview: vi.fn(), external: vi.fn() }, instanceId, () => current,
+ );
+ const ready = () => {
+ guest.emit('dom-ready');
+ const script = guest.executeJavaScript.mock.lastCall?.[0] as string;
+ return JSON.parse(script.slice(script.lastIndexOf(',') + 1, -1)) as string;
+ };
+ return { host, guest, ready, expire: () => { current = false; } };
+ }
+
+ it('wires registration into the real guest handlers and retires a reloaded guest token', () => {
+ const source = makeSource();
+ const token = source.ready();
+ expect(resolveGhostMediaHandoverTarget(token, uri)).toEqual({ ghostId: 'helper', instanceId: '_ns__acme__helper' });
+ const replacement = source.ready();
+ expect(replacement).not.toBe(token);
+ expect(resolveGhostMediaHandoverTarget(token, uri)).toBeNull();
+ expect(resolveGhostMediaHandoverTarget(replacement, uri)?.instanceId).toBe('_ns__acme__helper');
+ source.guest.emit('destroyed');
+ expect(resolveGhostMediaHandoverTarget(replacement, uri)).toBeNull();
+ expect(source.host.listenerCount('destroyed')).toBe(0);
+ });
+
+ it.each(['destroyed', 'render-process-gone', 'did-navigate'])('revokes the source on guest %s', (event) => {
+ const source = makeSource();
+ const token = source.ready();
+ source.guest.emit(event, {}, 'cindy-ghost://helper/panel.html', false, true);
+ expect(resolveGhostMediaHandoverTarget(token, uri)).toBeNull();
+ source.guest.emit('destroyed');
+ });
+
+ it('does not retire a source on subframe or same-document navigation', () => {
+ const source = makeSource();
+ const token = source.ready();
+ source.guest.emit('did-start-navigation', {}, 'cindy-ghost://helper/panel.html', true, true);
+ source.guest.emit('did-start-navigation', {}, 'cindy-ghost://helper/frame.html', false, false);
+ const navigation = { preventDefault: vi.fn() };
+ source.guest.emit('will-navigate', navigation, uri);
+ expect(navigation.preventDefault).toHaveBeenCalledOnce();
+ expect(resolveGhostMediaHandoverTarget(token, uri)?.instanceId).toBe('_ns__acme__helper');
+ source.guest.emit('destroyed');
+ });
+
+ it('revokes a source when its host closes or receipt expires', () => {
+ const source = makeSource();
+ const token = source.ready();
+ source.expire();
+ expect(resolveGhostMediaHandoverTarget(token, uri)).toBeNull();
+ source.guest.emit('dom-ready');
+ expect(source.guest.executeJavaScript).toHaveBeenCalledOnce();
+ source.guest.emit('destroyed');
+ const other = makeSource('helper');
+ const rootToken = other.ready();
+ other.host.emit('destroyed');
+ expect(resolveGhostMediaHandoverTarget(rootToken, uri)).toBeNull();
+ other.guest.emit('destroyed');
+ });
+
+ it('rechecks the Main attach receipt and owner generation, including A to B to A', () => {
+ const session = vi.spyOn(appSessionState, 'getActiveAppSession').mockReturnValue({ mode: 'cloud', dataOwnerId: 'owner-a', generation: 1 });
+ const approved = {
+ ghost: { manifest: { id: 'helper', version: '1.0.0' }, dir: '/plugins/_ns/acme/helper', namespace: 'acme', approval: { state: 'approved', revision: 'receipt-a' } },
+ partition: 'cindy-ghost-owner:cloud:owner-a:_ns__acme__helper',
+ owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ };
+ const resolver = vi.fn(() => approved);
+ const attach = authorizeGhostWebviewAttach({}, { partition: 'cindy-ghost-_ns__acme__helper', src: 'cindy-ghost://helper/panel.html' }, resolver as never);
+ expect(attach?.isCurrent()).toBe(true);
+ resolver.mockReturnValue({ ...approved, ghost: { ...approved.ghost, approval: { state: 'approved', revision: 'receipt-b' } } });
+ expect(attach?.isCurrent()).toBe(false);
+ resolver.mockReturnValue(approved);
+ session.mockReturnValue({ mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 });
+ expect(attach?.isCurrent()).toBe(false);
+ session.mockReturnValue({ mode: 'cloud', dataOwnerId: 'owner-a', generation: 3 });
+ expect(attach?.isCurrent()).toBe(false);
+ });
+
+ it('revokes tokens when script injection fails', async () => {
+ const host = Object.assign(new EventEmitter(), { isDestroyed: () => false });
+ const guest = Object.assign(new EventEmitter(), { isDestroyed: () => false, executeJavaScript: vi.fn().mockRejectedValue(new Error('gone')) });
+ installGhostMediaHandoverSource(host as unknown as WebContents, guest as unknown as WebContents, { ghostId: 'helper', instanceId: 'helper' }, () => true);
+ guest.emit('dom-ready');
+ const script = guest.executeJavaScript.mock.lastCall?.[0] as string;
+ const token = JSON.parse(script.slice(script.lastIndexOf(',') + 1, -1)) as string;
+ await Promise.resolve();
+ expect(resolveGhostMediaHandoverTarget(token, uri)).toBeNull();
+ guest.emit('destroyed');
+ });
+});
+
describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用导航链)', () => {
- function makeHarness() {
+ function makeHarness(instanceId?: string) {
let openHandler: (() => { action: 'deny' }) | null = null;
const guest = new EventEmitter() as EventEmitter & {
setWindowOpenHandler: ReturnType<typeof vi.fn>;
@@ -538,8 +681,9 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
guest.setWindowOpenHandler = vi.fn((handler) => {
openHandler = handler;
});
- const host = { id: 10 } as unknown as WebContents;
+ const host = Object.assign(new EventEmitter(), { id: 10 }) as unknown as WebContents;
let ownerActive = true;
+ let attachCurrent = true;
const gesture = vi.fn();
const preview = vi.fn();
const external = vi.fn();
@@ -549,6 +693,8 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
'xd-sites',
() => ownerActive,
{ gesture, preview, external },
+ instanceId,
+ () => attachCurrent,
);
return {
guest,
@@ -559,10 +705,26 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
setOwnerActive: (active: boolean) => {
ownerActive = active;
},
+ setAttachCurrent: (current: boolean) => { attachCurrent = current; },
getOpenHandler: () => openHandler,
};
}
+ it('does not navigate or record a gesture after its attached instance is replaced', () => {
+ const harness = makeHarness('_ns__acme__xd-sites');
+ const url = 'https://example.invalid/control';
+ harness.guest.emit('will-navigate', { preventDefault: vi.fn() }, url);
+ expect(harness.external).toHaveBeenCalledTimes(1);
+ const isCurrent = harness.external.mock.calls[0]![4] as () => boolean;
+ expect(isCurrent()).toBe(true);
+ harness.setAttachCurrent(false);
+ expect(isCurrent()).toBe(false);
+ harness.guest.emit('will-navigate', { preventDefault: vi.fn() }, url);
+ harness.guest.emit('before-input-event', {}, { type: 'mouseDown' });
+ expect(harness.external).toHaveBeenCalledTimes(1);
+ expect(harness.gesture).not.toHaveBeenCalled();
+ });
+
it('普通 HTTPS <a> 的 will-navigate 被拦下并带真实 host/guest 交给外链处理', () => {
const harness = makeHarness();
const event = { preventDefault: vi.fn() };
@@ -576,10 +738,22 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
harness.host,
harness.guest,
expect.any(Function),
+ undefined,
);
expect(harness.preview).not.toHaveBeenCalled();
});
+ it('carries the attached organization instance through external navigation and gestures', () => {
+ const harness = makeHarness('_ns__acme__xd-sites');
+ harness.guest.emit('will-navigate', { preventDefault: vi.fn() }, 'https://example.com/');
+ expect(harness.external).toHaveBeenCalledWith(
+ 'xd-sites', 'https://example.com/', harness.host, harness.guest,
+ expect.any(Function), '_ns__acme__xd-sites',
+ );
+ harness.guest.emit('before-mouse-event', {}, { type: 'mouseDown' });
+ expect(harness.gesture).toHaveBeenCalledWith('_ns__acme__xd-sites');
+ });
+
it('预览仍走既有处理,同 Ghost 协议普通页面仍允许原位导航', () => {
const harness = makeHarness();
const previewEvent = { preventDefault: vi.fn() };
@@ -594,6 +768,17 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
expect(allowEvent.preventDefault).not.toHaveBeenCalled();
});
+ it('passes the verified instance to preview without changing the manifest URL host', () => {
+ const harness = makeHarness('_ns__xd__xd-sites');
+ const url = 'cindy-ghost://xd-sites/preview/' + 'a'.repeat(64) + '.png';
+ const event = { preventDefault: vi.fn() };
+ harness.guest.emit('will-navigate', event, url);
+ expect(harness.preview).toHaveBeenCalledExactlyOnceWith(
+ 'xd-sites', url, harness.host, harness.guest, expect.any(Function), '_ns__xd__xd-sites',
+ );
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ });
+
it('HTTP/自定义协议被静默拦下,不进入外链处理', () => {
const harness = makeHarness();
for (const url of ['http://workers.xd.team/', 'custom://workers.xd.team/']) {
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 8210967337..05b0842c63 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1096,6 +1096,7 @@ import {
suspendAllGhosts,
waitForGhostMutations,
} from './cindy-brain/index.js';
+import { installedGhostStoragePart } from '../shared/pluginIdentity.js';
import { setCodexImageAuthBinding } from './cindy-brain/codexImageAuthBinding.js';
import { listActiveClaudeBackgroundActivitySessions } from './maker-host/claude-session-background-activity.js';
import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';
@@ -2274,14 +2275,14 @@ const ghostPanelWindowsController = new GhostPanelWindowsController({
createWindow: (ghostId) => {
const ghost = getGhostManager()
.list()
- .find((g) => g.manifest.id === ghostId);
+ .find((g) => installedGhostStoragePart(g) === ghostId);
const title = ghost?.manifest.panel?.title ?? ghost?.manifest.name ?? ghostId;
return createGhostPanelWindow(ghostId, title);
},
isGhostDetachable: (ghostId) => {
const ghost = getGhostManager()
.list()
- .find((g) => g.manifest.id === ghostId);
+ .find((g) => installedGhostStoragePart(g) === ghostId);
return (
ghost !== undefined &&
ghost.enabled !== false &&
@@ -9067,6 +9068,14 @@ app.on('ready', async () => {
}
return;
}
+ if (getActiveAppSession().dataOwnerId === userId) {
+ void getGhostManager().retryInterruptedMutationsAfterDbReady().catch((error) => {
+ dbClientLog.warn('ghost mutation recovery after DB readiness failed', {
+ userId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
checkDatabaseSizeWarningAtStartup();
// Bot recovery is owner-scoped and must start only after DbClient
// takeover. registerMakerIpc also invokes this once its services exist,
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 7fba7b0fe4..eac71b102e 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -12,12 +12,33 @@ import {
PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES,
} from '@cindy/plugin-protocol';
+import { authorDeclaredNamespaceReason, isValidPluginNamespace } from '@cindy/plugin-protocol';
+import {
+ createPluginLogicalIdentity,
+ findConflictingGhostCommand,
+ findInstalledGhostByIdentity,
+ findInstalledGhostByInstanceId,
+ hasDeliveryNamespace,
+ installedGhostStoragePart,
+ isValidPluginInstallRelId,
+ parsePluginInstallRelId,
+ parsePluginStoragePart,
+ PLUGIN_NS_INSTALL_ROOT,
+ PLUGIN_ROOT_INSTALL_DIR,
+ PLUGIN_ROOT_INSTALL_ROOT,
+ pluginNewInstallRelId,
+ pluginInstanceInstallRelId,
+ pluginInstallStoragePart,
+ pluginInstallRelId,
+ pluginStoragePart,
+} from '../../shared/pluginIdentity.js';
+
+
import {
GHOST_MANIFEST_FILE,
GHOST_MANIFEST_MAX_BYTES,
GHOST_LOCALE_MAX_BYTES,
GHOST_ICON_MAX_BYTES,
- GHOST_INSTALL_MANIFEST_MAX_BYTES,
GHOST_MANUAL_ENTRY_FILE,
GHOST_MANUAL_MD_MAX_BYTES,
GHOST_SKILL_MD_MAX_BYTES,
@@ -50,10 +71,40 @@ import {
import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
import { checkSkillMdConsistency } from './skillSlot.js';
import {
+ createPluginInstanceRegistryStore,
+ findBlockingInstance,
+ findInstanceByContentRelId,
+ findReusableInstance,
+ pluginInstanceRegistryPath,
+ type InstanceConfirmationEvidence,
+ type PluginInstanceCensus,
+ type PluginInstanceReceiptFact,
+ type PluginInstanceRecord,
+ type PluginInstanceRegistry,
+ type PluginInstanceSource,
+} from './pluginInstanceRegistry.js';
+import {
+ type NamespaceClassification,
+ type NamespaceMigrationBasis,
+} from './pluginNamespaceMigration.js';
+import { confirmUnconfirmedInstances } from './pluginInstanceConfirmation.js';
+import {
+ commitPendingNamespaceMigration,
+ reconcilePendingNamespaceMigrations,
+ type NamespaceCommitReceiptSnapshot,
+} from './pluginNamespaceMigration.js';
+import {
+ collectRootInstallCensusCandidates,
+ PluginInstanceRegistryService,
+} from './pluginInstanceRegistryService.js';
+import {
+ assertManagedPluginParentSync,
createGhostInstallReceipt,
effectiveInstallOrigin,
+ legacyFirstPartyEligibilityAfterUpdate,
GhostInstallReceiptStore,
hashApprovedSkillContent,
+ isValidGhostSourceStateArchiveId,
readLegacyInstallTrust,
type GhostInstallReceipt,
type GhostInstallReceiptReadResult,
@@ -123,6 +174,12 @@ function isZipSymbolicLink(entry: JSZip.JSZipObject): boolean {
return isZipSymbolicLinkMode(entry.unixPermissions);
}
+function relIdFromUpdatingBackupName(name: string): string | null {
+ const match = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(name);
+ if (!match) return null;
+ return pluginInstanceInstallRelId(match[1]);
+}
+
/** 只有宿主安装/播种路径可以写入的 Cindy 官方身份。 */
export const CINDY_OFFICIAL_GHOST_TRUST: GhostTrustInfo = Object.freeze({
level: 'cindy-official',
@@ -203,10 +260,44 @@ export interface GhostManagerOptions {
*/
isTrustedBundledId?: (id: string) => boolean;
/**
- * tokenBroker 装入闸。缺省只认静态官方前缀(测试夹具)。生产接线问
- * first-party 判据,官方前缀命中仍走静态表。
+ * tokenBroker 装入闸。缺省拒绝(测试夹具须显式注入)。生产接线问
+ * first-party 判据:名称前缀不构成资格。
*/
isTokenBrokerAuthorized?: (manifest: GhostManifest) => boolean;
+ /** Classify a pending pre-namespace install using market/org facts. */
+ classifyPendingNamespace?: (
+ ghostId: string,
+ marketSyncCompleted?: boolean,
+ ) => NamespaceClassification;
+ /**
+ * Facts that may move an unconfirmed instance back to confirmed.
+ * Undefined or null means the facts are not ready. This is not a census.
+ */
+ readUnconfirmedConfirmationEvidence?: (
+ record: PluginInstanceRecord,
+ ) => InstanceConfirmationEvidence | null | undefined;
+ captureLegacyFirstPartyEligibility?: (ghostId: string, approvedPackageSha256: string) => boolean;
+ /** True when runtime/OAuth/install work should delay a first-time namespace stamp. */
+ isNamespaceMigrationBusy?: (ghostId: string) => boolean;
+ /**
+ * Market plugin id for this exact instance. A same-name install in another
+ * namespace must not be returned.
+ */
+ marketIdentityForInstance?: (instance: {
+ ghostId: string;
+ contentRelId: string;
+ namespace: string | null;
+ packageSha256: string | null;
+ }) => { pluginId: string } | null;
+ canResumePendingResidentOffline?: (ghostId: string) => boolean;
+ onResumePendingResidentOffline?: (ghost: InstalledGhost) => void;
+ preparePendingResidentForMigration?: (ghostId: string) => Promise<boolean>;
+ onPendingResidentMigrationDeferred?: (ghostId: string) => void;
+ onPendingResidentMigrationSettled?: (ghostId: string, committed: boolean) => void;
+ /** Best-effort side effect after the receipt and registry census commit. */
+ onNamespaceCommitted?: (ghostId: string, namespace: string | null) => void;
+ beforeNamespaceCommit?: (ghostId: string, namespace: string | null) => void;
+ onArchiveSourceState?: (fromPart: string, archivePart: string) => Promise<void>;
/** sourceDir 是否就是该 id 的随包只读种子目录,而非任意本机可变目录。 */
isTrustedBundledSource?: (id: string, sourceDir: string) => boolean;
/** Persist the user's builtin-uninstall intent before approval/content removal. */
@@ -229,6 +320,7 @@ export type InstallRejection =
| { code: 'not-installed'; reason: string }
| { code: 'command-conflict'; reason: string }
| { code: 'state-changed'; reason: string }
+ | { code: 'namespace-migration-pending'; reason: string }
| {
code: 'io';
reason: string;
@@ -525,6 +617,33 @@ export class GhostManager {
private readonly untrustedApprovals = new Set<string>();
/** Owner namespaces whose mutation journal could not be authoritatively scanned. */
private readonly recoveryBlockedApprovalNamespaces = new Set<string>();
+ private readonly pendingRecoverySideEffects = new Set<Promise<void>>();
+ private readonly pendingMutationRecoveries = new Set<string>();
+ private recoveryRetry: Promise<void> | null = null;
+ private readonly instanceRegistryService = new PluginInstanceRegistryService({
+ ensureOwner: () => this.ensureCurrentOwnerContextSync(),
+ registryStore: () => this.instanceRegistryStore(),
+ listContentEntries: () => this.listContentEntries(),
+ receiptFact: (relId) => this.receiptFact(relId),
+ censusCandidates: () => collectRootInstallCensusCandidates({
+ contentRoot: this.contentRootDir(),
+ readApproval: (relId) => this.readApproval(relId),
+ listPendingMutationIds: () => this.receiptStore.listPendingMutationIdsSync(),
+ readPendingMutation: (id) => this.receiptStore.readPendingMutationSync(id),
+ readRecoveryApproval: (id) => this.receiptStore.readForRecovery(id),
+ recoveryEntryKind: (absPath) => this.recoveryEntryKind(absPath),
+ }),
+ readApproval: (relId) => this.readApproval(relId),
+ captureInstalledLegacy: (ghostId, packageSha256) =>
+ this.options.captureLegacyFirstPartyEligibility?.(ghostId, packageSha256) === true,
+ recordLegacyEligibility: (relId, revision) => {
+ this.receiptStore.captureLegacyFirstPartyEligibilitySync(relId, revision);
+ },
+ marketIdentityForInstance: (instance) => this.options.marketIdentityForInstance?.(instance) ?? null,
+ log: {
+ warn: (message, meta) => { this.options.log?.warn(message, meta); },
+ },
+ });
/**
* 进程内隔离集合的键:以**当前 owner 的状态根**为命名空间。集合是 manager 级
@@ -577,6 +696,339 @@ export class GhostManager {
return this.activeMutationContext?.contentRoot ?? this.resolveContentRoot();
}
+ private contentPath(relId: string): string {
+ const root = this.contentRootDir();
+ const parts = relId.split('/');
+ if (parts.length > 1) {
+ let parent = root;
+ for (const part of parts.slice(0, -1)) {
+ parent = path.join(parent, part);
+ try {
+ if (classifyGhostDirEntrySync(parent) !== 'directory') {
+ throw new Error('plugin namespace parent is not a real directory');
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ }
+ return path.join(root, ...parts);
+ }
+
+ private instanceRegistryStore() {
+ return createPluginInstanceRegistryStore(pluginInstanceRegistryPath(this.stateRootDir()));
+ }
+
+ private listContentEntries(): Array<{ relId: string; dir: string }> {
+ const root = this.contentRootDir();
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(root, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const listed = this.listManagedInstallDirs(root);
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || entry.name === PLUGIN_NS_INSTALL_ROOT) continue;
+ const dir = path.join(root, entry.name);
+ try {
+ if (classifyGhostDirEntrySync(dir) !== 'directory') continue;
+ } catch {
+ continue;
+ }
+ if (!isValidGhostId(entry.name)) {
+ this.options.log?.warn('ghost dir skipped: invalid directory id', { dir });
+ continue;
+ }
+ listed.push({ relId: entry.name, dir });
+ }
+ return listed;
+ }
+
+ private receiptFact(relId: string): PluginInstanceReceiptFact | null | undefined {
+ const recovery = this.receiptStore.readForRecovery(relId);
+ if (recovery.state === 'invalid' || recovery.state === 'unreadable') return undefined;
+ if (recovery.state !== 'approved') return null;
+ const receipt = recovery.receipt;
+ return {
+ ghostId: receipt.id,
+ hasNamespace: hasDeliveryNamespace(receipt),
+ namespace: hasDeliveryNamespace(receipt) ? receipt.namespace ?? null : null,
+ revision: receipt.revision,
+ packageSha256: receipt.packageSha256 ?? null,
+ ...(receipt.installOrigin === 'agent-forge' ? { installOrigin: 'agent-forge' } : {}),
+ };
+ }
+
+ /** Load the instance registry. A corrupt file is not rewritten and not used to invent keys. */
+ private syncInstanceRegistry(): PluginInstanceRegistry {
+ return this.instanceRegistryService.sync();
+ }
+
+ private instanceRecordForAddress(id: string): PluginInstanceRecord | null {
+ return this.instanceRegistryService.recordForAddress(id);
+ }
+
+
+ private instanceProjection(relId: string, ghostId: string): {
+ instanceKey?: string;
+ namespace?: string | null;
+ namespaceState?: PluginInstanceRecord['namespaceState'];
+ } {
+ const registry = this.instanceRegistryService.current();
+ if (this.instanceRegistryService.isBlocked() || !registry) return {};
+ const record = findInstanceByContentRelId(registry, relId);
+ if (!record || record.ghostId !== ghostId) return {};
+ return {
+ instanceKey: record.instanceKey,
+ namespaceState: record.namespaceState,
+ ...(record.namespaceState === 'confirmed' || record.namespaceState === 'unconfirmed'
+ ? { namespace: record.namespace } : {}),
+ };
+ }
+
+ private storageKeyForContent(relId: string): string {
+ const record = this.instanceRegistryService.isBlocked() ? undefined : findInstanceByContentRelId(this.syncInstanceRegistry(), relId);
+ return record?.instanceKey ?? pluginInstallStoragePart(relId);
+ }
+
+ private planInstancePlacement(
+ ghostId: string,
+ namespace: string | null,
+ source?: PluginInstanceSource,
+ pluginId?: string | null,
+ ):
+ | { kind: 'blocked'; reason: string }
+ | { kind: 'ok'; instanceKey: string; relId: string } {
+ const registry = this.syncInstanceRegistry();
+ const relId = pluginNewInstallRelId(createPluginLogicalIdentity(namespace, ghostId));
+ const instanceKey = pluginInstallStoragePart(relId);
+ if (!this.instanceRegistryService.isBlocked()) {
+ const blocker = findBlockingInstance(registry, ghostId, namespace);
+ if (blocker && blocker.namespaceState !== 'pending') {
+ return { kind: 'blocked', reason: '意识 ' + ghostId + ' 已装入' };
+ }
+ const reusable = findReusableInstance(registry, { ghostId, namespace, source, pluginId });
+ if (reusable) return { kind: 'ok', instanceKey: reusable.instanceKey, relId: reusable.contentRelId };
+ }
+ return { kind: 'ok', instanceKey, relId };
+ }
+
+ /**
+ * Pending is only the upgrade census. A missing ledger means this process
+ * has not recorded the census yet, so bare directories present now are it.
+ * Once the ledger exists, a directory is pending only while its entry is.
+ */
+
+ private publishInstalledInstance(record: PluginInstanceRecord): void {
+ try {
+ this.instanceRegistryService.publish(record);
+ } catch (error) {
+ this.options.log?.warn('plugin instance registry publish failed after install commit', {
+ instanceKey: record.instanceKey,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ private confirmRecordedNamespace(
+ relOrKey: string,
+ namespace: string | null,
+ revision: string,
+ packageSha256: string | null,
+ ): boolean {
+ try {
+ return this.instanceRegistryService.confirmNamespace(relOrKey, namespace, revision, packageSha256);
+ } catch (error) {
+ // Receipt is already committed. A registry write failure must not turn
+ // that success into a migration error; the next list() adopts the row.
+ this.options.log?.warn('plugin instance registry confirm failed after namespace commit', {
+ instanceKey: relOrKey,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return true;
+ }
+ }
+
+
+ private persistedNamespaceFields(
+ opts: { namespace?: string | null },
+ existing: { namespace?: string | null } | null,
+ ): { namespace: string | null } | Record<string, never> {
+ if (hasDeliveryNamespace(opts)) {
+ return { namespace: opts.namespace ?? null };
+ }
+ if (existing && hasDeliveryNamespace(existing)) {
+ return { namespace: existing.namespace };
+ }
+ return existing === null ? { namespace: null } : {};
+ }
+
+
+ ensureNamespaceMigrationCensus(): PluginInstanceCensus | null {
+ return this.instanceRegistryService.ensureCensus();
+ }
+
+ /** True after a corrupt registry was quarantined. Market placement must wait. */
+ isInstanceRegistryBlocked(): boolean {
+ return this.instanceRegistryService.isBlocked();
+ }
+
+ private async resolvePendingNamespaceInstall(
+ ghostId: string,
+ requestedNamespace: string | null,
+ ): Promise<{ kind: 'proceed' } | { kind: 'already-installed' } | { kind: 'wait'; reason: string }> {
+ const registry = this.syncInstanceRegistry();
+ if (!this.instanceRegistryService.isBlocked()) {
+ const blocker = findBlockingInstance(registry, ghostId, requestedNamespace);
+ if (blocker?.namespaceState === 'pending') {
+ return { kind: 'wait', reason: 'namespace migration is pending' };
+ }
+ if (blocker) return { kind: 'already-installed' };
+ }
+ return { kind: 'proceed' };
+ }
+
+ async reconcilePendingRootNamespaces(marketSyncCompleted: boolean): Promise<void> {
+ await reconcilePendingNamespaceMigrations({
+ ensureCensus: () => this.ensureNamespaceMigrationCensus(),
+ ownerContextKey: () => this.currentOwnerContextKey(),
+ preparePendingResident: this.options.preparePendingResidentForMigration,
+ onPendingResidentDeferred: this.options.onPendingResidentMigrationDeferred,
+ onPendingResidentMigrationSettled: this.options.onPendingResidentMigrationSettled,
+ readApproval: (ghostId) => this.readApproval(ghostId),
+ classify: this.options.classifyPendingNamespace,
+ commit: (ghostId, namespace, basis, expectedReceipt) =>
+ this.commitPendingNamespace(ghostId, namespace, basis, expectedReceipt),
+ confirmUnconfirmed: () => this.confirmUnconfirmedInstances(),
+ log: this.options.log,
+ }, marketSyncCompleted);
+ }
+
+
+ private async confirmUnconfirmedInstances(): Promise<void> {
+ await confirmUnconfirmedInstances({
+ readEvidence: this.options.readUnconfirmedConfirmationEvidence,
+ isBlocked: () => this.instanceRegistryService.isBlocked(),
+ sync: () => this.syncInstanceRegistry(),
+ ownerContextKey: () => this.currentOwnerContextKey(),
+ readApproval: (relId) => this.readApproval(relId),
+ log: this.options.log,
+ runExclusive: (body) => this.runExclusiveMutation(body),
+ contentPath: (relId) => this.contentPath(relId),
+ writeReceipt: (relId, receipt) => this.receiptStore.write(receipt, {
+ skillSourceDir: this.contentPath(relId),
+ requireSkillSnapshot: false,
+ relId,
+ }),
+ writeRegistry: (registry) => {
+ this.instanceRegistryStore().write(registry);
+ this.instanceRegistryService.replaceCache(registry);
+ },
+ });
+ }
+
+ resumePendingResidentsOffline(): void {
+ const ledger = this.ensureNamespaceMigrationCensus();
+ if (!ledger || !this.options.canResumePendingResidentOffline ||
+ !this.options.onResumePendingResidentOffline) return;
+ const ghosts = this.list();
+ for (const ghost of ghosts) {
+ const ghostId = ghost.manifest.id;
+ if (ghost.dir !== this.contentPath(ghostId) ||
+ ghost.namespaceState !== 'pending' || !ghost.enabled ||
+ ghost.approval.state !== 'approved' || this.hasPendingMutationJournal(ghostId)) continue;
+ const approval = this.readApproval(ghostId);
+ if (approval.state !== 'approved' || hasDeliveryNamespace(approval.receipt)) continue;
+ if (this.options.canResumePendingResidentOffline(ghostId)) {
+ this.options.onResumePendingResidentOffline(ghost);
+ }
+ }
+ }
+
+ async commitPendingRootNamespace(
+ ghostId: string,
+ basis: NamespaceMigrationBasis,
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
+ return this.commitPendingNamespace(ghostId, null, basis);
+ }
+
+ async commitPendingNamespace(
+ ghostId: string,
+ namespace: string | null,
+ basis: NamespaceMigrationBasis,
+ expectedReceipt?: NamespaceCommitReceiptSnapshot,
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
+ return this.runExclusiveMutation(() =>
+ this.commitPendingNamespaceUnlocked(ghostId, namespace, basis, expectedReceipt),
+ );
+ }
+
+ private async commitPendingNamespaceUnlocked(
+ ghostId: string,
+ namespace: string | null,
+ basis: NamespaceMigrationBasis,
+ expectedReceipt?: NamespaceCommitReceiptSnapshot,
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
+ return commitPendingNamespaceMigration({
+ ownerContextKey: () => this.currentOwnerContextKey(),
+ ensureCensus: () => this.ensureNamespaceMigrationCensus(),
+ readApproval: (id) => this.readApproval(id),
+ hasPendingMutationJournal: (id) => this.hasPendingMutationJournal(id),
+ isNamespaceMigrationBusy: (id) => this.options.isNamespaceMigrationBusy?.(id) === true,
+ beforeNamespaceCommit: (id, committedNamespace) => {
+ this.options.beforeNamespaceCommit?.(id, committedNamespace);
+ },
+ writeReceiptNamespace: async (id, receipt, committedNamespace) => {
+ await this.receiptStore.write(
+ { ...receipt, namespace: committedNamespace },
+ { skillSourceDir: this.contentPath(id), requireSkillSnapshot: false, relId: id },
+ );
+ },
+ onNamespaceCommitted: (id, committedNamespace) => {
+ this.options.onNamespaceCommitted?.(id, committedNamespace);
+ },
+ confirmRecordedNamespace: (id, committedNamespace, revision, packageSha256) =>
+ this.confirmRecordedNamespace(id, committedNamespace, revision, packageSha256),
+ notifyChanged: () => { this.options.onChanged?.(this.list()); },
+ }, ghostId, namespace, basis, expectedReceipt);
+ }
+
+ private listManagedInstallDirs(root: string): Array<{ relId: string; dir: string }> {
+ const listed: Array<{ relId: string; dir: string }> = [];
+ const managedRoot = path.join(root, PLUGIN_NS_INSTALL_ROOT);
+ let parents: string[];
+ try {
+ if (classifyGhostDirEntrySync(managedRoot) !== 'directory') return listed;
+ parents = fs.readdirSync(managedRoot)
+ .filter((namespace) => namespace === PLUGIN_ROOT_INSTALL_DIR || isValidPluginNamespace(namespace))
+ .map((namespace) => PLUGIN_NS_INSTALL_ROOT + '/' + namespace);
+ } catch {
+ return listed;
+ }
+ for (const parent of parents) {
+ const parentDir = path.join(root, ...parent.split('/'));
+ let entries: string[];
+ try {
+ if (classifyGhostDirEntrySync(parentDir) !== 'directory') continue;
+ entries = fs.readdirSync(parentDir);
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ const relId = parent + '/' + entry;
+ if (!parsePluginInstallRelId(relId)) continue;
+ const dir = path.join(parentDir, entry);
+ try {
+ if (classifyGhostDirEntrySync(dir) === 'directory') listed.push({ relId, dir });
+ } catch {
+ continue;
+ }
+ }
+ }
+ return listed;
+ }
+
private stateRootDir(): string {
return this.activeMutationContext?.stateRoot ?? this.resolveStateRoot();
}
@@ -638,9 +1090,33 @@ export class GhostManager {
if (next === this.ownerContextKey) return;
this.assertDisjointRoots(this.resolveContentRoot(), this.resolveStateRoot());
this.ownerContextKey = next;
+ this.instanceRegistryService.clear();
this.recoverInterruptedMutationsSync();
}
+ retryInterruptedMutationsAfterDbReady(): Promise<void> {
+ if (this.recoveryRetry) return this.recoveryRetry;
+ const ownerContextKey = this.currentOwnerContextKey();
+ const retry = (async () => {
+ await Promise.allSettled([...this.pendingRecoverySideEffects]);
+ if (this.currentOwnerContextKey() !== ownerContextKey) return;
+ this.ensureCurrentOwnerContextSync();
+ await Promise.allSettled([...this.pendingRecoverySideEffects]);
+ if (this.currentOwnerContextKey() !== ownerContextKey) return;
+ await this.runExclusiveMutation(async () => {
+ if (this.currentOwnerContextKey() !== ownerContextKey) return;
+ this.recoverInterruptedMutationsSync();
+ });
+ await Promise.allSettled([...this.pendingRecoverySideEffects]);
+ })();
+ this.recoveryRetry = retry;
+ const clearRetry = () => {
+ if (this.recoveryRetry === retry) this.recoveryRetry = null;
+ };
+ void retry.then(clearRetry, clearRetry);
+ return retry;
+ }
+
private currentOwnerContextKey(): string {
return `${this.options.getOwnerContextKey?.() ?? ''}\u0000${this.resolveContentRoot()}\u0000${this.resolveStateRoot()}`;
}
@@ -723,7 +1199,7 @@ export class GhostManager {
}
for (const id of pendingScan.ids) {
const markerResult = this.receiptStore.readPendingMutationSync(id);
- const finalDir = path.join(root, id);
+ const finalDir = path.join(root, ...id.split('/'));
if (markerResult.state === 'missing') continue;
// A pending transaction means the receipt cannot authorize finalDir until
// recovery proves commit/rollback and clears the marker.
@@ -748,12 +1224,13 @@ export class GhostManager {
if (!this.options.recordBuiltinTombstone) {
throw new Error('builtin uninstall recovery has no tombstone writer');
}
- this.options.recordBuiltinTombstone(id);
+ this.options.recordBuiltinTombstone(parsePluginInstallRelId(id)!.ghostId);
}
this.receiptStore.removeSync(id);
if (this.recoveryEntryKind(finalDir) === 'directory') {
fs.rmSync(finalDir, { recursive: true, force: true });
}
+ this.forgetPendingNamespaceMigration(id);
} else {
const approval = this.receiptStore.readForRecovery(id);
if (approval.state === 'unreadable') {
@@ -802,6 +1279,77 @@ export class GhostManager {
(marker.oldPackageSha256 !== undefined
? marker.oldPackageSha256 !== marker.packageSha256
: marker.phase === 'published'));
+ if (marker.sourceStateArchiveId !== undefined) {
+ if (!this.options.onArchiveSourceState) throw new Error('source archive recovery callback unavailable');
+ if (backupKind !== 'directory' && backupKind !== 'missing') {
+ throw new Error('managed update backup is not a real directory');
+ }
+ if (finalKind !== 'directory' && finalKind !== 'missing') {
+ throw new Error('managed update final is not a real directory');
+ }
+ if (!committed && approval.state === 'approved' &&
+ approval.receipt.revision === marker.receiptRevision) {
+ throw new Error('committed update receipt has no published directory');
+ }
+ if (!committed && backupKind === 'missing' &&
+ (finalKind !== 'directory' || marker.phase !== 'prepared')) {
+ throw new Error('source archive update rollback has no verified backup');
+ }
+ const recoveryKey = this.isolationKey(id);
+ if (!this.pendingMutationRecoveries.has(recoveryKey)) {
+ const recoveryOwner = this.currentOwnerContextKey();
+ const fromPart = this.storageKeyForContent(id);
+ const archivePart = marker.sourceStateArchiveId;
+ this.pendingMutationRecoveries.add(recoveryKey);
+ const recovery = this.runExclusiveMutation(async () => {
+ let expectedMarker = marker;
+ const assertRecoveryCurrent = () => {
+ if (this.currentOwnerContextKey() !== recoveryOwner) {
+ throw new Error('source archive recovery owner changed');
+ }
+ const currentMarker = this.receiptStore.readPendingMutationSync(id);
+ const currentApproval = this.receiptStore.readForRecovery(id);
+ if (currentMarker.state !== 'valid' ||
+ JSON.stringify(currentMarker.mutation) !== JSON.stringify(expectedMarker) ||
+ JSON.stringify(currentApproval) !== JSON.stringify(approval)) {
+ throw new Error('source archive recovery transaction superseded');
+ }
+ };
+ assertRecoveryCurrent();
+ await this.options.onArchiveSourceState!(
+ committed ? fromPart : archivePart, committed ? archivePart : fromPart,
+ );
+ assertRecoveryCurrent();
+ if (committed) {
+ if (this.recoveryEntryKind(backupPath) === 'directory') {
+ fs.rmSync(backupPath, { recursive: true, force: true });
+ }
+ } else if (backupKind === 'directory') {
+ expectedMarker = { ...marker, phase: 'prepared' };
+ await this.receiptStore.writePendingMutation(id, expectedMarker);
+ assertRecoveryCurrent();
+ if (this.recoveryEntryKind(finalDir) === 'directory') {
+ fs.rmSync(finalDir, { recursive: true, force: true });
+ }
+ fs.renameSync(backupPath, finalDir);
+ }
+ assertRecoveryCurrent();
+ this.receiptStore.clearPendingMutationSync(id);
+ this.untrustedApprovals.delete(recoveryKey);
+ }).catch((error) => {
+ this.options.log?.warn('ghost source archive recovery failed', {
+ id, error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ this.pendingRecoverySideEffects.add(recovery);
+ const clearRecovery = () => {
+ this.pendingRecoverySideEffects.delete(recovery);
+ this.pendingMutationRecoveries.delete(recoveryKey);
+ };
+ void recovery.then(clearRecovery, clearRecovery);
+ }
+ continue;
+ }
if (committed) {
if (backupKind === 'directory') {
fs.rmSync(backupPath, { recursive: true, force: true }); // 陈旧旧字节
@@ -882,9 +1430,8 @@ export class GhostManager {
(entry) => entry.name.startsWith('.cindy-updating-') && !handledBackupNames.has(entry.name),
);
for (const entry of backups) {
- const match = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(entry.name);
- if (!match || !isValidGhostId(match[1])) continue;
- const id = match[1];
+ const id = relIdFromUpdatingBackupName(entry.name);
+ if (!id) continue;
if (blockedMutationIds.has(id)) continue;
const backupPath = path.join(root, entry.name);
try {
@@ -892,18 +1439,15 @@ export class GhostManager {
} catch {
continue;
}
- const finalDir = path.join(root, id);
+ const finalDir = path.join(root, ...id.split('/'));
// 按解析后的 id 精确比对,不能用前缀 startsWith:合法 id 允许带 `-`,
// `.cindy-updating-foo-<hex>` 是 `.cindy-updating-foo-bar-<hex>` 的前缀,
// 若用前缀匹配,foo 与 foo-bar 同时留有 backup 时,foo 的唯一 backup 会被
// 误统计成多个而判为"多备份,留待人工",崩溃后 foo 持续消失(评审 P1)。
- const siblings = backups.filter((other) => {
- const otherMatch = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(other.name);
- return otherMatch !== null && otherMatch[1] === id;
- });
+ const siblings = backups.filter((other) => relIdFromUpdatingBackupName(other.name) === id);
let finalKind: GhostDirEntryKind | 'missing';
try {
- finalKind = classifyGhostDirEntrySync(finalDir);
+ finalKind = this.recoveryEntryKind(finalDir);
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
finalKind = 'missing';
@@ -973,9 +1517,44 @@ export class GhostManager {
}
/** `<root>/<id>` 是否真目录(非链接/junction;判据同 ghostContentTree,避免穿透删除)。 */
+ private resolvePhysicalRelId(id: string, allowLegacyRoot = false): string | null {
+ const identity = parsePluginInstallRelId(id) ?? parsePluginStoragePart(id);
+ if (!identity) return null;
+ if (isValidGhostId(id) && this.isRealDirChildRel(id)) return id;
+ const logicalRel = pluginNewInstallRelId(identity);
+ if (this.isRealDirChildRel(logicalRel)) return logicalRel;
+ if (!allowLegacyRoot && (id.startsWith(PLUGIN_ROOT_INSTALL_ROOT + '/') ||
+ id.startsWith(PLUGIN_ROOT_INSTALL_DIR + '__'))) return logicalRel;
+ if (this.isRealDirChildRel(identity.ghostId)) {
+ const approval = this.receiptStore.read(identity.ghostId);
+ if (identity.namespace === null) {
+ if (approval.state !== 'approved' || !hasDeliveryNamespace(approval.receipt) ||
+ approval.receipt.namespace === null) return identity.ghostId;
+ } else if (approval.state === 'approved' && hasDeliveryNamespace(approval.receipt) &&
+ approval.receipt.namespace === identity.namespace) {
+ return identity.ghostId;
+ }
+ }
+ return logicalRel;
+ }
+
+ /** Receipts live under install rel id (helper or _ns/acme/helper), including in-place org dirs. */
+ private approvalRelIdFor(id: string): string | null {
+ const record = this.instanceRecordForAddress(id);
+ if (record) return record.contentRelId;
+ const identity = parsePluginStoragePart(id) ?? parsePluginInstallRelId(id);
+ if (!identity) return null;
+ return this.resolvePhysicalRelId(id) ?? pluginInstallRelId(identity);
+ }
+
+ private isRealDirChildRel(relId: string): boolean {
+ return this.isRealDirChild(this.contentRootDir(), relId);
+ }
+
private isRealDirChild(root: string, id: string): boolean {
try {
- return classifyGhostDirEntrySync(path.join(root, id)) === 'directory';
+ if (!assertManagedPluginParentSync(root, id)) return false;
+ return classifyGhostDirEntrySync(path.join(root, ...id.split('/'))) === 'directory';
} catch {
return false;
}
@@ -984,6 +1563,9 @@ export class GhostManager {
/** Recovery distinguishes a missing path from transiently unreadable state. */
private recoveryEntryKind(absPath: string): GhostDirEntryKind | 'missing' {
try {
+ const root = this.contentRootDir();
+ const relPath = path.relative(root, absPath).split(path.sep).join('/');
+ if (!assertManagedPluginParentSync(root, relPath)) return 'missing';
return classifyGhostDirEntrySync(absPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';
@@ -1036,8 +1618,10 @@ export class GhostManager {
/** 只认显式 Forge 安装写入的来源;未知/手动来源一律按 manual。 */
readEffectiveInstallOrigin(id: string): 'manual' | 'agent-forge' {
this.ensureCurrentOwnerContextSync();
+ const relId = this.approvalRelIdFor(id);
+ if (!relId) return 'manual';
try {
- const approval = this.readApproval(id);
+ const approval = this.readApproval(relId);
if (approval.state !== 'approved') return 'manual';
return effectiveInstallOrigin(approval.receipt);
} catch {
@@ -1045,19 +1629,91 @@ export class GhostManager {
}
}
+ /**
+ * Registry view used by privilege fallback. A missing row or a blocked
+ * registry is unknown, so callers may still parse a path. unconfirmed is
+ * explicit and must not be treated as unknown.
+ */
+ readNamespaceState(id: string): 'confirmed' | 'pending' | 'unconfirmed' | 'unknown' {
+ this.ensureCurrentOwnerContextSync();
+ if (this.instanceRegistryService.isBlocked()) return 'unknown';
+ const record = this.instanceRecordForAddress(id);
+ return record?.namespaceState ?? 'unknown';
+ }
+
+ /** Trusted receipt namespace. undefined means the delivery field is absent. */
+ readDeliveryNamespace(id: string): string | null | undefined {
+ this.ensureCurrentOwnerContextSync();
+ const record = this.instanceRecordForAddress(id);
+ if (record) return record.namespaceState === 'confirmed' ? record.namespace : undefined;
+ if (this.instanceRegistryService.isBlocked()) return undefined;
+ const relId = this.approvalRelIdFor(id);
+ if (!relId) return undefined;
+ try {
+ const approval = this.readApproval(relId);
+ if (approval.state !== 'approved' || !hasDeliveryNamespace(approval.receipt)) {
+ return undefined;
+ }
+ return approval.receipt.namespace ?? null;
+ } catch {
+ return undefined;
+ }
+ }
+
+ readLegacyFirstPartyEligible(id: string): boolean {
+ this.ensureCurrentOwnerContextSync();
+ const relId = this.approvalRelIdFor(id);
+ if (!relId) return false;
+ try {
+ const approval = this.readApproval(relId);
+ return approval.state === 'approved' && approval.receipt.legacyFirstPartyEligible === true;
+ } catch {
+ return false;
+ }
+ }
+
+ isPendingLegacyForge(id: string): boolean {
+ return this.isPendingLegacyNamespace(id) && this.readEffectiveInstallOrigin(id) === 'agent-forge';
+ }
+
+ isPendingLegacyNamespace(id: string): boolean {
+ this.ensureCurrentOwnerContextSync();
+ const record = this.instanceRecordForAddress(id);
+ return record?.active === true && record.namespaceState === 'pending';
+ }
+
/**
* 自动接管只能把一份成功读取且仍为 approved 的 receipt 当作来源证据。
* 与授权链的宽松投影不同,这里任何缺失、损坏或 I/O 异常都必须上抛。
*/
readApprovedInstallOriginStrict(id: string): 'manual' | 'agent-forge' {
this.ensureCurrentOwnerContextSync();
- const approval = this.readApproval(id);
+ const relId = this.approvalRelIdFor(id);
+ if (!relId) {
+ throw new Error('approved Plugin receipt is unavailable: invalid-id');
+ }
+ const approval = this.readApproval(relId);
if (approval.state !== 'approved') {
throw new Error(`approved Plugin receipt is unavailable: ${approval.state}`);
}
return effectiveInstallOrigin(approval.receipt);
}
+ readApprovedInstallReceipt(id: string, expectedRevision?: string): GhostInstallReceipt | null {
+ this.ensureCurrentOwnerContextSync();
+ const relId = this.approvalRelIdFor(id);
+ if (!relId) return null;
+ try {
+ if (this.hasPendingMutationJournal(relId)) return null;
+ const approval = this.readApproval(relId);
+ if (approval.state !== 'approved' ||
+ (expectedRevision !== undefined && approval.receipt.revision !== expectedRevision)) return null;
+ return approval.receipt;
+ } catch {
+ return null;
+ }
+ }
+
/**
* Host-owned evidence for reconnecting an installation to retained source metadata.
* A pending package mutation or an invalid approval fails closed. Legacy provenance
@@ -1065,8 +1721,11 @@ export class GhostManager {
*/
approvedInstallEvidence(id: string): ApprovedGhostInstallEvidence | null {
this.ensureCurrentOwnerContextSync();
- if (!isValidGhostId(id) || this.hasPendingMutationJournal(id)) return null;
- const approval = this.readApproval(id);
+ const identity = parsePluginStoragePart(id) ?? parsePluginInstallRelId(id);
+ if (!identity) return null;
+ const relId = this.approvalRelIdFor(id) ?? pluginInstallRelId(identity);
+ if (this.hasPendingMutationJournal(relId)) return null;
+ const approval = this.readApproval(relId);
if (approval.state !== 'approved') return null;
const packageSha256 = approval.receipt.packageSha256;
const migration = this.receiptStore.readMigrationLedger();
@@ -1077,7 +1736,7 @@ export class GhostManager {
legacyMigrated: Boolean(
migration
&& migration.state !== 'in-progress'
- && migration.migratedIds.includes(id)
+ && migration.migratedIds.includes(identity.ghostId)
),
};
}
@@ -1155,12 +1814,14 @@ export class GhostManager {
) {
return false;
}
- const current = this.readApproval(ghost.manifest.id);
+ const relId = path.relative(this.contentRootDir(), ghost.dir).split(path.sep).join('/');
+ if (!isValidPluginInstallRelId(relId)) return false;
+ const current = this.readApproval(relId);
if (current.state !== 'approved' || current.receipt.revision !== ghost.approval.revision) {
return false;
}
const expectedRoot = this.receiptStore.skillSnapshotRoot(
- current.receipt.id,
+ relId,
current.receipt.revision,
);
if (path.resolve(ghost.approvedSkillRoot) !== path.resolve(expectedRoot)) {
@@ -1230,7 +1891,7 @@ export class GhostManager {
},
removeInstallApproval: async (id) => {
assertCapabilityActive();
- return this.removeInstallApprovalUnlocked(id);
+ return this.removeInstallApprovalUnlocked(this.resolvePhysicalRelId(id) ?? id);
},
uninstall: async (id, options = {}) => {
assertCapabilityActive();
@@ -1351,7 +2012,7 @@ export class GhostManager {
if (id.startsWith('.') || !isValidGhostId(id)) continue;
// 判据走 ghostContentTree(lstat 分类),不信 Dirent 类型位:根子项是 junction/
// 链接时一律不进迁移,也与 §3「只有真目录才算安装」同向。
- if (classifyGhostDirEntrySync(path.join(root, id)) !== 'directory') continue;
+ if (classifyGhostDirEntrySync(path.join(root, ...id.split('/'))) !== 'directory') continue;
// 随包种子交给 provisioning,不在迁移范围。
if (this.options.isTrustedBundledId?.(id)) {
result.skipped.push(id);
@@ -1453,7 +2114,7 @@ export class GhostManager {
for (const id of candidates) {
try {
- const migrated = await this.backfillLegacyApproval(path.join(root, id), id, {
+ const migrated = await this.backfillLegacyApproval(path.join(root, ...id.split('/')), id, {
expectedApprovalProjectionSha256:
resumeApprovalProjectionDigest?.[id],
});
@@ -1638,7 +2299,7 @@ export class GhostManager {
continue;
}
try {
- const targetDir = path.join(root, id);
+ const targetDir = path.join(root, ...id.split('/'));
const expectedApprovalProjectionSha256 =
options.expectedApprovalProjectionSha256ById[id];
if (expectedApprovalProjectionSha256 === undefined) {
@@ -1763,7 +2424,7 @@ export class GhostManager {
skillContentSha256: projection.skillContentSha256,
...(projection.iconDataUrl !== undefined ? { iconDataUrl: projection.iconDataUrl } : {}),
}),
- { skillSourceDir: dir },
+ { skillSourceDir: dir, relId: id },
);
this.options.log?.info('legacy ghost approval migrated', {
id,
@@ -1777,30 +2438,14 @@ export class GhostManager {
/** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */
list(): InstalledGhost[] {
this.ensureCurrentOwnerContextSync();
- const root = this.contentRootDir();
- let entries: fs.Dirent[];
- try {
- entries = fs.readdirSync(root, { withFileTypes: true });
- } catch {
- return []; // 根目录还不存在 = 没装过任何意识
- }
-
+ this.syncInstanceRegistry();
+ const listedDirs = this.listContentEntries();
const result: InstalledGhost[] = [];
- for (const entry of entries) {
- if (entry.name.startsWith('.')) continue; // staging / 系统目录
- const dir = path.join(root, entry.name);
- // 判据走 ghostContentTree(lstat 分类),不信 Dirent 类型位:根子项是 junction/
- // 链接时不算已装插件 —— 与迁移扫描、内容树遍历同一份判据(§3)。
- try {
- if (classifyGhostDirEntrySync(dir) !== 'directory') continue;
- } catch {
- continue; // lstat 不动(条目消失/权限)= 不算已装
- }
- if (!isValidGhostId(entry.name)) {
- this.options.log?.warn('ghost dir skipped: invalid directory id', { dir });
- continue;
- }
- const approvalResult = this.readApproval(entry.name);
+ for (const listed of listedDirs) {
+ const { relId, dir } = listed;
+ const identity = parsePluginInstallRelId(relId);
+ if (!identity) continue;
+ const approvalResult = this.readApproval(relId);
if (approvalResult.state === 'approved') {
const receipt = approvalResult.receipt;
const localizedManifest = this.localizeApprovedManifest(receipt);
@@ -1810,7 +2455,7 @@ export class GhostManager {
try {
retirement = this.retirements.observe(
retired.id,
- receipt.id,
+ pluginInstallStoragePart(relId),
this.effectiveEnabled(dir, receipt.enabled),
);
} catch (error) {
@@ -1830,6 +2475,7 @@ export class GhostManager {
result.push({
manifest: localizedManifest,
dir,
+ ...this.instanceProjection(relId, identity.ghostId),
enabled: !retired && this.effectiveEnabled(dir, receipt.enabled),
...(retirement ? { retirement } : {}),
approval: { state: 'approved', revision: receipt.revision },
@@ -1838,19 +2484,19 @@ export class GhostManager {
...(!retired && receipt.manifest.skill?.items.length
? {
approvedSkillRoot: this.receiptStore.skillSnapshotRoot(
- receipt.id,
+ relId,
receipt.revision,
),
}
: {}),
...(receipt.iconDataUrl !== undefined ? { iconDataUrl: receipt.iconDataUrl } : {}),
- ...(this.options.isTrustedBundledId?.(entry.name) ? { builtin: true } : {}),
+ ...(identity.namespace === null && this.options.isTrustedBundledId?.(identity.ghostId) ? { builtin: true } : {}),
});
continue;
}
if (approvalResult.state === 'invalid') {
this.options.log?.warn('ghost approval receipt invalid; plugin kept disabled', {
- id: entry.name,
+ id: relId,
reason: approvalResult.reason,
});
}
@@ -1887,7 +2533,7 @@ export class GhostManager {
this.options.log?.warn('ghost dir skipped: invalid manifest', { dir, reason: v.reason });
continue;
}
- if (v.manifest.id !== entry.name) {
+ if (v.manifest.id !== identity.ghostId) {
this.options.log?.warn('ghost dir skipped: dir name != manifest id', {
dir,
manifestId: v.manifest.id,
@@ -1907,6 +2553,7 @@ export class GhostManager {
result.push({
manifest: localizedManifest,
dir,
+ ...this.instanceProjection(relId, identity.ghostId),
enabled: false,
approval: { state: approvalResult.state },
...(retired ? { retirement: { id: retired.id, eligible: false, unread: false } } : {}),
@@ -1918,7 +2565,7 @@ export class GhostManager {
reviewed: false,
},
...(iconDataUrl !== null ? { iconDataUrl } : {}),
- ...(this.options.isTrustedBundledId?.(entry.name) ? { builtin: true } : {}),
+ ...(identity.namespace === null && this.options.isTrustedBundledId?.(identity.ghostId) ? { builtin: true } : {}),
});
}
result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));
@@ -1937,7 +2584,8 @@ export class GhostManager {
} {
const list = this.list();
const ghost =
- list.find((item) => item.manifest.id === fallback.manifest.id) ??
+ list.find((item) => item.dir === fallback.dir) ??
+ findInstalledGhostByInstanceId(list, installedGhostStoragePart(fallback)) ??
({
...fallback,
enabled: false,
@@ -1948,9 +2596,14 @@ export class GhostManager {
}
acknowledgeRetirement(id: string): void {
- const ghost = this.list().find((item) => item.manifest.id === id);
+ const listed = this.list();
+ let ghost = findInstalledGhostByInstanceId(listed, id);
+ if (!ghost) {
+ const sameName = listed.filter((item) => item.manifest.id === id);
+ if (sameName.length === 1) ghost = sameName[0];
+ }
if (!ghost?.retirement) throw new Error('Retired plugin is not installed');
- this.retirements.acknowledge(ghost.retirement.id, id);
+ this.retirements.acknowledge(ghost.retirement.id, installedGhostStoragePart(ghost));
this.options.onChanged?.(this.list());
}
@@ -2020,14 +2673,17 @@ export class GhostManager {
/** Called only after Host permission UI confirms this exact installed revision. */
async approveTaskCapability(id: string, revision: string, isCurrent: () => boolean): Promise<boolean> {
return this.runExclusiveMutation(async () => {
- const approval = this.readApproval(id);
+ const relId = this.approvalRelIdFor(id);
+ if (!relId) return false;
+ const approval = this.readApproval(relId);
if (!isCurrent() || approval.state !== 'approved' || approval.receipt.revision !== revision ||
approval.receipt.manifest.agent?.tasks !== true ||
- !this.list().some(ghost => ghost.manifest.id === id && ghost.enabled)) return false;
+ !findInstalledGhostByInstanceId(this.list(), id)?.enabled) return false;
if (approval.receipt.taskCapabilityApproved !== true) {
const expired = new Error('Task capability approval owner changed');
try {
await this.receiptStore.write({ ...approval.receipt, taskCapabilityApproved: true }, {
+ relId,
assertCurrent: () => { if (!isCurrent()) throw expired; },
});
} catch (error) {
@@ -2050,18 +2706,22 @@ export class GhostManager {
async setEnabled(
id: string,
enabled: boolean,
+ expectedInstalledApproval?: string,
): Promise<{ ok: true } | { rejection: UninstallRejection }> {
- return this.runExclusiveMutation(() => this.setEnabledUnlocked(id, enabled));
+ return this.runExclusiveMutation(() => this.setEnabledUnlocked(id, enabled, expectedInstalledApproval));
}
private async setEnabledUnlocked(
id: string,
enabled: boolean,
+ expectedInstalledApproval?: string,
): Promise<{ ok: true } | { rejection: UninstallRejection }> {
- if (!isValidGhostId(id)) {
+ const identity = parsePluginInstallRelId(id);
+ if (!identity) {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
}
- const dir = path.join(this.contentRootDir(), id);
+ const relId = this.resolvePhysicalRelId(id) ?? pluginInstallRelId(identity);
+ const dir = this.contentPath(relId);
// pathExists(fs.access)跟随链接:`<root>/<id>` 被换成 junction 时,下面对
// `<dir>/.disabled` 的写/删会穿透到安装根之外的目标。判据改用 ghostContentTree 的
// lstat 分类(与 list()「只有真目录才算安装」同源):不存在(ENOENT→抛错)或非真目录
@@ -2073,9 +2733,9 @@ export class GhostManager {
dirKind = null;
}
if (dirKind !== 'directory') {
- return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
+ return { rejection: { code: 'not-installed', reason: `意识 ${identity.ghostId} 未装入` } };
}
- const receiptResult = this.readApproval(id);
+ const receiptResult = this.readApproval(relId);
if (
enabled &&
receiptResult.state === 'approved' &&
@@ -2088,19 +2748,22 @@ export class GhostManager {
},
};
}
+ if (expectedInstalledApproval !== undefined && approvalTokenFor(receiptResult) !== expectedInstalledApproval) {
+ return { rejection: { code: 'not-installed', reason: '目标插件安装状态已变化,请重新操作' } };
+ }
if (receiptResult.state !== 'approved' && enabled) {
return {
rejection: {
code: 'approval-required',
- reason: `插件 ${id} 缺少有效的安装验证记录,请重新安装`,
+ reason: `插件 ${identity.ghostId} 缺少有效的安装验证记录,请重新安装`,
},
};
}
// Re-check immediately before touching the compatibility mirror. This does not
// replace OS-level handle protection, but prevents a stale initial classification
// from authorizing a link/file target in the common race window.
- if (!this.isRealDirChild(this.contentRootDir(), id)) {
- return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
+ if (!this.isRealDirChildRel(relId)) {
+ return { rejection: { code: 'not-installed', reason: `意识 ${identity.ghostId} 未装入` } };
}
const marker = path.join(dir, DISABLED_MARKER_FILE);
// 回滚基准取"镜像先前是否在盘上",不是 receipt.enabled:两者可以背离(旧客户端
@@ -2147,7 +2810,7 @@ export class GhostManager {
// 也照样落盘,由技能对账把落链撤掉。
await this.receiptStore.write(
{ ...receiptResult.receipt, enabled },
- { skillSourceDir: dir, requireSkillSnapshot: enabled },
+ { skillSourceDir: dir, requireSkillSnapshot: enabled, relId },
);
} catch (err) {
if (!enabled) {
@@ -2386,6 +3049,10 @@ export class GhostManager {
rejection: { code: 'file-invalid', reason: `${GHOST_MANIFEST_FILE} 不是合法 JSON` },
};
}
+ const reservedNamespace = authorDeclaredNamespaceReason(manifestRaw);
+ if (reservedNamespace) {
+ return { rejection: { code: 'file-invalid', reason: reservedNamespace } };
+ }
const hostUnsupportedReason = ghostManifestHostUnsupportedReason(manifestRaw);
if (hostUnsupportedReason) {
return { rejection: { code: 'host-unsupported', reason: hostUnsupportedReason } };
@@ -2678,7 +3345,11 @@ export class GhostManager {
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
- installOrigin?: 'agent-forge';
+ installOrigin?: 'manual' | 'agent-forge';
+ /** Market installs record this so a later reinstall can find the same instance. */
+ registrySource?: PluginInstanceSource;
+ pluginId?: string | null;
+ namespace?: string | null;
/** Synchronous live-authority check immediately before publishing the staged package. */
beforePackagePlacement?: () => void;
},
@@ -2693,7 +3364,11 @@ export class GhostManager {
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
- installOrigin?: 'agent-forge';
+ installOrigin?: 'manual' | 'agent-forge';
+ /** Market installs record this so a later reinstall can find the same instance. */
+ registrySource?: PluginInstanceSource;
+ pluginId?: string | null;
+ namespace?: string | null;
beforePackagePlacement?: () => void;
},
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
@@ -2731,19 +3406,48 @@ export class GhostManager {
// 4) 目标目录冲突检查
const root = this.contentRootDir();
- const finalDir = path.join(root, manifest.id);
+ const identity = createPluginLogicalIdentity(opts?.namespace ?? null, manifest.id);
+ const registrySource = opts?.registrySource ??
+ (opts?.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual');
+ const placement = this.planInstancePlacement(
+ manifest.id, identity.namespace, registrySource, opts?.pluginId,
+ );
+ if (placement.kind === 'blocked') {
+ return { rejection: { code: 'already-installed', reason: placement.reason } };
+ }
+ const instanceKey = placement.instanceKey;
+ const relId = placement.relId;
+ if (this.hasPendingMutationJournal(relId)) {
+ return { rejection: { code: 'io', reason: '意识正在恢复,请稍后重试' } };
+ }
+ if (findInstalledGhostByIdentity(this.list(), identity)) {
+ return { rejection: { code: 'already-installed', reason: `意识 ${manifest.id} 已装入` } };
+ }
+ const physicalRel = this.resolvePhysicalRelId(relId) ?? relId;
+ if (physicalRel !== relId && this.isRealDirChildRel(physicalRel)) {
+ return { rejection: { code: 'already-installed', reason: `意识 ${manifest.id} 已装入` } };
+ }
+ const finalDir = this.contentPath(relId);
if (await pathExists(finalDir)) {
return { rejection: { code: 'already-installed', reason: `意识 ${manifest.id} 已装入` } };
}
+ const pendingInstall = await this.resolvePendingNamespaceInstall(manifest.id, identity.namespace);
+ if (pendingInstall.kind === 'already-installed') {
+ return { rejection: { code: 'already-installed', reason: `意识 ${manifest.id} 已装入` } };
+ }
+ if (pendingInstall.kind === 'wait') {
+ return { rejection: { code: 'namespace-migration-pending', reason: pendingInstall.reason } };
+ }
+ await fs.promises.mkdir(path.dirname(finalDir), { recursive: true });
+ this.contentPath(relId);
// 4.5) 显式指令查重(2026-07-09 Lizi 定案):command 由意识作者自定,
// 与本机已装意识撞名即拒——不静默改名(确定性),由用户抽离旧的或
// 作者换名解决。大小写折叠比较,防 /Draw 与 /draw 并存互踩。
if (manifest.command !== undefined) {
- const commandFold = manifest.command.toLowerCase();
- const holder = this.list().find(
- (g) => g.manifest.command !== undefined && g.manifest.command.toLowerCase() === commandFold,
- );
+ const holder = findConflictingGhostCommand(this.list(), manifest.command, {
+ incomingNamespace: identity.namespace,
+ });
if (holder) {
return {
rejection: {
@@ -2757,7 +3461,7 @@ export class GhostManager {
// 5) 解压到 staging(zip-slip / zip bomb 防御),全过才切正式目录
const stagingDir = path.join(
root,
- `.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`,
+ `.cindy-installing-${pluginStoragePart(identity)}-${crypto.randomBytes(4).toString('hex')}`,
);
const receiptRevision = crypto.randomUUID();
// receipt 在内容落到 finalDir 之后才创建:技能字节指纹必须从这次批准的内容
@@ -2777,20 +3481,20 @@ export class GhostManager {
// "有 finalDir、无 receipt、无 ledger"的目录,与 legacy 安装无法区分,被迁移当
// 存量批准掉(而崩溃窗口内同权限进程可改写 finalDir 的 manifest)。带 packageSha256
// 让启动恢复能判定 receipt 是否已提交。
- await this.receiptStore.writePendingMutation(manifest.id, {
+ await this.receiptStore.writePendingMutation(relId, {
kind: 'install',
packageSha256,
receiptRevision,
...(clearBuiltinTombstoneOnCommit ? { clearBuiltinTombstone: true } : {}),
});
- this.untrustedApprovals.add(this.isolationKey(manifest.id));
+ this.untrustedApprovals.add(this.isolationKey(relId));
try {
opts?.beforePackagePlacement?.();
} catch (error) {
// No package bytes were published. Clear the prepared journal so a
// cancelled request cannot leave an installation waiting for recovery.
- await this.receiptStore.clearPendingMutation(manifest.id);
- this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ await this.receiptStore.clearPendingMutation(relId);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
throw error;
}
await fs.promises.rename(stagingDir, finalDir);
@@ -2812,8 +3516,9 @@ export class GhostManager {
revision: receiptRevision,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
...(opts?.installOrigin ? { installOrigin: opts.installOrigin } : {}),
+ ...this.persistedNamespaceFields(opts ?? {}, null),
});
- await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ await this.receiptStore.write(receipt, { skillSourceDir: finalDir, relId });
let tombstoneClearPending = false;
if (clearBuiltinTombstoneOnCommit) {
try {
@@ -2834,8 +3539,8 @@ export class GhostManager {
// receipt.packageSha256 与标记相符即判已提交、幂等清理。
if (!tombstoneClearPending) {
try {
- await this.receiptStore.clearPendingMutation(manifest.id);
- this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ await this.receiptStore.clearPendingMutation(relId);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
} catch {
// Keep quarantine while the durable journal remains.
}
@@ -2843,13 +3548,13 @@ export class GhostManager {
// The receipt and installed bytes are committed. The remaining
// journal only records a deferred builtin tombstone side effect and
// must not keep an otherwise valid builtin disabled in-process.
- this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ this.untrustedApprovals.delete(this.isolationKey(relId));
}
} catch (error) {
try {
await fs.promises.rm(finalDir, { recursive: true, force: true });
- await this.receiptStore.clearPendingMutation(manifest.id);
- this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ await this.receiptStore.clearPendingMutation(relId);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
} catch (rollbackError) {
// Keep the install journal whenever rollback cannot prove the published
// directory is gone. Migration treats that journal as a hard block, and
@@ -2880,13 +3585,27 @@ export class GhostManager {
return { rejection: { code: 'io', reason: '安装批准状态未能生成' } };
}
+ this.publishInstalledInstance({
+ instanceKey,
+ contentRelId: relId,
+ ghostId: manifest.id,
+ namespace: identity.namespace,
+ namespaceState: 'confirmed',
+ pluginId: opts?.pluginId ?? null,
+ source: registrySource,
+ receiptRevision: receipt.revision,
+ packageSha256: receipt.packageSha256 ?? null,
+ active: true,
+ });
const ghost: InstalledGhost = {
manifest,
dir: finalDir,
+ instanceKey,
enabled: initiallyEnabled,
approval: { state: 'approved', revision: receipt.revision },
trust,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ ...this.persistedNamespaceFields(opts ?? {}, null),
};
this.options.log?.info('ghost installed', { id: manifest.id, version: manifest.version });
const projected = this.projectCommittedMutationResult(ghost);
@@ -2910,7 +3629,9 @@ export class GhostManager {
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
- installOrigin?: 'agent-forge';
+ installOrigin?: 'manual' | 'agent-forge';
+ namespace?: string | null;
+ sourceStateArchiveId?: string;
beforePackageCommit?: () => GhostPackageCommitPreparation | void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
onPackagePlaced?: () => void;
@@ -2926,7 +3647,9 @@ export class GhostManager {
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
- installOrigin?: 'agent-forge';
+ installOrigin?: 'manual' | 'agent-forge';
+ namespace?: string | null;
+ sourceStateArchiveId?: string;
/** 新目录已换位、旧目录仍可回滚时执行;抛错会恢复旧版本。 */
beforePackageCommit?: () => GhostPackageCommitPreparation | void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
@@ -2960,13 +3683,27 @@ export class GhostManager {
: parsed.trust;
const root = this.contentRootDir();
- const finalDir = path.join(root, manifest.id);
- if (!this.isRealDirChild(root, manifest.id)) {
+ const identity = createPluginLogicalIdentity(opts.namespace ?? null, manifest.id);
+ const relId =
+ this.resolvePhysicalRelId(pluginNewInstallRelId(identity), true) ?? pluginNewInstallRelId(identity);
+ if (this.hasPendingMutationJournal(relId)) {
+ this.untrustedApprovals.add(this.isolationKey(relId));
+ return { rejection: { code: 'io', reason: '意识正在恢复,请稍后重试' } };
+ }
+ const fromPart = this.storageKeyForContent(relId);
+ const archiveId = opts.sourceStateArchiveId;
+ if (archiveId !== undefined &&
+ (!isValidGhostSourceStateArchiveId(archiveId) || archiveId === fromPart ||
+ !this.options.onArchiveSourceState)) {
+ return { rejection: { code: 'io', reason: 'source state archive identity or callback unavailable' } };
+ }
+ const finalDir = this.contentPath(relId);
+ if (!this.isRealDirChildRel(relId)) {
return {
rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` },
};
}
- const approvalResult = this.readApproval(manifest.id);
+ const approvalResult = this.readApproval(relId);
const actualApproval = approvalTokenFor(approvalResult);
if (actualApproval !== opts.expectedInstalledApproval) {
return {
@@ -2992,13 +3729,10 @@ export class GhostManager {
// 指令查重同 install,但豁免自己(新版本沿用/改名自己的指令都合法)。
if (manifest.command !== undefined) {
- const commandFold = manifest.command.toLowerCase();
- const holder = this.list().find(
- (g) =>
- g.manifest.id !== manifest.id &&
- g.manifest.command !== undefined &&
- g.manifest.command.toLowerCase() === commandFold,
- );
+ const holder = findConflictingGhostCommand(this.list(), manifest.command, {
+ incomingNamespace: identity.namespace,
+ exemptPhysicalRelId: relId,
+ });
if (holder) {
return {
rejection: {
@@ -3010,8 +3744,9 @@ export class GhostManager {
}
const rand = crypto.randomBytes(4).toString('hex');
- const stagingDir = path.join(root, `.cindy-installing-${manifest.id}-${rand}`);
- const backupDir = path.join(root, `.cindy-updating-${manifest.id}-${rand}`);
+ const workName = pluginInstallStoragePart(relId);
+ const stagingDir = path.join(root, `.cindy-installing-${workName}-${rand}`);
+ const backupDir = path.join(root, `.cindy-updating-${workName}-${rand}`);
try {
await this.extractToStaging(allEntries, prefix, stagingDir, {
disabled: !enabled,
@@ -3036,12 +3771,13 @@ export class GhostManager {
// 已提交:未提交则回滚到 backup。
const receiptRevision = crypto.randomUUID();
try {
- await this.receiptStore.writePendingMutation(manifest.id, {
+ await this.receiptStore.writePendingMutation(relId, {
kind: 'update',
packageSha256,
backupDirName: path.basename(backupDir),
receiptRevision,
phase: 'prepared',
+ ...(archiveId !== undefined ? { sourceStateArchiveId: archiveId } : {}),
...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256
? { oldPackageSha256: approvalResult.receipt.packageSha256 }
: {}),
@@ -3057,11 +3793,11 @@ export class GhostManager {
// exchange so concurrent list/spawn/host calls cannot project the old
// receipt onto the new finalDir while the new receipt and skill snapshot
// are still being committed.
- this.untrustedApprovals.add(this.isolationKey(manifest.id));
+ this.untrustedApprovals.add(this.isolationKey(relId));
const clearUpdateQuarantineAfterRollback = async (): Promise<void> => {
try {
- await this.receiptStore.clearPendingMutation(manifest.id);
- this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ await this.receiptStore.clearPendingMutation(relId);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
} catch {
// Keep the in-process quarantine if the journal cannot be cleared;
// restart recovery must see the marker before authorization resumes.
@@ -3081,12 +3817,13 @@ export class GhostManager {
// this write is interrupted, recovery can infer the same state from the
// presence of the backup and will never treat a pre-rename final as new code.
await this.receiptStore
- .writePendingMutation(manifest.id, {
+ .writePendingMutation(relId, {
kind: 'update',
packageSha256,
backupDirName: path.basename(backupDir),
receiptRevision,
phase: 'backed-up',
+ ...(archiveId !== undefined ? { sourceStateArchiveId: archiveId } : {}),
...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256
? { oldPackageSha256: approvalResult.receipt.packageSha256 }
: {}),
@@ -3136,14 +3873,21 @@ export class GhostManager {
// committed. Later failures compensate both this side effect and the
// directory swap; either rollback failure keeps journal + quarantine.
let packageCommitPreparation: GhostPackageCommitPreparation | undefined;
+ let archiveAttempted = false;
+ let archiveCompleted = false;
let receipt: GhostInstallReceipt;
try {
+ if (archiveId !== undefined) {
+ archiveAttempted = true;
+ await this.options.onArchiveSourceState!(fromPart, archiveId);
+ archiveCompleted = true;
+ }
packageCommitPreparation = opts.beforePackageCommit?.() ?? undefined;
receipt = createGhostInstallReceipt({
manifest: approvedManifest,
localeResources,
enabled,
- ...((opts.taskCapabilityApproved === true || (approvalResult.state === 'approved' && approvalResult.receipt.taskCapabilityApproved === true)) &&
+ ...((opts.taskCapabilityApproved === true || (archiveId === undefined && approvalResult.state === 'approved' && approvalResult.receipt.taskCapabilityApproved === true)) &&
approvedManifest.agent?.tasks === true ? { taskCapabilityApproved: true as const } : {}),
trust,
// 同 install:指纹取自包投影,发布后的目录漂移在快照对账时 fail closed(P0-8)。
@@ -3156,15 +3900,35 @@ export class GhostManager {
revision: receiptRevision,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
...(installOrigin ? { installOrigin } : {}),
+ ...(approvalResult.state === 'approved' &&
+ legacyFirstPartyEligibilityAfterUpdate(approvalResult.receipt, archiveId !== undefined)
+ ? { legacyFirstPartyEligible: true } : {}),
+ ...this.persistedNamespaceFields(opts, approvalResult.state === 'approved' ? approvalResult.receipt : null),
});
- await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ await this.receiptStore.write(receipt, { skillSourceDir: finalDir, relId });
} catch (err) {
- let sideEffectRolledBack = !(
+ let archiveRestored = !archiveAttempted;
+ if (archiveCompleted && archiveId !== undefined) {
+ try {
+ await this.options.onArchiveSourceState!(archiveId, fromPart);
+ const pending = this.receiptStore.readPendingMutationSync(relId);
+ if (pending.state !== 'valid' || pending.mutation.kind !== 'update') {
+ throw new Error('source archive rollback journal unavailable');
+ }
+ await this.receiptStore.writePendingMutation(relId, { ...pending.mutation, phase: 'prepared' });
+ archiveRestored = true;
+ } catch (rollbackError) {
+ this.options.log?.warn('ghost source archive rollback failed', {
+ id: manifest.id, error: rollbackError instanceof Error ? rollbackError.message : String(rollbackError),
+ });
+ }
+ }
+ let sideEffectRolledBack = archiveRestored && !(
err instanceof Error &&
'rollbackFailed' in err &&
err.rollbackFailed === true
);
- if (packageCommitPreparation) {
+ if (packageCommitPreparation && archiveRestored) {
try {
packageCommitPreparation.rollback();
} catch (rollbackErr) {
@@ -3220,8 +3984,8 @@ export class GhostManager {
}
// receipt 已就位 = 事务提交,清标记后再回收 backup;顺序保证"标记在 ⟺ 可能未提交"。
try {
- await this.receiptStore.clearPendingMutation(manifest.id);
- this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ await this.receiptStore.clearPendingMutation(relId);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
} catch {
// Keep quarantine while the durable journal remains; recovery retries it.
}
@@ -3244,6 +4008,7 @@ export class GhostManager {
approval: { state: 'approved', revision: receipt.revision },
trust,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ ...this.persistedNamespaceFields(opts, approvalResult.state === 'approved' ? approvalResult.receipt : null),
};
opts?.onPackagePlaced?.();
this.options.log?.info('ghost updated', { id: manifest.id, version: manifest.version });
@@ -3285,10 +4050,14 @@ export class GhostManager {
}
const packageSha256 = await hashApprovedDirectory(sourceDir);
const root = this.contentRootDir();
- const finalDir = path.join(root, id);
+ const relId = this.isRealDirChildRel(id) ? id
+ : this.isRealDirChildRel(pluginNewInstallRelId(createPluginLogicalIdentity(null, id)))
+ ? pluginNewInstallRelId(createPluginLogicalIdentity(null, id)) : id;
+ const storagePart = pluginInstallStoragePart(relId);
+ const finalDir = path.join(root, ...relId.split('/'));
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}`);
+ const stagingDir = path.join(root, `.cindy-installing-${storagePart}-${rand}`);
+ const backupDir = path.join(root, `.cindy-updating-${storagePart}-${rand}`);
let finalKind: GhostDirEntryKind | 'missing';
try {
finalKind = classifyGhostDirEntrySync(finalDir);
@@ -3312,28 +4081,28 @@ export class GhostManager {
);
}
if (finalKind === 'missing') {
- await this.receiptStore.writePendingMutation(id, { kind: 'install', packageSha256 });
- this.untrustedApprovals.add(this.isolationKey(id));
+ await this.receiptStore.writePendingMutation(relId, { kind: 'install', packageSha256 });
+ this.untrustedApprovals.add(this.isolationKey(relId));
await fs.promises.rename(stagingDir, finalDir);
return;
}
- await this.receiptStore.writePendingMutation(id, {
+ await this.receiptStore.writePendingMutation(relId, {
kind: 'update',
packageSha256,
backupDirName: path.basename(backupDir),
phase: 'prepared',
});
- this.untrustedApprovals.add(this.isolationKey(id));
+ this.untrustedApprovals.add(this.isolationKey(relId));
await fs.promises.rename(finalDir, backupDir);
- await this.receiptStore.writePendingMutation(id, {
+ await this.receiptStore.writePendingMutation(relId, {
kind: 'update',
packageSha256,
backupDirName: path.basename(backupDir),
phase: 'backed-up',
});
await fs.promises.rename(stagingDir, finalDir);
- await this.receiptStore.writePendingMutation(id, {
+ await this.receiptStore.writePendingMutation(relId, {
kind: 'update',
packageSha256,
backupDirName: path.basename(backupDir),
@@ -3352,15 +4121,15 @@ export class GhostManager {
if (backupKind === 'directory' && publishedKind === null) {
try {
await fs.promises.rename(backupDir, finalDir);
- await this.receiptStore.clearPendingMutation(id);
- this.untrustedApprovals.delete(this.isolationKey(id));
+ await this.receiptStore.clearPendingMutation(relId);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
} 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));
+ await this.receiptStore.clearPendingMutation(relId);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
} catch {
// Keep the in-process quarantine while the journal remains.
}
@@ -3389,7 +4158,8 @@ export class GhostManager {
`approveTrustedBundledInstall 只服务随包种子插件:${manifest.id} 不在种子清单里`,
);
}
- const dir = path.join(this.contentRootDir(), manifest.id);
+ const relId = this.resolvePhysicalRelId(manifest.id) ?? manifest.id;
+ const dir = this.contentPath(relId);
if (!options || typeof options.sourceDir !== 'string' || options.sourceDir.trim() === '') {
throw new Error('approveTrustedBundledInstall requires a verified bundled source directory');
}
@@ -3424,7 +4194,7 @@ export class GhostManager {
const iconDataUrl = this.readInstalledIconDataUrl(sourceDir, approvedManifest) ?? undefined;
const packageSha256 = await hashApprovedDirectory(sourceDir);
const skillContentSha256 = await hashApprovedSkillContent(approvedManifest, sourceDir);
- const pendingPublish = this.receiptStore.readPendingMutationSync(approvedManifest.id);
+ const pendingPublish = this.receiptStore.readPendingMutationSync(relId);
if (pendingPublish.state === 'invalid' || pendingPublish.state === 'unreadable') {
throw new Error(`builtin seed publish journal is ${pendingPublish.state}`);
}
@@ -3439,12 +4209,12 @@ export class GhostManager {
throw new Error('builtin seed publish journal does not match immutable source');
}
const trust = CINDY_OFFICIAL_GHOST_TRUST;
- const current = this.readApproval(approvedManifest.id);
+ const current = this.readApproval(relId);
// priorEnabled 直接读盘上的 receipt 而不是 readApproval 的投影:进程内隔离态的
// receipt 不可作授权事实,但"曾经停用"这个位只用于往下拉,是 fail closed 方向,
// 采纳它只会更保守 —— 否则"隔离 + 镜像同时丢失"的组合会让自愈把插件带回启用。
const persisted =
- current.state === 'approved' ? current : this.receiptStore.read(approvedManifest.id);
+ current.state === 'approved' ? current : this.receiptStore.read(relId);
const priorEnabled = persisted.state === 'approved' ? persisted.receipt.enabled : undefined;
const enabled = priorEnabled === undefined ? markerEnabled : markerEnabled && priorEnabled;
if (enabled !== markerEnabled) {
@@ -3477,7 +4247,7 @@ export class GhostManager {
(approvedManifest.skill?.items.length ?? 0) === 0 ||
(await this.receiptStore.skillSnapshotMatchesReceipt(
current.receipt,
- this.receiptStore.skillSnapshotRoot(approvedManifest.id, current.receipt.revision),
+ this.receiptStore.skillSnapshotRoot(relId, current.receipt.revision),
));
if (!snapshotHealthy) {
// Snapshot repair must persist the same one-way disabled merge as the
@@ -3488,10 +4258,10 @@ export class GhostManager {
...current.receipt,
enabled,
},
- { skillSourceDir: sourceDir },
+ { skillSourceDir: sourceDir, relId },
);
- await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);
- this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));
+ await this.finishTrustedBundledPublish(relId, pendingPublish);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
return true;
}
if (current.receipt.enabled !== enabled) {
@@ -3500,20 +4270,20 @@ export class GhostManager {
...current.receipt,
enabled,
},
- { skillSourceDir: sourceDir },
+ { skillSourceDir: sourceDir, relId },
);
- await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);
- this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));
+ await this.finishTrustedBundledPublish(relId, pendingPublish);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
return true;
}
- await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);
+ await this.finishTrustedBundledPublish(relId, pendingPublish);
// Receipt already matches the immutable seed — no write needed,
// but the process-internal untrusted approval quarantine from
// publishTrustedBundledSeed must still be cleared. The other
// two branches (full write and enabled toggle) both clear it;
// without it here, the no-op path leaves the plugin quarantined
// until the next restart (P1, PRRT_kwDOTgdRUs6YcxiH).
- this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));
+ this.untrustedApprovals.delete(this.isolationKey(relId));
return false;
}
await this.receiptStore.write(
@@ -3527,11 +4297,12 @@ export class GhostManager {
...(current.state === 'approved' && current.receipt.taskCapabilityApproved === true &&
approvedManifest.agent?.tasks === true ? { taskCapabilityApproved: true as const } : {}),
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ namespace: null,
}),
- { skillSourceDir: sourceDir },
+ { skillSourceDir: sourceDir, relId },
);
- await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);
- this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));
+ await this.finishTrustedBundledPublish(relId, pendingPublish);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
return true;
}
@@ -3674,49 +4445,61 @@ export class GhostManager {
return this.runExclusiveMutation(() => this.uninstallUnlocked(id, options));
}
+
+ private forgetPendingNamespaceMigration(relId: string): void {
+ this.instanceRegistryService.release(relId);
+ }
+
private async uninstallUnlocked(
id: string,
options: GhostUninstallOptions = {},
): Promise<UninstallResult> {
- if (!isValidGhostId(id)) {
+ const identity = parsePluginInstallRelId(id);
+ if (!identity) {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
}
- const root = this.contentRootDir();
- const dir = path.join(root, id);
- // 双保险:id 格式校验已排除路径穿越,这里再确认是 root 的直接子目录。
- if (path.dirname(dir) !== path.resolve(root) && path.dirname(dir) !== root) {
- return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
+ const relId = this.resolvePhysicalRelId(id) ?? pluginInstallRelId(identity);
+ const dir = this.contentPath(relId);
+ const pending = this.receiptStore.readPendingMutationSync(relId);
+ const existingUninstall = pending.state === 'valid' && pending.mutation.kind === 'uninstall'
+ ? pending.mutation : null;
+ if (pending.state !== 'missing' && !existingUninstall) {
+ this.untrustedApprovals.add(this.isolationKey(relId));
+ return { rejection: { code: 'io', reason: '意识正在恢复,请稍后重试' } };
}
- if (!this.isRealDirChild(root, id)) {
- return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
+ if (!this.isRealDirChildRel(relId)) {
+ return { rejection: { code: 'not-installed', reason: `意识 ${identity.ghostId} 未装入` } };
}
// 顺序是安全要点:先撤批准(receipt + 快照 + 隔离),再删内容目录。反过来(旧写法)
// 若崩在两步之间,会留下"孤立 approved receipt + 目录暂缺";之后同 id 路径被恢复/
// 同权限进程新建目录时,list() 会拿这份陈旧 receipt 授权那个目录(manifest/slots/
// trust 全来自 receipt),等于卸载过的插件被"借尸还魂"。事务标记让崩溃后的启动恢复
// 把这次卸载收尾干净。
- const builtinTombstone =
- options.recordBuiltinTombstone !== false && this.options.isTrustedBundledId?.(id) === true;
- await this.receiptStore.writePendingMutation(id, {
- kind: 'uninstall',
- ...(builtinTombstone ? { builtinTombstone: true } : {}),
- });
- this.untrustedApprovals.add(this.isolationKey(id));
+ const builtinTombstone = existingUninstall ? existingUninstall.builtinTombstone === true :
+ options.recordBuiltinTombstone !== false && identity.namespace === null &&
+ this.options.isTrustedBundledId?.(identity.ghostId) === true;
+ const previouslyQuarantined = this.untrustedApprovals.has(this.isolationKey(relId));
+ if (!existingUninstall) {
+ await this.receiptStore.writePendingMutation(relId, {
+ kind: 'uninstall',
+ ...(builtinTombstone ? { builtinTombstone: true } : {}),
+ });
+ }
+ this.untrustedApprovals.add(this.isolationKey(relId));
if (builtinTombstone) {
try {
if (!this.options.recordBuiltinTombstone) {
throw new Error('builtin uninstall has no tombstone writer');
}
- this.options.recordBuiltinTombstone(id);
+ this.options.recordBuiltinTombstone(identity.ghostId);
} catch (err) {
- // Tombstone persistence is part of the uninstall transaction. If it
- // fails, roll back the pending journal and in-process quarantine so a
- // reported failure cannot be completed by startup recovery later.
- const journalCleared = await this.receiptStore
- .clearPendingMutation(id)
- .then(() => true)
- .catch(() => false);
- if (journalCleared) this.untrustedApprovals.delete(this.isolationKey(id));
+ if (!existingUninstall) {
+ const journalCleared = await this.receiptStore
+ .clearPendingMutation(relId)
+ .then(() => true)
+ .catch(() => false);
+ if (journalCleared && !previouslyQuarantined) this.untrustedApprovals.delete(this.isolationKey(relId));
+ }
return {
rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
};
@@ -3724,7 +4507,7 @@ export class GhostManager {
}
// 走同一个撤销入口:成功即清掉隔离记录,失败由该入口转进程内隔离并记日志。撤批准
// 在删目录之前 —— 即便随后删目录失败/崩溃,也不会留下"目录在 + 旧 receipt 授权"。
- const approvalRemoved = await this.removeInstallApprovalUnlocked(id);
+ const approvalRemoved = await this.removeInstallApprovalUnlocked(relId);
try {
await fs.promises.rm(dir, { recursive: true, force: true });
} catch (err) {
@@ -3737,12 +4520,21 @@ export class GhostManager {
// Receipt 删除失败时保留 uninstall journal,即使内容目录已经删掉;下次启动
// 仍需据 journal 清理孤立 receipt,不能让进程内隔离随重启丢失。
if (approvalRemoved) {
- await this.receiptStore.clearPendingMutation(id).catch(() => undefined);
- this.untrustedApprovals.delete(this.isolationKey(id));
+ try {
+ this.forgetPendingNamespaceMigration(relId);
+ await this.receiptStore.clearPendingMutation(relId).catch(() => undefined);
+ this.untrustedApprovals.delete(this.isolationKey(relId));
+ } catch (error) {
+ this.untrustedApprovals.add(this.isolationKey(relId));
+ this.options.log?.warn('ghost uninstall left journal for namespace cleanup', {
+ id: relId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
} else {
- this.options.log?.warn('ghost uninstall left journal for approval cleanup', { id });
+ this.options.log?.warn('ghost uninstall left journal for approval cleanup', { id: relId });
}
- this.options.log?.info('ghost uninstalled', { id });
+ this.options.log?.info('ghost uninstalled', { id: relId });
if (options.notify !== false) this.options.onChanged?.(this.list());
return { ok: true };
}
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 99d0a2c5af..3ec9a1b8f0 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -13,7 +13,7 @@ import {
validateGhostManifest,
type InstalledGhost,
} from '../../../shared/ghost';
-import { CINDY_OFFICIAL_GHOST_TRUST, GhostManager, readLegacyGhostApprovalProjection } from '../GhostManager';
+import { CINDY_OFFICIAL_GHOST_TRUST, GhostManager, readLegacyGhostApprovalProjection, type GhostManagerOptions } from '../GhostManager';
import {
installedFileModeFromZip,
unixPermissionsForRepackedEntry,
@@ -21,7 +21,9 @@ import {
import { signGhostPackage } from '../ghostSignature';
import { GhostInstallReceiptStore, hashApprovedSkillContent } from '../ghostInstallReceipt';
import { forgeInstallOriginForMembership } from '../forgeOidcInstallConfirmBridge';
+import { installedGhostPhysicalRelId, installedGhostStoragePart, pluginInstallStoragePart } from '../../../shared/pluginIdentity';
import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess';
+import { writeTestCindyPackage } from './cindyPackageFixture';
const canLinkFile = (() => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ghost-manager-file-link-probe-'));
@@ -94,6 +96,23 @@ function goodManifest(id = 'hello'): Record<string, unknown> {
};
}
+describe('GhostManager enable revision boundary', () => {
+ it('rejects a delayed enable change bound to an obsolete approval revision', async () => {
+ await manager.install(await makeCindy('original.cindy', goodManifest(), { 'main.js': 'module.exports = {};' }));
+ const original = manager.list()[0];
+ const id = installedGhostPhysicalRelId(original);
+ const originalApproval = ghostInstallApprovalToken(original.approval);
+ await updateGhost(await makeCindy('replacement.cindy', { ...goodManifest(), version: '2.0.0' },
+ { 'main.js': 'module.exports = { updated: true };' }));
+ const result = await manager.setEnabled(id, false, originalApproval);
+ await expectRejection(result, 'not-installed');
+ expect(manager.list()[0].enabled).toBe(true);
+ expect(await manager.setEnabled(id, false, ghostInstallApprovalToken(manager.list()[0].approval)))
+ .toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(false);
+ });
+});
+
describe('installedFileModeFromZip', () => {
it('normalizes strings, strips special bits, and skips Windows or missing metadata', () => {
expect(installedFileModeFromZip('755', 'linux')).toBe(0o755);
@@ -152,13 +171,24 @@ async function makeCindy(
manifest: Record<string, unknown> | null,
entries: Record<string, string | Buffer> = {},
): Promise<string> {
- const zip = new JSZip();
- if (manifest) zip.file('ghost.json', JSON.stringify(manifest));
- for (const [name, content] of Object.entries(entries)) zip.file(name, content);
- const buf = await zip.generateAsync({ type: 'nodebuffer' });
- const out = path.join(workDir, fileName);
- await fs.promises.writeFile(out, buf);
- return out;
+ return writeTestCindyPackage(path.join(workDir, fileName), manifest, entries);
+}
+
+async function installLegacyApproved(file: string): Promise<void> {
+ const result = await manager.install(file);
+ expect(result).toHaveProperty('ghost');
+ if (!('ghost' in result)) return;
+ const ghostId = result.ghost.manifest.id;
+ await fs.promises.rename(result.ghost.dir, path.join(rootDir, ghostId));
+ const stateRoot = manager.approvalStateRoot();
+ await fs.promises.rename(
+ path.join(stateRoot, '_ns', '_root', ghostId + '.json'),
+ path.join(stateRoot, ghostId + '.json'),
+ );
+ await fs.promises.rename(
+ path.join(stateRoot, '.migrated-_ns._root.' + ghostId),
+ path.join(stateRoot, '.migrated-' + ghostId),
+ );
}
/** 用 UNIX central-directory metadata 构造 mode 回归包。 */
@@ -308,6 +338,21 @@ describe('hashApprovedSkillContent · item.dir 路径段校验', () => {
});
describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {
+ it.each([null, 'acme'] as const)('binds task approval to the selected instance %s', async (namespace) => {
+ const manifest = { ...goodManifest(), slots: ['tool', 'agent'], agent: { tasks: true } };
+ const pkg = await makeCindy('tasks.cindy', manifest, { 'main.js': '// plugin' });
+ await manager.install(pkg);
+ await manager.install(pkg, { namespace: 'acme' });
+ const selected = manager.list().find(ghost => (ghost.namespace ?? null) === namespace)!;
+ const other = manager.list().find(ghost => ghost.dir !== selected.dir)!;
+ const instanceId = installedGhostStoragePart(selected);
+ if (selected.approval.state !== 'approved' || other.approval.state !== 'approved') throw new Error('fixture not approved');
+ expect(await manager.approveTaskCapability(instanceId, other.approval.revision, () => true)).toBe(false);
+ expect(await manager.approveTaskCapability(instanceId, selected.approval.revision, () => true)).toBe(true);
+ expect(manager.list().find(ghost => installedGhostStoragePart(ghost) === instanceId)?.taskCapabilityApproved).toBe(true);
+ expect(manager.list().find(ghost => installedGhostStoragePart(ghost) !== instanceId)?.taskCapabilityApproved).toBeUndefined();
+ });
+
it.each(['future', { future: true }, ['future'], null, false])('keeps historical unknown tasks %j enabled without task approval', async (tasks) => {
await writeLegacyInstall('hello', {...goodManifest(), slots:['tool','agent'], agent:{tasks}});
await manager.migrateLegacyApprovalsOnce();
@@ -650,7 +695,7 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
});
it('已有 receipt 不可读后即使消失也不从可变安装目录重铸', async () => {
- await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await installLegacyApproved(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/权限瞬时锁住。
@@ -708,7 +753,7 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
});
it('修复 #1080 历史 mixed 状态:有效 receipt 不封死其余 legacy/旧 schema 插件', async () => {
- await manager.install(await makeCindy('approved.cindy', goodManifest('approved')));
+ await installLegacyApproved(await makeCindy('approved.cindy', goodManifest('approved')));
const approvedReceiptPath = path.join(workDir, 'ghosts-install-state', 'approved.json');
const approvedReceiptBefore = await fs.promises.readFile(approvedReceiptPath, 'utf8');
@@ -737,7 +782,7 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
});
it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {
- await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await installLegacyApproved(await makeCindy('a.cindy', goodManifest()));
const before = await fs.promises.readFile(
path.join(workDir, 'ghosts-install-state', 'hello.json'),
'utf8',
@@ -985,7 +1030,7 @@ describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命
it('启用失败的回滚按"镜像先前是否在盘上",不吞掉旧客户端的停用决定', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
// 旧客户端只写镜像:receipt.enabled=true + .disabled 在盘 → 读时合并 = 停用。
- const marker = path.join(rootDir, 'hello', '.disabled');
+ const marker = path.join(rootDir, '_ns', '_root', 'hello', '.disabled');
await fs.promises.writeFile(marker, '');
expect(manager.list()[0].enabled).toBe(false);
@@ -1159,18 +1204,14 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
expect(fs.existsSync(migrationLedgerPath())).toBe(false);
// 攻击:删掉 receipt,指望整个插件消失变成 legacy-unapproved。
// 不加 slot 修改(避免 backfillLegacyApproval 校验失败进入 failed 分支)。
- await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
- // Per-id migration marker prevents backfill. Without the marker, the
- // coordinator would re-approve from the current mutable directory. With
- // the marker, the system knows this was a new-model install whose receipt
- // was deleted — not a legacy install. It stays fail-closed.
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'));
const outcome = await manager.migrateLegacyApprovalsOnce();
- expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [], retryPending: [] });
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });
expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
});
it('P0-2: unreadable per-id migration marker keeps deleted receipt fail-closed', async () => {
- await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await installLegacyApproved(await makeCindy('a.cindy', goodManifest()));
await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
const marker = path.join(workDir, 'ghosts-install-state', '.migrated-hello');
@@ -1201,40 +1242,44 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
// install, and the migration door stays open for the coordinator.
const result = await manager.install(await makeCindy('a.cindy', goodManifest()));
expect('ghost' in result).toBe(true);
- expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'))).toBe(true);
expect(fs.existsSync(migrationLedgerPath())).toBe(false);
// Door remains open: coordinator can still run.
expect(manager.list()).toHaveLength(1);
});
it('首次批准与目录回滚同时失败时保留 install journal,不让迁移收编未提交字节', async () => {
- const finalDir = path.join(rootDir, 'hello');
- // The ledger auto-close is removed; without ledger-level failure injection
- // the install succeeds normally. The rollback path (rm finalDir) is only
- // reached when a previous step fails; a healthy install never hits it.
- // The migration door remains open; the coordinator handles this by
- // finding a valid receipt and skipping hello.
- const result = await manager.install(await makeCindy('a.cindy', goodManifest()));
- expect('ghost' in result).toBe(true);
-
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const write = vi.spyOn(store, 'write').mockRejectedValueOnce(new Error('receipt blocked'));
+ const realRm = fs.promises.rm;
+ const remove = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === finalDir) throw new Error('rollback blocked');
+ return realRm(target, options);
+ });
+ try {
+ await expectRejection(await manager.install(await makeCindy('a.cindy', goodManifest())), 'io');
+ } finally {
+ write.mockRestore();
+ remove.mockRestore();
+ }
expect(fs.existsSync(finalDir)).toBe(true);
- expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);
+ expect(store.readPendingMutationSync('_ns/_root/hello').state).toBe('valid');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'))).toBe(false);
expect(fs.existsSync(migrationLedgerPath())).toBe(false);
-
const migration = await manager.migrateLegacyApprovalsOnce();
- // Coordinator finds approved receipt for hello → skipped (already has receipt).
expect(migration.migrated).toEqual([]);
- expect(migration.skipped).toEqual(['hello']);
+ expect(migration.skipped).toEqual([]);
expect(manager.list()).toHaveLength(1);
-
+ expect(manager.list()[0].approval.state).not.toBe('approved');
const recovered = new GhostManager({
getRootDir: () => rootDir,
getLocale: () => hostLocale,
onChanged,
});
- // Receipt persisted → plugin visible across manager instances.
- expect(recovered.list()).toHaveLength(1);
- expect(fs.existsSync(finalDir)).toBe(true);
+ expect(recovered.list()).toHaveLength(0);
+ expect(fs.existsSync(finalDir)).toBe(false);
+ expect(store.readPendingMutationSync('_ns/_root/hello').state).toBe('missing');
});
it('P0-2:安装根读失败(EACCES 类)本轮放弃且不落台账,不把迁移永久封死', async () => {
@@ -1389,7 +1434,7 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
});
it('closes the recovery ledger when a queued id is already approved', async () => {
- await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await installLegacyApproved(await makeCindy('a.cindy', goodManifest()));
await fs.promises.writeFile(
migrationLedgerPath(),
JSON.stringify({
@@ -1434,7 +1479,7 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
});
it('恢复旁路遇到 unreadable receipt 后不再允许自动重铸批准', async () => {
- await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await installLegacyApproved(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(), { force: true });
@@ -1573,7 +1618,7 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
it('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
- const finalDir = path.join(rootDir, 'hello');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
const realRename = fs.promises.rename;
const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
// staging→final 与 backup→final 都失败(Windows 文件锁/AV 的典型形态)。
@@ -1590,7 +1635,7 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
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')),
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json')),
).toBe(true);
} finally {
spy.mockRestore();
@@ -1600,15 +1645,65 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {
const pendingMarkerPath = (id = 'hello') =>
- path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);
+ path.join(workDir, 'ghosts-install-state', ...id.split('/').slice(0, -1), '.pending-' + id.split('/').at(-1) + '.json');
const receiptPath = (id = 'hello') =>
path.join(workDir, 'ghosts-install-state', `${id}.json`);
/** 在同一组根上新建 manager —— 构造期跑一次崩溃恢复扫描。 */
const freshManager = () =>
new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
- it('rejects cancellation during install preparation before publishing bytes and allows retry', async () => {
+ it('does not recover a live update while its directory swap is waiting', async () => {
+ await manager.install(
+ await makeCindy('old.cindy', goodManifest(), { 'main.js': '// old bytes\n' }),
+ { namespace: 'acme' },
+ );
+ const oldApproval = manager.list()[0]!.approval;
+ const finalDir = path.join(rootDir, '_ns', 'acme', 'hello');
+ const marker = path.join(workDir, 'ghosts-install-state', '_ns', 'acme', '.pending-hello.json');
+ let enterRename!: () => void;
+ let resumeRename!: () => void;
+ const renameEntered = new Promise<void>((resolve) => { enterRename = resolve; });
+ const renameGate = new Promise<void>((resolve) => { resumeRename = resolve; });
+ const realRename = fs.promises.rename;
+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (path.resolve(String(from)) === path.resolve(finalDir) &&
+ path.basename(String(to)).startsWith('.cindy-updating-')) {
+ enterRename();
+ await renameGate;
+ }
+ return realRename(from, to);
+ });
+ try {
+ const update = manager.update(
+ await makeCindy('new.cindy', { ...goodManifest(), version: '2.0.0' }, { 'main.js': '// new bytes\n' }),
+ { expectedInstalledApproval: ghostInstallApprovalToken(oldApproval), namespace: 'acme' },
+ );
+ await renameEntered;
+ expect(fs.existsSync(marker)).toBe(true);
+ const retry = manager.retryInterruptedMutationsAfterDbReady();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ const stillProtected = fs.existsSync(marker) && manager.list()[0]?.approval.state === 'invalid';
+ resumeRename();
+ const [updated] = await Promise.all([update, retry]);
+ expect(stillProtected).toBe(true);
+ expect(updated).toHaveProperty('ghost');
+ expect(manager.list()[0]).toMatchObject({
+ manifest: { version: '2.0.0' },
+ approval: { state: 'approved' },
+ });
+ expect(fs.readFileSync(path.join(finalDir, 'main.js'), 'utf8')).toBe('// new bytes\n');
+ } finally {
+ resumeRename();
+ spy.mockRestore();
+ }
+ });
+
+ it.each([null, 'acme'] as const)('rejects %s install cancellation before publishing bytes and clears physical journals on retry and update', async (namespace) => {
const file = await makeCindy('cancelled.cindy', goodManifest());
+ const relId = namespace === null ? '_ns/_root/hello' : '_ns/acme/hello';
+ const finalDir = path.join(rootDir, ...relId.split('/'));
+ const marker = pendingMarkerPath(relId);
+ const siblingMarker = pendingMarkerPath(namespace === null ? '_ns/acme/hello' : '_ns/_root/hello');
const controller = new AbortController();
const writePending = GhostInstallReceiptStore.prototype.writePendingMutation;
const pendingSpy = vi.spyOn(GhostInstallReceiptStore.prototype, 'writePendingMutation')
@@ -1617,23 +1712,48 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
controller.abort();
});
const guard = vi.fn(() => {
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(marker)).toBe(true);
+ expect(fs.existsSync(finalDir)).toBe(false);
controller.signal.throwIfAborted();
});
try {
- await expectRejection(await manager.install(file, { beforePackagePlacement: guard }), 'io');
+ await expectRejection(await manager.install(file, { namespace, beforePackagePlacement: guard }), 'io');
expect(guard).toHaveBeenCalledOnce();
expect(manager.list()).toEqual([]);
- expect(fs.existsSync(pendingMarkerPath())).toBe(false);
- expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(fs.existsSync(marker)).toBe(false);
+ expect(fs.existsSync(siblingMarker)).toBe(false);
+ expect(fs.existsSync(receiptPath(relId))).toBe(false);
expect((await fs.promises.readdir(rootDir)).filter(name => name.startsWith('.cindy-installing-'))).toEqual([]);
expect(onChanged).not.toHaveBeenCalled();
} finally {
pendingSpy.mockRestore();
}
- const retried = await manager.install(file);
- expect(retried).toMatchObject({ ghost: { manifest: { id: 'hello' }, enabled: true } });
+ const installed = await manager.install(file, { namespace });
+ expect(installed).toMatchObject({
+ ghost: { manifest: { id: 'hello' }, namespace, enabled: true },
+ });
+ expect(fs.existsSync(marker)).toBe(false);
+ expect(fs.existsSync(siblingMarker)).toBe(false);
+ expect(fs.existsSync(path.join(finalDir, 'ghost.json'))).toBe(true);
+
+ const recovered = freshManager();
+ expect(recovered.list()).toEqual([
+ expect.objectContaining({
+ namespace,
+ approval: expect.objectContaining({ state: 'approved' }),
+ }),
+ ]);
+
+ const bumped = await makeCindy('ns-journal-v2.cindy', { ...goodManifest(), version: '1.0.1' });
+ const updated = await manager.update(bumped, {
+ expectedInstalledApproval: ghostInstallApprovalToken(
+ (installed as { ghost: InstalledGhost }).ghost.approval,
+ ),
+ namespace,
+ });
+ expect('ghost' in updated).toBe(true);
+ expect(fs.existsSync(marker)).toBe(false);
+ expect(fs.existsSync(siblingMarker)).toBe(false);
});
it('崩溃的装入(有 finalDir、无 receipt、有 install 标记)被恢复删除,不被迁移收编', async () => {
@@ -1675,8 +1795,8 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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({
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(true);
+ expect(JSON.parse(await fs.promises.readFile(pendingMarkerPath('_ns/_root/hello'), 'utf8'))).toMatchObject({
kind: 'install',
clearBuiltinTombstone: true,
});
@@ -1689,7 +1809,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
});
expect(clearBuiltinTombstone).toHaveBeenCalledTimes(2);
- expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(false);
expect(recoveredAfterClearFailure.list()[0]).toMatchObject({
approval: { state: 'approved' },
});
@@ -1697,7 +1817,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
it('install 恢复必须用 packageSha256 证明旧 receipt 属于这次安装', async () => {
await manager.install(await makeCindy('old.cindy', goodManifest()));
- const finalDir = path.join(rootDir, 'hello');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
await fs.promises.rm(finalDir, { recursive: true, force: true });
await fs.promises.mkdir(finalDir, { recursive: true });
await fs.promises.writeFile(
@@ -1705,12 +1825,12 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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.mkdir(path.dirname(pendingMarkerPath('_ns/_root/hello')), { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'install',
packageSha256: 'f'.repeat(64),
}),
@@ -1718,23 +1838,23 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
expect(fs.existsSync(finalDir)).toBe(false);
- expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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';
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupName = '.cindy-updating-_root__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.mkdir(path.dirname(pendingMarkerPath('_ns/_root/hello')), { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: 'f'.repeat(64),
backupDirName: '..\\outside',
@@ -1743,7 +1863,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
const recovered = freshManager();
expect(fs.existsSync(path.join(rootDir, backupName))).toBe(true);
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(true);
expect(recovered.list()[0]).toMatchObject({
enabled: false,
approval: { state: 'invalid' },
@@ -1752,13 +1872,13 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__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');
+ const invalidMarker = path.join(path.dirname(pendingMarkerPath('_ns/_root/hello')), '.pending-BAD!.json');
await fs.promises.writeFile(invalidMarker, '{}');
const recovered = freshManager();
@@ -1772,18 +1892,18 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__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');
+ await fs.promises.writeFile(pendingMarkerPath('_ns/_root/hello'), 'null');
const recovered = freshManager();
expect(fs.existsSync(finalDir)).toBe(true);
expect(fs.existsSync(backupDir)).toBe(true);
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(true);
expect(recovered.list()[0]).toMatchObject({
enabled: false,
approval: { state: 'invalid' },
@@ -1792,16 +1912,16 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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');
+ const stateRoot = path.dirname(pendingMarkerPath('_ns/_root/hello'));
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__hello-abcdef12');
+ const stagingDir = path.join(rootDir, '.cindy-installing-_root__hello-deadbeef');
await fs.promises.mkdir(backupDir, { recursive: true });
await fs.promises.mkdir(stagingDir, { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: 'f'.repeat(64),
backupDirName: path.basename(backupDir),
@@ -1826,16 +1946,16 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
// 未提交 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(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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 stateRoot = path.dirname(pendingMarkerPath('_ns/_root/hello'));
const realReaddirSync = fs.readdirSync;
const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
const resolved = path.resolve(String(target));
@@ -1858,15 +1978,71 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
});
});
+ it.each(['EACCES', 'EIO'])('namespaced journal directory %s keeps an interrupted update isolated and recoverable', async (errorCode) => {
+ await manager.install(
+ await makeCindy('ns-before.cindy', goodManifest(), { 'main.js': '// old bytes\n' }),
+ { namespace: 'acme' },
+ );
+ const finalDir = path.join(rootDir, '_ns', 'acme', 'hello');
+ const backupName = '.cindy-updating-_ns__acme__hello-abcdef12';
+ const backupDir = path.join(rootDir, backupName);
+ const stateDir = path.join(workDir, 'ghosts-install-state', '_ns', 'acme');
+ const marker = path.join(stateDir, '.pending-hello.json');
+ await fs.promises.writeFile(marker, JSON.stringify({
+ version: 1,
+ id: '_ns/acme/hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ receiptRevision: crypto.randomUUID(),
+ backupDirName: backupName,
+ phase: 'published',
+ }));
+ 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(), version: '1.0.1' }),
+ );
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), '// new bytes\n');
+
+ const realReaddirSync = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
+ if (path.resolve(String(target)) === path.resolve(stateDir)) {
+ throw Object.assign(new Error(errorCode + ': organization journal unavailable'), { code: errorCode });
+ }
+ 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' } });
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(marker)).toBe(true);
+
+ await recovered.retryInterruptedMutationsAfterDbReady();
+ expect(recovered.list()[0]).toMatchObject({
+ manifest: { version: '1.0.0' },
+ enabled: true,
+ approval: { state: 'approved' },
+ });
+ expect(fs.existsSync(marker)).toBe(false);
+ expect(fs.existsSync(backupDir)).toBe(false);
+ expect(fs.readFileSync(path.join(finalDir, 'main.js'), 'utf8')).toBe('// old bytes\n');
+ });
+
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');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__hello-abcdef12');
await fs.promises.mkdir(backupDir, { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: 'f'.repeat(64),
backupDirName: path.basename(backupDir),
@@ -1877,7 +2053,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
// 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())) {
+ if (path.resolve(String(target)) === path.resolve(pendingMarkerPath('_ns/_root/hello'))) {
throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });
}
return (realOpenSync as (...args: unknown[]) => unknown)(target, ...rest);
@@ -1892,23 +2068,23 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
spy.mockRestore();
}
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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 {
+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8')) as {
packageSha256: string;
}).packageSha256;
await fs.promises.writeFile(
- pendingMarkerPath(),
- JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256 }),
+ pendingMarkerPath('_ns/_root/hello'),
+ JSON.stringify({ version: 1, id: '_ns/_root/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())) {
+ if (path.resolve(String(target)) === path.resolve(receiptPath('_ns/_root/hello'))) {
throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
}
return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);
@@ -1923,23 +2099,23 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
spy.mockRestore();
}
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
- expect(fs.existsSync(receiptPath())).toBe(true);
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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 {
+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8')) as {
packageSha256: string;
}).packageSha256;
- const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__hello-abcdef12');
await fs.promises.mkdir(backupDir, { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256,
backupDirName: path.basename(backupDir),
@@ -1947,7 +2123,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
);
const realOpenSync = fs.openSync;
const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
- if (path.resolve(String(target)) === path.resolve(receiptPath())) {
+ if (path.resolve(String(target)) === path.resolve(receiptPath('_ns/_root/hello'))) {
throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
}
return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);
@@ -1962,21 +2138,21 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
spy.mockRestore();
}
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
expect(fs.existsSync(backupDir)).toBe(true);
- expect(fs.existsSync(receiptPath())).toBe(true);
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__hello-abcdef12');
await fs.promises.mkdir(backupDir, { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: 'f'.repeat(64),
backupDirName: path.basename(backupDir),
@@ -1999,9 +2175,9 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
spy.mockRestore();
}
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
expect(fs.existsSync(backupDir)).toBe(true);
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(true);
});
it('动态 owner 根切换时,首次读取会先恢复新 owner 的 pending mutation', async () => {
@@ -2110,7 +2286,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
});
expect(fs.existsSync(path.join(rootA, 'hello'))).toBe(false);
- expect(fs.existsSync(path.join(stateA, 'hello.json'))).toBe(false);
+ expect(fs.existsSync(path.join(stateA, '_ns', '_root', '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',
@@ -2119,9 +2295,9 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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';
+ const receiptBefore = await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupName = '.cindy-updating-_root__hello-abcdef12';
// 模拟 staging→final 之后、写 receipt 之前崩溃:旧字节挪到 backup,新字节在 final,
// receipt 仍是旧的。标记的 packageSha256 与旧 receipt 不同 = 未提交。
@@ -2132,12 +2308,12 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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.mkdir(path.dirname(pendingMarkerPath('_ns/_root/hello')), { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: 'f'.repeat(64),
backupDirName: backupName,
@@ -2148,26 +2324,26 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(false);
// receipt 一字未动,与回滚后的旧字节自洽(不是"新字节 + 旧 receipt"的错位)。
- expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);
+ expect(await fs.promises.readFile(receiptPath('_ns/_root/hello'), '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 {
+ const committedReceipt = JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8')) as {
packageSha256: string;
revision: string;
};
- const backupName = '.cindy-updating-hello-abcdef34';
+ const backupName = '.cindy-updating-_root__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.mkdir(path.dirname(pendingMarkerPath('_ns/_root/hello')), { recursive: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: committedReceipt.packageSha256,
receiptRevision: committedReceipt.revision,
@@ -2178,23 +2354,23 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true); // 新版保留
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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 receiptBefore = await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8');
const receipt = JSON.parse(receiptBefore) as { packageSha256: string };
- const finalDir = path.join(rootDir, 'hello');
- const backupName = '.cindy-updating-hello-acde0011';
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupName = '.cindy-updating-_root__hello-acde0011';
await fs.promises.rename(finalDir, path.join(rootDir, backupName));
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: receipt.packageSha256,
oldPackageSha256: receipt.packageSha256,
@@ -2207,25 +2383,25 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(false);
+ expect(await fs.promises.readFile(receiptPath('_ns/_root/hello'), '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 {
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8')) as {
packageSha256: string;
};
- const finalDir = path.join(rootDir, 'hello');
- const backupName = '.cindy-updating-hello-acde0022';
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupName = '.cindy-updating-_root__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(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: receipt.packageSha256,
oldPackageSha256: receipt.packageSha256,
@@ -2239,28 +2415,28 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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 {
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8')) as {
packageSha256: string;
};
- await fs.promises.rm(path.join(rootDir, 'hello'), { recursive: true, force: true });
+ await fs.promises.rm(path.join(rootDir, '_ns', '_root', 'hello'), { recursive: true, force: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
+ pendingMarkerPath('_ns/_root/hello'),
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'install',
packageSha256: receipt.packageSha256,
}),
);
freshManager();
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
- expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(true);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(true);
expect(manager.list()).toEqual([]);
});
@@ -2270,7 +2446,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
// 让内容目录的 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')) {
+ if (String(p) === path.join(rootDir, '_ns', '_root', 'hello')) {
rmSpy.mockRestore();
const err = new Error('EBUSY: resource busy') as NodeJS.ErrnoException;
err.code = 'EBUSY';
@@ -2283,39 +2459,39 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
await expectRejection(res, 'io');
// 关键:撤批准在删目录之前 —— receipt 已没了,目录还在但 fail closed(list 报
// legacy-unapproved),不会被这份 receipt 授权。孤立标记留给启动恢复收尾。
- expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(false);
expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
- expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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.rm(receiptPath('_ns/_root/hello'), { force: true });
await fs.promises.writeFile(
- pendingMarkerPath(),
- JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),
+ pendingMarkerPath('_ns/_root/hello'),
+ JSON.stringify({ version: 1, id: '_ns/_root/hello', kind: 'uninstall' }),
);
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
freshManager(); // 构造期恢复
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
- expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).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' }),
+ pendingMarkerPath('_ns/_root/hello'),
+ JSON.stringify({ version: 1, id: '_ns/_root/hello', kind: 'uninstall' }),
);
- expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(true);
freshManager();
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
- expect(fs.existsSync(receiptPath())).toBe(false);
- expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath('_ns/_root/hello'))).toBe(false);
});
it('setEnabled 不跟随非真目录:<id> 是普通文件时按未装入拒,不越安装根写标记', async () => {
@@ -2327,7 +2503,7 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
it('setEnabled 不跟随 junction:<id> 是指向外部的链接时拒,不在外部目标写/删 .disabled', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
- const dir = path.join(rootDir, 'hello');
+ const dir = path.join(rootDir, '_ns', '_root', 'hello');
const outside = path.join(workDir, 'outside-target');
await fs.promises.mkdir(outside, { recursive: true });
await fs.promises.rm(dir, { recursive: true, force: true });
@@ -2346,11 +2522,11 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
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');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const stagingDir = path.join(rootDir, '.cindy-installing-_root__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 stateReceiptPath = path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json');
+ const statePendingPath = path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json');
const receipt = JSON.parse(await fs.promises.readFile(stateReceiptPath, 'utf8')) as {
packageSha256?: string;
};
@@ -2358,10 +2534,10 @@ describe('GhostManager · update pre-rename recovery', () => {
statePendingPath,
JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/hello',
kind: 'update',
packageSha256: 'f'.repeat(64),
- backupDirName: '.cindy-updating-hello-deadbeef',
+ backupDirName: '.cindy-updating-_root__hello-deadbeef',
phase: 'prepared',
oldPackageSha256: receipt.packageSha256,
}),
@@ -2385,7 +2561,7 @@ describe('GhostManager · install', () => {
);
expect(personal).toHaveProperty('ghost');
const personalReceipt = JSON.parse(
- await fs.promises.readFile(path.join(manager.approvalStateRoot(), 'personal.json'), 'utf8'),
+ await fs.promises.readFile(path.join(manager.approvalStateRoot(), '_ns', '_root', 'personal.json'), 'utf8'),
) as Record<string, unknown>;
expect(personalReceipt).toHaveProperty('installOrigin', 'agent-forge');
expect(manager.readEffectiveInstallOrigin('personal')).toBe('agent-forge');
@@ -2397,7 +2573,7 @@ describe('GhostManager · install', () => {
);
expect(forged).toHaveProperty('ghost');
const organizationReceipt = JSON.parse(
- await fs.promises.readFile(path.join(manager.approvalStateRoot(), 'acme-tool.json'), 'utf8'),
+ await fs.promises.readFile(path.join(manager.approvalStateRoot(), '_ns', '_root', 'acme-tool.json'), 'utf8'),
) as Record<string, unknown>;
expect(organizationReceipt).toHaveProperty('installOrigin', 'agent-forge');
expect(manager.readEffectiveInstallOrigin('acme-tool')).toBe('agent-forge');
@@ -2405,7 +2581,7 @@ describe('GhostManager · install', () => {
it('strict origin reading rejects unreadable, invalid, and non-approved receipts', async () => {
await manager.install(await makeCindy('strict-origin.cindy', goodManifest()));
- const receiptPath = path.join(manager.approvalStateRoot(), 'hello.json');
+ const receiptPath = path.join(manager.approvalStateRoot(), '_ns', '_root', 'hello.json');
const mockUnreadableOnce = (): void => {
const realOpenSync = fs.openSync;
const openSpy = vi.spyOn(fs, 'openSync');
@@ -2499,7 +2675,7 @@ describe('GhostManager · install', () => {
'locales/en.json': locale('Packaged name'),
});
await manager.install(cindy);
- const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');
+ const localePath = path.join(rootDir, '_ns', '_root', '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);
@@ -2579,15 +2755,105 @@ describe('GhostManager · install', () => {
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(ghost.dir).toBe(path.join(rootDir, '_ns', '_root', 'hello'));
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', '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.each([{}, { namespace: null }] as const)('persists root identity for install options %j', async (options) => {
+ const cindy = await makeCindy('hello.cindy', goodManifest());
+ const result = await manager.install(cindy, options);
+ expect(result).toMatchObject({
+ ghost: { manifest: { id: 'hello' }, namespace: null, dir: path.join(rootDir, '_ns', '_root', 'hello') },
+ });
+ expect(manager.list()[0]!.namespace).toBeNull();
+ const receipt = JSON.parse(
+ fs.readFileSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'), 'utf8'),
+ ) as { namespace?: unknown };
+ expect(receipt.namespace).toBeNull();
+ expect(Object.prototype.hasOwnProperty.call(receipt, 'namespace')).toBe(true);
+ });
+
+ it.each([undefined, 'Draw'] as const)('installs an organization instance beside the same root ghostId with command %s', async (command) => {
+ const rootManifest = command === undefined ? goodManifest() : chipManifestWithCommand('hello', command);
+ const orgManifest = command === undefined ? goodManifest() : chipManifestWithCommand('hello', command.toLowerCase());
+ const rootCindy = await makeCindy('hello-root.cindy', rootManifest);
+ await expect(manager.install(rootCindy)).resolves.toMatchObject({
+ ghost: { manifest: { id: 'hello' }, dir: path.join(rootDir, '_ns', '_root', 'hello') },
+ });
+ const orgCindy = await makeCindy('hello-org.cindy', orgManifest);
+ const orgResult = await manager.install(orgCindy, { namespace: 'acme' });
+ expect(orgResult).toMatchObject({
+ ghost: {
+ manifest: { id: 'hello' },
+ namespace: 'acme',
+ dir: path.join(rootDir, '_ns', 'acme', 'hello'),
+ },
+ });
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', 'acme', '.pending-hello.json'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json'))).toBe(false);
+ const listed = manager.list();
+ expect(listed).toHaveLength(2);
+ expect(listed.map((item) => [item.namespace ?? null, item.manifest.id])).toEqual(
+ expect.arrayContaining([
+ [null, 'hello'],
+ ['acme', 'hello'],
+ ]),
+ );
+
+ await expect(manager.setEnabled('_ns/acme/hello', false)).resolves.toEqual({ ok: true });
+ expect(manager.list().find((item) => item.namespace === 'acme')?.enabled).toBe(false);
+ expect(manager.list().find((item) => item.namespace == null)?.enabled).toBe(true);
+
+ await expect(manager.uninstall('_ns/acme/hello')).resolves.toEqual({ ok: true });
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+ expect(manager.list().map((item) => [item.namespace ?? null, item.manifest.id])).toEqual([
+ [null, 'hello'],
+ ]);
+ });
+ it('refuses a linked namespace parent before installing or uninstalling outside the managed root', async () => {
+ const outside = path.join(workDir, 'outside-namespaces');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ try {
+ await fs.promises.symlink(outside, path.join(rootDir, '_ns'), process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return;
+ }
+ const file = await makeCindy('linked-ns.cindy', goodManifest());
+ await expect(manager.install(file, { namespace: 'acme' })).rejects.toThrow(/namespace parent/);
+ expect(fs.existsSync(path.join(outside, 'acme', 'hello'))).toBe(false);
+ });
+
+
+ it('reads namespaced receipts from storage part and install rel id', async () => {
+ const organizationOrigin = forgeInstallOriginForMembership('org');
+ const result = await manager.install(
+ await makeCindy('hello-org.cindy', goodManifest()),
+ {
+ namespace: 'acme',
+ ...(organizationOrigin ? { installOrigin: organizationOrigin } : {}),
+ },
+ );
+ expect(result).toHaveProperty('ghost');
+ expect(manager.readEffectiveInstallOrigin('_ns__acme__hello')).toBe('agent-forge');
+ expect(manager.readEffectiveInstallOrigin('_ns/acme/hello')).toBe('agent-forge');
+ expect(manager.readApprovedInstallOriginStrict('_ns__acme__hello')).toBe('agent-forge');
+ expect(manager.approvedInstallEvidence('_ns__acme__hello')?.packageSha256).toEqual(
+ expect.stringMatching(/^[a-f0-9]{64}$/),
+ );
+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('manual');
+ });
+
it('returns the quarantined projection when install journal cleanup fails', async () => {
const store = (
manager as unknown as {
@@ -2620,12 +2886,12 @@ describe('GhostManager · install', () => {
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 });
+ await fs.promises.rm(path.join(rootDir, '_ns', '_root', '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'),
+ await fs.promises.readFile(path.join(rootDir, '_ns', '_root', 'cindy-github', '.cindy-trust.json'), 'utf8'),
) as { level?: unknown };
expect(receipt.level).toBe('cindy-official');
expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);
@@ -2635,7 +2901,7 @@ describe('GhostManager · install', () => {
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 metadataPath = path.join(rootDir, '_ns', '_root', '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`);
@@ -2647,7 +2913,7 @@ describe('GhostManager · install', () => {
const cindy = await makeCindy('at-resource.cindy', atResourceManifest());
await manager.install(cindy);
- const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');
+ const metadataPath = path.join(rootDir, '_ns', '_root', 'hello', '.cindy-trust.json');
const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<
string,
unknown
@@ -2666,7 +2932,7 @@ describe('GhostManager · install', () => {
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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(true);
// 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。
expect(onChanged).toHaveBeenCalledTimes(1);
expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);
@@ -2685,8 +2951,8 @@ describe('GhostManager · install', () => {
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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'assets', 'a.txt'))).toBe(true);
});
it('源文件不存在 → source-not-found', async () => {
@@ -2715,6 +2981,15 @@ describe('GhostManager · install', () => {
await expectRejection(await manager.install(out), 'file-invalid');
});
+ it('作者声明 namespace → file-invalid, v2 规范化前拒绝', async () => {
+ const cindy = await makeCindy('ns.cindy', { ...goodManifest(), namespace: 'xd' });
+ const result = await manager.install(cindy);
+ await expectRejection(result, 'file-invalid');
+ expect(result).toMatchObject({
+ rejection: { reason: 'ghost.json 不允许作者声明 namespace' },
+ });
+ });
+
it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {
const cindy = await makeCindy('decl.cindy', {
schemaVersion: 1,
@@ -2737,7 +3012,7 @@ describe('GhostManager · install', () => {
});
await expectRejection(await manager.inspect(cindy), 'file-invalid');
await expectRejection(await manager.install(cindy), 'file-invalid');
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
});
it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {
@@ -2794,7 +3069,7 @@ describe('GhostManager · install', () => {
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(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false); // staging 已清理,无半截安装
expect(onChanged).not.toHaveBeenCalled();
});
@@ -2812,7 +3087,7 @@ describe('GhostManager · install', () => {
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(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
expect(onChanged).not.toHaveBeenCalled();
},
);
@@ -2824,7 +3099,7 @@ describe('GhostManager · install', () => {
await manager.install(await makeCindy('b.cindy', goodManifest())),
'already-installed',
);
- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'ghost.json'))).toBe(true);
expect(onChanged).not.toHaveBeenCalled();
});
@@ -2834,13 +3109,14 @@ describe('GhostManager · install', () => {
await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),
'command-conflict',
);
- expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', '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', () => {
@@ -2850,7 +3126,7 @@ describe('GhostManager · uninstall', () => {
const result = await manager.uninstall('hello');
expect('ok' in result).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
expect(manager.list()).toEqual([]);
expect(onChanged).toHaveBeenCalledTimes(1);
expect(onChanged.mock.calls[0][0]).toEqual([]);
@@ -2871,15 +3147,15 @@ describe('GhostManager · uninstall', () => {
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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'))).toBe(false);
});
it('does not turn Host reconciliation cleanup into a user builtin tombstone', async () => {
@@ -2894,9 +3170,13 @@ describe('GhostManager · uninstall', () => {
expect(manager.list()).toEqual([]);
});
- it('rolls back builtin uninstall journal and quarantine when tombstone persistence fails', async () => {
+ it.each([false, true])('cancels only its new uninstall journal after tombstone failure with prior quarantine=%s', async (priorQuarantine) => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
trustedBundledIds.add('hello');
+ if (priorQuarantine) {
+ (manager as unknown as { untrustedApprovals: Set<string> }).untrustedApprovals
+ .add(manager.approvalStateRoot() + '\u0000_ns/_root/hello');
+ }
recordBuiltinTombstone.mockImplementationOnce(() => {
const error = new Error('access denied') as NodeJS.ErrnoException;
error.code = 'EACCES';
@@ -2907,34 +3187,223 @@ describe('GhostManager · uninstall', () => {
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(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'))).toBe(true);
expect(manager.list()[0]).toMatchObject({
manifest: { id: 'hello' },
- enabled: true,
- approval: { state: 'approved' },
+ enabled: !priorQuarantine,
+ approval: { state: priorQuarantine ? 'invalid' : 'approved' },
});
- expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json'))).toBe(
false,
);
});
+ it.each([null, 'acme'] as const)(
+ 'preserves a failed %s update journal when builtin uninstall would fail its tombstone', async (namespace) => {
+ const originalCode = 'module.exports = { original: true };';
+ const unpublishedCode = 'module.exports = { unpublished: true };';
+ const installed = await manager.install(await makeCindy('original.cindy', goodManifest(), { 'main.js': originalCode }), { namespace });
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const previous = store.readForRecovery(relId);
+ const actualRemove = fs.promises.rm;
+ const remove = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === installed.ghost.dir) throw new Error('rollback removal blocked');
+ return actualRemove(target, options);
+ });
+ const receiptWrite = vi.spyOn(store, 'write').mockRejectedValueOnce(new Error('receipt blocked'));
+ try {
+ expect(await manager.update(await makeCindy('unpublished.cindy', { ...goodManifest(), version: '2.0.0' }, { 'main.js': unpublishedCode }), {
+ namespace, expectedInstalledApproval: ghostInstallApprovalToken(installed.ghost.approval),
+ })).toMatchObject({ rejection: { code: 'io', rollbackFailed: true } });
+ } finally {
+ remove.mockRestore();
+ receiptWrite.mockRestore();
+ }
+ const pending = store.readPendingMutationSync(relId);
+ expect(pending).toMatchObject({ state: 'valid', mutation: { kind: 'update' } });
+ trustedBundledIds.add('hello');
+ recordBuiltinTombstone.mockImplementation(() => { throw new Error('tombstone blocked'); });
+ const pendingWrite = vi.spyOn(store, 'writePendingMutation');
+ const pendingClear = vi.spyOn(store, 'clearPendingMutation');
+ try {
+ expect(await manager.uninstall(relId)).toMatchObject({ rejection: { code: 'io' } });
+ expect(pendingWrite).not.toHaveBeenCalled();
+ expect(pendingClear).not.toHaveBeenCalled();
+ expect(store.readPendingMutationSync(relId)).toEqual(pending);
+ expect(store.readForRecovery(relId)).toEqual(previous);
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ expect(fs.readFileSync(path.join(installed.ghost.dir, 'main.js'), 'utf8')).toBe(unpublishedCode);
+ } finally {
+ pendingWrite.mockRestore();
+ pendingClear.mockRestore();
+ recordBuiltinTombstone.mockReset();
+ }
+ await manager.retryInterruptedMutationsAfterDbReady();
+ expect(store.readPendingMutationSync(relId).state).toBe('missing');
+ expect(store.readForRecovery(relId)).toEqual(previous);
+ expect(fs.readFileSync(path.join(installed.ghost.dir, 'main.js'), 'utf8')).toBe(originalCode);
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'approved' }, enabled: true });
+ expect(await manager.uninstall(relId)).toEqual({ ok: true });
+ expect(manager.list()).toEqual([]);
+ },
+ );
+
+ it.each([null, 'acme'].flatMap((namespace) =>
+ ['install', 'update', 'invalid', 'unreadable'].map((kind) => ({ namespace, kind }))))(
+ 'blocks $namespace uninstall without replacing its $kind journal, then allows repaired recovery', async ({ namespace, kind }) => {
+ const installed = await manager.install(await makeCindy('original.cindy', goodManifest()), { namespace });
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const previous = store.readForRecovery(relId);
+ if (previous.state !== 'approved') throw new Error('expected original approval');
+ const markerPath = path.join(manager.approvalStateRoot(), ...relId.split('/').slice(0, -1), '.pending-hello.json');
+ const update = {
+ kind: 'update' as const, packageSha256: 'a'.repeat(64), receiptRevision: crypto.randomUUID(),
+ phase: 'prepared' as const, backupDirName: '.cindy-updating-' + pluginInstallStoragePart(relId) + '-deadbeef',
+ oldPackageSha256: previous.receipt.packageSha256,
+ };
+ await store.writePendingMutation(relId, kind === 'install'
+ ? { kind: 'install', packageSha256: previous.receipt.packageSha256!, receiptRevision: previous.receipt.revision }
+ : update);
+ if (kind === 'invalid') fs.writeFileSync(markerPath, '{');
+ const markerBytes = fs.readFileSync(markerPath);
+ const read = kind === 'unreadable'
+ ? vi.spyOn(store, 'readPendingMutationSync').mockReturnValue({ state: 'unreadable', reason: 'journal locked' })
+ : undefined;
+ const pendingWrite = vi.spyOn(store, 'writePendingMutation');
+ const pendingClear = vi.spyOn(store, 'clearPendingMutation');
+ try {
+ expect(await manager.uninstall(relId)).toMatchObject({ rejection: { code: 'io' } });
+ expect(fs.readFileSync(markerPath)).toEqual(markerBytes);
+ expect(store.readForRecovery(relId)).toEqual(previous);
+ expect(pendingWrite).not.toHaveBeenCalled();
+ expect(pendingClear).not.toHaveBeenCalled();
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ } finally {
+ read?.mockRestore();
+ pendingWrite.mockRestore();
+ pendingClear.mockRestore();
+ }
+ if (kind === 'invalid') await store.writePendingMutation(relId, update);
+ await manager.retryInterruptedMutationsAfterDbReady();
+ expect(store.readPendingMutationSync(relId).state).toBe('missing');
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'approved' }, enabled: true });
+ expect(await manager.uninstall(relId)).toEqual({ ok: true });
+ expect(manager.list()).toEqual([]);
+ },
+ );
+
+ it.each([null, 'acme'] as const)(
+ 'retries an existing %s uninstall journal without cancelling its tombstone intention', async (namespace) => {
+ const installed = await manager.install(await makeCindy('original.cindy', goodManifest()), { namespace });
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ await store.writePendingMutation(relId, { kind: 'uninstall', builtinTombstone: true });
+ const pending = store.readPendingMutationSync(relId);
+ recordBuiltinTombstone.mockImplementationOnce(() => { throw new Error('tombstone blocked'); });
+ const pendingWrite = vi.spyOn(store, 'writePendingMutation');
+ const pendingClear = vi.spyOn(store, 'clearPendingMutation');
+ try {
+ expect(await manager.uninstall(relId, { recordBuiltinTombstone: false })).toMatchObject({ rejection: { code: 'io' } });
+ expect(store.readPendingMutationSync(relId)).toEqual(pending);
+ expect(pendingWrite).not.toHaveBeenCalled();
+ expect(pendingClear).not.toHaveBeenCalled();
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ expect(await manager.uninstall(relId, { recordBuiltinTombstone: false })).toEqual({ ok: true });
+ expect(recordBuiltinTombstone).toHaveBeenCalledTimes(2);
+ expect(recordBuiltinTombstone).toHaveBeenLastCalledWith('hello');
+ expect(pendingWrite).not.toHaveBeenCalled();
+ expect(store.readPendingMutationSync(relId).state).toBe('missing');
+ } finally {
+ pendingWrite.mockRestore();
+ pendingClear.mockRestore();
+ }
+ expect(manager.list()).toEqual([]);
+ },
+ );
+
+ it.each([null, 'acme'] as const)('keeps an existing %s uninstall without a tombstone intent unchanged', async (namespace) => {
+ const installed = await manager.install(await makeCindy('original.cindy', goodManifest()), { namespace });
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ trustedBundledIds.add('hello');
+ await store.writePendingMutation(relId, { kind: 'uninstall' });
+ const pendingWrite = vi.spyOn(store, 'writePendingMutation');
+ try {
+ expect(await manager.uninstall(relId)).toEqual({ ok: true });
+ expect(recordBuiltinTombstone).not.toHaveBeenCalled();
+ expect(pendingWrite).not.toHaveBeenCalled();
+ expect(store.readPendingMutationSync(relId).state).toBe('missing');
+ expect(manager.list()).toEqual([]);
+ } finally {
+ pendingWrite.mockRestore();
+ }
+ });
+
+ it.each([null, 'acme'] as const)('finishes %s uninstall approval cleanup through retry recovery after its directory is gone', async (namespace) => {
+ const installed = await manager.install(await makeCindy('original.cindy', goodManifest()), { namespace });
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const remove = vi.spyOn(store, 'remove').mockRejectedValueOnce(new Error('approval cleanup blocked'));
+ try {
+ expect(await manager.uninstall(relId)).toEqual({ ok: true });
+ } finally {
+ remove.mockRestore();
+ }
+ expect(fs.existsSync(installed.ghost.dir)).toBe(false);
+ expect(store.readForRecovery(relId).state).toBe('approved');
+ const pending = store.readPendingMutationSync(relId);
+ expect(pending).toMatchObject({ state: 'valid', mutation: { kind: 'uninstall' } });
+ expect(await manager.uninstall(relId)).toMatchObject({ rejection: { code: 'not-installed' } });
+ expect(store.readPendingMutationSync(relId)).toEqual(pending);
+ await manager.retryInterruptedMutationsAfterDbReady();
+ expect(store.readForRecovery(relId).state).toBe('missing');
+ expect(store.readPendingMutationSync(relId).state).toBe('missing');
+ expect(manager.list()).toEqual([]);
+ });
+
+ it.skipIf(!canLinkFile).each([null, 'acme'] as const)('does not resume %s uninstall through a linked final directory', async (namespace) => {
+ const installed = await manager.install(await makeCindy('original.cindy', goodManifest()), { namespace });
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const outside = path.join(workDir, 'outside-uninstall');
+ fs.mkdirSync(outside);
+ fs.writeFileSync(path.join(outside, 'sentinel'), 'keep');
+ fs.rmSync(installed.ghost.dir, { recursive: true, force: true });
+ fs.symlinkSync(outside, installed.ghost.dir, process.platform === 'win32' ? 'junction' : 'dir');
+ await store.writePendingMutation(relId, { kind: 'uninstall' });
+ const pending = store.readPendingMutationSync(relId);
+ const previous = store.readForRecovery(relId);
+ expect(await manager.uninstall(relId)).toMatchObject({ rejection: { code: 'not-installed' } });
+ expect(store.readPendingMutationSync(relId)).toEqual(pending);
+ expect(store.readForRecovery(relId)).toEqual(previous);
+ expect(fs.readFileSync(path.join(outside, 'sentinel'), 'utf8')).toBe('keep');
+ });
+
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'),
+ path.join(stateDir, '_ns', '_root', '.pending-hello.json'),
`${JSON.stringify({
version: 1,
- id: 'hello',
+ id: '_ns/_root/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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'))).toBe(true);
});
const recovered = new GhostManager({
@@ -2946,9 +3415,9 @@ describe('GhostManager · uninstall', () => {
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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json'))).toBe(false);
+ expect(fs.existsSync(path.join(stateDir, '_ns', '_root', '.pending-hello.json'))).toBe(false);
});
it('卸未装的 id → not-installed', async () => {
@@ -2985,12 +3454,12 @@ describe('GhostManager · list', () => {
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.mkdir(path.join(rootDir, '_ns', '_root', 'no-manifest'));
+ await fs.promises.mkdir(path.join(rootDir, '_ns', '_root', 'bad-manifest'));
+ await fs.promises.writeFile(path.join(rootDir, '_ns', '_root', 'bad-manifest', 'ghost.json'), '{ nope');
+ await fs.promises.mkdir(path.join(rootDir, '_ns', '_root', 'wrong-name'));
await fs.promises.writeFile(
- path.join(rootDir, 'wrong-name', 'ghost.json'),
+ path.join(rootDir, '_ns', '_root', 'wrong-name', 'ghost.json'),
JSON.stringify(goodManifest('other-id')),
);
// 隐藏目录(staging 残留形态)也不进清单
@@ -3190,7 +3659,7 @@ describe('GhostManager · Host approval receipt', () => {
}
},
);
- expect(receiptStore.read('legacy-broker')).toMatchObject({ state: 'approved' });
+ expect(receiptStore.read('_ns/_root/legacy-broker')).toMatchObject({ state: 'approved' });
// 新进程从盘上回读仍须投影该插件;若规则误放回共用 validator,这里会消失。
const restarted = new GhostManager({ getRootDir: () => rootDir });
@@ -3225,11 +3694,11 @@ describe('GhostManager · Host approval receipt', () => {
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);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(true);
+ expect(path.dirname(receiptPath('_ns/_root/hello'))).not.toBe(rootDir);
await fs.promises.writeFile(
- path.join(rootDir, 'hello', 'ghost.json'),
+ path.join(rootDir, '_ns', '_root', 'hello', 'ghost.json'),
JSON.stringify({
...goodManifest(),
version: '99.0.0',
@@ -3237,9 +3706,9 @@ describe('GhostManager · Host approval receipt', () => {
node: { entry: 'evil.cjs', protocol: 'json-rpc-stdio' },
}),
);
- await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');
+ await fs.promises.writeFile(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'), '');
await fs.promises.writeFile(
- path.join(rootDir, 'hello', '.cindy-trust.json'),
+ path.join(rootDir, '_ns', '_root', 'hello', '.cindy-trust.json'),
JSON.stringify({
level: 'cindy-official',
publisherSigned: true,
@@ -3258,7 +3727,7 @@ describe('GhostManager · Host approval receipt', () => {
expect(after.approval.state).toBe('approved');
// 移除镜像 → 回到 receipt 的授权事实(enabled=true 是用户确认装入时的决定)。
- await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));
+ await fs.promises.rm(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'));
expect(manager.list()[0].enabled).toBe(true);
});
@@ -3333,7 +3802,7 @@ describe('GhostManager · Host approval receipt', () => {
releasePublish = resolve;
});
const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
- if (String(from).includes('.cindy-installing-hello-')) {
+ if (String(from).includes('.cindy-installing-_root__hello-')) {
const result = await originalRename(from, to);
publishStarted();
await publishGate;
@@ -3383,7 +3852,7 @@ describe('GhostManager · Host approval receipt', () => {
enabled: false,
});
expect(
- fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json')),
).toBe(true);
} finally {
clearSpy.mockRestore();
@@ -3399,10 +3868,91 @@ describe('GhostManager · Host approval receipt', () => {
approval: { state: 'approved' },
});
expect(
- fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json')),
).toBe(false);
});
+ it.each([null, 'acme'] as const)('preserves the %s recovery journal across a second failed update', async (namespace) => {
+ const originalCode = 'module.exports = { original: true };';
+ const unpublishedCode = 'module.exports = { unpublished: true };';
+ const installed = await manager.install(await makeCindy('v1.cindy', goodManifest(), {
+ 'main.js': originalCode,
+ }), { namespace });
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const finalDir = installed.ghost.dir;
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const oldReceipt = store.readForRecovery(relId);
+ const candidate = await makeCindy('candidate.cindy', goodManifest(), { 'main.js': unpublishedCode });
+ const actualRemove = fs.promises.rm;
+ const remove = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === finalDir) throw new Error('rollback removal blocked');
+ return actualRemove(target, options);
+ });
+ const write = vi.spyOn(store, 'write').mockRejectedValueOnce(new Error('receipt blocked'));
+ try {
+ expect(await manager.update(candidate, {
+ namespace, expectedInstalledApproval: ghostInstallApprovalToken(installed.ghost.approval),
+ })).toMatchObject({ rejection: { code: 'io', rollbackFailed: true } });
+ } finally {
+ remove.mockRestore();
+ write.mockRestore();
+ }
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ expect(fs.readFileSync(path.join(finalDir, 'main.js'), 'utf8')).toBe(unpublishedCode);
+ const pending = store.readPendingMutationSync(relId);
+ expect(pending.state).toBe('valid');
+ const actualRename = fs.promises.rename;
+ const rename = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(from) === finalDir) throw new Error('second directory swap blocked');
+ return actualRename(from, to);
+ });
+ try {
+ await expectRejection(await manager.update(candidate, {
+ namespace, expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),
+ }), 'io');
+ expect(store.readPendingMutationSync(relId)).toEqual(pending);
+ expect(store.readForRecovery(relId)).toEqual(oldReceipt);
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ expect(rename).not.toHaveBeenCalled();
+ } finally {
+ rename.mockRestore();
+ }
+ manager = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'approved' }, enabled: true });
+ expect(fs.readFileSync(path.join(finalDir, 'main.js'), 'utf8')).toBe(originalCode);
+ expect(store.readPendingMutationSync(relId).state).toBe('missing');
+ expect(await manager.update(candidate, {
+ namespace, expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),
+ })).toMatchObject({ ghost: { approval: { state: 'approved' }, enabled: true } });
+ expect(fs.readFileSync(path.join(finalDir, 'main.js'), 'utf8')).toBe(unpublishedCode);
+ });
+
+ it.each(['invalid', 'unreadable'] as const)('rejects an update while its existing journal is %s', async (state) => {
+ const installed = await manager.install(await makeCindy('v1.cindy', goodManifest()));
+ if (!('ghost' in installed)) throw new Error('expected installation');
+ const relId = installedGhostPhysicalRelId(installed.ghost);
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const markerPath = path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json');
+ const markerBytes = '{ broken journal';
+ fs.writeFileSync(markerPath, markerBytes);
+ const read = state === 'unreadable'
+ ? vi.spyOn(store, 'readPendingMutationSync').mockReturnValue({ state, reason: 'read blocked' })
+ : undefined;
+ const write = vi.spyOn(store, 'writePendingMutation');
+ try {
+ await expectRejection(await manager.update(await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }), {
+ expectedInstalledApproval: ghostInstallApprovalToken(installed.ghost.approval),
+ }), 'io');
+ expect(write).not.toHaveBeenCalled();
+ expect(fs.readFileSync(markerPath, 'utf8')).toBe(markerBytes);
+ expect(manager.list()[0]).toMatchObject({ manifest: { version: '1.0.0' }, approval: { state: 'invalid' }, enabled: false });
+ } finally {
+ read?.mockRestore();
+ write.mockRestore();
+ }
+ });
+
it('removes the receipt and approved skill snapshots on uninstall', async () => {
const manifest = {
...goodManifest('skilled'),
@@ -3421,25 +3971,25 @@ describe('GhostManager · Host approval receipt', () => {
expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(true);
await manager.uninstall('skilled');
- expect(fs.existsSync(receiptPath('skilled'))).toBe(false);
+ expect(fs.existsSync(receiptPath('_ns/_root/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');
+ await fs.promises.rm(receiptPath('_ns/_root/hello'));
+ await fs.promises.mkdir(receiptPath('_ns/_root/hello'));
+ await fs.promises.writeFile(path.join(receiptPath('_ns/_root/hello'), 'blocked'), 'x');
const result = await manager.uninstall('hello');
expect(result).toEqual({ ok: true });
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
expect(manager.list()).toEqual([]);
- expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json'))).toBe(
true,
);
- await fs.promises.rm(receiptPath(), { recursive: true, force: true });
+ await fs.promises.rm(receiptPath('_ns/_root/hello'), { recursive: true, force: true });
const recovered = new GhostManager({
getRootDir: () => rootDir,
getLocale: () => hostLocale,
@@ -3447,7 +3997,7 @@ describe('GhostManager · Host approval receipt', () => {
});
expect(recovered.list()).toEqual([]);
expect(
- fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json')),
).toBe(false);
});
@@ -3480,7 +4030,7 @@ describe('GhostManager · Host approval receipt', () => {
// 停用照样成功(安全方向),但重建快照必须拒——否则启用就等于批准一份用户
// 没看过的技能指令。
await fs.promises.writeFile(
- path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),
+ path.join(rootDir, '_ns', '_root', '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 });
@@ -3512,9 +4062,11 @@ describe('GhostManager · Host approval receipt', () => {
);
});
- it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {
+ it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async ({ skip }) => {
await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
- const idDir = path.join(workDir, 'ghosts-install-state', 'skill-snapshots', 'skilled');
+ const ghost = manager.list()[0];
+ const idDir = path.dirname(ghost.approvedSkillRoot!);
+ expect(fs.existsSync(ghost.approvedSkillRoot!)).toBe(true);
// 外部目录里放一个"看起来像旧 revision"的子目录 + 哨兵文件。
const external = path.join(workDir, 'external-data');
await fs.promises.mkdir(path.join(external, 'stale-revision'), { recursive: true });
@@ -3524,13 +4076,14 @@ describe('GhostManager · Host approval receipt', () => {
try {
await fs.promises.symlink(external, idDir, process.platform === 'win32' ? 'junction' : 'dir');
} catch {
- return; // 环境建不了链接则跳过;判定逻辑平台同源。
+ return skip();
}
+ expect(await fs.promises.realpath(idDir)).toBe(external);
// 触发一次 receipt 写(启停翻转):修复前 ensureSkillSnapshot 会沿 junction 把
// 快照发布到外部目录,prune 的 readdir + 逐项 recursive rm 更会把外部目录里的
// "旧 revision"整个删掉(sentinel 消失)。修复后父段遏制先行:可疑父段整体跳过。
- await manager.setEnabled('skilled', false);
+ expect(await manager.setEnabled(installedGhostPhysicalRelId(ghost), false)).toEqual({ ok: true });
expect(fs.existsSync(path.join(external, 'stale-revision', 'sentinel.txt'))).toBe(true);
// 外部目录里也不应多出任何被"发布"进去的快照字节。
expect(await fs.promises.readdir(external)).toEqual(['stale-revision']);
@@ -3539,7 +4092,7 @@ describe('GhostManager · Host approval receipt', () => {
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');
+ const installedSkillMd = path.join(rootDir, '_ns', '_root', 'skilled', 'skills', 'demo', 'SKILL.md');
// 快照缺失时取字节的来源是可变安装目录。这里塞的 SKILL.md frontmatter 与批准
// manifest 完全一致(躲过一致性校验),只是正文超过装入侧上限 —— 重建必须照样拒,
// 否则启用这条路会批准一份装入/更新永远不会接受的超大技能指令,而且要先整份
@@ -3567,7 +4120,7 @@ describe('GhostManager · Host approval receipt', () => {
// frontmatter 的 name/description 一字未动,只改正文 —— 一致性校验看不出来,
// 但这份指令会被主 Agent 以用户全部权限执行,必须靠批准时点的字节指纹拦住。
await fs.promises.writeFile(
- path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),
+ path.join(rootDir, '_ns', '_root', '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 });
@@ -3583,7 +4136,7 @@ describe('GhostManager · Host approval receipt', () => {
const snapshotRoot = manager.list()[0].approvedSkillRoot!;
// SKILL.md 完全没动,只往技能目录里塞一个被指令引用的辅助文件(点文件同样算)。
await fs.promises.writeFile(
- path.join(rootDir, 'skilled', 'skills', 'demo', '.helper.sh'),
+ path.join(rootDir, '_ns', '_root', 'skilled', 'skills', 'demo', '.helper.sh'),
'#!/bin/sh\necho injected\n',
);
await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
@@ -3606,7 +4159,7 @@ describe('GhostManager · Host approval receipt', () => {
try {
await fs.promises.symlink(
outside,
- path.join(rootDir, 'skilled', 'skills', 'demo', 'linked'),
+ path.join(rootDir, '_ns', '_root', 'skilled', 'skills', 'demo', 'linked'),
process.platform === 'win32' ? 'junction' : 'dir',
);
} catch {
@@ -3715,7 +4268,7 @@ describe('GhostManager · Host approval receipt', () => {
spy.mockRestore();
}
- expect(fs.existsSync(receiptPath())).toBe(true); // receipt 还在盘上
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(true); // receipt 还在盘上
expect(manager.list()[0]).toMatchObject({
enabled: false,
approval: { state: 'invalid' },
@@ -3747,7 +4300,7 @@ describe('GhostManager · Host approval receipt', () => {
// 快照与安装目录都被改成同一份未批准内容:此时没有任何可信来源可重建,必须拒。
await fs.promises.writeFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), tampered);
await fs.promises.writeFile(
- path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),
+ path.join(rootDir, '_ns', '_root', 'skilled', 'skills', 'demo', 'SKILL.md'),
tampered,
);
@@ -3827,14 +4380,14 @@ describe('GhostManager · Host approval receipt', () => {
expect(await manager.approveTrustedBundledInstall(listed.manifest, true, source)).toBe(true);
const snapshotRoot = manager.list()[0].approvedSkillRoot!;
- const disabledMarker = path.join(rootDir, listed.manifest.id, '.disabled');
+ const disabledMarker = path.join(listed.dir, '.disabled');
await fs.promises.writeFile(disabledMarker, '');
await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
expect(
await manager.approveTrustedBundledInstall(listed.manifest, false, source),
).toBe(true);
- expect(JSON.parse(await fs.promises.readFile(receiptPath('skilled'), 'utf8'))).toMatchObject({
+ expect(JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/skilled'), 'utf8'))).toMatchObject({
enabled: false,
});
@@ -3859,11 +4412,11 @@ describe('GhostManager · Host approval receipt', () => {
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'),
+ await fs.promises.readFile(receiptPath('_ns/_root/skilled'), 'utf8'),
) as Record<string, unknown>;
// 手工把指纹字段抹掉:必填项缺失一律判 invalid,不允许退化成"跳过校验"。
delete receipt.skillContentSha256;
- await fs.promises.writeFile(receiptPath('skilled'), JSON.stringify(receipt));
+ await fs.promises.writeFile(receiptPath('_ns/_root/skilled'), JSON.stringify(receipt));
expect(manager.list()[0]).toMatchObject({
enabled: false,
@@ -3874,11 +4427,11 @@ describe('GhostManager · Host approval receipt', () => {
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'),
+ await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8'),
) as Record<string, unknown>;
// v2 改了内容摘要 framing;旧 receipt 的摘要不能拿来继续授权,必须 fail closed。
receipt.schemaVersion = 1;
- await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));
+ await fs.promises.writeFile(receiptPath('_ns/_root/hello'), JSON.stringify(receipt));
expect(manager.list()[0]).toMatchObject({
enabled: false,
@@ -3894,7 +4447,7 @@ describe('GhostManager · Host approval receipt', () => {
// 撤掉之后插件必须彻底不可运行,而不是继续拿旧批准跑新代码。
await manager.removeInstallApproval('hello');
- expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(fs.existsSync(receiptPath('_ns/_root/hello'))).toBe(false);
expect(manager.list()[0]).toMatchObject({
enabled: false,
approval: { state: 'legacy-unapproved' },
@@ -3926,7 +4479,7 @@ describe('GhostManager · Host approval receipt', () => {
JSON.stringify(ghostManifestToAuthorFormat(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');
+ await fs.promises.writeFile(path.join(manager.list()[0].dir, 'main.js'), 'mutable bytes');
const unsafeCall = manager.approveTrustedBundledInstall as unknown as (
manifest: InstalledGhost['manifest'],
@@ -3937,7 +4490,7 @@ describe('GhostManager · Host approval receipt', () => {
);
await expect(
manager.approveTrustedBundledInstall(approvedManifest, true, {
- sourceDir: path.join(rootDir, approvedManifest.id),
+ sourceDir: manager.list()[0].dir,
}),
).rejects.toThrow(/mutable installed directory/);
const arbitrarySourceDir = path.join(workDir, 'arbitrary-source', approvedManifest.id);
@@ -3955,13 +4508,13 @@ describe('GhostManager · Host approval receipt', () => {
expect(
await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir }),
).toBe(true);
- const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8')) as {
packageSha256?: string;
};
const sourcePackageSha256 = receipt.packageSha256;
- await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'different mutable bytes');
+ await fs.promises.writeFile(path.join(manager.list()[0].dir, 'main.js'), 'different mutable bytes');
await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });
- const stableReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ const stableReceipt = JSON.parse(await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8')) as {
packageSha256?: string;
};
expect(stableReceipt.packageSha256).toBe(sourcePackageSha256);
@@ -3974,7 +4527,7 @@ describe('GhostManager · Host approval receipt', () => {
'main.js': 'immutable replacement bytes',
});
const stateRoot = manager.approvalStateRoot();
- const pendingPath = path.join(stateRoot, '.pending-hello.json');
+ const pendingPath = path.join(stateRoot, '_ns', '_root', '.pending-hello.json');
await manager.runExclusiveMutation(async (mutation) => {
expect(await mutation.removeInstallApproval('hello')).toBe(true);
@@ -3982,19 +4535,19 @@ describe('GhostManager · Host approval receipt', () => {
expect(fs.existsSync(pendingPath)).toBe(true);
expect(
(await fs.promises.readdir(rootDir)).some((name) =>
- name.startsWith('.cindy-updating-hello-'),
+ name.startsWith('.cindy-updating-_root__hello-'),
),
).toBe(true);
await mutation.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });
});
- expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'main.js'), 'utf8')).toBe(
+ expect(await fs.promises.readFile(path.join(rootDir, '_ns', '_root', '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-'),
+ name.startsWith('.cindy-updating-_root__hello-'),
),
).toBe(false);
expect(manager.list()[0].approval.state).toBe('approved');
@@ -4003,7 +4556,7 @@ describe('GhostManager · Host approval receipt', () => {
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'),
+ await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8'),
) as { manifest: InstalledGhost['manifest'] };
const source = await writeBundledSource(approvedManifest);
// 随包对账首轮把安装收编成 bundled 批准(trust 归一),后续轮次走稳态分支。
@@ -4011,27 +4564,27 @@ describe('GhostManager · Host approval receipt', () => {
expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);
// 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。
- await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));
+ await fs.promises.rm(path.join(rootDir, '_ns', '_root', '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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(true);
});
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'),
+ await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8'),
) as { manifest: InstalledGhost['manifest'] };
const source = await writeBundledSource(approvedManifest);
expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);
// 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——
// 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。
- await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');
+ await fs.promises.writeFile(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'), '');
expect(await manager.approveTrustedBundledInstall(approvedManifest, false, source)).toBe(true);
expect(manager.list()[0].enabled).toBe(false);
});
@@ -4039,7 +4592,7 @@ describe('GhostManager · Host approval receipt', () => {
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'),
+ await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8'),
) as { manifest: InstalledGhost['manifest'] };
expect(
await manager.approveTrustedBundledInstall(
@@ -4049,7 +4602,7 @@ describe('GhostManager · Host approval receipt', () => {
),
).toBe(true);
expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);
- await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));
+ await fs.promises.rm(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'));
// 随包更新那一轮走的是"建全新 receipt"分支,与稳态分支共用同一条合并规则:
// 只堵稳态分支的话,镜像在更新 tick 之前丢失仍会静默重新启用,同一个洞换条路。
@@ -4065,7 +4618,7 @@ describe('GhostManager · Host approval receipt', () => {
enabled: false,
manifest: { version: '1.0.1' },
});
- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(true);
});
it('refuses to mint a bundled approval for an id outside the seed roster', async () => {
@@ -4099,10 +4652,10 @@ describe('GhostManager · Host approval receipt', () => {
}),
);
const receipt = JSON.parse(
- await fs.promises.readFile(receiptPath(), 'utf8'),
+ await fs.promises.readFile(receiptPath('_ns/_root/hello'), 'utf8'),
) as Record<string, unknown>;
receipt.localeResources = {};
- await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));
+ await fs.promises.writeFile(receiptPath('_ns/_root/hello'), JSON.stringify(receipt));
expect(manager.list()[0]).toMatchObject({
enabled: false,
@@ -4123,7 +4676,7 @@ describe('GhostManager · 技能批准基线取自包投影(publish 后篡改必
// 故障注入:staging→final 的 rename 真实执行后,立刻在 finalDir 里改写 SKILL.md
// 正文 —— 模拟"发布与首次 hash 之间"的本机进程篡改窗口。
const realRename = fs.promises.rename;
- const finalDir = path.join(rootDir, 'skilled');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'skilled');
const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
await realRename(from, to);
if (String(to) === finalDir) {
@@ -4145,7 +4698,7 @@ describe('GhostManager · 技能批准基线取自包投影(publish 后篡改必
// 拒装收尾:不留半截安装,也没有任何批准事实落盘。
expect(manager.list()).toHaveLength(0);
expect(
- fs.existsSync(path.join(workDir, 'ghosts-install-state', 'skilled.json')),
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'skilled.json')),
).toBe(false);
});
});
@@ -4155,8 +4708,8 @@ describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
// 模拟崩溃现场:final→backup 已发生,staging→final 没来得及。
await fs.promises.rename(
- path.join(rootDir, 'hello'),
- path.join(rootDir, '.cindy-updating-hello-abcdef01'),
+ path.join(rootDir, '_ns', '_root', 'hello'),
+ path.join(rootDir, '.cindy-updating-_root__hello-abcdef01'),
);
// 崩溃前 list() 视角:插件消失(点目录被跳过)—— 这正是要修的现场。
expect(manager.list()).toHaveLength(0);
@@ -4164,15 +4717,15 @@ describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
// "重启":新建 manager,构造期恢复扫描搬回。receipt 从未更新过,恢复后
// receipt 与内容完全一致,等价于那次更新从未发生。
const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', '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);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-_root__hello-abcdef01'))).toBe(false);
});
it('final 是普通文件时不删除唯一 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');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__hello-abcdef01');
await fs.promises.rename(finalDir, backupDir);
await fs.promises.writeFile(finalDir, 'unexpected file');
@@ -4184,8 +4737,8 @@ describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
it('final 是 junction/链接时不删除唯一 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');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__hello-abcdef01');
const outsideDir = path.join(workDir, 'outside-final-target');
await fs.promises.rename(finalDir, backupDir);
await fs.promises.mkdir(outsideDir, { recursive: true });
@@ -4203,8 +4756,8 @@ describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
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');
+ const finalDir = path.join(rootDir, '_ns', '_root', 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-_root__hello-abcdef01');
await fs.promises.rename(finalDir, backupDir);
const realLstatSync = fs.lstatSync;
const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
@@ -4225,25 +4778,25 @@ describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
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 });
+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-_root__hello-abcdef01'), { recursive: true });
+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-_root__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);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-_root__hello-abcdef01'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-installing-_root__hello-deadbeef'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', '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 });
+ await fs.promises.rename(path.join(rootDir, '_ns', '_root', 'hello'), path.join(rootDir, '.cindy-updating-_root__hello-11111111'));
+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-_root__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);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-_root__hello-11111111'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-_root__hello-22222222'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
});
it('id 是另一个 id 的 `-` 前缀(hello / hello-x)各留唯一 backup → 两者都搬回,不因前缀误判互相拖累(P1)', async () => {
// 回归:siblings 统计曾用 startsWith(`.cindy-updating-${id}-`) 前缀匹配,
- // `.cindy-updating-hello-<hex>` 是 `.cindy-updating-hello-x-<hex>` 的前缀,
+ // `.cindy-updating-_root__hello-<hex>` 是 `.cindy-updating-_root__hello-x-<hex>` 的前缀,
// 于是处理 hello 时把 hello-x 的 backup 也算进来 → siblings 变 2 → 判"多备份
// 留待人工" → hello 崩溃后持续消失。修复后按解析 id 精确比对,两者各自恢复。
await manager.install(await makeCindy('a.cindy', goodManifest('hello')));
@@ -4251,21 +4804,21 @@ describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
// 两个插件都卡在"final→backup 已发生,staging→final 未完成"的崩溃现场,
// 且各自只有唯一 backup(合法可恢复的场景)。
await fs.promises.rename(
- path.join(rootDir, 'hello'),
- path.join(rootDir, '.cindy-updating-hello-11111111'),
+ path.join(rootDir, '_ns', '_root', 'hello'),
+ path.join(rootDir, '.cindy-updating-_root__hello-11111111'),
);
await fs.promises.rename(
- path.join(rootDir, 'hello-x'),
- path.join(rootDir, '.cindy-updating-hello-x-22222222'),
+ path.join(rootDir, '_ns', '_root', 'hello-x'),
+ path.join(rootDir, '.cindy-updating-_root__hello-x-22222222'),
);
new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
// 两者都应搬回 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);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello-x', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-_root__hello-11111111'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-_root__hello-x-22222222'))).toBe(false);
});
});
@@ -4288,7 +4841,7 @@ describe('GhostManager · setEnabled(启用/停用)', () => {
// "镜像已就位"降级 —— 但镜像根本没写成,receipt.enabled 仍为 true,重启即复活。
expect('rejection' in result && result.rejection.code).toBe('io');
expect(manager.list()[0].enabled).toBe(true); // 如实:停用没有生效
- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(false);
} finally {
spy.mockRestore();
}
@@ -4303,13 +4856,13 @@ describe('GhostManager · setEnabled(启用/停用)', () => {
const off = await manager.setEnabled('hello', false);
expect('ok' in off).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(true);
expect(manager.list()[0].enabled).toBe(false);
expect(onChanged).toHaveBeenCalledTimes(1);
const on = await manager.setEnabled('hello', true);
expect('ok' in on).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(false);
expect(manager.list()[0].enabled).toBe(true);
});
@@ -4562,7 +5115,7 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {
expect((result as { ghost: InstalledGhost }).ghost.iconDataUrl).toBe(ok.iconDataUrl);
// list 从安装目录读盘重建,与装入时一致
expect(manager.list()[0].iconDataUrl).toBe(ok.iconDataUrl);
- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'icon.png'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'assets', 'icon.png'))).toBe(true);
});
it('清单声明了 icon 但包内缺文件 → file-invalid', async () => {
@@ -4580,7 +5133,7 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {
it('installed icon removal cannot replace the Host-approved icon snapshot', async () => {
const cindy = await makeCindy('icon2.cindy', iconManifest(), { 'assets/icon.png': 'PNGDATA' });
await manager.install(cindy);
- await fs.promises.rm(path.join(rootDir, 'hello', 'assets', 'icon.png'));
+ await fs.promises.rm(path.join(rootDir, '_ns', '_root', 'hello', 'assets', 'icon.png'));
// 受体模型:已批准投影的 icon 来自 receipt 快照(GhostManager.ts:1684),
// 装后删盘上 icon 文件不改变 list() 输出——快照即批准时钉下的图标。
// main 旧的"删文件/换软链 → 降级为无图标"两个用例前提在受体模型下不再成立
@@ -4648,11 +5201,11 @@ describe('GhostManager · Unix file permissions', () => {
}
if (process.platform !== 'win32') {
- expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'tool'))).mode & 0o777)
+ expect((await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'bin', 'tool'))).mode & 0o777)
.toBe(0o755);
- expect((await fs.promises.stat(path.join(rootDir, 'hello', 'config.txt'))).mode & 0o777)
+ expect((await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'config.txt'))).mode & 0o777)
.toBe(0o644);
- const special = await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'special'));
+ const special = await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'bin', 'special'));
expect(special.mode & 0o777).toBe(0o755);
expect(special.mode & 0o4000).toBe(0);
}
@@ -4663,13 +5216,13 @@ describe('GhostManager · Unix file permissions', () => {
'v2',
);
expect(await updateGhost(v2)).toHaveProperty('ghost');
- expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'config.txt'), 'utf8')).toBe('v2');
+ expect(await fs.promises.readFile(path.join(rootDir, '_ns', '_root', 'hello', 'config.txt'), 'utf8')).toBe('v2');
if (process.platform !== 'win32') {
- expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'tool'))).mode & 0o777)
+ expect((await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'bin', 'tool'))).mode & 0o777)
.toBe(0o755);
- expect((await fs.promises.stat(path.join(rootDir, 'hello', 'config.txt'))).mode & 0o777)
+ expect((await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'config.txt'))).mode & 0o777)
.toBe(0o644);
- expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'special'))).mode & 0o777)
+ expect((await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'bin', 'special'))).mode & 0o777)
.toBe(0o755);
}
});
@@ -4697,15 +5250,15 @@ describe('GhostManager · Unix file permissions', () => {
expect((installed as { ghost: InstalledGhost }).ghost.trust?.publisherSigned).toBe(true);
expect(
- await fs.promises.readFile(path.join(rootDir, 'hello', 'bin', 'tool'), 'utf8'),
+ await fs.promises.readFile(path.join(rootDir, '_ns', '_root', 'hello', 'bin', 'tool'), 'utf8'),
).toContain('v1');
if (process.platform !== 'win32') {
// 签名包与未签名包走同一条恢复路径:0755 保留、0644 保留、特殊位剥除。
- expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'tool'))).mode & 0o777)
+ expect((await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'bin', 'tool'))).mode & 0o777)
.toBe(0o755);
- expect((await fs.promises.stat(path.join(rootDir, 'hello', 'config.txt'))).mode & 0o777)
+ expect((await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'config.txt'))).mode & 0o777)
.toBe(0o644);
- const special = await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'special'));
+ const special = await fs.promises.stat(path.join(rootDir, '_ns', '_root', 'hello', 'bin', 'special'));
expect(special.mode & 0o777).toBe(0o755);
expect(special.mode & 0o4000).toBe(0);
}
@@ -4719,7 +5272,7 @@ describe('GhostManager · Unix file permissions', () => {
try {
expect(await manager.install(cindy)).toHaveProperty('ghost');
expect(chmodSpy).not.toHaveBeenCalled();
- await expect(fs.promises.readFile(path.join(rootDir, 'hello', 'plain.txt'), 'utf8'))
+ await expect(fs.promises.readFile(path.join(rootDir, '_ns', '_root', 'hello', 'plain.txt'), 'utf8'))
.resolves.toBe('plain');
} finally {
chmodSpy.mockRestore();
@@ -4760,25 +5313,29 @@ describe('GhostManager · update(原位换版)', () => {
);
expect(result).toHaveProperty('ghost');
const receipt = JSON.parse(
- await fs.promises.readFile(path.join(manager.approvalStateRoot(), 'hello.json'), 'utf8'),
+ await fs.promises.readFile(path.join(manager.approvalStateRoot(), '_ns', '_root', 'hello.json'), 'utf8'),
) as Record<string, unknown>;
expect(receipt).toHaveProperty('installOrigin', 'agent-forge');
expect(manager.readEffectiveInstallOrigin('hello')).toBe('agent-forge');
});
- it('普通本地导入覆盖 Forge 安装后回到 manual', async () => {
+ it.each([undefined, 'manual'] as const)('普通本地导入覆盖 Forge 安装后回到 manual (installOrigin=%s)', async (installOrigin) => {
await manager.install(await makeCindy('forge-v1.cindy', goodManifest()), {
installOrigin: 'agent-forge',
});
const installed = manager.list().find((ghost) => ghost.manifest.id === 'hello');
+ expect(manager.readApprovedInstallOriginStrict('hello')).toBe('agent-forge');
const result = await manager.update(
await makeCindy('manual-v2.cindy', { ...goodManifest(), version: '2.0.0' }),
- { expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval) },
+ { expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval), ...(installOrigin ? { installOrigin } : {}) },
);
expect(result).toHaveProperty('ghost');
expect(manager.readEffectiveInstallOrigin('hello')).toBe('manual');
+ expect(manager.readApprovedInstallOriginStrict('hello')).toBe('manual');
+ const receipt = JSON.parse(fs.readFileSync(path.join(manager.approvalStateRoot(), '_ns', '_root', 'hello.json'), 'utf8'));
+ expect(receipt.installOrigin).toBe(installOrigin);
});
it('happy path:版本替换、旧文件清干净、目录不变、onChanged 广播', async () => {
@@ -4799,9 +5356,9 @@ describe('GhostManager · update(原位换版)', () => {
expect('ghost' in result, JSON.stringify(result)).toBe(true);
const { ghost } = result as { ghost: InstalledGhost };
expect(ghost.manifest.version).toBe('2.0.0');
- expect(ghost.dir).toBe(path.join(rootDir, 'hello'));
- expect(fs.existsSync(path.join(rootDir, 'hello', 'new.txt'))).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(false); // 换版不留旧文件
+ expect(ghost.dir).toBe(path.join(rootDir, '_ns', '_root', 'hello'));
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'new.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'old.txt'))).toBe(false); // 换版不留旧文件
expect(onPackagePlaced).toHaveBeenCalledTimes(1);
expect(onPackagePlaced.mock.invocationCallOrder[0]).toBeLessThan(
onChanged.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
@@ -4837,12 +5394,12 @@ describe('GhostManager · update(原位换版)', () => {
await manager.install(await makeCindy('v1.cindy', goodManifest()), { initiallyEnabled: false });
const r1 = await updateGhost(await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }));
expect((r1 as { ghost: InstalledGhost }).ghost.enabled).toBe(false);
- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(true);
await manager.setEnabled('hello', true);
const r2 = await updateGhost(await makeCindy('v3.cindy', { ...goodManifest(), version: '3.0.0' }));
expect((r2 as { ghost: InstalledGhost }).ghost.enabled).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', '.disabled'))).toBe(false);
});
it('提交前回调失败时恢复旧版本', async () => {
@@ -4863,8 +5420,244 @@ describe('GhostManager · update(原位换版)', () => {
await expectRejection(result, 'io');
expect(manager.list()[0]?.manifest.version).toBe('1.0.0');
- expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', 'new.txt'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'old.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'new.txt'))).toBe(false);
+ });
+
+ const archiveId = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__hello';
+
+ function sourceArchiveManager(onArchiveSourceState: NonNullable<GhostManagerOptions['onArchiveSourceState']>): GhostManager {
+ return new GhostManager({
+ getRootDir: () => rootDir,
+ onArchiveSourceState,
+ mutateSnapshot: async ({ parentDir, ...request }) => runGhostSnapshotWorkerRequest(request, parentDir),
+ });
+ }
+
+ function moveSourceState(state: Map<string, string>, fromPart: string, toPart: string): void {
+ if (!state.has(fromPart)) return;
+ state.set(toPart, state.get(fromPart)!);
+ state.delete(fromPart);
+ }
+
+ async function prepareSourceArchiveUpdate(
+ onArchiveSourceState: NonNullable<GhostManagerOptions['onArchiveSourceState']>,
+ manifest = goodManifest(),
+ installOptions: Parameters<GhostManager['install']>[1] = {},
+ ) {
+ const archiveManager = sourceArchiveManager(onArchiveSourceState);
+ manager = archiveManager;
+ await archiveManager.install(await makeCindy('v1.cindy', manifest), installOptions);
+ const file = await makeCindy('v2.cindy', { ...manifest, version: '2.0.0' });
+ const sourceKey = installedGhostStoragePart(archiveManager.list()[0]!);
+ return {
+ sourceKey,
+ store: (archiveManager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore,
+ update: (options: Pick<Parameters<GhostManager['update']>[1], 'beforePackageCommit'> = {}) => archiveManager.update(file, {
+ expectedInstalledApproval: ghostInstallApprovalToken(archiveManager.list()[0]?.approval),
+ sourceStateArchiveId: archiveId,
+ ...options,
+ }),
+ };
+ }
+
+
+ function useSourceKey(state: Map<string, string>, sourceKey: string): void {
+ const value = state.get('_root__hello');
+ if (value === undefined) return;
+ state.delete('_root__hello');
+ state.set(sourceKey, value);
+ }
+
+ it('archives source state before package side effects and leaves the replacement with empty state', async () => {
+ const manifest = { ...goodManifest(), slots: ['tool', 'agent'], agent: { tasks: true } };
+ const state = new Map<string, string>([['_root__hello', 'old-credentials-and-data']]);
+ const archive = vi.fn(async (fromPart: string, archivePart: string) => {
+ moveSourceState(state, fromPart, archivePart);
+ });
+ const { store, update, sourceKey } = await prepareSourceArchiveUpdate(archive, manifest, { taskCapabilityApproved: true });
+ useSourceKey(state, sourceKey);
+ const result = await update({
+ beforePackageCommit: () => {
+ expect(state.has(sourceKey)).toBe(false);
+ expect(store.readPendingMutationSync('_ns/_root/hello')).toMatchObject({
+ state: 'valid', mutation: { sourceStateArchiveId: archiveId },
+ });
+ },
+ });
+ expect(result).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+ expect(manager.list()[0].taskCapabilityApproved).toBeUndefined();
+ expect(archive).toHaveBeenCalledWith(sourceKey, archiveId);
+ expect(state.has(sourceKey)).toBe(false);
+ expect(state.get(archiveId)).toBe('old-credentials-and-data');
+ });
+
+ it('restores archived source state before compensating side effects on receipt failure', async () => {
+ const manifest = { ...goodManifest(), slots: ['tool', 'agent'], agent: { tasks: true } };
+ const state = new Map<string, string>([['_root__hello', 'old-data']]);
+ const { store, update, sourceKey } = await prepareSourceArchiveUpdate(async (fromPart, archivePart) => {
+ moveSourceState(state, fromPart, archivePart);
+ }, manifest, { taskCapabilityApproved: true });
+ useSourceKey(state, sourceKey);
+ const rollback = vi.fn(() => { expect(state.get(sourceKey)).toBe('old-data'); });
+ const write = vi.spyOn(store, 'write').mockRejectedValueOnce(new Error('receipt blocked'));
+ const result = await update({
+ beforePackageCommit: () => ({ rollback, commit: vi.fn() }),
+ });
+ write.mockRestore();
+ expect(result).toMatchObject({ rejection: { code: 'io' } });
+ expect(rollback).toHaveBeenCalledOnce();
+ expect(state.get(sourceKey)).toBe('old-data');
+ expect(state.has(archiveId)).toBe(false);
+ expect(manager.list()[0]?.manifest.version).toBe('1.0.0');
+ expect(manager.list()[0]?.taskCapabilityApproved).toBe(true);
+ expect(store.readPendingMutationSync('_ns/_root/hello').state).toBe('missing');
+ });
+
+ it('retains the archive journal and quarantine after rollback failure until asynchronous recovery finishes', async () => {
+ const state = new Map<string, string>([['_root__hello', 'old-data']]);
+ const move = (fromPart: string, archivePart: string) => {
+ moveSourceState(state, fromPart, archivePart);
+ };
+ const { store, update, sourceKey } = await prepareSourceArchiveUpdate(async (fromPart, archivePart) => {
+ if (fromPart === archiveId) throw new Error('rollback blocked');
+ move(fromPart, archivePart);
+ });
+ useSourceKey(state, sourceKey);
+ const write = vi.spyOn(store, 'write').mockRejectedValueOnce(new Error('receipt blocked'));
+ const result = await update();
+ write.mockRestore();
+ expect(result).toMatchObject({ rejection: { code: 'io', rollbackFailed: true } });
+ expect(manager.list()[0]?.approval.state).toBe('invalid');
+ let finishRecovery!: () => void;
+ const recoveryGate = new Promise<void>((resolve) => { finishRecovery = resolve; });
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ onArchiveSourceState: async (fromPart, archivePart) => {
+ expect(fromPart).toBe(archiveId);
+ expect(archivePart).toBe(sourceKey);
+ await recoveryGate;
+ move(fromPart, archivePart);
+ },
+ });
+ expect(recovered.list()[0]?.approval.state).toBe('invalid');
+ expect(store.readPendingMutationSync('_ns/_root/hello').state).toBe('valid');
+ finishRecovery();
+ await recovered.retryInterruptedMutationsAfterDbReady();
+ expect(recovered.list()[0]?.manifest.version).toBe('1.0.0');
+ expect(recovered.list()[0]?.approval.state).toBe('approved');
+ expect(state.get(sourceKey)).toBe('old-data');
+ expect(state.has(archiveId)).toBe(false);
+ expect(store.readPendingMutationSync('_ns/_root/hello').state).toBe('missing');
+ });
+
+ it('recovers a committed source archive journal before allowing the new runtime', async () => {
+ const state = new Map<string, string>([['_root__hello', 'old-data']]);
+ const archive = vi.fn(async (fromPart: string, toPart: string) => {
+ moveSourceState(state, fromPart, toPart);
+ });
+ const { store, update, sourceKey } = await prepareSourceArchiveUpdate(archive);
+ useSourceKey(state, sourceKey);
+ const clear = vi.spyOn(store, 'clearPendingMutation').mockRejectedValueOnce(new Error('clear blocked'));
+ const result = await update();
+ clear.mockRestore();
+ expect(result).toMatchObject({ ghost: { approval: { state: 'invalid' } } });
+ let finishRecovery!: () => void;
+ const gate = new Promise<void>((resolve) => { finishRecovery = resolve; });
+ const recovered = new GhostManager({ getRootDir: () => rootDir,
+ onArchiveSourceState: async (fromPart, toPart) => {
+ expect([fromPart, toPart]).toEqual([sourceKey, archiveId]);
+ await gate;
+ await archive(fromPart, toPart);
+ },
+ });
+ expect(recovered.list()[0]?.approval.state).toBe('invalid');
+ finishRecovery();
+ await recovered.retryInterruptedMutationsAfterDbReady();
+ expect(recovered.list()[0]).toMatchObject({ manifest: { version: '2.0.0' }, approval: { state: 'approved' } });
+ expect(state.get(archiveId)).toBe('old-data');
+ expect(state.has(sourceKey)).toBe(false);
+ expect(store.readPendingMutationSync('_ns/_root/hello').state).toBe('missing');
+ });
+
+ it('retains partial source archive failure until inverse recovery proves restoration', async () => {
+ const state = new Map<string, string>();
+ const archive = vi.fn(async (fromPart: string, toPart: string) => {
+ state.set(toPart, state.get(fromPart)!);
+ state.delete(fromPart);
+ throw new Error('other data path blocked');
+ });
+ const { update, sourceKey } = await prepareSourceArchiveUpdate(archive);
+ state.set(sourceKey, 'secret');
+ const beforeCommit = vi.fn();
+ const result = await update({ beforePackageCommit: beforeCommit });
+ expect(result).toMatchObject({ rejection: { rollbackFailed: true } });
+ expect(archive).toHaveBeenCalledTimes(1);
+ expect(beforeCommit).not.toHaveBeenCalled();
+ expect(manager.list()[0]?.approval.state).toBe('invalid');
+ const recovered = new GhostManager({ getRootDir: () => rootDir,
+ onArchiveSourceState: async (fromPart, toPart) => {
+ expect([fromPart, toPart]).toEqual([archiveId, sourceKey]);
+ moveSourceState(state, fromPart, toPart);
+ },
+ });
+ await recovered.retryInterruptedMutationsAfterDbReady();
+ expect(recovered.list()[0]).toMatchObject({ manifest: { version: '1.0.0' }, approval: { state: 'approved' } });
+ expect(state.get(sourceKey)).toBe('secret');
+ });
+
+ it('serializes source archive recovery before uninstall and reinstall', async () => {
+ const { update } = await prepareSourceArchiveUpdate(async () => { throw new Error('partial archive blocked'); });
+ await update();
+ const nextPackage = await makeCindy('v3.cindy', { ...goodManifest(), version: '3.0.0' });
+ let finishRecovery!: () => void;
+ let recoveryStarted!: () => void;
+ const gate = new Promise<void>((resolve) => { finishRecovery = resolve; });
+ const started = new Promise<void>((resolve) => { recoveryStarted = resolve; });
+ const recovered = sourceArchiveManager(async () => { recoveryStarted(); await gate; });
+ await started;
+ let uninstallFinished = false;
+ const replacement = recovered.uninstall('hello').then(async () => {
+ uninstallFinished = true;
+ return recovered.install(nextPackage);
+ });
+ await new Promise<void>((resolve) => setTimeout(resolve, 100));
+ const finishedWhilePaused = uninstallFinished;
+ finishRecovery();
+ await replacement;
+ await recovered.retryInterruptedMutationsAfterDbReady();
+ expect(finishedWhilePaused).toBe(false);
+ expect(recovered.list()[0]).toMatchObject({ manifest: { version: '3.0.0' }, approval: { state: 'approved' } });
+ });
+
+ it.each(['journal', 'receipt'] as const)('preserves superseding %s during source archive recovery', async (superseded) => {
+ const { store, update } = await prepareSourceArchiveUpdate(async () => {});
+ const clear = vi.spyOn(store, 'clearPendingMutation').mockRejectedValueOnce(new Error('clear blocked'));
+ await update();
+ clear.mockRestore();
+ let finishRecovery!: () => void;
+ let recoveryStarted!: () => void;
+ const gate = new Promise<void>((resolve) => { finishRecovery = resolve; });
+ const started = new Promise<void>((resolve) => { recoveryStarted = resolve; });
+ const recovered = new GhostManager({ getRootDir: () => rootDir,
+ onArchiveSourceState: async () => { recoveryStarted(); await gate; },
+ });
+ await started;
+ const originalMarker = store.readPendingMutationSync('_ns/_root/hello');
+ if (superseded === 'journal') {
+ await store.writePendingMutation('_ns/_root/hello', { kind: 'uninstall' });
+ } else {
+ const receiptPath = path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json');
+ const receipt = JSON.parse(fs.readFileSync(receiptPath, 'utf8'));
+ fs.writeFileSync(receiptPath, JSON.stringify({ ...receipt, revision: crypto.randomUUID() }));
+ }
+ const recoveries = [...(recovered as unknown as { pendingRecoverySideEffects: Set<Promise<void>> }).pendingRecoverySideEffects];
+ finishRecovery();
+ await Promise.all(recoveries);
+ expect(store.readPendingMutationSync('_ns/_root/hello')).toEqual(superseded === 'journal'
+ ? expect.objectContaining({ state: 'valid', mutation: expect.objectContaining({ kind: 'uninstall' }) })
+ : originalMarker);
+ expect(recovered.list()[0]?.approval.state).toBe('invalid');
});
it('receipt 提交失败时补偿副作用并恢复旧版本', async () => {
@@ -4892,7 +5685,7 @@ describe('GhostManager · update(原位换版)', () => {
expect(rollback).toHaveBeenCalledTimes(1);
expect(commit).not.toHaveBeenCalled();
expect(manager.list()[0]?.manifest.version).toBe('1.0.0');
- expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'old.txt'))).toBe(true);
});
it('副作用补偿失败时保留 journal、隔离和可恢复的目录交换现场', async () => {
@@ -4921,9 +5714,9 @@ describe('GhostManager · update(原位换版)', () => {
writeSpy.mockRestore();
}
expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
- expect(fs.existsSync(path.join(rootDir, 'hello', 'new.txt'))).toBe(true);
- expect(fs.readdirSync(rootDir).some((name) => name.startsWith('.cindy-updating-hello-'))).toBe(true);
- expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'new.txt'))).toBe(true);
+ expect(fs.readdirSync(rootDir).some((name) => name.startsWith('.cindy-updating-_root__hello-'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '_ns', '_root', '.pending-hello.json'))).toBe(true);
const recovered = new GhostManager({
getRootDir: () => rootDir,
@@ -4931,7 +5724,7 @@ describe('GhostManager · update(原位换版)', () => {
onChanged,
});
expect(recovered.list()[0]?.manifest.version).toBe('1.0.0');
- expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello', 'old.txt'))).toBe(true);
});
it('副作用只在 receipt 提交后 commit', async () => {
@@ -5009,7 +5802,7 @@ describe('GhostManager · skill 槽装入校验(确认框看到的 = Agent 读
});
const result = await manager.install(cindy);
expect('ghost' in result, JSON.stringify(result)).toBe(true);
- const landed = path.join(rootDir, 'skilled', 'skills', 'foo', 'SKILL.md');
+ const landed = path.join(rootDir, '_ns', '_root', 'skilled', 'skills', 'foo', 'SKILL.md');
const st = await fs.promises.lstat(landed);
expect(st.isFile()).toBe(true);
expect(st.isSymbolicLink()).toBe(false);
@@ -5208,3 +6001,63 @@ describe('GhostManager · manual 装入侧对等校验', () => {
);
});
});
+
+describe('registry publish after install commit', () => {
+ it('keeps the install successful when the registry write fails and adopts it on the next list', async () => {
+ let marketPluginId: string | null = null;
+ const warnings: string[] = [];
+ const local = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => 'zh-CN',
+ log: {
+ info: () => {},
+ warn: (message) => { warnings.push(message); },
+ },
+ marketIdentityForInstance: () => (marketPluginId ? { pluginId: marketPluginId } : null),
+ mutateSnapshot: async (request) => {
+ const { parentDir, ...workerRequest } = request;
+ await runGhostSnapshotWorkerRequest(workerRequest, parentDir);
+ },
+ });
+ const original = fs.writeFileSync.bind(fs);
+ const spy = vi.spyOn(fs, 'writeFileSync').mockImplementation((file, data, encoding) => {
+ if (String(file).includes('plugin-instances')) throw new Error('disk full');
+ return original(file, data, encoding as never);
+ });
+ const file = await makeCindy('market.cindy', goodManifest('helper'), { 'main.js': 'module.exports = {};' });
+ const result = await local.install(file, {
+ namespace: 'acme',
+ registrySource: 'market',
+ pluginId: 'plugin-helper',
+ });
+ const afterCommit = vi.fn();
+ expect(result).toHaveProperty('ghost');
+ if (!('ghost' in result)) {
+ spy.mockRestore();
+ return;
+ }
+ afterCommit(result.ghost);
+ expect(afterCommit).toHaveBeenCalledTimes(1);
+ expect(warnings).toContain('plugin instance registry publish failed after install commit');
+ const registryPath = path.join(local.approvalStateRoot(), 'plugin-instances.v2.json');
+ expect(fs.existsSync(registryPath)).toBe(false);
+ expect(fs.existsSync(result.ghost.dir)).toBe(true);
+ spy.mockRestore();
+ local.list();
+ const saved = JSON.parse(fs.readFileSync(registryPath, 'utf8')) as {
+ instances: Record<string, { ghostId: string; namespace: string | null; namespaceState: string; source: string; pluginId: string | null }>;
+ };
+ const adopted = Object.values(saved.instances).find((item) => item.ghostId === 'helper');
+ expect(adopted).toMatchObject({ namespace: 'acme', namespaceState: 'confirmed' });
+ marketPluginId = 'plugin-helper';
+ local.list();
+ const healed = JSON.parse(fs.readFileSync(registryPath, 'utf8')) as typeof saved;
+ const sourced = Object.values(healed.instances).find((item) => item.ghostId === 'helper');
+ expect(sourced).toMatchObject({
+ namespace: 'acme',
+ namespaceState: 'confirmed',
+ source: 'market',
+ pluginId: 'plugin-helper',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts
index bcbe6f5538..90874a5474 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../cardStoreDb.js', () => ({ getGhostCard: vi.fn(), upsertGhostCard: vi.fn() }));
vi.mock('../../device-link/broadcast-tap.js', () => ({ captureDataOwnerBroadcastScope: vi.fn(), isDataOwnerBroadcastScopeCurrent: vi.fn(), tapWindowBroadcast: vi.fn(), getSafeDataOwnerPushStamp: vi.fn() }));
-import { createPluginIdentityRemoteProvider, createGhostCardRemoteProvider, projectGhostCardBlocks, projectGhostCardActions, persistGhostCardWithRemoteChange } from '../cardRemoteResource.js';
+import { createPluginIdentityRemoteProvider, createGhostCardRemoteProvider, projectGhostCardBlocks, projectGhostCardActions, persistGhostCardWithRemoteChange, findGhostForRemotePluginIdentity } from '../cardRemoteResource.js';
import { upsertGhostCard } from '../cardStoreDb.js';
import { isDataOwnerBroadcastScopeCurrent, tapWindowBroadcast } from '../../device-link/broadcast-tap.js';
const image = `cindy-media://blobs/${'b'.repeat(64)}.png`;
@@ -94,6 +94,38 @@ describe('read-only plugin card projection', () => {
describe('plugin identity for mobile annotations', () => {
+ it('resolves explicit root and organization identities, but never guesses an ambiguous legacy id', () => {
+ const root = { manifest: { id: 'helper' }, namespace: null, name: 'Root' };
+ const org = { manifest: { id: 'helper' }, namespace: 'acme', name: 'Organization' };
+ expect(findGhostForRemotePluginIdentity([root, org], JSON.stringify([null, 'helper']))).toBe(root);
+ expect(findGhostForRemotePluginIdentity([root, org], JSON.stringify(['acme', 'helper']))).toBe(org);
+ expect(findGhostForRemotePluginIdentity([root, org], '_ns__acme__helper')).toBe(org);
+ expect(findGhostForRemotePluginIdentity([root, org], '_ns/acme/helper')).toBe(org);
+ expect(findGhostForRemotePluginIdentity([root, org], 'helper')).toBeUndefined();
+ expect(findGhostForRemotePluginIdentity([org], 'helper')).toBe(org);
+ expect(findGhostForRemotePluginIdentity([root, org], JSON.stringify(['other', 'helper']))).toBeUndefined();
+ expect(findGhostForRemotePluginIdentity([root, org], '["acme","../helper"]')).toBeUndefined();
+ });
+ it('projects the requested organization identity through the task-scoped resource', async () => {
+ const ghosts = [
+ { manifest: { id: 'helper' }, namespace: null, name: 'Root' },
+ { manifest: { id: 'helper' }, namespace: 'acme', name: 'Organization' },
+ ];
+ const provider = createPluginIdentityRemoteProvider({
+ readIdentity: (id) => {
+ const ghost = findGhostForRemotePluginIdentity(ghosts, id);
+ return ghost ? { name: ghost.name } : undefined;
+ },
+ authorize: async () => {}, captureScope: () => () => true,
+ });
+ const ref = { ...request.ref, id: JSON.stringify(['s', JSON.stringify(['acme', 'helper'])]) };
+ expect((await provider.get!(context, { ...request, ref })).display.title).toBe('Organization');
+ await expect(provider.get!(context, { ...request, ref: { ...ref, id: JSON.stringify(['s', 'helper']) } })).rejects.toThrow('Plugin not found');
+ const longNamespace = 'a'.repeat(126);
+ ghosts.push({ manifest: { id: 'helper' }, namespace: longNamespace, name: 'Long Namespace' });
+ const longRef = { ...ref, id: JSON.stringify(['s', JSON.stringify([longNamespace, 'helper'])]) };
+ expect((await provider.get!(context, { ...request, ref: longRef })).display.title).toBe('Long Namespace');
+ });
const request = { ref: { collectionId: 'plugin-identities', kind: 'plugin', id: '["s","art"]' }, client: { protocolVersion: 1, primitives: [] } };
it('projects only public name and bounded raster data, never credentials or local URLs', async () => {
const readIdentity = vi.fn(() => ({ name: 'Art', iconDataUrl: 'data:image/png;base64,YQ==', secret: 'private' }));
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts
index c5dcf843ba..ef4108a7e4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts
@@ -50,7 +50,97 @@ const update = (callId: string, html = '<p>x</p>', extra: Record<string, unknown
...extra,
});
+function deferredWrite() {
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<void>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+describe('GhostCardService relocation', () => {
+ it('drains every accepted source write even after its call was swept, without waiting for other plugins', async () => {
+ const pending = [deferredWrite(), deferredWrite(), deferredWrite()];
+ const persist = vi.fn()
+ .mockReturnValueOnce(pending[0].promise)
+ .mockReturnValueOnce(pending[1].promise)
+ .mockReturnValueOnce(pending[2].promise);
+ const { svc, advance } = makeService({ persist });
+ svc.registerCall('old', { ghostId: 'helper', toolUseId: null, sessionId: 's1' });
+ svc.handleCardUpdate('helper', update('old'));
+ advance(1000);
+ svc.handleCardUpdate('helper', update('old'));
+ svc.finalizeCall('old');
+ advance(31_000);
+ svc.registerCall('other', { ghostId: 'other', toolUseId: null, sessionId: 's2' });
+ svc.handleCardUpdate('other', update('other'));
+ expect(svc.ownerOf('old')).toBeNull();
+
+ const moved = vi.fn();
+ const relocation = svc.relocateGhost('helper', '_ns__acme__helper').then(moved);
+ pending[0].resolve();
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(moved).not.toHaveBeenCalled();
+ pending[1].resolve();
+ await relocation;
+ expect(moved).toHaveBeenCalledOnce();
+ pending[2].resolve();
+ });
+
+ it('awaits a failing outstanding write while preserving best-effort persistence', async () => {
+ const pending = deferredWrite();
+ const log = { debug: vi.fn(), warn: vi.fn() };
+ const { svc } = makeService({ persist: () => pending.promise, log });
+ svc.registerCall('old', { ghostId: 'helper', toolUseId: null, sessionId: 's1' });
+ svc.handleCardUpdate('helper', update('old'));
+ const moved = vi.fn();
+ const relocation = svc.relocateGhost('helper', '_ns__acme__helper').then(moved);
+ expect(svc.handleCardUpdate('helper', update('old')).reason).toBe('not-owner');
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(moved).not.toHaveBeenCalled();
+ pending.reject(new Error('db down'));
+ await relocation;
+ expect(log.warn).toHaveBeenCalledWith('ghost card persist failed', { callId: 'old', error: 'db down' });
+ expect(svc.ownerOf('old')).toBe('_ns__acme__helper');
+ });
+
+ it.each(['_ns__acme__helper', '_archive_helper'])('is idempotent and reversible without changing call scopes: %s', async (target) => {
+ const { svc } = makeService();
+ svc.registerCall('script', {
+ ghostId: 'helper', toolUseId: null, sessionId: null, channel: 'script',
+ scriptWorkdir: '/project', scriptWritePath: 'result.txt', remoteHostId: null,
+ });
+ svc.registerCall('session', {
+ ghostId: 'helper', toolUseId: 'tool-1', sessionId: 's1',
+ sessionInstanceId: 'instance-1', remoteHostId: 'ssh-1',
+ });
+ for (const [source, destination] of [['helper', target], ['helper', target], [target, 'helper']]) {
+ await svc.relocateGhost(source, destination);
+ expect(svc.inFlightCallInfoOf('script')).toEqual({
+ ghostId: destination, sessionId: null, remoteHostId: null, channel: 'script',
+ scriptWorkdir: '/project', scriptWritePath: 'result.txt',
+ });
+ expect(svc.inFlightCallInfoOf('session')).toEqual({
+ ghostId: destination, sessionId: 's1', sessionInstanceId: 'instance-1',
+ remoteHostId: 'ssh-1', channel: 'session', scriptWorkdir: null, scriptWritePath: null,
+ });
+ }
+ });
+});
+
describe('GhostCardService', () => {
+ it('broadcasts the trusted logical identity only for an in-place namespace install', () => {
+ const { svc, broadcast } = makeService();
+ svc.registerCall('org', { ghostId: 'helper', logicalGhostId: '_ns__acme__helper', toolUseId: null, sessionId: 's1' });
+ expect(svc.handleCardUpdate('helper', update('org')).accepted).toBe(true);
+ expect(broadcast).toHaveBeenCalledWith(expect.objectContaining({
+ ghostId: 'helper', logicalGhostId: '_ns__acme__helper',
+ }));
+ expect(svc.handleCardUpdate('_ns__acme__helper', update('org')).accepted).toBe(false);
+ });
+
it('接受链路:sanitize 产物落库并推送,hasCard/finalize 语义正确', async () => {
const { svc, persist, broadcast } = makeService();
svc.registerCall('c1', { ghostId: 'g1', toolUseId: 'tu1', sessionId: 's1' });
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardStoreDb.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardStoreDb.test.ts
index 579b62870b..b4731101df 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cardStoreDb.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardStoreDb.test.ts
@@ -11,6 +11,9 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';
import fs from 'node:fs';
import path from 'node:path';
import type { GhostCardDb } from '../cardStoreDb';
+import { GhostCardService } from '../cardService';
+import { GhostCardActionDispatcher } from '../cardActionDispatch';
+import { GHOST_CARD_REOPEN_WINDOW_MS, type InstalledGhost } from '../../../shared/ghost';
vi.mock('electron', () => ({
app: { getPath: () => '/tmp/never-used-here' },
@@ -51,6 +54,69 @@ beforeEach(() => {
});
describe('cardStoreDb', () => {
+ it.each(['_ns__acme__helper', '_archive_helper'])('drains queued inserts before reassigning live and historical actions: %s', async (target) => {
+ let releaseWrite!: () => void;
+ let now = 1_000_000;
+ const pending = new Promise<void>((resolve) => { releaseWrite = resolve; });
+ const svc = new GhostCardService({
+ hasCardSlot: () => true,
+ sanitize: (html) => ({ ok: true, html }),
+ persist: async (card) => { await pending; await store.upsertGhostCard(card, db); },
+ broadcast: vi.fn(),
+ now: () => now,
+ });
+ svc.registerCall('old', { ghostId: 'helper', toolUseId: null, sessionId: 'org-session' });
+ expect(svc.handleCardUpdate('helper', { type: 'card-update', callId: 'old', html: '<p>org</p>' }).accepted).toBe(true);
+ svc.finalizeCall('old');
+
+ const reassign = vi.fn(() => store.reassignGhostCards('helper', target, db));
+ const relocation = svc.relocateGhost('helper', target).then(reassign);
+ await Promise.resolve();
+ expect(reassign).not.toHaveBeenCalled();
+ releaseWrite();
+ await relocation;
+ expect(await store.getGhostCard('old', db)).toEqual(expect.objectContaining({ ghostId: target, sessionId: 'org-session' }));
+ await svc.relocateGhost('helper', target);
+ await store.reassignGhostCards('helper', target, db);
+
+ const archived = target.startsWith('_archive');
+ const sendToGhost = vi.fn();
+ const issueUserActionToken = vi.fn(() => 'user-action-token');
+ const dispatcher = new GhostCardActionDispatcher({
+ resolveLiveInfo: (callId) => svc.callInfoOf(callId),
+ resolvePersistedCard: (callId) => store.getGhostCard(callId, db),
+ reopenForAction: (callId, info) => svc.reopenForAction(callId, info),
+ getGhost: (ghostId) => ghostId === 'helper' || (!archived && ghostId === target)
+ ? { manifest: { id: 'helper', card: {} }, namespace: ghostId === target ? 'acme' : null, enabled: true } as InstalledGhost : null,
+ isRunning: () => true,
+ wake: async () => {},
+ sendToGhost,
+ issueUserActionToken,
+ now: () => now,
+ });
+ for (const historical of [false, true]) {
+ if (historical) {
+ now += GHOST_CARD_REOPEN_WINDOW_MS + 31_000;
+ svc.registerCall('root', { ghostId: 'helper', toolUseId: null, sessionId: 'root-session' });
+ expect(svc.callInfoOf('old')).toBeNull();
+ }
+ expect(await dispatcher.dispatch('old', 'retry', 'org prompt')).toEqual(
+ archived ? { ok: false, reason: 'ghost-unavailable' } : { ok: true },
+ );
+ }
+ if (archived) {
+ expect(sendToGhost).not.toHaveBeenCalled();
+ expect(issueUserActionToken).not.toHaveBeenCalled();
+ } else {
+ expect(sendToGhost.mock.calls.map(([ghostId]) => ghostId)).toEqual([target, target]);
+ expect(sendToGhost).toHaveBeenCalledWith(target, expect.objectContaining({ sessionId: 'org-session', prompt: 'org prompt' }));
+ expect(issueUserActionToken.mock.calls).toEqual([[target, 'org-session'], [target, 'org-session']]);
+ }
+ await svc.relocateGhost(target, 'helper');
+ await store.reassignGhostCards(target, 'helper', db);
+ expect(await store.getGhostCard('old', db)).toEqual(expect.objectContaining({ ghostId: 'helper', sessionId: 'org-session', html: '<p>org</p>' }));
+ });
+
it('upsert 幂等:同 callId 二次写入覆盖为最新版本', async () => {
await store.upsertGhostCard(row('c1', { html: '<p>过程</p>' }), db);
await store.upsertGhostCard(row('c1', { html: '<p>终版</p>', height: 400, updatedAt: 2000 }), db);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindyPackageFixture.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindyPackageFixture.ts
new file mode 100644
index 0000000000..1275640ad6
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindyPackageFixture.ts
@@ -0,0 +1,14 @@
+import fs from 'node:fs/promises';
+import JSZip from 'jszip';
+
+export async function writeTestCindyPackage(
+ filePath: string,
+ manifest: object | null,
+ files: Record<string, string | Uint8Array> = { 'main.js': '// ok\n' },
+): Promise<string> {
+ const zip = new JSZip();
+ if (manifest !== null) zip.file('ghost.json', JSON.stringify(manifest));
+ for (const [name, content] of Object.entries(files)) zip.file(name, content);
+ await fs.writeFile(filePath, await zip.generateAsync({ type: 'nodebuffer' }));
+ return filePath;
+}
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
index 43775ffffd..a0395ca32c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
@@ -1,7 +1,11 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import type { GhostManifest } from '../../../shared/ghost.js';
import {
ghostManifestDigest,
+ PluginMarketLedger,
type PluginMarketInstallationRecord,
} from '../../plugin-market/ledger.js';
import {
@@ -138,6 +142,68 @@ describe('installed Plugin Connection audience resolver', () => {
).toBeNull();
});
+ it('does not authorize a root twin through an uninstalled root row and a live organization row', () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-connection-identity-'));
+ try {
+ const ledger = new PluginMarketLedger(path.join(directory, 'ledger.v1.json'));
+ ledger.upsertInstallation({ ...marketInstallation, namespace: null, installed: false });
+ ledger.upsertInstallation({
+ ...marketInstallation,
+ pluginId: 'plugin-market-org',
+ namespace: identity.orgSlug,
+ });
+ const options = {
+ ...resolverOptions(),
+ readMarketInstallation: (id: string) => ledger.lookupInstallationForOidc(id),
+ readInstallNamespace: (id: string) =>
+ id === 'plugin-a' ? null : identity.orgSlug,
+ readApprovedPackageSha256: (id: string) =>
+ id === 'plugin-a' ? 'b'.repeat(64) : marketInstallation.sha256,
+ };
+ expect(ledger.lookupInstallationForOidc('plugin-a')).toMatchObject({
+ kind: 'found',
+ record: { namespace: identity.orgSlug, installed: true },
+ });
+ expect(loadConnectionAudienceResolver(options).resolve('plugin-a', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({
+ ...options,
+ readInstallNamespace: () => undefined,
+ }).resolve('plugin-a', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({
+ ...options,
+ readInstallNamespace: () => 'other-org',
+ }).resolve('plugin-a', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({
+ ...options,
+ readMarketInstallation: () => ({
+ kind: 'found' as const,
+ record: { ...marketInstallation, namespace: 'other-org' },
+ }),
+ readInstallNamespace: () => 'other-org',
+ }).resolve('plugin-a', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({
+ ...options,
+ readInstallNamespace: () => { throw new Error('receipt unavailable'); },
+ }).resolve('plugin-a', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({
+ ...options,
+ readMarketInstallation: () => ({
+ kind: 'found' as const,
+ record: { ...marketInstallation, namespace: null },
+ }),
+ readInstallNamespace: () => identity.orgSlug,
+ }).resolve('plugin-a', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({
+ ...options,
+ readInstallNamespace: () => identity.orgSlug,
+ }).resolve('plugin-a', identity)).toMatchObject({ audience: 'org-example:plugin-a' });
+ expect(loadConnectionAudienceResolver(options).resolve('_ns__org-example__plugin-a', identity))
+ .toMatchObject({ audience: 'org-example:plugin-a' });
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+ });
+
it('uses raw manifest bytes when the legacy digest is absent', () => {
const resolver = loadConnectionAudienceResolver(
resolverOptions(manifest, { ...marketInstallation, manifestDigest: undefined }),
@@ -208,7 +274,7 @@ describe('installed Plugin Connection audience resolver', () => {
}),
readInstallOrigin: () => 'agent-forge',
readApprovedPackageSha256: () => 'a'.repeat(64),
- lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ readInstallNamespace: () => 'org-example',
});
expect(resolver.resolve('acme-tool', identity)).toEqual({
membershipId: 'membership-1',
@@ -218,23 +284,75 @@ describe('installed Plugin Connection audience resolver', () => {
});
});
- it('does not extend Forge OIDC to a manual install or another prefix', () => {
+ it('preserves OIDC for a verified pending legacy Forge receipt in the current organization', () => {
const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };
+ const options = {
+ ...resolverOptions(forgeManifest, null),
+ readInstallOrigin: () => 'agent-forge' as const,
+ readInstallNamespace: () => undefined,
+ readApprovedPackageSha256: () => 'a'.repeat(64),
+ isPendingLegacyForge: () => true,
+ lookupOrganizationPrefix: () => ({ kind: 'known' as const, pluginPrefix: 'acme' }),
+ };
+ expect(loadConnectionAudienceResolver(options).resolve('acme-tool', identity)).toMatchObject({
+ audience: 'org-example:acme-tool',
+ });
+ expect(loadConnectionAudienceResolver({ ...options, isPendingLegacyForge: () => false })
+ .resolve('acme-tool', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({ ...options, lookupOrganizationPrefix: () => ({
+ kind: 'known' as const, pluginPrefix: 'other',
+ }) }).resolve('acme-tool', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({ ...options, lookupOrganizationPrefix: () => ({
+ kind: 'known' as const, pluginPrefix: null,
+ }) }).resolve('acme-tool', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({ ...options, readInstallNamespace: () => null })
+ .resolve('acme-tool', identity)).toBeNull();
+ expect(loadConnectionAudienceResolver({ ...options, lookupOrganizationPrefix: () => ({
+ kind: 'unavailable' as const,
+ }) }).resolve('acme-tool', identity)).toBeNull();
+ });
+
+ it('does not extend Forge OIDC to a manual install or another organization', () => {
+ const forgeManifest: GhostManifest = { ...manifest, id: 'helper' };
for (const options of [
- { readInstallOrigin: () => 'manual' as const, pluginPrefix: 'acme' },
- { readInstallOrigin: () => 'agent-forge' as const, pluginPrefix: 'other' },
+ { readInstallOrigin: () => 'manual' as const, namespace: 'org-example' as string | null },
+ { readInstallOrigin: () => 'agent-forge' as const, namespace: 'other' as string | null },
]) {
const resolver = loadConnectionAudienceResolver({
...resolverOptions(forgeManifest, null),
readInstallOrigin: options.readInstallOrigin,
readApprovedPackageSha256: () => 'a'.repeat(64),
- lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: options.pluginPrefix }),
+ readInstallNamespace: () => options.namespace,
});
- expect(resolver.resolve('acme-tool', identity)).toBeNull();
+ expect(resolver.resolve('helper', identity)).toBeNull();
}
});
- it('resolves a named local mivo-canvas install without a market record', () => {
+ it('resolves a prefix-free Forge helper bound to the current organization', () => {
+ const forgeManifest: GhostManifest = { ...manifest, id: 'helper' };
+ const resolver = loadConnectionAudienceResolver({
+ ...resolverOptions(forgeManifest, null),
+ readInstallOrigin: () => 'agent-forge',
+ readApprovedPackageSha256: () => 'a'.repeat(64),
+ readInstalledManifestIdentity: (id) =>
+ id === '_ns__org-example__helper' || id === 'helper'
+ ? {
+ manifest: forgeManifest,
+ rawManifestSha256: ghostManifestDigest(forgeManifest),
+ legacyManifestDigest: ghostManifestDigest(forgeManifest),
+ legacyManifestDigests: [ghostManifestDigest(forgeManifest)],
+ }
+ : null,
+ });
+ expect(resolver.resolve('_ns__org-example__helper', identity)).toEqual({
+ membershipId: 'membership-1',
+ audience: 'org-example:helper',
+ pluginSlug: 'helper',
+ allowedHosts: ['service-a.x.test'],
+ });
+ });
+
+ it('resolves a root local mivo-canvas install without a market record', () => {
const localManifest: GhostManifest = {
...manifest,
id: 'mivo-canvas',
@@ -254,28 +372,83 @@ describe('installed Plugin Connection audience resolver', () => {
],
},
};
- const resolver = loadConnectionAudienceResolver({
- ...resolverOptions(localManifest, null),
- readInstallOrigin: () => 'manual',
- });
- expect(resolver.resolve('mivo-canvas', identity)).toEqual({
+ const allowed = {
membershipId: 'membership-1',
audience: 'org-example:mivo-canvas',
pluginSlug: 'mivo-canvas',
allowedHosts: ['mivo-canvas.dsworks.cn'],
- });
- expect(
- loadConnectionAudienceResolver({
+ };
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(localManifest, null),
+ readInstallOrigin: () => 'manual',
+ }).resolve('mivo-canvas', identity)).toEqual(allowed);
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(localManifest, null),
+ readMarketInstallation: () => ({ kind: 'absent' }),
+ readInstallOrigin: () => 'manual',
+ readInstallNamespace: () => null,
+ }).resolve('_root__mivo-canvas', identity)).toEqual(allowed);
+ });
+
+ it('does not apply the local mivo-canvas exception to an organization instance', () => {
+ const localManifest: GhostManifest = {
+ ...manifest,
+ id: 'mivo-canvas',
+ network: {
+ hosts: ['mivo-canvas.dsworks.cn'],
+ secrets: [
+ {
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token' as const,
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['mivo-canvas.dsworks.cn'],
+ },
+ },
+ ],
+ },
+ };
+ for (const instanceId of ['_ns/xd/mivo-canvas', '_ns/acme/mivo-canvas', '_ns__xd__mivo-canvas']) {
+ expect(loadConnectionAudienceResolver({
...resolverOptions(localManifest, null),
- readMarketInstallation: () => ({ kind: 'absent' }),
readInstallOrigin: () => 'manual',
- }).resolve('mivo-canvas', identity),
- ).toEqual({
- membershipId: 'membership-1',
- audience: 'org-example:mivo-canvas',
- pluginSlug: 'mivo-canvas',
- allowedHosts: ['mivo-canvas.dsworks.cn'],
- });
+ }).resolve(instanceId, identity)).toBeNull();
+ }
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(localManifest, null),
+ readInstallOrigin: () => 'manual',
+ readInstallNamespace: () => 'xd',
+ }).resolve('mivo-canvas', identity)).toBeNull();
+ });
+
+ it('does not apply the local mivo-canvas exception to a different plugin id', () => {
+ for (const id of ['mivo-canvas2', 'xd-mivo-canvas']) {
+ const localManifest: GhostManifest = {
+ ...manifest,
+ id,
+ network: {
+ hosts: ['mivo-canvas.dsworks.cn'],
+ secrets: [
+ {
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token' as const,
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['mivo-canvas.dsworks.cn'],
+ },
+ },
+ ],
+ },
+ };
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(localManifest, null),
+ readInstallOrigin: () => 'manual',
+ }).resolve(id, identity)).toBeNull();
+ }
});
it('does not extend the local mivo-canvas exception past an exact id and org membership', () => {
@@ -489,6 +662,213 @@ describe('installed Plugin Connection audience resolver', () => {
expect(resolver.resolve('mivo-canvas', identity)).toBeNull();
});
+ it('resolves a namespaced instance id to the plugin slug audience', () => {
+ const readInstalledManifestIdentity = vi.fn((id: string) =>
+ id === '_ns__org-example__plugin-a'
+ ? {
+ manifest,
+ rawManifestSha256: ghostManifestDigest(manifest),
+ legacyManifestDigest: ghostManifestDigest(manifest),
+ legacyManifestDigests: [ghostManifestDigest(manifest)],
+ }
+ : null,
+ );
+ const readMarketInstallation = vi.fn((id: string) =>
+ id === '_ns__org-example__plugin-a'
+ ? { kind: 'found' as const, record: { ...marketInstallation, namespace: 'org-example' } }
+ : { kind: 'absent' as const },
+ );
+ const readInstallOrigin = vi.fn(() => 'manual' as const);
+ const resolver = loadConnectionAudienceResolver({
+ readInstalledManifestIdentity,
+ readMarketInstallation,
+ readInstallOrigin,
+ readInstallNamespace: () => 'org-example',
+ });
+ expect(resolver.resolve('_ns__org-example__plugin-a', identity)).toEqual({
+ membershipId: 'membership-1',
+ audience: 'org-example:plugin-a',
+ pluginSlug: 'plugin-a',
+ allowedHosts: ['service-a.x.test'],
+ });
+ expect(readInstalledManifestIdentity).toHaveBeenCalledWith('_ns__org-example__plugin-a');
+ expect(readMarketInstallation).toHaveBeenCalledWith('_ns__org-example__plugin-a');
+ expect(readInstallOrigin).toHaveBeenCalledWith('_ns__org-example__plugin-a');
+ });
+
+ it('resolves a pending legacy xd-mivo-canvas after the market row gains namespace xd', () => {
+ const canvasManifest: GhostManifest = { ...manifest, id: 'xd-mivo-canvas' };
+ const xdIdentity = { ...identity, orgId: 'org-xd', orgSlug: 'xd' };
+ const record: PluginMarketInstallationRecord = {
+ ...marketInstallation,
+ pluginId: 'cb163dbadea776c1b9ce9be38',
+ ghostId: 'xd-mivo-canvas',
+ organizationId: 'org-xd',
+ namespace: 'xd',
+ manifestDigest: ghostManifestDigest(canvasManifest),
+ rawManifestSha256: ghostManifestDigest(canvasManifest),
+ };
+ const resolver = loadConnectionAudienceResolver({
+ ...resolverOptions(canvasManifest, record),
+ readInstallNamespace: () => undefined,
+ isPendingLegacyNamespace: () => true,
+ });
+ expect(resolver.resolve('xd-mivo-canvas', xdIdentity)).toEqual({
+ membershipId: 'membership-1',
+ audience: 'xd:xd-mivo-canvas',
+ pluginSlug: 'xd-mivo-canvas',
+ allowedHosts: ['service-a.x.test'],
+ });
+ });
+
+
+ it('resolves xd-mivo-canvas after the pending install is confirmed in place', () => {
+ const canvasManifest: GhostManifest = { ...manifest, id: 'xd-mivo-canvas' };
+ const xdIdentity = { ...identity, orgId: 'org-xd', orgSlug: 'xd' };
+ const record: PluginMarketInstallationRecord = {
+ ...marketInstallation,
+ pluginId: 'cb163dbadea776c1b9ce9be38',
+ ghostId: 'xd-mivo-canvas',
+ organizationId: 'org-xd',
+ namespace: 'xd',
+ manifestDigest: ghostManifestDigest(canvasManifest),
+ rawManifestSha256: ghostManifestDigest(canvasManifest),
+ };
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(canvasManifest, record),
+ readInstallNamespace: () => 'xd',
+ }).resolve('xd-mivo-canvas', xdIdentity)).toMatchObject({ audience: 'xd:xd-mivo-canvas' });
+ });
+
+ it('resolves a newly installed namespaced xd-mivo-canvas', () => {
+ const canvasManifest: GhostManifest = { ...manifest, id: 'xd-mivo-canvas' };
+ const xdIdentity = { ...identity, orgId: 'org-xd', orgSlug: 'xd' };
+ const record: PluginMarketInstallationRecord = {
+ ...marketInstallation,
+ pluginId: 'cb163dbadea776c1b9ce9be38',
+ ghostId: 'xd-mivo-canvas',
+ organizationId: 'org-xd',
+ namespace: 'xd',
+ manifestDigest: ghostManifestDigest(canvasManifest),
+ rawManifestSha256: ghostManifestDigest(canvasManifest),
+ };
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(canvasManifest, record),
+ readInstallNamespace: () => 'xd',
+ }).resolve('_ns__xd__xd-mivo-canvas', xdIdentity)).toMatchObject({
+ audience: 'xd:xd-mivo-canvas',
+ pluginSlug: 'xd-mivo-canvas',
+ });
+ });
+
+ it('rejects a pending legacy install whose catalog namespace is another org', () => {
+ const canvasManifest: GhostManifest = { ...manifest, id: 'xd-mivo-canvas' };
+ const xdIdentity = { ...identity, orgId: 'org-xd', orgSlug: 'xd' };
+ const record: PluginMarketInstallationRecord = {
+ ...marketInstallation,
+ ghostId: 'xd-mivo-canvas',
+ organizationId: 'org-xd',
+ namespace: 'other-org',
+ manifestDigest: ghostManifestDigest(canvasManifest),
+ rawManifestSha256: ghostManifestDigest(canvasManifest),
+ };
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(canvasManifest, record),
+ readInstallNamespace: () => undefined,
+ isPendingLegacyNamespace: () => true,
+ }).resolve('xd-mivo-canvas', xdIdentity)).toBeNull();
+ });
+
+ it('rejects a pending legacy install for a different organization id', () => {
+ const canvasManifest: GhostManifest = { ...manifest, id: 'xd-mivo-canvas' };
+ const xdIdentity = { ...identity, orgId: 'org-xd', orgSlug: 'xd' };
+ const record: PluginMarketInstallationRecord = {
+ ...marketInstallation,
+ ghostId: 'xd-mivo-canvas',
+ organizationId: 'org-other',
+ namespace: 'xd',
+ manifestDigest: ghostManifestDigest(canvasManifest),
+ rawManifestSha256: ghostManifestDigest(canvasManifest),
+ };
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(canvasManifest, record),
+ readInstallNamespace: () => undefined,
+ isPendingLegacyNamespace: () => true,
+ }).resolve('xd-mivo-canvas', xdIdentity)).toBeNull();
+ });
+
+ it('does not authorize an unconfirmed install just because the catalog namespace was backfilled', () => {
+ const canvasManifest: GhostManifest = { ...manifest, id: 'xd-mivo-canvas' };
+ const xdIdentity = { ...identity, orgId: 'org-xd', orgSlug: 'xd' };
+ const record: PluginMarketInstallationRecord = {
+ ...marketInstallation,
+ ghostId: 'xd-mivo-canvas',
+ organizationId: 'org-xd',
+ namespace: 'xd',
+ manifestDigest: ghostManifestDigest(canvasManifest),
+ rawManifestSha256: ghostManifestDigest(canvasManifest),
+ };
+ expect(loadConnectionAudienceResolver({
+ ...resolverOptions(canvasManifest, record),
+ readInstallNamespace: () => undefined,
+ isPendingLegacyNamespace: () => false,
+ }).resolve('xd-mivo-canvas', xdIdentity)).toBeNull();
+ });
+
+ it('resolves a local mivo-canvas and a pending xd-mivo-canvas independently', () => {
+ const localManifest: GhostManifest = {
+ ...manifest,
+ id: 'mivo-canvas',
+ network: {
+ hosts: ['mivo-canvas.dsworks.cn'],
+ secrets: [{
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token' as const,
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['mivo-canvas.dsworks.cn'],
+ },
+ }],
+ },
+ };
+ const canvasManifest: GhostManifest = { ...manifest, id: 'xd-mivo-canvas' };
+ const xdIdentity = { ...identity, orgId: 'org-xd', orgSlug: 'xd' };
+ const record: PluginMarketInstallationRecord = {
+ ...marketInstallation,
+ pluginId: 'cb163dbadea776c1b9ce9be38',
+ ghostId: 'xd-mivo-canvas',
+ organizationId: 'org-xd',
+ namespace: 'xd',
+ manifestDigest: ghostManifestDigest(canvasManifest),
+ rawManifestSha256: ghostManifestDigest(canvasManifest),
+ };
+ const resolver = loadConnectionAudienceResolver({
+ readInstalledManifestIdentity: (id: string) => {
+ const chosen = id === 'mivo-canvas' ? localManifest : canvasManifest;
+ return {
+ manifest: chosen,
+ rawManifestSha256: ghostManifestDigest(chosen),
+ legacyManifestDigest: ghostManifestDigest(chosen),
+ legacyManifestDigests: [ghostManifestDigest(chosen)],
+ };
+ },
+ readMarketInstallation: (id: string) => (id === 'mivo-canvas' ? null : record),
+ readInstallOrigin: () => 'manual',
+ readInstallNamespace: () => undefined,
+ isPendingLegacyNamespace: (id: string) => id !== 'mivo-canvas',
+ });
+ expect(resolver.resolve('mivo-canvas', xdIdentity)).toMatchObject({
+ audience: 'xd:mivo-canvas',
+ pluginSlug: 'mivo-canvas',
+ });
+ expect(resolver.resolve('xd-mivo-canvas', xdIdentity)).toMatchObject({
+ audience: 'xd:xd-mivo-canvas',
+ pluginSlug: 'xd-mivo-canvas',
+ });
+ });
+
it('requires the managed secret target to match a declared exact host', () => {
const resolver = loadConnectionAudienceResolver({
...resolverOptions(),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.ts
index 835b0abf3b..6d200148bf 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.ts
@@ -8,11 +8,11 @@ const source = fs.readFileSync(path.join(__dirname, '..', 'index.ts'), 'utf8');
it('uninstall waits for actual Node exit before removing plugin files and cache', () => {
const start = source.indexOf('async function uninstallGhostAndCleanupLocked(');
const body = source.slice(start, source.indexOf('\n}', start));
- const wait = body.indexOf('await getGhostNodeRuntimeBroker().stopAndWait(id)');
+ const wait = body.indexOf('await getGhostNodeRuntimeBroker().stopAndWait(storagePart)');
expect(wait).toBeGreaterThan(0);
- expect(body.indexOf('runtime.stop(id)')).toBeGreaterThan(0);
- expect(body.indexOf('runtime.stop(id)')).toBeLessThan(wait);
- expect(body.indexOf('await manager.uninstall(')).toBeGreaterThan(wait);
+ expect(body.indexOf('runtime.stop(storagePart)')).toBeGreaterThan(0);
+ expect(body.indexOf('runtime.stop(storagePart)')).toBeLessThan(wait);
+ expect(body.indexOf('await mutation.uninstall(')).toBeGreaterThan(wait);
expect(body.indexOf('await pluginDownloads.removePlugin(')).toBeGreaterThan(wait);
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/featureRetirement.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/featureRetirement.test.ts
index b18661b04e..59a2e9bdc8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/featureRetirement.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/featureRetirement.test.ts
@@ -155,4 +155,13 @@ describe('feature retirement upgrade', () => {
});
expect(manager().list()).toEqual([]);
});
+ it('keeps same-name retirement receipts on separate instance keys', () => {
+ const store = new FeatureRetirementStore(() => state);
+ expect(store.observe('ios-simulator', '_root__helper', true).unread).toBe(true);
+ expect(store.observe('ios-simulator', '_ns__acme__helper', true).unread).toBe(true);
+ store.acknowledge('ios-simulator', '_root__helper');
+ expect(store.observe('ios-simulator', '_root__helper', true).unread).toBe(false);
+ expect(store.observe('ios-simulator', '_ns__acme__helper', true).unread).toBe(true);
+ });
+
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/filoGoogleClientConfig.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/filoGoogleClientConfig.test.ts
deleted file mode 100644
index 87648fa8d7..0000000000
--- a/apps/desktop/src/main/cindy-brain/__tests__/filoGoogleClientConfig.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { GhostManifest } from '../../../shared/ghost.js';
-import { withFiloGoogleBuildClientConfig } from '../filoGoogleClientConfig.js';
-
-function manifest(oauth: Record<string, unknown> = {}): GhostManifest {
- return {
- schemaVersion: 2,
- id: 'filo-google',
- name: 'Filo Google',
- version: '1.0.0',
- kind: 'chip',
- entry: 'main.js',
- network: {
- hosts: ['accounts.google.com'],
- secrets: [{
- key: 'google_account',
- label: 'Google 账号',
- source: 'oauth',
- inject: { header: 'Authorization', format: 'Bearer {value}' },
- oauth: {
- authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
- tokenUrl: 'https://oauth2.googleapis.com/token',
- ...oauth,
- },
- }],
- },
- };
-}
-
-describe('withFiloGoogleBuildClientConfig', () => {
- it('只在 main 内存 manifest 补构建环境 client,不修改原对象', () => {
- const source = manifest();
- const hydrated = withFiloGoogleBuildClientConfig(source, {
- clientId: ' build-client ',
- clientSecret: ' build-secret ',
- });
- const oauth = hydrated.network?.secrets?.[0]?.oauth;
- expect(oauth).toMatchObject({ clientId: 'build-client', clientSecret: 'build-secret' });
- expect(source.network?.secrets?.[0]?.oauth?.clientId).toBeUndefined();
- });
-
- it('非 Filo Google 或未配置环境变量时原样返回', () => {
- const source = manifest();
- expect(withFiloGoogleBuildClientConfig(source, {})).toBe(source);
- expect(withFiloGoogleBuildClientConfig({ ...source, id: 'other' }, { clientId: 'x' }).id).toBe('other');
- });
-
- it('发布环境只给 clientId 时按纯 PKCE 处理,不混用旧 secret', () => {
- const source = manifest({ clientId: 'old-client', clientSecret: 'old-secret' });
- const oauth = withFiloGoogleBuildClientConfig(source, { clientId: 'new-client' })
- .network?.secrets?.[0]?.oauth;
- expect(oauth?.clientId).toBe('new-client');
- expect(oauth?.clientSecret).toBeUndefined();
- });
-});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts
index 8fce157cce..a644077a3e 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts
@@ -19,8 +19,9 @@ describe('FORGE_GUIDE · Cindy Connection 凭证章节', () => {
'POST / PUT / PATCH / DELETE',
'显式调用 `ghost_forge_install` 安装',
'要求用户手输相同 id',
- '个人身份与手动导入默认不签发',
- '仅 `ghostId` 精确等于 `mivo-canvas` 且精确 oidc-token host 仅为 `mivo-canvas.dsworks.cn` 的组织成员本地安装可解析 audience',
+ '个人身份与手动导入不签发',
+ '临时例外,只对 root 实例生效',
+ '不得借例外跳过',
'市场账本损坏、schema 不认或该 ghostId 记录校验失败时 fail-closed',
]) {
expect(FORGE_GUIDE).toContain(marker);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts
index e726caf578..9332928996 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts
@@ -40,7 +40,7 @@ describe('FORGE_GUIDE · oauth 凭证章节', () => {
'tokenBroker 没同时声明 redirectPort',
'或与 clientSecret 同时声明',
'三路资格',
- '静态官方前缀照旧放行',
+ '随包官方种子或受信任公开市场的官方插件',
'当前组织的服务端',
'organization market 包已安装',
'organizationId 与当前组织一致',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 1acc8f21cc..ff31272341 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -166,6 +166,18 @@ async function makeSrcDir(files: Record<string, string | Buffer>): Promise<strin
}
describe('packGhostDir', () => {
+ it.each([null, 'xd'])('rejects author-declared namespace %s before v2 normalization', async (namespace) => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify({ ...GOOD_MANIFEST, namespace }),
+ 'main.js': 'export default {};',
+ });
+ await expect(packGhostDir(dir)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: expect.stringContaining('ghost.json 不允许作者声明 namespace'),
+ });
+ });
+
it('rejects a new tokenBroker package without redirectPort but accepts the declared-port shape', async () => {
const brokerManifest = {
...GOOD_MANIFEST,
@@ -1724,9 +1736,7 @@ describe('FORGE_GUIDE', () => {
'个人身份下的 Forge 安装绝不会仅凭自测标记取得 Broker 或 Connection 权限',
);
expect(FORGE_GUIDE).toContain('受组织默认插件自动接管保护');
- expect(FORGE_GUIDE).toContain(
- '仅 `ghostId` 精确等于 `mivo-canvas` 且精确 oidc-token host 仅为 `mivo-canvas.dsworks.cn` 的组织成员本地安装可解析 audience',
- );
+ expect(FORGE_GUIDE).toContain('仅 `ghostId` 精确等于 `mivo-canvas`、namespace 为 null 或尚未确认,且精确 oidc-token host 仅为 `mivo-canvas.dsworks.cn` 的组织成员本地安装可解析 audience');
});
it('开场白要求读完沙箱红线与打包测试两章', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
index eedff4194f..7895223aee 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
@@ -35,7 +35,7 @@ describe('Forge OIDC install entry wiring', () => {
expect(body).toContain('const installOrigin = forgeInstallOriginForMembership(membershipKind);');
expect(body).toContain('...(installOrigin ? { installOrigin } : {})');
expect(body).toContain(
- 'ghostInstallApprovalToken(installed.approval),\n consent,\n installOrigin,',
+ 'ghostInstallApprovalToken(installed.approval),\n installedGhostStoragePart(installed),\n consent,\n installOrigin,',
);
expect(body).not.toContain("installOrigin: 'agent-forge'");
});
@@ -61,9 +61,10 @@ describe('Forge OIDC install entry wiring', () => {
expect(lease).toBeGreaterThan(lock);
});
- it('tokenBroker 只在企业身份下拿 Forge facts,且不触发 OIDC 确认窗', () => {
+ it('tokenBroker 拿 Forge facts 时带上当前组织 namespace,且不触发 OIDC 确认窗', () => {
const body = forgeInstallBody();
- expect(body).toContain('installOrigin ? { installOrigin } : undefined');
+ expect(body).toContain('...(installOrigin ? { installOrigin } : {})');
+ expect(body).toContain('namespace: forgeNamespace ?? null');
expect(body).toContain('forgeOidcInstallConfirmFacts(');
});
@@ -80,4 +81,14 @@ describe('Forge OIDC install entry wiring', () => {
expect(wiring).not.toContain('BrowserWindow.getAllWindows');
expect(source).not.toContain('function pickTrustedAppWindow');
});
+
+ it('只把同一 namespace 的已装实例当成更新', () => {
+ const body = forgeInstallBody();
+ const check = body.indexOf('if (!existingForForge && !isValidNewGhostId(inspected.manifest.id))');
+ const existing = body.indexOf('const existingForForge = findInstalledGhostForDeliveryTarget');
+ expect(existing).toBeGreaterThanOrEqual(0);
+ expect(check).toBeGreaterThan(existing);
+ expect(body).not.toContain('ghost.manifest.id === inspected.manifest.id');
+ });
+
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
index 57fd831c9a..8117552a9d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
@@ -85,7 +85,13 @@ function makeHarness(dataRoot: string, overrides: HarnessOverrides = {}) {
writeSaveDeposit:
overrides.saveWrite ?? (async (_ghostId, _token, fileName) => ({ fileName })),
};
- return { slot: new GhostFsSlot(deps), confirmCalls };
+ return { slot: new GhostFsSlot(deps), confirmCalls, deps };
+}
+
+function deferredSignal() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((accept) => { resolve = accept; });
+ return { promise, resolve };
}
/** Real Session authority with an in-memory provider, so the production resolver is exercised. */
@@ -159,9 +165,134 @@ describe('GhostFsSlot', () => {
});
afterEach(async () => {
+ vi.restoreAllMocks();
await fs.promises.rm(tmpRoot, { recursive: true, force: true });
});
+ describe('in-flight requests', () => {
+ it.each(['data', 'session-workdir', 'script-workdir'] as const)(
+ '%s blocks relocation through the final native write and cleans up on success or failure',
+ async (channel) => {
+ const base = path.join(dataRoot, GHOST_ID);
+ const relocated = path.join(dataRoot, '_ns__acme__' + GHOST_ID);
+ await fs.promises.mkdir(base, { recursive: true });
+ const target = path.join(channel === 'data' ? base : await fs.promises.realpath(workdir), 'pending.txt');
+ const { slot } = makeHarness(dataRoot, channel === 'script-workdir' ? {
+ callSessionId: null, callScriptWorkdir: workdir,
+ } : { session: {
+ workingDir: workdir, permissionMode: 'acceptEdits', planModeEnabled: false, remoteHostId: null,
+ } });
+ const migrate = () => {
+ if (slot.hasInFlightRequests(GHOST_ID)) throw new Error('FS busy');
+ fs.renameSync(base, relocated);
+ };
+ const nativeWrite = fs.promises.writeFile;
+ for (const failWrite of [false, true]) {
+ const started = deferredSignal();
+ const resume = deferredSignal();
+ const write = vi.spyOn(fs.promises, 'writeFile').mockImplementation(async (...args) => {
+ if (args[0] === target) {
+ started.resolve();
+ await resume.promise;
+ if (failWrite) throw new Error('write failed');
+ }
+ return nativeWrite(...args);
+ });
+ const pending = slot.handleFsRequest(GHOST_ID, {
+ op: 'write', root: channel === 'data' ? 'data' : 'workdir',
+ path: 'pending.txt', content: 'org-data', callId: 'call-1',
+ });
+ try {
+ await started.promise;
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(true);
+ expect(slot.hasInFlightRequests('_ns__acme__' + GHOST_ID)).toBe(false);
+ expect(migrate).toThrow('FS busy');
+ expect(fs.existsSync(base)).toBe(true);
+ expect(fs.existsSync(relocated)).toBe(false);
+ } finally {
+ resume.resolve();
+ await pending;
+ write.mockRestore();
+ }
+ expect(await pending).toMatchObject({ ok: !failWrite });
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(false);
+ }
+ expect(migrate).not.toThrow();
+ expect(fs.existsSync(relocated)).toBe(true);
+ },
+ );
+
+ it.each(['unlink', 'rmdir'] as const)('tracks data deletion through %s and cleanup on native failure', async (operation) => {
+ const { slot } = makeHarness(dataRoot);
+ const directory = path.join(dataRoot, GHOST_ID, 'nested');
+ const target = path.join(directory, 'delete.txt');
+ const nativeRemove = fs.promises[operation];
+ for (const failRemove of [false, true]) {
+ await fs.promises.mkdir(directory, { recursive: true });
+ await fs.promises.writeFile(target, 'org-data');
+ const started = deferredSignal();
+ const resume = deferredSignal();
+ const remove = vi.spyOn(fs.promises, operation).mockImplementation(async (entry) => {
+ if (entry === (operation === 'unlink' ? target : directory)) {
+ started.resolve();
+ await resume.promise;
+ if (failRemove) throw new Error('remove failed');
+ }
+ return nativeRemove(entry);
+ });
+ const pending = slot.handleFsRequest(GHOST_ID, { op: 'delete', root: 'data', path: 'nested/delete.txt' });
+ try {
+ await started.promise;
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(true);
+ } finally {
+ resume.resolve();
+ await pending;
+ remove.mockRestore();
+ }
+ expect(await pending).toMatchObject({ ok: true, existed: !(operation === 'unlink' && failRemove) });
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(false);
+ }
+ });
+
+ it('counts concurrent save writes per physical instance until every request settles', async () => {
+ const first = deferredSignal();
+ const second = deferredSignal();
+ const namespaced = deferredSignal();
+ const gates = [first, second, namespaced];
+ const { deps } = makeHarness(dataRoot, { saveWrite: async (_ghostId, token, fileName) => {
+ await gates[Number(token)]!.promise;
+ if (token === '1') throw new Error('save failed');
+ return { fileName };
+ } });
+ const slot = new GhostFsSlot({ ...deps, getGhost: () => makeGhost(true) });
+ const namespacedId = '_ns__acme__' + GHOST_ID;
+ const requests = [GHOST_ID, GHOST_ID, namespacedId].map((id, index) => slot.handleFsRequest(id, {
+ op: 'write', root: 'save', path: 'save.txt', content: 'org-data', token: String(index),
+ }));
+ try {
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(true);
+ expect(slot.hasInFlightRequests(namespacedId)).toBe(true);
+ slot.setSessionSnapshotResolver(async () => null);
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(true);
+ expect(slot.hasInFlightRequests(namespacedId)).toBe(true);
+ first.resolve();
+ expect(await requests[0]).toMatchObject({ ok: true });
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(true);
+ second.resolve();
+ expect(await requests[1]).toMatchObject({ ok: false });
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(false);
+ expect(slot.hasInFlightRequests(namespacedId)).toBe(true);
+ } finally {
+ gates.forEach((gate) => gate.resolve());
+ await Promise.all(requests);
+ }
+ expect(await requests[2]).toMatchObject({ ok: true });
+ expect(slot.hasInFlightRequests(namespacedId)).toBe(false);
+ expect(await slot.handleFsRequest(GHOST_ID, { op: 'invalid', root: 'data' })).toMatchObject({ ok: false });
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(false);
+ });
+ });
+
it('未声明 fs 能力一律拒', async () => {
const { slot } = makeHarness(dataRoot, { fs: false });
const r = await slot.handleFsRequest(GHOST_ID, {
@@ -378,6 +509,20 @@ describe('GhostFsSlot', () => {
expect(confirmCalls).toHaveLength(3);
});
+ it('a root occupying the old organization key cannot inherit its workdir confirmation', async () => {
+ const { slot, deps, confirmCalls } = makeHarness(dataRoot, {
+ session: { workingDir: workdir, permissionMode: 'default', planModeEnabled: false, remoteHostId: null },
+ });
+ let current = { ...makeGhost(true), namespace: 'acme' as string | null };
+ deps.getGhost = () => current;
+ const request = { type: 'fs-request', op: 'write', root: 'workdir', path: 'a.txt', content: 'org', callId: 'call-1' };
+ expect(await slot.handleFsRequest(GHOST_ID, request)).toMatchObject({ ok: true });
+ expect(slot.hasInFlightRequests(GHOST_ID)).toBe(false);
+ current = { ...current, namespace: null };
+ expect(await slot.handleFsRequest(GHOST_ID, { ...request, content: 'root' })).toMatchObject({ ok: true });
+ expect(confirmCalls).toHaveLength(2);
+ });
+
it('workdir:plan / planModeEnabled 拒', async () => {
for (const session of [
{ workingDir: workdir, permissionMode: 'plan', planModeEnabled: false, remoteHostId: null },
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostComposerIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostComposerIpc.test.ts
index 0607c7886f..58267c78be 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostComposerIpc.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostComposerIpc.test.ts
@@ -52,6 +52,23 @@ describe('remote composer catalog boundary', () => {
expect(mocks.trusted).not.toHaveBeenCalled();
});
+ it('keeps directory disablement on the instance key when ids collide', () => {
+ const root = ghost('helper');
+ const migrated = { ...ghost('helper'), namespace: 'acme' as const, instanceKey: 'helper' };
+ const installed = { ...ghost('helper'), namespace: 'acme' as const, instanceKey: '_ns__acme__helper' };
+ const result = createGhostComposerListHandler({
+ list: () => [root, migrated, installed],
+ disabledIds: () => ['helper'],
+ })(event, '/host/project');
+ expect(result.map((item) => [item.instanceKey, item.namespace ?? null, item.enabled])).toEqual([
+ ['helper', null, false],
+ ['helper', 'acme', false],
+ ['_ns__acme__helper', 'acme', true],
+ ]);
+ expect(JSON.stringify(result)).not.toMatch(/private|approval/);
+ expect(ghostComposerListSchema.safeParse(result).success).toBe(true);
+ });
+
it('validates local senders and rejects shared-task or mismatched invoke contexts', () => {
const list = vi.fn(() => [ghost('art')]);
const handler = createGhostComposerListHandler({ list, disabledIds: () => [] });
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostCredentialProtocolCallbacks.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostCredentialProtocolCallbacks.test.ts
new file mode 100644
index 0000000000..36abe1fa02
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostCredentialProtocolCallbacks.test.ts
@@ -0,0 +1,199 @@
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import { GhostConnectionManager } from '../ghostConnections.js';
+import { GhostOauthAccountManager } from '../ghostOauthAccounts.js';
+import { handleGhostConnectionsRequest } from '../runtime/ghostConnectionsEndpoint.js';
+import { handleGhostOauthRequest } from '../runtime/ghostOauthEndpoint.js';
+import { handleGhostSecretsRequest } from '../runtime/ghostSecretsEndpoint.js';
+
+type RequestArgs = {
+ ghostId: string;
+ method: string;
+ pathname: string;
+ readBodyText: () => Promise<string>;
+ isCurrent: () => boolean;
+};
+type Callback = (args: RequestArgs) => Promise<{ status: number; body?: string }>;
+
+const routes = [
+ { setter: 'setGhostSecretsHandler', method: 'PUT', pathname: '/secrets/user_key', body: '{"value":"fake-old-secret"}', status: 204 },
+ { setter: 'setGhostOauthHandler', method: 'PUT', pathname: '/oauth/oauth_key/client', body: '{"clientId":"fake-old-client"}', status: 204 },
+ { setter: 'setGhostConnectionsHandler', method: 'POST', pathname: '/connections/api', body: '{"host":"api.example.com","token":"fake-old-token"}', status: 200 },
+] as const;
+type Route = typeof routes[number];
+
+function loadCallback(setter: string, deps: Record<string, unknown>, omitGuard = false): Callback {
+ return createGhostProductionCallbacks<{ handler: Callback }>({
+ callbacks: { handler: [setter] },
+ transformCallback: omitGuard ? (source) => source.replace(/^\s*isCurrent,\r?\n/gm, '') : undefined,
+ })(deps).handler;
+}
+
+function deferred<Value>() {
+ let resolve!: (value: Value) => void;
+ const promise = new Promise<Value>((finish) => { resolve = finish; });
+ return { promise, resolve };
+}
+
+function harness(route: Route, opts: { omitGuard?: boolean; githubProbe?: boolean; storagePart?: string } = {}) {
+ const ghostId = opts.storagePart ?? (opts.githubProbe ? 'cindy-github' : 'helper');
+ const inject = { header: 'Authorization', format: 'Bearer {value}', hosts: ['api.example.com'] };
+ let installed: InstalledGhost = {
+ dir: '/plugins/helper', enabled: true,
+ approval: { state: 'approved', revision: 'original-receipt' },
+ manifest: {
+ schemaVersion: 2, id: opts.githubProbe ? 'cindy-github' : 'helper', name: 'Helper',
+ version: '1.0.0', kind: 'chip', entry: 'main.js', slots: ['network'],
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ { key: 'user_key', source: 'user', label: 'User key', inject },
+ { key: 'oauth_key', source: 'oauth', label: 'OAuth', inject, oauth: { authorizeUrl: 'https://api.example.com/auth', tokenUrl: 'https://api.example.com/token', scopes: [] } },
+ ...(opts.githubProbe ? [{ key: 'host_cli', source: 'gh-cli' as const, label: 'Host CLI', inject }] : []),
+ ],
+ connections: [{ key: 'api', label: 'API', maxConnections: 2, inject: { header: inject.header, format: inject.format } }],
+ },
+ },
+ };
+ const data = new Map([['replacement-sentinel', 'fake-new-source']]);
+ const store = vi.fn((targetId: string, key: string, value: string) => {
+ data.set(targetId + ' ' + key, value);
+ return true;
+ });
+ const remove = vi.fn((targetId: string, key: string) => { data.delete(targetId + ' ' + key); });
+ const vault = { read: (targetId: string, key: string) => data.get(targetId + ' ' + key) ?? null, store, remove };
+ const oauthManager = new GhostOauthAccountManager({
+ vault, openExternal: vi.fn(), fetchImpl: vi.fn() as unknown as typeof fetch,
+ });
+ const connectionManager = new GhostConnectionManager({ vault: { ...vault, readTail: () => null } });
+ const emit = vi.fn();
+ const notice = vi.fn();
+ const broadcast = vi.fn();
+ const lock = vi.fn(async (_ghostId: string, task: () => unknown) => task());
+ const showMessageBox = vi.fn(async () => ({ response: 0 }));
+ const probeAvailability = vi.fn(async () => true);
+ const handler = loadCallback(route.setter, {
+ findGhostForInstanceId: (targetId: string) => targetId === ghostId ? installed : null,
+ handleGhostSecretsRequest, handleGhostOauthRequest, handleGhostConnectionsRequest,
+ getGhostOauthAccountManager: () => oauthManager,
+ getGhostConnectionManager: () => connectionManager,
+ getGhostManager: () => ({ list: () => [installed] }),
+ isGhostTokenBrokerAuthorized: () => false,
+ withActiveOwnerGhostOauthMutationLock: lock,
+ readGhostSecret: vault.read, readGhostSecretTail: () => null,
+ storeGhostSecret: store, removeGhostSecret: remove,
+ getGhostSetupChangeBus: () => ({ emit }),
+ broadcastGhostHostNotice: notice, broadcastGhostsChanged: broadcast,
+ getAuthState: () => ({ user: null }),
+ resolveConnectionAudienceForGhost: () => null, isConnectionSecretReady: () => false,
+ isCindyOfficialTrustInfo: () => true,
+ getSharedGhCliTokenSource: () => ({ probeAvailability }),
+ GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL: 2,
+ dialog: { showMessageBox }, t: (key: string) => key,
+ log: { warn: vi.fn() },
+ }, opts.omitGuard);
+ const isCurrent = vi.fn(() => installed.approval.state === 'approved' && installed.approval.revision === 'original-receipt');
+ const request = (readBodyText: () => Promise<string>) => handler({
+ ghostId, method: route.method, pathname: route.pathname, readBodyText, isCurrent,
+ });
+ const change = (state: 'replacement' | 'invalid') => {
+ installed = { ...installed, approval: state === 'invalid'
+ ? { state: 'invalid' } : { state: 'approved', revision: 'replacement-receipt' } };
+ };
+ return { ghostId, request, change, isCurrent, data, store, remove, emit, notice, broadcast, lock, showMessageBox, probeAvailability };
+}
+
+describe('Credential protocol wiring through actual index callbacks', () => {
+ it.each(routes.flatMap((route) => (['replacement', 'invalid'] as const).map((change) => ({ route, change }))))(
+ 'blocks $route.pathname after $change while the old body is pending', async ({ route, change }) => {
+ const target = harness(route);
+ const body = deferred<string>();
+ const before = new Map(target.data);
+ const pending = target.request(() => body.promise);
+ target.change(change);
+ body.resolve(route.body);
+ expect(await pending).toEqual({ status: 403 });
+ expect(target.data).toEqual(before);
+ expect(target.store).not.toHaveBeenCalled();
+ expect(target.emit).not.toHaveBeenCalled();
+ expect(target.notice).not.toHaveBeenCalled();
+ expect(target.broadcast).not.toHaveBeenCalled();
+ expect(target.isCurrent).toHaveBeenCalled();
+ },
+ );
+
+ it.each(routes)('demonstrates the late-write regression when $setter omits only the forwarded guard', async (route) => {
+ const target = harness(route, { omitGuard: true });
+ const body = deferred<string>();
+ const before = new Map(target.data);
+ const pending = target.request(() => body.promise);
+ target.change('replacement');
+ body.resolve(route.body);
+ expect((await pending).status).toBe(route.status);
+ expect(target.data).not.toEqual(before);
+ expect(target.store).toHaveBeenCalled();
+ expect(target.emit).toHaveBeenCalled();
+ expect(target.isCurrent).not.toHaveBeenCalled();
+ });
+
+ it.each(routes)('allows $pathname for the unchanged organization instance', async (route) => {
+ const target = harness(route, { storagePart: '_ns__acme__helper' });
+ const result = await target.request(async () => route.body);
+ expect(result.status).toBe(route.status);
+ expect(target.store).toHaveBeenCalled();
+ expect(target.store.mock.calls.every(([targetId]) => targetId === '_ns__acme__helper')).toBe(true);
+ expect(target.emit).toHaveBeenCalled();
+ expect(target.isCurrent).toHaveBeenCalled();
+ });
+
+ it('keeps the forwarded OAuth guard inside the production mutation lock', async () => {
+ const target = harness(routes[1]);
+ const entered = deferred<void>();
+ const release = deferred<void>();
+ target.lock.mockImplementationOnce(async (_ghostId, task) => {
+ entered.resolve();
+ await release.promise;
+ return task();
+ });
+ const pending = target.request(async () => routes[1].body);
+ await entered.promise;
+ target.change('replacement');
+ release.resolve();
+ expect(await pending).toEqual({ status: 403 });
+ expect(target.store).not.toHaveBeenCalled();
+ expect(target.emit).not.toHaveBeenCalled();
+ expect(target.broadcast).not.toHaveBeenCalled();
+ });
+
+ it('keeps the forwarded connection guard after the production host confirmation', async () => {
+ const target = harness(routes[2]);
+ const entered = deferred<void>();
+ const confirmation = deferred<{ response: number }>();
+ target.showMessageBox.mockImplementationOnce(() => { entered.resolve(); return confirmation.promise; });
+ const pending = target.request(async () => routes[2].body);
+ await entered.promise;
+ target.change('replacement');
+ confirmation.resolve({ response: 0 });
+ expect(await pending).toEqual({ status: 403 });
+ expect(target.store).not.toHaveBeenCalled();
+ expect(target.emit).not.toHaveBeenCalled();
+ expect(target.notice).not.toHaveBeenCalled();
+ });
+
+ it('forwards the original guard after the Secrets callback awaits its host credential probe', async () => {
+ const target = harness(routes[0], { githubProbe: true });
+ const probe = deferred<boolean>();
+ target.probeAvailability.mockReturnValueOnce(probe.promise);
+ const readBodyText = vi.fn(async () => routes[0].body);
+ const pending = target.request(readBodyText);
+ target.change('replacement');
+ probe.resolve(true);
+ expect(await pending).toEqual({ status: 403 });
+ expect(readBodyText).not.toHaveBeenCalled();
+ expect(target.store).not.toHaveBeenCalled();
+ expect(target.emit).not.toHaveBeenCalled();
+ expect(target.notice).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts
index 1e81a3e15e..9b819937b3 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type { PluginMarketInstallationRecord } from '../../plugin-market/ledger.js';
import { createOrganizationPrefixStore } from '../../plugin-market/organizationPrefixStore.js';
@@ -24,11 +24,13 @@ const PERSONAL: GhostFirstPartyFactsIdentity = {
const ORG_A: GhostFirstPartyFactsIdentity = {
membershipKind: 'org',
orgId: 'org-a',
+ orgSlug: 'slug-a',
};
const ORG_B: GhostFirstPartyFactsIdentity = {
membershipKind: 'org',
orgId: 'org-b',
+ orgSlug: 'slug-b',
};
const MARKET_ROW: PluginMarketInstallationRecord = {
@@ -58,7 +60,10 @@ function loader(overrides: Partial<LoadGhostFirstPartyFactsLoaderOptions> = {})
return loadGhostFirstPartyFactsLoader({
readInstalledBuiltin: () => false,
readMarketInstallation: () => null,
- readApprovedPackageSha256: () => null,
+ readApprovedPackageSha256: (ghostId) => ['xd-feishu', 'xd-atlassian'].includes(ghostId) ? 'a'.repeat(64) : null,
+ readTrustedSource: (ghostId) => ['xd-feishu', 'xd-atlassian'].includes(ghostId) ? {
+ kind: 'builtin-official', ghostId, namespace: null, packageSha256: 'a'.repeat(64),
+ } : null,
lookupOrganizationPrefix: () => ({ kind: 'absent' }),
readInstallOrigin: () => 'manual',
...overrides,
@@ -66,6 +71,16 @@ function loader(overrides: Partial<LoadGhostFirstPartyFactsLoaderOptions> = {})
}
describe('loadGhostFirstPartyFactsLoader', () => {
+ it('reads a new root receipt without inheriting the same-name legacy organization receipt', () => {
+ const reads: string[] = [];
+ const loaded = loader({
+ readInstallNamespace: (id) => { reads.push(id); return id === 'xd-feishu' ? 'xd' : null; },
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'xd' }),
+ }).load('_root__xd-feishu', 'runtime', ORG_A);
+ expect(reads).toEqual(['_ns/_root/xd-feishu']);
+ expect(loaded).toMatchObject({ kind: 'ready', facts: { namespace: null } });
+ if (loaded.kind === 'ready') expect(resolveGhostFirstPartyPrivilege(loaded.facts).brokerEligible).toBe(false);
+ });
it('gives builtin official plugins broker on a personal identity with no prefix cache', () => {
const factsLoader = loader({
readInstalledBuiltin: (ghostId) => ghostId === 'xd-feishu' || ghostId === 'xd-atlassian',
@@ -80,10 +95,13 @@ describe('loadGhostFirstPartyFactsLoader', () => {
if (loaded.kind !== 'ready') continue;
expect(loaded.facts).toEqual({
ghostId,
+ namespace: null,
builtin: true,
marketRecord: null,
currentOrganization: null,
installOrigin: 'manual',
+ trustedSource: { kind: 'builtin-official', ghostId, namespace: null, packageSha256: 'a'.repeat(64) },
+ approvedPackageSha256: 'a'.repeat(64),
});
expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({
brokerEligible: true,
@@ -93,6 +111,37 @@ describe('loadGhostFirstPartyFactsLoader', () => {
}
});
+ it.each(['_ns__acme__acme-tool', '_ns/acme/acme-tool'])('loads logical facts using physical instance id %s', (instanceId) => {
+ const seen = {
+ builtin: vi.fn(() => false),
+ origin: vi.fn<LoadGhostFirstPartyFactsLoaderOptions['readInstallOrigin']>(() => 'manual'),
+ approved: vi.fn(() => 'a'.repeat(64)),
+ market: vi.fn(() => MARKET_ROW),
+ };
+ const factsLoader = loader({
+ readInstalledBuiltin: seen.builtin,
+ readInstallOrigin: seen.origin,
+ readApprovedPackageSha256: seen.approved,
+ readMarketInstallation: seen.market,
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ });
+
+ // The instance namespace is acme. A present orgSlug must match it.
+ const loaded = factsLoader.load(instanceId, 'runtime', { ...ORG_A, orgSlug: 'acme' });
+ expect(loaded.kind).toBe('ready');
+ if (loaded.kind !== 'ready') throw new Error('expected ready facts');
+ expect(loaded.facts.ghostId).toBe('acme-tool');
+ expect(seen.builtin.mock.calls).toEqual([[instanceId]]);
+ expect(seen.origin.mock.calls).toEqual([['_ns/acme/acme-tool']]);
+ expect(seen.approved.mock.calls).toEqual([['_ns/acme/acme-tool']]);
+ expect(seen.market.mock.calls).toEqual([[instanceId]]);
+ expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({
+ brokerEligible: true,
+ hostPrimitiveEligible: false,
+ basis: 'market-organization-current',
+ });
+ });
+
it('re-evaluates the current organization prefix after an org switch and keeps the previous key', () => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-first-party-facts-'));
const store = createOrganizationPrefixStore(path.join(tempDir, 'organization.v1.json'));
@@ -162,6 +211,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
kind: 'ready',
facts: {
ghostId: 'local-tool',
+ namespace: null,
builtin: false,
marketRecord: null,
currentOrganization: null,
@@ -214,7 +264,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
facts: {
marketRecord: null,
installOrigin: 'agent-forge',
- currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },
+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme', orgSlug: 'slug-a' },
},
});
});
@@ -244,9 +294,10 @@ describe('loadGhostFirstPartyFactsLoader', () => {
kind: 'ready',
facts: {
ghostId: 'acme-tool',
+ namespace: null,
builtin: false,
marketRecord: null,
- currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },
+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme', orgSlug: 'slug-a' },
installOrigin: 'manual',
},
});
@@ -263,6 +314,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
kind: 'ready',
facts: {
ghostId: 'acme-tool',
+ namespace: null,
builtin: false,
marketRecord: {
scope: 'organization',
@@ -272,7 +324,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
sha256: MARKET_ROW.sha256,
approvedPackageSha256: MARKET_ROW.sha256,
},
- currentOrganization: { organizationId: 'org-a', pluginPrefix: null },
+ currentOrganization: { organizationId: 'org-a', pluginPrefix: null, orgSlug: 'slug-a' },
installOrigin: 'manual',
},
});
@@ -296,7 +348,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
sha256: 'a'.repeat(64),
approvedPackageSha256: 'b'.repeat(64),
},
- currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },
+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme', orgSlug: 'slug-a' },
},
});
expect(MARKET_ROW.manifestDigest).toBe('c'.repeat(64));
@@ -306,6 +358,70 @@ describe('loadGhostFirstPartyFactsLoader', () => {
expect(resolveGhostFirstPartyPrivilege(loaded.facts).brokerEligible).toBe(false);
});
+ it('reads install namespace from a storage-part ghost id', () => {
+ const loaded = loader({
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: null }),
+ }).load('_ns__slug-a__helper', 'runtime', ORG_A);
+ expect(loaded).toMatchObject({
+ kind: 'ready',
+ facts: { ghostId: 'helper', namespace: 'slug-a' },
+ });
+ });
+
+ it('reads trusted receipt namespace for an in-place physical id', () => {
+ const factsLoader = loader({
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: null }),
+ readInstallOrigin: () => 'agent-forge',
+ readInstallNamespace: (id) => (id === 'acme-tool' ? 'slug-a' : undefined),
+ });
+ const loaded = factsLoader.load('acme-tool', 'runtime', ORG_A);
+ expect(loaded).toMatchObject({
+ kind: 'ready',
+ facts: { ghostId: 'acme-tool', namespace: 'slug-a', installOrigin: 'agent-forge' },
+ });
+ if (loaded.kind === 'ready') {
+ expect(authorizeGhostTokenBroker('acme-tool', loaded)).toBe(true);
+ }
+ });
+
+ it('distinguishes a censused legacy Forge from a new missing-namespace install', () => {
+ const factsLoader = loader({
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ readInstallOrigin: () => 'agent-forge',
+ isPendingLegacyForge: (id) => id === 'acme-old',
+ });
+ const legacy = factsLoader.load('acme-old', 'runtime', ORG_A);
+ expect(legacy).toMatchObject({ kind: 'ready', facts: { legacyPendingForge: true } });
+ if (legacy.kind === 'ready') expect(authorizeGhostTokenBroker('acme-old', legacy)).toBe(true);
+ const fresh = factsLoader.load('acme-new', 'install', ORG_A, { installOrigin: 'agent-forge' });
+ if (fresh.kind === 'ready') expect(authorizeGhostTokenBroker('acme-new', fresh)).toBe(false);
+ });
+
+ it.each([
+ ['missing', 'helper', {}, null, 'denied-foreign-org'],
+ ['organization', 'helper', { namespace: 'slug-a' }, 'slug-a', 'forge-current-org'],
+ ['explicit root', '_ns__slug-a__helper', { namespace: null }, null, 'denied-foreign-org'],
+ ] as const)('lets %s install-time namespace override win over the ghost id', (_label, instanceId, override, namespace, basis) => {
+ const factsLoader = loader({
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: null }),
+ });
+ const loaded = factsLoader.load(instanceId, 'install', ORG_A, {
+ installOrigin: 'agent-forge',
+ ...override,
+ });
+ expect(loaded).toMatchObject({
+ kind: 'ready',
+ facts: { ghostId: 'helper', namespace, installOrigin: 'agent-forge' },
+ });
+ if (loaded.kind !== 'ready') throw new Error('expected ready facts');
+ expect(authorizeGhostTokenBroker('helper', loaded)).toBe(namespace !== null);
+ expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({
+ brokerEligible: namespace !== null,
+ hostPrimitiveEligible: false,
+ basis,
+ });
+ });
+
it('binds pending organization-market authorization to the inspected package bytes', () => {
const pending = {
scope: 'organization' as const,
@@ -318,12 +434,13 @@ describe('loadGhostFirstPartyFactsLoader', () => {
kind: 'ready' as const,
facts: {
ghostId: 'acme-tool',
+ namespace: 'slug-a',
builtin: false,
marketRecord: bindPendingMarketRecordToInspectedPackage(
pending,
inspectedPackageSha256,
),
- currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },
+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme', orgSlug: 'slug-a' },
installOrigin: 'manual' as const,
},
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyInstallGate.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyInstallGate.test.ts
new file mode 100644
index 0000000000..a320a39f3e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyInstallGate.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import {
+ bindPendingMarketRecordToInspectedPackage,
+ loadGhostFirstPartyFactsLoader,
+} from '../ghostFirstPartyFacts.js';
+import { authorizeGhostHostPrimitive, authorizeGhostTokenBroker } from '../ghostFirstPartyPrivilege.js';
+
+const PACKAGE_SHA256 = 'a'.repeat(64);
+const PERSONAL = { membershipKind: 'personal' as const, orgId: null };
+const XD = { membershipKind: 'org' as const, orgId: 'org-xd' };
+
+function loader(namespace: string | null | undefined = undefined, pending = false, prefix?: 'xd') {
+ return loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false,
+ readMarketInstallation: () => ({
+ pluginId: 'plugin-helper', ghostId: 'helper', releaseId: 'release-1', version: '1.0.0',
+ scope: 'organization', source: 'market', installed: true, organizationId: 'org-xd',
+ sha256: PACKAGE_SHA256, updatedAt: '2026-09-30T00:00:00Z',
+ }),
+ readApprovedPackageSha256: () => PACKAGE_SHA256,
+ readInstallOrigin: () => 'manual', readInstallNamespace: () => namespace,
+ readLegacyFirstPartyEligible: () => true,
+ isPendingLegacyNamespace: () => pending,
+ lookupOrganizationPrefix: () => prefix ? { kind: 'known', pluginPrefix: prefix } : { kind: 'absent' },
+ });
+}
+
+describe('first-party install authorization and old organization tokens', () => {
+ it('authorizes a first official Cindy public broker install only from exact inspected server bytes', () => {
+ const pending = {
+ scope: 'public' as const, source: 'market' as const, installed: true,
+ organizationId: null, sha256: PACKAGE_SHA256,
+ };
+ for (const inspectedPackageSha256 of [PACKAGE_SHA256, 'b'.repeat(64)]) {
+ const loaded = loader().load('cindy-web-search', 'install', PERSONAL, {
+ marketRecord: bindPendingMarketRecordToInspectedPackage(pending, inspectedPackageSha256),
+ });
+ expect(authorizeGhostTokenBroker('cindy-web-search', loaded)).toBe(inspectedPackageSha256 === PACKAGE_SHA256);
+ }
+ });
+
+ it('uses a Host legacy override only for same-source root updates, never an implicit install-time reader', () => {
+ const marketRecord = bindPendingMarketRecordToInspectedPackage({
+ scope: 'public', source: 'market', installed: true, organizationId: null, sha256: PACKAGE_SHA256,
+ }, PACKAGE_SHA256);
+ for (const legacyFirstPartyEligible of [undefined, false, true]) {
+ const loaded = loader().load('filo-google', 'install', PERSONAL, {
+ marketRecord, ...(legacyFirstPartyEligible !== undefined ? { legacyFirstPartyEligible } : {}),
+ });
+ expect(authorizeGhostTokenBroker('filo-google', loaded)).toBe(legacyFirstPartyEligible === true);
+ }
+ const freshXd = loader().load('xd-helper', 'install', PERSONAL, { marketRecord, legacyFirstPartyEligible: false });
+ expect(authorizeGhostHostPrimitive('xd-helper', freshXd)).toBe(false);
+ });
+
+ it('allows approved XD namespace with an old token missing orgSlug, but rejects an explicit different slug', () => {
+ const loaded = loader('xd').load('_ns/xd/helper', 'runtime', XD);
+ expect(authorizeGhostHostPrimitive('helper', loaded)).toBe(true);
+ const foreignSlug = loader('xd').load('_ns/xd/helper', 'runtime', { ...XD, orgSlug: 'other' });
+ expect(authorizeGhostHostPrimitive('helper', foreignSlug)).toBe(false);
+ });
+
+ it('does not authorize a known root from a copied organization row with the same approved hash', () => {
+ for (const ghostId of ['helper', 'xd-helper', 'cindy-helper']) {
+ const loaded = loader(null, false, 'xd').load(ghostId, 'runtime', { ...XD, orgSlug: 'xd' });
+ expect(authorizeGhostTokenBroker(ghostId, loaded)).toBe(false);
+ expect(authorizeGhostHostPrimitive(ghostId, loaded)).toBe(false);
+ }
+ });
+
+ it('allows only a real old pending XD instance with a known fixed prefix when orgSlug is missing', () => {
+ expect(authorizeGhostHostPrimitive('helper', loader(undefined, true, 'xd').load('helper', 'runtime', XD))).toBe(true);
+ expect(authorizeGhostHostPrimitive('helper', loader(undefined, false, 'xd').load('helper', 'runtime', XD))).toBe(false);
+ expect(authorizeGhostHostPrimitive('helper', loader(null, true, 'xd').load('helper', 'runtime', XD))).toBe(false);
+ expect(authorizeGhostHostPrimitive('helper', loader(undefined, true).load('helper', 'runtime', XD))).toBe(false);
+ expect(authorizeGhostHostPrimitive('helper', loader(undefined, true, 'xd').load('helper', 'runtime', { ...XD, orgSlug: 'other' }))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyLegacy.manager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyLegacy.manager.test.ts
new file mode 100644
index 0000000000..daf3b2c661
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyLegacy.manager.test.ts
@@ -0,0 +1,153 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ghostInstallApprovalToken, validateGhostManifest } from '../../../shared/ghost.js';
+import { GhostManager } from '../GhostManager.js';
+import { createGhostInstallReceipt, GhostInstallReceiptStore } from '../ghostInstallReceipt.js';
+import { writeTestCindyPackage } from './cindyPackageFixture.js';
+
+const roots: string[] = [];
+const PACKAGE_SHA256 = 'a'.repeat(64);
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+async function fixture(official = false) {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-legacy-first-party-')));
+ roots.push(root);
+ const contentRoot = path.join(root, 'content');
+ const stateRoot = path.join(root, 'state');
+ const raw = {
+ schemaVersion: 2, id: 'filo-helper', name: 'Helper', version: '1.0.0',
+ kind: 'chip', entry: 'main.js', slots: [],
+ };
+ const parsed = validateGhostManifest(raw);
+ if (!parsed.ok) throw new Error(parsed.reason);
+ const store = new GhostInstallReceiptStore(() => stateRoot);
+ const plant = async (id: string, packageSha256: string | undefined = PACKAGE_SHA256) => {
+ const manifest = { ...parsed.manifest, id };
+ fs.mkdirSync(path.join(contentRoot, id), { recursive: true });
+ fs.writeFileSync(path.join(contentRoot, id, 'ghost.json'), JSON.stringify({ ...raw, id }));
+ fs.writeFileSync(path.join(contentRoot, id, 'main.js'), 'module.exports = {};');
+ const receipt = createGhostInstallReceipt({
+ manifest, localeResources: {}, enabled: true, skillContentSha256: {}, packageSha256,
+ trust: {
+ level: official ? 'cindy-official' : 'unverified',
+ publisherSigned: false, publisherVerified: false, reviewed: false,
+ },
+ });
+ await store.write(receipt);
+ return receipt;
+ };
+ const receipt = await plant('filo-helper');
+ const packageFile = () => writeTestCindyPackage(
+ path.join(root, 'update.cindy'), { ...raw, version: '2.0.0' },
+ { 'main.js': 'module.exports = { version: 2 };' },
+ );
+ return { root, contentRoot, stateRoot, store, receipt, plant, packageFile };
+}
+
+describe('Host legacy first-party receipt capture', () => {
+ it('reads the approved receipt only for the pinned instance revision', async () => {
+ const setup = await fixture();
+ const manager = new GhostManager({ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot });
+ expect(manager.readApprovedInstallReceipt('filo-helper', setup.receipt.revision)).toEqual(setup.receipt);
+ expect(manager.readApprovedInstallReceipt('filo-helper', 'stale-revision')).toBeNull();
+ expect(manager.readApprovedInstallReceipt('filo-missing')).toBeNull();
+ expect(manager.readApprovedInstallReceipt('../filo-helper')).toBeNull();
+ });
+
+ it('does not expose legacy evidence from a damaged receipt or pending transaction', async () => {
+ const setup = await fixture();
+ const manager = new GhostManager({ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot });
+ expect(manager.readApprovedInstallReceipt('filo-helper')).not.toBeNull();
+ await setup.store.writePendingMutation('filo-helper', {
+ kind: 'update', packageSha256: PACKAGE_SHA256,
+ backupDirName: '.cindy-updating-filo-helper-12345678',
+ });
+ expect(manager.readApprovedInstallReceipt('filo-helper')).toBeNull();
+ fs.rmSync(path.join(setup.stateRoot, '.pending-filo-helper.json'));
+ fs.writeFileSync(path.join(setup.stateRoot, 'filo-helper.json'), '{ damaged');
+ expect(manager.readApprovedInstallReceipt('filo-helper')).toBeNull();
+ });
+
+ it('captures once, survives pending removal and restart, and never qualifies a later missing-namespace receipt', async () => {
+ const setup = await fixture();
+ const capture = vi.fn(() => true);
+ const options = {
+ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot,
+ captureLegacyFirstPartyEligibility: capture,
+ };
+ const manager = new GhostManager(options);
+ manager.ensureNamespaceMigrationCensus();
+ expect(capture).toHaveBeenCalledExactlyOnceWith('filo-helper', PACKAGE_SHA256);
+ expect(manager.readLegacyFirstPartyEligible('filo-helper')).toBe(true);
+ expect(setup.store.readForRecovery('filo-helper')).toMatchObject({
+ state: 'approved', receipt: { legacyFirstPartyEligible: true, revision: setup.receipt.revision },
+ });
+ await expect(manager.commitPendingRootNamespace('filo-helper', 'market-public')).resolves.toEqual({ ok: true });
+ expect(manager.readLegacyFirstPartyEligible('filo-helper')).toBe(true);
+ await setup.plant('filo-later');
+ const restarted = new GhostManager(options);
+ restarted.ensureNamespaceMigrationCensus();
+ expect(capture).toHaveBeenCalledTimes(1);
+ expect(restarted.readLegacyFirstPartyEligible('filo-helper')).toBe(true);
+ expect(restarted.readLegacyFirstPartyEligible('filo-later')).toBe(false);
+ expect(restarted.isPendingLegacyNamespace('filo-later')).toBe(false);
+ });
+
+ it('captures retired officially approved plugins without a seed roster or market ledger', async () => {
+ const setup = await fixture(true);
+ const manager = new GhostManager({ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot });
+ manager.ensureNamespaceMigrationCensus();
+ expect(manager.readLegacyFirstPartyEligible('filo-helper')).toBe(true);
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'filo-helper')?.builtin === true).toBe(false);
+ });
+
+ it('does not retroactively qualify old receipts after an offline first census', async () => {
+ const setup = await fixture();
+ new GhostManager({ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot })
+ .ensureNamespaceMigrationCensus();
+ const capture = vi.fn(() => true);
+ const later = new GhostManager({
+ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot,
+ captureLegacyFirstPartyEligibility: capture,
+ });
+ later.ensureNamespaceMigrationCensus();
+ expect(capture).not.toHaveBeenCalled();
+ expect(later.readLegacyFirstPartyEligible('filo-helper')).toBe(false);
+ });
+
+ it.each([false, true])('preserves same-source qualification and clears archive replacement=%s', async (sourceChanged) => {
+ const setup = await fixture();
+ const manager = new GhostManager({
+ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot,
+ captureLegacyFirstPartyEligibility: () => true,
+ onArchiveSourceState: async () => {},
+ });
+ manager.ensureNamespaceMigrationCensus();
+ await manager.commitPendingRootNamespace('filo-helper', 'market-public');
+ const installed = manager.list().find((ghost) => ghost.manifest.id === 'filo-helper');
+ if (!installed) throw new Error('installed fixture unavailable');
+ const result = await manager.update(await setup.packageFile(), {
+ expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
+ namespace: null,
+ ...(sourceChanged ? { sourceStateArchiveId: '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__filo-helper' } : {}),
+ });
+ expect(result).not.toHaveProperty('rejection');
+ expect(manager.readLegacyFirstPartyEligible('filo-helper')).toBe(!sourceChanged);
+ });
+
+ it('does not capture damaged or hashless approval and does not read damaged flags', async () => {
+ const setup = await fixture(true);
+ const receiptPath = path.join(setup.stateRoot, 'filo-helper.json');
+ fs.writeFileSync(receiptPath, JSON.stringify({ ...setup.receipt, packageSha256: undefined }));
+ const manager = new GhostManager({ getRootDir: () => setup.contentRoot, getStateDir: () => setup.stateRoot });
+ manager.ensureNamespaceMigrationCensus();
+ expect(manager.readLegacyFirstPartyEligible('filo-helper')).toBe(false);
+ fs.writeFileSync(receiptPath, JSON.stringify({ ...setup.receipt, legacyFirstPartyEligible: 'true' }));
+ expect(manager.readLegacyFirstPartyEligible('filo-helper')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyNaming.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyNaming.test.ts
new file mode 100644
index 0000000000..3ce3532a4c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyNaming.test.ts
@@ -0,0 +1,291 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { isUserInstallReservedGhostId, validateGhostManifest } from '../../../shared/ghost.js';
+import { loadGhostFirstPartyFactsLoader } from '../ghostFirstPartyFacts.js';
+import {
+ captureLegacyFirstPartyEligibility,
+ authorizeGhostHostPrimitive,
+ resolveGhostFirstPartyPrivilege,
+ type GhostFirstPartyFacts,
+ type GhostFirstPartyMarketRecord,
+} from '../ghostFirstPartyPrivilege.js';
+import {
+ createGhostInstallReceipt,
+ GhostInstallReceiptStore,
+ legacyFirstPartyEligibilityAfterUpdate,
+} from '../ghostInstallReceipt.js';
+
+const PACKAGE_SHA256 = 'a'.repeat(64);
+const XD = { organizationId: 'org-xd', orgSlug: 'xd', pluginPrefix: 'xd' };
+const PUBLIC_RECORD: GhostFirstPartyMarketRecord = {
+ scope: 'public', organizationId: null, source: 'market', installed: true,
+ sha256: PACKAGE_SHA256, approvedPackageSha256: PACKAGE_SHA256,
+};
+
+function facts(overrides: Partial<GhostFirstPartyFacts> = {}): GhostFirstPartyFacts {
+ return {
+ ghostId: 'helper', namespace: null, builtin: false, marketRecord: null,
+ currentOrganization: null, installOrigin: 'manual', ...overrides,
+ };
+}
+
+const tempRoots: string[] = [];
+afterEach(() => {
+ for (const root of tempRoots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('first-party naming and approved source eligibility', () => {
+ it.each(['xd-helper', 'filo-helper', 'cindy-helper'])('does not grant new root %s by name or builtin roster', (ghostId) => {
+ for (const builtin of [false, true]) {
+ expect(resolveGhostFirstPartyPrivilege(facts({ ghostId, builtin, marketRecord: null }))).toMatchObject({
+ brokerEligible: false, hostPrimitiveEligible: false,
+ });
+ }
+ expect(isUserInstallReservedGhostId(ghostId)).toBe(ghostId === 'cindy-helper');
+ expect(resolveGhostFirstPartyPrivilege(facts({ ghostId, marketRecord: PUBLIC_RECORD })).hostPrimitiveEligible)
+ .toBe(ghostId === 'cindy-helper');
+ });
+
+ it.each(['helper', 'xd-helper', 'filo-helper'])('grants trusted XD organization %s without a naming or phase gate', (ghostId) => {
+ const trusted = facts({
+ ghostId, namespace: 'xd', currentOrganization: XD,
+ marketRecord: { ...PUBLIC_RECORD, scope: 'organization', organizationId: XD.organizationId },
+ });
+ expect(resolveGhostFirstPartyPrivilege(trusted)).toEqual({
+ brokerEligible: true, hostPrimitiveEligible: true, basis: 'market-organization-current',
+ });
+ for (const source of ['legacy-adopted', 'local-market', 'git-market'] as const) {
+ expect(resolveGhostFirstPartyPrivilege({ ...trusted, marketRecord: { ...trusted.marketRecord!, source } }).hostPrimitiveEligible).toBe(false);
+ }
+ expect(resolveGhostFirstPartyPrivilege({ ...trusted, marketRecord: null }).hostPrimitiveEligible).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({ ...trusted, namespace: null }).hostPrimitiveEligible).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({ ...trusted, currentOrganization: { ...XD, organizationId: 'other' } }).hostPrimitiveEligible).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({ ...trusted, marketRecord: { ...trusted.marketRecord!, approvedPackageSha256: 'b'.repeat(64) } }).hostPrimitiveEligible).toBe(false);
+ });
+
+ it.each(['helper', 'cindy-helper'])('binds official %s to exact approved identity and hash, not a prefix', (ghostId) => {
+ const trusted = facts({
+ ghostId, builtin: true, approvedPackageSha256: PACKAGE_SHA256,
+ trustedSource: { kind: 'builtin-official', ghostId, namespace: null, packageSha256: PACKAGE_SHA256 },
+ });
+ expect(resolveGhostFirstPartyPrivilege(trusted).hostPrimitiveEligible).toBe(true);
+ for (const changed of [
+ { ...trusted, ghostId: 'different' },
+ { ...trusted, namespace: 'xd' },
+ { ...trusted, approvedPackageSha256: null },
+ { ...trusted, approvedPackageSha256: 'b'.repeat(64) },
+ { ...trusted, trustedSource: { ...trusted.trustedSource!, packageSha256: 'invalid' }, approvedPackageSha256: 'invalid' },
+ ]) expect(resolveGhostFirstPartyPrivilege(changed).hostPrimitiveEligible).toBe(false);
+ const publicInstall = { ...trusted, builtin: false, marketRecord: PUBLIC_RECORD, trustedSource: null };
+ expect(resolveGhostFirstPartyPrivilege(publicInstall).hostPrimitiveEligible).toBe(ghostId === 'cindy-helper');
+ expect(resolveGhostFirstPartyPrivilege({ ...publicInstall, marketRecord: null }).hostPrimitiveEligible).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({ ...publicInstall, marketRecord: { ...PUBLIC_RECORD, sha256: 'b'.repeat(64) } }).hostPrimitiveEligible).toBe(false);
+ });
+
+ it('keeps an exact Cindy public resource usable without builtin facts or an organization prefix cache', () => {
+ const loader = loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false,
+ readMarketInstallation: () => ({
+ ...PUBLIC_RECORD, pluginId: 'plugin-cindy', ghostId: 'cindy-helper',
+ releaseId: 'release-1', version: '1.0.0', updatedAt: '2026-09-30T00:00:00Z',
+ }),
+ readApprovedPackageSha256: () => PACKAGE_SHA256,
+ readInstallOrigin: () => 'manual',
+ readInstallNamespace: () => null,
+ lookupOrganizationPrefix: () => { throw new Error('prefix lookup must not be required'); },
+ });
+ const loaded = loader.load('cindy-helper', 'runtime', { membershipKind: 'org', orgId: XD.organizationId, orgSlug: 'xd' });
+ expect(loaded.kind).toBe('ready');
+ if (loaded.kind !== 'ready') throw new Error('public resource facts unavailable');
+ expect(loaded.facts.trustedSource).toBeUndefined();
+ expect(resolveGhostFirstPartyPrivilege(loaded.facts).basis).toBe('market-public');
+ });
+
+ it('allows an exact official Cindy web-search market update before alias denial but never public XD Mivo', () => {
+ const official = facts({ ghostId: 'cindy-web-search', marketRecord: PUBLIC_RECORD });
+ expect(resolveGhostFirstPartyPrivilege(official)).toEqual({
+ brokerEligible: true, hostPrimitiveEligible: true, basis: 'market-public',
+ });
+ for (const changed of [
+ { ...official, namespace: 'xd' },
+ { ...official, marketRecord: { ...PUBLIC_RECORD, approvedPackageSha256: 'b'.repeat(64) } },
+ { ...official, marketRecord: { ...PUBLIC_RECORD, source: 'local-market' as const } },
+ { ...official, ghostId: 'xd-mivo' },
+ ]) expect(resolveGhostFirstPartyPrivilege(changed).basis).toBe('denied-alias');
+ });
+
+ it('captures only a real census installation with approved trusted public package evidence', () => {
+ const candidate = {
+ legacyExistingInstall: true, approved: true, ghostId: 'filo-google', namespace: null,
+ approvedPackageSha256: PACKAGE_SHA256, marketRecord: { ...PUBLIC_RECORD, ghostId: 'filo-google' },
+ };
+ expect(captureLegacyFirstPartyEligibility(candidate)).toBe(true);
+ for (const changed of [
+ { ...candidate, legacyExistingInstall: false },
+ { ...candidate, approved: false },
+ { ...candidate, namespace: 'xd' },
+ { ...candidate, approvedPackageSha256: 'b'.repeat(64) },
+ { ...candidate, ghostId: 'helper' },
+ { ...candidate, marketRecord: null },
+ { ...candidate, marketRecord: { ...candidate.marketRecord, ghostId: 'other' } },
+ { ...candidate, marketRecord: { ...candidate.marketRecord, namespace: 'xd' } },
+ { ...candidate, marketRecord: { ...candidate.marketRecord, installed: false } },
+ { ...candidate, marketRecord: { ...candidate.marketRecord, approvedPackageSha256: null } },
+ { ...candidate, marketRecord: { ...candidate.marketRecord, approvedPackageSha256: 'b'.repeat(64) } },
+ { ...candidate, marketRecord: { ...candidate.marketRecord, source: 'legacy-adopted' as const } },
+ { ...candidate, marketRecord: { ...candidate.marketRecord, scope: 'organization' as const, organizationId: XD.organizationId } },
+ ]) expect(captureLegacyFirstPartyEligibility(changed)).toBe(false);
+ });
+
+ it('does not let a legacy flag bypass alias, namespace, organization or changed-source gates', () => {
+ for (const ghostId of ['xd-mivo', 'cindy-web-search']) {
+ expect(resolveGhostFirstPartyPrivilege(facts({ ghostId, legacyFirstPartyEligible: true })).basis).toBe('denied-alias');
+ }
+ const legacy = facts({ ghostId: 'xd-helper', legacyFirstPartyEligible: true });
+ expect(resolveGhostFirstPartyPrivilege(legacy).hostPrimitiveEligible).toBe(true);
+ for (const changed of [
+ { ...legacy, namespace: 'xd' },
+ { ...legacy, installOrigin: 'agent-forge' as const },
+ { ...legacy, marketRecord: { ...PUBLIC_RECORD, installed: false } },
+ { ...legacy, marketRecord: { ...PUBLIC_RECORD, source: 'local-market' as const } },
+ { ...legacy, marketRecord: { ...PUBLIC_RECORD, scope: 'organization' as const, organizationId: 'foreign' }, currentOrganization: XD },
+ ]) expect(resolveGhostFirstPartyPrivilege(changed).hostPrimitiveEligible).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({
+ ...legacy, namespace: 'xd', currentOrganization: XD,
+ marketRecord: { ...PUBLIC_RECORD, scope: 'organization', organizationId: 'foreign' },
+ }).brokerEligible).toBe(false);
+ });
+
+ it.each(['absent', 'unavailable', 'throws'] as const)('authorizes natural XD names with %s prefix cache and keeps legacy Forge closed', (prefixState) => {
+ let prefixReads = 0;
+ const loader = loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false,
+ readMarketInstallation: () => ({
+ ...PUBLIC_RECORD, scope: 'organization', organizationId: XD.organizationId,
+ pluginId: 'plugin-helper', ghostId: 'helper', releaseId: 'release-1',
+ version: '1.0.0', updatedAt: '2026-09-30T00:00:00Z',
+ }),
+ readApprovedPackageSha256: () => PACKAGE_SHA256,
+ readInstallOrigin: () => 'manual',
+ lookupOrganizationPrefix: () => {
+ prefixReads += 1;
+ if (prefixState === 'throws') throw new Error('prefix cache unavailable');
+ return { kind: prefixState };
+ },
+ });
+ const identity = { membershipKind: 'org' as const, orgId: XD.organizationId, orgSlug: 'xd' };
+ const loaded = loader.load('_ns/xd/helper', 'runtime', identity);
+ expect(loaded.kind).toBe('ready');
+ if (loaded.kind === 'ready') {
+ expect(loaded.facts.currentOrganization).toEqual({ organizationId: XD.organizationId, orgSlug: 'xd' });
+ expect(resolveGhostFirstPartyPrivilege(loaded.facts).hostPrimitiveEligible).toBe(true);
+ }
+ expect(prefixReads).toBe(0);
+ const legacyForge = loader.load('xd-helper', 'runtime', identity, { installOrigin: 'agent-forge' });
+ expect(legacyForge.kind).toBe('unavailable');
+ expect(prefixReads).toBe(1);
+ });
+
+ it('preserves offline pending XD enterprise privileges only for the censused unbound instance', () => {
+ const createLoader = (recordedNamespace: string | null | undefined, pending: boolean) => loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false,
+ readMarketInstallation: () => ({
+ ...PUBLIC_RECORD, scope: 'organization', organizationId: XD.organizationId,
+ pluginId: 'plugin-old', ghostId: 'xd-helper', releaseId: 'release-1',
+ version: '1.0.0', updatedAt: '2026-09-30T00:00:00Z',
+ }),
+ readApprovedPackageSha256: () => PACKAGE_SHA256,
+ readInstallOrigin: () => 'manual',
+ readInstallNamespace: () => recordedNamespace,
+ isPendingLegacyNamespace: () => pending,
+ isPendingLegacyForge: () => pending,
+ lookupOrganizationPrefix: () => { throw new Error('offline prefix cache'); },
+ });
+ const identity = { membershipKind: 'org' as const, orgId: XD.organizationId, orgSlug: 'xd' };
+ const oldPending = createLoader(undefined, true).load('xd-helper', 'runtime', identity);
+ expect(oldPending.kind).toBe('ready');
+ if (oldPending.kind !== 'ready') throw new Error('pending facts unavailable');
+ expect(oldPending.facts.legacyPendingNamespace).toBe(true);
+ expect(oldPending.facts.installOrigin).toBe('manual');
+ expect(resolveGhostFirstPartyPrivilege(oldPending.facts).hostPrimitiveEligible).toBe(true);
+ expect(resolveGhostFirstPartyPrivilege({ ...oldPending.facts, legacyPendingNamespace: false }).hostPrimitiveEligible).toBe(false);
+ for (const denied of [
+ createLoader(null, true).load('xd-helper', 'runtime', identity),
+ createLoader(undefined, false).load('xd-helper', 'runtime', identity),
+ createLoader(undefined, true).load('xd-helper', 'install', identity),
+ createLoader(undefined, true).load('xd-helper', 'runtime', { ...identity, orgId: 'foreign' }),
+ createLoader(undefined, true).load('xd-helper', 'runtime', identity, { installOrigin: 'agent-forge' }),
+ ]) expect(authorizeGhostHostPrimitive('xd-helper', denied)).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({
+ ...oldPending.facts, marketRecord: { ...oldPending.facts.marketRecord!, approvedPackageSha256: null },
+ }).hostPrimitiveEligible).toBe(false);
+ const committed = createLoader('xd', true).load('xd-helper', 'runtime', identity);
+ if (committed.kind !== 'ready') throw new Error('committed facts unavailable');
+ expect(committed.facts.legacyPendingNamespace).toBeUndefined();
+ expect(resolveGhostFirstPartyPrivilege(committed.facts).hostPrimitiveEligible).toBe(true);
+ });
+
+ it('loads captured receipt eligibility offline after census pending entries disappear, but never for a new install', () => {
+ const loader = loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false,
+ readMarketInstallation: () => { throw new Error('offline ledger'); },
+ readApprovedPackageSha256: () => null,
+ readInstallOrigin: () => 'manual',
+ lookupOrganizationPrefix: () => { throw new Error('offline organization cache'); },
+ readLegacyFirstPartyEligible: () => true,
+ });
+ const identity = { membershipKind: 'org' as const, orgId: XD.organizationId, orgSlug: 'xd' };
+ const runtime = loader.load('filo-google', 'runtime', identity);
+ expect(runtime.kind).toBe('ready');
+ if (runtime.kind === 'ready') expect(resolveGhostFirstPartyPrivilege(runtime.facts)).toEqual({
+ brokerEligible: true, hostPrimitiveEligible: true, basis: 'legacy-existing-install',
+ });
+ expect(loader.load('filo-google', 'install', identity).kind).toBe('unavailable');
+ expect(legacyFirstPartyEligibilityAfterUpdate({ legacyFirstPartyEligible: true }, false)).toBe(true);
+ expect(legacyFirstPartyEligibilityAfterUpdate({ legacyFirstPartyEligible: true }, true)).toBe(false);
+ expect(legacyFirstPartyEligibilityAfterUpdate({}, false)).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege(facts({ ghostId: 'filo-google', legacyFirstPartyEligible: false })).hostPrimitiveEligible).toBe(false);
+ });
+
+ it('persists the Host legacy qualification and rejects damaged receipt fields', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-first-party-naming-'));
+ tempRoots.push(root);
+ const store = new GhostInstallReceiptStore(() => root);
+ const parsed = validateGhostManifest({
+ schemaVersion: 2, id: 'filo-google', name: 'Google', version: '1.0.0', kind: 'chip', entry: 'main.js', slots: [],
+ });
+ if (!parsed.ok) throw new Error(parsed.reason);
+ const input = {
+ manifest: parsed.manifest, localeResources: {}, enabled: true, skillContentSha256: {},
+ trust: { level: 'unverified' as const, publisherSigned: false, publisherVerified: false, reviewed: false },
+ };
+ expect(createGhostInstallReceipt(input).legacyFirstPartyEligible).toBeUndefined();
+ const receipt = createGhostInstallReceipt({ ...input, legacyFirstPartyEligible: true });
+ await store.write(receipt);
+ expect(store.readForRecovery('filo-google')).toMatchObject({ state: 'approved', receipt: { legacyFirstPartyEligible: true } });
+ const loader = loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false, readMarketInstallation: () => null,
+ readApprovedPackageSha256: () => null, readInstallOrigin: () => 'manual',
+ lookupOrganizationPrefix: () => ({ kind: 'absent' }),
+ readLegacyFirstPartyEligible: (relId) => {
+ const read = store.readForRecovery(relId);
+ return read.state === 'approved' && read.receipt.legacyFirstPartyEligible === true;
+ },
+ });
+ const identity = { membershipKind: 'personal' as const, orgId: null };
+ const approved = loader.load('filo-google', 'runtime', identity);
+ if (approved.kind !== 'ready') throw new Error('approved facts unavailable');
+ expect(resolveGhostFirstPartyPrivilege(approved.facts).hostPrimitiveEligible).toBe(true);
+ for (const legacyFirstPartyEligible of ['true', 1, {}, null]) {
+ fs.writeFileSync(path.join(root, 'filo-google.json'), JSON.stringify({ ...receipt, legacyFirstPartyEligible }));
+ expect(store.readForRecovery('filo-google').state).not.toBe('approved');
+ const damaged = loader.load('filo-google', 'runtime', identity);
+ if (damaged.kind !== 'ready') throw new Error('damaged facts unavailable');
+ expect(resolveGhostFirstPartyPrivilege(damaged.facts).hostPrimitiveEligible).toBe(false);
+ }
+ fs.writeFileSync(path.join(root, 'filo-google.json'), JSON.stringify({ ...receipt, revision: 'damaged' }));
+ expect(store.readForRecovery('filo-google').state).not.toBe('approved');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts
index 7f0d3157c9..a6a95f3c9f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts
@@ -2,13 +2,15 @@ import { describe, expect, it } from 'vitest';
import {
FIRST_PARTY_ALIAS_GHOST_IDS,
+ isTrustedMivoSecretAlias,
+ authorizeGhostHostPrimitive,
authorizeGhostTokenBroker,
resolveGhostFirstPartyPrivilege,
type GhostFirstPartyFacts,
type GhostFirstPartyMarketRecord,
} from '../ghostFirstPartyPrivilege.js';
-const CURRENT_ORG = { organizationId: 'org-acme', pluginPrefix: 'acme' as const };
+const CURRENT_ORG = { organizationId: 'org-acme', pluginPrefix: 'acme' as const, orgSlug: 'acme' as const };
const BUNDLED_NON_OFFICIAL_IDS = [
'163-mail',
@@ -26,11 +28,26 @@ const BUNDLED_NON_OFFICIAL_IDS = [
] as const;
function facts(partial: Partial<GhostFirstPartyFacts> & Pick<GhostFirstPartyFacts, 'ghostId'>): GhostFirstPartyFacts {
+ const namespace = partial.namespace !== undefined ? partial.namespace :
+ !partial.builtin && partial.marketRecord?.scope === 'organization'
+ ? partial.currentOrganization?.orgSlug ?? 'acme' : null;
return {
builtin: false,
+ namespace,
marketRecord: null,
currentOrganization: null,
installOrigin: 'manual',
+ ...(partial.builtin && ['xd-feishu', 'xd-atlassian', 'xd-mivo', 'cindy-web-search', 'cindy-art'].includes(partial.ghostId)
+ ? {
+ trustedSource: {
+ kind: 'builtin-official' as const,
+ ghostId: partial.ghostId,
+ namespace,
+ packageSha256: 'a'.repeat(64),
+ },
+ approvedPackageSha256: 'a'.repeat(64),
+ }
+ : {}),
...partial,
};
}
@@ -49,10 +66,50 @@ function market(
}
describe('resolveGhostFirstPartyPrivilege', () => {
+ it('does not treat pluginPrefix as the organization namespace', () => {
+ const currentOrganization = { organizationId: 'org-1', orgSlug: 'org-abcdefgh', pluginPrefix: 'acme' };
+ const marketRecord = market({ scope: 'organization', organizationId: 'org-1' });
+ expect(resolveGhostFirstPartyPrivilege(facts({
+ ghostId: 'helper', namespace: 'org-abcdefgh', currentOrganization, marketRecord,
+ })).brokerEligible).toBe(true);
+ expect(resolveGhostFirstPartyPrivilege(facts({
+ ghostId: 'helper', namespace: 'acme', currentOrganization, marketRecord,
+ })).brokerEligible).toBe(false);
+ expect(authorizeGhostTokenBroker('helper', { kind: 'ready', facts: facts({
+ ghostId: 'helper', namespace: 'org-abcdefgh', currentOrganization, marketRecord,
+ }) })).toBe(true);
+ });
+
+ it.each(['xd', null])('retains the trusted Mivo alias with an old token and namespace %s', (namespace) => {
+ const trusted = facts({ ghostId: 'xd-mivo', namespace,
+ currentOrganization: { organizationId: 'org-xd', orgSlug: null, pluginPrefix: 'xd' },
+ marketRecord: market({ scope: 'organization', organizationId: 'org-xd' }),
+ });
+ expect(isTrustedMivoSecretAlias(trusted, namespace === null)).toBe(true);
+ expect(isTrustedMivoSecretAlias({ ...trusted,
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'other', pluginPrefix: 'xd' },
+ }, namespace === null)).toBe(true);
+ expect(isTrustedMivoSecretAlias({ ...trusted,
+ marketRecord: market({ scope: 'organization', organizationId: 'org-other' }),
+ }, namespace === null)).toBe(false);
+ });
+
+ it('binds the Mivo historical key to a real XD installation, not the plugin name', () => {
+ const xdOrganization = { organizationId: 'org-xd', orgSlug: 'xd', pluginPrefix: 'xd' };
+ const trusted = facts({
+ ghostId: 'xd-mivo', namespace: 'xd', currentOrganization: xdOrganization,
+ marketRecord: market({ scope: 'organization', organizationId: 'org-xd' }),
+ });
+ expect(isTrustedMivoSecretAlias(trusted, false)).toBe(true);
+ expect(isTrustedMivoSecretAlias({ ...trusted, namespace: null }, true)).toBe(true);
+ expect(isTrustedMivoSecretAlias({ ...trusted, namespace: null }, false)).toBe(false);
+ expect(isTrustedMivoSecretAlias({ ...trusted, installOrigin: 'agent-forge', marketRecord: null }, true)).toBe(false);
+ expect(isTrustedMivoSecretAlias({ ...trusted, currentOrganization: CURRENT_ORG }, false)).toBe(false);
+ expect(isTrustedMivoSecretAlias({ ...trusted, marketRecord: market({ scope: 'organization', organizationId: 'org-xd', source: 'legacy-adopted' }) }, false)).toBe(false);
+ expect(isTrustedMivoSecretAlias({ ...trusted, marketRecord: market({ scope: 'organization', organizationId: 'org-xd', approvedPackageSha256: null }) }, false)).toBe(false);
+ });
// 纯函数分支测试:用 xd-feishu / xd-atlassian 作为代表性官方前缀 id,验证
// builtin + 官方前缀会同时得到 Broker 与宿主原语;这不表示它们随发行包分发。
- // 静态官方前缀的存量兼容由后面的 authorizeGhostTokenBroker(...,
- // { kind: 'unavailable' }) 对照用例锁定。
// `currentOrganization: null` 与 `marketRecord: null` 在这里**显式写出**,不吃
// `facts()` 的默认值:否则将来有人为省事把默认改成"有组织",这条依然会通过
// (优先级 1 本就不看 org),但"个人身份"这个场景就悄悄没人守了。
@@ -137,7 +194,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {
).toMatchObject({ basis: 'builtin-official', brokerEligible: true });
});
- it('trusts server-market public installs only when the id hits the static table', () => {
+ it('trusts server-market public installs only with approved official resource evidence', () => {
expect(
resolveGhostFirstPartyPrivilege(
facts({
@@ -218,6 +275,46 @@ describe('resolveGhostFirstPartyPrivilege', () => {
hostPrimitiveEligible: false,
basis: 'market-organization-current',
});
+ expect(
+ resolveGhostFirstPartyPrivilege(
+ facts({
+ ghostId: 'helper',
+ marketRecord: market({ scope: 'organization', organizationId: 'org-acme' }),
+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: null, orgSlug: 'acme' },
+ }),
+ ),
+ ).toEqual({
+ brokerEligible: true,
+ hostPrimitiveEligible: false,
+ basis: 'market-organization-current',
+ });
+ expect(
+ resolveGhostFirstPartyPrivilege(
+ facts({
+ ghostId: 'xd-feishu',
+ namespace: 'xd',
+ marketRecord: market({ scope: 'organization', organizationId: 'org-acme' }),
+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'xd', orgSlug: 'xd' },
+ }),
+ ),
+ ).toEqual({
+ brokerEligible: true,
+ hostPrimitiveEligible: true,
+ basis: 'market-organization-current',
+ });
+ });
+
+ it('denies organization broker when the namespace is not the current org slug', () => {
+ expect(resolveGhostFirstPartyPrivilege(facts({
+ ghostId: 'helper',
+ namespace: 'other',
+ marketRecord: market({ scope: 'organization', organizationId: 'org-acme' }),
+ currentOrganization: CURRENT_ORG,
+ }))).toEqual({
+ brokerEligible: false,
+ hostPrimitiveEligible: false,
+ basis: 'denied-foreign-org',
+ });
});
it('denies same-manifest organization packages when Release and approved package bytes differ', () => {
@@ -262,19 +359,20 @@ describe('resolveGhostFirstPartyPrivilege', () => {
});
});
- it('denies an official-looking org plugin whose prefix does not belong to the current org', () => {
+ it('does not let an official-looking name veto a trusted current-org market plugin', () => {
expect(
resolveGhostFirstPartyPrivilege(
facts({
ghostId: 'xd-evil',
+ namespace: 'acme',
marketRecord: market({ scope: 'organization', organizationId: 'org-acme' }),
currentOrganization: CURRENT_ORG,
}),
),
).toEqual({
- brokerEligible: false,
+ brokerEligible: true,
hostPrimitiveEligible: false,
- basis: 'denied-unknown-origin',
+ basis: 'market-organization-current',
});
});
@@ -320,13 +418,14 @@ describe('resolveGhostFirstPartyPrivilege', () => {
facts({
ghostId: 'acme-feishu',
currentOrganization: CURRENT_ORG,
+ namespace: 'acme',
installOrigin: 'agent-forge',
}),
),
).toEqual({
brokerEligible: true,
hostPrimitiveEligible: false,
- basis: 'forge-current-org-prefix',
+ basis: 'forge-current-org',
});
expect(
resolveGhostFirstPartyPrivilege(
@@ -338,6 +437,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {
source: 'local-market',
}),
currentOrganization: CURRENT_ORG,
+ namespace: 'acme',
installOrigin: 'agent-forge',
}),
).brokerEligible,
@@ -347,10 +447,25 @@ describe('resolveGhostFirstPartyPrivilege', () => {
facts({
ghostId: 'other-feishu',
currentOrganization: CURRENT_ORG,
+ namespace: 'acme',
installOrigin: 'agent-forge',
}),
).brokerEligible,
- ).toBe(false);
+ ).toBe(true);
+ expect(
+ resolveGhostFirstPartyPrivilege(
+ facts({
+ ghostId: 'helper',
+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: null, orgSlug: 'acme' },
+ namespace: 'acme',
+ installOrigin: 'agent-forge',
+ }),
+ ),
+ ).toEqual({
+ brokerEligible: true,
+ hostPrimitiveEligible: false,
+ basis: 'forge-current-org',
+ });
});
it('lets explicit Forge self-test win over every stale or foreign market-row shape', () => {
@@ -366,13 +481,14 @@ describe('resolveGhostFirstPartyPrivilege', () => {
ghostId: 'acme-feishu',
marketRecord,
currentOrganization: CURRENT_ORG,
- installOrigin: 'agent-forge',
+ namespace: 'acme',
+ installOrigin: 'agent-forge',
}),
),
).toEqual({
brokerEligible: true,
hostPrimitiveEligible: false,
- basis: 'forge-current-org-prefix',
+ basis: 'forge-current-org',
});
}
});
@@ -402,10 +518,13 @@ describe('resolveGhostFirstPartyPrivilege', () => {
// 手动本地包不能借一个 installed=false 的市场行取得资格。
});
- it('keeps official-prefix broker even when facts are unavailable, and asks the resolver otherwise', () => {
+ it('fails closed when facts are unavailable, even for official-looking ids', () => {
expect(
authorizeGhostTokenBroker('xd-feishu', { kind: 'unavailable' }),
- ).toBe(true);
+ ).toBe(false);
+ expect(
+ authorizeGhostHostPrimitive('xd-feishu', { kind: 'unavailable' }),
+ ).toBe(false);
expect(
authorizeGhostTokenBroker('acme-feishu', { kind: 'unavailable' }),
).toBe(false);
@@ -423,7 +542,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {
).toBe(false);
});
- it('uses pending org-market facts only for non-official ids; official prefix never consults them', () => {
+ it('grants organization-market broker from trusted facts, not from an official-looking name', () => {
const pendingOrgMarket = facts({
ghostId: 'acme-feishu',
marketRecord: market({ scope: 'organization', organizationId: 'org-acme' }),
@@ -442,17 +561,11 @@ describe('resolveGhostFirstPartyPrivilege', () => {
currentOrganization: null,
}),
}),
- ).toBe(true);
- expect(authorizeGhostTokenBroker('cindy-art', { kind: 'unavailable' })).toBe(true);
+ ).toBe(false);
+ expect(authorizeGhostTokenBroker('cindy-art', { kind: 'unavailable' })).toBe(false);
+ expect(authorizeGhostHostPrimitive('cindy-art', { kind: 'unavailable' })).toBe(false);
});
- // `legacy-adopted` 是市场列表成功后为「早于市场就已装在本机的官方前缀插件」合成的
- // 来源(`plugin-market/service.ts::adoptLegacyInstallations`)。判据对它一律 deny:
- // 它既不是 `source: 'market'`(所以进不了 public 那支),也不是 git/local market。
- //
- // `legacy-adopted` 不是静态官方资格或组织资格的替代来源:即使 id 命中静态官方前缀,
- // 或命中当前组织前缀,也必须 fail-closed。若要改变这条来源边界必须显式决策,
- // 不能把它当漏网 bug 顺手放宽。
it('denies legacy-adopted rows for static official and matching organization ids', () => {
for (const scope of ['public', 'organization'] as const) {
expect(
@@ -503,6 +616,38 @@ describe('resolveGhostFirstPartyPrivilege', () => {
});
});
+ it('denies Forge broker when the install namespace is not the current organization', () => {
+ expect(
+ resolveGhostFirstPartyPrivilege(
+ facts({
+ ghostId: 'helper',
+ namespace: 'acme',
+ currentOrganization: { organizationId: 'org-b', pluginPrefix: 'beta', orgSlug: 'beta' },
+ installOrigin: 'agent-forge',
+ }),
+ ),
+ ).toEqual({
+ brokerEligible: false,
+ hostPrimitiveEligible: false,
+ basis: 'denied-foreign-org',
+ });
+ });
+
+ it('preserves only a verified pending pre-namespace Forge for its original organization', () => {
+ const pending = facts({
+ ghostId: 'acme-helper',
+ currentOrganization: CURRENT_ORG,
+ installOrigin: 'agent-forge',
+ legacyPendingForge: true,
+ });
+ expect(resolveGhostFirstPartyPrivilege(pending).brokerEligible).toBe(true);
+ expect(resolveGhostFirstPartyPrivilege({ ...pending, legacyPendingForge: false }).brokerEligible).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({ ...pending, ghostId: 'helper' }).brokerEligible).toBe(false);
+ expect(resolveGhostFirstPartyPrivilege({ ...pending, currentOrganization: {
+ organizationId: 'org-b', pluginPrefix: 'beta', orgSlug: 'beta',
+ } }).brokerEligible).toBe(false);
+ });
+
it('fail-closes unknown origin, missing prefix, and unmatched prefix', () => {
expect(resolveGhostFirstPartyPrivilege(facts({ ghostId: 'mystery' }))).toEqual({
brokerEligible: false,
@@ -513,7 +658,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {
resolveGhostFirstPartyPrivilege(
facts({
ghostId: 'acme-feishu',
- currentOrganization: { organizationId: 'org-acme', pluginPrefix: null },
+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: null, orgSlug: 'acme' },
}),
),
).toEqual({
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
index 6842e0cb7e..df3c30c0ef 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
@@ -11,9 +11,18 @@ import {
effectiveInstallOrigin,
type GhostInstallReceipt,
GhostInstallReceiptStore,
+ isValidGhostSourceStateArchiveId,
} from '../ghostInstallReceipt';
describe('GhostInstallReceiptStore cleanup', () => {
+ it('accepts only a canonical random archive namespace destination', () => {
+ expect(isValidGhostSourceStateArchiveId('_ns__cindy-archive-00000000-0000-4000-8000-000000000002__hello')).toBe(true);
+ for (const value of ['hello', '../hello', '_ns__acme__hello',
+ 'cindy-source-00000000-0000-4000-8000-000000000002',
+ '_ns__cindy-archive-not-random__hello']) {
+ expect(isValidGhostSourceStateArchiveId(value)).toBe(false);
+ }
+ });
let workDir: string;
let stateRoot: string;
let store: GhostInstallReceiptStore;
@@ -33,6 +42,32 @@ describe('GhostInstallReceiptStore cleanup', () => {
await fs.promises.rm(workDir, { recursive: true, force: true });
});
+ it('lists legacy, root and organization journals together', async () => {
+ const ids = ['hello', '_ns/_root/hello', '_ns/acme/hello'];
+ for (const id of ids) await store.writePendingMutation(id, { kind: 'uninstall' });
+ expect(store.listPendingMutationIdsSync()).toEqual({ state: 'ok', ids: expect.arrayContaining(ids), blocked: false });
+ });
+
+ it.each(['_ns/_root', '_ns/acme'])('blocks cleanup for malformed journals under %s', async (parent) => {
+ await store.writePendingMutation(parent + '/hello', { kind: 'uninstall' });
+ await fs.promises.writeFile(path.join(stateRoot, parent, '.pending-BAD!.json'), '{}');
+ expect(store.listPendingMutationIdsSync()).toEqual({
+ state: 'ok', ids: [parent + '/hello'], blocked: true,
+ });
+ });
+
+ it.each(['_ns/_root', '_ns/acme'])('does not ignore journals when %s disappears during scanning', async (parent) => {
+ await store.writePendingMutation(parent + '/hello', { kind: 'uninstall' });
+ const readdir = fs.readdirSync;
+ vi.spyOn(fs, 'readdirSync').mockImplementation((...args) => {
+ if (String(args[0]) === path.join(stateRoot, parent)) {
+ throw Object.assign(new Error('journal parent disappeared'), { code: 'ENOENT' });
+ }
+ return readdir(...args);
+ });
+ expect(store.listPendingMutationIdsSync().state).toBe('unreadable');
+ });
+
function createSetupReceipt(): GhostInstallReceipt {
const parsed = validateGhostManifest({
schemaVersion: 2,
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
new file mode 100644
index 0000000000..02beb6fcba
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { GhostCardActionDispatcher } from '../cardActionDispatch.js';
+import { GhostPreviewGate } from '../previewGate.js';
+import { ghostInstallApprovalToken, ghostWebviewEntryPaths, type InstalledGhost } from '../../../shared/ghost.js';
+import { findInstalledGhostByInstanceId, installedGhostLogicalIdentity, installedGhostPhysicalKeys, installedGhostStoragePart,
+ parsePluginStoragePart, pluginStoragePart, resolveInstalledGhost } from '../../../shared/pluginIdentity.js';
+import { ownerScopedGhostPartitionForInstalledGhost, resolveGhostWebviewPartitionClaim } from '../ghostWebviewPartition.js';
+
+const load = createGhostProductionCallbacks<{
+ resolveGhostWebviewAttach: (claim: string, src: string) => { ghost: InstalledGhost } | null;
+ getGhostCardActionDispatcher: () => GhostCardActionDispatcher;
+ resolveMobilePluginMedia: (id: string, url: string, current: () => boolean) => Promise<unknown>;
+ setGhostEnabledForUser: (id: string, enabled: boolean, expectedInstalledApproval?: string) => Promise<{ ok: true }>;
+}>({ functions: ['findGhostForInstanceId', 'findGhostForPhysicalStoragePart', 'resolveGhostWebviewAttach',
+ 'getGhostCardActionDispatcher', 'resolveMobilePluginMedia', 'setGhostEnabledForUser'],
+ initialize: 'let cardActionDispatcherSingleton = null;' });
+
+function harness() {
+ const root: InstalledGhost = { manifest: { schemaVersion: 3, id: 'helper', name: 'Root', version: '1.0.0',
+ kind: 'chip', entry: 'main.js', panel: { html: 'panel.html' }, settingsHtml: 'settings.html', card: {} },
+ namespace: null, dir: '/ghosts/_ns/_root/helper', enabled: true,
+ approval: { state: 'approved', revision: 'root' } };
+ const organization: InstalledGhost = { ...root, namespace: 'acme', dir: '/ghosts/helper',
+ manifest: { ...root.manifest, name: 'Organization' }, approval: { state: 'approved', revision: 'org' } };
+ const ghosts = [organization, root];
+ let storedId = 'helper';
+ const send = vi.fn(() => true);
+ const setEnabled = vi.fn(async () => ({}));
+ const stop = vi.fn();
+ const ghostCanRead = vi.fn(async () => true);
+ const preview = new GhostPreviewGate({ ghostCanRead,
+ getBlobInfo: async () => ({ mimeType: 'image/png', ext: '.png' }),
+ blobUrl: (hash, ext) => 'cindy-media://blobs/' + hash + ext });
+ const api = load({ availableGhosts: () => ghosts, findInstalledGhostByInstanceId, resolveInstalledGhost,
+ installedGhostPhysicalKeys,
+ requireGhostAvailableForActiveSession: vi.fn(), getGhostManager: () => ({ setEnabled }),
+ beginGhostMutation: () => vi.fn(), captureGhostMutationOwner: vi.fn(),
+ getGhostNodeRuntimeBroker: () => ({ stop }), getGhostSubscriptionGateway: () => ({ dropGhost: vi.fn() }),
+ getGhostErrandSlot: () => ({ clearGhost: vi.fn() }),
+ getGhostLibrarySlot: () => ({ disposeGhost: vi.fn() }),
+ suspendGhostUnreadProjection: vi.fn(), refreshMivoLibraryExtraDirGrant: async () => {},
+ broadcastGhostsChanged: vi.fn(),
+ throwIpcError: (code: string) => { throw new Error(code); },
+ installedGhostLogicalIdentity, installedGhostStoragePart, pluginStoragePart, parsePluginStoragePart,
+ resolveGhostWebviewPartitionClaim, ownerScopedGhostPartitionForInstalledGhost, ghostWebviewEntryPaths,
+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: 'owner', generation: 1 }),
+ GHOST_SCHEME: 'cindy-ghost', ensureGhostProtocolRegistered: vi.fn(), GhostCardActionDispatcher,
+ getGhostCardService: () => ({ callInfoOf: () => null, reopenForAction: vi.fn() }),
+ getGhostCard: async () => ({ ghostId: storedId, sessionId: 'old-user-task' }),
+ getGhostRuntime: () => ({ stateOf: () => 'running', spawn: vi.fn(async () => ({ ok: true })), stop }),
+ sendToGhostLogic: send, getGhostAgentSlot: () => ({ issueUserActionToken: () => null, clearGhost: vi.fn() }),
+ getGhostSessionActivityTracker: () => ({ begin: vi.fn() }), ghostOwnerScope: undefined,
+ ghostInstallApprovalToken, log: { info: vi.fn(), warn: vi.fn() },
+ getGhostPreviewGate: () => preview,
+ });
+ return { ...api, root, organization, ghosts, send, setEnabled, stop, ghostCanRead, setStoredId: (id: string) => { storedId = id; } };
+}
+
+describe('production plugin instance boundaries', () => {
+ it('rejects a confirmed close after source replacement before stopping any runtime', async () => {
+ const fixture = harness();
+ const confirmedApproval = ghostInstallApprovalToken(fixture.organization.approval);
+ fixture.organization.approval = { state: 'approved', revision: 'replacement' };
+ await expect(fixture.setGhostEnabledForUser('helper', false, confirmedApproval)).rejects.toThrow('NOT_FOUND');
+ expect(fixture.setEnabled).not.toHaveBeenCalled();
+ expect(fixture.stop).not.toHaveBeenCalled();
+ const currentApproval = ghostInstallApprovalToken(fixture.organization.approval);
+ await fixture.setGhostEnabledForUser('helper', false, currentApproval);
+ expect(fixture.setEnabled).toHaveBeenCalledExactlyOnceWith('helper', false, currentApproval);
+ });
+ it('does not disable a logical twin after the original physical target disappears', async () => {
+ const fixture = harness();
+ await fixture.setGhostEnabledForUser('helper', false);
+ expect(fixture.setEnabled).toHaveBeenCalledWith('helper', false, ghostInstallApprovalToken(fixture.organization.approval));
+ fixture.setEnabled.mockClear();
+ fixture.stop.mockClear();
+ fixture.ghosts.splice(0, 1);
+ await expect(fixture.setGhostEnabledForUser('helper', false)).rejects.toThrow('NOT_FOUND');
+ expect(fixture.setEnabled).not.toHaveBeenCalled();
+ expect(fixture.stop).not.toHaveBeenCalled();
+ });
+ it.each(['root', 'in-place', 'organization'])('opens Mobile media with the protocol host and %s physical authority', async (layout) => {
+ const fixture = harness();
+ const ghost = layout === 'root' ? fixture.root : fixture.organization;
+ if (layout === 'organization') ghost.dir = '/ghosts/_ns/acme/helper';
+ const id = installedGhostStoragePart(ghost), hash = 'a'.repeat(64);
+ await expect(fixture.resolveMobilePluginMedia(id, 'cindy-ghost://helper/preview/' + hash + '.jpg', () => true))
+ .resolves.toEqual({ path: '/media/' + hash + '.png', mediaKind: 'image' });
+ expect(fixture.ghostCanRead).toHaveBeenCalledWith(hash, id);
+ await expect(fixture.resolveMobilePluginMedia(id, 'cindy-ghost://other/preview/' + hash + '.png', () => true))
+ .resolves.toBeNull();
+ fixture.ghosts.splice(fixture.ghosts.indexOf(ghost), 1);
+ await expect(fixture.resolveMobilePluginMedia(id, 'cindy-ghost://helper/preview/' + hash + '.png', () => true))
+ .resolves.toBeNull();
+ });
+ it.each(['panel.html', 'settings.html'])('attaches the logical root %s beside an in-place enterprise twin', (entry) => {
+ const fixture = harness();
+ expect(fixture.resolveGhostWebviewAttach('cindy-ghost-_root__helper', 'cindy-ghost://helper/' + entry)?.ghost).toBe(fixture.root);
+ expect(fixture.resolveGhostWebviewAttach('cindy-ghost-helper', 'cindy-ghost://helper/' + entry)?.ghost)
+ .toBe(fixture.organization);
+ expect(fixture.resolveGhostWebviewAttach('cindy-ghost-helper', 'cindy-ghost://helper/undeclared.html')).toBeNull();
+ });
+
+ it('never redirects a persisted physical card owner to a logical root after uninstall', async () => {
+ const fixture = harness(), dispatcher = fixture.getGhostCardActionDispatcher();
+ await expect(dispatcher.dispatch('old-card', 'continue', 'private input')).resolves.toEqual({ ok: true });
+ expect(fixture.send).toHaveBeenLastCalledWith('helper', expect.objectContaining({ prompt: 'private input' }));
+ fixture.send.mockClear();
+ fixture.ghosts.splice(0, 1);
+ await expect(dispatcher.dispatch('old-card', 'continue', 'private input')).resolves.toEqual({ ok: false, reason: 'ghost-unavailable' });
+ expect(fixture.send).not.toHaveBeenCalled();
+ fixture.setStoredId('_root__helper');
+ await expect(dispatcher.dispatch('root-card', 'continue')).resolves.toEqual({ ok: true });
+ expect(fixture.send).toHaveBeenLastCalledWith('_root__helper', expect.any(Object));
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
index faa4811960..e1e44117c8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
@@ -55,7 +55,8 @@ describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {
it('ghosts:set-enabled 同步委托共用入口,入口先持 owner 租约再异步修改', () => {
const block = handlerBlock(source, 'ghosts:set-enabled');
expect(block).toContain('assertTrustedAppRendererEvent(event)');
- expect(block).toContain('return setGhostEnabledForUser(id, enabled)');
+ expect(block).toContain('return setGhostEnabledForUser(id, enabled, expectedInstalledApproval)');
+ expect(block).toContain('!isGhostInstallApprovalToken(expectedInstalledApproval)');
expect(block).not.toMatch(/\bawait\b/);
const start = source.indexOf('async function setGhostEnabledForUser(');
expect(start).toBeGreaterThan(-1);
@@ -64,7 +65,9 @@ describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {
const lease = fn.indexOf('beginGhostMutation(captureGhostMutationOwner())');
expect(lease).toBeGreaterThan(-1);
expect(lease).toBeLessThan(fn.indexOf('await '));
- expect(fn).toContain('await manager.setEnabled(id, enabled)');
+ expect(fn).toContain('const relId = installedGhostPhysicalRelId(target)');
+ expect(fn).toContain('const storagePart = installedGhostStoragePart(target)');
+ expect(fn).toContain('await manager.setEnabled(relId, enabled, expectedInstalledApproval ?? approvalToken)');
expect(fn).toMatch(/finally\s*\{\s*releaseMutation\(\)/);
});
@@ -76,13 +79,24 @@ describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {
const outerStart = source.indexOf('export async function uninstallGhostAndCleanup');
expect(outerStart).toBeGreaterThan(-1);
const outer = source.slice(outerStart, source.indexOf('\n}', outerStart));
- expect(outer).toContain('withGhostInstallLock(');
+ expect(outer).toContain('withGhostInstallLock(identity.ghostId');
+ expect(outer).toContain('installedGhostStoragePart(ghost)');
const start = source.indexOf('async function uninstallGhostAndCleanupLocked');
expect(start).toBeGreaterThan(-1);
const fn = source.slice(start, source.indexOf('\n}', start));
expect(fn).toContain('beginGhostMutation(');
});
+ it('卸载按物理存储键清理寄存引用、近期使用及提醒,而非目录相对路径', () => {
+ const start = source.indexOf('async function uninstallGhostAndCleanupLocked');
+ const block = source.slice(start, source.indexOf('\n}', start));
+ expect(block).toContain("removeRefs({ refKind: 'ghost-deposit', refId: storagePart })");
+ expect(block).toContain('forgetGhostRecentUsage(storagePart)');
+ expect(block).toContain('forgetGhostRecommendations(storagePart)');
+ expect(block).toContain('extinguishGhostUnread(storagePart)');
+ expect(block).toContain('badgeSlotSingleton?.forget(storagePart)');
+ });
+
it('市场装入/更新持租约(installOrUpdateMarketGhostPackage)', () => {
// 同上:外层委托 withGhostInstallLock,owner 捕获 + 起租约在 ...Locked 内。
const outerStart = source.indexOf('export async function installOrUpdateMarketGhostPackage');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts
index cf06946b60..965f53f7ca 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts
@@ -2,6 +2,8 @@ import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
+import { isValidGhostId } from '../../../shared/ghost.js';
+import { isPluginInstanceKey } from '../../../shared/pluginIdentity.js';
/**
* 源码契约测试:所有会改写插件世界(装/卸/更/启停/导出/恢复内置)或发放
@@ -84,4 +86,12 @@ describe('高权限 ghost IPC 的来源闸(源码契约)', () => {
expect(update).toContain('replaceGhostRecommendations(id,');
expect(update).not.toMatch(/payload\.(?:id|ghostId)/);
});
+ it('accepts an organization instance key when acknowledging a retirement', () => {
+ const block = handlerBlock(source, 'ghosts:acknowledge-retirement');
+ expect(block).toContain('isPluginInstanceKey(id)');
+ expect(block).not.toContain('isValidGhostId(id)');
+ expect(isPluginInstanceKey('_ns__acme__x')).toBe(true);
+ expect(isValidGhostId('_ns__acme__x')).toBe(false);
+ });
+
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostKvStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostKvStore.test.ts
index b35efdc19c..e50f6895b4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostKvStore.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostKvStore.test.ts
@@ -50,6 +50,18 @@ describe('cindy-brain · ghostKvStore(意识自定义参数持久化)', () => {
expect(fs.existsSync(path.join(root, 'beta.json'))).toBe(true);
});
+ it('root helper 与企业 _ns__acme__helper 落成不同文件', () => {
+ store.write('helper', { from: 'root' });
+ store.write('_ns__acme__helper', { from: 'acme' });
+ expect(store.read('helper')).toEqual({ from: 'root' });
+ expect(store.read('_ns__acme__helper')).toEqual({ from: 'acme' });
+ expect(fs.existsSync(path.join(root, 'helper.json'))).toBe(true);
+ expect(fs.existsSync(path.join(root, '_ns__acme__helper.json'))).toBe(true);
+ store.remove('helper');
+ expect(store.read('helper')).toEqual({});
+ expect(store.read('_ns__acme__helper')).toEqual({ from: 'acme' });
+ });
+
it('损坏 JSON → 读回 {} 且不抛', () => {
fs.writeFileSync(path.join(root, 'demo.json'), '{broken', 'utf8');
expect(store.read('demo')).toEqual({});
@@ -125,13 +137,13 @@ describe('cindy-brain · ghostKvStore(意识自定义参数持久化)', () => {
expect(finalizeUninstall).toHaveBeenCalledOnce();
expect(log.warn).toHaveBeenCalledWith('ghost KV 清理失败', {
- ghostId: 'demo',
+ instanceKey: 'demo',
error: 'file locked',
});
});
it('非法 ghostId:写抛 INVALID_GHOST_ID,读回 {},删静默——文件名安全双保险', () => {
- for (const bad of ['../evil', 'UPPER', 'a/b', '']) {
+ for (const bad of ['../evil', 'UPPER', 'a/b', '', '_ns/acme/helper']) {
expect(() => store.write(bad, { a: 1 }), bad).toThrowError(GhostKvError);
expect(store.read(bad), bad).toEqual({});
expect(() => store.remove(bad), bad).not.toThrow();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLibraryDelete.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLibraryDelete.test.ts
new file mode 100644
index 0000000000..1a7d496915
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLibraryDelete.test.ts
@@ -0,0 +1,230 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost.js';
+import {
+ deliveryNamespaceFields,
+ findInstalledGhostByInstanceId,
+ installedGhostMutationTargetToken,
+ resolvePluginLibraryStorageKey,
+ isGhostInstanceId,
+} from '../../../shared/pluginIdentity.js';
+import { GhostManager } from '../GhostManager.js';
+import { GhostMutationCoordinator } from '../ghostMutationCoordinator.js';
+import { assertLibraryMetaOwner, LibraryBindingStore, relocateLibraryMetaOwner } from '../libraryBinding.js';
+import { trashGhostLibrary } from '../libraryTrash.js';
+
+function deferred<Value>() {
+ let resolve!: (value: Value) => void;
+ const promise = new Promise<Value>((finish) => { resolve = finish; });
+ return { promise, resolve };
+}
+
+const loadDelete = createGhostProductionCallbacks<{
+ handler: (event: { sender: object }, id: string) => Promise<{ ok: boolean }>;
+ deleteGhostLibraryForActiveOwner: (id: string) => Promise<{ ok: boolean }>;
+}>({
+ functions: [
+ 'captureGhostMutationOwner', 'beginGhostMutation', 'ghostInstallMutationTargetFor',
+ 'libraryStorageKeyFor', 'ghostLibraryDeleteTargetFor', 'deleteGhostLibraryForActiveOwner',
+ 'deleteGhostLibraryLocked',
+ ],
+ callbacks: { handler: ['ipcMain.handle', 'ghosts:library-delete'] },
+});
+
+let directory: string;
+
+function harness() {
+ const state = { owner: { mode: 'cloud', dataOwnerId: 'owner', generation: 1 }, pending: false };
+ const scopeKey = () => state.owner.dataOwnerId + ':' + state.owner.generation;
+ const userPath = (...parts: string[]) => path.join(directory, state.owner.dataOwnerId, ...parts);
+ const ghost = (namespace: string | null = 'acme', revision = 'original'): InstalledGhost => ({
+ manifest: { schemaVersion: 3, id: 'helper', name: namespace ? 'Organization helper' : 'Root helper',
+ version: '1.0.0', kind: 'chip', entry: 'main.js', library: true },
+ dir: userPath('ghosts', 'helper'), namespace, enabled: true,
+ approval: { state: 'approved', revision },
+ });
+ let ghosts = [ghost()];
+ const coordinator = new GhostMutationCoordinator();
+ const manager = new GhostManager({ getRootDir: () => userPath('ghosts'), getOwnerContextKey: scopeKey });
+ const binding = new LibraryBindingStore({
+ getFile: () => userPath('libraries-binding.json'), getManagedRoots: () => [],
+ getDefaultRoot: (id) => userPath('libraries', id),
+ });
+ const removeBinding = vi.spyOn(binding, 'removeBinding');
+ const disposeGhost = vi.fn(async () => {});
+ const checkMeta = vi.fn(assertLibraryMetaOwner);
+ const dialog = deferred<{ response: number }>();
+ const showMessageBox = vi.fn(() => dialog.promise);
+ const setRelocating = vi.fn();
+ const api = loadDelete({
+ path, ghostInstallApprovalToken, deliveryNamespaceFields, installedGhostMutationTargetToken,
+ resolvePluginLibraryStorageKey, isGhostInstanceId,
+ findGhostForInstanceId: (id: string) => findInstalledGhostByInstanceId(ghosts, id) ?? null,
+ activeOwnerScopeKey: scopeKey, isAppSessionBoundaryPending: () => state.pending,
+ getActiveAppSession: () => ({ ...state.owner }), ghostMutationCoordinator: coordinator,
+ getGhostManager: () => manager, getGhostLibrarySlot: () => ({ disposeGhost, setRelocating }),
+ getGhostLibraryBindingStore: () => binding, assertLibraryMetaOwner: checkMeta,
+ ownerScopedUserDataPath: userPath, trashGhostLibrary,
+ refreshMivoLibraryExtraDirGrant: async () => {}, assertTrustedAppRendererEvent: () => {},
+ throwIpcError: (code: string, message: string) => { throw new Error(code + ': ' + message); },
+ BrowserWindow: { fromWebContents: () => ({}) }, dialog: { showMessageBox },
+ t: (key: string) => key, log: { info: vi.fn(), warn: vi.fn() },
+ });
+ const createLibrary = (id = 'helper', contents = 'organization data') => {
+ const root = userPath('libraries', id);
+ fs.mkdirSync(path.join(root, '.cindy-library'), { recursive: true });
+ fs.writeFileSync(path.join(root, '.cindy-library', 'meta.json'), JSON.stringify({ version: 1, ghostId: id, createdAt: 1 }));
+ fs.writeFileSync(path.join(root, 'data.txt'), contents);
+ return root;
+ };
+ const root = createLibrary();
+ return { ...api, state, ghost, manager, binding, removeBinding, disposeGhost, checkMeta,
+ dialog, showMessageBox, setRelocating, coordinator, createLibrary, root, userPath,
+ setGhosts: (next: InstalledGhost[]) => { ghosts = next; },
+ invoke: () => api.handler({ sender: {} }, 'helper'),
+ unchanged: () => {
+ expect(fs.readFileSync(path.join(root, 'data.txt'), 'utf8')).toBe('organization data');
+ expect(removeBinding).not.toHaveBeenCalled();
+ expect(fs.existsSync(userPath('libraries-trash'))).toBe(false);
+ },
+ };
+}
+
+beforeEach(() => { directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-library-delete-')); });
+afterEach(() => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); });
+
+describe('Library delete Host confirmation', () => {
+ it('does not apply organization confirmation to a root that reuses its physical key', async () => {
+ const run = harness();
+ const deleting = run.invoke();
+ expect(run.showMessageBox.mock.calls[0]).toBeDefined();
+ const orgId = '_ns__acme__helper';
+ fs.renameSync(run.root, run.userPath('libraries', orgId));
+ await relocateLibraryMetaOwner(run.userPath('libraries', orgId), 'helper', orgId);
+ const organization = { ...run.ghost(), dir: run.userPath('ghosts', '_ns', 'acme', 'helper') };
+ run.setGhosts([run.ghost(null, 'new-root'), organization]);
+ run.createLibrary('helper', 'root data');
+ run.dialog.resolve({ response: 0 });
+ await expect(deleting).rejects.toThrow(/重新确认/);
+ expect(fs.readFileSync(path.join(run.root, 'data.txt'), 'utf8')).toBe('root data');
+ expect(fs.readFileSync(run.userPath('libraries', orgId, 'data.txt'), 'utf8')).toBe('organization data');
+ expect(run.disposeGhost).not.toHaveBeenCalled();
+ expect(run.removeBinding).not.toHaveBeenCalled();
+ });
+
+ it.each(['receipt', 'owner', 'boundary'] as const)('rejects a stale %s after confirmation', async (change) => {
+ const run = harness();
+ const deleting = run.invoke();
+ if (change === 'receipt') run.setGhosts([run.ghost('acme', 'replacement')]);
+ if (change === 'owner') run.state.owner = { ...run.state.owner, generation: 2 };
+ if (change === 'boundary') run.state.pending = true;
+ run.dialog.resolve({ response: 0 });
+ await expect(deleting).rejects.toThrow();
+ run.unchanged();
+ await run.coordinator.waitForIdle();
+ });
+
+ it('revalidates the target after waiting for the existing mutation lane', async () => {
+ const run = harness();
+ const entered = deferred<void>();
+ const release = deferred<void>();
+ const competing = run.manager.runExclusiveMutation(async () => { entered.resolve(); await release.promise; });
+ await entered.promise;
+ const deleting = run.invoke();
+ run.dialog.resolve({ response: 0 });
+ await Promise.resolve();
+ run.setGhosts([run.ghost(null, 'replacement')]);
+ release.resolve();
+ await competing;
+ await expect(deleting).rejects.toThrow(/重新确认/);
+ run.unchanged();
+ });
+
+ it.each(['dispose', 'binding', 'meta'] as const)('revalidates after the delete helper awaits %s', async (stage) => {
+ const run = harness();
+ const entered = deferred<void>();
+ const release = deferred<void>();
+ const pause = async () => { entered.resolve(); await release.promise; };
+ if (stage === 'dispose') run.disposeGhost.mockImplementationOnce(pause);
+ if (stage === 'binding') vi.spyOn(run.binding, 'resolveLibraryRoot').mockImplementationOnce(async () => {
+ await pause(); return { kind: 'default', root: run.root };
+ });
+ if (stage === 'meta') run.checkMeta.mockImplementationOnce(async (root, id) => {
+ await assertLibraryMetaOwner(root, id); await pause();
+ });
+ const deleting = run.invoke();
+ run.dialog.resolve({ response: 0 });
+ await entered.promise;
+ run.setGhosts([run.ghost(null, 'replacement')]);
+ release.resolve();
+ await expect(deleting).rejects.toThrow(/重新确认/);
+ run.unchanged();
+ expect(run.setRelocating).toHaveBeenLastCalledWith('helper', false);
+ });
+
+ it('keeps installed-instance mutations queued throughout the trash filesystem awaits', async () => {
+ const run = harness();
+ const entered = deferred<void>();
+ const release = deferred<void>();
+ const rename = fs.promises.rename.bind(fs.promises);
+ vi.spyOn(fs.promises, 'rename').mockImplementation(async (...args) => {
+ if (args[0] === run.root) { entered.resolve(); await release.promise; }
+ return rename(...args);
+ });
+ const deleting = run.invoke();
+ run.dialog.resolve({ response: 0 });
+ await entered.promise;
+ const mutate = vi.fn(() => run.setGhosts([run.ghost(null, 'replacement')]));
+ const competing = run.manager.runExclusiveMutation(async () => { mutate(); });
+ await Promise.resolve();
+ expect(mutate).not.toHaveBeenCalled();
+ release.resolve();
+ await expect(deleting).resolves.toEqual({ ok: true });
+ await competing;
+ expect(mutate).toHaveBeenCalledOnce();
+ expect(run.removeBinding).toHaveBeenCalledWith('helper');
+ });
+
+ it.each(['approved', 'invalid', 'legacy-unapproved', 'orphan'] as const)('retains cleanup of a stable %s Library', async (approval) => {
+ const run = harness();
+ if (approval === 'orphan') run.setGhosts([]);
+ else if (approval !== 'approved') run.setGhosts([{ ...run.ghost(), approval: { state: approval } }]);
+ const deleting = run.invoke();
+ run.dialog.resolve({ response: 0 });
+ await expect(deleting).resolves.toEqual({ ok: true });
+ expect(fs.existsSync(run.root)).toBe(false);
+ const names = fs.readdirSync(run.userPath('libraries-trash'));
+ expect(fs.readFileSync(run.userPath('libraries-trash', names[0], 'data.txt'), 'utf8')).toBe('organization data');
+ expect(run.removeBinding).toHaveBeenCalledWith('helper');
+ });
+
+ it.each(['invalid', 'legacy-unapproved', 'orphan'] as const)('does not apply stale %s cleanup to a newly installed root', async (approval) => {
+ const run = harness();
+ run.setGhosts(approval === 'orphan' ? [] : [{ ...run.ghost(), approval: { state: approval } }]);
+ const deleting = run.invoke();
+ run.setGhosts([run.ghost(null, 'replacement')]);
+ run.dialog.resolve({ response: 0 });
+ await expect(deleting).rejects.toThrow(/重新确认/);
+ run.unchanged();
+ });
+
+ it('supports direct orphan cleanup without an approval requirement', async () => {
+ const run = harness();
+ run.setGhosts([]);
+ await expect(run.deleteGhostLibraryForActiveOwner('helper')).resolves.toEqual({ ok: true });
+ expect(fs.existsSync(run.root)).toBe(false);
+ });
+
+ it('does not start cleanup when the user cancels', async () => {
+ const run = harness();
+ const deleting = run.invoke();
+ run.dialog.resolve({ response: 1 });
+ await expect(deleting).resolves.toEqual({ ok: false, cancelled: true });
+ expect(run.disposeGhost).not.toHaveBeenCalled();
+ run.unchanged();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLibraryMutation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLibraryMutation.test.ts
new file mode 100644
index 0000000000..7b4e01ae2a
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLibraryMutation.test.ts
@@ -0,0 +1,137 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { GhostManager } from '../GhostManager.js';
+import { GhostMutationCoordinator } from '../ghostMutationCoordinator.js';
+import { LibraryBindingStore, assertLibraryMetaOwner } from '../libraryBinding.js';
+import { migrateGhostLibrary } from '../libraryMigrate.js';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost.js';
+import { deliveryNamespaceFields, installedGhostMutationTargetToken, resolvePluginLibraryStorageKey } from '../../../shared/pluginIdentity.js';
+
+const load = createGhostProductionCallbacks<{
+ relocateGhostLibraryTo: (id: string, candidate: string) => Promise<{ ok: boolean }>;
+ bind: (event: unknown, id: string, candidate: string) => Promise<{ ok: boolean }>;
+ unbind: (event: unknown, id: string) => Promise<{ ok: boolean }>;
+ revert: (event: unknown, id: string) => Promise<{ ok: boolean }>;
+}>({ functions: ['beginGhostMutation', 'ghostInstallMutationTargetFor', 'ghostLibraryDeleteTargetFor',
+ 'libraryStorageKeyFor', 'withGhostLibraryMutation', 'relocateGhostLibraryToLocked', 'relocateGhostLibraryTo'],
+ callbacks: { bind: ['ipcMain.handle', 'ghosts:library-bind'], unbind: ['ipcMain.handle', 'ghosts:library-unbind'],
+ revert: ['ipcMain.handle', 'ghosts:library-revert-default'] } });
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((finish) => { resolve = finish; });
+ return { promise, resolve };
+}
+const directories: string[] = [];
+afterEach(() => { for (const directory of directories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }); });
+
+function harness() {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-library-mutation-'));
+ directories.push(directory);
+ const userPath = (...parts: string[]) => path.join(directory, ...parts);
+ const manager = new GhostManager({ getRootDir: () => userPath('ghosts'), getOwnerContextKey: () => 'owner' });
+ const binding = new LibraryBindingStore({ getFile: () => userPath('libraries-binding.json'),
+ getManagedRoots: () => [], getDefaultRoot: (id) => userPath('libraries', id) });
+ const ghost: InstalledGhost = { manifest: { schemaVersion: 3, id: 'helper', name: 'Helper', version: '1', kind: 'chip',
+ entry: 'main.js', library: true }, namespace: 'acme', dir: userPath('ghosts', 'helper'),
+ enabled: true, approval: { state: 'approved', revision: 'original' } };
+ const root = userPath('libraries', 'helper');
+ fs.mkdirSync(path.join(root, '.cindy-library'), { recursive: true });
+ fs.writeFileSync(path.join(root, '.cindy-library', 'meta.json'), JSON.stringify({ version: 1, ghostId: 'helper', createdAt: 1 }));
+ fs.writeFileSync(path.join(root, 'data.sqlite'), 'original data');
+ const candidate = userPath('chosen');
+ fs.mkdirSync(candidate);
+ const copied = deferred(), resume = deferred();
+ const slot = { setRelocating: vi.fn(), disposeGhost: vi.fn(async () => {}) };
+ const api = load({ fs, path, getGhostManager: () => manager, findGhostForInstanceId: () => ghost,
+ ghostInstallApprovalToken, deliveryNamespaceFields, installedGhostMutationTargetToken, resolvePluginLibraryStorageKey,
+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: 'owner', generation: 1 }),
+ activeOwnerScopeKey: () => 'owner', isAppSessionBoundaryPending: () => false,
+ ghostMutationCoordinator: new GhostMutationCoordinator(),
+ getGhostLibrarySlot: () => slot, assertTrustedAppRendererEvent: () => {}, isGhostInstanceId: () => true,
+ getGhostLibraryBindingStore: () => binding, ownerScopedUserDataPath: userPath,
+ assertLibraryMetaOwner, migrateGhostLibrary, app: { getPath: () => userPath('managed') },
+ statfsFreeBytes: async () => 1e12, refreshMivoLibraryExtraDirGrant: async () => {},
+ createBetterSqliteDatabase: (file: string) => ({ backup: async (to: string) => {
+ await fs.promises.copyFile(file, to); copied.resolve(); await resume.promise;
+ }, prepare: () => ({ get: () => ({ quick_check: 'ok' }) }), close: () => {} }),
+ throwIpcError: (code: string) => { throw new Error(code); }, log: { warn: vi.fn(), info: vi.fn() },
+ });
+ return { ...api, ghost, manager, binding, candidate, userPath, copied, resume, slot };
+}
+
+describe('Host Library mutation isolation', () => {
+ it('holds the existing mutation lane until copying and binding commit finish', async () => {
+ const fixture = harness();
+ const relocating = fixture.relocateGhostLibraryTo('helper', fixture.candidate);
+ await fixture.copied.promise;
+ let archived = false;
+ const archive = fixture.manager.runExclusiveMutation(async () => {
+ archived = true;
+ await fixture.binding.relocateBinding('helper', '_ns__archive__helper');
+ fixture.ghost.approval = { state: 'approved', revision: 'replacement' };
+ });
+ await Promise.resolve();
+ const archiveWaited = !archived;
+ fixture.resume.resolve();
+ await expect(relocating).resolves.toMatchObject({ ok: true });
+ await archive;
+ expect(archiveWaited).toBe(true);
+ expect(await fixture.binding.getBinding('helper')).toBeNull();
+ const retained = await fixture.binding.getBinding('_ns__archive__helper');
+ expect(retained).not.toBeNull();
+ expect(fs.readFileSync(path.join(retained!.root, '_ns__archive__helper', 'data.sqlite'), 'utf8')).toBe('original data');
+ });
+
+ it('rejects a settings operation queued for an installation that was replaced', async () => {
+ const fixture = harness(), entered = deferred(), release = deferred();
+ const replacement = fixture.manager.runExclusiveMutation(async () => {
+ entered.resolve(); await release.promise;
+ fixture.ghost.approval = { state: 'approved', revision: 'replacement' };
+ });
+ await entered.promise;
+ const relocating = fixture.relocateGhostLibraryTo('helper', fixture.candidate);
+ const rejected = expect(relocating).rejects.toThrow('PRECONDITION_FAILED');
+ fixture.resume.resolve();
+ release.resolve();
+ await replacement;
+ await rejected;
+ expect(await fixture.binding.getBinding('helper')).toBeNull();
+ expect(fs.existsSync(path.join(fixture.candidate, 'helper'))).toBe(false);
+ });
+
+ it.each(['bind', 'unbind', 'revert'] as const)('rejects stale queued %s before touching the Library', async (operation) => {
+ const fixture = harness(), entered = deferred(), release = deferred();
+ const replacement = fixture.manager.runExclusiveMutation(async () => {
+ entered.resolve(); await release.promise;
+ fixture.ghost.approval = { state: 'approved', revision: 'replacement' };
+ });
+ await entered.promise;
+ const updating = fixture[operation](undefined, 'helper', fixture.candidate);
+ const rejected = expect(updating).rejects.toThrow('PRECONDITION_FAILED');
+ release.resolve();
+ await replacement;
+ await rejected;
+ expect(fixture.slot.disposeGhost).not.toHaveBeenCalled();
+ expect(await fixture.binding.getBinding('helper')).toBeNull();
+ });
+
+ it('binds, unbinds and reverts through the shared lane without nesting it', async () => {
+ const fixture = harness();
+ await expect(fixture.bind(undefined, 'helper', fixture.candidate)).resolves.toMatchObject({ ok: true });
+ expect(await fixture.binding.getBinding('helper')).not.toBeNull();
+ await expect(fixture.unbind(undefined, 'helper')).resolves.toMatchObject({ ok: true });
+ expect(await fixture.binding.getBinding('helper')).toBeNull();
+ fixture.resume.resolve();
+ await expect(fixture.relocateGhostLibraryTo('helper', fixture.candidate)).resolves.toMatchObject({ ok: true });
+ const metadata = path.join(fixture.candidate, 'helper', '.cindy-library');
+ fs.mkdirSync(metadata, { recursive: true });
+ fs.writeFileSync(path.join(metadata, 'meta.json'), JSON.stringify({ version: 1, ghostId: 'helper', createdAt: 1 }));
+ await expect(fixture.revert(undefined, 'helper')).resolves.toEqual({ ok: true });
+ expect(await fixture.binding.getBinding('helper')).toBeNull();
+ expect(fs.readFileSync(fixture.userPath('libraries', 'helper', 'data.sqlite'), 'utf8')).toBe('original data');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
new file mode 100644
index 0000000000..b3165b9610
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
@@ -0,0 +1,511 @@
+import { createHash } from 'node:crypto';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ ghostInstallApprovalToken,
+ isGhostInstallApprovalToken,
+ type InstalledGhost,
+ type GhostTrustInfo,
+} from '../../../shared/ghost.js';
+import type { PluginMarketInstallationRecord } from '../../plugin-market/ledger.js';
+import {
+ deliveryNamespaceFields,
+ hasDeliveryNamespace,
+ findInstalledGhostByInstanceId,
+ findInstalledGhostForLocalUpdate,
+ installedGhostStoragePart,
+ isGhostInstanceId,
+ resolveInstalledGhost,
+} from '../../../shared/pluginIdentity.js';
+import { loadGhostFirstPartyFactsLoader } from '../ghostFirstPartyFacts.js';
+import { authorizeGhostTokenBroker } from '../ghostFirstPartyPrivilege.js';
+import { createGhostInstallReceipt, type GhostInstallReceipt } from '../ghostInstallReceipt.js';
+import { classifyGhostLocalUpdateSource } from '../ghostLocalUpdateSource.js';
+import { confirmedTaskCapability } from '../ghostInstallConsent.js';
+import { isCindyOverrideModelAllowed } from '../cindyOverrideWhitelist.js';
+
+type Handler = (event: unknown, ...args: unknown[]) => Promise<unknown>;
+
+const callbackChannels = {
+ inspect: 'ghosts:inspect', update: 'ghosts:update', exportGhost: 'ghosts:export',
+ cindyPrefs: 'ghosts:cindy-prefs:set', errandPrefs: 'ghosts:errand-prefs:set',
+};
+const createCallbacks = createGhostProductionCallbacks<Record<keyof typeof callbackChannels, Handler>>({
+ functions: [
+ 'readLocalGhostUpdateSource', 'updateLocalGhostPackageLocked', 'rejectUnauthorizedTokenBroker',
+ 'assertGhostRelocationIdle', 'findGhostForInstanceId',
+ ],
+ callbacks: Object.fromEntries(Object.entries(callbackChannels).map(([name, channel]) =>
+ [name, ['ipcMain.handle', channel] as const],
+ )),
+});
+
+function productionCallbacks(deps: Record<string, unknown>): Record<string, Handler> {
+ const callbacks = createCallbacks(deps);
+ return Object.fromEntries(Object.entries(callbackChannels).map(([name, channel]) =>
+ [channel, callbacks[name as keyof typeof callbacks]],
+ ));
+}
+
+const packageSha256 = 'a'.repeat(64);
+const originalRevision = '11111111-1111-4111-8111-111111111111';
+const replacementRevision = '22222222-2222-4222-8222-222222222222';
+const unsigned: GhostTrustInfo = {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+};
+const signed: GhostTrustInfo = {
+ level: 'verified-publisher',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: false,
+ publisherKeyId: 'original-publisher',
+};
+
+function harness(
+ options: {
+ broker?: boolean;
+ namespace?: string | null;
+ approval?: 'approved' | 'invalid' | 'legacy-unapproved';
+ missingReceipt?: boolean;
+ fsBusy?: boolean;
+ networkBusy?: boolean;
+ } = {},
+) {
+ const manifest: InstalledGhost['manifest'] = {
+ schemaVersion: 2,
+ id: 'filo-local',
+ name: 'Local',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ ...(options.broker
+ ? {
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'oauth',
+ source: 'oauth',
+ label: 'OAuth',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.example.com'],
+ },
+ oauth: {
+ authorizeUrl: 'https://api.example.com/auth',
+ tokenUrl: 'https://api.example.com/token',
+ scopes: [],
+ tokenBroker: 'feishu',
+ redirectPort: 8123,
+ },
+ },
+ ],
+ },
+ }
+ : {}),
+ };
+ const ghost: InstalledGhost = {
+ manifest,
+ namespace: options.namespace ?? null,
+ dir: options.namespace
+ ? '/plugins/_ns/' + options.namespace + '/filo-local'
+ : '/plugins/filo-local',
+ enabled: true,
+ trust: unsigned,
+ approval:
+ options.approval && options.approval !== 'approved'
+ ? { state: options.approval }
+ : { state: 'approved', revision: originalRevision },
+ };
+ const installed = new Map([[installedGhostStoragePart(ghost), ghost]]);
+ const receipts = new Map<string, GhostInstallReceipt>();
+ const marketRecords = new Map<string, PluginMarketInstallationRecord>();
+ if (options.namespace)
+ marketRecords.set(installedGhostStoragePart(ghost), {
+ pluginId: 'organization-resource',
+ ghostId: manifest.id,
+ namespace: options.namespace,
+ releaseId: 'original-release',
+ version: manifest.version,
+ scope: 'organization',
+ organizationId: 'org-xd',
+ source: 'market',
+ installed: true,
+ sha256: packageSha256,
+ updatedAt: '2026-09-30T00:00:00Z',
+ });
+ if (ghost.approval.state === 'approved' && !options.missingReceipt)
+ receipts.set(
+ installedGhostStoragePart(ghost),
+ createGhostInstallReceipt({
+ manifest,
+ namespace: ghost.namespace,
+ localeResources: {},
+ enabled: true,
+ trust: unsigned,
+ revision: ghost.approval.revision,
+ skillContentSha256: {},
+ packageSha256,
+ legacyFirstPartyEligible: options.broker === true && !options.namespace,
+ }),
+ );
+ let inspected = {
+ manifest,
+ canonicalManifest: manifest,
+ trust: unsigned,
+ packageSha256,
+ unsupportedLegacySlots: [],
+ };
+ const ledger = {
+ bind: () => ledger,
+ installationForPlugin: vi.fn(() => null),
+ markRemovedRecord: vi.fn(),
+ restoreInstallation: vi.fn(),
+ };
+ const manager = {
+ list: () => [...installed.values()],
+ inspect: vi.fn(async () => inspected),
+ readApprovedInstallReceipt: vi.fn((id: string, revision: string) =>
+ receipts.get(id)?.revision === revision ? receipts.get(id) : null,
+ ),
+ update: vi.fn(async (_path: string, updateOptions: { onPackagePlaced?: () => void }) => {
+ updateOptions.onPackagePlaced?.();
+ return { ghost: { ...ghost, approval: { state: 'approved', revision: 'new-receipt' } } };
+ }),
+ };
+ const loader = loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false,
+ readMarketInstallation: (id) => marketRecords.get(id) ?? null,
+ readApprovedPackageSha256: (id) => {
+ const target = findInstalledGhostByInstanceId(manager.list(), id);
+ return receipts.get(target ? installedGhostStoragePart(target) : id)?.packageSha256 ?? null;
+ },
+ readInstallNamespace: (id) => findInstalledGhostByInstanceId(manager.list(), id)?.namespace,
+ readInstallOrigin: () => 'manual',
+ readLegacyFirstPartyEligible: (id) => receipts.get(id)?.legacyFirstPartyEligible === true,
+ lookupOrganizationPrefix: () => ({ kind: 'absent' }),
+ });
+ const runtime = { stop: vi.fn(), resetFuse: vi.fn() };
+ const release = vi.fn();
+ const session = { mode: 'local', dataOwnerId: 'owner', generation: 1 };
+ let exportMutation: (() => void) | undefined;
+ const exportBytes = Buffer.from('host-produced-export-snapshot');
+ const exportDigest = createHash('sha256').update(exportBytes).digest('hex');
+ const exportPackage = vi.fn(
+ async (
+ _id: string,
+ deps: {
+ listInstalled: () => InstalledGhost[];
+ writeFile: (path: string, bytes: Buffer) => Promise<void>;
+ inspectPackage: (path: string) => Promise<boolean>;
+ },
+ ) => {
+ expect(deps.listInstalled().some((candidate) => candidate.dir === ghost.dir)).toBe(true);
+ await deps.writeFile('/exports/snapshot.tmp', exportBytes);
+ inspected = { ...inspected, packageSha256: exportDigest };
+ exportMutation?.();
+ return (await deps.inspectPackage('/exports/snapshot.tmp'))
+ ? { status: 'saved', savedPath: '/exports/plugin.cindy' }
+ : { status: 'error', code: 'verify_failed' };
+ },
+ );
+ const callbacks = productionCallbacks({
+ manager,
+ assertTrustedAppRendererEvent: vi.fn(),
+ captureGhostMutationOwner: () => ({ ...session }),
+ beginGhostMutation: () => release,
+ getActiveAppSession: () => session,
+ isAppSessionBoundaryPending: () => false,
+ isSameAppSession: (left: typeof session, right: typeof session) =>
+ left.generation === right.generation && left.dataOwnerId === right.dataOwnerId,
+ ghostOwnerScope: {
+ isStable: (owner: typeof session) => owner.generation === session.generation,
+ },
+ throwIpcError: (code: string, message: string) => {
+ throw Object.assign(new Error(message), { code });
+ },
+ throwInstallError: (rejection: unknown) => {
+ throw new Error(JSON.stringify(rejection));
+ },
+ rejectReservedGhostId: vi.fn(),
+ rejectBrokerWithoutDeclaredRedirectPort: vi.fn(),
+ ghostTokenBrokerInstallError: () => ({ code: 'PERMISSION_DENIED', reason: 'Broker denied' }),
+ isGhostTokenBrokerAuthorized: (
+ id: string,
+ purpose: 'runtime' | 'install',
+ overrides: Parameters<typeof loader.load>[3],
+ ) =>
+ authorizeGhostTokenBroker(
+ id,
+ loader.load(
+ id,
+ purpose,
+ options.namespace
+ ? { membershipKind: 'org', orgId: 'org-xd', orgSlug: options.namespace }
+ : { membershipKind: 'personal', orgId: null },
+ overrides,
+ ),
+ ),
+ findInstalledGhostForLocalUpdate,
+ findInstalledGhostByInstanceId,
+ installedGhostStoragePart,
+ resolveInstalledGhost,
+ availableGhosts: () => Array.from(installed.values()),
+ CINDY_CAPABILITY_KEYS: ['image.generate'],
+ isCindyOverrideModelAllowed,
+ getGhostMediaPreferenceConfig: () => ({ models: [] }),
+ getCatalogEmbedConfig: () => ({ models: [] }),
+ buildTextOneshotPinOptions: () => [],
+ getActiveCatalog: () => ({}),
+ readModelDisableOverrides: () => ({}),
+ writeGhostCindyOverride: vi.fn((id: string) => ({ id })),
+ writePluginTaskConfig: vi.fn((id: string) => ({ id })),
+ validatePluginTaskConfig: vi.fn(async () => {}),
+ getGhostSetupChangeBus: () => ({ emit: vi.fn() }),
+ ghostInstallApprovalToken,
+ isGhostInstanceId,
+ isGhostInstallApprovalToken,
+ deliveryNamespaceFields,
+ hasDeliveryNamespace,
+ classifyGhostLocalUpdateSource,
+ getPluginMarketLedger: () => ledger,
+ ownerScopedUserDataPath: () => '/owner/ledger.json',
+ obtainGhostInstallConsent: vi.fn(async () => ({ action: 'install' })),
+ createWindowGhostInstallConsentPrompt: vi.fn(),
+ assertGhostInstallConsent: vi.fn(),
+ confirmedTaskCapability,
+ withGhostInstallLock: async (_id: string, task: () => unknown) => task(),
+ withActiveOwnerGhostOauthMutationLock: async (_id: string, task: () => unknown) => task(),
+ getGhostRuntime: () => runtime,
+ hasPendingGhostCalls: () => false,
+ hasRunningGhostErrand: () => false,
+ hasRunningGhostCindyWork: () => false,
+ fsSlotSingleton: { hasInFlightRequests: () => options.fsBusy === true },
+ networkSlotSingleton: { hasInFlightRequests: () => options.networkBusy === true },
+ getGhostNodeRuntimeBroker: () => ({ stopAndWait: vi.fn() }),
+ getGhostAgentSlot: () => ({ clearGhost: vi.fn() }),
+ getGhostErrandSlot: () => ({ clearGhost: vi.fn() }),
+ getGhostOauthAccountManager: () => ({ prepareAccountsForChangedClients: vi.fn() }),
+ ghostSourceStateArchiveId: () => '_ns__cindy-archive-test__filo-local',
+ getLayoutStore: () => ({ getLayout: () => ({}), setLayout: vi.fn() }),
+ layoutWithGhostPanel: () => null,
+ spawnIfResident: vi.fn(),
+ exportGhostPackage: exportPackage,
+ BrowserWindow: { fromWebContents: () => null },
+ dialog: { showSaveDialog: vi.fn() },
+ app: { getPath: () => '/exports' },
+ t: (key: string) => key,
+ fs: { promises: { writeFile: vi.fn() } },
+ createHash,
+ findConflictingGhostCommand: () => null,
+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },
+ });
+ const target = {
+ expectedInstalledInstanceId: installedGhostStoragePart(ghost),
+ expectedInstalledApproval: ghostInstallApprovalToken(ghost.approval),
+ };
+ return {
+ callbacks,
+ ghost,
+ manager,
+ receipts,
+ installed,
+ target,
+ updateOptions: { ...target, expectedPackageSha256: packageSha256 },
+ addSameNameRoot: () => installed.set(manifest.id, {
+ ...ghost, namespace: null, dir: '/plugins/filo-local',
+ }),
+ runtime,
+ release,
+ session,
+ replacePackage: (values: Partial<typeof inspected>) => {
+ inspected = { ...inspected, ...values };
+ },
+ mutateExport: (mutation: () => void) => {
+ exportMutation = mutation;
+ },
+ };
+}
+
+describe('local file recovery and source gates through production IPC callbacks', () => {
+ it.each(['invalid', 'legacy-unapproved'] as const)(
+ 'repairs %s receipt without inheriting source state',
+ async (approval) => {
+ const target = harness({ approval });
+ await expect(
+ target.callbacks['ghosts:update']({}, '/local.cindy', target.updateOptions),
+ ).resolves.toMatchObject({ ghost: { approval: { state: 'approved' } } });
+ expect(target.manager.update).toHaveBeenCalledWith(
+ '/local.cindy',
+ expect.objectContaining({ sourceStateArchiveId: '_ns__cindy-archive-test__filo-local' }),
+ );
+ expect(target.release).toHaveBeenCalledOnce();
+ },
+ );
+ it('treats missing approved receipt as source replacement, not inherited approval', async () => {
+ const target = harness({ missingReceipt: true });
+ await expect(
+ target.callbacks['ghosts:update']({}, '/local.cindy', target.updateOptions),
+ ).resolves.toBeTruthy();
+ expect(target.manager.update).toHaveBeenCalledWith(
+ '/local.cindy',
+ expect.objectContaining({ sourceStateArchiveId: '_ns__cindy-archive-test__filo-local' }),
+ );
+ });
+ it.each(['invalid', 'legacy-unapproved'] as const)(
+ 'cannot restore legacy Broker qualification from %s receipt',
+ async (approval) => {
+ const target = harness({ approval, broker: true });
+ await expect(
+ target.callbacks['ghosts:update']({}, '/local.cindy', target.updateOptions),
+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(target.manager.update).not.toHaveBeenCalled();
+ expect(target.runtime.stop).not.toHaveBeenCalled();
+ },
+ );
+ it('inspects an exact same-source legacy Broker package for the selected receiver', async () => {
+ const target = harness({ broker: true });
+ await expect(
+ target.callbacks['ghosts:inspect']({}, '/local.cindy', target.target),
+ ).resolves.toMatchObject({ packageSha256 });
+ });
+ it('inspects a verified update signed by the previously pinned publisher', async () => {
+ const target = harness({ broker: true });
+ target.receipts.get('filo-local')!.trust = signed;
+ target.replacePackage({ trust: signed, packageSha256: 'b'.repeat(64) });
+ await expect(
+ target.callbacks['ghosts:inspect']({}, '/local.cindy', target.target),
+ ).resolves.toMatchObject({ packageSha256: 'b'.repeat(64) });
+ });
+ it.each([undefined, 'target'])(
+ 'rejects a new unsigned same-name Broker package with context %s',
+ async (context) => {
+ const target = harness({ broker: true });
+ target.replacePackage({ packageSha256: 'b'.repeat(64) });
+ await expect(
+ target.callbacks['ghosts:inspect']({}, '/local.cindy', context ? target.target : undefined),
+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ },
+ );
+ it('does not silently replace a mismatched inspect receiver', async () => {
+ const target = harness();
+ await expect(
+ target.callbacks['ghosts:inspect']({}, '/local.cindy', {
+ ...target.target,
+ expectedInstalledApproval: 'approved:' + replacementRevision,
+ }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ });
+ it('keeps old one-argument inspect working for an ordinary package', async () => {
+ await expect(harness().callbacks['ghosts:inspect']({}, '/local.cindy')).resolves.toMatchObject({
+ packageSha256,
+ });
+ });
+ it('exports the source-qualified legacy snapshot instead of treating it as a fresh install', async () => {
+ const target = harness({ broker: true });
+ await expect(target.callbacks['ghosts:export']({}, 'filo-local')).resolves.toMatchObject({
+ status: 'saved',
+ });
+ });
+ it('does not export a Broker merely because an ordinary root has the same name', async () => {
+ const target = harness({ broker: true });
+ target.receipts.get('filo-local')!.legacyFirstPartyEligible = false;
+ await expect(target.callbacks['ghosts:export']({}, 'filo-local')).rejects.toMatchObject({
+ code: 'INTERNAL',
+ });
+ });
+ it('rejects export after the selected receipt changes', async () => {
+ const target = harness();
+ target.mutateExport(() =>
+ target.installed.set('filo-local', {
+ ...target.ghost,
+ approval: { state: 'approved', revision: 'replacement' },
+ }),
+ );
+ await expect(target.callbacks['ghosts:export']({}, 'filo-local')).rejects.toMatchObject({
+ code: 'INTERNAL',
+ });
+ });
+ it('rejects export bytes replaced after the Host wrote its snapshot', async () => {
+ const target = harness();
+ target.mutateExport(() => target.replacePackage({ packageSha256: 'b'.repeat(64) }));
+ await expect(target.callbacks['ghosts:export']({}, 'filo-local')).rejects.toMatchObject({
+ code: 'INTERNAL',
+ });
+ });
+
+ it('exports the qualified organization instance without borrowing a same-name root', async () => {
+ const target = harness({ broker: true, namespace: 'xd' });
+ target.addSameNameRoot();
+ await expect(
+ target.callbacks['ghosts:export']({}, target.target.expectedInstalledInstanceId),
+ ).resolves.toMatchObject({ status: 'saved' });
+ });
+
+ it.each(['fsBusy', 'networkBusy'] as const)('rejects source replacement before stopping the runtime while %s is in flight', async (busy) => {
+ const target = harness({ approval: 'invalid', [busy]: true });
+ await expect(target.callbacks['ghosts:update']({}, '/local.cindy', target.updateOptions))
+ .rejects.toThrow('waiting for active work');
+ expect(target.runtime.stop).not.toHaveBeenCalled();
+ expect(target.manager.update).not.toHaveBeenCalled();
+ expect(target.release).toHaveBeenCalledOnce();
+ });
+
+ it.each(['cindy', 'errand'])('binds %s preferences to the current physical instance and rejects missing targets', async (kind) => {
+ const target = harness({ namespace: 'xd', approval: 'invalid' });
+ const handler = target.callbacks['ghosts:' + kind + '-prefs:set'];
+ const args = kind === 'cindy' ? ['image.generate', null] : [null];
+ expect(await handler({}, 'filo-local', ...args)).toMatchObject(
+ kind === 'cindy' ? { overrides: { id: '_ns__xd__filo-local' } } : { config: { id: '_ns__xd__filo-local' } },
+ );
+ target.installed.clear();
+ await expect(Promise.resolve().then(() => handler({}, 'filo-local', ...args))).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('does not update an enterprise instance from a local file', async () => {
+ const target = harness({ namespace: 'xd', approval: 'invalid' });
+ target.addSameNameRoot();
+ await expect(target.callbacks['ghosts:update']({}, '/local.cindy', target.updateOptions))
+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(target.manager.update).not.toHaveBeenCalled();
+ expect(target.runtime.stop).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ null,
+ {},
+ { legacyFirstPartyEligible: true },
+ { expectedInstalledInstanceId: 'filo-local' },
+ ])('rejects unbound inspect options %j', async (options) => {
+ await expect(
+ harness({ broker: true }).callbacks['ghosts:inspect']({}, '/local.cindy', options),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ });
+
+ it('cancels targeted inspect when the owner changes while inspecting bytes', async () => {
+ const target = harness({ broker: true });
+ const original = target.manager.inspect.getMockImplementation()!;
+ target.manager.inspect.mockImplementation(async () => {
+ const result = await original();
+ target.session.generation += 1;
+ return result;
+ });
+ await expect(
+ target.callbacks['ghosts:inspect']({}, '/local.cindy', target.target),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ });
+
+ it('cancels export when the owner changes after the snapshot is captured', async () => {
+ const target = harness();
+ target.mutateExport(() => {
+ target.session.generation += 1;
+ });
+ await expect(target.callbacks['ghosts:export']({}, 'filo-local')).rejects.toMatchObject({
+ code: 'INTERNAL',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
new file mode 100644
index 0000000000..c4e6d26aae
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import type { GhostInstallConsentRequest } from '../../../shared/ghostInstallConsent.js';
+import { findInstalledGhostForDeliveryTarget, installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
+import { assertGhostInstallConsent, confirmedTaskCapability, obtainGhostInstallConsent } from '../ghostInstallConsent.js';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+
+const createCallbacks = createGhostProductionCallbacks<{
+ install: (event: unknown, file: string, options: unknown) => Promise<{ ghost: InstalledGhost }>;
+}>({
+ functions: ['installAndDock', 'installAndDockLocked'],
+ callbacks: { install: ['ipcMain.handle', 'ghosts:install'] },
+});
+
+describe('local root installation consent identity', () => {
+ it.each([true, false])('confirms an independent root beside an approved organization (allow=%s)', async (allow) => {
+ const manifest: InstalledGhost['manifest'] = {
+ schemaVersion: 3, minCindyVersion: '0.0.0', id: 'helper', name: 'Helper',
+ version: '1.0.0', kind: 'chip', entry: 'main.js',
+ node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio', lifecycle: 'resident' },
+ };
+ const organization: InstalledGhost = {
+ manifest, namespace: 'acme', dir: '/plugins/_ns/acme/helper', enabled: true,
+ approval: { state: 'approved', revision: '11111111-1111-4111-8111-111111111111' },
+ };
+ const root: InstalledGhost = { ...organization, namespace: null, dir: '/plugins/_ns/_root/helper' };
+ const packageSha256 = 'a'.repeat(64);
+ const prompt = vi.fn(async (_request: Omit<GhostInstallConsentRequest, 'requestId'>) => allow);
+ const release = vi.fn();
+ const manager = {
+ list: () => [organization],
+ inspect: vi.fn(async () => ({ manifest, packageSha256 })),
+ install: vi.fn(async () => ({ ghost: root })),
+ };
+ const callbacks = createCallbacks({
+ manager, assertTrustedAppRendererEvent: vi.fn(), captureGhostMutationOwner: () => 'owner',
+ beginGhostMutation: () => release, rejectReservedGhostId: vi.fn(),
+ rejectBrokerWithoutDeclaredRedirectPort: vi.fn(), rejectUnauthorizedTokenBroker: vi.fn(),
+ throwIpcError: (code: string) => { throw new Error(code); },
+ throwInstallError: () => { throw new Error('install rejected'); },
+ obtainGhostInstallConsent, assertGhostInstallConsent, confirmedTaskCapability,
+ createWindowGhostInstallConsentPrompt: () => prompt,
+ findInstalledGhostForDeliveryTarget, installedGhostStoragePart,
+ withGhostInstallLock: async (_id: string, operation: () => unknown) => operation(),
+ getLayoutStore: () => ({ getLayout: () => ({}) }), layoutWithGhostPanel: () => null,
+ spawnIfResident: vi.fn(), markGhostRecommendationInstalled: vi.fn(), log: { warn: vi.fn() },
+ });
+ const installing = callbacks.install({ sender: {} }, '/tmp/helper.cindy', { enable: true, expectedPackageSha256: packageSha256 });
+ if (allow) {
+ await expect(installing).resolves.toMatchObject({ ghost: root });
+ expect(manager.install).toHaveBeenCalledOnce();
+ expect(release).toHaveBeenCalledOnce();
+ } else {
+ await expect(installing).rejects.toThrow();
+ expect(manager.install).not.toHaveBeenCalled();
+ }
+ expect(prompt).toHaveBeenCalledOnce();
+ expect(prompt.mock.calls[0]?.[0]).toMatchObject({ facts: { kind: 'install' } });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalUpdateSource.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalUpdateSource.test.ts
new file mode 100644
index 0000000000..d64ef88975
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalUpdateSource.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it } from 'vitest';
+import type { GhostTrustInfo } from '../../../shared/ghost.js';
+import { resolveGhostFirstPartyPrivilege } from '../ghostFirstPartyPrivilege.js';
+import {
+ classifyGhostLocalUpdateSource,
+ type GhostLocalUpdateSourceInput,
+} from '../ghostLocalUpdateSource.js';
+
+const OLD_SHA = 'a'.repeat(64);
+const NEW_SHA = 'b'.repeat(64);
+const UNSIGNED: GhostTrustInfo = {
+ level: 'unverified', publisherSigned: false, publisherVerified: false, reviewed: false,
+};
+const OFFICIAL: GhostTrustInfo = {
+ level: 'cindy-official', publisherSigned: true, publisherVerified: true,
+ reviewed: true, publisherName: 'Cindy Plugin Market',
+};
+const SIGNED: GhostTrustInfo = {
+ level: 'verified-publisher', publisherSigned: true, publisherVerified: true,
+ reviewed: false, publisherKeyId: 'ed25519:' + 'c'.repeat(32),
+};
+
+function input(): GhostLocalUpdateSourceInput {
+ return {
+ existingSourceChanged: false,
+ previousApprovedReceipt: {
+ id: 'filo-google', namespace: null, packageSha256: OLD_SHA,
+ trust: OFFICIAL, legacyFirstPartyEligible: true,
+ },
+ inspectedPackage: {
+ ghostId: 'filo-google', namespace: null, packageSha256: NEW_SHA, trust: UNSIGNED,
+ },
+ };
+}
+
+describe('local update provenance independent of legacy privileges', () => {
+ it('only feeds the install gate a legacy override after proving package continuity', () => {
+ for (const packageSha256 of [OLD_SHA, NEW_SHA]) {
+ const facts = input();
+ facts.inspectedPackage.packageSha256 = packageSha256;
+ const decision = classifyGhostLocalUpdateSource(facts);
+ const privilege = resolveGhostFirstPartyPrivilege({
+ ghostId: 'filo-google', namespace: null, builtin: false, marketRecord: null,
+ currentOrganization: null, installOrigin: 'manual',
+ legacyFirstPartyEligible: decision.legacyFirstPartyEligible,
+ });
+ expect(privilege.brokerEligible).toBe(packageSha256 === OLD_SHA);
+ expect(privilege.hostPrimitiveEligible).toBe(packageSha256 === OLD_SHA);
+ }
+ });
+
+ it('isolates a ledgerless retired official instance from a new same-ID unsigned manual package', () => {
+ expect(classifyGhostLocalUpdateSource(input())).toEqual({
+ sourceChanged: true, legacyFirstPartyEligible: false,
+ });
+ });
+
+ it('protects Host-official receipts even before a legacy qualification was captured', () => {
+ const facts = input();
+ facts.previousApprovedReceipt!.legacyFirstPartyEligible = false;
+ expect(classifyGhostLocalUpdateSource(facts).sourceChanged).toBe(true);
+ });
+
+ it('protects captured public legacy qualification without Host-official trust', () => {
+ const facts = input();
+ facts.previousApprovedReceipt!.trust = UNSIGNED;
+ expect(classifyGhostLocalUpdateSource(facts).sourceChanged).toBe(true);
+ });
+
+ it('retains the old qualification for the exact approved package bytes', () => {
+ const facts = input();
+ facts.inspectedPackage.packageSha256 = OLD_SHA;
+ expect(classifyGhostLocalUpdateSource(facts)).toEqual({
+ sourceChanged: false, legacyFirstPartyEligible: true,
+ });
+ });
+
+ it.each(['other-id', 'other-namespace'])('does not accept exact bytes with %s', (change) => {
+ const facts = input();
+ facts.inspectedPackage.packageSha256 = OLD_SHA;
+ if (change === 'other-id') facts.inspectedPackage.ghostId = 'filo-other';
+ else facts.inspectedPackage.namespace = 'xd';
+ expect(classifyGhostLocalUpdateSource(facts).sourceChanged).toBe(true);
+ });
+
+ it('does not treat an arbitrary new verified publisher or official-looking display name as continuity', () => {
+ const facts = input();
+ facts.inspectedPackage.trust = { ...SIGNED, publisherName: 'Cindy Plugin Market' };
+ expect(classifyGhostLocalUpdateSource(facts).sourceChanged).toBe(true);
+ });
+
+ it('accepts a newly inspected signature from the previously pinned verified publisher key', () => {
+ const facts = input();
+ facts.previousApprovedReceipt!.trust = SIGNED;
+ facts.inspectedPackage.trust = { ...SIGNED, publisherName: 'renamed publisher' };
+ expect(classifyGhostLocalUpdateSource(facts)).toEqual({
+ sourceChanged: false, legacyFirstPartyEligible: true,
+ });
+ });
+
+ it.each(['other-key', 'unsigned', 'unverified', 'missing-key', 'unverified-old-key'])(
+ 'does not carry credentials or legacy qualification across %s', (change) => {
+ const facts = input();
+ facts.previousApprovedReceipt!.trust = { ...SIGNED };
+ facts.inspectedPackage.trust = { ...SIGNED };
+ if (change === 'other-key') facts.inspectedPackage.trust.publisherKeyId = 'another-key';
+ if (change === 'unsigned') facts.inspectedPackage.trust.publisherSigned = false;
+ if (change === 'unverified') facts.inspectedPackage.trust.publisherVerified = false;
+ if (change === 'missing-key') delete facts.inspectedPackage.trust.publisherKeyId;
+ if (change === 'unverified-old-key') facts.previousApprovedReceipt!.trust.publisherVerified = false;
+ expect(classifyGhostLocalUpdateSource(facts)).toEqual({
+ sourceChanged: true, legacyFirstPartyEligible: false,
+ });
+ },
+ );
+
+ it('never overrides an already established market-route or origin change, even with identical bytes', () => {
+ const facts = input();
+ facts.existingSourceChanged = true;
+ facts.inspectedPackage.packageSha256 = OLD_SHA;
+ expect(classifyGhostLocalUpdateSource(facts)).toEqual({
+ sourceChanged: true, legacyFirstPartyEligible: false,
+ });
+ });
+
+ it.each(['missing-receipt', 'missing-old-hash', 'invalid-old-hash', 'invalid-new-hash'])(
+ 'fails closed for %s', (change) => {
+ const facts = input();
+ facts.inspectedPackage.packageSha256 = OLD_SHA;
+ if (change === 'missing-receipt') facts.previousApprovedReceipt = null;
+ if (change === 'missing-old-hash') delete facts.previousApprovedReceipt!.packageSha256;
+ if (change === 'invalid-old-hash') facts.previousApprovedReceipt!.packageSha256 = 'invalid';
+ if (change === 'invalid-new-hash') facts.inspectedPackage.packageSha256 = 'invalid';
+ expect(classifyGhostLocalUpdateSource(facts)).toEqual({
+ sourceChanged: true, legacyFirstPartyEligible: false,
+ });
+ },
+ );
+
+ it('keeps ordinary unsigned local-to-local update semantics without granting legacy privilege', () => {
+ const facts = input();
+ facts.previousApprovedReceipt!.trust = UNSIGNED;
+ facts.previousApprovedReceipt!.legacyFirstPartyEligible = false;
+ expect(classifyGhostLocalUpdateSource(facts)).toEqual({
+ sourceChanged: false, legacyFirstPartyEligible: false,
+ });
+ });
+
+ it('does not mint a legacy qualification for a new trusted publisher update', () => {
+ const facts = input();
+ facts.previousApprovedReceipt!.trust = SIGNED;
+ facts.previousApprovedReceipt!.legacyFirstPartyEligible = false;
+ facts.inspectedPackage.trust = SIGNED;
+ expect(classifyGhostLocalUpdateSource(facts)).toEqual({
+ sourceChanged: false, legacyFirstPartyEligible: false,
+ });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalUpdateSource.wiring.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalUpdateSource.wiring.test.ts
new file mode 100644
index 0000000000..e5a5c8fb3f
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalUpdateSource.wiring.test.ts
@@ -0,0 +1,53 @@
+import fs from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+
+const source = fs.readFileSync(fileURLToPath(new URL('../index.ts', import.meta.url)), 'utf8');
+
+function bodyBetween(startMarker: string, endMarker: string): string {
+ const start = source.indexOf(startMarker);
+ const end = source.indexOf(endMarker, start + startMarker.length);
+ expect(start).toBeGreaterThanOrEqual(0);
+ expect(end).toBeGreaterThan(start);
+ return source.slice(start, end);
+}
+
+describe('local update production source gate wiring', () => {
+ it('rechecks approved source and broker eligibility under the install lock before stopping the old runtime', () => {
+ const body = bodyBetween('async function updateLocalGhostPackageLocked(', 'export async function installOrUpdateLocalGhostPackageFromForge(');
+ const classify = body.indexOf('readLocalGhostUpdateSource(');
+ const gate = body.indexOf('rejectUnauthorizedTokenBroker(inspected.canonicalManifest, authorizationOverrides)');
+ const stop = body.indexOf('runtime.stop(');
+ expect(classify).toBeGreaterThanOrEqual(0);
+ expect(gate).toBeGreaterThan(classify);
+ expect(stop).toBeGreaterThan(gate);
+ expect(body).toContain('sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(previousGhost) }');
+ });
+
+ it('never borrows the old market or builtin trust for the newly inspected local package', () => {
+ const body = bodyBetween('function readLocalGhostUpdateSource(', 'async function updateLocalGhostPackageLocked(');
+ expect(body).toContain('manager.readApprovedInstallReceipt(instanceId, previousGhost.approval.revision)');
+ expect(body).toContain('classifyGhostLocalUpdateSource({');
+ expect(body).toContain('packageSha256: inspected.packageSha256');
+ expect(body).toContain('trust: inspected.trust');
+ expect(body).toContain('marketRecord: null');
+ expect(body).toContain('trustedSource: null');
+ expect(body).toContain('legacyFirstPartyEligible: decision.legacyFirstPartyEligible');
+ });
+
+ it('checks the selected local update target before computing its legacy gate override', () => {
+ const target = source.indexOf('const existingForUpdate = findInstalledGhostForLocalUpdate(');
+ const classify = source.indexOf('const updateSource = readLocalGhostUpdateSource(', target);
+ const gate = source.indexOf('rejectUnauthorizedTokenBroker(inspected.canonicalManifest, updateSource.authorizationOverrides)', target);
+ expect(target).toBeGreaterThanOrEqual(0);
+ expect(classify).toBeGreaterThan(target);
+ expect(gate).toBeGreaterThan(classify);
+ expect(source.slice(target, gate)).toContain("if (!existingForUpdate) throwIpcError('PRECONDITION_FAILED'");
+ });
+
+ it('uses the same source decision for Forge updates before entering the common locked transaction', () => {
+ const body = bodyBetween('export async function installOrUpdateLocalGhostPackageFromForge(', 'export async function installOrUpdateMarketGhostPackage(');
+ expect(body).toContain('readLocalGhostUpdateSource(manager, existingForForge, inspected, installOrigin).authorizationOverrides');
+ expect(body).toContain('ghost: await updateLocalGhostPackageLocked(');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostMediaHandoverIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostMediaHandoverIpc.test.ts
new file mode 100644
index 0000000000..491f40e38b
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostMediaHandoverIpc.test.ts
@@ -0,0 +1,92 @@
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type InstalledGhost } from '../../../shared/ghost';
+import { installedGhostStoragePart, isGhostInstanceId } from '../../../shared/pluginIdentity';
+import { ghostMediaHandoverTargetTracker, resolveGhostMediaHandoverTarget } from '../ghostMediaHandoverTargetTracker';
+import { parseGhostPanelMediaUrl, resolveGhostPanelMedia } from '../previewGate';
+
+const createHandler = createGhostProductionCallbacks<{
+ handler: (event: unknown, uri: unknown, purpose?: unknown, instanceId?: unknown, sourceToken?: unknown) => Promise<unknown>;
+}>({ callbacks: { handler: ['ipcMain.handle', 'ghosts:resolve-panel-media'] } });
+
+const hash = 'a'.repeat(64);
+const uri = 'cindy-ghost://helper/preview/' + hash + '.png';
+
+function harness() {
+ const root = { manifest: { id: 'helper', version: '1.0.0' }, dir: '/plugins/helper', namespace: null, approval: { state: 'approved', revision: 'root-receipt' } } as InstalledGhost;
+ const organization = { ...root, dir: '/plugins/_ns/acme/helper', namespace: 'acme', approval: { state: 'approved', revision: 'acme-receipt' } } as InstalledGhost;
+ const installed = new Map([['helper', root], ['_ns__acme__helper', organization]]);
+ const ledger = {
+ ghostCanRead: vi.fn(async (_hash: string, instanceId: string) => instanceId === '_ns__acme__helper'),
+ getBlobInfo: vi.fn(async () => ({ ext: '.png', mimeType: 'image/png' })),
+ };
+ const findAvailable = vi.fn(() => installed.size === 1 ? [...installed.values()][0] : null);
+ const { handler } = createHandler({
+ throwIpcError: (code: string, message: string) => { throw Object.assign(new Error(message), { code }); },
+ isGhostInstanceId, resolveGhostMediaHandoverTarget, parseGhostPanelMediaUrl, installedGhostStoragePart, resolveGhostPanelMedia,
+ findAvailableGhostForAuthorization: findAvailable,
+ findGhostForInstanceId: (instanceId: string) => installed.get(instanceId) ?? null,
+ ghostInstallMutationTargetFor: (instanceId: string) => installed.get(instanceId)?.approval.state === 'approved'
+ ? (installed.get(instanceId)?.approval as { revision: string }).revision : null,
+ ledger,
+ blobStore: { blobUrl: () => 'cindy-media://blobs/image.png', resolveHashRef: () => ({ absPath: '/blobs/image.png' }) },
+ fs: { promises: { stat: async () => ({ size: 42 }) } },
+ });
+ const token = ghostMediaHandoverTargetTracker.register({
+ ghostId: 'helper', instanceId: '_ns__acme__helper',
+ isCurrent: () => installed.get('_ns__acme__helper')?.approval.state === 'approved'
+ && (installed.get('_ns__acme__helper')?.approval as { revision: string }).revision === 'acme-receipt',
+ });
+ return { handler, ledger, installed, token, findAvailable };
+}
+
+describe('Registered Ghost handover through the actual media IPC handler', () => {
+ it('selects the token-bound instance, not a same-name root or URL declaration', async () => {
+ const target = harness();
+ try {
+ await expect(target.handler({}, uri, 'attach', undefined, target.token)).resolves.toMatchObject({ kind: 'image' });
+ expect(target.ledger.ghostCanRead).toHaveBeenCalledExactlyOnceWith(hash, '_ns__acme__helper');
+ expect(target.findAvailable).not.toHaveBeenCalled();
+ } finally { ghostMediaHandoverTargetTracker.revoke(target.token); }
+ });
+
+ it.each([
+ ['attach', undefined, 'unknown-token'],
+ ['menu', undefined, 'registered'],
+ ['attach', 'helper', 'registered'],
+ ['attach', undefined, ''],
+ ])('rejects %s with instance %s and token %s without a legacy fallback', async (purpose, instanceId, token) => {
+ const target = harness();
+ try {
+ await expect(target.handler({}, uri, purpose, instanceId, token === 'registered' ? target.token : token)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(target.findAvailable).not.toHaveBeenCalled();
+ expect(target.ledger.ghostCanRead).not.toHaveBeenCalled();
+ } finally { ghostMediaHandoverTargetTracker.revoke(target.token); }
+ });
+
+ it.each(['token revoked', 'same-version receipt replaced'])('cancels when %s while the ledger lookup is pending', async (change) => {
+ const target = harness();
+ let release: (granted: boolean) => void = () => {};
+ target.ledger.ghostCanRead.mockImplementation(() => new Promise<boolean>((resolve) => { release = resolve; }));
+ const pending = target.handler({}, uri, 'attach', undefined, target.token);
+ if (change === 'token revoked') ghostMediaHandoverTargetTracker.revoke(target.token);
+ else {
+ const installed = target.installed.get('_ns__acme__helper')!;
+ target.installed.set('_ns__acme__helper', { ...installed, approval: { state: 'approved', revision: 'replacement-receipt' } });
+ }
+ release(true);
+ await expect(pending).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ ghostMediaHandoverTargetTracker.revoke(target.token);
+ });
+
+ it('preserves an old root controller without instance or source token', async () => {
+ const target = harness();
+ try {
+ target.installed.delete('_ns__acme__helper');
+ target.ledger.ghostCanRead.mockResolvedValue(true);
+ await expect(target.handler({}, uri)).resolves.toMatchObject({ kind: 'image' });
+ expect(target.ledger.ghostCanRead).toHaveBeenCalledExactlyOnceWith(hash, 'helper');
+ } finally { ghostMediaHandoverTargetTracker.revoke(target.token); }
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostMediaHandoverTargetTracker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostMediaHandoverTargetTracker.test.ts
new file mode 100644
index 0000000000..d4686f000f
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostMediaHandoverTargetTracker.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { GhostMediaHandoverTargetTracker } from '../ghostMediaHandoverTargetTracker';
+import { resolveGhostPanelMedia } from '../previewGate';
+
+const hash = 'a'.repeat(64);
+const uri = 'cindy-ghost://helper/media/' + hash + '.png';
+
+describe('Ghost media handover targets', () => {
+ it.each(['media', 'preview'])('keeps same-name root and organization %s drags isolated through a cascade', async (shape) => {
+ const tracker = new GhostMediaHandoverTargetTracker();
+ const sources = ['helper', '_ns__acme__helper', '_ns__other__helper'];
+ const tokens = sources.map((instanceId) => tracker.register({ ghostId: 'helper', instanceId, isCurrent: () => true }));
+ expect(new Set(tokens).size).toBe(3);
+ const dragUri = 'cindy-ghost://helper/' + shape + '/' + hash + '.png';
+ for (const position of [1, 0, 2, 1]) {
+ const target = tracker.resolve(tokens[position], dragUri);
+ expect(target).toEqual({ ghostId: 'helper', instanceId: sources[position] });
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId === sources[position]);
+ await expect(resolveGhostPanelMedia(dragUri, 'attach', {
+ ghostCanRead,
+ getBlobInfo: async () => ({ ext: '.png', mimeType: 'image/png' }),
+ blobUrl: () => 'cindy-media://blobs/image.png',
+ blobAbsPath: () => '/blobs/image.png', statSize: async () => 42,
+ }, target!)).resolves.toMatchObject({ kind: 'image' });
+ expect(ghostCanRead).toHaveBeenCalledWith(hash, sources[position]);
+ }
+ });
+
+ it('never grants a sibling instance ledger reference', async () => {
+ const tracker = new GhostMediaHandoverTargetTracker();
+ const token = tracker.register({ ghostId: 'helper', instanceId: '_ns__acme__helper', isCurrent: () => true });
+ const target = tracker.resolve(token, uri);
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId === 'helper');
+ await expect(resolveGhostPanelMedia(uri, 'attach', {
+ ghostCanRead,
+ getBlobInfo: async () => ({ ext: '.png', mimeType: 'image/png' }),
+ blobUrl: () => 'cindy-media://blobs/image.png',
+ blobAbsPath: () => '/blobs/image.png', statSize: async () => 42,
+ }, target!)).resolves.toBeNull();
+ expect(ghostCanRead).toHaveBeenCalledExactlyOnceWith(hash, '_ns__acme__helper');
+ });
+
+ it('revokes a detached guest without revoking its same-name sibling', () => {
+ const tracker = new GhostMediaHandoverTargetTracker();
+ const root = tracker.register({ ghostId: 'helper', instanceId: 'helper', isCurrent: () => true });
+ const organization = tracker.register({ ghostId: 'helper', instanceId: '_ns__acme__helper', isCurrent: () => true });
+ tracker.revoke(organization);
+ expect(tracker.resolve(organization, uri)).toBeNull();
+ expect(tracker.resolve(root, uri)?.instanceId).toBe('helper');
+ });
+
+ it('does not revive an invalidated target when it becomes current again', () => {
+ const tracker = new GhostMediaHandoverTargetTracker();
+ let current = true;
+ const token = tracker.register({ ghostId: 'helper', instanceId: 'helper', isCurrent: () => current });
+ current = false;
+ expect(tracker.resolve(token, uri)).toBeNull();
+ current = true;
+ expect(tracker.resolve(token, uri)).toBeNull();
+ });
+
+ it('rejects unknown tokens, self-reported instances and another URL host', () => {
+ const tracker = new GhostMediaHandoverTargetTracker();
+ const token = tracker.register({ ghostId: 'helper', instanceId: '_ns__acme__helper', isCurrent: () => true });
+ for (const invalid of [undefined, null, '', '_ns__acme__helper', {}, 'a'.repeat(1024)]) {
+ expect(tracker.resolve(invalid, uri)).toBeNull();
+ }
+ expect(tracker.resolve(token, uri.replace('helper', 'other'))).toBeNull();
+ expect(tracker.resolve(token, uri + '?instanceId=helper')).toBeNull();
+ expect(tracker.resolve(token, uri)?.instanceId).toBe('_ns__acme__helper');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
index 9ec70b0136..73be5011a4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
@@ -29,6 +29,12 @@ const DECL: GhostOauthDecl = {
identity: { url: 'https://api.example.com/userinfo', labelPath: 'email' },
};
+/** §4.4: 特权不再随官方前缀默认放行,测试夹具显式授予。 */
+const FIRST_PARTY_HOST = {
+ isTokenBrokerAuthorized: () => true,
+ isHostPrimitiveAuthorized: () => true,
+} as const;
+
function memoryVault(
seed?: Record<string, string>,
): GhostOauthVault & { data: Map<string, string> } {
@@ -138,7 +144,7 @@ describe('插件 OAuth clientId 迁移', () => {
});
expect(
- mgr.expireAccountsForChangedClients(oauthManifest('old-client'), oauthManifest('new-client')),
+ mgr.expireAccountsForChangedClients(oauthManifest('old-client'), oauthManifest('new-client'), GHOST),
).toBe(1);
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
expect(mgr.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(1);
@@ -154,6 +160,33 @@ describe('插件 OAuth clientId 迁移', () => {
});
});
+ it('migrates accounts stored under a namespaced vault id', () => {
+ const vaultId = '_ns__xd__xd-feishu';
+ const vault = memoryVault();
+ vault.store(
+ vaultId,
+ `${KEY}-accounts`,
+ JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [{ id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 }],
+ }),
+ );
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+ expect(
+ mgr.expireAccountsForChangedClients(
+ oauthManifest('old-client'),
+ oauthManifest('new-client'),
+ vaultId,
+ ),
+ ).toBe(1);
+ expect(mgr.listAccounts(vaultId, KEY)[0]?.status).toBe('expired');
+ expect(mgr.listAccounts(GHOST, KEY)).toEqual([]);
+ });
+
it('clientId 未变化或用户使用自定义 clientId 时不改变账号状态', () => {
const unchangedVault = memoryVault({
[`${KEY}-accounts`]: JSON.stringify({
@@ -170,6 +203,7 @@ describe('插件 OAuth clientId 迁移', () => {
unchanged.expireAccountsForChangedClients(
oauthManifest('same-client'),
oauthManifest('same-client'),
+ GHOST,
),
).toBe(0);
expect(unchanged.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
@@ -191,6 +225,7 @@ describe('插件 OAuth clientId 迁移', () => {
customized.expireAccountsForChangedClients(
oauthManifest('old-client'),
oauthManifest('new-client'),
+ GHOST,
),
).toBe(0);
expect(customized.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
@@ -215,6 +250,7 @@ describe('插件 OAuth clientId 迁移', () => {
const rolledBack = mgr.prepareAccountsForChangedClients(
oauthManifest('old-client'),
oauthManifest('new-client'),
+ GHOST,
);
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
expect(onAccountStatusChanged).not.toHaveBeenCalled();
@@ -225,6 +261,7 @@ describe('插件 OAuth clientId 迁移', () => {
const committed = mgr.prepareAccountsForChangedClients(
oauthManifest('old-client'),
oauthManifest('new-client'),
+ GHOST,
);
committed.commit();
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
@@ -250,6 +287,7 @@ describe('插件 OAuth clientId 迁移', () => {
const migration = mgr.prepareAccountsForChangedClients(
oauthManifest('old-client'),
oauthManifest('new-client'),
+ GHOST,
);
const concurrent = JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}') as {
accounts: Array<Record<string, unknown>>;
@@ -291,11 +329,11 @@ describe('插件 OAuth clientId 迁移', () => {
onAccountStatusChanged,
});
- expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('new-client'))).toBe(0);
+ expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('new-client'), GHOST)).toBe(0);
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
- expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('third-client'))).toBe(0);
+ expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('third-client'), GHOST)).toBe(0);
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
- expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('old-client'))).toBe(1);
+ expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('old-client'), GHOST)).toBe(1);
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
expect(onAccountStatusChanged).toHaveBeenCalledWith({
ghostId: GHOST,
@@ -327,7 +365,7 @@ describe('插件 OAuth clientId 迁移', () => {
openExternal: vi.fn(),
});
- expect(mgr.reconcileAccountsForInstalledManifestWithResult(oauthManifest('old-client')))
+ expect(mgr.reconcileAccountsForInstalledManifestWithResult(oauthManifest('old-client'), GHOST))
.toEqual({ restored: 0, retryPending: true });
});
@@ -344,7 +382,7 @@ describe('插件 OAuth clientId 迁移', () => {
openExternal: vi.fn(),
});
- expect(mgr.reconcileAccountsForInstalledManifestWithResult(oauthManifest('old-client')))
+ expect(mgr.reconcileAccountsForInstalledManifestWithResult(oauthManifest('old-client'), GHOST))
.toEqual({ restored: 0, retryPending: true });
});
@@ -377,6 +415,7 @@ describe('插件 OAuth clientId 迁移', () => {
const migration = mgr.prepareAccountsForChangedClients(
oauthManifest('new-client'),
oauthManifest('old-client'),
+ GHOST,
);
const preparedAccounts = mgr.listAccounts(GHOST, KEY);
expect(preparedAccounts.find((account) => account.id === 'old-account')?.status).toBe(
@@ -421,6 +460,7 @@ describe('插件 OAuth clientId 迁移', () => {
const removed = mgr.prepareAccountsForChangedClients(
oauthManifest('client-a'),
oauthManifestWithoutBuiltinClient(),
+ GHOST,
);
removed.commit();
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
@@ -428,6 +468,7 @@ describe('插件 OAuth clientId 迁移', () => {
const restored = mgr.prepareAccountsForChangedClients(
oauthManifestWithoutBuiltinClient(),
oauthManifest('client-a'),
+ GHOST,
);
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
restored.commit();
@@ -460,6 +501,7 @@ describe('插件 OAuth clientId 迁移', () => {
const migration = mgr.prepareAccountsForChangedClients(
oauthManifest('new-client'),
oauthManifest('old-client'),
+ GHOST,
);
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
migration.rollback();
@@ -484,7 +526,7 @@ describe('插件 OAuth clientId 迁移', () => {
});
expect(() =>
- mgr.expireAccountsForChangedClients(oauthManifest('old-client'), oauthManifest('new-client')),
+ mgr.expireAccountsForChangedClients(oauthManifest('old-client'), oauthManifest('new-client'), GHOST),
).toThrow('Unable to persist OAuth client migration state');
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBe('rt-old-client');
@@ -753,6 +795,177 @@ describe('missingAuthScopes(快照推断)', () => {
});
describe('connectAccount', () => {
+ function targetConnectDeps() {
+ return {
+ vault: memoryVault(),
+ openExternal: vi.fn(autoBrowser()),
+ fetchImpl: vi.fn(async (input: string | URL | Request) => String(input) === DECL.tokenUrl
+ ? jsonResponse({ access_token: 'fake-access', refresh_token: 'fake-refresh', expires_in: 3600 })
+ : jsonResponse({ email: '[email protected]' })),
+ };
+ }
+
+ it.each([
+ ['same declaration on a replacement root instance', 'token'],
+ ['physical relocation during identity lookup', 'identity'],
+ ['approval replacement before the mutation lock', 'mutation'],
+ ['owner invalidation before the mutation lock', 'owner'],
+ ] as const)('rejects %s without committing tokens', async (_name, transition) => {
+ const ghostId = 'helper';
+ const vault = memoryVault();
+ const originalTarget = { ownerGeneration: 1, revision: 'approved-org', storagePart: ghostId };
+ let currentTarget: typeof originalTarget | null = originalTarget;
+ let insideMutationLock = false;
+ const captureConnectTarget = vi.fn(() => currentTarget);
+ const isConnectTargetCurrent = vi.fn((
+ _ghostId: string, _secretKey: string, _decl: GhostOauthDecl, expected?: unknown,
+ ) => expected === undefined || expected === currentTarget);
+ const decl = { ...DECL, clientId: 'fake-public-client' };
+ const deps = {
+ vault,
+ captureConnectTarget,
+ isConnectTargetCurrent,
+ openExternal: autoBrowser(),
+ fetchImpl: (async (input) => {
+ if (String(input) === decl.tokenUrl) {
+ if (transition === 'token') {
+ currentTarget = { ownerGeneration: 1, revision: 'approved-root', storagePart: ghostId };
+ }
+ return jsonResponse({ access_token: 'fake-org-access', refresh_token: 'fake-org-refresh', expires_in: 3600 });
+ }
+ if (transition === 'identity') {
+ currentTarget = { ownerGeneration: 1, revision: 'approved-org', storagePart: '_ns__acme__helper' };
+ }
+ return jsonResponse({ email: '[email protected]' });
+ }) as typeof fetch,
+ withMutationLock: async <Result>(_ghostId: string, task: () => Promise<Result> | Result) => {
+ insideMutationLock = true;
+ if (transition === 'mutation') {
+ currentTarget = { ownerGeneration: 1, revision: 'approved-new', storagePart: ghostId };
+ }
+ if (transition === 'owner') currentTarget = null;
+ return task();
+ },
+ };
+ const manager = new GhostOauthAccountManager(deps);
+
+ await expect(manager.connectAccount(ghostId, KEY, decl)).resolves.toMatchObject({
+ ok: false, error: 'INVALID_CONFIG',
+ });
+ expect(captureConnectTarget).toHaveBeenCalledExactlyOnceWith(ghostId);
+ expect(isConnectTargetCurrent).toHaveBeenLastCalledWith(ghostId, KEY, decl, originalTarget);
+ expect(insideMutationLock).toBe(transition !== 'token');
+ expect(vault.data.size).toBe(0);
+ expect(manager.listAccounts(ghostId, KEY)).toHaveLength(0);
+ await expect(manager.getFreshAccessToken(ghostId, KEY, decl)).resolves.toMatchObject({
+ ok: false, error: 'NO_ACCOUNT',
+ });
+ });
+
+ it.each([
+ { revision: 'legacy-approval', storagePart: 'helper' },
+ { namespace: null, revision: 'root-approval', storagePart: '_root__helper' },
+ { namespace: 'acme', revision: 'relocated-approval', storagePart: '_ns__acme__helper' },
+ ])('keeps an unchanged approved target usable: $revision', async (target) => {
+ let insideMutationLock = false;
+ const captureConnectTarget = vi.fn(() => target);
+ const isConnectTargetCurrent = vi.fn((
+ _ghostId: string, _secretKey: string, _decl: GhostOauthDecl, expected?: unknown,
+ ) => expected === undefined || expected === target);
+ const decl = { ...DECL, clientId: 'fake-public-client' };
+ const deps = {
+ ...targetConnectDeps(), captureConnectTarget, isConnectTargetCurrent,
+ withMutationLock: async <Result>(_ghostId: string, task: () => Promise<Result> | Result) => {
+ insideMutationLock = true;
+ return task();
+ },
+ };
+ const manager = new GhostOauthAccountManager(deps);
+ const result = await manager.connectAccount(target.storagePart, KEY, decl);
+
+ expect(result.ok).toBe(true);
+ expect(captureConnectTarget).toHaveBeenCalledExactlyOnceWith(target.storagePart);
+ expect(isConnectTargetCurrent).toHaveBeenLastCalledWith(target.storagePart, KEY, decl, target);
+ expect(insideMutationLock).toBe(true);
+ expect(manager.listAccounts(target.storagePart, KEY)).toHaveLength(1);
+ if (!result.ok) throw new Error('Expected the unchanged target to connect');
+ expect(deps.vault.read(target.storagePart, KEY + '-rt-' + result.account.id)).toBe('fake-refresh');
+ const fetchCount = deps.fetchImpl.mock.calls.length;
+ await expect(manager.getFreshAccessToken(target.storagePart, KEY, decl)).resolves.toMatchObject({
+ ok: true, accessToken: 'fake-access',
+ });
+ expect(deps.fetchImpl).toHaveBeenCalledTimes(fetchCount);
+ });
+
+ it.each([null, undefined])('refuses an unavailable captured target (%s) before authorization', async (target) => {
+ const deps = {
+ ...targetConnectDeps(),
+ captureConnectTarget: () => target,
+ isConnectTargetCurrent: () => true,
+ };
+ const manager = new GhostOauthAccountManager(deps);
+ await expect(manager.connectAccount('helper', KEY, { ...DECL, clientId: 'fake-client' })).resolves.toMatchObject({
+ ok: false, error: 'INVALID_CONFIG',
+ });
+ expect(deps.openExternal).not.toHaveBeenCalled();
+ expect(deps.fetchImpl).not.toHaveBeenCalled();
+ expect(deps.vault.data.size).toBe(0);
+ });
+
+ it('does not recapture a replacement instance when the endpoint provides its original target', async () => {
+ const originalTarget = { revision: 'approved-org', storagePart: 'helper' };
+ const replacementTarget = { revision: 'approved-root', storagePart: 'helper' };
+ const captureConnectTarget = vi.fn(() => replacementTarget);
+ const deps = {
+ ...targetConnectDeps(), captureConnectTarget,
+ isConnectTargetCurrent: (
+ _ghostId: string, _secretKey: string, _decl: GhostOauthDecl, expected?: unknown,
+ ) => expected === replacementTarget,
+ };
+ const manager = new GhostOauthAccountManager(deps);
+ await expect(manager.connectAccount('helper', KEY, { ...DECL, clientId: 'fake-client' }, {
+ expectedConnectTarget: originalTarget,
+ })).resolves.toMatchObject({ ok: false, error: 'INVALID_CONFIG' });
+ expect(captureConnectTarget).not.toHaveBeenCalled();
+ expect(deps.openExternal).not.toHaveBeenCalled();
+ expect(deps.vault.data.size).toBe(0);
+ });
+
+ it('fails closed when a captured target has no lifecycle verifier', async () => {
+ const deps = {
+ ...targetConnectDeps(),
+ captureConnectTarget: () => ({ revision: 'approved-org' }),
+ };
+ const manager = new GhostOauthAccountManager(deps);
+ await expect(manager.connectAccount('helper', KEY, { ...DECL, clientId: 'fake-client' })).resolves.toMatchObject({
+ ok: false, error: 'INVALID_CONFIG',
+ });
+ expect(deps.openExternal).not.toHaveBeenCalled();
+ expect(deps.vault.data.size).toBe(0);
+ });
+
+ it('keeps refresh token comparison independent of connect target capture', async () => {
+ const vault = seededVault();
+ const captureConnectTarget = vi.fn(() => null);
+ const isConnectTargetCurrent = vi.fn(() => true);
+ const fetchImpl = vi.fn(async () => {
+ vault.remove(GHOST, KEY + '-rt-acc-1');
+ return jsonResponse({ access_token: 'fake-stale-access', refresh_token: 'fake-stale-refresh', expires_in: 3600 });
+ });
+ const deps = {
+ vault, captureConnectTarget, isConnectTargetCurrent,
+ openExternal: vi.fn(), fetchImpl: fetchImpl as unknown as typeof fetch,
+ };
+ const manager = new GhostOauthAccountManager(deps);
+ await expect(manager.getFreshAccessToken(GHOST, KEY, DECL)).resolves.toMatchObject({
+ ok: false, error: 'AUTH_EXPIRED',
+ });
+ expect(captureConnectTarget).not.toHaveBeenCalled();
+ expect(isConnectTargetCurrent).toHaveBeenCalledWith(GHOST, KEY, DECL);
+ expect(vault.read(GHOST, KEY + '-rt-acc-1')).toBeNull();
+ expect([...vault.data.values()]).not.toContain('fake-stale-refresh');
+ });
+
it.each(['boundary', 'policy'] as const)('does not commit OAuth tokens when %s becomes invalid during identity lookup', async (reason) => {
const vault = memoryVault({ [`${KEY}-client-id`]: 'cid' });
const before = new Map(vault.data);
@@ -791,21 +1004,22 @@ describe('connectAccount', () => {
redirectPort: heldPort,
};
const reclaimPort = vi.fn(async () => false);
- const mkMgr = (): GhostOauthAccountManager =>
+ const mkMgr = (hostPrimitive: boolean): GhostOauthAccountManager =>
new GhostOauthAccountManager({
vault: memoryVault(),
fetchImpl: vi.fn() as unknown as typeof fetch,
openExternal: vi.fn(),
reclaimPort,
+ isHostPrimitiveAuthorized: () => hostPrimitive,
});
// 第三方 id:门控挡住,占用直接报错,回收器(杀进程)绝不能被调用。
- await expect(mkMgr().connectAccount('evil-tools', KEY, decl)).resolves.toMatchObject({
+ await expect(mkMgr(false).connectAccount('evil-tools', KEY, decl)).resolves.toMatchObject({
ok: false,
error: 'LISTEN_FAILED',
});
expect(reclaimPort).not.toHaveBeenCalled();
- // 官方前缀 id:回收器放行被调用(此处回收失败仍 LISTEN_FAILED,只验门控)。
- await expect(mkMgr().connectAccount('cindy-google', KEY, decl)).resolves.toMatchObject({
+ // 经第一方宿主原语授权后才调用回收器(此处回收失败仍 LISTEN_FAILED,只验门控)。
+ await expect(mkMgr(true).connectAccount('cindy-google', KEY, decl)).resolves.toMatchObject({
ok: false,
error: 'LISTEN_FAILED',
});
@@ -934,6 +1148,7 @@ describe('connectAccount', () => {
vault,
fetchImpl: fetchImpl as unknown as typeof fetch,
openExternal: autoBrowser(),
+ ...FIRST_PARTY_HOST,
});
const result = await mgr.connectAccount(GHOST, KEY, avatarDecl);
@@ -1014,6 +1229,7 @@ describe('connectAccount', () => {
vault: memoryVault({ [`${KEY}-client-id`]: 'cid' }),
fetchImpl: fetchImpl as unknown as typeof fetch,
openExternal: autoBrowser(),
+ ...FIRST_PARTY_HOST,
});
const result = await mgr.connectAccount(GHOST, KEY, avatarDecl);
expect(result.ok).toBe(true);
@@ -1257,6 +1473,154 @@ describe('connectAccount', () => {
});
});
+describe('invalidateGhost', () => {
+ it.each(['success', 'invalid-grant', 'missing-token'] as const)('blocks stale %s mutations after waiting for the OAuth lock', async (outcome) => {
+ const vault = seededVault('fake-same-refresh');
+ if (outcome === 'missing-token') vault.remove(GHOST, KEY + '-rt-acc-1');
+ const before = new Map(vault.data);
+ const manager: GhostOauthAccountManager = new GhostOauthAccountManager({
+ vault, openExternal: vi.fn(), sleep: instantSleep,
+ fetchImpl: vi.fn(async () => outcome === 'success'
+ ? jsonResponse({ access_token: 'fake-stale-access', refresh_token: 'fake-stale-rotated', expires_in: 3600 })
+ : jsonResponse({ error: 'invalid_grant' }, 400)) as unknown as typeof fetch,
+ withMutationLock: async (_ghostId, task) => {
+ manager.invalidateGhost(GHOST);
+ return task();
+ },
+ });
+ await expect(manager.getFreshAccessToken(GHOST, KEY, DECL)).resolves.toMatchObject({
+ ok: false, error: 'AUTH_EXPIRED',
+ });
+ expect(vault.data).toEqual(before);
+ });
+
+ it('does not write old asynchronous identity backfill into restored credentials', async () => {
+ const vault = seededVault('fake-same-refresh');
+ const before = new Map(vault.data);
+ let releaseIdentity!: (response: Response) => void;
+ const identityResponse = new Promise<Response>((resolve) => { releaseIdentity = resolve; });
+ const fetchImpl = vi.fn(async (input: string | URL | Request) => String(input) === DECL.tokenUrl
+ ? jsonResponse({ access_token: 'fake-access', expires_in: 3600 })
+ : identityResponse);
+ const manager = new GhostOauthAccountManager({
+ vault, openExternal: vi.fn(), fetchImpl: fetchImpl as typeof fetch,
+ });
+ const backfillTarget = manager as unknown as {
+ backfillIdentityExtras: (...parameters: unknown[]) => Promise<void>;
+ };
+ const runBackfill = backfillTarget.backfillIdentityExtras.bind(manager);
+ let backfillTask: Promise<void> | null = null;
+ vi.spyOn(backfillTarget, 'backfillIdentityExtras').mockImplementation((...parameters) => {
+ backfillTask = runBackfill(...parameters);
+ return backfillTask;
+ });
+ const decl = { ...DECL, identity: { ...DECL.identity!, displayTemplate: '{email}' } };
+ await expect(manager.getFreshAccessToken(GHOST, KEY, decl)).resolves.toMatchObject({ ok: true });
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ expect(backfillTask).not.toBeNull();
+ manager.invalidateGhost(GHOST);
+ releaseIdentity(jsonResponse({ email: '[email protected]' }));
+ await backfillTask;
+ expect(vault.data).toEqual(before);
+ });
+
+ it.each(['token', 'identity', 'mutation'] as const)('retires a connect during %s and permits a fresh connect after rollback', async (transition) => {
+ const vault = memoryVault();
+ const target = { revision: 'approved-original' };
+ const decl = { ...DECL, clientId: 'fake-client' };
+ let shouldInvalidate = true;
+ const manager: GhostOauthAccountManager = new GhostOauthAccountManager({
+ vault, openExternal: autoBrowser(), captureConnectTarget: () => target,
+ isConnectTargetCurrent: () => true,
+ fetchImpl: (async (input) => {
+ const tokenRequest = String(input) === decl.tokenUrl;
+ if (shouldInvalidate && transition === (tokenRequest ? 'token' : 'identity')) {
+ manager.invalidateGhost?.(GHOST);
+ }
+ return tokenRequest
+ ? jsonResponse({ access_token: 'fake-access', refresh_token: 'fake-refresh', expires_in: 3600 })
+ : jsonResponse({ email: '[email protected]' });
+ }) as typeof fetch,
+ withMutationLock: async (_ghostId, task) => {
+ if (shouldInvalidate && transition === 'mutation') manager.invalidateGhost?.(GHOST);
+ return task();
+ },
+ });
+ await expect(manager.connectAccount(GHOST, KEY, decl)).resolves.toMatchObject({
+ ok: false, error: 'INVALID_CONFIG',
+ });
+ expect(vault.data.size).toBe(0);
+ shouldInvalidate = false;
+ await expect(manager.connectAccount(GHOST, KEY, decl)).resolves.toMatchObject({ ok: true });
+ expect(manager.listAccounts(GHOST, KEY)).toHaveLength(1);
+ });
+
+ it('clears only the invalidated ghost cache even when restored credentials are identical', async () => {
+ const vault = seededVault('fake-same-refresh');
+ const otherGhostId = '_ns__acme__' + GHOST;
+ for (const [key, value] of [...vault.data]) {
+ vault.data.set(otherGhostId + key.slice(GHOST.length), value);
+ }
+ let fetchCount = 0;
+ const fetchImpl = vi.fn(async () => {
+ fetchCount += 1;
+ return jsonResponse({ access_token: 'fake-access-' + fetchCount, expires_in: 3600 });
+ });
+ const manager = new GhostOauthAccountManager({
+ vault, openExternal: vi.fn(), fetchImpl: fetchImpl as unknown as typeof fetch,
+ });
+ await expect(manager.getFreshAccessToken(GHOST, KEY, DECL)).resolves.toMatchObject({ accessToken: 'fake-access-1' });
+ await expect(manager.getFreshAccessToken(otherGhostId, KEY, DECL)).resolves.toMatchObject({ accessToken: 'fake-access-2' });
+ manager.invalidateGhost?.(GHOST);
+ await expect(manager.getFreshAccessToken(otherGhostId, KEY, DECL)).resolves.toMatchObject({ accessToken: 'fake-access-2' });
+ await expect(manager.getFreshAccessToken(GHOST, KEY, DECL)).resolves.toMatchObject({ accessToken: 'fake-access-3' });
+ expect(fetchImpl).toHaveBeenCalledTimes(3);
+ });
+
+ it('rejects an old refresh with an identical token and does not delete the new generation single flight', async () => {
+ const vault = seededVault('fake-same-refresh');
+ let releaseOld!: (response: Response) => void;
+ let releaseNew!: (response: Response) => void;
+ const oldResponse = new Promise<Response>((resolve) => { releaseOld = resolve; });
+ const newResponse = new Promise<Response>((resolve) => { releaseNew = resolve; });
+ const fetchImpl = vi.fn().mockReturnValueOnce(oldResponse).mockReturnValueOnce(newResponse);
+ const manager = new GhostOauthAccountManager({
+ vault, openExternal: vi.fn(), fetchImpl: fetchImpl as unknown as typeof fetch,
+ });
+ const oldFlow = manager.getFreshAccessToken(GHOST, KEY, DECL);
+ manager.invalidateGhost?.(GHOST);
+ const newFlow = manager.getFreshAccessToken(GHOST, KEY, DECL);
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ releaseOld(jsonResponse({ access_token: 'fake-old-access', refresh_token: 'fake-old-rotated', expires_in: 3600 }));
+ await expect(oldFlow).resolves.toMatchObject({ ok: false, error: 'AUTH_EXPIRED' });
+ expect(vault.read(GHOST, KEY + '-rt-acc-1')).toBe('fake-same-refresh');
+ const joinedNewFlow = manager.getFreshAccessToken(GHOST, KEY, DECL);
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ releaseNew(jsonResponse({ access_token: 'fake-new-access', refresh_token: 'fake-new-rotated', expires_in: 3600 }));
+ await expect(newFlow).resolves.toMatchObject({ ok: true, accessToken: 'fake-new-access' });
+ await expect(joinedNewFlow).resolves.toMatchObject({ ok: true, accessToken: 'fake-new-access' });
+ expect(vault.read(GHOST, KEY + '-rt-acc-1')).toBe('fake-new-rotated');
+ });
+
+ it('does not delete or expire restored credentials after an old invalid_grant', async () => {
+ const vault = seededVault('fake-same-refresh');
+ const before = new Map(vault.data);
+ let releaseOld!: (response: Response) => void;
+ const response = new Promise<Response>((resolve) => { releaseOld = resolve; });
+ const onAccountStatusChanged = vi.fn();
+ const manager = new GhostOauthAccountManager({
+ vault, openExternal: vi.fn(), sleep: instantSleep, onAccountStatusChanged,
+ fetchImpl: vi.fn(() => response) as unknown as typeof fetch,
+ });
+ const oldFlow = manager.getFreshAccessToken(GHOST, KEY, DECL);
+ manager.invalidateGhost?.(GHOST);
+ releaseOld(jsonResponse({ error: 'invalid_grant' }, 400));
+ await expect(oldFlow).resolves.toMatchObject({ ok: false, error: 'AUTH_EXPIRED' });
+ expect(vault.data).toEqual(before);
+ expect(onAccountStatusChanged).not.toHaveBeenCalled();
+ });
+});
+
describe('内置 client 回落链', () => {
const BAKED: GhostOauthDecl = { ...DECL, clientId: 'baked-cid', clientSecret: 'baked-sec' };
@@ -1637,6 +2001,7 @@ describe('多实例共库的 RT 轮换竞态(invalid_grant 防误删)', () => {
openExternal: vi.fn(),
broker: { exchange: vi.fn(), refresh },
sleep: instantSleep,
+ ...FIRST_PARTY_HOST,
});
const brokerDecl: GhostOauthDecl = {
authorizeUrl: 'https://auth.example.com/authorize',
@@ -1769,6 +2134,7 @@ describe('tokenBroker 模式', () => {
autoBrowser('c-bk')(url);
},
broker: { exchange, refresh: vi.fn() },
+ ...FIRST_PARTY_HOST,
});
const result = await mgr.connectAccount(GHOST, KEY, BROKER_DECL);
@@ -1780,6 +2146,21 @@ describe('tokenBroker 模式', () => {
expect(fetchImpl.mock.calls.map((c) => String(c[0]))).not.toContain(BROKER_DECL.tokenUrl);
});
+ it('connect: missing first-party grant denies even an official-looking id', async () => {
+ const openExternal = vi.fn();
+ const mgr = new GhostOauthAccountManager({
+ vault: memoryVault(),
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal,
+ broker: { exchange: vi.fn(), refresh: vi.fn() },
+ });
+ await expect(mgr.connectAccount(GHOST, KEY, BROKER_DECL)).resolves.toMatchObject({
+ ok: false,
+ error: 'BROKER_FORBIDDEN',
+ });
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+
it('clientConfigured:brokered + 内置 clientId 恒 true,与保险库无关', () => {
const mgr = new GhostOauthAccountManager({
vault: memoryVault(),
@@ -1812,6 +2193,7 @@ describe('tokenBroker 模式', () => {
})),
refresh: vi.fn(),
},
+ ...FIRST_PARTY_HOST,
});
await expect(
mgr.connectAccount(GHOST, KEY, BROKER_DECL, { clientId: 'global-cid' }),
@@ -1824,6 +2206,7 @@ describe('tokenBroker 模式', () => {
fetchImpl: vi.fn() as unknown as typeof fetch,
openExternal: blockedOpenExternal,
broker: { exchange: vi.fn(), refresh: vi.fn() },
+ ...FIRST_PARTY_HOST,
});
await expect(
blocked.connectAccount(GHOST, KEY, BROKER_DECL, { clientId: 'foreign-cid' }),
@@ -1851,6 +2234,7 @@ describe('tokenBroker 模式', () => {
openExternal: vi.fn(),
broker: { exchange: vi.fn(), refresh },
sleep: instantSleep,
+ ...FIRST_PARTY_HOST,
});
await expect(mgr.getFreshAccessToken(GHOST, KEY, BROKER_DECL)).resolves.toMatchObject({
ok: false,
@@ -1943,6 +2327,7 @@ describe('brokerBounce(双地址弹跳回调)', () => {
fetchImpl: vi.fn() as unknown as typeof fetch,
openExternal: openExternal1,
broker: { exchange: vi.fn(), refresh: vi.fn() },
+ ...FIRST_PARTY_HOST,
});
await expect(
mgrNoResolver.connectAccount(GHOST, KEY, bounceDecl(53699)),
@@ -1960,6 +2345,7 @@ describe('brokerBounce(双地址弹跳回调)', () => {
openExternal: openExternal2,
broker: { exchange: vi.fn(), refresh: vi.fn() },
resolveBrokerPublicUrl: vi.fn(() => null),
+ ...FIRST_PARTY_HOST,
});
await expect(
mgrNullResolver.connectAccount(GHOST, KEY, bounceDecl(53699)),
@@ -2014,6 +2400,7 @@ describe('brokerBounce(双地址弹跳回调)', () => {
},
broker: { exchange, refresh: vi.fn() },
resolveBrokerPublicUrl,
+ ...FIRST_PARTY_HOST,
});
const result = await mgr.connectAccount(GHOST, KEY, bounceDecl(freePort));
expect(result).toMatchObject({ ok: true });
@@ -2335,6 +2722,7 @@ describe('identity.avatarPath 头像回填', () => {
vault,
fetchImpl: avatarFetch() as unknown as typeof fetch,
openExternal: vi.fn(),
+ ...FIRST_PARTY_HOST,
});
await expect(mgr.getFreshAccessToken(GHOST, KEY, AVATAR_DECL)).resolves.toMatchObject({
ok: true,
@@ -2419,6 +2807,7 @@ describe('identity.avatarPath 头像回填', () => {
vault,
fetchImpl: fetchImpl as unknown as typeof fetch,
openExternal: vi.fn(),
+ ...FIRST_PARTY_HOST,
});
await expect(mgr.getFreshAccessToken(GHOST, KEY, AVATAR_DECL)).resolves.toMatchObject({
ok: true,
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostPreferenceRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostPreferenceRelocation.test.ts
new file mode 100644
index 0000000000..eed3ae22a1
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostPreferenceRelocation.test.ts
@@ -0,0 +1,345 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const owner = vi.hoisted(() => ({ root: '', id: 'owner-a', generation: 1, pending: false }));
+
+vi.mock('../../appSessionState.js', () => ({
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(owner.root, owner.id, ...parts),
+ activeOwnerScopeKey: () => `${owner.id}:${owner.generation}`,
+ isAppSessionBoundaryPending: () => owner.pending,
+}));
+vi.mock('../../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: { child: () => ({ info: vi.fn(), warn: vi.fn() }) },
+}));
+
+import * as locks from '../../device-link/crossProcessLock.js';
+import {
+ relocateGhostCindyPrefs, readGhostCindyOverrides, readGhostCindyInflightLimit,
+ writeGhostCindyOverride, writeGhostCindyInflightLimit,
+} from '../cindyPrefsStore.js';
+import {
+ relocateGhostErrandPrefs, readPluginTaskConfig, readGhostErrandSessionId,
+ writePluginTaskConfig, writeGhostErrandSessionId,
+} from '../pluginTaskPrefsStore.js';
+import { relocateGhostPickedDirs, isGhostPickedDir, recordGhostPickedDir } from '../pickGrantsStore.js';
+import { relocateGhostUnread, readGhostUnread, markGhostUnread, clearGhostUnread } from '../ghostUnreadStore.js';
+import { updateGhostPrefsForRelocation } from '../ghostPreferenceRelocation.js';
+
+const from = 'helper';
+const to = '_ns__acme__helper';
+const resources = [
+ {
+ name: 'Cindy overrides and limits',
+ file: 'ghost-cindy-prefs.json',
+ relocate: relocateGhostCindyPrefs,
+ source: { overrides: { [from]: { 'image.generate': 'model', future: { value: 1 } } }, inflightLimits: { [from]: 2 } },
+ destination: { overrides: { [to]: { 'image.generate': 'model', future: { value: 1 } } }, inflightLimits: { [to]: 2 } },
+ collision: { overrides: { [from]: { 'image.generate': 'model' } }, inflightLimits: { [to]: 3 } },
+ invalid: { overrides: [] },
+ },
+ {
+ name: 'errand configuration and all session keys',
+ file: 'ghost-errand-prefs.json',
+ relocate: relocateGhostErrandPrefs,
+ source: {
+ errand: { [from]: { permissionMode: 'acceptEdits', workingDir: '/project', future: true } },
+ sessions: { [from]: 'shared-session', [`${from}#daily`]: 'daily-session', 'helper-other#daily': 'other-session' },
+ },
+ destination: {
+ errand: { [to]: { permissionMode: 'acceptEdits', workingDir: '/project', future: true } },
+ sessions: { [to]: 'shared-session', [`${to}#daily`]: 'daily-session', 'helper-other#daily': 'other-session' },
+ },
+ collision: { errand: { [from]: { permissionMode: 'auto' } }, sessions: { [`${to}#other`]: 'other-session' } },
+ invalid: { sessions: null },
+ },
+ {
+ name: 'picked directory grants',
+ file: 'ghost-pick-grants.json',
+ relocate: relocateGhostPickedDirs,
+ source: { grants: { [from]: ['/project'], unrelated: ['/other'] } },
+ destination: { grants: { [to]: ['/project'], unrelated: ['/other'] } },
+ collision: { grants: { [from]: ['/project'], [to]: ['/project'] } },
+ invalid: { grants: 'unreadable' },
+ },
+ {
+ name: 'unread entries',
+ file: 'ghost-unread.json',
+ relocate: relocateGhostUnread,
+ source: { entries: { [from]: { summary: 'new activity', at: 100, future: true } } },
+ destination: { entries: { [to]: { summary: 'new activity', at: 100, future: true } } },
+ collision: { entries: { [from]: { at: 100 }, [to]: { at: 100 } } },
+ invalid: { entries: [] },
+ },
+];
+
+function write(file: string, value: unknown, ownerId = owner.id): string {
+ const target = path.join(owner.root, ownerId, file);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(value));
+ return target;
+}
+
+const writers = [
+ {
+ name: 'Cindy override', resource: resources[0],
+ prime: () => readGhostCindyOverrides(from),
+ write: (id: string) => writeGhostCindyOverride(id, 'image.generate', 'next-model'),
+ },
+ {
+ name: 'Cindy limit', resource: resources[0],
+ prime: () => readGhostCindyInflightLimit(from),
+ write: (id: string) => writeGhostCindyInflightLimit(id, 4),
+ },
+ {
+ name: 'errand config', resource: resources[1],
+ prime: () => readPluginTaskConfig(from),
+ write: (id: string) => writePluginTaskConfig(id, { permissionMode: 'auto' }),
+ },
+ ...[undefined, 'daily'].map((sessionKey) => ({
+ name: 'errand session ' + (sessionKey ?? 'shared'), resource: resources[1],
+ prime: () => readGhostErrandSessionId(from, sessionKey),
+ write: (id: string) => writeGhostErrandSessionId(id, 'next-session', sessionKey),
+ })),
+ {
+ name: 'picked directory', resource: resources[2],
+ prime: () => isGhostPickedDir(from, '/project'),
+ write: (id: string) => recordGhostPickedDir(id, '/next-project'),
+ },
+ {
+ name: 'unread mark', resource: resources[3],
+ prime: () => readGhostUnread(from),
+ write: (id: string) => markGhostUnread(id, 'next activity', 200),
+ },
+ {
+ name: 'unread clear', resource: resources[3],
+ prime: () => readGhostUnread(from),
+ write: (id: string) => clearGhostUnread(id),
+ },
+];
+
+describe.each(writers)('$name relocation write gate', ({ resource, prime, write: mutate }) => {
+ it.each([from, 'another-plugin'])('blocks %s during actual lock release, even with unchanged mtime', async (id) => {
+ const file = write(resource.file, resource.source);
+ const time = new Date('2000-01-01T00:00:00Z');
+ fs.utimesSync(file, time, time);
+ prime();
+ const rename = fs.promises.rename;
+ let attempted = false;
+ let failure: unknown;
+ vi.spyOn(fs.promises, 'rename').mockImplementation(async (source, destination) => {
+ if (String(source) === file + '.lock' && String(destination).startsWith(file + '.lock.release-')) {
+ attempted = true;
+ fs.utimesSync(file, time, time);
+ try { mutate(id); } catch (error) { failure = error; }
+ }
+ await rename(source, destination);
+ });
+ await resource.relocate(from, to);
+ expect(attempted).toBe(true);
+ expect(failure).toBeInstanceOf(Error);
+ expect((failure as Error).message).toMatch(/relocating/);
+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual(resource.destination);
+ expect(() => mutate('another-plugin')).not.toThrow();
+ const contents = fs.readFileSync(file, 'utf8');
+ expect(contents).not.toContain('"' + from + '"');
+ expect(contents).toContain('"' + to + '"');
+ });
+
+ it.each(['write', 'release'])('recovers after a %s failure and refreshes caches before unblocking', async (stage) => {
+ const file = write(resource.file, resource.source);
+ const time = new Date('2000-01-01T00:00:00Z');
+ fs.utimesSync(file, time, time);
+ prime();
+ if (stage === 'write') {
+ const rename = fs.renameSync;
+ vi.spyOn(fs, 'renameSync').mockImplementation((source, destination) => {
+ if (String(destination) === file) throw new Error('simulated write failure');
+ rename(source, destination);
+ });
+ } else {
+ const withLock = locks.withCrossProcessLock;
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (target, options, task, signal) => {
+ await withLock(target, options, task, signal);
+ fs.utimesSync(file, time, time);
+ throw new Error('simulated release failure');
+ });
+ }
+ await expect(resource.relocate(from, to)).rejects.toThrow('simulated ' + stage + ' failure');
+ vi.restoreAllMocks();
+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual(stage === 'write' ? resource.source : resource.destination);
+ expect(() => mutate('another-plugin')).not.toThrow();
+ if (stage === 'release') {
+ const committed = fs.readFileSync(file, 'utf8');
+ expect(committed).not.toContain('"' + from + '"');
+ expect(committed).toContain('"' + to + '"');
+ }
+ await resource.relocate(from, to);
+ const contents = fs.readFileSync(file, 'utf8');
+ expect(contents).not.toContain('"' + from + '"');
+ expect(contents).toContain('"' + to + '"');
+ });
+
+ it('allows another owner to write during release without changing the relocating owner', async () => {
+ const file = write(resource.file, resource.source);
+ const otherFile = write(resource.file, resource.source, 'owner-b');
+ prime();
+ const withLock = locks.withCrossProcessLock;
+ let attempted = false;
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (target, options, task, signal) => {
+ const result = await withLock(target, options, task, signal);
+ owner.id = 'owner-b';
+ try {
+ mutate(from);
+ attempted = true;
+ } finally {
+ owner.id = 'owner-a';
+ }
+ return result;
+ });
+ await resource.relocate(from, to);
+ expect(attempted).toBe(true);
+ expect(fs.existsSync(otherFile)).toBe(true);
+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual(resource.destination);
+ expect(() => mutate('another-plugin')).not.toThrow();
+ });
+});
+
+it('keeps the gate through cache reset, rejects overlap, and clears it if the callback fails', async () => {
+ write('ghost-cindy-prefs.json', resources[0].source);
+ const reset = vi.fn(() => {
+ expect(() => writeGhostCindyInflightLimit(from, 4)).toThrow(/relocating/);
+ throw new Error('simulated cache reset failure');
+ });
+ const withLock = locks.withCrossProcessLock;
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (target, options, task, signal) => {
+ await expect(relocateGhostCindyPrefs(from, to)).rejects.toThrow(/relocating/);
+ expect(() => writeGhostCindyInflightLimit(from, 4)).toThrow(/relocating/);
+ expect(() => writeGhostErrandSessionId(from, 'other-file-session')).not.toThrow();
+ return withLock(target, options, task, signal);
+ });
+ await expect(updateGhostPrefsForRelocation('ghost-cindy-prefs.json', () => ({}), reset))
+ .rejects.toThrow(/simulated cache reset failure/);
+ expect(reset).toHaveBeenCalledOnce();
+ expect(() => writeGhostCindyInflightLimit(from, 4)).not.toThrow();
+ await relocateGhostCindyPrefs(from, to);
+});
+
+beforeEach(() => {
+ owner.root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-prefs-relocation-'));
+ owner.id = 'owner-a';
+ owner.generation = 1;
+ owner.pending = false;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ fs.rmSync(owner.root, { recursive: true, force: true });
+});
+
+describe.each(resources)('$name relocation', (resource) => {
+ it('moves the complete identity, preserves unknown fields, replays and reverses', async () => {
+ const extra = { futureTopLevel: { enabled: true } };
+ const file = write(resource.file, { ...resource.source, ...extra });
+ await resource.relocate(from, to);
+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual({ ...resource.destination, ...extra });
+ await resource.relocate(from, to);
+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual({ ...resource.destination, ...extra });
+ await resource.relocate(to, from);
+ await resource.relocate(to, from);
+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual({ ...resource.source, ...extra });
+ });
+
+ it('refuses a destination collision without merging identities or grants', async () => {
+ const file = write(resource.file, resource.collision);
+ const before = fs.readFileSync(file, 'utf8');
+ await expect(resource.relocate(from, to)).rejects.toThrow(/collision/);
+ expect(fs.readFileSync(file, 'utf8')).toBe(before);
+ });
+
+ it.each(['{invalid json', '[]'])('preserves an unreadable document: %s', async (contents) => {
+ const file = write(resource.file, {});
+ fs.writeFileSync(file, contents);
+ await expect(resource.relocate(from, to)).rejects.toThrow(/unreadable/);
+ expect(fs.readFileSync(file, 'utf8')).toBe(contents);
+ });
+
+ it('refuses a malformed identity map', async () => {
+ const file = write(resource.file, resource.invalid);
+ const before = fs.readFileSync(file, 'utf8');
+ await expect(resource.relocate(from, to)).rejects.toThrow(/unreadable/);
+ expect(fs.readFileSync(file, 'utf8')).toBe(before);
+ });
+
+ it('does not mutate another owner or recreate absent data', async () => {
+ const otherFile = write(resource.file, resource.source, 'owner-b');
+ const before = fs.readFileSync(otherFile, 'utf8');
+ await resource.relocate(from, to);
+ expect(fs.readFileSync(otherFile, 'utf8')).toBe(before);
+ expect(fs.existsSync(path.join(owner.root, owner.id, resource.file))).toBe(false);
+ });
+
+ it('rejects owner generation changes while acquiring the write lock', async () => {
+ const file = write(resource.file, resource.source);
+ const before = fs.readFileSync(file, 'utf8');
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (_file, _options, task) => {
+ owner.generation += 1;
+ return task({ held: true });
+ });
+ await expect(resource.relocate(from, to)).rejects.toThrow(/scope changed/);
+ expect(fs.readFileSync(file, 'utf8')).toBe(before);
+ });
+
+ it('does not write when the lock is unavailable', async () => {
+ const file = write(resource.file, resource.source);
+ const before = fs.readFileSync(file, 'utf8');
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (_file, _options, task) =>
+ task({ held: false, reason: 'unavailable' }),
+ );
+ await expect(resource.relocate(from, to)).rejects.toThrow(/busy/);
+ expect(fs.readFileSync(file, 'utf8')).toBe(before);
+ });
+});
+
+describe.each([
+ {
+ resource: resources[0],
+ read: (id: string) => [readGhostCindyOverrides(id), readGhostCindyInflightLimit(id)],
+ empty: [{}, null],
+ },
+ {
+ resource: resources[1],
+ read: (id: string) => [readPluginTaskConfig(id), readGhostErrandSessionId(id), readGhostErrandSessionId(id, 'daily')],
+ empty: [{}, null, null],
+ },
+ {
+ resource: resources[2],
+ read: (id: string) => isGhostPickedDir(id, '/project'),
+ empty: false,
+ },
+ {
+ resource: resources[3],
+ read: (id: string) => {
+ const entry = readGhostUnread(id);
+ return entry ? { summary: entry.summary, at: entry.at } : null;
+ },
+ empty: null,
+ },
+])('$resource.name live reader', ({ resource, read, empty }) => {
+ it('does not expose the old identity even when the replacement has the same mtime', async () => {
+ const file = write(resource.file, resource.source);
+ const time = new Date('2026-09-01T00:00:00Z');
+ fs.utimesSync(file, time, time);
+ const previous = read(from);
+ expect(previous).not.toEqual(empty);
+ await resource.relocate(from, to);
+ fs.utimesSync(file, time, time);
+ expect(read(from)).toEqual(empty);
+ expect(read(to)).toEqual(previous);
+ await resource.relocate(to, from);
+ fs.utimesSync(file, time, time);
+ expect(read(to)).toEqual(empty);
+ expect(read(from)).toEqual(previous);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostProductionCallbacksFixture.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostProductionCallbacksFixture.ts
new file mode 100644
index 0000000000..7936233d8c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostProductionCallbacksFixture.ts
@@ -0,0 +1,70 @@
+import fs from 'node:fs';
+import ts from 'typescript';
+import {
+ installedGhostPhysicalRelId,
+ installedGhostStoragePart,
+ isPluginInstanceKey,
+ resolvePluginInstanceQuery,
+} from '../../../shared/pluginIdentity.js';
+
+const productionIdentityDeps = {
+ installedGhostPhysicalRelId,
+ installedGhostStoragePart,
+ isPluginInstanceKey,
+ resolvePluginInstanceQuery,
+};
+
+const source = fs.readFileSync(new URL('../index.ts', import.meta.url), 'utf8');
+const ast = ts.createSourceFile('index.ts', source, ts.ScriptTarget.Latest, true);
+
+export function createGhostProductionCallbacks<Result>(options: {
+ functions?: string[];
+ variables?: string[];
+ callbacks?: Record<string, readonly [callee: string, channel?: string]>;
+ initialize?: string;
+ transformCallback?: (source: string) => string;
+}): (deps: Record<string, unknown>) => Result {
+ const { functions = [], variables = [], callbacks = {} } = options;
+ const names = [...functions, ...variables, ...Object.keys(callbacks)];
+ if (new Set(names).size !== names.length) throw new Error('Duplicate production export names');
+ const declarations = new Map<string, string>();
+ const record = (name: string, declaration: string) => {
+ if (declarations.has(name)) throw new Error('Duplicate production declaration: ' + name);
+ declarations.set(name, declaration);
+ };
+ const visit = (node: ts.Node): void => {
+ if (ts.isFunctionDeclaration(node) && node.name && functions.includes(node.name.text)) {
+ record(node.name.text, node.getText(ast).replace(/^export /, ''));
+ }
+ if (ts.isVariableDeclaration(node) && variables.includes(node.name.getText(ast))) {
+ record(node.name.getText(ast), 'const ' + node.getText(ast) + ';');
+ }
+ if (ts.isCallExpression(node)) {
+ for (const [name, [callee, channel]] of Object.entries(callbacks)) {
+ if (node.expression.getText(ast) !== callee) continue;
+ const firstArgument = node.arguments[0];
+ if (channel !== undefined && (!firstArgument || !ts.isStringLiteral(firstArgument) ||
+ firstArgument.text !== channel)) continue;
+ const callback = node.arguments[channel === undefined ? 0 : 1];
+ if (!callback) throw new Error('Production callback missing: ' + name);
+ const text = callback.getText(ast);
+ record(name, 'const ' + name + ' = ' + (options.transformCallback?.(text) ?? text) + ';');
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ const missing = names.filter((name) => !declarations.has(name));
+ if (missing.length) throw new Error('Production declarations missing: ' + missing.join(', '));
+ const compiled = ts.transpileModule(
+ (options.initialize ?? '') + '\n' + [...declarations.values()].join('\n'),
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+ return (deps) => {
+ const merged = { ...productionIdentityDeps, ...deps };
+ return new Function(
+ 'deps', 'const {' + Object.keys(merged).join(',') + '} = deps;' + compiled +
+ ';return {' + names.join(',') + '};',
+ )(merged) as Result;
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostRecentUsageStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostRecentUsageStore.test.ts
index e0c86ac52a..1b45257f68 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostRecentUsageStore.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostRecentUsageStore.test.ts
@@ -9,8 +9,16 @@ import { normalizeGhostRecentIds } from '../ghostRecentUsageStore';
describe('ghostRecentUsageStore', () => {
it('keeps valid ids newest-first while removing invalid and duplicate values', () => {
expect(
- normalizeGhostRecentIds(['cindy-github', '', 'bad id', 'xd-mivo', 'cindy-github', 42]),
- ).toEqual(['cindy-github', 'xd-mivo']);
+ normalizeGhostRecentIds([
+ 'cindy-github',
+ '',
+ 'bad id',
+ 'xd-mivo',
+ '_ns__acme__helper',
+ 'cindy-github',
+ 42,
+ ]),
+ ).toEqual(['cindy-github', 'xd-mivo', '_ns__acme__helper']);
});
it('bounds persisted history', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.ts
index cf42ea816d..5537e40e61 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostRecommendations.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
import type { InstalledGhost } from '../../../shared/ghost';
import { validateGhostManifest } from '../../../shared/ghost';
import { buildGhostRecommendationSnapshot } from '../ghostRecommendationSnapshot';
@@ -6,18 +7,22 @@ import { buildGhostRecommendationSnapshot } from '../ghostRecommendationSnapshot
const state = vi.hoisted(() => ({
owner: 'owner-a',
buckets: new Map<string, Record<string, unknown>>(),
+ failRecentWrite: false,
+ failRecommendationRead: false,
}));
-vi.mock('../../appSessionState.js', () => ({ ownerScopedUserDataPath: () => state.owner }));
+vi.mock('../../appSessionState.js', () => ({ ownerScopedUserDataPath: (...parts: string[]) => path.join(state.owner, ...parts) }));
vi.mock('electron-store', () => ({
default: class {
- constructor(private options: { cwd: string; defaults: Record<string, unknown> }) {
+ constructor(private options: { cwd: string; name: string; defaults: Record<string, unknown> }) {
if (!state.buckets.has(options.cwd))
state.buckets.set(options.cwd, structuredClone(options.defaults));
}
get(key: string) {
+ if (state.failRecommendationRead && this.options.name === 'ghost-recommendations') throw new Error('read unavailable');
return state.buckets.get(this.options.cwd)?.[key];
}
set(key: string, value: unknown) {
+ if (state.failRecentWrite && this.options.name === 'ghost-recent-usage') throw new Error('disk unavailable');
state.buckets.get(this.options.cwd)![key] = structuredClone(value);
}
},
@@ -37,8 +42,10 @@ const ghost = {
} as unknown as InstalledGhost;
beforeEach(() => {
state.owner = 'owner-a';
- state.buckets.set('owner-a', { entries: [] });
- state.buckets.set('owner-b', { entries: [] });
+ state.failRecentWrite = false;
+ state.failRecommendationRead = false;
+ state.buckets.set('owner-a', { entries: [], ids: [] });
+ state.buckets.set('owner-b', { entries: [], ids: [] });
});
describe('plugin recommendation state', () => {
it('replaces, withdraws, preserves install priority and isolates owners', () => {
@@ -63,6 +70,23 @@ describe('plugin recommendation state', () => {
forgetGhostRecommendations('example');
expect(readGhostRecommendationEntries()).toEqual([]);
});
+ it('accepts namespaced instance ids used by the pipe binding', () => {
+ expect(replaceGhostRecommendations('_ns__xd__helper', [item])).toEqual({ ok: true });
+ expect(readGhostRecommendationEntries()[0].id).toBe('_ns__xd__helper');
+ });
+ it('keeps same-name root and organization recommendations and history separate', () => {
+ const root = { ...ghost, manifest: { ...ghost.manifest, id: 'helper', name: 'Root' }, dir: '/ghosts/helper', namespace: null };
+ const org = { ...ghost, manifest: { ...ghost.manifest, id: 'helper', name: 'Org' }, dir: '/ghosts/_ns/acme/helper', namespace: 'acme' };
+ replaceGhostRecommendations('helper', [{ ...item, id: 'root' }]);
+ replaceGhostRecommendations('_ns__acme__helper', [{ ...item, id: 'org' }]);
+ markGhostRecommendationInstalled('_ns__acme__helper');
+ const snapshot = buildGhostRecommendationSnapshot('owner-a', [root, org], readGhostRecommendationEntries(), ['_ns__acme__helper']);
+ expect(snapshot.sources.map((source) => [source.ghostId, source.items?.[0]?.id])).toEqual([
+ ['helper', 'root'], ['_ns__acme__helper', 'org'],
+ ]);
+ expect(snapshot.recentIds).toEqual(['_ns__acme__helper']);
+ expect(snapshot.newlyInstalledId).toBe('_ns__acme__helper');
+ });
it('rejects invalid replacement without losing previous tasks', () => {
replaceGhostRecommendations('example', [item]);
expect(replaceGhostRecommendations('example', [{ ...item, pluginId: 'other' }]).ok).toBe(false);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
index 719d0f4366..e1830995e3 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
@@ -12,6 +12,7 @@ import { GhostMutationCoordinator } from '../ghostMutationCoordinator';
import {
GhostSetupCoordinator,
type GhostSetupActionResult,
+ type GhostSetupInlineActionInput,
type GhostSetupTargetValidation,
} from '../ghostSetupCoordinator';
import {
@@ -194,7 +195,10 @@ function requiredNavigation(revision = 0): GhostSetupAssessment {
};
}
-function harness(initial: GhostSetupAssessment) {
+function harness(
+ initial: GhostSetupAssessment,
+ extras?: { resolveStoreId?: (ghostId: string) => string; getTargetToken?: (ghostId: string) => string | null },
+) {
const changeBus = new GhostSetupChangeBus();
const broadcast = vi.fn();
const bridge = new GhostSetupInteractionBridge({ broadcast });
@@ -208,7 +212,7 @@ function harness(initial: GhostSetupAssessment) {
responseTarget?: GhostSetupInteractionResponseTarget;
}): Promise<GhostSetupActionResult> => ({ ok: true }),
);
- const executeInlineAction = vi.fn(async (): Promise<GhostSetupActionResult> => ({ ok: true }));
+ const executeInlineAction = vi.fn(async (_args: GhostSetupInlineActionInput): Promise<GhostSetupActionResult> => ({ ok: true }));
let requestNumber = 0;
const coordinator = new GhostSetupCoordinator({
changeBus,
@@ -225,6 +229,8 @@ function harness(initial: GhostSetupAssessment) {
createRequestId: () => `request-${++requestNumber}`,
timeoutMs: 5_000,
terminalGraceMs: 0,
+ ...(extras?.resolveStoreId ? { resolveStoreId: extras.resolveStoreId } : {}),
+ ...(extras?.getTargetToken ? { getTargetToken: extras.getTargetToken } : {}),
});
return {
bridge,
@@ -243,6 +249,45 @@ function harness(initial: GhostSetupAssessment) {
}
describe('GhostSetupCoordinator', () => {
+ it('refuses the old inline card after a same-key installation replacement without a lifecycle event', async () => {
+ let token = 'original';
+ const h = harness(requiredInline(), { getTargetToken: () => token });
+ const abort = new AbortController();
+ const waiting = h.coordinator.ensureReady({ sessionId: 'task', ghostId: 'api', signal: abort.signal });
+ try {
+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));
+ const card = h.bridge.pendingSnapshots()[0].request;
+ token = 'replacement';
+ expect(h.bridge.submitInline(card.requestId, {
+ actionId: 'inline_form:opaque', expectedRevision: card.revision, value: 'synthetic-secret',
+ })).toBe(false);
+ expect(h.executeInlineAction).not.toHaveBeenCalled();
+ expect(h.bridge.pendingSnapshots()).toHaveLength(0);
+ } finally { abort.abort(); await waiting; }
+ });
+
+ it('rechecks the original install binding at the final inline commit', async () => {
+ let token = 'original';
+ const h = harness(requiredInline(), { getTargetToken: () => token });
+ const abort = new AbortController();
+ const waiting = h.coordinator.ensureReady({ sessionId: 'task', ghostId: 'api', signal: abort.signal });
+ let rejected = false;
+ h.executeInlineAction.mockImplementationOnce(async ({ commit }) => {
+ token = 'replacement';
+ try { commit!.assertCurrent('api', 'inline_form:opaque', 'secret:api_key'); }
+ catch { rejected = true; }
+ return { ok: false, errorCode: 'ACTION_STALE' };
+ });
+ try {
+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));
+ const card = h.bridge.pendingSnapshots()[0].request;
+ expect(h.bridge.submitInline(card.requestId, {
+ actionId: 'inline_form:opaque', expectedRevision: card.revision, value: 'synthetic-secret',
+ })).toBe(true);
+ await vi.waitFor(() => expect(h.executeInlineAction).toHaveBeenCalledOnce());
+ expect(rejected).toBe(true);
+ } finally { abort.abort(); await waiting; }
+ });
it('completes local reconfiguration only after opening settings and a committed write to that connection', async () => {
const action = { id: 'manage_connection:connection:service', kind: 'manage_connection' as const };
const assessment: GhostSetupAssessment = { state: 'ready', revision: 1, groups: [{ id: 'connection', mode: 'any_of',
@@ -451,6 +496,24 @@ describe('GhostSetupCoordinator', () => {
await waiting;
});
+ it('wakes setup waiters from namespaced store ids emitted by plugin settings', async () => {
+ const h = harness(required(), {
+ resolveStoreId: (ghostId) => (ghostId === 'gmail' ? '_ns__xd__gmail' : ghostId),
+ });
+ const waiting = h.coordinator.ensureReady({
+ sessionId: 'session-1',
+ ghostId: 'gmail',
+ tool: 'search',
+ });
+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));
+ h.setAssessment(ready(4));
+ h.changeBus.emit('_ns__xd__gmail', { source: 'oauth', ref: 'google' });
+ await expect(waiting).resolves.toMatchObject({
+ ok: true,
+ assessment: { state: 'ready', revision: 4 },
+ });
+ });
+
it('submits inline Secret per request, re-assesses on change, and never snapshots the value', async () => {
const h = harness(requiredInline());
const waiting = h.coordinator.ensureReady({
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts
index 69ef8a3610..d4f2a68bb1 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts
@@ -28,6 +28,52 @@ function ghost(
}
describe('GhostSetupManifestTracker', () => {
+ it('emits when the same manifest and physical instance receives a new approval', () => {
+ const bus = new GhostSetupChangeBus();
+ const tracker = new GhostSetupManifestTracker(bus, () => true);
+ const installed = ghost('helper');
+ tracker.seed([installed]);
+ expect(tracker.note([{ ...installed, approval: { state: 'approved', revision: 'replacement' } }])).toEqual(['helper']);
+ expect(bus.currentRevision('helper')).toBe(1);
+ });
+ it('tracks colliding ids independently by physical instance', () => {
+ const bus = new GhostSetupChangeBus();
+ const onRoot = vi.fn();
+ const onOrg = vi.fn();
+ bus.subscribe('helper', onRoot);
+ bus.subscribe('_ns__acme__helper', onOrg);
+ const tracker = new GhostSetupManifestTracker(bus, () => true);
+ const root = ghost('helper');
+ const org = { ...ghost('helper'), namespace: 'acme', dir: '/plugins/_ns/acme/helper' };
+ tracker.seed([root, org]);
+ expect(tracker.note([{ ...root, enabled: false }, org])).toEqual(['helper']);
+ expect(onRoot).toHaveBeenCalledTimes(1);
+ expect(onOrg).not.toHaveBeenCalled();
+ expect(tracker.note([{ ...root, enabled: false }, { ...org, enabled: false }])).toEqual(['_ns__acme__helper']);
+ expect(onOrg).toHaveBeenCalledTimes(1);
+ expect(tracker.note([{ ...root, enabled: false }])).toEqual(['_ns__acme__helper']);
+ expect(onOrg).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps the bare physical id for an in-place namespace stamp', () => {
+ const bus = new GhostSetupChangeBus();
+ const listener = vi.fn();
+ bus.subscribe('helper', listener);
+ const tracker = new GhostSetupManifestTracker(bus, () => true);
+ const org = { ...ghost('helper'), namespace: 'acme' };
+ tracker.seed([org]);
+ expect(tracker.note([{ ...org, enabled: false }])).toEqual(['helper']);
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+
+ it('checks availability against each installed physical id', () => {
+ const availability = vi.fn((_instanceId: string) => true);
+ const tracker = new GhostSetupManifestTracker(new GhostSetupChangeBus(), availability);
+ tracker.seed([ghost('helper'), { ...ghost('helper'), namespace: 'acme', dir: '/plugins/_ns/acme/helper' }]);
+ expect(availability.mock.calls.map(([instanceId]) => instanceId)).toEqual([
+ 'helper', '_ns__acme__helper',
+ ]);
+ });
it('emits only for install, update, enable/disable, and uninstall diffs', () => {
const bus = new GhostSetupChangeBus();
const listener = vi.fn();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostTrustedXdTarget.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostTrustedXdTarget.test.ts
new file mode 100644
index 0000000000..b194d9fcc5
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostTrustedXdTarget.test.ts
@@ -0,0 +1,297 @@
+import { describe, expect, it } from 'vitest';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import type { GhostFirstPartyFactsLoad } from '../ghostFirstPartyFacts.js';
+import type {
+ GhostFirstPartyCurrentOrganization,
+ GhostFirstPartyFacts,
+ GhostFirstPartyMarketRecord,
+} from '../ghostFirstPartyPrivilege.js';
+import { isTrustedXdGhostForScriptTarget } from '../ghostTrustedXdTarget.js';
+
+const packageSha256 = 'a'.repeat(64);
+const organization: GhostFirstPartyCurrentOrganization = {
+ organizationId: 'org-xd',
+ orgSlug: 'xd',
+ pluginPrefix: 'xd',
+};
+const marketRecord: GhostFirstPartyMarketRecord = {
+ scope: 'organization',
+ organizationId: organization.organizationId,
+ source: 'market',
+ installed: true,
+ sha256: packageSha256,
+ approvedPackageSha256: packageSha256,
+};
+
+function installed(overrides: Partial<InstalledGhost> = {}): InstalledGhost {
+ const ghost: InstalledGhost = {
+ manifest: {
+ schemaVersion: 2,
+ id: 'xd-feishu',
+ name: 'Feishu',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ },
+ dir: '/tmp/brain/_ns/xd/xd-feishu',
+ namespace: 'xd',
+ enabled: true,
+ approval: { state: 'approved', revision: 'trusted-revision' },
+ ...overrides,
+ };
+ if (ghost.namespace === undefined) delete ghost.namespace;
+ return ghost;
+}
+
+function ready(overrides: Partial<GhostFirstPartyFacts> = {}): GhostFirstPartyFactsLoad {
+ return {
+ kind: 'ready',
+ facts: {
+ ghostId: 'xd-feishu',
+ namespace: 'xd',
+ builtin: false,
+ marketRecord,
+ currentOrganization: organization,
+ installOrigin: 'manual',
+ ...overrides,
+ },
+ };
+}
+
+function builtin(namespace: string | null): GhostFirstPartyFactsLoad {
+ return ready({
+ namespace,
+ builtin: true,
+ marketRecord: null,
+ approvedPackageSha256: packageSha256,
+ trustedSource: { kind: 'builtin-official', ghostId: 'xd-feishu', namespace, packageSha256 },
+ });
+}
+
+describe('trusted XD script target', () => {
+ it.each(['xd', undefined, null])('accepts verified XD namespace with orgSlug %s', (orgSlug) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed(),
+ ready({
+ currentOrganization: { organizationId: organization.organizationId, orgSlug },
+ }),
+ false,
+ ),
+ ).toBe(true);
+ });
+
+ it.each(['xd', undefined, null])(
+ 'accepts approved pending legacy with current XD identity %s',
+ (orgSlug) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: undefined }),
+ ready({
+ namespace: null,
+ currentOrganization: { ...organization, orgSlug },
+ }),
+ true,
+ ),
+ ).toBe(true);
+ },
+ );
+
+ it.each(['xd', undefined])(
+ 'accepts pending trusted builtin with current XD identity %s',
+ (orgSlug) => {
+ const load = builtin(null);
+ if (load.kind === 'ready') load.facts.currentOrganization = { ...organization, orgSlug };
+ expect(isTrustedXdGhostForScriptTarget(installed({ namespace: undefined }), load, true)).toBe(
+ true,
+ );
+ },
+ );
+
+ it('accepts trusted builtin evidence for explicit XD namespace', () => {
+ expect(isTrustedXdGhostForScriptTarget(installed(), builtin('xd'), false)).toBe(true);
+ });
+
+ it.each(['xd', undefined])(
+ 'rejects known root even with pending argument and slug %s',
+ (orgSlug) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: null }),
+ ready({
+ namespace: null,
+ currentOrganization: { ...organization, orgSlug },
+ }),
+ true,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it('rejects unknown namespace outside the pending transition', () => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: undefined }),
+ ready({ namespace: null }),
+ false,
+ ),
+ ).toBe(false);
+ });
+
+ it('does not treat an explicit undefined delivery field as missing legacy namespace', () => {
+ const ghost = installed({ namespace: undefined });
+ ghost.namespace = undefined;
+ expect(isTrustedXdGhostForScriptTarget(ghost, ready({ namespace: null }), true)).toBe(false);
+ });
+
+ it.each([false, true])(
+ 'rejects explicit foreign slug despite prefix XD, pending %s',
+ (pending) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: pending ? undefined : 'xd' }),
+ ready({
+ namespace: pending ? null : 'xd',
+ currentOrganization: { ...organization, orgSlug: 'foreign' },
+ }),
+ pending,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it.each([undefined, null, 'foreign'])(
+ 'rejects pending legacy without affirmative XD identity, prefix %s',
+ (pluginPrefix) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: undefined }),
+ ready({
+ namespace: null,
+ currentOrganization: { organizationId: organization.organizationId, pluginPrefix },
+ }),
+ true,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it.each(['invalid', 'legacy-unapproved'] as const)(
+ 'rejects pending legacy approval %s',
+ (state) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: undefined, approval: { state } }),
+ ready({ namespace: null }),
+ true,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it('rejects foreign delivery namespace even with trusted current-org market evidence', () => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: 'foreign' }),
+ ready({ namespace: 'foreign' }),
+ true,
+ ),
+ ).toBe(false);
+ });
+
+ it.each([
+ { organizationId: 'foreign-org' },
+ { scope: 'public', organizationId: null },
+ { source: 'local-market' },
+ { source: 'git-market' },
+ { source: 'legacy-adopted' },
+ { installed: false },
+ { sha256: 'b'.repeat(64) },
+ { approvedPackageSha256: null },
+ { sha256: 'invalid', approvedPackageSha256: 'invalid' },
+ ] satisfies Partial<GhostFirstPartyMarketRecord>[])(
+ 'rejects untrusted market evidence %j',
+ (overrides) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed(),
+ ready({
+ marketRecord: { ...marketRecord, ...overrides },
+ }),
+ false,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it.each([false, true])('rejects new public XD name even on builtin roster %s', (builtin) => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed({ namespace: undefined }),
+ ready({
+ namespace: null,
+ builtin,
+ legacyFirstPartyEligible: true,
+ marketRecord: { ...marketRecord, scope: 'public', organizationId: null },
+ }),
+ true,
+ ),
+ ).toBe(false);
+ });
+
+ it.each([
+ { trustedSource: null },
+ { approvedPackageSha256: 'b'.repeat(64) },
+ {
+ trustedSource: {
+ kind: 'builtin-official',
+ ghostId: 'other-plugin',
+ namespace: 'xd',
+ packageSha256,
+ },
+ },
+ {
+ trustedSource: {
+ kind: 'builtin-official',
+ ghostId: 'xd-feishu',
+ namespace: null,
+ packageSha256,
+ },
+ },
+ ] satisfies Partial<GhostFirstPartyFacts>[])(
+ 'rejects builtin without matching receipt evidence %j',
+ (overrides) => {
+ const load = builtin('xd');
+ if (load.kind === 'ready') Object.assign(load.facts, overrides);
+ expect(isTrustedXdGhostForScriptTarget(installed(), load, false)).toBe(false);
+ },
+ );
+
+ it.each([false, true])('rejects anonymous identity with builtin evidence %s', (useBuiltin) => {
+ const load = useBuiltin ? builtin('xd') : ready();
+ if (load.kind === 'ready') load.facts.currentOrganization = null;
+ expect(isTrustedXdGhostForScriptTarget(installed(), load, false)).toBe(false);
+ });
+
+ it.each([{ ghostId: 'other-plugin' }, { namespace: null }])(
+ 'rejects mismatched facts %j',
+ (overrides) => {
+ expect(isTrustedXdGhostForScriptTarget(installed(), ready(overrides), false)).toBe(false);
+ },
+ );
+
+ it('rejects unavailable facts', () => {
+ expect(
+ isTrustedXdGhostForScriptTarget(
+ installed(),
+ {
+ kind: 'unavailable',
+ reason: 'market-installation-read-failed',
+ purpose: 'runtime',
+ action: 'load-without-privilege',
+ },
+ false,
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts
index f028cf2608..dcb8d4dfc7 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts
@@ -15,7 +15,13 @@ import type { InstalledGhost } from '../../../shared/ghost';
function ghost(
id: string,
- opts: { enabled?: boolean; notify?: boolean; badge?: boolean } = {},
+ opts: {
+ enabled?: boolean;
+ notify?: boolean;
+ badge?: boolean;
+ namespace?: string | null;
+ dir?: string;
+ } = {},
): InstalledGhost {
const badge = opts.badge ?? true;
return {
@@ -31,8 +37,9 @@ function ghost(
...(badge ? { badge: true } : {}),
},
- dir: `/fake/${id}`,
+ dir: opts.dir ?? `/fake/${id}`,
enabled: opts.enabled ?? true,
+ ...(Object.hasOwn(opts, 'namespace') ? { namespace: opts.namespace } : {}),
} as InstalledGhost;
}
@@ -58,6 +65,31 @@ describe('ghostUnreadProjection', () => {
expect(selectRevokedGhostUnreadIds(entries, [ghost('a', { enabled: false })])).toEqual([]);
});
+ it.each([true, false])('已迁移的组织插件按物理实例保留未读, enabled=%s', (enabled) => {
+ const installed = ghost('helper', {
+ enabled, namespace: 'acme', dir: '/fake/_ns/acme/helper',
+ });
+ expect(selectRevokedGhostUnreadIds([{ ghostId: '_ns__acme__helper' }], [installed], true))
+ .toEqual([]);
+ });
+
+ it.each([undefined, null, 'acme'])('未搬迁的实例按原物理键保留未读, namespace=%s', (namespace) => {
+ const installed = ghost('helper', { namespace });
+ expect(selectRevokedGhostUnreadIds([{ ghostId: 'helper' }], [installed], true)).toEqual([]);
+ });
+
+ it('同名 root 与组织实例的权限分别撤销,不会互相保留或误删', () => {
+ const entries = [{ ghostId: 'helper' }, { ghostId: '_ns__acme__helper' }];
+ const root = ghost('helper', { namespace: null });
+ const organization = ghost('helper', { namespace: 'acme', dir: '/fake/_ns/acme/helper' });
+ expect(selectRevokedGhostUnreadIds(entries, [
+ ghost('helper', { namespace: null, badge: false }), organization,
+ ], true)).toEqual(['helper']);
+ expect(selectRevokedGhostUnreadIds(entries, [
+ root, ghost('helper', { namespace: 'acme', dir: '/fake/_ns/acme/helper', badge: false }),
+ ], true)).toEqual(['_ns__acme__helper']);
+ });
+
it('能力撤销进撤销名单:更新后不再声明 badge / 包已卸载', () => {
const entries = [{ ghostId: 'revoked' }, { ghostId: 'noslot' }, { ghostId: 'gone' }, { ghostId: 'ok' }];
const ids = selectRevokedGhostUnreadIds(entries, [
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
new file mode 100644
index 0000000000..62b44e7f47
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
@@ -0,0 +1,275 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import ts from 'typescript';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import { ghostInstallApprovalToken, type GhostManifest } from '../../../shared/ghost.js';
+import type { GhostCardDb } from '../cardStoreDb.js';
+import type { DbClient } from '../../localDb/client/DbClient.js';
+import { createPluginTaskStore } from '../../maker-ipc/pluginTaskStore.js';
+import { createPluginTaskService } from '../../maker-ipc/pluginTaskService.js';
+import { LayoutStore } from '../../layout/LayoutStore.js';
+import { createDefaultLayout, walkPanes } from '../../../shared/layoutTree.js';
+import { GhostManager } from '../GhostManager.js';
+import { createGhostInstallReceipt, GhostInstallReceiptStore, hashApprovedSkillContent } from '../ghostInstallReceipt.js';
+import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess.js';
+import { relocateGhostUserDataResources, type GhostUserDataRelocationResources } from '../ghostUserDataRelocation.js';
+import { writeTestCindyPackage } from './cindyPackageFixture.js';
+
+const scope = vi.hoisted(() => ({ dir: '' }));
+vi.mock('electron', () => ({ app: { getPath: () => scope.dir } }));
+vi.mock('../../appSessionState.js', () => ({
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(scope.dir, ...parts),
+ activeOwnerScopeKey: () => scope.dir,
+ isAppSessionBoundaryPending: () => false,
+}));
+vi.mock('../../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: { child: () => ({ info: vi.fn(), warn: vi.fn() }) },
+}));
+
+const cindy = await import('../cindyPrefsStore.js');
+const errand = await import('../pluginTaskPrefsStore.js');
+const pick = await import('../pickGrantsStore.js');
+const workdir = await import('../ghostWorkdirPrefs.js');
+const unread = await import('../ghostUnreadStore.js');
+const cards = await import('../cardStoreDb.js');
+const schema = await import('../../localDb/schema.js');
+let rawDb: Database.Database | undefined;
+let db: GhostCardDb;
+let root: string;
+let receipts: GhostInstallReceiptStore;
+let layout: LayoutStore;
+let resources: GhostUserDataRelocationResources;
+let tasks: ReturnType<typeof createPluginTaskStore>;
+const from = 'helper';
+const to = '_ns__acme__helper';
+const manifest = {
+ schemaVersion: 2, id: from, name: 'Helper', version: '1.0.0',
+ kind: 'chip', entry: 'main.js', slots: ['tool'],
+ tools: [{ name: 'do_thing', description: 'do' }],
+} as GhostManifest;
+const mutateSnapshot: NonNullable<ConstructorParameters<typeof GhostInstallReceiptStore>[1]> = async ({ parentDir, ...request }) => {
+ await runGhostSnapshotWorkerRequest(request, parentDir);
+};
+
+beforeEach(() => {
+ scope.dir = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-relocation-')));
+ root = path.join(scope.dir, 'ghosts');
+ rawDb = undefined;
+ const noOp = async () => {};
+ resources = {
+ userDataPath: (...parts) => path.join(scope.dir, ...parts),
+ assertCurrent: () => {},
+ secrets: noOp, libraryBinding: noOp, libraryMeta: noOp,
+ tasks: noOp,
+ cindyPreferences: cindy.relocateGhostCindyPrefs,
+ errandPreferences: errand.relocateGhostErrandPrefs,
+ pickedDirectories: pick.relocateGhostPickedDirs,
+ workdirPreferences: workdir.relocateGhostWorkdirPrefs,
+ media: noOp,
+ cards: noOp,
+ unread: unread.relocateGhostUnread,
+ routines: noOp,
+ recommendations: noOp,
+ recentUsage: noOp,
+ };
+});
+
+function createTaskFixture() {
+ rawDb = new Database(':memory:');
+ db = drizzle(rawDb, { schema });
+ rawDb.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,
+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,
+ revision INTEGER, created_at INTEGER, UNIQUE(plugin_id, operation, target_id, request_key))`);
+ tasks = createPluginTaskStore({ drizzle: db } as unknown as DbClient);
+ resources.tasks = (source, destination) => tasks.relocatePlugin(source, destination);
+ return rawDb;
+}
+
+async function seedSourceResources() {
+ createTaskFixture().exec(fs.readFileSync(path.resolve(__dirname, '../../../../drizzle/0072_first_lightspeed.sql'), 'utf8'));
+ resources.cards = (source, destination) => cards.reassignGhostCards(source, destination, db);
+ receipts = new GhostInstallReceiptStore(() => path.join(scope.dir, 'ghosts-install-state'), mutateSnapshot);
+ layout = new LayoutStore({ getFilePath: () => path.join(scope.dir, 'layout.json') });
+ const initial = createDefaultLayout();
+ if (initial.content.type !== 'split') throw new Error('expected default split');
+ for (const child of initial.content.children) child.fraction = 0.4;
+ initial.content.children.push({ fraction: 0.2, node: { type: 'pane', id: 'org-placement', panelKind: 'ghost:helper' } });
+ expect(layout.setLayout(initial)).toMatchObject({ persisted: true });
+ fs.mkdirSync(path.join(root, from), { recursive: true });
+ fs.writeFileSync(path.join(root, from, 'ghost.json'), JSON.stringify(manifest));
+ fs.writeFileSync(path.join(root, from, 'main.js'), 'void 0;');
+ await receipts.write(createGhostInstallReceipt({
+ manifest, localeResources: {}, enabled: true,
+ trust: { level: 'unverified', publisherSigned: false, publisherVerified: false, reviewed: false },
+ skillContentSha256: await hashApprovedSkillContent(manifest, path.join(root, from)),
+ }), { skillSourceDir: path.join(root, from) });
+ fs.mkdirSync(path.join(scope.dir, 'ghost-kv'));
+ fs.writeFileSync(path.join(scope.dir, 'ghost-kv', from + '.json'), JSON.stringify({ private: 'org' }));
+ cindy.writeGhostCindyOverride(from, 'image.generate', 'org-model');
+ errand.writePluginTaskConfig(from, { permissionMode: 'auto', workingDir: '/org-workspace' });
+ errand.writeGhostErrandSessionId(from, 'org-session');
+ errand.writeGhostErrandSessionId(from, 'org-keyed-session', 'draft');
+ pick.recordGhostPickedDir(from, '/org-picked');
+ workdir.setGhostDisabledForWorkdir('/project', from, true);
+ unread.markGhostUnread(from, 'org activity', 100);
+ await cards.upsertGhostCard({
+ callId: 'org-card', ghostId: from, sessionId: 'org-session', html: '<p>org</p>',
+ height: 240, v: 1, updatedAt: 1,
+ }, db);
+}
+
+afterEach(() => { rawDb?.close(); fs.rmSync(scope.dir, { recursive: true, force: true }); });
+
+it('installs a same-name root without changing legacy data or UI references', async () => {
+ await seedSourceResources();
+ const archive = vi.fn();
+ const manager = new GhostManager({ getRootDir: () => root, onArchiveSourceState: archive });
+ expect(await manager.commitPendingNamespace(from, 'acme', 'market-organization')).toEqual({ ok: true });
+ const receiptBefore = fs.readFileSync(path.join(scope.dir, 'ghosts-install-state', from + '.json'), 'utf8');
+ const packageFile = await writeTestCindyPackage(path.join(scope.dir, 'root.cindy'), manifest, { 'main.js': 'void 1;' });
+ expect(await manager.install(packageFile)).toMatchObject({ ghost: { namespace: null, dir: path.join(root, '_ns', '_root', from) } });
+ expect(archive).not.toHaveBeenCalled();
+ expect(fs.readFileSync(path.join(scope.dir, 'ghosts-install-state', from + '.json'), 'utf8')).toBe(receiptBefore);
+ expect(fs.readFileSync(path.join(scope.dir, 'ghost-kv', from + '.json'), 'utf8')).toBe(JSON.stringify({ private: 'org' }));
+ expect(fs.existsSync(path.join(scope.dir, 'ghost-kv', '_root__' + from + '.json'))).toBe(false);
+ expect(cindy.readGhostCindyOverrides(from)['image.generate']).toBe('org-model');
+ expect(errand.readPluginTaskConfig(from)).toMatchObject({ permissionMode: 'auto', workingDir: '/org-workspace' });
+ expect(errand.readGhostErrandSessionId(from, 'draft')).toBe('org-keyed-session');
+ expect(unread.readGhostUnread(from)).toMatchObject({ summary: 'org activity', at: 100 });
+ expect(await cards.getGhostCard('org-card', db)).toMatchObject({ ghostId: from });
+ expect(walkPanes(layout.getLayout())).toContainEqual({ type: 'pane', id: 'org-placement', panelKind: 'ghost:helper' });
+});
+
+it('archives and restores source-owned data without changing logical UI placement', async () => {
+ await seedSourceResources();
+ const archive = '_ns__cindy-archive-test__helper';
+ const task = { id: 'task', pluginId: from, operation: 'create' as const, targetId: '',
+ requestKey: 'create', fingerprint: 'hash', payload: '{"title":"keep"}', revision: 0, createdAt: 1 };
+ const run = { ...task, id: 'run', operation: 'send' as const, targetId: task.id, requestKey: 'send', payload: '{"status":"completed"}' };
+ await tasks.insert(task);
+ await tasks.insert(run);
+ await tasks.insert({ ...task, id: 'other', pluginId: to });
+ await relocateGhostUserDataResources(from, archive, resources);
+ expect(await tasks.find(from, 'create', '', task.requestKey)).toBeUndefined();
+ expect(await tasks.get(task.id)).toEqual({ ...task, pluginId: archive, revision: 1 });
+ expect(await tasks.get(run.id)).toEqual({ ...run, pluginId: archive, revision: 1 });
+ expect(await tasks.get('other')).toEqual({ ...task, id: 'other', pluginId: to });
+ await expect(tasks.save(task)).rejects.toThrow('revision conflict');
+ await relocateGhostUserDataResources(from, archive, resources);
+ expect((await tasks.get(task.id))?.revision).toBe(1);
+ expect(errand.readGhostErrandSessionId(from)).toBeNull();
+ expect(await cards.getGhostCard('org-card', db)).toMatchObject({ ghostId: archive });
+ expect(unread.readGhostUnread(from)).toBeNull();
+ expect(unread.readGhostUnread(archive)).toMatchObject({ summary: 'org activity', at: 100 });
+ expect(walkPanes(layout.getLayout())).toContainEqual({ type: 'pane', id: 'org-placement', panelKind: 'ghost:helper' });
+ await relocateGhostUserDataResources(archive, from, resources);
+ expect(await tasks.get(task.id)).toEqual({ ...task, revision: 2 });
+ expect(await tasks.get(run.id)).toEqual({ ...run, revision: 2 });
+ expect(errand.readGhostErrandSessionId(from, 'draft')).toBe('org-keyed-session');
+ expect(await cards.getGhostCard('org-card', db)).toMatchObject({ ghostId: from });
+ expect(unread.readGhostUnread(from)).toMatchObject({ summary: 'org activity', at: 100 });
+});
+
+it('keeps task ownership isolated after partial archival and restores it through inverse replay', async () => {
+ await seedSourceResources();
+ const archive = '_ns__cindy-archive-test__helper';
+ await tasks.insert({ id: 'task', pluginId: from, operation: 'create', targetId: '',
+ requestKey: 'key', fingerprint: 'hash', payload: '{}', revision: 0, createdAt: 1 });
+ await expect(relocateGhostUserDataResources(from, archive, {
+ ...resources, secrets: () => { throw new Error('archive interrupted'); },
+ })).rejects.toThrow('archive interrupted');
+ expect((await tasks.get('task'))?.pluginId).toBe(archive);
+ await relocateGhostUserDataResources(archive, from, resources);
+ expect(await tasks.get('task')).toMatchObject({ pluginId: from, revision: 2 });
+});
+
+it('completes source replacement and another plugin uninstall without reversing mutation queues', async () => {
+ await seedSourceResources();
+ const archive = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__helper';
+ const service = createPluginTaskService({
+ store: tasks, assertCurrent: () => {}, assertAuthorized: vi.fn(), readPermissionMode: vi.fn(),
+ resolveRoute: vi.fn(), createSession: vi.fn(), readSession: vi.fn(),
+ dispatch: vi.fn(), inspect: vi.fn(), cancel: vi.fn(),
+ });
+ let entered!: () => void, finish!: () => void;
+ const started = new Promise<void>(resolve => { entered = resolve; });
+ const gate = new Promise<void>(resolve => { finish = resolve; });
+ const manager = new GhostManager({ getRootDir: () => root, onArchiveSourceState: async (source, destination) => {
+ entered(); await gate; await service.relocatePlugin(source, destination);
+ } });
+ await manager.commitPendingNamespace(from, 'acme', 'market-organization');
+ await manager.install(await writeTestCindyPackage(path.join(scope.dir, 'other.cindy'), { ...manifest, id: 'other' }));
+ await tasks.insert({ id: 'task', pluginId: from, operation: 'create', targetId: '',
+ requestKey: 'key', fingerprint: 'hash', payload: '{}', revision: 0, createdAt: 1 });
+ const packageFile = await writeTestCindyPackage(path.join(scope.dir, 'update.cindy'), { ...manifest, version: '2.0.0' });
+ const updating = manager.update(packageFile, { namespace: 'acme', sourceStateArchiveId: archive,
+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list().find(ghost => ghost.manifest.id === from)?.approval) });
+ await started;
+ const source = fs.readFileSync(new URL('../index.ts', import.meta.url), 'utf8');
+ const start = source.indexOf(' const downloadScope = activeOwnerScopeKey();');
+ const end = source.indexOf(' await pluginDownloads.removePlugin', start);
+ expect(start).toBeGreaterThan(0);
+ expect(end).toBeGreaterThan(start);
+ const code = ts.transpileModule(`return (async () => { ${source.slice(start, end)} })();`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ const remove = new Function('activeOwnerScopeKey', 'pluginTaskUninstaller', 'storagePart', 'manager', 'relId', 'throwUninstallError', code);
+ const removing = remove(() => scope.dir, (id: string, callback: () => Promise<void>) => service.withUninstall(id, callback),
+ '_root__other', manager, '_ns/_root/other', (failure: { reason: string }) => { throw new Error(failure.reason); });
+ await new Promise<void>(resolve => setImmediate(resolve));
+ finish();
+ const [updated] = await Promise.all([updating, removing]);
+ expect(updated).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+ expect(manager.list().some(ghost => ghost.manifest.id === 'other')).toBe(false);
+ expect((await tasks.get('task'))?.pluginId).toBe(archive);
+});
+
+it('stops at an owner change after an asynchronous resource instead of writing later references', async () => {
+ errand.writeGhostErrandSessionId(from, 'org-session');
+ let current = true;
+ const binding = vi.fn();
+ const guarded = { ...resources, secrets: () => { current = false; }, libraryBinding: binding,
+ assertCurrent: () => { if (!current) throw new Error('owner changed'); },
+ };
+ await expect(relocateGhostUserDataResources(from, to, guarded)).rejects.toThrow('owner changed');
+ expect(binding).not.toHaveBeenCalled();
+ expect(errand.readGhostErrandSessionId(from)).toBe('org-session');
+});
+
+it('rejects colliding task identities atomically without overwriting either source', async () => {
+ createTaskFixture();
+ const task = { id: 'task', pluginId: from, operation: 'create' as const, targetId: '',
+ requestKey: 'key', fingerprint: 'hash', payload: '{}', revision: 0, createdAt: 1 };
+ const other = { ...task, id: 'other', pluginId: to };
+ await tasks.insert(task);
+ await tasks.insert(other);
+ await expect(tasks.relocatePlugin(from, to)).rejects.toThrow('UNIQUE constraint failed');
+ await tasks.relocatePlugin(from, from);
+ expect(await tasks.get(task.id)).toEqual(task);
+ expect(await tasks.get(other.id)).toEqual(other);
+});
+
+it('moves downloads, recent usage and recommendations with the archived instance', async () => {
+ const archive = 'arch_' + 'a'.repeat(32);
+ fs.mkdirSync(path.join(scope.dir, 'plugin-downloads', from), { recursive: true });
+ fs.writeFileSync(path.join(scope.dir, 'plugin-downloads', from, 'pkg.bin'), 'bytes');
+ const recent = await import('../ghostRecentUsageStore.js');
+ const recs = await import('../ghostRecommendationStore.js');
+ recent.markGhostRecentlyUsed(from);
+ recent.markGhostRecentlyUsed('other-plugin');
+ recs.markGhostRecommendationInstalled(from);
+ resources.recentUsage = recent.relocateGhostRecentUsage;
+ resources.recommendations = recs.relocateGhostRecommendations;
+ const routines = vi.fn();
+ resources.routines = routines;
+ await relocateGhostUserDataResources(from, archive, resources);
+ expect(fs.readFileSync(path.join(scope.dir, 'plugin-downloads', archive, 'pkg.bin'), 'utf8')).toBe('bytes');
+ expect(fs.existsSync(path.join(scope.dir, 'plugin-downloads', from))).toBe(false);
+ expect(recent.loadGhostRecentIds()).toEqual(['other-plugin', archive]);
+ expect(recs.readGhostRecommendationEntries().map((entry) => entry.id)).toEqual([archive]);
+ expect(routines).toHaveBeenCalledWith(from, archive);
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostVisibility.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostVisibility.test.ts
new file mode 100644
index 0000000000..b67e4f1cd4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostVisibility.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest';
+
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import { classifyGhostVisibility, classifyInstalledGhostVisibility } from '../ghostVisibility.js';
+
+function ghost(id: string, namespace?: string | null, enabled = true): InstalledGhost {
+ return {
+ manifest: { schemaVersion: 2, id, name: id, version: '1.0.0', kind: 'chip', entry: 'index.js', slots: [] },
+ dir: namespace ? `/tmp/_ns/${namespace}/${id}` : `/tmp/${id}`,
+ enabled,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ ...(namespace !== undefined ? { namespace } : {}),
+ } as InstalledGhost;
+}
+
+describe('classifyGhostVisibility namespace', () => {
+ const root = ghost('helper', null);
+ const enterprise = ghost('helper', 'acme');
+ const deps = {
+ listGhosts: () => [root, enterprise],
+ isAvailableForActiveSession: () => true,
+ isDisabledForWorkdir: () => false,
+ };
+
+ it('returns GHOST_AMBIGUOUS when the same ghostId has two instances and namespace is omitted', () => {
+ const result = classifyGhostVisibility('helper', null, deps);
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.errorCode).toBe('GHOST_AMBIGUOUS');
+ expect(result.candidates).toEqual([
+ { ghostId: 'helper', namespace: null },
+ { ghostId: 'helper', namespace: 'acme' },
+ ]);
+ });
+
+ it('selects the requested namespace when provided', () => {
+ expect(classifyGhostVisibility('helper', null, deps, 'acme')).toMatchObject({
+ ok: true,
+ ghost: { dir: '/tmp/_ns/acme/helper' },
+ });
+ expect(classifyGhostVisibility('helper', null, deps, null)).toMatchObject({
+ ok: true,
+ ghost: { dir: '/tmp/helper' },
+ });
+ });
+
+ it('checks workdir disable against the physical storage part', () => {
+ const org = ghost('helper', 'acme');
+ const inPlace = { ...ghost('xd-feishu', 'xd'), dir: '/tmp/xd-feishu' };
+ const disabled = new Set(['_ns__acme__helper', 'xd-feishu']);
+ const workdirDeps = {
+ listGhosts: () => [org, inPlace],
+ isAvailableForActiveSession: () => true,
+ isDisabledForWorkdir: (id: string) => disabled.has(id),
+ };
+ expect(classifyGhostVisibility('helper', '/proj', workdirDeps, 'acme')).toMatchObject({
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ });
+ expect(classifyGhostVisibility('xd-feishu', '/proj', workdirDeps, 'xd')).toMatchObject({
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ });
+ });
+
+ it('addresses a pending legacy candidate when namespace null is retried', () => {
+ const pending = { ...ghost('helper'), namespaceState: 'pending' as const };
+ const stageDeps = { ...deps, listGhosts: () => [pending, enterprise] };
+ expect(classifyGhostVisibility('helper', null, stageDeps)).toMatchObject({
+ ok: false,
+ errorCode: 'GHOST_AMBIGUOUS',
+ candidates: [
+ { ghostId: 'helper', namespace: null },
+ { ghostId: 'helper', namespace: 'acme' },
+ ],
+ });
+ expect(classifyGhostVisibility('helper', null, stageDeps, null)).toMatchObject({
+ ok: true,
+ ghost: pending,
+ });
+ });
+
+ it('resolves a unique pending install only when namespace is omitted', () => {
+ const pending = { ...ghost('xd-feishu'), namespaceState: 'pending' as const };
+ const stageDeps = { ...deps, listGhosts: () => [pending] };
+ expect(classifyGhostVisibility('xd-feishu', null, stageDeps)).toMatchObject({ ok: true, ghost: pending });
+ expect(classifyGhostVisibility('xd-feishu', null, stageDeps, null)).toMatchObject({
+ ok: false, errorCode: 'GHOST_NOT_FOUND',
+ });
+ });
+
+
+ it('resolves local mivo-canvas and enterprise xd-mivo-canvas as different plugins', () => {
+ const local = ghost('mivo-canvas', null);
+ const enterprise = ghost('xd-mivo-canvas', 'xd');
+ const stageDeps = { ...deps, listGhosts: () => [local, enterprise] };
+ expect(classifyGhostVisibility('mivo-canvas', null, stageDeps)).toMatchObject({
+ ok: true,
+ ghost: { dir: '/tmp/mivo-canvas' },
+ });
+ expect(classifyGhostVisibility('xd-mivo-canvas', null, stageDeps)).toMatchObject({
+ ok: true,
+ ghost: { dir: '/tmp/_ns/xd/xd-mivo-canvas' },
+ });
+ });
+
+ it('resolves a storage-part instance id when namespace is omitted', () => {
+ expect(classifyGhostVisibility('_ns__acme__helper', null, deps)).toMatchObject({
+ ok: true,
+ ghost: { dir: '/tmp/_ns/acme/helper' },
+ });
+ });
+
+ it.each(['pending', 'root', 'in-place', 'canonical', 'coexist'] as const)(
+ 'revalidates the selected physical instance in %s without erasing delivery state', (stage) => {
+ const selected = stage === 'pending'
+ ? { ...ghost('helper'), namespaceState: 'pending' as const }
+ : stage === 'root' ? root
+ : stage === 'in-place' ? { ...enterprise, dir: root.dir } : enterprise;
+ const others = stage === 'coexist' ? [root] : [];
+ const stageDeps = { ...deps, listGhosts: () => [selected, ...others] };
+ expect(classifyInstalledGhostVisibility(selected, null, stageDeps)).toMatchObject({ ok: true, ghost: selected });
+ const replacement = { ...selected, namespace: selected.namespace === null ? 'acme' : null };
+ expect(classifyInstalledGhostVisibility(selected, null, { ...stageDeps, listGhosts: () => [replacement] }))
+ .toMatchObject({ ok: false, errorCode: 'GHOST_NOT_FOUND' });
+ },
+ );
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartition.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartition.test.ts
index 4734c04695..b15613e888 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartition.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartition.test.ts
@@ -7,6 +7,7 @@ vi.mock('../../appSessionState', () => ({
import { ghostPartition } from '../../../shared/ghost';
import {
ownerScopedGhostPartition,
+ ownerScopedGhostPartitionForInstalledGhost,
resolveGhostWebviewPartitionClaim,
} from '../ghostWebviewPartition';
@@ -14,6 +15,14 @@ describe('ghost WebView Main partition', () => {
const ownerA = { mode: 'cloud' as const, dataOwnerId: 'owner-a' };
const ownerB = { mode: 'cloud' as const, dataOwnerId: 'owner-b' };
+ it('isolates approved receipts even when source version and panel HTML are unchanged', () => {
+ const original = { manifest: { id: 'source-change', version: '1.0.0' }, approval: { state: 'approved' as const, revision: 'receipt-a' } };
+ const replacement = { ...original, approval: { state: 'approved' as const, revision: 'receipt-b' } };
+ const originalPartition = ownerScopedGhostPartitionForInstalledGhost(original, ownerA);
+ expect(ownerScopedGhostPartitionForInstalledGhost(original, ownerA)).toBe(originalPartition);
+ expect(ownerScopedGhostPartitionForInstalledGhost(replacement, ownerA)).not.toBe(originalPartition);
+ });
+
it('同 owner + ghost 稳定,不同 owner + 同 ghost 使用不同 session', () => {
const partitionA = ownerScopedGhostPartition('same-ghost', ownerA);
const partitionB = ownerScopedGhostPartition('same-ghost', ownerB);
@@ -51,4 +60,27 @@ describe('ghost WebView Main partition', () => {
).toBeNull();
expect(resolveGhostWebviewPartitionClaim(undefined, ownerA)).toBeNull();
});
+
+ it('企业实例使用 storage part 作为 session 分区后缀', () => {
+ expect(ownerScopedGhostPartition('_ns__acme__helper', ownerA)).toBe(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:_ns__acme__helper',
+ );
+ expect(resolveGhostWebviewPartitionClaim(ghostPartition('_ns__acme__helper'), ownerA)).toEqual({
+ ghostId: '_ns__acme__helper',
+ partition: 'cindy-ghost-owner:cloud:opaque-owner-a:_ns__acme__helper',
+ });
+ expect(ownerScopedGhostPartition('_ns/acme/helper', ownerA)).toBeNull();
+ });
+
+ it('迁移前的旧 root、原位企业实例与新 root 各自使用不同的会话', () => {
+ const legacy = { manifest: { id: 'helper' } };
+ const organization = { manifest: { id: 'helper' }, namespace: 'acme' };
+ const root = { manifest: { id: 'helper' }, namespace: null };
+ expect(ownerScopedGhostPartitionForInstalledGhost(legacy, ownerA))
+ .toBe('cindy-ghost-owner:cloud:opaque-owner-a:helper');
+ expect(ownerScopedGhostPartitionForInstalledGhost(organization, ownerA))
+ .toBe('cindy-ghost-owner:cloud:opaque-owner-a:_ns__acme__helper:ns:acme');
+ expect(ownerScopedGhostPartitionForInstalledGhost(root, ownerA))
+ .toBe('cindy-ghost-owner:cloud:opaque-owner-a:helper:root');
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartitionClaim.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartitionClaim.test.ts
new file mode 100644
index 0000000000..91749d9cac
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartitionClaim.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../appSessionState', () => ({
+ dataOwnerStorageKey: (ownerId: string) => `opaque-${ownerId}`,
+}));
+
+import {
+ installedGhostLogicalIdentity,
+ installedGhostStoragePart,
+ installedGhostWebviewPartitionClaim,
+ pluginStoragePart,
+} from '../../../shared/pluginIdentity';
+import { resolveGhostWebviewPartitionClaim } from '../ghostWebviewPartition';
+
+const owner = { mode: 'cloud' as const, dataOwnerId: 'owner-a' };
+
+describe('renderer webview claim matches the physical instance', () => {
+ const ghosts = [
+ {
+ label: 'legacy root',
+ manifest: { id: 'helper' },
+ dir: '/ghosts/helper',
+ instanceKey: 'helper',
+ namespaceState: 'pending' as const,
+ },
+ {
+ label: 'new root',
+ manifest: { id: 'helper' },
+ dir: '/ghosts/_ns/_root/helper',
+ instanceKey: '_root__helper',
+ namespace: null,
+ namespaceState: 'confirmed' as const,
+ },
+ {
+ label: 'in-place organization',
+ manifest: { id: 'xd-feishu' },
+ dir: '/ghosts/xd-feishu',
+ instanceKey: 'xd-feishu',
+ namespace: 'xd',
+ namespaceState: 'confirmed' as const,
+ },
+ {
+ label: 'new organization',
+ manifest: { id: 'helper' },
+ dir: '/ghosts/_ns/xd/helper',
+ instanceKey: '_ns__xd__helper',
+ namespace: 'xd',
+ namespaceState: 'confirmed' as const,
+ },
+ ];
+
+ it.each(ghosts)('resolves the $label claim to that instance', (ghost) => {
+ const claim = installedGhostWebviewPartitionClaim(ghost);
+ const resolved = resolveGhostWebviewPartitionClaim(claim, owner);
+ expect(resolved?.ghostId).toBe(installedGhostStoragePart(ghost));
+ expect(ghosts.filter((candidate) => installedGhostStoragePart(candidate) === resolved?.ghostId))
+ .toEqual([ghost]);
+ });
+
+ it('keeps the in-place organization height key on the logical id', () => {
+ const inPlace = ghosts[2]!;
+ expect(installedGhostStoragePart(inPlace)).toBe('xd-feishu');
+ expect(pluginStoragePart(installedGhostLogicalIdentity(inPlace))).toBe('_ns__xd__xd-feishu');
+ expect(installedGhostWebviewPartitionClaim(inPlace)).toBe('cindy-ghost-xd-feishu');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts
index 07c586f2e3..81d04b44cf 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostWorkdirPrefs.test.ts
@@ -4,14 +4,157 @@
* 兜底)见 mcp-integrations/__tests__/ghostWorkdirGate.test.ts。
*/
-import { describe, it, expect, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
+import * as locks from '../../device-link/crossProcessLock.js';
+
+const scope = vi.hoisted(() => ({ dir: '' }));
vi.mock('electron', () => ({ app: { getPath: () => '/tmp/never-used-here' } }));
vi.mock('../../maker-host/logger-adapter.js', () => ({
desktopMakerLogger: { child: () => ({ info: () => {}, warn: () => {}, error: () => {} }) },
}));
+vi.mock('../../appSessionState.js', () => ({
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(scope.dir, ...parts),
+ activeOwnerScopeKey: () => scope.dir,
+ isAppSessionBoundaryPending: () => false,
+}));
+
+const {
+ __testing, setGhostDisabledForWorkdir, listDisabledGhostIdsForWorkdir,
+ relocateGhostWorkdirPrefs,
+} = await import('../ghostWorkdirPrefs');
+
+describe('relocateGhostWorkdirPrefs', () => {
+ beforeEach(() => {
+ scope.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ghost-prefs-relocate-'));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ fs.rmSync(scope.dir, { recursive: true, force: true });
+ });
+
+ it('moves disabled projects to the namespaced identity without disabling a new root plugin', async () => {
+ setGhostDisabledForWorkdir('/project/a', 'helper', true);
+ setGhostDisabledForWorkdir('/project/b', 'helper', true);
+ await relocateGhostWorkdirPrefs('helper', '_ns__acme__helper');
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper']);
+ expect(listDisabledGhostIdsForWorkdir('/project/b')).toEqual(['_ns__acme__helper']);
+ await relocateGhostWorkdirPrefs('helper', '_ns__acme__helper');
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper']);
+ });
+
+ it('refuses existing destination disables without merging plugin preferences', async () => {
+ setGhostDisabledForWorkdir('/project/a', 'helper', true);
+ setGhostDisabledForWorkdir('/project/a', 'another', true);
+ setGhostDisabledForWorkdir('/project/a', '_ns__acme__helper', true);
+ setGhostDisabledForWorkdir('/project/b', '_ns__acme__helper', true);
+ await expect(relocateGhostWorkdirPrefs('helper', '_ns__acme__helper')).rejects.toThrow(/collision/);
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper', 'another', 'helper']);
+ expect(listDisabledGhostIdsForWorkdir('/project/b')).toEqual(['_ns__acme__helper']);
+ });
-const { __testing } = await import('../ghostWorkdirPrefs');
+ it('replays the inverse without relying on an in-memory rollback closure', async () => {
+ setGhostDisabledForWorkdir('/project/a', 'helper', true);
+ setGhostDisabledForWorkdir('/project/b', 'helper', true);
+ await relocateGhostWorkdirPrefs('helper', '_ns__acme__helper');
+ await relocateGhostWorkdirPrefs('_ns__acme__helper', 'helper');
+ await relocateGhostWorkdirPrefs('_ns__acme__helper', 'helper');
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['helper']);
+ expect(listDisabledGhostIdsForWorkdir('/project/b')).toEqual(['helper']);
+ });
+
+ it('does not overwrite unreadable preferences; retry succeeds once repaired', async () => {
+ setGhostDisabledForWorkdir('/project/a', 'helper', true);
+ const file = path.join(scope.dir, 'ghost-workdir-prefs.json');
+ fs.writeFileSync(file, '{bad json');
+ await expect(relocateGhostWorkdirPrefs('helper', '_ns__acme__helper')).rejects.toThrow(/unreadable/);
+ expect(fs.readFileSync(file, 'utf8')).toBe('{bad json');
+ fs.writeFileSync(file, JSON.stringify({ disabledByWorkdir: { '/project/a': ['helper'] } }));
+ await relocateGhostWorkdirPrefs('helper', '_ns__acme__helper');
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper']);
+ });
+
+ it.each(['helper', 'another-plugin'])('blocks %s writes during lock release with unchanged mtime', async (id) => {
+ setGhostDisabledForWorkdir('/project/a', 'helper', true);
+ const file = path.join(scope.dir, 'ghost-workdir-prefs.json');
+ const time = new Date('2000-01-01T00:00:00Z');
+ fs.utimesSync(file, time, time);
+ listDisabledGhostIdsForWorkdir('/project/a');
+ const rename = fs.promises.rename;
+ let attempted = false;
+ let failure: unknown;
+ vi.spyOn(fs.promises, 'rename').mockImplementation(async (source, destination) => {
+ if (String(source) === file + '.lock' && String(destination).startsWith(file + '.lock.release-')) {
+ attempted = true;
+ fs.utimesSync(file, time, time);
+ try { setGhostDisabledForWorkdir('/project/a', id, true); } catch (error) { failure = error; }
+ }
+ await rename(source, destination);
+ });
+ await relocateGhostWorkdirPrefs('helper', '_ns__acme__helper');
+ expect(attempted).toBe(true);
+ expect(failure).toBeInstanceOf(Error);
+ expect((failure as Error).message).toMatch(/relocating/);
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper']);
+ setGhostDisabledForWorkdir('/project/a', 'another-plugin', true);
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper', 'another-plugin']);
+ });
+
+ it.each(['write', 'release'])('recovers after %s failure without restoring stale cache', async (stage) => {
+ setGhostDisabledForWorkdir('/project/a', 'helper', true);
+ const file = path.join(scope.dir, 'ghost-workdir-prefs.json');
+ const time = new Date('2000-01-01T00:00:00Z');
+ fs.utimesSync(file, time, time);
+ listDisabledGhostIdsForWorkdir('/project/a');
+ if (stage === 'write') {
+ const rename = fs.renameSync;
+ vi.spyOn(fs, 'renameSync').mockImplementation((source, destination) => {
+ if (String(destination) === file) throw new Error('simulated write failure');
+ rename(source, destination);
+ });
+ } else {
+ const withLock = locks.withCrossProcessLock;
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (target, options, task, signal) => {
+ await withLock(target, options, task, signal);
+ fs.utimesSync(file, time, time);
+ throw new Error('simulated release failure');
+ });
+ }
+ await expect(relocateGhostWorkdirPrefs('helper', '_ns__acme__helper'))
+ .rejects.toThrow('simulated ' + stage + ' failure');
+ vi.restoreAllMocks();
+ setGhostDisabledForWorkdir('/project/a', 'another-plugin', true);
+ if (stage === 'release') {
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper', 'another-plugin']);
+ }
+ await relocateGhostWorkdirPrefs('helper', '_ns__acme__helper');
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper', 'another-plugin']);
+ });
+
+ it('allows another owner to write while this owner releases its lock', async () => {
+ setGhostDisabledForWorkdir('/project/a', 'helper', true);
+ const originalDir = scope.dir;
+ const withLock = locks.withCrossProcessLock;
+ vi.spyOn(locks, 'withCrossProcessLock').mockImplementationOnce(async (target, options, task, signal) => {
+ const result = await withLock(target, options, task, signal);
+ scope.dir = path.join(originalDir, 'owner-b');
+ try {
+ expect(setGhostDisabledForWorkdir('/project/b', 'helper', true)).toEqual(['helper']);
+ } finally {
+ scope.dir = originalDir;
+ }
+ return result;
+ });
+ await relocateGhostWorkdirPrefs('helper', '_ns__acme__helper');
+ expect(listDisabledGhostIdsForWorkdir('/project/a')).toEqual(['_ns__acme__helper']);
+ expect(JSON.parse(fs.readFileSync(path.join(originalDir, 'owner-b', 'ghost-workdir-prefs.json'), 'utf8')))
+ .toEqual({ disabledByWorkdir: { '/project/b': ['helper'] } });
+ });
+});
describe('normalizeWorkdirKey(纯字符串归一化,不碰 fs)', () => {
it('Windows 形态:统一反斜杠、去尾分隔符、小写折叠', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/googleAccountsMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/googleAccountsMigration.test.ts
deleted file mode 100644
index 86590be2d2..0000000000
--- a/apps/desktop/src/main/cindy-brain/__tests__/googleAccountsMigration.test.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * googleAccountsMigration 单测:老 Google 集成 → Filo Google 意识搬账
- * (只迁 filoCurrent、幂等、清单写败回退;规则 14 内存假体零 Electron)。
- */
-import { describe, expect, it, vi } from 'vitest';
-
-import {
- FILO_CURRENT_PROFILE_ID,
- FILO_GOOGLE_GHOST_ID,
- FILO_GOOGLE_SECRET_KEY,
- migrateFiloGoogleAccounts,
- migrateFiloGoogleAccountsWithResult,
- type GoogleAccountsMigrationDeps,
- type LegacyGoogleAccountRow,
-} from '../googleAccountsMigration.js';
-
-function memoryVault(seed?: Record<string, string>) {
- const data = new Map<string, string>(Object.entries(seed ?? {}));
- return {
- data,
- read: (g: string, k: string) => data.get(`${g} ${k}`) ?? null,
- store: (g: string, k: string, v: string) => {
- data.set(`${g} ${k}`, v);
- return true;
- },
- remove: (g: string, k: string) => {
- data.delete(`${g} ${k}`);
- },
- };
-}
-
-const CURRENT = (id: string, email: string | null): LegacyGoogleAccountRow => ({
- id,
- email,
- credentialProfileId: FILO_CURRENT_PROFILE_ID,
- updatedAt: 100,
-});
-const available = <T>(value: T) => ({ status: 'available' as const, value });
-const missing = { status: 'missing' as const };
-const retryableFailure = { status: 'retryable-failure' as const };
-
-function deps(over: Partial<GoogleAccountsMigrationDeps>): GoogleAccountsMigrationDeps {
- return {
- readLegacyManifest: () => available({ accounts: [CURRENT('acc-1', '[email protected]')] }),
- readLegacyRefreshToken: () => available('rt-legacy'),
- vault: memoryVault(),
- ...over,
- };
-}
-
-const RT_KEY = (id: string) => `${FILO_GOOGLE_SECRET_KEY}-rt-${id}`;
-const ACCOUNTS_KEY = `${FILO_GOOGLE_SECRET_KEY}-accounts`;
-
-describe('migrateFiloGoogleAccounts', () => {
- it('happy:filoCurrent 账号迁入,rt 落库 + 清单成形 + 默认账号', () => {
- const vault = memoryVault();
- const n = migrateFiloGoogleAccounts(deps({ vault }));
- expect(n).toBe(1);
- expect(vault.read(FILO_GOOGLE_GHOST_ID, RT_KEY('acc-1'))).toBe('rt-legacy');
- const manifest = JSON.parse(vault.read(FILO_GOOGLE_GHOST_ID, ACCOUNTS_KEY) ?? '{}');
- expect(manifest.defaultAccountId).toBe('acc-1');
- expect(manifest.accounts[0]).toMatchObject({ id: 'acc-1', label: '[email protected]', status: 'connected' });
- });
-
- it('legacy 档案账号不迁(原本的就算了)', () => {
- const vault = memoryVault();
- const n = migrateFiloGoogleAccounts(
- deps({
- vault,
- readLegacyManifest: () => available({
- accounts: [{ id: 'old-1', email: '[email protected]', credentialProfileId: 'filoLegacy', updatedAt: 1 }],
- }),
- }),
- );
- expect(n).toBe(0);
- expect(vault.read(FILO_GOOGLE_GHOST_ID, ACCOUNTS_KEY)).toBeNull();
- });
-
- it('幂等:意识侧已有账号清单 → 整体跳过,不读老存储', () => {
- const vault = memoryVault({ [`${FILO_GOOGLE_GHOST_ID} ${ACCOUNTS_KEY}`]: '{"defaultAccountId":"x","accounts":[]}' });
- const readLegacyManifest = vi.fn(() => available({ accounts: [CURRENT('acc-1', '[email protected]')] }));
- const n = migrateFiloGoogleAccounts(deps({ vault, readLegacyManifest }));
- expect(n).toBe(0);
- expect(readLegacyManifest).not.toHaveBeenCalled();
- });
-
- it('老存储缺失 / 无 filoCurrent 账号 → 0,不建清单', () => {
- expect(migrateFiloGoogleAccounts(deps({ readLegacyManifest: () => missing }))).toBe(0);
- expect(
- migrateFiloGoogleAccounts(deps({ readLegacyManifest: () => available({ accounts: [] }) })),
- ).toBe(0);
- });
-
- it('refresh token 读不到的账号跳过,只迁能迁的', () => {
- const vault = memoryVault();
- const n = migrateFiloGoogleAccounts(
- deps({
- vault,
- readLegacyManifest: () => available({ accounts: [CURRENT('acc-1', '[email protected]'), CURRENT('acc-2', '[email protected]')] }),
- readLegacyRefreshToken: (id) => (id === 'acc-1' ? available('rt-1') : missing),
- }),
- );
- expect(n).toBe(1);
- const manifest = JSON.parse(vault.read(FILO_GOOGLE_GHOST_ID, ACCOUNTS_KEY) ?? '{}');
- expect(manifest.accounts.map((a: { id: string }) => a.id)).toEqual(['acc-1']);
- });
-
- it('任一旧 token 暂时读失败 → 回滚本轮已写 token 并保留整轮重试', () => {
- const vault = memoryVault();
- const result = migrateFiloGoogleAccountsWithResult(
- deps({
- vault,
- readLegacyManifest: () => available({
- accounts: [CURRENT('acc-1', '[email protected]'), CURRENT('acc-2', '[email protected]')],
- }),
- readLegacyRefreshToken: (id) => (id === 'acc-1' ? available('rt-1') : retryableFailure),
- }),
- );
- expect(result).toEqual({ migrated: 0, retryPending: true });
- expect(vault.data.size).toBe(0);
- });
-
- it('旧账号清单暂时读失败 → 不写目标并保留重试', () => {
- const vault = memoryVault();
- expect(
- migrateFiloGoogleAccountsWithResult(
- deps({ vault, readLegacyManifest: () => retryableFailure }),
- ),
- ).toEqual({ migrated: 0, retryPending: true });
- expect(vault.data.size).toBe(0);
- });
-
- it('清单写失败 → 回收已搬 rt,保持"没迁过"状态', () => {
- const vault = memoryVault();
- // 清单键写入失败(rt 键正常):模拟 safeStorage 半可用。
- const store = vi.fn((g: string, k: string, v: string) => {
- if (k === ACCOUNTS_KEY) return false;
- vault.data.set(`${g} ${k}`, v);
- return true;
- });
- const failing = { ...vault, store };
- const n = migrateFiloGoogleAccounts(deps({ vault: failing }));
- expect(n).toBe(0);
- // 已搬的 rt 被回收,下次启动可干净重试。
- expect(vault.read(FILO_GOOGLE_GHOST_ID, RT_KEY('acc-1'))).toBeNull();
- expect(migrateFiloGoogleAccountsWithResult(deps({ vault: failing }))).toEqual({
- migrated: 0,
- retryPending: true,
- });
- });
-});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts
index eeaf3ecb23..1ad567b525 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts
@@ -1,7 +1,123 @@
import fs from 'node:fs';
import path from 'node:path';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
+import { migrateAtlassianAccountsWithResult, XD_ATLASSIAN_GHOST_ID, XD_ATLASSIAN_SECRET_KEY } from '../atlassianAccountsMigration.js';
+const FILO_GOOGLE_GHOST_ID = 'filo-google';
+const FILO_GOOGLE_SECRET_KEY = 'google_account';
+import { isCindyOfficialTrustInfo, CINDY_OFFICIAL_GHOST_TRUST } from '../GhostManager.js';
+import { GhostOauthAccountManager } from '../ghostOauthAccounts.js';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+
+const loadActivation = createGhostProductionCallbacks<{ activateGhostsAndMigrateLegacyAccounts: () => string }>({
+ variables: ['activateGhostsAndMigrateLegacyAccounts'],
+});
+
+function legacyAccountsFixture(id: string) {
+ const secretKey = id === XD_ATLASSIAN_GHOST_ID ? XD_ATLASSIAN_SECRET_KEY : FILO_GOOGLE_SECRET_KEY;
+ const oauth = { authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
+ tokenUrl: id === FILO_GOOGLE_GHOST_ID ? 'https://oauth2.googleapis.com/token' : 'https://auth.atlassian.com/oauth/token',
+ clientId: 'fake-legacy-client', scopes: [],
+ ...(id === XD_ATLASSIAN_GHOST_ID ? { tokenBroker: 'jira', redirectPort: 53682 } : {}),
+ };
+ let qualified = true;
+ const ghost: InstalledGhost = { manifest: { schemaVersion: 3, id, name: id, version: '1.0.0',
+ kind: 'chip', entry: 'main.js', network: { hosts: ['api.example.com'], secrets: [{ key: secretKey,
+ label: 'Account', source: 'oauth', inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['api.example.com'] }, oauth }] } },
+ dir: '/plugins/' + id, enabled: true, namespace: null,
+ approval: { state: 'approved', revision: 'legacy' },
+ };
+ const data = new Map<string, string>();
+ const vault = { read: (targetId: string, key: string) => data.get(targetId + ' ' + key) ?? null,
+ store: (targetId: string, key: string, value: string) => { data.set(targetId + ' ' + key, value); return true; },
+ remove: (targetId: string, key: string) => { data.delete(targetId + ' ' + key); },
+ };
+ const readLegacyEncryptedSecret = vi.fn(() => ({ status: 'available', value: 'fake-legacy-refresh-token' }));
+ const log = { info: vi.fn(), warn: vi.fn() };
+ const manager = { list: () => [ghost], reconcilePendingRootNamespaces: async () => {},
+ readLegacyFirstPartyEligible: () => qualified,
+ readApprovedInstallReceipt: (targetId: string, revision: string) => targetId === id &&
+ ghost.approval?.state === 'approved' && ghost.approval.revision === revision
+ ? { legacyFirstPartyEligible: qualified, trust: ghost.trust } : null,
+ };
+ const api = loadActivation({ manager, installedGhostStoragePart, isCindyOfficialTrustInfo,
+ findGhostForPhysicalStoragePart: (targetId: string) => installedGhostStoragePart(ghost) === targetId ? ghost : null,
+ spawnIfResident: vi.fn(), getActiveAppSession: () => ({ dataOwnerId: 'owner' }),
+ getAppCapabilities: () => ({ canUseCindyAccountServices: true }), hasLegacyOwnerNamespaceClaim: () => true,
+ app: { getPath: () => '/test-user-data' }, path, log, readLegacyEncryptedSecret,
+ readLegacyJson: () => ({ status: 'available', value: { email: '[email protected]',
+ accounts: [{ id: 'account', email: '[email protected]', credentialProfileId: 'filoCurrent', updatedAt: 1 }] } }),
+ readGhostSecret: vault.read, storeGhostSecret: vault.store, removeGhostSecret: vault.remove,
+ migrateAtlassianAccountsWithResult,
+ XD_ATLASSIAN_GHOST_ID, XD_ATLASSIAN_SECRET_KEY, FILO_GOOGLE_GHOST_ID, FILO_GOOGLE_SECRET_KEY,
+ LEGACY_JIRA_RT_FILE: 'jira_refresh_token.enc', LEGACY_JIRA_CONNECTION_FILE: 'jira_connection.json',
+ CINDY_GITHUB_GHOST_ID: 'cindy-github', CINDY_GITLAB_GHOST_ID: 'cindy-gitlab',
+ getGhostSetupChangeBus: () => ({ emit: vi.fn() }),
+ });
+ return { ...api, ghost, vault, data, readLegacyEncryptedSecret, secretKey,
+ replaceSource: () => { qualified = false; data.clear(); ghost.approval = { state: 'approved', revision: 'replacement' }; },
+ };
+}
+
+describe('legacy account activation source boundaries', () => {
+ it('does not import legacy Google accounts into Filo', () => {
+ const fixture = legacyAccountsFixture(FILO_GOOGLE_GHOST_ID);
+ expect(fixture.activateGhostsAndMigrateLegacyAccounts()).toBe('completed');
+ expect(fixture.readLegacyEncryptedSecret).not.toHaveBeenCalled();
+ expect(fixture.data.size).toBe(0);
+ });
+
+ it.each([XD_ATLASSIAN_GHOST_ID])('does not restore archived %s tokens to a replacement source', async (id) => {
+ const fixture = legacyAccountsFixture(id);
+ fixture.ghost.namespace = 'acme';
+ fixture.activateGhostsAndMigrateLegacyAccounts();
+ expect(fixture.readLegacyEncryptedSecret).toHaveBeenCalled();
+ expect(fixture.data.size).toBeGreaterThan(0);
+ fixture.replaceSource();
+ fixture.readLegacyEncryptedSecret.mockClear();
+ fixture.activateGhostsAndMigrateLegacyAccounts();
+ expect(fixture.data.size).toBe(0);
+ expect(fixture.readLegacyEncryptedSecret).not.toHaveBeenCalled();
+ const oauth = fixture.ghost.manifest.network!.secrets![0].oauth!;
+ oauth.tokenUrl = 'https://attacker.example/token';
+ delete oauth.tokenBroker;
+ expect(fixture.activateGhostsAndMigrateLegacyAccounts()).toBe('completed');
+ const fetchImpl = vi.fn(async () => new Response('{}', { status: 400 }));
+ const accounts = new GhostOauthAccountManager({ vault: fixture.vault, openExternal: vi.fn(), fetchImpl });
+ expect(await accounts.getFreshAccessToken(id, fixture.secretKey, oauth)).toEqual({ ok: false, error: 'NO_ACCOUNT' });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(fixture.readLegacyEncryptedSecret).not.toHaveBeenCalled();
+ expect(fixture.data.size).toBe(0);
+ });
+
+ it.each([XD_ATLASSIAN_GHOST_ID, FILO_GOOGLE_GHOST_ID])('does not migrate %s to a different physical instance', (id) => {
+ const fixture = legacyAccountsFixture(id);
+ fixture.ghost.dir = '/plugins/_ns/_root/' + id;
+ fixture.activateGhostsAndMigrateLegacyAccounts();
+ expect(fixture.readLegacyEncryptedSecret).not.toHaveBeenCalled();
+ expect(fixture.data.size).toBe(0);
+ });
+
+ it.each([XD_ATLASSIAN_GHOST_ID, FILO_GOOGLE_GHOST_ID])('does not migrate %s to an incompatible OAuth provider', (id) => {
+ const fixture = legacyAccountsFixture(id);
+ fixture.ghost.manifest.network!.secrets![0].oauth!.tokenUrl = 'https://attacker.example/token';
+ delete fixture.ghost.manifest.network!.secrets![0].oauth!.tokenBroker;
+ fixture.activateGhostsAndMigrateLegacyAccounts();
+ expect(fixture.readLegacyEncryptedSecret).not.toHaveBeenCalled();
+ expect(fixture.data.size).toBe(0);
+ });
+
+ it('does not import legacy Google accounts into a trusted bundled Filo install', () => {
+ const fixture = legacyAccountsFixture(FILO_GOOGLE_GHOST_ID);
+ fixture.ghost.builtin = true;
+ fixture.ghost.trust = CINDY_OFFICIAL_GHOST_TRUST;
+ fixture.activateGhostsAndMigrateLegacyAccounts();
+ expect(fixture.readLegacyEncryptedSecret).not.toHaveBeenCalled();
+ expect(fixture.data.size).toBe(0);
+ });
+});
describe('legacy Ghost recovery acknowledgement orchestration', () => {
it('routes startup migration through the stable-owner task instead of timing callbacks', () => {
@@ -29,10 +145,10 @@ describe('legacy Ghost recovery acknowledgement orchestration', () => {
);
expect(
source.match(/if \(migration\.retryPending\) legacyMigrationNeedsRetry = true;/g),
- ).toHaveLength(4);
+ ).toHaveLength(3);
expect(
source.match(/catch \(err\) \{\n\s+legacyMigrationNeedsRetry = true;/g),
- ).toHaveLength(4);
+ ).toHaveLength(3);
expect(source).toContain(
"return legacyMigrationNeedsRetry ? 'retry-pending' : 'completed';",
);
@@ -61,5 +177,7 @@ describe('legacy Ghost recovery acknowledgement orchestration', () => {
expect(acknowledgementBlock).toContain(
'recoveredLegacyIds.filter((id) => !pending.has(id) && !failed.has(id))',
);
+ expect(acknowledgementBlock).not.toContain('captureRecoveredLegacyNamespace(');
+ expect(acknowledgementBlock).toContain('await acknowledgeRecoveredLegacyGhosts(');
});
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts
index 9fadc3e5c9..2e5b0b7ca0 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts
@@ -3,12 +3,12 @@
* 候选位置校验(受管根排斥/UNC 拒/云盘警告/可写探针)、损坏文件回落默认。
* 注入 deps + os.tmpdir,零 Electron。identity 用例带平台能力探针。
*/
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-import { LibraryBindingStore, validateLibraryCandidateLocation, type LibraryBindingDeps } from '../libraryBinding.js';
+import { LibraryBindingStore, assertLibraryMetaOwner, relocateLibraryMetaOwner, validateLibraryCandidateLocation, type LibraryBindingDeps } from '../libraryBinding.js';
const GHOST_ID = 'mivo-canvas';
@@ -36,9 +36,338 @@ describe('LibraryBindingStore', () => {
});
afterEach(async () => {
+ vi.restoreAllMocks();
await fs.promises.rm(tmp, { recursive: true, force: true });
});
+ async function createArchiveSource() {
+ const store = new LibraryBindingStore(deps);
+ const result = await store.setBinding('hello', candidate);
+ expect(result.ok).toBe(true);
+ await fs.promises.mkdir(path.join(candidate, 'hello'));
+ await fs.promises.writeFile(path.join(candidate, 'hello', 'keep.txt'), 'original');
+ await store.markLibraryReady('hello');
+ const record = await store.getBinding('hello');
+ const contents = await fs.promises.readFile(bindingFile, 'utf8');
+ return { store, record, contents };
+ }
+
+ async function expectArchiveReadFailure(store: LibraryBindingStore): Promise<void> {
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow();
+ await expect(store.assertCanRelocateBinding('hello', '_ns__acme__hello')).rejects.toThrow();
+ await expect(store.getBinding('_ns__acme__hello', { strict: true })).rejects.toThrow();
+ }
+
+ it.each(['EACCES', 'EIO', 'malformed JSON', 'invalid schema', 'invalid bindings'] as const)(
+ 'fails custom library archive on %s and preserves the readable source for retry', async (failure) => {
+ const { store, record, contents } = await createArchiveSource();
+ const readFile = fs.promises.readFile.bind(fs.promises);
+ const error = Object.assign(new Error(failure), { code: failure });
+ const readFailure = failure === 'EACCES' || failure === 'EIO'
+ ? vi.spyOn(fs.promises, 'readFile').mockImplementation(async (...args) => {
+ if (args[0] === bindingFile) throw error;
+ return readFile(...args);
+ })
+ : null;
+ let corrupted = contents;
+ if (!readFailure) {
+ const data = JSON.parse(contents);
+ corrupted = failure === 'malformed JSON' ? '{corrupt'
+ : JSON.stringify(failure === 'invalid schema' ? { ...data, version: 2 } : { ...data, bindings: [] });
+ await fs.promises.writeFile(bindingFile, corrupted);
+ }
+ try {
+ expect(await store.resolveLibraryRoot('hello')).toEqual({
+ kind: 'default', root: path.join(defaultRootBase, 'hello'),
+ });
+ await expectArchiveReadFailure(store);
+ expect(await readFile(bindingFile, 'utf8')).toBe(corrupted);
+ } finally {
+ readFailure?.mockRestore();
+ if (!readFailure) await fs.promises.writeFile(bindingFile, contents);
+ }
+ expect(await store.getBinding('hello', { strict: true })).toEqual(record);
+ expect(await store.getBinding('_ns__acme__hello', { strict: true })).toBeNull();
+ expect(await fs.promises.readFile(path.join(candidate, 'hello', 'keep.txt'), 'utf8')).toBe('original');
+ expect(fs.existsSync(path.join(candidate, '_ns__acme__hello'))).toBe(false);
+ await store.relocateBinding('hello', '_ns__acme__hello');
+ expect(await store.getBinding('hello', { strict: true })).toBeNull();
+ expect(await store.getBinding('_ns__acme__hello', { strict: true })).toEqual(record);
+ expect(await fs.promises.readFile(path.join(candidate, '_ns__acme__hello', 'keep.txt'), 'utf8')).toBe('original');
+ },
+ );
+
+ it.each([
+ ['null record', null],
+ ['false record', false],
+ ['missing fields', {}],
+ ['relative root', { root: 'relative' }],
+ ['relative snapshot', { realPathAtGrant: 'relative' }],
+ ['invalid identity', { identity: {} }],
+ ['invalid grant time', { grantedAt: 'yesterday' }],
+ ['invalid generation', { generation: 0 }],
+ ['invalid readiness', { libraryReady: 'false' }],
+ ] as const)('rejects %s instead of treating an untrusted binding as an empty archive', async (_label, invalid) => {
+ const { store, record, contents } = await createArchiveSource();
+ const data = JSON.parse(contents);
+ data.bindings.hello = invalid === null || invalid === false || Object.keys(invalid).length === 0
+ ? invalid : { ...record, ...invalid };
+ const corrupted = JSON.stringify(data);
+ await fs.promises.writeFile(bindingFile, corrupted);
+ await expectArchiveReadFailure(store);
+ expect(await fs.promises.readFile(bindingFile, 'utf8')).toBe(corrupted);
+ expect(await fs.promises.readFile(path.join(candidate, 'hello', 'keep.txt'), 'utf8')).toBe('original');
+ await fs.promises.writeFile(bindingFile, contents);
+ expect(await store.getBinding('hello', { strict: true })).toEqual(record);
+ });
+
+ it.each(['legacy readiness', 'zero inode', 'null identity'] as const)(
+ 'preserves %s records and unknown fields through strict archive reads', async (compatibility) => {
+ const { store, contents } = await createArchiveSource();
+ const data = JSON.parse(contents);
+ const record = data.bindings.hello;
+ if (compatibility === 'legacy readiness') delete record.libraryReady;
+ if (compatibility === 'zero inode') record.identity.ino = 0;
+ if (compatibility === 'null identity') record.identity = null;
+ record.futureField = 'preserved';
+ await fs.promises.writeFile(bindingFile, JSON.stringify(data));
+ expect(await store.getBinding('hello', { strict: true })).toEqual(record);
+ await store.assertCanRelocateBinding('hello', '_ns__acme__hello');
+ await store.relocateBinding('hello', '_ns__acme__hello');
+ expect(await store.getBinding('_ns__acme__hello', { strict: true })).toEqual(record);
+ expect(await fs.promises.readFile(path.join(candidate, '_ns__acme__hello', 'keep.txt'), 'utf8')).toBe('original');
+ },
+ );
+
+ it('accepts a missing binding file on archive paths without creating storage', async () => {
+ const store = new LibraryBindingStore(deps);
+ await expect(store.getBinding('_ns__acme__hello', { strict: true })).resolves.toBeNull();
+ await expect(store.assertCanRelocateBinding('hello', '_ns__acme__hello')).resolves.toBeUndefined();
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).resolves.toBeUndefined();
+ expect(fs.existsSync(bindingFile)).toBe(false);
+ });
+
+ async function interruptRelocation(stage: 'before-folder' | 'folder' | 'binding'): Promise<void> {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ await fs.promises.mkdir(path.join(candidate, 'hello'));
+ await fs.promises.writeFile(path.join(candidate, 'hello', 'keep.txt'), 'original');
+ const rename = fs.promises.rename.bind(fs.promises);
+ let bindingWrites = 0;
+ const interrupted = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (stage === 'before-folder' && path.basename(String(to)) === '_ns__acme__hello') {
+ throw new Error('simulated process interruption');
+ }
+ await rename(from, to);
+ if (to === bindingFile) bindingWrites += 1;
+ if ((stage === 'folder' && path.basename(String(to)) === '_ns__acme__hello') ||
+ (stage === 'binding' && to === bindingFile && bindingWrites === 2)) {
+ throw new Error('simulated process interruption');
+ }
+ });
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow('interruption');
+ interrupted.mockRestore();
+ }
+
+ it('recovers a durable custom relocation after rename but before binding commit', async () => {
+ await interruptRelocation('folder');
+ const restarted = new LibraryBindingStore(deps);
+ await expect(restarted.assertCanRelocateBinding('hello', '_ns__acme__hello')).resolves.toBeUndefined();
+ await restarted.relocateBinding('hello', '_ns__acme__hello');
+ expect(await restarted.getBinding('hello')).toBeNull();
+ expect((await restarted.getBinding('_ns__acme__hello'))?.generation).toBe(1);
+ expect(await fs.promises.readFile(path.join(candidate, '_ns__acme__hello', 'keep.txt'), 'utf8')).toBe('original');
+ expect(JSON.parse(await fs.promises.readFile(bindingFile, 'utf8')).pendingRelocation).toBeUndefined();
+ });
+
+ it('recovers binding committed before marker cleanup and supports reverse rollback', async () => {
+ await interruptRelocation('binding');
+ const interrupted = JSON.parse(await fs.promises.readFile(bindingFile, 'utf8'));
+ expect(interrupted.bindings.hello).toBeUndefined();
+ expect(interrupted.bindings._ns__acme__hello.generation).toBe(1);
+ expect(interrupted.pendingRelocation).toBeDefined();
+ const restarted = new LibraryBindingStore(deps);
+ await restarted.relocateBinding('hello', '_ns__acme__hello');
+ expect(await restarted.getBinding('hello')).toBeNull();
+ expect((await restarted.getBinding('_ns__acme__hello'))?.generation).toBe(1);
+ await restarted.relocateBinding('_ns__acme__hello', 'hello');
+ expect((await restarted.getBinding('hello'))?.generation).toBe(1);
+ expect(await restarted.getBinding('_ns__acme__hello')).toBeNull();
+ expect(await fs.promises.readFile(path.join(candidate, 'hello', 'keep.txt'), 'utf8')).toBe('original');
+ });
+
+ it('supports reverse rollback directly from an interrupted forward rename', async () => {
+ await interruptRelocation('folder');
+ const restarted = new LibraryBindingStore(deps);
+ await restarted.relocateBinding('_ns__acme__hello', 'hello');
+ expect((await restarted.getBinding('hello'))?.generation).toBe(1);
+ expect(await restarted.getBinding('_ns__acme__hello')).toBeNull();
+ expect(await fs.promises.readFile(path.join(candidate, 'hello', 'keep.txt'), 'utf8')).toBe('original');
+ });
+
+ it('rejects a foreign target even with an unfinished relocation journal and retries after restoration', async () => {
+ await interruptRelocation('folder');
+ const target = path.join(candidate, '_ns__acme__hello');
+ const original = path.join(candidate, 'saved-original');
+ await fs.promises.rename(target, original);
+ await fs.promises.mkdir(target);
+ await fs.promises.writeFile(path.join(target, 'foreign.txt'), 'foreign');
+ const restarted = new LibraryBindingStore(deps);
+ await expect(restarted.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow('directory identity changed');
+ await expect(restarted.getBinding('_ns__acme__hello')).rejects.toThrow('directory identity changed');
+ expect(await fs.promises.readFile(path.join(target, 'foreign.txt'), 'utf8')).toBe('foreign');
+ expect(JSON.parse(await fs.promises.readFile(bindingFile, 'utf8')).bindings.hello.generation).toBe(1);
+ await fs.promises.rm(target, { recursive: true });
+ await fs.promises.rename(original, target);
+ await restarted.relocateBinding('hello', '_ns__acme__hello');
+ expect(await fs.promises.readFile(path.join(target, 'keep.txt'), 'utf8')).toBe('original');
+ });
+
+ it('rejects a changed parent identity without rewriting the binding or marker', async () => {
+ await interruptRelocation('folder');
+ const contents = await fs.promises.readFile(bindingFile, 'utf8');
+ const saved = path.join(tmp, 'saved-parent');
+ await fs.promises.rename(candidate, saved);
+ await fs.promises.mkdir(candidate);
+ const restarted = new LibraryBindingStore(deps);
+ await expect(restarted.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow('root identity changed');
+ expect(await fs.promises.readFile(bindingFile, 'utf8')).toBe(contents);
+ await fs.promises.rm(candidate, { recursive: true });
+ await fs.promises.rename(saved, candidate);
+ await restarted.relocateBinding('hello', '_ns__acme__hello');
+ expect((await restarted.getBinding('_ns__acme__hello'))?.generation).toBe(1);
+ });
+
+ it('rejects a replaced source identity before a recorded rename', async () => {
+ await interruptRelocation('before-folder');
+ const source = path.join(candidate, 'hello');
+ const original = path.join(candidate, 'saved-original');
+ await fs.promises.rename(source, original);
+ await fs.promises.mkdir(source);
+ await fs.promises.writeFile(path.join(source, 'foreign.txt'), 'foreign');
+ const restarted = new LibraryBindingStore(deps);
+ await expect(restarted.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow('directory identity changed');
+ expect(await fs.promises.readFile(path.join(source, 'foreign.txt'), 'utf8')).toBe('foreign');
+ expect(fs.existsSync(path.join(candidate, '_ns__acme__hello'))).toBe(false);
+ await fs.promises.rm(source, { recursive: true });
+ await fs.promises.rename(original, source);
+ await restarted.relocateBinding('hello', '_ns__acme__hello');
+ expect(await fs.promises.readFile(path.join(candidate, '_ns__acme__hello', 'keep.txt'), 'utf8')).toBe('original');
+ });
+
+ it.each(['generation', 'owner', 'malformed', 'schema'] as const)('rejects %s journal drift', async (drift) => {
+ await interruptRelocation('folder');
+ const data = JSON.parse(await fs.promises.readFile(bindingFile, 'utf8'));
+ if (drift === 'generation') data.bindings.hello.generation += 1;
+ if (drift === 'owner') data.pendingRelocation.ownerFile = path.join(tmp, 'other-owner', 'libraries-binding.json');
+ if (drift === 'malformed') data.pendingRelocation.libraryIdentity = { dev: 1, ino: 0 };
+ if (drift === 'schema') data.version = 2;
+ const contents = JSON.stringify(data);
+ await fs.promises.writeFile(bindingFile, contents);
+ await expect(new LibraryBindingStore(deps).relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow(
+ drift === 'generation' ? 'generation changed' : 'journal is invalid',
+ );
+ expect(await fs.promises.readFile(bindingFile, 'utf8')).toBe(contents);
+ expect(await fs.promises.readFile(path.join(candidate, '_ns__acme__hello', 'keep.txt'), 'utf8')).toBe('original');
+ });
+
+ it('retains intent after a rename error and recovers only the recorded source', async () => {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ await fs.promises.mkdir(path.join(candidate, 'hello'));
+ await fs.promises.writeFile(path.join(candidate, 'hello', 'keep.txt'), 'original');
+ const rename = fs.promises.rename.bind(fs.promises);
+ const failure = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (path.basename(String(to)) === '_ns__acme__hello') throw new Error('rename unavailable');
+ await rename(from, to);
+ });
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow('rename unavailable');
+ failure.mockRestore();
+ expect(JSON.parse(await fs.promises.readFile(bindingFile, 'utf8')).pendingRelocation).toBeDefined();
+ const restarted = new LibraryBindingStore(deps);
+ expect((await restarted.getBinding('_ns__acme__hello'))?.generation).toBe(1);
+ expect(await fs.promises.readFile(path.join(candidate, '_ns__acme__hello', 'keep.txt'), 'utf8')).toBe('original');
+ });
+
+ it('rejects a symlink target rather than following the original directory identity', async () => {
+ await interruptRelocation('folder');
+ const target = path.join(candidate, '_ns__acme__hello');
+ const original = path.join(candidate, 'saved-original');
+ await fs.promises.rename(target, original);
+ await fs.promises.symlink(original, target, 'junction');
+ await expect(new LibraryBindingStore(deps).relocateBinding('hello', '_ns__acme__hello'))
+ .rejects.toThrow('directory identity unavailable');
+ expect(await fs.promises.readFile(path.join(original, 'keep.txt'), 'utf8')).toBe('original');
+ });
+
+ it('does not recover an owner journal through a different owner-scoped binding file', async () => {
+ await interruptRelocation('folder');
+ const otherFile = path.join(tmp, 'owners', 'k2', 'libraries-binding.json');
+ await fs.promises.mkdir(path.dirname(otherFile), { recursive: true });
+ const contents = await fs.promises.readFile(bindingFile, 'utf8');
+ await fs.promises.writeFile(otherFile, contents);
+ const otherStore = new LibraryBindingStore({ ...deps, getFile: () => otherFile });
+ await expect(otherStore.getBinding('_ns__acme__hello')).rejects.toThrow('journal is invalid');
+ expect(await fs.promises.readFile(bindingFile, 'utf8')).toBe(contents);
+ expect(await fs.promises.readFile(otherFile, 'utf8')).toBe(contents);
+ });
+
+ it('preserves a never-opened custom binding without creating a library directory', async () => {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ await store.relocateBinding('hello', '_ns__acme__hello');
+ expect(await store.getBinding('hello')).toBeNull();
+ expect(await store.getBinding('_ns__acme__hello')).toMatchObject({ generation: 1, libraryReady: false });
+ expect(fs.existsSync(path.join(candidate, '_ns__acme__hello'))).toBe(false);
+ await store.relocateBinding('_ns__acme__hello', 'hello');
+ expect(await store.getBinding('hello')).toMatchObject({ generation: 1, libraryReady: false });
+ });
+
+ it('rejects a dangling foreign target before recording a relocation intent', async () => {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ const target = path.join(candidate, '_ns__acme__hello');
+ await fs.promises.symlink(path.join(tmp, 'missing-foreign'), target, 'junction');
+ await expect(store.assertCanRelocateBinding('hello', '_ns__acme__hello')).rejects.toThrow('destination already exists');
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow('destination already exists');
+ expect(JSON.parse(await fs.promises.readFile(bindingFile, 'utf8')).pendingRelocation).toBeUndefined();
+ expect((await fs.promises.lstat(target)).isSymbolicLink()).toBe(true);
+ });
+
+ it('rejects an owner change while reading a pending relocation without touching either owner', async () => {
+ await interruptRelocation('folder');
+ const contents = await fs.promises.readFile(bindingFile, 'utf8');
+ const originalFile = bindingFile;
+ const readFile = fs.promises.readFile.bind(fs.promises);
+ const changed = vi.spyOn(fs.promises, 'readFile').mockImplementation(async (...args) => {
+ const value = await readFile(...args);
+ bindingFile = path.join(tmp, 'owners', 'k2', 'libraries-binding.json');
+ return value;
+ });
+ await expect(new LibraryBindingStore(deps).getBinding('_ns__acme__hello')).rejects.toThrow('owner changed');
+ changed.mockRestore();
+ expect(fs.existsSync(bindingFile)).toBe(false);
+ bindingFile = originalFile;
+ expect(await fs.promises.readFile(bindingFile, 'utf8')).toBe(contents);
+ });
+
+ it('moves a library owner exactly once without losing other metadata or reassigning another plugin', async () => {
+ const root = path.join(defaultRootBase, 'hello');
+ const file = path.join(root, '.cindy-library', 'meta.json');
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
+ await fs.promises.writeFile(file, JSON.stringify({ version: 1, ghostId: 'hello', createdAt: 1, orphaned: { at: 2, name: 'old' } }));
+ await expect(assertLibraryMetaOwner(root, 'other')).rejects.toThrow('different plugin');
+ await expect(assertLibraryMetaOwner(root, 'hello')).resolves.toBeUndefined();
+ expect(await relocateLibraryMetaOwner(root, 'hello', '_ns__acme__hello')).toBe(true);
+ await expect(assertLibraryMetaOwner(root, '_ns__acme__hello')).resolves.toBeUndefined();
+ expect(await relocateLibraryMetaOwner(root, 'hello', '_ns__acme__hello')).toBe(false);
+ expect(JSON.parse(await fs.promises.readFile(file, 'utf8'))).toEqual({
+ version: 1, ghostId: '_ns__acme__hello', createdAt: 1, orphaned: { at: 2, name: 'old' },
+ });
+ await expect(relocateLibraryMetaOwner(root, 'other', 'hello')).rejects.toThrow('different plugin');
+ expect(await relocateLibraryMetaOwner(path.join(defaultRootBase, 'missing'), 'hello', '_ns__acme__hello')).toBe(false);
+ });
+
it('无 binding → 默认根;绑定后解析到 <candidate>/<ghostId>', async () => {
const store = new LibraryBindingStore(deps);
const before = await store.resolveLibraryRoot(GHOST_ID);
@@ -67,6 +396,98 @@ describe('LibraryBindingStore', () => {
expect(reread.kind).toBe('custom');
});
+ it('企业实例 storage part 可绑定且与 root 分键;斜杠 id 非法', async () => {
+ const store = new LibraryBindingStore(deps);
+ const orgId = '_ns__acme__mivo-canvas';
+ const set = await store.setBinding(orgId, candidate);
+ expect(set.ok).toBe(true);
+ const resolved = await store.resolveLibraryRoot(orgId);
+ expect(resolved.kind).toBe('custom');
+ if (resolved.kind === 'custom' && resolved.root !== null) {
+ expect(resolved.root).toBe(path.join(await fs.promises.realpath(candidate), orgId));
+ }
+ const rootResolved = await store.resolveLibraryRoot(GHOST_ID);
+ expect(rootResolved.kind).toBe('default');
+ const bad = await store.setBinding('_ns/acme/mivo-canvas', candidate);
+ expect(bad.ok).toBe(false);
+ if (!bad.ok) expect(bad.errorCode).toBe('PATH_INVALID');
+ });
+
+ it('relocates a custom binding key and folder after an in-place instance moves', async () => {
+ const store = new LibraryBindingStore(deps);
+ const fromId = 'hello';
+ const toId = '_ns__acme__hello';
+ const set = await store.setBinding(fromId, candidate);
+ expect(set.ok).toBe(true);
+ const fromRoot = path.join(await fs.promises.realpath(candidate), fromId);
+ await fs.promises.mkdir(fromRoot, { recursive: true });
+ await fs.promises.writeFile(path.join(fromRoot, 'keep.txt'), 'org');
+ await store.relocateBinding(fromId, toId);
+ expect(await store.getBinding(fromId)).toBeNull();
+ expect(await store.getBinding(toId)).not.toBeNull();
+ const resolved = await store.resolveLibraryRoot(toId);
+ expect(resolved.kind).toBe('custom');
+ if (resolved.kind === 'custom' && resolved.root !== null) {
+ expect(resolved.root).toBe(path.join(await fs.promises.realpath(candidate), toId));
+ await expect(fs.promises.readFile(path.join(resolved.root, 'keep.txt'), 'utf8')).resolves.toBe('org');
+ }
+ });
+
+ it('refuses to relocate a binding onto an existing destination', async () => {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ await store.setBinding('_ns__acme__hello', candidate);
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow(
+ 'library binding destination already exists',
+ );
+ expect(await store.getBinding('hello')).not.toBeNull();
+ });
+
+ it('detects a binding conflict before moving the plugin directory', async () => {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ await store.setBinding('_ns__acme__hello', candidate);
+ await expect(store.assertCanRelocateBinding('hello', '_ns__acme__hello')).rejects.toThrow(
+ 'library binding destination already exists',
+ );
+ expect(await store.getBinding('hello')).not.toBeNull();
+ });
+
+
+ it('refuses to relocate onto an existing custom library folder without deleting source', async () => {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ const fromRoot = path.join(await fs.promises.realpath(candidate), 'hello');
+ const toRoot = path.join(await fs.promises.realpath(candidate), '_ns__acme__hello');
+ await fs.promises.mkdir(fromRoot, { recursive: true });
+ await fs.promises.writeFile(path.join(fromRoot, 'keep.txt'), 'org');
+ await fs.promises.mkdir(toRoot, { recursive: true });
+ await fs.promises.writeFile(path.join(toRoot, 'old.txt'), 'orphan');
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow(
+ 'library custom root destination already exists',
+ );
+ expect(await store.getBinding('hello')).not.toBeNull();
+ await expect(fs.promises.readFile(path.join(fromRoot, 'keep.txt'), 'utf8')).resolves.toBe('org');
+ await expect(fs.promises.readFile(path.join(toRoot, 'old.txt'), 'utf8')).resolves.toBe('orphan');
+ });
+
+ it('does not claim an existing destination folder when the source folder is missing', async () => {
+ const store = new LibraryBindingStore(deps);
+ await store.setBinding('hello', candidate);
+ const destination = path.join(await fs.promises.realpath(candidate), '_ns__acme__hello');
+ await fs.promises.mkdir(destination);
+ await fs.promises.writeFile(path.join(destination, 'keep.txt'), 'other');
+ await expect(store.assertCanRelocateBinding('hello', '_ns__acme__hello')).rejects.toThrow(
+ 'library custom root destination already exists',
+ );
+ await expect(store.relocateBinding('hello', '_ns__acme__hello')).rejects.toThrow(
+ 'library custom root destination already exists',
+ );
+ expect(await store.getBinding('hello')).not.toBeNull();
+ expect(await store.getBinding('_ns__acme__hello')).toBeNull();
+ await expect(fs.promises.readFile(path.join(destination, 'keep.txt'), 'utf8')).resolves.toBe('other');
+ });
+
it('重新绑定 generation 递增;撤销后回落默认', async () => {
const store = new LibraryBindingStore(deps);
await store.setBinding(GHOST_ID, candidate);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts
index 28ff8a7322..8bc83eca7a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts
@@ -29,7 +29,7 @@ describe('library extraDirs grant wiring', () => {
it('slot sync refuses to no-op-success when the opener is not library-capable', () => {
expect(body).toContain('async function syncMivoLibraryExtraDirFromSlot(');
- expect(body).toContain('if (root !== null && !isLibraryCapableGhost(findAvailableGhost(ghostId)))');
+ expect(body).toContain('if (root !== null && !isLibraryCapableGhost(findGhostForInstanceId(ghostId)))');
expect(body).toContain('if (libraryExtraDirOwnerGhostId !== null && libraryExtraDirOwnerGhostId !== ghostId)');
expect(body).toContain("if (result === 'granted') libraryExtraDirOwnerGhostId = ghostId;");
expect(body).toContain('return result;');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
index 11ffee7bd1..814617399e 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
@@ -8,6 +8,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import Database from 'better-sqlite3';
+import JSZip from 'jszip';
import {
GhostLibrarySlot,
@@ -20,14 +21,19 @@ import {
} from '../librarySlot.js';
import { createHash } from 'node:crypto';
import { crc32 } from 'node:zlib';
-import { LibraryBindingStore } from '../libraryBinding.js';
+import { LibraryBindingStore, relocateLibraryMetaOwner } from '../libraryBinding.js';
import { LibraryVault } from '../libraryVault.js';
import { initCustomLibraryTree, openExistingCustomLibrary } from '../libraryDirFd.js';
import { createLibraryDbCore, type SqliteDatabaseConstructor } from '../libraryDbCore.js';
import { LibrarySqlService } from '../librarySqlService.js';
+import { GhostManager } from '../GhostManager.js';
+import { findInstalledGhostByInstanceId, installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
+import { GhostInstallReceiptStore } from '../ghostInstallReceipt.js';
+import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess.js';
import {
classifyGhostLibraryOperationSupport,
GHOST_LIBRARY_CAPABILITIES_V1,
+ ghostInstallApprovalToken,
type InstalledGhost,
} from '../../../shared/ghost.js';
@@ -70,6 +76,7 @@ describe('GhostLibrarySlot', () => {
let resolveLibraryRoot: ReturnType<typeof vi.fn>;
let createVault: ReturnType<typeof vi.fn>;
let createSqlService: ReturnType<typeof vi.fn>;
+ let getGhost: GhostLibrarySlotDeps['getGhost'];
let clock: number;
beforeEach(async () => {
@@ -82,6 +89,7 @@ describe('GhostLibrarySlot', () => {
await fs.promises.mkdir(candidate, { recursive: true });
ghost = makeGhost(true);
ghosts = new Map([[GHOST_ID, ghost]]);
+ getGhost = (id) => ghosts.get(id) ?? null;
bindingStore = new LibraryBindingStore({
getFile: () => bindingFile,
getManagedRoots: () => [path.join(tmp, 'managed')],
@@ -100,7 +108,7 @@ describe('GhostLibrarySlot', () => {
}),
);
const deps: GhostLibrarySlotDeps = {
- getGhost: (id) => ghosts.get(id) ?? null,
+ getGhost: (id) => getGhost(id),
bindingStore,
getDefaultRoot: (id) => path.join(defaultRootBase, id),
captureOwnerScope: () => captureOwnerScope(),
@@ -128,6 +136,21 @@ describe('GhostLibrarySlot', () => {
await fs.promises.rm(tmp, { recursive: true, force: true });
});
+ function pauseNextLibraryRootResolution() {
+ let resume!: () => void;
+ let entered!: () => void;
+ const gate = new Promise<void>((resolve) => { resume = resolve; });
+ const started = new Promise<void>((resolve) => { entered = resolve; });
+ const original = LibraryBindingStore.prototype.resolveLibraryRoot.bind(bindingStore);
+ resolveLibraryRoot.mockImplementationOnce(async (id: string) => {
+ const resolution = await original(id);
+ entered();
+ await gate;
+ return resolution;
+ });
+ return { resume, started };
+ }
+
it('资格审:未声明 library 能力/停用 → NOT_DECLARED', async () => {
ghosts.set(GHOST_ID, makeGhost(false));
const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
@@ -304,6 +327,306 @@ describe('GhostLibrarySlot', () => {
expect(backups.some((f) => f.startsWith('pre-migrate-'))).toBe(true);
});
+ async function relocateLibraryState(
+ fromPart: string,
+ toPart: string,
+ afterRelocate?: () => Promise<void>,
+ ): Promise<void> {
+ slot.setRelocating(fromPart, true);
+ slot.setRelocating(toPart, true);
+ try {
+ await slot.disposeGhost(fromPart);
+ await slot.disposeGhost(toPart);
+ const binding = await bindingStore.getBinding(fromPart);
+ let destination: string;
+ if (binding) {
+ await bindingStore.relocateBinding(fromPart, toPart);
+ destination = path.join(binding.realPathAtGrant, toPart);
+ } else {
+ destination = path.join(defaultRootBase, toPart);
+ if (fs.existsSync(destination)) throw new Error('Library relocation destination already exists');
+ await fs.promises.rename(path.join(defaultRootBase, fromPart), destination);
+ }
+ await relocateLibraryMetaOwner(destination, fromPart, toPart);
+ await afterRelocate?.();
+ } finally {
+ try {
+ await slot.disposeGhost(fromPart);
+ await slot.disposeGhost(toPart);
+ } finally {
+ slot.setRelocating(fromPart, false);
+ slot.setRelocating(toPart, false);
+ }
+ }
+ }
+
+ async function seedSourceDatabase(value: string, instanceId = GHOST_ID): Promise<void> {
+ expect(await slot.handleLibraryRequest(instanceId, { op: 'db.open', dbPath: 'library.sqlite' }))
+ .toMatchObject({ ok: true, op: 'db.open' });
+ expect(await slot.handleLibraryRequest(instanceId, {
+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'CREATE TABLE source_state (value TEXT)',
+ })).toMatchObject({ ok: true, op: 'db.exec' });
+ expect(await slot.handleLibraryRequest(instanceId, {
+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'INSERT INTO source_state VALUES (?)', params: [value],
+ })).toMatchObject({ ok: true, op: 'db.exec' });
+ expect(await slot.handleLibraryRequest(instanceId, {
+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'SELECT value FROM source_state',
+ })).toMatchObject({ ok: true, op: 'db.exec', rows: [{ value }] });
+ }
+
+ it.each(['default', 'custom'] as const)('source archive wrapper isolates the real SQLite %s Library from a replacement source', async (location) => {
+ if (location === 'custom') {
+ expect((await bindingStore.setBinding(GHOST_ID, candidate)).ok).toBe(true);
+ }
+ await seedSourceDatabase('old-source');
+ const archivePart = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__mivo-canvas';
+ await relocateLibraryState(GHOST_ID, archivePart);
+ ghosts.set(GHOST_ID, {
+ ...makeGhost(true),
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000003' },
+ });
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'open' })).toMatchObject({ ok: true, state: 'ready' });
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'library.sqlite' }))
+ .toMatchObject({ ok: true, op: 'db.open' });
+ expect(await slot.handleLibraryRequest(GHOST_ID, {
+ op: 'db.exec', dbPath: 'library.sqlite',
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'source_state'",
+ })).toMatchObject({ ok: true, op: 'db.exec', rows: [] });
+ await seedSourceDatabase('new-source');
+ const archivedRoot = location === 'custom' ? candidate : defaultRootBase;
+ const archived = new Database(path.join(archivedRoot, archivePart, 'library.sqlite'), { readonly: true });
+ try {
+ expect(archived.prepare('SELECT value FROM source_state').all()).toEqual([{ value: 'old-source' }]);
+ } finally {
+ archived.close();
+ }
+ expect(await slot.handleLibraryRequest(GHOST_ID, {
+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'SELECT value FROM source_state',
+ })).toMatchObject({ ok: true, op: 'db.exec', rows: [{ value: 'new-source' }] });
+ });
+
+ it.each(['default', 'custom'] as const)('source archive wrapper restores the real SQLite %s Library on inverse after failure', async (location) => {
+ if (location === 'custom') {
+ expect((await bindingStore.setBinding(GHOST_ID, candidate)).ok).toBe(true);
+ }
+ await seedSourceDatabase('original-source');
+ const initialService = createSqlService.mock.results[0].value as LibrarySqlService;
+ const archivePart = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__mivo-canvas';
+ await expect(relocateLibraryState(GHOST_ID, archivePart, async () => {
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'library.sqlite' }))
+ .toMatchObject({ ok: false, errorCode: 'LIBRARY_READONLY' });
+ throw new Error('failure before source receipt commit');
+ })).rejects.toThrow('failure before source receipt commit');
+ expect(await initialService.exec(path.join(defaultRootBase, GHOST_ID, 'library.sqlite'), 'SELECT 1'))
+ .toMatchObject({ ok: false, code: 'DB_ERROR' });
+ const originalRoot = location === 'custom' ? candidate : defaultRootBase;
+ expect(fs.existsSync(path.join(originalRoot, GHOST_ID))).toBe(false);
+ await relocateLibraryState(archivePart, GHOST_ID);
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'library.sqlite' }))
+ .toMatchObject({ ok: true, op: 'db.open' });
+ expect(await slot.handleLibraryRequest(GHOST_ID, {
+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'SELECT value FROM source_state',
+ })).toMatchObject({ ok: true, op: 'db.exec', rows: [{ value: 'original-source' }] });
+ expect(await slot.handleLibraryRequest(GHOST_ID, {
+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'INSERT INTO source_state VALUES (?)', params: ['after-rollback'],
+ })).toMatchObject({ ok: true, op: 'db.exec', changes: 1 });
+ expect(fs.existsSync(path.join(originalRoot, archivePart))).toBe(false);
+ const restored = new Database(path.join(originalRoot, GHOST_ID, 'library.sqlite'), { readonly: true });
+ try {
+ expect(restored.prepare('SELECT value FROM source_state ORDER BY rowid').all())
+ .toEqual([{ value: 'original-source' }, { value: 'after-rollback' }]);
+ } finally {
+ restored.close();
+ }
+ });
+
+ it.each(['default', 'custom'] as const)('delayed session creation does not block real Manager %s source archive rollback', async (location) => {
+ const manager = new GhostManager({
+ getRootDir: () => path.join(tmp, 'ghosts'),
+ onArchiveSourceState: relocateLibraryState,
+ mutateSnapshot: async ({ parentDir, ...request }) => runGhostSnapshotWorkerRequest(request, parentDir),
+ });
+ getGhost = (id) => findInstalledGhostByInstanceId(manager.list(), id) ?? null;
+ const pack = async (version: string): Promise<string> => {
+ const zip = new JSZip();
+ zip.file('ghost.json', JSON.stringify({
+ schemaVersion: 2, id: GHOST_ID, name: 'Library regression', version,
+ kind: 'chip', entry: 'main.js', slots: ['library'],
+ }));
+ const file = path.join(tmp, version + '.cindy');
+ await fs.promises.writeFile(file, await zip.generateAsync({ type: 'nodebuffer' }));
+ return file;
+ };
+ expect(await manager.install(await pack('1.0.0'))).toHaveProperty('ghost');
+ const instanceId = installedGhostStoragePart(manager.list()[0]);
+ if (location === 'custom') expect((await bindingStore.setBinding(instanceId, candidate)).ok).toBe(true);
+ await seedSourceDatabase('original-source', instanceId);
+ await slot.disposeGhost(instanceId);
+ const { resume, started } = pauseNextLibraryRootResolution();
+ const pending = slot.handleLibraryRequest(instanceId, { op: 'db.open', dbPath: 'late.sqlite' });
+ await started;
+ const store = (manager as unknown as { receiptStore: GhostInstallReceiptStore }).receiptStore;
+ const write = vi.spyOn(store, 'write').mockImplementationOnce(async () => {
+ expect(manager.list()[0]?.approval.state).toBe('invalid');
+ resume();
+ await pending;
+ throw new Error('simulated receipt write failure');
+ });
+ const archivePart = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__mivo-canvas';
+ let result;
+ try {
+ result = await manager.update(await pack('2.0.0'), {
+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0]?.approval),
+ sourceStateArchiveId: archivePart,
+ });
+ } finally {
+ resume();
+ write.mockRestore();
+ }
+ expect(await pending).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', reason: 'CANCELLED' });
+ expect(result).toMatchObject({ rejection: { code: 'io', reason: 'simulated receipt write failure' } });
+ expect(result).not.toHaveProperty('rejection.rollbackFailed');
+ await manager.retryInterruptedMutationsAfterDbReady();
+ expect(manager.list()[0]).toMatchObject({ manifest: { version: '1.0.0' }, approval: { state: 'approved' } });
+ expect(store.readPendingMutationSync('_ns/_root/' + GHOST_ID).state).toBe('missing');
+ const restoredRoot = path.join(location === 'custom' ? candidate : defaultRootBase, instanceId);
+ expect(fs.existsSync(path.join(restoredRoot, 'late.sqlite'))).toBe(false);
+ expect(fs.existsSync(path.join(location === 'custom' ? candidate : defaultRootBase, archivePart))).toBe(false);
+ const restored = new Database(path.join(restoredRoot, 'library.sqlite'), { readonly: true });
+ try {
+ expect(restored.prepare('SELECT value FROM source_state').all()).toEqual([{ value: 'original-source' }]);
+ } finally {
+ restored.close();
+ }
+ expect(await slot.handleLibraryRequest(instanceId, { op: 'db.open', dbPath: 'library.sqlite' })).toMatchObject({ ok: true });
+ });
+
+ it.each(['open', 'db.open'] as const)('delayed %s and queued writes stay cancelled after relocation flags clear', async (op) => {
+ await seedSourceDatabase('original-source');
+ await slot.disposeGhost(GHOST_ID);
+ const { resume, started } = pauseNextLibraryRootResolution();
+ const pending = slot.handleLibraryRequest(GHOST_ID, { op, dbPath: 'late.sqlite' });
+ await started;
+ const queued = op === 'db.open'
+ ? slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'queued.sqlite' })
+ : undefined;
+ const archivePart = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__mivo-canvas';
+ try {
+ await relocateLibraryState(GHOST_ID, archivePart);
+ } finally {
+ resume();
+ }
+ expect(await pending).toMatchObject({ ok: false, reason: 'CANCELLED' });
+ if (queued) expect(await queued).toMatchObject({ ok: false, reason: 'CANCELLED' });
+ expect(fs.existsSync(path.join(defaultRootBase, GHOST_ID))).toBe(false);
+ await relocateLibraryState(archivePart, GHOST_ID);
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'library.sqlite' })).toMatchObject({ ok: true });
+ });
+
+ it.each(['receipt', 'unapproved', 'directory'] as const)('delayed session creation rejects a changed %s target without relocation', async (change) => {
+ const { resume, started } = pauseNextLibraryRootResolution();
+ const pending = slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ await started;
+ ghosts.set(GHOST_ID, {
+ ...ghost,
+ ...(change === 'directory' ? { dir: '/tmp/replaced-install' } : {
+ approval: change === 'unapproved'
+ ? { state: 'invalid' }
+ : { state: 'approved', revision: '00000000-0000-4000-8000-000000000003' },
+ }),
+ });
+ resume();
+ expect(await pending).toMatchObject({ ok: false, reason: 'CANCELLED' });
+ expect(createVault).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(defaultRootBase, GHOST_ID))).toBe(false);
+ });
+
+ it('locale projection changes keep the same approved Library request and session current', async () => {
+ const original = LibraryBindingStore.prototype.resolveLibraryRoot.bind(bindingStore);
+ resolveLibraryRoot.mockImplementationOnce(async (id: string) => {
+ const resolution = await original(id);
+ ghosts.set(GHOST_ID, {
+ ...ghost, manifest: { ...ghost.manifest, name: 'Localized Library', resolvedLocale: 'en' },
+ });
+ return resolution;
+ });
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'open' })).toMatchObject({ ok: true, state: 'ready' });
+ ghosts.set(GHOST_ID, { ...ghost, manifest: { ...ghost.manifest, resolvedLocale: 'zh-CN' } });
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'library.sqlite' })).toMatchObject({ ok: true });
+ expect(createVault).toHaveBeenCalledTimes(1);
+ expect(createSqlService).toHaveBeenCalledTimes(1);
+ });
+
+ it('queued vault open cannot publish a disposed session after archive', async () => {
+ await seedSourceDatabase('original-source');
+ await slot.disposeGhost(GHOST_ID);
+ let resume!: () => void;
+ let entered!: () => void;
+ const gate = new Promise<void>((resolve) => { resume = resolve; });
+ const started = new Promise<void>((resolve) => { entered = resolve; });
+ const original = LibraryVault.prototype.open;
+ const open = vi.spyOn(LibraryVault.prototype, 'open').mockImplementationOnce(async function (this: LibraryVault) {
+ entered();
+ await gate;
+ return original.call(this);
+ });
+ const pending = slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ await started;
+ const archivePart = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__mivo-canvas';
+ try {
+ await relocateLibraryState(GHOST_ID, archivePart);
+ } finally {
+ resume();
+ open.mockRestore();
+ }
+ expect(await pending).toMatchObject({ ok: false, reason: 'CANCELLED' });
+ expect(fs.existsSync(path.join(defaultRootBase, GHOST_ID))).toBe(false);
+ expect(syncAgentReadonlyExtraDir).not.toHaveBeenCalledWith(GHOST_ID, path.join(defaultRootBase, GHOST_ID));
+ await relocateLibraryState(archivePart, GHOST_ID);
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'open' })).toMatchObject({ ok: true, state: 'ready' });
+ });
+
+ it('delayed db path resolution cannot recreate the original root after relocation', async () => {
+ await seedSourceDatabase('original-source');
+ syncAgentReadonlyExtraDir.mockClear();
+ let resume!: () => void;
+ let entered!: () => void;
+ const gate = new Promise<void>((resolve) => { resume = resolve; });
+ const started = new Promise<void>((resolve) => { entered = resolve; });
+ const original = LibraryVault.prototype.resolveDbTarget;
+ const resolve = vi.spyOn(LibraryVault.prototype, 'resolveDbTarget').mockImplementationOnce(async function (this: LibraryVault, relativePath: string) {
+ const target = await original.call(this, relativePath);
+ entered();
+ await gate;
+ return target;
+ });
+ const pending = slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'late.sqlite' });
+ await started;
+ const archivePart = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__mivo-canvas';
+ try {
+ await relocateLibraryState(GHOST_ID, archivePart);
+ } finally {
+ resume();
+ resolve.mockRestore();
+ }
+ expect(await pending).toMatchObject({ ok: false, reason: 'CANCELLED' });
+ expect(fs.existsSync(path.join(defaultRootBase, GHOST_ID))).toBe(false);
+ await relocateLibraryState(archivePart, GHOST_ID);
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'library.sqlite' })).toMatchObject({ ok: true });
+ });
+
+ it('open during relocation cannot create an empty default root', async () => {
+ slot.setRelocating(GHOST_ID, true);
+ try {
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'open' })).toMatchObject({ ok: false });
+ expect(createVault).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(defaultRootBase, GHOST_ID))).toBe(false);
+ } finally {
+ slot.setRelocating(GHOST_ID, false);
+ }
+ expect(await slot.handleLibraryRequest(GHOST_ID, { op: 'open' })).toMatchObject({ ok: true, state: 'ready' });
+ });
+
it('dbPath 非法/越界 → PATH_INVALID + INVALID_REQUEST', async () => {
await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
const missing = await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open' });
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryStaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryStaging.test.ts
index 9c045c8b9f..bfd3d3cf07 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/libraryStaging.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryStaging.test.ts
@@ -9,7 +9,7 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
-import { LibraryStagingStore, DEFAULT_LIBRARY_STAGING_LIMITS } from '../libraryStaging.js';
+import { LibraryStagingStore, DEFAULT_LIBRARY_STAGING_LIMITS, relocateLibraryStagingOwner } from '../libraryStaging.js';
import { LibraryVault, DEFAULT_LIBRARY_LIMITS } from '../libraryVault.js';
const sha256Of = (s: string | Buffer): string => createHash('sha256').update(s).digest('hex');
@@ -93,6 +93,64 @@ describe('LibraryStagingStore 故障恢复', () => {
return { stagingId: begin.stagingId, digest, bytes: buf.byteLength };
}
+ it('relocates durable manifests and unfinished intents without losing upload identity or bytes', async () => {
+ const originalRoot = path.join(tmp, 'library-staging', ghostId);
+ const original = makeStore(originalRoot);
+ const durable = await beginChunk(original, 'durable', body);
+ expect((await original.commit({ ghostId, stagingId: durable.stagingId })).ok).toBe(true);
+ const unfinished = await beginChunk(original, 'unfinished', 'pending');
+ await original.dispose();
+ const destinationId = '_ns__xd__mivo-canvas';
+ const destinationRoot = path.join(tmp, 'library-staging', destinationId);
+ await fs.promises.rename(originalRoot, destinationRoot);
+ const before = await fs.promises.readFile(path.join(destinationRoot, 'tasks', durable.stagingId, 'manifest.json'), 'utf8');
+ await relocateLibraryStagingOwner(destinationRoot, ghostId, destinationId, 'local:owner-a:1', () => {});
+ await relocateLibraryStagingOwner(destinationRoot, ghostId, destinationId, 'local:owner-a:1', () => {});
+ const after = JSON.parse(await fs.promises.readFile(path.join(destinationRoot, 'tasks', durable.stagingId, 'manifest.json'), 'utf8'));
+ expect(after).toEqual({ ...JSON.parse(before), ghostId: destinationId });
+ const intent = JSON.parse(await fs.promises.readFile(path.join(destinationRoot, 'tasks', unfinished.stagingId, 'intent.json'), 'utf8'));
+ expect(intent).toMatchObject({ ghostId: destinationId, taskId: 'unfinished' });
+ const restored = new LibraryStagingStore({
+ rootDir: destinationRoot, ghostId: destinationId, ownerScopeKey: 'local:owner-a:1',
+ captureOwnerScope: () => scope, getDiskFreeBytes: async () => 1024 ** 4,
+ });
+ expect(await restored.list({ ghostId: destinationId })).toMatchObject({
+ ok: true, items: [expect.objectContaining({ stagingId: durable.stagingId, sha256: durable.digest })],
+ });
+ expect(await restored.read({ ghostId: destinationId, stagingId: durable.stagingId })).toMatchObject({
+ ok: true, content: Buffer.from(body).toString('base64'),
+ });
+ expect(await restored.begin({
+ ghostId: destinationId, taskId: 'new', sourceRevision: 'rev-1',
+ totalBytes: body.length, sha256: sha, mime: 'image/png', recovery,
+ })).toMatchObject({ ok: true });
+ await restored.dispose();
+ });
+
+ it.each(['foreign-plugin', 'foreign-owner', 'corrupt'] as const)('refuses %s task metadata and can resume after repairing it', async (fault) => {
+ const { store, stagingId } = await commitOne();
+ await store.dispose();
+ const root = path.join(tmp, 'library-staging', ghostId);
+ const file = path.join(root, 'tasks', stagingId, 'manifest.json');
+ const original = await fs.promises.readFile(file, 'utf8');
+ const changed = fault === 'corrupt' ? '{' : JSON.stringify({
+ ...JSON.parse(original), ...(fault === 'foreign-plugin' ? { ghostId: 'other' } : { ownerScopeKey: 'local:owner-b:1' }),
+ });
+ await fs.promises.writeFile(file, changed);
+ await expect(relocateLibraryStagingOwner(root, ghostId, '_ns__xd__mivo-canvas', 'local:owner-a:1', () => {})).rejects.toThrow();
+ expect(await fs.promises.readFile(file, 'utf8')).toBe(changed);
+ expect(await fs.promises.readFile(path.join(root, 'tasks', stagingId, 'blob.bin'), 'utf8')).toBe(body);
+ await fs.promises.writeFile(file, original);
+ await relocateLibraryStagingOwner(root, ghostId, '_ns__xd__mivo-canvas', 'local:owner-a:1', () => {});
+ expect(JSON.parse(await fs.promises.readFile(file, 'utf8'))).toMatchObject({ ghostId: '_ns__xd__mivo-canvas' });
+ });
+
+ it('does not create a missing staging root', async () => {
+ const root = path.join(tmp, 'missing');
+ await relocateLibraryStagingOwner(root, ghostId, '_ns__xd__mivo-canvas', 'local:owner-a:1', () => {});
+ await expect(fs.promises.stat(root)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
async function commitOne(
store = makeStore(),
taskId = 'task-1',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts
index 6ad9228aa5..0a421c9caf 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts
@@ -20,6 +20,7 @@ import {
type LibraryReadHandle,
} from '../libraryVault.js';
import { initCustomLibraryTree, openExistingCustomLibrary, parseExistingStdout, PROVABLE_STAGING_NAME } from '../libraryDirFd.js';
+import { relocateLibraryMetaOwner } from '../libraryBinding.js';
const sha256Of = (s: string): string => createHash('sha256').update(s).digest('hex');
@@ -109,6 +110,38 @@ describe('LibraryVault', () => {
});
describe('open / status / meta', () => {
+ it('does not open a default library whose persisted owner differs from the plugin', async () => {
+ const previous = makeVault({ ghostId: 'other-plugin' });
+ expect(await previous.open()).toMatchObject({ ok: true, state: 'ready' });
+ await fs.promises.writeFile(path.join(libraryRoot, 'keep.txt'), 'private');
+ const current = makeVault();
+ expect(await current.open()).toMatchObject({ ok: true, state: 'unavailable', reason: 'corrupt' });
+ expect(await fs.promises.readFile(path.join(libraryRoot, 'keep.txt'), 'utf8')).toBe('private');
+ });
+
+ it('opens a physically relocated library after its owner meta is migrated', async () => {
+ const original = path.join(tmpRoot, 'libraries', 'hello');
+ const previous = makeVault({ rootDir: () => original, ghostId: 'hello' });
+ expect(await previous.open()).toMatchObject({ ok: true, state: 'ready' });
+ await fs.promises.writeFile(path.join(original, 'keep.txt'), 'org');
+ const destination = path.join(tmpRoot, 'libraries', '_ns__acme__hello');
+ await fs.promises.rename(original, destination);
+ expect(await relocateLibraryMetaOwner(destination, 'hello', '_ns__acme__hello')).toBe(true);
+ const current = makeVault({ rootDir: () => destination, ghostId: '_ns__acme__hello' });
+ expect(await current.open()).toMatchObject({ ok: true, state: 'ready' });
+ expect(await fs.promises.readFile(path.join(destination, 'keep.txt'), 'utf8')).toBe('org');
+ });
+
+ it('does not open a custom library whose persisted owner differs from the plugin', async () => {
+ const parent = path.join(tmpRoot, 'picked-owner');
+ const custom = path.join(parent, 'test-ghost');
+ await fs.promises.mkdir(parent, { recursive: true });
+ const previous = makeVault({ rootDir: () => custom, locationKind: 'custom', ghostId: 'other-plugin' });
+ expect(await previous.open()).toMatchObject({ ok: true, state: 'ready' });
+ const current = makeVault({ rootDir: () => custom, locationKind: 'custom' });
+ expect(await current.open()).toMatchObject({ ok: true, state: 'unavailable', reason: 'binding-moved' });
+ });
+
it('open 建骨架并写 meta;重复 open 幂等', async () => {
const vault = makeVault();
const first = await vault.open();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index cfe8e456c5..f4daa40e5f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -148,10 +148,53 @@ describe('market Ghost session boundary', () => {
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;');
+ 'const resolved = resolveInstalledGhost(availableGhosts(), id, namespace);',
+ );
+ const resolverStart = source.indexOf('export function findGhostForInstanceId(');
+ const resolverBody = source.slice(resolverStart, source.indexOf('\n}', resolverStart));
+ expect(resolverBody.match(/availableGhosts\(\)/g)).toHaveLength(1);
+ expect(resolverBody).toContain('resolvePluginInstanceQuery(availableGhosts(), id, namespace)');
+ expect(resolverBody).not.toContain('findInstalledGhostByInstanceId');
+ expect(resolverBody).not.toContain('if (namespace === undefined)');
+ expect(source.match(/getGhost: findAvailableGhost/g)?.length ?? 0).toBe(0);
+ expect(source.match(/getGhost: findGhostForInstanceId/g)?.length ?? 0).toBeGreaterThanOrEqual(12);
+ expect(resolverBody).toContain(
+ "return resolved.status === 'unique' ? resolved.ghost : null;",
+ );
+ expect(source).toContain('availableByInstanceId.get(entry.ghostId)');
+ expect(source).toContain('hasCardSlot: (ghostId) => {');
+ expect(source).toContain('const g = findGhostForPhysicalStoragePart(ghostId);');
+ expect(source).toContain(
+ 'export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLibraryOverview> {',
+ );
+ const overviewStart = source.indexOf(
+ 'export async function getGhostLibraryOverview(ghostId: string)',
+ );
+ expect(source.slice(overviewStart, overviewStart + 280)).toContain(
+ 'const ghost = findGhostForInstanceId(ghostId);',
+ );
+ const assessStart = source.indexOf(
+ 'export function getGhostSetupAssessment(ghostId: string)',
+ );
+ const assessBody = source.slice(assessStart, assessStart + 1600);
+ expect(assessBody).toContain('const ghost = findGhostForInstanceId(ghostId);');
+ expect(assessBody).toContain('const storeId = installedGhostStoragePart(ghost);');
+ expect(assessBody).toContain('getGhostSetupProbes(storeId, runtimeManifest)');
+ expect(assessBody).not.toContain('oauthManager.listAccounts(ghostId, key)');
+ const probesStart = source.indexOf('function getGhostSetupProbes(');
+ const probesBody = source.slice(probesStart, source.indexOf('export function getGhostSetupAssessment', probesStart));
+ expect(probesBody).toContain('oauthManager.listAccounts(storeId, key)');
+ expect(probesBody).not.toContain('oauthManager.listAccounts(ghostId, key)');
+ expect(source).toContain('return findGhostForInstanceId(id)?.manifest.name ?? null;');
+ });
+
+ it('blocks relocation and source archival while a private filesystem request is in flight', () => {
+ const start = source.indexOf('function assertGhostRelocationIdle(part: string): void {');
+ const guard = source.slice(start, source.indexOf('\n}', start));
+ expect(guard).toContain('fsSlotSingleton?.hasInFlightRequests(part)');
+ expect(source).toContain('assertGhostRelocationIdle(fromPart);');
+ expect(source).toContain('if (sourceChanged) assertGhostRelocationIdle(instanceId);');
+ expect(source).toContain('if (expected.sourceChanged) assertGhostRelocationIdle(installedGhostStoragePart(installed));');
});
it('allows explicit local replacement and detaches market routing before landing', () => {
@@ -171,7 +214,7 @@ describe('market Ghost session boundary', () => {
const helperBody = source.slice(helperStart, helperEnd);
const ledgerReadIndex = helperBody.indexOf(
- 'marketLedger.installationForGhost(inspected.manifest.id)',
+ '= readLocalGhostUpdateSource(',
);
const captureIndex = updateBody.indexOf('const mutationOwner = captureGhostMutationOwner();');
const inspectIndex = updateBody.indexOf('await manager.inspect(lizFilePath)');
@@ -181,16 +224,18 @@ describe('market Ghost session boundary', () => {
const detachDecisionIndex = helperBody.indexOf(
'const detachMarketRecord = Boolean(marketRecord?.installed)',
);
- const runtimeStopIndex = helperBody.indexOf('runtime.stop(inspected.manifest.id)');
+ const runtimeStopIndex = helperBody.indexOf(
+ 'runtime.stop(instanceId)',
+ );
const stopAndWaitIndex = helperBody.indexOf(
- 'await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);',
+ 'await getGhostNodeRuntimeBroker().stopAndWait(instanceId);',
);
const oauthLockIndex = helperBody.indexOf(
- 'result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id',
+ 'result = await withActiveOwnerGhostOauthMutationLock(',
);
const managerUpdateIndex = helperBody.indexOf('manager.update(cindyFilePath,');
const detachIndex = helperBody.indexOf(
- 'marketLedger.markRemoved(inspected.manifest.id, null)',
+ 'marketLedger.markRemovedRecord(marketRecord, null)',
);
expect(captureIndex).toBeGreaterThan(-1);
@@ -199,7 +244,8 @@ describe('market Ghost session boundary', () => {
expect(helperCallIndex).toBeGreaterThan(leaseIndex);
expect(ledgerBindIndex).toBeGreaterThan(-1);
expect(runtimeStopIndex).toBeGreaterThan(ledgerBindIndex);
- expect(ledgerReadIndex).toBeGreaterThan(stopAndWaitIndex);
+ expect(ledgerReadIndex).toBeGreaterThan(ledgerBindIndex);
+ expect(ledgerReadIndex).toBeLessThan(runtimeStopIndex);
expect(detachDecisionIndex).toBeGreaterThan(ledgerReadIndex);
expect(stopAndWaitIndex).toBeGreaterThan(runtimeStopIndex);
// 只有确认旧进程退出,才切断旧市场的自动更新路由;等待失败时保留原路由,
@@ -210,6 +256,7 @@ describe('market Ghost session boundary', () => {
expect(oauthLockIndex).toBeGreaterThan(detachIndex);
expect(managerUpdateIndex).toBeGreaterThan(oauthLockIndex);
expect(helperBody).toContain('marketLedger.restoreInstallation(');
+ expect(helperBody).toContain('...deliveryNamespaceFields(previousGhost)');
expect(helperBody).not.toContain('marketLedger.isDefaultInstallSuppressed(');
expect(helperBody).not.toContain('marketInstallSubject');
expect(helperBody).toContain('用户显式卸载,不得产生 default-install opt-out');
@@ -238,16 +285,24 @@ describe('market Ghost session boundary', () => {
expect(body.match(/expected\.beforeCommitInLock\?\.\(\);/g)).toHaveLength(1);
const waitIndex = body.indexOf(
- 'await getGhostNodeRuntimeBroker().stopAndWait(expected.ghostId);',
+ 'await getGhostNodeRuntimeBroker().stopAndWait(',
);
const oauthLockIndex = body.indexOf(
- 'await withActiveOwnerGhostOauthMutationLock(expected.ghostId',
+ 'await withActiveOwnerGhostOauthMutationLock(installedGhostStoragePart(installed)',
);
const updateIndex = body.indexOf('manager.update(cindyFilePath,');
expect(waitIndex).toBeGreaterThan(-1);
expect(waitIndex).toBeLessThan(oauthLockIndex);
expect(oauthLockIndex).toBeLessThan(updateIndex);
+ expect(body).toContain('runtime.stop(installedGhostStoragePart(installed));');
+ expect(body).toContain(
+ 'await getGhostNodeRuntimeBroker().stopAndWait(installedGhostStoragePart(installed));',
+ );
+ expect(body).toContain('runtime.resetFuse(installedGhostStoragePart(result.ghost));');
+ expect(body).not.toContain(
+ 'pluginStoragePart(createPluginLogicalIdentity(expected.namespace ?? null, expected.ghostId))',
+ );
const restoreIndex = body.indexOf('spawnIfResident(installed);');
expect(restoreIndex).toBeGreaterThan(updateIndex);
});
@@ -264,14 +319,14 @@ describe('market Ghost session boundary', () => {
const helperBody = source.slice(helperStart, helperEnd);
const waitIndex = helperBody.indexOf(
- 'await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);',
+ 'await getGhostNodeRuntimeBroker().stopAndWait(instanceId);',
);
const oauthLockIndex = helperBody.indexOf(
- 'result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id',
+ 'result = await withActiveOwnerGhostOauthMutationLock(',
);
const updateIndex = helperBody.indexOf('manager.update(cindyFilePath');
const restoreIndex = helperBody.indexOf(
- 'if (previousGhost) spawnIfResident(previousGhost);',
+ 'spawnIfResident(previousGhost);',
);
// stopAndWait must be called before manager.update (safe directory
@@ -284,7 +339,12 @@ describe('market Ghost session boundary', () => {
// stopAndWait (rollback if provenance check fails).
expect(restoreIndex).toBeGreaterThan(waitIndex);
expect(updateBody).toContain('finally {\n releaseMutation();');
- expect(helperBody).toContain("throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');");
+ const provenanceStart = source.indexOf('function readLocalGhostUpdateSource(');
+ const provenanceBody = source.slice(provenanceStart, helperStart);
+ expect(provenanceBody).toContain("throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');");
+ expect(provenanceBody).toContain('installationForPlugin({');
+ expect(provenanceBody).toContain('...deliveryNamespaceFields(previousGhost)');
+ expect(helperBody.indexOf('= readLocalGhostUpdateSource(')).toBeLessThan(waitIndex);
expect(helperBody).toContain("throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');");
});
@@ -322,10 +382,13 @@ describe('market Ghost session boundary', () => {
// 捕获)。它的落仓路径(ghost-gallery 作品归属 + recordGhostCallMedia)必须同样
// 有本地 owner 守卫 + assertStillValid + 补偿 journal,否则账号切换期间的
// as:'media' fetch 仍可能落仓到错误 owner 的画廊。
- const networkStart = source.indexOf('saveGhostMedia: async ({ ghostId, buffer, mimeType, label, callId }) =>');
+ const networkStart = source.indexOf('saveGhostMedia: async ({ ghostId, buffer, mimeType, label, callId, assertStillValid }) =>');
expect(networkStart).toBeGreaterThan(-1);
const networkBody = source.slice(networkStart, networkStart + 1800);
expect(networkBody).toContain('const ownerScopeKey = activeOwnerScopeKey();');
+ expect(networkBody).toContain('assertStillValid?.();');
+ expect(source).toContain('captureRequestGuard: captureGhostNetworkRequestGuard');
+ expect(source).toContain('networkSlotSingleton?.hasInFlightRequests(part)');
expect(networkBody).toContain('isGhostBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey');
expect(networkBody).toContain('assertStillValid: assertOwnerScopeCurrent');
expect(networkBody).toContain('refCompensationScope: captureMediaRefCompensationScope(ownerScopeKey)');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
index f68aab0ede..fe8908e376 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
@@ -2,7 +2,8 @@ import { describe, expect, it, vi } from 'vitest';
import { MobilePluginPages } from '../mobilePageService.js';
import type { InstalledGhost } from '../../../shared/ghost.js';
import { toGhostPluginDetail } from '../../../renderer/features/plugin/lib/ghostPluginViewModel.js';
-
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
+import { parseRemoteResourceGetRequest, type PluginPageDocument } from '@cindy/device-link';
function setup(
projection: Pick<
ConstructorParameters<typeof MobilePluginPages>[0],
@@ -23,6 +24,12 @@ function setup(
enabled: true,
approval: { state: 'approved', revision: 'r1' },
} as InstalledGhost;
+ const ghosts = [ghost];
+ const setEnabled = vi.fn(async (id: string, enabled: boolean) => {
+ const target = ghosts.find((candidate) => installedGhostStoragePart(candidate) === id);
+ if (target) target.enabled = enabled;
+ });
+ const taskSettings = { read: vi.fn(() => ({} as never)), update: vi.fn(async () => ({} as never)) };
const clearUnread = vi.fn(),
post = vi.fn(),
disconnect = vi.fn(async () => {}),
@@ -38,7 +45,7 @@ function setup(
const captured = peerGeneration;
return () => captured === peerGeneration;
},
- list: () => [ghost],
+ list: () => ghosts,
revision: () => revision,
captureOwner: () => {
const expected = owner;
@@ -46,9 +53,8 @@ function setup(
},
unread: () => ({ at: unreadAt, summary: 'New course' }),
clearUnread,
- setEnabled: async (_id, enabled) => {
- ghost.enabled = enabled;
- },
+ setEnabled,
+ taskSettings,
bundle: async () => [{ path: 'panel.html', mime: 'text/html', size: 3 }],
asset: async () => ({ mime: 'text/html', base64: 'YWJj' }),
connect: async () => {},
@@ -82,6 +88,9 @@ function setup(
invoke,
open,
ghost,
+ ghosts,
+ setEnabled,
+ taskSettings,
clearUnread,
post,
disconnect,
@@ -135,6 +144,40 @@ describe('mobile plugin pages', () => {
);
expect(list.items[0].actions?.find((action) => action.id === 'enable')?.disabled).toBe(true);
});
+ it.each([true, false])('keeps same-name resource details and mutations instance-bound (root first: %s)', async (rootFirst) => {
+ const fixture = setup();
+ const root = { ...fixture.ghost, namespace: null, dir: '/ghosts/_ns/_root/practice',
+ manifest: { ...fixture.ghost.manifest, name: 'Root', agent: { tasks: true } } } as InstalledGhost;
+ const organization = { ...fixture.ghost, namespace: 'acme', dir: '/ghosts/practice',
+ manifest: { ...fixture.ghost.manifest, name: 'Organization', agent: { tasks: true } } } as InstalledGhost;
+ fixture.ghosts.splice(0, 1, ...(rootFirst ? [root, organization] : [organization, root]));
+ const context = { controllerDeviceId: 'phone-a' };
+ const client = { protocolVersion: 1, primitives: ['plugin-page'] };
+ const list = await fixture.provider.list(context, { collectionId: 'plugins', client });
+ expect(new Set(list.items.map((item) => item.ref.id)).size).toBe(2);
+ const ref = list.items.find((item) => item.display.title === 'Root')!.ref;
+ expect((await fixture.provider.get!(context, { ref, client })).display.title).toBe('Root');
+ const opened = await fixture.provider.invoke!(context, { collectionId: 'plugins', resourceRef: ref,
+ actionId: 'open:panel', input: {}, client });
+ expect((opened.result as PluginPageDocument).pluginId).toBe('_root__practice');
+ await fixture.provider.invoke!(context, { collectionId: 'plugins', resourceRef: ref,
+ actionId: 'task-settings:set', input: { permissionMode: 'auto' }, client });
+ expect(fixture.taskSettings.update).toHaveBeenCalledWith('_root__practice', 'r1', { permissionMode: 'auto' }, expect.any(Function));
+ await fixture.provider.invoke!(context, { collectionId: 'plugins', resourceRef: ref, actionId: 'disable', input: {}, client });
+ expect(fixture.setEnabled).toHaveBeenCalledWith('_root__practice', false);
+ expect(organization.enabled).toBe(true);
+ });
+ it('keeps the longest valid physical identity usable through the wire parser', async () => {
+ const fixture = setup();
+ fixture.ghost.namespace = 'a'.repeat(128);
+ fixture.ghost.manifest.id = 'p'.repeat(32);
+ fixture.ghost.dir = '/ghosts/_ns/' + fixture.ghost.namespace + '/' + fixture.ghost.manifest.id;
+ const context = { controllerDeviceId: 'phone-a' }, client = { protocolVersion: 1, primitives: ['plugin-page'] };
+ const list = await fixture.provider.list(context, { collectionId: 'plugins', client });
+ const request = parseRemoteResourceGetRequest({ ref: list.items[0].ref, client });
+ expect(request).not.toBeNull();
+ expect((await fixture.provider.get!(context, request!)).display.title).toBe('Practice');
+ });
it('keeps a covered native preview readable but rejects source writes, unread consumption and another controller', async () => {
const h = setup(),
page = await h.open();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
index b5865dd593..478ff72ba6 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
@@ -137,6 +137,98 @@ function makeSlot(overrides: Partial<NetworkSlotDeps> = {}): {
const BRAVE_URL = 'https://api.search.brave.com/res/v1/web/search?q=hi';
+describe('network request installation binding', () => {
+ it.each(['redirect-credential', '401-response'] as const)('does not dispatch or invalidate after replacement during %s', async (phase) => {
+ for (const replaced of [false, true]) {
+ let current = true;
+ let credentialReads = 0;
+ let requestCount = 0;
+ const invalidate = vi.fn();
+ const fetchImpl = vi.fn(async () => {
+ requestCount += 1;
+ if (requestCount > 1) return fakeResponse();
+ if (phase === '401-response') current = !replaced;
+ return fakeResponse({ status: phase === '401-response' ? 401 : 302,
+ headers: { location: `${BRAVE_URL}&redirect=1` } });
+ });
+ const { slot } = makeSlot({
+ captureRequestGuard: () => () => { if (!current) throw new Error('installation changed'); },
+ getGhost: () => fakeGhost({ network: { hosts: ['api.search.brave.com'], secrets: [{
+ key: 'token', label: 'Token', source: 'oidc-token',
+ inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['api.search.brave.com'] },
+ }] } }),
+ connectionTokens: {
+ resolve: () => ({ membershipId: 'membership', audience: 'acme:web-search', allowedHosts: ['api.search.brave.com'] }),
+ getToken: async () => {
+ credentialReads += 1;
+ if (phase === 'redirect-credential' && credentialReads === 2) current = !replaced;
+ return 'token';
+ },
+ invalidate,
+ },
+ fetchImpl,
+ });
+ expect((await slot.handleFetchRequest('web-search', { url: BRAVE_URL })).ok).toBe(!replaced);
+ expect(fetchImpl).toHaveBeenCalledTimes(replaced ? 1 : 2);
+ expect(invalidate).toHaveBeenCalledTimes(phase === '401-response' && !replaced ? 1 : 0);
+ }
+ });
+
+ it.each([false, true])('rejects late media after target replacement (replaced=%s)', async (replaced) => {
+ let target = 'original';
+ let releaseResponse!: (response: Response) => void;
+ let markStarted!: () => void;
+ const started = new Promise<void>((resolve) => { markStarted = resolve; });
+ const writeSaveDeposit = vi.fn(async () => ({ fileName: 'old.png' }));
+ const { slot, saveGhostMedia } = makeSlot({
+ captureRequestGuard: () => {
+ const expected = target;
+ return () => { if (target !== expected) throw new Error('installation changed'); };
+ },
+ fetchImpl: async () => {
+ markStarted();
+ return new Promise<Response>((resolve) => { releaseResponse = resolve; });
+ },
+ writeSaveDeposit,
+ });
+ const fetching = slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ await started;
+ if (replaced) target = 'replacement';
+ releaseResponse(fakeResponse({ headers: { 'content-type': 'image/png' }, body: toArrayBuffer(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) }));
+ expect((await fetching).ok).toBe(!replaced);
+ expect(saveGhostMedia).toHaveBeenCalledTimes(replaced ? 0 : 1);
+ expect(writeSaveDeposit).not.toHaveBeenCalled();
+ });
+
+ it('includes asynchronous credential preparation in relocation idle checks', async () => {
+ let releaseCredential!: () => void;
+ let markStarted!: () => void;
+ const started = new Promise<void>((resolve) => { markStarted = resolve; });
+ const { slot } = makeSlot({
+ getGhost: () => fakeGhost({ network: { hosts: ['api.search.brave.com'], secrets: [{
+ key: 'token', label: 'Token', source: 'oidc-token',
+ inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['api.search.brave.com'] },
+ }] } }),
+ connectionTokens: {
+ resolve: () => ({ membershipId: 'membership', audience: 'acme:web-search', allowedHosts: ['api.search.brave.com'] }),
+ getToken: async () => {
+ markStarted();
+ await new Promise<void>((resolve) => { releaseCredential = resolve; });
+ return 'token';
+ },
+ invalidate: vi.fn(),
+ },
+ });
+ const fetchPreparing = slot.handleFetchRequest('web-search', { url: BRAVE_URL });
+ await started;
+ const busy = slot.hasInFlightRequests?.('web-search');
+ releaseCredential();
+ await fetchPreparing;
+ expect(busy).toBe(true);
+ expect(slot.hasInFlightRequests?.('web-search')).toBe(false);
+ });
+});
+
describe('networkSlot · 载荷与 URL 校验', () => {
it('url 缺失/非 https/带端口/内嵌凭证/不是绝对地址一律拒', async () => {
const { slot } = makeSlot();
@@ -1559,6 +1651,21 @@ describe('networkSlot · GitHub CLI 优先凭证(source:gh-cli)', () => {
expect(readGhCliToken).not.toHaveBeenCalled();
expect(fetchImpl).not.toHaveBeenCalled();
});
+
+ it('组织同名或尚未确认 root 的 cindy-github 不能借用 gh-cli token', async () => {
+ for (const identity of [{ namespace: 'acme' }, { namespaceState: 'pending' }] as const) {
+ const readGhCliToken = vi.fn(async () => 'gho_should_not_be_read');
+ const { slot, fetchImpl } = makeGithubSlot({
+ getGhost: () => ({ ...fakeGhost({ id: 'cindy-github', network: githubNetwork,
+ trust: { level: 'cindy-official', publisherSigned: true, publisherVerified: true,
+ reviewed: true, publisherName: 'Cindy Plugin Market' } }), ...identity }),
+ readGhCliToken,
+ });
+ expect((await slot.handleFetchRequest('web-search', { url: GITHUB_URL })).ok).toBe(false);
+ expect(readGhCliToken).not.toHaveBeenCalled();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ }
+ });
});
describe('networkSlot · 目录上传(uploadDir,过户票据)', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
index 618b193ee1..aa747a85d1 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
@@ -545,6 +545,36 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {
broker.destroyAll();
});
+
+ it('同 ghostId 的 root 与企业实例可同时跑 Node 进程', async () => {
+ const rootGhost = fakeGhost();
+ const orgGhost: InstalledGhost = { ...fakeGhost(), namespace: 'acme', dir: '/fake/_ns/acme/node-ghost' };
+ const children: FakeNodeProcess[] = [];
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: (id) => {
+ if (id === '_ns__acme__node-ghost') return orgGhost;
+ if (id === 'node-ghost') return rootGhost;
+ return null;
+ },
+ spawnProcess: () => {
+ const child = makeAutoReplyProcess();
+ children.push(child);
+ return child as unknown as NodeWorkerProcess;
+ },
+ });
+
+ expect(await broker.handleRequest('node-ghost', rpcRequest('root'))).toMatchObject({ ok: true });
+ expect(await broker.handleRequest('_ns__acme__node-ghost', rpcRequest('org'))).toMatchObject({
+ ok: true,
+ });
+ expect(children).toHaveLength(2);
+ expect(broker.stateOf('node-ghost')).toBe('running');
+ expect(broker.stateOf('_ns__acme__node-ghost')).toBe('running');
+ broker.stop('node-ghost');
+ expect(broker.stateOf('node-ghost')).toBe('off');
+ expect(broker.stateOf('_ns__acme__node-ghost')).toBe('running');
+ broker.destroyAll();
+ });
it('停用式 stop 立即拒绝在途请求并关闭进程', async () => {
const ghost = fakeGhost();
const child = new FakeNodeProcess(); // 不回 response,保持在途
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeCancellation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeCancellation.test.ts
index 7b37fd49b3..8a4cedaf84 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeCancellation.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeCancellation.test.ts
@@ -42,14 +42,18 @@ afterEach(() => {
for (const b of brokers.splice(0)) b.destroyAll();
});
-function harness(autoSpawn = true, extra: Partial<GhostNodeRuntimeBrokerDeps> = {}) {
+function harness(
+ autoSpawn = true,
+ extra: Partial<GhostNodeRuntimeBrokerDeps> = {},
+ identity?: { ghost?: InstalledGhost; requestId?: string },
+) {
const worker = new Worker();
const children: Worker[] = [];
const calls = new Map([
['call-a', new AbortController()],
['call-b', new AbortController()],
]);
- const ghost = {
+ const ghost = identity?.ghost ?? {
manifest: {
id: 'test-plugin',
name: 'Test',
@@ -65,11 +69,12 @@ function harness(autoSpawn = true, extra: Partial<GhostNodeRuntimeBrokerDeps> =
dir: path.resolve('test-plugin'),
enabled: true,
} as InstalledGhost;
+ const requestId = identity?.requestId ?? ghost.manifest.id;
const broker = new GhostNodeRuntimeBroker({
...extra,
- getGhost: () => ghost,
- getCallSignal: (id, callId) =>
- id === 'test-plugin' ? (calls.get(callId)?.signal ?? null) : null,
+ getGhost: extra.getGhost ?? (() => ghost),
+ getCallSignal: extra.getCallSignal ?? ((id, callId) =>
+ id === requestId ? (calls.get(callId)?.signal ?? null) : null),
spawnProcess: () => {
queueMicrotask(() => worker.emit('spawn'));
return worker as NodeWorkerProcess;
@@ -82,7 +87,7 @@ function harness(autoSpawn = true, extra: Partial<GhostNodeRuntimeBrokerDeps> =
});
brokers.push(broker);
const request = (callId?: string) =>
- broker.handleRequest('test-plugin', {
+ broker.handleRequest(requestId, {
type: 'node-request',
method: 'tools/call',
params: { name: 'login' },
@@ -368,6 +373,61 @@ describe('Node private authorization bridge', () => {
);
await second;
});
+
+ it('looks up remote authorization by physical instance id, not manifest ghostId', async () => {
+ const storagePart = '_ns__acme__test-plugin';
+ const orgGhost = {
+ manifest: {
+ id: 'test-plugin',
+ name: 'Test',
+ version: '1.0.0',
+ network: { hosts: ['provider.example'] },
+ node: {
+ entry: 'worker.cjs',
+ entries: ['child.cjs'],
+ protocol: 'json-rpc-stdio',
+ childSpawn: true,
+ },
+ },
+ namespace: 'acme',
+ dir: '/fake/_ns/acme/test-plugin',
+ enabled: true,
+ } as InstalledGhost;
+ let input!: Parameters<NonNullable<GhostNodeRuntimeBrokerDeps['openDeviceAuthorization']>>[0];
+ const open = vi.fn((value: typeof input) => {
+ input = value;
+ return { opened: Promise.resolve(), finish: vi.fn(), dispose: vi.fn() };
+ });
+ const h = harness(
+ true,
+ {
+ getGhost: (id) => (id === storagePart ? orgGhost : null),
+ getCallSessionId: (g, id) =>
+ g === storagePart && id === 'call-a' ? 'trusted-session' : null,
+ openDeviceAuthorization: open,
+ },
+ { ghost: orgGhost, requestId: storagePart },
+ );
+ const result = h.request('call-a');
+ await until(() => h.worker.requests.length === 1);
+ h.worker.listener?.({
+ type: 'device-authorize',
+ reqId: 'authorize-ns',
+ rpcId: h.worker.requests[0].id,
+ url: 'https://provider.example/device',
+ });
+ await until(() => h.worker.controls.some((x) => x.reqId === 'authorize-ns'));
+ expect(open).toHaveBeenCalledTimes(1);
+ expect(h.worker.controls.find((x) => x.reqId === 'authorize-ns')).toMatchObject({ ok: true });
+ expect(input.ghost.id).toBe(storagePart);
+ expect(input.sessionId).toBe('trusted-session');
+ input.assertCurrent();
+ h.worker.stdout.write(
+ JSON.stringify({ jsonrpc: '2.0', id: h.worker.requests[0].id, result: { ok: true } }) + '\n',
+ );
+ expect(await result).toEqual({ ok: true, result: { ok: true } });
+ });
+
it.each([true, false])(
'finishes the authorization before invalidating its binding (CLI ok=%s)',
async (ok) => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts
index f925d25acf..c4631393cc 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts
@@ -3,6 +3,7 @@
import { describe, expect, it, vi } from 'vitest';
import type { InstalledGhost } from '../../../shared/ghost';
+import { installedGhostMutationTargetToken } from '../../../shared/pluginIdentity';
import { GhostPickSlot, type PickSlotDeps } from '../pickSlot';
function pickGhost(options: { pick?: boolean; node?: boolean; enabled?: boolean } = {}): InstalledGhost {
@@ -28,6 +29,7 @@ function makeSlot(overrides: Partial<PickSlotDeps> = {}) {
let clock = 0;
const deps: PickSlotDeps = {
getGhost: () => pickGhost(),
+ getMutationTarget: () => 'installed-target',
showDirectoryDialog: vi.fn(async () => '/Users/me/projects'),
depositDir: vi.fn(() => ({
ok: true as const,
@@ -155,6 +157,54 @@ describe('pickSlot · 授权 = 用户亲选', () => {
});
});
+describe('pickSlot · 晚到的选择结果', () => {
+ it.each(['root-reuse', 'source-switch', 'owner-switch', 'disabled', 'unchanged'])(
+ '%s 不把旧授权交给新目标',
+ async (change) => {
+ let current = {
+ ...pickGhost(),
+ namespace: 'acme' as string | null,
+ approval: { state: 'approved' as const, revision: 'receipt-1' },
+ };
+ let owner = 'owner-1';
+ let release!: (value: string | null) => void;
+ const dialog = new Promise<string | null>((resolve) => { release = resolve; });
+ const recordPickedDir = vi.fn();
+ const { slot, deps } = makeSlot({
+ getGhost: () => current,
+ getMutationTarget: () => installedGhostMutationTargetToken(current, owner),
+ showDirectoryDialog: () => dialog,
+ recordPickedDir,
+ });
+ const pending = slot.handleRequest('pick-ghost', { mode: 'directory', deposit: true });
+ if (change === 'root-reuse') current = { ...current, namespace: null };
+ if (change === 'source-switch') {
+ current = { ...current, approval: { state: 'approved', revision: 'receipt-2' } };
+ }
+ if (change === 'owner-switch') owner = 'owner-2';
+ if (change === 'disabled') current = { ...current, enabled: false };
+ release('/Users/me/projects');
+ if (change === 'unchanged') {
+ expect(await pending).toMatchObject({ ok: true });
+ expect(recordPickedDir).toHaveBeenCalledOnce();
+ expect(deps.depositDir).toHaveBeenCalledOnce();
+ } else {
+ expect(await pending).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(recordPickedDir).not.toHaveBeenCalled();
+ expect(deps.depositDir).not.toHaveBeenCalled();
+ }
+ },
+ );
+
+ it('无法绑定目标时不打开选择框', async () => {
+ const { slot, deps } = makeSlot({ getMutationTarget: () => null });
+ expect(await slot.handleRequest('pick-ghost', { mode: 'directory' })).toMatchObject({
+ ok: false, errorCode: 'PERMISSION_DENIED',
+ });
+ expect(deps.showDirectoryDialog).not.toHaveBeenCalled();
+ });
+});
+
describe('pickSlot · 骚扰钳制', () => {
it('同插件两次请求间隔不足 = RATE_LIMITED(按尝试记账)', async () => {
let clock = 0;
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceAssembly.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceAssembly.test.ts
new file mode 100644
index 0000000000..009043ff5a
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceAssembly.test.ts
@@ -0,0 +1,129 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { describe, expect, it, vi } from 'vitest';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import { ghostExternalLinkUrls, ghostInstallApprovalToken } from '../../../shared/ghost.js';
+import { hasPluginTaskApproval } from '../taskCapability.js';
+import { findInstalledGhostByInstanceId, installedGhostStoragePart, resolveInstalledGhost } from '../../../shared/pluginIdentity.js';
+import { PluginDownloadSlot } from '../downloadSlot.js';
+import { GhostExternalLinkGate } from '../previewGate.js';
+import { runGhostExternalLinkNavigation } from '../ghostExternalLinkNavigation.js';
+
+const productionAssembly = createGhostProductionCallbacks<{
+ pluginDownloads: PluginDownloadSlot;
+ handleGhostExternalLinkNavigation: (...args: unknown[]) => void;
+}>({
+ functions: ['findAvailableGhost', 'findGhostForInstanceId', 'getGhostExternalLinkGate', 'handleGhostExternalLinkNavigation'],
+ variables: ['pluginDownloads'],
+ initialize: 'let externalLinkGateSingleton = null;',
+});
+
+function installed(namespace?: string | null, inPlace = false): InstalledGhost {
+ return {
+ manifest: {
+ schemaVersion: 2, id: 'helper', name: 'Helper', version: '1.0.0', kind: 'chip', entry: 'main.js',
+ node: { entry: 'node.js' }, network: {
+ hosts: ['example.invalid'], secrets: [{ key: 'account', label: 'Account', url: 'https://example.invalid/control' }],
+ },
+ },
+ dir: namespace && !inPlace ? '/plugins/_ns/' + namespace + '/helper' : '/plugins/helper',
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ ...(namespace === undefined ? { namespaceState: 'pending' } : { namespace }),
+ } as InstalledGhost;
+}
+
+describe('production plugin instance assembly', () => {
+ it.each([false, true])('retries source archival when task storage becomes ready (failure: %s)', async (fails) => {
+ const retry = vi.fn(async () => { if (fails) throw new Error('storage unavailable'); });
+ const warn = vi.fn();
+ const assembly = createGhostProductionCallbacks<{
+ setPluginTaskRelocator: (handler: ((from: string, to: string) => Promise<void>) | null) => void;
+ }>({
+ functions: ['setPluginTaskRelocator'], initialize: 'let pluginTaskRelocator = null;',
+ })({ managerSingleton: { retryInterruptedMutationsAfterDbReady: retry }, log: { warn } });
+ assembly.setPluginTaskRelocator(null);
+ expect(retry).not.toHaveBeenCalled();
+ assembly.setPluginTaskRelocator(async () => {});
+ await vi.waitFor(() => expect(retry).toHaveBeenCalledOnce());
+ if (fails) await vi.waitFor(() => expect(warn).toHaveBeenCalledOnce());
+ else expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('resolves task authorization and approval revisions by physical instance', () => {
+ const root = { ...installed(null), dir: '/plugins/_ns/_root/helper', taskCapabilityApproved: true as const };
+ const organization = installed('acme');
+ for (const ghost of [root, organization]) ghost.manifest.agent = { tasks: true };
+ const assembly = createGhostProductionCallbacks<{
+ isPluginTaskAuthorized: (id: string) => boolean;
+ pluginTaskAuthorizationRevision: (id: string) => string | null;
+ getPluginTaskInstallRevision: (id: string) => string | null;
+ }>({
+ functions: ['findAvailableGhost', 'findGhostForInstanceId', 'isPluginTaskAuthorized', 'pluginTaskAuthorizationRevision', 'getPluginTaskInstallRevision'],
+ })({
+ availableGhosts: () => [root, organization], resolveInstalledGhost, findInstalledGhostByInstanceId,
+ hasPluginTaskApproval, ghostInstallApprovalToken,
+ });
+ const rootId = installedGhostStoragePart(root);
+ const orgId = installedGhostStoragePart(organization);
+ expect(assembly.isPluginTaskAuthorized(rootId)).toBe(true);
+ expect(assembly.isPluginTaskAuthorized(orgId)).toBe(false);
+ expect(assembly.pluginTaskAuthorizationRevision(rootId)).toBe(root.approval.state === 'approved' ? root.approval.revision : null);
+ expect(assembly.pluginTaskAuthorizationRevision(orgId)).toBe(organization.approval.state === 'approved' ? organization.approval.revision : null);
+ expect(assembly.getPluginTaskInstallRevision(rootId)).toBe(ghostInstallApprovalToken(root.approval));
+ expect(assembly.getPluginTaskInstallRevision(orgId)).toBeNull();
+ });
+
+ it.each(['S1', 'S2-off', 'S2-on', 'S2-coexist'])(
+ 'downloads and external navigation keep the selected instance in %s', async (stage) => {
+ const selected = stage === 'S1' ? installed()
+ : stage === 'S2-off' ? installed('acme', true) : installed('acme');
+ const other = { ...installed(null), enabled: false };
+ const ghosts = stage === 'S2-coexist' ? [other, selected] : [selected];
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-instance-assembly-'));
+ const send = vi.fn();
+ const openExternal = vi.fn(async () => {});
+ const showMessageBox = vi.fn(async () => ({ response: 0 }));
+ const host = { isDestroyed: () => false };
+ const guest = { isDestroyed: () => false, isFocused: () => true, hostWebContents: host };
+ const download = vi.fn(async (options) => {
+ await fs.promises.writeFile(options.targetPath, 'ok');
+ return { path: options.targetPath, size: 2, sha256: options.sha256, fromCache: false, durationMs: 1, resumedFromBytes: 0 };
+ });
+ const assembly = productionAssembly({
+ availableGhosts: () => ghosts, resolveInstalledGhost, findInstalledGhostByInstanceId,
+ PluginDownloadSlot, GhostExternalLinkGate, ghostExternalLinkUrls, runGhostExternalLinkNavigation,
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(tmp, ...parts),
+ activeOwnerScopeKey: () => 'owner', getActiveAppSession: () => ({ dataOwnerId: 'owner' }),
+ anonymousDownloadRoots: new Map(), sendToGhostLogic: send, createDownloader: () => download,
+ BrowserWindow: { fromWebContents: () => ({ isDestroyed: () => false }) }, dialog: { showMessageBox },
+ shell: { openExternal }, t: (key: string) => key,
+ log: { debug: vi.fn(), warn: vi.fn() },
+ });
+ const instanceId = installedGhostStoragePart(selected);
+ try {
+ expect(await assembly.pluginDownloads.handle(instanceId, {
+ kind: 'start', id: 'artifact', url: 'https://example.invalid/file', bytes: 2,
+ sha256: createHash('sha256').update('ok').digest('hex'),
+ })).toMatchObject({ ok: true });
+ expect(download).toHaveBeenCalledTimes(1);
+ expect(send.mock.calls.every(([id]) => id === instanceId)).toBe(true);
+ assembly.handleGhostExternalLinkNavigation('helper', 'https://example.invalid/control', host, guest, () => true, instanceId);
+ await vi.waitFor(() => expect(openExternal).toHaveBeenCalledWith('https://example.invalid/control'));
+ expect(showMessageBox).not.toHaveBeenCalled();
+ selected.enabled = false;
+ expect(await assembly.pluginDownloads.handle(instanceId, {
+ kind: 'start', id: 'denied', url: 'https://example.invalid/file', bytes: 2,
+ sha256: 'a'.repeat(64),
+ })).toMatchObject({ ok: false });
+ expect(download).toHaveBeenCalledTimes(1);
+ } finally {
+ await assembly.pluginDownloads.stopAndWait();
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ },
+ );
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistry.test.ts
new file mode 100644
index 0000000000..9f76cefb2d
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistry.test.ts
@@ -0,0 +1,379 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ adoptContentInstall,
+ confirmInstanceNamespace,
+ confirmUnconfirmedInstance,
+ createPluginInstanceRegistryStore,
+ emptyPluginInstanceRegistry,
+ findReusableInstance,
+ parsePluginInstanceRegistryDocument,
+ reconcileInstanceReceipt,
+ upsertInstance,
+ selectMarketPluginIdForInstance,
+ type PluginInstanceRecord,
+} from '../pluginInstanceRegistry.js';
+
+function record(overrides: Partial<PluginInstanceRecord> = {}): PluginInstanceRecord {
+ return {
+ instanceKey: 'helper',
+ contentRelId: 'helper',
+ ghostId: 'helper',
+ namespace: 'xd',
+ namespaceState: 'confirmed',
+ pluginId: 'plugin-1',
+ source: 'market',
+ receiptRevision: 'rev-1',
+ packageSha256: 'sha-1',
+ active: true,
+ ...overrides,
+ };
+}
+
+describe('plugin instance registry', () => {
+ it('adopts an old directory under its existing storage key and does not invent a namespace', () => {
+ const adopted = adoptContentInstall({ relId: 'helper', ghostId: 'helper', receipt: null, pendingMigration: true });
+ expect(adopted).toMatchObject({
+ instanceKey: 'helper',
+ contentRelId: 'helper',
+ namespace: null,
+ namespaceState: 'pending',
+ pluginId: null,
+ source: 'legacy',
+ });
+ });
+
+ it('keeps a market plugin id on an upgraded install so another plugin cannot reuse it', () => {
+ const adopted = adoptContentInstall({
+ relId: 'helper',
+ ghostId: 'helper',
+ receipt: {
+ ghostId: 'helper',
+ hasNamespace: false,
+ namespace: null,
+ revision: 'rev-1',
+ packageSha256: 'sha-1',
+ },
+ pendingMigration: true,
+ marketPluginId: 'plugin-a',
+ });
+ expect(adopted).toMatchObject({
+ pluginId: 'plugin-a',
+ source: 'market',
+ namespaceState: 'pending',
+ });
+ const registry = upsertInstance(emptyPluginInstanceRegistry(), { ...adopted!, active: false });
+ expect(findReusableInstance(registry, {
+ ghostId: 'helper', namespace: null, source: 'market', pluginId: 'plugin-a',
+ })?.instanceKey).toBe('helper');
+ expect(findReusableInstance(registry, {
+ ghostId: 'helper', namespace: null, source: 'market', pluginId: 'plugin-b',
+ })).toBeNull();
+ });
+
+ it('does not copy a market plugin id onto a forge install', () => {
+ const adopted = adoptContentInstall({
+ relId: 'helper',
+ ghostId: 'helper',
+ receipt: {
+ ghostId: 'helper',
+ hasNamespace: false,
+ namespace: null,
+ revision: 'rev-1',
+ packageSha256: 'sha-1',
+ installOrigin: 'agent-forge',
+ },
+ pendingMigration: true,
+ marketPluginId: 'plugin-a',
+ });
+ expect(adopted).toMatchObject({ pluginId: null, source: 'agent-forge' });
+ });
+
+ it('keeps the encoded storage key for an already-migrated directory', () => {
+ const adopted = adoptContentInstall({
+ relId: '_ns/xd/helper',
+ ghostId: 'helper',
+ receipt: {
+ ghostId: 'helper',
+ hasNamespace: true,
+ namespace: 'xd',
+ revision: 'rev-1',
+ packageSha256: 'sha-1',
+ },
+ });
+ expect(adopted).toMatchObject({
+ instanceKey: '_ns__xd__helper',
+ namespace: 'xd',
+ namespaceState: 'confirmed',
+ });
+ });
+
+ it('drops confirmation when an old client strips the receipt field, without a new key', () => {
+ const next = reconcileInstanceReceipt(record(), {
+ directoryPresent: true,
+ receipt: {
+ ghostId: 'helper',
+ hasNamespace: false,
+ namespace: null,
+ revision: 'rev-1',
+ packageSha256: 'sha-1',
+ },
+ });
+ expect(next.instanceKey).toBe('helper');
+ expect(next.namespaceState).toBe('unconfirmed');
+ expect(next.namespace).toBe('xd');
+ });
+
+ it('does not confirm a pending install just because a receipt field appeared', () => {
+ const pending = record({ namespace: null, namespaceState: 'pending', receiptRevision: null, packageSha256: null });
+ const next = reconcileInstanceReceipt(pending, {
+ directoryPresent: true,
+ receipt: {
+ ghostId: 'helper',
+ hasNamespace: true,
+ namespace: 'xd',
+ revision: 'rev-2',
+ packageSha256: 'sha-2',
+ },
+ });
+ expect(next.namespaceState).toBe('pending');
+ expect(next.instanceKey).toBe('helper');
+ });
+
+ it('reuses the inactive instance key on reinstall and refuses a second confirmed identity', () => {
+ const inactive = record({ active: false });
+ const registry = upsertInstance(emptyPluginInstanceRegistry(), inactive);
+ expect(findReusableInstance(registry, { ghostId: 'helper', namespace: 'xd' })?.instanceKey).toBe('helper');
+ const confirmed = confirmInstanceNamespace(registry, 'helper', 'xd', { revision: 'rev-2', packageSha256: 'sha-2' });
+ const other = record({ instanceKey: '_ns__other__helper', active: true, namespaceState: 'pending', namespace: null });
+ const withOther = upsertInstance(confirmed, other);
+ const blocked = confirmInstanceNamespace(withOther, other.instanceKey, 'xd', { revision: 'rev-3', packageSha256: 'sha-3' });
+ expect(blocked.instances[other.instanceKey]?.namespaceState).toBe('pending');
+ });
+
+ it('does not treat a directory outside the upgrade census as pending', () => {
+ const adopted = adoptContentInstall({ relId: 'helper', ghostId: 'helper', receipt: null });
+ expect(adopted).toMatchObject({
+ instanceKey: 'helper',
+ namespaceState: 'unconfirmed',
+ namespace: null,
+ });
+ });
+
+ it('does not confirm an unconfirmed install just because the receipt namespace comes back', () => {
+ const stripped = record({ namespaceState: 'unconfirmed', namespace: 'xd' });
+ const next = reconcileInstanceReceipt(stripped, {
+ directoryPresent: true,
+ receipt: {
+ ghostId: 'helper',
+ hasNamespace: true,
+ namespace: 'xd',
+ revision: 'rev-2',
+ packageSha256: 'sha-2',
+ },
+ });
+ expect(next).toMatchObject({
+ instanceKey: 'helper',
+ namespaceState: 'unconfirmed',
+ namespace: 'xd',
+ receiptRevision: 'rev-2',
+ packageSha256: 'sha-2',
+ });
+ });
+
+ it('does not reuse another source when the caller names one', () => {
+ const registry = upsertInstance(emptyPluginInstanceRegistry(), record({ active: false, source: 'agent-forge' }));
+ expect(findReusableInstance(registry, { ghostId: 'helper', namespace: 'xd', source: 'manual' })).toBeNull();
+ expect(findReusableInstance(registry, { ghostId: 'helper', namespace: 'xd', source: 'agent-forge' })?.instanceKey).toBe('helper');
+ const legacy = upsertInstance(emptyPluginInstanceRegistry(), record({ active: false, source: 'legacy', pluginId: null }));
+ expect(findReusableInstance(legacy, { ghostId: 'helper', namespace: 'xd', source: 'manual' })?.instanceKey).toBe('helper');
+ expect(findReusableInstance(legacy, { ghostId: 'helper', namespace: 'xd', source: 'market', pluginId: 'plugin-a' })?.instanceKey).toBe('helper');
+ const marketA = record({ active: false, source: 'market', pluginId: 'plugin-a', instanceKey: 'helper', contentRelId: 'helper' });
+ const marketB = record({
+ active: false, source: 'market', pluginId: 'plugin-b',
+ instanceKey: '_root__helper', contentRelId: '_ns/_root/helper',
+ });
+ const markets = upsertInstance(upsertInstance(emptyPluginInstanceRegistry(), marketA), marketB);
+ expect(findReusableInstance(markets, { ghostId: 'helper', namespace: 'xd', source: 'market', pluginId: 'plugin-a' })?.instanceKey).toBe('helper');
+ expect(findReusableInstance(markets, { ghostId: 'helper', namespace: 'xd', source: 'market', pluginId: 'plugin-b' })?.instanceKey).toBe('_root__helper');
+ const manual = record({ active: false, source: 'manual', pluginId: null, instanceKey: 'helper', contentRelId: 'helper' });
+ const alsoLegacy = record({ active: false, source: 'legacy', pluginId: null, instanceKey: '_root__helper', contentRelId: '_ns/_root/helper' });
+ const ambiguous = upsertInstance(upsertInstance(emptyPluginInstanceRegistry(), manual), alsoLegacy);
+ expect(findReusableInstance(ambiguous, { ghostId: 'helper', namespace: 'xd', source: 'market', pluginId: 'plugin-a' })).toBeNull();
+ });
+});
+
+const sha = 'ab'.repeat(32);
+
+describe('confirmUnconfirmedInstance', () => {
+ const org = { organizationId: 'org-xd', orgSlug: 'xd' };
+ const market = {
+ namespace: 'xd' as string | null,
+ organizationId: 'org-xd',
+ packageSha256: sha,
+ scope: 'organization' as const,
+ installed: true,
+ };
+
+ it('confirms the last known namespace when market, organization, and package sha agree', () => {
+ const stripped = record({ namespaceState: 'unconfirmed', packageSha256: sha });
+ expect(confirmUnconfirmedInstance(stripped, {
+ marketRecords: [market],
+ currentOrganization: org,
+ packageSha256: sha,
+ })).toEqual({ namespace: 'xd' });
+ });
+
+ it('does not invent a namespace the registry does not already hold', () => {
+ const root = record({ namespaceState: 'unconfirmed', namespace: null, packageSha256: sha });
+ expect(confirmUnconfirmedInstance(root, {
+ marketRecords: [market],
+ currentOrganization: org,
+ packageSha256: sha,
+ })).toBeNull();
+ });
+
+ it.each([
+ ['sha mismatch', { packageSha256: 'cd'.repeat(32) }],
+ ['other organization', { currentOrganization: { organizationId: 'org-other', orgSlug: 'other' } }],
+ ['ambiguous market rows', { marketRecords: [market, market] }],
+ ['market facts not ready', { marketRecords: undefined, forgeSelfTest: false }],
+ ['missing market namespace field', { marketRecords: [{ ...market, namespace: undefined }] }],
+ ] as const)('refuses %s', (_name, patch) => {
+ const stripped = record({ namespaceState: 'unconfirmed', packageSha256: sha });
+ expect(confirmUnconfirmedInstance(stripped, {
+ marketRecords: [market],
+ currentOrganization: org,
+ packageSha256: sha,
+ ...patch,
+ })).toBeNull();
+ });
+
+ it('confirms a forge self-test only when the last namespace is the current org slug', () => {
+ const stripped = record({ namespaceState: 'unconfirmed', source: 'agent-forge', packageSha256: sha });
+ expect(confirmUnconfirmedInstance(stripped, {
+ marketRecords: [],
+ currentOrganization: org,
+ packageSha256: sha,
+ forgeSelfTest: true,
+ })).toEqual({ namespace: 'xd' });
+ expect(confirmUnconfirmedInstance(stripped, {
+ currentOrganization: { organizationId: 'org-other', orgSlug: 'other' },
+ packageSha256: sha,
+ forgeSelfTest: true,
+ })).toBeNull();
+ expect(confirmUnconfirmedInstance(
+ record({ namespaceState: 'unconfirmed', namespace: null }),
+ { currentOrganization: org, forgeSelfTest: true },
+ )).toBeNull();
+ });
+
+ it('confirms an explicit public root when the market package sha matches', () => {
+ const root = record({
+ namespaceState: 'unconfirmed', namespace: null, pluginId: null, source: 'manual', packageSha256: sha,
+ });
+ expect(confirmUnconfirmedInstance(root, {
+ marketRecords: [{
+ namespace: null, organizationId: null, packageSha256: sha, scope: 'public', installed: true,
+ }],
+ packageSha256: sha,
+ })).toEqual({ namespace: null });
+ });
+
+ it('does not confirm a pending or inactive record', () => {
+ const evidence = { marketRecords: [market], currentOrganization: org, packageSha256: sha };
+ expect(confirmUnconfirmedInstance(record({ namespaceState: 'pending', namespace: 'xd' }), evidence)).toBeNull();
+ expect(confirmUnconfirmedInstance(record({ namespaceState: 'unconfirmed', active: false }), evidence)).toBeNull();
+ });
+});
+
+describe('plugin instance registry schema', () => {
+ let dir: string | null = null;
+ afterEach(() => {
+ if (dir) fs.rmSync(dir, { recursive: true, force: true });
+ dir = null;
+ });
+
+ it('treats another integer schema as unknown and leaves the file in place', () => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-registry-'));
+ const filePath = path.join(dir, 'plugin-instances.v2.json');
+ const original = '{"schemaVersion":3,"census":null,"instances":{"future":true}}\n';
+ fs.writeFileSync(filePath, original);
+ const store = createPluginInstanceRegistryStore(filePath);
+ expect(store.read().kind).toBe('unknown-schema');
+ expect(parsePluginInstanceRegistryDocument({ schemaVersion: 3, census: null, instances: {} }).kind).toBe('unknown-schema');
+ expect(parsePluginInstanceRegistryDocument({ schemaVersion: 2, instances: {} }).kind).toBe('corrupt');
+ expect(parsePluginInstanceRegistryDocument({ schemaVersion: 1.5, instances: {} }).kind).toBe('corrupt');
+ expect(parsePluginInstanceRegistryDocument({ instances: {} }).kind).toBe('corrupt');
+ expect(store.discardCorrupt()).toBe(false);
+ expect(() => store.write(emptyPluginInstanceRegistry())).toThrow(/unknown-schema/);
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(original);
+ });
+
+ it('upgrades a v1 file into v2 and leaves the v1 file in place', () => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-registry-'));
+ const v1Path = path.join(dir, 'plugin-instances.v1.json');
+ const row = record({ instanceKey: 'helper', contentRelId: 'helper' });
+ fs.writeFileSync(v1Path, JSON.stringify({ schemaVersion: 1, instances: { helper: row } }) + String.fromCharCode(10));
+ const v1Text = fs.readFileSync(v1Path, 'utf8');
+ const store = createPluginInstanceRegistryStore(path.join(dir, 'plugin-instances.v2.json'));
+ const read = store.read();
+ expect(read.kind).toBe('ok');
+ if (read.kind !== 'ok') return;
+ expect(read.registry).toMatchObject({ schemaVersion: 2, census: null });
+ expect(read.registry.instances.helper.namespace).toBe('xd');
+ store.write({ ...read.registry, census: { completedAt: '2026-01-01T00:00:00.000Z', pendingRelIds: [] } });
+ expect(fs.readFileSync(v1Path, 'utf8')).toBe(v1Text);
+ const again = store.read();
+ expect(again.kind).toBe('ok');
+ if (again.kind !== 'ok') return;
+ expect(again.registry.census?.completedAt).toBe('2026-01-01T00:00:00.000Z');
+ expect(again.registry.instances.helper.active).toBe(true);
+ });
+});
+
+describe('selectMarketPluginIdForInstance', () => {
+ const instance = {
+ ghostId: 'helper',
+ contentRelId: 'helper',
+ namespace: null as string | null,
+ packageSha256: 'sha-root',
+ };
+ const org = {
+ ...instance,
+ contentRelId: '_ns/xd/helper',
+ namespace: 'xd',
+ packageSha256: 'sha-org',
+ };
+
+ it('does not stamp a root install with an organization row', () => {
+ const records = [{
+ pluginId: 'plugin-org', ghostId: 'helper', installed: true,
+ namespace: 'xd', scope: 'organization', organizationId: 'org-xd', sha256: 'sha-org',
+ }];
+ expect(selectMarketPluginIdForInstance(instance, records)).toBeNull();
+ expect(selectMarketPluginIdForInstance(org, records)).toBe('plugin-org');
+ });
+
+ it('matches a row with no namespace only to the legacy bare directory', () => {
+ const records = [{
+ pluginId: 'plugin-old', ghostId: 'helper', installed: true, sha256: 'sha-root',
+ }];
+ expect(selectMarketPluginIdForInstance(instance, records)).toBe('plugin-old');
+ expect(selectMarketPluginIdForInstance({ ...instance, contentRelId: '_ns/_root/helper' }, records)).toBeNull();
+ });
+
+ it('rejects a package sha mismatch and an organization row labeled root', () => {
+ expect(selectMarketPluginIdForInstance(org, [{
+ pluginId: 'plugin-org', ghostId: 'helper', installed: true,
+ namespace: 'xd', scope: 'organization', organizationId: 'org-xd', sha256: 'other',
+ }])).toBeNull();
+ expect(selectMarketPluginIdForInstance(instance, [{
+ pluginId: 'plugin-org', ghostId: 'helper', installed: true,
+ namespace: null, scope: 'organization', organizationId: 'org-xd', sha256: 'sha-root',
+ }])).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistryService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistryService.test.ts
new file mode 100644
index 0000000000..0c089858fd
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistryService.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ emptyPluginInstanceRegistry,
+ selectMarketPluginIdForInstance,
+ type PluginInstanceRegistry,
+ type PluginInstanceRegistryStore,
+} from '../pluginInstanceRegistry.js';
+import {
+ pendingCensusMismatches,
+ PluginInstanceRegistryService,
+} from '../pluginInstanceRegistryService.js';
+
+const NOW = '2026-10-08T00:00:00.000Z';
+
+function memoryStore(initial: PluginInstanceRegistry): PluginInstanceRegistryStore & { snapshot(): PluginInstanceRegistry } {
+ let current = initial;
+ return {
+ read: () => ({ kind: 'ok', registry: current }),
+ write(registry) { current = registry; },
+ discardCorrupt: () => false,
+ snapshot: () => current,
+ };
+}
+
+function service(options: {
+ registry: PluginInstanceRegistry;
+ relIds?: string[];
+ marketIdentityForInstance?: (instance: {
+ ghostId: string;
+ contentRelId: string;
+ namespace: string | null;
+ packageSha256: string | null;
+ }) => { pluginId: string } | null;
+}) {
+ const store = memoryStore(options.registry);
+ const created = new PluginInstanceRegistryService({
+ ensureOwner: () => {},
+ registryStore: () => store,
+ listContentEntries: () => (options.relIds ?? []).map((relId) => ({ relId, dir: relId })),
+ receiptFact: (relId) => ({
+ ghostId: relId,
+ hasNamespace: false,
+ namespace: null,
+ revision: 'rev-1',
+ packageSha256: 'ab'.repeat(32),
+ }),
+ censusCandidates: () => [],
+ readApproval: () => ({ state: 'missing' }),
+ recordLegacyEligibility: () => {},
+ marketIdentityForInstance: options.marketIdentityForInstance,
+ });
+ return { created, store };
+}
+
+describe('plugin instance registry service', () => {
+ it('returns the stored census allowlist', () => {
+ const registry: PluginInstanceRegistry = {
+ ...emptyPluginInstanceRegistry(),
+ census: { completedAt: NOW, pendingRelIds: ['hello'] },
+ };
+ const { created } = service({ registry, relIds: ['hello'] });
+ expect(created.ensureCensus()?.pendingRelIds).toEqual(['hello']);
+ const synced = created.sync();
+ expect(synced.instances.hello?.namespaceState).toBe('pending');
+ expect(pendingCensusMismatches(synced, 'strict')).toEqual([]);
+ });
+
+ it('reports a pending row that is missing from the census allowlist', () => {
+ const registry: PluginInstanceRegistry = {
+ ...emptyPluginInstanceRegistry(),
+ census: { completedAt: NOW, pendingRelIds: [] },
+ instances: {
+ hello: {
+ instanceKey: 'hello',
+ contentRelId: 'hello',
+ ghostId: 'hello',
+ namespace: null,
+ namespaceState: 'pending',
+ pluginId: null,
+ source: 'legacy',
+ receiptRevision: null,
+ packageSha256: null,
+ active: true,
+ },
+ },
+ };
+ expect(pendingCensusMismatches(registry)).toEqual(['hello:pending-but-not-listed']);
+ });
+});
+
+describe('market identity backfill', () => {
+ const sha = 'ab'.repeat(32);
+ function row(overrides: Partial<PluginInstanceRegistry['instances'][string]> = {}) {
+ return {
+ instanceKey: 'helper',
+ contentRelId: 'helper',
+ ghostId: 'helper',
+ namespace: null,
+ namespaceState: 'pending' as const,
+ pluginId: null,
+ source: 'manual' as const,
+ receiptRevision: 'rev-1',
+ packageSha256: sha,
+ active: true,
+ ...overrides,
+ };
+ }
+
+ it('writes the only installed market plugin id onto an unlabeled upgrade', () => {
+ const registry: PluginInstanceRegistry = {
+ ...emptyPluginInstanceRegistry(),
+ census: { completedAt: NOW, pendingRelIds: ['helper'] },
+ instances: { helper: row() },
+ };
+ const { created, store } = service({
+ registry,
+ relIds: ['helper'],
+ marketIdentityForInstance: () => ({ pluginId: 'plugin-a' }),
+ });
+ created.sync();
+ expect(store.snapshot().instances.helper).toMatchObject({
+ pluginId: 'plugin-a',
+ source: 'market',
+ });
+ });
+
+ it('does not relabel forge or builtin installs', () => {
+ const registry: PluginInstanceRegistry = {
+ ...emptyPluginInstanceRegistry(),
+ census: { completedAt: NOW, pendingRelIds: ['helper', '_ns/_root/builtin-helper'] },
+ instances: {
+ helper: row({ source: 'agent-forge' }),
+ '_root__builtin-helper': row({
+ instanceKey: '_root__builtin-helper',
+ contentRelId: '_ns/_root/builtin-helper',
+ ghostId: 'builtin-helper',
+ source: 'builtin',
+ }),
+ },
+ };
+ const { created, store } = service({
+ registry,
+ relIds: ['helper', '_ns/_root/builtin-helper'],
+ marketIdentityForInstance: (instance) => ({ pluginId: instance.ghostId + '-market' }),
+ });
+ created.sync();
+ const next = store.snapshot();
+ expect(next.instances.helper).toMatchObject({ pluginId: null, source: 'agent-forge' });
+ expect(next.instances['_root__builtin-helper']).toMatchObject({ pluginId: null, source: 'builtin' });
+ });
+
+ it('does not give a manual root the enterprise plugin id of the same ghost id', () => {
+ const sha = 'ab'.repeat(32);
+ const registry: PluginInstanceRegistry = {
+ ...emptyPluginInstanceRegistry(),
+ census: { completedAt: NOW, pendingRelIds: ['helper'] },
+ instances: {
+ helper: row({ source: 'manual', packageSha256: sha }),
+ '_ns__xd__helper': row({
+ instanceKey: '_ns__xd__helper',
+ contentRelId: '_ns/xd/helper',
+ namespace: 'xd',
+ namespaceState: 'confirmed',
+ source: 'manual',
+ packageSha256: sha,
+ }),
+ },
+ };
+ const records = [{
+ pluginId: 'plugin-org',
+ ghostId: 'helper',
+ installed: true,
+ namespace: 'xd',
+ scope: 'organization',
+ organizationId: 'org-xd',
+ sha256: sha,
+ }];
+ const { created, store } = service({
+ registry,
+ relIds: ['helper', '_ns/xd/helper'],
+ marketIdentityForInstance: (instance) => {
+ const pluginId = selectMarketPluginIdForInstance(instance, records);
+ return pluginId ? { pluginId } : null;
+ },
+ });
+ created.sync();
+ const next = store.snapshot();
+ expect(next.instances.helper).toMatchObject({ pluginId: null, source: 'manual' });
+ expect(next.instances['_ns__xd__helper']).toMatchObject({ pluginId: 'plugin-org', source: 'market' });
+ });
+
+ it('does not drop existing records when publish runs before the cache is loaded', () => {
+ const registry: PluginInstanceRegistry = {
+ ...emptyPluginInstanceRegistry(),
+ census: { completedAt: NOW, pendingRelIds: [] },
+ instances: {
+ other: {
+ instanceKey: 'other',
+ contentRelId: 'other',
+ ghostId: 'other',
+ namespace: null,
+ namespaceState: 'confirmed',
+ pluginId: null,
+ source: 'manual',
+ receiptRevision: 'rev-1',
+ packageSha256: 'ab'.repeat(32),
+ active: true,
+ },
+ },
+ };
+ const store = memoryStore(registry);
+ const created = new PluginInstanceRegistryService({
+ ensureOwner: () => {},
+ registryStore: () => store,
+ listContentEntries: () => [{ relId: 'other', dir: 'other' }],
+ receiptFact: () => ({
+ ghostId: 'other',
+ hasNamespace: true,
+ namespace: null,
+ revision: 'rev-1',
+ packageSha256: 'ab'.repeat(32),
+ }),
+ censusCandidates: () => [],
+ readApproval: () => ({ state: 'missing' }),
+ recordLegacyEligibility: () => {},
+ });
+ created.publish({
+ instanceKey: '_ns__acme__helper',
+ contentRelId: '_ns/acme/helper',
+ ghostId: 'helper',
+ namespace: 'acme',
+ namespaceState: 'confirmed',
+ pluginId: 'plugin-helper',
+ source: 'market',
+ receiptRevision: 'rev-2',
+ packageSha256: 'cd'.repeat(32),
+ active: true,
+ });
+ const saved = store.snapshot();
+ expect(saved.instances.other?.namespaceState).toBe('confirmed');
+ expect(saved.instances['_ns__acme__helper']?.namespace).toBe('acme');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceDowngradeMatrix.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceDowngradeMatrix.test.ts
new file mode 100644
index 0000000000..9275e74810
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceDowngradeMatrix.test.ts
@@ -0,0 +1,418 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
+import { ghostSecretStorageKey } from '../../../shared/providerSecrets.js';
+import { GhostManager, type GhostManagerOptions } from '../GhostManager.js';
+import { pluginInstanceRegistryPath, type PluginInstanceRegistry } from '../pluginInstanceRegistry.js';
+import { pendingCensusMismatches } from '../pluginInstanceRegistryService.js';
+import {
+ authorizeGhostHostPrimitive,
+ authorizeGhostTokenBroker,
+ resolveGhostFirstPartyPrivilege,
+ type GhostFirstPartyFacts,
+} from '../ghostFirstPartyPrivilege.js';
+import {
+ createGhostInstallReceipt,
+ GhostInstallReceiptStore,
+ hashApprovedSkillContent,
+} from '../ghostInstallReceipt.js';
+import { createGhostKvStore } from '../ghostKvStore.js';
+import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess.js';
+import { writeTestCindyPackage } from './cindyPackageFixture.js';
+
+const SHA = 'ab'.repeat(32);
+const CLASSES = ['public-tool', 'manual-tool', 'xd-feishu', 'cindy-helper'] as const;
+type PluginClass = (typeof CLASSES)[number];
+
+let workDir: string;
+let rootDir: string;
+let dataRoot: string;
+let manager: GhostManager;
+
+const mutateSnapshot: NonNullable<GhostManagerOptions['mutateSnapshot']> = async ({ parentDir, ...request }) => {
+ await runGhostSnapshotWorkerRequest(request, parentDir);
+};
+
+function createManager(options: Omit<GhostManagerOptions, 'getRootDir' | 'getStateDir'> = {}): GhostManager {
+ return new GhostManager({
+ getRootDir: () => rootDir,
+ getStateDir: () => path.join(workDir, 'ghosts-install-state'),
+ mutateSnapshot,
+ ...options,
+ });
+}
+
+function manifest(id: string): Record<string, unknown> {
+ return {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'do_thing', description: 'do' }],
+ };
+}
+
+async function plant(id: string): Promise<void> {
+ const dir = path.join(rootDir, id);
+ await fs.promises.mkdir(dir, { recursive: true });
+ const declared = manifest(id);
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), JSON.stringify(declared));
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// ok\n');
+ const store = new GhostInstallReceiptStore(
+ () => path.join(workDir, 'ghosts-install-state'),
+ mutateSnapshot,
+ );
+ await store.write(createGhostInstallReceipt({
+ manifest: declared as InstalledGhost['manifest'],
+ localeResources: {},
+ enabled: true,
+ trust: { level: 'unverified', publisherSigned: false, publisherVerified: false, reviewed: false },
+ skillContentSha256: await hashApprovedSkillContent(declared as InstalledGhost['manifest'], dir),
+ packageSha256: SHA,
+ }), { skillSourceDir: dir });
+}
+
+async function makeCindy(id: string): Promise<string> {
+ return writeTestCindyPackage(path.join(workDir, id + '.cindy'), manifest(id), { 'main.js': '// next\n' });
+}
+
+function kv() {
+ return createGhostKvStore({ getRootDir: () => path.join(dataRoot, 'kv') });
+}
+
+function writeOwnedData(instanceKey: string, payload: string): void {
+ kv().write(instanceKey, { payload });
+ fs.mkdirSync(path.join(dataRoot, 'secrets'), { recursive: true });
+ fs.writeFileSync(path.join(dataRoot, 'secrets', ghostSecretStorageKey(instanceKey, 'token')), payload);
+ fs.mkdirSync(path.join(dataRoot, 'oauth'), { recursive: true });
+ fs.writeFileSync(path.join(dataRoot, 'oauth', instanceKey + '.json'), JSON.stringify({ refresh: payload }));
+ const library = path.join(dataRoot, 'libraries', instanceKey);
+ fs.mkdirSync(library, { recursive: true });
+ fs.writeFileSync(path.join(library, 'marker.txt'), payload);
+}
+
+function expectOwnedData(instanceKey: string, payload: string): void {
+ expect(kv().read(instanceKey)).toEqual({ payload });
+ expect(fs.readFileSync(path.join(dataRoot, 'secrets', ghostSecretStorageKey(instanceKey, 'token')), 'utf8')).toBe(payload);
+ expect(JSON.parse(fs.readFileSync(path.join(dataRoot, 'oauth', instanceKey + '.json'), 'utf8'))).toEqual({ refresh: payload });
+ expect(fs.readFileSync(path.join(dataRoot, 'libraries', instanceKey, 'marker.txt'), 'utf8')).toBe(payload);
+}
+
+
+function censusMismatches(): string[] {
+ const file = pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state'));
+ return pendingCensusMismatches(JSON.parse(fs.readFileSync(file, 'utf8')) as PluginInstanceRegistry, 'strict');
+}
+
+function byId(id: string): InstalledGhost {
+ const ghost = manager.list().find((item) => item.manifest.id === id);
+ if (!ghost) throw new Error('missing ' + id);
+ return ghost;
+}
+
+function factsFor(id: PluginClass, namespace: string | null, pending: boolean): GhostFirstPartyFacts {
+ const org = id === 'xd-feishu'
+ ? { organizationId: 'org-xd', orgSlug: 'xd' as string | null, pluginPrefix: 'xd' }
+ : null;
+ return {
+ ghostId: id,
+ namespace,
+ builtin: false,
+ installOrigin: 'manual',
+ legacyPendingNamespace: pending && id === 'xd-feishu',
+ legacyFirstPartyEligible: id === 'cindy-helper',
+ currentOrganization: org,
+ approvedPackageSha256: SHA,
+ marketRecord: id === 'public-tool' || id === 'cindy-helper'
+ ? {
+ scope: 'public', source: 'market', installed: true, organizationId: null,
+ sha256: SHA, approvedPackageSha256: SHA,
+ }
+ : id === 'xd-feishu'
+ ? {
+ scope: 'organization', source: 'market', installed: true, organizationId: 'org-xd',
+ sha256: SHA, approvedPackageSha256: SHA,
+ }
+ : null,
+ };
+}
+
+function expectPrivileges(id: PluginClass, namespace: string | null, pending: boolean, broker: boolean, host: boolean): void {
+ const facts = factsFor(id, namespace, pending);
+ const resolved = resolveGhostFirstPartyPrivilege(facts);
+ expect(resolved.brokerEligible).toBe(broker);
+ expect(resolved.hostPrimitiveEligible).toBe(host);
+ expect(authorizeGhostTokenBroker(id, { kind: 'ready', facts })).toBe(broker);
+ expect(authorizeGhostHostPrimitive(id, { kind: 'ready', facts })).toBe(host);
+}
+
+beforeEach(async () => {
+ workDir = fs.realpathSync.native(await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-ns-matrix-')));
+ rootDir = path.join(workDir, 'ghosts');
+ dataRoot = path.join(workDir, 'owner-a-data');
+ manager = createManager();
+});
+
+afterEach(async () => {
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+});
+
+describe('namespace downgrade matrix', () => {
+ it('keeps all four plugin classes usable offline after the upgrade census', async () => {
+ for (const id of CLASSES) await plant(id);
+ manager.list();
+ const keys = Object.fromEntries(CLASSES.map((id) => [id, installedGhostStoragePart(byId(id))])) as Record<PluginClass, string>;
+ for (const id of CLASSES) writeOwnedData(keys[id], 'data:' + id);
+ await manager.reconcilePendingRootNamespaces(false);
+
+ expect(manager.list().map((ghost) => ghost.manifest.id).sort()).toEqual([...CLASSES].sort());
+ for (const id of CLASSES) {
+ const ghost = byId(id);
+ expect(ghost.enabled).toBe(true);
+ expect(ghost.dir).toBe(path.join(rootDir, id));
+ expect(installedGhostStoragePart(ghost)).toBe(keys[id]);
+ expect(ghost.namespaceState).toBe('pending');
+ expect(manager.readDeliveryNamespace(keys[id])).toBeUndefined();
+ expectOwnedData(keys[id], 'data:' + id);
+ }
+ expect(kv().read(keys['public-tool'])).not.toEqual(kv().read(keys['xd-feishu']));
+ expectPrivileges('public-tool', null, true, false, false);
+ expectPrivileges('manual-tool', null, true, false, false);
+ expectPrivileges('xd-feishu', null, true, true, true);
+ expectPrivileges('cindy-helper', null, true, true, true);
+ });
+
+ it('survives an old client editing each class and still restores only confirmed privileges', async () => {
+ for (const id of CLASSES) await plant(id);
+ await manager.commitPendingNamespace('public-tool', null, 'market-public');
+ await manager.commitPendingNamespace('manual-tool', null, 'manual-after-sync');
+ await manager.commitPendingNamespace('xd-feishu', 'xd', 'market-organization');
+ await manager.commitPendingNamespace('cindy-helper', null, 'builtin');
+ const keys = Object.fromEntries(CLASSES.map((id) => [id, installedGhostStoragePart(byId(id))])) as Record<PluginClass, string>;
+ for (const id of CLASSES) writeOwnedData(keys[id], 'kept:' + id);
+
+ for (const id of CLASSES) {
+ const store = new GhostInstallReceiptStore(() => path.join(workDir, 'ghosts-install-state'), mutateSnapshot);
+ const approval = store.read(id);
+ if (approval.state !== 'approved') throw new Error('expected approval');
+ const { namespace: _namespace, ...downgraded } = approval.receipt;
+ await store.write({ ...downgraded, enabled: id !== 'public-tool', packageSha256: SHA }, {
+ relId: id, requireSkillSnapshot: false,
+ });
+ const marker = path.join(rootDir, id, '.disabled');
+ if (id === 'public-tool') fs.writeFileSync(marker, '');
+ else fs.rmSync(marker, { force: true });
+ }
+ manager = createManager();
+ expect(byId('public-tool').enabled).toBe(false);
+ await expect(manager.setEnabled('public-tool', true)).resolves.toEqual({ ok: true });
+ await expect(manager.setEnabled('xd-feishu', false)).resolves.toEqual({ ok: true });
+ await expect(manager.setEnabled('xd-feishu', true)).resolves.toEqual({ ok: true });
+ const updated = await manager.update(await makeCindy('cindy-helper'), {
+ expectedInstalledApproval: ghostInstallApprovalToken(byId('cindy-helper').approval),
+ namespace: null,
+ });
+ expect(updated).toMatchObject({ ghost: { dir: path.join(rootDir, 'cindy-helper') } });
+ await expect(manager.uninstall('manual-tool', { notify: false })).resolves.toEqual({ ok: true });
+ await expect(manager.install(await makeCindy('manual-tool'))).resolves.toMatchObject({
+ ghost: { instanceKey: keys['manual-tool'], namespace: null },
+ });
+
+ for (const id of CLASSES) {
+ const ghost = byId(id);
+ expect(ghost.dir).toBe(path.join(rootDir, id));
+ expect(installedGhostStoragePart(ghost)).toBe(keys[id]);
+ expectOwnedData(keys[id], 'kept:' + id);
+ expect(manager.readDeliveryNamespace(keys[id])).not.toBe('xd');
+ }
+ expect(byId('xd-feishu').namespaceState).toBe('unconfirmed');
+ expectPrivileges('xd-feishu', null, false, false, false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'xd', 'xd-feishu'))).toBe(false);
+
+ manager = createManager({
+ readUnconfirmedConfirmationEvidence: (record) => record.ghostId === 'xd-feishu' ? {
+ marketRecords: [{
+ namespace: 'xd', organizationId: 'org-xd', packageSha256: SHA, scope: 'organization', installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd' },
+ packageSha256: SHA,
+ } : { marketRecords: [], packageSha256: SHA },
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(byId('xd-feishu')).toMatchObject({ namespace: 'xd', namespaceState: 'confirmed', enabled: true });
+ expect(manager.readDeliveryNamespace(keys['xd-feishu'])).toBe('xd');
+ expectPrivileges('xd-feishu', 'xd', false, true, true);
+ expectOwnedData(keys['xd-feishu'], 'kept:xd-feishu');
+ expectOwnedData(keys['public-tool'], 'kept:public-tool');
+ });
+
+ it('does not leak plugin data or identity across data owners', async () => {
+ let owner = 'a';
+ const switched = new GhostManager({
+ getRootDir: () => path.join(workDir, owner, 'ghosts'),
+ getStateDir: () => path.join(workDir, owner, 'state'),
+ getOwnerContextKey: () => owner,
+ mutateSnapshot,
+ });
+ rootDir = path.join(workDir, 'a', 'ghosts');
+ dataRoot = path.join(workDir, 'a', 'data');
+ manager = switched;
+ for (const id of CLASSES) await plant(id);
+ manager.list();
+ const keys = Object.fromEntries(CLASSES.map((id) => [id, installedGhostStoragePart(byId(id))])) as Record<PluginClass, string>;
+ for (const id of CLASSES) writeOwnedData(keys[id], 'owner-a:' + id);
+ await manager.reconcilePendingRootNamespaces(false);
+
+ owner = 'b';
+ rootDir = path.join(workDir, 'b', 'ghosts');
+ dataRoot = path.join(workDir, 'b', 'data');
+ expect(manager.list()).toEqual([]);
+ expect(kv().read(keys['public-tool'])).toEqual({});
+ await plant('public-tool');
+ manager.list();
+ writeOwnedData(installedGhostStoragePart(byId('public-tool')), 'owner-b:public-tool');
+
+ owner = 'a';
+ rootDir = path.join(workDir, 'a', 'ghosts');
+ dataRoot = path.join(workDir, 'a', 'data');
+ expect(manager.list().map((ghost) => ghost.manifest.id).sort()).toEqual([...CLASSES].sort());
+ for (const id of CLASSES) {
+ expect(installedGhostStoragePart(byId(id))).toBe(keys[id]);
+ expectOwnedData(keys[id], 'owner-a:' + id);
+ }
+ expect(byId('public-tool').namespaceState).toBe('pending');
+ });
+
+ it('reconnects an enterprise plugin after an old client changes its package and rewrites the market row', async () => {
+ await plant('xd-feishu');
+ await manager.commitPendingNamespace('xd-feishu', 'xd', 'market-organization');
+ const key = installedGhostStoragePart(byId('xd-feishu'));
+ writeOwnedData(key, 'kept:xd-feishu');
+ const newSha = 'cd'.repeat(32);
+ const store = new GhostInstallReceiptStore(() => path.join(workDir, 'ghosts-install-state'), mutateSnapshot);
+ const approval = store.read('xd-feishu');
+ if (approval.state !== 'approved') throw new Error('expected approval');
+ const { namespace: dropped, ...rewritten } = approval.receipt;
+ expect(dropped).toBe('xd');
+ await store.write({ ...rewritten, packageSha256: newSha }, {
+ relId: 'xd-feishu', requireSkillSnapshot: false,
+ });
+
+ const staleRow = {
+ organizationId: 'org-xd', packageSha256: newSha, scope: 'organization' as const, installed: true,
+ };
+ manager = createManager({
+ readUnconfirmedConfirmationEvidence: () => ({
+ marketRecords: [staleRow],
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd' },
+ packageSha256: newSha,
+ }),
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(byId('xd-feishu')).toMatchObject({ namespaceState: 'unconfirmed', dir: path.join(rootDir, 'xd-feishu') });
+ expect(manager.readDeliveryNamespace(key)).toBeUndefined();
+ expect(installedGhostStoragePart(byId('xd-feishu'))).toBe(key);
+ expectOwnedData(key, 'kept:xd-feishu');
+ expect(manager.approvedInstallEvidence('xd-feishu')?.packageSha256).toBe(newSha);
+ const denied = resolveGhostFirstPartyPrivilege({
+ ghostId: 'xd-feishu', namespace: null, builtin: false, installOrigin: 'manual',
+ legacyPendingNamespace: false,
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd', pluginPrefix: 'xd' },
+ approvedPackageSha256: newSha,
+ marketRecord: {
+ scope: 'organization', source: 'market', installed: true, organizationId: 'org-xd',
+ sha256: newSha, approvedPackageSha256: newSha,
+ },
+ });
+ expect(denied.brokerEligible).toBe(false);
+
+ manager = createManager({
+ readUnconfirmedConfirmationEvidence: (record) => record.ghostId === 'xd-feishu' ? {
+ marketRecords: [{
+ namespace: 'xd', organizationId: 'org-xd', packageSha256: newSha,
+ scope: 'organization', installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd' },
+ packageSha256: newSha,
+ } : { marketRecords: [], packageSha256: newSha },
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(byId('xd-feishu')).toMatchObject({
+ namespace: 'xd', namespaceState: 'confirmed', dir: path.join(rootDir, 'xd-feishu'),
+ });
+ expect(manager.readDeliveryNamespace(key)).toBe('xd');
+ expect(installedGhostStoragePart(byId('xd-feishu'))).toBe(key);
+ expectOwnedData(key, 'kept:xd-feishu');
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'xd', 'xd-feishu'))).toBe(false);
+ expect(censusMismatches()).toEqual([]);
+ const restored = resolveGhostFirstPartyPrivilege({
+ ghostId: 'xd-feishu', namespace: 'xd', builtin: false, installOrigin: 'manual',
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd', pluginPrefix: 'xd' },
+ approvedPackageSha256: newSha,
+ marketRecord: {
+ scope: 'organization', source: 'market', installed: true, organizationId: 'org-xd',
+ sha256: newSha, approvedPackageSha256: newSha,
+ },
+ });
+ expect(restored).toMatchObject({ brokerEligible: true, hostPrimitiveEligible: true, basis: 'market-organization-current' });
+ expect(authorizeGhostTokenBroker('xd-feishu', { kind: 'ready', facts: {
+ ghostId: 'xd-feishu', namespace: 'xd', builtin: false, installOrigin: 'manual',
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd', pluginPrefix: 'xd' },
+ approvedPackageSha256: newSha,
+ marketRecord: {
+ scope: 'organization', source: 'market', installed: true, organizationId: 'org-xd',
+ sha256: newSha, approvedPackageSha256: newSha,
+ },
+ } })).toBe(true);
+ });
+
+ it('keeps official cindy plugin broker eligibility after an old client strips namespace', async () => {
+ manager = createManager({
+ captureLegacyFirstPartyEligibility: (ghostId) => ghostId === 'cindy-helper',
+ });
+ await plant('cindy-helper');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('cindy-helper');
+ expect(manager.readLegacyFirstPartyEligible('cindy-helper')).toBe(true);
+ await manager.commitPendingNamespace('cindy-helper', null, 'builtin');
+ const key = installedGhostStoragePart(byId('cindy-helper'));
+ writeOwnedData(key, 'kept:cindy-helper');
+ const store = new GhostInstallReceiptStore(() => path.join(workDir, 'ghosts-install-state'), mutateSnapshot);
+ const approval = store.read('cindy-helper');
+ if (approval.state !== 'approved') throw new Error('expected approval');
+ const { namespace: dropped, ...downgraded } = approval.receipt;
+ expect(dropped).toBeNull();
+ expect(downgraded.legacyFirstPartyEligible).toBe(true);
+ await store.write(downgraded, { relId: 'cindy-helper', requireSkillSnapshot: false });
+
+ manager = createManager();
+ manager.list();
+ expect(byId('cindy-helper')).toMatchObject({ namespaceState: 'unconfirmed', dir: path.join(rootDir, 'cindy-helper') });
+ expect(manager.readDeliveryNamespace(key)).toBeUndefined();
+ expect(manager.readLegacyFirstPartyEligible('cindy-helper')).toBe(true);
+ expect(installedGhostStoragePart(byId('cindy-helper'))).toBe(key);
+ expectOwnedData(key, 'kept:cindy-helper');
+ expect(censusMismatches()).toEqual([]);
+ const facts = {
+ ghostId: 'cindy-helper',
+ namespace: null,
+ builtin: false,
+ installOrigin: 'manual' as const,
+ legacyFirstPartyEligible: manager.readLegacyFirstPartyEligible('cindy-helper'),
+ currentOrganization: null,
+ approvedPackageSha256: SHA,
+ marketRecord: null,
+ };
+ expect(resolveGhostFirstPartyPrivilege(facts)).toMatchObject({
+ brokerEligible: true, hostPrimitiveEligible: true, basis: 'legacy-existing-install',
+ });
+ expect(authorizeGhostTokenBroker('cindy-helper', { kind: 'ready', facts })).toBe(true);
+ expect(authorizeGhostHostPrimitive('cindy-helper', { kind: 'ready', facts })).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.legacyLedger.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.legacyLedger.test.ts
new file mode 100644
index 0000000000..1a09b34d87
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.legacyLedger.test.ts
@@ -0,0 +1,212 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ classifyNamespaceMigration,
+ isCensusCandidate,
+ planNamespaceCommit,
+ readNamespaceMigrationInstallOrigin,
+ readNamespaceMigrationMarketRecord,
+ type ClassifyNamespaceMigrationInput,
+ type NamespaceCensusCandidate,
+} from '../pluginNamespaceMigration.js';
+
+const NOW = '2026-09-22T12:00:00.000Z';
+
+function candidate(ghostId: string, identitySource?: object): NamespaceCensusCandidate {
+ return { ghostId, relId: ghostId, ...(identitySource ? { identitySource } : {}) };
+}
+
+function classify(
+ partial: Partial<ClassifyNamespaceMigrationInput> & Pick<ClassifyNamespaceMigrationInput, 'ghostId'>,
+) {
+ return classifyNamespaceMigration({
+ builtin: false,
+ installOrigin: 'manual',
+ marketSyncCompleted: false,
+ marketRecord: null,
+ currentOrganization: null,
+ ...partial,
+ });
+}
+
+describe('isCensusCandidate', () => {
+ it('accepts root-dir installs whose identity has not recorded namespace', () => {
+ expect(isCensusCandidate(candidate('xd-feishu'))).toBe(true);
+ expect(isCensusCandidate(candidate('hello', { id: 'hello' }))).toBe(true);
+ expect(isCensusCandidate(candidate('hello', { namespace: null }))).toBe(false);
+ expect(isCensusCandidate(candidate('hello', { namespace: 'acme' }))).toBe(false);
+ expect(isCensusCandidate({ ghostId: 'hello', relId: '_ns/acme/hello' })).toBe(false);
+ expect(isCensusCandidate({ ghostId: 'BAD', relId: 'BAD' })).toBe(false);
+ });
+});
+
+describe('classifyNamespaceMigration', () => {
+ it('commits builtin and public/personal/custom market installs as root', () => {
+ const cases: [Partial<ClassifyNamespaceMigrationInput> & { ghostId: string }, string][] = [
+ [{ ghostId: 'cindy-art', builtin: true }, 'builtin'],
+ [{ ghostId: 'helper', marketRecord: { scope: 'public', source: 'market', organizationId: null } }, 'market-public'],
+ [{ ghostId: 'helper', marketRecord: { scope: 'personal', source: 'market', organizationId: 'user-1' } }, 'market-personal'],
+ [{ ghostId: 'helper', marketRecord: { scope: 'public', source: 'git-market', organizationId: null } }, 'market-custom'],
+ ];
+ for (const [input, basis] of cases) {
+ expect(classify(input)).toEqual({ kind: 'commit', namespace: null, basis });
+ }
+ });
+
+ it('commits organization installs in place when orgSlug is a trusted current-org fact', () => {
+ const cases: [Partial<ClassifyNamespaceMigrationInput> & { ghostId: string }, ReturnType<typeof classify>][] = [
+ [{ ghostId: 'xd-feishu', marketRecord: { scope: 'organization', source: 'market', organizationId: 'org-xd', namespace: 'xd' },
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd', pluginPrefix: 'xd' } },
+ { kind: 'commit', namespace: 'xd', basis: 'market-organization' }],
+ [{ ghostId: 'helper', marketRecord: { scope: 'organization', source: 'market', organizationId: 'org-acme' },
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix: 'acme' } },
+ { kind: 'commit', namespace: 'acme', basis: 'market-organization' }],
+ [{ ghostId: 'helper', marketRecord: { scope: 'organization', source: 'market', organizationId: 'org-acme' },
+ currentOrganization: { organizationId: 'org-other', orgSlug: 'other', pluginPrefix: 'oth' } },
+ { kind: 'pending', reason: 'awaiting-organization-namespace' }],
+ ];
+ for (const [input, expected] of cases) expect(classify(input)).toEqual(expected);
+ });
+
+ it('commits a known root namespace on the market record, and waits without market facts', () => {
+ expect(classify({
+ ghostId: 'helper',
+ marketRecord: { scope: 'public', source: 'market', organizationId: null, namespace: null },
+ })).toEqual({ kind: 'commit', namespace: null, basis: 'explicit-root' });
+ expect(classify({ ghostId: 'xd-feishu' })).toEqual({
+ kind: 'pending',
+ reason: 'awaiting-market-facts',
+ });
+ });
+
+ it('uses orgSlug as the namespace when it differs from pluginPrefix', () => {
+ const currentOrganization = {
+ organizationId: 'org-1', orgSlug: 'org-abcdefgh', pluginPrefix: 'acme',
+ };
+ expect(classify({
+ ghostId: 'helper',
+ marketRecord: { scope: 'organization', source: 'market', organizationId: 'org-1' },
+ currentOrganization,
+ })).toEqual({ kind: 'commit', namespace: 'org-abcdefgh', basis: 'market-organization' });
+ expect(classify({
+ ghostId: 'acme-tool', installOrigin: 'agent-forge', currentOrganization,
+ })).toEqual({ kind: 'commit', namespace: 'org-abcdefgh', basis: 'forge-current-org' });
+ expect(classify({
+ ghostId: 'helper', installOrigin: 'agent-forge', currentOrganization,
+ })).toEqual({ kind: 'pending', reason: 'awaiting-market-facts' });
+ });
+
+ it('commits explicit Forge self-tests to the current orgSlug', () => {
+ expect(classify({
+ ghostId: 'acme-tool', installOrigin: 'agent-forge',
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix: 'acme' },
+ })).toEqual({ kind: 'commit', namespace: 'acme', basis: 'forge-current-org' });
+ });
+
+ it('commits unmatched manual installs only after a completed market sync', () => {
+ expect(classify({ ghostId: 'local-tool', marketSyncCompleted: false })).toEqual({
+ kind: 'pending',
+ reason: 'awaiting-market-facts',
+ });
+ expect(classify({ ghostId: 'local-tool', marketSyncCompleted: true })).toEqual({
+ kind: 'commit',
+ namespace: null,
+ basis: 'manual-after-sync',
+ });
+ });
+
+ it('keeps old installs pending when market records cannot be read or resolved', () => {
+ const organizationRecord = { scope: 'organization' as const, source: 'market' as const, organizationId: 'org-xd' };
+ const unavailable = readNamespaceMigrationMarketRecord(() => { throw new Error('locked ledger'); });
+ const ambiguous = readNamespaceMigrationMarketRecord(() => [organizationRecord, organizationRecord]);
+ expect(unavailable).toBeUndefined();
+ expect(ambiguous).toBeUndefined();
+ expect(readNamespaceMigrationMarketRecord(() => [])).toBeNull();
+ for (const marketRecord of [unavailable, ambiguous]) {
+ expect(classify({ ghostId: 'xd-feishu', marketSyncCompleted: true, marketRecord }))
+ .toEqual({ kind: 'pending', reason: 'awaiting-market-facts' });
+ }
+ expect(classify({
+ ghostId: 'xd-feishu',
+ marketSyncCompleted: true,
+ marketRecord: readNamespaceMigrationMarketRecord(() => [organizationRecord]),
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd', pluginPrefix: 'xd' },
+ })).toEqual({ kind: 'commit', namespace: 'xd', basis: 'market-organization' });
+ });
+
+ it('does not treat a removed organization route as evidence for a manual replacement', () => {
+ const removed = { scope: 'organization' as const, source: 'market' as const, organizationId: 'org-acme', namespace: 'acme', installed: false };
+ const record = readNamespaceMigrationMarketRecord(() => [removed]);
+ expect(classify({
+ ghostId: 'helper',
+ marketRecord: record,
+ marketSyncCompleted: true,
+ installOrigin: 'manual',
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix: null },
+ })).toEqual({ kind: 'commit', namespace: null, basis: 'manual-after-sync' });
+ expect(classify({
+ ghostId: 'helper', marketRecord: removed, marketSyncCompleted: true, installOrigin: 'manual',
+ })).toEqual({ kind: 'commit', namespace: null, basis: 'manual-after-sync' });
+ });
+
+ it('does not turn an unreadable approved origin into a manual root install', () => {
+ const unavailable = readNamespaceMigrationInstallOrigin(() => { throw new Error('locked receipt'); });
+ const currentOrganization = { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix: null };
+ expect(unavailable).toBeUndefined();
+ const cases: [Partial<ClassifyNamespaceMigrationInput> & { ghostId: string }, ReturnType<typeof classify>][] = [
+ [{ ghostId: 'acme-tool', installOrigin: unavailable }, { kind: 'pending', reason: 'awaiting-install-origin' }],
+ [{ ghostId: 'acme-tool', installOrigin: unavailable, builtin: true }, { kind: 'commit', namespace: null, basis: 'builtin' }],
+ [{ ghostId: 'acme-tool', installOrigin: unavailable, marketRecord: { scope: 'public', source: 'market', organizationId: null } },
+ { kind: 'commit', namespace: null, basis: 'market-public' }],
+ [{ ghostId: 'acme-tool', installOrigin: readNamespaceMigrationInstallOrigin(() => 'agent-forge'), currentOrganization },
+ { kind: 'pending', reason: 'awaiting-market-facts' }],
+ [{ ghostId: 'local-tool', installOrigin: readNamespaceMigrationInstallOrigin(() => 'manual') },
+ { kind: 'commit', namespace: null, basis: 'manual-after-sync' }],
+ ];
+ for (const [input, expected] of cases) {
+ expect(classify({ marketSyncCompleted: true, ...input })).toEqual(expected);
+ }
+ });
+});
+
+describe('legacy Forge ownership exception', () => {
+ const current = { organizationId: 'org-1', orgSlug: 'org-abcdefgh', pluginPrefix: 'acme' };
+
+ it('keeps the install pending when the signed-in organization uses another prefix', () => {
+ expect(classify({
+ ghostId: 'acme-tool', installOrigin: 'agent-forge', marketSyncCompleted: true,
+ currentOrganization: { ...current, pluginPrefix: 'other' },
+ })).toEqual({ kind: 'pending', reason: 'awaiting-market-facts' });
+ });
+
+ it('keeps the install pending when the current token has no orgSlug', () => {
+ expect(classify({
+ ghostId: 'acme-tool', installOrigin: 'agent-forge',
+ currentOrganization: { ...current, orgSlug: null },
+ })).toEqual({ kind: 'pending', reason: 'awaiting-organization-namespace' });
+ });
+
+ it('does not apply the prefix exception to a manual import', () => {
+ expect(classify({
+ ghostId: 'acme-tool', installOrigin: 'manual', marketSyncCompleted: true,
+ currentOrganization: current,
+ })).toEqual({ kind: 'commit', namespace: null, basis: 'manual-after-sync' });
+ });
+});
+
+describe('planNamespaceCommit', () => {
+ const cases: [string, Parameters<typeof planNamespaceCommit>[0], ReturnType<typeof planNamespaceCommit>][] = [
+ ['recovers a receipt that already has namespace even when the plugin is busy',
+ { pending: true, busy: true, receiptNamespace: 'xd', requested: { namespace: null, basis: 'builtin' } },
+ { kind: 'write-registry-only', namespace: 'xd', basis: 'receipt-recovered' }],
+ ['blocks the first receipt write while the plugin is busy',
+ { pending: true, busy: true, requested: { namespace: 'acme', basis: 'market-organization' } },
+ { kind: 'skip', reason: 'busy' }],
+ ['applies the requested namespace when the receipt is still legacy',
+ { pending: true, busy: false, requested: { namespace: 'acme', basis: 'market-organization' } },
+ { kind: 'write-receipt-and-registry', namespace: 'acme', basis: 'market-organization' }],
+ ];
+ it.each(cases)('%s', (_name, input, expected) => {
+ expect(planNamespaceCommit(input)).toEqual(expected);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
new file mode 100644
index 0000000000..f7ab774a19
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
@@ -0,0 +1,1535 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost.js';
+import { PluginMarketLedger } from '../../plugin-market/ledger.js';
+import { GhostManager, type GhostManagerOptions } from '../GhostManager.js';
+import { resolveGhostFirstPartyPrivilege } from '../ghostFirstPartyPrivilege.js';
+import {
+ classifyNamespaceMigration,
+ readNamespaceMigrationInstallOrigin,
+ readNamespaceMigrationMarketRecord,
+} from '../pluginNamespaceMigration.js';
+import {
+ assertManagedPluginParentSync,
+ GhostInstallReceiptStore,
+ createGhostInstallReceipt,
+ hashApprovedSkillContent,
+} from '../ghostInstallReceipt.js';
+import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess.js';
+import { writeTestCindyPackage } from './cindyPackageFixture.js';
+import { installedGhostStoragePart, pluginStoragePart } from '../../../shared/pluginIdentity.js';
+import { pluginInstanceRegistryPath } from '../pluginInstanceRegistry.js';
+
+let workDir: string;
+let rootDir: string;
+let manager: GhostManager;
+const demoSkillSource = '---\nname: demo\ndescription: Demo skill\n---\n\nDemo\n';
+
+const mutateSnapshot: NonNullable<GhostManagerOptions['mutateSnapshot']> = async ({ parentDir, ...request }) => {
+ await runGhostSnapshotWorkerRequest(request, parentDir);
+};
+
+function createManager(options: Omit<GhostManagerOptions, 'getRootDir'> = {}): GhostManager {
+ return new GhostManager({ getRootDir: () => rootDir, ...options });
+}
+
+function receiptStore(mutation?: GhostManagerOptions['mutateSnapshot']): GhostInstallReceiptStore {
+ const stateRoot = path.join(workDir, 'ghosts-install-state');
+ return new GhostInstallReceiptStore(() => stateRoot, mutation);
+}
+
+beforeEach(async () => {
+ workDir = fs.realpathSync.native(
+ await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-ns-mig-mgr-')),
+ );
+ rootDir = path.join(workDir, 'ghosts');
+ manager = createManager({ mutateSnapshot });
+});
+
+afterEach(async () => {
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+});
+
+function manifest(id = 'hello', withSkill = false): Record<string, unknown> {
+ return {
+ schemaVersion: 2,
+ id,
+ name: 'Hello',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: withSkill ? ['tool', 'skill'] : ['tool'],
+ tools: [{ name: 'do_thing', description: 'do' }],
+ ...(withSkill ? {
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ } : {}),
+ };
+}
+
+it.each(['_ns', '_ns/_root'])('rejects linked %s parents for content recovery and state journals', async (reservedRoot) => {
+ const outside = path.join(workDir, 'outside');
+ const contentNs = path.join(rootDir, reservedRoot);
+ const relId = reservedRoot === '_ns' ? '_ns/acme/hello' : '_ns/_root/hello';
+ const stateRoot = path.join(workDir, 'ghosts-install-state');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.mkdir(path.dirname(contentNs), { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'sentinel'), 'keep');
+ await fs.promises.symlink(outside, contentNs, 'dir');
+ expect(() => assertManagedPluginParentSync(rootDir, relId)).toThrow();
+
+ const store = new GhostInstallReceiptStore(() => stateRoot);
+ await fs.promises.mkdir(path.dirname(path.join(stateRoot, reservedRoot)), { recursive: true });
+ await fs.promises.symlink(outside, path.join(stateRoot, reservedRoot), 'dir');
+ await expect(store.writePendingMutation(relId, {
+ kind: 'install', packageSha256: 'a'.repeat(64),
+ })).rejects.toThrow();
+ expect(store.readPendingMutationSync(relId).state).toBe('unreadable');
+ expect(store.listPendingMutationIdsSync().state).toBe('unreadable');
+ expect(fs.readFileSync(path.join(outside, 'sentinel'), 'utf8')).toBe('keep');
+});
+
+it('does not recover an interrupted namespaced uninstall through a linked content parent', async () => {
+ const outside = path.join(workDir, 'outside');
+ const stateRoot = path.join(workDir, 'ghosts-install-state');
+ await fs.promises.mkdir(path.join(outside, 'acme', 'hello'), { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'acme', 'hello', 'sentinel'), 'keep');
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ await fs.promises.symlink(outside, path.join(rootDir, '_ns'), 'dir');
+ const store = new GhostInstallReceiptStore(() => stateRoot);
+ await store.writePendingMutation('_ns/acme/hello', { kind: 'uninstall' });
+ manager = createManager({ getStateDir: () => stateRoot });
+ expect(fs.readFileSync(path.join(outside, 'acme', 'hello', 'sentinel'), 'utf8')).toBe('keep');
+ expect(store.readPendingMutationSync('_ns/acme/hello').state).toBe('valid');
+});
+
+it('refuses to publish a namespaced receipt through a linked approval parent', async () => {
+ await plantLegacyInstall('hello');
+ const stateRoot = path.join(workDir, 'ghosts-install-state');
+ const outside = path.join(workDir, 'outside');
+ await fs.promises.mkdir(outside);
+ await fs.promises.writeFile(path.join(outside, 'sentinel'), 'keep');
+ await fs.promises.symlink(outside, path.join(stateRoot, '_ns'), 'dir');
+ const store = new GhostInstallReceiptStore(() => stateRoot);
+ const approval = store.read('hello');
+ expect(approval.state).toBe('approved');
+ if (approval.state !== 'approved') return;
+ await expect(store.write({ ...approval.receipt, namespace: 'acme' }, {
+ relId: '_ns/acme/hello', requireSkillSnapshot: false,
+ })).rejects.toThrow('parent is not a real directory');
+ expect(fs.readFileSync(path.join(outside, 'sentinel'), 'utf8')).toBe('keep');
+});
+
+async function plantLegacyInstall(
+ id: string,
+ withSkill = false,
+ installOrigin?: 'agent-forge',
+): Promise<void> {
+ const dir = path.join(rootDir, id);
+ await fs.promises.mkdir(dir, { recursive: true });
+ const declared = manifest(id, withSkill);
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), JSON.stringify(declared));
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// ok\n');
+ if (withSkill) {
+ await fs.promises.mkdir(path.join(dir, 'skills', 'demo'), { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'skills', 'demo', 'SKILL.md'), demoSkillSource);
+ }
+ const store = receiptStore(mutateSnapshot);
+ const approvedManifest = {
+ ...declared,
+ } as InstalledGhost['manifest'];
+ await store.write(
+ createGhostInstallReceipt({
+ manifest: approvedManifest,
+ localeResources: {},
+ enabled: true,
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ skillContentSha256: await hashApprovedSkillContent(approvedManifest, dir),
+ installOrigin,
+ }),
+ { skillSourceDir: dir },
+ );
+}
+
+async function makeCindy(id: string, withSkill = false): Promise<string> {
+ return writeTestCindyPackage(path.join(workDir, `${id}.cindy`), manifest(id, withSkill), {
+ 'main.js': '// ok\n',
+ ...(withSkill ? { 'skills/demo/SKILL.md': demoSkillSource } : {}),
+ });
+}
+
+async function stampLegacyOrganizationInstall(id = 'hello', withSkill = false): Promise<void> {
+ await plantLegacyInstall(id, withSkill);
+ manager.list();
+ await manager.commitPendingNamespace(id, 'acme', 'market-organization');
+}
+
+describe('GhostManager namespace migration census', () => {
+ it('retries a failed first directory scan instead of persisting an empty census', async () => {
+ await plantLegacyInstall('hello');
+ const actualRead = fs.readdirSync;
+ const read = vi.spyOn(fs, 'readdirSync').mockImplementation(((directory: fs.PathLike, ...args: unknown[]) => {
+ if (String(directory) === rootDir) {
+ read.mockRestore();
+ throw Object.assign(new Error('unavailable'), { code: 'EACCES' });
+ }
+ return actualRead(directory, ...(args as []));
+ }) as typeof fs.readdirSync);
+ try {
+ expect(manager.ensureNamespaceMigrationCensus()).toBeNull();
+ } finally {
+ read.mockRestore();
+ }
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ });
+ it('ignores a corrupt leftover migration file and still censuses the directory', async () => {
+ await plantLegacyInstall('hello');
+ const legacyPath = path.join(workDir, 'ghosts-install-state', 'namespace-migration.v1.json');
+ fs.writeFileSync(legacyPath, '{');
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ expect(fs.readFileSync(legacyPath, 'utf8')).toBe('{');
+ });
+
+
+ it('keeps a pending legacy xd-mivo-canvas addressable without a committed namespace', async () => {
+ await plantLegacyInstall('xd-mivo-canvas');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('xd-mivo-canvas');
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'xd-mivo-canvas')?.namespaceState).toBe('pending');
+ expect(manager.isPendingLegacyNamespace('xd-mivo-canvas')).toBe(true);
+ expect(manager.readDeliveryNamespace('xd-mivo-canvas')).toBeUndefined();
+ });
+
+ it('rejects a namespace commit when the receipt changes after classification', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ const classify = vi.fn(() => {
+ const current = receiptStore().read('hello');
+ if (current.state !== 'approved') throw new Error('expected approved receipt');
+ fs.writeFileSync(
+ path.join(workDir, 'ghosts-install-state', 'hello.json'),
+ JSON.stringify({ ...current.receipt, packageSha256: 'c'.repeat(64) }),
+ );
+ return { kind: 'commit' as const, namespace: 'acme', basis: 'market-organization' as const };
+ });
+ const beforeCommit = vi.fn();
+ manager = createManager({ classifyPendingNamespace: classify, beforeNamespaceCommit: beforeCommit });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(beforeCommit).not.toHaveBeenCalled();
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ expect(manager.list()[0]?.namespace).toBeUndefined();
+ });
+ it('passes sync state to classification and commits only after facts become available', async () => {
+ await plantLegacyInstall('hello');
+ let factsAvailable = false;
+ const committed = vi.fn();
+ const classify = vi.fn<NonNullable<GhostManagerOptions['classifyPendingNamespace']>>(
+ (_ghostId, synced) => factsAvailable && synced
+ ? { kind: 'commit', namespace: 'acme', basis: 'market-organization' }
+ : { kind: 'pending', reason: 'awaiting-market-facts' },
+ );
+ manager = createManager({
+ classifyPendingNamespace: classify,
+ onNamespaceCommitted: committed,
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(classify).toHaveBeenLastCalledWith('hello', true);
+ expect(manager.list()[0]?.namespace).toBeUndefined();
+ expect(committed).not.toHaveBeenCalled();
+ factsAvailable = true;
+ await manager.reconcilePendingRootNamespaces(false);
+ expect(classify).toHaveBeenLastCalledWith('hello', false);
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]).toMatchObject({ namespace: 'acme' });
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ expect(committed).toHaveBeenCalledOnce();
+ });
+
+ it('waits for the real legacy Forge receipt and organization prefix before committing namespace', async () => {
+ await plantLegacyInstall('acme-tool', false, 'agent-forge');
+ const receiptFile = path.join(workDir, 'ghosts-install-state', 'acme-tool.json');
+ const receiptBytes = fs.readFileSync(receiptFile);
+ let pluginPrefix: string | null = null;
+ manager = createManager({
+ classifyPendingNamespace: (ghostId, marketSyncCompleted = false) => classifyNamespaceMigration({
+ ghostId,
+ builtin: false,
+ installOrigin: readNamespaceMigrationInstallOrigin(() => manager.readApprovedInstallOriginStrict(ghostId)),
+ marketSyncCompleted,
+ marketRecord: null,
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix },
+ }),
+ });
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('acme-tool');
+
+ fs.writeFileSync(receiptFile, '{');
+ expect(() => manager.readApprovedInstallOriginStrict('acme-tool')).toThrow();
+ await manager.reconcilePendingRootNamespaces(true);
+ // An invalid receipt is not adopted, so the registry does not project pending.
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ expect(manager.list()[0]?.namespace).toBeUndefined();
+
+ fs.writeFileSync(receiptFile, receiptBytes);
+ expect(manager.readApprovedInstallOriginStrict('acme-tool')).toBe('agent-forge');
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ expect(manager.list()[0]?.namespace).toBeUndefined();
+
+ pluginPrefix = 'acme';
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]?.namespace).toBe('acme');
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ expect(receiptStore().read('acme-tool')).toMatchObject({
+ state: 'approved', receipt: { installOrigin: 'agent-forge', namespace: 'acme' },
+ });
+ });
+
+ it('keeps a mismatched legacy Forge install pending and enabled', async () => {
+ await plantLegacyInstall('acme-tool', false, 'agent-forge');
+ manager = createManager({
+ classifyPendingNamespace: (ghostId, marketSyncCompleted = false) => classifyNamespaceMigration({
+ ghostId,
+ builtin: false,
+ installOrigin: readNamespaceMigrationInstallOrigin(() => manager.readApprovedInstallOriginStrict(ghostId)),
+ marketSyncCompleted,
+ marketRecord: null,
+ currentOrganization: { organizationId: 'org-other', orgSlug: 'other', pluginPrefix: 'other' },
+ }),
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]).toMatchObject({ enabled: true, dir: path.join(rootDir, 'acme-tool') });
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ expect(manager.list()[0]?.namespace).toBeUndefined();
+ expect(manager.readDeliveryNamespace('acme-tool')).toBeUndefined();
+ });
+
+ it.each([false, true])('stops, stamps and restarts an offline resident with in-flight work %s', async (initiallyInFlight) => {
+ await plantLegacyInstall('hello');
+ vi.useFakeTimers();
+ try {
+ let inFlight = initiallyInFlight;
+ let runtimeBusy = false;
+ let retry: Promise<void> | undefined;
+ const events: string[] = [];
+ const stop = vi.fn(async () => {
+ if (inFlight) return false;
+ runtimeBusy = false;
+ events.push('stopped');
+ return true;
+ });
+ const deferred = vi.fn(() => {
+ setTimeout(() => { retry = manager.reconcilePendingRootNamespaces(true); }, 1000);
+ });
+ manager = createManager({
+ classifyPendingNamespace: (_ghostId, synced) => synced
+ ? { kind: 'commit', namespace: 'acme', basis: 'market-organization' }
+ : { kind: 'pending', reason: 'awaiting-market-facts' },
+ isNamespaceMigrationBusy: () => inFlight || runtimeBusy,
+ canResumePendingResidentOffline: () => true,
+ onResumePendingResidentOffline: (ghost) => {
+ expect(ghost.approval.state).toBe('approved');
+ runtimeBusy = true;
+ events.push('started');
+ },
+ preparePendingResidentForMigration: stop,
+ onPendingResidentMigrationDeferred: deferred,
+ beforeNamespaceCommit: () => events.push('stamped'),
+ onNamespaceCommitted: () => events.push('restarted'),
+ });
+ manager.resumePendingResidentsOffline();
+ await manager.reconcilePendingRootNamespaces(false);
+ expect(events).toEqual(['started']);
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ await manager.reconcilePendingRootNamespaces(true);
+ if (initiallyInFlight) {
+ expect(stop).toHaveBeenCalledOnce();
+ expect(deferred).toHaveBeenCalledWith('hello');
+ expect(events).toEqual(['started']);
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ expect(manager.list()[0]?.namespace).toBeUndefined();
+ inFlight = false;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(retry).toBeDefined();
+ await retry;
+ } else {
+ expect(deferred).not.toHaveBeenCalled();
+ }
+ expect(stop).toHaveBeenCalledTimes(initiallyInFlight ? 2 : 1);
+ expect(events).toEqual(['started', 'stopped', 'stamped', 'restarted']);
+ expect(manager.list()[0]?.namespace).toBe('acme');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('defers a failed market namespace commit so the offline resident can retry', async () => {
+ await plantLegacyInstall('hello');
+ const deferred = vi.fn();
+ let failStamp = true;
+ manager = createManager({
+ classifyPendingNamespace: () => ({ kind: 'commit', namespace: 'acme', basis: 'market-organization' }),
+ preparePendingResidentForMigration: async () => true,
+ onPendingResidentMigrationDeferred: deferred,
+ beforeNamespaceCommit: () => {
+ if (failStamp) throw new Error('market ledger unavailable');
+ },
+ });
+ await expect(manager.reconcilePendingRootNamespaces(true)).resolves.toBeUndefined();
+ expect(deferred).toHaveBeenCalledWith('hello');
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ expect(receiptStore().read('hello')).toMatchObject({ state: 'approved' });
+ const approval = receiptStore().read('hello');
+ if (approval.state !== 'approved') throw new Error('expected approved receipt');
+ expect(approval.receipt).not.toHaveProperty('namespace');
+ failStamp = false;
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]?.namespace).toBe('acme');
+ });
+
+ it('continues migrating other entries after one entry fails', async () => {
+ await plantLegacyInstall('first');
+ await plantLegacyInstall('second');
+ manager.list();
+ manager = createManager({
+ classifyPendingNamespace: () => ({ kind: 'commit', namespace: 'acme', basis: 'market-organization' }),
+ beforeNamespaceCommit: (ghostId) => {
+ if (ghostId === 'first') throw new Error('first entry unavailable');
+ },
+ });
+ await expect(manager.reconcilePendingRootNamespaces(true)).resolves.toBeUndefined();
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'first')).toMatchObject({
+ namespaceState: 'pending',
+ });
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'second')).toMatchObject({
+ namespace: 'acme',
+ });
+ });
+
+ it('abandons an offline migration if its owner changes during safe stop', async () => {
+ await plantLegacyInstall('hello');
+ let owner = 'original';
+ let releaseStop: (() => void) | undefined;
+ const stopping = new Promise<void>((resolve) => { releaseStop = resolve; });
+ const committed = vi.fn();
+ manager = createManager({
+ getOwnerContextKey: () => owner,
+ classifyPendingNamespace: () => ({ kind: 'commit', namespace: 'acme', basis: 'market-organization' }),
+ canResumePendingResidentOffline: () => true,
+ onResumePendingResidentOffline: vi.fn(),
+ preparePendingResidentForMigration: async () => { await stopping; return true; },
+ onNamespaceCommitted: committed,
+ });
+ manager.resumePendingResidentsOffline();
+ const migration = manager.reconcilePendingRootNamespaces(true);
+ owner = 'replacement';
+ releaseStop?.();
+ await migration;
+ expect(committed).not.toHaveBeenCalled();
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ });
+
+ it('does not publish a namespace commit when its owner changes while writing the receipt', async () => {
+ await plantLegacyInstall('hello');
+ let owner = 'original';
+ let releaseWrite: (() => void) | undefined;
+ let writeStarted: (() => void) | undefined;
+ const writing = new Promise<void>((resolve) => { writeStarted = resolve; });
+ const blocked = new Promise<void>((resolve) => { releaseWrite = resolve; });
+ const write = vi.spyOn(GhostInstallReceiptStore.prototype, 'write').mockImplementation(async () => {
+ writeStarted?.();
+ await blocked;
+ });
+ const committed = vi.fn();
+ try {
+ manager = createManager({
+ getOwnerContextKey: () => owner,
+ onNamespaceCommitted: committed,
+ });
+ manager.list();
+ const migration = manager.commitPendingNamespace('hello', 'acme', 'market-organization');
+ await writing;
+ owner = 'replacement';
+ releaseWrite?.();
+ await expect(migration).rejects.toThrow('owner changed');
+ expect(committed).not.toHaveBeenCalled();
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ } finally {
+ write.mockRestore();
+ }
+ });
+
+ it('does not stop a resident while classification is still pending', async () => {
+ await plantLegacyInstall('hello');
+ let slugKnown = false;
+ let busy = false;
+ const stopped = vi.fn(async () => { busy = false; return true; });
+ const resumed = vi.fn();
+ manager = createManager({
+ classifyPendingNamespace: () => slugKnown
+ ? { kind: 'commit', namespace: 'acme', basis: 'market-organization' }
+ : { kind: 'pending', reason: 'awaiting-organization-namespace' },
+ isNamespaceMigrationBusy: () => busy,
+ canResumePendingResidentOffline: () => true,
+ onResumePendingResidentOffline: () => { busy = true; },
+ preparePendingResidentForMigration: stopped,
+ onPendingResidentMigrationSettled: resumed,
+ });
+ manager.resumePendingResidentsOffline();
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(stopped).not.toHaveBeenCalled();
+ expect(resumed).not.toHaveBeenCalled();
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ slugKnown = true;
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(stopped).toHaveBeenCalledOnce();
+ expect(manager.list()[0]?.namespace).toBe('acme');
+ });
+
+ it('treats bare directories as pending only until the one-shot census is written', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ expect(manager.list()).toEqual([]);
+ await plantLegacyInstall('recovered');
+ await plantLegacyInstall('unverified');
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'recovered')?.namespaceState).toBe('pending');
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'recovered')?.namespaceState).toBe('pending');
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'unverified')?.namespaceState).toBe('pending');
+ const orgCindy = await makeCindy('recovered');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ rejection: { code: 'namespace-migration-pending' },
+ });
+ expect(fs.existsSync(path.join(rootDir, 'recovered'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, 'unverified'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'recovered'))).toBe(false);
+ expect(manager.list().find((ghost) => ghost.dir === path.join(rootDir, 'recovered'))?.namespaceState).toBe('pending');
+ });
+
+ it('recovers an organization install whose approved namespace was erased by a downgraded client', async () => {
+ await plantLegacyInstall('hello');
+ await manager.commitPendingNamespace('hello', 'acme', 'market-organization');
+ const store = receiptStore();
+ const approval = store.read('hello');
+ expect(approval.state).toBe('approved');
+ if (approval.state !== 'approved') return;
+ const { namespace: oldNamespace, ...downgradedReceipt } = approval.receipt;
+ expect(oldNamespace).toBe('acme');
+ await store.write(downgradedReceipt, { relId: 'hello', requireSkillSnapshot: false });
+ expect(manager.list()[0]).toMatchObject({ namespaceState: 'unconfirmed' });
+ expect(manager.readDeliveryNamespace('hello')).toBeUndefined();
+ const orgCindy = await makeCindy('hello');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ rejection: { code: 'already-installed' },
+ });
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+
+ const sha = 'ab'.repeat(32);
+ const stripped = receiptStore().read('hello');
+ if (stripped.state !== 'approved') throw new Error('expected stripped receipt');
+ await receiptStore().write({ ...stripped.receipt, packageSha256: sha }, { relId: 'hello', requireSkillSnapshot: false });
+ manager = createManager({ mutateSnapshot });
+ await manager.reconcilePendingRootNamespaces(true);
+ const legacy = () => manager.list().find((ghost) => ghost.dir === path.join(rootDir, 'hello'));
+ expect(legacy()).toMatchObject({ namespace: 'acme', namespaceState: 'unconfirmed' });
+ expect(manager.readDeliveryNamespace('hello')).toBeUndefined();
+ manager = createManager({
+ mutateSnapshot,
+ readUnconfirmedConfirmationEvidence: () => ({
+ marketRecords: [{
+ namespace: 'acme', organizationId: 'org-acme', packageSha256: sha, scope: 'organization', installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ packageSha256: sha,
+ }),
+ });
+ await manager.reconcilePendingRootNamespaces(false);
+ expect(legacy()).toMatchObject({ namespace: 'acme', namespaceState: 'unconfirmed' });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(legacy()).toMatchObject({ namespace: 'acme', namespaceState: 'confirmed' });
+ expect(manager.readDeliveryNamespace('hello')).toBe('acme');
+ });
+
+ it.each([false, true].flatMap((enabled) => [0, 1, 2].map((updates) => ({ enabled, updates }))))(
+ 'recaptures a migrated Forge namespace after $updates updates and old-client setEnabled($enabled)', async ({ enabled, updates }) => {
+ await plantLegacyInstall('acme-tool', true, 'agent-forge');
+ const options: Omit<GhostManagerOptions, 'getRootDir'> = {
+ mutateSnapshot,
+ classifyPendingNamespace: (ghostId, marketSyncCompleted = false) => classifyNamespaceMigration({
+ ghostId, builtin: false, marketSyncCompleted, marketRecord: null,
+ installOrigin: readNamespaceMigrationInstallOrigin(() => manager.readApprovedInstallOriginStrict(ghostId)),
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix: 'acme' },
+ }),
+ readUnconfirmedConfirmationEvidence: () => ({
+ marketRecords: [],
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ forgeSelfTest: true,
+ }),
+ };
+ manager = createManager(options);
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]).toMatchObject({ namespace: 'acme', enabled: true });
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ for (let updateIndex = 0; updateIndex < updates; updateIndex += 1) {
+ const previousRevision = manager.list()[0].approval;
+ const updated = await manager.update(await makeCindy('acme-tool', true), {
+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),
+ namespace: 'acme', installOrigin: 'agent-forge',
+ });
+ expect(updated).toMatchObject({ ghost: { namespace: 'acme', approval: { state: 'approved' } } });
+ if (!('ghost' in updated) || previousRevision.state !== 'approved' || updated.ghost.approval.state !== 'approved') {
+ throw new Error('expected approved Forge update');
+ }
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ expect(JSON.stringify(manager.ensureNamespaceMigrationCensus())).not.toContain('forgeNamespaces');
+ }
+ const store = receiptStore(mutateSnapshot);
+ const approval = store.read('acme-tool');
+ if (approval.state !== 'approved') throw new Error('expected migrated Forge receipt');
+ const { namespace: oldNamespace, ...downgradedReceipt } = approval.receipt;
+ expect(oldNamespace).toBe('acme');
+ await store.write({ ...downgradedReceipt, enabled }, {
+ relId: 'acme-tool', skillSourceDir: path.join(rootDir, 'acme-tool'),
+ });
+ if (!enabled) fs.writeFileSync(path.join(rootDir, 'acme-tool', '.disabled'), '');
+ manager = createManager(options);
+ await manager.reconcilePendingRootNamespaces(false);
+ expect(manager.list()[0]).toMatchObject({ namespace: 'acme', namespaceState: 'unconfirmed' });
+ expect(manager.readDeliveryNamespace('acme-tool')).toBeUndefined();
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]).toMatchObject({ namespace: 'acme', enabled, dir: path.join(rootDir, 'acme-tool') });
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ expect(manager.readDeliveryNamespace('acme-tool')).toBe('acme');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ expect(fs.existsSync(path.join(rootDir, '_ns'))).toBe(false);
+ expect(await manager.verifyApprovedSkillSnapshot(manager.list()[0])).toBe(true);
+ },
+ );
+
+ it('does not write a forge revision chain or replace an unknown migration schema during update', async () => {
+ await plantLegacyInstall('acme-tool', false, 'agent-forge');
+ manager = createManager({
+ classifyPendingNamespace: () => ({ kind: 'commit', namespace: 'acme', basis: 'forge-current-org' }),
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ const ledgerPath = path.join(manager.approvalStateRoot(), 'namespace-migration.v1.json');
+ const future = '{"schemaVersion":2,"entries":{"keep":true}}\n';
+ fs.writeFileSync(ledgerPath, future);
+ expect(await manager.update(await makeCindy('acme-tool'), {
+ namespace: 'acme', installOrigin: 'agent-forge',
+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),
+ })).toHaveProperty('ghost');
+ expect(fs.readFileSync(ledgerPath, 'utf8')).toBe(future);
+ manager = createManager({});
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ expect(fs.readFileSync(ledgerPath, 'utf8')).toBe(future);
+ expect(manager.list()[0]).toMatchObject({ namespace: 'acme', enabled: true });
+ });
+
+ it.each(['post-census-forge', 'post-census-manual', 'reinstalled-forge', 'changed-origin', 'different-org', 'missing-prefix'] as const)(
+ 'does not recapture an unverified Forge namespace for %s', async (scenario) => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ let orgSlug = 'acme';
+ let pluginPrefix: string | null = 'acme';
+ const options: Omit<GhostManagerOptions, 'getRootDir'> = {
+ classifyPendingNamespace: (ghostId, marketSyncCompleted = false) => classifyNamespaceMigration({
+ ghostId, builtin: false, marketSyncCompleted, marketRecord: null,
+ installOrigin: readNamespaceMigrationInstallOrigin(() => manager.readApprovedInstallOriginStrict(ghostId)),
+ currentOrganization: { organizationId: 'org-acme', orgSlug, pluginPrefix },
+ }),
+ };
+ manager = createManager(options);
+ if (scenario.startsWith('post-census')) {
+ manager.ensureNamespaceMigrationCensus();
+ } else {
+ await plantLegacyInstall('acme-tool', false, 'agent-forge');
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]?.namespace).toBe('acme');
+ }
+ if (scenario.startsWith('post-census') || scenario === 'reinstalled-forge') {
+ await plantLegacyInstall('acme-tool', false, scenario === 'post-census-manual' ? undefined : 'agent-forge');
+ } else {
+ const store = receiptStore();
+ const approval = store.read('acme-tool');
+ if (approval.state !== 'approved') throw new Error('expected migrated receipt');
+ const { namespace: _namespace, ...unstamped } = approval.receipt;
+ await store.write({
+ ...unstamped, ...(scenario === 'changed-origin' ? { installOrigin: 'manual' } : {}),
+ }, { relId: 'acme-tool', requireSkillSnapshot: false });
+ if (scenario === 'different-org') orgSlug = 'other';
+ if (scenario === 'missing-prefix') pluginPrefix = null;
+ }
+ manager = createManager(options);
+ await manager.reconcilePendingRootNamespaces(true);
+ if (scenario.startsWith('post-census')) {
+ expect(manager.list()[0]).toMatchObject({ namespace: null, namespaceState: 'unconfirmed' });
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ } else {
+ expect(manager.list()[0]).toMatchObject({ namespace: 'acme', namespaceState: 'unconfirmed' });
+ expect(manager.readDeliveryNamespace('acme-tool')).toBeUndefined();
+ }
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ },
+ );
+
+ it('does not claim a post-census downgrade install without verified market evidence', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ manager.list();
+ await plantLegacyInstall('hello');
+ manager = createManager({
+ classifyPendingNamespace: () => ({ kind: 'commit', namespace: null, basis: 'manual-after-sync' }),
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]).toMatchObject({ namespace: null, namespaceState: 'confirmed' });
+ expect(manager.readDeliveryNamespace('hello')).toBeNull();
+ const orgCindy = await makeCindy('hello');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ ghost: { manifest: { id: 'hello' }, namespace: 'acme' },
+ });
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ });
+
+ it('resumes a post-census unstamped resident offline without assigning it root identity', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ manager.list();
+ await plantLegacyInstall('hello');
+ const resumed = vi.fn((ghost: InstalledGhost) => ghost.namespaceState);
+ manager = createManager({
+ canResumePendingResidentOffline: () => true,
+ onResumePendingResidentOffline: resumed,
+ });
+ manager.resumePendingResidentsOffline();
+ expect(resumed).toHaveBeenCalledOnce();
+ expect(resumed.mock.results[0]?.value).toBe('pending');
+ });
+
+ it('does not assign an organization namespace to a plugin planted after the census', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ await plantLegacyInstall('hello');
+ manager = createManager({
+ mutateSnapshot,
+ classifyPendingNamespace: () => ({ kind: 'commit', namespace: 'acme', basis: 'market-organization' }),
+ readUnconfirmedConfirmationEvidence: () => ({
+ marketRecords: [{
+ namespace: 'acme', organizationId: 'org-acme', packageSha256: 'ab'.repeat(32), scope: 'organization', installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ packageSha256: 'ab'.repeat(32),
+ }),
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ // Planted after the empty census. Evidence for a different namespace must not adopt it.
+ expect(manager.list()[0]).toMatchObject({ namespace: null, namespaceState: 'unconfirmed' });
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ expect(manager.readDeliveryNamespace('hello')).toBeUndefined();
+ expect(manager.list()[0]?.enabled).toBe(true);
+ });
+
+ it('keeps a receipt-stamped namespace pending until its market record is stamped', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ let shouldFail = true;
+ manager = createManager({
+ mutateSnapshot,
+ onNamespaceCommitted: () => {
+ if (shouldFail) throw new Error('market ledger unavailable');
+ },
+ });
+ await expect(manager.commitPendingNamespace('hello', 'acme', 'market-organization'))
+ .rejects.toThrow('market ledger unavailable');
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ shouldFail = false;
+ await expect(manager.commitPendingNamespace('hello', 'acme', 'market-organization'))
+ .resolves.toEqual({ ok: true });
+ expect(manager.list()[0]?.namespace).toBe('acme');
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ });
+
+ it('captures a pre-namespace root install as pending and does not treat a later install as pending', async () => {
+ await plantLegacyInstall('xd-feishu');
+ const listed = manager.list();
+ expect(listed).toEqual([
+ expect.objectContaining({
+ manifest: expect.objectContaining({ id: 'xd-feishu' }),
+ namespaceState: 'pending',
+ }),
+ ]);
+ expect(listed[0]?.namespace).toBeUndefined();
+
+ const planted = await makeCindy('helper');
+ const installed = await manager.install(planted);
+ expect('ghost' in installed).toBe(true);
+ const helperGhost = (installed as { ghost: { manifest: { id: string }; namespace?: unknown } }).ghost;
+ expect(helperGhost.manifest.id).toBe('helper');
+ expect(helperGhost).toHaveProperty('namespace', null);
+ const helper = manager.list().find((ghost) => ghost.manifest.id === 'helper');
+ expect(helper).toBeDefined();
+ expect(helper).toHaveProperty('namespace', null);
+ expect(helper?.namespaceState).not.toBe('pending');
+ });
+
+ it('lets a root reinstall proceed after uninstalling a pending legacy install', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });
+ const cindy = await makeCindy('hello');
+ await expect(manager.install(cindy)).resolves.toMatchObject({
+ ghost: { manifest: { id: 'hello' } },
+ });
+ });
+
+ it.each(['interrupted', 'ledger-write-failed'] as const)(
+ 'finishes pending legacy uninstall after %s before allowing a root reinstall', async (boundary) => {
+ await plantLegacyInstall('hello');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ const store = receiptStore(mutateSnapshot);
+ if (boundary === 'interrupted') {
+ await store.writePendingMutation('hello', { kind: 'uninstall' });
+ } else {
+ const registryPath = pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state'));
+ const rename = fs.renameSync;
+ const blocked = vi.spyOn(fs, 'renameSync').mockImplementation((source, target) => {
+ if (String(target) === registryPath) throw new Error('EIO: registry publication failed');
+ return rename(source, target);
+ });
+ try {
+ await expect(manager.uninstall('hello')).resolves.toEqual({ ok: true });
+ expect(store.readPendingMutationSync('hello').state).toBe('valid');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ } finally { blocked.mockRestore(); }
+ }
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list()).toEqual([]);
+ expect(store.readPendingMutationSync('hello').state).toBe('missing');
+ expect(store.readForRecovery('hello').state).toBe('missing');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds ?? []).not.toContain('hello');
+ manager = createManager({ mutateSnapshot });
+ await expect(manager.install(await makeCindy('hello'))).resolves.toMatchObject({
+ ghost: { manifest: { id: 'hello' }, namespace: null },
+ });
+ },
+ );
+
+ it('keeps a pending census while the root directory is in an update backup', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ const live = path.join(rootDir, 'hello');
+ const backup = path.join(rootDir, '.cindy-updating-hello-deadbeef');
+ await fs.promises.rename(live, backup);
+ manager.list();
+ await fs.promises.rename(backup, live);
+ const orgCindy = await makeCindy('hello');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ rejection: { code: 'namespace-migration-pending' },
+ });
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+ });
+
+ it('captures the original receipt when the first census sees an update backup', async () => {
+ await plantLegacyInstall('hello');
+ const receipts = receiptStore();
+ const backupName = '.cindy-updating-hello-deadbeef';
+ await receipts.writePendingMutation('hello', {
+ kind: 'update',
+ packageSha256: 'a'.repeat(64),
+ backupDirName: backupName,
+ phase: 'backed-up',
+ });
+ await fs.promises.rename(path.join(rootDir, 'hello'), path.join(rootDir, backupName));
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ await fs.promises.rename(path.join(rootDir, backupName), path.join(rootDir, 'hello'));
+ await receipts.clearPendingMutation('hello');
+ expect(manager.list()[0]?.namespaceState).toBe('pending');
+ });
+
+ it('blocks a same-name organization install while the root instance is still pending', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ const orgCindy = await makeCindy('hello');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ rejection: { code: 'namespace-migration-pending' },
+ });
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+ });
+
+ it('defers a classified busy root and commits its identity before installing a sibling', async () => {
+ await plantLegacyInstall('hello');
+ const marketLedger = new PluginMarketLedger(path.join(workDir, 'market', 'ledger.v1.json'));
+ marketLedger.upsertInstallation({
+ pluginId: 'root-resource', ghostId: 'hello', releaseId: 'root-release',
+ version: '1.0.0', sha256: 'a'.repeat(64), scope: 'public', organizationId: null,
+ source: 'market', installed: true, updatedAt: '2026-09-30T00:00:00.000Z',
+ });
+ let busy = true;
+ manager = createManager({
+ isNamespaceMigrationBusy: () => busy,
+ classifyPendingNamespace: (ghostId) => classifyNamespaceMigration({
+ ghostId, builtin: false, installOrigin: 'manual', marketSyncCompleted: true,
+ marketRecord: readNamespaceMigrationMarketRecord(() => marketLedger.installationsForGhost(ghostId)),
+ currentOrganization: null,
+ }),
+ beforeNamespaceCommit: (ghostId, namespace) => {
+ if (!marketLedger.stampNamespaceIfAbsent(ghostId, namespace)) throw new Error('stamp failed');
+ },
+ mutateSnapshot,
+ });
+ manager.list();
+ await manager.reconcilePendingRootNamespaces(true);
+ const orgCindy = await makeCindy('hello');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ rejection: { code: 'namespace-migration-pending' },
+ });
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+ expect(marketLedger.installationsForGhost('hello')).toHaveLength(1);
+ expect(manager.list().find((ghost) => ghost.dir === path.join(rootDir, 'hello'))?.namespaceState).toBe('pending');
+ busy = false;
+ await manager.reconcilePendingRootNamespaces(true);
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ ghost: { manifest: { id: 'hello' }, namespace: 'acme' },
+ });
+ expect(marketLedger.installationForPlugin({ ghostId: 'hello', namespace: null })).toMatchObject({ namespace: null });
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ expect(manager.list().find((ghost) => ghost.dir === path.join(rootDir, 'hello'))).toMatchObject({
+ namespace: null,
+ namespaceState: 'confirmed',
+ });
+ });
+
+ it('keeps an already ambiguous multi-record pending install blocked without stamping either row', async () => {
+ await plantLegacyInstall('hello');
+ const beforeCommit = vi.fn();
+ manager = createManager({
+ classifyPendingNamespace: (ghostId) => classifyNamespaceMigration({
+ ghostId, builtin: false, installOrigin: 'manual', marketSyncCompleted: true,
+ marketRecord: readNamespaceMigrationMarketRecord(() => [
+ { scope: 'public', source: 'market', organizationId: null, installed: true },
+ { scope: 'organization', source: 'market', organizationId: 'org-acme', namespace: 'acme', installed: true },
+ ]),
+ currentOrganization: null,
+ }),
+ beforeNamespaceCommit: beforeCommit,
+ });
+ manager.list();
+ await manager.reconcilePendingRootNamespaces(true);
+ await expect(manager.install(await makeCindy('hello'), { namespace: 'other' })).resolves.toMatchObject({
+ rejection: { code: 'namespace-migration-pending' },
+ });
+ expect(beforeCommit).not.toHaveBeenCalled();
+ expect(manager.list().find((ghost) => ghost.dir === path.join(rootDir, 'hello'))?.namespaceState).toBe('pending');
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'other', 'hello'))).toBe(false);
+ });
+
+ it('allows the organization instance after the pending root install is classified', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ await manager.commitPendingRootNamespace('hello', 'market-public');
+ const orgCindy = await makeCindy('hello');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ ghost: { namespace: 'acme', dir: path.join(rootDir, '_ns', 'acme', 'hello') },
+ });
+ expect(manager.list().map((ghost) => [ghost.namespace ?? null, ghost.manifest.id])).toEqual(
+ expect.arrayContaining([
+ [null, 'hello'],
+ ['acme', 'hello'],
+ ]),
+ );
+ });
+
+ it.each([null, 'xd'] as const)('commits namespace %s without moving the directory or storage key', async (namespace) => {
+ await plantLegacyInstall('xd-feishu');
+ manager.list();
+ const committed = namespace === null
+ ? manager.commitPendingRootNamespace('xd-feishu', 'builtin')
+ : manager.commitPendingNamespace('xd-feishu', namespace, 'market-organization');
+ await expect(committed).resolves.toEqual({ ok: true });
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ const ghost = manager.list()[0];
+ expect(ghost).toMatchObject({
+ manifest: { id: 'xd-feishu' },
+ namespace,
+ dir: path.join(rootDir, 'xd-feishu'),
+ });
+ expect(ghost?.namespaceState).not.toBe('pending');
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'xd', 'xd-feishu'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'xd-feishu'))).toBe(false);
+ expect(installedGhostStoragePart(ghost!)).toBe('xd-feishu');
+ });
+
+ it('finishes a receipt-first commit by removing the pending entry after a restart', async () => {
+ await plantLegacyInstall('hello');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ const stateRoot = path.join(workDir, 'ghosts-install-state');
+ const receipts = receiptStore(mutateSnapshot);
+ const approval = receipts.read('hello');
+ if (approval.state !== 'approved') throw new Error('expected approved receipt');
+ await receipts.write({ ...approval.receipt, namespace: 'xd' }, {
+ relId: 'hello', skillSourceDir: path.join(rootDir, 'hello'), requireSkillSnapshot: false,
+ });
+ manager = createManager({ getStateDir: () => stateRoot });
+ await expect(manager.commitPendingNamespace('hello', null, 'market-public')).resolves.toEqual({ ok: true });
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ manager = createManager({ getStateDir: () => stateRoot });
+ expect(manager.list()[0]).toMatchObject({ namespace: 'xd', dir: path.join(rootDir, 'hello') });
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ });
+
+ it('disables and uninstalls an in-place namespaced plugin without inventing _ns paths', async () => {
+ await plantLegacyInstall('xd-feishu');
+ manager.list();
+ await expect(manager.commitPendingNamespace('xd-feishu', 'xd', 'market-organization')).resolves.toEqual({
+ ok: true,
+ });
+ await expect(manager.setEnabled('_ns/xd/xd-feishu', false)).resolves.toEqual({ ok: true });
+ expect(manager.list()[0]?.enabled).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, 'xd-feishu'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'xd', 'xd-feishu'))).toBe(false);
+ await expect(manager.setEnabled('xd-feishu', true)).resolves.toEqual({ ok: true });
+ expect(manager.list()[0]?.enabled).toBe(true);
+ await expect(manager.uninstall('_ns/xd/xd-feishu', { notify: false })).resolves.toEqual({ ok: true });
+ expect(fs.existsSync(path.join(rootDir, 'xd-feishu'))).toBe(false);
+ expect(manager.list()).toEqual([]);
+ });
+
+ it.each([false, true])('installs a same-name root without moving or stopping a legacy organization with skill %s', async (withSkill) => {
+ await stampLegacyOrganizationInstall('hello', withSkill);
+ const before = receiptStore(mutateSnapshot).read('hello');
+ const busy = vi.fn(() => true);
+ manager = createManager({ mutateSnapshot, isNamespaceMigrationBusy: busy });
+ const rootCindy = await makeCindy('hello');
+ await expect(manager.install(rootCindy)).resolves.toMatchObject({
+ ghost: { namespace: null, dir: path.join(rootDir, '_ns', '_root', 'hello') },
+ });
+ expect(busy).not.toHaveBeenCalled();
+ expect(receiptStore(mutateSnapshot).read('hello')).toEqual(before);
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+ expect(manager.list().map((ghost) => [ghost.namespace, ghost.dir])).toEqual(expect.arrayContaining([
+ ['acme', path.join(rootDir, 'hello')], [null, path.join(rootDir, '_ns', '_root', 'hello')],
+ ]));
+ expect(manager.list().map(installedGhostStoragePart).sort()).toEqual(expect.arrayContaining(['hello']));
+ expect(manager.list().map(installedGhostStoragePart)).toEqual(expect.arrayContaining(['hello', '_root__hello']));
+ if (withSkill) {
+ const org = manager.list().find((ghost) => ghost.namespace === 'acme');
+ expect(org).toBeDefined();
+ await expect(manager.verifyApprovedSkillSnapshot(org!)).resolves.toBe(true);
+ }
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list()).toHaveLength(2);
+ await expect(manager.setEnabled('_ns/_root/hello', false)).resolves.toEqual({ ok: true });
+ expect(manager.list().find((ghost) => ghost.namespace === 'acme')?.enabled).toBe(true);
+ await expect(manager.uninstall('_ns/_root/hello')).resolves.toEqual({ ok: true });
+ expect(manager.list()).toEqual([expect.objectContaining({ namespace: 'acme', dir: path.join(rootDir, 'hello') })]);
+ });
+
+ it.each([null, 'acme'] as const)('updates a legacy %s installation in place', async (namespace) => {
+ await plantLegacyInstall('hello', true);
+ manager.list();
+ await manager.commitPendingNamespace('hello', namespace, namespace === null ? 'explicit-root' : 'market-organization');
+ const ghost = manager.list()[0];
+ const { ghostInstallApprovalToken } = await import('../../../shared/ghost.js');
+ await expect(manager.update(await makeCindy('hello'), {
+ namespace, expectedInstalledApproval: ghostInstallApprovalToken(ghost.approval),
+ })).resolves.toMatchObject({ ghost: { namespace, dir: path.join(rootDir, 'hello') } });
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+ });
+
+ it('does not let an absent new root instance mutate a same-name legacy root', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ await manager.commitPendingNamespace('hello', null, 'explicit-root');
+ const before = receiptStore().read('hello');
+ expect(await manager.setEnabled('_ns/_root/hello', false)).toMatchObject({ rejection: { code: 'not-installed' } });
+ expect(await manager.uninstall('_ns/_root/hello')).toMatchObject({ rejection: { code: 'not-installed' } });
+ expect(await manager.removeInstallApproval('_ns/_root/hello')).toBe(true);
+ expect(receiptStore().read('hello')).toEqual(before);
+ expect(manager.list()).toEqual([expect.objectContaining({ enabled: true, dir: path.join(rootDir, 'hello') })]);
+ });
+
+ it.each(['_ns/_root', '_ns/acme', '_ns/acme/org-helper'])('keeps other installs visible when %s is temporarily unreadable', async (unreadable) => {
+ await manager.install(await makeCindy('hello'));
+ await manager.install(await makeCindy('org-helper'), { namespace: 'acme' });
+ const target = path.join(rootDir, ...unreadable.split('/'));
+ const realLstat = fs.lstatSync;
+ const locked = vi.spyOn(fs, 'lstatSync').mockImplementation((filePath, options) => {
+ if (String(filePath) === target) throw Object.assign(new Error('locked'), { code: 'EACCES' });
+ return realLstat(filePath, options as never);
+ });
+ try {
+ expect(manager.list().map((ghost) => ghost.manifest.id)).toEqual([unreadable === '_ns/_root' ? 'org-helper' : 'hello']);
+ } finally {
+ locked.mockRestore();
+ }
+ });
+
+ it('keeps the legacy organization approved when a new root package cannot be installed', async () => {
+ await stampLegacyOrganizationInstall('hello', true);
+ const before = receiptStore(mutateSnapshot).read('hello');
+ const file = await makeCindy('hello', true);
+ manager = createManager({ mutateSnapshot: async () => { throw new Error('snapshot unavailable'); } });
+ await expect(manager.install(file)).resolves.toMatchObject({ rejection: { code: 'io' } });
+ expect(receiptStore(mutateSnapshot).read('hello')).toEqual(before);
+ expect(manager.list()).toEqual([expect.objectContaining({ namespace: 'acme', approval: expect.objectContaining({ state: 'approved' }) })]);
+ });
+
+ it('installs and verifies a namespaced skill snapshot under its physical identity', async () => {
+ const filePath = await makeCindy('helper', true);
+ const result = await manager.install(filePath, { namespace: 'acme' });
+ expect(result).toMatchObject({ ghost: { manifest: { id: 'helper' } } });
+ if (!('ghost' in result)) return;
+ expect(result.ghost.approvedSkillRoot).toContain(path.join('_ns', 'acme', 'helper'));
+ await expect(manager.verifyApprovedSkillSnapshot(result.ghost)).resolves.toBe(true);
+ });
+
+ it('treats a later install of the same organization identity as already installed', async () => {
+ await stampLegacyOrganizationInstall();
+ const orgCindy = await makeCindy('hello');
+ await expect(manager.install(orgCindy, { namespace: 'acme' })).resolves.toMatchObject({
+ rejection: { code: 'already-installed' },
+ });
+ expect(fs.existsSync(path.join(rootDir, '_ns', 'acme', 'hello'))).toBe(false);
+ });
+
+ it('skips the first namespace stamp while the plugin is busy', async () => {
+ await plantLegacyInstall('hello');
+ const busyManager = createManager({
+ isNamespaceMigrationBusy: () => true,
+ mutateSnapshot,
+ });
+ busyManager.list();
+ await expect(busyManager.commitPendingNamespace('hello', null, 'builtin')).resolves.toEqual({
+ ok: false,
+ reason: 'busy',
+ });
+ expect(busyManager.list()[0]?.namespaceState).toBe('pending');
+ });
+
+
+});
+
+describe('plugin instance registry boundaries', () => {
+ it('uses the directory key for a new install and removes that key on uninstall', async () => {
+ const installed = await manager.install(await makeCindy('hello'));
+ expect(installed).toMatchObject({ ghost: { instanceKey: '_root__hello', namespace: null } });
+ expect(installedGhostStoragePart(manager.list()[0]!)).toBe('_root__hello');
+ await expect(manager.setEnabled('_ns/_root/hello', false)).resolves.toEqual({ ok: true });
+ expect(manager.list()[0]?.enabled).toBe(false);
+ await expect(manager.uninstall('_ns/_root/hello', { notify: false })).resolves.toEqual({ ok: true });
+ expect(manager.list()).toEqual([]);
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(false);
+ });
+
+ it('rebuilds the same directory key when the registry file is missing or corrupt', async () => {
+ await expect(manager.install(await makeCindy('hello'), { namespace: 'xd' })).resolves.toMatchObject({
+ ghost: { instanceKey: '_ns__xd__hello', namespace: 'xd' },
+ });
+ const registryPath = pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state'));
+ await fs.promises.rm(registryPath);
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list()[0]).toMatchObject({
+ instanceKey: '_ns__xd__hello', namespace: 'xd', namespaceState: 'confirmed',
+ });
+ fs.writeFileSync(registryPath, '{');
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list()[0]).toMatchObject({
+ instanceKey: '_ns__xd__hello', namespace: 'xd', namespaceState: 'confirmed',
+ });
+ expect(fs.existsSync(registryPath)).toBe(true);
+ expect(fs.readFileSync(registryPath, 'utf8')).not.toBe('{');
+ });
+
+ it('does not quarantine or rewrite a newer instance registry schema', async () => {
+ await expect(manager.install(await makeCindy('hello'), { namespace: 'xd' })).resolves.toHaveProperty('ghost');
+ const registryPath = pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state'));
+ const future = '{"schemaVersion":3,"census":null,"instances":{"keep":true}}\n';
+ fs.writeFileSync(registryPath, future);
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list()[0]).toMatchObject({ manifest: { id: 'hello' }, enabled: true });
+ expect(manager.readDeliveryNamespace('_ns__xd__hello')).toBeUndefined();
+ expect(fs.readFileSync(registryPath, 'utf8')).toBe(future);
+ expect(fs.readdirSync(path.dirname(registryPath)).some((name) => name.includes('corrupt-'))).toBe(false);
+ });
+
+ it('does not grant legacy pending to a plugin planted after the census', async () => {
+ expect(manager.list()).toEqual([]);
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ await plantLegacyInstall('later');
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list()[0]).toMatchObject({ namespaceState: 'unconfirmed', namespace: null });
+ expect(manager.list()[0]?.namespaceState).not.toBe('pending');
+ expect(manager.isPendingLegacyNamespace('later')).toBe(false);
+ expect(manager.readDeliveryNamespace('later')).toBeUndefined();
+ });
+
+ it('addresses an in-place organization by its directory key beside a root sibling', async () => {
+ await plantLegacyInstall('hello');
+ await expect(manager.commitPendingNamespace('hello', 'acme', 'market-organization')).resolves.toEqual({ ok: true });
+ await expect(manager.install(await makeCindy('hello'))).resolves.toMatchObject({
+ ghost: { instanceKey: '_root__hello', namespace: null },
+ });
+ expect(manager.readDeliveryNamespace('hello')).toBe('acme');
+ expect(manager.readDeliveryNamespace('_root__hello')).toBeNull();
+ expect(manager.list().map(installedGhostStoragePart).sort()).toEqual(['_root__hello', 'hello']);
+ });
+
+ it('reattaches an upgraded install when the market reinstalls it', async () => {
+ await expect(manager.install(await makeCindy('hello'))).resolves.toMatchObject({
+ ghost: { instanceKey: '_root__hello' },
+ });
+ await expect(manager.uninstall('_ns/_root/hello', { notify: false })).resolves.toEqual({ ok: true });
+ await expect(manager.install(await makeCindy('hello'), {
+ registrySource: 'market', pluginId: 'plugin-a',
+ })).resolves.toMatchObject({ ghost: { instanceKey: '_root__hello' } });
+ const registry = JSON.parse(fs.readFileSync(
+ pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state')), 'utf8',
+ )) as { instances: Record<string, { source: string; pluginId: string | null; contentRelId: string; active: boolean }> };
+ expect(registry.instances['_root__hello']).toMatchObject({
+ source: 'market', pluginId: 'plugin-a', contentRelId: '_ns/_root/hello', active: true,
+ });
+ expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
+ });
+
+ it('records the market plugin id instead of treating the install as manual', async () => {
+ await expect(manager.install(await makeCindy('hello'), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a',
+ })).resolves.toMatchObject({ ghost: { instanceKey: '_ns__acme__hello' } });
+ const registry = JSON.parse(fs.readFileSync(
+ pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state')), 'utf8',
+ )) as { instances: Record<string, { source: string; pluginId: string | null }> };
+ expect(registry.instances['_ns__acme__hello']).toMatchObject({
+ source: 'market', pluginId: 'plugin-a',
+ });
+ });
+
+ it('clears the registry cache when the data owner changes', async () => {
+ let owner = 'a';
+ const switched = new GhostManager({
+ getRootDir: () => path.join(workDir, owner, 'ghosts'),
+ getStateDir: () => path.join(workDir, owner, 'state'),
+ getOwnerContextKey: () => owner,
+ mutateSnapshot,
+ });
+ await expect(switched.install(await makeCindy('hello'), { namespace: 'xd' })).resolves.toMatchObject({
+ ghost: { namespace: 'xd' },
+ });
+ expect(switched.readDeliveryNamespace('_ns__xd__hello')).toBe('xd');
+ owner = 'b';
+ await expect(switched.install(await makeCindy('hello'))).resolves.toMatchObject({
+ ghost: { namespace: null, instanceKey: '_root__hello' },
+ });
+ expect(switched.readDeliveryNamespace('_ns__xd__hello')).toBeUndefined();
+ expect(switched.readDeliveryNamespace('_root__hello')).toBeNull();
+ expect(switched.list()).toEqual([
+ expect.objectContaining({ namespace: null, namespaceState: 'confirmed', instanceKey: '_root__hello' }),
+ ]);
+ owner = 'a';
+ expect(switched.readDeliveryNamespace('_ns__xd__hello')).toBe('xd');
+ expect(switched.list()).toEqual([
+ expect.objectContaining({ namespace: 'xd', namespaceState: 'confirmed', instanceKey: '_ns__xd__hello' }),
+ ]);
+ });
+});
+
+describe('downgrade then upgrade', () => {
+ const sha = 'cd'.repeat(32);
+
+ async function rewriteLikeOldClient(relId: string, enabled: boolean): Promise<void> {
+ const store = receiptStore(mutateSnapshot);
+ const approval = store.read(relId);
+ if (approval.state !== 'approved') throw new Error('expected approved receipt');
+ const { namespace: _namespace, ...downgraded } = approval.receipt;
+ await store.write(
+ { ...downgraded, enabled, packageSha256: sha },
+ { relId, requireSkillSnapshot: false },
+ );
+ const marker = path.join(rootDir, relId, '.disabled');
+ if (enabled) fs.rmSync(marker, { force: true });
+ else fs.writeFileSync(marker, '');
+ }
+
+ it('keeps every pre-namespace class usable and restores privileges only from positive evidence', async () => {
+ await plantLegacyInstall('public-tool');
+ await plantLegacyInstall('manual-tool');
+ await plantLegacyInstall('org-tool');
+ await plantLegacyInstall('cindy-helper');
+ await expect(manager.commitPendingNamespace('public-tool', null, 'market-public')).resolves.toEqual({ ok: true });
+ await expect(manager.commitPendingNamespace('manual-tool', null, 'manual-after-sync')).resolves.toEqual({ ok: true });
+ await expect(manager.commitPendingNamespace('org-tool', 'acme', 'market-organization')).resolves.toEqual({ ok: true });
+ await expect(manager.commitPendingNamespace('cindy-helper', null, 'builtin')).resolves.toEqual({ ok: true });
+
+ await rewriteLikeOldClient('public-tool', false);
+ await rewriteLikeOldClient('manual-tool', true);
+ await rewriteLikeOldClient('org-tool', true);
+ await rewriteLikeOldClient('cindy-helper', true);
+
+ manager = createManager({ mutateSnapshot });
+ const byId = (id: string) => manager.list().find((ghost) => ghost.manifest.id === id);
+ expect(manager.list().map((ghost) => ghost.manifest.id).sort()).toEqual([
+ 'cindy-helper', 'manual-tool', 'org-tool', 'public-tool',
+ ]);
+ expect(byId('public-tool')).toMatchObject({
+ enabled: false, namespace: null, namespaceState: 'unconfirmed', dir: path.join(rootDir, 'public-tool'),
+ });
+ expect(byId('manual-tool')).toMatchObject({
+ enabled: true, namespace: null, namespaceState: 'unconfirmed', dir: path.join(rootDir, 'manual-tool'),
+ });
+ expect(byId('org-tool')).toMatchObject({
+ enabled: true, namespace: 'acme', namespaceState: 'unconfirmed', dir: path.join(rootDir, 'org-tool'),
+ });
+ expect(byId('cindy-helper')).toMatchObject({
+ enabled: true, namespace: null, namespaceState: 'unconfirmed', dir: path.join(rootDir, 'cindy-helper'),
+ });
+ for (const id of ['public-tool', 'manual-tool', 'org-tool', 'cindy-helper']) {
+ expect(manager.readDeliveryNamespace(id)).toBeUndefined();
+ expect(byId(id)?.namespaceState).not.toBe('pending');
+ }
+
+ manager = createManager({
+ mutateSnapshot,
+ readUnconfirmedConfirmationEvidence: (record) => {
+ if (record.ghostId === 'manual-tool') return { marketRecords: [], packageSha256: sha };
+ if (record.ghostId === 'org-tool') {
+ return {
+ marketRecords: [{
+ namespace: 'acme', organizationId: 'org-acme', packageSha256: sha, scope: 'organization', installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ packageSha256: sha,
+ };
+ }
+ return {
+ marketRecords: [{
+ namespace: null, organizationId: null, packageSha256: sha, scope: 'public', installed: true,
+ }],
+ packageSha256: sha,
+ };
+ },
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(byId('public-tool')).toMatchObject({ enabled: false, namespace: null, namespaceState: 'confirmed' });
+ expect(manager.readDeliveryNamespace('public-tool')).toBeNull();
+ expect(byId('cindy-helper')).toMatchObject({ enabled: true, namespace: null, namespaceState: 'confirmed' });
+ expect(manager.readDeliveryNamespace('cindy-helper')).toBeNull();
+ expect(byId('org-tool')).toMatchObject({ enabled: true, namespace: 'acme', namespaceState: 'confirmed' });
+ expect(manager.readDeliveryNamespace('org-tool')).toBe('acme');
+ expect(byId('manual-tool')).toMatchObject({ enabled: true, namespace: null, namespaceState: 'unconfirmed' });
+ expect(manager.readDeliveryNamespace('manual-tool')).toBeUndefined();
+ expect(fs.existsSync(path.join(rootDir, '_ns'))).toBe(false);
+ });
+
+ it('does not show the previous owner registry after a downgrade', async () => {
+ let owner = 'a';
+ const switched = new GhostManager({
+ getRootDir: () => path.join(workDir, owner, 'ghosts'),
+ getStateDir: () => path.join(workDir, owner, 'state'),
+ getOwnerContextKey: () => owner,
+ mutateSnapshot,
+ });
+ await expect(switched.install(await makeCindy('hello'), { namespace: 'xd' })).resolves.toMatchObject({
+ ghost: { namespace: 'xd', instanceKey: '_ns__xd__hello' },
+ });
+ const store = new GhostInstallReceiptStore(() => path.join(workDir, 'a', 'state'), mutateSnapshot);
+ const approval = store.read('_ns/xd/hello');
+ if (approval.state !== 'approved') throw new Error('expected owner approval');
+ const { namespace: _namespace, ...downgraded } = approval.receipt;
+ await store.write(downgraded, { relId: '_ns/xd/hello', requireSkillSnapshot: false });
+ expect(switched.list()[0]).toMatchObject({ namespace: 'xd', namespaceState: 'unconfirmed' });
+ expect(switched.readDeliveryNamespace('_ns__xd__hello')).toBeUndefined();
+ owner = 'b';
+ expect(switched.list()).toEqual([]);
+ expect(switched.readDeliveryNamespace('_ns__xd__hello')).toBeUndefined();
+ owner = 'a';
+ expect(switched.readDeliveryNamespace('_ns__xd__hello')).toBeUndefined();
+ expect(switched.list()).toEqual([
+ expect.objectContaining({ namespace: 'xd', namespaceState: 'unconfirmed', instanceKey: '_ns__xd__hello' }),
+ ]);
+ });
+});
+
+
+describe('unconfirmed organization recovery', () => {
+ const sha = 'ab'.repeat(32);
+ const org = { organizationId: 'org-xd', orgSlug: 'xd' as string | null };
+
+ async function stripNamespace(relId: string): Promise<void> {
+ const store = receiptStore(mutateSnapshot);
+ const approval = store.read(relId);
+ if (approval.state !== 'approved') throw new Error('expected approval');
+ const { namespace: _namespace, ...rest } = approval.receipt;
+ await store.write({ ...rest, packageSha256: sha }, { relId, requireSkillSnapshot: false });
+ }
+
+ it('confirms again after market sync restores a namespace an old client removed', async () => {
+ await plantLegacyInstall('xd-feishu');
+ await expect(manager.commitPendingNamespace('xd-feishu', 'xd', 'market-organization')).resolves.toEqual({ ok: true });
+ await stripNamespace('xd-feishu');
+ const ledger = new PluginMarketLedger(path.join(workDir, 'market', 'ledger.v1.json'));
+ const pluginId = 'c' + 'e'.repeat(24);
+ ledger.upsertInstallation({
+ pluginId, ghostId: 'xd-feishu', releaseId: 'release-1', version: '1.0.0',
+ sha256: sha, scope: 'organization', organizationId: 'org-xd', source: 'market',
+ installed: true, updatedAt: '2026-10-08T00:00:00.000Z',
+ });
+ const evidenceFor = () => {
+ const row = ledger.installationForPlugin({ ghostId: 'xd-feishu', namespace: 'xd' })
+ ?? ledger.installationForPlugin({ ghostId: 'xd-feishu' });
+ return {
+ marketRecords: row ? [{
+ ...(Object.prototype.hasOwnProperty.call(row, 'namespace') ? { namespace: row.namespace ?? null } : {}),
+ organizationId: row.organizationId,
+ packageSha256: row.sha256,
+ scope: row.scope,
+ installed: row.installed,
+ }] : [],
+ currentOrganization: org,
+ packageSha256: sha,
+ };
+ };
+ manager = createManager({ mutateSnapshot, readUnconfirmedConfirmationEvidence: evidenceFor });
+ expect(manager.list()[0]).toMatchObject({ namespace: 'xd', namespaceState: 'unconfirmed' });
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-other', namespace: 'xd',
+ }])).toBe(0);
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]?.namespaceState).toBe('unconfirmed');
+ ledger.upsertInstallation({ ...ledger.installationForPlugin({ ghostId: 'xd-feishu' })!, sha256: 'cd'.repeat(32) });
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-xd', namespace: 'xd',
+ }])).toBe(1);
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.readDeliveryNamespace('xd-feishu')).toBeUndefined();
+ ledger.upsertInstallation({ ...ledger.installationForPlugin({ ghostId: 'xd-feishu', namespace: 'xd' })!, sha256: sha });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]).toMatchObject({ namespace: 'xd', namespaceState: 'confirmed' });
+ expect(manager.readDeliveryNamespace('xd-feishu')).toBe('xd');
+ expect(resolveGhostFirstPartyPrivilege({
+ ghostId: 'xd-feishu', namespace: 'xd', builtin: false, installOrigin: 'manual',
+ currentOrganization: { organizationId: 'org-xd', orgSlug: null, pluginPrefix: 'xd' },
+ marketRecord: {
+ scope: 'organization', source: 'market', installed: true, organizationId: 'org-xd',
+ sha256: sha, approvedPackageSha256: sha,
+ },
+ approvedPackageSha256: sha,
+ }).brokerEligible).toBe(true);
+ });
+
+ it('does not stamp a namespace when the receipt changes while evidence is collected', async () => {
+ await plantLegacyInstall('hello');
+ await expect(manager.commitPendingNamespace('hello', 'acme', 'market-organization')).resolves.toEqual({ ok: true });
+ await stripNamespace('hello');
+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
+ manager = createManager({
+ mutateSnapshot,
+ readUnconfirmedConfirmationEvidence: () => {
+ const raw = JSON.parse(fs.readFileSync(receiptPath, 'utf8')) as { revision: string };
+ raw.revision = '99999999-9999-4999-8999-999999999999';
+ fs.writeFileSync(receiptPath, JSON.stringify(raw));
+ return {
+ marketRecords: [{
+ namespace: 'acme', organizationId: 'org-acme', packageSha256: sha, scope: 'organization', installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ packageSha256: sha,
+ };
+ },
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ expect(manager.list()[0]).toMatchObject({ namespaceState: 'unconfirmed', namespace: 'acme' });
+ expect(manager.readDeliveryNamespace('hello')).toBeUndefined();
+ const after = receiptStore(mutateSnapshot).read('hello');
+ expect(after.state === 'approved' && after.receipt.namespace).not.toBe('acme');
+ });
+
+ it('confirms a root and an organization instance from their own market rows', async () => {
+ await plantLegacyInstall('helper');
+ await expect(manager.commitPendingNamespace('helper', 'xd', 'market-organization')).resolves.toEqual({ ok: true });
+ await expect(manager.install(await makeCindy('helper'))).resolves.toHaveProperty('ghost');
+ await stripNamespace('helper');
+ await stripNamespace('_ns/_root/helper');
+ manager = createManager({
+ mutateSnapshot,
+ readUnconfirmedConfirmationEvidence: (record) => ({
+ marketRecords: [record.namespace === 'xd'
+ ? { namespace: 'xd', organizationId: 'org-xd', packageSha256: sha, scope: 'organization' as const, installed: true }
+ : { namespace: null, organizationId: null, packageSha256: sha, scope: 'public' as const, installed: true }],
+ currentOrganization: org,
+ packageSha256: sha,
+ }),
+ });
+ await manager.reconcilePendingRootNamespaces(true);
+ const listed = manager.list();
+ expect(listed.find((ghost) => ghost.namespace === 'xd')).toMatchObject({ namespaceState: 'confirmed' });
+ expect(listed.find((ghost) => ghost.namespace === null)).toMatchObject({ namespaceState: 'confirmed' });
+ expect(manager.readDeliveryNamespace('helper')).toBe('xd');
+ expect(manager.readDeliveryNamespace('_root__helper')).toBeNull();
+ });
+
+ it('censuses only the legacy root directories present at the first scan', async () => {
+ await plantLegacyInstall('hello');
+ await plantLegacyInstall('kept');
+ const receipts = receiptStore(mutateSnapshot);
+ const keptReceipt = receipts.read('kept');
+ if (keptReceipt.state !== 'approved') throw new Error('expected approved receipt');
+ await receipts.write({ ...keptReceipt.receipt, namespace: 'acme' }, {
+ relId: 'kept', skillSourceDir: path.join(rootDir, 'kept'), requireSkillSnapshot: false,
+ });
+ const census = manager.ensureNamespaceMigrationCensus();
+ expect(census?.pendingRelIds).toEqual(['hello']);
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'hello')?.namespaceState).toBe('pending');
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'kept')?.namespaceState).not.toBe('pending');
+ await plantLegacyInstall('later');
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'later')?.namespaceState).not.toBe('pending');
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'hello')?.namespaceState).toBe('pending');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'namespace-migration.v1.json'))).toBe(false);
+ });
+
+ it('ignores a future migration file instead of blocking the census', async () => {
+ await plantLegacyInstall('hello');
+ const legacyPath = path.join(workDir, 'ghosts-install-state', 'namespace-migration.v1.json');
+ const future = '{"schemaVersion":2,"entries":{"keep":true}}' + String.fromCharCode(10);
+ fs.writeFileSync(legacyPath, future);
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ expect(fs.readFileSync(legacyPath, 'utf8')).toBe(future);
+ await plantLegacyInstall('later');
+ manager = createManager({ mutateSnapshot });
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'later')?.namespaceState).not.toBe('pending');
+ expect(manager.list().find((ghost) => ghost.manifest.id === 'hello')?.namespaceState).toBe('pending');
+ expect(fs.readFileSync(legacyPath, 'utf8')).toBe(future);
+ });
+
+ it('finishes a receipt-first namespace commit as one registry write and one active instance', async () => {
+ await plantLegacyInstall('hello');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toContain('hello');
+ const state = path.join(workDir, 'ghosts-install-state');
+ const receipts = receiptStore(mutateSnapshot);
+ const approval = receipts.read('hello');
+ if (approval.state !== 'approved') throw new Error('expected approved receipt');
+ await receipts.write({ ...approval.receipt, namespace: 'xd' }, {
+ relId: 'hello', skillSourceDir: path.join(rootDir, 'hello'), requireSkillSnapshot: false,
+ });
+ const before = JSON.parse(fs.readFileSync(pluginInstanceRegistryPath(state), 'utf8'));
+ expect(before.census.pendingRelIds).toEqual(['hello']);
+ expect(before.instances.hello).toBeUndefined();
+ manager = createManager({ mutateSnapshot, getStateDir: () => state });
+ await expect(manager.commitPendingNamespace('hello', null, 'market-public')).resolves.toEqual({ ok: true });
+ const after = JSON.parse(fs.readFileSync(pluginInstanceRegistryPath(state), 'utf8')) as {
+ instances: Record<string, { active: boolean; instanceKey: string; namespace: string | null; namespaceState: string }>;
+ };
+ const active = Object.values(after.instances).filter((record) => record.active);
+ expect(active).toEqual([
+ expect.objectContaining({ instanceKey: 'hello', namespace: 'xd', namespaceState: 'confirmed' }),
+ ]);
+ expect(manager.list().filter((ghost) => ghost.manifest.id === 'hello')).toHaveLength(1);
+ expect(fs.existsSync(path.join(state, 'namespace-migration.v1.json'))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.test.ts
new file mode 100644
index 0000000000..81ac0c2057
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildUnconfirmedConfirmationEvidence } from '../pluginInstanceConfirmation.js';
+import { reconcilePendingNamespaceMigrations, stampInstanceCensus } from '../pluginNamespaceMigration.js';
+import { emptyPluginInstanceRegistry, type PluginInstanceRecord } from '../pluginInstanceRegistry.js';
+
+const NOW = '2026-10-08T00:00:00.000Z';
+
+function row(overrides: Partial<PluginInstanceRecord> = {}): PluginInstanceRecord {
+ return {
+ instanceKey: 'hello',
+ contentRelId: 'hello',
+ ghostId: 'hello',
+ namespace: null,
+ namespaceState: 'unconfirmed',
+ pluginId: null,
+ source: 'legacy',
+ receiptRevision: null,
+ packageSha256: null,
+ active: true,
+ ...overrides,
+ };
+}
+
+describe('stampInstanceCensus', () => {
+ it('records legacy root directories without rewriting existing rows', () => {
+ const registry = {
+ ...emptyPluginInstanceRegistry(),
+ instances: {
+ hello: row(),
+ kept: row({
+ instanceKey: 'kept', contentRelId: 'kept', ghostId: 'kept',
+ namespace: 'acme', namespaceState: 'confirmed',
+ }),
+ },
+ };
+ const stamped = stampInstanceCensus({
+ registry,
+ candidates: [
+ { ghostId: 'hello', relId: 'hello' },
+ { ghostId: 'kept', relId: 'kept', identitySource: { namespace: 'acme' } },
+ { ghostId: 'later', relId: '_ns/_root/later' },
+ ],
+ now: NOW,
+ readApproval: () => ({ state: 'missing' }),
+ recordLegacyEligibility: () => { throw new Error('missing approval is not recaptured'); },
+ });
+ expect(stamped?.census).toEqual({ completedAt: NOW, pendingRelIds: ['hello'] });
+ expect(stamped?.instances.hello?.namespaceState).toBe('unconfirmed');
+ expect(stamped?.instances.kept?.namespaceState).toBe('confirmed');
+ });
+
+ it('does not allocate rows for a fresh census', () => {
+ const stamped = stampInstanceCensus({
+ registry: emptyPluginInstanceRegistry(),
+ candidates: [
+ { ghostId: 'hello', relId: 'hello' },
+ { ghostId: 'later', relId: '_ns/_root/later' },
+ ],
+ now: NOW,
+ readApproval: () => ({ state: 'missing' }),
+ recordLegacyEligibility: () => undefined,
+ });
+ expect(stamped?.census?.pendingRelIds).toEqual(['hello']);
+ expect(stamped?.instances).toEqual({});
+ });
+});
+
+describe('buildUnconfirmedConfirmationEvidence', () => {
+ it('keeps an absent namespace field distinct from an explicit null', () => {
+ const evidence = buildUnconfirmedConfirmationEvidence({
+ rows: [{ installed: true, scope: 'organization', organizationId: 'org-xd', sha256: 'ab' }],
+ record: row({ namespace: 'xd', namespaceState: 'unconfirmed' }),
+ currentOrganization: { organizationId: 'org-xd', orgSlug: 'xd' },
+ packageSha256: 'ab',
+ forgeSelfTest: false,
+ });
+ expect(evidence.marketRecords?.[0]).not.toHaveProperty('namespace');
+ const explicit = buildUnconfirmedConfirmationEvidence({
+ rows: [{ installed: true, namespace: null, scope: 'public', organizationId: null, sha256: 'ab' }],
+ record: row({ namespace: null }),
+ currentOrganization: null,
+ packageSha256: 'ab',
+ forgeSelfTest: false,
+ });
+ expect(explicit.marketRecords?.[0]).toMatchObject({ namespace: null });
+ });
+});
+
+describe('reconcilePendingNamespaceMigrations', () => {
+ const census = { completedAt: NOW, pendingRelIds: ['hello'] };
+
+ it('does not stop a plugin whose classification is still pending', async () => {
+ const prepare = vi.fn(async () => true);
+ const commit = vi.fn(async () => ({ ok: true as const }));
+ await reconcilePendingNamespaceMigrations({
+ ensureCensus: () => census,
+ ownerContextKey: () => 'owner',
+ preparePendingResident: prepare,
+ readApproval: () => ({ state: 'legacy-unapproved' }),
+ classify: () => ({ kind: 'pending', reason: 'awaiting-organization-namespace' }),
+ commit,
+ confirmUnconfirmed: async () => {},
+ }, true);
+ expect(prepare).not.toHaveBeenCalled();
+ expect(commit).not.toHaveBeenCalled();
+ });
+
+ it('restores a stopped resident when the commit fails', async () => {
+ const settled = vi.fn();
+ await reconcilePendingNamespaceMigrations({
+ ensureCensus: () => census,
+ ownerContextKey: () => 'owner',
+ preparePendingResident: async () => true,
+ onPendingResidentMigrationSettled: settled,
+ readApproval: () => ({ state: 'legacy-unapproved' }),
+ classify: () => ({ kind: 'commit', namespace: 'acme', basis: 'market-organization' }),
+ commit: async () => ({ ok: false as const, reason: 'busy' }),
+ confirmUnconfirmed: async () => {},
+ }, true);
+ expect(settled).toHaveBeenCalledWith('hello', false);
+ });
+
+ it('does not restore when the commit succeeds', async () => {
+ const settled = vi.fn();
+ await reconcilePendingNamespaceMigrations({
+ ensureCensus: () => census,
+ ownerContextKey: () => 'owner',
+ preparePendingResident: async () => true,
+ onPendingResidentMigrationSettled: settled,
+ readApproval: () => ({ state: 'legacy-unapproved' }),
+ classify: () => ({ kind: 'commit', namespace: 'acme', basis: 'market-organization' }),
+ commit: async () => ({ ok: true as const }),
+ confirmUnconfirmed: async () => {},
+ }, true);
+ expect(settled).toHaveBeenCalledWith('hello', true);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
new file mode 100644
index 0000000000..169dec53c9
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
@@ -0,0 +1,132 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createNamespaceMigrationHost, type NamespaceMigrationHostDeps } from '../pluginNamespaceMigrationHost.js';
+
+function deps(overrides: Partial<NamespaceMigrationHostDeps> = {}): NamespaceMigrationHostDeps {
+ return {
+ activeOwnerScopeKey: () => 'owner-a',
+ isAppSessionBoundaryPending: () => false,
+ getGhostManager: () => ({
+ list: () => [],
+ approvedInstallEvidence: () => null,
+ readApprovedInstallOriginStrict: () => 'manual',
+ reconcilePendingRootNamespaces: async () => {},
+ }),
+ getPluginMarketLedger: () => ({
+ lookupInstallationsForNamespaceMigration: () => ({ kind: 'missing' }),
+ }),
+ getAuthState: () => ({ isAuthenticated: false, user: null }),
+ createOrganizationPrefixStore: () => ({ lookup: () => ({ kind: 'missing' }) }),
+ ownerScopedUserDataPath: (...parts) => parts.join('/'),
+ brainRootDir: () => '/brain',
+ readInstalledGhostManifestSnapshot: () => ({ ok: false }),
+ oauthLockExists: () => false,
+ hasPendingWork: () => false,
+ runtimeState: () => null,
+ nodeRuntimeRunning: () => false,
+ stopRuntime: () => {},
+ stopNodeRuntime: async () => {},
+ captureGhostMutationOwner: () => ({}),
+ beginGhostMutation: () => () => {},
+ log: { warn: () => {} },
+ ...overrides,
+ };
+}
+
+describe('pending resident migration host', () => {
+ it('stops a resident that is already running after the client comes online', async () => {
+ const stopRuntime = vi.fn();
+ const stopNodeRuntime = vi.fn(async () => {});
+ const host = createNamespaceMigrationHost(deps({
+ getGhostManager: () => ({
+ list: () => [{
+ manifest: { id: 'ns-resident-probe', launch: 'resident' as const },
+ namespaceState: 'pending',
+ dir: '/ghosts/ns-resident-probe',
+ }],
+ approvedInstallEvidence: () => null,
+ readApprovedInstallOriginStrict: () => 'manual',
+ reconcilePendingRootNamespaces: async () => {},
+ }),
+ runtimeState: (instanceKey) => instanceKey === 'ns-resident-probe' ? 'running' : null,
+ stopRuntime,
+ stopNodeRuntime,
+ }));
+
+ await expect(host.preparePendingResidentForMigration('ns-resident-probe')).resolves.toBe(true);
+ expect(stopRuntime).toHaveBeenCalledWith('ns-resident-probe');
+ expect(stopNodeRuntime).toHaveBeenCalledWith('ns-resident-probe');
+ });
+
+ it('does not stop a running panel plugin', async () => {
+ const stopRuntime = vi.fn();
+ const host = createNamespaceMigrationHost(deps({
+ getGhostManager: () => ({
+ list: () => [{
+ manifest: { id: 'panel-probe' },
+ namespaceState: 'pending',
+ dir: '/ghosts/panel-probe',
+ }],
+ approvedInstallEvidence: () => null,
+ readApprovedInstallOriginStrict: () => 'manual',
+ reconcilePendingRootNamespaces: async () => {},
+ }),
+ runtimeState: () => 'running',
+ stopRuntime,
+ }));
+ await expect(host.preparePendingResidentForMigration('panel-probe')).resolves.toBe(false);
+ expect(stopRuntime).not.toHaveBeenCalled();
+ });
+
+ it('restarts a resident when the commit does not land', async () => {
+ const spawn = vi.fn();
+ const host = createNamespaceMigrationHost(deps({
+ getGhostManager: () => ({
+ list: () => [{
+ manifest: { id: 'ns-resident-probe', node: { lifecycle: 'resident' } },
+ namespaceState: 'pending',
+ dir: '/ghosts/ns-resident-probe',
+ }],
+ approvedInstallEvidence: () => null,
+ readApprovedInstallOriginStrict: () => 'manual',
+ reconcilePendingRootNamespaces: async () => {},
+ }),
+ runtimeState: () => 'running',
+ spawnIfResident: spawn,
+ }));
+ await expect(host.preparePendingResidentForMigration('ns-resident-probe')).resolves.toBe(true);
+ host.onPendingResidentMigrationSettled('ns-resident-probe', false);
+ expect(spawn).toHaveBeenCalledWith('ns-resident-probe');
+ host.onPendingResidentMigrationSettled('ns-resident-probe', false);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves an idle online resident alone', async () => {
+ const stopRuntime = vi.fn();
+ const host = createNamespaceMigrationHost(deps({ stopRuntime }));
+ await expect(host.preparePendingResidentForMigration('ns-resident-probe')).resolves.toBe(true);
+ expect(stopRuntime).not.toHaveBeenCalled();
+ });
+
+ it('retries a pending resident that is not in the offline set', async () => {
+ const reconcile = vi.fn(async () => {});
+ const scheduled: Array<() => void> = [];
+ const host = createNamespaceMigrationHost(deps({
+ getGhostManager: () => ({
+ list: () => [],
+ approvedInstallEvidence: () => null,
+ readApprovedInstallOriginStrict: () => 'manual',
+ reconcilePendingRootNamespaces: reconcile,
+ }),
+ setTimeout: (handler) => {
+ scheduled.push(handler);
+ return { unref() {} };
+ },
+ }));
+
+ host.schedulePendingResidentMigrationRetry('ns-resident-probe');
+ expect(reconcile).not.toHaveBeenCalled();
+ scheduled[0]?.();
+ await vi.waitFor(() => expect(reconcile).toHaveBeenCalledWith(true));
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespacePrivilegeMatrix.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespacePrivilegeMatrix.test.ts
new file mode 100644
index 0000000000..585d62a135
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespacePrivilegeMatrix.test.ts
@@ -0,0 +1,238 @@
+import { describe, expect, it } from 'vitest';
+import type { GhostManifest } from '../../../shared/ghost.js';
+import { ghostManifestDigest, type PluginMarketInstallationRecord } from '../../plugin-market/ledger.js';
+import { loadConnectionAudienceResolver } from '../connectionAudienceResolver.js';
+import { confirmUnconfirmedInstances } from '../pluginInstanceConfirmation.js';
+import {
+ confirmUnconfirmedInstance,
+ emptyPluginInstanceRegistry,
+ upsertInstance,
+ type PluginInstanceRecord,
+ type PluginInstanceRegistry,
+} from '../pluginInstanceRegistry.js';
+import {
+ loadGhostFirstPartyFactsLoader,
+ type GhostFirstPartyFactsIdentity,
+} from '../ghostFirstPartyFacts.js';
+import {
+ authorizeGhostHostPrimitive,
+ authorizeGhostTokenBroker,
+} from '../ghostFirstPartyPrivilege.js';
+
+type State = 'confirmed' | 'pending' | 'unconfirmed' | 'unknown';
+type Row = {
+ label: string;
+ ghostId: string;
+ orgSlug: string;
+ orgId: string;
+ prefix: string;
+ trustedNamespace: string | null;
+ state: State;
+ pending: boolean;
+ broker: boolean;
+ host: boolean;
+ marketConnection: boolean;
+ forgeConnection: boolean;
+ forgeReason?: string;
+};
+
+const sha = 'a'.repeat(64);
+
+function manifestFor(id: string): GhostManifest {
+ return {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'index.js',
+ network: {
+ hosts: ['service.example'],
+ secrets: [{
+ key: 'cindy_identity',
+ label: 'Cindy organization identity',
+ source: 'oidc-token',
+ inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['service.example'] },
+ }],
+ },
+ };
+}
+
+function marketRow(id: string, orgId: string, namespace: string | null): PluginMarketInstallationRecord {
+ const manifest = manifestFor(id);
+ return {
+ pluginId: 'plugin-' + id,
+ ghostId: id,
+ releaseId: 'release-1',
+ version: '1.0.0',
+ sha256: sha,
+ scope: 'organization',
+ organizationId: orgId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-10-12T00:00:00.000Z',
+ namespace,
+ manifestDigest: ghostManifestDigest(manifest),
+ rawManifestSha256: ghostManifestDigest(manifest),
+ };
+}
+
+function evaluate(row: Row) {
+ const manifest = manifestFor(row.ghostId.includes('__') ? row.ghostId.split('__').at(-1)! : row.ghostId);
+ const logicalId = manifest.id;
+ const identity: GhostFirstPartyFactsIdentity = {
+ membershipKind: 'org',
+ orgId: row.orgId,
+ orgSlug: row.orgSlug,
+ };
+ const recorded = row.state === 'confirmed' ? row.trustedNamespace : undefined;
+ const factsLoader = loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false,
+ readMarketInstallation: () => marketRow(logicalId, row.orgId, row.trustedNamespace),
+ readApprovedPackageSha256: () => sha,
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: row.prefix }),
+ readInstallOrigin: () => 'manual',
+ readInstallNamespace: () => recorded,
+ readNamespaceState: () => row.state,
+ isPendingLegacyNamespace: () => row.pending,
+ isPendingLegacyForge: () => row.pending,
+ });
+ const loaded = factsLoader.load(row.ghostId, 'runtime', identity);
+ const warnings: string[] = [];
+ const connection = (origin: 'manual' | 'agent-forge') => loadConnectionAudienceResolver({
+ readInstalledManifestIdentity: () => ({
+ manifest,
+ rawManifestSha256: ghostManifestDigest(manifest),
+ legacyManifestDigest: ghostManifestDigest(manifest),
+ legacyManifestDigests: [ghostManifestDigest(manifest)],
+ }),
+ readMarketInstallation: () => marketRow(logicalId, row.orgId, row.trustedNamespace),
+ readApprovedPackageSha256: () => sha,
+ readInstallOrigin: () => origin,
+ readInstallNamespace: () => recorded,
+ readNamespaceState: () => row.state,
+ isPendingLegacyNamespace: () => row.pending,
+ isPendingLegacyForge: () => row.pending,
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: row.prefix }),
+ log: { info() {}, warn(_message, meta) { if (typeof meta?.reason === 'string') warnings.push(meta.reason); } },
+ }).resolve(row.ghostId, {
+ membershipId: 'member-1',
+ membershipKind: 'org',
+ orgId: row.orgId,
+ orgSlug: row.orgSlug,
+ });
+ return {
+ broker: authorizeGhostTokenBroker(row.ghostId, loaded),
+ host: authorizeGhostHostPrimitive(row.ghostId, loaded),
+ marketConnection: connection('manual') !== null,
+ forgeConnection: connection('agent-forge') !== null,
+ warnings,
+ };
+}
+
+const rows: Row[] = [
+ { label: 'old root confirmed', ghostId: 'helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: null, state: 'confirmed', pending: false, broker: false, host: false, marketConnection: true, forgeConnection: true },
+ { label: 'old root pending', ghostId: 'helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: null, state: 'pending', pending: true, broker: true, host: false, marketConnection: true, forgeConnection: true },
+ { label: 'old root unconfirmed', ghostId: 'helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: null, state: 'unconfirmed', pending: false, broker: false, host: false, marketConnection: false, forgeConnection: false, forgeReason: 'installed-namespace-unconfirmed' },
+ { label: 'new root confirmed', ghostId: '_root__helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: null, state: 'confirmed', pending: false, broker: false, host: false, marketConnection: true, forgeConnection: true },
+ { label: 'new root unconfirmed', ghostId: '_root__helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: null, state: 'unconfirmed', pending: false, broker: false, host: false, marketConnection: false, forgeConnection: false, forgeReason: 'installed-namespace-unconfirmed' },
+ { label: 'in-place org confirmed', ghostId: 'xd-feishu', orgSlug: 'xd', orgId: 'org-xd', prefix: 'xd', trustedNamespace: 'xd', state: 'confirmed', pending: false, broker: true, host: true, marketConnection: true, forgeConnection: true },
+ { label: 'in-place org pending', ghostId: 'xd-feishu', orgSlug: 'xd', orgId: 'org-xd', prefix: 'xd', trustedNamespace: 'xd', state: 'pending', pending: true, broker: true, host: true, marketConnection: true, forgeConnection: true },
+ { label: 'in-place org unconfirmed', ghostId: 'xd-feishu', orgSlug: 'xd', orgId: 'org-xd', prefix: 'xd', trustedNamespace: 'xd', state: 'unconfirmed', pending: false, broker: false, host: false, marketConnection: false, forgeConnection: false, forgeReason: 'installed-namespace-unconfirmed' },
+ { label: 'namespaced org confirmed', ghostId: '_ns__acme__helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: 'acme', state: 'confirmed', pending: false, broker: true, host: false, marketConnection: true, forgeConnection: true },
+ { label: 'namespaced org unconfirmed', ghostId: '_ns__acme__helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: 'acme', state: 'unconfirmed', pending: false, broker: false, host: false, marketConnection: false, forgeConnection: false, forgeReason: 'installed-namespace-unconfirmed' },
+ { label: 'namespaced org unknown', ghostId: '_ns__acme__helper', orgSlug: 'acme', orgId: 'org-acme', prefix: 'acme', trustedNamespace: 'acme', state: 'unknown', pending: false, broker: true, host: false, marketConnection: false, forgeConnection: true },
+];
+
+describe('plugin namespace privilege matrix', () => {
+ it.each(rows)('$label', (row) => {
+ const actual = evaluate(row);
+ expect({
+ broker: actual.broker,
+ host: actual.host,
+ marketConnection: actual.marketConnection,
+ forgeConnection: actual.forgeConnection,
+ }).toEqual({
+ broker: row.broker,
+ host: row.host,
+ marketConnection: row.marketConnection,
+ forgeConnection: row.forgeConnection,
+ });
+ if (row.forgeReason) expect(actual.warnings).toContain(row.forgeReason);
+ });
+
+ it('restores broker access after an unconfirmed instance is confirmed', async () => {
+ const record: PluginInstanceRecord = {
+ instanceKey: '_ns__acme__helper',
+ contentRelId: '_ns/acme/helper',
+ ghostId: 'helper',
+ namespace: 'acme',
+ namespaceState: 'unconfirmed',
+ pluginId: 'plugin-helper',
+ source: 'market',
+ receiptRevision: 'rev-1',
+ packageSha256: sha,
+ active: true,
+ };
+ expect(confirmUnconfirmedInstance(record, {
+ marketRecords: [{
+ namespace: 'acme',
+ organizationId: 'org-acme',
+ packageSha256: sha,
+ scope: 'organization',
+ installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ packageSha256: sha,
+ forgeSelfTest: false,
+ })).toEqual({ namespace: 'acme' });
+ let registry: PluginInstanceRegistry = upsertInstance(emptyPluginInstanceRegistry(), record);
+ const receipt = {
+ id: 'helper',
+ revision: 'rev-1',
+ namespace: 'acme',
+ packageSha256: sha,
+ manifest: manifestFor('helper'),
+ enabled: true,
+ };
+ await confirmUnconfirmedInstances({
+ readEvidence: () => ({
+ marketRecords: [{
+ namespace: 'acme',
+ organizationId: 'org-acme',
+ packageSha256: sha,
+ scope: 'organization',
+ installed: true,
+ }],
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ packageSha256: sha,
+ forgeSelfTest: false,
+ }),
+ isBlocked: () => false,
+ sync: () => registry,
+ ownerContextKey: () => 'owner',
+ readApproval: () => ({ state: 'approved', receipt: receipt as never }),
+ runExclusive: (body) => body(),
+ contentPath: (relId) => relId,
+ writeReceipt: async () => {},
+ writeRegistry: (next) => { registry = next; },
+ });
+ expect(registry.instances[record.instanceKey]?.namespaceState).toBe('confirmed');
+ const restored = evaluate({
+ label: 'restored',
+ ghostId: '_ns__acme__helper',
+ orgSlug: 'acme',
+ orgId: 'org-acme',
+ prefix: 'acme',
+ trustedNamespace: 'acme',
+ state: 'confirmed',
+ pending: false,
+ broker: true,
+ host: false,
+ marketConnection: true,
+ forgeConnection: true,
+ });
+ expect(restored.broker).toBe(true);
+ expect(restored.marketConnection).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts
index 66cceccb95..0d4fb2a89f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS,
@@ -366,6 +366,54 @@ describe('parseGhostPanelMediaUrl(右键菜单形状:图片 + 视频)', () => {
});
});
+describe('GhostPreviewGate instance isolation', () => {
+ it('keeps same-name root and organization preview grants and rate limits independent', async () => {
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) =>
+ ['art', '_ns__acme__art', '_ns__other__art'].includes(instanceId));
+ const gate = new GhostPreviewGate({
+ ghostCanRead,
+ getBlobInfo: async () => ({ ext: '.png', mimeType: 'image/png' }),
+ blobUrl: () => 'cindy-media://blobs/' + HASH + '.png',
+ now: () => 1000,
+ });
+ for (const instanceId of ['art', '_ns__acme__art', '_ns__other__art']) {
+ await expect(gate.request({
+ ghostId: 'art', instanceId, url: URL_OK, isPanelFocused: () => true,
+ })).resolves.toMatchObject({ ok: true });
+ expect(ghostCanRead).toHaveBeenLastCalledWith(HASH, instanceId);
+ await expect(gate.request({
+ ghostId: 'art', instanceId, url: URL_OK, isPanelFocused: () => true,
+ })).resolves.toEqual({ ok: false, reason: 'rate-limited' });
+ }
+ });
+
+ it('never falls back to the root grant when the organization does not own the image', async () => {
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId === 'art');
+ const gate = new GhostPreviewGate({
+ ghostCanRead,
+ getBlobInfo: async () => ({ ext: '.png', mimeType: 'image/png' }),
+ blobUrl: () => 'cindy-media://blobs/' + HASH + '.png',
+ });
+ await expect(gate.request({
+ ghostId: 'art', instanceId: '_ns__acme__art', url: URL_OK, isPanelFocused: () => true,
+ })).resolves.toEqual({ ok: false, reason: 'not-owned' });
+ expect(ghostCanRead).toHaveBeenCalledExactlyOnceWith(HASH, '_ns__acme__art');
+ });
+
+ it('rejects a mismatched instance before querying the ledger', async () => {
+ const ghostCanRead = vi.fn(async () => true);
+ const gate = new GhostPreviewGate({
+ ghostCanRead,
+ getBlobInfo: async () => ({ ext: '.png', mimeType: 'image/png' }),
+ blobUrl: () => 'cindy-media://blobs/' + HASH + '.png',
+ });
+ await expect(gate.request({
+ ghostId: 'art', instanceId: '_ns__acme__other', url: URL_OK, isPanelFocused: () => true,
+ })).resolves.toEqual({ ok: false, reason: 'bad-url' });
+ expect(ghostCanRead).not.toHaveBeenCalled();
+ });
+});
+
describe('resolveGhostPanelMedia(换发闸:attach / menu 两用途)', () => {
const DEPS = {
ghostCanRead: async () => true,
@@ -374,6 +422,76 @@ describe('resolveGhostPanelMedia(换发闸:attach / menu 两用途)', () => {
blobAbsPath: (hash: string, ext: string) => `/blobs/${hash.slice(0, 2)}/${hash}${ext}`,
statSize: async () => 1234,
};
+
+ it.each([
+ ['menu', 'media'],
+ ['menu', 'preview'],
+ ['attach', 'media'],
+ ['attach', 'preview'],
+ ] as const)('%s resolves %s through the verified namespaced instance', async (purpose, shape) => {
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId === '_ns__acme__art');
+ await expect(resolveGhostPanelMedia(
+ 'cindy-ghost://art/' + shape + '/' + HASH + '.png',
+ purpose,
+ { ...DEPS, ghostCanRead },
+ { ghostId: 'art', instanceId: '_ns__acme__art' },
+ )).resolves.toEqual({ url: 'cindy-media://blobs/' + HASH + '.png', kind: 'image' });
+ expect(ghostCanRead).toHaveBeenCalledWith(HASH, '_ns__acme__art');
+ });
+
+ it('does not borrow a root or another organization media grant', async () => {
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId !== '_ns__acme__art');
+ await expect(resolveGhostPanelMedia(
+ 'cindy-ghost://art/media/' + HASH + '.png',
+ 'menu',
+ { ...DEPS, ghostCanRead },
+ { ghostId: 'art', instanceId: '_ns__acme__art' },
+ )).resolves.toBeNull();
+ expect(ghostCanRead).toHaveBeenCalledExactlyOnceWith(HASH, '_ns__acme__art');
+ });
+
+ it('rejects a URL host that differs from the verified installed manifest', async () => {
+ const ghostCanRead = vi.fn(async () => true);
+ await expect(resolveGhostPanelMedia(
+ 'cindy-ghost://other/media/' + HASH + '.png',
+ 'attach',
+ { ...DEPS, ghostCanRead },
+ { ghostId: 'art', instanceId: '_ns__acme__art' },
+ )).resolves.toBeNull();
+ expect(ghostCanRead).not.toHaveBeenCalled();
+ });
+
+ it('keeps the legacy root call on the physical root grant', async () => {
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId === 'art');
+ await expect(resolveGhostPanelMedia(
+ 'cindy-ghost://art/media/' + HASH + '.png',
+ 'attach',
+ { ...DEPS, ghostCanRead },
+ )).resolves.toEqual({ url: 'cindy-media://blobs/' + HASH + '.png', kind: 'image' });
+ expect(ghostCanRead).toHaveBeenCalledWith(HASH, 'art');
+ });
+
+ it.each(['', '../art', '_ns/acme/art', '_ns__acme__other'])('rejects invalid or mismatched storage identity %s', async (instanceId) => {
+ const ghostCanRead = vi.fn(async () => true);
+ await expect(resolveGhostPanelMedia(
+ 'cindy-ghost://art/media/' + HASH + '.png',
+ 'attach',
+ { ...DEPS, ghostCanRead },
+ { ghostId: 'art', instanceId },
+ )).resolves.toBeNull();
+ expect(ghostCanRead).not.toHaveBeenCalled();
+ });
+
+ it('keeps the legacy physical key after an in-place namespace stamp', async () => {
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId === 'art');
+ await expect(resolveGhostPanelMedia(
+ 'cindy-ghost://art/media/' + HASH + '.png',
+ 'menu',
+ { ...DEPS, ghostCanRead },
+ { ghostId: 'art', instanceId: 'art' },
+ )).resolves.toEqual({ url: 'cindy-media://blobs/' + HASH + '.png', kind: 'image' });
+ expect(ghostCanRead).toHaveBeenCalledExactlyOnceWith(HASH, 'art');
+ });
/** HASH = 'a'×64 的视频换发预期(路径引用元数据齐全)。 */
const VIDEO_RESOLVED = {
url: `cindy-media://blobs/${HASH}.mp4`,
@@ -385,6 +503,17 @@ describe('resolveGhostPanelMedia(换发闸:attach / menu 两用途)', () => {
mimeType: 'video/mp4',
};
+ it.each(['menu', 'attach'] as const)('%s resolves namespaced video without changing its public filename', async (purpose) => {
+ const ghostCanRead = vi.fn(async (_hash: string, instanceId: string) => instanceId === '_ns__acme__art');
+ await expect(resolveGhostPanelMedia(
+ 'cindy-ghost://art/media/' + HASH + '.mp4',
+ purpose,
+ { ...DEPS, ghostCanRead, getBlobInfo: async () => ({ ext: '.mp4', mimeType: 'video/mp4' }) },
+ { ghostId: 'art', instanceId: '_ns__acme__art' },
+ )).resolves.toEqual(VIDEO_RESOLVED);
+ expect(ghostCanRead).toHaveBeenCalledExactlyOnceWith(HASH, '_ns__acme__art');
+ });
+
it('menu:图片换发成功并回传 kind=image', async () => {
await expect(
resolveGhostPanelMedia(`cindy-ghost://art/media/${HASH}.png`, 'menu', DEPS),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/residentGhost.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/residentGhost.test.ts
index b6a23f77cc..560509c7b4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/residentGhost.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/residentGhost.test.ts
@@ -51,3 +51,14 @@ it('preserves disabled/unavailable gates and ordinary on-demand startup behavior
expect(deps.startNode).not.toHaveBeenCalled();
expect(deps.spawnBrowser).not.toHaveBeenCalled();
});
+
+it('starts a pending install without waiting for namespace confirmation', () => {
+ const checked = validateGhostManifest(manifest);
+ if (!checked.ok) throw new Error(checked.reason);
+ const ghost = { enabled: true, manifest: checked.manifest, namespaceState: 'pending' } as InstalledGhost;
+ const deps = { isAvailable: () => true, startNode: vi.fn(), spawnBrowser: vi.fn(async () => ({ ok: true })), warn: vi.fn() };
+ spawnResidentGhost(ghost, deps);
+ expect(deps.spawnBrowser).toHaveBeenCalledOnce();
+ spawnResidentGhost({ ...ghost, enabled: false }, deps);
+ expect(deps.spawnBrowser).toHaveBeenCalledOnce();
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts
index 583609014d..824f8afcf8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/routineSlot.test.ts
@@ -1,4 +1,5 @@
import { afterEach, describe, it, expect, vi } from 'vitest';
+import path from 'node:path';
import { RoutineEngine } from '@cindy/maker-scheduler';
import type { InstalledGhost } from '../../../shared/ghost.js';
import { handleRoutineRequest } from '../routineSlot.js';
@@ -80,10 +81,11 @@ describe('Plugin routine publisher', () => {
async function statusFixture() {
let now = 1000;
+ let sequence = 0;
const changed = vi.fn();
const engine = new RoutineEngine({
load: async () => null, save: vi.fn(async () => {}), execute: vi.fn(async () => ({})),
- id: () => 'id', now: () => now, changed, onError: vi.fn(),
+ id: () => 'id-' + ++sequence, now: () => now, changed, onError: vi.fn(),
});
await engine.start();
return {
@@ -207,6 +209,102 @@ const listening = { action: 'status', status: 'listening' };
const publish = { action: 'publish', event: { id: 'startup-event', type: 'new', occurredAt: 1, data: {} } };
const busy = { ok: false, message: 'Routine request intake is busy; retry later' };
+const rootMail = { ...ghost, namespace: null, dir: path.join('ghosts', '_ns', '_root', 'mail') };
+const orgMail = { ...ghost, namespace: 'acme', dir: path.join('ghosts', '_ns', 'acme', 'mail') };
+
+it.each([
+ ['mail', { ...ghost, dir: path.join('ghosts', 'mail'), namespaceState: 'pending' as const }],
+ ['mail', { ...ghost, dir: path.join('ghosts', 'mail'), namespace: 'acme' }],
+ ['_root__mail', rootMail],
+ ['_ns__acme__mail', orgMail],
+] as const)('uses the physical source key %s for status and publication', async (instanceId, plugin) => {
+ const fixture = await statusFixture();
+ try {
+ expect(await fixture.request(listening, plugin)).toEqual({ ok: true });
+ expect(fixture.engine.listSources().map(({ id }) => id)).toEqual(['plugin:' + instanceId]);
+ expect(await fixture.request(publish, plugin)).toEqual({ ok: true, accepted: 0, duplicate: false });
+ expect(await fixture.request(publish, plugin)).toEqual({ ok: true, accepted: 0, duplicate: true });
+ } finally {
+ await fixture.engine.stop();
+ }
+});
+
+it('isolates same-name routine triggers, receipts and Host disconnects by physical instance', async () => {
+ const fixture = await statusFixture();
+ const sources = ['plugin:_root__mail', 'plugin:_ns__acme__mail'];
+ try {
+ const routines = [];
+ for (const sourceId of sources) {
+ routines.push(await fixture.engine.createOnce('bot', {
+ name: sourceId, prompt: 'Read new mail', enabled: true,
+ triggers: [{ id: 'new-mail', kind: 'event', sourceId, eventType: 'new', filters: [] }],
+ }, 'routine-' + sourceId.replace(/:/g, '-')));
+ }
+ await fixture.request(listening, rootMail);
+ await fixture.request(listening, orgMail);
+ expect(await fixture.request({ ...publish, sourceId: sources[1] }, rootMail))
+ .toEqual({ ok: true, accepted: 1, duplicate: false });
+ expect(fixture.engine.history(routines[0].id)[0].events).toEqual([{ sourceId: sources[0], event: publish.event }]);
+ expect(fixture.engine.history(routines[1].id)).toEqual([]);
+ expect(await fixture.request(publish, orgMail)).toEqual({ ok: true, accepted: 1, duplicate: false });
+ expect(fixture.engine.history(routines[1].id)[0].events).toEqual([{ sourceId: sources[1], event: publish.event }]);
+ expect(await fixture.request(publish, rootMail)).toEqual({ ok: true, accepted: 0, duplicate: true });
+ expect(await fixture.request(publish, orgMail)).toEqual({ ok: true, accepted: 0, duplicate: true });
+ fixture.engine.removeSource(sources[1]);
+ expect(fixture.engine.listSources().map(({ id, status }) => ({ id, status }))).toEqual([
+ { id: sources[0], status: 'listening' },
+ { id: sources[1], status: 'disconnected' },
+ ]);
+ const next = { ...publish, event: { ...publish.event, id: 'next-event' } };
+ expect(await fixture.request(next, orgMail)).toEqual({ ok: false, message: 'Event source is not listening' });
+ expect(await fixture.request(next, rootMail)).toEqual({ ok: true, accepted: 1, duplicate: false });
+ } finally {
+ await fixture.engine.stop();
+ }
+});
+
+it('keeps same-name source rate limits independent', async () => {
+ const fixture = await statusFixture();
+ try {
+ for (let index = 0; index < 60; index += 1) {
+ expect(await fixture.request(listening, rootMail)).toEqual({ ok: true });
+ }
+ expect(await fixture.request(listening, rootMail)).toMatchObject({ ok: false, message: expect.stringContaining('rate limit') });
+ expect(await fixture.request(listening, orgMail)).toEqual({ ok: true });
+ for (let index = 0; index < 60; index += 1) {
+ const event = { ...publish, event: { ...publish.event, id: 'event-' + index } };
+ expect(await fixture.request(event, rootMail)).toMatchObject({ ok: true, duplicate: false });
+ }
+ expect(await fixture.request(publish, rootMail)).toMatchObject({ ok: false, message: expect.stringContaining('rate limit') });
+ expect(await fixture.request(publish, orgMail)).toMatchObject({ ok: true, duplicate: false });
+ } finally {
+ await fixture.engine.stop();
+ }
+});
+
+it('reserves intake slots per physical instance and shares them across an in-place namespace confirmation', async () => {
+ const fixture = await statusFixture();
+ const ready = deferred<RoutineEngine>();
+ const getEngine = vi.fn(() => ready.promise);
+ const legacy = { ...ghost, dir: path.join('ghosts', 'mail') };
+ const stamped = { ...legacy, namespace: 'acme' };
+ const request = (plugin: InstalledGhost) => handleRoutineRequest(plugin, listening, getEngine, () => true);
+ const pending = Array.from({ length: 8 }, () => request(legacy));
+ try {
+ expect(await request(stamped)).toEqual(busy);
+ pending.push(...Array.from({ length: 8 }, () => request(rootMail)));
+ pending.push(...Array.from({ length: 8 }, () => request(orgMail)));
+ expect(getEngine).toHaveBeenCalledTimes(24);
+ expect(await request(rootMail)).toEqual(busy);
+ expect(await request(orgMail)).toEqual(busy);
+ } finally {
+ ready.resolve(fixture.engine);
+ const results = await Promise.all(pending);
+ await fixture.engine.stop();
+ expect(results.every(({ ok }) => ok)).toBe(true);
+ }
+});
+
it('bounds the entire request including ignored fields before waiting, with UTF-8 accounting', async () => {
const getEngine = vi.fn();
const invalid: unknown[] = [
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts
index a5fe550edd..17fd7a3ae5 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts
@@ -22,6 +22,8 @@ function scheduleGhost(
schedule?: boolean;
enabled?: boolean;
background?: boolean;
+ namespace?: string | null;
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
} = {},
): InstalledGhost {
const agentNeeds = {
@@ -41,6 +43,8 @@ function scheduleGhost(
dir: '/fake/sched-ghost',
enabled: options.enabled ?? true,
iconDataUrl: 'data:image/png;base64,AAAA',
+ ...(options.namespaceState !== undefined ? { namespaceState: options.namespaceState } : {}),
+ ...(options.namespace !== undefined ? { namespace: options.namespace } : {}),
} as InstalledGhost;
}
@@ -147,7 +151,9 @@ describe('GhostScheduleSlot 载荷校验', () => {
});
expect(res).toEqual({ ok: true });
expect(pushes[0].name).toHaveLength(GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS);
- expect(pushes[0].prompt).toHaveLength(GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS);
+ // 用户原文截到上限;寻址说明接在后面,不能被截掉。
+ const address = '\n\n调用这个插件时只传 ghost_id「sched-ghost」,不要传 namespace。';
+ expect(pushes[0].prompt).toBe('p'.repeat(GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS) + address);
});
});
@@ -201,6 +207,36 @@ describe('GhostScheduleSlot 骚扰钳制', () => {
});
describe('GhostScheduleSlot 推送内容', () => {
+ it('企业实例的预填提示带上 namespace', () => {
+ const { slot, pushes } = makeSlot({
+ getGhost: () => scheduleGhost({ namespace: 'acme', namespaceState: 'confirmed' }),
+ });
+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });
+ expect(pushes[0]).toMatchObject({
+ ghostId: 'sched-ghost',
+ namespace: 'acme',
+ });
+ expect(pushes[0].prompt).toContain('namespace 传「acme」');
+ });
+
+ it('待迁移实例不在草稿上写 namespace', () => {
+ const { slot, pushes } = makeSlot({
+ getGhost: () => scheduleGhost({ namespaceState: 'pending' }),
+ });
+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });
+ expect(pushes[0].namespace).toBeUndefined();
+ expect(pushes[0].prompt).toContain('不要传 namespace');
+ });
+
+ it('已确认 root 显式带上 namespace null', () => {
+ const { slot, pushes } = makeSlot({
+ getGhost: () => scheduleGhost({ namespace: null, namespaceState: 'confirmed' }),
+ });
+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });
+ expect(pushes[0].namespace).toBeNull();
+ expect(pushes[0].prompt).toContain('namespace 传 null');
+ });
+
it('身份由主机按已装清单填,沙箱伪装不了', () => {
const { slot, pushes } = makeSlot();
slot.handleRequest('sched-ghost', {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
index 9f9d370aba..7916dc1560 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
@@ -1,3 +1,4 @@
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -112,6 +113,25 @@ function sameRealPath(a: string, b: string): boolean {
}
describe('skillSlot · checkSkillMdConsistency', () => {
+ it('reclaims a new root snapshot link before reinstalling the same skill', async () => {
+ const installed = { ...ghost('helper', [{ dir: 'skills/guide', name: 'guide' }]), namespace: null };
+ const snapshotRoot = path.join(approvalStateRoot, 'skill-snapshots', '_ns', '_root', 'helper');
+ const skillRoot = (revision: string) => path.join(snapshotRoot, revision);
+ const write = async (revision: string) => {
+ installed.approvedSkillRoot = skillRoot(revision);
+ const directory = path.join(installed.approvedSkillRoot, 'skills', 'guide');
+ await fs.promises.mkdir(directory, { recursive: true });
+ await fs.promises.writeFile(path.join(directory, 'SKILL.md'), '---\nname: guide\ndescription: 说明\n---\n正文\n');
+ };
+ const reconcile = (ghosts: InstalledGhost[]) => reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });
+ await write('original');
+ expect((await reconcile([installed])).actions).toContainEqual({ linkName: 'helper--guide', op: 'linked' });
+ await fs.promises.rm(snapshotRoot, { recursive: true });
+ expect((await reconcile([])).actions).toContainEqual({ linkName: 'helper--guide', op: 'removed' });
+ await write('replacement');
+ expect((await reconcile([installed])).actions).toContainEqual({ linkName: 'helper--guide', op: 'linked' });
+ expect(sameRealPath(path.join(sharedDir(), 'helper--guide'), path.join(skillRoot('replacement'), 'skills', 'guide'))).toBe(true);
+ });
const item = { dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' };
const md = (name: string, description: string) =>
`---\nname: ${name}\ndescription: ${description}\n---\n\n正文\n`;
@@ -136,6 +156,46 @@ describe('skillSlot · checkSkillMdConsistency', () => {
});
describe('skillSlot · reconcileGhostSkillLinks', () => {
+ it('projects root and organization skills separately and reclaims a namespaced dangling link', async () => {
+ const root = ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }]);
+ const organization = {
+ ...ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }]),
+ namespace: 'acme',
+ dir: path.join(brainRoot, '_ns', 'acme', 'my-ghost'),
+ approvedSkillRoot: path.join(approvalStateRoot, 'skill-snapshots', '_ns', 'acme', 'my-ghost', 'revision'),
+ };
+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');
+ await fs.promises.mkdir(path.join(organization.approvedSkillRoot, 'skills', 'foo'), { recursive: true });
+ await fs.promises.writeFile(path.join(organization.approvedSkillRoot, 'skills', 'foo', 'SKILL.md'),
+ '---\nname: foo\ndescription: 说明\n---\n正文\n');
+ await reconcileGhostSkillLinks({ ghosts: [root, organization], brainRoot, approvalStateRoot, homeDir });
+ const rootLink = path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo'));
+ const orgLink = path.join(sharedDir(), ghostSkillLinkName('_ns__acme__my-ghost', 'foo'));
+ expect(sameRealPath(rootLink, path.join(brainRoot, 'my-ghost', 'skills', 'foo'))).toBe(true);
+ expect(sameRealPath(orgLink, path.join(organization.approvedSkillRoot, 'skills', 'foo'))).toBe(true);
+ await fs.promises.rm(organization.approvedSkillRoot, { recursive: true });
+ await reconcileGhostSkillLinks({ ghosts: [root], brainRoot, approvalStateRoot, homeDir });
+ await expect(fs.promises.lstat(orgLink)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('reclaims a pre-namespace-link-named orphan under a namespaced snapshot path', async () => {
+ const snapshot = path.join(approvalStateRoot, 'skill-snapshots', '_ns', 'acme', 'my-ghost', 'revision', 'skills', 'foo');
+ const legacyLink = path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo'));
+ await fs.promises.mkdir(sharedDir(), { recursive: true });
+ await fs.promises.symlink(snapshot, legacyLink, process.platform === 'win32' ? 'junction' : 'dir');
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
+ await expect(fs.promises.lstat(legacyLink)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it.each(['other', '_root'])('does not reclaim a namespaced dangling link to a %s snapshot', async (namespace) => {
+ const snapshot = path.join(approvalStateRoot, 'skill-snapshots', '_ns', namespace, 'my-ghost', 'revision', 'skills', 'foo');
+ const externalLink = path.join(sharedDir(), ghostSkillLinkName('_ns__acme__my-ghost', 'foo'));
+ await fs.promises.mkdir(sharedDir(), { recursive: true });
+ await fs.promises.symlink(snapshot, externalLink, process.platform === 'win32' ? 'junction' : 'dir');
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
+ expect(await fs.promises.readlink(externalLink)).toBe(snapshot);
+ });
+
it('启用插件 → 私有目录可见;二次对账幂等', async () => {
await writeSkillDir('my-ghost', 'skills/foo', 'foo');
const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];
@@ -788,7 +848,7 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'
validateApprovedSkillSnapshot: (candidate) =>
manager.verifyApprovedSkillSnapshot(candidate),
});
- const linkName = ghostSkillLinkName('e2e-ghost', 'demo');
+ const linkName = ghostSkillLinkName(installedGhostStoragePart(manager.list()[0]!), 'demo');
const approvedSkillRoot = manager.list()[0].approvedSkillRoot;
expect(approvedSkillRoot).toBeTruthy();
const target = path.join(approvedSkillRoot!, 'skills', 'demo');
@@ -798,7 +858,7 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'
await fs.promises.readFile(path.join(sharedDir(), linkName, 'SKILL.md'), 'utf8'),
).toContain('演示技能');
await fs.promises.writeFile(
- path.join(brainRoot, 'e2e-ghost', 'skills', 'demo', 'SKILL.md'),
+ path.join(manager.list()[0].dir, 'skills', 'demo', 'SKILL.md'),
'---\nname: demo\ndescription: 演示技能\n---\n\n篡改后的指令\n',
);
expect(
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts
index d2b032bfe8..49bd20047b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts
@@ -33,6 +33,7 @@ import {
type GhostPipeEventPush,
type InstalledGhost,
} from '../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
describe('did-session-switched primary session resolution', () => {
it('allows ordinary sessions and Orca leads, but never workers or background sessions', () => {
@@ -280,7 +281,7 @@ function makeGateway(overrides: Partial<GhostSubscriptionGatewayDeps> = {}) {
listGhosts: () => [ghost('a', { topics: ['turn'] })],
isRunning: (id) => running.has(id),
wake: vi.fn(async (g: InstalledGhost) => {
- running.add(g.manifest.id);
+ running.add(installedGhostStoragePart(g));
}),
sendToGhost: (ghostId, payload) => {
sent.push({ ghostId, payload });
@@ -323,6 +324,36 @@ describe('subscriptionGateway owner boundary', () => {
const TURN_DATA = { sessionId: 's1', agent: 'claude-code' };
describe('did- 旁听扇出', () => {
+ it('does not deliver an old buffered event after its physical key has been reused', async () => {
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => { release = resolve; });
+ const { gw, sent, running } = makeGateway({ wake: () => pending });
+ gw.publish('turn', 'did-turn-start', TURN_DATA);
+ gw.dropGhost('a');
+ running.add('a');
+ release();
+ await pending;
+ await Promise.resolve();
+ expect(sent).toHaveLength(0);
+ gw.publish('turn', 'did-turn-start', TURN_DATA);
+ expect(sent).toHaveLength(1);
+ expect((sent[0]!.payload as { seq: number }).seq).toBe(1);
+ });
+ it('isolates same-name subscriber queues and never sends organization events to root', () => {
+ const root = ghost('helper', undefined);
+ const organization = { ...ghost('helper', { topics: ['turn'] }), namespace: 'acme', dir: '/fake/_ns/acme/helper' };
+ const { gw, sent, running } = makeGateway({ listGhosts: () => [root, organization] });
+ running.add('helper');
+ running.add('_ns__acme__helper');
+ gw.publish('turn', 'did-turn-start', TURN_DATA);
+ expect(sent.map((event) => event.ghostId)).toEqual(['_ns__acme__helper']);
+ root.manifest.subscribe = { topics: ['turn'] };
+ gw.publish('turn', 'did-turn-start', TURN_DATA);
+ expect(sent.map((event) => [event.ghostId, (event.payload as { seq: number }).seq])).toEqual([
+ ['_ns__acme__helper', 1], ['helper', 1], ['_ns__acme__helper', 2],
+ ]);
+ });
+
it('只投声明了该 topic 的启用意识;seq 单调', async () => {
const { gw, sent, running } = makeGateway({
listGhosts: () => [
@@ -506,6 +537,21 @@ describe('GhostActivityTracker', () => {
});
describe('will- 拦截', () => {
+ it.each(['will-user-message', 'will-assistant-message'] as const)('wakes and routes %s only to its selected organization instance', async (hook) => {
+ const root = ghost('helper', undefined);
+ const org = { ...ghost('helper', { hooks: [hook] }), namespace: 'acme', dir: '/fake/_ns/acme/helper' };
+ const { gw, sent, running } = makeGateway({ listGhosts: () => [root, org] });
+ const screening = hook === 'will-user-message'
+ ? gw.screenUserMessage({ sessionId: 's', text: 'input' })
+ : gw.screenAssistantMessage({ sessionId: 's', text: 'input' });
+ await vi.waitFor(() => expect(sent).toHaveLength(1));
+ expect(running).toEqual(new Set(['_ns__acme__helper']));
+ expect(sent[0]!.ghostId).toBe('_ns__acme__helper');
+ const hookId = (sent[0]!.payload as unknown as { hookId: string }).hookId;
+ gw.handleVerdict('helper', { type: 'event-verdict', hookId, action: 'rewrite', text: 'wrong instance' });
+ gw.handleVerdict('_ns__acme__helper', { type: 'event-verdict', hookId, action: 'rewrite', text: 'organization' });
+ expect(await screening).toMatchObject({ action: 'rewrite', ghostId: '_ns__acme__helper', text: 'organization' });
+ });
beforeEach(() => {
vi.useFakeTimers();
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts
index 828635c242..cd1a7971bf 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts
@@ -41,6 +41,7 @@ function makeSlot(
let clock = 0;
const deps: WorkspaceSlotDeps = {
getGhost: () => workspaceGhost(),
+ getMutationTarget: () => 'original-installation',
showDirectoryDialog: vi.fn(async () => '/Users/me/projects/demo'),
resolveCallContext: vi.fn(() => ({ ghostId: 'ws-ghost', sessionId: 'sess-1' })),
getSessionDirInfo: vi.fn(async () => ({
@@ -66,6 +67,130 @@ const DIR_REQ = {
callId: 'call-1',
} as const;
+describe('workspace installed target boundary', () => {
+ it('does not grant a late selection after the plugin is disabled without a new receipt', async () => {
+ let enabled = true;
+ let finishDialog!: (directory: string) => void;
+ const service = makeService();
+ const { slot } = makeSlot({
+ getGhost: () => workspaceGhost({ enabled }),
+ showDirectoryDialog: () => new Promise<string>((resolve) => { finishDialog = resolve; }),
+ }, service);
+ const pending = slot.handleRequest('ws-ghost', PICK_REQ);
+ enabled = false;
+ finishDialog('/Users/me/projects/demo');
+ expect(await pending).toMatchObject({ ok: false, errorCode: 'CANCELLED' });
+ expect(service.findActiveSessionByWorkdir).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unavailable installed target before asking for a directory', async () => {
+ const service = makeService();
+ const { slot, deps } = makeSlot({ getMutationTarget: () => null }, service);
+ expect(await slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(deps.showDirectoryDialog).not.toHaveBeenCalled();
+ expect(service.findActiveSessionByWorkdir).not.toHaveBeenCalled();
+ });
+
+ it.each(['relocated-installation', 'replacement-source', 'new-owner', null])(
+ 'cancels a late directory selection when the target becomes %s', async (nextTarget) => {
+ let target: string | null = 'original-installation';
+ let finishDialog!: (directory: string) => void;
+ const service = makeService();
+ const { slot } = makeSlot({
+ getMutationTarget: () => target,
+ showDirectoryDialog: () => new Promise<string>((resolve) => { finishDialog = resolve; }),
+ }, service);
+ const pending = slot.handleRequest('ws-ghost', { ...PICK_REQ, focus: true });
+ target = nextTarget;
+ finishDialog('/Users/me/projects/demo');
+ expect(await pending).toMatchObject({ ok: false, errorCode: 'CANCELLED' });
+ expect(service.findActiveSessionByWorkdir).not.toHaveBeenCalled();
+ expect(service.createDraftSession).not.toHaveBeenCalled();
+ expect(service.focusSession).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['reuse', 'create'] as const)('does not %s after the target changes during lookup', async (outcome) => {
+ let target = 'original-installation';
+ const service = makeService({
+ findActiveSessionByWorkdir: vi.fn(async () => {
+ target = 'replacement-source';
+ return outcome === 'reuse' ? 'existing-session' : null;
+ }),
+ });
+ const { slot } = makeSlot({ getMutationTarget: () => target }, service);
+ expect(await slot.handleRequest('ws-ghost', { ...PICK_REQ, focus: true })).toMatchObject({ ok: false, errorCode: 'CANCELLED' });
+ expect(service.createDraftSession).not.toHaveBeenCalled();
+ expect(service.focusSession).not.toHaveBeenCalled();
+ });
+
+ it('passes the installed target guard to draft creation and refuses late focus', async () => {
+ let target = 'original-installation';
+ const service = makeService({
+ createDraftSession: vi.fn(async ({ shouldContinue }) => {
+ expect(shouldContinue?.()).toBe(true);
+ target = 'replacement-source';
+ expect(shouldContinue?.()).toBe(false);
+ return 'late-session';
+ }),
+ });
+ const { slot } = makeSlot({ getMutationTarget: () => target }, service);
+ expect(await slot.handleRequest('ws-ghost', { ...PICK_REQ, focus: true })).toMatchObject({ ok: false, errorCode: 'CANCELLED' });
+ expect(service.focusSession).not.toHaveBeenCalled();
+ });
+
+ it('rechecks the installed target when an authorized request leaves the ensure queue', async () => {
+ let secondCurrent = true;
+ let finishFirst!: (sessionId: string) => void;
+ const service = makeService({
+ createDraftSession: vi.fn(async () => 'second-session')
+ .mockImplementationOnce(() => new Promise<string>((resolve) => { finishFirst = resolve; })),
+ });
+ const { slot, deps } = makeSlot({
+ getMutationTarget: (id) => id === 'second-ghost' && !secondCurrent ? 'replacement-source' : id,
+ }, service);
+ const first = slot.handleRequest('first-ghost', PICK_REQ);
+ await vi.waitFor(() => expect(service.createDraftSession).toHaveBeenCalledOnce());
+ const second = slot.handleRequest('second-ghost', { ...PICK_REQ, focus: true });
+ await vi.waitFor(() => expect(deps.showDirectoryDialog).toHaveBeenCalledTimes(2));
+ secondCurrent = false;
+ finishFirst('first-session');
+ expect(await first).toMatchObject({ ok: true });
+ expect(await second).toMatchObject({ ok: false, errorCode: 'CANCELLED' });
+ expect(service.findActiveSessionByWorkdir).toHaveBeenCalledOnce();
+ expect(service.createDraftSession).toHaveBeenCalledOnce();
+ expect(service.focusSession).not.toHaveBeenCalled();
+ });
+
+ it.each(['stat', 'session', 'review', 'confirm'] as const)(
+ 'stops a dir request when its installed target changes during %s', async (phase) => {
+ let target = 'original-installation';
+ const service = makeService({ reviewPermissionAction: vi.fn(async () => {
+ if (phase === 'review') target = 'replacement-source';
+ return { verdict: 'ask' as const };
+ }) });
+ const { slot, deps } = makeSlot({
+ getMutationTarget: () => target,
+ resolveCallContext: () => ({ ghostId: 'ws-ghost', sessionId: 'sess-1', sessionInstanceId: 'instance-1' }),
+ isInsideWorkdir: () => false,
+ statDir: vi.fn(async () => { if (phase === 'stat') target = 'replacement-source'; return 'ok' as const; }),
+ getSessionDirInfo: vi.fn(async () => {
+ if (phase === 'session') target = 'replacement-source';
+ return { workingDir: '/Users/me/projects/demo', remoteHostId: null };
+ }),
+ confirmDir: vi.fn(async () => { target = 'replacement-source'; return { ok: true as const }; }),
+ }, service);
+ expect(await slot.handleRequest('ws-ghost', { ...DIR_REQ, focus: true })).toMatchObject({ ok: false, errorCode: 'CANCELLED' });
+ expect(deps.getSessionDirInfo).toHaveBeenCalledTimes(phase === 'stat' ? 0 : 1);
+ expect(service.reviewPermissionAction).toHaveBeenCalledTimes(phase === 'stat' || phase === 'session' ? 0 : 1);
+ expect(deps.confirmDir).toHaveBeenCalledTimes(phase === 'confirm' ? 1 : 0);
+ expect(service.findActiveSessionByWorkdir).not.toHaveBeenCalled();
+ expect(service.createDraftSession).not.toHaveBeenCalled();
+ expect(service.focusSession).not.toHaveBeenCalled();
+ },
+ );
+});
+
describe('workspaceSlot · 资格审与载荷校验', () => {
it('未声明 workspace 能力 / 未启用 一律 PERMISSION_DENIED', async () => {
const noSlot = makeSlot({ getGhost: () => workspaceGhost({ workspace: false }) });
@@ -117,6 +242,7 @@ describe('workspaceSlot · pick 流(亲选即授权)', () => {
dirAbs: '/Users/me/projects/demo',
title: '选择项目',
ghostId: 'ws-ghost',
+ shouldContinue: expect.any(Function),
});
expect(JSON.stringify(result)).not.toContain('/Users');
});
diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index f3591f34fe..6f5219067b 100644
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@ -3,6 +3,7 @@ import path from 'node:path';
import crypto from 'node:crypto';
import os from 'node:os';
+import { authorDeclaredNamespaceReason } from '@cindy/plugin-protocol';
import {
GHOST_MANIFEST_FILE,
ghostIconMimeType,
@@ -942,6 +943,11 @@ function readSeedManifest(
});
return null;
}
+ const reservedNamespace = authorDeclaredNamespaceReason(raw);
+ if (reservedNamespace) {
+ log?.warn('builtin seed skipped: invalid manifest', { seedDir, reason: reservedNamespace });
+ return null;
+ }
const v = validateGhostManifest(raw);
if (!v.ok) {
log?.warn('builtin seed skipped: invalid manifest', { seedDir, reason: v.reason });
diff --git a/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts b/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts
index 14610d7597..ad776d1974 100644
--- a/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts
+++ b/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts
@@ -7,10 +7,32 @@ import { getGhostCard, upsertGhostCard, type GhostCardRecord } from './cardStore
import { assertRemoteBotInvocationAllowed } from '../device-link/remoteBotSessionBoundary.js';
import { remoteResourceRegistry, RemoteResourceRegistryError, type RemoteResourceProvider } from '../device-link/remoteResourceRegistry.js';
import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent, tapWindowBroadcast, getSafeDataOwnerPushStamp } from '../device-link/broadcast-tap.js';
+import { isValidGhostId } from '../../shared/ghost.js';
+import { createPluginLogicalIdentity, findInstalledGhostByIdentity, findInstalledGhostByInstanceId, isGhostInstanceId } from '../../shared/pluginIdentity.js';
const COLLECTION = 'plugin-results';
const KIND = 'card';
+export function findGhostForRemotePluginIdentity<T extends { manifest: { id: string }; namespace?: string | null }>(
+ ghosts: readonly T[], id: string,
+): T | undefined {
+ if (isGhostInstanceId(id) && !isValidGhostId(id)) {
+ return findInstalledGhostByInstanceId(ghosts, id);
+ }
+ if (!id.startsWith('[')) {
+ const matches = ghosts.filter((ghost) => ghost.manifest.id === id);
+ return matches.length === 1 ? matches[0] : undefined;
+ }
+ try {
+ const parsed: unknown = JSON.parse(id);
+ if (!Array.isArray(parsed) || parsed.length !== 2 ||
+ (parsed[0] !== null && typeof parsed[0] !== 'string') || !isValidGhostId(parsed[1])) return undefined;
+ return findInstalledGhostByIdentity(ghosts, createPluginLogicalIdentity(parsed[0], parsed[1]));
+ } catch {
+ return undefined;
+ }
+}
+
function decodeText(value: string): string {
return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (full, entity: string) => {
const named: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
@@ -168,7 +190,9 @@ export function createPluginIdentityRemoteProvider(deps: {
const valid = deps.captureScope();
let ids: unknown;
try { ids = JSON.parse(request.ref.id); } catch { /* validated below */ }
- if (!Array.isArray(ids) || ids.length !== 2 || !ids.every((id) => typeof id === 'string' && id.length > 0 && id.length <= 128)) {
+ if (!Array.isArray(ids) || ids.length !== 2 ||
+ typeof ids[0] !== 'string' || ids[0].length === 0 || ids[0].length > 128 ||
+ typeof ids[1] !== 'string' || ids[1].length === 0 || ids[1].length > 320) {
throw new RemoteResourceRegistryError('NOT_FOUND', 'Plugin not found');
}
await deps.authorize(ids[0]);
diff --git a/apps/desktop/src/main/cindy-brain/cardService.ts b/apps/desktop/src/main/cindy-brain/cardService.ts
index 1b15493e99..03d5be1bbb 100644
--- a/apps/desktop/src/main/cindy-brain/cardService.ts
+++ b/apps/desktop/src/main/cindy-brain/cardService.ts
@@ -98,6 +98,8 @@ export interface GhostCardRow {
export interface GhostCardPush {
callId: string;
ghostId: string;
+ /** 物理键与逻辑身份不同时,供进行中调用按 namespace 精确配对。 */
+ logicalGhostId?: string;
/** agent 侧 tool_use id(claude 路径有,codex 为 null → renderer 走启发式锚定)。 */
toolUseId: string | null;
/** 静态版(settle 后 / 历史回放用;与落库内容一致)。 */
@@ -151,6 +153,7 @@ const SWEEP_MIN_INTERVAL_MS = 30_000;
interface CallEntry {
ghostId: string;
+ logicalGhostId?: string;
toolUseId: string | null;
sessionId: string | null;
sessionInstanceId?: string;
@@ -200,6 +203,7 @@ interface CallEntry {
/** 卡片供片服务(单例装配见 cindy-brain/index.ts)。 */
export class GhostCardService {
private readonly calls = new Map<string, CallEntry>();
+ private readonly pendingWrites = new Map<Promise<void>, string>();
private lastSweepAt = 0;
constructor(private readonly deps: GhostCardServiceDeps) {}
@@ -237,6 +241,7 @@ export class GhostCardService {
callId: string,
info: {
ghostId: string;
+ logicalGhostId?: string;
toolUseId: string | null;
sessionId: string | null;
sessionInstanceId?: string;
@@ -253,6 +258,7 @@ export class GhostCardService {
this.sweep();
this.calls.set(callId, {
ghostId: info.ghostId,
+ ...(info.logicalGhostId !== undefined ? { logicalGhostId: info.logicalGhostId } : {}),
toolUseId: info.toolUseId,
sessionId: info.sessionId,
sessionInstanceId: info.sessionInstanceId,
@@ -292,6 +298,17 @@ export class GhostCardService {
return this.calls.get(callId)?.ghostId ?? null;
}
+ async relocateGhost(fromPart: string, toPart: string): Promise<void> {
+ for (const entry of this.calls.values()) {
+ if (entry.ghostId === fromPart) entry.ghostId = toPart;
+ }
+ await Promise.all(
+ [...this.pendingWrites]
+ .filter(([, ghostId]) => ghostId === fromPart)
+ .map(([pending]) => pending),
+ );
+ }
+
/**
* 内存条目全息查询(card-action 派发用):除归属外带出 sessionId——
* 铸衍生卡位(spawnCallId)登记时要续上会话归属,历史回放才能按会话
@@ -442,15 +459,17 @@ export class GhostCardService {
updatedAt: now,
};
// 落库失败不阻断推送:活卡先见,历史回放缺卡由 renderer missing 降级兜底。
- void this.deps.persist(row).catch((err) => {
+ const pending = this.deps.persist(row).catch((err) => {
this.deps.log?.warn('ghost card persist failed', {
callId: p.callId,
error: err instanceof Error ? err.message : String(err),
});
- });
+ }).finally(() => this.pendingWrites.delete(pending));
+ this.pendingWrites.set(pending, senderGhostId);
this.deps.broadcast({
callId: p.callId,
ghostId: senderGhostId,
+ ...(entry.logicalGhostId !== undefined ? { logicalGhostId: entry.logicalGhostId } : {}),
toolUseId: entry.toolUseId,
html: sanitized.html,
animatedHtml: sanitized.animatedHtml ?? null,
diff --git a/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts b/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts
index 6273751d99..0cf7cf1766 100644
--- a/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts
+++ b/apps/desktop/src/main/cindy-brain/cindyPrefsStore.ts
@@ -18,9 +18,16 @@
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { assertGhostPrefsWritable, relocateGhostPreferenceMaps } from './ghostPreferenceRelocation.js';
const log = desktopMakerLogger.child('cindy-prefs-store');
+export async function relocateGhostCindyPrefs(from: string, to: string): Promise<void> {
+ await relocateGhostPreferenceMaps('ghost-cindy-prefs.json', ['overrides', 'inflightLimits'], from, to, () => {
+ store = createStore();
+ });
+}
+
/** cindy 槽能力键(类目.动作;与身份卡详单同一词汇表,当前包含 video)。 */
// text.oneshot(快问快答)与图像/视频同表:每项覆盖记的都是一组供应商×模型。
// 文本类的取值是轻量任务模型链的档位键(codex-gpt-5.4-mini 等),不是媒体目录模型 id。
@@ -113,13 +120,18 @@ function normalize(raw: unknown): GhostCindyPrefs {
return { overrides, inflightLimits };
}
-const store = createOverrideSettingsFile<GhostCindyPrefs>({
- filePath: () => ownerScopedUserDataPath('ghost-cindy-prefs.json'),
- defaults: DEFAULTS,
- normalize,
- log,
- label: 'ghost-cindy-prefs',
-});
+function createStore() {
+ return createOverrideSettingsFile<GhostCindyPrefs>({
+ filePath: () => ownerScopedUserDataPath('ghost-cindy-prefs.json'),
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'ghost-cindy-prefs',
+ preserveUnreadableFile: true,
+ });
+}
+
+let store = createStore();
/** 读某意识的全部覆盖(缺省空对象 = 全跟随默认)。 */
export function readGhostCindyOverrides(ghostId: string): Partial<Record<CindyCapabilityKey, string>> {
@@ -138,6 +150,7 @@ export function writeGhostCindyOverride(
capability: CindyCapabilityKey,
model: string | null,
): Partial<Record<CindyCapabilityKey, string>> {
+ assertGhostPrefsWritable('ghost-cindy-prefs.json');
// 写前同样失效缓存:避免把用户刚手改的文件内容用旧缓存整体覆写掉。
store.invalidateIfChanged();
const overrides = { ...store.read().overrides };
@@ -163,6 +176,7 @@ export function readGhostCindyInflightLimit(ghostId: string): number | null {
* 只收正整数,非法值直接抛(调用方应在入口校验,这里是最后防线)。
*/
export function writeGhostCindyInflightLimit(ghostId: string, limit: number | null): void {
+ assertGhostPrefsWritable('ghost-cindy-prefs.json');
if (limit !== null && (!Number.isInteger(limit) || limit < 1)) {
throw new Error(`inflight limit 必须是正整数或 null,收到:${String(limit)}`);
}
diff --git a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
index 106a10023f..b0112eeebc 100644
--- a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
+++ b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
@@ -1,23 +1,27 @@
/**
* Host-owned Connection audience resolution. Explicit Forge installs for the
* current organization and intact organization-market installs are the two
- * dynamic bases. A named local-install exception exists only for ghostId
- * `mivo-canvas`: organization members may resolve after the org gate when the
- * installed manifest's exact oidc-token host is only `mivo-canvas.dsworks.cn`.
- * An intact organization market record, including installed:false, still takes
- * the digest path and must not skip via this exception. A present but invalid
- * market ledger is a hard failure, not an absent record. The Host derives the
- * audience from current identity + plugin id.
+ * dynamic bases. A temporary local-install exception exists only for root
+ * ghostId `mivo-canvas`: organization members may resolve after the org gate
+ * when the installed manifest's exact oidc-token host is only
+ * `mivo-canvas.dsworks.cn` and the instance namespace is null or not yet
+ * recorded. Organization installs such as `_ns/xd/mivo-canvas` are excluded.
+ * Delete it after the XD enterprise-market build and the one-time data
+ * migration ship. An intact organization market record, including
+ * installed:false, still takes the digest path and must not skip via this
+ * exception. A present but invalid market ledger is a hard failure, not an
+ * absent record. The Host derives the audience from current identity + plugin id.
*/
import { isValidGhostId, isValidGhostNetworkHostPattern } from '../../shared/ghost.js';
import type { GhostManifest } from '../../shared/ghost.js';
+import { hasDeliveryNamespace, parsePluginInstanceId } from '../../shared/pluginIdentity.js';
import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';
+import { matchesPendingLegacyForge } from './ghostFirstPartyPrivilege.js';
import {
verifyInstalledMarketManifest,
type InstalledMarketManifestIdentity,
} from '../plugin-market/installedManifestIdentity.js';
import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID } from '../plugin-publisher/types.js';
-import { PLUGIN_PREFIX_PATTERN } from '@cindy/plugin-protocol';
export interface ConnectionAudienceIdentity {
membershipId: string;
@@ -42,9 +46,13 @@ export interface ConnectionAudienceResolver {
const ORG_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
const PLUGIN_SLUG_RE = /^[a-z][a-z0-9-]{0,31}$/;
-/** Named local-install Connection exception. Must stay an exact id, not a prefix. */
+/**
+ * Temporary root-only exception for the locally imported mivo-canvas.
+ * Delete it after the XD enterprise-market build ships and the follow-up
+ * one-time Library/KV migration is released.
+ */
const LOCAL_OIDC_ALLOWLIST_GHOST_ID = 'mivo-canvas';
-/** Local exception may inject the org JWT only to this exact BFF host. */
+/** Local exception may inject the org JWT only to this exact host. */
const LOCAL_OIDC_ALLOWLIST_HOST = 'mivo-canvas.dsworks.cn';
/**
@@ -94,6 +102,13 @@ export interface LoadConnectionAudienceResolverOptions {
): PluginMarketInstallationRecord | MarketInstallationLookup | null;
readApprovedPackageSha256?(ghostId: string): string | null;
readInstallOrigin?(ghostId: string): 'manual' | 'agent-forge';
+ /** Trusted receipt namespace. undefined means no delivery field. */
+ readInstallNamespace?(ghostId: string): string | null | undefined;
+ /** See ghostFirstPartyFacts. Path fallback is only legal for unknown. */
+ readNamespaceState?(ghostId: string): 'confirmed' | 'pending' | 'unconfirmed' | 'unknown';
+ /** Upgrade-census root install still running under the pre-namespace rules. */
+ isPendingLegacyNamespace?(ghostId: string): boolean;
+ isPendingLegacyForge?(ghostId: string): boolean;
lookupOrganizationPrefix?(
orgId: string,
): { kind: 'known'; pluginPrefix: string | null } | { kind: 'absent' } | { kind: 'unavailable' };
@@ -108,17 +123,19 @@ export function loadConnectionAudienceResolver(
): ConnectionAudienceResolver {
return {
resolve(ghostId, identity) {
+ const pluginSlug = parsePluginInstanceId(ghostId)?.ghostId ?? ghostId;
const reject = (reason: string): null => {
options.log?.warn('ghost Connection audience resolution rejected', {
ghostId,
+ pluginSlug,
reason,
});
return null;
};
- if (!isValidGhostId(ghostId) || !PLUGIN_SLUG_RE.test(ghostId)) {
+ if (!isValidGhostId(pluginSlug) || !PLUGIN_SLUG_RE.test(pluginSlug)) {
return reject('plugin-id-invalid');
}
- if (isReservedConnectionPluginSlug(ghostId)) {
+ if (isReservedConnectionPluginSlug(pluginSlug)) {
return reject('plugin-id-reserved');
}
if (identity.membershipKind !== 'org') return reject('membership-not-org');
@@ -131,16 +148,17 @@ export function loadConnectionAudienceResolver(
const finish = (manifest: GhostManifest): ConnectionAudienceResolution | null => {
const allowedHosts = declaredOidcTokenHosts(manifest);
if (allowedHosts.length === 0) return reject('oidc-host-declaration-missing');
- const audience = `${identity.orgSlug}:${ghostId}`;
+ const audience = `${identity.orgSlug}:${pluginSlug}`;
if (audience.length > 64) return reject('audience-too-long');
options.log?.info('ghost Connection audience resolved', {
ghostId,
+ pluginSlug,
allowedHostCount: allowedHosts.length,
});
return {
membershipId: identity.membershipId,
audience,
- pluginSlug: ghostId,
+ pluginSlug,
allowedHosts,
};
};
@@ -154,24 +172,53 @@ export function loadConnectionAudienceResolver(
};
// 显式 ghost_forge_install 的企业作者自测分支,同时兼容升级前已有的
- // agent-forge receipt。个人身份、未知前缀与缺失批准包哈希均 fail closed。
+ // agent-forge receipt。资格绑定当前组织身份,不再要求旧认领前缀。
const forgeOrigin = options.readInstallOrigin?.(ghostId);
if (forgeOrigin === 'agent-forge') {
- const prefixLookup = options.lookupOrganizationPrefix?.(identity.orgId);
- const prefix =
- prefixLookup && prefixLookup.kind === 'known' ? prefixLookup.pluginPrefix : null;
- if (prefix && PLUGIN_PREFIX_PATTERN.test(prefix) && ghostId.startsWith(`${prefix}-`)) {
+ const namespaceState = options.readNamespaceState?.(ghostId);
+ if (namespaceState === 'unconfirmed') return reject('installed-namespace-unconfirmed');
+ const parsedNamespace = parsePluginInstanceId(ghostId)?.namespace ?? null;
+ const recordedNamespace = options.readInstallNamespace?.(ghostId);
+ const namespace = recordedNamespace !== undefined ? recordedNamespace : parsedNamespace;
+ let pendingLegacyForCurrentOrg = false;
+ if (recordedNamespace === undefined && parsedNamespace === null) {
+ try {
+ const prefix = options.lookupOrganizationPrefix?.(identity.orgId);
+ pendingLegacyForCurrentOrg = prefix?.kind === 'known' && matchesPendingLegacyForge(
+ pluginSlug,
+ namespace,
+ options.isPendingLegacyForge?.(ghostId) === true,
+ prefix.pluginPrefix,
+ );
+ } catch {
+ pendingLegacyForCurrentOrg = false;
+ }
+ }
+ if (identity.orgSlug && (namespace === identity.orgSlug || pendingLegacyForCurrentOrg)) {
const approvedSha = options.readApprovedPackageSha256?.(ghostId) ?? null;
if (!approvedSha || !/^[a-f0-9]{64}$/.test(approvedSha)) {
return reject('forge-package-sha-missing');
}
const identitySnapshot = readManifestIdentity();
if (!identitySnapshot) return reject('plugin-not-installed');
- if (identitySnapshot.manifest.id !== ghostId) return reject('plugin-id-mismatch');
+ if (identitySnapshot.manifest.id !== pluginSlug) return reject('plugin-id-mismatch');
return finish(identitySnapshot.manifest);
}
}
+ const temporaryRootMivoCanvas = (): boolean => {
+ if (pluginSlug !== LOCAL_OIDC_ALLOWLIST_GHOST_ID) return false;
+ const parsed = parsePluginInstanceId(ghostId);
+ if (!parsed || parsed.namespace !== null) return false;
+ let recordedNamespace: string | null | undefined;
+ try {
+ recordedNamespace = options.readInstallNamespace?.(ghostId);
+ } catch {
+ return false;
+ }
+ return recordedNamespace === undefined || recordedNamespace === null;
+ };
+
let installation: PluginMarketInstallationRecord | null = null;
try {
const lookup = options.readMarketInstallation(ghostId);
@@ -190,12 +237,11 @@ export function loadConnectionAudienceResolver(
return reject('market-installation-read-failed');
}
if (!installation) {
- // Named exception after the org gate and before market-missing reject.
- // Any persisted market row, including installed:false, still takes digest.
- if (ghostId === LOCAL_OIDC_ALLOWLIST_GHOST_ID) {
+ // Temporary root-only exception. Any persisted market row still takes digest.
+ if (temporaryRootMivoCanvas()) {
const allowlisted = readManifestIdentity();
if (!allowlisted) return reject('plugin-not-installed');
- if (allowlisted.manifest.id !== ghostId) return reject('plugin-id-mismatch');
+ if (allowlisted.manifest.id !== pluginSlug) return reject('plugin-id-mismatch');
const allowlistedHosts = declaredOidcTokenHosts(allowlisted.manifest);
if (
allowlistedHosts.length !== 1 ||
@@ -215,6 +261,27 @@ export function loadConnectionAudienceResolver(
if (installation.organizationId !== identity.orgId) {
return reject('market-installation-org-mismatch');
}
+ if (hasDeliveryNamespace(installation)) {
+ let installedNamespace: string | null | undefined;
+ try {
+ installedNamespace = options.readInstallNamespace?.(ghostId);
+ } catch {
+ return reject('installed-namespace-unavailable');
+ }
+ // A running pre-namespace install stays pending until it can stop.
+ // Do not require a receipt namespace that has not been committed yet.
+ // The catalog namespace must still be the current org.
+ const pendingLegacyRoot =
+ installedNamespace === undefined &&
+ options.isPendingLegacyNamespace?.(ghostId) === true;
+ if (
+ (!pendingLegacyRoot && installedNamespace !== installation.namespace) ||
+ (installation.namespace !== null && identity.orgSlug != null &&
+ installation.namespace !== identity.orgSlug)
+ ) {
+ return reject('market-installation-namespace-mismatch');
+ }
+ }
if (!installation.rawManifestSha256 && !installation.manifestDigest) {
return reject('market-manifest-identity-missing');
}
@@ -226,7 +293,7 @@ export function loadConnectionAudienceResolver(
return reject('installed-manifest-read-failed');
}
if (!identitySnapshot) return reject('plugin-not-installed');
- if (identitySnapshot.manifest.id !== ghostId) return reject('plugin-id-mismatch');
+ if (identitySnapshot.manifest.id !== pluginSlug) return reject('plugin-id-mismatch');
if (!verifyInstalledMarketManifest(installation, identitySnapshot)) {
return reject('installed-manifest-identity-mismatch');
}
diff --git a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
index 9b806d22c6..6ec48fde97 100644
--- a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
+++ b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
@@ -37,7 +37,8 @@ import path from 'node:path';
import JSZip from 'jszip';
-import { isValidGhostId, type InstalledGhost } from '../../shared/ghost.js';
+import { type InstalledGhost } from '../../shared/ghost.js';
+import { findInstalledGhostByInstanceId, isGhostInstanceId } from '../../shared/pluginIdentity.js';
import {
MAX_BASIC_CINDY_FILE_BYTES,
MAX_BASIC_UNCOMPRESSED_BYTES,
@@ -529,10 +530,10 @@ export async function exportGhostPackage(
id: unknown,
deps: ExportGhostPackageDeps,
): Promise<ExportGhostPackageResult> {
- if (typeof id !== 'string' || !isValidGhostId(id)) {
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) {
return { status: 'invalid_id' };
}
- const ghost = deps.listInstalled().find((candidate) => candidate.manifest.id === id);
+ const ghost = findInstalledGhostByInstanceId(deps.listInstalled(), id);
if (!ghost) return { status: 'not_installed' };
// 双保险:dir 来自 GhostManager 扫描,这里再确认它是真实目录(lstat
diff --git a/apps/desktop/src/main/cindy-brain/featureRetirementStore.ts b/apps/desktop/src/main/cindy-brain/featureRetirementStore.ts
index 73b6922d15..c66f6218e8 100644
--- a/apps/desktop/src/main/cindy-brain/featureRetirementStore.ts
+++ b/apps/desktop/src/main/cindy-brain/featureRetirementStore.ts
@@ -3,6 +3,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { isValidGhostId } from '../../shared/ghost.js';
+import { isPluginInstanceKey } from '../../shared/pluginIdentity.js';
import type { InstalledFeatureRetirement } from '../../shared/featureRetirements.js';
interface RetirementRecord {
@@ -18,7 +19,7 @@ export class FeatureRetirementStore {
constructor(private readonly getStateRoot: () => string) {}
private file(retirementId: string, pluginId: string): string {
- if (!isValidGhostId(retirementId) || !isValidGhostId(pluginId))
+ if (!isValidGhostId(retirementId) || !isPluginInstanceKey(pluginId))
throw new Error('Invalid retirement identity');
return path.join(this.getStateRoot(), 'feature-retirements', retirementId, `${pluginId}.json`);
}
diff --git a/apps/desktop/src/main/cindy-brain/filoGoogleClientConfig.ts b/apps/desktop/src/main/cindy-brain/filoGoogleClientConfig.ts
deleted file mode 100644
index 7c673bf75c..0000000000
--- a/apps/desktop/src/main/cindy-brain/filoGoogleClientConfig.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type { GhostManifest } from '../../shared/ghost.js';
-import { FILO_GOOGLE_GHOST_ID, FILO_GOOGLE_SECRET_KEY } from './googleAccountsMigration.js';
-
-/**
- * Filo Google 的 OAuth client 随插件清单分发(desktop 类 client 凭证按
- * Google 口径非机密,2026-07 维护者拍板回填 ghost.json)。本模块保留构建
- * 环境覆写通道:.env / 发布环境注入时优先于清单值,只在 main 内存里的出网
- * 声明上补值,不改磁盘 manifest,也不把覆写值广播给 renderer。
- */
-export interface FiloGoogleBuildClientConfig {
- clientId?: string;
- clientSecret?: string;
-}
-
-/** 给 main 内部使用的 Filo Google manifest 补上构建环境里的 OAuth client。 */
-export function withFiloGoogleBuildClientConfig(
- manifest: GhostManifest,
- config: FiloGoogleBuildClientConfig,
-): GhostManifest {
- const clientId = config.clientId?.trim();
- if (manifest.id !== FILO_GOOGLE_GHOST_ID || !clientId || !manifest.network) return manifest;
-
- let changed = false;
- const clientSecret = config.clientSecret?.trim();
- const secrets = manifest.network.secrets?.map((secret) => {
- if (
- secret.key !== FILO_GOOGLE_SECRET_KEY ||
- secret.source !== 'oauth' ||
- !secret.oauth
- ) {
- return secret;
- }
- changed = true;
- const oauth = { ...secret.oauth, clientId };
- delete oauth.clientSecret;
- if (clientSecret) oauth.clientSecret = clientSecret;
- return {
- ...secret,
- oauth,
- };
- });
- if (!changed || !secrets) return manifest;
- return { ...manifest, network: { ...manifest.network, secrets } };
-}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index aceff04885..d878d4f075 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -22,6 +22,7 @@ import { promisify } from 'node:util';
import JSZip from 'jszip';
import {
+ authorDeclaredNamespaceReason,
PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,
PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES,
PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES,
@@ -35,6 +36,7 @@ import {
GHOST_MANIFEST_FILE,
GHOST_MANIFEST_SUMMARY_MAX_CHARS,
GHOST_SKILL_MD_MAX_BYTES,
+ isValidNewGhostId,
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
@@ -672,7 +674,25 @@ export async function scaffoldGhostDir(
if (typeof manifestRaw !== 'string') {
return { ok: false, errorCode: 'INTERNAL', message: 'scaffold manifest 必须是 JSON 字符串' };
}
- const validation = validateGhostManifest(JSON.parse(manifestRaw));
+ let scaffoldManifest: unknown;
+ try {
+ scaffoldManifest = JSON.parse(manifestRaw);
+ } catch {
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: '插件信息不合格:ghost.json 不是合法 JSON',
+ };
+ }
+ const reservedScaffoldNamespace = authorDeclaredNamespaceReason(scaffoldManifest);
+ if (reservedScaffoldNamespace) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: `插件信息不合格:${reservedScaffoldNamespace}`,
+ };
+ }
+ const validation = validateGhostManifest(scaffoldManifest);
if (!validation.ok) {
return {
ok: false,
@@ -680,6 +700,13 @@ export async function scaffoldGhostDir(
message: `插件信息不合格:${validation.reason}`,
};
}
+ if (!isValidNewGhostId(validation.manifest.id)) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: '新建插件 id 必须以小写字母开头,只能包含小写字母、数字和连字符,最长 32 个字符',
+ };
+ }
const brokerPortIssue = brokerRedirectPortDeclarationIssue(validation.manifest);
if (brokerPortIssue) {
return { ok: false, errorCode: 'INVALID_INPUT', message: `插件信息不合格:${brokerPortIssue}` };
@@ -882,6 +909,10 @@ async function buildGhostPackage(
manifestBytes = Buffer.from(`${JSON.stringify(manifestRaw)}\n`, 'utf-8');
}
}
+ const reservedNamespace = authorDeclaredNamespaceReason(manifestRaw);
+ if (reservedNamespace) {
+ return { ok: false, errorCode: 'MANIFEST_INVALID', message: `清单不合格:${reservedNamespace}` };
+ }
const v = validateGhostManifest(manifestRaw);
if (!v.ok) {
return { ok: false, errorCode: 'MANIFEST_INVALID', message: `清单不合格:${v.reason}` };
@@ -1948,7 +1979,7 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它
"extraAuthorizeParams": { "access_type": "offline", "prompt": "consent" }, // 可选 ≤8 条:服务商特有授权参数(协议保留参数禁写)
"identity": { "url": "https://api.example.com/userinfo", "labelPath": "email", "displayTemplate": "{team} · {user}", "avatarPath": "data.avatar_thumb" }, // 可选:授权后拉一次身份端点给账号打标签(设置页"已连接为 xxx";url 域名须命中 hosts)。labelPath 应指向**唯一且稳定**字段(如邮箱 / user_id)——它是重复授权时的同身份合并判定键,选 name 这类可重名可改名字段会误合并。displayTemplate 可选:人类可读展示名模板,\`{点分路径}\` 占位符从同一份身份响应取值(至少一个占位符,≤200 字符),任一占位符取不到值整体降级为空、回落显示 labelPath 的值——labelPath 的稳定字段不可读(如 Slack 的 user_id)时声明它,设置页与账号工具展示的就是渲染后的名字(邮箱这类本身可读的服务商不需要)。avatarPath 可选:头像 URL 在身份响应里的点分路径(如飞书的 "data.avatar_thumb")——主机取 https 地址后**不带凭证**下载小图(仅 png/jpeg/webp/gif、≤256KB)转 data URL 存库,\`/oauth\` 回查里以 account.avatarDataUrl 给你的 settingsHtml 展示(<img> 直接用)。**下载仅对第一方官方意识生效**(头像地址不受 hosts 白名单约束,第三方声明合法但恒降级 null)——所以页面必须能没头像也好看(如回落姓名首字圆片)
"redirectPort": 53682, // 可选:loopback 回调固定端口(1024–65535);声明 tokenBroker 时必填。服务商要求回调 URI 与注册值精确匹配(如 Atlassian)时声明,回调恒为 http://127.0.0.1:<端口>/callback;非 broker 模式缺省 = 随机端口(Google 等允许任意 loopback 端口的服务商不用声明)
- "tokenBroker": "jira", // 可选:三路资格:静态官方前缀照旧放行;当前组织的服务端 organization market 包满足来源/组织/前缀/整包 sha256 绑定;或企业作者用 ghost_forge_install 明确安装且 id 命中本组织已登记前缀。后两路只给 Broker 与 oidc-token,不给宿主原语;手动导入与个人身份不放行。声明时必须同时声明 redirectPort;code/refresh 交换经 Cindy 服务端 broker 完成(client secret 在服务端,不随包分发),与 clientSecret 互斥;设置页不再支持自填 client
+ "tokenBroker": "jira", // 可选:三路资格:随包官方种子或受信任公开市场的官方插件(名称本身不构成资格);当前组织的服务端 organization market 包满足来源/组织/namespace/整包 sha256 绑定;或企业作者用 ghost_forge_install 明确安装到当前组织 namespace。后两路只给 Broker 与 oidc-token,不给宿主原语;手动导入与个人身份不放行。声明时必须同时声明 redirectPort;code/refresh 交换经 Cindy 服务端 broker 完成(client secret 在服务端,不随包分发),与 clientSecret 互斥;设置页不再支持自填 client
"brokerBounce": { "path": "/example/bounce", "callbackPath": "/example/callback" } // 可选:双地址弹跳回调(服务商后台只收 https redirect、不收 http loopback 时用)。必须与 tokenBroker、redirectPort 同时声明;报给服务商的 redirect_uri = broker 服务基地址 + path(主机运行时拼,清单不落域名),浏览器授权后由弹跳路由 302 回 http://127.0.0.1:<redirectPort><callbackPath>
}
}],
@@ -3145,13 +3176,12 @@ PAT。支持宿主管理连接入口时还返回可选的 \`hostManagedSetup:tru
**Cindy 企业身份断言(source:"oidc-token",可选)**:适用于接入 Cindy Connection
Auth 的企业服务。主机只在当前登录账号属于组织 Membership,且满足以下任一安装基座时
按需向 auth-server 换取短时 Connection JWT:①当前组织的 Plugin Market organization
-安装记录(source 必须是服务端 \`market\`),且安装 manifest digest 与记录一致;②企业作者
-显式调用 \`ghost_forge_install\` 安装,插件 id 命中当前组织已登记前缀,且批准 receipt
+安装记录(source 必须是服务端 \`market\`),且 namespace 属于当前组织、已批准整包 sha256 与记录一致;②企业作者
+显式调用 \`ghost_forge_install\` 安装到当前组织 namespace,且批准 receipt
保有本次包的完整 sha256。两路都要求清单声明目标服务域名。
audience 与组织身份由主机推导,插件清单和运行时代码都不能选择、读取或保存
audience/token;audience 固定为 \`\${orgSlug}:\${ghostId}\`,总长不得超过 64 字符。
-个人身份与手动导入默认不签发。点名例外:\`ghostId\` 精确等于 \`mivo-canvas\` 的组织成员本地安装,
-在已装清单声明的精确 oidc-token host 仅为 \`mivo-canvas.dsworks.cn\` 时可解析 audience;其它本地插件、其它精确 host 仍不签发。已有市场
+个人身份与手动导入不签发。临时例外,只对 root 实例生效:\`ghostId\` 精确等于 \`mivo-canvas\`、namespace 为 null 或尚未确认的旧 root 安装,且已装清单声明的精确 oidc-token host 仅为 \`mivo-canvas.dsworks.cn\` 时可解析 audience;企业 namespace 下的同名插件、其它本地插件、其它精确 host 仍不签发。已有市场
organization 记录(含 installed:false)时必须仍走 digest,不得借例外跳过。市场账本损坏、schema 不认或该 ghostId 记录校验失败时 fail-closed,不得当成无记录。企业身份的 Forge 安装前会展示插件名、id 与精确域名,并要求手输相同 id
确认。市场与 Forge 两条组织基座都只给 Broker 与 oidc-token、不给宿主原语。
该凭证必须固定声明
@@ -3240,12 +3270,13 @@ identity.displayTemplate 时,\`/oauth\` 回查与连接结果里 account.label
即可;第一方官方内置意识会先自动结束占用进程并重试,第三方意识不享受此回收
——请选一个不易撞车的端口)。声明 \`tokenBroker\` 时必须提供;非 broker 模式下,
Google 这类允许任意 loopback 端口的服务商不用声明。
-- \`tokenBroker\`:资格有三路:①静态官方前缀命中,照旧放行;②当前组织的服务端
+- \`tokenBroker\`:资格有三路:①随包官方种子或受信任公开市场的官方插件,名称本身不构成资格;②当前组织的服务端
organization market 包已安装、source 为 \`market\`、organizationId 与当前组织一致,
- id 命中本组织已登记前缀,且 release sha256 与批准 receipt 的 packageSha256 相等。
- ③企业作者通过 \`ghost_forge_install\` 明确安装,且 id 命中当前组织已登记前缀;是否已有
- 同 id 市场记录不影响这条自测路径。后两路不接受个人身份或别的组织前缀,且只给 Broker
- 与 oidc-token,不给宿主原语;手动导入不属于 Forge 路径。
+ namespace 与当前组织的可信身份一致,且 release sha256 与批准 receipt 的 packageSha256 相等。
+ ③企业作者通过 \`ghost_forge_install\` 明确安装,Host 绑定当前组织 namespace;只有真实
+ 存量待迁移安装仍使用本组织已登记前缀核对。是否已有同 id 市场记录不影响这条自测路径。
+ 后两路不接受个人身份或别的组织身份;Forge 只给 Broker 与 oidc-token,不给宿主原语,
+ 可信 XD 企业市场安装的宿主能力另按可信组织身份核验,不依赖名称前缀。手动导入不属于 Forge 路径。
code/refresh 交换改经 Cindy 服务端 broker 完成,client secret 由服务端持有、不随包
分发,且要求用户已登录 Cindy。声明它时必须同时声明 redirectPort,并与 clientSecret
互斥;PKCE 缺省开(verifier
@@ -4446,6 +4477,8 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);
以下只解释存量包的兼容形态,用于维护与迁移,**不要照抄到新插件**。存量插件装入且
启用后,主机把每个技能目录投影到 Cindy 的账号隔离目录,分别接入 Claude Code、
Codex、Pi,不写入用户的全局技能目录;停用/卸载即撤销这些入口。
+已知企业 namespace 的实例用 \`_ns__<namespace>__<插件id>--<技能name>\`,
+root 和存量未标记 namespace 的实例继续沿用旧链接名。
目录形态(每条 item 一个目录,内必须有 SKILL.md):
@@ -4773,13 +4806,14 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件
产生的确切包:首次安装、以及权限比已装版本变多的更新,会先在任务里弹确认卡列出权限,
用户允许后才落位;用户拒绝返回 \`MUTATION_CANCELLED\`,不要重试,除非用户再次要求。
首次安装会启用,同 id 已安装时原位更新并保留启用状态、配置、
- 数据与面板位置,同版本也可覆盖。不要因为 scaffold 或 pack 成功就自动调用本工具。
+ 数据与面板位置,同版本也可覆盖。同来源更新延续旧数据;从市场等不同来源切换到 Forge
+ 时旧账号、密钥及数据隔离保留,新来源需要重新连接。不要因为 scaffold 或 pack 成功就自动调用本工具。
企业身份下若清单声明 \`source:"oidc-token"\`,提交安装前会展示插件名、id 与精确请求
域名,并要求用户手输相同 id;取消不会安装。个人与企业身份下的明确 Forge 安装都会标记为
作者本地自测并受组织默认插件自动接管保护;但 Connection JWT 资格仍只来自当前企业身份、
组织前缀与 OIDC 窄确认,个人身份下的 Forge 安装绝不会仅凭自测标记取得 Broker 或 Connection 权限,
普通手动导入也不取得这项资格。
- 本地安装另有一条点名例外,见 §4.7:仅 \`ghostId\` 精确等于 \`mivo-canvas\` 且精确 oidc-token host 仅为 \`mivo-canvas.dsworks.cn\` 的组织成员本地安装可解析 audience;
+ 本地安装另有一条临时例外,只对 root 实例生效,见 §4.7:仅 \`ghostId\` 精确等于 \`mivo-canvas\`、namespace 为 null 或尚未确认,且精确 oidc-token host 仅为 \`mivo-canvas.dsworks.cn\` 的组织成员本地安装可解析 audience;
4. 安装后再让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。
企业组织成员需要发布时,调用 \`ghost_forge_pack({ dir: '<绝对路径>', intent: 'publish' })\`。
@@ -4855,7 +4889,9 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件
- agent 详单格式错(background / errand / schedule 存在但不是 true;基础点击触发请写 \`agent: {}\`)
- node 详单格式错(entry 不是包内 CommonJS .js/.cjs、protocol 不在 json-rpc-stdio / mcp-stdio、
resident 又写 idleTimeoutSeconds);未知 command/args/shell/env 只保留,不传给进程启动器
-- id 用了 \`cindy-\` / \`filo-\` / \`xd-\` 前缀(官方保留,正式版用户通道拒装;给自己的意识换个前缀)
+- id 用了 \`cindy-\` 前缀(平台保留,正式版用户通道拒装)。\`filo-\` / \`xd-\` 只是普通名称,不授予官方资格
+- ghost.json 声明了 namespace(包括 null)。namespace 由可信交付及 Host 安装事实决定,作者不能自报
+- 企业发布遵循当前服务端准入。S1 或 S2 尚未开启时仍保留旧认领和前缀命名流程,不能把收到 namespace 当作自由命名已开放
- network 详单格式错(hosts 缺失/裸 TLD/IP/带端口/通配不在最左、secret 缺 inject、
inject.format 没有 {value} 占位、inject.header 用了 Host/Cookie 等协议关键头、
inject.hosts 不是 hosts 声明条目的子集、
diff --git a/apps/desktop/src/main/cindy-brain/fsSlot.ts b/apps/desktop/src/main/cindy-brain/fsSlot.ts
index 01521732e3..3dfe3e78c7 100644
--- a/apps/desktop/src/main/cindy-brain/fsSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/fsSlot.ts
@@ -67,6 +67,7 @@ import {
type InstalledGhost,
} from '../../shared/ghost.js';
import type { GhostGrantConfirmDecision, GhostGrantConfirmPayload } from './ghostGrantConfirmBridge.js';
+import { installedGhostMutationTargetToken } from '../../shared/pluginIdentity.js';
/** 会话快照:fs 槽 workdir 档守门要看的全部字段。 */
export interface FsSessionSnapshot {
@@ -286,6 +287,7 @@ export class GhostFsSlot {
* 纯内存、进程生命周期内,不落盘)。
*/
private readonly workdirGrants = new Set<string>();
+ private readonly inFlightRequests = new Map<string, number>();
private sessionSnapshotResolver: FsSlotDeps['getSessionSnapshot'];
@@ -298,8 +300,13 @@ export class GhostFsSlot {
this.sessionSnapshotResolver = resolve;
}
+ hasInFlightRequests(ghostId: string): boolean {
+ return this.inFlightRequests.has(ghostId);
+ }
+
/** 处理一条 fs-request(ghost-pipe:send 的 invoke 返回值即本结果)。 */
async handleFsRequest(ghostId: string, payload: unknown): Promise<GhostPipeFsResult> {
+ this.inFlightRequests.set(ghostId, (this.inFlightRequests.get(ghostId) ?? 0) + 1);
try {
return await this.dispatch(ghostId, payload);
} catch (err) {
@@ -309,6 +316,10 @@ export class GhostFsSlot {
error: err instanceof Error ? err.message : String(err),
});
return fail('写文件失败(主机内部错误)');
+ } finally {
+ const remaining = this.inFlightRequests.get(ghostId)! - 1;
+ if (remaining > 0) this.inFlightRequests.set(ghostId, remaining);
+ else this.inFlightRequests.delete(ghostId);
}
}
@@ -641,7 +652,9 @@ export class GhostFsSlot {
if (verdict === 'confirm') {
const parentDir = path.dirname(target);
const memoryKey = `${info.sessionId}${ghostId}${foldCase(parentDir)}`;
- if (automaticReview || !this.workdirGrants.has(memoryKey)) {
+ const targetToken = installedGhostMutationTargetToken(ghost, '');
+ const bindingKey = memoryKey + '\u0000' + targetToken;
+ if (automaticReview || targetToken === null || !this.workdirGrants.has(bindingKey)) {
const decision = await this.deps.requestWriteConfirm(info.sessionId, {
ghostId,
ghostName: ghost.manifest.name || ghostId,
@@ -655,7 +668,7 @@ export class GhostFsSlot {
if (decision.reason === 'cancelled') return fail('用户拒绝了本次工作目录写入');
return fail('确认通道未就绪或会话已关闭,本次工作目录写入未执行');
}
- if (!automaticReview) confirmedMemoryKey = memoryKey;
+ if (!automaticReview && targetToken !== null) confirmedMemoryKey = bindingKey;
}
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts
index 9a39d77637..650965c9f4 100644
--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts
@@ -18,10 +18,17 @@
*/
import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';
import type { OrganizationPrefixLookup } from '../plugin-market/organizationPrefixStore.js';
+import { isTrustedPublicCindyResource } from './ghostFirstPartyPrivilege.js';
import type {
GhostFirstPartyFacts,
GhostFirstPartyMarketRecord,
+ GhostFirstPartyTrustedSource,
} from './ghostFirstPartyPrivilege.js';
+import {
+ parsePluginInstallRelId,
+ parsePluginStoragePart,
+ pluginInstanceInstallRelId,
+} from '../../shared/pluginIdentity.js';
export type GhostFirstPartyFactsPurpose = 'install' | 'runtime';
@@ -38,6 +45,7 @@ export type GhostFirstPartyFactsUnavailableReason =
export interface GhostFirstPartyFactsIdentity {
membershipKind: 'personal' | 'org';
orgId: string | null;
+ orgSlug?: string | null;
}
export type GhostFirstPartyFactsLoad =
@@ -66,6 +74,20 @@ export interface LoadGhostFirstPartyFactsLoaderOptions {
lookupOrganizationPrefix(orgId: string): OrganizationPrefixLookup;
/** 显式 ghost_forge_install 返回 agent-forge;其它入口返回 manual。 */
readInstallOrigin(ghostId: string): 'manual' | 'agent-forge';
+ /**
+ * Trusted receipt namespace. `undefined` means no delivery field; explicit
+ * `null` is root. Do not invent the current org slug here.
+ */
+ readInstallNamespace?(ghostId: string): string | null | undefined;
+ /**
+ * unknown: no registry row, or the registry is blocked. Only then may the
+ * loader parse a namespace out of the install path. unconfirmed must not.
+ */
+ readNamespaceState?(ghostId: string): 'confirmed' | 'pending' | 'unconfirmed' | 'unknown';
+ isPendingLegacyForge?(ghostId: string): boolean;
+ isPendingLegacyNamespace?(installRelId: string): boolean;
+ readTrustedSource?(installRelId: string): GhostFirstPartyTrustedSource | null;
+ readLegacyFirstPartyEligible?(installRelId: string): boolean;
}
function actionFor(purpose: GhostFirstPartyFactsPurpose): GhostFirstPartyFactsUnavailableAction {
@@ -106,6 +128,14 @@ export function bindPendingMarketRecordToInspectedPackage(
export type GhostFirstPartyFactsOverrides = {
installOrigin?: 'manual' | 'agent-forge';
marketRecord?: GhostFirstPartyMarketRecord | null;
+ /**
+ * Install-time delivery namespace. Runtime keeps parsing the storage part /
+ * install rel id; callers must not invent the current org slug at runtime.
+ * `undefined` means "parse from ghostId"; explicit `null` is root.
+ */
+ namespace?: string | null;
+ trustedSource?: GhostFirstPartyTrustedSource | null;
+ legacyFirstPartyEligible?: boolean;
};
export function loadGhostFirstPartyFactsLoader(
@@ -113,6 +143,27 @@ export function loadGhostFirstPartyFactsLoader(
): GhostFirstPartyFactsLoader {
return {
load(ghostId, purpose, identity, overrides) {
+ const parsed =
+ parsePluginStoragePart(ghostId) ?? parsePluginInstallRelId(ghostId);
+ const logicalGhostId = parsed?.ghostId ?? ghostId;
+ // Receipts / origin live under install rel id (`helper` or `_ns/acme/helper`).
+ // Runtime oauth may pass a storage part (`_ns__acme__helper`).
+ const installRelId = pluginInstanceInstallRelId(ghostId) ?? ghostId;
+ const recordedNamespace =
+ overrides?.namespace !== undefined
+ ? overrides.namespace
+ : options.readInstallNamespace?.(installRelId);
+ const namespaceState = options.readNamespaceState?.(installRelId);
+ const namespace =
+ recordedNamespace !== undefined
+ ? recordedNamespace
+ : namespaceState === 'unconfirmed'
+ ? null
+ : (parsed?.namespace ?? null);
+ const legacyPendingForge = purpose === 'runtime' && recordedNamespace === undefined &&
+ namespace === null && options.isPendingLegacyForge?.(installRelId) === true;
+ const legacyPendingNamespace = purpose === 'runtime' && recordedNamespace === undefined &&
+ namespace === null && options.isPendingLegacyNamespace?.(installRelId) === true;
const unavailable = (
reason: GhostFirstPartyFactsUnavailableReason,
): GhostFirstPartyFactsLoad => ({
@@ -122,6 +173,30 @@ export function loadGhostFirstPartyFactsLoader(
action: actionFor(purpose),
});
+ let trustedSource: GhostFirstPartyTrustedSource | null = null;
+ let legacyFirstPartyEligible = false;
+ let approvedPackageSha256: string | null = null;
+ try {
+ trustedSource = overrides?.trustedSource !== undefined
+ ? overrides.trustedSource
+ : purpose === 'runtime' ? options.readTrustedSource?.(installRelId) ?? null : null;
+ legacyFirstPartyEligible = overrides?.legacyFirstPartyEligible !== undefined
+ ? overrides.legacyFirstPartyEligible === true
+ : purpose === 'runtime' && options.readLegacyFirstPartyEligible?.(installRelId) === true;
+ approvedPackageSha256 = overrides?.marketRecord !== undefined
+ ? overrides.marketRecord?.approvedPackageSha256 ?? null
+ : options.readApprovedPackageSha256(installRelId);
+ } catch {
+ trustedSource = null;
+ legacyFirstPartyEligible = false;
+ approvedPackageSha256 = null;
+ }
+ const privilegeEvidence = {
+ ...(legacyPendingNamespace ? { legacyPendingNamespace: true } : {}),
+ ...(trustedSource ? { trustedSource, approvedPackageSha256 } : {}),
+ ...(legacyFirstPartyEligible ? { legacyFirstPartyEligible: true } : {}),
+ };
+
let builtin: boolean;
try {
builtin = options.readInstalledBuiltin(ghostId);
@@ -134,7 +209,7 @@ export function loadGhostFirstPartyFactsLoader(
installOrigin = overrides.installOrigin;
} else {
try {
- installOrigin = options.readInstallOrigin(ghostId);
+ installOrigin = options.readInstallOrigin(installRelId);
} catch {
installOrigin = 'manual';
}
@@ -147,12 +222,12 @@ export function loadGhostFirstPartyFactsLoader(
try {
const installation = options.readMarketInstallation(ghostId);
marketRecord = installation
- ? toMarketRecord(installation, options.readApprovedPackageSha256(ghostId))
+ ? toMarketRecord(installation, approvedPackageSha256)
: null;
} catch {
// Builtin official plugins and explicit Forge self-tests do not depend
// on the ledger. A corrupt cache must not take either qualification away.
- if (!builtin && installOrigin !== 'agent-forge') {
+ if (!builtin && !trustedSource && !legacyFirstPartyEligible && installOrigin !== 'agent-forge') {
return unavailable('market-installation-read-failed');
}
marketRecord = null;
@@ -163,11 +238,14 @@ export function loadGhostFirstPartyFactsLoader(
return {
kind: 'ready',
facts: {
- ghostId,
+ ghostId: logicalGhostId,
+ namespace,
builtin,
marketRecord,
currentOrganization: null,
installOrigin,
+ ...(legacyPendingForge ? { legacyPendingForge: true } : {}),
+ ...privilegeEvidence,
},
};
}
@@ -187,16 +265,35 @@ export function loadGhostFirstPartyFactsLoader(
* 哪天有人让优先级 1 开始读这两个字段,那条测试会红,
* 提醒他这里的填充值会变成静默误报。
*/
- const builtinOnlyFacts = (): GhostFirstPartyFactsLoad => ({
+ const builtinOnlyFacts = (): Extract<GhostFirstPartyFactsLoad, { kind: 'ready' }> => ({
kind: 'ready',
- facts: { ghostId, builtin, marketRecord, currentOrganization: null, installOrigin },
+ facts: { ghostId: logicalGhostId, namespace, builtin, marketRecord, currentOrganization: null, installOrigin, ...(legacyPendingForge ? { legacyPendingForge: true } : {}), ...privilegeEvidence },
});
+ if (installOrigin === 'manual' && isTrustedPublicCindyResource(builtinOnlyFacts().facts)) {
+ return builtinOnlyFacts();
+ }
+
+ if (identity.orgSlug && (namespace === identity.orgSlug ||
+ (legacyPendingNamespace && installOrigin !== 'agent-forge')) ||
+ (namespace !== null && identity.orgSlug == null && installOrigin !== 'agent-forge' &&
+ marketRecord?.source === 'market' && marketRecord.scope === 'organization' &&
+ marketRecord.organizationId === identity.orgId)) {
+ return {
+ kind: 'ready',
+ facts: {
+ ghostId: logicalGhostId, namespace, builtin, marketRecord, installOrigin,
+ currentOrganization: { organizationId: identity.orgId, orgSlug: identity.orgSlug },
+ ...privilegeEvidence,
+ },
+ };
+ }
+
let lookup: OrganizationPrefixLookup;
try {
lookup = options.lookupOrganizationPrefix(identity.orgId);
} catch {
- if (builtin) return builtinOnlyFacts();
+ if (builtin || trustedSource || legacyFirstPartyEligible) return builtinOnlyFacts();
return unavailable('organization-prefix-unavailable');
}
@@ -204,21 +301,25 @@ export function loadGhostFirstPartyFactsLoader(
return {
kind: 'ready',
facts: {
- ghostId,
+ ghostId: logicalGhostId,
+ namespace,
builtin,
marketRecord,
currentOrganization: {
organizationId: identity.orgId,
pluginPrefix: lookup.pluginPrefix,
+ orgSlug: identity.orgSlug ?? null,
},
installOrigin,
+ ...(legacyPendingForge ? { legacyPendingForge: true } : {}),
+ ...privilegeEvidence,
},
};
}
// Prefix is required for non-builtin evaluation. Builtin still concludes
// from `facts.builtin` and must not wait on a market-list cache fill.
- if (builtin) return builtinOnlyFacts();
+ if (builtin || trustedSource || legacyFirstPartyEligible) return builtinOnlyFacts();
return unavailable(
lookup.kind === 'absent'
diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts
index aa84f4a718..f7f7d434e5 100644
--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts
@@ -5,14 +5,15 @@
* conclusion. Callers decide whether to refuse install or only withhold
* privileges; this module does not refuse loading.
*
- * Call sites that previously used only `isBrokerEligibleGhostId` now ask this
- * resolver **after** the static official-prefix hit (`cindy-` / `filo-` / `xd-`).
- * Official-prefix plugins keep today's grant. Everything else is decided here.
+ * Call sites must not treat `cindy-` / `filo-` / `xd-` names as privileges.
+ * Official plugins still qualify through builtin seed or trusted public market
+ * facts; enterprise broker qualifies through current-organization market facts.
*
* Input priority: first evaluable of
- * 1. builtin seed → static official table
+ * 1. approved builtin resource, or a captured legacy qualification
* 2. explicit agent-forge install + current organization prefix
- * 3. plugin-market ledger (source + scope + organizationId + Release sha256)
+ * 3. reserved Cindy public resources or current organization server packages
+ * in the plugin-market ledger (source + scope + organizationId + Release sha256)
* paired with the approved receipt packageSha256
* 4. neither → fail-closed, no privilege
*
@@ -21,19 +22,19 @@
* (`plugin-market/service.ts`); that is not a trust statement. Server-market
* public is only trusted when `source === 'market'`.
*
- * A matching official prefix is never a security proof by itself. The
- * static table is only a criterion on the builtin branch and on trusted
- * server-market public installs.
+ * A matching official prefix is never a security proof by itself. Cindy public
+ * resources require exact approved server-market package evidence; historical
+ * XD/Filo names require a captured qualification from a real old public install.
*
* `facts.builtin` is id-based, not byte-based: it means "this id is on the
* bundled seed roster" (`listBuiltinSeedIds` / directory name), not "these
* bytes came from the bundled seed". Byte-level guarantees live in
- * provisioning content matching and `approveTrustedBundledInstall`. That is
- * the same strength as today's `isOfficialGhostId(id)`.
+ * provisioning content matching and `approveTrustedBundledInstall`. A trusted
+ * source resource must additionally match the approved identity and content hash.
*/
-import { PLUGIN_PREFIX_PATTERN, type PluginScope } from '@cindy/plugin-protocol';
+import type { PluginScope } from '@cindy/plugin-protocol';
-import { isBrokerEligibleGhostId, isOfficialGhostId } from '../../shared/ghost.js';
+import { GHOST_OFFICIAL_ID_PREFIX, isOfficialGhostId } from '../../shared/ghost.js';
const PACKAGE_SHA256_RE = /^[a-f0-9]{64}$/;
@@ -48,7 +49,8 @@ export type GhostFirstPartyBasis =
| 'builtin-official'
| 'market-public'
| 'market-organization-current'
- | 'forge-current-org-prefix'
+ | 'forge-current-org'
+ | 'legacy-existing-install'
| 'denied-alias'
| 'denied-foreign-org'
| 'denied-unknown-origin';
@@ -72,26 +74,73 @@ export interface GhostFirstPartyMarketRecord {
export interface GhostFirstPartyCurrentOrganization {
organizationId: string;
- pluginPrefix: string | null;
+ pluginPrefix?: string | null;
+ /** Permanent org slug; required to bind Forge self-test to the install namespace. */
+ orgSlug?: string | null;
}
export interface GhostFirstPartyFacts {
ghostId: string;
+ /** Install namespace. null is root; a string is the bound orgSlug. */
+ namespace: string | null;
/** True when the id is on the bundled seed roster (`InstalledGhost.builtin`). */
builtin: boolean;
marketRecord: GhostFirstPartyMarketRecord | null;
currentOrganization: GhostFirstPartyCurrentOrganization | null;
/** 仅显式 ghost_forge_install 写入 agent-forge;其它入口均为 manual。 */
installOrigin: 'manual' | 'agent-forge';
+ legacyPendingForge?: boolean;
+ legacyPendingNamespace?: boolean;
+ trustedSource?: GhostFirstPartyTrustedSource | null;
+ approvedPackageSha256?: string | null;
+ legacyFirstPartyEligible?: boolean;
}
-function matchesCurrentOrgPrefix(
- ghostId: string,
- currentOrganization: GhostFirstPartyCurrentOrganization | null,
-): boolean {
- const prefix = currentOrganization?.pluginPrefix;
- if (!prefix || !PLUGIN_PREFIX_PATTERN.test(prefix)) return false;
- return ghostId.startsWith(`${prefix}-`);
+export interface GhostFirstPartyTrustedSource {
+ kind: 'builtin-official';
+ ghostId: string;
+ namespace: string | null;
+ packageSha256: string;
+}
+
+export function hasTrustedFirstPartySource(facts: GhostFirstPartyFacts): boolean {
+ const source = facts.trustedSource;
+ return source != null && source.ghostId === facts.ghostId &&
+ source.namespace === facts.namespace &&
+ PACKAGE_SHA256_RE.test(source.packageSha256) &&
+ source.packageSha256 === facts.approvedPackageSha256;
+}
+
+export function isTrustedPublicCindyResource(facts: GhostFirstPartyFacts): boolean {
+ const record = facts.marketRecord;
+ return facts.namespace === null && facts.ghostId.startsWith(GHOST_OFFICIAL_ID_PREFIX) &&
+ record !== null && record.installed && record.source === 'market' &&
+ record.scope === 'public' && record.organizationId === null &&
+ record.approvedPackageSha256 !== null && PACKAGE_SHA256_RE.test(record.sha256) &&
+ record.sha256 === record.approvedPackageSha256;
+}
+
+export function captureLegacyFirstPartyEligibility(input: {
+ legacyExistingInstall: boolean;
+ ghostId: string;
+ namespace: string | null;
+ approved: boolean;
+ approvedPackageSha256: string | null;
+ marketRecord: (GhostFirstPartyMarketRecord & { ghostId: string; namespace?: string | null }) | null;
+ approvedOfficialTrust?: boolean;
+}): boolean {
+ const record = input.marketRecord;
+ if (!input.legacyExistingInstall || !input.approved || input.namespace !== null ||
+ !isOfficialGhostId(input.ghostId) || input.approvedPackageSha256 === null ||
+ !PACKAGE_SHA256_RE.test(input.approvedPackageSha256)) return false;
+ if (input.approvedOfficialTrust === true) return true;
+ return record !== null && record.ghostId === input.ghostId &&
+ record.namespace == null &&
+ record.installed && record.source === 'market' &&
+ record.scope === 'public' && record.organizationId === null &&
+ record.approvedPackageSha256 !== null && PACKAGE_SHA256_RE.test(record.sha256) &&
+ record.approvedPackageSha256 === input.approvedPackageSha256 &&
+ record.sha256 === record.approvedPackageSha256;
}
function isCurrentOrganizationRecord(
@@ -125,6 +174,23 @@ export function marketInstallationMatchesApprovedPackage(
);
}
+export function isTrustedMivoSecretAlias(facts: GhostFirstPartyFacts, pendingLegacy: boolean): boolean {
+ if (facts.ghostId !== 'xd-mivo') return false;
+ if (facts.builtin && facts.trustedSource?.kind === 'builtin-official' &&
+ hasTrustedFirstPartySource(facts)) return true;
+ const record = facts.marketRecord;
+ if (!record || record.source !== 'market' || record.scope !== 'organization' ||
+ !record.installed || !record.organizationId) return false;
+ // Org id is an install fact. The session slug is not: a relabel must not move the key.
+ if (facts.currentOrganization &&
+ record.organizationId !== facts.currentOrganization.organizationId) return false;
+ if (!(facts.namespace === 'xd' || (facts.namespace === null && pendingLegacy))) return false;
+ return record.approvedPackageSha256 !== null &&
+ PACKAGE_SHA256_RE.test(record.sha256) &&
+ PACKAGE_SHA256_RE.test(record.approvedPackageSha256) &&
+ record.sha256 === record.approvedPackageSha256;
+}
+
function allow(basis: GhostFirstPartyBasis, hostPrimitiveEligible: boolean): GhostFirstPartyPrivilege {
return { brokerEligible: true, hostPrimitiveEligible, basis };
}
@@ -133,40 +199,69 @@ function deny(basis: Extract<GhostFirstPartyBasis, `denied-${string}`>): GhostFi
return { brokerEligible: false, hostPrimitiveEligible: false, basis };
}
+export function matchesPendingLegacyForge(
+ ghostId: string,
+ namespace: string | null,
+ pending: boolean,
+ pluginPrefix: string | null,
+): boolean {
+ return pending && namespace === null && !!pluginPrefix && ghostId.startsWith(pluginPrefix + '-');
+}
+
/**
* Pure first-party privilege conclusion from already-collected facts.
* Does not read disk, ledger, or Electron.
*/
export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): GhostFirstPartyPrivilege {
- if (facts.builtin) {
- return isOfficialGhostId(facts.ghostId)
- ? allow('builtin-official', true)
- : deny('denied-unknown-origin');
+ if (facts.builtin && facts.trustedSource?.kind === 'builtin-official' &&
+ hasTrustedFirstPartySource(facts)) {
+ return allow('builtin-official', true);
+ }
+
+ if (facts.installOrigin === 'manual' && isTrustedPublicCindyResource(facts)) {
+ return allow('market-public', true);
}
if ((FIRST_PARTY_ALIAS_GHOST_IDS as readonly string[]).includes(facts.ghostId)) {
return deny('denied-alias');
}
- // 企业作者的显式 Forge 自测资格来自本次安装来源与当前组织前缀,和市场账本
+ if (facts.namespace === null && facts.installOrigin === 'manual' &&
+ facts.legacyFirstPartyEligible === true && isOfficialGhostId(facts.ghostId) &&
+ (facts.marketRecord === null || (facts.marketRecord.installed &&
+ facts.marketRecord.source === 'market' && facts.marketRecord.scope === 'public' &&
+ facts.marketRecord.organizationId === null &&
+ PACKAGE_SHA256_RE.test(facts.marketRecord.sha256) &&
+ facts.marketRecord.sha256 === facts.marketRecord.approvedPackageSha256))) {
+ return allow('legacy-existing-install', true);
+ }
+
+ // 企业作者的显式 Forge 自测资格来自本次安装来源与当前组织身份,和市场账本
// 是否已有同 id、是否仍标记 installed 无关。它只开放 Broker / oidc-token,
// 宿主原语仍保持拒绝。
- if (
- facts.installOrigin === 'agent-forge' &&
- matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)
- ) {
- return allow('forge-current-org-prefix', false);
+ if (facts.installOrigin === 'agent-forge') {
+ const orgSlug = facts.currentOrganization?.orgSlug;
+ const legacyMatchesCurrentOrg = matchesPendingLegacyForge(
+ facts.ghostId,
+ facts.namespace,
+ facts.legacyPendingForge === true,
+ facts.currentOrganization?.pluginPrefix ?? null,
+ );
+ if (!orgSlug || (facts.namespace !== orgSlug && !legacyMatchesCurrentOrg)) {
+ return deny(facts.currentOrganization ? 'denied-foreign-org' : 'denied-unknown-origin');
+ }
+ return allow('forge-current-org', false);
}
const record = facts.marketRecord;
if (record !== null) {
if (!record.installed) {
// Uninstalled ledger rows stay denied. Explicit Forge self-test is
- // decided above from origin + org prefix, before this market branch.
+ // decided above from origin + current organization, before this market branch.
return deny('denied-unknown-origin');
}
if (record.scope === 'public' && record.source === 'market') {
- return isOfficialGhostId(facts.ghostId)
+ return isTrustedPublicCindyResource(facts)
? allow('market-public', true)
: deny('denied-unknown-origin');
}
@@ -179,16 +274,27 @@ export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): Gh
// that organization's server market". `git-market` / `local-market` rows
// carry a placeholder scope, which is likewise not a trust statement.
if (record.source !== 'market') return deny('denied-unknown-origin');
- if (!isCurrentOrganizationRecord(record, facts.currentOrganization)) {
+ const organization = facts.currentOrganization;
+ // Same gate as OIDC: a known namespace must be the current orgSlug.
+ // A missing namespace is only the upgrade census, not an implicit root.
+ if (facts.namespace === null) {
+ if (facts.legacyPendingNamespace !== true) return deny('denied-unknown-origin');
+ } else if (organization?.orgSlug != null && facts.namespace !== organization.orgSlug) {
+ // Old tokens omit orgSlug. Reject only an explicit different slug.
return deny('denied-foreign-org');
}
- if (!marketInstallationMatchesApprovedPackage(record, facts.currentOrganization)) {
- return deny('denied-unknown-origin');
+ if (!isCurrentOrganizationRecord(record, organization)) {
+ return deny('denied-foreign-org');
}
- if (!matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)) {
+ if (!marketInstallationMatchesApprovedPackage(record, organization)) {
return deny('denied-unknown-origin');
}
- return allow('market-organization-current', false);
+ const legacyXd = facts.namespace === null && facts.legacyPendingNamespace === true &&
+ (organization?.orgSlug === 'xd' ||
+ (organization?.orgSlug == null && organization?.pluginPrefix === 'xd'));
+ const namespacedXd = facts.namespace === 'xd' &&
+ (organization?.orgSlug == null || organization.orgSlug === 'xd');
+ return allow('market-organization-current', namespacedXd || legacyXd);
}
return deny('denied-unknown-origin');
}
@@ -197,15 +303,22 @@ export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): Gh
}
/**
- * Incremental broker gate: official prefix (`cindy-` / `filo-` / `xd-`) keeps
- * today's grant without consulting facts. Everything else asks the resolver.
- * Unavailable facts are fail-closed (no broker).
+ * Broker gate from collected facts. Prefixes are not a grant.
+ * Unavailable facts are fail-closed.
*/
export function authorizeGhostTokenBroker(
- ghostId: string,
+ _ghostId: string,
load: { kind: 'ready'; facts: GhostFirstPartyFacts } | { kind: string },
): boolean {
- if (isBrokerEligibleGhostId(ghostId)) return true;
if (load.kind !== 'ready' || !('facts' in load)) return false;
return resolveGhostFirstPartyPrivilege(load.facts).brokerEligible;
}
+
+/** Port reclaim / identity avatar download. Prefixes are not a grant. */
+export function authorizeGhostHostPrimitive(
+ _ghostId: string,
+ load: { kind: 'ready'; facts: GhostFirstPartyFacts } | { kind: string },
+): boolean {
+ if (load.kind !== 'ready' || !('facts' in load)) return false;
+ return resolveGhostFirstPartyPrivilege(load.facts).hostPrimitiveEligible;
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallLock.ts b/apps/desktop/src/main/cindy-brain/ghostInstallLock.ts
index 360b9ba8f5..fa1a3420e3 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallLock.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallLock.ts
@@ -21,6 +21,8 @@
*/
import { AsyncLocalStorage } from 'node:async_hooks';
+import { createPluginLogicalIdentity, hasDeliveryNamespace } from '../../shared/pluginIdentity.js';
+
/** 当前异步上下文已持有的 ghostId 集合(重入判定依据)。 */
const heldIds = new AsyncLocalStorage<ReadonlySet<string>>();
@@ -64,3 +66,13 @@ export async function withGhostInstallLock<T>(
export function resetGhostInstallLocksForTest(): void {
locks.clear();
}
+
+export function withPluginDeliveryInstallLock<T>(
+ plugin: { ghostId: string; namespace?: string | null },
+ fn: () => Promise<T>,
+): Promise<T> {
+ if (hasDeliveryNamespace(plugin)) {
+ createPluginLogicalIdentity(plugin.namespace ?? null, plugin.ghostId);
+ }
+ return withGhostInstallLock(plugin.ghostId, fn);
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 9c1700dc5a..46fef52f75 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -2,7 +2,19 @@ import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
+import {
+ createPluginLogicalIdentity,
+ hasDeliveryNamespace,
+ isValidPluginInstallRelId,
+ parsePluginInstallRelId,
+ parsePluginStoragePart,
+ PLUGIN_NS_INSTALL_ROOT,
+ pluginInstallRelId,
+ pluginInstallStoragePart,
+ pluginStoragePart,
+} from '../../shared/pluginIdentity.js';
import {
GHOST_LOCALE_MAX_BYTES,
GHOST_SKILL_MD_MAX_BYTES,
@@ -38,6 +50,36 @@ 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;
+
+export function assertManagedPluginParentSync(
+ root: string,
+ relPath: string,
+ createMissing = false,
+): boolean {
+ const segments = relPath.split('/');
+ if (segments.some((segment) => !segment || segment === '.' || segment === '..' ||
+ segment.includes('\\') || segment.includes(path.sep))) {
+ throw new Error('invalid managed plugin path');
+ }
+ let parent = root;
+ for (const segment of segments.slice(0, -1)) {
+ parent = path.join(parent, segment);
+ try {
+ const kind = classifyGhostDirEntrySync(parent);
+ if (kind !== 'directory') throw new Error('managed plugin parent is not a real directory');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ if (!createMissing) return false;
+ try {
+ fs.mkdirSync(parent);
+ } catch (mkdirError) {
+ if ((mkdirError as NodeJS.ErrnoException).code !== 'EEXIST' ||
+ classifyGhostDirEntrySync(parent) !== 'directory') throw mkdirError;
+ }
+ }
+ }
+ return true;
+}
/**
* 受管 icon 快照的完整形态:声明的图片 mime + 严格 base64 载荷。载荷字符集也要
* 校验 —— 只认前缀会让被改写的 receipt 把任意字符串塞进 renderer 的 img src。
@@ -56,6 +98,8 @@ export interface GhostInstallReceipt {
taskCapabilityApproved?: true;
schemaVersion: typeof RECEIPT_SCHEMA_VERSION;
id: string;
+ /** Missing is a pre-namespace receipt. null is root; a string is an organization. */
+ namespace?: string | null;
revision: string;
manifest: GhostManifest;
localeResources: Record<string, GhostManifestLocaleResource>;
@@ -72,6 +116,7 @@ export interface GhostInstallReceipt {
* receipt 中的同名值继续有效,避免升级后丢失既有企业作者自测资格。
*/
installOrigin?: string;
+ legacyFirstPartyEligible?: boolean;
/**
* 按 skill item 目录钉住的固化字节指纹(`item.dir` → sha256)。声明了 skill 能力
* 时逐项必填,没声明时是空对象。
@@ -169,6 +214,7 @@ export type GhostPendingMutation =
phase?: 'prepared' | 'backed-up' | 'published';
/** Hash of the previously approved bytes, when an approval existed. */
oldPackageSha256?: string;
+ sourceStateArchiveId?: string;
}
// uninstall 不带 packageSha256:它的提交信号不是"receipt 写到某版本",而是"receipt +
// 内容目录都已移除"。恢复见到它就把两者删干净(顺序无关,幂等)。
@@ -180,6 +226,15 @@ export type GhostPendingMutationReadResult =
| { state: 'invalid'; reason: string }
| { state: 'unreadable'; reason: string };
+export function isValidGhostSourceStateArchiveId(value: unknown): value is string {
+ if (typeof value !== 'string') return false;
+ if (/^arch_[a-f0-9]{32}$/.test(value)) return true;
+ const identity = parsePluginStoragePart(value);
+ return identity !== null && pluginStoragePart(identity) === value &&
+ identity.namespace !== null && identity.namespace.startsWith('cindy-archive-') &&
+ isRevision(identity.namespace.slice('cindy-archive-'.length));
+}
+
export type GhostPendingMutationListResult =
{ state: 'ok'; ids: string[]; blocked: boolean } | { state: 'unreadable'; reason: string };
@@ -196,6 +251,24 @@ export class GhostInstallReceiptStore {
return path.resolve(this.getRootDir());
}
+ private assertPathParentSync(absPath: string, createMissing = false): boolean {
+ const root = this.rootDir();
+ return assertManagedPluginParentSync(
+ root,
+ path.relative(root, absPath).split(path.sep).join('/'),
+ createMissing,
+ );
+ }
+
+ private receiptRelId(receipt: { id: string; namespace?: string | null }): string {
+ return pluginInstallRelId(
+ createPluginLogicalIdentity(
+ hasDeliveryNamespace(receipt) ? receipt.namespace : null,
+ receipt.id,
+ ),
+ );
+ }
+
private realRootDirSync(): string {
return fs.realpathSync(this.rootDir());
}
@@ -207,11 +280,41 @@ export class GhostInstallReceiptStore {
return { state: 'invalid', reason: result.reason };
}
+ captureLegacyFirstPartyEligibilitySync(id: string, expectedRevision: string): void {
+ const identity = parsePluginInstallRelId(id);
+ const read = this.readForRecovery(id);
+ if (!identity || identity.namespace !== null || read.state !== 'approved' ||
+ read.receipt.revision !== expectedRevision || hasDeliveryNamespace(read.receipt)) {
+ throw new Error('legacy qualification requires the exact censused root approval');
+ }
+ const target = this.receiptPath(id);
+ this.assertPathParentSync(target);
+ const root = this.realRootDirSync();
+ const temp = path.join(root, '.legacy-qualification-' + crypto.randomBytes(12).toString('hex') + '.tmp');
+ const receipt = {
+ ...read.receipt, legacyFirstPartyEligible: true,
+ manifest: ghostManifestToAuthorFormat(read.receipt.manifest),
+ };
+ try {
+ fs.writeFileSync(temp, JSON.stringify(receipt, null, 2) + '\n', { encoding: 'utf8', flag: 'wx', mode: 0o600 });
+ fs.renameSync(temp, target);
+ } finally {
+ try {
+ fs.rmSync(temp, { force: true });
+ } catch (error) {
+ void error;
+ }
+ }
+ }
+
/** 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 {
+ if (!this.assertPathParentSync(receiptPath)) {
+ return { state: 'missing' };
+ }
bytes = readBoundedFileNoFollowSync(receiptPath, MAX_RECEIPT_BYTES, {
containWithin: this.realRootDirSync(),
});
@@ -234,7 +337,8 @@ export class GhostInstallReceiptStore {
} catch (error) {
return { state: 'invalid', reason: error instanceof Error ? error.message : String(error) };
}
- const validated = validateReceipt(parsed, id);
+ const expectedGhostId = parsePluginInstallRelId(id)?.ghostId ?? id;
+ const validated = validateReceipt(parsed, expectedGhostId);
return validated.ok
? { state: 'approved', receipt: validated.receipt }
: { state: 'invalid', reason: validated.reason };
@@ -250,16 +354,22 @@ export class GhostInstallReceiptStore {
*/
async write(
receipt: GhostInstallReceipt,
- options: { skillSourceDir?: string; requireSkillSnapshot?: boolean; assertCurrent?: () => void } = {},
+ options: { skillSourceDir?: string; requireSkillSnapshot?: boolean; relId?: string; assertCurrent?: () => void } = {},
): 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 });
+ const relId = options.relId ?? this.receiptRelId(receipt);
+ if (parsePluginInstallRelId(relId)?.ghostId !== receipt.id) {
+ throw new Error('ghost receipt relId does not match receipt id');
+ }
+ const receiptFile = this.receiptPath(relId);
+ fs.mkdirSync(root, { recursive: true });
+ this.assertPathParentSync(receiptFile, true);
try {
- await this.ensureSkillSnapshot(receipt, options.skillSourceDir);
+ await this.ensureSkillSnapshot(receipt, relId, options.skillSourceDir);
} catch (error) {
if (options.requireSkillSnapshot !== false) throw error;
}
@@ -279,12 +389,12 @@ export class GhostInstallReceiptStore {
// writer may have observed it and committed the receipt; pathname-based
// rollback could remove that install's only durable migration guard.
if (!this.hasMigrationLedger()) {
- await this.ensureMigrationMarker(receipt.id);
+ await this.ensureMigrationMarker(relId);
}
- const target = this.receiptPath(receipt.id);
+ const target = receiptFile;
const temp = path.join(
root,
- `.${receipt.id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
+ `.${this.receiptRelId(receipt).replaceAll('/', '.')}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
);
const persistedReceipt = {
...validated.receipt,
@@ -313,6 +423,7 @@ export class GhostInstallReceiptStore {
async remove(id: string): Promise<void> {
const receiptPath = this.receiptPath(id);
+ if (!this.assertPathParentSync(receiptPath)) return;
const receiptKind = await classifyCleanupEntry(receiptPath);
if (receiptKind === 'missing') {
// ENOENT is already-clean and must remain idempotent.
@@ -326,7 +437,7 @@ export class GhostInstallReceiptStore {
// and transient IO failures remain observable so the caller keeps its journal.
const snapshotPath = await this.assertManagedSnapshotParent(id, { createMissing: false });
if (!snapshotPath) return;
- const parentDir = path.join(this.rootDir(), 'skill-snapshots');
+ const parentDir = path.dirname(snapshotPath);
const parentStats = await fs.promises.lstat(parentDir, { bigint: true });
await this.mutateSnapshot({
parentDir,
@@ -336,13 +447,14 @@ export class GhostInstallReceiptStore {
ino: parentStats.ino,
},
operation: 'remove',
- targetName: id,
+ targetName: id.split('/').at(-1)!,
});
}
/** `remove` 的同步版:启动恢复(构造期同步)收尾未完成卸载用,判据同 `remove`。 */
removeSync(id: string): void {
const receiptPath = this.receiptPath(id);
+ if (!this.assertPathParentSync(receiptPath)) return;
const receiptKind = classifyCleanupEntrySync(receiptPath);
if (receiptKind === 'missing') {
// ENOENT is already-clean and must remain idempotent.
@@ -360,10 +472,10 @@ export class GhostInstallReceiptStore {
}
skillSnapshotRoot(id: string, revision: string): string {
- if (!isValidGhostId(id) || !isRevision(revision)) {
+ if (!isValidPluginInstallRelId(id) || !isRevision(revision)) {
throw new Error('invalid ghost skill snapshot identity');
}
- return path.join(this.rootDir(), 'skill-snapshots', id, revision);
+ return path.join(this.rootDir(), 'skill-snapshots', ...id.split('/'), revision);
}
/**
@@ -384,10 +496,10 @@ export class GhostInstallReceiptStore {
id: string,
opts: { createMissing: boolean },
): Promise<string | null> {
- if (!isValidGhostId(id)) throw new Error('invalid ghost id for snapshot path');
+ if (!isValidPluginInstallRelId(id)) throw new Error('invalid ghost id for snapshot path');
const root = this.rootDir();
let current = root;
- for (const segment of ['skill-snapshots', id]) {
+ for (const segment of ['skill-snapshots', ...id.split('/')]) {
current = path.join(current, segment);
let kind: Awaited<ReturnType<typeof classifyGhostDirEntry>> | null;
try {
@@ -422,10 +534,10 @@ export class GhostInstallReceiptStore {
id: string,
opts: { createMissing: boolean },
): string | null {
- if (!isValidGhostId(id)) throw new Error('invalid ghost id for snapshot path');
+ if (!isValidPluginInstallRelId(id)) throw new Error('invalid ghost id for snapshot path');
const root = this.rootDir();
let current = root;
- for (const segment of ['skill-snapshots', id]) {
+ for (const segment of ['skill-snapshots', ...id.split('/')]) {
current = path.join(current, segment);
let kind: ReturnType<typeof classifyGhostDirEntrySync> | null;
try {
@@ -543,8 +655,8 @@ export class GhostInstallReceiptStore {
* 时用它区分"安装了 receipt 之前就是 legacy"与"新模型安装后 receipt 被删"。
*/
private migrationMarkerPath(id: string): string {
- if (!isValidGhostId(id)) throw new Error('invalid ghost id for migration marker path');
- return path.join(this.rootDir(), `.migrated-${id}`);
+ if (!isValidPluginInstallRelId(id)) throw new Error('invalid ghost id for migration marker path');
+ return path.join(this.rootDir(), `.migrated-${id.replaceAll('/', '.')}`);
}
/**
@@ -565,7 +677,7 @@ export class GhostInstallReceiptStore {
const root = this.rootDir();
await fs.promises.mkdir(root, { recursive: true });
const target = this.migrationMarkerPath(id);
- const temp = path.join(root, `.migrated-${id}-${process.pid}-${crypto.randomBytes(4).toString('hex')}.tmp`);
+ const temp = path.join(root, `.migrated-${id.replaceAll('/', '.')}-${process.pid}-${crypto.randomBytes(4).toString('hex')}.tmp`);
try {
await fs.promises.writeFile(temp, '', { encoding: 'utf8', flag: 'wx', mode: 0o600 });
// Publish via hard-link first so the operation is no-clobber:
@@ -656,18 +768,29 @@ export class GhostInstallReceiptStore {
/** 事务标记路径。点开头,不与 `<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`);
+ const identity = parsePluginInstallRelId(id);
+ if (!identity) throw new Error('invalid ghost id for pending mutation path');
+ return path.join(
+ this.rootDir(),
+ ...id.split('/').slice(0, -1),
+ `.pending-${identity.ghostId}.json`,
+ );
}
/** 事务开始:装入/更新 rename 动盘**之前**落标记(原子 temp+rename;re-begin 覆盖)。 */
async writePendingMutation(id: string, entry: GhostPendingMutation): Promise<void> {
+ if (entry.kind === 'update' && entry.sourceStateArchiveId !== undefined &&
+ (!isValidGhostSourceStateArchiveId(entry.sourceStateArchiveId) ||
+ entry.receiptRevision === undefined)) {
+ throw new Error('journal source state archive identity is invalid');
+ }
const root = this.rootDir();
- await fs.promises.mkdir(root, { recursive: true });
const target = this.pendingMutationPath(id);
+ fs.mkdirSync(root, { recursive: true });
+ this.assertPathParentSync(target, true);
const temp = path.join(
root,
- `.pending-${id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
+ `.pending-${id.replaceAll('/', '.')}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
);
try {
await fs.promises.writeFile(temp, `${JSON.stringify({ version: 1, id, ...entry })}\n`, {
@@ -683,12 +806,18 @@ export class GhostInstallReceiptStore {
/** 事务提交:receipt 写成功后清标记。删不动只多留一份标记,下轮恢复幂等重判。 */
async clearPendingMutation(id: string): Promise<void> {
- await fs.promises.rm(this.pendingMutationPath(id), { force: true });
+ const target = this.pendingMutationPath(id);
+ if (this.assertPathParentSync(target)) {
+ await fs.promises.rm(target, { force: true });
+ }
}
/** 同步清标记(启动恢复在构造期同步跑,不能留 fire-and-forget 的异步删除)。 */
clearPendingMutationSync(id: string): void {
- fs.rmSync(this.pendingMutationPath(id), { force: true });
+ const target = this.pendingMutationPath(id);
+ if (this.assertPathParentSync(target)) {
+ fs.rmSync(target, { force: true });
+ }
}
readPendingMutationSync(id: string): GhostPendingMutationReadResult {
@@ -696,6 +825,9 @@ export class GhostInstallReceiptStore {
const markerPath = this.pendingMutationPath(id);
let bytes: Buffer | null;
try {
+ if (!this.assertPathParentSync(markerPath)) {
+ return { state: 'missing' };
+ }
// 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
@@ -784,6 +916,11 @@ export class GhostInstallReceiptStore {
}
const oldPackageSha256 = raw.oldPackageSha256;
const receiptRevision = raw.receiptRevision;
+ const sourceStateArchiveId = raw.sourceStateArchiveId;
+ if (sourceStateArchiveId !== undefined &&
+ (!isValidGhostSourceStateArchiveId(sourceStateArchiveId) || receiptRevision === undefined)) {
+ return { state: 'invalid', reason: 'journal source state archive identity is invalid' };
+ }
if (
receiptRevision !== undefined &&
(typeof receiptRevision !== 'string' || !isRevision(receiptRevision))
@@ -805,6 +942,7 @@ export class GhostInstallReceiptStore {
...(receiptRevision !== undefined ? { receiptRevision } : {}),
...(phase !== undefined ? { phase } : {}),
...(oldPackageSha256 !== undefined ? { oldPackageSha256 } : {}),
+ ...(sourceStateArchiveId !== undefined ? { sourceStateArchiveId } : {}),
},
};
}
@@ -833,16 +971,39 @@ export class GhostInstallReceiptStore {
if (isValidGhostId(match[1])) ids.push(match[1]);
else blocked = true;
}
+ try {
+ const nsRoot = path.join(this.rootDir(), PLUGIN_NS_INSTALL_ROOT);
+ if (this.assertPathParentSync(path.join(nsRoot, '.pending-scan'))) {
+ for (const nsEntry of fs.readdirSync(nsRoot, { withFileTypes: true })) {
+ if (!nsEntry.isDirectory() && !nsEntry.isSymbolicLink()) continue;
+ const parent = path.join(nsRoot, nsEntry.name);
+ if (!this.assertPathParentSync(path.join(parent, '.pending-scan'))) continue;
+ for (const name of fs.readdirSync(parent)) {
+ if (!name.startsWith('.pending-') || !name.endsWith('.json')) continue;
+ const ghostId = name.slice('.pending-'.length, -'.json'.length);
+ const relId = PLUGIN_NS_INSTALL_ROOT + '/' + nsEntry.name + '/' + ghostId;
+ if (isValidPluginInstallRelId(relId)) ids.push(relId);
+ else blocked = true;
+ }
+ }
+ }
+ } catch (error) {
+ return {
+ state: 'unreadable',
+ reason: error instanceof Error ? error.message : String(error),
+ };
+ }
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`);
+ if (!isValidPluginInstallRelId(id)) throw new Error('invalid ghost id for receipt path');
+ return path.join(this.rootDir(), ...id.split('/').slice(0, -1), `${id.split('/').at(-1)}.json`);
}
private async ensureSkillSnapshot(
receipt: GhostInstallReceipt,
+ relId: string,
skillSourceDir: string | undefined,
): Promise<void> {
const items = receipt.manifest.skill?.items ?? [];
@@ -851,17 +1012,20 @@ export class GhostInstallReceiptStore {
try { await fs.promises.mkdir(snapshotsRoot, { recursive: false }); } catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
}
- const rootStats = await fs.promises.lstat(snapshotsRoot, { bigint: true });
+ const snapshotParent = await this.assertManagedSnapshotParent(relId, { createMissing: true });
+ if (!snapshotParent) throw new Error('skill snapshot parent unavailable');
+ const parentDir = path.dirname(snapshotParent);
+ const rootStats = await fs.promises.lstat(parentDir, { bigint: true });
if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error('skill snapshot root unavailable');
await this.mutateSnapshot({
- parentDir: snapshotsRoot,
+ parentDir,
expectedParent: {
- realPath: await fs.promises.realpath(snapshotsRoot),
+ realPath: await fs.promises.realpath(parentDir),
dev: rootStats.dev,
ino: rootStats.ino,
},
operation: 'ensure',
- targetName: `${receipt.id}/${receipt.revision}`,
+ targetName: `${relId.split('/').at(-1)}/${receipt.revision}`,
receipt,
...(skillSourceDir ? { sourceDir: skillSourceDir } : {}),
});
@@ -969,7 +1133,8 @@ function isValidUniqueGhostIdArray(value: unknown): value is string[] {
}
function isManagedBackupDirName(id: string, name: string): boolean {
- return new RegExp(`^\\.cindy-updating-${escapeRegExp(id)}-[0-9a-f]{8}$`).test(name);
+ if (!isValidPluginInstallRelId(id)) return false;
+ return new RegExp(`^\\.cindy-updating-${escapeRegExp(pluginInstallStoragePart(id))}-[0-9a-f]{8}$`).test(name);
}
function escapeRegExp(value: string): string {
@@ -1039,6 +1204,8 @@ export function createGhostInstallReceipt(input: {
revision?: string;
iconDataUrl?: string;
installOrigin?: string;
+ namespace?: string | null;
+ legacyFirstPartyEligible?: boolean;
}): GhostInstallReceipt {
if (input.installOrigin !== undefined && !isPersistableInstallOrigin(input.installOrigin)) {
throw new Error('receipt installOrigin 不合法');
@@ -1046,6 +1213,9 @@ export function createGhostInstallReceipt(input: {
return {
schemaVersion: RECEIPT_SCHEMA_VERSION,
id: input.manifest.id,
+ ...(hasDeliveryNamespace(input)
+ ? { namespace: input.namespace ?? null }
+ : {}),
revision: input.revision ?? crypto.randomUUID(),
manifest: input.manifest,
localeResources: input.localeResources,
@@ -1056,6 +1226,7 @@ export function createGhostInstallReceipt(input: {
...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),
...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),
...(input.installOrigin !== undefined ? { installOrigin: input.installOrigin } : {}),
+ ...(input.legacyFirstPartyEligible === true ? { legacyFirstPartyEligible: true } : {}),
};
}
@@ -1077,6 +1248,13 @@ export function effectiveInstallOrigin(
return receipt.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual';
}
+export function legacyFirstPartyEligibilityAfterUpdate(
+ receipt: Pick<GhostInstallReceipt, 'legacyFirstPartyEligible'>,
+ sourceChanged: boolean,
+): boolean {
+ return !sourceChanged && receipt.legacyFirstPartyEligible === true;
+}
+
/**
* 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。
*
@@ -1208,6 +1386,17 @@ function validateReceipt(
if (!validated.ok) return { ok: false, reason: `receipt locale 不合法:${localePath}` };
localeResources[localePath] = validated.resource;
}
+ let namespace: string | null | undefined;
+ if (hasDeliveryNamespace(value)) {
+ if (value.namespace !== null && !isValidPluginNamespace(value.namespace)) {
+ return { ok: false, reason: 'receipt namespace 不合法' };
+ }
+ namespace = value.namespace === null ? null : value.namespace;
+ }
+ if (value.legacyFirstPartyEligible !== undefined &&
+ typeof value.legacyFirstPartyEligible !== 'boolean') {
+ return { ok: false, reason: 'receipt legacyFirstPartyEligible 不合法' };
+ }
let installOrigin: string | undefined;
if (value.installOrigin !== undefined) {
if (
@@ -1233,6 +1422,8 @@ function validateReceipt(
...(typeof value.packageSha256 === 'string' ? { packageSha256: value.packageSha256 } : {}),
...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),
...(installOrigin !== undefined ? { installOrigin } : {}),
+ ...(value.legacyFirstPartyEligible === true ? { legacyFirstPartyEligible: true } : {}),
+ ...(namespace !== undefined ? { namespace } : {}),
},
};
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostKvStore.ts b/apps/desktop/src/main/cindy-brain/ghostKvStore.ts
index 4c2e3ddbc9..07523c78b9 100644
--- a/apps/desktop/src/main/cindy-brain/ghostKvStore.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostKvStore.ts
@@ -1,7 +1,8 @@
/**
* ghostKvStore —— 意识自定义参数的持久化真身(/kv 协议端点的存储层)。
*
- * File: <rootDir>/<ghostId>.json(生产 rootDir = <userData>/ghost-kv/)
+ * File: <rootDir>/<storagePart>.json(生产 rootDir = <userData>/ghost-kv/;
+ * root = helper.json, org = _ns__acme__helper.json)
*
* 语义(docs/dev-rules/plugin-security-and-authoring.md / FORGE_GUIDE §4.8):
* - 单意识单文件:损坏只伤一个意识,卸下清理 = unlink 一个文件;
@@ -13,7 +14,7 @@
* 炸掉设置页;
* - 写:tmp + rename 原子落盘(override-settings-file 同款),同步 IO
* 天然串行,≤64KB 量级无阻塞之虞;
- * - ghostId 过 isValidGhostId 双保险(调用方来自分区绑定,理论上已合法;
+ * - storage part 过 isValidPluginStoragePart 双保险(调用方来自分区绑定,理论上已合法;
* 文件名安全不省这道)。
*
* 与 Electron 解耦:rootDir 经工厂注入,单测直接用 os.tmpdir()(规范 14/23)。
@@ -22,7 +23,7 @@
import fs from 'node:fs';
import path from 'node:path';
-import { isValidGhostId } from '../../shared/ghost.js';
+import { isValidPluginStoragePart } from '../../shared/pluginIdentity.js';
/** 单意识 KV 序列化后的字节上限(64KB;超限写入拒 413)。 */
export const GHOST_KV_MAX_BYTES = 64 * 1024;
@@ -34,21 +35,21 @@ interface GhostKvLogger {
export interface GhostKvStore {
/** 读某意识的 KV;无文件 / 损坏 → {}(永不抛)。 */
- read(ghostId: string): Record<string, unknown>;
+ read(instanceKey: string): Record<string, unknown>;
/**
* 严格读:无文件 → {},但 IO 异常 / JSON 损坏**原样上抛**。setup 就绪
* 检查(ghosts:setup-status)专用——「查询失败」≠「未配置」,不能拿
* read 的宽松口径把存储层故障误判成缺配置去拦用户;设置页协议端点
* 仍走 read(损坏不炸设置页的语义不变)。
*/
- readStrict(ghostId: string): Record<string, unknown>;
+ readStrict(instanceKey: string): Record<string, unknown>;
/**
* 整体覆盖写;值非 plain object 或序列化超限时抛带 code 的错
* ('INVALID_VALUE' | 'TOO_LARGE' | 'INVALID_GHOST_ID'),由端点层折叠成状态码。
*/
- write(ghostId: string, value: Record<string, unknown>): void;
+ write(instanceKey: string, value: Record<string, unknown>): void;
/** 删除某意识的 KV 文件;幂等,不存在静默。 */
- remove(ghostId: string): void;
+ remove(instanceKey: string): void;
}
/**
@@ -57,14 +58,14 @@ export interface GhostKvStore {
*/
export function removeGhostKvBestEffort(
store: Pick<GhostKvStore, 'remove'>,
- ghostId: string,
+ instanceKey: string,
log: GhostKvLogger,
): void {
try {
- store.remove(ghostId);
+ store.remove(instanceKey);
} catch (error) {
log.warn('ghost KV 清理失败', {
- ghostId,
+ instanceKey,
error: error instanceof Error ? error.message : String(error),
});
}
@@ -126,18 +127,18 @@ export function createGhostKvStore(options: {
}): GhostKvStore {
const { getRootDir, log } = options;
- const fileFor = (ghostId: string): string => {
- if (!isValidGhostId(ghostId)) {
- throw new GhostKvError('INVALID_GHOST_ID', `非法 ghostId: ${String(ghostId)}`);
+ const fileFor = (instanceKey: string): string => {
+ if (!isValidPluginStoragePart(instanceKey)) {
+ throw new GhostKvError('INVALID_GHOST_ID', `非法 ghostId: ${String(instanceKey)}`);
}
- return path.join(getRootDir(), `${ghostId}.json`);
+ return path.join(getRootDir(), `${instanceKey}.json`);
};
return {
- read(ghostId) {
+ read(instanceKey) {
let file: string;
try {
- file = fileFor(ghostId);
+ file = fileFor(instanceKey);
} catch {
return {};
}
@@ -151,13 +152,13 @@ export function createGhostKvStore(options: {
const parsed: unknown = JSON.parse(text);
return isPlainObject(parsed) ? parsed : {};
} catch {
- log?.warn('ghost KV 文件损坏,按空对象处理', { ghostId });
+ log?.warn('ghost KV 文件损坏,按空对象处理', { instanceKey });
return {};
}
},
- readStrict(ghostId) {
- const file = fileFor(ghostId);
+ readStrict(instanceKey) {
+ const file = fileFor(instanceKey);
let text: string;
try {
text = fs.readFileSync(file, 'utf8');
@@ -170,8 +171,8 @@ export function createGhostKvStore(options: {
return isPlainObject(parsed) ? parsed : {};
},
- write(ghostId, value) {
- const file = fileFor(ghostId); // 非法 id 抛 INVALID_GHOST_ID
+ write(instanceKey, value) {
+ const file = fileFor(instanceKey); // 非法 id 抛 INVALID_GHOST_ID
const text = serializeGhostKvValue(value);
fs.mkdirSync(path.dirname(file), { recursive: true });
// tmp + rename 原子写(override-settings-file 同款;Windows rename 覆盖已有文件 OK)。
@@ -180,10 +181,10 @@ export function createGhostKvStore(options: {
fs.renameSync(tmp, file);
},
- remove(ghostId) {
+ remove(instanceKey) {
let file: string;
try {
- file = fileFor(ghostId);
+ file = fileFor(instanceKey);
} catch {
return; // 非法 id 无文件可删,幂等语义直接返回
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostLocalUpdateSource.ts b/apps/desktop/src/main/cindy-brain/ghostLocalUpdateSource.ts
new file mode 100644
index 0000000000..22ad938666
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostLocalUpdateSource.ts
@@ -0,0 +1,55 @@
+import type { GhostTrustInfo } from '../../shared/ghost.js';
+import type { GhostInstallReceipt } from './ghostInstallReceipt.js';
+
+const PACKAGE_SHA256_RE = /^[a-f0-9]{64}$/;
+
+export interface GhostLocalUpdatePackageEvidence {
+ ghostId: string;
+ namespace: string | null;
+ packageSha256: string;
+ trust: GhostTrustInfo;
+}
+
+export interface GhostLocalUpdateSourceInput {
+ existingSourceChanged: boolean;
+ previousApprovedReceipt: Pick<GhostInstallReceipt,
+ 'id' | 'namespace' | 'packageSha256' | 'trust' | 'legacyFirstPartyEligible'> | null;
+ inspectedPackage: GhostLocalUpdatePackageEvidence;
+}
+
+export interface GhostLocalUpdateSourceDecision {
+ sourceChanged: boolean;
+ legacyFirstPartyEligible: boolean;
+}
+
+function verifiedPublisherKey(trust: GhostTrustInfo): string | null {
+ return trust.publisherSigned && trust.publisherVerified &&
+ typeof trust.publisherKeyId === 'string' && trust.publisherKeyId.length > 0
+ ? trust.publisherKeyId : null;
+}
+
+export function classifyGhostLocalUpdateSource(
+ input: GhostLocalUpdateSourceInput,
+): GhostLocalUpdateSourceDecision {
+ const previous = input.previousApprovedReceipt;
+ const next = input.inspectedPackage;
+ const identityMatches = previous !== null && previous.id === next.ghostId &&
+ (previous.namespace ?? null) === next.namespace;
+ const previousHashValid = previous?.packageSha256 !== undefined &&
+ PACKAGE_SHA256_RE.test(previous.packageSha256);
+ const nextHashValid = PACKAGE_SHA256_RE.test(next.packageSha256);
+ const previousPublisherKey = previous ? verifiedPublisherKey(previous.trust) : null;
+ const sameSourceProven = identityMatches && previousHashValid && nextHashValid && (
+ previous.packageSha256 === next.packageSha256 ||
+ (previousPublisherKey !== null && previousPublisherKey === verifiedPublisherKey(next.trust))
+ );
+ const previousProtectedSource = previous?.legacyFirstPartyEligible === true ||
+ previous?.trust.level === 'cindy-official' || previousPublisherKey !== null;
+ const sourceChanged = input.existingSourceChanged || !identityMatches || !nextHashValid ||
+ (previousProtectedSource && !sameSourceProven);
+ return {
+ sourceChanged,
+ legacyFirstPartyEligible: !sourceChanged && previousHashValid &&
+ previous?.legacyFirstPartyEligible === true,
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostMediaHandoverTargetTracker.ts b/apps/desktop/src/main/cindy-brain/ghostMediaHandoverTargetTracker.ts
new file mode 100644
index 0000000000..3ff5d46b22
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostMediaHandoverTargetTracker.ts
@@ -0,0 +1,89 @@
+import { randomUUID } from 'node:crypto';
+
+import { GHOST_MEDIA_HANDOVER_MIME, type GhostPanelMediaTarget } from '../../shared/ghost.js';
+import { parsePluginStoragePart } from '../../shared/pluginIdentity.js';
+import { parseGhostMediaHandoverUrl } from './previewGate.js';
+
+interface GhostMediaHandoverSource extends GhostPanelMediaTarget {
+ instanceId: string;
+ isCurrent(): boolean;
+}
+
+export class GhostMediaHandoverTargetTracker {
+ private readonly sources = new Map<string, GhostMediaHandoverSource>();
+
+ register(source: GhostMediaHandoverSource): string {
+ if (parsePluginStoragePart(source.instanceId)?.ghostId !== source.ghostId) {
+ throw new Error('Invalid ghost media handover source');
+ }
+ const token = randomUUID();
+ this.sources.set(token, { ...source });
+ return token;
+ }
+
+ revoke(token: string): void {
+ this.sources.delete(token);
+ }
+
+ resolve(token: unknown, uri: unknown): GhostPanelMediaTarget | null {
+ if (typeof token !== 'string' || token.length !== 36 || typeof uri !== 'string') return null;
+ const source = this.sources.get(token);
+ if (!source) return null;
+ try {
+ if (!source.isCurrent()) {
+ this.revoke(token);
+ return null;
+ }
+ } catch {
+ this.revoke(token);
+ return null;
+ }
+ if (parseGhostMediaHandoverUrl(uri)?.ghostId !== source.ghostId) return null;
+ return { ghostId: source.ghostId, instanceId: source.instanceId };
+ }
+}
+
+export const ghostMediaHandoverTargetTracker = new GhostMediaHandoverTargetTracker();
+
+export function resolveGhostMediaHandoverTarget(token: unknown, uri: unknown): GhostPanelMediaTarget | null {
+ return ghostMediaHandoverTargetTracker.resolve(token, uri);
+}
+
+export function ghostMediaHandoverDragScript(sourceToken: string): string {
+ return '(' + installGhostMediaHandoverDrag.toString() + ')('
+ + JSON.stringify(GHOST_MEDIA_HANDOVER_MIME) + ',' + JSON.stringify(sourceToken) + ')';
+}
+
+function installGhostMediaHandoverDrag(mime: string, sourceToken: string): void {
+ const handleDrag = (event: DragEvent) => {
+ if (!event.isTrusted || !event.dataTransfer) return;
+ const candidates: string[] = [];
+ for (const type of ['text/uri-list', 'text/plain']) {
+ const raw = event.dataTransfer.getData(type);
+ candidates.push(...raw.split(String.fromCharCode(10)).map((line) => line.trim()));
+ }
+ const target = event.target instanceof Element ? event.target : null;
+ const anchor = target?.closest('a');
+ if (anchor instanceof HTMLAnchorElement) candidates.push(anchor.href);
+ const media = target?.closest('img,video');
+ if (media instanceof HTMLImageElement || media instanceof HTMLVideoElement) {
+ candidates.push(media.currentSrc || media.src);
+ }
+ const uri = candidates.find((candidate) => {
+ try {
+ const parsed = new URL(candidate);
+ const parts = parsed.pathname.split('/');
+ return parsed.protocol === 'cindy-ghost:' && parts.length === 3
+ && ['media', 'preview'].includes(parts[1])
+ && /^[a-f0-9]{64}[.](png|jpg|jpeg|gif|webp|mp4|webm)$/i.test(parts[2])
+ && !parsed.search && !parsed.hash;
+ } catch {
+ return false;
+ }
+ });
+ if (!uri) return;
+ event.dataTransfer.setData(mime, JSON.stringify({ uri, sourceToken }));
+ };
+ window.addEventListener('dragstart', handleDrag, true);
+ window.addEventListener('dragstart', handleDrag, false);
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
index 925fe503e3..d4e2583e41 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
@@ -46,8 +46,6 @@ import {
} from './ghostOauthFlow.js';
import {
changedBuiltinOauthClientSecretKeys,
- isBrokerEligibleGhostId,
- isFirstPartyHostPrivilegeGhostId,
type GhostManifest,
type GhostSecretOauthDecl,
} from '../../shared/ghost.js';
@@ -101,12 +99,12 @@ export interface GhostOauthAccountView {
/** 保险库最小面(providerSecretStore 在接线处适配;测试喂内存假体)。 */
export interface GhostOauthVault {
- read(ghostId: string, storageKey: string): string | null;
+ read(instanceKey: string, storageKey: string): string | null;
/** Optional strict read used only by durable reconciliation. */
- readStrict?(ghostId: string, storageKey: string): string | null;
+ readStrict?(instanceKey: string, storageKey: string): string | null;
/** 返回 false = 写失败(safeStorage 不可用等),调用方折叠结构化错误。 */
- store(ghostId: string, storageKey: string, value: string): boolean;
- remove(ghostId: string, storageKey: string): void;
+ store(instanceKey: string, storageKey: string, value: string): boolean;
+ remove(instanceKey: string, storageKey: string): void;
}
export interface GhostOauthAccountManagerDeps {
@@ -148,20 +146,27 @@ export interface GhostOauthAccountManagerDeps {
* verifies that the plugin and the exact OAuth declaration still exist
* before any callback result is persisted.
*/
- isConnectTargetCurrent?: (ghostId: string, secretKey: string, decl: GhostOauthDecl) => boolean;
+ captureConnectTarget?: (instanceKey: string) => unknown;
+ isConnectTargetCurrent?: (instanceKey: string,
+ secretKey: string,
+ decl: GhostOauthDecl,
+ expectedConnectTarget?: unknown,
+ ) => boolean;
/**
* Serialize the final declaration check and every related vault mutation
* with plugin update migration. Browser authorization and identity requests
* intentionally remain outside this lock.
*/
- withMutationLock?: <T>(ghostId: string, task: () => Promise<T> | T) => Promise<T>;
+ withMutationLock?: <T>(instanceKey: string, task: () => Promise<T> | T) => Promise<T>;
/** 延时器(仅 invalid_grant 轮换探测用;测试注入即时假体,生产缺省 setTimeout)。 */
sleep?: (ms: number) => Promise<void>;
/**
- * tokenBroker 资格复核。官方前缀命中照今天放行;否则问 first-party 判据。
- * 缺省只认静态官方前缀,存量单测零行为变化。
+ * tokenBroker 资格复核。按可信安装事实判定,名称前缀不放行。
+ * 缺省拒绝。
*/
- isTokenBrokerAuthorized?: (ghostId: string) => boolean;
+ isTokenBrokerAuthorized?: (instanceKey: string) => boolean;
+ /** Port reclaim / identity avatar. Missing = deny. */
+ isHostPrimitiveAuthorized?: (instanceKey: string) => boolean;
}
/**
@@ -366,15 +371,16 @@ interface CachedAccessToken {
/* ------------------------------------------------------------------------ */
/**
- * 一个进程级单例管所有意识的所有 oauth 凭证槽(缓存键含 ghostId + secretKey +
+ * 一个进程级单例管所有意识的所有 oauth 凭证槽(缓存键含 instanceKey + secretKey +
* accountId,互不串)。接线处(cindy-brain/index.ts)构造一次注入各消费方。
*/
export class GhostOauthAccountManager {
private readonly deps: GhostOauthAccountManagerDeps;
- /** access token 内存缓存:`${ghostId} ${secretKey} ${accountId}`。 */
+ /** access token 内存缓存:`${instanceKey} ${secretKey} ${accountId}`。 */
private readonly tokenCache = new Map<string, CachedAccessToken>();
/** 刷新单飞:同键并发只跑一单,其余等结果。 */
private readonly refreshInflight = new Map<string, Promise<GhostOauthAccessTokenResult>>();
+ private readonly ghostGenerations = new Map<string, number>();
constructor(deps: GhostOauthAccountManagerDeps) {
this.deps = deps;
@@ -383,16 +389,16 @@ export class GhostOauthAccountManager {
/* ---------------------------- client 凭证 ----------------------------- */
/** client 凭证是否可用(用户自填或清单内置任一即可;设置页状态展示,不回明文)。 */
- clientConfigured(ghostId: string, secretKey: string, decl?: GhostOauthDecl): boolean {
+ clientConfigured(instanceKey: string, secretKey: string, decl?: GhostOauthDecl): boolean {
// broker 模式:secret 在服务端,声明了内置 clientId 即视为可连(用户零配置)。
if (decl?.tokenBroker) return typeof decl.clientId === 'string' && decl.clientId.length > 0;
- if (this.clientCustomized(ghostId, secretKey)) return true;
+ if (this.clientCustomized(instanceKey, secretKey)) return true;
return typeof decl?.clientId === 'string' && decl.clientId.length > 0;
}
/** 用户是否自填过 client 凭证(区分"内置应用身份"与"已自定义"的 UI 态)。 */
- clientCustomized(ghostId: string, secretKey: string): boolean {
- const clientId = this.deps.vault.read(ghostId, clientIdKey(secretKey));
+ clientCustomized(instanceKey: string, secretKey: string): boolean {
+ const clientId = this.deps.vault.read(instanceKey, clientIdKey(secretKey));
return typeof clientId === 'string' && clientId.length > 0;
}
@@ -401,30 +407,29 @@ export class GhostOauthAccountManager {
* 可省略——纯 PKCE 公共客户端)。改 client 后既有 access token 缓存作废
* (旧 client 换的令牌不该再续命)。
*/
- setClientConfig(
- ghostId: string,
+ setClientConfig(instanceKey: string,
secretKey: string,
clientId: string,
clientSecret?: string,
): boolean {
- if (!this.deps.vault.store(ghostId, clientIdKey(secretKey), clientId)) return false;
+ if (!this.deps.vault.store(instanceKey, clientIdKey(secretKey), clientId)) return false;
if (clientSecret !== undefined && clientSecret.length > 0) {
- if (!this.deps.vault.store(ghostId, clientSecretKey(secretKey), clientSecret)) return false;
+ if (!this.deps.vault.store(instanceKey, clientSecretKey(secretKey), clientSecret)) return false;
} else {
- this.deps.vault.remove(ghostId, clientSecretKey(secretKey));
+ this.deps.vault.remove(instanceKey, clientSecretKey(secretKey));
}
for (const key of this.tokenCache.keys()) {
- if (key.startsWith(`${ghostId} ${secretKey} `)) this.tokenCache.delete(key);
+ if (key.startsWith(`${instanceKey} ${secretKey} `)) this.tokenCache.delete(key);
}
return true;
}
/** 清除 client 凭证(幂等;已连账号保留但刷新会 NO_CLIENT_CONFIG,重填即恢复)。 */
- clearClientConfig(ghostId: string, secretKey: string): void {
- this.deps.vault.remove(ghostId, clientIdKey(secretKey));
- this.deps.vault.remove(ghostId, clientSecretKey(secretKey));
+ clearClientConfig(instanceKey: string, secretKey: string): void {
+ this.deps.vault.remove(instanceKey, clientIdKey(secretKey));
+ this.deps.vault.remove(instanceKey, clientSecretKey(secretKey));
for (const key of this.tokenCache.keys()) {
- if (key.startsWith(`${ghostId} ${secretKey} `)) this.tokenCache.delete(key);
+ if (key.startsWith(`${instanceKey} ${secretKey} `)) this.tokenCache.delete(key);
}
}
@@ -437,8 +442,13 @@ export class GhostOauthAccountManager {
expireAccountsForChangedClients(
previousManifest: GhostManifest,
currentManifest: GhostManifest,
+ vaultId: string,
): number {
- const migration = this.prepareAccountsForChangedClients(previousManifest, currentManifest);
+ const migration = this.prepareAccountsForChangedClients(
+ previousManifest,
+ currentManifest,
+ vaultId,
+ );
migration.commit();
return migration.expiredCount;
}
@@ -453,8 +463,9 @@ export class GhostOauthAccountManager {
prepareAccountsForChangedClients(
previousManifest: GhostManifest,
currentManifest: GhostManifest,
+ vaultId: string,
): GhostOauthClientMigration {
- const ghostId = currentManifest.id;
+ const instanceKey = vaultId;
const applied: Array<{
secretKey: string;
beforeRaw: string;
@@ -474,7 +485,7 @@ export class GhostOauthAccountManager {
)
.map((secret) => secret.key);
for (const secretKey of new Set([...changedKeys, ...currentDirectOauthKeys])) {
- if (this.clientCustomized(ghostId, secretKey)) continue;
+ if (this.clientCustomized(instanceKey, secretKey)) continue;
const previousClientId = previousManifest.network?.secrets
?.find((secret) => secret.key === secretKey && secret.source === 'oauth')
?.oauth?.clientId?.trim();
@@ -484,10 +495,10 @@ export class GhostOauthAccountManager {
?.oauth?.clientId?.trim() || null;
const clientChanged =
previousClientId !== undefined && previousClientId !== currentClientId;
- const beforeRaw = this.deps.vault.read(ghostId, accountsKey(secretKey));
+ const beforeRaw = this.deps.vault.read(instanceKey, accountsKey(secretKey));
const manifest = parseManifest(beforeRaw);
if (beforeRaw === null) {
- this.clearCachedTokens(ghostId, secretKey);
+ this.clearCachedTokens(instanceKey, secretKey);
continue;
}
let expiredCount = 0;
@@ -515,11 +526,11 @@ export class GhostOauthAccountManager {
const afterRaw = JSON.stringify(manifest);
if (
afterRaw !== beforeRaw &&
- !this.deps.vault.store(ghostId, accountsKey(secretKey), afterRaw)
+ !this.deps.vault.store(instanceKey, accountsKey(secretKey), afterRaw)
) {
throw new Error('Unable to persist OAuth client migration state');
}
- this.clearCachedTokens(ghostId, secretKey);
+ this.clearCachedTokens(instanceKey, secretKey);
applied.push({
secretKey,
beforeRaw,
@@ -531,9 +542,9 @@ export class GhostOauthAccountManager {
} catch (error) {
let rollbackFailed = false;
for (const change of [...applied].reverse()) {
- const current = this.deps.vault.read(ghostId, accountsKey(change.secretKey));
+ const current = this.deps.vault.read(instanceKey, accountsKey(change.secretKey));
if (current !== change.afterRaw) continue;
- if (!this.deps.vault.store(ghostId, accountsKey(change.secretKey), change.beforeRaw)) {
+ if (!this.deps.vault.store(instanceKey, accountsKey(change.secretKey), change.beforeRaw)) {
rollbackFailed = true;
}
}
@@ -556,7 +567,7 @@ export class GhostOauthAccountManager {
let restoredForSecret = 0;
if (change.restoreOnCommitAccountIds.length > 0) {
const fresh = parseManifest(
- this.deps.vault.read(ghostId, accountsKey(change.secretKey)),
+ this.deps.vault.read(instanceKey, accountsKey(change.secretKey)),
);
const restoreIds = new Set(change.restoreOnCommitAccountIds);
for (const account of fresh.accounts) {
@@ -574,12 +585,11 @@ export class GhostOauthAccountManager {
}
if (
restoredForSecret > 0 &&
- !this.deps.vault.store(ghostId, accountsKey(change.secretKey), JSON.stringify(fresh))
+ !this.deps.vault.store(instanceKey, accountsKey(change.secretKey), JSON.stringify(fresh))
) {
this.deps.logger?.warn?.(
'ghost oauth client migration post-commit recovery write failed',
- {
- ghostId,
+ { ghostId: instanceKey,
secretKey: change.secretKey,
},
);
@@ -588,13 +598,12 @@ export class GhostOauthAccountManager {
}
restoredCount += restoredForSecret;
if (change.expiredCount > 0) {
- this.notifyStatusChanged(ghostId, change.secretKey, 'expired');
+ this.notifyStatusChanged(instanceKey, change.secretKey, 'expired');
}
if (restoredForSecret > 0) {
- this.notifyStatusChanged(ghostId, change.secretKey, 'connected');
+ this.notifyStatusChanged(instanceKey, change.secretKey, 'connected');
}
- this.deps.logger?.info?.('ghost oauth accounts reconciled for client change', {
- ghostId,
+ this.deps.logger?.info?.('ghost oauth accounts reconciled for client change', { ghostId: instanceKey,
secretKey: change.secretKey,
expiredCount: change.expiredCount,
restoredCount: restoredForSecret,
@@ -605,9 +614,9 @@ export class GhostOauthAccountManager {
rollback: () => {
if (settled) return;
for (const change of [...applied].reverse()) {
- const current = this.deps.vault.read(ghostId, accountsKey(change.secretKey));
+ const current = this.deps.vault.read(instanceKey, accountsKey(change.secretKey));
if (current !== change.afterRaw) continue;
- if (!this.deps.vault.store(ghostId, accountsKey(change.secretKey), change.beforeRaw)) {
+ if (!this.deps.vault.store(instanceKey, accountsKey(change.secretKey), change.beforeRaw)) {
throw new Error('Unable to roll back OAuth client migration state');
}
}
@@ -626,28 +635,30 @@ export class GhostOauthAccountManager {
* the update-crash half state and incorrectly reusing that token for a third
* client introduced by a later update.
*/
- reconcileAccountsForInstalledManifestWithResult(currentManifest: GhostManifest): {
+ reconcileAccountsForInstalledManifestWithResult(
+ currentManifest: GhostManifest,
+ vaultId: string,
+ ): {
restored: number;
retryPending: boolean;
} {
- const ghostId = currentManifest.id;
+ const instanceKey = vaultId;
let restoredCount = 0;
let retryPending = false;
for (const secret of currentManifest.network?.secrets ?? []) {
if (secret.source !== 'oauth' || secret.oauth?.tokenBroker) continue;
- if (this.clientCustomized(ghostId, secret.key)) continue;
+ if (this.clientCustomized(instanceKey, secret.key)) continue;
const currentClientId = secret.oauth?.clientId?.trim();
if (!currentClientId) continue;
let beforeRaw: string | null;
try {
beforeRaw = (this.deps.vault.readStrict ?? this.deps.vault.read)(
- ghostId,
+ instanceKey,
accountsKey(secret.key),
);
} catch (error) {
retryPending = true;
- this.deps.logger?.warn?.('ghost oauth client migration recovery read failed', {
- ghostId,
+ this.deps.logger?.warn?.('ghost oauth client migration recovery read failed', { ghostId: instanceKey,
secretKey: secret.key,
error: error instanceof Error ? error.message : String(error),
});
@@ -672,29 +683,31 @@ export class GhostOauthAccountManager {
changed += 1;
}
if (changed === 0) continue;
- if (!this.deps.vault.store(ghostId, accountsKey(secret.key), JSON.stringify(manifest))) {
+ if (!this.deps.vault.store(instanceKey, accountsKey(secret.key), JSON.stringify(manifest))) {
retryPending = true;
- this.deps.logger?.warn?.('ghost oauth client migration recovery write failed', {
- ghostId,
+ this.deps.logger?.warn?.('ghost oauth client migration recovery write failed', { ghostId: instanceKey,
secretKey: secret.key,
});
continue;
}
restoredCount += changed;
- this.clearCachedTokens(ghostId, secret.key);
- this.notifyStatusChanged(ghostId, secret.key, 'connected');
+ this.clearCachedTokens(instanceKey, secret.key);
+ this.notifyStatusChanged(instanceKey, secret.key, 'connected');
}
return { restored: restoredCount, retryPending };
}
/** Compatibility wrapper for callers that only need the restored count. */
- reconcileAccountsForInstalledManifest(currentManifest: GhostManifest): number {
- return this.reconcileAccountsForInstalledManifestWithResult(currentManifest).restored;
+ reconcileAccountsForInstalledManifest(
+ currentManifest: GhostManifest,
+ vaultId: string,
+ ): number {
+ return this.reconcileAccountsForInstalledManifestWithResult(currentManifest, vaultId).restored;
}
/** 返回仍未完成重新授权的 clientId 迁移账号数;普通撤销授权不计入。 */
- clientMigrationExpiredAccountCount(ghostId: string, secretKey: string): number {
- return parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey))).accounts.filter(
+ clientMigrationExpiredAccountCount(instanceKey: string, secretKey: string): number {
+ return parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey))).accounts.filter(
(account) => account.status === 'expired' && account.expiredReason === 'oauth_client_changed',
).length;
}
@@ -706,8 +719,7 @@ export class GhostOauthAccountManager {
* id/secret 只会换来 invalid_client。清除自填即回落内置(配置设计原则
* 的"恢复默认 = 清除 override")。
*/
- private readClientConfig(
- ghostId: string,
+ private readClientConfig(instanceKey: string,
secretKey: string,
decl: GhostOauthDecl,
clientIdOverride?: string,
@@ -718,7 +730,7 @@ export class GhostOauthAccountManager {
// 复验的备用 clientId,供同一意识按 region 选择不同 OAuth App。
const customId = decl.tokenBroker
? null
- : this.deps.vault.read(ghostId, clientIdKey(secretKey));
+ : this.deps.vault.read(instanceKey, clientIdKey(secretKey));
let clientId: string | null;
let clientSecret: string | null | undefined;
if (clientIdOverride !== undefined) {
@@ -726,7 +738,7 @@ export class GhostOauthAccountManager {
clientSecret = decl.clientSecret;
} else if (customId) {
clientId = customId;
- clientSecret = this.deps.vault.read(ghostId, clientSecretKey(secretKey));
+ clientSecret = this.deps.vault.read(instanceKey, clientSecretKey(secretKey));
} else {
clientId = decl.clientId ?? null;
clientSecret = decl.clientSecret;
@@ -758,16 +770,16 @@ export class GhostOauthAccountManager {
/* ------------------------------ 账号清单 ------------------------------ */
- listAccounts(ghostId: string, secretKey: string, decl?: GhostOauthDecl): GhostOauthAccountView[] {
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ listAccounts(instanceKey: string, secretKey: string, decl?: GhostOauthDecl): GhostOauthAccountView[] {
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
return manifest.accounts.map((a) =>
- toView(a, manifest.defaultAccountId, this.readAvatar(ghostId, secretKey, a.id), decl?.scopes),
+ toView(a, manifest.defaultAccountId, this.readAvatar(instanceKey, secretKey, a.id), decl?.scopes),
);
}
/** 默认账号相对当前声明缺失的 scope;空数组 = 无需重连或判不准。 */
- defaultMissingScopes(ghostId: string, secretKey: string, decl: GhostOauthDecl): string[] {
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ defaultMissingScopes(instanceKey: string, secretKey: string, decl: GhostOauthDecl): string[] {
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
const row = manifest.accounts.find((account) => account.id === manifest.defaultAccountId);
return row ? accountMissingScopes(decl.scopes ?? [], row) : [];
}
@@ -778,13 +790,12 @@ export class GhostOauthAccountManager {
* 'unchanged' = 证据已在库未重写(调用方据此跳过广播);false = 无默认账号
* 或写失败。
*/
- reportInsufficientScopes(
- ghostId: string,
+ reportInsufficientScopes(instanceKey: string,
secretKey: string,
scopes: readonly string[],
declScopes: readonly string[],
): 'stored' | 'unchanged' | false {
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
const row = manifest.accounts.find((account) => account.id === manifest.defaultAccountId);
if (!row) return false;
const declared = new Set(declScopes);
@@ -795,36 +806,36 @@ export class GhostOauthAccountManager {
return 'unchanged';
}
row.insufficientScopes = merged;
- return this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest))
+ return this.deps.vault.store(instanceKey, accountsKey(secretKey), JSON.stringify(manifest))
? 'stored'
: false;
}
/** 头像 data URL 读取(形状校验兜底:库里的坏值当无头像,不喂给 <img>)。 */
- private readAvatar(ghostId: string, secretKey: string, accountId: string): string | null {
- const raw = this.deps.vault.read(ghostId, avatarKey(secretKey, accountId));
+ private readAvatar(instanceKey: string, secretKey: string, accountId: string): string | null {
+ const raw = this.deps.vault.read(instanceKey, avatarKey(secretKey, accountId));
return typeof raw === 'string' && raw.startsWith('data:image/') ? raw : null;
}
- setDefaultAccount(ghostId: string, secretKey: string, accountId: string): boolean {
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ setDefaultAccount(instanceKey: string, secretKey: string, accountId: string): boolean {
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
if (!manifest.accounts.some((a) => a.id === accountId)) return false;
return this.deps.vault.store(
- ghostId,
+ instanceKey,
accountsKey(secretKey),
JSON.stringify({ ...manifest, defaultAccountId: accountId }),
);
}
/** 断开账号:清 refresh token、清头像、清缓存、从清单摘除(幂等)。 */
- disconnectAccount(ghostId: string, secretKey: string, accountId: string): void {
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ disconnectAccount(instanceKey: string, secretKey: string, accountId: string): void {
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
const remaining = manifest.accounts.filter((a) => a.id !== accountId);
- this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, accountId));
- this.deps.vault.remove(ghostId, avatarKey(secretKey, accountId));
- this.tokenCache.delete(this.cacheKey(ghostId, secretKey, accountId));
+ this.deps.vault.remove(instanceKey, refreshTokenKey(secretKey, accountId));
+ this.deps.vault.remove(instanceKey, avatarKey(secretKey, accountId));
+ this.tokenCache.delete(this.cacheKey(instanceKey, secretKey, accountId));
this.deps.vault.store(
- ghostId,
+ instanceKey,
accountsKey(secretKey),
JSON.stringify({
defaultAccountId:
@@ -845,12 +856,30 @@ export class GhostOauthAccountManager {
* 多行)。标签为 null(未声明 identity / 拉取失败)时无从判定,保持追加。
* client 凭证未填直接拒;授权流程失败原样透传结构化错误(设置页据此提示)。
*/
- private isTokenBrokerAuthorized(ghostId: string): boolean {
- return this.deps.isTokenBrokerAuthorized?.(ghostId) ?? isBrokerEligibleGhostId(ghostId);
+ private isTokenBrokerAuthorized(instanceKey: string): boolean {
+ return this.deps.isTokenBrokerAuthorized?.(instanceKey) === true;
+ }
+
+ captureConnectTarget(instanceKey: string): unknown {
+ return this.deps.captureConnectTarget?.(instanceKey);
+ }
+
+ invalidateGhost(instanceKey: string): void {
+ this.ghostGenerations.set(instanceKey, this.ghostGeneration(instanceKey) + 1);
+ const prefix = instanceKey + ' ';
+ for (const key of this.tokenCache.keys()) {
+ if (key.startsWith(prefix)) this.tokenCache.delete(key);
+ }
+ for (const key of this.refreshInflight.keys()) {
+ if (key.startsWith(prefix)) this.refreshInflight.delete(key);
+ }
+ }
+
+ private ghostGeneration(instanceKey: string): number {
+ return this.ghostGenerations.get(instanceKey) ?? 0;
}
- async connectAccount(
- ghostId: string,
+ async connectAccount(instanceKey: string,
secretKey: string,
decl: GhostOauthDecl,
opts?: {
@@ -877,9 +906,27 @@ export class GhostOauthAccountManager {
/** Main-only caller boundary, checked inside the credential mutation lock. */
assertCurrent?: () => void;
beforeCommit?: () => Promise<void>;
+ expectedConnectTarget?: unknown;
},
): Promise<GhostOauthConnectResult> {
- if (decl.tokenBroker !== undefined && !this.isTokenBrokerAuthorized(ghostId)) {
+ const generation = this.ghostGeneration(instanceKey);
+ const targetProvided = Object.prototype.hasOwnProperty.call(opts ?? {}, 'expectedConnectTarget');
+ const expectedConnectTarget = targetProvided
+ ? opts?.expectedConnectTarget
+ : this.captureConnectTarget(instanceKey);
+ const targetCaptured = targetProvided || this.deps.captureConnectTarget !== undefined;
+ const isConnectTargetCurrent = (): boolean => this.ghostGeneration(instanceKey) === generation &&
+ (targetCaptured
+ ? expectedConnectTarget !== null && expectedConnectTarget !== undefined &&
+ this.deps.isConnectTargetCurrent?.(instanceKey, secretKey, decl, expectedConnectTarget) === true
+ : this.deps.isConnectTargetCurrent?.(instanceKey, secretKey, decl) !== false);
+ const targetChanged: GhostOauthConnectResult = {
+ ok: false,
+ error: 'INVALID_CONFIG',
+ detail: '插件或授权声明已变更',
+ };
+ if (targetCaptured && !isConnectTargetCurrent()) return targetChanged;
+ if (decl.tokenBroker !== undefined && !this.isTokenBrokerAuthorized(instanceKey)) {
return {
ok: false,
error: 'BROKER_FORBIDDEN',
@@ -896,7 +943,7 @@ export class GhostOauthAccountManager {
};
}
}
- const config = this.readClientConfig(ghostId, secretKey, decl, opts?.clientId);
+ const config = this.readClientConfig(instanceKey, secretKey, decl, opts?.clientId);
if (!config) return { ok: false, error: 'NO_CLIENT_CONFIG' };
if (opts?.deliveryHosts?.length) config.corsDeliveryHosts = opts.deliveryHosts;
if (decl.brokerBounce && !config.publicRedirectUri) {
@@ -934,17 +981,11 @@ export class GhostOauthAccountManager {
// 回收 = 强杀占用进程,而"杀谁"由 redirectPort 决定——第三方 manifest
// 可声明任意端口(如 5432),放开等于让任意意识借「连接账号」之手
// 强杀用户本地服务(Postgres 等),故第三方一律回落"占用即报错"。
- reclaimPort: isFirstPartyHostPrivilegeGhostId(ghostId) ? this.deps.reclaimPort : undefined,
+ reclaimPort: this.deps.isHostPrimitiveAuthorized?.(instanceKey) ? this.deps.reclaimPort : undefined,
});
if (!flow.ok) return { ok: false, error: flow.error, detail: flow.detail };
opts?.remote?.assertCurrent();
- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) {
- return {
- ok: false,
- error: 'INVALID_CONFIG',
- detail: '插件或授权声明已变更',
- };
- }
+ if (!isConnectTargetCurrent()) return targetChanged;
// 身份标签:声明了 identity 才拉,失败降级 null(不阻断授权)。label 是
// 同身份合并的判定键;display 是展示名(declaration 有 displayTemplate 才有);
@@ -969,7 +1010,7 @@ export class GhostOauthAccountManager {
// 头像地址是身份端点响应里的任意 https,不受 hosts 白名单约束——放开
// 等于给第三方意识一个"主机代发 GET + 小图字节回沙箱"的 SSRF 读原语。
// 下载本身不带任何凭证(CDN 域名不在注入白名单);失败降级无头像。
- if (identity.avatarUrl !== null && isFirstPartyHostPrivilegeGhostId(ghostId)) {
+ if (identity.avatarUrl !== null && this.deps.isHostPrimitiveAuthorized?.(instanceKey)) {
avatar = await fetchGhostOauthAvatar({
url: identity.avatarUrl,
fetchImpl: this.deps.fetchImpl,
@@ -977,25 +1018,19 @@ export class GhostOauthAccountManager {
}
}
- return this.withMutationLock(ghostId, async () => {
+ return this.withMutationLock(instanceKey, async () => {
await opts?.beforeCommit?.();
opts?.assertCurrent?.();
opts?.remote?.assertCurrent();
// Identity/avatar fetches are asynchronous as well. Recheck inside the
// same strict mutation lock as the first vault read/write so a package
// update cannot replace the declaration between validation and commit.
- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) {
- return {
- ok: false,
- error: 'INVALID_CONFIG',
- detail: '插件或授权声明已变更',
- };
- }
+ if (!isConnectTargetCurrent()) return targetChanged;
// 清单在授权**之后**才读:授权流可长达数分钟,期间清单可能被并发写
// (断开其它账号 / 刷新 invalidGrant 标过期),以新鲜清单为准收窄
// 陈旧写回窗口。
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
// 同身份合并:复用既有账号 id(默认位 / 意识侧记住的 account id 全部
// 保持有效),只换令牌与状态。
@@ -1005,7 +1040,7 @@ export class GhostOauthAccountManager {
if (flow.bundle.refreshToken !== null) {
if (
!this.deps.vault.store(
- ghostId,
+ instanceKey,
refreshTokenKey(secretKey, existing.id),
flow.bundle.refreshToken,
)
@@ -1015,7 +1050,7 @@ export class GhostOauthAccountManager {
} else if (existing.expiredReason === 'oauth_client_changed') {
// 新 client 的授权响应没有 refresh token 时,不能继续保留旧 client
// 签发的 token;当前 access token 过期后按无 refresh token 正常引导重连。
- this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, existing.id));
+ this.deps.vault.remove(instanceKey, refreshTokenKey(secretKey, existing.id));
}
// 重连顺带刷新展示名:老账号(displayTemplate 上线前连的)或用户改过
// 显示名/workspace 名的,这里追上最新值。
@@ -1054,31 +1089,30 @@ export class GhostOauthAccountManager {
}
if (
manifestDirty &&
- !this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest))
+ !this.deps.vault.store(instanceKey, accountsKey(secretKey), JSON.stringify(manifest))
) {
return { ok: false, error: 'VAULT_WRITE_FAILED' };
}
// 重连顺带刷新头像(用户可能换过头像;写失败不影响连接结果)。
if (avatar !== null) {
- this.deps.vault.store(ghostId, avatarKey(secretKey, existing.id), avatar);
+ this.deps.vault.store(instanceKey, avatarKey(secretKey, existing.id), avatar);
}
- this.tokenCache.set(this.cacheKey(ghostId, secretKey, existing.id), {
+ this.tokenCache.set(this.cacheKey(instanceKey, secretKey, existing.id), {
accessToken: flow.bundle.accessToken,
expiresAt: flow.bundle.expiresAt,
});
- this.deps.logger?.info('ghost oauth 账号已重连(同身份合并)', {
- ghostId,
+ this.deps.logger?.info('ghost oauth 账号已重连(同身份合并)', { ghostId: instanceKey,
secretKey,
accountId: existing.id,
});
opts?.remote?.finish(true);
- this.notifyConnected(ghostId, secretKey, existing.displayLabel ?? existing.label);
+ this.notifyConnected(instanceKey, secretKey, existing.displayLabel ?? existing.label);
return {
ok: true,
account: toView(
existing,
manifest.defaultAccountId,
- avatar ?? this.readAvatar(ghostId, secretKey, existing.id),
+ avatar ?? this.readAvatar(instanceKey, secretKey, existing.id),
decl.scopes,
),
};
@@ -1106,7 +1140,7 @@ export class GhostOauthAccountManager {
if (flow.bundle.refreshToken !== null) {
if (
!this.deps.vault.store(
- ghostId,
+ instanceKey,
refreshTokenKey(secretKey, account.id),
flow.bundle.refreshToken,
)
@@ -1118,26 +1152,25 @@ export class GhostOauthAccountManager {
defaultAccountId: manifest.defaultAccountId ?? account.id,
accounts: [...manifest.accounts, account],
};
- if (!this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(nextManifest))) {
- this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, account.id));
+ if (!this.deps.vault.store(instanceKey, accountsKey(secretKey), JSON.stringify(nextManifest))) {
+ this.deps.vault.remove(instanceKey, refreshTokenKey(secretKey, account.id));
return { ok: false, error: 'VAULT_WRITE_FAILED' };
}
// 头像最后落(清单已是事实源;写失败只是没头像,不回滚账号)。
if (avatar !== null) {
- this.deps.vault.store(ghostId, avatarKey(secretKey, account.id), avatar);
+ this.deps.vault.store(instanceKey, avatarKey(secretKey, account.id), avatar);
}
- this.tokenCache.set(this.cacheKey(ghostId, secretKey, account.id), {
+ this.tokenCache.set(this.cacheKey(instanceKey, secretKey, account.id), {
accessToken: flow.bundle.accessToken,
expiresAt: flow.bundle.expiresAt,
});
- this.deps.logger?.info('ghost oauth 账号已连接', {
- ghostId,
+ this.deps.logger?.info('ghost oauth 账号已连接', { ghostId: instanceKey,
secretKey,
accountId: account.id,
});
opts?.remote?.finish(true);
- this.notifyConnected(ghostId, secretKey, account.displayLabel ?? account.label);
+ this.notifyConnected(instanceKey, secretKey, account.displayLabel ?? account.label);
return {
ok: true,
account: toView(account, nextManifest.defaultAccountId, avatar, decl.scopes),
@@ -1145,17 +1178,16 @@ export class GhostOauthAccountManager {
});
}
- private withMutationLock<T>(ghostId: string, task: () => Promise<T> | T): Promise<T> {
- return this.deps.withMutationLock?.(ghostId, task) ?? Promise.resolve(task());
+ private withMutationLock<T>(instanceKey: string, task: () => Promise<T> | T): Promise<T> {
+ return this.deps.withMutationLock?.(instanceKey, task) ?? Promise.resolve(task());
}
/** 授权成功通知(自兜异常:提示挂了不影响连接结果)。 */
- private notifyConnected(ghostId: string, secretKey: string, label: string | null): void {
+ private notifyConnected(instanceKey: string, secretKey: string, label: string | null): void {
try {
- this.deps.onAccountConnected?.({ ghostId, secretKey, label });
+ this.deps.onAccountConnected?.({ ghostId: instanceKey, secretKey, label });
} catch (err) {
- this.deps.logger?.warn?.('ghost oauth onAccountConnected 通知失败(不影响连接结果)', {
- ghostId,
+ this.deps.logger?.warn?.('ghost oauth onAccountConnected 通知失败(不影响连接结果)', { ghostId: instanceKey,
secretKey,
err: String(err),
});
@@ -1169,16 +1201,15 @@ export class GhostOauthAccountManager {
* 缓存未过期直接回;否则单飞刷新。invalid_grant 标账号 expired 并回
* AUTH_EXPIRED(networkSlot 折叠给意识的错误里不含任何令牌字节)。
*/
- async getFreshAccessToken(
- ghostId: string,
+ async getFreshAccessToken(instanceKey: string,
secretKey: string,
decl: GhostOauthDecl,
accountId?: string,
): Promise<GhostOauthAccessTokenResult> {
- if (decl.tokenBroker !== undefined && !this.isTokenBrokerAuthorized(ghostId)) {
+ if (decl.tokenBroker !== undefined && !this.isTokenBrokerAuthorized(instanceKey)) {
return { ok: false, error: 'BROKER_FORBIDDEN' };
}
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
const resolvedId = accountId ?? manifest.defaultAccountId;
if (!resolvedId) return { ok: false, error: 'NO_ACCOUNT' };
const row = manifest.accounts.find((a) => a.id === resolvedId);
@@ -1189,7 +1220,7 @@ export class GhostOauthAccountManager {
return { ok: false, error: 'AUTH_EXPIRED' };
}
- const key = this.cacheKey(ghostId, secretKey, resolvedId);
+ const key = this.cacheKey(instanceKey, secretKey, resolvedId);
const cached = this.tokenCache.get(key);
if (cached && (cached.expiresAt === null || cached.expiresAt > Date.now())) {
return { ok: true, accessToken: cached.accessToken, accountId: resolvedId };
@@ -1198,9 +1229,11 @@ export class GhostOauthAccountManager {
const inflight = this.refreshInflight.get(key);
if (inflight) return inflight;
- const task = this.refreshAccount(ghostId, secretKey, decl, resolvedId, key).finally(() => {
- this.refreshInflight.delete(key);
- });
+ const generation = this.ghostGeneration(instanceKey);
+ const task = this.refreshAccount(instanceKey, secretKey, decl, resolvedId, key, generation)
+ .finally(() => {
+ if (this.refreshInflight.get(key) === task) this.refreshInflight.delete(key);
+ });
this.refreshInflight.set(key, task);
return task;
}
@@ -1209,25 +1242,26 @@ export class GhostOauthAccountManager {
* 401 作废通道(networkSlot 上游 401 时调用):丢缓存,下一单强制刷新。
* 与 exchange 引擎的"作废重换整链重试一次"同一套路。
*/
- invalidateAccessToken(ghostId: string, secretKey: string, accountId: string): void {
- this.tokenCache.delete(this.cacheKey(ghostId, secretKey, accountId));
+ invalidateAccessToken(instanceKey: string, secretKey: string, accountId: string): void {
+ this.tokenCache.delete(this.cacheKey(instanceKey, secretKey, accountId));
}
- private async refreshAccount(
- ghostId: string,
+ private async refreshAccount(instanceKey: string,
secretKey: string,
decl: GhostOauthDecl,
accountId: string,
cacheKey: string,
+ generation: number,
): Promise<GhostOauthAccessTokenResult> {
- const config = this.readClientConfig(ghostId, secretKey, decl);
+ const config = this.readClientConfig(instanceKey, secretKey, decl);
if (!config) return { ok: false, error: 'NO_CLIENT_CONFIG' };
- let refreshToken = this.deps.vault.read(ghostId, refreshTokenKey(secretKey, accountId));
+ let refreshToken = this.deps.vault.read(instanceKey, refreshTokenKey(secretKey, accountId));
if (!refreshToken) {
// 无 rt 且缓存已失效:只能重新授权。
- await this.withMutationLock(ghostId, () => {
- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
- this.markExpired(ghostId, secretKey, accountId);
+ await this.withMutationLock(instanceKey, () => {
+ if (this.ghostGeneration(instanceKey) !== generation) return;
+ if (this.deps.isConnectTargetCurrent?.(instanceKey, secretKey, decl) === false) return;
+ this.markExpired(instanceKey, secretKey, accountId);
});
return { ok: false, error: 'AUTH_EXPIRED' };
}
@@ -1236,6 +1270,7 @@ export class GhostOauthAccountManager {
// 多实例共库纪律),探测到新 RT 就换它重试一轮;第二轮仍 invalid_grant
// 才判真失效。
for (let attempt = 0; ; attempt += 1) {
+ if (this.ghostGeneration(instanceKey) !== generation) return { ok: false, error: 'AUTH_EXPIRED' };
const result = await refreshGhostOauthToken({
config,
refreshToken,
@@ -1243,11 +1278,13 @@ export class GhostOauthAccountManager {
broker: this.deps.broker,
logger: this.deps.logger,
});
+ if (this.ghostGeneration(instanceKey) !== generation) return { ok: false, error: 'AUTH_EXPIRED' };
if (result.ok) {
- const committed = await this.withMutationLock(ghostId, () => {
- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return false;
+ const committed = await this.withMutationLock(instanceKey, () => {
+ if (this.ghostGeneration(instanceKey) !== generation) return false;
+ if (this.deps.isConnectTargetCurrent?.(instanceKey, secretKey, decl) === false) return false;
const currentRefreshToken = this.deps.vault.read(
- ghostId,
+ instanceKey,
refreshTokenKey(secretKey, accountId),
);
if (currentRefreshToken !== refreshToken) return false;
@@ -1255,14 +1292,14 @@ export class GhostOauthAccountManager {
if (result.bundle.refreshToken !== null && result.bundle.refreshToken !== refreshToken) {
if (
!this.deps.vault.store(
- ghostId,
+ instanceKey,
refreshTokenKey(secretKey, accountId),
result.bundle.refreshToken,
)
) {
this.deps.logger?.warn(
'ghost oauth 轮换后的新 refresh token 落库失败——新令牌仅存内存,重启后需要重新授权',
- { ghostId, secretKey, accountId },
+ { ghostId: instanceKey, secretKey, accountId },
);
}
}
@@ -1271,18 +1308,19 @@ export class GhostOauthAccountManager {
expiresAt: result.bundle.expiresAt,
});
// 曾标 expired 的账号刷新成功即复活(用户在别处重授权后 rt 又有效的边角)。
- this.markConnected(ghostId, secretKey, accountId);
+ this.markConnected(instanceKey, secretKey, accountId);
return true;
});
- if (!committed) return { ok: false, error: 'AUTH_EXPIRED' };
+ if (!committed || this.ghostGeneration(instanceKey) !== generation) return { ok: false, error: 'AUTH_EXPIRED' };
// 展示名/头像回填(fire-and-forget,不拖累令牌热路径):displayTemplate /
// avatarPath 上线前连的老账号缺这些,借下一次令牌刷新顺路补上,无需重连。
void this.backfillIdentityExtras(
- ghostId,
+ instanceKey,
secretKey,
decl,
accountId,
result.bundle.accessToken,
+ generation,
);
return { ok: true, accessToken: result.bundle.accessToken, accountId };
}
@@ -1296,15 +1334,16 @@ export class GhostOauthAccountManager {
if (attempt === 0) {
const rotated = await this.readRotatedRefreshToken(
- ghostId,
+ instanceKey,
secretKey,
accountId,
refreshToken,
+ generation,
);
if (rotated !== null) {
this.deps.logger?.info(
'ghost oauth invalid_grant 后检测到 refresh token 已被其它实例轮换,用新令牌重试',
- { ghostId, secretKey, accountId },
+ { ghostId: instanceKey, secretKey, accountId },
);
refreshToken = rotated;
continue;
@@ -1313,14 +1352,15 @@ export class GhostOauthAccountManager {
// 真失效:标 expired 引导重新授权。删除走 compare-and-delete——只删
// 仍等于自己最后用过的这枚;若期间有并发实例写入了更新的 RT,留给它。
- await this.withMutationLock(ghostId, () => {
+ await this.withMutationLock(instanceKey, () => {
+ if (this.ghostGeneration(instanceKey) !== generation) return;
// 插件可能在 provider 请求期间换版。旧声明的 invalid_grant 不得
// 删除为包事务保留的旧 client token。
- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
- this.markExpired(ghostId, secretKey, accountId);
- const current = this.deps.vault.read(ghostId, refreshTokenKey(secretKey, accountId));
+ if (this.deps.isConnectTargetCurrent?.(instanceKey, secretKey, decl) === false) return;
+ this.markExpired(instanceKey, secretKey, accountId);
+ const current = this.deps.vault.read(instanceKey, refreshTokenKey(secretKey, accountId));
if (current === refreshToken) {
- this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, accountId));
+ this.deps.vault.remove(instanceKey, refreshTokenKey(secretKey, accountId));
}
this.tokenCache.delete(cacheKey);
});
@@ -1333,19 +1373,21 @@ export class GhostOauthAccountManager {
* (并发赢家的成功响应可能还在落库路上)再读一次。返回已轮换的新 RT,或
* null(确认未轮换,invalid_grant 是真失效)。
*/
- private async readRotatedRefreshToken(
- ghostId: string,
+ private async readRotatedRefreshToken(instanceKey: string,
secretKey: string,
accountId: string,
usedRefreshToken: string,
+ generation: number,
): Promise<string | null> {
+ if (this.ghostGeneration(instanceKey) !== generation) return null;
const key = refreshTokenKey(secretKey, accountId);
- const immediate = this.deps.vault.read(ghostId, key);
+ const immediate = this.deps.vault.read(instanceKey, key);
if (immediate !== null && immediate !== usedRefreshToken) return immediate;
const sleep =
this.deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
await sleep(GHOST_OAUTH_INVALID_GRANT_RECHECK_DELAY_MS);
- const delayed = this.deps.vault.read(ghostId, key);
+ if (this.ghostGeneration(instanceKey) !== generation) return null;
+ const delayed = this.deps.vault.read(instanceKey, key);
if (delayed !== null && delayed !== usedRefreshToken) return delayed;
return null;
}
@@ -1356,25 +1398,26 @@ export class GhostOauthAccountManager {
* 拉一次身份端点补上。best-effort——任何失败静默放弃(下次刷新再试),
* 绝不影响令牌获取结果。
*/
- private async backfillIdentityExtras(
- ghostId: string,
+ private async backfillIdentityExtras(instanceKey: string,
secretKey: string,
decl: GhostOauthDecl,
accountId: string,
accessToken: string,
+ generation: number,
): Promise<void> {
try {
+ if (this.ghostGeneration(instanceKey) !== generation) return;
if (decl.identity === undefined) return;
const template = decl.identity.displayTemplate;
- const before = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ const before = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
const row = before.accounts.find((a) => a.id === accountId);
if (!row) return;
const needDisplay = template !== undefined && row.displayLabel === null;
// 头像回填同样只对第一方官方意识放行(connectAccount 处的 SSRF 口径)。
const needAvatar =
decl.identity.avatarPath !== undefined &&
- isFirstPartyHostPrivilegeGhostId(ghostId) &&
- this.readAvatar(ghostId, secretKey, accountId) === null;
+ this.deps.isHostPrimitiveAuthorized?.(instanceKey) === true &&
+ this.readAvatar(instanceKey, secretKey, accountId) === null;
if (!needDisplay && !needAvatar) return;
const identity = await fetchGhostOauthIdentity({
url: decl.identity.url,
@@ -1384,34 +1427,37 @@ export class GhostOauthAccountManager {
accessToken,
fetchImpl: this.deps.fetchImpl,
});
+ if (this.ghostGeneration(instanceKey) !== generation) return;
if (needDisplay && identity.display !== null) {
// 拉取期间清单可能被并发写(断开/设默认/新连接):用 patchAccount 做
// 定向字段写入——只改目标行的 displayLabel/label,不覆盖清单其它状态。
- await this.withMutationLock(ghostId, () => {
- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
- this.patchAccount(ghostId, secretKey, accountId, (fresh) => {
+ await this.withMutationLock(instanceKey, () => {
+ if (this.ghostGeneration(instanceKey) !== generation) return;
+ if (this.deps.isConnectTargetCurrent?.(instanceKey, secretKey, decl) === false) return;
+ this.patchAccount(instanceKey, secretKey, accountId, (fresh) => {
if (fresh.displayLabel !== null) return false;
fresh.displayLabel = identity.display;
if (fresh.label === null && identity.label !== null) fresh.label = identity.label;
return true;
});
});
- this.deps.logger?.info('ghost oauth 账号展示名已回填', { ghostId, secretKey, accountId });
+ this.deps.logger?.info('ghost oauth 账号展示名已回填', { ghostId: instanceKey, secretKey, accountId });
}
if (needAvatar && identity.avatarUrl !== null) {
+ if (this.ghostGeneration(instanceKey) !== generation) return;
const avatar = await fetchGhostOauthAvatar({
url: identity.avatarUrl,
fetchImpl: this.deps.fetchImpl,
});
// 存前重验账号仍在清单(拉取期间可能被断开;断开后不再写孤儿头像键)。
if (avatar !== null) {
- await this.withMutationLock(ghostId, () => {
- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
- const fresh = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ await this.withMutationLock(instanceKey, () => {
+ if (this.ghostGeneration(instanceKey) !== generation) return;
+ if (this.deps.isConnectTargetCurrent?.(instanceKey, secretKey, decl) === false) return;
+ const fresh = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
if (fresh.accounts.some((a) => a.id === accountId)) {
- this.deps.vault.store(ghostId, avatarKey(secretKey, accountId), avatar);
- this.deps.logger?.info('ghost oauth 账号头像已回填', {
- ghostId,
+ this.deps.vault.store(instanceKey, avatarKey(secretKey, accountId), avatar);
+ this.deps.logger?.info('ghost oauth 账号头像已回填', { ghostId: instanceKey,
secretKey,
accountId,
});
@@ -1420,8 +1466,7 @@ export class GhostOauthAccountManager {
}
}
} catch (err) {
- this.deps.logger?.warn('ghost oauth 展示名/头像回填失败(不影响令牌获取)', {
- ghostId,
+ this.deps.logger?.warn('ghost oauth 展示名/头像回填失败(不影响令牌获取)', { ghostId: instanceKey,
secretKey,
accountId,
err: String(err),
@@ -1434,35 +1479,34 @@ export class GhostOauthAccountManager {
* mutator 返回 true 表示有改动需落盘,false/undefined = 无需写回。
* 读→改→写之间无 yield(同步),单线程 JS 保证无并发插入。
*/
- private patchAccount(
- ghostId: string,
+ private patchAccount(instanceKey: string,
secretKey: string,
accountId: string,
mutator: (row: AccountRow) => boolean | undefined,
): boolean {
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
+ const manifest = parseManifest(this.deps.vault.read(instanceKey, accountsKey(secretKey)));
const row = manifest.accounts.find((a) => a.id === accountId);
if (!row || !mutator(row)) return false;
- return this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest));
+ return this.deps.vault.store(instanceKey, accountsKey(secretKey), JSON.stringify(manifest));
}
- private markExpired(ghostId: string, secretKey: string, accountId: string): void {
- const changed = this.patchAccount(ghostId, secretKey, accountId, (row) => {
+ private markExpired(instanceKey: string, secretKey: string, accountId: string): void {
+ const changed = this.patchAccount(instanceKey, secretKey, accountId, (row) => {
if (row.status === 'expired') return false;
row.status = 'expired';
return true;
});
- if (changed) this.notifyStatusChanged(ghostId, secretKey, 'expired');
+ if (changed) this.notifyStatusChanged(instanceKey, secretKey, 'expired');
}
- private clearCachedTokens(ghostId: string, secretKey: string): void {
+ private clearCachedTokens(instanceKey: string, secretKey: string): void {
for (const key of this.tokenCache.keys()) {
- if (key.startsWith(`${ghostId} ${secretKey} `)) this.tokenCache.delete(key);
+ if (key.startsWith(`${instanceKey} ${secretKey} `)) this.tokenCache.delete(key);
}
}
- private markConnected(ghostId: string, secretKey: string, accountId: string): void {
- const changed = this.patchAccount(ghostId, secretKey, accountId, (row) => {
+ private markConnected(instanceKey: string, secretKey: string, accountId: string): void {
+ const changed = this.patchAccount(instanceKey, secretKey, accountId, (row) => {
if (row.status === 'connected' && row.expiredReason === undefined) return false;
row.status = 'connected';
delete row.expiredReason;
@@ -1470,19 +1514,17 @@ export class GhostOauthAccountManager {
delete row.expiredForClientId;
return true;
});
- if (changed) this.notifyStatusChanged(ghostId, secretKey, 'connected');
+ if (changed) this.notifyStatusChanged(instanceKey, secretKey, 'connected');
}
- private notifyStatusChanged(
- ghostId: string,
+ private notifyStatusChanged(instanceKey: string,
secretKey: string,
status: GhostOauthAccountStatus,
): void {
try {
- this.deps.onAccountStatusChanged?.({ ghostId, secretKey, status });
+ this.deps.onAccountStatusChanged?.({ ghostId: instanceKey, secretKey, status });
} catch (err) {
- this.deps.logger?.warn?.('ghost oauth onAccountStatusChanged 通知失败(不影响状态写入)', {
- ghostId,
+ this.deps.logger?.warn?.('ghost oauth onAccountStatusChanged 通知失败(不影响状态写入)', { ghostId: instanceKey,
secretKey,
status,
err: String(err),
@@ -1490,7 +1532,7 @@ export class GhostOauthAccountManager {
}
}
- private cacheKey(ghostId: string, secretKey: string, accountId: string): string {
- return `${ghostId} ${secretKey} ${accountId}`;
+ private cacheKey(instanceKey: string, secretKey: string, accountId: string): string {
+ return `${instanceKey} ${secretKey} ${accountId}`;
}
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts b/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts
index 34d8bca2cd..b69dc6dc13 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts
@@ -1,8 +1,8 @@
/**
* ghostOauthBroker.ts — tokenBroker 声明的 XDT server 授权 broker 调用器。
* ---------------------------------------------------------------------------
- * oauth 详单声明 `tokenBroker: "<slug>"` 的意识。静态官方前缀照旧放行;
- * 其余资格由装入来源与当前组织事实共同判定。校验层保持纯函数不感知装入语境,
+ * oauth 详单声明 `tokenBroker: "<slug>"` 的意识。资格按可信安装事实判定,
+ * 名称前缀不放行。校验层保持纯函数不感知装入语境,
* 门控在装入闸与连接闸。符合资格后,code 换 token 与 refresh 不直连服务商
* tokenUrl,改经 XDT server
* 的授权 broker 端点(`/api/integrations/<slug>/oauth/exchange|refresh`,JWT
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts
index 16fc3ebbe7..d1d3aae42a 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts
@@ -76,9 +76,8 @@ export interface GhostOauthClientConfig {
/**
* 可选:XDT server token broker 的 provider slug(如 'jira')。声明后
* code 换 token 与 refresh 不直连 tokenUrl,改经注入的 broker 调用器
- * (client secret 在服务端,不随包分发)。静态官方前缀照旧放行;其余资格由装入
- * 来源与当前组织事实共同判定。校验层保持纯函数不感知装入语境,门控在运行时
- * 接线层。broker 模式兼容
+ * (client secret 在服务端,不随包分发)。资格按可信安装事实判定,名称前缀不放行。
+ * 校验层保持纯函数不感知装入语境,门控在运行时接线层。broker 模式兼容
* PKCE(pkce 缺省开):verifier 经 broker
* exchange 透传到服务端,由 provider 决定是否消费(feishu 要、jira/slack
* 显式声明 pkce:false)。
diff --git a/apps/desktop/src/main/cindy-brain/ghostPreferenceRelocation.ts b/apps/desktop/src/main/cindy-brain/ghostPreferenceRelocation.ts
new file mode 100644
index 0000000000..863fa55a59
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostPreferenceRelocation.ts
@@ -0,0 +1,88 @@
+import {
+ activeOwnerScopeKey,
+ isAppSessionBoundaryPending,
+ ownerScopedUserDataPath,
+} from '../appSessionState.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
+
+const log = desktopMakerLogger.child('ghost-preference-relocation');
+const relocatingFiles = new Set<string>();
+
+export function assertGhostPrefsWritable(fileName: string): void {
+ if (relocatingFiles.has(ownerScopedUserDataPath(fileName))) {
+ throw new Error(fileName + ' preferences are relocating');
+ }
+}
+
+export async function updateGhostPrefsForRelocation(
+ fileName: string,
+ updater: (raw: Record<string, unknown>) => Record<string, unknown>,
+ onSettled?: () => void,
+): Promise<void> {
+ if (isAppSessionBoundaryPending()) throw new Error('ghost preferences owner scope is changing');
+ assertGhostPrefsWritable(fileName);
+ const file = ownerScopedUserDataPath(fileName);
+ relocatingFiles.add(file);
+ try {
+ const relocationStore = createOverrideSettingsFile<Record<string, unknown>>({
+ filePath: () => ownerScopedUserDataPath(fileName),
+ scopeKey: activeOwnerScopeKey,
+ defaults: {},
+ normalize: (raw) => raw as Record<string, unknown>,
+ preserveUnreadableFile: true,
+ logLoadedValue: false,
+ logReadErrorDetails: false,
+ log,
+ label: fileName,
+ });
+ await relocationStore.updateAtomic(({ value }) => {
+ if (isAppSessionBoundaryPending()) throw new Error('ghost preferences owner scope is changing');
+ return updater(value);
+ }, { preserveDefaults: true });
+ } finally {
+ try {
+ onSettled?.();
+ } finally {
+ relocatingFiles.delete(file);
+ }
+ }
+}
+
+export async function relocateGhostPreferenceMaps(
+ fileName: string,
+ mapNames: readonly string[],
+ from: string,
+ to: string,
+ onSettled?: () => void,
+): Promise<void> {
+ if (from === to) return;
+ await updateGhostPrefsForRelocation(fileName, (raw) => {
+ const maps = mapNames.map((name) => {
+ const value = raw[name];
+ if (value !== undefined && (value === null || typeof value !== 'object' || Array.isArray(value))) {
+ throw new Error(`${fileName} ${name} is unreadable`);
+ }
+ return { name, value: (value ?? {}) as Record<string, unknown> };
+ });
+ const matches = (name: string, key: string, id: string) =>
+ key === id || (name === 'sessions' && key.startsWith(`${id}#`));
+ if (!maps.some(({ name, value }) => Object.keys(value).some((key) => matches(name, key, from)))) {
+ return {};
+ }
+ if (maps.some(({ name, value }) => Object.keys(value).some((key) => matches(name, key, to)))) {
+ throw new Error(`${fileName} relocation destination collision`);
+ }
+ const patch: Record<string, unknown> = {};
+ for (const { name, value } of maps) {
+ const next = { ...value };
+ for (const key of Object.keys(value)) {
+ if (!matches(name, key, from)) continue;
+ next[`${to}${key.slice(from.length)}`] = value[key];
+ delete next[key];
+ }
+ if (Object.keys(value).some((key) => matches(name, key, from))) patch[name] = next;
+ }
+ return patch;
+ }, onSettled);
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostRecentUsageStore.ts b/apps/desktop/src/main/cindy-brain/ghostRecentUsageStore.ts
index e56d6c1667..d9492eb573 100644
--- a/apps/desktop/src/main/cindy-brain/ghostRecentUsageStore.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostRecentUsageStore.ts
@@ -8,7 +8,7 @@
import Store from 'electron-store';
-import { isValidGhostId } from '../../shared/ghost.js';
+import { isArchiveInstanceKey, isGhostInstanceId } from '../../shared/pluginIdentity.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
interface GhostRecentUsageShape {
@@ -41,7 +41,11 @@ export function normalizeGhostRecentIds(value: unknown): string[] {
const seen = new Set<string>();
const ids: string[] = [];
for (const candidate of value) {
- if (typeof candidate !== 'string' || !isValidGhostId(candidate) || seen.has(candidate)) {
+ if (
+ typeof candidate !== 'string' ||
+ (!isGhostInstanceId(candidate) && !isArchiveInstanceKey(candidate)) ||
+ seen.has(candidate)
+ ) {
continue;
}
seen.add(candidate);
@@ -71,3 +75,25 @@ export function forgetGhostRecentUsage(id: string): string[] {
getStore().set('ids', next);
return next;
}
+
+/** Rename one history entry when its instance is archived. Order is preserved. */
+export function relocateGhostRecentUsage(fromId: string, toId: string): void {
+ if (fromId === toId) return;
+ if (
+ (!isGhostInstanceId(fromId) && !isArchiveInstanceKey(fromId)) ||
+ (!isGhostInstanceId(toId) && !isArchiveInstanceKey(toId))
+ ) {
+ throw new Error('Invalid plugin identity');
+ }
+ const ids = loadGhostRecentIds();
+ if (!ids.includes(fromId)) return;
+ const next: string[] = [];
+ const seen = new Set<string>();
+ for (const id of ids) {
+ const renamed = id === fromId ? toId : id;
+ if (seen.has(renamed)) continue;
+ seen.add(renamed);
+ next.push(renamed);
+ }
+ getStore().set('ids', next);
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostRecommendationSnapshot.ts b/apps/desktop/src/main/cindy-brain/ghostRecommendationSnapshot.ts
index cd56595674..853846a3b6 100644
--- a/apps/desktop/src/main/cindy-brain/ghostRecommendationSnapshot.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostRecommendationSnapshot.ts
@@ -1,6 +1,7 @@
import type { InstalledGhost } from '../../shared/ghost.js';
import type { HomePluginRecommendationsSnapshot } from '../../shared/homePluginRecommendations.js';
import { validateGhostRecommendations, type GhostRecommendation } from '@cindy/plugin-protocol';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
export function buildGhostRecommendationSnapshot(
ownerId: string | null,
@@ -9,14 +10,15 @@ export function buildGhostRecommendationSnapshot(
recentIds: string[],
): HomePluginRecommendationsSnapshot {
const sources = ghosts.map((g) => {
+ const instanceId = installedGhostStoragePart(g);
// Keep legacy manifest/receipt content intact; invalid optional metadata must not disable a plugin.
const candidates =
- entries.find((e) => e.id === g.manifest.id)?.items ?? g.manifest.recommendations;
+ entries.find((e) => e.id === instanceId)?.items ?? g.manifest.recommendations;
const validated =
candidates === undefined ? undefined : validateGhostRecommendations(candidates);
const items = validated?.ok ? validated.items : undefined;
return {
- ghostId: g.manifest.id,
+ ghostId: instanceId,
name: g.manifest.name,
enabled: g.enabled,
...(items !== undefined ? { items } : {}),
diff --git a/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.ts b/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.ts
index 75004f2078..dc1ecc9313 100644
--- a/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostRecommendationStore.ts
@@ -1,7 +1,7 @@
import Store from 'electron-store';
import { validateGhostRecommendations, type GhostRecommendation } from '@cindy/plugin-protocol';
import { ownerScopedUserDataPath } from '../appSessionState.js';
-import { isValidGhostId } from '../../shared/ghost.js';
+import { isArchiveInstanceKey, isGhostInstanceId } from '../../shared/pluginIdentity.js';
interface Entry {
id: string;
@@ -33,7 +33,8 @@ export function readGhostRecommendationEntries(): Entry[] {
const raw: unknown = store().get('entries');
if (!Array.isArray(raw)) return [];
return raw.flatMap((entry): Entry[] => {
- if (!entry || !isValidGhostId(entry.id)) return [];
+ if (!entry || typeof entry.id !== 'string' ||
+ (!isGhostInstanceId(entry.id) && !isArchiveInstanceKey(entry.id))) return [];
const parsed =
entry.items === undefined ? undefined : validateGhostRecommendations(entry.items);
return [
@@ -52,7 +53,7 @@ export function readGhostRecommendationEntries(): Entry[] {
}
function update(id: string, patch: Partial<Entry>): void {
- if (!isValidGhostId(id)) throw new Error('Invalid plugin identity');
+ if (!isGhostInstanceId(id) && !isArchiveInstanceKey(id)) throw new Error('Invalid plugin identity');
const entries = readGhostRecommendationEntries();
const previous = entries.find((e) => e.id === id);
store().set('entries', [...entries.filter((e) => e.id !== id), { ...previous, ...patch, id }]);
@@ -96,3 +97,24 @@ export function forgetGhostRecommendations(id: string): void {
readGhostRecommendationEntries().filter((e) => e.id !== id),
);
}
+
+function isStoredPluginIdentity(id: string): boolean {
+ return isGhostInstanceId(id) || isArchiveInstanceKey(id);
+}
+
+/** Move publisher recommendations onto the archived instance key. */
+export function relocateGhostRecommendations(fromId: string, toId: string): void {
+ if (fromId === toId) return;
+ if (!isStoredPluginIdentity(fromId) || !isStoredPluginIdentity(toId)) {
+ throw new Error('Invalid plugin identity');
+ }
+ const entries = readGhostRecommendationEntries();
+ if (!entries.some((entry) => entry.id === fromId)) return;
+ if (entries.some((entry) => entry.id === toId)) {
+ throw new Error('recommendation destination already exists');
+ }
+ store().set(
+ 'entries',
+ entries.map((entry) => (entry.id === fromId ? { ...entry, id: toId } : entry)),
+ );
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
index b47803575e..819a8865bb 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
@@ -37,6 +37,7 @@ export type GhostSetupEnsureResult =
| 'GHOST_RETIRED'
| 'GHOST_ASLEEP'
| 'GHOST_DISABLED_IN_WORKDIR'
+ | 'GHOST_AMBIGUOUS'
| 'TOOL_NOT_FOUND';
message: string;
setup?: GhostSetupAssessment;
@@ -47,8 +48,14 @@ export type GhostSetupTargetValidation =
| {
ok: false;
errorCode:
- 'GHOST_NOT_FOUND' | 'GHOST_ASLEEP' | 'GHOST_DISABLED_IN_WORKDIR' | 'GHOST_RETIRED' | 'TOOL_NOT_FOUND';
+ | 'GHOST_NOT_FOUND'
+ | 'GHOST_RETIRED'
+ | 'GHOST_ASLEEP'
+ | 'GHOST_DISABLED_IN_WORKDIR'
+ | 'GHOST_AMBIGUOUS'
+ | 'TOOL_NOT_FOUND';
message: string;
+ candidates?: Array<{ ghostId: string; namespace: string | null }>;
};
export type GhostSetupActionResult =
@@ -82,6 +89,7 @@ export interface GhostSetupInlineActionInput {
}
export interface GhostSetupCoordinatorDeps {
+ getTargetToken?: (ghostId: string) => string | null;
remoteConnection?: true;
changeBus: GhostSetupChangeBus;
bridge: GhostSetupInteractionBridge;
@@ -101,6 +109,7 @@ export interface GhostSetupCoordinatorDeps {
ghostId: string;
action: GhostSetupAllowedAction;
responseTarget?: GhostSetupInteractionResponseTarget;
+ assertCurrent?: () => void;
}) => Promise<GhostSetupActionResult>;
executeInlineAction?: (args: GhostSetupInlineActionInput) => Promise<GhostSetupActionResult>;
timeoutMs?: number;
@@ -110,6 +119,8 @@ export interface GhostSetupCoordinatorDeps {
logger?: {
warn: (message: string, context?: Record<string, unknown>) => void;
};
+ /** Map MCP/logical ghostId onto the credential/store instance id. */
+ resolveStoreId?: (ghostId: string) => string;
}
export interface GhostSetupEnsureRequest {
@@ -153,17 +164,24 @@ export class GhostSetupCoordinator {
ok: false, errorCode: 'SETUP_CANCELLED', message: 'Plugin setup was cancelled; no plugin operation was executed.',
});
if (request.signal?.aborted) return cancelled();
+ const expectedTarget = this.deps.getTargetToken?.(request.ghostId);
+ const isTargetCurrent = () => !this.deps.getTargetToken ||
+ (expectedTarget != null && this.deps.getTargetToken(request.ghostId) === expectedTarget);
+ const validateTarget = (): GhostSetupTargetValidation => isTargetCurrent()
+ ? this.deps.validateTarget(request.ghostId, request.tool, request.workingDir)
+ : { ok: false, errorCode: 'GHOST_NOT_FOUND', message: 'Plugin installation changed; open a new setup request.' };
let assessment: GhostSetupAssessment;
let unsubscribe = () => {};
let wakeVerify: (() => void) | null = null;
let assessmentDirty = false;
const reconnectedActions = new Set<string>();
let localConnectionAction: { id: string; ref: string; revision: number } | undefined;
+ const storeId = this.deps.resolveStoreId?.(request.ghostId) ?? request.ghostId;
// Subscribe before the initial read. A committed settings write racing the
// first assessment will then keep the read loop running until one complete
// assessment observes a quiet revision.
- unsubscribe = this.deps.changeBus.subscribe(request.ghostId, event => {
+ unsubscribe = this.deps.changeBus.subscribe(storeId, event => {
if (localConnectionAction && event.source === 'connection' && event.ref === localConnectionAction.ref &&
event.revision > localConnectionAction.revision) {
reconnectedActions.add(localConnectionAction.id);
@@ -178,13 +196,13 @@ export class GhostSetupCoordinator {
> => {
for (;;) {
assessmentDirty = false;
- const startRevision = this.deps.changeBus.currentRevision(request.ghostId);
- const target = this.deps.validateTarget(request.ghostId, request.tool, request.workingDir);
+ const startRevision = this.deps.changeBus.currentRevision(storeId);
+ const target = validateTarget();
if (!target.ok) return { ok: false, target };
const next = await this.deps.assess(request.ghostId);
if (
!assessmentDirty &&
- this.deps.changeBus.currentRevision(request.ghostId) === startRevision
+ this.deps.changeBus.currentRevision(storeId) === startRevision
) {
return { ok: true, assessment: next };
}
@@ -391,7 +409,7 @@ export class GhostSetupCoordinator {
await verify();
return;
}
- const target = this.deps.validateTarget(request.ghostId, request.tool, request.workingDir);
+ const target = validateTarget();
if (!target.ok) {
settleTargetFailure(target);
return;
@@ -417,7 +435,8 @@ export class GhostSetupCoordinator {
? `session:${sessionId}:target:${responseTarget.id}`
: `session:${sessionId}`;
const flightKey = `${request.ghostId}\u0000${action.id}\u0000${flightScope}`;
- let flight = this.actionFlights.get(flightKey);
+ const targetFlightKey = JSON.stringify([flightKey, expectedTarget]);
+ let flight = this.actionFlights.get(targetFlightKey);
if (!flight) {
flight = this.trackAction(
this.deps
@@ -426,10 +445,13 @@ export class GhostSetupCoordinator {
ghostId: request.ghostId,
action,
...(responseTarget ? { responseTarget } : {}),
+ assertCurrent: () => {
+ if (!validateTarget().ok) throw new Error('PLUGIN_SETUP_TARGET_STALE');
+ },
})
- .finally(() => this.actionFlights.delete(flightKey)),
+ .finally(() => this.actionFlights.delete(targetFlightKey)),
);
- this.actionFlights.set(flightKey, flight);
+ this.actionFlights.set(targetFlightKey, flight);
}
let result: GhostSetupActionResult;
try {
@@ -500,7 +522,7 @@ export class GhostSetupCoordinator {
await verify();
return;
}
- const target = this.deps.validateTarget(request.ghostId, request.tool, request.workingDir);
+ const target = validateTarget();
if (!target.ok) {
settleTargetFailure(target);
return;
@@ -523,7 +545,7 @@ export class GhostSetupCoordinator {
if (settled || committed || request.signal?.aborted || !inlineSubmitting ||
activeActionId !== action.id || ghostId !== request.ghostId ||
actionId !== action.id || requirementRef !== boundItem.ref ||
- !this.deps.validateTarget(request.ghostId, request.tool, request.workingDir).ok) {
+ !validateTarget().ok) {
throw new Error('PLUGIN_SETUP_INLINE_STALE');
}
},
@@ -583,7 +605,7 @@ export class GhostSetupCoordinator {
reconnectedActions.add(actionId);
assessmentDirty = true;
void verify();
- });
+ }, isTargetCurrent);
} catch (error) {
settle(this.internalFailure('插件设置卡片打开失败', error), 'open-failed', 0);
return;
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
index af91b96523..7906f88c30 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
@@ -115,6 +115,7 @@ interface PendingSetupInteraction {
) => Promise<void> | void;
onInlineSubmit?: (submit: GhostSetupInlineSubmit) => Promise<void> | void;
onConnectionCommitted?: (actionId: string) => void;
+ isTargetCurrent?: () => boolean;
}
export class GhostSetupInteractionBridge {
@@ -128,6 +129,7 @@ export class GhostSetupInteractionBridge {
onCommand: PendingSetupInteraction['onCommand'],
onInlineSubmit?: PendingSetupInteraction['onInlineSubmit'],
onConnectionCommitted?: PendingSetupInteraction['onConnectionCommitted'],
+ isTargetCurrent?: PendingSetupInteraction['isTargetCurrent'],
): void {
if (this.pending.has(snapshot.requestId)) {
throw new Error(`plugin setup interaction already exists: ${snapshot.requestId}`);
@@ -139,6 +141,7 @@ export class GhostSetupInteractionBridge {
onCommand,
...(onInlineSubmit ? { onInlineSubmit } : {}),
...(onConnectionCommitted ? { onConnectionCommitted } : {}),
+ ...(isTargetCurrent ? { isTargetCurrent } : {}),
});
try {
this.broadcastSnapshot(sessionId, snapshot);
@@ -186,7 +189,7 @@ export class GhostSetupInteractionBridge {
*/
submitInline(requestId: string, rawSubmit: unknown): boolean {
const entry = this.pending.get(requestId);
- if (!entry || entry.completed) return false;
+ if (!entry || entry.completed || entry.isTargetCurrent?.() === false) return false;
const submit = parseGhostSetupInlineSubmit(rawSubmit);
if (!submit || !entry.onInlineSubmit) {
this.deps.logger?.warn('plugin setup interaction received invalid inline submission', {
@@ -207,7 +210,8 @@ export class GhostSetupInteractionBridge {
connectionCommitted(requestId: string, actionId: string, expectedRevision: number): boolean {
const entry = this.pending.get(requestId);
if (!entry || entry.completed || entry.snapshot.terminal ||
- entry.snapshot.revision !== expectedRevision || !entry.onConnectionCommitted) return false;
+ entry.snapshot.revision !== expectedRevision || !entry.onConnectionCommitted ||
+ entry.isTargetCurrent?.() === false) return false;
const step = entry.snapshot.steps.find(step => step.action?.id === actionId &&
step.action.kind === 'manage_connection' && (step.phase === 'pending' || step.phase === 'failed'));
if (!step) return false;
@@ -293,7 +297,8 @@ export class GhostSetupInteractionBridge {
}> {
return Array.from(this.pending.values())
.filter(
- (entry) => !entry.completed && (sessionId === undefined || entry.sessionId === sessionId),
+ (entry) => !entry.completed && entry.isTargetCurrent?.() !== false &&
+ (sessionId === undefined || entry.sessionId === sessionId),
)
.map((entry) => ({ sessionId: entry.sessionId, request: entry.snapshot }));
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupManifestTracker.ts b/apps/desktop/src/main/cindy-brain/ghostSetupManifestTracker.ts
index 76e492e24b..ebac1395a1 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupManifestTracker.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupManifestTracker.ts
@@ -3,10 +3,11 @@
*
* GhostManager and builtin reconciliation both publish full snapshots. This
* tracker turns those broad broadcasts into one revision-only change event
- * per plugin whose manifest, enabled state, or session availability changed.
+ * per plugin whose manifest, approval, enabled state, or session availability changed.
*/
import type { InstalledGhost } from '../../shared/ghost.js';
+import { installedGhostStoragePart, installedGhostMutationTargetToken } from '../../shared/pluginIdentity.js';
import type { GhostSetupChangeBus } from './ghostSetupChangeBus.js';
export class GhostSetupManifestTracker {
@@ -41,11 +42,12 @@ export class GhostSetupManifestTracker {
private snapshot(ghosts: InstalledGhost[]): Map<string, string> {
return new Map(
ghosts.map((ghost) => [
- ghost.manifest.id,
+ installedGhostStoragePart(ghost),
JSON.stringify({
enabled: ghost.enabled,
- available: this.isAvailable(ghost.manifest.id),
+ available: this.isAvailable(installedGhostStoragePart(ghost)),
manifest: ghost.manifest,
+ target: installedGhostMutationTargetToken(ghost, ''),
}),
]),
);
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
index 7484845c0e..a1fdbfd2b7 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
@@ -37,7 +37,8 @@ import type {
GhostSetupStatus,
GhostSetupStatusItem,
} from '../../shared/ghost.js';
-import { GHOST_SECRET_VALUE_MAX_CHARS, isValidGhostId } from '../../shared/ghost.js';
+import { GHOST_SECRET_VALUE_MAX_CHARS } from '../../shared/ghost.js';
+import { isGhostInstanceId } from '../../shared/pluginIdentity.js';
import { throwIpcError } from '../utils/ipcValidate.js';
/** OAuth 凭证的分项状态(index.ts 由 GhostOauthAccountManager 现查)。 */
@@ -393,7 +394,7 @@ export function handleGhostSetupStatusRequest(args: {
probesFor: (manifest: GhostManifest) => GhostSetupProbes;
}): GhostSetupStatus {
const { id } = args;
- if (typeof id !== 'string' || !isValidGhostId(id)) {
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) {
throwIpcError('INVALID_PARAMS', 'id must be a valid Ghost id');
}
const manifest = args.getRuntimeManifest(id);
diff --git a/apps/desktop/src/main/cindy-brain/ghostSignature.ts b/apps/desktop/src/main/cindy-brain/ghostSignature.ts
index 3915e94e1d..d3da26e6f3 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSignature.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSignature.ts
@@ -14,6 +14,7 @@ import crypto from 'node:crypto';
import JSZip from 'jszip';
+import { authorDeclaredNamespaceReason } from '@cindy/plugin-protocol';
import {
GHOST_MANIFEST_FILE,
type GhostManifest,
@@ -418,7 +419,10 @@ export async function signGhostPackage(
zip.remove(`${prefix}${GHOST_SIGNATURE_FILE}`);
const manifestEntry = zip.file(`${prefix}${GHOST_MANIFEST_FILE}`);
if (!manifestEntry) throw new Error(`缺少 ${GHOST_MANIFEST_FILE}`);
- const validation = validateGhostManifest(JSON.parse(await manifestEntry.async('text')));
+ const rawManifest = JSON.parse(await manifestEntry.async('text'));
+ const reservedNamespace = authorDeclaredNamespaceReason(rawManifest);
+ if (reservedNamespace) throw new Error(reservedNamespace);
+ const validation = validateGhostManifest(rawManifest);
if (!validation.ok) throw new Error(validation.reason);
if (!options.publisherName.trim() || options.publisherName.length > 64) {
throw new Error('publisherName 必须是 1–64 字符');
@@ -461,7 +465,10 @@ export async function reviewGhostPackage(
const manifestEntry = zip.file(`${prefix}${GHOST_MANIFEST_FILE}`);
const signatureEntry = zip.file(`${prefix}${GHOST_SIGNATURE_FILE}`);
if (!manifestEntry || !signatureEntry) throw new Error('审核前必须已有发布者签名');
- const validation = validateGhostManifest(JSON.parse(await manifestEntry.async('text')));
+ const rawManifest = JSON.parse(await manifestEntry.async('text'));
+ const reservedNamespace = authorDeclaredNamespaceReason(rawManifest);
+ if (reservedNamespace) throw new Error(reservedNamespace);
+ const validation = validateGhostManifest(rawManifest);
if (!validation.ok) throw new Error(validation.reason);
const verified = await verifyGhostZipSignatures(zip, prefix, validation.manifest);
if (!verified.ok || !verified.document) {
diff --git a/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts b/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts
index 316f84bdff..699249a912 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts
@@ -105,7 +105,10 @@ async function removeVerifiedDirectory(
|| movedStat.isSymbolicLink()
|| movedStat.dev !== targetStat.dev
|| movedStat.ino !== targetStat.ino
- || !samePath(await fs.promises.realpath(quarantinePath), targetRealPath)
+ || !samePath(
+ await fs.promises.realpath(quarantinePath),
+ path.join(await fs.promises.realpath(path.dirname(quarantinePath)), path.basename(quarantinePath)),
+ )
) {
// Never recursively delete an unverified path. Leave the quarantined
// directory for a later owner-checked cleanup pass.
@@ -115,7 +118,9 @@ async function removeVerifiedDirectory(
// owner-bound parent before recursive deletion; on failure the isolated
// directory is intentionally left for a later guarded cleanup pass.
await verifyParent(expectedParent, workingDir);
- await verifyDirectory(workingDir, parentName);
+ if (!samePath(targetPath, path.join(workingDir, parentName))) {
+ await verifyDirectory(workingDir, parentName);
+ }
await fs.promises.rm(quarantinePath, { recursive: true, force: true });
}
async function copyDirectory(source: string, target: string): Promise<void> {
diff --git a/apps/desktop/src/main/cindy-brain/ghostTrustedXdTarget.ts b/apps/desktop/src/main/cindy-brain/ghostTrustedXdTarget.ts
new file mode 100644
index 0000000000..9fd7a04b3e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostTrustedXdTarget.ts
@@ -0,0 +1,39 @@
+import type { InstalledGhost } from '../../shared/ghost.js';
+import { hasDeliveryNamespace } from '../../shared/pluginIdentity.js';
+import type { GhostFirstPartyFactsLoad } from './ghostFirstPartyFacts.js';
+import {
+ hasTrustedFirstPartySource,
+ marketInstallationMatchesApprovedPackage,
+} from './ghostFirstPartyPrivilege.js';
+
+export function isTrustedXdGhostForScriptTarget(
+ ghost: InstalledGhost,
+ load: GhostFirstPartyFactsLoad,
+ pendingLegacy: boolean,
+): boolean {
+ if (load.kind !== 'ready' || ghost.approval.state !== 'approved') return false;
+ const facts = load.facts;
+ const organization = facts.currentOrganization;
+ if (
+ !organization?.organizationId ||
+ (organization.orgSlug != null && organization.orgSlug !== 'xd') ||
+ facts.ghostId !== ghost.manifest.id ||
+ facts.namespace !== (ghost.namespace ?? null)
+ )
+ return false;
+ if (hasDeliveryNamespace(ghost)) {
+ if (ghost.namespace !== 'xd') return false;
+ } else if (
+ !pendingLegacy ||
+ (organization.orgSlug !== 'xd' && organization.pluginPrefix !== 'xd')
+ )
+ return false;
+ const trustedMarket =
+ facts.marketRecord !== null &&
+ marketInstallationMatchesApprovedPackage(facts.marketRecord, organization);
+ const trustedBuiltin =
+ facts.builtin &&
+ facts.trustedSource?.kind === 'builtin-official' &&
+ hasTrustedFirstPartySource(facts);
+ return trustedMarket || trustedBuiltin;
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts b/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts
index 4db90175af..3673593dbf 100644
--- a/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts
@@ -13,6 +13,7 @@
*/
import type { InstalledGhost } from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
/**
* 该意识当前是否还持有未读角标能力(资格,与启用与否无关)。
@@ -46,7 +47,7 @@ export function selectRevokedGhostUnreadIds(
if (entries.length === 0) return [];
if (ghosts.length === 0 && !rosterAuthoritative) return [];
const stillDeclared = new Set(
- ghosts.filter(ghostDeclaresBadge).map((ghost) => ghost.manifest.id),
+ ghosts.filter(ghostDeclaresBadge).map(installedGhostStoragePart),
);
return entries.map((entry) => entry.ghostId).filter((id) => !stillDeclared.has(id));
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostUnreadStore.ts b/apps/desktop/src/main/cindy-brain/ghostUnreadStore.ts
index e03ce211d8..dbcebcd4f3 100644
--- a/apps/desktop/src/main/cindy-brain/ghostUnreadStore.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostUnreadStore.ts
@@ -13,8 +13,10 @@
*/
import Store from 'electron-store';
+import { assertGhostPrefsWritable, relocateGhostPreferenceMaps } from './ghostPreferenceRelocation.js';
-import { GHOST_BADGE_SUMMARY_MAX_CHARS, isValidGhostId } from '../../shared/ghost.js';
+import { GHOST_BADGE_SUMMARY_MAX_CHARS } from '../../shared/ghost.js';
+import { isGhostInstanceId } from '../../shared/pluginIdentity.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
/** 一条未读记录(ghostId → 最近一次点亮的摘要与时刻)。 */
@@ -36,6 +38,13 @@ const MAX_UNREAD_ENTRIES = 200;
let storeInstance: Store<GhostUnreadShape> | null = null;
let storePath: string | null = null;
+export async function relocateGhostUnread(from: string, to: string): Promise<void> {
+ await relocateGhostPreferenceMaps('ghost-unread.json', ['entries'], from, to, () => {
+ storeInstance = null;
+ storePath = null;
+ });
+}
+
function getStore(): Store<GhostUnreadShape> {
const currentPath = ownerScopedUserDataPath();
if (!storeInstance || storePath !== currentPath) {
@@ -60,7 +69,7 @@ export function normalizeGhostUnreadEntries(value: unknown): GhostUnreadEntry[]
if (typeof value !== 'object' || value === null || Array.isArray(value)) return [];
const entries: GhostUnreadEntry[] = [];
for (const [ghostId, raw] of Object.entries(value as Record<string, unknown>)) {
- if (!isValidGhostId(ghostId)) continue;
+ if (!isGhostInstanceId(ghostId)) continue;
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) continue;
const at = (raw as { at?: unknown }).at;
if (typeof at !== 'number' || !Number.isFinite(at) || at <= 0) continue;
@@ -114,6 +123,7 @@ export function markGhostUnread(
summary: string | undefined,
at: number,
): { entries: GhostUnreadEntry[]; evicted: string[] } {
+ assertGhostPrefsWritable('ghost-unread.json');
const result = applyGhostUnreadMark(loadGhostUnread(), {
ghostId,
...(summary ? { summary } : {}),
@@ -153,6 +163,7 @@ export function applyGhostUnreadMark(
* "看见了哪一条"可言。
*/
export function clearGhostUnread(ghostId: string, seenAt?: number): GhostUnreadEntry[] | null {
+ assertGhostPrefsWritable('ghost-unread.json');
const current = loadGhostUnread();
const entry = current.find((candidate) => candidate.ghostId === ghostId);
if (!entry) return null;
diff --git a/apps/desktop/src/main/cindy-brain/ghostUserDataRelocation.ts b/apps/desktop/src/main/cindy-brain/ghostUserDataRelocation.ts
new file mode 100644
index 0000000000..e06074781b
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostUserDataRelocation.ts
@@ -0,0 +1,81 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+const USER_DATA_PATHS = [
+ ['ghost-kv', '.json'],
+ ['ghost-fs', ''],
+ ['libraries', ''],
+ ['library-staging', ''],
+ ['plugin-downloads', ''],
+] as const;
+
+const USER_DATA_REFERENCES = [
+ 'tasks',
+ 'secrets',
+ 'libraryBinding',
+ 'libraryMeta',
+ 'workdirPreferences',
+ 'cindyPreferences',
+ 'errandPreferences',
+ 'pickedDirectories',
+ 'media',
+ 'cards',
+ 'unread',
+ 'routines',
+ 'recommendations',
+ 'recentUsage',
+] as const;
+
+type RelocateReference = (fromPart: string, toPart: string) => void | Promise<unknown>;
+
+export type GhostUserDataRelocationResources = Record<
+ (typeof USER_DATA_REFERENCES)[number],
+ RelocateReference
+> & {
+ userDataPath: (...parts: string[]) => string;
+ assertCurrent: () => void;
+};
+
+export function ghostUserDataRelocationPaths(
+ fromPart: string,
+ toPart: string,
+ userDataPath: GhostUserDataRelocationResources['userDataPath'],
+): Array<{ from: string; to: string }> {
+ return USER_DATA_PATHS.map(([directory, suffix]) => ({
+ from: userDataPath(directory, fromPart + suffix),
+ to: userDataPath(directory, toPart + suffix),
+ }));
+}
+
+export function assertGhostUserDataPathsCanRelocate(
+ paths: Array<{ from: string; to: string }>,
+): void {
+ for (const move of paths) {
+ if (fs.lstatSync(move.from, { throwIfNoEntry: false }) &&
+ fs.lstatSync(move.to, { throwIfNoEntry: false })) {
+ throw new Error(`relocate destination already exists: ${move.to}`);
+ }
+ }
+}
+
+export async function relocateGhostUserDataResources(
+ fromPart: string,
+ toPart: string,
+ resources: GhostUserDataRelocationResources,
+): Promise<void> {
+ if (fromPart === toPart) return;
+ resources.assertCurrent();
+ const paths = ghostUserDataRelocationPaths(fromPart, toPart, resources.userDataPath);
+ assertGhostUserDataPathsCanRelocate(paths);
+ for (const move of paths) {
+ resources.assertCurrent();
+ if (!fs.lstatSync(move.from, { throwIfNoEntry: false })) continue;
+ fs.mkdirSync(path.dirname(move.to), { recursive: true });
+ fs.renameSync(move.from, move.to);
+ }
+ for (const resource of USER_DATA_REFERENCES) {
+ resources.assertCurrent();
+ await resources[resource](fromPart, toPart);
+ }
+ resources.assertCurrent();
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostVisibility.ts b/apps/desktop/src/main/cindy-brain/ghostVisibility.ts
index 43c81dd294..bff3d349b2 100644
--- a/apps/desktop/src/main/cindy-brain/ghostVisibility.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostVisibility.ts
@@ -9,15 +9,25 @@
* 披露是产品有意接受的取舍,不要重新合并成 GHOST_NOT_FOUND。
*/
-import type { InstalledGhost } from '../../shared/ghost.js';
+import { isValidGhostId, type InstalledGhost } from '../../shared/ghost.js';
+import {
+ findInstalledGhostByInstanceId,
+ formatInstalledGhostAmbiguity,
+ installedGhostStoragePart,
+ installedGhostLogicalIdentity,
+ deliveryNamespaceFields,
+ resolveInstalledGhost,
+ hasDeliveryNamespace,
+} from '../../shared/pluginIdentity.js';
import { t } from '../i18n.js';
export type GhostVisibilityResult =
| { ok: true; ghost: InstalledGhost }
| {
ok: false;
- errorCode: 'GHOST_NOT_FOUND' | 'GHOST_ASLEEP' | 'GHOST_DISABLED_IN_WORKDIR' | 'GHOST_RETIRED';
+ errorCode: 'GHOST_NOT_FOUND' | 'GHOST_ASLEEP' | 'GHOST_DISABLED_IN_WORKDIR' | 'GHOST_RETIRED' | 'GHOST_AMBIGUOUS';
message: string;
+ candidates?: Array<{ ghostId: string; namespace: string | null }>;
};
export interface GhostVisibilityDeps {
@@ -30,16 +40,49 @@ export function classifyGhostVisibility(
ghostId: string,
workdir: string | null,
deps: GhostVisibilityDeps,
+ namespace?: string | null,
): GhostVisibilityResult {
- const ghost = deps.listGhosts().find((candidate) => candidate.manifest.id === ghostId);
- if (!ghost) {
+ const listed = deps.listGhosts();
+ // Agent、用户和深链传来的是逻辑名。裸 ghostId 在多个实例之间必须报歧义,
+ // 不能因为旧 root 的实例键恰好也是这个名字就选中它。
+ // 存储键(_root__helper、_ns__acme__helper)不是合法 ghostId,按实例精确匹配。
+ const byName = namespace !== undefined || isValidGhostId(ghostId);
+ const resolved = byName
+ ? resolveInstalledGhost(listed, ghostId, namespace)
+ : (() => {
+ const ghost = findInstalledGhostByInstanceId(listed, ghostId);
+ return ghost
+ ? { status: 'unique' as const, ghost }
+ : { status: 'missing' as const };
+ })();
+ if (resolved.status === 'missing') {
return {
ok: false,
errorCode: 'GHOST_NOT_FOUND',
message: t('newChat.pluginSetup.targetNotFound'),
};
}
- if (!deps.isAvailableForActiveSession(ghostId)) {
+ if (resolved.status === 'ambiguous') {
+ return {
+ ok: false,
+ errorCode: 'GHOST_AMBIGUOUS',
+ message: formatInstalledGhostAmbiguity(ghostId, resolved.candidates),
+ candidates: resolved.candidates.map((candidate) => ({
+ ghostId: candidate.manifest.id,
+ namespace: hasDeliveryNamespace(candidate) ? candidate.namespace ?? null : null,
+ })),
+ };
+ }
+ return classifyGhostAvailability(resolved.ghost, workdir, deps);
+}
+
+function classifyGhostAvailability(
+ ghost: InstalledGhost,
+ workdir: string | null,
+ deps: GhostVisibilityDeps,
+): GhostVisibilityResult {
+ const instanceId = installedGhostStoragePart(ghost);
+ if (!deps.isAvailableForActiveSession(instanceId)) {
return {
ok: false,
errorCode: 'GHOST_NOT_FOUND',
@@ -51,7 +94,7 @@ export function classifyGhostVisibility(
if (ghost.retirement) {
return { ok: false, errorCode: 'GHOST_RETIRED', message: t('settings.ghosts.retirement.agentNotice') };
}
- if (deps.isDisabledForWorkdir(ghostId, workdir)) {
+ if (deps.isDisabledForWorkdir(instanceId, workdir)) {
return {
ok: false,
errorCode: 'GHOST_DISABLED_IN_WORKDIR',
@@ -67,3 +110,21 @@ export function classifyGhostVisibility(
}
return { ok: true, ghost };
}
+
+export function classifyInstalledGhostVisibility(
+ target: InstalledGhost,
+ workdir: string | null,
+ deps: GhostVisibilityDeps,
+): GhostVisibilityResult {
+ const identity = installedGhostLogicalIdentity(target);
+ const ghost = findInstalledGhostByInstanceId(deps.listGhosts(), installedGhostStoragePart(target));
+ if (!ghost || ghost.manifest.id !== identity.ghostId ||
+ installedGhostLogicalIdentity(ghost).namespace !== identity.namespace ||
+ ghost.dir !== target.dir ||
+ JSON.stringify(ghost.approval) !== JSON.stringify(target.approval) ||
+ JSON.stringify(deliveryNamespaceFields(ghost)) !== JSON.stringify(deliveryNamespaceFields(target)) ||
+ installedGhostStoragePart(ghost) !== installedGhostStoragePart(target)) {
+ return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
+ }
+ return classifyGhostAvailability(ghost, workdir, deps);
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostWebviewPartition.ts b/apps/desktop/src/main/cindy-brain/ghostWebviewPartition.ts
index 030466cc98..7539e149e3 100644
--- a/apps/desktop/src/main/cindy-brain/ghostWebviewPartition.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostWebviewPartition.ts
@@ -1,4 +1,7 @@
-import { GHOST_PARTITION_PREFIX, isValidGhostId, parseGhostPartition } from '../../shared/ghost.js';
+import { createHash } from 'node:crypto';
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
+import { GHOST_PARTITION_PREFIX, ghostInstallApprovalToken, parseGhostPartition, type GhostInstallApproval } from '../../shared/ghost.js';
+import { installedGhostStoragePart, isPluginInstanceKey } from '../../shared/pluginIdentity.js';
import { dataOwnerStorageKey, type ActiveAppSession } from '../appSessionState.js';
const GHOST_OWNER_PARTITION_PREFIX = `${GHOST_PARTITION_PREFIX}owner:`;
@@ -12,9 +15,28 @@ export interface ResolvedGhostWebviewPartition {
export function ownerScopedGhostPartition(
ghostId: string,
owner: Pick<ActiveAppSession, 'mode' | 'dataOwnerId'>,
+ namespace?: string | null,
): string | null {
- if (!isValidGhostId(ghostId) || owner.mode === 'signed-out' || !owner.dataOwnerId) return null;
- return `${GHOST_OWNER_PARTITION_PREFIX}${owner.mode}:${dataOwnerStorageKey(owner.dataOwnerId)}:${ghostId}`;
+ if (!isPluginInstanceKey(ghostId) || owner.mode === 'signed-out' || !owner.dataOwnerId) return null;
+ // 原地确认的旧安装沿用目录键;namespace 段让它离开迁移时撤销的旧分区。
+ const scope = namespace === null ? ':root' : isValidPluginNamespace(namespace) ? `:ns:${namespace}` : '';
+ return `${GHOST_OWNER_PARTITION_PREFIX}${owner.mode}:${dataOwnerStorageKey(owner.dataOwnerId)}:${ghostId}${scope}`;
+}
+
+export function ownerScopedGhostPartitionForInstalledGhost(
+ ghost: { manifest: { id: string }; namespace?: string | null; approval?: GhostInstallApproval; dir?: string },
+ owner: Pick<ActiveAppSession, 'mode' | 'dataOwnerId'> & Partial<Pick<ActiveAppSession, 'generation'>>,
+): string | null {
+ const partition = ownerScopedGhostPartition(
+ installedGhostStoragePart(ghost),
+ owner,
+ ghost.namespace,
+ );
+ if (!partition || ghost.approval?.state !== 'approved') return partition;
+ const receipt = createHash('sha256')
+ .update(JSON.stringify([ghostInstallApprovalToken(ghost.approval), ghost.dir ?? null, owner.generation ?? null]))
+ .digest('hex');
+ return partition + ':receipt:' + receipt;
}
/**
diff --git a/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts b/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts
index 654b28f7c4..08df2d409c 100644
--- a/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostWorkdirPrefs.ts
@@ -27,6 +27,7 @@ import path from 'node:path';
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { assertGhostPrefsWritable, updateGhostPrefsForRelocation } from './ghostPreferenceRelocation.js';
const log = desktopMakerLogger.child('ghost-workdir-prefs');
@@ -71,13 +72,18 @@ function normalize(raw: unknown): GhostWorkdirPrefs {
return { disabledByWorkdir };
}
-const store = createOverrideSettingsFile<GhostWorkdirPrefs>({
- filePath: () => ownerScopedUserDataPath('ghost-workdir-prefs.json'),
- defaults: DEFAULTS,
- normalize,
- log,
- label: 'ghost-workdir-prefs',
-});
+function createStore() {
+ return createOverrideSettingsFile<GhostWorkdirPrefs>({
+ filePath: () => ownerScopedUserDataPath('ghost-workdir-prefs.json'),
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'ghost-workdir-prefs',
+ preserveUnreadableFile: true,
+ });
+}
+
+let store = createStore();
function readPrefs(): GhostWorkdirPrefs {
store.invalidateIfChanged();
@@ -97,6 +103,7 @@ export function isGhostDisabledForWorkdir(ghostId: string, workdir: string | nul
/** 写入目录级例外;返回该目录写后的禁用列表(供 IPC 回包)。 */
export function setGhostDisabledForWorkdir(workdir: string, ghostId: string, disabled: boolean): string[] {
+ assertGhostPrefsWritable('ghost-workdir-prefs.json');
const key = normalizeWorkdirKey(workdir);
if (key.length === 0) throw new Error('workdir must be a non-empty path');
const current = readPrefs().disabledByWorkdir;
@@ -111,5 +118,35 @@ export function setGhostDisabledForWorkdir(workdir: string, ghostId: string, dis
return next[key] ?? [];
}
+/** 原位组织插件改用 namespace 物理 ID 时,保留各项目的禁用例外。 */
+export async function relocateGhostWorkdirPrefs(fromPart: string, toPart: string): Promise<void> {
+ if (fromPart === toPart) return;
+ await updateGhostPrefsForRelocation('ghost-workdir-prefs.json', (raw) => {
+ const map = raw.disabledByWorkdir;
+ if (map === undefined) return {};
+ if (map === null || typeof map !== 'object' || Array.isArray(map)) {
+ throw new Error('ghost workdir preferences are unreadable');
+ }
+ const entries = Object.entries(map);
+ if (entries.some(([, ids]) => !Array.isArray(ids) || ids.some((id) => typeof id !== 'string'))) {
+ throw new Error('ghost workdir preferences are unreadable');
+ }
+ const disabled = map as Record<string, string[]>;
+ if (!Object.values(disabled).some((ids) => ids.includes(fromPart))) return {};
+ if (Object.values(disabled).some((ids) => ids.includes(toPart))) {
+ throw new Error('ghost workdir preferences relocation destination collision');
+ }
+ return {
+ disabledByWorkdir: Object.fromEntries(
+ Object.entries(disabled).map(([workdir, ids]) => [
+ workdir, ids.map((id) => id === fromPart ? toPart : id),
+ ]),
+ ),
+ };
+ }, () => {
+ store = createStore();
+ });
+}
+
/** 测试钩子(仅纯函数;读写链路由 IPC / 生效点测试覆盖)。 */
export const __testing = { normalize, normalizeWorkdirKey };
diff --git a/apps/desktop/src/main/cindy-brain/googleAccountsMigration.ts b/apps/desktop/src/main/cindy-brain/googleAccountsMigration.ts
deleted file mode 100644
index 7b110e2fa3..0000000000
--- a/apps/desktop/src/main/cindy-brain/googleAccountsMigration.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * googleAccountsMigration.ts — 老 Google 集成账号 → Filo Google 意识(一次性搬账)。
- * ---------------------------------------------------------------------------
- * lizi_google MCP 退役(2026-07-13)前置:老「第三方平台」里授权过的账号,
- * 凡是用 filoCurrent 内置 client 换的(refresh token 与 client 绑定,意识内置
- * 的正是同一个 client,令牌通用),直接迁进意识 OAuth 保险库——用户无感,
- * 不用重新授权。filoLegacy 档案的账号不迁(Lizi 定案"原本的就算了"):
- * 老 client 不随意识走,那批账号由用户在意识里重新点一次「连接账号」。
- *
- * 幂等与安全:
- * - 意识侧已有账号清单(用户已连接过 / 已迁移过)→ 整体跳过,绝不合并覆盖;
- * - 老存储原样保留(不删不改)——退役删的是代码,用户数据留作回滚余地;
- * - refresh token 只在两个 safeStorage 存储之间搬运,不进日志、不进返回值。
- *
- * 依赖注入(规则 14):老存储读取 / 意识保险库全经 deps,单测内存假体零 Electron。
- */
-
-import type { GhostOauthVault } from './ghostOauthAccounts.js';
-import type { LegacyMigrationRead } from './legacyMigrationRead.js';
-
-/** filo-google 意识与其 oauth 凭证槽(与 ghost.json 声明一致,搬账目的地)。 */
-export const FILO_GOOGLE_GHOST_ID = 'filo-google';
-export const FILO_GOOGLE_SECRET_KEY = 'google_account';
-
-/** 老集成账号清单行(mcp-integrations/google.ts 的 manifest 形态,退役后此处是唯一读者)。 */
-export interface LegacyGoogleAccountRow {
- id: string;
- email: string | null;
- credentialProfileId: string;
- updatedAt: number;
-}
-
-export interface GoogleAccountsMigrationDeps {
- /** 读老账号清单,并区分确实缺失与可重试读取失败。 */
- readLegacyManifest(): LegacyMigrationRead<{ accounts: LegacyGoogleAccountRow[] }>;
- /** 读老账号的 refresh token 明文,并区分确实缺失与可重试读取失败。 */
- readLegacyRefreshToken(accountId: string): LegacyMigrationRead<string>;
- /** 意识 OAuth 保险库(与 GhostOauthAccountManager 同一本账)。 */
- vault: GhostOauthVault;
- log?: { info(msg: string, meta?: Record<string, unknown>): void; warn(msg: string, meta?: Record<string, unknown>): void };
-}
-
-export interface GoogleAccountsMigrationResult {
- migrated: number;
- retryPending: boolean;
-}
-
-/** 老账号 id 形状(镜像老集成的 SAFE_ACCOUNT_ID_RE;同时满足保险库键名字符集)。 */
-const SAFE_ACCOUNT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
-
-/** 当前内置档案 id(googleCredentials.ts 的 FILO_GOOGLE_CURRENT_PROFILE_ID;退役后常量归此)。 */
-export const FILO_CURRENT_PROFILE_ID = 'filoCurrent';
-
-/**
- * 执行一次搬账。返回迁移的账号数(0 = 无可迁 / 已迁过 / 意识侧已有账号)。
- * 在内置意识对账完成后调用(见 index.ts 启动序列);同步 IO 量级为个位数
- * 小文件,不值得异步化。
- */
-export function migrateFiloGoogleAccountsWithResult(
- deps: GoogleAccountsMigrationDeps,
-): GoogleAccountsMigrationResult {
- const { readLegacyManifest, readLegacyRefreshToken, vault, log } = deps;
-
- const accountsKey = `${FILO_GOOGLE_SECRET_KEY}-accounts`;
- // 意识侧已有账号(用户手动连过 / 上次已迁)→ 不碰,防重复合并。
- if (vault.read(FILO_GOOGLE_GHOST_ID, accountsKey) !== null) {
- return { migrated: 0, retryPending: false };
- }
-
- const legacy = readLegacyManifest();
- if (legacy.status === 'retryable-failure') {
- return { migrated: 0, retryPending: true };
- }
- if (legacy.status === 'missing' || legacy.value.accounts.length === 0) {
- return { migrated: 0, retryPending: false };
- }
-
- const rows: Array<{ id: string; label: string | null; status: 'connected'; createdAt: number }> = [];
- for (const account of legacy.value.accounts) {
- // 只迁 filoCurrent:意识内置同一 client,refresh token 直接通用;
- // legacy 档案的令牌换了 client 刷不动,迁了也是死账号,不如引导重连。
- if (account.credentialProfileId !== FILO_CURRENT_PROFILE_ID) continue;
- if (typeof account.id !== 'string' || !SAFE_ACCOUNT_ID_RE.test(account.id)) continue;
- const refreshToken = readLegacyRefreshToken(account.id);
- if (refreshToken.status === 'retryable-failure') {
- for (const row of rows) {
- vault.remove(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${row.id}`);
- }
- return { migrated: 0, retryPending: true };
- }
- if (refreshToken.status === 'missing') continue;
- if (!vault.store(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${account.id}`, refreshToken.value)) {
- for (const row of rows) {
- vault.remove(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${row.id}`);
- }
- log?.warn('filo-google 搬账:refresh token 写入失败,整体回退并等待重试', {
- accountId: account.id,
- });
- return { migrated: 0, retryPending: true };
- }
- rows.push({
- id: account.id,
- label: typeof account.email === 'string' && account.email.length > 0 ? account.email : null,
- status: 'connected',
- createdAt: typeof account.updatedAt === 'number' && Number.isFinite(account.updatedAt) ? account.updatedAt : 0,
- });
- }
- if (rows.length === 0) return { migrated: 0, retryPending: false };
-
- const manifest = { defaultAccountId: rows[0].id, accounts: rows };
- if (!vault.store(FILO_GOOGLE_GHOST_ID, accountsKey, JSON.stringify(manifest))) {
- // 清单写失败:回收已搬的 rt,保持"没迁过"的干净状态,下次启动重试。
- for (const row of rows) vault.remove(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${row.id}`);
- log?.warn('filo-google 搬账:账号清单写入失败,整体回退');
- return { migrated: 0, retryPending: true };
- }
- log?.info('filo-google 搬账完成:老 Google 集成账号已迁入意识', { migrated: rows.length });
- return { migrated: rows.length, retryPending: false };
-}
-
-/** Compatibility wrapper for callers that only need the migrated count. */
-export function migrateFiloGoogleAccounts(deps: GoogleAccountsMigrationDeps): number {
- return migrateFiloGoogleAccountsWithResult(deps).migrated;
-}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 9c900a0ace..747b3fdc84 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -13,7 +13,7 @@ let mobilePluginPages: MobilePluginPages | null = null;
export async function showMobilePluginTaskPermission(pluginId: string, pageId: string, presentation: {
title: string; message: string; detail: string; allow: string; cancel: string;
}): Promise<boolean> {
- const ghost = findAvailableGhost(pluginId);
+ const ghost = findGhostForPhysicalStoragePart(pluginId);
if (!mobilePluginPages || !ghost?.enabled) return false;
return mobilePluginPages.confirm(pageId, {
ghostId: pluginId, ghostName: ghost.manifest.name, iconDataUrl: ghost.iconDataUrl,
@@ -26,6 +26,15 @@ function notifyMobilePluginsChanged(): void {
mobilePluginPages?.invalidate();
tapWindowBroadcast(REMOTE_RESOURCE_CHANGED_CHANNEL, { collectionId: PLUGIN_COLLECTION }, getSafeDataOwnerPushStamp());
}
+
+async function resolveMobilePluginMedia(instanceId: string, url: string, current: () => boolean) {
+ const ghost = findGhostForPhysicalStoragePart(instanceId);
+ if (!ghost?.enabled) return null;
+ const result = await getGhostPreviewGate().request({ ghostId: ghost.manifest.id, instanceId, url, isPanelFocused: current });
+ if (!result.ok || !current()) return null;
+ const file = result.src.split('/').pop();
+ return file && /^[a-f0-9]{64}\.[a-z0-9]+$/.test(file) ? { path: `/media/${file}`, mediaKind: result.kind } : null;
+}
import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';
import { projectGhostAgentModels } from './ghostAgentModels.js';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
@@ -36,6 +45,7 @@ import { ensurePluginTaskApproval, hasPluginTaskApproval, PluginTaskApprovalGate
import {
registerGhostCardRemoteProvider,
persistGhostCardWithRemoteChange,
+ findGhostForRemotePluginIdentity,
} from './cardRemoteResource.js';
import {
openDeviceAuthorizationCard,
@@ -45,7 +55,7 @@ import { t as authorizationText } from '../i18n.js';
import { getBotAuthorizationService } from '../maker-ipc/botAuthorizationService.js';
import { isResidentBrowserGhost, spawnResidentGhost } from './residentGhost.js';
import { handleRoutineRequest } from './routineSlot.js';
-import { getRoutineEngine, disconnectRoutineSource } from '../routines/service.js';
+import { getRoutineEngine, disconnectRoutineSource, relocateRoutinePluginSource } from '../routines/service.js';
import {
app,
BrowserWindow,
@@ -57,7 +67,7 @@ import {
shell,
type WebContents,
} from 'electron';
-import { randomUUID } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { isDeepStrictEqual } from 'node:util';
@@ -65,7 +75,7 @@ import type { GhostInstallConsentFacts } from '../../shared/ghostInstallConsent.
const taskApprovalGate = new PluginTaskApprovalGate();
function requestPluginTaskApproval(id: string, isCurrent: () => boolean, confirm: (facts: GhostInstallConsentFacts) => Promise<boolean>, explicit = false): Promise<boolean> {
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
if (!isCurrent()) return Promise.resolve(false);
if (hasPluginTaskApproval(ghost)) return Promise.resolve(true);
const owner = getActiveDataOwnerPushStamp();
@@ -74,15 +84,15 @@ function requestPluginTaskApproval(id: string, isCurrent: () => boolean, confirm
const active = () => {
const current = getActiveDataOwnerPushStamp();
return isCurrent() && owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration &&
- ghostInstallApprovalToken(findAvailableGhost(id)?.approval) === revision;
+ ghostInstallApprovalToken(findGhostForInstanceId(id)?.approval) === revision;
};
return taskApprovalGate.request(id, JSON.stringify([owner.dataOwnerId, owner.ownerGeneration, revision]), explicit, () => ensurePluginTaskApproval(id, {
- getGhost: findAvailableGhost, isCurrent: active, confirm,
+ getGhost: findGhostForInstanceId, isCurrent: active, confirm,
approve: (pluginId, expected, current) => manager.approveTaskCapability(pluginId, expected, current),
}));
}
-import { supportsCindyVersion } from '@cindy/plugin-protocol';
+import { isValidPluginNamespace, supportsCindyVersion } from '@cindy/plugin-protocol';
import { buildGhostRecommendationSnapshot } from './ghostRecommendationSnapshot.js';
import {
readGhostRecommendationEntries,
@@ -91,6 +101,7 @@ import {
recordGhostAdded,
consumeGhostRecommendationPriority,
forgetGhostRecommendations,
+ relocateGhostRecommendations,
} from './ghostRecommendationStore.js';
import { createLogger } from '../logger.js';
@@ -118,10 +129,9 @@ import {
unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
isCindyAccountGhostId,
- isBrokerEligibleGhostId,
- isOfficialGhostId,
isUserInstallReservedGhostId,
isValidGhostId,
+ isValidNewGhostId,
layoutWithGhostPanel,
type GhostHostNoticeKey,
type GhostManifest,
@@ -151,6 +161,7 @@ import {
type AppSessionMode,
} from '../appSessionState.js';
import { getLayoutStore } from '../layout/index.js';
+import { relocateGhostUserDataResources } from './ghostUserDataRelocation.js';
import {
GhostManager,
type GhostExclusiveMutation,
@@ -167,6 +178,37 @@ import {
invalidateForgePackTicketsForOwner,
} from './forgePackStaging.js';
import { withGhostInstallLock } from './ghostInstallLock.js';
+import {
+ createPluginLogicalIdentity,
+ findConflictingGhostCommand,
+ findInstalledGhostByIdentity,
+ findInstalledGhostByInstanceId,
+ findInstalledGhostForLocalUpdate,
+ findInstalledGhostForDeliveryTarget,
+ installedGhostLogicalIdentity,
+ installedGhostPhysicalRelId,
+ blockedInstanceRegistryMarketError,
+ organizationMarketPlacementError,
+ installedGhostStoragePart,
+ installedGhostMutationTargetToken,
+ isGhostInstanceId,
+ resolvePluginLibraryStorageKey,
+ parsePluginInstallRelId,
+ parsePluginInstanceId,
+ parsePluginStoragePart,
+ pluginInstallStoragePart,
+ isValidPluginInstallRelId,
+ isPluginInstanceKey,
+ resolveInstalledGhost,
+ resolvePluginInstanceQuery,
+ hasDeliveryNamespace,
+ deliveryNamespaceFields,
+} from '../../shared/pluginIdentity.js';
+import { allocateArchiveInstanceKey, selectMarketPluginIdForInstance } from './pluginInstanceRegistry.js';
+import {
+ createNamespaceMigrationHost,
+ type NamespaceMigrationHost,
+} from './pluginNamespaceMigrationHost.js';
import {
clearBuiltinTombstone,
listEligibleBuiltinCommands,
@@ -191,6 +233,7 @@ import { GhostRuntime } from './runtime/GhostRuntime.js';
import {
electronSandboxAdapter,
ensureGhostProtocolRegistered,
+ revokeLegacyGhostProtocolPartition,
ghostIdForLogicWebContents,
sendToGhostLogic,
setGhostAppContextProvider,
@@ -253,13 +296,6 @@ import {
isTrustedAppRendererEvent,
isTrustedAppRendererWindow,
} from '../security/trustedAppRenderer.js';
-import {
- FILO_GOOGLE_GHOST_ID,
- FILO_GOOGLE_SECRET_KEY,
- migrateFiloGoogleAccountsWithResult,
- type LegacyGoogleAccountRow,
-} from './googleAccountsMigration.js';
-import { withFiloGoogleBuildClientConfig } from './filoGoogleClientConfig.js';
import {
LEGACY_JIRA_CONNECTION_FILE,
LEGACY_JIRA_RT_FILE,
@@ -321,13 +357,13 @@ import {
} from './cindySlot.js';
import { GhostAgentSlot, type GhostAgentTurnRunner } from './agentSlot.js';
import { GhostErrandSlot, type GhostErrandRunner } from './errandSlot.js';
-import { readPluginTaskConfig, writePluginTaskConfig, validatePluginTaskConfig } from './pluginTaskPrefsStore.js';
+import { readPluginTaskConfig, writePluginTaskConfig, validatePluginTaskConfig, relocateGhostErrandPrefs } from './pluginTaskPrefsStore.js';
import {
GhostNodeRuntimeBroker,
type NodeRuntimeStartAttemptContext,
} from './nodeRuntimeBroker.js';
import { GhostPickSlot } from './pickSlot.js';
-import { recordGhostPickedDir } from './pickGrantsStore.js';
+import { recordGhostPickedDir, relocateGhostPickedDirs } from './pickGrantsStore.js';
import { GhostPreviewSlot } from './previewSlot.js';
import { GhostScheduleSlot, isMainShellWindowUrl } from './scheduleSlot.js';
import { GhostWorkspaceSlot, type WorkspaceSessionService } from './workspaceSlot.js';
@@ -339,6 +375,7 @@ import {
loadGhostUnread,
markGhostUnread,
readGhostUnread,
+ relocateGhostUnread,
type GhostUnreadEntry,
} from './ghostUnreadStore.js';
import { isGhostUnreadProjectable, selectRevokedGhostUnreadIds } from './ghostUnreadProjection.js';
@@ -380,15 +417,22 @@ import {
type GhostFirstPartyPendingMarketRecord,
type GhostFirstPartyFactsPurpose,
} from './ghostFirstPartyFacts.js';
-import { authorizeGhostTokenBroker } from './ghostFirstPartyPrivilege.js';
+import {
+ authorizeGhostHostPrimitive,
+ authorizeGhostTokenBroker,
+ captureLegacyFirstPartyEligibility,
+ isTrustedMivoSecretAlias,
+} from './ghostFirstPartyPrivilege.js';
+import { isTrustedXdGhostForScriptTarget } from './ghostTrustedXdTarget.js';
+import { classifyGhostLocalUpdateSource, type GhostLocalUpdateSourceDecision } from './ghostLocalUpdateSource.js';
import { ghostTokenBrokerInstallError } from './ghostTokenBrokerInstallError.js';
import { ghostBrokerRedirectPortInstallError } from './ghostBrokerRedirectPort.js';
import { ConnectionTokenProvider, type IssuedConnectionToken } from './connectionTokenProvider.js';
import { GhostFsSlot } from './fsSlot.js';
import { GhostLibrarySlot } from './librarySlot.js';
-import { LibraryBindingStore, validateLibraryCandidateLocation } from './libraryBinding.js';
+import { LibraryBindingStore, assertLibraryMetaOwner, relocateLibraryMetaOwner, validateLibraryCandidateLocation } from './libraryBinding.js';
import { LibraryVault, statfsFreeBytes, DEFAULT_LIBRARY_LIMITS } from './libraryVault.js';
-import { LibraryStagingStore } from './libraryStaging.js';
+import { LibraryStagingStore, relocateLibraryStagingOwner } from './libraryStaging.js';
import { LibrarySqlService, defaultLibraryDbWorkerPath } from './librarySqlService.js';
import { trashGhostLibrary } from './libraryTrash.js';
import { migrateGhostLibrary } from './libraryMigrate.js';
@@ -427,10 +471,15 @@ import {
type GhostScreenResult,
type MinimalAgentEvent,
} from './subscriptionGateway.js';
-import { GhostExternalLinkGate, GhostPreviewGate, resolveGhostPanelMedia } from './previewGate.js';
+import {
+ GhostExternalLinkGate,
+ GhostPreviewGate,
+ parseGhostPanelMediaUrl,
+ resolveGhostPanelMedia,
+} from './previewGate.js';
import { runGhostExternalLinkNavigation } from './ghostExternalLinkNavigation.js';
import { runGhostPreviewNavigation } from './ghostPreviewNavigation.js';
-import { resolveGhostWebviewPartitionClaim } from './ghostWebviewPartition.js';
+import { ownerScopedGhostPartitionForInstalledGhost, resolveGhostWebviewPartitionClaim } from './ghostWebviewPartition.js';
import {
ghostSecretSaved,
readGhostSecret,
@@ -439,7 +488,9 @@ import {
readCustomProviderKey,
readGhostSecretTail,
removeGhostSecret,
+ migrateGhostSecrets,
removeGhostSecrets,
+ setMivoSecretAliasVerifier,
storeGhostSecret,
} from '../secrets/providerSecretStore.js';
import { getActiveCatalog, getXdGatewayModels } from '../maker-host/active-catalog.js';
@@ -482,6 +533,7 @@ import {
readGhostCindyOverrides,
readGhostCindyInflightLimit,
writeGhostCindyOverride,
+ relocateGhostCindyPrefs,
type CindyCapabilityKey,
} from './cindyPrefsStore.js';
import { isCindyOverrideModelAllowed } from './cindyOverrideWhitelist.js';
@@ -490,12 +542,14 @@ import { GHOST_COMPOSER_LIST_CHANNEL } from '../../shared/ghostComposer.js';
import {
isGhostDisabledForWorkdir,
listDisabledGhostIdsForWorkdir,
+ relocateGhostWorkdirPrefs,
setGhostDisabledForWorkdir,
} from './ghostWorkdirPrefs.js';
import {
forgetGhostRecentUsage,
loadGhostRecentIds,
markGhostRecentlyUsed,
+ relocateGhostRecentUsage,
} from './ghostRecentUsageStore.js';
import { createXaiImageChannel } from './xaiImageClient.js';
import {
@@ -533,6 +587,7 @@ import { ingestMedia, supportedMime } from '../cindy-media/ingest.js';
import { captureMediaRefCompensationScope } from '../cindy-media/refCompensationJournal.js';
import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
import { recordGhostCallMedia } from './ghostMediaLedger.js';
+import { resolveGhostMediaHandoverTarget } from './ghostMediaHandoverTargetTracker.js';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
import { ghostSetupNavigationForAction } from './ghostSetupNavigation.js';
import { assessGhostHostSetupRequirements } from './ghostHostSetupRequirements.js';
@@ -550,7 +605,7 @@ import {
// delete require.cache[__filename] 不在 CJS 缓存里——跨 chunk require 会把整个
// 主进程 bundle 重新求值,启动副作用全量重跑直至 IPC 二次注册抛错,反复触发即
// 主进程 OOM(2026-07-12 实事故,详见 bootstrap-electron.ts 末尾的缓存自愈注释)。
-import { getDbClient } from '../localDb/client/current.js';
+import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current.js';
import * as localDbSchema from '../localDb/schema.js';
import { eq } from 'drizzle-orm';
import { requireAppCapability } from '../appCapabilities.js';
@@ -829,9 +884,9 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
if (authorizedStatus.deferredReason === 'legacy-discovery-incomplete') return authorizedStatus;
const existingGhosts = getGhostManager().list();
- const existingGhostById = new Map(existingGhosts.map((ghost) => [ghost.manifest.id, ghost]));
+ const existingGhostById = new Map(existingGhosts.map((ghost) => [installedGhostStoragePart(ghost), ghost]));
const existingGhostDirs = new Map(
- existingGhosts.map((ghost) => [ghost.manifest.id, ghost.dir]),
+ existingGhosts.map((ghost) => [installedGhostStoragePart(ghost), ghost.dir]),
);
type StoppedActiveGhost = {
ghost: InstalledGhost;
@@ -939,11 +994,12 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
const restoredBeforeReconcile = getGhostManager().list();
const movedGhostIds = new Set<string>();
for (const ghost of restoredBeforeReconcile) {
- const previousDir = existingGhostDirs.get(ghost.manifest.id);
+ const instanceId = installedGhostStoragePart(ghost);
+ const previousDir = existingGhostDirs.get(instanceId);
if (previousDir !== undefined && path.resolve(previousDir) !== path.resolve(ghost.dir)) {
- movedGhostIds.add(ghost.manifest.id);
- getGhostRuntime().stop(ghost.manifest.id);
- getGhostNodeRuntimeBroker().stop(ghost.manifest.id);
+ movedGhostIds.add(instanceId);
+ getGhostRuntime().stop(installedGhostStoragePart(ghost));
+ getGhostNodeRuntimeBroker().stop(installedGhostStoragePart(ghost));
}
}
// 只有 owner recovery 在 rename 前写入并在本轮确认的 durable marker 才能进入
@@ -979,12 +1035,13 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();
const ghosts = getGhostManager().list();
for (const ghost of ghosts) {
- const previousDir = existingGhostDirs.get(ghost.manifest.id);
+ const instanceId = installedGhostStoragePart(ghost);
+ const previousDir = existingGhostDirs.get(instanceId);
const relocatedExistingGhost =
- movedGhostIds.has(ghost.manifest.id) ||
+ movedGhostIds.has(instanceId) ||
(previousDir !== undefined && path.resolve(previousDir) !== path.resolve(ghost.dir));
if (relocatedExistingGhost) ensureGhostProtocolRegistered(ghost);
- const stopped = stoppedActiveGhosts.get(ghost.manifest.id);
+ const stopped = stoppedActiveGhosts.get(instanceId);
if (relocatedExistingGhost && stopped) {
restoreGhostRuntimes(ghost, stopped);
} else if (builtinReconcileSucceeded && previousDir === undefined) {
@@ -1007,7 +1064,9 @@ export function waitForGhostMutations(): Promise<void> {
/** Account-managed built-ins are unavailable outside a verified cloud session. */
export function isGhostAvailableForActiveSession(id: string): boolean {
if (isAppSessionBoundaryPending()) return false;
- return !isCindyAccountGhostId(id) || getAppCapabilities().canUseCindyAccountServices;
+ const identity = parsePluginStoragePart(id) ?? parsePluginInstallRelId(id);
+ const ghostId = identity?.ghostId ?? id;
+ return !isCindyAccountGhostId(ghostId) || getAppCapabilities().canUseCindyAccountServices;
}
function availableGhosts(): InstalledGhost[] {
@@ -1019,16 +1078,18 @@ function availableGhosts(): InstalledGhost[] {
function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {
try {
- const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);
+ const runtimeManifest = ghost.manifest;
+ const storeId = installedGhostStoragePart(ghost);
const oauthManager = getGhostOauthAccountManager();
const expiredAccountCount = (runtimeManifest.network?.secrets ?? []).reduce(
(count, secret) =>
secret.source === 'oauth' && secret.oauth
- ? count + oauthManager.clientMigrationExpiredAccountCount(runtimeManifest.id, secret.key)
+ ? count +
+ oauthManager.clientMigrationExpiredAccountCount(storeId, secret.key)
: count,
0,
);
- const suggest = getGhostOauthReauthSuggest(runtimeManifest);
+ const suggest = getGhostOauthReauthSuggest(runtimeManifest, storeId);
return {
...ghost,
...(expiredAccountCount > 0 ? { oauthAuthorizationExpired: { expiredAccountCount } } : {}),
@@ -1051,19 +1112,45 @@ function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {
}
}
-function findAvailableGhost(id: string): InstalledGhost | null {
- return availableGhosts().find((ghost) => ghost.manifest.id === id) ?? null;
+function findAvailableGhost(id: string, namespace?: string | null): InstalledGhost | null {
+ const resolved = resolveInstalledGhost(availableGhosts(), id, namespace);
+ return resolved.status === 'unique' ? resolved.ghost : null;
+}
+
+export function findGhostForInstanceId(id: string, namespace?: string | null): InstalledGhost | null {
+ const resolved = resolvePluginInstanceQuery(availableGhosts(), id, namespace);
+ return resolved.status === 'unique' ? resolved.ghost : null;
+}
+
+function libraryStorageKeyFor(id: string): string | null {
+ return resolvePluginLibraryStorageKey(id, findGhostForInstanceId(id));
+}
+
+function findGhostForPhysicalStoragePart(id: string): InstalledGhost | null {
+ return availableGhosts().find((ghost) => installedGhostStoragePart(ghost) === id) ?? null;
}
/** Runtime-authorized lookup for integrations outside this module. */
-export function findAvailableGhostForAuthorization(id: string): InstalledGhost | null {
- return findAvailableGhost(id);
+export function findAvailableGhostForAuthorization(
+ id: string,
+ namespace?: string | null,
+): InstalledGhost | null {
+ return findAvailableGhost(id, namespace);
}
export function listAvailableGhostsForAuthorization(): InstalledGhost[] {
return availableGhosts();
}
+export function findTrustedXdGhostForScript(id: string): InstalledGhost | null {
+ const ghost = findAvailableGhostForAuthorization(id, 'xd') ?? findAvailableGhostForAuthorization(id);
+ if (!ghost) return null;
+ const storagePart = installedGhostStoragePart(ghost);
+ const loaded = loadGhostFirstPartyFactsForGhost(storagePart, 'runtime');
+ return isTrustedXdGhostForScriptTarget(ghost, loaded, getGhostManager().isPendingLegacyNamespace(storagePart))
+ ? ghost : null;
+}
+
function requireGhostAvailableForActiveSession(id: string): void {
if (!isGhostAvailableForActiveSession(id)) {
if (isAppSessionBoundaryPending()) {
@@ -1079,7 +1166,19 @@ function requireGhostAvailableForActiveSession(id: string): void {
/** Stop any account-managed sandbox before an auth/data-owner boundary switch. */
export function suspendCindyAccountGhosts(): void {
if (!runtimeSingleton) return;
- for (const id of CINDY_ACCOUNT_GHOST_IDS) runtimeSingleton.stop(id);
+ const stopped = new Set<string>();
+ for (const ghost of managerSingleton?.list() ?? []) {
+ if (!CINDY_ACCOUNT_GHOST_IDS.has(ghost.manifest.id)) continue;
+ const key = installedGhostStoragePart(ghost);
+ runtimeSingleton.stop(key);
+ getGhostNodeRuntimeBroker().stop(key);
+ stopped.add(key);
+ }
+ for (const id of CINDY_ACCOUNT_GHOST_IDS) {
+ if (stopped.has(id)) continue;
+ runtimeSingleton.stop(id);
+ getGhostNodeRuntimeBroker().stop(id);
+ }
}
/**
@@ -1353,6 +1452,92 @@ function migrateGhostKvOnRename(fromId: string, toId: string): void {
}
}
+function assertGhostRelocationDbReady(): void {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ if (!ownerId || getCurrentDbClientUserId() !== ownerId) {
+ throw new Error('Ghost relocation database owner is not ready');
+ }
+ getDbClient();
+}
+
+function assertGhostRelocationIdle(part: string): void {
+ if (hasPendingGhostCalls(part) || hasRunningGhostErrand(part) ||
+ hasRunningGhostCindyWork(part) || fsSlotSingleton?.hasInFlightRequests(part) ||
+ networkSlotSingleton?.hasInFlightRequests(part)) {
+ throw new Error('Ghost relocation is waiting for active work to finish');
+ }
+}
+
+async function relocateGhostUserData(
+ fromPart: string, toPart: string,
+): Promise<void> {
+ if (fromPart === toPart) return;
+ assertGhostRelocationIdle(fromPart);
+ const ownerKey = activeOwnerScopeKey();
+ const assertCurrent = (): void => {
+ if (activeOwnerScopeKey() !== ownerKey || isAppSessionBoundaryPending()) {
+ throw new Error('Ghost relocation owner changed');
+ }
+ assertGhostRelocationDbReady();
+ };
+ assertCurrent();
+ getGhostOauthAccountManager().invalidateGhost(fromPart);
+ getGhostOauthAccountManager().invalidateGhost(toPart);
+ getBotAuthorizationService()?.invalidatePlugin(fromPart);
+ getBotAuthorizationService()?.invalidatePlugin(toPart);
+ subscriptionGatewaySingleton?.dropGhost(fromPart);
+ subscriptionGatewaySingleton?.dropGhost(toPart);
+ const slot = getGhostLibrarySlot();
+ slot.setRelocating(fromPart, true);
+ slot.setRelocating(toPart, true);
+ try {
+ await slot.disposeGhost(fromPart);
+ await slot.disposeGhost(toPart);
+ await relocateGhostUserDataResources(fromPart, toPart, {
+ userDataPath: ownerScopedUserDataPath,
+ assertCurrent,
+ tasks: (from, to) => {
+ if (!pluginTaskRelocator) throw new Error('Plugin task storage is not ready for source archival');
+ return pluginTaskRelocator(from, to);
+ },
+ secrets: (from, to) => { migrateGhostSecrets(from, to); },
+ libraryBinding: (from, to) => getGhostLibraryBindingStore().relocateBinding(from, to),
+ libraryMeta: async (from, to) => {
+ const binding = await getGhostLibraryBindingStore().getBinding(to, { strict: true });
+ assertCurrent();
+ const root = binding ? path.join(binding.root, to) : ownerScopedUserDataPath('libraries', to);
+ await relocateLibraryMetaOwner(root, from, to, assertCurrent);
+ assertCurrent();
+ await relocateLibraryStagingOwner(
+ ownerScopedUserDataPath('library-staging', to), from, to, ownerKey, assertCurrent,
+ );
+ },
+ workdirPreferences: relocateGhostWorkdirPrefs,
+ cindyPreferences: relocateGhostCindyPrefs,
+ errandPreferences: relocateGhostErrandPrefs,
+ pickedDirectories: relocateGhostPickedDirs,
+ media: ledger.relocateGhostMediaRefs,
+ cards: async (from, to) => {
+ await getGhostCardService().relocateGhost(from, to);
+ assertCurrent();
+ await reassignGhostCards(from, to);
+ },
+ unread: relocateGhostUnread,
+ routines: relocateRoutinePluginSource,
+ recommendations: relocateGhostRecommendations,
+ recentUsage: relocateGhostRecentUsage,
+ });
+ } finally {
+ try {
+ await slot.disposeGhost(fromPart);
+ await slot.disposeGhost(toPart);
+ } finally {
+ slot.setRelocating(fromPart, false);
+ slot.setRelocating(toPart, false);
+ }
+ }
+}
+
/** 单轮对账:一次性 legacy 迁移 → 播种 → (有变化时)广播 + 首装停靠 + 常驻点火。 */
async function reconcileBuiltinGhosts(
reason: string,
@@ -1605,6 +1790,41 @@ async function reconcileBuiltinGhostsLocked(
return approvalNeedsRetry;
}
+
+let namespaceMigrationHost: NamespaceMigrationHost | null = null;
+function getNamespaceMigrationHost(): NamespaceMigrationHost {
+ if (!namespaceMigrationHost) {
+ namespaceMigrationHost = createNamespaceMigrationHost({
+ activeOwnerScopeKey,
+ isAppSessionBoundaryPending,
+ getGhostManager: () => getGhostManager(),
+ getPluginMarketLedger,
+ getAuthState,
+ createOrganizationPrefixStore,
+ ownerScopedUserDataPath,
+ brainRootDir,
+ readInstalledGhostManifestSnapshot,
+ oauthLockExists: (ghostId) => fs.existsSync(ghostOauthMutationLockPath(ghostId)),
+ hasPendingWork: (ghostId) => hasPendingGhostCalls(ghostId) || hasRunningGhostErrand(ghostId) ||
+ hasRunningGhostCindyWork(ghostId),
+ runtimeState: (instanceKey) => runtimeSingleton?.stateOf(instanceKey),
+ nodeRuntimeRunning: (instanceKey) => nodeRuntimeBrokerSingleton?.stateOf(instanceKey) === 'running',
+ stopRuntime: (instanceKey) => { getGhostRuntime().stop(instanceKey); },
+ stopNodeRuntime: (instanceKey) => getGhostNodeRuntimeBroker().stopAndWait(instanceKey),
+ spawnIfResident: (ghostId) => {
+ const ghost = managerSingleton?.list().find((candidate) =>
+ candidate.namespaceState === 'pending' &&
+ installedGhostPhysicalRelId(candidate) === ghostId);
+ if (ghost) spawnIfResident(ghost, true);
+ },
+ captureGhostMutationOwner,
+ beginGhostMutation,
+ log,
+ });
+ }
+ return namespaceMigrationHost;
+}
+
export function getGhostManager(): GhostManager {
if (!managerSingleton) {
managerSingleton = new GhostManager({
@@ -1617,7 +1837,77 @@ export function getGhostManager(): GhostManager {
// 随包批准入口的 builtin-only 边界:id 必须对应一颗随包种子。该入口不经用户
// 确认就铸出批准,不能只靠"唯一调用者是随包对账"这条纪律。
isTrustedBundledId: (id) => listBuiltinSeedIds(builtinSeedRootDirs()).includes(id),
- isTokenBrokerAuthorized: (manifest) => isGhostTokenBrokerAuthorized(manifest.id, 'install'),
+ isTokenBrokerAuthorized: (manifest) =>
+ isGhostTokenBrokerAuthorized(manifest.id, 'install'),
+ classifyPendingNamespace: (ghostId, marketSyncCompleted) =>
+ getNamespaceMigrationHost().classifyPendingNamespaceForGhost(ghostId, marketSyncCompleted === true),
+ captureLegacyFirstPartyEligibility: (ghostId, approvedPackageSha256) => {
+ const records = getPluginMarketLedger().installationsForGhost(ghostId).filter((record) =>
+ record.installed && record.source === 'market' && record.scope === 'public' &&
+ record.organizationId === null && record.namespace == null && record.sha256 === approvedPackageSha256);
+ return records.length === 1 && captureLegacyFirstPartyEligibility({
+ legacyExistingInstall: true,
+ ghostId,
+ namespace: null,
+ approved: true,
+ approvedPackageSha256,
+ marketRecord: { ...records[0]!, approvedPackageSha256 },
+ });
+ },
+ readUnconfirmedConfirmationEvidence: (record) =>
+ getNamespaceMigrationHost().readUnconfirmedConfirmationEvidence(record),
+ isNamespaceMigrationBusy: (ghostId) => getNamespaceMigrationHost().isNamespaceMigrationBusy(ghostId),
+ marketIdentityForInstance: (instance) => {
+ try {
+ const lookup = getPluginMarketLedger().lookupInstallationsForNamespaceMigration(instance.ghostId);
+ if (lookup.kind !== 'found') return null;
+ const pluginId = selectMarketPluginIdForInstance(instance, lookup.records ?? []);
+ return pluginId ? { pluginId } : null;
+ } catch {
+ return null;
+ }
+ },
+ canResumePendingResidentOffline: (ghostId) => getNamespaceMigrationHost().canResumePendingResidentOffline(ghostId),
+ onResumePendingResidentOffline: (ghost) => {
+ if (!isGhostAvailableForActiveSession(ghost.manifest.id)) return;
+ getNamespaceMigrationHost().rememberOfflineResident(ghost.manifest.id);
+ spawnIfResident(ghost, true);
+ },
+ preparePendingResidentForMigration: (ghostId) =>
+ getNamespaceMigrationHost().preparePendingResidentForMigration(ghostId),
+ onPendingResidentMigrationDeferred: (ghostId) =>
+ getNamespaceMigrationHost().schedulePendingResidentMigrationRetry(ghostId),
+ onPendingResidentMigrationSettled: (ghostId, committed) =>
+ getNamespaceMigrationHost().onPendingResidentMigrationSettled(ghostId, committed),
+ beforeNamespaceCommit: (ghostId, namespace) => {
+ const marketLedger = getPluginMarketLedger();
+ if (!marketLedger.stampNamespaceIfAbsent(ghostId, namespace) &&
+ marketLedger.hasInstalledRecordForGhostId(ghostId)) {
+ throw new Error('Plugin market namespace migration could not stamp the installed record');
+ }
+ },
+ onNamespaceCommitted: (ghostId, namespace) => {
+ revokeLegacyGhostProtocolPartition(ghostId);
+ getNamespaceMigrationHost().forgetOfflineResident(ghostId);
+ getNamespaceMigrationHost().clearPendingResidentMigrationRetry(ghostId);
+ const ownerKey = activeOwnerScopeKey();
+ queueMicrotask(() => {
+ if (activeOwnerScopeKey() !== ownerKey) return;
+ const ghost = managerSingleton?.list().find((candidate) =>
+ candidate.manifest.id === ghostId && candidate.namespace === namespace &&
+ candidate.namespaceState !== 'pending');
+ if (ghost) spawnIfResident(ghost);
+ });
+ },
+ onArchiveSourceState: async (fromPart, archivePart) => {
+ assertGhostRelocationDbReady();
+ const releaseMutation = beginGhostMutation(captureGhostMutationOwner());
+ try {
+ await relocateGhostUserData(fromPart, archivePart);
+ } finally {
+ releaseMutation();
+ }
+ },
isTrustedBundledSource,
recordBuiltinTombstone: (id) => recordBuiltinTombstone(brainRootDir(), id, log),
clearBuiltinTombstone: (id) => clearBuiltinTombstone(brainRootDir(), id, log),
@@ -1662,14 +1952,6 @@ function loadGhostTrustRegistry(): GhostTrustRegistry {
}
}
-/** 仅供 main 出网/OAuth 链使用;不要把补过 client 的 manifest 广播给 renderer。 */
-function withRuntimeFiloGoogleClient(manifest: GhostManifest): GhostManifest {
- return withFiloGoogleBuildClientConfig(manifest, {
- clientId: process.env.XDT_FILO_GOOGLE_CLIENT_ID,
- clientSecret: process.env.XDT_FILO_GOOGLE_CLIENT_SECRET,
- });
-}
-
let runtimeSingleton: GhostRuntime | null = null;
/**
@@ -1686,10 +1968,11 @@ export function getGhostRuntime(): GhostRuntime {
// 关闭(沉睡)/ 重载都由用户在面板上决定,主机只记日志。
onFused: (id) => log.warn('ghost fused after repeated crashes', { id }),
onStateChanged: (id, state) => {
+ const storagePart = isValidPluginInstallRelId(id) ? pluginInstallStoragePart(id) : id;
log.info('ghost runtime state', { id, state });
- if (state !== 'running') disconnectRoutineSource(id);
+ if (state !== 'running') disconnectRoutineSource(storagePart);
// 崩溃/熄灯时把该意识名下的在途工具调用收掉(结构化失败给 agent)。
- getGhostPipeDispatcher().onRuntimeState(id, state);
+ getGhostPipeDispatcher().onRuntimeState(storagePart, state);
broadcastGhostRuntimeStates();
},
});
@@ -1707,7 +1990,7 @@ let dispatcherSingleton: GhostPipeDispatcher | null = null;
export function getGhostPipeDispatcher(): GhostPipeDispatcher {
if (!dispatcherSingleton) {
dispatcherSingleton = new GhostPipeDispatcher({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
ownerScope: ghostOwnerScope,
runtimeStateOf: (id) => getGhostRuntime().stateOf(id),
spawn: async (ghost) => {
@@ -1731,7 +2014,7 @@ let agentSlotSingleton: GhostAgentSlot | null = null;
export function getGhostAgentSlot(): GhostAgentSlot {
if (!agentSlotSingleton) {
agentSlotSingleton = new GhostAgentSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
log,
});
}
@@ -1753,16 +2036,27 @@ let pluginTaskHandler: PluginTaskHandler | null = null;
export function setPluginTaskHandler(handler: PluginTaskHandler | null): void { pluginTaskHandler = handler; }
let pluginTaskUninstaller: ((pluginId: string, remove: () => Promise<void>) => Promise<void>) | null = null;
export function setPluginTaskUninstaller(handler: typeof pluginTaskUninstaller): void { pluginTaskUninstaller = handler; }
+let pluginTaskRelocator: ((from: string, to: string) => Promise<void>) | null = null;
+export function setPluginTaskRelocator(handler: typeof pluginTaskRelocator): void {
+ pluginTaskRelocator = handler;
+ if (handler) {
+ void managerSingleton?.retryInterruptedMutationsAfterDbReady().catch((error) => {
+ log.warn('ghost mutation recovery after task storage readiness failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+}
/** Approval revision participates in Auto decision cache identity (including reinstall/update). */
export function pluginTaskAuthorizationRevision(id: string): string | null {
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
return ghost?.enabled && ghost.manifest.agent?.tasks && ghost.approval.state === 'approved'
? ghost.approval.revision : null;
}
export function isPluginTaskAuthorized(id: string): boolean {
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
return hasPluginTaskApproval(ghost);
}
@@ -1780,7 +2074,7 @@ export function getGhostErrandSlot(): GhostErrandSlot {
if (!errandSlotSingleton) {
errandSlotSingleton = new GhostErrandSlot({
resolveSourceSessionId: getPluginTaskSourceSessionId,
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
// wait 模式的署名单在途期间替管子那头的 tool-call 续命(同 cindy 槽契约)。
holdPipeCall: (ghostId, callId, budgetMs) =>
getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),
@@ -1813,12 +2107,12 @@ export function noteGhostUserGesture(ghostId: string): void {
/** 插件展示名(errand 会话默认标题等宿主侧使用;未装返回 null)。 */
export function getInstalledGhostName(id: string): string | null {
- return findAvailableGhost(id)?.manifest.name ?? null;
+ return findGhostForInstanceId(id)?.manifest.name ?? null;
}
/** Host-only identity for permission attempts; never a plugin-provided revision. */
export function getPluginTaskInstallRevision(id: string): string | null {
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
return hasPluginTaskApproval(ghost) ? ghostInstallApprovalToken(ghost?.approval) : null;
}
@@ -1856,7 +2150,7 @@ function resetNodeRuntimeBrokerForAccountBoundary(): void {
export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
if (!nodeRuntimeBrokerSingleton) {
nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
getCallSignal: (ghostId, callId) =>
getGhostPipeDispatcher().getPendingCallSignal(ghostId, callId),
getCallSessionId: (ghostId, callId) =>
@@ -1868,7 +2162,7 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
{
bridge,
changeBus: getGhostSetupChangeBus(),
- getManifest: (ghostId) => findAvailableGhost(ghostId)?.manifest ?? null,
+ getManifest: (ghostId) => findGhostForInstanceId(ghostId)?.manifest ?? null,
secretSaved: ghostSecretSaved,
storeSecret: storeGhostSecret,
},
@@ -1904,9 +2198,9 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),
secretSaved: ghostSecretSaved,
resolveOauthSecret: async (ghostId, secretKey, accountId) => {
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
const source = ghost
- ? withRuntimeFiloGoogleClient(ghost.manifest).network?.secrets?.find(
+ ? ghost.manifest.network?.secrets?.find(
(s) => s.key === secretKey,
)
: undefined;
@@ -1969,7 +2263,7 @@ export function getGhostCardService(): GhostCardService {
if (!cardServiceSingleton) {
cardServiceSingleton = new GhostCardService({
hasCardSlot: (ghostId) => {
- const g = findAvailableGhost(ghostId);
+ const g = findGhostForPhysicalStoragePart(ghostId);
return !!g && g.enabled && g.manifest.card !== undefined;
},
sanitize: sanitizeGhostCardHtml,
@@ -2000,14 +2294,18 @@ export function getGhostCardActionDispatcher(): GhostCardActionDispatcher {
return c ? { ghostId: c.ghostId, sessionId: c.sessionId ?? null } : null;
},
reopenForAction: (callId, info) => getGhostCardService().reopenForAction(callId, info),
- getGhost: findAvailableGhost,
- isRunning: (id) => getGhostRuntime().stateOf(id) === 'running',
+ getGhost: findGhostForPhysicalStoragePart,
+ isRunning: (id) => {
+ const ghost = findGhostForPhysicalStoragePart(id);
+ return !!ghost && getGhostRuntime().stateOf(installedGhostStoragePart(ghost)) === 'running';
+ },
wake: async (ghost) => {
const r = await getGhostRuntime().spawn(ghost);
if (!r.ok) throw new Error(r.reason);
},
sendToGhost: (ghostId, payload) => {
- if (!sendToGhostLogic(ghostId, payload)) {
+ const ghost = findGhostForPhysicalStoragePart(ghostId);
+ if (!ghost || !sendToGhostLogic(installedGhostStoragePart(ghost), payload)) {
throw new Error('ghost pipe send failed');
}
},
@@ -2049,14 +2347,18 @@ export function getGhostSubscriptionGateway(): GhostSubscriptionGateway {
if (!subscriptionGatewaySingleton) {
subscriptionGatewaySingleton = new GhostSubscriptionGateway({
listGhosts: availableGhosts,
- isRunning: (id) => getGhostRuntime().stateOf(id) === 'running',
+ isRunning: (id) => {
+ const ghost = findGhostForInstanceId(id);
+ return getGhostRuntime().stateOf(ghost ? installedGhostStoragePart(ghost) : id) === 'running';
+ },
wake: async (ghost) => {
const r = await getGhostRuntime().spawn(ghost);
if (!r.ok) throw new Error(r.reason);
},
sendToGhost: (ghostId, payload) => {
+ const ghost = findGhostForInstanceId(ghostId);
// 适配:底层返回 false 表示投递失败(网关契约是抛错 → 走缓冲/熔断)。
- if (!sendToGhostLogic(ghostId, payload)) {
+ if (!sendToGhostLogic(ghost ? installedGhostStoragePart(ghost) : ghostId, payload)) {
throw new Error('ghost pipe send failed');
}
},
@@ -2660,7 +2962,7 @@ let cindySlotSingleton: GhostCindySlot | null = null;
// redirect cleanup into the newly active account's persistent cache.
const anonymousDownloadRoots = new Map<string, { root: string; scope: string }>();
const pluginDownloads = new PluginDownloadSlot({
- getGhost: findAvailableGhost, root: id => {
+ getGhost: findGhostForInstanceId, root: id => {
const root = ownerScopedUserDataPath('plugin-downloads', id);
if (!getActiveAppSession().dataOwnerId) anonymousDownloadRoots.set(id, { root, scope: activeOwnerScopeKey() });
return root;
@@ -2683,13 +2985,18 @@ function getPluginMarketLedger(): PluginMarketLedger {
return pluginMarketLedgerSingleton;
}
+function pluginMarketAuthorizationTargetFor(ghostId: string): { ghostId: string; namespace?: string | null } {
+ const ghost = findGhostForInstanceId(ghostId);
+ if (ghost) return { ghostId: ghost.manifest.id, ...deliveryNamespaceFields(ghost) };
+ const identity = parsePluginInstanceId(ghostId);
+ return identity ?? { ghostId };
+}
+
/** Read Manifest and byte identity together from one installed ghost.json snapshot. */
function readInstalledGhostManifestIdentity(
ghostId: string,
): InstalledMarketManifestIdentity | null {
- const ghost = getGhostManager()
- .list()
- .find((candidate) => candidate.manifest.id === ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost) return null;
const result = readInstalledGhostManifestSnapshot(ghost.dir, GHOST_INSTALL_MANIFEST_MAX_BYTES);
return result.ok ? installedMarketManifestIdentity(result.snapshot) : null;
@@ -2701,10 +3008,14 @@ function getConnectionAudienceResolver(): ConnectionAudienceResolver {
connectionAudienceResolverSingleton = loadConnectionAudienceResolver({
readInstalledManifestIdentity: readInstalledGhostManifestIdentity,
readMarketInstallation: (ghostId) =>
- getPluginMarketLedger().lookupInstallationForOidc(ghostId),
+ getPluginMarketLedger().lookupInstallationForOidc(pluginMarketAuthorizationTargetFor(ghostId)),
readApprovedPackageSha256: (ghostId) =>
getGhostManager().approvedInstallEvidence(ghostId)?.packageSha256 ?? null,
readInstallOrigin: (ghostId) => getGhostManager().readEffectiveInstallOrigin(ghostId),
+ readInstallNamespace: (ghostId) => getGhostManager().readDeliveryNamespace(ghostId),
+ readNamespaceState: (ghostId) => getGhostManager().readNamespaceState(ghostId),
+ isPendingLegacyNamespace: (ghostId) => getGhostManager().isPendingLegacyNamespace(ghostId),
+ isPendingLegacyForge: (ghostId) => getGhostManager().isPendingLegacyForge(ghostId),
lookupOrganizationPrefix: (orgId) =>
createOrganizationPrefixStore(
ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),
@@ -2730,11 +3041,9 @@ function resolveConnectionAudienceForGhost(ghostId: string): ConnectionAudienceR
function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {
if (!ghostFirstPartyFactsLoaderSingleton) {
ghostFirstPartyFactsLoaderSingleton = loadGhostFirstPartyFactsLoader({
- readInstalledBuiltin: (ghostId) =>
- getGhostManager()
- .list()
- .find((candidate) => candidate.manifest.id === ghostId)?.builtin === true,
- readMarketInstallation: (ghostId) => getPluginMarketLedger().installationForGhost(ghostId),
+ readInstalledBuiltin: (ghostId) => findGhostForInstanceId(ghostId)?.builtin === true,
+ readMarketInstallation: (ghostId) =>
+ getPluginMarketLedger().installationForAuthorization(pluginMarketAuthorizationTargetFor(ghostId)),
readApprovedPackageSha256: (ghostId) =>
getGhostManager().approvedInstallEvidence(ghostId)?.packageSha256 ?? null,
lookupOrganizationPrefix: (orgId) =>
@@ -2742,6 +3051,22 @@ function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {
ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),
).lookup(orgId),
readInstallOrigin: (ghostId) => getGhostManager().readEffectiveInstallOrigin(ghostId),
+ readInstallNamespace: (ghostId) => getGhostManager().readDeliveryNamespace(ghostId),
+ readNamespaceState: (ghostId) => getGhostManager().readNamespaceState(ghostId),
+ isPendingLegacyForge: (ghostId) => getGhostManager().isPendingLegacyForge(ghostId),
+ isPendingLegacyNamespace: (ghostId) => getGhostManager().isPendingLegacyNamespace(ghostId),
+ readLegacyFirstPartyEligible: (ghostId) => getGhostManager().readLegacyFirstPartyEligible(ghostId),
+ readTrustedSource: (ghostId) => {
+ const ghost = findGhostForInstanceId(ghostId);
+ const evidence = getGhostManager().approvedInstallEvidence(ghostId);
+ if (!ghost?.builtin || ghost.trust?.level !== 'cindy-official' || !evidence?.packageSha256) return null;
+ return {
+ kind: 'builtin-official',
+ ghostId: ghost.manifest.id,
+ namespace: ghost.namespace ?? null,
+ packageSha256: evidence.packageSha256,
+ };
+ },
});
}
return ghostFirstPartyFactsLoaderSingleton;
@@ -2771,24 +3096,41 @@ export function loadGhostFirstPartyFactsForGhost(
{
membershipKind: user?.membershipKind ?? 'personal',
orgId: user?.orgId ?? null,
+ orgSlug: user?.orgSlug ?? null,
},
overrides,
);
}
+setMivoSecretAliasVerifier((ghostId) => {
+ const loaded = loadGhostFirstPartyFactsForGhost(ghostId, 'runtime');
+ if (loaded.kind !== 'ready') return false;
+ const pendingLegacy = loaded.facts.namespace === null &&
+ getGhostManager().isPendingLegacyNamespace(ghostId);
+ return isTrustedMivoSecretAlias(loaded.facts, pendingLegacy);
+});
+
function isGhostTokenBrokerAuthorized(
ghostId: string,
purpose: GhostFirstPartyFactsPurpose,
overrides?: GhostFirstPartyFactsOverrides,
): boolean {
- // Official prefix keeps today's grant without consulting facts.
- if (isBrokerEligibleGhostId(ghostId)) return true;
return authorizeGhostTokenBroker(
ghostId,
loadGhostFirstPartyFactsForGhost(ghostId, purpose, overrides),
);
}
+function isGhostHostPrimitiveAuthorized(
+ ghostId: string,
+ purpose: GhostFirstPartyFactsPurpose = 'runtime',
+): boolean {
+ return authorizeGhostHostPrimitive(
+ ghostId,
+ loadGhostFirstPartyFactsForGhost(ghostId, purpose),
+ );
+}
+
/** Main-memory-only Connection token issuer/cache. */
export function getConnectionTokenProvider(): ConnectionTokenProvider {
if (!connectionTokenProviderSingleton) {
@@ -2831,7 +3173,7 @@ export function broadcastGhostHostNotice(
tone?: 'info' | 'success' | 'warning' | 'error';
},
): void {
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost) return; // 卸载竞态:意识已不在,提示无从署名,静默丢
const now = Date.now();
const last = hostNoticeLastAt.get(ghostId);
@@ -2868,7 +3210,7 @@ export function broadcastGhostHostNotice(
export function getGhostNotifySlot(): GhostNotifySlot {
if (!notifySlotSingleton) {
notifySlotSingleton = new GhostNotifySlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
broadcast: (payload) => {
broadcastGhostWindowPush(GHOST_NOTIFY_CHANNEL, payload);
},
@@ -2941,9 +3283,26 @@ function visibleGhostUnread(): GhostUnreadEntry[] {
// locale / 图标 / 信任文件。账本允许 200 条,逐条查就是 O(未读 × 已装) 次
// 磁盘扫描,而本函数服务的是**同步** ghosts:unread(首屏渲染路径),
// 足以卡住启动(codex review)。
- const available = new Map(availableGhosts().map((ghost) => [ghost.manifest.id, ghost]));
+ const ghosts = availableGhosts();
+ const availableByInstanceId = new Map(
+ ghosts.map((ghost) => [installedGhostStoragePart(ghost), ghost]),
+ );
+ const uniqueByGhostId = new Map<string, InstalledGhost>();
+ const ambiguousGhostIds = new Set<string>();
+ for (const ghost of ghosts) {
+ const ghostId = ghost.manifest.id;
+ if (ambiguousGhostIds.has(ghostId)) continue;
+ if (uniqueByGhostId.has(ghostId)) {
+ uniqueByGhostId.delete(ghostId);
+ ambiguousGhostIds.add(ghostId);
+ continue;
+ }
+ uniqueByGhostId.set(ghostId, ghost);
+ }
return entries.filter((entry) =>
- isGhostUnreadProjectable(available.get(entry.ghostId) ?? null),
+ isGhostUnreadProjectable(
+ availableByInstanceId.get(entry.ghostId) ?? uniqueByGhostId.get(entry.ghostId) ?? null,
+ ),
);
} catch (error) {
log.warn('ghost unread 读取失败', {
@@ -2961,7 +3320,7 @@ function visibleGhostUnread(): GhostUnreadEntry[] {
export function getGhostBadgeSlot(): GhostBadgeSlot {
if (!badgeSlotSingleton) {
badgeSlotSingleton = new GhostBadgeSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
mark: (ghostId, summary, at) => {
try {
// 触到上限被挤掉的条目要补一条熄灭广播,否则 renderer 表里留着账本
@@ -3161,7 +3520,7 @@ export function getGhostConfirmSlot(): GhostConfirmSlot {
log,
});
confirmSlotSingleton = new GhostConfirmSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
showConfirm: (params) => params.mobilePageId
? (mobilePluginPages?.confirm(params.mobilePageId, params) ?? Promise.reject(new Error('PLUGIN_PAGE_UNAVAILABLE')))
: bridge.request({
@@ -3189,7 +3548,8 @@ let pickSlotSingleton: GhostPickSlot | null = null;
export function getGhostPickSlot(): GhostPickSlot {
if (!pickSlotSingleton) {
pickSlotSingleton = new GhostPickSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
+ getMutationTarget: ghostInstallMutationTargetFor,
showDirectoryDialog: async ({ ghostName, purpose, ghostId, mobilePageId }) => {
if (mobilePageId) {
if (!mobilePluginPages) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
@@ -3232,7 +3592,8 @@ let workspaceSlotSingleton: GhostWorkspaceSlot | null = null;
export function getGhostWorkspaceSlot(): GhostWorkspaceSlot {
if (!workspaceSlotSingleton) {
workspaceSlotSingleton = new GhostWorkspaceSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
+ getMutationTarget: ghostInstallMutationTargetFor,
showDirectoryDialog: async ({ ghostName, purpose, ghostId, mobilePageId }) => {
if (mobilePageId) {
if (!mobilePluginPages) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
@@ -3288,7 +3649,7 @@ export function getGhostWorkspaceSlot(): GhostWorkspaceSlot {
}
const decision = await bridge.request(sessionId, {
ghostId,
- ghostName: findAvailableGhost(ghostId)?.manifest.name ?? ghostId,
+ ghostName: findGhostForInstanceId(ghostId)?.manifest.name ?? ghostId,
lane: 'workspace',
items: [{ name: path.basename(dirAbs), absPath: dirAbs, size: 0, isDirectory: true }],
});
@@ -3333,7 +3694,7 @@ function isLibraryCapableGhost(ghost: InstalledGhost | null | undefined): ghost
}
async function resolveLibraryCapableRoot(ghostId: string): Promise<string | null> {
- if (!isLibraryCapableGhost(findAvailableGhost(ghostId))) return null;
+ if (!isLibraryCapableGhost(findGhostForInstanceId(ghostId))) return null;
const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(ghostId);
if (resolution.kind === 'custom' && resolution.root === null) return null;
return resolution.kind === 'custom' && resolution.root !== null
@@ -3370,7 +3731,7 @@ async function syncMivoLibraryExtraDirFromSlot(
root: string | null,
): Promise<LibraryExtraDirSyncResult> {
if (!libraryExtraDirSync) return 'not-granted';
- if (root !== null && !isLibraryCapableGhost(findAvailableGhost(ghostId))) {
+ if (root !== null && !isLibraryCapableGhost(findGhostForInstanceId(ghostId))) {
return 'not-granted';
}
if (root === null) {
@@ -3398,7 +3759,7 @@ export const GHOST_PREVIEW_OPEN_CHANNEL = 'ghosts:preview-open';
export function getGhostPreviewSlot(): GhostPreviewSlot {
if (!previewSlotSingleton) {
previewSlotSingleton = new GhostPreviewSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
focusedSessionId: () => ghostSessionFocusTracker.current(),
openMobile: (pageId, ghostId, url) => mobilePluginPages?.present(pageId, ghostId, { kind: 'preview', url }) ?? false,
broadcast: (payload) => {
@@ -3440,7 +3801,7 @@ export const GHOST_SCHEDULE_DRAFT_CHANNEL = 'ghosts:schedule-draft';
export function getGhostScheduleSlot(): GhostScheduleSlot {
if (!scheduleSlotSingleton) {
scheduleSlotSingleton = new GhostScheduleSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
sendToMobile: (pageId, payload) => mobilePluginPages?.present(pageId, payload.ghostId, {
kind: 'schedule', name: payload.name, prompt: payload.prompt, intervalMs: payload.intervalMs,
}) ?? false,
@@ -3875,7 +4236,7 @@ async function getGhostConfigurableMediaModels(
ghostId: string,
type: GhostMediaModelType,
): Promise<GhostMediaModelsResult> {
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost || !ghost.enabled) {
return { ok: false, errorCode: 'NOT_AVAILABLE', message: '插件当前不可用' };
}
@@ -3980,7 +4341,7 @@ function getGhostConfiguredMediaModel(
}
const mediaCapability = capability as GhostMediaCapability;
const [type, action] = mediaCapability.split('.') as ['image' | 'video', 'generate' | 'edit'];
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost || !ghost.enabled) {
return { ok: false, errorCode: 'NOT_AVAILABLE', message: '插件当前不可用' };
}
@@ -4596,7 +4957,7 @@ function isGhostBoundaryPending(): boolean {
export function getGhostCindySlot(): GhostCindySlot {
if (!cindySlotSingleton) {
cindySlotSingleton = new GhostCindySlot({
- getGhost: (id) => findAvailableGhost(id),
+ getGhost: findGhostForInstanceId,
getOwnerScopeKey: () => activeOwnerScopeKey(),
isOwnerBoundaryPending: () => isGhostBoundaryPending(),
// model 已在 modelSlot 按白名单校验;归属来源(providerId)按白名单条目
@@ -4989,12 +5350,14 @@ export async function reconcileGhostOauthAccountsForActiveOwner(): Promise<boole
const oauthManager = getGhostOauthAccountManager();
let retryPending = false;
for (const ghost of getGhostManager().list()) {
- await withActiveOwnerGhostOauthMutationLock(ghost.manifest.id, () => {
+ const vaultId = installedGhostStoragePart(ghost);
+ await withActiveOwnerGhostOauthMutationLock(vaultId, () => {
if (activeOwnerScopeKey() !== ownerScope) {
throw new Error('Plugin OAuth owner changed during reconciliation');
}
const reconciliation = oauthManager.reconcileAccountsForInstalledManifestWithResult(
- withRuntimeFiloGoogleClient(ghost.manifest),
+ ghost.manifest,
+ vaultId,
);
if (reconciliation.retryPending) retryPending = true;
});
@@ -5017,7 +5380,7 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
// 意识 OAuth 的 token 端点(Google / Atlassian 等)多在境外。
fetchImpl: (url, init) => outboundFetch(url, init as RequestInit),
openExternal: (url) => shell.openExternal(url),
- // 静态官方前缀照旧放行;其余资格由装入来源与当前组织事实共同判定。
+ // tokenBroker 资格按可信安装事实判定,名称前缀不放行。
// 校验层保持纯函数不感知装入语境,门控在装入闸与连接闸。经独立 oauth-broker
// 服务换/刷 token:serverApiFetch 自带登录 JWT 注入与
// TOKEN_EXPIRED 自动刷新。基地址来自运行期端点清单;当前 region 提供该
@@ -5070,10 +5433,13 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
});
broadcastGhostsChanged(getGhostManager().list(), false, { projectionOnly: true });
},
- isConnectTargetCurrent: (ghostId, secretKey, decl) => {
- const ghost = findAvailableGhost(ghostId);
+ captureConnectTarget: ghostInstallMutationTargetFor,
+ isConnectTargetCurrent: (ghostId, secretKey, decl, expectedConnectTarget) => {
+ const ghost = findGhostForInstanceId(ghostId);
+ if (expectedConnectTarget !== undefined &&
+ (!ghost || installedGhostMutationTargetToken(ghost, activeOwnerScopeKey()) !== expectedConnectTarget)) return false;
const currentDecl = ghost
- ? withRuntimeFiloGoogleClient(ghost.manifest).network?.secrets?.find(
+ ? ghost.manifest.network?.secrets?.find(
(secret) => secret.key === secretKey && secret.source === 'oauth',
)?.oauth
: undefined;
@@ -5081,11 +5447,18 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
},
withMutationLock: withActiveOwnerGhostOauthMutationLock,
isTokenBrokerAuthorized: (ghostId) => isGhostTokenBrokerAuthorized(ghostId, 'runtime'),
+ isHostPrimitiveAuthorized: (ghostId) => isGhostHostPrimitiveAuthorized(ghostId, 'runtime'),
});
}
return ghostOauthManagerSingleton;
}
+export function ghostInstallMutationTargetFor(ghostId: string): string | null {
+ if (isAppSessionBoundaryPending()) return null;
+ const ghost = findGhostForInstanceId(ghostId);
+ return ghost ? installedGhostMutationTargetToken(ghost, activeOwnerScopeKey()) : null;
+}
+
/**
* 多连接(network.connections)管理器单例:连接清单与 token 的主机侧真身,
* /connections 设置页端点与 networkSlot 出网注入共用同一实例。保险库真身 =
@@ -5112,14 +5485,15 @@ let ghostSetupKvStore: GhostKvStore | null = null;
/** 默认 OAuth 账号的授权面陈旧建议;只返回首个凭证槽,保持 envelope 有界。 */
function getGhostOauthReauthSuggest(
runtimeManifest: GhostManifest,
+ storeId: string,
): GhostSetupReauthSuggest | undefined {
const oauthManager = getGhostOauthAccountManager();
return findGhostOauthReauthSuggest(runtimeManifest, (secretKey, decl) => {
const defaultAccount = oauthManager
- .listAccounts(runtimeManifest.id, secretKey)
+ .listAccounts(storeId, secretKey)
.find((account) => account.isDefault);
if (defaultAccount?.status === 'expired') return [];
- return oauthManager.defaultMissingScopes(runtimeManifest.id, secretKey, decl);
+ return oauthManager.defaultMissingScopes(storeId, secretKey, decl);
});
}
@@ -5129,41 +5503,42 @@ function getGhostOauthReauthSuggest(
* omit setup; ghost_call preflight is strict, so storage or manifest drift
* errors block dispatch.
*/
-function getGhostSetupProbes(ghostId: string, runtimeManifest: GhostManifest): GhostSetupProbes {
- if (!ghostSetupKvStore) throw new Error(`ghost setup unavailable: ${ghostId}`);
+function getGhostSetupProbes(storeId: string, runtimeManifest: GhostManifest): GhostSetupProbes {
+ if (!ghostSetupKvStore) throw new Error('ghost setup unavailable: ' + storeId);
const oauthManager = getGhostOauthAccountManager();
const connectionManager = getGhostConnectionManager();
let kvSnapshot: Record<string, unknown> | null = null;
return {
- secretSaved: (key) => ghostSecretSaved(ghostId, key),
- oauthStatus: (key) => {
- const decl = runtimeManifest.network?.secrets?.find((secret) => secret.key === key)?.oauth;
- const accounts = oauthManager.listAccounts(ghostId, key);
- return {
- clientConfigured: oauthManager.clientConfigured(ghostId, key, decl),
- connected: accounts.filter((account) => account.status === 'connected').length,
- expired: accounts.filter((account) => account.status === 'expired').length,
- };
- },
- connectionCount: (key) => connectionManager.list(ghostId, key).length,
- kvValue: (key) => {
- if (kvSnapshot === null) kvSnapshot = ghostSetupKvStore?.readStrict(ghostId) ?? {};
- return kvSnapshot[key];
- },
+ secretSaved: (key) => ghostSecretSaved(storeId, key),
+ oauthStatus: (key) => {
+ const decl = runtimeManifest.network?.secrets?.find((secret) => secret.key === key)?.oauth;
+ const accounts = oauthManager.listAccounts(storeId, key);
+ return {
+ clientConfigured: oauthManager.clientConfigured(storeId, key, decl),
+ connected: accounts.filter((account) => account.status === 'connected').length,
+ expired: accounts.filter((account) => account.status === 'expired').length,
+ };
+ },
+ connectionCount: (key) => connectionManager.list(storeId, key).length,
+ kvValue: (key) => {
+ if (kvSnapshot === null) kvSnapshot = ghostSetupKvStore?.readStrict(storeId) ?? {};
+ return kvSnapshot[key];
+ },
};
}
export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost || !ghostSetupKvStore) {
- throw new Error(`ghost setup unavailable: ${ghostId}`);
+ throw new Error('ghost setup unavailable: ' + ghostId);
}
- const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);
+ const storeId = installedGhostStoragePart(ghost);
+ const runtimeManifest = ghost.manifest;
const assessment = evaluateGhostSetupAssessment(
runtimeManifest,
- getGhostSetupProbes(ghostId, runtimeManifest),
+ getGhostSetupProbes(storeId, runtimeManifest),
{
- revision: getGhostSetupChangeBus().currentRevision(ghostId),
+ revision: getGhostSetupChangeBus().currentRevision(storeId),
strict: true,
additionalGroups: assessGhostHostSetupRequirements(runtimeManifest, {
clientConfigReady: (configId) => configId === 'model-provider' && isModelAccessReady(),
@@ -5175,7 +5550,7 @@ export function getGhostSetupAssessment(ghostId: string): GhostSetupAssessment {
if (assessment.state !== 'ready') return assessment;
return appendReadyGhostOauthReauthSuggest(
assessment,
- getGhostOauthReauthSuggest(runtimeManifest),
+ getGhostOauthReauthSuggest(runtimeManifest, storeId),
);
}
@@ -5192,7 +5567,7 @@ export async function executeGhostSetupAction(args: {
assertCurrent?: () => void;
beforeCommit?: () => Promise<void>;
}): Promise<GhostSetupActionResult> {
- const ghost = findAvailableGhost(args.ghostId);
+ const ghost = findGhostForInstanceId(args.ghostId);
if (!ghost) {
return {
ok: false,
@@ -5200,12 +5575,13 @@ export async function executeGhostSetupAction(args: {
message: t('newChat.pluginSetup.pluginUnavailable'),
};
}
+ const storeId = installedGhostStoragePart(ghost);
if (args.action.kind === 'oauth_connect') {
const secretKey = parseOauthConnectSecretKey(args.action.id);
if (!secretKey) {
return { ok: false, errorCode: 'ACTION_STALE', message: '授权动作已失效' };
}
- const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);
+ const runtimeManifest = ghost.manifest;
const decl = runtimeManifest.network?.secrets?.find(
(secret) => secret.key === secretKey && secret.source === 'oauth',
)?.oauth;
@@ -5216,7 +5592,7 @@ export async function executeGhostSetupAction(args: {
message: '授权声明已变更,请重新尝试',
};
}
- if (decl.tokenBroker !== undefined && !isGhostTokenBrokerAuthorized(args.ghostId, 'runtime')) {
+ if (decl.tokenBroker !== undefined && !isGhostTokenBrokerAuthorized(storeId, 'runtime')) {
return {
ok: false,
errorCode: 'AUTH_FAILED',
@@ -5227,7 +5603,7 @@ export async function executeGhostSetupAction(args: {
try {
remote?.assertCurrent();
const connected = await getGhostOauthAccountManager().connectAccount(
- args.ghostId,
+ storeId,
secretKey,
decl,
{
@@ -5256,7 +5632,7 @@ export async function executeGhostSetupAction(args: {
}
}
- const navigation = ghostSetupNavigationForAction(args.ghostId, args.action);
+ const navigation = ghostSetupNavigationForAction(storeId, args.action);
if (!navigation) {
return { ok: false, errorCode: 'ACTION_STALE', message: '不支持的插件设置动作' };
}
@@ -5290,12 +5666,20 @@ export async function executeGhostSetupInlineAction(
{
getAssessment: getGhostSetupAssessment,
getManifest: (ghostId) => {
- const ghost = findAvailableGhost(ghostId);
- return ghost ? withRuntimeFiloGoogleClient(ghost.manifest) : null;
+ const ghost = findGhostForInstanceId(ghostId);
+ return ghost ? ghost.manifest : null;
+ },
+ storeSecret: (ghostId, secretKey, value) => {
+ const ghost = findGhostForInstanceId(ghostId);
+ return storeGhostSecret(
+ ghost ? installedGhostStoragePart(ghost) : ghostId,
+ secretKey,
+ value,
+ );
},
- storeSecret: storeGhostSecret,
emitChange: (ghostId, secretKey) => {
- getGhostSetupChangeBus().emit(ghostId, {
+ const ghost = findGhostForInstanceId(ghostId);
+ getGhostSetupChangeBus().emit(ghost ? installedGhostStoragePart(ghost) : ghostId, {
source: 'secret',
ref: secretKey,
});
@@ -5313,38 +5697,53 @@ export async function executeGhostSetupInlineAction(
}
/** Only called under the authenticated remote connection-card context. */
-export function bindGhostSetupConnectionAction(args: {
- ghostId: string;
- actionId: string;
- onCommitted(): void;
-}): ((value: import('@cindy/device-link').PluginConnectionInput) => boolean) | null {
- const manifest = findAvailableGhost(args.ghostId)?.manifest;
- if (!manifest) return null;
+export function bindGhostSetupConnectionAction(args: { ghostId: string; actionId: string; onCommitted(): void }):
+ ((value: import('@cindy/device-link').PluginConnectionInput) => boolean) | null {
+ const ghost = findGhostForInstanceId(args.ghostId);
+ const manifest = ghost?.manifest;
+ if (!manifest || !ghost) return null;
const expectedManifest = JSON.stringify(manifest);
- return (value) =>
- executeGhostSetupConnectionSubmission(
- {
- getAssessment: getGhostSetupAssessment,
- getManifest: (ghostId) => findAvailableGhost(ghostId)?.manifest ?? null,
- manager: getGhostConnectionManager(),
- emitChange: (ghostId, key) => {
- getGhostSetupChangeBus().emit(ghostId, { source: 'connection', ref: key });
- },
+ const storagePart = installedGhostStoragePart(ghost);
+ const expectedTarget = ghostInstallMutationTargetFor(storagePart);
+ return value => {
+ if (expectedTarget === null || ghostInstallMutationTargetFor(storagePart) !== expectedTarget) return false;
+ return executeGhostSetupConnectionSubmission({
+ getAssessment: getGhostSetupAssessment,
+ getManifest: ghostId => findGhostForInstanceId(ghostId)?.manifest ?? null,
+ manager: getGhostConnectionManager(),
+ emitChange: (ghostId, key) => {
+ const instance = findGhostForInstanceId(ghostId);
+ getGhostSetupChangeBus().emit(
+ instance ? installedGhostStoragePart(instance) : ghostId,
+ { source: 'connection', ref: key },
+ );
},
- { ...args, value, expectedManifest },
- );
+ }, { ...args, ghostId: storagePart, value, expectedManifest });
+ };
}
/**
* network 槽单例:deps 全部懒取现查——意识清单实扫、凭证保险库现读,
* 用户填/改 key 后下一单即生效,无需任何重启。
*/
+function captureGhostNetworkRequestGuard(ghostId: string): () => void {
+ const ownerScopeKey = activeOwnerScopeKey();
+ const expectedTarget = ghostInstallMutationTargetFor(ghostId);
+ return () => {
+ if (isGhostBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey ||
+ expectedTarget === null || ghostInstallMutationTargetFor(ghostId) !== expectedTarget) {
+ throw new Error('插件安装或账号已变化,本次网络结果已丢弃');
+ }
+ };
+}
+
export function getGhostNetworkSlot(): GhostNetworkSlot {
if (!networkSlotSingleton) {
networkSlotSingleton = new GhostNetworkSlot({
+ captureRequestGuard: captureGhostNetworkRequestGuard,
getGhost: (id) => {
- const ghost = findAvailableGhost(id);
- return ghost ? { ...ghost, manifest: withRuntimeFiloGoogleClient(ghost.manifest) } : null;
+ const ghost = findGhostForInstanceId(id);
+ return ghost;
},
inFlightCallInfo: (callId) => getGhostCardService().inFlightCallInfoOf(callId),
readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),
@@ -5367,12 +5766,13 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {
// 意识,与 cindy 槽产物同一记账口径),走统一入库助手 ingestMedia
// (规则 25)。mime 白名单同一来源(blobStore),槽内归一化后再判。
isSupportedMediaMime: (mime) => supportedMime(mime),
- saveGhostMedia: async ({ ghostId, buffer, mimeType, label, callId }) => {
+ saveGhostMedia: async ({ ghostId, buffer, mimeType, label, callId, assertStillValid }) => {
// 与 cindy 槽 saveGhostMedia 同口径的应用会话守卫:落盘前与
// ingestMedia 每个 await 边界都复查,防止当前进程在 fetch 读取窗口切换
// 账号后,字节仍被登记为 ghost-gallery 作品。
const ownerScopeKey = activeOwnerScopeKey();
const assertOwnerScopeCurrent = (): void => {
+ assertStillValid?.();
if (isGhostBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey) {
throw new Error('媒体任务期间账号已切换,本次结果已丢弃');
}
@@ -5443,7 +5843,7 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {
// 时取第一个)。每单现查现读,设置页增删下一单即生效。
connections: {
hostsFor: (ghostId) => {
- const decls = findAvailableGhost(ghostId)?.manifest.network?.connections ?? [];
+ const decls = (findGhostForInstanceId(ghostId))?.manifest.network?.connections ?? [];
const mgr = getGhostConnectionManager();
const hosts: string[] = [];
for (const decl of decls) {
@@ -5454,7 +5854,7 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {
return hosts;
},
tokenFor: (ghostId, hostname) => {
- const decls = findAvailableGhost(ghostId)?.manifest.network?.connections ?? [];
+ const decls = (findGhostForInstanceId(ghostId))?.manifest.network?.connections ?? [];
const mgr = getGhostConnectionManager();
for (const decl of decls) {
const token = mgr.resolveTokenByHost(ghostId, decl.key, hostname);
@@ -5481,7 +5881,7 @@ let fsSlotSingleton: GhostFsSlot | null = null;
export function getGhostFsSlot(): GhostFsSlot {
if (!fsSlotSingleton) {
fsSlotSingleton = new GhostFsSlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
dataRootDir: () => ownerScopedUserDataPath('ghost-fs'),
// callId → 归属/会话反查:与卡片供片同一本账(ghost_call 派单时
// cardService.registerCall 登记),不信意识自报。
@@ -5523,7 +5923,7 @@ export function getGhostLibrarySlot(): GhostLibrarySlot {
log,
});
librarySlotSingleton = new GhostLibrarySlot({
- getGhost: findAvailableGhost,
+ getGhost: findGhostForInstanceId,
bindingStore,
getDefaultRoot: (ghostId) => ownerScopedUserDataPath('libraries', ghostId),
getStagingRoot: (ghostId) => ownerScopedUserDataPath('library-staging', ghostId),
@@ -5610,7 +6010,32 @@ async function relocateGhostLibraryTo(
candidate: string,
opts?: { allowInsideManagedRoot?: boolean },
): Promise<{ ok: boolean; message?: string }> {
- const releaseMutation = beginGhostMutation();
+ return withGhostLibraryMutation(id, () => relocateGhostLibraryToLocked(id, candidate, opts));
+}
+
+async function withGhostLibraryMutation<T>(id: string, operation: () => Promise<T>): Promise<T> {
+ const expectedTarget = ghostLibraryDeleteTargetFor(id);
+ return getGhostManager().runExclusiveMutation(async () => {
+ if (expectedTarget === null || ghostLibraryDeleteTargetFor(id) !== expectedTarget) {
+ throwIpcError('PRECONDITION_FAILED', 'Library 对应的 Plugin 或账号已变化,请重试');
+ }
+ const releaseMutation = beginGhostMutation();
+ try {
+ return await operation();
+ } finally {
+ releaseMutation();
+ }
+ });
+}
+
+async function relocateGhostLibraryToLocked(
+ id: string,
+ candidate: string,
+ opts?: { allowInsideManagedRoot?: boolean },
+): Promise<{ ok: boolean; message?: string }> {
+ const storagePart = libraryStorageKeyFor(id);
+ if (!storagePart) return { ok: false, message: '非法插件 id' };
+ id = storagePart;
const slot = getGhostLibrarySlot();
slot.setRelocating(id, true);
try {
@@ -5640,6 +6065,11 @@ async function relocateGhostLibraryTo(
await refreshMivoLibraryExtraDirGrant();
return set.ok ? { ok: true } : { ok: false, message: set.message };
}
+ try {
+ await assertLibraryMetaOwner(fromRoot, id);
+ } catch {
+ return { ok: false, message: 'Library 归属无法确认,请先恢复原位置' };
+ }
const result = await migrateGhostLibrary({
ghostId: id,
fromRoot,
@@ -5683,7 +6113,6 @@ async function relocateGhostLibraryTo(
return result.ok ? { ok: true } : { ok: false, message: result.message };
} finally {
slot.setRelocating(id, false);
- releaseMutation();
}
}
@@ -5692,15 +6121,30 @@ async function relocateGhostLibraryTo(
* 不触发 open 的目录创建),漂移/未声明都给结构化结果,渲染层据此出横幅。
*/
export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLibraryOverview> {
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
+ const storagePart = libraryStorageKeyFor(ghostId);
const supported = ghost?.manifest.library === true;
+ if (!storagePart) {
+ return {
+ supported,
+ state: 'unavailable',
+ reason: '非法插件 id',
+ location: 'default',
+ customCandidate: null,
+ usedBytes: 0,
+ fileCount: 0,
+ diskFreeBytes: null,
+ softLimitBytes: DEFAULT_LIBRARY_LIMITS.softLimitBytes,
+ softLimitExceeded: false,
+ orphaned: false,
+ };
+ }
const store = getGhostLibraryBindingStore();
- const binding = await store.getBinding(ghostId);
- const resolution = await store.resolveLibraryRoot(ghostId);
- const root =
- resolution.kind === 'custom' && resolution.root !== null
- ? resolution.root
- : ownerScopedUserDataPath('libraries', ghostId);
+ const binding = await store.getBinding(storagePart);
+ const resolution = await store.resolveLibraryRoot(storagePart);
+ const root = resolution.kind === 'custom' && resolution.root !== null
+ ? resolution.root
+ : ownerScopedUserDataPath('libraries', storagePart);
let usedBytes = 0;
let fileCount = 0;
let orphaned = false;
@@ -5715,7 +6159,9 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
await fs.promises.readFile(path.join(root, '.cindy-library', 'meta.json'), 'utf8'),
) as {
orphaned?: unknown;
+ ghostId?: unknown;
};
+ if (meta?.ghostId !== storagePart) throw new Error('Library owner mismatch');
orphaned = meta.orphaned !== undefined;
try {
const usage = JSON.parse(
@@ -5729,8 +6175,11 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
} catch {
/* 账本缺失按 0 计;设置页可触发重扫 */
}
- } catch {
- /* 尚未创建过 Library = 全零;不是错误 */
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || fs.existsSync(root)) {
+ state = 'unavailable';
+ reason = 'corrupt';
+ }
}
}
let diskFreeBytes: number | null = null;
@@ -5754,6 +6203,20 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
};
}
+function ghostLibraryDeleteTargetFor(ghostId: string): string | null {
+ if (isAppSessionBoundaryPending()) return null;
+ const approvedTarget = ghostInstallMutationTargetFor(ghostId);
+ if (approvedTarget !== null) return approvedTarget;
+ const ghost = findGhostForInstanceId(ghostId);
+ return JSON.stringify([
+ activeOwnerScopeKey(),
+ ghost?.dir ?? null,
+ ghost?.manifest.id ?? null,
+ ghostInstallApprovalToken(ghost?.approval),
+ ghost ? deliveryNamespaceFields(ghost) : null,
+ ]);
+}
+
/**
* 删除 Library(设置页独立确认后的执行体;与卸载是两个操作):作废运行会话,
* 库根 rename 进 owner 级回收站(30 天回滚窗),撤销 binding。调用方(设置页
@@ -5761,23 +6224,52 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
*/
export async function deleteGhostLibraryForActiveOwner(
ghostId: string,
+ expectedTarget = ghostLibraryDeleteTargetFor(ghostId),
): Promise<{ ok: boolean; message?: string }> {
- if (!isValidGhostId(ghostId)) return { ok: false, message: '非法插件 id' };
+ return getGhostManager().runExclusiveMutation(() =>
+ deleteGhostLibraryLocked(ghostId, expectedTarget),
+ );
+}
+
+async function deleteGhostLibraryLocked(
+ ghostId: string,
+ expectedTarget: string | null,
+): Promise<{ ok: boolean; message?: string }> {
+ const storagePart = libraryStorageKeyFor(ghostId);
+ if (!storagePart) return { ok: false, message: '非法插件 id' };
+ const assertCurrent = (): void => {
+ if (expectedTarget === null || ghostLibraryDeleteTargetFor(ghostId) !== expectedTarget) {
+ throw new Error('Library 对应的 Plugin 或账号已变化,请重新确认删除');
+ }
+ };
+ assertCurrent();
const slot = getGhostLibrarySlot();
- slot.setRelocating(ghostId, true);
+ slot.setRelocating(storagePart, true);
try {
- await slot.disposeGhost(ghostId);
- const result = await trashGhostLibrary(ghostId, {
+ await slot.disposeGhost(storagePart);
+ assertCurrent();
+ const result = await trashGhostLibrary(storagePart, {
// 默认根与自定义根都经 binding store 的解析口径(漂移时返回 null → 上层
// 引导恢复位置,不误删)。
resolveLibraryRoot: async (id) => {
const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(id);
- return resolution.kind === 'custom'
- ? resolution.root
- : ownerScopedUserDataPath('libraries', id);
+ assertCurrent();
+ const root = resolution.kind === 'custom' ? resolution.root : ownerScopedUserDataPath('libraries', id);
+ if (!root) return null;
+ try {
+ await assertLibraryMetaOwner(root, id);
+ } catch {
+ return null;
+ }
+ assertCurrent();
+ return root;
+ },
+ trashRoot: () => {
+ assertCurrent();
+ return ownerScopedUserDataPath('libraries-trash');
},
- trashRoot: () => ownerScopedUserDataPath('libraries-trash'),
removeBinding: async (id) => {
+ assertCurrent();
await getGhostLibraryBindingStore().removeBinding(id);
},
log,
@@ -5785,7 +6277,7 @@ export async function deleteGhostLibraryForActiveOwner(
if (result.ok) {
await refreshMivoLibraryExtraDirGrant().catch((error) => {
log.warn('library extraDirs delete sync failed', {
- ghostId,
+ ghostId: storagePart,
error: error instanceof Error ? error.message : String(error),
});
});
@@ -5793,7 +6285,7 @@ export async function deleteGhostLibraryForActiveOwner(
}
return { ok: false, message: result.message };
} finally {
- slot.setRelocating(ghostId, false);
+ slot.setRelocating(storagePart, false);
}
}
@@ -5815,9 +6307,9 @@ export function getGhostLibraryBindingStore(): LibraryBindingStore {
/**
* 官方保留前缀守门(docs/dev-rules/plugin-security-and-authoring.md):packaged 版本上,用户装入
* 通道(install/update/inspect 三个 IPC,即拖入/选文件/forge 转交的共同出口)
- * 对 `cindy-` / `filo-` / `xd-` 前缀 id 一律拒装——抢注同 id 的第三方包会冒充官方身份并
+ * 对 `cindy-` 前缀 id 一律拒装——抢注同 id 的第三方包会冒充官方身份并
* 蹭走凭证别名(用户历史填过的机器级 key 被注入攻击者白名单域名)。
- * dev 构建默认豁免:方便 `cindy-` / `filo-` / `xd-` 官方前缀插件在本地迭代;需要复现
+ * dev 构建默认豁免:方便 `cindy-` 官方前缀插件在本地迭代;需要复现
* packaged 行为时可设置 `XDT_GHOST_RESERVED_PREFIX_GATE=1`,此开关只能收紧、不能放宽。
* 若恢复随包 seed,builtinGhostProvisioner 的内部安装路径不经这些 IPC;不要把本闸套到播种路径。
*/
@@ -5829,14 +6321,14 @@ function rejectReservedPublisherSlug(id: string): void {
function rejectReservedGhostId(id: string): void {
// Member-publisher identity slugs are never installable, including market
// packages and unpackaged dev builds. Official prefix rejection stays
- // packaged-only by default so first-party iteration can still reload cindy-/filo-/xd- plugins.
+ // packaged-only by default so first-party iteration can still reload cindy- plugins.
// The hidden dev override can reproduce the packaged gate but can never disable it.
rejectReservedPublisherSlug(id);
if (!shouldRejectReservedGhostIds(app.isPackaged)) return;
if (!isUserInstallReservedGhostId(id)) return;
throwIpcError(
'GHOST_ID_RESERVED',
- `id "${id}" 使用了官方保留前缀(cindy- / filo- / xd-),用户通道不可装入`,
+ `id "${id}" 使用了官方保留前缀(cindy-),用户通道不可装入`,
);
}
@@ -5849,14 +6341,13 @@ export function rejectReservedGhostIdForCustomMarket(id: string): void {
}
/**
- * tokenBroker 第一方门控·装入闸。官方前缀命中照今天放行;否则问 first-party
- * 判据。不区分 dev/packaged:broker 是服务端资产,dev 也不豁免。
+ * tokenBroker 第一方门控·装入闸。按可信安装事实判定,名称前缀不放行。
+ * 不区分 dev/packaged:broker 是服务端资产,dev 也不豁免。
*/
function rejectUnauthorizedTokenBroker(
manifest: GhostManifest,
overrides?: GhostFirstPartyFactsOverrides,
): void {
- if (isBrokerEligibleGhostId(manifest.id)) return;
const brokered = (manifest.network?.secrets ?? []).some(
(s) => s.oauth?.tokenBroker !== undefined,
);
@@ -5892,6 +6383,8 @@ function throwInstallError(rejection: InstallRejection): never {
throwIpcError('GHOST_COMMAND_CONFLICT', rejection.reason);
case 'state-changed':
throwIpcError('PRECONDITION_FAILED', rejection.reason);
+ case 'namespace-migration-pending':
+ throwIpcError('PRECONDITION_FAILED', rejection.reason);
default:
throwIpcError('INTERNAL', rejection.reason);
}
@@ -5935,7 +6428,11 @@ export async function installAndDock(
* 同一份包)。必填,与 ghostId 同理:新增装入路径无法忘记交出确认结论。
*/
consent: { decision: GhostInstallConsentDecision; manifest: GhostManifest };
+ /** Explicit root is null. Omission is not root. */
+ namespace: string | null;
trustOverride?: GhostHostTrustOverride;
+ registrySource?: 'market' | 'manual' | 'agent-forge' | 'legacy' | 'builtin';
+ pluginId?: string | null;
beforePackagePlacement?: () => void;
},
): Promise<InstalledGhost> {
@@ -5950,14 +6447,20 @@ async function installAndDockLocked(
enable?: boolean;
expectedPackageSha256: string;
consent: { decision: GhostInstallConsentDecision; manifest: GhostManifest };
+ namespace: string | null;
trustOverride?: GhostHostTrustOverride;
installOrigin?: 'agent-forge';
+ registrySource?: 'market' | 'manual' | 'agent-forge' | 'legacy' | 'builtin';
+ pluginId?: string | null;
beforePackagePlacement?: () => void;
},
): Promise<InstalledGhost> {
// 确认依据的 manifest 必须就是 expectedPackageSha256 钉住的那份包;锁内现读受体
// 复核,确认后同 id 被别处装上或包内容变化都不能沿用这次确认。
- const installedBefore = manager.list().find((ghost) => ghost.manifest.id === opts.ghostId);
+ const installedBefore = findInstalledGhostForDeliveryTarget(
+ manager.list(),
+ { ghostId: opts.ghostId, namespace: opts.namespace },
+ );
assertGhostInstallConsent(
opts.consent.decision,
installedBefore,
@@ -5972,6 +6475,9 @@ async function installAndDockLocked(
expectedPackageSha256: opts.expectedPackageSha256,
...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),
...(opts.installOrigin ? { installOrigin: opts.installOrigin } : {}),
+ ...(opts.registrySource ? { registrySource: opts.registrySource } : {}),
+ ...(opts.pluginId ? { pluginId: opts.pluginId } : {}),
+ namespace: opts.namespace,
...(opts.beforePackagePlacement ? { beforePackagePlacement: opts.beforePackagePlacement } : {}),
});
if ('rejection' in result) throwInstallError(result.rejection);
@@ -5983,7 +6489,7 @@ async function installAndDockLocked(
);
}
if (!installedBefore) {
- try { recordGhostAdded(result.ghost.manifest.id); }
+ try { recordGhostAdded(installedGhostStoragePart(result.ghost)); }
catch { log.warn('ghost addition history unavailable'); }
}
// 内置墓碑清除已并入 GhostManager 的 durable install journal(marker.clearBuiltinTombstone
@@ -5993,7 +6499,7 @@ async function installAndDockLocked(
// 顺序刻意:manager.install 内已广播 ghosts:changed(renderer 先注册面板),
// 这里再 setLayout 触发 layout:changed(pane 出现时面板组件必然已就位,规则 7)。
const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest, installedGhostStoragePart(result.ghost));
if (docked) {
const applied = store.setLayout(docked);
if ('rejection' in applied) {
@@ -6014,6 +6520,59 @@ type InspectedGhostPackage = Exclude<
{ rejection: InstallRejection }
>;
+function ghostSourceStateArchiveId(_ghost: InstalledGhost): string {
+ return allocateArchiveInstanceKey();
+}
+
+function readLocalGhostUpdateSource(
+ manager: GhostManager,
+ previousGhost: InstalledGhost,
+ inspected: InspectedGhostPackage,
+ installOrigin?: 'agent-forge',
+): GhostLocalUpdateSourceDecision & {
+ marketRecord: PluginMarketInstallationRecord | null;
+ authorizationOverrides: GhostFirstPartyFactsOverrides;
+} {
+ const instanceId = installedGhostStoragePart(previousGhost);
+ const receipt = previousGhost.approval.state === 'approved'
+ ? manager.readApprovedInstallReceipt(instanceId, previousGhost.approval.revision)
+ : null;
+ let marketRecord: PluginMarketInstallationRecord | null;
+ try {
+ marketRecord = getPluginMarketLedger().bind(
+ ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),
+ ).installationForPlugin({
+ ghostId: previousGhost.manifest.id,
+ ...deliveryNamespaceFields(previousGhost),
+ });
+ } catch {
+ throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');
+ }
+ const nextOrigin = installOrigin ?? 'manual';
+ const decision = classifyGhostLocalUpdateSource({
+ existingSourceChanged: Boolean(marketRecord?.installed) ||
+ (receipt?.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual') !== nextOrigin,
+ previousApprovedReceipt: receipt,
+ inspectedPackage: {
+ ghostId: inspected.manifest.id,
+ namespace: hasDeliveryNamespace(previousGhost) ? previousGhost.namespace : null,
+ packageSha256: inspected.packageSha256,
+ trust: inspected.trust,
+ },
+ });
+ return {
+ ...decision,
+ marketRecord,
+ authorizationOverrides: {
+ ...(hasDeliveryNamespace(previousGhost) ? { namespace: previousGhost.namespace } : {}),
+ installOrigin: nextOrigin,
+ marketRecord: null,
+ trustedSource: null,
+ legacyFirstPartyEligible: decision.legacyFirstPartyEligible,
+ },
+ };
+}
+
/**
* 本地包原位更新的共享事务。调用方必须已经持有 owner lease 和对应 ghostId
* 的安装锁;Renderer 导入与 Forge 显式安装共用,避免两条路径在运行时、OAuth、
@@ -6025,6 +6584,7 @@ async function updateLocalGhostPackageLocked(
inspected: InspectedGhostPackage,
expectedPackageSha256: string,
expectedInstalledApproval: string,
+ expectedInstalledInstanceId: string,
consent: GhostInstallConsentDecision,
installOrigin?: 'agent-forge',
isCurrent?: () => boolean,
@@ -6039,26 +6599,27 @@ async function updateLocalGhostPackageLocked(
const marketLedger = getPluginMarketLedger().bind(
ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),
);
- const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
+ const previousGhost = findInstalledGhostForLocalUpdate(
+ manager.list(), inspected.manifest.id, expectedInstalledInstanceId, expectedInstalledApproval,
+ );
+ if (!previousGhost) throwIpcError('PRECONDITION_FAILED', '目标插件实例已变化,请刷新后重试');
+ if (installOrigin !== 'agent-forge' && typeof previousGhost.namespace === 'string') {
+ throwIpcError('PRECONDITION_FAILED', '本地文件不能更新企业插件实例,请另装一个 root 实例');
+ }
+ const instanceId = installedGhostStoragePart(previousGhost);
// 锁内按真实包与现读受体复核锁外求得的确认;熄灯之前拒绝,不打断正在用的旧版本。
assertGhostInstallConsent(consent, previousGhost, inspected.manifest, expectedPackageSha256);
- runtime.stop(inspected.manifest.id);
+ const { marketRecord, sourceChanged, authorizationOverrides } = readLocalGhostUpdateSource(
+ manager, previousGhost, inspected, installOrigin,
+ );
+ if (sourceChanged) assertGhostRelocationIdle(instanceId);
+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest, authorizationOverrides);
+ runtime.stop(instanceId);
// 等待失败表示旧进程仍可能存活;此时不能恢复 resident,否则会产生
// 两份后台进程。仅在确认退出后的更新阶段失败时恢复旧版本。
- await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);
- let marketRecord: PluginMarketInstallationRecord | null;
- try {
- marketRecord = marketLedger.installationForGhost(inspected.manifest.id);
- } catch (error) {
- if (previousGhost) spawnIfResident(previousGhost);
- 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');
- }
+ await getGhostNodeRuntimeBroker().stopAndWait(instanceId);
// 用户已明确选择了这份本地真实包:同 id 可以原位替换,市场来源不是永久所有权。
- // 替换前先切断旧市场更新路由;落位失败再恢复,不清理按 ghostId 保存的用户状态。
+ // 替换前先切断旧市场更新路由;用户状态由安装事务隔离归档,落位失败再恢复。
const detachMarketRecord = Boolean(marketRecord?.installed);
const restoreMarketRecord = (): void => {
if (!detachMarketRecord || !marketRecord) return;
@@ -6074,14 +6635,14 @@ async function updateLocalGhostPackageLocked(
});
}
};
- if (detachMarketRecord) {
+ if (detachMarketRecord && marketRecord) {
try {
// 先持久化切断自动更新路由,再改真实包。普通本地/Forge 换源不是
// 用户显式卸载,不得产生 default-install opt-out。
- marketLedger.markRemoved(inspected.manifest.id, null);
+ marketLedger.markRemovedRecord(marketRecord, null);
} catch (error) {
restoreMarketRecord();
- if (previousGhost) spawnIfResident(previousGhost);
+ spawnIfResident(previousGhost);
log.warn('failed to detach Plugin market provenance before local update', {
ghostId: inspected.manifest.id,
error: error instanceof Error ? error.message : String(error),
@@ -6089,26 +6650,27 @@ async function updateLocalGhostPackageLocked(
throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');
}
}
- getGhostAgentSlot().clearGhost(inspected.manifest.id);
- getGhostErrandSlot().clearGhost(inspected.manifest.id);
+ getGhostAgentSlot().clearGhost(instanceId);
+ getGhostErrandSlot().clearGhost(instanceId);
let result: Awaited<ReturnType<typeof manager.update>>;
let packagePlaced = false;
try {
- result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id, () =>
- manager.update(cindyFilePath, {
+ result = await withActiveOwnerGhostOauthMutationLock(
+ instanceId,
+ () =>
+ manager.update(cindyFilePath, {
taskCapabilityApproved: confirmedTaskCapability(consent, previousGhost, inspected.manifest),
expectedPackageSha256,
expectedInstalledApproval,
- ...(installOrigin ? { installOrigin } : {}),
- ...(previousGhost
- ? {
- beforePackageCommit: () =>
- getGhostOauthAccountManager().prepareAccountsForChangedClients(
- withRuntimeFiloGoogleClient(previousGhost.manifest),
- withRuntimeFiloGoogleClient(inspected.canonicalManifest),
- ),
- }
- : {}),
+ installOrigin: installOrigin ?? 'manual',
+ ...(sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(previousGhost) } : {}),
+ ...deliveryNamespaceFields(previousGhost),
+ beforePackageCommit: () =>
+ getGhostOauthAccountManager().prepareAccountsForChangedClients(
+ previousGhost.manifest,
+ inspected.canonicalManifest,
+ instanceId,
+ ),
onPackagePlaced: () => {
packagePlaced = true;
},
@@ -6117,10 +6679,11 @@ async function updateLocalGhostPackageLocked(
} catch (err) {
if (!packagePlaced) {
restoreMarketRecord();
- if (previousGhost) spawnIfResident(previousGhost);
+ spawnIfResident(previousGhost);
throw err;
}
- const placed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);
+ const placed = findInstalledGhostByInstanceId(manager.list(), instanceId) ??
+ manager.list().find((ghost) => ghost.dir === previousGhost.dir);
if (!placed) throw err;
log.warn('local ghost post-placement notification failed', {
ghostId: inspected.manifest.id,
@@ -6132,13 +6695,13 @@ async function updateLocalGhostPackageLocked(
// 回滚失败时安装目录可能已是新字节或缺失,不能恢复旧 runtime 或旧市场来源路由。
if (!(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {
restoreMarketRecord();
- if (previousGhost) spawnIfResident(previousGhost);
+ spawnIfResident(previousGhost);
}
throwInstallError(result.rejection);
}
- runtime.resetFuse(inspected.manifest.id);
+ runtime.resetFuse(instanceId);
const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest, installedGhostStoragePart(result.ghost));
if (docked) {
const applied = store.setLayout(docked);
if ('rejection' in applied) {
@@ -6184,11 +6747,31 @@ export async function installOrUpdateLocalGhostPackageFromForge(
const user = authState.isAuthenticated ? authState.user : null;
const membershipKind = user?.membershipKind ?? 'personal';
const installOrigin = forgeInstallOriginForMembership(membershipKind);
- rejectUnauthorizedTokenBroker(inspected.manifest, installOrigin ? { installOrigin } : undefined);
+ let forgeNamespace: string | null = null;
+ if (membershipKind === 'org') {
+ if (!user?.orgSlug || !isValidPluginNamespace(user.orgSlug)) {
+ throwIpcError('PRECONDITION_FAILED', '无法确认当前企业身份,请重新登录后重试');
+ }
+ forgeNamespace = user.orgSlug;
+ }
+ const existingForForge = findInstalledGhostForDeliveryTarget(
+ manager.list(),
+ { ghostId: inspected.manifest.id, namespace: forgeNamespace },
+ );
+ // A same-id install in another namespace is a new instance, not an update.
+ if (!existingForForge && !isValidNewGhostId(inspected.manifest.id)) {
+ throwIpcError('GHOST_FILE_INVALID', '新建插件 id 必须以小写字母开头,只能包含小写字母、数字和连字符,最长 32 个字符');
+ }
+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest, existingForForge
+ ? readLocalGhostUpdateSource(manager, existingForForge, inspected, installOrigin).authorizationOverrides
+ : {
+ ...(installOrigin ? { installOrigin } : {}),
+ namespace: forgeNamespace ?? null,
+ });
// 首装与扩权更新先在任务里请用户确认;权限没变多的更新不打扰。
const consent = await obtainGhostInstallConsent(
{ mode: 'prompt', prompt: expected.consentPrompt, initiator: 'agent', origin: 'forge' },
- manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id),
+ existingForForge,
inspected.manifest,
inspected.packageSha256,
);
@@ -6221,7 +6804,10 @@ export async function installOrUpdateLocalGhostPackageFromForge(
// 确认已在 owner 租约外完成;落位再用 packing 时钉住的 owner 取租约。
const releaseMutation = beginGhostMutation(expected.mutationOwner);
try {
- const installed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);
+ const installed = findInstalledGhostForDeliveryTarget(
+ manager.list(),
+ { ghostId: inspected.manifest.id, namespace: forgeNamespace },
+ );
if (!installed) {
return {
ghost: await installAndDockLocked(manager, cindyFilePath, {
@@ -6230,9 +6816,10 @@ export async function installOrUpdateLocalGhostPackageFromForge(
expectedPackageSha256: expected.packageSha256,
consent: { decision: consent, manifest: inspected.manifest },
...(installOrigin ? { installOrigin } : {}),
+ namespace: forgeNamespace,
}).then((ghost) => {
try {
- markGhostRecommendationInstalled(ghost.manifest.id);
+ markGhostRecommendationInstalled(installedGhostStoragePart(ghost));
} catch {
log.warn('ghost recommendation install history unavailable');
}
@@ -6248,6 +6835,7 @@ export async function installOrUpdateLocalGhostPackageFromForge(
inspected,
expected.packageSha256,
ghostInstallApprovalToken(installed.approval),
+ installedGhostStoragePart(installed),
consent,
installOrigin,
expected.isCurrent,
@@ -6279,16 +6867,19 @@ export async function installOrUpdateMarketGhostPackage(
expected: {
ghostId: string;
version: string;
+ namespace?: string | null;
+ sourceChanged?: boolean;
/** receipt 模型并发护栏:更新分支比对 receipt 派生 token(与 main 硬化叠加,决策 A)。 */
expectedInstalledApproval?: string;
/**
* Organization server-market packages pass this Host-built fact because the
- * ledger row is written after install/update. Official-prefix ids never
- * consult it (they short-circuit). Not "first install only": the same
- * commitDownloadedPackage path covers org server-market install, update,
+ * ledger row is written after install/update. Not "first install only": the
+ * same commitDownloadedPackage path covers org server-market install, update,
* defaultInstall, and source replacement.
*/
pendingMarketRecord?: GhostFirstPartyPendingMarketRecord;
+ /** Server-market resource id. Recorded on the instance so another market does not reuse it. */
+ pluginId?: string;
/** 自定义 Git/本地市场在打包前读取的 Manifest,用于防止打包窗口内能力扩张。 */
manifestCap?: GhostManifest;
beforeCommitInLock?: () => void;
@@ -6321,9 +6912,13 @@ async function installOrUpdateMarketGhostPackageLocked(
expected: {
ghostId: string;
version: string;
+ namespace?: string | null;
+ sourceChanged?: boolean;
expectedInstalledApproval?: string;
/** Same Host-built org server-market fact as the exported entry; not first-install only. */
pendingMarketRecord?: GhostFirstPartyPendingMarketRecord;
+ /** Server-market resource id. Recorded on the instance so another market does not reuse it. */
+ pluginId?: string;
manifestCap?: GhostManifest;
beforeCommitInLock?: () => void;
/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */
@@ -6341,6 +6936,8 @@ async function installOrUpdateMarketGhostPackageLocked(
let releaseMutation: (() => void) | null = null;
try {
const manager = getGhostManager();
+ const registryError = blockedInstanceRegistryMarketError(manager.isInstanceRegistryBlocked());
+ if (registryError) throwIpcError('PRECONDITION_FAILED', registryError);
const inspected = await manager.inspect(cindyFilePath);
if ('rejection' in inspected) throwInstallError(inspected.rejection);
const commitEvidence: MarketGhostPackageCommitEvidence = {
@@ -6358,14 +6955,25 @@ async function installOrUpdateMarketGhostPackageLocked(
throwIpcError('GHOST_FILE_INVALID', '下载包清单与市场 Release 不一致');
}
const trustOverride: GhostHostTrustOverride | undefined =
- expected.officialCindyGithub === true && expected.ghostId === 'cindy-github'
+ expected.officialCindyGithub === true && expected.ghostId === 'cindy-github' &&
+ expected.namespace == null
? 'cindy-official'
: undefined;
requireGhostAvailableForActiveSession(expected.ghostId);
// 自定义 Git/本地市场的活目录可能在发现后、打包前变化;它们传入发现时的
// Manifest 作为 TOCTOU 上限。官方市场由服务端 Release SHA 绑定真实包,目录
// Manifest 只用于展示,不参与这里的安装准入。
- const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
+ const marketNamespace: string | null = hasDeliveryNamespace(expected) ? expected.namespace : null;
+ const installIdentity = createPluginLogicalIdentity(marketNamespace, expected.ghostId);
+ const installed = findInstalledGhostByIdentity(manager.list(), installIdentity);
+ const placementError = organizationMarketPlacementError({
+ scope: expected.pendingMarketRecord?.scope ?? null,
+ requestedNamespace: marketNamespace,
+ installedRelId: installed ? installedGhostPhysicalRelId(installed) : null,
+ });
+ if (placementError) {
+ throwIpcError('PRECONDITION_FAILED', placementError);
+ }
if (expected.manifestCap) {
const undeclaredCapabilities = unreviewedGhostPermissionItems(
expected.manifestCap,
@@ -6392,17 +7000,19 @@ async function installOrUpdateMarketGhostPackageLocked(
);
}
}
- rejectUnauthorizedTokenBroker(
- inspected.canonicalManifest,
- expected.pendingMarketRecord !== undefined
+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest, {
+ namespace: marketNamespace,
+ legacyFirstPartyEligible: !expected.sourceChanged && installed != null &&
+ manager.readLegacyFirstPartyEligible(installedGhostStoragePart(installed)),
+ ...(expected.pendingMarketRecord !== undefined
? {
marketRecord: bindPendingMarketRecordToInspectedPackage(
expected.pendingMarketRecord,
inspected.packageSha256,
),
}
- : undefined,
- );
+ : {}),
+ });
// 用户确认在锁外求得;这里用即将落位的真实包与锁内现读的受体复核,确认后
// 包内容或已装版本变了就拒绝,后台更新遇到需要确认的扩权直接放弃本轮。
@@ -6427,28 +7037,32 @@ async function installOrUpdateMarketGhostPackageLocked(
const installedGhost = await installAndDock(manager, cindyFilePath, {
ghostId: expected.ghostId,
enable: true,
+ registrySource: 'market',
+ ...(expected.pluginId ? { pluginId: expected.pluginId } : {}),
expectedPackageSha256: inspected.packageSha256,
consent: { decision: expected.consent, manifest: inspected.manifest },
beforePackagePlacement: expected.beforeCommitInLock,
...(trustOverride ? { trustOverride } : {}),
+ namespace: marketNamespace,
});
await expected.afterCommitInLock?.(installedGhost, commitEvidence);
return installedGhost;
}
expected.beforeCommitInLock?.();
+ if (expected.sourceChanged) assertGhostRelocationIdle(installedGhostStoragePart(installed));
const runtime = getGhostRuntime();
- runtime.stop(expected.ghostId);
+ runtime.stop(installedGhostStoragePart(installed));
// 无法确认旧进程已退出时保持停止态,不能启动第二份 resident。只有旧进程
// 已确认退出、后续目录更新失败时,才恢复原版本。
- await getGhostNodeRuntimeBroker().stopAndWait(expected.ghostId);
+ await getGhostNodeRuntimeBroker().stopAndWait(installedGhostStoragePart(installed));
let result: Awaited<ReturnType<typeof manager.update>>;
let packagePlaced = false;
try {
// 市场更新同样会原位 rename 插件目录。Windows 上不能只发停止信号,
// 必须确认旧 utilityProcess 已离开,否则入口文件仍可能被占用而报 EPERM。
- getGhostAgentSlot().clearGhost(expected.ghostId);
- getGhostErrandSlot().clearGhost(expected.ghostId);
+ getGhostAgentSlot().clearGhost(installedGhostStoragePart(installed));
+ getGhostErrandSlot().clearGhost(installedGhostStoragePart(installed));
// receipt 模型下更新必须绑定 receipt token(决策 A:与 main 的 sha 钉扎叠加),
// 否则并发批准变更绕不过去。
if (!expected.expectedInstalledApproval) {
@@ -6459,16 +7073,19 @@ async function installOrUpdateMarketGhostPackageLocked(
}
// Lock order: owner lease -> install lock -> OAuth security lock. Keep
// the strict lock through package swap, receipt commit, and compensation.
- result = await withActiveOwnerGhostOauthMutationLock(expected.ghostId, () =>
+ result = await withActiveOwnerGhostOauthMutationLock(installedGhostStoragePart(installed), () =>
manager.update(cindyFilePath, {
taskCapabilityApproved: confirmedTaskCapability(expected.consent, installed, inspected.manifest),
expectedPackageSha256: inspected.packageSha256,
expectedInstalledApproval: expected.expectedInstalledApproval!,
+ ...(expected.sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(installed) } : {}),
...(trustOverride ? { trustOverride } : {}),
+ namespace: marketNamespace,
beforePackageCommit: () =>
getGhostOauthAccountManager().prepareAccountsForChangedClients(
- withRuntimeFiloGoogleClient(installed.manifest),
- withRuntimeFiloGoogleClient(inspected.canonicalManifest),
+ installed.manifest,
+ inspected.canonicalManifest,
+ installedGhostStoragePart(installed),
),
onPackagePlaced: () => {
packagePlaced = true;
@@ -6481,7 +7098,7 @@ async function installOrUpdateMarketGhostPackageLocked(
spawnIfResident(installed);
throw error;
}
- const placed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
+ const placed = findInstalledGhostByIdentity(manager.list(), installIdentity);
if (!placed) throw error;
log.warn('market ghost post-placement notification failed', {
ghostId: expected.ghostId,
@@ -6497,9 +7114,9 @@ async function installOrUpdateMarketGhostPackageLocked(
}
throwInstallError(result.rejection);
}
- runtime.resetFuse(expected.ghostId);
+ runtime.resetFuse(installedGhostStoragePart(result.ghost));
const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest, installedGhostStoragePart(result.ghost));
if (docked) {
const applied = store.setLayout(docked);
if ('rejection' in applied) {
@@ -6518,7 +7135,7 @@ async function installOrUpdateMarketGhostPackageLocked(
}
type GhostUninstallLedgerCompletion = () => Promise<void>;
-type GhostUninstallLedgerPreparer = (ghostId: string) => GhostUninstallLedgerCompletion | null;
+type GhostUninstallLedgerPreparer = (target: string | InstalledGhost) => GhostUninstallLedgerCompletion | null;
let prepareGhostUninstallLedgerCompletion: GhostUninstallLedgerPreparer | null = null;
@@ -6538,11 +7155,20 @@ export async function uninstallGhostAndCleanup(
id: string,
options?: { skipMarketLedger?: boolean },
): Promise<void> {
- // 按 ghostId 与装入/更新互斥:卸载与同 id 的市场/本地装入不得交错,否则
- // 市场装入的"目标是否已装"判定会被本卸载在其落位前抽走(反之亦然)。
- return withGhostInstallLock(id, () =>
- withActiveOwnerGhostOauthMutationLock(id, () => uninstallGhostAndCleanupLocked(id, options)),
- );
+ // Install lock is the catalog ghostId so public and org instances of the
+ // same name stay serial. OAuth/vault lock is the storage part, never a
+ // slashy `_ns/acme/helper.lock` path.
+ const identity = parsePluginInstanceId(id);
+ if (!identity) {
+ throwIpcError('INVALID_PARAMS', 'id must be a valid Ghost id');
+ }
+ return withGhostInstallLock(identity.ghostId, () => {
+ const ghost = findGhostForInstanceId(id);
+ if (!ghost) throwIpcError('NOT_FOUND', '目标插件实例已不存在');
+ return withActiveOwnerGhostOauthMutationLock(installedGhostStoragePart(ghost), () =>
+ uninstallGhostAndCleanupLocked(id, options),
+ );
+ });
}
async function uninstallGhostAndCleanupLocked(
@@ -6552,46 +7178,53 @@ async function uninstallGhostAndCleanupLocked(
const releaseMutation = beginGhostMutation();
try {
requireGhostAvailableForActiveSession(id);
+ const ghost = findGhostForInstanceId(id);
+ if (!ghost) throwIpcError('NOT_FOUND', '目标插件实例已不存在');
+ // In-place migrated org plugins keep the original directory. Physical keys
+ // must follow that directory, not the namespaced logical identity.
+ const relId = installedGhostPhysicalRelId(ghost);
+ const storagePart = installedGhostStoragePart(ghost);
+ getBotAuthorizationService()?.invalidatePlugin(storagePart);
const completeLedger =
options?.skipMarketLedger === true
? null
- : (prepareGhostUninstallLedgerCompletion?.(id) ?? null);
+ : (prepareGhostUninstallLedgerCompletion?.(ghost) ?? null);
const manager = getGhostManager();
const runtime = getGhostRuntime();
// Library 的 orphaned 标记要在 uninstall 之前取显示名(收走后 list 里就没了)。
- const libraryDisplayName =
- manager.list().find((g) => g.manifest.id === id)?.manifest.name ?? id;
- runtime.stop(id);
- await getGhostNodeRuntimeBroker().stopAndWait(id);
- getGhostAgentSlot().clearGhost(id);
- getGhostErrandSlot().clearGhost(id);
- getGhostSubscriptionGateway().dropGhost(id);
- const downloadRoot = ownerScopedUserDataPath('plugin-downloads', id);
+ const libraryDisplayName = ghost.manifest.name;
+ runtime.stop(storagePart);
+ await getGhostNodeRuntimeBroker().stopAndWait(storagePart);
+ getGhostAgentSlot().clearGhost(storagePart);
+ getGhostErrandSlot().clearGhost(storagePart);
+ getGhostSubscriptionGateway().dropGhost(storagePart);
+ const downloadRoot = ownerScopedUserDataPath('plugin-downloads', storagePart);
const downloadScope = activeOwnerScopeKey();
- if (!pluginTaskUninstaller) throw new Error('Plugin task storage is not ready for uninstall');
- await pluginTaskUninstaller(id, async () => {
- const result = await manager.uninstall(id, { notify: false });
+ const uninstallTasks = pluginTaskUninstaller;
+ if (!uninstallTasks) throw new Error('Plugin task storage is not ready for uninstall');
+ await manager.runExclusiveMutation(mutation => uninstallTasks(storagePart, async () => {
+ const result = await mutation.uninstall(relId, { notify: false });
if ('rejection' in result) throwUninstallError(result.rejection);
- });
- await pluginDownloads.removePlugin(id, downloadRoot, downloadScope).catch(err => log.warn('plugin download cache cleanup failed', { id, error: String(err) }));
- removeGhostSecrets(id);
+ }));
+ await pluginDownloads.removePlugin(storagePart, downloadRoot, downloadScope).catch(err => log.warn('plugin download cache cleanup failed', { id: storagePart, error: String(err) }));
+ removeGhostSecrets(storagePart);
removeGhostKvBestEffort(
createGhostKvStore({
getRootDir: () => ownerScopedUserDataPath('ghost-kv'),
log,
}),
- id,
+ storagePart,
log,
);
- if (isValidGhostId(id)) {
+ if (storagePart) {
try {
- await fs.promises.rm(ownerScopedUserDataPath('ghost-fs', id), {
+ await fs.promises.rm(ownerScopedUserDataPath('ghost-fs', storagePart), {
recursive: true,
force: true,
});
} catch (err) {
log.warn('ghost-fs 私有目录回收失败', {
- id,
+ id: storagePart,
error: err instanceof Error ? err.message : String(err),
});
}
@@ -6602,11 +7235,11 @@ async function uninstallGhostAndCleanupLocked(
// 存储位置不因重装消失(对齐 pick-grants 先例)。best-effort:失败只
// warn,不把卸载报成失败(与上面清账同纪律)。
try {
- await getGhostLibrarySlot().disposeGhost(id);
+ await getGhostLibrarySlot().disposeGhost(storagePart);
await refreshMivoLibraryExtraDirGrant();
const vault = new LibraryVault({
- rootDir: () => ownerScopedUserDataPath('libraries', id),
- ghostId: id,
+ rootDir: () => ownerScopedUserDataPath('libraries', storagePart),
+ ghostId: storagePart,
log,
});
await vault.open();
@@ -6627,7 +7260,7 @@ async function uninstallGhostAndCleanupLocked(
// 卸载是用户明确动作,失败只记日志:包已经收走了,不能因为清账失败把
// 卸载报成失败(与上面 ghost-fs / kv 清理同纪律)。
try {
- const removed = await ledger.removeRefs({ refKind: 'ghost-deposit', refId: id });
+ const removed = await ledger.removeRefs({ refKind: 'ghost-deposit', refId: storagePart });
if (removed > 0) log.info('ghost deposit media refs removed', { id, removed });
} catch (err) {
log.warn('ghost deposit media refs 清理失败', {
@@ -6637,7 +7270,7 @@ async function uninstallGhostAndCleanupLocked(
}
let recentIds: string[] | null = null;
try {
- recentIds = forgetGhostRecentUsage(id);
+ recentIds = forgetGhostRecentUsage(storagePart);
} catch (error) {
log.warn('ghost recent usage 清理失败', {
id,
@@ -6645,14 +7278,14 @@ async function uninstallGhostAndCleanupLocked(
});
}
try {
- forgetGhostRecommendations(id);
+ forgetGhostRecommendations(storagePart);
} catch {
log.warn('ghost recommendation cleanup unavailable', { id });
}
// 未读随意识一起走:包都没了还留一颗点,用户既点不开也清不掉。
// 限速记账一并抹掉,重装后的第一条不该被上一世的时刻挡住。
- extinguishGhostUnread(id);
- badgeSlotSingleton?.forget(id);
+ extinguishGhostUnread(storagePart);
+ badgeSlotSingleton?.forget(storagePart);
// 卸载刚落地,manager.list() 就是当下的全部事实(哪怕是空表)——标权威,
// 好让「卸掉最后一个插件」也能把账本里的孤儿记录一并清掉。
broadcastGhostsChanged(manager.list(), true);
@@ -6682,9 +7315,10 @@ export function isBuiltinGhostRemovedByUser(id: string): boolean {
* "该在场了"时机的统一入口(应用启动扫描 / 装入即开 / 唤醒 / 更新换代后)。
* spawn 幂等,重复调用零成本;失败走熔断记账,不抛出(fire-and-forget)。
*/
-function spawnIfResident(ghost: InstalledGhost): void {
+function spawnIfResident(ghost: InstalledGhost, allowPendingLegacy = false): void {
spawnResidentGhost(ghost, {
isAvailable: isGhostAvailableForActiveSession,
+ allowPendingLegacy,
startNode: (installed) => getGhostNodeRuntimeBroker().startResident(installed),
spawnBrowser: (installed) => getGhostRuntime().spawn(installed),
warn: (message, fields) => log.warn(message, fields),
@@ -6714,32 +7348,40 @@ function readLegacyEncryptedSecret(file: string): LegacyMigrationRead<string> {
}
-async function setGhostEnabledForUser(id: string, enabled: boolean) {
+async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInstalledApproval?: string) {
+ const target = findGhostForPhysicalStoragePart(id);
+ if (!target) throwIpcError('NOT_FOUND', '目标插件实例已不存在');
+ const approvalToken = ghostInstallApprovalToken(target.approval);
+ if (expectedInstalledApproval !== undefined && expectedInstalledApproval !== approvalToken) {
+ throwIpcError('NOT_FOUND', '目标插件安装已变更');
+ }
requireGhostAvailableForActiveSession(id);
const manager = getGhostManager();
const runtime = getGhostRuntime();
+ const relId = installedGhostPhysicalRelId(target);
+ const storagePart = installedGhostStoragePart(target);
// 同 install/update 的 owner 租约:setEnabled 先 await pathExists(旧 owner 的
// 安装目录)再动态写 receipt —— 不持租约,这个异步窗口里切号落定会拿 A 的镜像
// 状态改 B 的 receipt(启停同时落在两个 owner 的两半)。
const releaseMutation = beginGhostMutation(captureGhostMutationOwner());
try {
if (!enabled) {
- runtime.stop(id); // 沉睡立即熄灯
- getGhostNodeRuntimeBroker().stop(id); // 随包 Node 也立即关闭
- getGhostSubscriptionGateway().dropGhost(id); // 订阅态清零(缓冲/熔断/seq)
+ runtime.stop(storagePart); // 沉睡立即熄灯
+ getGhostNodeRuntimeBroker().stop(storagePart); // 随包 Node 也立即关闭
+ getGhostSubscriptionGateway().dropGhost(storagePart); // 订阅态清零(缓冲/熔断/seq)
// 与更新/撤销路径同款:agent 工具授权与 errand 节流/在途记录不跨停用存活,
// 重新启用后从干净状态开始。
- getGhostAgentSlot().clearGhost(id);
- getGhostErrandSlot().clearGhost(id);
+ getGhostAgentSlot().clearGhost(storagePart);
+ getGhostErrandSlot().clearGhost(storagePart);
// 停用即熄灯 Library 会话:db worker 终止、handle 作废——被禁用的插件
// 不得继续后台读写(数据本体不动,重新启用后重开)。
- await getGhostLibrarySlot().disposeGhost(id);
+ await getGhostLibrarySlot().disposeGhost(storagePart);
}
- const result = await manager.setEnabled(id, enabled);
+ const result = await manager.setEnabled(relId, enabled, expectedInstalledApproval ?? approvalToken);
if ('rejection' in result) throwUninstallError(result.rejection);
if (enabled) {
- runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起
- const ghost = findAvailableGhost(id);
+ runtime.resetFuse(storagePart); // 重新唤醒 = 清熔断记账,可再拉起
+ const ghost = findGhostForPhysicalStoragePart(storagePart);
if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动
resumeGhostUnreadProjection(id); // 沉睡期间保留的那颗点回来(#1421)
await refreshMivoLibraryExtraDirGrant().catch((error) => {
@@ -6772,10 +7414,10 @@ async function setGhostEnabledForUser(id: string, enabled: boolean) {
export function registerGhostIpc(): void {
registerGhostCardRemoteProvider((id) => {
- const ghost = availableGhosts().find((item) => item.manifest.id === id);
+ const ghost = findGhostForRemotePluginIdentity(availableGhosts(), id);
return ghost ? { name: ghost.manifest.name, iconDataUrl: ghost.iconDataUrl } : undefined;
}, {
- externalLinks: id => findAvailableGhost(id)?.manifest.card?.externalLinks === true,
+ externalLinks: id => findGhostForPhysicalStoragePart(id)?.manifest.card?.externalLinks === true,
dispatch: async (callId, actionId, prompt, pageId, ghostId, controllerId) => {
if (!mobilePluginPages) return false;
mobilePluginPages.assertInteraction(pageId, ghostId, controllerId);
@@ -6802,12 +7444,15 @@ export function registerGhostIpc(): void {
},
setupAssessment: getGhostSetupAssessment,
configuration: (id, assessment) => {
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
if (!ghost) throw new Error('PLUGIN_UNAVAILABLE');
- const manifest = withRuntimeFiloGoogleClient(ghost.manifest);
- return mobilePluginConfiguration(manifest, getGhostSetupProbes(id, manifest), assessment);
+ const storeId = installedGhostStoragePart(ghost);
+ return mobilePluginConfiguration(ghost.manifest, getGhostSetupProbes(storeId, ghost.manifest), assessment);
+ },
+ runtimeState: (id) => {
+ const ghost = findGhostForInstanceId(id);
+ return runtime.stateOf(ghost ? installedGhostStoragePart(ghost) : id);
},
- runtimeState: id => runtime.stateOf(id),
revision: ghost => JSON.stringify([ghost.manifest.version, ghostInstallApprovalToken(ghost.approval)]),
captureOwner: () => { const scope = captureDataOwnerBroadcastScope(); return () => isDataOwnerBroadcastScopeCurrent(scope); },
// This existing peer fence is invalidated on disconnect, revoke, owner switch and relay teardown.
@@ -6819,20 +7464,17 @@ export function registerGhostIpc(): void {
asset: readMobilePageChunk,
connect: async (ghost, pageId, channels) => {
await runtime.spawn(ghost);
- await invokeGhostMobileRelay(ghost.manifest.id, { op: 'connect', pageId, channels });
+ await invokeGhostMobileRelay(ghost, { op: 'connect', pageId, channels });
+ },
+ post: async (ghost, pageId, channel, data) => { await invokeGhostMobileRelay(ghost, { op: 'post', pageId, channel, data }); },
+ poll: async (ghost, pageId, after) => await invokeGhostMobileRelay(ghost, { op: 'poll', pageId, after }) as PluginPagePoll['events'],
+ disconnect: async (id, pageId) => {
+ const ghost = findGhostForPhysicalStoragePart(id);
+ if (ghost) await invokeGhostMobileRelay(ghost, { op: 'disconnect', pageId });
},
- post: async (ghost, pageId, channel, data) => { await invokeGhostMobileRelay(ghost.manifest.id, { op: 'post', pageId, channel, data }); },
- poll: async (ghost, pageId, after) => await invokeGhostMobileRelay(ghost.manifest.id, { op: 'poll', pageId, after }) as PluginPagePoll['events'],
- disconnect: async (id, pageId) => { await invokeGhostMobileRelay(id, { op: 'disconnect', pageId }); },
fetch: fetchGhostMobilePage,
fetchPreview: readMobilePreview,
- resolveMedia: async (ghostId, url, current) => {
- const result = await getGhostPreviewGate().request({ ghostId, url, isPanelFocused: current });
- if (!result.ok || !current()) return null;
- // The ledger-selected extension is authoritative, not the caller's link suffix.
- const file = result.src.split('/').pop();
- return file && /^[a-f0-9]{64}\.[a-z0-9]+$/.test(file) ? { path: `/media/${file}`, mediaKind: result.kind } : null;
- },
+ resolveMedia: resolveMobilePluginMedia,
validateDirectory: async input => {
if (!path.isAbsolute(input)) throw new Error('INVALID_DIRECTORY');
const real = await fs.promises.realpath(input);
@@ -6861,21 +7503,21 @@ export function registerGhostIpc(): void {
setGhostSandboxDevToolsDisabled(app.isPackaged);
setGhostAppContextProvider(currentGhostAppContext);
setGhostMediaModelsProvider(getGhostConfigurableMediaModels);
- setGhostAgentModelsProvider(async (ghostId) => {
+ setGhostAgentModelsProvider(async (instanceId) => {
const owner = activeOwnerScopeKey();
- if (!findAvailableGhost(ghostId)?.enabled) {
+ if (!findGhostForInstanceId(instanceId)?.enabled) {
return { ok: false, errorCode: 'NOT_AVAILABLE', message: 'Plugin unavailable' };
}
const views = await getDesktopProviderService({ allowSideEffects: false }).listProviders({ allowSideEffects: false, snapshotOnly: true });
- if (owner !== activeOwnerScopeKey() || !findAvailableGhost(ghostId)?.enabled) {
+ if (owner !== activeOwnerScopeKey() || !findGhostForInstanceId(instanceId)?.enabled) {
return { ok: false, errorCode: 'NOT_AVAILABLE', message: 'Plugin unavailable' };
}
await waitForModelVisibilityMirror();
- if (owner !== activeOwnerScopeKey() || !findAvailableGhost(ghostId)?.enabled) return { ok: false, errorCode: 'NOT_AVAILABLE', message: 'Plugin unavailable' };
+ if (owner !== activeOwnerScopeKey() || !findGhostForInstanceId(instanceId)?.enabled) return { ok: false, errorCode: 'NOT_AVAILABLE', message: 'Plugin unavailable' };
// Do not initialize runtimes as a side effect of a plugin's read-only GET.
const { getMakerIfReady } = await import('../maker-host/index.js');
const maker = getMakerIfReady();
- if (owner !== activeOwnerScopeKey() || !findAvailableGhost(ghostId)?.enabled || !maker) {
+ if (owner !== activeOwnerScopeKey() || !findGhostForInstanceId(instanceId)?.enabled || !maker) {
return { ok: false, errorCode: 'NOT_AVAILABLE', message: 'Model runtimes unavailable' };
}
return projectGhostAgentModels(views, maker.listAvailableAgents(), getModelVisibilityOverride);
@@ -6884,11 +7526,12 @@ export function registerGhostIpc(): void {
// 自己的协议通道进来。只对"已装且唤醒"的意识放行;熔断态不清账(重载 /
// 重新唤醒才 resetFuse),spawn 幂等所以重复唤醒零成本。
setGhostWakeHandler(async (ghostId) => {
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost || !ghost.enabled) return { state: 'off' };
- if (runtime.stateOf(ghostId) === 'fused') return { state: 'fused' };
+ const runtimeId = installedGhostStoragePart(ghost);
+ if (runtime.stateOf(runtimeId) === 'fused') return { state: 'fused' };
const spawned = await runtime.spawn(ghost);
- return { state: spawned.ok ? spawned.state : runtime.stateOf(ghostId) };
+ return { state: spawned.ok ? spawned.state : runtime.stateOf(runtimeId) };
});
// 意识自定义参数 KV(/kv 协议端点的存储接线,FORGE_GUIDE §4.8):
// 真身单意识单文件落 userData/ghost-kv/;注入 adapter 的是带"在装态守卫"
@@ -6899,8 +7542,11 @@ export function registerGhostIpc(): void {
log,
});
ghostSetupKvStore = ghostKv;
- const ghostInstalled = (ghostId: string): boolean => findAvailableGhost(ghostId) !== null;
+ const ghostInstalled = (ghostId: string): boolean => findGhostForInstanceId(ghostId) !== null;
setGhostKvStore({
+ captureTarget: ghostInstallMutationTargetFor,
+ isTargetCurrent: (ghostId, expectedTarget) => expectedTarget != null &&
+ ghostInstallMutationTargetFor(ghostId) === expectedTarget,
read: (ghostId) => (ghostInstalled(ghostId) ? ghostKv.read(ghostId) : {}),
write: (ghostId, value) => {
if (!ghostInstalled(ghostId)) return; // 幽灵写静默丢弃,不留文件
@@ -6914,8 +7560,8 @@ export function registerGhostIpc(): void {
// 旧快照);login-email 派生凭证没有收单动作,不在键集内。保险库真身 =
// providerSecretStore(safeStorage 键名与官方别名同一套)。卸下后的残留
// 请求查无此意识,统一 404。
- setGhostSecretsHandler(async ({ ghostId, method, pathname, readBodyText }) => {
- const ghost = findAvailableGhost(ghostId);
+ setGhostSecretsHandler(async ({ ghostId, method, pathname, readBodyText, isCurrent }) => {
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost) return { status: 404 };
const networkSecretDecls = ghost.manifest.network?.secrets ?? [];
const nodeSecretDecls = (ghost.manifest.node?.secretBindings ?? []).filter(
@@ -6961,6 +7607,7 @@ export function registerGhostIpc(): void {
method,
pathname,
readBodyText,
+ isCurrent,
userSecretKeys,
identitySecretKeys,
managedSecretStates,
@@ -7000,10 +7647,10 @@ export function registerGhostIpc(): void {
// /oauth 通道(source:'oauth' 凭证的设置页动作面,FORGE_GUIDE §4.7):
// client 凭证只写入库、连接/断开/默认账号由主机代办。同 /secrets 模式
// 现查在装清单(意识更新立即以新声明为准);卸下后残留请求统一 404。
- setGhostOauthHandler(async ({ ghostId, method, pathname, readBodyText }) => {
- const ghost = findAvailableGhost(ghostId);
+ setGhostOauthHandler(async ({ ghostId, method, pathname, readBodyText, isCurrent }) => {
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost) return { status: 404 };
- const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);
+ const runtimeManifest = ghost.manifest;
const oauthSecrets = new Map<string, GhostOauthDecl>();
for (const s of runtimeManifest.network?.secrets ?? []) {
if (s.source === 'oauth' && s.oauth) oauthSecrets.set(s.key, s.oauth);
@@ -7012,6 +7659,7 @@ export function registerGhostIpc(): void {
method,
pathname,
readBodyText,
+ isCurrent,
oauthSecrets,
networkHosts: runtimeManifest.network?.hosts,
manager: getGhostOauthAccountManager(),
@@ -7031,8 +7679,8 @@ export function registerGhostIpc(): void {
// 关键闸:**新增地址必须过 main 侧受信确认弹窗**——意识设置页是意识自绘
// 的不可信界面,动态白名单扩张必须由主机模态拿到用户点头(规则 9:用代码
// 保证,不靠意识自觉)。
- setGhostConnectionsHandler(async ({ ghostId, method, pathname, readBodyText }) => {
- const ghost = findAvailableGhost(ghostId);
+ setGhostConnectionsHandler(async ({ ghostId, method, pathname, readBodyText, isCurrent }) => {
+ const ghost = findGhostForInstanceId(ghostId);
if (!ghost) return { status: 404 };
const connectionDecls = ghost.manifest.network?.connections ?? [];
const decls = new Map<string, { label: string; maxConnections: number }>();
@@ -7046,13 +7694,14 @@ export function registerGhostIpc(): void {
method,
pathname,
readBodyText,
+ isCurrent,
decls,
manager: getGhostConnectionManager(),
ghostId,
// 受信确认:main 侧系统模态(对照 bootstrap 的 moveToApplications 弹窗
// 用法),默认落在「取消」上防误触;意识名从在装清单现查。
confirmAddHost: async (declLabel, host) => {
- const ghostName = findAvailableGhost(ghostId)?.manifest.name ?? ghostId;
+ const ghostName = (findGhostForInstanceId(ghostId))?.manifest.name ?? ghostId;
// main 迷你 i18n 只内置 {{appName}} 插值,其余变量按其约定在调用点
// 自行 replace(对照 bootstrap 菜单的用法)。
const { response } = await dialog.showMessageBox({
@@ -7101,61 +7750,44 @@ export function registerGhostIpc(): void {
// 保持为 retry-pending,避免被 coordinator 误记为完成。
const activateGhostsAndMigrateLegacyAccounts = (): 'completed' | 'retry-pending' => {
for (const ghost of manager.list()) spawnIfResident(ghost);
+ void manager.reconcilePendingRootNamespaces(false).catch((error) => {
+ log.warn('namespace migration reconcile failed', {
+ err: error instanceof Error ? error.message : String(error),
+ });
+ });
let legacyMigrationNeedsRetry = false;
const activeOwnerId = getActiveAppSession().dataOwnerId;
const canMigrateLegacyAccounts =
getAppCapabilities().canUseCindyAccountServices &&
activeOwnerId !== null &&
hasLegacyOwnerNamespaceClaim(activeOwnerId);
- // 老 Google 集成 → Filo Google 意识的一次性搬账(lizi_google 退役配套):
- // filoCurrent 档案的账号同 client、refresh token 通用,直接迁入意识
- // 保险库;意识侧已有账号或老存储不存在时为 no-op(模块内幂等)。
- if (
- canMigrateLegacyAccounts &&
- manager.list().some((g) => g.manifest.id === FILO_GOOGLE_GHOST_ID)
- ) {
- try {
- const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
- const migration = migrateFiloGoogleAccountsWithResult({
- readLegacyManifest: () => {
- return readLegacyJson(path.join(legacyDir, 'google_accounts.json'), (raw) => {
- if (!raw || typeof raw !== 'object') return null;
- const candidate = raw as { accounts?: unknown };
- if (!Array.isArray(candidate.accounts)) return null;
- return { accounts: candidate.accounts as LegacyGoogleAccountRow[] };
- });
- },
- readLegacyRefreshToken: (accountId) =>
- readLegacyEncryptedSecret(
- path.join(legacyDir, `google_account_refresh_token_${accountId}.enc`),
- ),
- vault: {
- read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),
- store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),
- remove: (ghostId, storageKey) => removeGhostSecret(ghostId, storageKey),
- },
- log,
- });
- if (migration.retryPending) legacyMigrationNeedsRetry = true;
- if (migration.migrated > 0) {
- getGhostSetupChangeBus().emit(FILO_GOOGLE_GHOST_ID, {
- source: 'oauth',
- ref: FILO_GOOGLE_SECRET_KEY,
- });
- }
- } catch (err) {
- legacyMigrationNeedsRetry = true;
- log.warn('filo-google 搬账意外失败(不阻断启动)', {
- err: err instanceof Error ? err.message : String(err),
- });
- }
- }
+ const canMigrateLegacyAccountTarget = (id: string): boolean => {
+ if (!canMigrateLegacyAccounts) return false;
+ const ghost = findGhostForPhysicalStoragePart(id);
+ if (ghost?.manifest.id !== id || ghost.approval?.state !== 'approved') return false;
+ const receipt = manager.readApprovedInstallReceipt(id, ghost.approval.revision);
+ return receipt !== null && (receipt.legacyFirstPartyEligible === true ||
+ (ghost.builtin === true && isCindyOfficialTrustInfo(receipt.trust)));
+ };
+ const canMigrateLegacyOauthTarget = (id: string, secretKey: string): boolean => {
+ if (!canMigrateLegacyAccountTarget(id)) return false;
+ const decl = findGhostForPhysicalStoragePart(id)?.manifest.network?.secrets?.find(
+ (secret) => secret.key === secretKey && secret.source === 'oauth',
+ )?.oauth;
+ if (!decl) return false;
+ if (id === XD_ATLASSIAN_GHOST_ID) return decl.tokenBroker === 'jira';
+ return decl.tokenBroker === undefined && typeof decl.clientId === 'string' &&
+ decl.clientId.trim().length > 0 && [
+ 'https://oauth2.googleapis.com/token',
+ 'https://accounts.google.com/o/oauth2/token',
+ 'https://www.googleapis.com/oauth2/v4/token',
+ ].includes(decl.tokenUrl);
+ };
// 老 Jira/Confluence 集成 → XD Atlassian 意识的一次性搬账(lizi_jira /
// lizi_confluence 退役配套):老 rt 与 server broker 同一 Atlassian 应用,
// tokenBroker 模式走同一 broker 刷新,令牌通用;幂等语义同上。
if (
- canMigrateLegacyAccounts &&
- manager.list().some((g) => g.manifest.id === XD_ATLASSIAN_GHOST_ID)
+ canMigrateLegacyOauthTarget(XD_ATLASSIAN_GHOST_ID, XD_ATLASSIAN_SECRET_KEY)
) {
try {
const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
@@ -7196,8 +7828,7 @@ export function registerGhostIpc(): void {
// PAT 直接迁入意识 user 凭证槽;仅迁 github.com 连接(意识白名单静态
// 钉死 github.com,GHE token 迁了也只会 401);幂等语义同上。
if (
- canMigrateLegacyAccounts &&
- manager.list().some((g) => g.manifest.id === CINDY_GITHUB_GHOST_ID)
+ canMigrateLegacyAccountTarget(CINDY_GITHUB_GHOST_ID)
) {
try {
const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
@@ -7235,8 +7866,7 @@ export function registerGhostIpc(): void {
// (gitlab_conn)并设为默认;仅迁 https 且不带端口的实例(意识出网
// 仅 https、连接白名单只认裸域,迁了也打不通);幂等语义同上。
if (
- canMigrateLegacyAccounts &&
- manager.list().some((g) => g.manifest.id === CINDY_GITLAB_GHOST_ID)
+ canMigrateLegacyAccountTarget(CINDY_GITLAB_GHOST_ID)
) {
try {
const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
@@ -7343,7 +7973,7 @@ export function registerGhostIpc(): void {
requireGhostAvailableForActiveSession(id);
const type = (payload as { type?: unknown } | null)?.type;
if (type === 'recommendations-update') {
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
if (!ghost || !ghost.enabled) return { ok: false, errorCode: 'GHOST_ASLEEP' };
return replaceGhostRecommendations(id, (payload as { items?: unknown }).items);
}
@@ -7414,7 +8044,7 @@ export function registerGhostIpc(): void {
!event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id && (!pageCurrent || pageCurrent());
};
return handlePluginTaskRequest(id, payload, {
- getGhost: findAvailableGhost, handler: pluginTaskHandler,
+ getGhost: findGhostForInstanceId, handler: pluginTaskHandler,
isCurrent,
ensureAuthorized: () => requestPluginTaskApproval(id, isCurrent, facts => {
const pageId = (payload as { mobilePageId?: string }).mobilePageId;
@@ -7473,25 +8103,16 @@ export function registerGhostIpc(): void {
// 资格审/净化/频率钳制/限速在 scheduleSlot,落地在 renderer。
if (type === 'routine-request') {
const owner = activeOwnerScopeKey();
- const ghost = getGhostManager()
- .list()
- .find((item) => item.manifest.id === id);
- return handleRoutineRequest(
- ghost,
- payload,
- getRoutineEngine,
- () =>
- activeOwnerScopeKey() === owner &&
- getGhostManager()
- .list()
- .some(
- (item) =>
- item.manifest.id === id &&
- item.enabled &&
- ghostInstallApprovalToken(item.approval) ===
- ghostInstallApprovalToken(ghost?.approval),
- ),
- );
+ const ghost = findGhostForInstanceId(id);
+ return handleRoutineRequest(ghost ?? undefined, payload, getRoutineEngine, () => {
+ if (activeOwnerScopeKey() !== owner || !ghost) return false;
+ const current = findGhostForInstanceId(id);
+ return Boolean(
+ current?.enabled &&
+ ghostInstallApprovalToken(current.approval) ===
+ ghostInstallApprovalToken(ghost.approval),
+ );
+ });
}
if (type === 'schedule-request') {
return getGhostScheduleSlot().handleRequest(id, payload);
@@ -7683,7 +8304,7 @@ export function registerGhostIpc(): void {
ipcMain.handle('ghosts:acknowledge-retirement', (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id))
+ if (typeof id !== 'string' || !isPluginInstanceKey(id))
throwIpcError('INVALID_PARAMS', 'Invalid plugin id');
requireGhostAvailableForActiveSession(id);
try {
@@ -7737,10 +8358,10 @@ export function registerGhostIpc(): void {
});
ipcMain.handle('ghosts:mark-used', (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id)) {
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) {
throwIpcError('INVALID_PARAMS', 'id must be a valid Ghost id');
}
- if (!findAvailableGhost(id)) {
+ if (!findGhostForInstanceId(id)) {
throwIpcError('NOT_FOUND', `意识 ${id} 未安装`);
}
try {
@@ -7779,7 +8400,7 @@ export function registerGhostIpc(): void {
// 插件 id 把别人的未读清掉(codex review)。
ipcMain.handle('ghosts:clear-unread', (event, id: unknown, seenAt: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id)) {
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) {
throwIpcError('INVALID_PARAMS', 'id must be a valid Ghost id');
}
if (seenAt !== undefined && (typeof seenAt !== 'number' || !Number.isFinite(seenAt))) {
@@ -7804,11 +8425,12 @@ export function registerGhostIpc(): void {
handleGhostSetupStatusRequest({
id,
getRuntimeManifest: (ghostId) => {
- const ghost = findAvailableGhost(ghostId);
- return ghost ? withRuntimeFiloGoogleClient(ghost.manifest) : null;
+ const ghost = findGhostForInstanceId(ghostId);
+ return ghost ? ghost.manifest : null;
},
probesFor: (runtimeManifest) => {
- const ghostId = runtimeManifest.id;
+ const ghost = findGhostForInstanceId(typeof id === 'string' ? id : runtimeManifest.id);
+ const ghostId = ghost ? installedGhostStoragePart(ghost) : runtimeManifest.id;
const oauthManager = getGhostOauthAccountManager();
const connectionManager = getGhostConnectionManager();
// kv 单意识单文件,同一次判定内最多读一次(多条 kv 需求不重复开盘);
@@ -7850,16 +8472,36 @@ export function registerGhostIpc(): void {
// 图片附件链路);视频附带指纹仓磁盘路径 + 体积(不复制字节,引渡侧落成与
// 「从系统拖 .mp4 进聊天」同款的 file 类别路径附件)。失败统一 NOT_FOUND
// (调用方 toast / 静默即可,无需区分原因)。
- ipcMain.handle('ghosts:resolve-panel-media', async (_event, uri: unknown, purpose: unknown) => {
+ ipcMain.handle('ghosts:resolve-panel-media', async (_event, uri: unknown, purpose: unknown, instanceId: unknown, sourceToken: unknown) => {
if (typeof uri !== 'string') throwIpcError('INVALID_PARAMS', 'uri must be a string');
+ if (instanceId !== undefined && (typeof instanceId !== 'string' || !isGhostInstanceId(instanceId))) {
+ throwIpcError('INVALID_PARAMS', 'instanceId must be a valid Plugin instance');
+ }
+ const handoverTarget = sourceToken === undefined ? null : resolveGhostMediaHandoverTarget(sourceToken, uri);
+ if (sourceToken !== undefined && (!handoverTarget || purpose === 'menu' ||
+ (instanceId !== undefined && instanceId !== handoverTarget.instanceId))) {
+ throwIpcError('NOT_FOUND', '媒体拖拽来源已失效,请从当前插件面板重新拖拽');
+ }
+ const requestedInstanceId = handoverTarget?.instanceId ?? instanceId;
+ const parsed = parseGhostPanelMediaUrl(uri);
+ const ghost = requestedInstanceId === undefined
+ ? parsed ? findAvailableGhostForAuthorization(parsed.ghostId) : null
+ : findGhostForInstanceId(requestedInstanceId as string);
+ if (!ghost) throwIpcError('NOT_FOUND', '目标插件实例已变化,请刷新后重试');
+ const expectedTarget = ghostInstallMutationTargetFor(installedGhostStoragePart(ghost));
+ if (expectedTarget === null) throwIpcError('NOT_FOUND', '目标插件实例暂不可用,请稍后重试');
const resolved = await resolveGhostPanelMedia(uri, purpose === 'menu' ? 'menu' : 'attach', {
ghostCanRead: (hash, ghostId) => ledger.ghostCanRead(hash, ghostId),
getBlobInfo: (hash) => ledger.getBlobInfo(hash),
blobUrl: (hash, ext) => blobStore.blobUrl(hash, ext),
blobAbsPath: (hash, ext) => blobStore.resolveHashRef(hash, ext).absPath,
statSize: (absPath) => fs.promises.stat(absPath).then((s) => s.size),
- });
+ }, { ghostId: ghost.manifest.id, instanceId: installedGhostStoragePart(ghost) });
if (!resolved) throwIpcError('NOT_FOUND', '不是本意识名下的可用媒体');
+ if (ghostInstallMutationTargetFor(installedGhostStoragePart(ghost)) !== expectedTarget ||
+ (sourceToken !== undefined && !resolveGhostMediaHandoverTarget(sourceToken, uri))) {
+ throwIpcError('NOT_FOUND', '媒体来源已变化,请从当前插件面板重试');
+ }
return resolved;
});
@@ -7910,12 +8552,10 @@ export function registerGhostIpc(): void {
);
// 纯展示口径,不走 findAvailableGhost 的"当前会话可用"闸:插件被当前项目
// 停用时卡片的其余部分(overrides/options)照常渲染,声明偏好也不该凭空消失。
- const declaredRaw =
- typeof ghostId === 'string'
- ? getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId)?.manifest.cindy?.oneshotModel
- : undefined;
+ const declaredRaw = typeof ghostId === 'string'
+ ? (findInstalledGhostByInstanceId(getGhostManager().list(), ghostId) ??
+ getGhostManager().list().find((g) => g.manifest.id === ghostId))?.manifest.cindy?.oneshotModel
+ : undefined;
const declaredResolved = declaredRaw
? resolveOneshotCatalogModel(
getActiveCatalog(),
@@ -7977,13 +8617,15 @@ export function registerGhostIpc(): void {
if (typeof disabled !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'disabled must be a boolean');
}
- const wasDisabled = isGhostDisabledForWorkdir(ghostId, workdir);
- const next = setGhostDisabledForWorkdir(workdir, ghostId, disabled);
+ const target = findGhostForInstanceId(ghostId);
+ const storedId = target ? installedGhostStoragePart(target) : ghostId;
+ const wasDisabled = isGhostDisabledForWorkdir(storedId, workdir);
+ const next = setGhostDisabledForWorkdir(workdir, storedId, disabled);
// A setup card may already be waiting for this plugin in the affected
// project. Wake all waiters for the plugin; each one revalidates its own
// captured workdir and only the matching scope is rejected.
if (wasDisabled !== disabled) {
- getGhostSetupChangeBus().emit(ghostId, { source: 'workdir_policy' });
+ getGhostSetupChangeBus().emit(storedId, { source: 'workdir_policy' });
}
// 生效面变了(新会话花名册 / $ 菜单),借 ghosts:changed 通知所有窗口
// 重拉——载荷仍是完整已装清单,消费方按需再 sendSync 取目录级清单。
@@ -8028,12 +8670,15 @@ export function registerGhostIpc(): void {
'model must be null or an allowed model of the capability category',
);
}
+ const ghost = findGhostForInstanceId(ghostId);
+ if (!ghost) throwIpcError('NOT_FOUND', '插件实例已变化,请刷新后重试');
+ const storedId = installedGhostStoragePart(ghost);
const overrides = writeGhostCindyOverride(
- ghostId,
+ storedId,
capability as CindyCapabilityKey,
model as string | null,
);
- getGhostSetupChangeBus().emit(ghostId, {
+ getGhostSetupChangeBus().emit(storedId, {
source: 'host_config',
ref: `cindy-pref:${String(capability)}`,
});
@@ -8061,7 +8706,11 @@ export function registerGhostIpc(): void {
try { await validatePluginTaskConfig(config); }
catch (error) { throwIpcError('INVALID_PARAMS', error instanceof Error ? error.message : '任务配置不可用'); }
const release = beginGhostMutation(owner);
- try { return { config: writePluginTaskConfig(ghostId, config) }; }
+ try {
+ const ghost = findGhostForInstanceId(ghostId);
+ if (!ghost) throwIpcError('NOT_FOUND', '插件实例已变化,请刷新后重试');
+ return { config: writePluginTaskConfig(installedGhostStoragePart(ghost), config) };
+ }
finally { release(); }
});
@@ -8104,7 +8753,7 @@ export function registerGhostIpc(): void {
initiator: 'user',
origin: 'local-file',
},
- manager.list().find((ghost) => ghost.manifest.id === probe.manifest.id),
+ findInstalledGhostForDeliveryTarget(manager.list(), { ghostId: probe.manifest.id, namespace: null }),
probe.manifest,
probe.packageSha256,
);
@@ -8119,9 +8768,10 @@ export function registerGhostIpc(): void {
enable,
expectedPackageSha256,
consent: { decision: consent, manifest: probe.manifest },
+ namespace: null,
}).then((ghost) => {
try {
- markGhostRecommendationInstalled(ghost.manifest.id);
+ markGhostRecommendationInstalled(installedGhostStoragePart(ghost));
} catch {
log.warn('ghost recommendation install history unavailable');
}
@@ -8147,10 +8797,12 @@ export function registerGhostIpc(): void {
| {
expectedPackageSha256?: unknown;
expectedInstalledApproval?: unknown;
+ expectedInstalledInstanceId?: unknown;
}
| undefined;
const expectedPackageSha256 = updateOptions?.expectedPackageSha256;
const expectedInstalledApproval = updateOptions?.expectedInstalledApproval;
+ const expectedInstalledInstanceId = updateOptions?.expectedInstalledInstanceId;
if (
typeof expectedPackageSha256 !== 'string' ||
!/^[a-f0-9]{64}$/.test(expectedPackageSha256)
@@ -8160,6 +8812,9 @@ export function registerGhostIpc(): void {
if (!isGhostInstallApprovalToken(expectedInstalledApproval)) {
throwIpcError('INVALID_PARAMS', 'expectedInstalledApproval must come from ghosts:list');
}
+ if (typeof expectedInstalledInstanceId !== 'string') {
+ throwIpcError('INVALID_PARAMS', 'expectedInstalledInstanceId must come from ghosts:list');
+ }
const inspected = await manager.inspect(lizFilePath);
if ('rejection' in inspected) throwInstallError(inspected.rejection);
if (inspected.packageSha256 !== expectedPackageSha256) {
@@ -8167,8 +8822,16 @@ export function registerGhostIpc(): void {
}
rejectReservedGhostId(inspected.manifest.id);
rejectBrokerWithoutDeclaredRedirectPort(inspected.manifest);
- rejectUnauthorizedTokenBroker(inspected.manifest);
// 新版本权限变多时先请用户确认;权限没变多的更新不打扰。
+ const existingForUpdate = findInstalledGhostForLocalUpdate(
+ manager.list(), inspected.manifest.id, expectedInstalledInstanceId, expectedInstalledApproval,
+ );
+ if (!existingForUpdate) throwIpcError('PRECONDITION_FAILED', '目标插件实例已变化,请刷新后重试');
+ if (typeof existingForUpdate.namespace === 'string') {
+ throwIpcError('PRECONDITION_FAILED', '本地文件不能更新企业插件实例,请另装一个 root 实例');
+ }
+ const updateSource = readLocalGhostUpdateSource(manager, existingForUpdate, inspected);
+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest, updateSource.authorizationOverrides);
const consent = await obtainGhostInstallConsent(
{
mode: 'prompt',
@@ -8176,7 +8839,7 @@ export function registerGhostIpc(): void {
initiator: 'user',
origin: 'local-file',
},
- manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id),
+ existingForUpdate,
inspected.manifest,
inspected.packageSha256,
);
@@ -8194,6 +8857,7 @@ export function registerGhostIpc(): void {
inspected,
expectedPackageSha256,
expectedInstalledApproval,
+ expectedInstalledInstanceId,
consent,
),
),
@@ -8225,17 +8889,41 @@ export function registerGhostIpc(): void {
});
// 只验不装:读出 .cindy 的真实清单,供兼容性判断与安装摘要使用,零副作用。
- ipcMain.handle('ghosts:inspect', async (event, lizFilePath: unknown) => {
+ ipcMain.handle('ghosts:inspect', async (event, lizFilePath: unknown, opts: unknown) => {
assertTrustedAppRendererEvent(event);
+ const inspectionOwner = captureGhostMutationOwner();
if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'lizFilePath must be a non-empty string');
}
const result = await manager.inspect(lizFilePath);
if ('rejection' in result) throwInstallError(result.rejection);
+ if (!ghostOwnerScope.isStable(inspectionOwner)) {
+ throwIpcError('PRECONDITION_FAILED', '账号已切换,请重新检查插件');
+ }
+ let target: InstalledGhost | undefined;
+ if (opts !== undefined) {
+ const options = opts as {
+ expectedInstalledInstanceId?: unknown;
+ expectedInstalledApproval?: unknown;
+ } | null;
+ if (!options || typeof options !== 'object' ||
+ typeof options.expectedInstalledInstanceId !== 'string' ||
+ !isGhostInstanceId(options.expectedInstalledInstanceId) ||
+ !isGhostInstallApprovalToken(options.expectedInstalledApproval)) {
+ throwIpcError('INVALID_PARAMS', 'inspect target must come from ghosts:list');
+ }
+ target = findInstalledGhostForLocalUpdate(
+ manager.list(), result.manifest.id,
+ options.expectedInstalledInstanceId, options.expectedInstalledApproval,
+ );
+ if (!target) throwIpcError('PRECONDITION_FAILED', '目标插件实例已变化,请刷新后重试');
+ }
// 官方前缀在 inspect 就拒,install/update 双保险再拦。
rejectReservedGhostId(result.manifest.id);
rejectBrokerWithoutDeclaredRedirectPort(result.manifest);
- rejectUnauthorizedTokenBroker(result.manifest);
+ rejectUnauthorizedTokenBroker(result.canonicalManifest, target
+ ? readLocalGhostUpdateSource(manager, target, result).authorizationOverrides
+ : undefined);
return {
manifest: result.manifest,
trust: result.trust,
@@ -8266,42 +8954,56 @@ export function registerGhostIpc(): void {
// 的坏包。
ipcMain.handle('ghosts:export', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
+ const exportOwner = captureGhostMutationOwner();
+ const exportedGhost = typeof id === 'string'
+ ? findInstalledGhostByInstanceId(manager.list(), id) : undefined;
+ const exportedInstanceId = exportedGhost ? installedGhostStoragePart(exportedGhost) : null;
+ const exportedApproval = exportedGhost ? ghostInstallApprovalToken(exportedGhost.approval) : null;
+ let exportedPackageSha256: string | null = null;
// 官方保留前缀在本地装入链路被拒,导出产物装不回——renderer 菜单
// 只是隐藏,handler 才是真正的强制边界(评审 P1)。
if (typeof id === 'string') rejectReservedGhostId(id);
const win = BrowserWindow.fromWebContents(event.sender);
const result = await exportGhostPackage(id, {
- listInstalled: () => manager.list(),
+ listInstalled: () => exportedGhost ? [exportedGhost] : [],
showSaveDialog: (opts) =>
win ? dialog.showSaveDialog(win, opts) : dialog.showSaveDialog(opts),
getDownloadsDir: () => app.getPath('downloads'),
fileTypeLabel: t('settings.ghosts.detail.exportFileType'),
- writeFile: (filePath, data) => fs.promises.writeFile(filePath, data),
+ writeFile: async (filePath, data) => {
+ exportedPackageSha256 = createHash('sha256').update(data).digest('hex');
+ await fs.promises.writeFile(filePath, data);
+ },
// 装入校验本尊 + 装入侧不变量:manager.inspect 带真实 trust
// registry;指令查重与 tokenBroker 门控只存在于 install/update,
// inspect 不覆盖,这里按同一口径补齐(评审 P1)。
inspectPackage: async (filePath) => {
const probe = await manager.inspect(filePath);
if ('rejection' in probe) return false;
- // tokenBroker 门控(同 rejectUnauthorizedTokenBroker):官方前缀照旧;
- // 其余问已装的市场来源与当前组织身份。
+ if (!ghostOwnerScope.isStable(exportOwner) || !exportedGhost ||
+ exportedInstanceId === null || exportedApproval === null ||
+ probe.packageSha256 !== exportedPackageSha256 ||
+ probe.manifest.id !== exportedGhost.manifest.id ||
+ probe.manifest.version !== exportedGhost.manifest.version) return false;
+ const current = findInstalledGhostForLocalUpdate(
+ manager.list(), exportedGhost.manifest.id, exportedInstanceId, exportedApproval,
+ );
+ if (!current || current.dir !== exportedGhost.dir) return false;
+ // tokenBroker 门控(同 rejectUnauthorizedTokenBroker):按可信安装事实判定,
+ // 名称前缀不放行。
const brokered = (probe.manifest.network?.secrets ?? []).some(
(s) => s.oauth?.tokenBroker !== undefined,
);
- if (brokered && !isGhostTokenBrokerAuthorized(probe.manifest.id, 'install')) {
+ if (brokered && (current.approval.state !== 'approved' ||
+ !isGhostTokenBrokerAuthorized(exportedInstanceId, 'runtime'))) {
return false;
}
// 指令查重(同 install/update):与当前已装撞名即拒,排除自身。
- const commandFold = probe.manifest.command?.toLowerCase();
- if (commandFold === undefined) return true;
- return !manager
- .list()
- .some(
- (g) =>
- g.manifest.id !== probe.manifest.id &&
- g.manifest.command !== undefined &&
- g.manifest.command.toLowerCase() === commandFold,
- );
+ if (probe.manifest.command === undefined) return true;
+ return !findConflictingGhostCommand(manager.list(), probe.manifest.command, {
+ incomingNamespace: current && hasDeliveryNamespace(current) ? current.namespace : null,
+ exemptPhysicalRelId: current ? installedGhostPhysicalRelId(current) : undefined,
+ });
},
});
switch (result.status) {
@@ -8388,7 +9090,7 @@ export function registerGhostIpc(): void {
return { granted };
});
- ipcMain.handle('ghosts:set-enabled', async (event, id: unknown, enabled: unknown) => {
+ ipcMain.handle('ghosts:set-enabled', async (event, id: unknown, enabled: unknown, expectedInstalledApproval: unknown) => {
// 启用 Node 插件会获得本机进程能力;即使按钮在 Renderer 里,来源判定也
// 必须由 Main 按真实顶层 frame 完成,不能信任页面自报。
assertTrustedAppRendererEvent(event);
@@ -8399,7 +9101,10 @@ export function registerGhostIpc(): void {
if (typeof enabled !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'enabled must be a boolean');
}
- return setGhostEnabledForUser(id, enabled);
+ if (expectedInstalledApproval !== undefined && !isGhostInstallApprovalToken(expectedInstalledApproval)) {
+ throwIpcError('INVALID_PARAMS', 'expectedInstalledApproval must be an install approval token');
+ }
+ return setGhostEnabledForUser(id, enabled, expectedInstalledApproval);
});
// 运行时状态快照(面板错误接管态的首帧数据源;广播只覆盖后续变化)。
@@ -8410,14 +9115,12 @@ export function registerGhostIpc(): void {
* 共用同一裁决链(原生选择器 → 候选校验 → binding/迁移)。 */
ipcMain.handle('ghosts:library-overview', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id))
- throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
return getGhostLibraryOverview(id);
});
ipcMain.handle('ghosts:library-pick-location', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id))
- throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
const win = BrowserWindow.fromWebContents(event.sender);
const picked = win
? await dialog.showOpenDialog(win, { properties: ['openDirectory', 'createDirectory'] })
@@ -8444,30 +9147,30 @@ export function registerGhostIpc(): void {
// 持 owner 租约:binding 写的是 owner-scoped 文件,切换在途不得跨 owner。
ipcMain.handle('ghosts:library-bind', async (event, id: unknown, candidate: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id) || typeof candidate !== 'string') {
+ if (typeof id !== 'string' || !isGhostInstanceId(id) || typeof candidate !== 'string') {
throwIpcError('INVALID_PARAMS', '参数非法');
}
- const releaseMutation = beginGhostMutation();
- const slot = getGhostLibrarySlot();
- try {
- slot.setRelocating(id, true);
- await slot.disposeGhost(id); // drain in-flight staging.release before binding changes
- const set = await getGhostLibraryBindingStore().setBinding(id, candidate, (root) =>
- statfsFreeBytes(root),
- );
- if (!set.ok) return { ok: false as const, message: set.message };
- await slot.disposeGhost(id); // 作废会话,下一请求用新根
- await refreshMivoLibraryExtraDirGrant();
- return { ok: true as const, warnings: set.warnings };
- } finally {
- slot.setRelocating(id, false);
- releaseMutation();
- }
+ return withGhostLibraryMutation(id, async () => {
+ const slot = getGhostLibrarySlot();
+ try {
+ slot.setRelocating(id, true);
+ await slot.disposeGhost(id);
+ const set = await getGhostLibraryBindingStore().setBinding(id, candidate, (root) =>
+ statfsFreeBytes(root),
+ );
+ if (!set.ok) return { ok: false as const, message: set.message };
+ await slot.disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
+ return { ok: true as const, warnings: set.warnings };
+ } finally {
+ slot.setRelocating(id, false);
+ }
+ });
});
// 设置页「更改位置」(带数据迁移):precheck→copying→verifying→switching→grace。
ipcMain.handle('ghosts:library-relocate', async (event, id: unknown, candidate: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id) || typeof candidate !== 'string') {
+ if (typeof id !== 'string' || !isGhostInstanceId(id) || typeof candidate !== 'string') {
throwIpcError('INVALID_PARAMS', '参数非法');
}
return relocateGhostLibraryTo(id, candidate);
@@ -8475,52 +9178,52 @@ export function registerGhostIpc(): void {
// 撤销自定义位置:迁回系统默认并清 binding(反向同一状态机)。
ipcMain.handle('ghosts:library-revert-default', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id))
- throwIpcError('INVALID_PARAMS', '非法插件 id');
- const defaultParent = path.dirname(ownerScopedUserDataPath('libraries', id));
- try {
- await fs.promises.mkdir(defaultParent, { recursive: true });
- } catch {
- /* 校验阶段会再探 */
- }
- // 默认根在宿主数据区内:豁免受管根排斥(那道闸拦的是用户自选数据区)。
- const res = await relocateGhostLibraryTo(id, defaultParent, { allowInsideManagedRoot: true });
- if (!res.ok) return res;
- await getGhostLibraryBindingStore().removeBinding(id);
- await getGhostLibrarySlot().disposeGhost(id);
- await refreshMivoLibraryExtraDirGrant();
- return { ok: true as const };
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ return withGhostLibraryMutation(id, async () => {
+ const defaultParent = path.dirname(ownerScopedUserDataPath('libraries', id));
+ try {
+ await fs.promises.mkdir(defaultParent, { recursive: true });
+ } catch {
+ /* 校验阶段会再探 */
+ }
+ const res = await relocateGhostLibraryToLocked(id, defaultParent, { allowInsideManagedRoot: true });
+ if (!res.ok) return res;
+ await getGhostLibraryBindingStore().removeBinding(id);
+ await getGhostLibrarySlot().disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
+ return { ok: true as const };
+ });
});
// 漂移恢复(位置失效):解除 binding 回默认(原自定义目录数据原样保留,
// 用户可手工找回;不自动猜测)。
ipcMain.handle('ghosts:library-unbind', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id))
- throwIpcError('INVALID_PARAMS', '非法插件 id');
- const releaseMutation = beginGhostMutation();
- const slot = getGhostLibrarySlot();
- try {
- slot.setRelocating(id, true);
- await slot.disposeGhost(id);
- await getGhostLibraryBindingStore().removeBinding(id);
- await slot.disposeGhost(id);
- await refreshMivoLibraryExtraDirGrant();
- return { ok: true as const };
- } finally {
- slot.setRelocating(id, false);
- releaseMutation();
- }
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ return withGhostLibraryMutation(id, async () => {
+ const slot = getGhostLibrarySlot();
+ try {
+ slot.setRelocating(id, true);
+ await slot.disposeGhost(id);
+ await getGhostLibraryBindingStore().removeBinding(id);
+ await slot.disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
+ return { ok: true as const };
+ } finally {
+ slot.setRelocating(id, false);
+ }
+ });
});
ipcMain.handle('ghosts:library-delete', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id))
- throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ const expectedOwner = captureGhostMutationOwner();
+ const expectedTarget = ghostLibraryDeleteTargetFor(id);
// **唯一有效的删除确认在 Main**:preload 即使被其它 trusted renderer
// 调用也绕不过用户点击(review:Renderer 确认可被内部调用方绕过)。文案走
// main i18n(与 Renderer 五语同一资源),壳由系统绘制;取消不取得 mutation
// 租约、不触碰 binding/数据。
const parent = BrowserWindow.fromWebContents(event.sender);
- const ghostName = findAvailableGhost(id)?.manifest.name ?? id;
+ const ghostName = findGhostForInstanceId(id)?.manifest.name ?? id;
const options = {
type: 'warning' as const,
title: t('settings.ghosts.library.deleteConfirmTitle'),
@@ -8538,9 +9241,9 @@ export function registerGhostIpc(): void {
? await dialog.showMessageBox(parent, options)
: await dialog.showMessageBox(options);
if (decision.response !== 0) return { ok: false as const, cancelled: true as const };
- const releaseMutation = beginGhostMutation();
+ const releaseMutation = beginGhostMutation(expectedOwner);
try {
- const res = await deleteGhostLibraryForActiveOwner(id);
+ const res = await deleteGhostLibraryForActiveOwner(id, expectedTarget);
return res.ok
? { ok: true as const }
: { ok: false as const, cancelled: false as const, message: res.message };
@@ -8556,10 +9259,10 @@ export function registerGhostIpc(): void {
throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');
}
requireGhostAvailableForActiveSession(id);
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
if (!ghost) throwIpcError('NOT_FOUND', `未装入意识 ${id}`);
if (!ghost.enabled) throwIpcError('INVALID_PARAMS', `意识 ${id} 处于沉睡态`);
- runtime.resetFuse(id);
+ runtime.resetFuse(installedGhostStoragePart(ghost));
const result = await runtime.spawn(ghost);
if (!result.ok) throwIpcError('INTERNAL', result.reason);
return { state: result.state };
@@ -8579,19 +9282,25 @@ export function registerGhostIpc(): void {
switch (action) {
case 'spawn': {
requireGhostAvailableForActiveSession(id);
- const ghost = findAvailableGhost(id);
+ const ghost = findGhostForInstanceId(id);
if (!ghost) throwIpcError('NOT_FOUND', `未装入意识 ${id}`);
if (!ghost.enabled) throwIpcError('INVALID_PARAMS', `意识 ${id} 处于沉睡态,先唤醒`);
const result = await runtime.spawn(ghost);
if (!result.ok) throwIpcError('INTERNAL', result.reason);
return { state: result.state };
}
- case 'stop':
- runtime.stop(id);
- return { state: runtime.stateOf(id) };
- case 'crash':
- if (!runtime.crashForTest(id)) throwIpcError('INVALID_PARAMS', `意识 ${id} 不在运行中`);
- return { state: runtime.stateOf(id) };
+ case 'stop': {
+ const target = findGhostForInstanceId(id);
+ const runtimeId = target ? installedGhostStoragePart(target) : id;
+ runtime.stop(runtimeId);
+ return { state: runtime.stateOf(runtimeId) };
+ }
+ case 'crash': {
+ const target = findGhostForInstanceId(id);
+ const runtimeId = target ? installedGhostStoragePart(target) : id;
+ if (!runtime.crashForTest(runtimeId)) throwIpcError('INVALID_PARAMS', `意识 ${id} 不在运行中`);
+ return { state: runtime.stateOf(runtimeId) };
+ }
case 'call': {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
throwIpcError('INVALID_PARAMS', 'call payload must be an object');
@@ -8656,11 +9365,15 @@ export function handleGhostPreviewNavigation(
hostContents: WebContents,
guestContents: WebContents,
isOwnerActive: () => boolean,
+ instanceId?: string,
): void {
void runGhostPreviewNavigation(
{ ghostId, url, hostContents, guestContents },
{
- request: (request) => getGhostPreviewGate().request(request),
+ request: (request) => getGhostPreviewGate().request({
+ ...request,
+ ...(instanceId !== undefined ? { instanceId } : {}),
+ }),
isOwnerActive,
send: (outcome) => {
sendGhostContentsPush(hostContents, GHOST_PREVIEW_MEDIA_CHANNEL, {
@@ -8680,7 +9393,7 @@ function getGhostExternalLinkGate(): GhostExternalLinkGate {
if (!externalLinkGateSingleton) {
externalLinkGateSingleton = new GhostExternalLinkGate({
declaredExternalUrls: (ghostId) => {
- const ghost = findAvailableGhost(ghostId);
+ const ghost = findGhostForInstanceId(ghostId);
return ghost && ghost.enabled ? ghostExternalLinkUrls(ghost.manifest) : null;
},
});
@@ -8700,9 +9413,10 @@ export function handleGhostExternalLinkNavigation(
hostContents: WebContents,
guestContents: WebContents,
isOwnerActive: () => boolean,
+ instanceId?: string,
): void {
void runGhostExternalLinkNavigation(
- { ghostId, url, hostContents, guestContents },
+ { ghostId: instanceId ?? ghostId, url, hostContents, guestContents },
{
gate: getGhostExternalLinkGate(),
resolveOwner: (contents) => BrowserWindow.fromWebContents(contents),
@@ -8736,8 +9450,14 @@ export function resolveGhostWebviewAttach(
const owner = getActiveAppSession();
const resolvedPartition = resolveGhostWebviewPartitionClaim(partitionClaim, owner);
if (!resolvedPartition) return null;
- const ghost = findAvailableGhost(resolvedPartition.ghostId);
+ if (!isPluginInstanceKey(resolvedPartition.ghostId)) return null;
+ const ghost = availableGhosts().find(
+ (candidate) => installedGhostStoragePart(candidate) === resolvedPartition.ghostId,
+ );
if (!ghost || !ghost.enabled) return null;
+ if (resolvedPartition.ghostId !== installedGhostStoragePart(ghost)) return null;
+ const partition = ownerScopedGhostPartitionForInstalledGhost(ghost, owner);
+ if (!partition) return null;
const allowedPaths = ghostWebviewEntryPaths(ghost.manifest);
if (allowedPaths.length === 0) return null;
let url: URL;
@@ -8746,12 +9466,12 @@ export function resolveGhostWebviewAttach(
} catch {
return null;
}
- if (url.protocol !== `${GHOST_SCHEME}:` || url.host !== resolvedPartition.ghostId) return null;
+ if (url.protocol !== `${GHOST_SCHEME}:` || url.host !== ghost.manifest.id) return null;
if (!allowedPaths.includes(url.pathname)) return null;
ensureGhostProtocolRegistered(ghost, owner);
return {
ghost,
- partition: resolvedPartition.partition,
+ partition,
owner: { mode: owner.mode, dataOwnerId: owner.dataOwnerId! },
};
}
@@ -8914,7 +9634,7 @@ export function refreshGhostLocalization(): void {
broadcastGhostsChanged(ghosts);
const context = currentGhostAppContext();
for (const ghost of ghosts) {
- sendToGhostLogic(ghost.manifest.id, {
+ sendToGhostLogic(installedGhostStoragePart(ghost), {
type: 'host-context-changed',
...context,
});
diff --git a/apps/desktop/src/main/cindy-brain/libraryBinding.ts b/apps/desktop/src/main/cindy-brain/libraryBinding.ts
index f1528f531e..6cea5d7ee1 100644
--- a/apps/desktop/src/main/cindy-brain/libraryBinding.ts
+++ b/apps/desktop/src/main/cindy-brain/libraryBinding.ts
@@ -21,6 +21,13 @@
import { randomUUID } from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
+import { isDeepStrictEqual } from 'node:util';
+
+import { isArchiveInstanceKey, isPluginInstanceKey } from '../../shared/pluginIdentity.js';
+
+function isLibraryOwnerId(value: unknown): value is string {
+ return isPluginInstanceKey(value) || isArchiveInstanceKey(value);
+}
/** 单个插件的自定义位置记录。 */
export interface LibraryBindingRecord {
@@ -43,6 +50,108 @@ export interface LibraryBindingRecord {
export interface LibraryBindingFileData {
version: 1;
bindings: Record<string, LibraryBindingRecord>;
+ pendingRelocation?: LibraryBindingRelocation;
+}
+
+interface LibraryBindingRelocation {
+ version: 1;
+ ownerFile: string;
+ fromGhostId: string;
+ toGhostId: string;
+ record: LibraryBindingRecord;
+ rootIdentity: { dev: number; ino: number };
+ libraryIdentity: { dev: number; ino: number } | null;
+}
+
+async function directoryIdentity(root: string): Promise<{ dev: number; ino: number } | null> {
+ try {
+ const stat = await fs.promises.lstat(root);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.ino === 0) {
+ throw new Error('library relocation directory identity unavailable');
+ }
+ return { dev: stat.dev, ino: stat.ino };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+async function syncDirectory(root: string): Promise<void> {
+ if (process.platform === 'win32') return;
+ const directory = await fs.promises.open(root, 'r');
+ try {
+ await directory.sync();
+ } finally {
+ await directory.close();
+ }
+}
+
+function isDirectoryIdentity(value: unknown, allowZeroInode = false): value is { dev: number; ino: number } {
+ if (!value || typeof value !== 'object') return false;
+ const identity = value as { dev?: unknown; ino?: unknown };
+ return typeof identity.dev === 'number' && Number.isFinite(identity.dev) &&
+ typeof identity.ino === 'number' && Number.isFinite(identity.ino) &&
+ (identity.ino > 0 || (allowZeroInode && identity.ino === 0));
+}
+
+function isLibraryBindingRecord(value: unknown): value is LibraryBindingRecord {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const record = value as Partial<LibraryBindingRecord>;
+ return typeof record.root === 'string' && path.isAbsolute(record.root) &&
+ typeof record.realPathAtGrant === 'string' && path.isAbsolute(record.realPathAtGrant) &&
+ (record.identity === null || isDirectoryIdentity(record.identity, true)) &&
+ typeof record.grantedAt === 'number' && Number.isFinite(record.grantedAt) &&
+ typeof record.generation === 'number' && Number.isInteger(record.generation) && record.generation >= 1 &&
+ (record.libraryReady === undefined || typeof record.libraryReady === 'boolean');
+}
+
+async function readLibraryMeta(root: string): Promise<Record<string, unknown> | null> {
+ const file = path.join(root, '.cindy-library', 'meta.json');
+ let raw: string;
+ try {
+ raw = await fs.promises.readFile(file, 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' && !fs.existsSync(root)) return null;
+ throw error;
+ }
+ const meta: unknown = JSON.parse(raw);
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta) ||
+ (meta as { version?: unknown }).version !== 1 ||
+ typeof (meta as { createdAt?: unknown }).createdAt !== 'number' ||
+ typeof (meta as { ghostId?: unknown }).ghostId !== 'string') {
+ throw new Error('library meta is invalid');
+ }
+ return meta as Record<string, unknown>;
+}
+
+export async function assertLibraryMetaOwner(root: string, ownerId: string): Promise<void> {
+ if (!isLibraryOwnerId(ownerId)) throw new Error('library owner id is invalid');
+ const meta = await readLibraryMeta(root);
+ if (meta && meta.ghostId !== ownerId) throw new Error('library meta belongs to a different plugin');
+}
+
+export async function relocateLibraryMetaOwner(
+ root: string, fromId: string, toId: string, assertCurrent: () => void = () => {},
+): Promise<boolean> {
+ if (!isLibraryOwnerId(fromId) || !isLibraryOwnerId(toId)) {
+ throw new Error('library meta relocate ids are invalid');
+ }
+ const meta = await readLibraryMeta(root);
+ assertCurrent();
+ if (!meta) return false;
+ const owner = meta.ghostId;
+ if (owner === toId) return false;
+ if (owner !== fromId) throw new Error('library meta belongs to a different plugin');
+ const file = path.join(root, '.cindy-library', 'meta.json');
+ const temporary = file + '.' + randomUUID() + '.tmp';
+ try {
+ await fs.promises.writeFile(temporary, JSON.stringify({ ...meta, ghostId: toId }), { flag: 'wx', mode: 0o600 });
+ assertCurrent();
+ await fs.promises.rename(temporary, file);
+ } finally {
+ await fs.promises.rm(temporary, { force: true });
+ }
+ return true;
}
export type LibraryLocationResolution =
@@ -199,30 +308,113 @@ export class LibraryBindingStore {
return next;
}
- private async readData(): Promise<LibraryBindingFileData> {
+ private async readData(strict = false): Promise<LibraryBindingFileData> {
+ const file = this.deps.getFile();
+ let data: LibraryBindingFileData;
+ let hasRelocation = false;
try {
- const raw = JSON.parse(await fs.promises.readFile(this.deps.getFile(), 'utf8')) as LibraryBindingFileData;
- if (typeof raw === 'object' && raw !== null && raw.version === 1 && typeof raw.bindings === 'object' && raw.bindings !== null) {
- return raw;
+ const raw = JSON.parse(await fs.promises.readFile(file, 'utf8')) as LibraryBindingFileData;
+ hasRelocation = typeof raw === 'object' && raw !== null && 'pendingRelocation' in raw;
+ if (typeof raw === 'object' && raw !== null && raw.version === 1 &&
+ typeof raw.bindings === 'object' && raw.bindings !== null && !Array.isArray(raw.bindings)) {
+ data = raw;
+ } else {
+ throw new Error('malformed');
+ }
+ if (strict && Object.entries(data.bindings).some(([ghostId, record]) =>
+ !isLibraryOwnerId(ghostId) || !isLibraryBindingRecord(record))) {
+ throw new Error('library binding record is invalid');
}
- throw new Error('malformed');
} catch (err) {
+ if (hasRelocation) throw new Error('library relocation journal is invalid');
+ if (strict && (err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
this.deps.log?.warn('library binding file unreadable; falling back to default roots', {
error: err instanceof Error ? err.message : String(err),
});
}
- return { version: 1, bindings: {} };
+ data = { version: 1, bindings: {} };
}
+ if (file !== this.deps.getFile()) throw new Error('library binding owner changed');
+ return this.recoverRelocation(data, file);
}
/** 原子写(tmp+rename;损坏不放大)。 */
- private async writeData(data: LibraryBindingFileData): Promise<void> {
- const file = this.deps.getFile();
+ private async writeData(data: LibraryBindingFileData, file = this.deps.getFile()): Promise<void> {
+ if (file !== this.deps.getFile()) throw new Error('library binding owner changed');
await fs.promises.mkdir(path.dirname(file), { recursive: true });
const tmp = `${file}.${randomUUID()}.tmp`;
- await fs.promises.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8');
+ const handle = await fs.promises.open(tmp, 'wx', 0o600);
+ try {
+ await handle.writeFile(JSON.stringify(data, null, 2), 'utf8');
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+ if (file !== this.deps.getFile()) throw new Error('library binding owner changed');
await fs.promises.rename(tmp, file);
+ await syncDirectory(path.dirname(file));
+ }
+
+ private async assertRelocationRoot(pending: LibraryBindingRelocation): Promise<void> {
+ const realRoot = await fs.promises.realpath(pending.record.root);
+ const identity = await directoryIdentity(realRoot);
+ if (realRoot !== pending.record.realPathAtGrant ||
+ !isDeepStrictEqual(identity, pending.rootIdentity) ||
+ (pending.record.identity?.ino && !isDeepStrictEqual(identity, pending.record.identity))) {
+ throw new Error('library relocation root identity changed');
+ }
+ }
+
+ private async recoverRelocation(data: LibraryBindingFileData, file: string): Promise<LibraryBindingFileData> {
+ if (data.pendingRelocation === undefined) return data;
+ const pending = data.pendingRelocation;
+ if (!pending || pending.version !== 1 || pending.ownerFile !== path.resolve(file) ||
+ !isLibraryOwnerId(pending.fromGhostId) || !isLibraryOwnerId(pending.toGhostId) ||
+ pending.fromGhostId === pending.toGhostId || !pending.record ||
+ typeof pending.record.root !== 'string' || !path.isAbsolute(pending.record.root) ||
+ typeof pending.record.realPathAtGrant !== 'string' ||
+ !Number.isInteger(pending.record.generation) || pending.record.generation < 1 ||
+ !isDirectoryIdentity(pending.rootIdentity) ||
+ (pending.libraryIdentity !== null && !isDirectoryIdentity(pending.libraryIdentity))) {
+ throw new Error('library relocation journal is invalid');
+ }
+ const sourceBinding = data.bindings[pending.fromGhostId];
+ const targetBinding = data.bindings[pending.toGhostId];
+ const beforeCommit = sourceBinding !== undefined && targetBinding === undefined &&
+ isDeepStrictEqual(sourceBinding, pending.record);
+ const afterCommit = sourceBinding === undefined && targetBinding !== undefined &&
+ isDeepStrictEqual(targetBinding, pending.record);
+ if (!beforeCommit && !afterCommit) throw new Error('library relocation binding generation changed');
+ await this.assertRelocationRoot(pending);
+ const fromRoot = path.join(pending.record.realPathAtGrant, pending.fromGhostId);
+ const toRoot = path.join(pending.record.realPathAtGrant, pending.toGhostId);
+ const sourceIdentity = await directoryIdentity(fromRoot);
+ const targetIdentity = await directoryIdentity(toRoot);
+ if (pending.libraryIdentity === null) {
+ if (sourceIdentity !== null || targetIdentity !== null || pending.record.libraryReady !== false) {
+ throw new Error('library relocation directory identity changed');
+ }
+ } else if (beforeCommit && isDeepStrictEqual(sourceIdentity, pending.libraryIdentity) && targetIdentity === null) {
+ if (file !== this.deps.getFile()) throw new Error('library binding owner changed');
+ await fs.promises.rename(fromRoot, toRoot);
+ } else if (sourceIdentity !== null || !isDeepStrictEqual(targetIdentity, pending.libraryIdentity)) {
+ throw new Error('library relocation directory identity changed');
+ }
+ await syncDirectory(pending.record.realPathAtGrant);
+ await this.assertRelocationRoot(pending);
+ if (!isDeepStrictEqual(await directoryIdentity(toRoot), pending.libraryIdentity) ||
+ await directoryIdentity(fromRoot) !== null) {
+ throw new Error('library relocation directory identity changed');
+ }
+ if (beforeCommit) {
+ data.bindings[pending.toGhostId] = pending.record;
+ delete data.bindings[pending.fromGhostId];
+ await this.writeData(data, file);
+ }
+ delete data.pendingRelocation;
+ await this.writeData(data, file);
+ return data;
}
/**
@@ -235,7 +427,7 @@ export class LibraryBindingStore {
getDiskFreeBytes?: (root: string) => Promise<number | null>,
opts?: { allowInsideManagedRoot?: boolean },
): Promise<{ ok: true; record: LibraryBindingRecord; warnings: string[] } | LocationValidationFailure> {
- if (!/^[a-z0-9][a-z0-9-]*$/.test(ghostId)) {
+ if (!isLibraryOwnerId(ghostId)) {
return { ok: false, errorCode: 'PATH_INVALID', message: 'ghostId 非法' };
}
return this.runSerialized(async () => {
@@ -288,8 +480,64 @@ export class LibraryBindingStore {
});
}
- getBinding(ghostId: string): Promise<LibraryBindingRecord | null> {
- return this.readData().then((d) => d.bindings[ghostId] ?? null);
+ getBinding(ghostId: string, opts?: { strict?: boolean }): Promise<LibraryBindingRecord | null> {
+ return this.runSerialized(async () => (await this.readData(opts?.strict)).bindings[ghostId] ?? null);
+ }
+
+ async assertCanRelocateBinding(fromGhostId: string, toGhostId: string): Promise<void> {
+ if (!isLibraryOwnerId(fromGhostId) || !isLibraryOwnerId(toGhostId)) {
+ throw new Error('library relocate ids are invalid');
+ }
+ if (fromGhostId === toGhostId) return;
+ await this.runSerialized(async () => {
+ const data = await this.readData(true);
+ this.assertRelocationDestination(data, fromGhostId, toGhostId);
+ });
+ }
+
+ private assertRelocationDestination(data: LibraryBindingFileData, fromGhostId: string, toGhostId: string): void {
+ const record = data.bindings[fromGhostId];
+ if (!record) return;
+ if (data.bindings[toGhostId]) {
+ throw new Error(`library binding destination already exists: ${toGhostId}`);
+ }
+ const toRoot = path.join(record.root, toGhostId);
+ if (fs.lstatSync(toRoot, { throwIfNoEntry: false })) {
+ throw new Error(`library custom root destination already exists: ${toRoot}`);
+ }
+ }
+
+ /** Move a custom binding key after a physical instance relocate. */
+ async relocateBinding(fromGhostId: string, toGhostId: string): Promise<void> {
+ if (fromGhostId === toGhostId) return;
+ if (!isLibraryOwnerId(fromGhostId) || !isLibraryOwnerId(toGhostId)) {
+ throw new Error('library relocate ids are invalid');
+ }
+ await this.runSerialized(async () => {
+ const file = this.deps.getFile();
+ const data = await this.readData(true);
+ const record = data.bindings[fromGhostId];
+ if (!record) return;
+ this.assertRelocationDestination(data, fromGhostId, toGhostId);
+ const rootIdentity = await directoryIdentity(record.realPathAtGrant);
+ if (!rootIdentity) throw new Error('library relocation root is missing');
+ const libraryIdentity = await directoryIdentity(path.join(record.realPathAtGrant, fromGhostId));
+ if (libraryIdentity === null && record.libraryReady !== false) {
+ throw new Error('library relocation source is missing');
+ }
+ data.pendingRelocation = {
+ version: 1,
+ ownerFile: path.resolve(file),
+ fromGhostId,
+ toGhostId,
+ record,
+ rootIdentity,
+ libraryIdentity,
+ };
+ await this.assertRelocationRoot(data.pendingRelocation);
+ await this.writeData(data, file);
+ await this.recoverRelocation(data, file);
+ });
}
/** First successful custom open: persist ready without bumping generation. */
diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.ts
index 25c3e262a0..898ce4a58d 100644
--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts
@@ -26,6 +26,7 @@ import {
GHOST_LIBRARY_CAPABILITIES_V1,
GHOST_LIBRARY_OPS,
GHOST_PICK_MIN_INTERVAL_MS,
+ ghostInstallApprovalToken,
type GhostLibraryErrorReason,
type GhostPipeLibraryResult,
type InstalledGhost,
@@ -167,6 +168,7 @@ export function mintLibraryEpochIdentity(input: {
/** 单插件的库会话(vault + sql 绑定到同一根与 owner scope)。 */
interface GhostLibrarySession {
ghostId: string;
+ requestTarget: GhostLibraryRequestTarget;
vault: LibraryVault;
sql: LibrarySqlService;
/** 会话创建时捕获的 owner scope key;每请求比对,变了就整会话作废。 */
@@ -180,6 +182,14 @@ interface GhostLibrarySession {
identity: string;
}
+interface GhostLibraryRequestTarget {
+ relocationGeneration: number;
+ ownerScopeKey: string | null;
+ ghostTarget: string | null;
+}
+
+class GhostLibraryRequestCancelled extends Error {}
+
export interface GhostLibrarySlotDeps {
getGhost(id: string): InstalledGhost | null;
/** 自定义位置 binding 存储(owner-scoped;生产注入)。 */
@@ -241,6 +251,7 @@ export class GhostLibrarySlot {
private readonly sessions = new Map<string, GhostLibrarySession>();
/** 迁移进行中的插件:全部写操作只读化(切换与 grace 前不再有写入落旧根)。 */
private readonly relocating = new Set<string>();
+ private readonly relocationGenerations = new Map<string, number>();
/** 插件 id → 上次 reveal 尝试时刻(按尝试记账;对齐 pick/confirm 骚扰钳制)。 */
private readonly lastRevealAttemptAt = new Map<string, number>();
/** 插件 id → 上次 saveAs 尝试时刻(按尝试记账;对齐 pick/confirm 骚扰钳制)。 */
@@ -273,8 +284,42 @@ export class GhostLibrarySlot {
/** 迁移期只读闸(设置页迁移在 copying 前置位、结束后清除)。 */
setRelocating(ghostId: string, on: boolean): void {
- if (on) this.relocating.add(ghostId);
- else this.relocating.delete(ghostId);
+ if (on) {
+ this.advanceRelocationGeneration(ghostId);
+ this.relocating.add(ghostId);
+ } else this.relocating.delete(ghostId);
+ }
+
+ private advanceRelocationGeneration(ghostId: string): void {
+ this.relocationGenerations.set(ghostId, (this.relocationGenerations.get(ghostId) ?? 0) + 1);
+ }
+
+ private ghostRequestTarget(ghostId: string): string | null {
+ const ghost = this.deps.getGhost(ghostId);
+ return ghost ? JSON.stringify([
+ ghost.manifest.id, ghost.dir, ghost.namespace ?? null, ghost.enabled !== false,
+ ghostInstallApprovalToken(ghost.approval),
+ ]) : null;
+ }
+
+ private captureRequestTarget(ghostId: string, ownerScopeKey = this.deps.captureOwnerScope()): GhostLibraryRequestTarget {
+ const relocationGeneration = this.relocationGenerations.get(ghostId) ?? 0;
+ this.relocationGenerations.set(ghostId, relocationGeneration);
+ return { relocationGeneration, ownerScopeKey, ghostTarget: this.ghostRequestTarget(ghostId) };
+ }
+
+ private isRequestCurrent(ghostId: string, target: GhostLibraryRequestTarget): boolean {
+ return !this.relocating.has(ghostId)
+ && target.relocationGeneration === this.relocationGenerations.get(ghostId)
+ && target.ownerScopeKey === this.deps.captureOwnerScope()
+ && this.checkEligibility(ghostId)
+ && target.ghostTarget === this.ghostRequestTarget(ghostId);
+ }
+
+ private assertRequestCurrent(ghostId: string, target: GhostLibraryRequestTarget, session?: GhostLibrarySession): void {
+ if (!this.isRequestCurrent(ghostId, target) || (session && this.sessions.get(ghostId) !== session)) {
+ throw new GhostLibraryRequestCancelled('Library 请求目标已变化,操作已取消');
+ }
}
private beginStagingRelease(ghostId: string): () => void {
@@ -357,6 +402,9 @@ export class GhostLibrarySlot {
try {
return await this.dispatch(ghostId, payload);
} catch (err) {
+ if (err instanceof GhostLibraryRequestCancelled) {
+ return fail('LIBRARY_UNAVAILABLE', err.message, 'CANCELLED');
+ }
this.deps.log?.warn('ghost library-request unexpected failure', {
ghostId,
error: err instanceof Error ? err.message : String(err),
@@ -396,7 +444,7 @@ export class GhostLibrarySlot {
}
return this.dispatchStaging(ghostId, op, req);
}
- // 迁移期只读:写类操作在 copying 全程拒绝(读与状态查询照常)。
+ // 迁移期只读:写类操作在 copying 全程拒绝。
const writeOps: ReadonlySet<string> = new Set([
'write', 'writeBegin', 'writeChunk', 'writeCommit', 'writeAbort',
'mkdir', 'delete', 'rename',
@@ -408,46 +456,60 @@ export class GhostLibrarySlot {
}
}
+ const target = this.captureRequestTarget(ghostId);
const runSessionOp = async (): Promise<GhostPipeLibraryResult> => {
- const scopeKey = this.deps.captureOwnerScope();
- const session = await this.getOrCreateSession(ghostId, scopeKey);
- return this.runOp(ghostId, session, op, req);
+ this.assertRequestCurrent(ghostId, target);
+ const session = await this.getOrCreateSession(ghostId, target.ownerScopeKey, target);
+ this.assertRequestCurrent(ghostId, target, session);
+ const result = await this.runOp(ghostId, session, op, req);
+ this.assertRequestCurrent(ghostId, target, session);
+ return result;
};
if (writeOps.has(op)) return this.runGhostExclusive(ghostId, runSessionOp);
return runSessionOp();
}
- private async getOrCreateSession(ghostId: string, scopeKey: string | null): Promise<GhostLibrarySession> {
+ private async getOrCreateSession(
+ ghostId: string,
+ scopeKey: string | null,
+ target = this.captureRequestTarget(ghostId, scopeKey),
+ ): Promise<GhostLibrarySession> {
+ this.assertRequestCurrent(ghostId, target);
let session = this.sessions.get(ghostId);
const capturedScope = session;
- if (session && session.ownerScopeKey !== scopeKey) {
+ if (session && !this.isRequestCurrent(ghostId, session.requestTarget)) {
await this.teardownSession(ghostId, capturedScope);
+ this.assertRequestCurrent(ghostId, target);
session = this.sessions.get(ghostId);
if (session === capturedScope) session = undefined;
}
- const resolution = await this.confirmLiveCustomRoot(
- await this.deps.bindingStore.resolveLibraryRoot(ghostId),
- );
- session = this.sessions.get(ghostId) ?? session;
+ const resolved = await this.deps.bindingStore.resolveLibraryRoot(ghostId);
+ this.assertRequestCurrent(ghostId, target);
+ const resolution = await this.confirmLiveCustomRoot(resolved);
+ this.assertRequestCurrent(ghostId, target);
+ session = this.sessions.get(ghostId);
if (session && session.ownerScopeKey !== scopeKey) {
const staleScope = session;
await this.teardownSession(ghostId, staleScope);
+ this.assertRequestCurrent(ghostId, target);
session = this.sessions.get(ghostId);
if (session === staleScope) session = undefined;
}
if (session && !this.sessionMatchesResolution(session, resolution)) {
const staleRoot = session;
await this.teardownSession(ghostId, staleRoot);
+ this.assertRequestCurrent(ghostId, target);
session = this.sessions.get(ghostId);
if (session === staleRoot) session = undefined;
}
if (!session) {
- session = this.createSession(ghostId, resolution, scopeKey);
+ session = this.createSession(ghostId, resolution, scopeKey, target);
this.sessions.set(ghostId, session);
// 会话建立即自动 open vault(幂等):消除"write 前忘 open"的脚枪。
// extraDirs 只在显式 open 时挂,status / 首次任意请求不得抢槽。
if (session.drift === null) {
const opened = await session.vault.open();
+ this.assertRequestCurrent(ghostId, target, session);
if (
opened.ok
&& opened.state === 'unavailable'
@@ -457,6 +519,7 @@ export class GhostLibrarySlot {
} else {
if (opened.ok && opened.state === 'ready' && resolution.kind === 'custom' && resolution.root !== null) {
await this.deps.bindingStore.markLibraryReady(ghostId).catch(() => {});
+ this.assertRequestCurrent(ghostId, target, session);
}
if (session.vault.getMeta()?.orphaned) {
// 重装自愈:能走到这里 = 插件已装入且启用,清掉卸载时留的 orphaned
@@ -468,6 +531,7 @@ export class GhostLibrarySlot {
await this.syncAgentReadonlyExtraDir(ghostId, null);
}
}
+ this.assertRequestCurrent(ghostId, target, session);
return session;
}
@@ -481,6 +545,7 @@ export class GhostLibrarySlot {
const ghost = this.deps.getGhost(ghostId);
if (!ghost) return false;
if (ghost.enabled === false) return false;
+ if (ghost.approval && ghost.approval.state !== 'approved') return false;
return ghost.manifest.library === true;
}
@@ -494,7 +559,9 @@ export class GhostLibrarySlot {
if (!this.checkEligibility(ghostId)) return null;
const session = await this.getOrCreateSession(ghostId, this.deps.captureOwnerScope());
if (session.drift !== null) return null;
- return await session.vault.resolveExistingFile(relPath);
+ const resolved = await session.vault.resolveExistingFile(relPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
+ return resolved;
} catch {
return null;
}
@@ -560,6 +627,7 @@ export class GhostLibrarySlot {
ghostId: string,
resolution: LibraryLocationResolution,
scopeKey: string | null,
+ requestTarget: GhostLibraryRequestTarget,
): GhostLibrarySession {
const drift = 'drift' in resolution && resolution.root === null ? resolution.drift : null;
const root = resolution.kind === 'custom' && resolution.root !== null
@@ -594,6 +662,7 @@ export class GhostLibrarySlot {
});
return {
ghostId,
+ requestTarget,
vault,
sql,
ownerScopeKey: scopeKey,
@@ -910,13 +979,14 @@ export class GhostLibrarySlot {
/** 停用/卸载/owner 切换收口:作废全部会话(commit 5 的生命周期接线点)。 */
async disposeGhost(ghostId: string): Promise<void> {
+ this.advanceRelocationGeneration(ghostId);
await this.waitForStagingReleases(ghostId);
await this.teardownSession(ghostId);
await this.disposeStagingStores(ghostId);
}
async disposeAll(): Promise<void> {
- const ids = new Set([...this.sessions.keys(), ...this.stagingReleaseInflight.keys()]);
+ const ids = new Set([...this.sessions.keys(), ...this.stagingReleaseInflight.keys(), ...this.relocationGenerations.keys()]);
for (const key of this.stagingStores.keys()) {
const ghostId = key.split('\0')[1];
if (ghostId) ids.add(ghostId);
@@ -954,7 +1024,7 @@ export class GhostLibrarySlot {
if (!this.checkEligibility(ghostId)) {
return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力', 'PERMISSION_DENIED');
}
- if (this.deps.captureOwnerScope() !== session.ownerScopeKey) {
+ if (!this.isRequestCurrent(ghostId, session.requestTarget)) {
return fail('LIBRARY_UNAVAILABLE', cancelledMessage, 'CANCELLED');
}
const live = this.sessions.get(ghostId);
@@ -1005,6 +1075,7 @@ export class GhostLibrarySlot {
op: string,
req: Record<string, unknown>,
): Promise<GhostPipeLibraryResult> {
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
// 漂移占位会话:open/status 如实报 unavailable+reason,其余操作全拒
// (绝不当空库、绝不落默认根冒充)。
if (session.drift !== null && op !== 'open' && op !== 'status') {
@@ -1025,6 +1096,7 @@ export class GhostLibrarySlot {
switch (op) {
case 'open': {
const r = await vault.open();
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!r.ok) return vaultFail(r);
if (r.state === 'unavailable' && (r.reason === 'disk-missing' || r.reason === 'binding-moved')) {
await this.latchCustomUnavailable(session, ghostId, r.reason);
@@ -1038,6 +1110,7 @@ export class GhostLibrarySlot {
const live = await this.confirmLiveCustomRoot(
await this.deps.bindingStore.resolveLibraryRoot(ghostId),
);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (live.kind !== 'custom' || live.root === null) {
const reason = live.kind === 'custom' && live.root === null && live.drift === 'binding-moved'
? 'binding-moved'
@@ -1060,6 +1133,7 @@ export class GhostLibrarySlot {
}
case 'status': {
const r = await vault.status();
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!r.ok) return vaultFail(r);
if (this.extraDirOpenerGhostId === ghostId) {
await this.syncAgentReadonlyExtraDir(ghostId, vault.getRootDir());
@@ -1325,9 +1399,11 @@ export class GhostLibrarySlot {
}
case 'db.open': {
const resolved = await this.resolveDbPath(session, req.dbPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!('abs' in resolved)) return resolved;
// 父目录由宿主建好(better-sqlite3 只建文件不建目录)。
await fs.promises.mkdir(path.dirname(resolved.abs), { recursive: true }).catch(() => {});
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
const r = await session.sql.open(resolved.abs);
return this.dbResultToPipe(op, r);
}
@@ -1335,6 +1411,7 @@ export class GhostLibrarySlot {
const diskGate = await this.dbDiskGate(session);
if (diskGate) return diskGate;
const resolved = await this.resolveDbPath(session, req.dbPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!('abs' in resolved)) return resolved;
const r = await session.sql.exec(resolved.abs, req.sql as string, req.params);
return this.dbResultToPipe(op, r);
@@ -1343,6 +1420,7 @@ export class GhostLibrarySlot {
const diskGate = await this.dbDiskGate(session);
if (diskGate) return diskGate;
const resolved = await this.resolveDbPath(session, req.dbPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!('abs' in resolved)) return resolved;
const r = await session.sql.batch(resolved.abs, (req.statements as Array<{ sql: string; params?: unknown }>) ?? []);
return this.dbResultToPipe(op, r);
@@ -1351,6 +1429,7 @@ export class GhostLibrarySlot {
const diskGate = await this.dbDiskGate(session);
if (diskGate) return diskGate;
const resolved = await this.resolveDbPath(session, req.dbPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!('abs' in resolved)) return resolved;
// 迁移前自动在线备份(宿主命名空间,插件路径语法写不进);备份失败
// 是硬前置——报错中止,不带伤迁移。
@@ -1359,7 +1438,9 @@ export class GhostLibrarySlot {
`pre-migrate-${Date.now()}-${Math.floor(Math.random() * 1e6)}.db`,
);
await fs.promises.mkdir(path.dirname(backupDest), { recursive: true }).catch(() => {});
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
const bak = await session.sql.backup(resolved.abs, backupDest);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!bak.ok) return this.dbResultToPipe('db.backup', bak);
const r = await session.sql.migrate(
resolved.abs,
@@ -1370,21 +1451,25 @@ export class GhostLibrarySlot {
}
case 'db.backup': {
const resolved = await this.resolveDbPath(session, req.dbPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!('abs' in resolved)) return resolved;
const label = typeof req.label === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(req.label) ? req.label : 'manual';
const dest = path.join(session.vault.getRootDir(), '.cindy-library', 'backups', `${label}-${Date.now()}.db`);
await fs.promises.mkdir(path.dirname(dest), { recursive: true }).catch(() => {});
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
const r = await session.sql.backup(resolved.abs, dest);
return this.dbResultToPipe(op, r);
}
case 'db.check': {
const resolved = await this.resolveDbPath(session, req.dbPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!('abs' in resolved)) return resolved;
const r = await session.sql.check(resolved.abs);
return this.dbResultToPipe(op, r);
}
case 'db.userVersion': {
const resolved = await this.resolveDbPath(session, req.dbPath);
+ this.assertRequestCurrent(ghostId, session.requestTarget, session);
if (!('abs' in resolved)) return resolved;
const r = await session.sql.userVersion(resolved.abs);
return this.dbResultToPipe(op, r);
diff --git a/apps/desktop/src/main/cindy-brain/libraryStaging.ts b/apps/desktop/src/main/cindy-brain/libraryStaging.ts
index 774310c173..d05f091524 100644
--- a/apps/desktop/src/main/cindy-brain/libraryStaging.ts
+++ b/apps/desktop/src/main/cindy-brain/libraryStaging.ts
@@ -5,6 +5,8 @@
*/
import { randomUUID } from 'node:crypto';
+import { lstat } from 'node:fs/promises';
+import { relocateLibraryMetaOwner } from './libraryBinding.js';
import {
LibraryVault,
@@ -355,6 +357,63 @@ function identityMatches(actual: TaskIdentity, expected: TaskIdentity): boolean
&& sameRecovery(actual.recovery, expected.recovery);
}
+export async function relocateLibraryStagingOwner(
+ root: string, fromId: string, toId: string, ownerScopeKey: string, assertCurrent: () => void,
+): Promise<void> {
+ assertCurrent();
+ const stat = await lstat(root).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ assertCurrent();
+ if (!stat) return;
+ if (!stat.isDirectory()) throw new Error('staging relocation root is not a directory');
+ await relocateLibraryMetaOwner(root, fromId, toId, assertCurrent);
+ assertCurrent();
+ const vault = new LibraryVault({ rootDir: () => root, ghostId: toId });
+ try {
+ const opened = await vault.open();
+ assertCurrent();
+ if (!opened.ok) throw new Error(opened.message);
+ let cursor: string | null = null;
+ do {
+ const page = await vault.list({ path: 'tasks', cursor, strict: true });
+ assertCurrent();
+ if (!page.ok) {
+ if (page.errorCode === 'NOT_FOUND' && cursor === null) break;
+ throw new Error(page.message);
+ }
+ for (const entry of page.entries) {
+ const stagingId = entry.path.slice('tasks/'.length);
+ if (entry.kind !== 'dir' || !UUID.test(stagingId)) continue;
+ for (const [file, parse] of [
+ [manifestPath(stagingId), parseManifest], [intentPath(stagingId), parseIntent],
+ ] as const) {
+ const raw = await vault.read({ path: file, encoding: 'utf8' });
+ assertCurrent();
+ if (!raw.ok) {
+ if (raw.errorCode === 'NOT_FOUND') continue;
+ throw new Error(raw.message);
+ }
+ const parsed = parseJsonObject(raw.content, 'staging relocation');
+ if (!parsed.ok) throw new Error(parsed.message);
+ const owner = parsed.value.ghostId;
+ if (owner !== fromId && owner !== toId) throw new Error('staging task belongs to a different plugin');
+ const task = parse(raw.content, stagingId, owner, ownerScopeKey);
+ if ('errorCode' in task) throw new Error(task.message);
+ if (owner === toId) continue;
+ const written = await vault.write({ path: file, content: JSON.stringify({ ...parsed.value, ghostId: toId }) });
+ assertCurrent();
+ if (!written.ok) throw new Error(written.message);
+ }
+ }
+ cursor = page.hasMore ? page.nextCursor : null;
+ } while (cursor !== null);
+ } finally {
+ await vault.invalidate();
+ }
+}
+
export class LibraryStagingStore {
private readonly limits: LibraryStagingLimits;
private readonly ownerScopeKey: string;
diff --git a/apps/desktop/src/main/cindy-brain/libraryVault.ts b/apps/desktop/src/main/cindy-brain/libraryVault.ts
index b257259417..a3d1a735b1 100644
--- a/apps/desktop/src/main/cindy-brain/libraryVault.ts
+++ b/apps/desktop/src/main/cindy-brain/libraryVault.ts
@@ -498,7 +498,7 @@ export class LibraryVault {
/* ── 打开与状态 ─────────────────────────────────────────────────── */
/**
- * 打开(幂等):建目录骨架 → 清理超龄 staging 残渣 → 读/建 meta → 读/扫
+ * 打开(幂等):建目录骨架 → 读/建 meta → 清理超龄 staging 残渣 → 读/扫
* 用量账本。meta 存在但读不出/不合法 → unavailable(corrupt),**不重建**。
*/
async open(): Promise<LibraryResult<{ state: LibraryState; reason: string | null; usedBytes: number; fileCount: number }>> {
@@ -540,6 +540,9 @@ export class LibraryVault {
ghostId: dirSeg,
});
if (existing.ok) {
+ if (this.deps.ghostId && existing.meta.ghostId !== this.deps.ghostId) {
+ return this.customRootUnavailable('binding-moved');
+ }
this.meta = existing.meta;
if (existing.usage) customUsage = existing.usage;
} else if (existing.code === 'MISSING') {
@@ -599,7 +602,6 @@ export class LibraryVault {
return { ok: true as const, state: this.state, reason: this.unavailableReason, usedBytes: 0, fileCount: 0 };
}
const customOpen = (this.deps.locationKind ?? 'default') === 'custom';
- if (!customOpen) await this.sweepStaleTmp();
// meta:已存在必须可解析(不可用 ≠ 空);不存在则首建。custom 首次 open 用 held-fd 已写的 meta,不再 path 写。
if (!this.meta) {
@@ -609,6 +611,7 @@ export class LibraryVault {
if (
typeof parsed !== 'object' || parsed === null || parsed.version !== 1 ||
typeof parsed.ghostId !== 'string' || typeof parsed.createdAt !== 'number'
+ || (this.deps.ghostId !== undefined && parsed.ghostId !== this.deps.ghostId)
) {
throw new Error('malformed meta');
}
@@ -634,6 +637,8 @@ export class LibraryVault {
}
}
+ if (!customOpen) await this.sweepStaleTmp();
+
// 用量:合法账本只读复用;坏/缺才 scan。custom 首次 open 不 persist/unlink。
let ledger: UsageLedger | null = customUsage;
if (!ledger) {
diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
index b7821055af..e71c356706 100644
--- a/apps/desktop/src/main/cindy-brain/mobilePageService.ts
+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
@@ -14,6 +14,7 @@ import {
type PluginConfigurationSummary,
} from '@cindy/device-link';
import { ghostContentKeys, ghostPermissionItems, ghostTrustLabelKey, type GhostSetupAssessment, type InstalledGhost } from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
import { resolvePreferredSystemLocale } from '../../shared/locale.js';
import { t } from '../i18n.js';
import { mobilePluginUsage } from './mobilePluginUsage.js';
@@ -116,7 +117,7 @@ export class MobilePluginPages {
return this.deps.now?.() ?? Date.now();
}
private ghost(id: string) {
- return this.deps.list().find((g) => g.manifest.id === id) ?? fail();
+ return this.deps.list().find((g) => installedGhostStoragePart(g) === id) ?? fail();
}
private check(page: Page, enabled = true): InstalledGhost {
const ghost = this.ghost(page.plugin);
@@ -305,10 +306,11 @@ export class MobilePluginPages {
}
private item(ghost: InstalledGhost, order?: RemoteCollectionItem['pluginOrder']): RemoteCollectionItem {
const m = ghost.manifest;
+ const id = installedGhostStoragePart(ghost);
const mobile = parsePluginMobileDeclaration(m.mobile);
- const unread = ghost.enabled ? this.deps.unread(m.id) : null;
+ const unread = ghost.enabled ? this.deps.unread(id) : null;
return {
- ref: { collectionId: PLUGIN_COLLECTION, kind: 'plugin', id: m.id },
+ ref: { collectionId: PLUGIN_COLLECTION, kind: 'plugin', id },
revision: this.deps.revision(ghost),
...(order ? { pluginOrder: order } : {}),
display: {
@@ -369,7 +371,7 @@ export class MobilePluginPages {
!q ||
`${g.manifest.name} ${g.manifest.description ?? ''}`.toLocaleLowerCase().includes(q),
)
- .map((g) => this.item(g, order?.get(g.manifest.id)));
+ .map((g) => this.item(g, order?.get(installedGhostStoragePart(g))));
return {
collectionId: PLUGIN_COLLECTION,
revision: createHash('sha256').update(JSON.stringify(items)).digest('hex'),
@@ -403,13 +405,13 @@ export class MobilePluginPages {
];
let assessment: GhostSetupAssessment | undefined;
try {
- assessment = this.deps.setupAssessment?.(ghost.manifest.id);
+ assessment = this.deps.setupAssessment?.(installedGhostStoragePart(ghost));
} catch {
// A failed read is unknown, never a fabricated missing configuration.
}
let configuration = mobilePluginConfiguration(ghost.manifest, undefined, assessment);
try {
- configuration = this.deps.configuration?.(ghost.manifest.id, assessment) ?? configuration;
+ configuration = this.deps.configuration?.(installedGhostStoragePart(ghost), assessment) ?? configuration;
} catch {
// A failed configuration read retains declarations with unknown status.
}
@@ -439,7 +441,7 @@ export class MobilePluginPages {
usage: mobilePluginUsage(
ghost,
assessment,
- this.deps.runtimeState?.(ghost.manifest.id),
+ this.deps.runtimeState?.(installedGhostStoragePart(ghost)),
configuration,
),
},
@@ -551,7 +553,7 @@ export class MobilePluginPages {
this.pages.set(page.id, page);
const result: PluginPageDocument = {
pageId: page.id,
- pluginId: id,
+ pluginId: installedGhostStoragePart(ghost),
title: ghost.manifest.name,
surface,
entry,
diff --git a/apps/desktop/src/main/cindy-brain/networkSlot.ts b/apps/desktop/src/main/cindy-brain/networkSlot.ts
index 36cda09831..629e5a8d7b 100644
--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts
@@ -17,7 +17,7 @@
* → 响应文本化(体积上限截断;响应头只回白名单字段)
* → 只回结构化 GhostPipeFetchResult(永不 reject)
*
- * 安全纪律:凭证明文与响应体永不进日志(只记 ghostId / host / 状态码 /
+ * 安全纪律:凭证明文与响应体永不进日志(只记 instanceKey / host / 状态码 /
* callId);URL 只记 host + pathname,query 可能携带敏感参数,不记。
*
* 依赖注入(规则 14):凭证读取与 HTTP 执行全部经 deps,单测直测零 Electron。
@@ -64,9 +64,10 @@ import {
export interface NetworkSlotDeps {
getGhost(id: string): InstalledGhost | null;
+ captureRequestGuard?(instanceKey: string): () => void;
/**
* callId → 严格在途的 Agent 调用上下文。只有 channel:'session'、
- * sessionId 存在、明确是本地会话(remoteHostId === null)且 ghostId
+ * sessionId 存在、明确是本地会话(remoteHostId === null)且 instanceKey
* 匹配时,才能复用外层 ghost_call 已经通过的 Cindy Agent 授权;
* 面板、订阅、后台、远程 SSH 与脚本通道都不在此列。
*/
@@ -81,7 +82,7 @@ export interface NetworkSlotDeps {
* 读某意识某条凭证的明文(safeStorage 现读,不缓存——用户改了 key 下一单
* 即生效);未配置 / 读失败返回 null。
*/
- readSecret(ghostId: string, secretKey: string): string | null;
+ readSecret(instanceKey: string, secretKey: string): string | null;
/** source:'gh-cli' 的宿主 GitHub CLI 登录 token;不可用返回 null。 */
readGhCliToken?: () => Promise<string | null>;
/**
@@ -121,17 +122,17 @@ export interface NetworkSlotDeps {
* ghostCanRead——出生自它 / 挂它画廊 / 用户显式过户;越权与不存在统一
* 返回 null,不给探测空间)。ext 含点(如 '.png')。
*/
- readGhostMedia(ghostId: string, hash: string): Promise<{
+ readGhostMedia(instanceKey: string, hash: string): Promise<{
buffer: Uint8Array;
mimeType: string;
ext: string;
} | null>;
/**
* 目录上传通道:凭一次性过户票据取货(生产为 dirDeposit 票据库的 take——
- * ghostId 绑定 + TTL + 单次消费;无效原因不分类统一 null,不给探测空间)。
+ * instanceKey 绑定 + TTL + 单次消费;无效原因不分类统一 null,不给探测空间)。
* 文件字节经 read() 闭包按需读盘,networkSlot 保持零 fs 依赖。
*/
- takeDirDeposit(ghostId: string, token: string): {
+ takeDirDeposit(instanceKey: string, token: string): {
files: Array<{ relPath: string; size: number; read(): Promise<Uint8Array> }>;
totalBytes: number;
} | null;
@@ -140,8 +141,7 @@ export interface NetworkSlotDeps {
* 响应字节写进主 agent 过户的 workdir 目录——文件名主机消毒去重,绝对
* 路径不出主机;无效票据统一 null。
*/
- writeSaveDeposit(
- ghostId: string,
+ writeSaveDeposit(instanceKey: string,
token: string,
fileName: string,
bytes: Uint8Array,
@@ -158,6 +158,7 @@ export interface NetworkSlotDeps {
/** 署名调用的 tool-call callId(记入 ghostMediaLedger 供收口带回);
* 未署名('unattributed')不传、不记账。 */
callId?: string;
+ assertStillValid?: () => void;
}): Promise<{ url: string; hash: string; ext: string }>;
/** 归一化后的 mime 是否可入总仓(生产为 cindy-media 的 supportedMime)。 */
isSupportedMediaMime(mime: string): boolean;
@@ -168,8 +169,7 @@ export interface NetworkSlotDeps {
* 未注入时 oauth 凭证一律快速失败(接线缺失是主机 bug,不静默跳过)。
*/
oauthTokens?: {
- getFreshAccessToken(
- ghostId: string,
+ getFreshAccessToken(instanceKey: string,
secretKey: string,
decl: GhostSecretOauthDecl,
accountId?: string,
@@ -187,14 +187,14 @@ export interface NetworkSlotDeps {
detail?: string;
}
>;
- invalidateAccessToken(ghostId: string, secretKey: string, accountId: string): void;
+ invalidateAccessToken(instanceKey: string, secretKey: string, accountId: string): void;
};
/**
* Cindy organization identity assertions (`source: 'oidc-token'`). Audience
* resolution is Host-owned; manifests and runtime messages cannot choose it.
*/
connectionTokens?: {
- resolve(ghostId: string): {
+ resolve(instanceKey: string): {
membershipId: string;
audience: string;
allowedHosts: readonly string[];
@@ -213,8 +213,8 @@ export interface NetworkSlotDeps {
* 未注入时连接声明形同虚设(动态地址不放行),fail-closed。
*/
connections?: {
- hostsFor(ghostId: string): string[];
- tokenFor(ghostId: string, hostname: string): { value: string; header: string; format: string } | null;
+ hostsFor(instanceKey: string): string[];
+ tokenFor(instanceKey: string, hostname: string): { value: string; header: string; format: string } | null;
};
log?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
@@ -755,7 +755,7 @@ export class GhostNetworkSlot {
private mediaReadsInflight = 0;
/**
* 交换型凭证的令牌缓存(内存,不落盘——重启重换一次开销可忽略,也免去
- * 磁盘上多一份凭证态文件)。键 `${ghostId}\u0000${secretKey}`;sourceValue
+ * 磁盘上多一份凭证态文件)。键 `${instanceKey}\u0000${secretKey}`;sourceValue
* 是换令牌时用的原始 key,用户改了 key 立即失配重换。
*/
private readonly exchangedTokens = new Map<
@@ -767,11 +767,15 @@ export class GhostNetworkSlot {
constructor(private readonly deps: NetworkSlotDeps) {}
+ hasInFlightRequests(instanceKey: string): boolean {
+ return (this.inflight.get(instanceKey) ?? 0) > 0;
+ }
+
/**
* 处理一条 fetch-request(ghost-pipe:send 的 invoke 返回值即本结果)。
* 永不 reject——一切失败折叠成 { ok:false, message }。
*/
- async handleFetchRequest(ghostId: string, payload: unknown): Promise<GhostPipeFetchResult> {
+ async handleFetchRequest(instanceKey: string, payload: unknown): Promise<GhostPipeFetchResult> {
const p = payload as {
url?: unknown;
method?: unknown;
@@ -1037,7 +1041,7 @@ export class GhostNetworkSlot {
const url = parsed.url;
// ── 资格审:意识在场 + 能力详单 ───────────────────────────────────
- const ghost = this.deps.getGhost(ghostId);
+ const ghost = this.deps.getGhost(instanceKey);
if (!ghost || !ghost.enabled) {
return { ok: false, message: '意识不在可用状态' };
}
@@ -1046,7 +1050,7 @@ export class GhostNetworkSlot {
const callInfo = requestCallId
? this.deps.inFlightCallInfo?.(requestCallId) ?? null
: null;
- return callInfo?.ghostId === ghostId
+ return callInfo?.ghostId === instanceKey
&& callInfo.channel === 'session'
&& callInfo.sessionId !== null
&& callInfo.remoteHostId === null;
@@ -1063,14 +1067,17 @@ export class GhostNetworkSlot {
const ghCliSecrets = declaredSecrets.filter((secret) => secret.source === 'gh-cli');
if (
ghCliSecrets.length > 0 &&
- (ghost.manifest.id !== 'cindy-github' || !isCindyOfficialTrustInfo(ghost.trust))
+ (ghost.manifest.id !== 'cindy-github' || ghost.namespace != null ||
+ ghost.namespaceState === 'pending' ||
+ ghost.namespaceState === 'unconfirmed' ||
+ !isCindyOfficialTrustInfo(ghost.trust))
) {
return { ok: false, message: '本意识未通过官方 GitHub 宿主凭证信任校验,已阻断 gh-cli 凭证请求' };
}
// 连接地址每单现读快照(用户在设置页增删地址下一单即生效);本单内含
// 重定向逐跳都用同一份快照,避免跳转中途清单变化产生放行摇摆。
const connectionHosts =
- connectionDecls.length > 0 ? (this.deps.connections?.hostsFor(ghostId) ?? []) : [];
+ connectionDecls.length > 0 ? (this.deps.connections?.hostsFor(instanceKey) ?? []) : [];
// 自主调用仍只能访问 manifest 声明的地址。Agent 在途调用已经
// 通过外层 ghost_call 的 Cindy 授权,因此可以访问未预声明的普通
// 地址;但只有真正命中 manifest 详单的 host 才可获得 Host 托管凭证。
@@ -1095,36 +1102,31 @@ export class GhostNetworkSlot {
// 即使目标是 Agent 临时放行的未声明 host,也必须走一遍
// injectSecrets:它会删掉上一跳/插件伪造的凭证头,只是不会注入
// 任何未命中 manifest 详单的 Host 托管凭证。
- const inject0 = await this.injectSecrets(
- ghostId,
- declaredSecrets,
- connectionDecls,
- url.hostname,
- declaredHosts,
- requestHeaders,
- authAccount,
- );
- if (inject0.error) return { ok: false, message: inject0.error };
- let usedExchange = inject0.usedExchange;
- const oauthInjected = new Map(inject0.oauthInjected);
- const connectionInjected = new Map(inject0.connectionInjected);
- let initialConnectionInjected = new Map(inject0.connectionInjected);
-
// ── 在途并发闸(常量硬顶,防死循环刷单;不是配额)──────────────────
- const inflight = this.inflight.get(ghostId) ?? 0;
+ const inflight = this.inflight.get(instanceKey) ?? 0;
if (inflight >= GHOST_FETCH_INFLIGHT_LIMIT) {
return { ok: false, message: `同时进行的网络请求已达上限(${GHOST_FETCH_INFLIGHT_LIMIT}),请等在途请求返回` };
}
- this.inflight.set(ghostId, inflight + 1);
+ this.inflight.set(instanceKey, inflight + 1);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
timer.unref?.();
let holdingMediaGate = false;
const guardedFetchReleases: Array<() => Promise<void>> = [];
try {
- this.deps.log?.info('ghost fetch-request start', {
- ghostId, callId, method, host: url.hostname, path: url.pathname,
+ const assertStillValid = this.deps.captureRequestGuard?.(instanceKey) ?? (() => {});
+ assertStillValid();
+ const inject0 = await this.injectSecrets(
+ instanceKey, declaredSecrets, connectionDecls, url.hostname, declaredHosts, requestHeaders, authAccount,
+ );
+ assertStillValid();
+ if (inject0.error) return { ok: false, message: inject0.error };
+ let usedExchange = inject0.usedExchange;
+ const oauthInjected = new Map(inject0.oauthInjected);
+ const connectionInjected = new Map(inject0.connectionInjected);
+ let initialConnectionInjected = new Map(inject0.connectionInjected);
+ this.deps.log?.info('ghost fetch-request start', { ghostId: instanceKey, callId, method, host: url.hostname, path: url.pathname,
...(upload ? { uploadFiles: upload.hashes.length } : {}),
...(uploadDir ? { dirUpload: true } : {}),
});
@@ -1137,7 +1139,7 @@ export class GhostNetworkSlot {
}
this.mediaReadsInflight += 1;
holdingMediaGate = true;
- const built = await this.buildUploadBody(ghostId, upload);
+ const built = await this.buildUploadBody(instanceKey, upload);
if ('error' in built) return { ok: false, message: built.error };
body = built.body;
// multipart 的 Content-Type(含 boundary)由主机独占,意识自带的删干净。
@@ -1152,7 +1154,7 @@ export class GhostNetworkSlot {
}
this.mediaReadsInflight += 1;
holdingMediaGate = true;
- const built = await this.buildDirUploadBody(ghostId, uploadDir);
+ const built = await this.buildDirUploadBody(instanceKey, uploadDir);
if ('error' in built) return { ok: false, message: built.error };
body = built.body;
deleteHeaderVariants(requestHeaders, 'Content-Type');
@@ -1167,10 +1169,11 @@ export class GhostNetworkSlot {
let response: Response | null = null;
const originalRequestMethod = method;
for (let attempt = 0; attempt < 2; attempt++) {
+ assertStillValid();
if (attempt > 0) {
- this.invalidateExchangedTokens(ghostId, declaredSecrets);
+ this.invalidateExchangedTokens(instanceKey, declaredSecrets);
for (const [secretKey, accountId] of oauthInjected) {
- this.deps.oauthTokens?.invalidateAccessToken(ghostId, secretKey, accountId);
+ this.deps.oauthTokens?.invalidateAccessToken(instanceKey, secretKey, accountId);
}
for (const input of connectionInjected.values()) {
this.deps.connectionTokens?.invalidate({
@@ -1179,7 +1182,7 @@ export class GhostNetworkSlot {
});
}
const reInject = await this.injectSecrets(
- ghostId,
+ instanceKey,
declaredSecrets,
connectionDecls,
url.hostname,
@@ -1191,8 +1194,7 @@ export class GhostNetworkSlot {
initialConnectionInjected = new Map(reInject.connectionInjected);
for (const [k, v] of reInject.oauthInjected) oauthInjected.set(k, v);
for (const [k, v] of reInject.connectionInjected) connectionInjected.set(k, v);
- this.deps.log?.info('ghost fetch-request 401 → re-auth retry', {
- ghostId, callId, host: url.hostname,
+ this.deps.log?.info('ghost fetch-request 401 → re-auth retry', { ghostId: instanceKey, callId, host: url.hostname,
});
}
let currentUrl = url;
@@ -1204,6 +1206,7 @@ export class GhostNetworkSlot {
response = null;
let currentConnectionInjected = initialConnectionInjected;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
+ assertStillValid();
const hopHeaders = { ...requestHeaders };
// 降级丢 body 后 Content-Type 也要跟着剥(fetch 规范的 request-body-
// headers 语义;multipart 的 boundary 头留着会误导服务端)。
@@ -1212,7 +1215,7 @@ export class GhostNetworkSlot {
// 换了域名的跳转:上一跳注入的凭证不能跟着走,按新 host 重算
// (injectSecrets 开头会先把所有声明凭证头的大小写变体删干净)。
const hopInject = await this.injectSecrets(
- ghostId,
+ instanceKey,
declaredSecrets,
connectionDecls,
currentUrl.hostname,
@@ -1233,7 +1236,7 @@ export class GhostNetworkSlot {
allowedHosts: readonly string[];
} | null = null;
try {
- current = this.deps.connectionTokens?.resolve(ghostId) ?? null;
+ current = this.deps.connectionTokens?.resolve(instanceKey) ?? null;
} catch {
current = null;
}
@@ -1262,6 +1265,7 @@ export class GhostNetworkSlot {
};
const hopHostDeclared = hostDeclared(currentUrl.hostname);
const hopAgentMediated = !hopHostDeclared && hasLiveAgentAuthorization();
+ assertStillValid();
if (!hopHostDeclared && !hopAgentMediated) {
return { ok: false, message: '当前 Agent 调用已结束,未声明目标不再允许访问' };
}
@@ -1270,6 +1274,7 @@ export class GhostNetworkSlot {
currentUrl.toString(),
fetchInit,
() => {
+ assertStillValid();
if (!hasLiveAgentAuthorization()) {
throw new Error('当前 Agent 调用已结束,未声明目标不再允许访问');
}
@@ -1280,6 +1285,7 @@ export class GhostNetworkSlot {
} else {
response = await this.deps.fetchImpl(currentUrl.toString(), fetchInit);
}
+ assertStillValid();
responseConnectionInjected = currentConnectionInjected;
responseMethod = currentMethod;
if (![301, 302, 303, 307, 308].includes(response.status)) break;
@@ -1324,8 +1330,7 @@ export class GhostNetworkSlot {
audience: input.audience,
});
}
- this.deps.log?.info('ghost fetch-request Connection 401 cache invalidated without replay', {
- ghostId, callId, method: responseMethod, host: url.hostname,
+ this.deps.log?.info('ghost fetch-request Connection 401 cache invalidated without replay', { ghostId: instanceKey, callId, method: responseMethod, host: url.hostname,
});
break;
}
@@ -1345,6 +1350,7 @@ export class GhostNetworkSlot {
break;
}
if (!response) return { ok: false, message: '请求未获得响应' };
+ assertStillValid();
// ── 响应收敛:媒体落仓 / 文本透传;体积护栏;响应头白名单 ──────────
const contentType = response.headers.get('content-type') ?? '';
@@ -1389,12 +1395,12 @@ export class GhostNetworkSlot {
}
}
if (!suggested) suggested = url.pathname.split('/').filter(Boolean).pop() ?? 'download';
- const written = await this.deps.writeSaveDeposit(ghostId, saveTo.token, suggested, fileBytes);
+ assertStillValid();
+ const written = await this.deps.writeSaveDeposit(instanceKey, saveTo.token, suggested, fileBytes);
if (!written) {
return { ok: false, message: '落盘票据无效(过期 / 已用完 / 超预算)——请让主 agent 重新过户 save_dir' };
}
- this.deps.log?.info('ghost fetch-request done (file)', {
- ghostId, callId, method, host: url.hostname, status: response.status,
+ this.deps.log?.info('ghost fetch-request done (file)', { ghostId: instanceKey, callId, method, host: url.hostname, status: response.status,
bytes: fileBytes.byteLength, fileName: written.fileName,
});
return {
@@ -1455,8 +1461,7 @@ export class GhostNetworkSlot {
}
if (sniffed.kind === 'text') {
const bodyText = new TextDecoder('utf-8', { fatal: false }).decode(sniffed.bytes);
- this.deps.log?.info('ghost fetch-request done', {
- ghostId, callId, method, host: url.hostname, status: response.status,
+ this.deps.log?.info('ghost fetch-request done', { ghostId: instanceKey, callId, method, host: url.hostname, status: response.status,
bytes: sniffed.bytes.byteLength, mediaSniffMiss: true,
...(sniffed.truncated ? { truncated: true } : {}),
});
@@ -1471,17 +1476,17 @@ export class GhostNetworkSlot {
if (sniffed.overLimit) {
return { ok: false, message: `媒体过大(上限 ${GHOST_FETCH_MEDIA_MAX_BYTES} 字节)——截断的媒体是坏文件,整单拒` };
}
- const saved = await this.deps.saveGhostMedia({
- ghostId,
+ assertStillValid();
+ const saved = await this.deps.saveGhostMedia({ ghostId: instanceKey,
buffer: sniffed.bytes,
// Always persist the MIME recovered from bytes, never the external
// declaration. This also corrects a valid but misdeclared response.
mimeType: sniffed.mime,
...(label !== undefined ? { label } : {}),
...(callId !== 'unattributed' ? { callId } : {}),
+ assertStillValid,
});
- this.deps.log?.info('ghost fetch-request done (media)', {
- ghostId, callId, method, host: url.hostname, status: response.status,
+ this.deps.log?.info('ghost fetch-request done (media)', { ghostId: instanceKey, callId, method, host: url.hostname, status: response.status,
bytes: sniffed.bytes.byteLength, hash: saved.hash, mime: sniffed.mime,
...(sniffGeneric ? { recoveredBySniff: true } : {}),
declaredMime,
@@ -1521,9 +1526,9 @@ export class GhostNetworkSlot {
return { ok: false, message: '文本响应超过 1MB 且大响应通道正忙(全局同时只读一单),请稍后重试' };
}
const { bytes: rawBytes, truncated } = textRead;
+ assertStillValid();
const bodyText = new TextDecoder('utf-8', { fatal: false }).decode(rawBytes);
- this.deps.log?.info('ghost fetch-request done', {
- ghostId, callId, method, host: url.hostname, status: response.status,
+ this.deps.log?.info('ghost fetch-request done', { ghostId: instanceKey, callId, method, host: url.hostname, status: response.status,
bytes: rawBytes.byteLength, ...(truncated ? { truncated } : {}),
});
return {
@@ -1540,17 +1545,16 @@ export class GhostNetworkSlot {
: err instanceof Error ? err.message : String(err);
// 错误消息可能带 URL(含 query),日志只记 host,消息本身回给沙箱前不动
// (意识本来就知道自己请求了什么,不构成泄露)。
- this.deps.log?.warn('ghost fetch-request failed', {
- ghostId, callId, method, host: url.hostname, aborted, error: message,
+ this.deps.log?.warn('ghost fetch-request failed', { ghostId: instanceKey, callId, method, host: url.hostname, aborted, error: message,
});
return { ok: false, message: `请求失败:${message}` };
} finally {
clearTimeout(timer);
await Promise.allSettled(guardedFetchReleases.map((release) => release()));
if (holdingMediaGate) this.mediaReadsInflight -= 1;
- const left = (this.inflight.get(ghostId) ?? 1) - 1;
- if (left <= 0) this.inflight.delete(ghostId);
- else this.inflight.set(ghostId, left);
+ const left = (this.inflight.get(instanceKey) ?? 1) - 1;
+ if (left <= 0) this.inflight.delete(instanceKey);
+ else this.inflight.set(instanceKey, left);
}
}
@@ -1561,8 +1565,7 @@ export class GhostNetworkSlot {
* 据此决定 401 是否触发重换重试)。凭证值只进 headers,不进日志、不进
* 返回值。
*/
- private async injectSecrets(
- ghostId: string,
+ private async injectSecrets(instanceKey: string,
secrets: readonly GhostSecretDecl[],
connectionDecls: readonly GhostConnectionDecl[],
hostname: string,
@@ -1600,7 +1603,7 @@ export class GhostNetworkSlot {
for (const secret of secrets) {
const scope = secret.inject.hosts ?? allHosts;
if (!scope.some((pattern) => ghostNetworkHostMatches(pattern, hostname))) continue;
- const resolved = await this.resolveSecretValue(ghostId, secret, hostname, authAccount);
+ const resolved = await this.resolveSecretValue(instanceKey, secret, hostname, authAccount);
if ('error' in resolved) {
return { error: resolved.error, usedExchange, oauthInjected, connectionInjected };
}
@@ -1617,9 +1620,9 @@ export class GhostNetworkSlot {
// 地址但 token 读不到 = 半身位(理论上不该出现:入库先 token 后清单),
// 与 secrets 同款快速失败,不发一个注定 401 的请求。
if (connectionDecls.length > 0 && this.deps.connections) {
- const connHosts = this.deps.connections.hostsFor(ghostId);
+ const connHosts = this.deps.connections.hostsFor(instanceKey);
if (connHosts.includes(hostname)) {
- const tok = this.deps.connections.tokenFor(ghostId, hostname);
+ const tok = this.deps.connections.tokenFor(instanceKey, hostname);
if (!tok) {
return {
error: `连接地址 ${hostname} 的凭证读取失败——请到主界面侧边栏「插件」的本插件详情页重新添加该连接`,
@@ -1642,8 +1645,7 @@ export class GhostNetworkSlot {
* 换了登录账号或缓存过期则重换,单飞去重——交换缓存按 sourceValue 失配重换,
* 登录邮箱变更天然生效)。
*/
- private async resolveSecretValue(
- ghostId: string,
+ private async resolveSecretValue(instanceKey: string,
secret: GhostSecretDecl,
hostname: string,
authAccount?: string,
@@ -1660,13 +1662,12 @@ export class GhostNetworkSlot {
try {
ghToken = (await this.deps.readGhCliToken?.()) ?? null;
} catch (error) {
- this.deps.log?.warn('ghost gh-cli credential source failed', {
- ghostId,
+ this.deps.log?.warn('ghost gh-cli credential source failed', { ghostId: instanceKey,
error: error instanceof Error ? error.message : String(error),
});
}
if (ghToken && ghToken.trim().length > 0) return { value: ghToken.trim() };
- const fallback = this.deps.readSecret(ghostId, secret.key);
+ const fallback = this.deps.readSecret(instanceKey, secret.key);
if (fallback && fallback.length > 0) return { value: fallback };
return {
error: `凭证「${secret.label}」不可用——未检测到本机 gh 登录,且尚未配置备用 Personal Access Token;请先运行 gh auth login,或到主界面侧边栏「插件」的本插件详情页填写 PAT`,
@@ -1683,21 +1684,19 @@ export class GhostNetworkSlot {
allowedHosts: readonly string[];
} | null;
try {
- resolution = manager.resolve(ghostId);
+ resolution = manager.resolve(instanceKey);
} catch {
- this.deps.log?.warn('ghost Connection audience resolver unavailable', { ghostId });
+ this.deps.log?.warn('ghost Connection audience resolver unavailable', { ghostId: instanceKey});
return { error: 'Cindy 企业身份暂时不可用,请稍后重试或反馈' };
}
if (!resolution) {
- this.deps.log?.warn('ghost Connection audience resolution returned no result', {
- ghostId,
+ this.deps.log?.warn('ghost Connection audience resolution returned no result', { ghostId: instanceKey,
host: hostname,
});
return { error: '当前 Cindy 企业身份不可用于此插件,请确认已登录正确的企业账号' };
}
if (!resolution.allowedHosts.includes(hostname)) {
- this.deps.log?.warn('ghost Connection audience host rejected', {
- ghostId,
+ this.deps.log?.warn('ghost Connection audience host rejected', { ghostId: instanceKey,
host: hostname,
});
return { error: '当前 Cindy 企业身份不可用于此服务地址' };
@@ -1713,8 +1712,7 @@ export class GhostNetworkSlot {
connectionTokenKey: { ...tokenInput, hostname },
};
} catch (error) {
- this.deps.log?.warn('ghost Connection token issuance failed', {
- ghostId,
+ this.deps.log?.warn('ghost Connection token issuance failed', { ghostId: instanceKey,
host: hostname,
error: error instanceof Error ? error.message : String(error),
});
@@ -1731,7 +1729,7 @@ export class GhostNetworkSlot {
if (!mgr) {
return { error: 'OAuth 凭证通道未就绪(主机未接线),请升级应用或反馈' };
}
- const result = await mgr.getFreshAccessToken(ghostId, secret.key, secret.oauth, authAccount);
+ const result = await mgr.getFreshAccessToken(instanceKey, secret.key, secret.oauth, authAccount);
if (!result.ok) {
switch (result.error) {
case 'NO_CLIENT_CONFIG':
@@ -1756,21 +1754,21 @@ export class GhostNetworkSlot {
if ('error' in resolved) return resolved;
raw = resolved.value;
} else {
- const stored = this.deps.readSecret(ghostId, secret.key);
+ const stored = this.deps.readSecret(instanceKey, secret.key);
if (stored === null || stored.length === 0) {
return { error: `凭证「${secret.label}」尚未配置——请到主界面侧边栏「插件」的本插件详情页填入后再试` };
}
raw = stored;
}
if (secret.exchange === undefined) return { value: raw };
- const cacheKey = `${ghostId}\u0000${secret.key}`;
+ const cacheKey = `${instanceKey}\u0000${secret.key}`;
const cached = this.exchangedTokens.get(cacheKey);
if (cached && cached.sourceValue === raw && Date.now() < cached.expiresAt) {
return { value: cached.token };
}
let inflightExchange = this.exchangeInflight.get(cacheKey);
if (!inflightExchange) {
- inflightExchange = this.performExchange(ghostId, secret, raw, cacheKey).finally(() => {
+ inflightExchange = this.performExchange(instanceKey, secret, raw, cacheKey).finally(() => {
this.exchangeInflight.delete(cacheKey);
});
this.exchangeInflight.set(cacheKey, inflightExchange);
@@ -1788,8 +1786,7 @@ export class GhostNetworkSlot {
* 名额(主机内部动作,自带 15s 超时),重定向一律阻断(令牌端点没有
* 跳转的正当理由,跟跳只会把 key 带去别处)。
*/
- private async performExchange(
- ghostId: string,
+ private async performExchange(instanceKey: string,
secret: GhostSecretDecl,
raw: string,
cacheKey: string,
@@ -1848,8 +1845,7 @@ export class GhostNetworkSlot {
token,
expiresAt: Date.now() + ttlMs,
});
- this.deps.log?.info('ghost secret exchange done', {
- ghostId, secretKey: secret.key, host: new URL(ex.url).hostname,
+ this.deps.log?.info('ghost secret exchange done', { ghostId: instanceKey, secretKey: secret.key, host: new URL(ex.url).hostname,
});
return token;
} catch (err) {
@@ -1889,10 +1885,10 @@ export class GhostNetworkSlot {
}
/** 作废某意识全部交换型凭证的令牌缓存(401 重试前调用)。 */
- private invalidateExchangedTokens(ghostId: string, secrets: readonly GhostSecretDecl[]): void {
+ private invalidateExchangedTokens(instanceKey: string, secrets: readonly GhostSecretDecl[]): void {
for (const secret of secrets) {
if (secret.exchange === undefined) continue;
- this.exchangedTokens.delete(`${ghostId}\u0000${secret.key}`);
+ this.exchangedTokens.delete(`${instanceKey}\u0000${secret.key}`);
}
}
@@ -1902,8 +1898,7 @@ export class GhostNetworkSlot {
* 手工拼接(确定性,规则 9;不依赖运行时 FormData 的实现差异)。
* filename 用指纹前 16 位 + 总仓后缀,不含任何用户可控文本。
*/
- private async buildUploadBody(
- ghostId: string,
+ private async buildUploadBody(instanceKey: string,
upload: { hashes: string[]; field: string; fields?: Record<string, string> },
): Promise<{ body: Uint8Array; boundary: string } | { error: string }> {
const boundary = `----cindy-ghost-${randomUUID()}`;
@@ -1912,7 +1907,7 @@ export class GhostNetworkSlot {
let total = 0;
const fileParts: Uint8Array[] = [];
for (const hash of upload.hashes) {
- const media = await this.deps.readGhostMedia(ghostId, hash);
+ const media = await this.deps.readGhostMedia(instanceKey, hash);
if (!media) {
return { error: `媒体不存在或不属于本意识(${hash.slice(0, 8)}…)——只能上传自己名下/用户过户的总仓媒体` };
}
@@ -1958,13 +1953,12 @@ export class GhostNetworkSlot {
/**
* 组装目录上传的 multipart/form-data 体:凭一次性过户票据取货(票据由
- * ghost_call 的 dir 过户发放,ghostId 绑定 + 单次消费 + TTL),先拼普通
+ * ghost_call 的 dir 过户发放,instanceKey 绑定 + 单次消费 + TTL),先拼普通
* 表单字段,再逐文件读盘拼 `<prefix>N` 文件段(filename = 相对路径,
* 服务端按它还原目录结构;Content-Type 统一 octet-stream,与 MCP 版
* FormData+Blob 行为一致)。读盘期间总量再钳一次(过户后文件可能被改)。
*/
- private async buildDirUploadBody(
- ghostId: string,
+ private async buildDirUploadBody(instanceKey: string,
uploadDir: {
token: string;
fields: Record<string, string>;
@@ -1972,7 +1966,7 @@ export class GhostNetworkSlot {
fileField?: string;
},
): Promise<{ body: Uint8Array; boundary: string } | { error: string }> {
- const deposit = this.deps.takeDirDeposit(ghostId, uploadDir.token);
+ const deposit = this.deps.takeDirDeposit(instanceKey, uploadDir.token);
if (!deposit) {
return { error: '目录过户票据无效(不存在 / 已使用 / 已过期)——请让主 agent 重新经 ghost_call 的 dir 参数过户目录' };
}
@@ -2006,8 +2000,7 @@ export class GhostNetworkSlot {
} catch (err) {
// fs 错误的 message 自带绝对路径,绝不能回沙箱("路径不进沙箱"
// 不变量);诊断走主机日志,沙箱只见相对路径 + 分类原因。
- this.deps.log?.warn('ghost dir-upload read failed', {
- ghostId, relPath: file.relPath,
+ this.deps.log?.warn('ghost dir-upload read failed', { ghostId: instanceKey, relPath: file.relPath,
error: err instanceof Error ? err.message : String(err),
});
return { error: `读取文件失败(${file.relPath}):文件可能已被移动、删除或占用——请让主 agent 重新过户目录后重试` };
diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
index f8befca744..e8ffb91841 100644
--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
@@ -39,6 +39,7 @@ import type {
GhostPipeNodeResult,
InstalledGhost,
} from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
import {
GHOST_NODE_CHILD_MODE_FLAG,
GHOST_NODE_MAX_CHILDREN_PER_GHOST,
@@ -785,9 +786,13 @@ export class GhostNodeRuntimeBroker {
return `${ghostId}::${entryRel}`;
}
+ private static instanceId(ghost: InstalledGhost): string {
+ return installedGhostStoragePart(ghost);
+ }
+
stateOf(ghostId: string): 'off' | 'running' {
for (const entry of this.workers.values()) {
- if (entry.ghost.manifest.id === ghostId) return 'running';
+ if (GhostNodeRuntimeBroker.instanceId(entry.ghost) === ghostId) return 'running';
}
return 'off';
}
@@ -795,21 +800,21 @@ export class GhostNodeRuntimeBroker {
/** resident 档在插件启用/启动时调用;按需档保持零进程。常驻只覆盖主入口。
* 同时也是 stop() 的对称点:上层完成更新/重启后调用此方法,清除停止标记。 */
async startResident(ghost: InstalledGhost): Promise<void> {
- this.stoppedGhosts.delete(ghost.manifest.id);
+ this.stoppedGhosts.delete(GhostNodeRuntimeBroker.instanceId(ghost));
if (!ghost.enabled || ghost.manifest.node?.lifecycle !== 'resident') return;
const ownerScopeSnapshot = this.captureOwnerScope();
const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry, ownerScopeSnapshot);
- this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
if (ghost.manifest.node.protocol === 'mcp-stdio') await this.ensureMcpInitialized(entry);
}
/** Recovery-only restart for a runtime that was already running on demand. */
async startForRecovery(ghost: InstalledGhost): Promise<void> {
- this.stoppedGhosts.delete(ghost.manifest.id);
+ this.stoppedGhosts.delete(GhostNodeRuntimeBroker.instanceId(ghost));
if (!ghost.enabled || !ghost.manifest.node) return;
const ownerScopeSnapshot = this.captureOwnerScope();
const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry, ownerScopeSnapshot);
- this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
if (ghost.manifest.node.protocol === 'mcp-stdio') await this.ensureMcpInitialized(entry);
}
@@ -1116,7 +1121,7 @@ export class GhostNodeRuntimeBroker {
/** worker 引导层上行控制帧的总入口:形状不合静默丢,资格逐项查。 */
private handleWorkerControl(entry: WorkerEntry, raw: unknown): void {
- if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;
+ if (!this.ownerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.ownerScopeSnapshot)) return;
const message = parseGhostNodeChildToHostMessage(raw);
if (!message) return;
if (message.type === 'device-authorize' || message.type === 'plugin-authorize') {
@@ -1142,7 +1147,7 @@ export class GhostNodeRuntimeBroker {
entry: WorkerEntry,
message: Extract<GhostNodeChildToHostMessage, { type: 'device-authorize' | 'plugin-authorize' }>,
): void {
- const ghostId = entry.ghost.manifest.id;
+ const ghostId = GhostNodeRuntimeBroker.instanceId(entry.ghost);
const pending = entry.pending.get(message.rpcId);
const reply = (ok: boolean, result?: Awaited<PluginAuthorizationHandle['result']>) =>
this.replyToWorker(entry, message.type === 'device-authorize'
@@ -1226,7 +1231,7 @@ export class GhostNodeRuntimeBroker {
private childCountOf(ghostId: string): number {
let count = 0;
for (const entry of this.workers.values()) {
- if (entry.ghost.manifest.id === ghostId) count += entry.children.size;
+ if (GhostNodeRuntimeBroker.instanceId(entry.ghost) === ghostId) count += entry.children.size;
}
return count;
}
@@ -1238,7 +1243,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;
+ if (!this.ownerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.ownerScopeSnapshot)) return;
entry.child.sendControl?.(message);
}
@@ -1252,7 +1257,7 @@ export class GhostNodeRuntimeBroker {
entry: WorkerEntry,
message: Extract<GhostNodeChildToHostMessage, { type: 'spawn-child' }>,
): Promise<void> {
- const ghostId = entry.ghost.manifest.id;
+ const ghostId = GhostNodeRuntimeBroker.instanceId(entry.ghost);
const fail = (reason: string): void => {
this.deps.log?.warn('ghost node child spawn rejected', { ghostId, reason });
this.replyToWorker(entry, {
@@ -1482,7 +1487,7 @@ export class GhostNodeRuntimeBroker {
this.stopStartingChild(starting);
}
for (const [key, entry] of [...this.workers]) {
- if (entry.ghost.manifest.id === ghostId) this.stopWorker(key, entry);
+ if (GhostNodeRuntimeBroker.instanceId(entry.ghost) === ghostId) this.stopWorker(key, entry);
}
}
@@ -1687,18 +1692,18 @@ export class GhostNodeRuntimeBroker {
entryRel: string,
ownerScopeSnapshot: unknown,
): Promise<WorkerEntry> {
- const key = GhostNodeRuntimeBroker.keyOf(ghost.manifest.id, entryRel);
+ const key = GhostNodeRuntimeBroker.keyOf(GhostNodeRuntimeBroker.instanceId(ghost), entryRel);
const inflight = this.startingWorkers.get(key);
if (inflight) {
const entry = await inflight;
- this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
- this.assertOwnerScopeUsable(ghost.manifest.id, entry.ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), entry.ownerScopeSnapshot);
return entry;
}
const existing = this.workers.get(key);
if (existing) {
- this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
- this.assertOwnerScopeUsable(ghost.manifest.id, existing.ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), existing.ownerScopeSnapshot);
return existing;
}
this.startingWorkerScopes.set(key, ownerScopeSnapshot);
@@ -1718,8 +1723,8 @@ export class GhostNodeRuntimeBroker {
key: string,
ownerScopeSnapshot: unknown,
): Promise<WorkerEntry> {
- this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
- if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) {
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
+ if (this.destroyed || this.stoppedGhosts.has(GhostNodeRuntimeBroker.instanceId(ghost))) {
throw new WorkerStartError('Node 工作进程启动已取消', false, true);
}
this.sendStatus(ghost, 'starting', undefined, entryRel);
@@ -1728,11 +1733,11 @@ 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);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
// 退避期间插件可能被停用/卸载/更新/停止,主机也可能正在退出:
// 现查现用;已停用/已收摊/已停止就不再拉进程,也不补发状态事件。
- if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) throw lastError;
- const fresh = this.deps.getGhost(ghost.manifest.id);
+ if (this.destroyed || this.stoppedGhosts.has(GhostNodeRuntimeBroker.instanceId(ghost))) throw lastError;
+ const fresh = this.deps.getGhost(GhostNodeRuntimeBroker.instanceId(ghost));
if (!fresh?.enabled) throw lastError;
// 跨更新边界时重验入口:新 manifest 可能已不再申报该 entry。
if (!fresh.manifest.node) throw lastError;
@@ -1814,7 +1819,7 @@ export class GhostNodeRuntimeBroker {
ownerScopeSnapshot: unknown,
attemptDiagnostic: StartAttemptDiagnostic,
): Promise<WorkerEntry> {
- this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
const node = ghost.manifest.node;
if (!node) throw new WorkerStartError('ghost.json 缺少 node 工作进程详单', false);
const entryPath = path.resolve(ghost.dir, ...entryRel.split('/'));
@@ -1835,7 +1840,7 @@ export class GhostNodeRuntimeBroker {
{ error: 'utility-process-fork-threw' },
);
}
- this.trackLiveProcess(ghost.manifest.id, child);
+ this.trackLiveProcess(GhostNodeRuntimeBroker.instanceId(ghost), child);
const readChildDiagnosticPid = (): number | undefined => readDiagnosticPid(child);
attemptDiagnostic.pid = readChildDiagnosticPid();
const entry: WorkerEntry = {
@@ -1907,7 +1912,7 @@ export class GhostNodeRuntimeBroker {
// 诊断订阅失败不能改变 ready / retry 语义。
}
this.workers.set(key, entry);
- if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) {
+ if (this.destroyed || this.stoppedGhosts.has(GhostNodeRuntimeBroker.instanceId(ghost))) {
this.workers.delete(key);
try { child.kill('SIGKILL'); } catch { /* already gone */ }
throw new WorkerStartError('Node 工作进程启动已取消', false, true);
@@ -1946,7 +1951,7 @@ export class GhostNodeRuntimeBroker {
// 进程已退出后不再续命——定时器已冻结,由 settleExit 统一结算。
if (
!entry.exitDrain
- && this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)
+ && this.ownerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.ownerScopeSnapshot)
) {
// stderr 是手册钦定的日志口——构建刷日志就是活着的证据,给续命请求重置沉默窗口。
this.renewPendingOnActivity(entry);
@@ -2044,7 +2049,7 @@ export class GhostNodeRuntimeBroker {
throw error;
}
entry.startupPhase = false;
- this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(ghost), ownerScopeSnapshot);
this.sendStatus(ghost, 'running', undefined, entryRel);
this.scheduleIdleStop(entry);
return entry;
@@ -2069,7 +2074,7 @@ export class GhostNodeRuntimeBroker {
},
10_000,
).then(() => {
- this.assertOwnerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.ownerScopeSnapshot);
this.writeLine(entry, {
jsonrpc: '2.0',
method: 'notifications/initialized',
@@ -2095,7 +2100,7 @@ export class GhostNodeRuntimeBroker {
callId?: string,
secretInputCompleted = false,
): Promise<unknown> {
- this.assertOwnerScopeUsable(entry.ghost.manifest.id, ownerScopeSnapshot);
+ this.assertOwnerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), ownerScopeSnapshot);
if (signal?.aborted) return Promise.reject(new NodeRpcError('cancelled', 'The tool call was cancelled'));
this.clearIdleTimer(entry);
const id = String(entry.nextId++);
@@ -2205,9 +2210,9 @@ export class GhostNodeRuntimeBroker {
}
private handleStdout(entry: WorkerEntry, chunk: Buffer | string): void {
- const key = GhostNodeRuntimeBroker.keyOf(entry.ghost.manifest.id, entry.entryRel);
+ const key = GhostNodeRuntimeBroker.keyOf(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.entryRel);
if (this.workers.get(key) !== entry) return;
- if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;
+ if (!this.ownerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.ownerScopeSnapshot)) return;
entry.stdoutBuffer += entry.stdoutDecoder.write(
Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8'),
);
@@ -2236,7 +2241,7 @@ export class GhostNodeRuntimeBroker {
}
private handleRpcMessage(entry: WorkerEntry, message: unknown): void {
- if (!this.ownerScopeUsable(entry.ghost.manifest.id, entry.ownerScopeSnapshot)) return;
+ if (!this.ownerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.ownerScopeSnapshot)) return;
if (!message || typeof message !== 'object' || Array.isArray(message)) {
this.failProtocol(entry, 'Node 返回的 JSON-RPC 消息必须是对象');
return;
@@ -2266,7 +2271,7 @@ export class GhostNodeRuntimeBroker {
entry.pending.delete(String(msg.id));
this.clearTimer(pending.timer);
pending.cleanup();
- if (!this.ownerScopeUsable(entry.ghost.manifest.id, pending.ownerScopeSnapshot)) {
+ if (!this.ownerScopeUsable(GhostNodeRuntimeBroker.instanceId(entry.ghost), pending.ownerScopeSnapshot)) {
pending.reject(new NodeRpcError('exit', 'Plugin owner boundary changed before response'));
return;
}
@@ -2298,7 +2303,7 @@ export class GhostNodeRuntimeBroker {
return;
}
if (typeof msg.method === 'string') {
- this.deps.sendToGhost?.(entry.ghost.manifest.id, {
+ this.deps.sendToGhost?.(GhostNodeRuntimeBroker.instanceId(entry.ghost), {
type: 'event',
name: 'node-notification',
method: msg.method,
@@ -2339,7 +2344,7 @@ export class GhostNodeRuntimeBroker {
// already belongs to the new owner. The runtime-level invalidation callback
// is only safe when no fresh generation exists for the same ghost.
for (const [key, entry] of [...this.workers]) {
- if (entry.ghost.manifest.id !== ghostId) continue;
+ if (GhostNodeRuntimeBroker.instanceId(entry.ghost) !== ghostId) continue;
if (isGhostOwnerScopeUsable(this.deps.ownerScope, entry.ownerScopeSnapshot)) {
hasCurrentWorker = true;
continue;
@@ -2374,7 +2379,7 @@ export class GhostNodeRuntimeBroker {
signal: string | null,
error: Error | null,
): void {
- const ghostId = entry.ghost.manifest.id;
+ const ghostId = GhostNodeRuntimeBroker.instanceId(entry.ghost);
const key = GhostNodeRuntimeBroker.keyOf(ghostId, entry.entryRel);
if (this.workers.get(key) !== entry) {
// stopWorker 已先移除 map。只有真实 exit 才能取消强杀;error 仍可能
@@ -2451,7 +2456,7 @@ export class GhostNodeRuntimeBroker {
entry.stderrSegments.push({ text: tail, at: this.now() });
entry.stderrTotalChars += tail.length;
}
- const ghostId = entry.ghost.manifest.id;
+ const ghostId = GhostNodeRuntimeBroker.instanceId(entry.ghost);
const exitHint = this.exitStderrHint(entry, exitedAt);
const detail = `${this.redactSecrets(entry, error?.message ?? `code=${code}, signal=${signal ?? 'none'}`)}${
exitHint ? `:${exitHint}` : ''
@@ -2537,7 +2542,7 @@ export class GhostNodeRuntimeBroker {
}
private scheduleIdleStop(entry: WorkerEntry): void {
- const key = GhostNodeRuntimeBroker.keyOf(entry.ghost.manifest.id, entry.entryRel);
+ const key = GhostNodeRuntimeBroker.keyOf(GhostNodeRuntimeBroker.instanceId(entry.ghost), entry.entryRel);
if (this.workers.get(key) !== entry) return;
if (entry.ghost.manifest.node?.lifecycle === 'resident' || entry.pending.size > 0) return;
// 有代启子进程在世时不空闲回收——收 worker 会级联杀掉正在干活的代理。
@@ -2578,7 +2583,7 @@ export class GhostNodeRuntimeBroker {
): void {
// entry 字段只在非主入口时携带("缺省 = 主入口"的协议语义;老包零变化)。
const isExtraEntry = entryRel !== undefined && entryRel !== ghost.manifest.node?.entry;
- this.deps.sendToGhost?.(ghost.manifest.id, {
+ this.deps.sendToGhost?.(GhostNodeRuntimeBroker.instanceId(ghost), {
type: 'event',
name: 'node-status',
state,
diff --git a/apps/desktop/src/main/cindy-brain/pickGrantsStore.ts b/apps/desktop/src/main/cindy-brain/pickGrantsStore.ts
index 860c651bb4..2e0bddce0e 100644
--- a/apps/desktop/src/main/cindy-brain/pickGrantsStore.ts
+++ b/apps/desktop/src/main/cindy-brain/pickGrantsStore.ts
@@ -24,9 +24,16 @@ import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { assertGhostPrefsWritable, relocateGhostPreferenceMaps } from './ghostPreferenceRelocation.js';
const log = desktopMakerLogger.child('pick-grants-store');
+export async function relocateGhostPickedDirs(from: string, to: string): Promise<void> {
+ await relocateGhostPreferenceMaps('ghost-pick-grants.json', ['grants'], from, to, () => {
+ store = createStore();
+ });
+}
+
/** 每插件保留的亲选目录条数(超出淘汰最旧;够覆盖"换过几次项目目录")。 */
export const GRANTS_PER_GHOST = 8;
/** 单条路径长度上限(与 errand 配置 workingDir 同口径)。 */
@@ -58,16 +65,22 @@ function normalize(raw: unknown): GhostPickGrants {
return { grants };
}
-const store = createOverrideSettingsFile<GhostPickGrants>({
- filePath: () => ownerScopedUserDataPath('ghost-pick-grants.json'),
- defaults: DEFAULTS,
- normalize,
- log,
- label: 'ghost-pick-grants',
-});
+function createStore() {
+ return createOverrideSettingsFile<GhostPickGrants>({
+ filePath: () => ownerScopedUserDataPath('ghost-pick-grants.json'),
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'ghost-pick-grants',
+ preserveUnreadableFile: true,
+ });
+}
+
+let store = createStore();
/** 记一笔亲选目录(pick 槽成功交付时调用;重选同目录提位到最前)。 */
export function recordGhostPickedDir(ghostId: string, dirAbs: string): void {
+ assertGhostPrefsWritable('ghost-pick-grants.json');
const dir = normalizeWorkingDirForStorage(dirAbs);
if (!dir || dir.length > MAX_DIR_LEN) return;
store.invalidateIfChanged();
diff --git a/apps/desktop/src/main/cindy-brain/pickSlot.ts b/apps/desktop/src/main/cindy-brain/pickSlot.ts
index 363a9ec4c5..06872d848b 100644
--- a/apps/desktop/src/main/cindy-brain/pickSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/pickSlot.ts
@@ -35,6 +35,7 @@ import { sanitizeGhostNoticeText } from './notifySlot.js';
export interface PickSlotDeps {
getGhost(id: string): InstalledGhost | null;
+ getMutationTarget(id: string): string | null;
/**
* 弹系统级选文件夹窗口;返回所选绝对路径,取消返回 null。
* 找不到可挂靠的 Cindy 窗口时应 reject(失败关闭,不弹无主对话框)。
@@ -115,6 +116,8 @@ export class GhostPickSlot {
const purposeRaw =
typeof request.title === 'string' ? sanitizeGhostNoticeText(request.title) : '';
const purpose = purposeRaw ? purposeRaw.slice(0, GHOST_PICK_TITLE_MAX_CHARS) : null;
+ const target = this.deps.getMutationTarget(ghostId);
+ if (target === null) return fail('PERMISSION_DENIED', '插件安装或账户状态已变化');
this.dialogInFlight = true;
let picked: string | null;
@@ -138,6 +141,11 @@ export class GhostPickSlot {
if (picked === null) {
return fail('CANCELLED', '用户取消了选择');
}
+ const current = this.deps.getGhost(ghostId);
+ if (!current?.enabled || current.manifest.pick !== true ||
+ this.deps.getMutationTarget(ghostId) !== target) {
+ return fail('PERMISSION_DENIED', '插件安装或账户状态已变化,请重新选择');
+ }
// 用户已亲手选中:先记台账再分档发结果(票据签发失败也不该丢掉这次
// 授权事实——用户确实选了)。
this.deps.recordPickedDir?.(ghostId, picked);
diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
index 70cf845b6e..9aaf477c68 100644
--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
@@ -27,12 +27,13 @@ import type {
InstalledGhost,
} from '../../shared/ghost.js';
import { GHOST_PIPE_CALL_MAX_TOTAL_MS, isGhostPluginErrorCode } from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
import type { GhostRuntimeState } from './runtime/GhostRuntime.js';
import { isGhostOwnerScopeUsable, type GhostOwnerScope } from './ghostOwnerScope.js';
export interface PipeDispatcherDeps {
/** 按 id 取已装意识(未装 → null)。 */
- getGhost(id: string): InstalledGhost | null;
+ getGhost(id: string, namespace?: string | null): InstalledGhost | null;
/** 当前运行时状态。 */
runtimeStateOf(id: string): GhostRuntimeState;
/** 拉起沙箱(幂等;fused/stopping 拒绝)。 */
@@ -172,6 +173,7 @@ export class GhostPipeDispatcher {
private async dispatchCall(request: {
ghostId: string;
+ namespace?: string | null;
tool: string;
args: Record<string, unknown>;
/**
@@ -186,10 +188,10 @@ export class GhostPipeDispatcher {
/** Trusted Host session attribution, never accepted from plugin input. */
sessionId?: string;
}): Promise<GhostToolCallResult> {
- const { ghostId, tool, args } = request;
+ const { ghostId, namespace, tool, args } = request;
// ── 资格审 ─────────────────────────────────────────────────────────
- const ghost = this.deps.getGhost(ghostId);
+ const ghost = this.deps.getGhost(ghostId, namespace);
if (!ghost) {
return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: `插件 ${ghostId} 未安装或已卸载` };
}
@@ -200,7 +202,8 @@ export class GhostPipeDispatcher {
if (!declared) {
return { ok: false, errorCode: 'TOOL_NOT_FOUND', message: toolNotFoundMessage(ghostId, tool, ghost.manifest.tools) };
}
- if (this.deps.runtimeStateOf(ghostId) === 'fused') {
+ const storagePart = installedGhostStoragePart(ghost);
+ if (this.deps.runtimeStateOf(storagePart) === 'fused') {
return { ok: false, errorCode: 'GHOST_CRASHED', message: `插件 ${ghostId} 已熔断(反复崩溃),重载或重新启用后再试` };
}
let ownerScopeSnapshot: unknown;
@@ -211,13 +214,13 @@ export class GhostPipeDispatcher {
}
// ── 按需拉起 ────────────────────────────────────────────────────────
- if (this.deps.runtimeStateOf(ghostId) !== 'running') {
+ if (this.deps.runtimeStateOf(storagePart) !== 'running') {
const spawned = await this.deps.spawn(ghost);
if (!spawned.ok) {
return { ok: false, errorCode: 'GHOST_CRASHED', message: `插件启动失败:${spawned.reason}` };
}
}
- if (!this.ownerScopeUsable(ghostId, ownerScopeSnapshot)) {
+ if (!this.ownerScopeUsable(storagePart, ownerScopeSnapshot)) {
return this.ownerBoundaryResult();
}
@@ -230,7 +233,7 @@ export class GhostPipeDispatcher {
const baseTimeoutMs = this.baseTimeoutMs(request.timeoutMs);
const entry: PendingCall = {
sessionId: request.sessionId,
- ghostId,
+ ghostId: storagePart,
tool,
ownerScopeSnapshot,
claimedBindings: new Map(),
@@ -247,11 +250,11 @@ export class GhostPipeDispatcher {
this.pending.set(callId, entry);
this.armTimer(callId, entry);
- if (!this.ownerScopeUsable(ghostId, ownerScopeSnapshot)) {
+ if (!this.ownerScopeUsable(storagePart, ownerScopeSnapshot)) {
this.settle(callId, this.ownerBoundaryResult());
return;
}
- if (!this.deps.sendToGhost(ghostId, payload)) {
+ if (!this.deps.sendToGhost(storagePart, payload)) {
// 逻辑页不在线(拉起后瞬时死亡等):立即收卷。
this.settle(callId, { ok: false, errorCode: 'GHOST_CRASHED', message: '电子脑离线,派发失败' });
}
diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts
new file mode 100644
index 0000000000..0954397d62
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts
@@ -0,0 +1,139 @@
+/**
+ * Positive evidence that may move an unconfirmed instance back to confirmed.
+ * Receipt rewrites are not evidence. Callers pass market rows they already trust.
+ */
+import { hasDeliveryNamespace } from '../../shared/pluginIdentity.js';
+import type { GhostInstallReceipt, GhostInstallReceiptReadResult } from './ghostInstallReceipt.js';
+import {
+ namespaceCommitReceiptSnapshot,
+ sameNamespaceCommitReceiptSnapshot,
+} from './pluginNamespaceMigration.js';
+import {
+ confirmInstanceNamespace,
+ confirmUnconfirmedInstance,
+ marketRowMatchesUnconfirmedInstance,
+ type InstanceConfirmationEvidence,
+ type InstanceConfirmationMarketRecord,
+ type PluginInstanceRecord,
+ type PluginInstanceRegistry,
+} from './pluginInstanceRegistry.js';
+
+interface ConfirmationMarketRow {
+ installed?: boolean;
+ namespace?: string | null;
+ scope?: 'public' | 'personal' | 'organization';
+ organizationId?: string | null;
+ sha256?: string | null;
+}
+
+function confirmationMarketRecords(input: {
+ rows: readonly ConfirmationMarketRow[];
+ record: PluginInstanceRecord;
+ currentOrganization: { organizationId: string; orgSlug: string | null } | null;
+}): InstanceConfirmationMarketRecord[] {
+ return input.rows
+ .filter((row) => row.installed !== false)
+ .filter((row) => marketRowMatchesUnconfirmedInstance(row, input.record, input.currentOrganization))
+ .map((row) => ({
+ ...(hasDeliveryNamespace(row) ? { namespace: row.namespace ?? null } : {}),
+ organizationId: row.organizationId,
+ packageSha256: row.sha256,
+ scope: row.scope,
+ installed: row.installed,
+ }));
+}
+
+export function buildUnconfirmedConfirmationEvidence(input: {
+ rows: readonly ConfirmationMarketRow[] | undefined;
+ record: PluginInstanceRecord;
+ currentOrganization: { organizationId: string; orgSlug: string | null } | null;
+ packageSha256: string | null;
+ forgeSelfTest: boolean;
+}): InstanceConfirmationEvidence {
+ return {
+ marketRecords: input.rows === undefined
+ ? undefined
+ : confirmationMarketRecords({
+ rows: input.rows,
+ record: input.record,
+ currentOrganization: input.currentOrganization,
+ }),
+ currentOrganization: input.currentOrganization,
+ packageSha256: input.packageSha256,
+ forgeSelfTest: input.forgeSelfTest,
+ };
+}
+
+interface UnconfirmedConfirmationHost {
+ readEvidence?(record: PluginInstanceRecord): InstanceConfirmationEvidence | null | undefined;
+ isBlocked(): boolean;
+ sync(): PluginInstanceRegistry;
+ ownerContextKey(): string;
+ readApproval(relId: string): GhostInstallReceiptReadResult;
+ log?: { warn(message: string, meta?: Record<string, unknown>): void };
+ runExclusive<T>(body: () => Promise<T>): Promise<T>;
+ contentPath(relId: string): string;
+ writeReceipt(relId: string, receipt: GhostInstallReceipt): Promise<void>;
+ writeRegistry(registry: PluginInstanceRegistry): void;
+}
+
+/** Confirm unconfirmed rows only when the caller supplies positive evidence. */
+export async function confirmUnconfirmedInstances(host: UnconfirmedConfirmationHost): Promise<void> {
+ const readEvidence = host.readEvidence;
+ if (!readEvidence || host.isBlocked()) return;
+ const registry = host.sync();
+ if (host.isBlocked()) return;
+ const ownerContextKey = host.ownerContextKey();
+ for (const record of Object.values(registry.instances)) {
+ if (host.ownerContextKey() !== ownerContextKey) return;
+ if (!record.active || record.namespaceState !== 'unconfirmed') continue;
+ const evidenceSnapshot = namespaceCommitReceiptSnapshot(host.readApproval(record.contentRelId));
+ let evidence: InstanceConfirmationEvidence | null | undefined;
+ try {
+ evidence = readEvidence(record);
+ } catch (error) {
+ host.log?.warn('unconfirmed instance evidence unavailable', {
+ instanceKey: record.instanceKey,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ continue;
+ }
+ if (!evidence) continue;
+ const decision = confirmUnconfirmedInstance(record, evidence);
+ if (!decision) continue;
+ try {
+ await host.runExclusive(async () => {
+ if (host.ownerContextKey() !== ownerContextKey) return;
+ const approval = host.readApproval(record.contentRelId);
+ if (!sameNamespaceCommitReceiptSnapshot(
+ evidenceSnapshot, namespaceCommitReceiptSnapshot(approval),
+ )) return;
+ if (approval.state !== 'approved' || approval.receipt.id !== record.ghostId) return;
+ let revision = approval.receipt.revision;
+ let packageSha256 = approval.receipt.packageSha256 ?? record.packageSha256;
+ const stamped = hasDeliveryNamespace(approval.receipt) &&
+ (approval.receipt.namespace ?? null) === decision.namespace;
+ if (!stamped) {
+ await host.writeReceipt(record.contentRelId, { ...approval.receipt, namespace: decision.namespace });
+ const written = host.readApproval(record.contentRelId);
+ if (written.state !== 'approved' || !hasDeliveryNamespace(written.receipt) ||
+ (written.receipt.namespace ?? null) !== decision.namespace) return;
+ revision = written.receipt.revision;
+ packageSha256 = written.receipt.packageSha256 ?? packageSha256;
+ }
+ const current = host.sync();
+ if (host.isBlocked()) return;
+ const confirmed = confirmInstanceNamespace(current, record.instanceKey, decision.namespace, {
+ revision, packageSha256,
+ });
+ if (confirmed === current) return;
+ host.writeRegistry(confirmed);
+ });
+ } catch (error) {
+ host.log?.warn('unconfirmed instance confirmation skipped', {
+ instanceKey: record.instanceKey,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
new file mode 100644
index 0000000000..f523a4caaf
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
@@ -0,0 +1,608 @@
+/**
+ * Per-data-owner plugin instance registry.
+ *
+ * instanceKey is the directory storage key (helper, _root__helper,
+ * _ns__xd__helper). It is not allocated. Logical namespace still lives
+ * here, because an old client can rewrite a receipt.
+ *
+ * Storage (KV, secrets, OAuth, library, partitions, skills) must use
+ * instanceKey. Do not derive a new key from a path or namespace.
+ */
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ pluginInstallStoragePart,
+ parsePluginInstallRelId,
+ hasDeliveryNamespace,
+} from '../../shared/pluginIdentity.js';
+import { isValidGhostId } from '../../shared/ghost.js';
+
+const PLUGIN_INSTANCE_REGISTRY_V1_VERSION = 1 as const;
+const PLUGIN_INSTANCE_REGISTRY_VERSION = 2 as const;
+/** Live registry. v1 is read once and left on disk. */
+const PLUGIN_INSTANCE_REGISTRY_FILE = 'plugin-instances.v2.json';
+const PLUGIN_INSTANCE_REGISTRY_V1_FILE = 'plugin-instances.v1.json';
+
+type PluginInstanceNamespaceState = 'confirmed' | 'unconfirmed' | 'pending';
+export type PluginInstanceSource = 'legacy' | 'market' | 'manual' | 'agent-forge' | 'builtin';
+
+export interface PluginInstanceRecord {
+ instanceKey: string;
+ /** Content directory relative to the plugin root. Not an identity. */
+ contentRelId: string;
+ ghostId: string;
+ /** Last known namespace. Privileges require namespaceState === 'confirmed'. */
+ namespace: string | null;
+ namespaceState: PluginInstanceNamespaceState;
+ pluginId: string | null;
+ source: PluginInstanceSource;
+ receiptRevision: string | null;
+ packageSha256: string | null;
+ active: boolean;
+}
+
+export interface PluginInstanceCensus {
+ completedAt: string;
+ /** Bare directories captured once. Commit and uninstall remove ids. */
+ pendingRelIds: string[];
+}
+
+export interface PluginInstanceRegistry {
+ schemaVersion: typeof PLUGIN_INSTANCE_REGISTRY_VERSION;
+ /** Null until the one-time upgrade census for this data owner has been stored. */
+ census: PluginInstanceCensus | null;
+ instances: Record<string, PluginInstanceRecord>;
+}
+
+type PluginInstanceRegistryRead =
+ | { kind: 'missing' }
+ | { kind: 'ok'; registry: PluginInstanceRegistry }
+ | { kind: 'corrupt' }
+ | { kind: 'unreadable' }
+ | { kind: 'unknown-schema' };
+
+export interface InstanceConfirmationMarketRecord {
+ /** Undefined means the row has no namespace field, which is not a match. */
+ namespace?: string | null;
+ organizationId?: string | null;
+ packageSha256?: string | null;
+ scope?: 'public' | 'personal' | 'organization';
+ installed?: boolean;
+}
+
+export interface InstanceConfirmationEvidence {
+ /**
+ * Undefined: market facts are not ready, so they cannot confirm or deny.
+ * Empty: no installed market row.
+ */
+ marketRecords?: readonly InstanceConfirmationMarketRecord[];
+ currentOrganization?: {
+ organizationId: string;
+ orgSlug: string | null;
+ } | null;
+ packageSha256?: string | null;
+ /** Approved receipt is an agent-forge self-test for this install. */
+ forgeSelfTest?: boolean;
+}
+
+export interface PluginInstanceReceiptFact {
+ ghostId: string;
+ hasNamespace: boolean;
+ namespace: string | null;
+ revision: string;
+ packageSha256: string | null;
+ installOrigin?: string;
+}
+
+export function emptyPluginInstanceRegistry(): PluginInstanceRegistry {
+ return { schemaVersion: PLUGIN_INSTANCE_REGISTRY_VERSION, census: null, instances: {} };
+}
+
+export function pluginInstanceRegistryPath(stateRoot: string): string {
+ return path.join(stateRoot, PLUGIN_INSTANCE_REGISTRY_FILE);
+}
+
+export function allocateArchiveInstanceKey(): string {
+ return 'arch_' + crypto.randomUUID().replace(/-/g, '');
+}
+
+/** Storage key already used by an on-disk install that has no registry row yet. */
+function instanceKeyForExistingContent(relId: string): string | null {
+ if (!parsePluginInstallRelId(relId)) return null;
+ return pluginInstallStoragePart(relId);
+}
+
+export function adoptContentInstall(input: {
+ relId: string;
+ ghostId: string;
+ receipt: PluginInstanceReceiptFact | null;
+ /** True only while the one-time upgrade census still lists this directory. */
+ pendingMigration?: boolean;
+ /** Set when the market ledger has exactly one installed record for this ghost. */
+ marketPluginId?: string | null;
+}): PluginInstanceRecord | null {
+ const instanceKey = instanceKeyForExistingContent(input.relId);
+ if (!instanceKey || !isValidGhostId(input.ghostId)) return null;
+ const origin = input.receipt?.installOrigin;
+ const identity = parsePluginInstallRelId(input.relId);
+ const pathNamespace = identity?.namespace ?? null;
+ const confirmed = input.receipt?.hasNamespace === true;
+ const pending = !confirmed && input.pendingMigration === true;
+ const marketPluginId = origin === 'agent-forge' ? null : input.marketPluginId ?? null;
+ return {
+ instanceKey,
+ contentRelId: input.relId,
+ ghostId: input.ghostId,
+ namespace: confirmed ? input.receipt!.namespace : pathNamespace,
+ namespaceState: confirmed ? 'confirmed' : pending ? 'pending' : 'unconfirmed',
+ pluginId: marketPluginId,
+ source: origin === 'agent-forge'
+ ? 'agent-forge'
+ : marketPluginId ? 'market' : input.receipt ? 'manual' : 'legacy',
+ receiptRevision: input.receipt?.revision ?? null,
+ packageSha256: input.receipt?.packageSha256 ?? null,
+ active: true,
+ };
+}
+
+
+/**
+ * The market row that belongs to this directory, or null when zero or several do.
+ * A missing namespace is not root: it only matches the legacy bare directory.
+ * An explicit namespace must match, and scope/organization must agree with it.
+ */
+export function selectMarketPluginIdForInstance(
+ instance: {
+ ghostId: string;
+ contentRelId: string;
+ namespace: string | null;
+ packageSha256: string | null;
+ },
+ records: readonly {
+ pluginId?: string | null;
+ ghostId?: string;
+ installed?: boolean;
+ namespace?: string | null;
+ scope?: string | null;
+ organizationId?: string | null;
+ sha256?: string | null;
+ }[],
+): string | null {
+ const matches = records.filter((record) => {
+ if (record.installed !== true || !record.pluginId || record.ghostId !== instance.ghostId) return false;
+ if (record.sha256 && instance.packageSha256 && record.sha256 !== instance.packageSha256) return false;
+ if (!hasDeliveryNamespace(record)) return instance.contentRelId === instance.ghostId;
+ if (record.namespace !== instance.namespace) return false;
+ if (record.namespace === null) return record.scope !== 'organization' && !record.organizationId;
+ return record.scope === undefined || record.scope === 'organization';
+ });
+ return matches.length === 1 ? matches[0]!.pluginId! : null;
+}
+
+/**
+ * Receipt rewrite never allocates a new instance.
+ * Losing the namespace field, or disagreeing with the registry, only
+ * drops confirmation. Positive confirmation is a separate call.
+ */
+export function reconcileInstanceReceipt(
+ record: PluginInstanceRecord,
+ input: { directoryPresent: boolean; receipt: PluginInstanceReceiptFact | null },
+): PluginInstanceRecord {
+ if (!input.directoryPresent) return record.active ? { ...record, active: false } : record;
+ const next: PluginInstanceRecord = record.active ? record : { ...record, active: true };
+ const receipt = input.receipt;
+ if (!receipt) return next;
+ if (receipt.ghostId !== record.ghostId) {
+ return next.namespaceState === 'unconfirmed' ? next : { ...next, namespaceState: 'unconfirmed' };
+ }
+ const sameRevision = record.receiptRevision === null || receipt.revision === record.receiptRevision;
+ const samePackage = record.packageSha256 === null || receipt.packageSha256 === record.packageSha256;
+ if (!receipt.hasNamespace) {
+ if (record.namespaceState === 'confirmed') {
+ return {
+ ...next,
+ namespaceState: 'unconfirmed',
+ receiptRevision: receipt.revision,
+ packageSha256: receipt.packageSha256,
+ };
+ }
+ if (!sameRevision || !samePackage) {
+ return { ...next, receiptRevision: receipt.revision, packageSha256: receipt.packageSha256 };
+ }
+ return next;
+ }
+ if (record.namespaceState === 'confirmed' && receipt.namespace !== record.namespace) {
+ return {
+ ...next,
+ namespaceState: 'unconfirmed',
+ receiptRevision: receipt.revision,
+ packageSha256: receipt.packageSha256,
+ };
+ }
+ if (record.namespaceState === 'unconfirmed') {
+ // A rewritten receipt is not positive evidence. Confirmation is separate.
+ if (receipt.revision !== record.receiptRevision || receipt.packageSha256 !== record.packageSha256) {
+ return { ...next, receiptRevision: receipt.revision, packageSha256: receipt.packageSha256 };
+ }
+ return next;
+ }
+ if (receipt.revision !== record.receiptRevision || receipt.packageSha256 !== record.packageSha256) {
+ return { ...next, receiptRevision: receipt.revision, packageSha256: receipt.packageSha256 };
+ }
+ return next;
+}
+
+function shaDoesNotConflict(
+ left: string | null | undefined,
+ right: string | null | undefined,
+): boolean {
+ if (!left || !right) return true;
+ return left === right;
+}
+
+function forgeEvidenceConfirms(
+ record: PluginInstanceRecord,
+ evidence: InstanceConfirmationEvidence,
+): boolean {
+ if (evidence.forgeSelfTest !== true || !record.namespace) return false;
+ if (evidence.currentOrganization?.orgSlug !== record.namespace) return false;
+ return shaDoesNotConflict(evidence.packageSha256, record.packageSha256);
+}
+
+function marketEvidenceConfirms(
+ record: PluginInstanceRecord,
+ evidence: InstanceConfirmationEvidence,
+): boolean {
+ if (evidence.marketRecords === undefined) return false;
+ const installed = evidence.marketRecords.filter((row) => row.installed !== false);
+ if (installed.length !== 1) return false;
+ const market = installed[0]!;
+ if (market.namespace === undefined || market.namespace !== record.namespace) return false;
+ const observed = evidence.packageSha256 ?? record.packageSha256 ?? null;
+ if (!market.packageSha256 || !observed || market.packageSha256 !== observed) return false;
+ if (!shaDoesNotConflict(evidence.packageSha256, record.packageSha256)) return false;
+ if (!shaDoesNotConflict(evidence.packageSha256, market.packageSha256)) return false;
+ if (!shaDoesNotConflict(record.packageSha256, market.packageSha256)) return false;
+ if (record.namespace !== null) {
+ const org = evidence.currentOrganization;
+ if (!org || org.orgSlug !== record.namespace) return false;
+ if (!market.organizationId || market.organizationId !== org.organizationId) return false;
+ if (market.scope !== undefined && market.scope !== 'organization') return false;
+ return true;
+ }
+ if (market.organizationId) return false;
+ if (market.scope === 'organization') return false;
+ return true;
+}
+
+/**
+ * Move unconfirmed back to confirmed only with positive evidence.
+ * The namespace must already be the one stored on the record. This does not
+ * invent an organization from a prefix, a path, or a rewritten receipt.
+ */
+
+export function marketRowMatchesUnconfirmedInstance(
+ row: {
+ installed?: boolean;
+ namespace?: string | null;
+ scope?: 'public' | 'personal' | 'organization';
+ organizationId?: string | null;
+ },
+ record: PluginInstanceRecord,
+ currentOrganization: { organizationId: string; orgSlug: string | null } | null,
+): boolean {
+ const hasNamespace = hasDeliveryNamespace(row);
+ if (hasNamespace) return (row.namespace ?? null) === record.namespace;
+ if (record.namespace === null) return row.scope !== 'organization';
+ return row.scope === 'organization' &&
+ currentOrganization !== null &&
+ row.organizationId === currentOrganization.organizationId &&
+ currentOrganization.orgSlug === record.namespace;
+}
+
+export function confirmUnconfirmedInstance(
+ record: PluginInstanceRecord,
+ evidence: InstanceConfirmationEvidence,
+): { namespace: string | null } | null {
+ if (!record.active || record.namespaceState !== 'unconfirmed') return null;
+ if (forgeEvidenceConfirms(record, evidence) || marketEvidenceConfirms(record, evidence)) {
+ return { namespace: record.namespace };
+ }
+ return null;
+}
+
+export function confirmInstanceNamespace(
+ registry: PluginInstanceRegistry,
+ instanceKey: string,
+ namespace: string | null,
+ receipt: { revision: string; packageSha256: string | null },
+): PluginInstanceRegistry {
+ const record = registry.instances[instanceKey];
+ if (!record) return registry;
+ const conflict = Object.values(registry.instances).some((other) =>
+ other.instanceKey !== instanceKey &&
+ other.active &&
+ other.namespaceState === 'confirmed' &&
+ other.ghostId === record.ghostId &&
+ other.namespace === namespace);
+ if (conflict) return registry;
+ const next: PluginInstanceRecord = {
+ ...record,
+ namespace,
+ namespaceState: 'confirmed',
+ receiptRevision: receipt.revision,
+ packageSha256: receipt.packageSha256,
+ active: true,
+ };
+ return { ...registry, instances: { ...registry.instances, [instanceKey]: next } };
+}
+
+export function upsertInstance(
+ registry: PluginInstanceRegistry,
+ record: PluginInstanceRecord,
+): PluginInstanceRegistry {
+ return { ...registry, instances: { ...registry.instances, [record.instanceKey]: record } };
+}
+
+export function findInstanceByContentRelId(
+ registry: PluginInstanceRegistry,
+ relId: string,
+): PluginInstanceRecord | undefined {
+ return Object.values(registry.instances).find((record) => record.contentRelId === relId);
+}
+
+/** Active install that must not be replaced by another copy of the same identity. */
+export function findBlockingInstance(
+ registry: PluginInstanceRegistry,
+ ghostId: string,
+ namespace: string | null,
+): PluginInstanceRecord | null {
+ return Object.values(registry.instances).find((record) => {
+ if (!record.active || record.ghostId !== ghostId) return false;
+ if (record.namespaceState === 'confirmed' && record.namespace === namespace) return true;
+ return record.namespaceState === 'pending' && record.contentRelId === record.ghostId;
+ }) ?? null;
+}
+
+export function findReusableInstance(
+ registry: PluginInstanceRegistry,
+ query: { ghostId: string; namespace: string | null; pluginId?: string | null; source?: PluginInstanceSource },
+): PluginInstanceRecord | null {
+ const matches = Object.values(registry.instances).filter((record) => {
+ if (record.active || record.ghostId !== query.ghostId) return false;
+ if (record.namespaceState === 'pending') {
+ return query.namespace === null && record.namespace === null && record.contentRelId === record.ghostId;
+ }
+ return record.namespace === query.namespace;
+ });
+ const sameSource = (record: PluginInstanceRecord): boolean => {
+ if (!query.source) return true;
+ if (record.source === query.source) return true;
+ // A pre-receipt directory is not a different product source.
+ return query.source === 'manual' && record.source === 'legacy';
+ };
+ if (query.pluginId) {
+ const exact = matches.find((record) => record.pluginId === query.pluginId && sameSource(record));
+ if (exact) return exact;
+ // An upgraded install has no market id yet. Reuse it only when it is the
+ // single unlabeled candidate, so two markets do not take each other's data
+ // and one upgraded market install can be reattached.
+ const unlabeled = matches.filter((record) =>
+ record.pluginId == null && (record.source === 'legacy' || record.source === 'manual'));
+ return unlabeled.length === 1 ? unlabeled[0]! : null;
+ }
+ if (query.source) {
+ const sourced = matches.filter(sameSource);
+ return sourced.length === 1 ? sourced[0]! : null;
+ }
+ return matches.length === 1 ? matches[0]! : null;
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function parseRecord(value: unknown, instanceKey: string): PluginInstanceRecord | null {
+ if (!isPlainObject(value)) return null;
+ if (value.instanceKey !== instanceKey || typeof value.instanceKey !== 'string') return null;
+ if (typeof value.contentRelId !== 'string' || value.contentRelId.length === 0) return null;
+ if (!isValidGhostId(value.ghostId)) return null;
+ if (value.namespace !== null && typeof value.namespace !== 'string') return null;
+ if (value.namespaceState !== 'confirmed' && value.namespaceState !== 'unconfirmed' && value.namespaceState !== 'pending') return null;
+ if (value.pluginId !== null && typeof value.pluginId !== 'string') return null;
+ if (value.source !== 'legacy' && value.source !== 'market' && value.source !== 'manual' &&
+ value.source !== 'agent-forge' && value.source !== 'builtin') return null;
+ if (value.receiptRevision !== null && typeof value.receiptRevision !== 'string') return null;
+ if (value.packageSha256 !== null && typeof value.packageSha256 !== 'string') return null;
+ if (typeof value.active !== 'boolean') return null;
+ return {
+ instanceKey,
+ contentRelId: value.contentRelId,
+ ghostId: value.ghostId,
+ namespace: value.namespace,
+ namespaceState: value.namespaceState,
+ pluginId: value.pluginId,
+ source: value.source,
+ receiptRevision: value.receiptRevision,
+ packageSha256: value.packageSha256,
+ active: value.active,
+ };
+}
+
+
+export function finishInstanceCensus(
+ registry: PluginInstanceRegistry,
+ completedAt: string,
+ pendingRelIds: readonly string[],
+): PluginInstanceRegistry {
+ return { ...registry, census: { completedAt, pendingRelIds: [...new Set(pendingRelIds)] } };
+}
+
+export function clearCensusPending(
+ registry: PluginInstanceRegistry,
+ relId: string,
+): PluginInstanceRegistry {
+ if (!registry.census || !registry.census.pendingRelIds.includes(relId)) return registry;
+ return {
+ ...registry,
+ census: {
+ ...registry.census,
+ pendingRelIds: registry.census.pendingRelIds.filter((id) => id !== relId),
+ },
+ };
+}
+
+/** Uninstall drops pending. A later root reinstall may reuse the inactive key. */
+export function releaseInstalledInstance(
+ registry: PluginInstanceRegistry,
+ relOrKey: string,
+): PluginInstanceRegistry {
+ const record = registry.instances[relOrKey] ?? findInstanceByContentRelId(registry, relOrKey);
+ const cleared = clearCensusPending(registry, record?.contentRelId ?? relOrKey);
+ if (!record) return cleared;
+ const namespaceState = record.namespaceState === 'pending' ? 'unconfirmed' : record.namespaceState;
+ if (!record.active && namespaceState === record.namespaceState && cleared === registry) return registry;
+ const base = cleared === registry ? registry : cleared;
+ return upsertInstance(base, { ...record, active: false, namespaceState });
+}
+
+function isIsoTimestamp(value: unknown): value is string {
+ return typeof value === 'string' && Number.isFinite(Date.parse(value));
+}
+
+function parseCensus(value: unknown): PluginInstanceCensus | null | undefined {
+ if (value === null) return null;
+ if (!isPlainObject(value) || !isIsoTimestamp(value.completedAt) || !Array.isArray(value.pendingRelIds)) {
+ return undefined;
+ }
+ const pendingRelIds: string[] = [];
+ for (const relId of value.pendingRelIds) {
+ if (typeof relId !== 'string' || !isValidGhostId(relId)) return undefined;
+ pendingRelIds.push(relId);
+ }
+ return { completedAt: value.completedAt, pendingRelIds };
+}
+
+function parseInstances(
+ raw: Record<string, unknown>,
+ census: PluginInstanceCensus | null,
+): PluginInstanceRegistryParse {
+ if (!isPlainObject(raw.instances)) return { kind: 'corrupt' };
+ const instances: Record<string, PluginInstanceRecord> = {};
+ for (const [key, value] of Object.entries(raw.instances)) {
+ const record = parseRecord(value, key);
+ if (!record) return { kind: 'corrupt' };
+ instances[key] = record;
+ }
+ return {
+ kind: 'ok',
+ registry: { schemaVersion: PLUGIN_INSTANCE_REGISTRY_VERSION, census, instances },
+ };
+}
+
+type PluginInstanceRegistryParse =
+ | { kind: 'ok'; registry: PluginInstanceRegistry }
+ | { kind: 'corrupt' }
+ | { kind: 'unknown-schema' };
+
+export function parsePluginInstanceRegistryDocument(raw: unknown): PluginInstanceRegistryParse {
+ if (!isPlainObject(raw)) return { kind: 'corrupt' };
+ if (!Number.isInteger(raw.schemaVersion)) return { kind: 'corrupt' };
+ if (raw.schemaVersion === PLUGIN_INSTANCE_REGISTRY_V1_VERSION) return parseInstances(raw, null);
+ if (raw.schemaVersion !== PLUGIN_INSTANCE_REGISTRY_VERSION) return { kind: 'unknown-schema' };
+ if (!Object.prototype.hasOwnProperty.call(raw, 'census')) return { kind: 'corrupt' };
+ const census = parseCensus(raw.census);
+ if (census === undefined) return { kind: 'corrupt' };
+ return parseInstances(raw, census);
+}
+
+function parsePluginInstanceRegistry(raw: unknown): PluginInstanceRegistry | null {
+ const parsed = parsePluginInstanceRegistryDocument(raw);
+ return parsed.kind === 'ok' ? parsed.registry : null;
+}
+
+export interface PluginInstanceRegistryStore {
+ read(): PluginInstanceRegistryRead;
+ write(registry: PluginInstanceRegistry): void;
+ /** Move a corrupt file aside so a later write can rebuild directory keys. */
+ discardCorrupt(): boolean;
+}
+
+function readPluginInstanceRegistryFile(filePath: string): PluginInstanceRegistryRead {
+ let text: string;
+ try {
+ text = fs.readFileSync(filePath, 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };
+ return { kind: 'unreadable' };
+ }
+ try {
+ const parsed = parsePluginInstanceRegistryDocument(JSON.parse(text));
+ if (parsed.kind === 'unknown-schema') return { kind: 'unknown-schema' };
+ if (parsed.kind !== 'ok') return { kind: 'corrupt' };
+ return { kind: 'ok', registry: parsed.registry };
+ } catch {
+ return { kind: 'corrupt' };
+ }
+}
+
+export function createPluginInstanceRegistryStore(filePath: string): PluginInstanceRegistryStore {
+ let corruptPath: string | null = null;
+ const read = (): PluginInstanceRegistryRead => {
+ const primary = readPluginInstanceRegistryFile(filePath);
+ if (primary.kind !== 'missing') {
+ corruptPath = primary.kind === 'corrupt' ? filePath : null;
+ return primary;
+ }
+ if (path.basename(filePath) !== PLUGIN_INSTANCE_REGISTRY_FILE) {
+ corruptPath = null;
+ return { kind: 'missing' };
+ }
+ const legacyPath = path.join(path.dirname(filePath), PLUGIN_INSTANCE_REGISTRY_V1_FILE);
+ const legacy = readPluginInstanceRegistryFile(legacyPath);
+ corruptPath = legacy.kind === 'corrupt' ? legacyPath : null;
+ return legacy;
+ };
+ return {
+ read,
+ discardCorrupt(): boolean {
+ if (read().kind !== 'corrupt' || !corruptPath) return false;
+ fs.renameSync(corruptPath, corruptPath + '.corrupt-' + crypto.randomUUID());
+ return true;
+ },
+ write(registry) {
+ const current = read();
+ if (current.kind === 'unreadable' || current.kind === 'corrupt' || current.kind === 'unknown-schema') {
+ throw new Error('plugin instance registry is ' + current.kind);
+ }
+ const document: PluginInstanceRegistry = {
+ ...registry,
+ schemaVersion: PLUGIN_INSTANCE_REGISTRY_VERSION,
+ };
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ const tempPath = filePath + '.' + crypto.randomUUID() + '.tmp';
+ try {
+ fs.writeFileSync(tempPath, JSON.stringify(document, null, 2) + "\n", 'utf8');
+ const descriptor = fs.openSync(tempPath, 'r+');
+ try {
+ fs.fsyncSync(descriptor);
+ } finally {
+ fs.closeSync(descriptor);
+ }
+ fs.renameSync(tempPath, filePath);
+ const directory = process.platform === 'win32'
+ ? fs.openSync(filePath, 'r+') : fs.openSync(path.dirname(filePath), 'r');
+ try {
+ fs.fsyncSync(directory);
+ } finally {
+ fs.closeSync(directory);
+ }
+ } catch (error) {
+ try { fs.unlinkSync(tempPath); } catch { /* temp may already be gone */ }
+ throw error;
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts
new file mode 100644
index 0000000000..08126d1826
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts
@@ -0,0 +1,376 @@
+/**
+ * Instance registry load, owner cache, directory sync, and the one-time census.
+ * Pending privileges follow namespaceState. pendingRelIds is only the adoption
+ * allowlist captured by that census.
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { isValidGhostId } from '../../shared/ghost.js';
+import { parsePluginInstallRelId, PLUGIN_NS_INSTALL_ROOT } from '../../shared/pluginIdentity.js';
+import { classifyGhostDirEntrySync } from './ghostContentTree.js';
+import {
+ type NamespaceCensusCandidate,
+ stampInstanceCensus,
+ type CensusApproval,
+} from './pluginNamespaceMigration.js';
+import {
+ adoptContentInstall,
+ clearCensusPending,
+ confirmInstanceNamespace,
+ emptyPluginInstanceRegistry,
+ findInstanceByContentRelId,
+ reconcileInstanceReceipt,
+ releaseInstalledInstance,
+ upsertInstance,
+ type PluginInstanceCensus,
+ type PluginInstanceReceiptFact,
+ type PluginInstanceRecord,
+ type PluginInstanceRegistry,
+ type PluginInstanceRegistryStore,
+} from './pluginInstanceRegistry.js';
+
+interface PluginInstanceRegistryLogger {
+ warn(message: string, meta?: Record<string, unknown>): void;
+}
+
+interface PluginInstanceRegistryServiceDeps {
+ ensureOwner(): void;
+ registryStore(): PluginInstanceRegistryStore;
+ listContentEntries(): Array<{ relId: string; dir: string }>;
+ receiptFact(relId: string): PluginInstanceReceiptFact | null | undefined;
+ censusCandidates(): NamespaceCensusCandidate[];
+ readApproval(relId: string): CensusApproval;
+ captureInstalledLegacy?(ghostId: string, packageSha256: string): boolean;
+ recordLegacyEligibility(relId: string, revision: string): void;
+ /** Market plugin id for this directory, or null when the ledger cannot say. */
+ marketIdentityForInstance?(instance: {
+ ghostId: string;
+ contentRelId: string;
+ namespace: string | null;
+ packageSha256: string | null;
+ }): { pluginId: string } | null;
+ log?: PluginInstanceRegistryLogger;
+}
+
+/**
+ * Active pending rows must be on the census allowlist. Strict mode also
+ * reports an allowlist id whose active row is no longer pending.
+ */
+export function pendingCensusMismatches(
+ registry: PluginInstanceRegistry,
+ mode: 'privileges' | 'strict' = 'privileges',
+): string[] {
+ if (!registry.census) return [];
+ const listed = new Set(registry.census.pendingRelIds);
+ const mismatches: string[] = [];
+ for (const record of Object.values(registry.instances)) {
+ if (!record.active) continue;
+ const isListed = listed.has(record.contentRelId);
+ if (record.namespaceState === 'pending' && !isListed) {
+ mismatches.push(record.contentRelId + ':pending-but-not-listed');
+ } else if (mode === 'strict' && isListed && record.namespaceState !== 'pending') {
+ mismatches.push(record.contentRelId + ':listed-but-' + record.namespaceState);
+ }
+ }
+ return mismatches;
+}
+
+export function collectRootInstallCensusCandidates(input: {
+ contentRoot: string;
+ readApproval: (relId: string) => { state: string; receipt?: object };
+ listPendingMutationIds: () => { state: string; blocked?: boolean; ids?: readonly string[] };
+ readPendingMutation: (id: string) => {
+ state: string;
+ mutation?: { kind?: string; backupDirName?: string };
+ };
+ readRecoveryApproval: (id: string) => { state: string; receipt?: object };
+ recoveryEntryKind: (absPath: string) => string;
+}): NamespaceCensusCandidate[] {
+ const root = input.contentRoot;
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(root, { withFileTypes: true });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ const candidates: NamespaceCensusCandidate[] = [];
+ for (const entry of entries) {
+ if (entry.name.startsWith('.') || entry.name === PLUGIN_NS_INSTALL_ROOT) continue;
+ if (!isValidGhostId(entry.name)) continue;
+ const dir = path.join(root, entry.name);
+ if (classifyGhostDirEntrySync(dir) !== 'directory') continue;
+ const approval = input.readApproval(entry.name);
+ candidates.push({
+ ghostId: entry.name,
+ relId: entry.name,
+ ...(approval.state === 'approved' ? { identitySource: approval.receipt } : {}),
+ });
+ }
+ const pending = input.listPendingMutationIds();
+ if (pending.state === 'ok' && !pending.blocked) {
+ const seen = new Set(candidates.map((candidate) => candidate.ghostId));
+ for (const id of pending.ids ?? []) {
+ if (!isValidGhostId(id) || seen.has(id)) continue;
+ const marker = input.readPendingMutation(id);
+ if (marker.state !== 'valid' || marker.mutation?.kind !== 'update' || !marker.mutation.backupDirName) {
+ continue;
+ }
+ const backup = path.join(root, marker.mutation.backupDirName);
+ if (input.recoveryEntryKind(backup) !== 'directory') continue;
+ const approval = input.readRecoveryApproval(id);
+ if (approval.state !== 'approved' || !approval.receipt) continue;
+ candidates.push({ ghostId: id, relId: id, identitySource: approval.receipt });
+ }
+ }
+ return candidates;
+}
+
+type OpenedRegistry =
+ | { status: 'ready'; registry: PluginInstanceRegistry }
+ | { status: 'blocked'; reason: 'unreadable' | 'unknown-schema' | 'quarantine-failed' };
+
+export class PluginInstanceRegistryService {
+ private registry: PluginInstanceRegistry | null = null;
+ private blocked = false;
+
+ constructor(private readonly deps: PluginInstanceRegistryServiceDeps) {}
+
+ clear(): void {
+ this.registry = null;
+ this.blocked = false;
+ }
+
+ isBlocked(): boolean {
+ return this.blocked;
+ }
+
+ current(): PluginInstanceRegistry | null {
+ return this.registry;
+ }
+
+ replaceCache(registry: PluginInstanceRegistry): void {
+ this.blocked = false;
+ this.registry = registry;
+ }
+
+ /** One quarantine path for sync and census. Unknown schemas are never rewritten. */
+ private open(store: PluginInstanceRegistryStore): OpenedRegistry {
+ let read = store.read();
+ if (read.kind === 'corrupt') {
+ try {
+ store.discardCorrupt();
+ read = { kind: 'missing' };
+ this.deps.log?.warn('plugin instance registry was corrupt; rebuilding directory keys');
+ } catch (error) {
+ this.deps.log?.warn('plugin instance registry corrupt and could not be quarantined', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return { status: 'blocked', reason: 'quarantine-failed' };
+ }
+ }
+ if (read.kind === 'unreadable' || read.kind === 'unknown-schema') {
+ this.deps.log?.warn('plugin instance registry unusable; privileges stay unconfirmed', { kind: read.kind });
+ return { status: 'blocked', reason: read.kind };
+ }
+ return {
+ status: 'ready',
+ registry: read.kind === 'ok' ? read.registry : emptyPluginInstanceRegistry(),
+ };
+ }
+
+ private block(): PluginInstanceRegistry {
+ this.blocked = true;
+ this.registry = emptyPluginInstanceRegistry();
+ return this.registry;
+ }
+
+ /**
+ * Adoption allowlist. Before the census is stored, a bare root directory is
+ * pending. Afterwards only the frozen pendingRelIds list is.
+ */
+ isPendingMigrationRel(relId: string, registry: PluginInstanceRegistry): boolean {
+ if (registry.census) return registry.census.pendingRelIds.includes(relId);
+ return parsePluginInstallRelId(relId)?.ghostId === relId;
+ }
+
+ sync(): PluginInstanceRegistry {
+ this.deps.ensureOwner();
+ const store = this.deps.registryStore();
+ const opened = this.open(store);
+ if (opened.status === 'blocked') return this.block();
+ this.blocked = false;
+ let registry = opened.registry;
+ let dirty = false;
+ const present = new Set<string>();
+ for (const listed of this.deps.listContentEntries()) {
+ present.add(listed.relId);
+ const fact = this.deps.receiptFact(listed.relId);
+ if (fact === undefined) continue;
+ const existing = findInstanceByContentRelId(registry, listed.relId);
+ if (!existing) {
+ const ghostId = parsePluginInstallRelId(listed.relId)?.ghostId ?? fact?.ghostId ?? null;
+ if (!ghostId) continue;
+ const adopted = adoptContentInstall({
+ relId: listed.relId,
+ ghostId,
+ receipt: fact,
+ pendingMigration: this.isPendingMigrationRel(listed.relId, registry),
+ marketPluginId: this.deps.marketIdentityForInstance?.({
+ ghostId,
+ contentRelId: listed.relId,
+ namespace: parsePluginInstallRelId(listed.relId)?.namespace ?? null,
+ packageSha256: fact?.packageSha256 ?? null,
+ })?.pluginId ?? null,
+ });
+ if (!adopted) continue;
+ registry = upsertInstance(registry, adopted);
+ dirty = true;
+ continue;
+ }
+ let next = reconcileInstanceReceipt(existing, { directoryPresent: true, receipt: fact });
+ const market = this.deps.marketIdentityForInstance?.({
+ ghostId: next.ghostId,
+ contentRelId: next.contentRelId,
+ namespace: next.namespace,
+ packageSha256: next.packageSha256,
+ }) ?? null;
+ if (market && next.pluginId == null && next.source !== 'agent-forge' && next.source !== 'builtin') {
+ next = { ...next, pluginId: market.pluginId, source: 'market' };
+ }
+ if (next !== existing) {
+ registry = upsertInstance(registry, next);
+ dirty = true;
+ }
+ }
+ for (const record of Object.values(registry.instances)) {
+ if (record.active && !present.has(record.contentRelId)) {
+ registry = upsertInstance(registry, { ...record, active: false });
+ dirty = true;
+ }
+ }
+ const mismatches = pendingCensusMismatches(registry);
+ if (mismatches.length > 0) {
+ this.deps.log?.warn('plugin instance census diverged from namespaceState', { mismatches });
+ }
+ if (dirty) {
+ try {
+ store.write(registry);
+ } catch (error) {
+ this.deps.log?.warn('plugin instance registry write failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ this.registry = registry;
+ return registry;
+ }
+
+ recordForAddress(id: string): PluginInstanceRecord | null {
+ if (this.registry && !this.blocked) return this.lookup(this.registry, id);
+ const registry = this.sync();
+ if (this.blocked) return null;
+ return this.lookup(registry, id);
+ }
+
+ private lookup(registry: PluginInstanceRegistry | null, id: string): PluginInstanceRecord | null {
+ if (!registry || this.blocked) return null;
+ return findInstanceByContentRelId(registry, id)
+ ?? registry.instances[id]
+ ?? Object.values(registry.instances).find((record) => record.instanceKey === id)
+ ?? null;
+ }
+
+ publish(record: PluginInstanceRecord): void {
+ if (this.blocked) return;
+ // A cold cache is not an empty registry. Sync first so this write cannot
+ // replace every other instance with the one row being published.
+ if (!this.registry) {
+ this.sync();
+ if (this.blocked) return;
+ }
+ const next = upsertInstance(this.registry ?? emptyPluginInstanceRegistry(), record);
+ this.deps.registryStore().write(next);
+ this.registry = next;
+ }
+
+ confirmNamespace(
+ relOrKey: string,
+ namespace: string | null,
+ revision: string,
+ packageSha256: string | null,
+ ): boolean {
+ const registry = this.sync();
+ if (this.blocked) return false;
+ const record = findInstanceByContentRelId(registry, relOrKey) ?? registry.instances[relOrKey]
+ ?? Object.values(registry.instances).find((item) =>
+ item.active && item.ghostId === relOrKey && item.contentRelId === relOrKey);
+ if (!record) return false;
+ const confirmed = confirmInstanceNamespace(registry, record.instanceKey, namespace, { revision, packageSha256 });
+ if (confirmed === registry && !(record.namespaceState === 'confirmed' && record.namespace === namespace)) {
+ return false;
+ }
+ const next = clearCensusPending(confirmed, record.contentRelId);
+ if (next === registry) return true;
+ this.deps.registryStore().write(next);
+ this.registry = next;
+ return true;
+ }
+
+ release(relOrKey: string): void {
+ const registry = this.sync();
+ if (this.blocked) throw new Error('plugin instance registry is blocked');
+ const next = releaseInstalledInstance(registry, relOrKey);
+ if (next === registry) return;
+ this.deps.registryStore().write(next);
+ this.registry = next;
+ }
+
+ ensureCensus(): PluginInstanceCensus | null {
+ this.deps.ensureOwner();
+ const store = this.deps.registryStore();
+ const opened = this.open(store);
+ if (opened.status === 'blocked') {
+ this.block();
+ return null;
+ }
+ if (opened.registry.census) {
+ this.blocked = false;
+ this.registry = opened.registry;
+ return opened.registry.census;
+ }
+ let candidates: NamespaceCensusCandidate[];
+ try {
+ candidates = this.deps.censusCandidates();
+ } catch (error) {
+ this.deps.log?.warn('namespace migration census scan failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+ const stamped = stampInstanceCensus({
+ registry: opened.registry,
+ candidates,
+ now: new Date().toISOString(),
+ readApproval: (relId) => this.deps.readApproval(relId),
+ captureInstalledLegacy: (ghostId, packageSha256) =>
+ this.deps.captureInstalledLegacy?.(ghostId, packageSha256) === true,
+ recordLegacyEligibility: (relId, revision) => {
+ this.deps.recordLegacyEligibility(relId, revision);
+ },
+ });
+ if (!stamped) return null;
+ try {
+ store.write(stamped);
+ } catch (error) {
+ this.deps.log?.warn('namespace migration census write failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+ this.blocked = false;
+ this.registry = stamped;
+ return stamped.census;
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigration.ts b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigration.ts
new file mode 100644
index 0000000000..808d281cd2
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigration.ts
@@ -0,0 +1,457 @@
+/**
+ * Upgrade census stored on the instance registry.
+ * The first census records the legacy root directories present at that moment.
+ * Later installs are not added to pendingRelIds.
+ */
+import { isValidPluginNamespace, PLUGIN_PREFIX_PATTERN } from '@cindy/plugin-protocol';
+import { isValidGhostId } from '../../shared/ghost.js';
+import { hasDeliveryNamespace, resolvePluginNamespaceState } from '../../shared/pluginIdentity.js';
+import { captureLegacyFirstPartyEligibility } from './ghostFirstPartyPrivilege.js';
+import {
+ type GhostInstallReceipt,
+ type GhostInstallReceiptReadResult,
+} from './ghostInstallReceipt.js';
+import {
+ finishInstanceCensus,
+ type PluginInstanceCensus,
+ type PluginInstanceRegistry,
+} from './pluginInstanceRegistry.js';
+
+export type NamespaceMigrationBasis =
+ | 'builtin'
+ | 'market-public'
+ | 'market-personal'
+ | 'market-custom'
+ | 'manual-after-sync'
+ | 'explicit-root'
+ | 'market-organization'
+ | 'forge-current-org'
+ | 'receipt-recovered';
+
+export type NamespaceClassification =
+ | { kind: 'commit'; namespace: string | null; basis: NamespaceMigrationBasis }
+ | { kind: 'pending'; reason: string };
+
+export interface NamespaceCensusCandidate {
+ ghostId: string;
+ relId: string;
+ /** Receipt/ledger object; missing namespace field means pre-namespace. */
+ identitySource?: object;
+}
+
+export interface ClassifyNamespaceMigrationInput {
+ ghostId: string;
+ builtin: boolean;
+ installOrigin: 'manual' | 'agent-forge' | undefined;
+ marketSyncCompleted: boolean;
+ marketRecord: {
+ scope: 'public' | 'personal' | 'organization';
+ source: 'market' | 'legacy-adopted' | 'git-market' | 'local-market';
+ organizationId: string | null;
+ namespace?: string | null;
+ installed?: boolean;
+ } | null | undefined;
+ currentOrganization: {
+ organizationId: string;
+ orgSlug: string | null;
+ pluginPrefix: string | null;
+ } | null;
+}
+
+export function readNamespaceMigrationMarketRecord(
+ readRecords: () => readonly NonNullable<ClassifyNamespaceMigrationInput['marketRecord']>[],
+): ClassifyNamespaceMigrationInput['marketRecord'] {
+ try {
+ const records = readRecords().filter((record) => record.installed !== false);
+ if (records.length === 0) return null;
+ return records.length === 1 ? records[0] : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function readNamespaceMigrationInstallOrigin(
+ readApprovedOrigin: () => 'manual' | 'agent-forge',
+): ClassifyNamespaceMigrationInput['installOrigin'] {
+ try {
+ return readApprovedOrigin();
+ } catch {
+ return undefined;
+ }
+}
+
+function matchesOrgPrefix(ghostId: string, prefix: string | null): boolean {
+ if (!prefix || !PLUGIN_PREFIX_PATTERN.test(prefix)) return false;
+ return ghostId.startsWith(`${prefix}-`);
+}
+
+export function isCensusCandidate(candidate: NamespaceCensusCandidate): boolean {
+ if (!isValidGhostId(candidate.ghostId)) return false;
+ if (candidate.relId !== candidate.ghostId) return false;
+ if (!candidate.identitySource) return true;
+ return resolvePluginNamespaceState(candidate.identitySource).kind === 'legacy';
+}
+
+export function classifyNamespaceMigration(
+ input: ClassifyNamespaceMigrationInput,
+): NamespaceClassification {
+ const record = input.marketRecord?.installed === false ? null : input.marketRecord;
+ if (record === undefined) {
+ return { kind: 'pending', reason: 'awaiting-market-facts' };
+ }
+ if (record) {
+ const recordState = resolvePluginNamespaceState(record);
+ if (recordState.kind === 'known') {
+ if (recordState.namespace !== null) {
+ return {
+ kind: 'commit',
+ namespace: recordState.namespace,
+ basis: 'market-organization',
+ };
+ }
+ return { kind: 'commit', namespace: null, basis: 'explicit-root' };
+ }
+ if (record.source === 'git-market' || record.source === 'local-market') {
+ return { kind: 'commit', namespace: null, basis: 'market-custom' };
+ }
+ if (record.scope === 'public') {
+ return { kind: 'commit', namespace: null, basis: 'market-public' };
+ }
+ if (record.scope === 'personal') {
+ return { kind: 'commit', namespace: null, basis: 'market-personal' };
+ }
+ if (record.scope === 'organization') {
+ const namespace = matchingOrganizationNamespace(record.organizationId, input.currentOrganization);
+ if (namespace) {
+ return { kind: 'commit', namespace, basis: 'market-organization' };
+ }
+ return { kind: 'pending', reason: 'awaiting-organization-namespace' };
+ }
+ }
+
+ if (input.builtin) {
+ return { kind: 'commit', namespace: null, basis: 'builtin' };
+ }
+
+ if (input.installOrigin === undefined) {
+ return { kind: 'pending', reason: 'awaiting-install-origin' };
+ }
+
+ if (
+ input.installOrigin === 'agent-forge' &&
+ input.currentOrganization &&
+ matchesOrgPrefix(input.ghostId, input.currentOrganization.pluginPrefix)
+ ) {
+ const namespace = input.currentOrganization.orgSlug;
+ if (namespace && isValidPluginNamespace(namespace)) {
+ return { kind: 'commit', namespace, basis: 'forge-current-org' };
+ }
+ return { kind: 'pending', reason: 'awaiting-organization-namespace' };
+ }
+
+ if (input.marketSyncCompleted && input.installOrigin === 'manual' && record === null) {
+ return { kind: 'commit', namespace: null, basis: 'manual-after-sync' };
+ }
+
+ return { kind: 'pending', reason: 'awaiting-market-facts' };
+}
+
+function matchingOrganizationNamespace(
+ organizationId: string | null,
+ currentOrganization: ClassifyNamespaceMigrationInput['currentOrganization'],
+): string | null {
+ if (!organizationId || !currentOrganization) return null;
+ if (currentOrganization.organizationId !== organizationId) return null;
+ const namespace = currentOrganization.orgSlug;
+ return namespace && isValidPluginNamespace(namespace) ? namespace : null;
+}
+
+export type NamespaceCommitPlan =
+ | { kind: 'skip'; reason: 'not-pending' | 'busy' }
+ | { kind: 'write-registry-only'; namespace: string | null; basis: 'receipt-recovered' }
+ | {
+ kind: 'write-receipt-and-registry';
+ namespace: string | null;
+ basis: NamespaceMigrationBasis;
+ };
+
+/**
+ * Crash window: receipt may already carry namespace while the registry census
+ * is still pending. Finish the registry record to match the receipt; do not reclassify.
+ * Busy only blocks a first-time receipt write, not registry recovery.
+ */
+export function planNamespaceCommit(input: {
+ pending: boolean;
+ busy: boolean;
+ receiptNamespace?: string | null;
+ requested: { namespace: string | null; basis: NamespaceMigrationBasis };
+}): NamespaceCommitPlan {
+ if (!input.pending) return { kind: 'skip', reason: 'not-pending' };
+ if (input.receiptNamespace !== undefined) {
+ return {
+ kind: 'write-registry-only',
+ namespace: input.receiptNamespace,
+ basis: 'receipt-recovered',
+ };
+ }
+ if (input.busy) return { kind: 'skip', reason: 'busy' };
+ return {
+ kind: 'write-receipt-and-registry',
+ namespace: input.requested.namespace,
+ basis: input.requested.basis,
+ };
+}
+
+export interface CensusApproval {
+ state: string;
+ receipt?: {
+ packageSha256?: string;
+ revision: string;
+ trust: { level: string };
+ };
+}
+
+/**
+ * One-shot census of the legacy root directories present now.
+ * Existing instance rows are not rewritten.
+ */
+export function stampInstanceCensus(input: {
+ registry: PluginInstanceRegistry;
+ candidates: readonly NamespaceCensusCandidate[];
+ now: string;
+ readApproval: (relId: string) => CensusApproval;
+ captureInstalledLegacy?: (ghostId: string, packageSha256: string) => boolean;
+ recordLegacyEligibility: (relId: string, revision: string) => void;
+}): PluginInstanceRegistry | null {
+ if (input.registry.census) return input.registry;
+ const pendingEntries = input.candidates.filter((candidate) => isCensusCandidate(candidate));
+ try {
+ for (const entry of pendingEntries) {
+ const approval = input.readApproval(entry.relId);
+ const sha = approval.receipt?.packageSha256;
+ if (approval.state !== 'approved' || !sha || !approval.receipt) continue;
+ const eligible = captureLegacyFirstPartyEligibility({
+ legacyExistingInstall: true,
+ ghostId: entry.ghostId,
+ namespace: null,
+ approved: true,
+ approvedPackageSha256: sha,
+ marketRecord: null,
+ approvedOfficialTrust: approval.receipt.trust.level === 'cindy-official',
+ }) || input.captureInstalledLegacy?.(entry.ghostId, sha) === true;
+ if (eligible) input.recordLegacyEligibility(entry.relId, approval.receipt.revision);
+ }
+ } catch {
+ return null;
+ }
+ return finishInstanceCensus(input.registry, input.now, pendingEntries.map((entry) => entry.relId));
+}
+
+export type NamespaceCommitReceiptSnapshot = {
+ state: GhostInstallReceiptReadResult['state'];
+ hasNamespace?: boolean;
+ namespace?: string | null;
+ revision?: string;
+ packageSha256?: string;
+ installOrigin?: string;
+};
+
+export function namespaceCommitReceiptSnapshot(
+ approval: GhostInstallReceiptReadResult,
+): NamespaceCommitReceiptSnapshot {
+ if (approval.state !== 'approved') return { state: approval.state };
+ return {
+ state: approval.state,
+ hasNamespace: hasDeliveryNamespace(approval.receipt),
+ ...(hasDeliveryNamespace(approval.receipt)
+ ? { namespace: approval.receipt.namespace }
+ : {}),
+ revision: approval.receipt.revision,
+ ...(approval.receipt.packageSha256 !== undefined
+ ? { packageSha256: approval.receipt.packageSha256 }
+ : {}),
+ ...(approval.receipt.installOrigin !== undefined
+ ? { installOrigin: approval.receipt.installOrigin }
+ : {}),
+ };
+}
+
+export function sameNamespaceCommitReceiptSnapshot(
+ left: NamespaceCommitReceiptSnapshot,
+ right: NamespaceCommitReceiptSnapshot,
+): boolean {
+ return left.state === right.state &&
+ (left.state !== 'approved' || (
+ left.hasNamespace === right.hasNamespace &&
+ left.namespace === right.namespace &&
+ left.revision === right.revision &&
+ left.packageSha256 === right.packageSha256 &&
+ left.installOrigin === right.installOrigin
+ ));
+}
+
+export interface PendingNamespaceCommitHost {
+ ownerContextKey(): string;
+ ensureCensus(): PluginInstanceCensus | null;
+ readApproval(ghostId: string): GhostInstallReceiptReadResult;
+ hasPendingMutationJournal(ghostId: string): boolean;
+ isNamespaceMigrationBusy(ghostId: string): boolean;
+ beforeNamespaceCommit(ghostId: string, namespace: string | null): void;
+ writeReceiptNamespace(ghostId: string, receipt: GhostInstallReceipt, namespace: string | null): Promise<void>;
+ onNamespaceCommitted(ghostId: string, namespace: string | null): void;
+ confirmRecordedNamespace(
+ ghostId: string,
+ namespace: string | null,
+ revision: string,
+ packageSha256: string | null,
+ ): boolean;
+ notifyChanged(): void;
+}
+
+/** Stamp one pending bare install. Receipt and registry census update stay in this call. */
+export async function commitPendingNamespaceMigration(
+ host: PendingNamespaceCommitHost,
+ ghostId: string,
+ namespace: string | null,
+ basis: NamespaceMigrationBasis,
+ expectedReceipt?: NamespaceCommitReceiptSnapshot,
+): Promise<{ ok: true } | { ok: false; reason: string }> {
+ const ownerContextKey = host.ownerContextKey();
+ if (!isValidGhostId(ghostId)) return { ok: false, reason: 'invalid ghost id' };
+ if (namespace !== null && !isValidPluginNamespace(namespace)) {
+ return { ok: false, reason: 'invalid namespace' };
+ }
+ const census = host.ensureCensus();
+ if (!census?.pendingRelIds.includes(ghostId)) return { ok: false, reason: 'not pending' };
+ const approval = host.readApproval(ghostId);
+ if (expectedReceipt && !sameNamespaceCommitReceiptSnapshot(
+ expectedReceipt, namespaceCommitReceiptSnapshot(approval),
+ )) {
+ return { ok: false, reason: 'state-changed' };
+ }
+ if (approval.state !== 'approved') return { ok: false, reason: 'busy' };
+ const receiptNamespace =
+ hasDeliveryNamespace(approval.receipt)
+ ? approval.receipt.namespace ?? null
+ : undefined;
+ const plan = planNamespaceCommit({
+ pending: true,
+ busy: host.hasPendingMutationJournal(ghostId) || host.isNamespaceMigrationBusy(ghostId),
+ ...(receiptNamespace !== undefined ? { receiptNamespace } : {}),
+ requested: { namespace, basis },
+ });
+ if (plan.kind === 'skip') return { ok: false, reason: plan.reason };
+ host.beforeNamespaceCommit(ghostId, plan.namespace);
+ if (plan.kind === 'write-receipt-and-registry') {
+ await host.writeReceiptNamespace(ghostId, approval.receipt, plan.namespace);
+ if (host.ownerContextKey() !== ownerContextKey) {
+ throw new Error('ghost owner changed while committing a namespace migration');
+ }
+ const committedApproval = host.readApproval(ghostId);
+ if (committedApproval.state !== 'approved' ||
+ committedApproval.receipt.revision !== approval.receipt.revision ||
+ committedApproval.receipt.packageSha256 !== approval.receipt.packageSha256 ||
+ committedApproval.receipt.installOrigin !== approval.receipt.installOrigin ||
+ !hasDeliveryNamespace(committedApproval.receipt) ||
+ committedApproval.receipt.namespace !== plan.namespace) {
+ return { ok: false, reason: 'state-changed' };
+ }
+ }
+ if (host.ownerContextKey() !== ownerContextKey) {
+ throw new Error('ghost owner changed while committing a namespace migration');
+ }
+ host.onNamespaceCommitted(ghostId, plan.namespace);
+ const confirmed = host.confirmRecordedNamespace(
+ ghostId,
+ plan.namespace,
+ approval.receipt.revision,
+ approval.receipt.packageSha256 ?? null,
+ );
+ if (!confirmed) return { ok: false, reason: 'namespace-conflict' };
+ host.notifyChanged();
+ return { ok: true };
+}
+
+export interface PendingNamespaceReconcileHost {
+ ensureCensus(): PluginInstanceCensus | null;
+ ownerContextKey(): string;
+ preparePendingResident?(ghostId: string): Promise<boolean>;
+ onPendingResidentDeferred?(ghostId: string): void;
+ /** committed false means a stop was not followed by a successful stamp. */
+ onPendingResidentMigrationSettled?(ghostId: string, committed: boolean): void;
+ readApproval(ghostId: string): GhostInstallReceiptReadResult;
+ classify?(ghostId: string, marketSyncCompleted: boolean): NamespaceClassification;
+ commit(
+ ghostId: string,
+ namespace: string | null,
+ basis: NamespaceMigrationBasis,
+ expectedReceipt: NamespaceCommitReceiptSnapshot,
+ ): Promise<{ ok: true } | { ok: false; reason: string }>;
+ confirmUnconfirmed(): Promise<void>;
+ log?: { warn(message: string, meta?: Record<string, unknown>): void };
+}
+
+/** Walk the stored census. One entry failing does not stop the rest. */
+export async function reconcilePendingNamespaceMigrations(
+ host: PendingNamespaceReconcileHost,
+ marketSyncCompleted: boolean,
+): Promise<void> {
+ const census = host.ensureCensus();
+ if (!census) return;
+ const ownerContextKey = host.ownerContextKey();
+ for (const ghostId of census.pendingRelIds) {
+ if (host.ownerContextKey() !== ownerContextKey) return;
+ let stopAttempted = false;
+ try {
+ const expectedReceipt = namespaceCommitReceiptSnapshot(host.readApproval(ghostId));
+ const classification = host.classify?.(ghostId, marketSyncCompleted) ?? {
+ kind: 'pending' as const,
+ reason: 'awaiting-market-facts',
+ };
+ // Stop only when this entry is about to be stamped. A pending result,
+ // such as a Forge install whose organization does not match, must leave
+ // the running plugin alone.
+ if (marketSyncCompleted && classification.kind === 'commit') {
+ const ready = await host.preparePendingResident?.(ghostId);
+ if (host.ownerContextKey() !== ownerContextKey) return;
+ if (ready === false) {
+ host.onPendingResidentDeferred?.(ghostId);
+ continue;
+ }
+ stopAttempted = true;
+ }
+ if (classification.kind === 'commit') {
+ const result = await host.commit(
+ ghostId, classification.namespace, classification.basis, expectedReceipt,
+ );
+ if (stopAttempted && host.ownerContextKey() === ownerContextKey) {
+ host.onPendingResidentMigrationSettled?.(ghostId, result.ok);
+ }
+ if (!result.ok && result.reason === 'busy' && marketSyncCompleted) {
+ host.onPendingResidentDeferred?.(ghostId);
+ }
+ if (!result.ok && result.reason === 'state-changed' && marketSyncCompleted) {
+ host.onPendingResidentDeferred?.(ghostId);
+ }
+ }
+ } catch (error) {
+ if (stopAttempted && host.ownerContextKey() === ownerContextKey) {
+ try {
+ host.onPendingResidentMigrationSettled?.(ghostId, false);
+ } catch {
+ // Restoring the plugin is best-effort; the entry is still deferred.
+ }
+ }
+ if (marketSyncCompleted && host.ownerContextKey() === ownerContextKey) {
+ host.onPendingResidentDeferred?.(ghostId);
+ }
+ host.log?.warn('pending namespace migration entry failed; continuing with remaining entries', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ if (marketSyncCompleted && host.ownerContextKey() === ownerContextKey) {
+ await host.confirmUnconfirmed();
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
new file mode 100644
index 0000000000..1d5bf271bf
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
@@ -0,0 +1,315 @@
+/**
+ * Process-local wiring for the namespace census: market evidence, offline
+ * resident retries, and unconfirmed confirmation facts. GhostManager stays
+ * unaware of auth, the market ledger, and runtime slots.
+ */
+import path from 'node:path';
+
+import { GHOST_INSTALL_MANIFEST_MAX_BYTES } from '../../shared/ghost.js';
+import { installedGhostPhysicalRelId, installedGhostStoragePart } from '../../shared/pluginIdentity.js';
+import type { GhostManifest, InstalledGhost } from '../../shared/ghost.js';
+import { isResidentBrowserGhost } from './residentGhost.js';
+import {
+ classifyNamespaceMigration,
+ readNamespaceMigrationInstallOrigin,
+ readNamespaceMigrationMarketRecord,
+ type NamespaceClassification,
+} from './pluginNamespaceMigration.js';
+import { buildUnconfirmedConfirmationEvidence } from './pluginInstanceConfirmation.js';
+import type { InstanceConfirmationEvidence, PluginInstanceRecord } from './pluginInstanceRegistry.js';
+import {
+ hasVerifiedDisconnectedOrganizationInstallation,
+ installedMarketManifestIdentity,
+} from '../plugin-market/installedManifestIdentity.js';
+import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';
+
+export interface NamespaceMigrationGhostView {
+ manifest: {
+ id: string;
+ launch?: GhostManifest['launch'];
+ routineEvents?: GhostManifest['routineEvents'];
+ node?: { lifecycle?: string | null };
+ };
+ builtin?: boolean;
+ namespaceState?: string;
+}
+
+export interface NamespaceMigrationManager {
+ list(): readonly NamespaceMigrationGhostView[];
+ approvedInstallEvidence(id: string): { packageSha256: string | null; approvedManifest: GhostManifest; legacyMigrated: boolean } | null;
+ readApprovedInstallOriginStrict(id: string): 'manual' | 'agent-forge';
+ reconcilePendingRootNamespaces(marketSyncCompleted: boolean): Promise<void>;
+}
+
+export interface NamespaceMigrationHostDeps {
+ activeOwnerScopeKey(): string;
+ isAppSessionBoundaryPending(): boolean;
+ getGhostManager(): NamespaceMigrationManager;
+ getPluginMarketLedger(): {
+ lookupInstallationsForNamespaceMigration(ghostId: string): {
+ kind: string;
+ records?: readonly PluginMarketInstallationRecord[];
+ };
+ };
+ getAuthState(): {
+ isAuthenticated: boolean;
+ user: {
+ membershipKind?: string;
+ orgId?: string | null;
+ orgSlug?: string | null;
+ } | null;
+ };
+ createOrganizationPrefixStore(filePath: string): {
+ lookup(orgId: string): { kind: string; pluginPrefix?: string | null };
+ };
+ ownerScopedUserDataPath(...parts: string[]): string;
+ brainRootDir(): string;
+ readInstalledGhostManifestSnapshot(dir: string, maxBytes: number): {
+ ok: boolean;
+ snapshot?: Parameters<typeof installedMarketManifestIdentity>[0];
+ };
+ oauthLockExists(ghostId: string): boolean;
+ hasPendingWork(ghostId: string): boolean;
+ runtimeState(instanceKey: string): string | null | undefined;
+ nodeRuntimeRunning(instanceKey: string): boolean;
+ stopRuntime(instanceKey: string): void;
+ stopNodeRuntime(instanceKey: string): Promise<void>;
+ /** Restart a resident that was stopped for a commit which then did not land. */
+ spawnIfResident?(ghostId: string): void;
+ captureGhostMutationOwner(): unknown;
+ beginGhostMutation(owner: unknown): () => void;
+ log: { warn(message: string, meta?: Record<string, unknown>): void };
+ /** Test seam. Production uses the host's own set. */
+ offlineResidentIdsForActiveScope?: () => Set<string>;
+ pendingResidentMigrationRetryTimers?: Map<string, { unref?: () => void }>;
+ pendingResidentMigrationRetryAttempts?: Map<string, number>;
+ setTimeout?: (handler: () => void, timeoutMs: number) => { unref?: () => void };
+}
+
+export interface NamespaceMigrationHost {
+ classifyPendingNamespaceForGhost(ghostId: string, marketSyncCompleted?: boolean): NamespaceClassification;
+ canResumePendingResidentOffline(ghostId: string): boolean;
+ schedulePendingResidentMigrationRetry(ghostId: string): void;
+ isNamespaceMigrationBusy(ghostId: string): boolean;
+ preparePendingResidentForMigration(ghostId: string): Promise<boolean>;
+ readUnconfirmedConfirmationEvidence(record: PluginInstanceRecord): InstanceConfirmationEvidence;
+ rememberOfflineResident(ghostId: string): void;
+ forgetOfflineResident(ghostId: string): void;
+ clearPendingResidentMigrationRetry(ghostId: string): void;
+ onPendingResidentMigrationSettled(ghostId: string, committed: boolean): void;
+}
+
+export function createNamespaceMigrationHost(deps: NamespaceMigrationHostDeps): NamespaceMigrationHost {
+ let offlineResidentScopeKey: string | null = null;
+ const ownedResidentIds = new Set<string>();
+ const retryTimers = deps.pendingResidentMigrationRetryTimers ?? new Map<string, { unref?: () => void }>();
+ const retryAttempts = deps.pendingResidentMigrationRetryAttempts ?? new Map<string, number>();
+ const stoppedForCommit = new Set<string>();
+ const scheduleTimeout = deps.setTimeout ?? ((handler, timeoutMs) => setTimeout(handler, timeoutMs));
+
+ function offlineResidentIdsForActiveScope(): Set<string> {
+ if (deps.offlineResidentIdsForActiveScope) return deps.offlineResidentIdsForActiveScope();
+ const scopeKey = deps.activeOwnerScopeKey();
+ if (offlineResidentScopeKey !== scopeKey) {
+ for (const timer of retryTimers.values()) clearTimeout(timer as ReturnType<typeof setTimeout>);
+ retryTimers.clear();
+ retryAttempts.clear();
+ ownedResidentIds.clear();
+ offlineResidentScopeKey = scopeKey;
+ }
+ return ownedResidentIds;
+ }
+
+ function namespaceMigrationMarketRecordsForGhost(ghostId: string): PluginMarketInstallationRecord[] {
+ const lookup = deps.getPluginMarketLedger().lookupInstallationsForNamespaceMigration(ghostId);
+ if (lookup.kind === 'invalid') throw new Error('Plugin namespace migration market evidence is invalid');
+ const records = lookup.kind === 'found' ? [...(lookup.records ?? [])] : [];
+ if (!records.some((record) => record.installed) &&
+ records.some((record) => !record.installed && record.scope === 'organization' &&
+ (record.source === 'market' || record.source === 'legacy-adopted'))) {
+ const snapshot = deps.readInstalledGhostManifestSnapshot(
+ path.join(deps.brainRootDir(), ghostId), GHOST_INSTALL_MANIFEST_MAX_BYTES);
+ const evidence = deps.getGhostManager().approvedInstallEvidence(ghostId);
+ if (!snapshot.ok || !snapshot.snapshot || !evidence) {
+ throw new Error('Plugin namespace migration approved installation evidence is unavailable');
+ }
+ if (hasVerifiedDisconnectedOrganizationInstallation({
+ records, evidence, identity: installedMarketManifestIdentity(snapshot.snapshot),
+ })) {
+ throw new Error('Plugin namespace migration awaits disconnected organization installation recovery');
+ }
+ }
+ return records;
+ }
+
+ function schedulePendingResidentMigrationRetry(ghostId: string): void {
+ // Touch the scope so an account switch clears stale timers. An online
+ // resident is not in the offline set, but it still needs a retry.
+ offlineResidentIdsForActiveScope();
+ if (retryTimers.has(ghostId)) return;
+ const ownerScopeKey = deps.activeOwnerScopeKey();
+ const attempts = retryAttempts.get(ghostId) ?? 0;
+ retryAttempts.set(ghostId, attempts + 1);
+ const timer = scheduleTimeout(() => {
+ if (retryTimers.get(ghostId) !== timer) return;
+ retryTimers.delete(ghostId);
+ if (deps.activeOwnerScopeKey() !== ownerScopeKey) return;
+ void (async () => {
+ let releaseMutation: (() => void) | null = null;
+ try {
+ const owner = deps.captureGhostMutationOwner();
+ releaseMutation = deps.beginGhostMutation(owner);
+ await deps.getGhostManager().reconcilePendingRootNamespaces(true);
+ } catch (error) {
+ deps.log.warn('offline resident namespace migration retry failed', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ schedulePendingResidentMigrationRetry(ghostId);
+ } finally {
+ releaseMutation?.();
+ }
+ })();
+ }, Math.min(1000 * 2 ** Math.min(attempts, 6), 60_000));
+ timer.unref?.();
+ retryTimers.set(ghostId, timer);
+ }
+
+ return {
+ schedulePendingResidentMigrationRetry,
+ rememberOfflineResident(ghostId: string): void {
+ offlineResidentIdsForActiveScope().add(ghostId);
+ },
+ forgetOfflineResident(ghostId: string): void {
+ offlineResidentIdsForActiveScope().delete(ghostId);
+ },
+ clearPendingResidentMigrationRetry(ghostId: string): void {
+ const retryTimer = retryTimers.get(ghostId);
+ if (retryTimer) clearTimeout(retryTimer as ReturnType<typeof setTimeout>);
+ retryTimers.delete(ghostId);
+ retryAttempts.delete(ghostId);
+ },
+ isNamespaceMigrationBusy(ghostId: string): boolean {
+ if (deps.isAppSessionBoundaryPending()) return true;
+ try {
+ if (deps.oauthLockExists(ghostId)) return true;
+ } catch {
+ return true;
+ }
+ if (deps.hasPendingWork(ghostId)) return true;
+ const ghost = deps.getGhostManager()
+ .list()
+ .find((candidate) => installedGhostPhysicalRelId(candidate as InstalledGhost) === ghostId);
+ if (!ghost) return false;
+ const runtimeId = installedGhostStoragePart(ghost as InstalledGhost);
+ const state = deps.runtimeState(runtimeId);
+ return state === 'starting' || state === 'running' || state === 'stopping' ||
+ deps.nodeRuntimeRunning(runtimeId);
+ },
+ canResumePendingResidentOffline(ghostId: string): boolean {
+ if (deps.isAppSessionBoundaryPending()) return false;
+ const record = readNamespaceMigrationMarketRecord(() =>
+ namespaceMigrationMarketRecordsForGhost(ghostId));
+ return record === null && readNamespaceMigrationInstallOrigin(() =>
+ deps.getGhostManager().readApprovedInstallOriginStrict(ghostId)) === 'manual';
+ },
+ onPendingResidentMigrationSettled(ghostId: string, committed: boolean): void {
+ if (!stoppedForCommit.delete(ghostId) || committed) return;
+ deps.spawnIfResident?.(ghostId);
+ },
+ async preparePendingResidentForMigration(ghostId: string): Promise<boolean> {
+ if (deps.isAppSessionBoundaryPending()) return false;
+ const ownerScopeKey = deps.activeOwnerScopeKey();
+ const ghost = deps.getGhostManager().list().find((candidate) =>
+ candidate.namespaceState === 'pending' &&
+ installedGhostPhysicalRelId(candidate as InstalledGhost) === ghostId);
+ const runtimeId = ghost ? installedGhostStoragePart(ghost as InstalledGhost) : ghostId;
+ const state = deps.runtimeState(runtimeId);
+ const running = state === 'starting' || state === 'running' || state === 'stopping' ||
+ deps.nodeRuntimeRunning(runtimeId);
+ const resident = ghost !== undefined && (
+ isResidentBrowserGhost(ghost.manifest as GhostManifest) ||
+ ghost.manifest.node?.lifecycle === 'resident'
+ );
+ // A panel the user has open is not a resident. Leave it running and retry.
+ if (running && !resident) return false;
+ if (!running) return true;
+ if (deps.hasPendingWork(ghostId)) return false;
+ try {
+ if (deps.oauthLockExists(ghostId)) return false;
+ } catch {
+ return false;
+ }
+ if (!ghost) return false;
+ deps.stopRuntime(runtimeId);
+ await deps.stopNodeRuntime(runtimeId);
+ if (deps.activeOwnerScopeKey() !== ownerScopeKey || deps.isAppSessionBoundaryPending()) {
+ throw new Error('ghost owner changed while stopping a pending resident');
+ }
+ stoppedForCommit.add(ghostId);
+ return true;
+ },
+ classifyPendingNamespaceForGhost(ghostId: string, marketSyncCompleted = false): NamespaceClassification {
+ const builtin = deps.getGhostManager()
+ .list()
+ .some((ghost) => ghost.manifest.id === ghostId && ghost.builtin === true);
+ const marketRecord = readNamespaceMigrationMarketRecord(() =>
+ namespaceMigrationMarketRecordsForGhost(ghostId));
+ const state = deps.getAuthState();
+ const user = state.isAuthenticated ? state.user : null;
+ let currentOrganization: {
+ organizationId: string;
+ orgSlug: string | null;
+ pluginPrefix: string | null;
+ } | null = null;
+ if (user?.membershipKind === 'org' && user.orgId) {
+ const prefix = deps.createOrganizationPrefixStore(
+ deps.ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),
+ ).lookup(user.orgId);
+ currentOrganization = {
+ organizationId: user.orgId,
+ orgSlug: user.orgSlug ?? null,
+ pluginPrefix: prefix.kind === 'known' ? prefix.pluginPrefix ?? null : null,
+ };
+ }
+ const installOrigin = readNamespaceMigrationInstallOrigin(() =>
+ deps.getGhostManager().readApprovedInstallOriginStrict(ghostId));
+ return classifyNamespaceMigration({
+ ghostId,
+ builtin,
+ installOrigin,
+ marketSyncCompleted,
+ marketRecord,
+ currentOrganization,
+ });
+ },
+ readUnconfirmedConfirmationEvidence(record: PluginInstanceRecord): InstanceConfirmationEvidence {
+ const state = deps.getAuthState();
+ const user = state.isAuthenticated ? state.user : null;
+ const currentOrganization = user?.membershipKind === 'org' && user.orgId
+ ? { organizationId: user.orgId, orgSlug: user.orgSlug ?? null }
+ : null;
+ let packageSha256: string | null = null;
+ let forgeSelfTest = false;
+ try {
+ packageSha256 = deps.getGhostManager().approvedInstallEvidence(record.contentRelId)?.packageSha256 ?? null;
+ } catch {
+ packageSha256 = null;
+ }
+ try {
+ forgeSelfTest = deps.getGhostManager().readApprovedInstallOriginStrict(record.contentRelId) === 'agent-forge';
+ } catch {
+ forgeSelfTest = false;
+ }
+ let rows: Parameters<typeof buildUnconfirmedConfirmationEvidence>[0]['rows'];
+ try {
+ rows = namespaceMigrationMarketRecordsForGhost(record.ghostId);
+ } catch {
+ rows = undefined;
+ }
+ return buildUnconfirmedConfirmationEvidence({
+ rows, record, currentOrganization, packageSha256, forgeSelfTest,
+ });
+ },
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
index 27fd851c3f..64cc69d9a1 100644
--- a/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
@@ -16,6 +16,7 @@ import {
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { assertGhostPrefsWritable, relocateGhostPreferenceMaps } from './ghostPreferenceRelocation.js';
/** User-owned plugin task permission policy. A model source never grants authority. */
export function clampPluginTaskPermissionMode(value: unknown, fallback: GhostErrandPermissionMode = 'ask'): GhostErrandPermissionMode {
@@ -25,6 +26,12 @@ export function clampPluginTaskPermissionMode(value: unknown, fallback: GhostErr
const log = desktopMakerLogger.child('errand-prefs-store');
+export async function relocateGhostErrandPrefs(from: string, to: string): Promise<void> {
+ await relocateGhostPreferenceMaps('ghost-errand-prefs.json', ['errand', 'sessions'], from, to, () => {
+ store = createStore();
+ });
+}
+
/** 插件任务可选的 agent 种类(与 sessions.agent_kind 同词汇表)。 */
export const PLUGIN_TASK_AGENT_KINDS = ['cc', 'codex', 'pi'] as const;
export type PluginTaskAgentKind = (typeof PLUGIN_TASK_AGENT_KINDS)[number];
@@ -120,13 +127,18 @@ function normalize(raw: unknown): PluginTaskPrefs {
return { errand, sessions };
}
-const store = createOverrideSettingsFile<PluginTaskPrefs>({
- filePath: () => ownerScopedUserDataPath('ghost-errand-prefs.json'),
- defaults: DEFAULTS,
- normalize,
- log,
- label: 'ghost-errand-prefs',
-});
+function createStore() {
+ return createOverrideSettingsFile<PluginTaskPrefs>({
+ filePath: () => ownerScopedUserDataPath('ghost-errand-prefs.json'),
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'ghost-errand-prefs',
+ preserveUnreadableFile: true,
+ });
+}
+
+let store = createStore();
// Register owns the runtime catalog; configuration persistence never builds another picker.
let validateSelection: ((config: PluginTaskConfig) => Promise<void>) | null = null;
@@ -160,6 +172,7 @@ export function readPluginTaskConfig(ghostId: string): PluginTaskConfig {
* 形状粗筛,逐字段值域清洗统一在这里(单一执法点)。返回清洗后的落盘值。
*/
export function writePluginTaskConfig(ghostId: string, config: unknown): PluginTaskConfig {
+ assertGhostPrefsWritable('ghost-errand-prefs.json');
store.invalidateIfChanged();
const errand = { ...store.read().errand };
const cfg = config === null ? {} : normalizeConfig(config);
@@ -182,6 +195,7 @@ export function writeGhostErrandSessionId(
sessionId: string | null,
sessionKey?: string,
): void {
+ assertGhostPrefsWritable('ghost-errand-prefs.json');
store.invalidateIfChanged();
const key = sessionMapKey(ghostId, sessionKey);
const sessions = { ...store.read().sessions };
diff --git a/apps/desktop/src/main/cindy-brain/previewGate.ts b/apps/desktop/src/main/cindy-brain/previewGate.ts
index 2ce15da02e..10359fceff 100644
--- a/apps/desktop/src/main/cindy-brain/previewGate.ts
+++ b/apps/desktop/src/main/cindy-brain/previewGate.ts
@@ -21,7 +21,8 @@
* 真实组装在 cindy-brain/index.ts(账本/字节仓/webContents)。
*/
-import { GHOST_SCHEME } from '../../shared/ghost.js';
+import { GHOST_SCHEME, type GhostPanelMediaTarget } from '../../shared/ghost.js';
+import { parsePluginStoragePart } from '../../shared/pluginIdentity.js';
/** 面板导航到该路径前缀 = 预览请求(不是真页面,协议 handler 也不会服务它)。 */
export const GHOST_PREVIEW_PATH_PREFIX = '/preview/';
@@ -135,9 +136,15 @@ export type GhostPanelMediaResolved =
| { url: string; kind: 'image' }
| { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string };
+function ghostPanelMediaStoragePart(ghostId: string, target?: GhostPanelMediaTarget): string | null {
+ if (target && target.ghostId !== ghostId) return null;
+ const instanceId = target?.instanceId ?? ghostId;
+ return parsePluginStoragePart(instanceId)?.ghostId === ghostId ? instanceId : null;
+}
+
/**
* 面板媒体换发闸(拖拽引渡 / 右键菜单共用一条校验链):
- * 形状 → 账本归属(绑定 URL 里声明的意识 id)→ mime(账本为准,不信后缀)。
+ * 形状 → 账本归属(绑定 Main 核准的安装实例)→ mime(账本为准,不信后缀)。
* 图片 / 视频都放行:图片回 cindy-media 地址;视频额外解析指纹仓磁盘路径与
* 体积(路径解析或 stat 失败视同查无,统一 null)。
* 任一环不过返回 null,调用方统一 NOT_FOUND,不区分原因。
@@ -152,11 +159,13 @@ export async function resolveGhostPanelMedia(
/** 文件体积(附件托盘/发送链路要 size;文件缺失时 reject)。 */
statSize(absPath: string): Promise<number>;
},
+ target?: GhostPanelMediaTarget,
): Promise<GhostPanelMediaResolved | null> {
// 两用途同一形状预筛(图片 + 视频);保留 purpose 是给未来通道分化留位。
const parsed = purpose === 'menu' ? parseGhostPanelMediaUrl(uri) : parseGhostMediaHandoverUrl(uri);
if (!parsed) return null;
- if (!(await deps.ghostCanRead(parsed.hash, parsed.ghostId))) return null;
+ const instanceId = ghostPanelMediaStoragePart(parsed.ghostId, target);
+ if (!instanceId || !(await deps.ghostCanRead(parsed.hash, instanceId))) return null;
const info = await deps.getBlobInfo(parsed.hash);
const kind = !info
? null
@@ -334,23 +343,24 @@ export class GhostPreviewGate {
constructor(private readonly deps: GhostPreviewGateDeps) {}
- async request(params: {
- ghostId: string;
+ async request(params: GhostPanelMediaTarget & {
url: string;
/** 面板 webview 当前是否持有焦点(guestContents.isFocused)。 */
isPanelFocused: () => boolean;
}): Promise<GhostPreviewOutcome> {
const parsed = parseGhostPreviewUrl(params.url, params.ghostId);
if (!parsed) return { ok: false, reason: 'bad-url' };
+ const instanceId = ghostPanelMediaStoragePart(params.ghostId, params);
+ if (!instanceId) return { ok: false, reason: 'bad-url' };
// 焦点闸:用户不在面板上 = 不是用户点的,拒。lightbox 打开后焦点离开
// 面板,自动触发的连环预览在这里断链。
if (!params.isPanelFocused()) return { ok: false, reason: 'not-focused' };
const now = this.deps.now?.() ?? Date.now();
- const last = this.lastOpenedAt.get(params.ghostId);
+ const last = this.lastOpenedAt.get(instanceId);
if (last !== undefined && now - last < GHOST_PREVIEW_MIN_INTERVAL_MS) {
return { ok: false, reason: 'rate-limited' };
}
- if (!(await this.deps.ghostCanRead(parsed.hash, params.ghostId))) {
+ if (!(await this.deps.ghostCanRead(parsed.hash, instanceId))) {
return { ok: false, reason: 'not-owned' };
}
// ext/mime 以账本为准(URL 后缀只是预筛):图片/视频各归各的 lightbox
@@ -364,7 +374,7 @@ export class GhostPreviewGate {
? ('video' as const)
: null;
if (!info || !kind) return { ok: false, reason: 'not-media' };
- this.lastOpenedAt.set(params.ghostId, now);
+ this.lastOpenedAt.set(instanceId, now);
return { ok: true, src: this.deps.blobUrl(parsed.hash, info.ext), kind };
}
}
diff --git a/apps/desktop/src/main/cindy-brain/residentGhost.ts b/apps/desktop/src/main/cindy-brain/residentGhost.ts
index 717ce391e6..32e73fb968 100644
--- a/apps/desktop/src/main/cindy-brain/residentGhost.ts
+++ b/apps/desktop/src/main/cindy-brain/residentGhost.ts
@@ -8,10 +8,12 @@ export function isResidentBrowserGhost(manifest: GhostManifest): boolean {
/** Shared startup/enable/recovery path; runtime spawn retains its own authorization checks. */
export function spawnResidentGhost(ghost: InstalledGhost, deps: {
isAvailable: (id: string) => boolean;
+ allowPendingLegacy?: boolean;
startNode: (ghost: InstalledGhost) => Promise<unknown>;
spawnBrowser: (ghost: InstalledGhost) => Promise<{ ok: boolean; reason?: string }>;
warn: (message: string, fields: Record<string, unknown>) => void;
}): void {
+ // Pending confirmation keeps the old install running.
if (!ghost.enabled || !deps.isAvailable(ghost.manifest.id)) return;
// Node residency remains an independent declaration; routine events do not expand it.
if (ghost.manifest.node?.lifecycle === 'resident') {
diff --git a/apps/desktop/src/main/cindy-brain/routineSlot.ts b/apps/desktop/src/main/cindy-brain/routineSlot.ts
index 555d970e40..2e50b10fff 100644
--- a/apps/desktop/src/main/cindy-brain/routineSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/routineSlot.ts
@@ -1,4 +1,5 @@
import type { InstalledGhost } from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
import { parseRoutineEvent, type RoutineEngine } from '@cindy/maker-scheduler';
import { createLogger } from '../logger.js';
import { Buffer } from 'node:buffer';
@@ -100,7 +101,8 @@ export async function handleRoutineRequest(
const request = payload as Record<string, unknown>;
let release: (() => void) | undefined;
try {
- release = reserveRequest(ghost.manifest.id);
+ const instanceId = installedGhostStoragePart(ghost);
+ release = reserveRequest(instanceId);
validateRequestSize(request);
if (request.action !== 'status' && request.action !== 'publish')
return { ok: false, message: 'Unknown routine operation' };
@@ -110,7 +112,7 @@ export async function handleRoutineRequest(
const event = request.action === 'publish' ? parseRoutineEvent(request.event) : undefined;
const engine = await getEngine();
if (!isCurrent()) return { ok: false, message: 'Plugin owner or installation changed' };
- const sourceId = `plugin:${ghost.manifest.id}`;
+ const sourceId = `plugin:${instanceId}`;
if (request.action === 'status') {
engine.registerSource({
id: sourceId,
diff --git a/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts b/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts
index 7ea543c043..ad6f0f771b 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts
@@ -1,4 +1,5 @@
import type { InstalledGhost } from '../../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
/**
* GhostRuntime — 意识运行时状态机(docs/dev-rules/plugin-security-and-authoring.md)。
@@ -83,7 +84,7 @@ export class GhostRuntime {
* 即用户重新唤醒);stopping 拒绝(等熄灯完成)。
*/
async spawn(ghost: InstalledGhost): Promise<{ ok: true; state: GhostRuntimeState } | { ok: false; reason: string }> {
- const id = ghost.manifest.id;
+ const id = installedGhostStoragePart(ghost);
const entry = this.getEntry(id);
if (entry.state === 'starting' || entry.state === 'running') return { ok: true, state: entry.state };
if (entry.state === 'fused') return { ok: false, reason: '已熔断(反复崩溃),重新唤醒后可再试' };
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
index 3ce7dd08b4..378f790137 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
@@ -165,4 +165,22 @@ describe('GhostRuntime · 状态机', () => {
expect(runtime.stateOf('a')).toBe('off');
expect(runtime.stateOf('b')).toBe('off');
});
+
+ it('同 ghostId 的 root 与企业实例可同时 running', async () => {
+ const { runtime, handles } = setup();
+ const root = chipGhost('helper');
+ const enterprise: InstalledGhost = {
+ ...chipGhost('helper'),
+ namespace: 'acme',
+ dir: '/fake/brain/_ns/acme/helper',
+ };
+ expect((await runtime.spawn(root)).ok).toBe(true);
+ expect((await runtime.spawn(enterprise)).ok).toBe(true);
+ expect(handles.length).toBe(2);
+ expect(runtime.stateOf('helper')).toBe('running');
+ expect(runtime.stateOf('_ns__acme__helper')).toBe('running');
+ runtime.stop('helper');
+ expect(runtime.stateOf('helper')).toBe('off');
+ expect(runtime.stateOf('_ns__acme__helper')).toBe('running');
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
index e27de8b472..5d28699203 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createHash } from 'node:crypto';
const harness = vi.hoisted(() => {
let nextWebContentsId = 1;
@@ -10,8 +11,11 @@ const harness = vi.hoisted(() => {
protocolHandle: ReturnType<typeof vi.fn>;
protocolHandler?: (request: Request) => Promise<Response>;
downloadHandler?: (event: { preventDefault(): void }) => void;
+ session?: object;
+ fetch: ReturnType<typeof vi.fn>;
};
const sessions = new Map<string, RegisteredSession>();
+ const contents = new Map<number, { session: object; isDestroyed(): boolean; executeJavaScript: ReturnType<typeof vi.fn> }>();
return {
activeOwner: {
mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
@@ -19,9 +23,10 @@ const harness = vi.hoisted(() => {
generation: 1,
},
sessions,
+ contents,
fromPartition: vi.fn((partition: string) => {
const existing = sessions.get(partition);
- if (existing) return existing;
+ if (existing) return existing.session;
const created: RegisteredSession = {
permissionRequest: vi.fn(),
permissionCheck: vi.fn(),
@@ -29,31 +34,35 @@ const harness = vi.hoisted(() => {
if (event === 'will-download') created.downloadHandler = handler;
}),
beforeRequest: vi.fn(),
+ fetch: vi.fn(async (url: string, options: RequestInit) => created.protocolHandler
+ ? created.protocolHandler(new Request(url, options)) : new Response(null, { status: 404 })),
protocolHandle: vi.fn(
(_scheme: string, handler: (request: Request) => Promise<Response>) => {
created.protocolHandler = handler;
},
),
};
- sessions.set(partition, created);
- return {
+ created.session = {
setPermissionRequestHandler: created.permissionRequest,
setPermissionCheckHandler: created.permissionCheck,
on: created.on,
webRequest: { onBeforeRequest: created.beforeRequest },
protocol: { handle: created.protocolHandle },
+ fetch: created.fetch,
};
+ sessions.set(partition, created);
+ return created.session;
}),
browserWindowOptions: [] as Array<Record<string, unknown>>,
BrowserWindow: vi.fn(function BrowserWindow(options: Record<string, unknown>) {
harness.browserWindowOptions.push(options);
+ const preferences = options.webPreferences as { partition: string };
+ const contents = { id: nextWebContentsId++, session: harness.fromPartition(preferences.partition)!,
+ on: vi.fn(), isDestroyed: vi.fn(() => false), forcefullyCrashRenderer: vi.fn(),
+ executeJavaScript: vi.fn(async () => []) };
+ harness.contents.set(contents.id, contents);
return {
- webContents: {
- id: nextWebContentsId++,
- on: vi.fn(),
- isDestroyed: vi.fn(() => false),
- forcefullyCrashRenderer: vi.fn(),
- },
+ webContents: contents,
loadURL: vi.fn().mockResolvedValue(undefined),
isDestroyed: vi.fn(() => false),
destroy: vi.fn(),
@@ -70,7 +79,7 @@ const kvEndpoint = vi.hoisted(() => ({
vi.mock('electron', () => ({
BrowserWindow: harness.BrowserWindow,
session: { fromPartition: harness.fromPartition },
- webContents: { fromId: vi.fn(() => null) },
+ webContents: { fromId: vi.fn((id: number) => harness.contents.get(id) ?? null) },
}));
vi.mock('node:fs', () => ({ createReadStream: vi.fn() }));
@@ -103,12 +112,24 @@ import type {
GhostMediaModelsResult,
InstalledGhost,
} from '../../../../shared/ghost';
+import { GhostConnectionManager } from '../../ghostConnections.js';
+import { GhostOauthAccountManager } from '../../ghostOauthAccounts.js';
+import { handleGhostConnectionsRequest } from '../ghostConnectionsEndpoint.js';
+import { handleGhostOauthRequest } from '../ghostOauthEndpoint.js';
+import { handleGhostSecretsRequest } from '../ghostSecretsEndpoint.js';
+import { ownerScopedGhostPartitionForInstalledGhost } from '../../ghostWebviewPartition.js';
import {
electronSandboxAdapter,
+ invokeGhostMobileRelay,
+ fetchGhostMobilePage,
ensureGhostProtocolRegistered,
+ revokeLegacyGhostProtocolPartition,
setGhostAppContextProvider,
setGhostAgentModelsProvider,
setGhostKvStore,
+ setGhostConnectionsHandler,
+ setGhostOauthHandler,
+ setGhostSecretsHandler,
setGhostMediaModelsProvider,
} from '../electronSandboxAdapter';
@@ -130,17 +151,288 @@ function ghost(id: string): InstalledGhost {
};
}
+function approvedPartition(base: string, generation = 1, dir?: string): string {
+ const storagePart = base.split(':')[3];
+ const ghostId = storagePart.startsWith('_ns__') ? storagePart.split('__')[2] : storagePart;
+ const receipt = createHash('sha256')
+ .update(JSON.stringify(['approved:00000000-0000-4000-8000-000000000001', dir ?? '/plugins/' + ghostId, generation]))
+ .digest('hex');
+ return base + ':receipt:' + receipt;
+}
+
beforeEach(() => {
harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-a', generation: 1 };
harness.sessions.clear();
+ harness.contents.clear();
harness.fromPartition.mockClear();
harness.BrowserWindow.mockClear();
harness.browserWindowOptions.length = 0;
kvEndpoint.handleGhostKvRequest.mockReset();
kvEndpoint.readBoundedBodyText.mockReset();
+ setGhostKvStore({ read: () => ({}), write: vi.fn(), captureTarget: () => 'approved', isTargetCurrent: () => true });
});
describe('electronSandboxAdapter owner partition', () => {
+ it.each([undefined, null, 'acme'])('uses the running receipt partition for mobile relay and fetch (%s)', async (namespace) => {
+ const installed = { ...ghost('mobile-' + (namespace ?? 'root')),
+ ...(namespace === undefined ? {} : { namespace }),
+ dir: namespace === undefined ? '/plugins/mobile-root' : '/plugins/_ns/' + (namespace ?? '_root') + '/mobile-' + (namespace ?? 'root') };
+ electronSandboxAdapter.create(installed);
+ await expect(invokeGhostMobileRelay(installed, { op: 'connect', pageId: 'phone', channels: [] })).resolves.toEqual([]);
+ const contents = [...harness.contents.values()][0];
+ expect(contents.executeJavaScript).toHaveBeenCalledOnce();
+ await expect(fetchGhostMobilePage(installed, '/gallery', 'GET')).resolves.toMatchObject({ status: 200 });
+ const partition = ownerScopedGhostPartitionForInstalledGhost(installed, harness.activeOwner)!;
+ expect(harness.sessions.get(partition)!.fetch).toHaveBeenCalledOnce();
+ harness.activeOwner.generation++;
+ await expect(invokeGhostMobileRelay(installed, { op: 'poll', pageId: 'phone', after: 0 })).rejects.toThrow('PLUGIN_PAGE_UNAVAILABLE');
+ expect(contents.executeJavaScript).toHaveBeenCalledOnce();
+ });
+ it('rejects stale registration before reading the request URL or body', async () => {
+ let target = 'original';
+ setGhostKvStore({ read: () => ({}), write: vi.fn(), captureTarget: () => target, isTargetCurrent: (_id, expected) => expected === target });
+ const installed = ghost('stale-registration');
+ ensureGhostProtocolRegistered(installed);
+ const handler = harness.sessions.get(ownerScopedGhostPartitionForInstalledGhost(installed, harness.activeOwner)!)!.protocolHandler!;
+ target = 'replacement';
+ const readUrl = vi.fn(() => 'cindy-ghost://' + installed.manifest.id + '/kv');
+ const request = { get url() { return readUrl(); } } as Request;
+ expect((await handler(request)).status).toBe(403);
+ expect(readUrl).not.toHaveBeenCalled();
+ expect(kvEndpoint.readBoundedBodyText).not.toHaveBeenCalled();
+ });
+
+ it.each([undefined, { state: 'legacy-unapproved' as const }, { state: 'invalid' as const }])('denies unsigned or nonapproved registrations without a trusted target (%s)', async (approval) => {
+ setGhostKvStore({ read: () => ({}), write: vi.fn(), captureTarget: () => null, isTargetCurrent: () => true });
+ const installed = { ...ghost('unapproved-' + (approval?.state ?? 'missing')), approval } as InstalledGhost;
+ ensureGhostProtocolRegistered(installed);
+ const handler = harness.sessions.get(ownerScopedGhostPartitionForInstalledGhost(installed, harness.activeOwner)!)!.protocolHandler!;
+ expect((await handler(new Request('cindy-ghost://' + installed.manifest.id + '/kv', { method: 'PUT' }))).status).toBe(403);
+ expect(kvEndpoint.readBoundedBodyText).not.toHaveBeenCalled();
+ });
+
+ it('keeps old A denied and new A usable after an owner generation ABA', async () => {
+ const installed = ghost('owner-aba');
+ const currentTarget = () => JSON.stringify([harness.activeOwner.mode, harness.activeOwner.dataOwnerId, harness.activeOwner.generation, installed.dir, installed.approval]);
+ setGhostKvStore({ read: () => ({}), write: vi.fn(), captureTarget: currentTarget, isTargetCurrent: (_id, expected) => currentTarget() === expected });
+ ensureGhostProtocolRegistered(installed);
+ const firstPartition = ownerScopedGhostPartitionForInstalledGhost(installed, harness.activeOwner)!;
+ const oldHandler = harness.sessions.get(firstPartition)!.protocolHandler!;
+ harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
+ expect((await oldHandler(new Request('cindy-ghost://owner-aba/'))).status).toBe(403);
+ harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-a', generation: 3 };
+ ensureGhostProtocolRegistered(installed);
+ const currentPartition = ownerScopedGhostPartitionForInstalledGhost(installed, harness.activeOwner)!;
+ expect((await oldHandler(new Request('cindy-ghost://owner-aba/'))).status).toBe(403);
+ expect((await harness.sessions.get(currentPartition)!.protocolHandler!(new Request('cindy-ghost://owner-aba/'))).status).toBe(200);
+ expect(currentPartition).not.toBe(firstPartition);
+ });
+
+ it('rejects a delayed read response after its registered receipt changes', async () => {
+ let target = 'original';
+ setGhostKvStore({ read: () => ({}), write: vi.fn(), captureTarget: () => target, isTargetCurrent: (_id, expected) => target === expected });
+ let finishProvider!: (result: GhostMediaModelsResult) => void;
+ const provider = vi.fn(() => new Promise<GhostMediaModelsResult>((resolve) => { finishProvider = resolve; }));
+ setGhostMediaModelsProvider(provider);
+ const installed = ghost('delayed-receipt-read');
+ ensureGhostProtocolRegistered(installed);
+ const handler = harness.sessions.get(ownerScopedGhostPartitionForInstalledGhost(installed, harness.activeOwner)!)!.protocolHandler!;
+ const pending = handler(new Request('cindy-ghost://delayed-receipt-read/media-models?type=image'));
+ expect(provider).toHaveBeenCalledOnce();
+ target = 'replacement';
+ finishProvider({ ok: true, type: 'image', models: [], defaultModelId: null, defaultProviderId: null });
+ expect((await pending).status).toBe(403);
+ });
+
+ it('denies a fresh old-session PUT after same-version receipt replacement and permits the new session', async () => {
+ const endpoint = await vi.importActual<typeof import('../ghostKvEndpoint.js')>('../ghostKvEndpoint.js');
+ kvEndpoint.handleGhostKvRequest.mockImplementation(endpoint.handleGhostKvRequest);
+ kvEndpoint.readBoundedBodyText.mockResolvedValue(JSON.stringify({ source: 'current' }));
+ let target = 'receipt-original';
+ const write = vi.fn();
+ const captureTarget = vi.fn(() => target);
+ setGhostKvStore({ read: () => ({}), write, captureTarget, isTargetCurrent: (_id, expected) => expected === target });
+ const original = ghost('fresh-receipt-write');
+ ensureGhostProtocolRegistered(original);
+ const oldPartition = ownerScopedGhostPartitionForInstalledGhost(original, harness.activeOwner)!;
+ const oldHandler = harness.sessions.get(oldPartition)!.protocolHandler!;
+ target = 'receipt-replacement';
+ const replacement = { ...original, approval: { state: 'approved' as const, revision: '00000000-0000-4000-8000-000000000002' } };
+ ensureGhostProtocolRegistered(replacement);
+ expect((await oldHandler(new Request('cindy-ghost://fresh-receipt-write/kv', { method: 'PUT' }))).status).toBe(403);
+ expect(write).not.toHaveBeenCalled();
+ expect(kvEndpoint.readBoundedBodyText).not.toHaveBeenCalled();
+ const newPartition = ownerScopedGhostPartitionForInstalledGhost(replacement, harness.activeOwner)!;
+ expect(newPartition).not.toBe(oldPartition);
+ expect((await harness.sessions.get(newPartition)!.protocolHandler!(new Request('cindy-ghost://fresh-receipt-write/kv', { method: 'PUT' }))).status).toBe(204);
+ expect(write).toHaveBeenCalledExactlyOnceWith('fresh-receipt-write', { source: 'current' });
+ expect(captureTarget).toHaveBeenCalledTimes(2);
+ });
+
+ const credentialRoutes = [
+ ['/secrets/token', 'PUT', '{"value":"fake-old-secret"}', 204],
+ ['/oauth/token/client', 'PUT', '{"clientId":"fake-old-client"}', 204],
+ ['/connections/token', 'POST', '{"host":"api.example.com","token":"fake-old-token"}', 200],
+ ] as const;
+
+ it.each(credentialRoutes.flatMap((route) =>
+ (['replacement', 'invalid', 'owner', 'unchanged'] as const).map((transition) => [...route, transition] as const),
+ ))('guards %s during a pending body (%s %s %s %s)', async (pathname, method, text, successStatus, transition) => {
+ let currentTarget: string | null = 'approved-original';
+ const captureTarget = vi.fn(() => currentTarget);
+ const store = vi.fn(() => true);
+ const remove = vi.fn();
+ const onChanged = vi.fn();
+ const vault = { read: () => null, store, remove };
+ const oauthManager = new GhostOauthAccountManager({
+ vault, openExternal: vi.fn(), fetchImpl: vi.fn() as unknown as typeof fetch,
+ });
+ const connectionManager = new GhostConnectionManager({ vault: { ...vault, readTail: () => null } });
+ setGhostKvStore({
+ read: vi.fn(() => ({})), write: vi.fn(), captureTarget,
+ isTargetCurrent: (_ghostId, expected) => currentTarget === expected,
+ });
+ setGhostSecretsHandler((args) => handleGhostSecretsRequest({
+ ...args, userSecretKeys: ['token'],
+ vault: { ...vault, saved: () => false, tail: () => null }, onStored: onChanged,
+ }));
+ setGhostOauthHandler((args) => handleGhostOauthRequest({
+ ...args, manager: oauthManager, onChanged,
+ oauthSecrets: new Map([['token', { authorizeUrl: 'https://api.example.com/auth', tokenUrl: 'https://api.example.com/token', scopes: [] }]]),
+ }));
+ setGhostConnectionsHandler((args) => handleGhostConnectionsRequest({
+ ...args, manager: connectionManager, onChanged, onAdded: onChanged,
+ decls: new Map([['token', { label: 'API', maxConnections: 2 }]]), confirmAddHost: async () => true,
+ }));
+ let finishBody!: (body: string) => void;
+ kvEndpoint.readBoundedBodyText.mockReturnValue(new Promise<string>((resolve) => { finishBody = resolve; }));
+ const installed = ghost('cred-' + pathname.split('/')[1].slice(0, 4) + '-' + transition);
+ ensureGhostProtocolRegistered(installed);
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:' + installed.manifest.id))!.protocolHandler!;
+ const pending = handler(new Request('cindy-ghost://' + installed.manifest.id + pathname, { method }));
+ if (transition === 'replacement') currentTarget = 'approved-replacement';
+ if (transition === 'invalid') currentTarget = null;
+ if (transition === 'owner') harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
+ finishBody(text);
+ expect((await pending).status).toBe(transition === 'unchanged' ? successStatus : 403);
+ if (transition === 'unchanged') {
+ expect(store).toHaveBeenCalled();
+ expect(onChanged).toHaveBeenCalled();
+ } else {
+ expect(store).not.toHaveBeenCalled();
+ expect(onChanged).not.toHaveBeenCalled();
+ }
+ expect(captureTarget).toHaveBeenCalledExactlyOnceWith(installed.manifest.id);
+ });
+
+ it.each(['replacement', 'invalid', 'owner'] as const)('rejects an old KV PUT after %s while its body is pending', async (transition) => {
+ const endpoint = await vi.importActual<typeof import('../ghostKvEndpoint.js')>('../ghostKvEndpoint.js');
+ kvEndpoint.handleGhostKvRequest.mockImplementation(endpoint.handleGhostKvRequest);
+ let finishBody!: (body: string) => void;
+ const body = new Promise<string>((resolve) => { finishBody = resolve; });
+ kvEndpoint.readBoundedBodyText.mockReturnValue(body);
+ const installed = { ...ghost('kv-late-' + transition), namespace: 'acme' };
+ let target: string | null = 'approved-original';
+ const captureTarget = vi.fn(() => target);
+ const write = vi.fn();
+ setGhostKvStore({
+ read: vi.fn(() => ({ source: 'replacement' })), write, captureTarget,
+ isTargetCurrent: (_ghostId, expected) => target === expected,
+ });
+ ensureGhostProtocolRegistered(installed);
+ const partition = approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:' + installed.manifest.id + ':ns:acme');
+ const handler = harness.sessions.get(partition)!.protocolHandler!;
+ const pending = handler(new Request('cindy-ghost://' + installed.manifest.id + '/kv', { method: 'PUT' }));
+ if (transition === 'replacement') target = 'approved-replacement';
+ if (transition === 'invalid') target = null;
+ if (transition === 'owner') harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
+ finishBody('{"source":"old"}');
+ expect((await pending).status).toBe(403);
+ expect(write).not.toHaveBeenCalled();
+ expect(captureTarget).toHaveBeenCalledTimes(1);
+ expect(captureTarget).toHaveBeenNthCalledWith(1, installed.manifest.id);
+ });
+
+ it.each([undefined, null])('rejects an unavailable KV install target (%s) before body reading', async (target) => {
+ const endpoint = await vi.importActual<typeof import('../ghostKvEndpoint.js')>('../ghostKvEndpoint.js');
+ kvEndpoint.handleGhostKvRequest.mockImplementation(endpoint.handleGhostKvRequest);
+ const write = vi.fn();
+ setGhostKvStore({
+ read: vi.fn(() => ({})), write, captureTarget: () => target, isTargetCurrent: () => true,
+ });
+ const installed = ghost('kv-unavailable-' + String(target));
+ ensureGhostProtocolRegistered(installed);
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:' + installed.manifest.id))!.protocolHandler!;
+ expect((await handler(new Request('cindy-ghost://' + installed.manifest.id + '/kv', { method: 'PUT' }))).status).toBe(403);
+ expect(kvEndpoint.readBoundedBodyText).not.toHaveBeenCalled();
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it('allows a delayed KV PUT when the captured install remains current', async () => {
+ const endpoint = await vi.importActual<typeof import('../ghostKvEndpoint.js')>('../ghostKvEndpoint.js');
+ kvEndpoint.handleGhostKvRequest.mockImplementation(endpoint.handleGhostKvRequest);
+ let finishBody!: (body: string) => void;
+ kvEndpoint.readBoundedBodyText.mockReturnValue(new Promise<string>((resolve) => { finishBody = resolve; }));
+ const captureTarget = vi.fn(() => 'approved-original');
+ const write = vi.fn();
+ setGhostKvStore({
+ read: vi.fn(() => ({})), write, captureTarget,
+ isTargetCurrent: (_ghostId, expected) => expected === 'approved-original',
+ });
+ ensureGhostProtocolRegistered(ghost('kv-unchanged'));
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:kv-unchanged'))!.protocolHandler!;
+ const pending = handler(new Request('cindy-ghost://kv-unchanged/kv', { method: 'PUT' }));
+ finishBody('{"source":"current"}');
+ expect((await pending).status).toBe(204);
+ expect(write).toHaveBeenCalledExactlyOnceWith('kv-unchanged', { source: 'current' });
+ expect(captureTarget).toHaveBeenCalledExactlyOnceWith('kv-unchanged');
+ });
+
+ it('keeps an in-place organization session on its directory key and separates a later root install', () => {
+ const organization = { ...ghost('shared'), namespace: 'acme' };
+ ensureGhostProtocolRegistered(organization);
+ expect(harness.sessions.has(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:shared:ns:acme'))).toBe(true);
+ expect(harness.sessions.has(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:_ns__acme__shared:ns:acme'))).toBe(false);
+ ensureGhostProtocolRegistered({ ...ghost('shared'), namespace: null, dir: '/plugins/_ns/_root/shared' });
+ expect(harness.sessions.size).toBe(2);
+ expect(harness.sessions.has(approvedPartition(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:_root__shared:root',
+ 1,
+ '/plugins/_ns/_root/shared',
+ ))).toBe(true);
+ });
+
+ it('reuses the directory key for an in-place stamp but opens a separate session per committed namespace', () => {
+ ensureGhostProtocolRegistered(ghost('legacy-shared'));
+ ensureGhostProtocolRegistered({ ...ghost('legacy-shared'), namespace: 'acme' });
+ ensureGhostProtocolRegistered({ ...ghost('legacy-shared'), namespace: null });
+ expect([...harness.sessions.keys()]).toEqual([
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:legacy-shared'),
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:legacy-shared:ns:acme'),
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:legacy-shared:root'),
+ ]);
+ });
+
+ it('refuses new protocol requests from a legacy WebView after namespace commit', async () => {
+ ensureGhostProtocolRegistered(ghost('committed-legacy'));
+ const oldHandler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:committed-legacy'))?.protocolHandler;
+ revokeLegacyGhostProtocolPartition('committed-legacy');
+ expect((await oldHandler?.(new Request('cindy-ghost://committed-legacy/kv')))?.status).toBe(403);
+ expect(kvEndpoint.handleGhostKvRequest).not.toHaveBeenCalled();
+ ensureGhostProtocolRegistered({ ...ghost('committed-legacy'), namespace: null });
+ const rootHandler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:committed-legacy:root'))?.protocolHandler;
+ expect((await rootHandler?.(new Request('cindy-ghost://committed-legacy/')))?.status).toBe(200);
+ });
+
+ it('serves an in-place organization commit from a fresh session while the legacy one stays revoked', async () => {
+ ensureGhostProtocolRegistered(ghost('committed-org'));
+ const oldHandler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:committed-org'))?.protocolHandler;
+ revokeLegacyGhostProtocolPartition('committed-org');
+ ensureGhostProtocolRegistered({ ...ghost('committed-org'), namespace: 'acme' });
+ const orgHandler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:committed-org:ns:acme'))?.protocolHandler;
+ expect((await orgHandler?.(new Request('cindy-ghost://committed-org/')))?.status).toBe(200);
+ expect((await oldHandler?.(new Request('cindy-ghost://committed-org/')))?.status).toBe(403);
+ });
it('同 ghostId 的不同 owner 使用不同的非持久 session,并显式拒绝权限和下载', () => {
const installed = ghost('same-ghost');
ensureGhostProtocolRegistered(installed, {
@@ -155,10 +447,10 @@ describe('electronSandboxAdapter owner partition', () => {
});
const sessionA = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-a:same-ghost',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:same-ghost'),
);
const sessionB = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-b:same-ghost',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-b:same-ghost', 2),
);
for (const registered of [sessionA, sessionB]) {
expect(registered).toBeDefined();
@@ -172,7 +464,7 @@ describe('electronSandboxAdapter owner partition', () => {
}
});
- it('同 owner 只增加 generation 时复用原 partition', () => {
+ it('同 owner 增加 generation 时使用新 partition', () => {
const installed = ghost('generation-stable');
ensureGhostProtocolRegistered(installed, {
mode: 'cloud',
@@ -185,14 +477,18 @@ describe('electronSandboxAdapter owner partition', () => {
generation: 2,
});
- expect(harness.fromPartition).toHaveBeenCalledOnce();
+ expect(harness.fromPartition).toHaveBeenCalledTimes(2);
expect([...harness.sessions.keys()]).toEqual([
- 'cindy-ghost-owner:cloud:opaque-owner-a:generation-stable',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:generation-stable'),
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:generation-stable', 2),
]);
});
it('owner 切换后旧 Session 的新请求在路由和业务读取前返回 403', async () => {
- const store = { read: vi.fn(() => ({})), write: vi.fn() };
+ const store = {
+ read: vi.fn(() => ({})), write: vi.fn(),
+ captureTarget: () => 'approved', isTargetCurrent: () => true,
+ };
setGhostKvStore(store);
ensureGhostProtocolRegistered(ghost('stale-request'), {
mode: 'cloud',
@@ -200,7 +496,7 @@ describe('electronSandboxAdapter owner partition', () => {
generation: 1,
});
const sessionA = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-a:stale-request',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:stale-request'),
);
const routeRead = vi.fn(() => 'cindy-ghost://stale-request/kv');
const request = {
@@ -223,7 +519,7 @@ describe('electronSandboxAdapter owner partition', () => {
expect(store.write).not.toHaveBeenCalled();
});
- it('同 owner generation 变化后旧 Session 仍可走静态与能力路由', async () => {
+ it('同 owner generation 变化后旧 Session 拒绝静态与能力路由', async () => {
const appContext: GhostAppContextResult = {
ok: true,
context: { region: 'global', locale: 'en' },
@@ -237,7 +533,7 @@ describe('electronSandboxAdapter owner partition', () => {
});
harness.activeOwner.generation = 99;
const registered = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-a:active-request',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:active-request'),
);
const bootResponse = await registered?.protocolHandler?.(
@@ -247,9 +543,9 @@ describe('electronSandboxAdapter owner partition', () => {
new Request('cindy-ghost://active-request/app-context'),
);
- expect(bootResponse?.status).toBe(200);
- expect(contextResponse?.status).toBe(200);
- expect(appContextProvider).toHaveBeenCalledOnce();
+ expect(bootResponse?.status).toBe(403);
+ expect(contextResponse?.status).toBe(403);
+ expect(appContextProvider).not.toHaveBeenCalled();
});
it('boot 与任意插件 HTML 响应统一允许 HTTPS 图片,其他 CSP 能力不放宽', async () => {
@@ -258,7 +554,7 @@ describe('electronSandboxAdapter owner partition', () => {
installed.manifest.mainView = { html: 'main-view.html' };
ensureGhostProtocolRegistered(installed);
const registered = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-a:https-image-csp',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:https-image-csp'),
);
for (const pathname of ['/', '/panel.html', '/settings.html', '/main-view.html', '/other.html']) {
@@ -278,7 +574,7 @@ describe('electronSandboxAdapter owner partition', () => {
it('插件 session 只额外放行 HTTPS image,同源资源保持放行', () => {
ensureGhostProtocolRegistered(ghost('https-image-network'));
const registered = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-a:https-image-network',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:https-image-network'),
);
const handler = registered?.beforeRequest.mock.calls[0]?.[0] as
| ((
@@ -322,14 +618,14 @@ describe('electronSandboxAdapter owner partition', () => {
ensureGhostProtocolRegistered(installed);
const registered = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-a:https-image-listener-once',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:https-image-listener-once'),
);
expect(harness.fromPartition).toHaveBeenCalledOnce();
expect(registered?.beforeRequest).toHaveBeenCalledOnce();
expect(registered?.protocolHandle).toHaveBeenCalledOnce();
});
- it('请求已进入 handler 后切换 owner 不取消或重新检查在途 provider', async () => {
+ it('请求已进入 handler 后切换 owner 拒绝在途 provider 的响应', async () => {
let finishProvider!: (result: GhostMediaModelsResult) => void;
const provider = vi.fn(
() =>
@@ -344,7 +640,7 @@ describe('electronSandboxAdapter owner partition', () => {
generation: 1,
});
const registered = harness.sessions.get(
- 'cindy-ghost-owner:cloud:opaque-owner-a:inflight-request',
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:inflight-request'),
);
const pending = registered?.protocolHandler?.(
new Request('cindy-ghost://inflight-request/media-models?type=image'),
@@ -362,8 +658,7 @@ describe('electronSandboxAdapter owner partition', () => {
finishProvider(outcome);
const response = await pending;
- expect(response?.status).toBe(200);
- await expect(response?.json()).resolves.toEqual(outcome);
+ expect(response?.status).toBe(403);
});
it('相同 partition 不能被不同 owner snapshot 重新认领', () => {
@@ -378,7 +673,7 @@ describe('electronSandboxAdapter owner partition', () => {
ensureGhostProtocolRegistered(installed, {
mode: 'cloud',
dataOwnerId: 'collision-b',
- generation: 2,
+ generation: 1,
}),
).toThrow('ghost protocol partition already belongs to a different data owner');
});
@@ -388,7 +683,7 @@ describe('electronSandboxAdapter owner partition', () => {
const handle = electronSandboxAdapter.create(ghost('panel-owner'));
expect(harness.browserWindowOptions[0]?.webPreferences).toMatchObject({
- partition: 'cindy-ghost-owner:local:opaque-local-owner:panel-owner',
+ partition: approvedPartition('cindy-ghost-owner:local:opaque-local-owner:panel-owner', 4),
});
expect(
(harness.browserWindowOptions[0]?.webPreferences as { partition: string }).partition,
@@ -398,11 +693,19 @@ describe('electronSandboxAdapter owner partition', () => {
});
describe('read-only agent model directory', () => {
+ it('identifies the organization instance when a root plugin has the same id', async () => {
+ const provider = vi.fn().mockResolvedValue({ ok: true, models: [] });
+ setGhostAgentModelsProvider(provider);
+ ensureGhostProtocolRegistered({ ...ghost('shared-models'), namespace: 'acme', dir: '/plugins/_ns/acme/shared-models' });
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:_ns__acme__shared-models:ns:acme', 1, '/plugins/_ns/acme/shared-models'))?.protocolHandler;
+ expect((await handler?.(new Request('cindy-ghost://shared-models/agent-models')))?.status).toBe(200);
+ expect(provider).toHaveBeenCalledWith('_ns__acme__shared-models');
+ });
it('serves no-store metadata without accepting writes or query overrides', async () => {
const provider = vi.fn().mockResolvedValue({ ok: true, models: [] });
setGhostAgentModelsProvider(provider);
ensureGhostProtocolRegistered(ghost('agent-directory'));
- const handler = harness.sessions.get('cindy-ghost-owner:cloud:opaque-owner-a:agent-directory')!.protocolHandler!;
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:agent-directory'))!.protocolHandler!;
for (const [url, method, status] of [
['agent-directory/agent-models', 'GET', 200],
['agent-directory/agent-models', 'POST', 405],
@@ -425,7 +728,7 @@ describe('read-only agent model directory', () => {
let finish!: (value: { ok: true; models: [] }) => void;
setGhostAgentModelsProvider(() => new Promise(resolve => { finish = resolve; }));
ensureGhostProtocolRegistered(ghost('agent-owner'));
- const handler = harness.sessions.get('cindy-ghost-owner:cloud:opaque-owner-a:agent-owner')!.protocolHandler!;
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:agent-owner'))!.protocolHandler!;
const pending = handler(new Request('cindy-ghost://agent-owner/agent-models'));
harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
finish({ ok: true, models: [] });
@@ -438,7 +741,7 @@ it('rejects failed in-flight model reads after owner changes', async () => {
let reject!: (error: Error) => void;
setGhostAgentModelsProvider(() => new Promise((_resolve, fail) => { reject = fail; }));
ensureGhostProtocolRegistered(ghost('agent-rejected-owner'));
- const handler = harness.sessions.get('cindy-ghost-owner:cloud:opaque-owner-a:agent-rejected-owner')!.protocolHandler!;
+ const handler = harness.sessions.get(approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:agent-rejected-owner'))!.protocolHandler!;
const pending = handler(new Request('cindy-ghost://agent-rejected-owner/agent-models'));
harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
reject(new Error('old visibility mirror cleared'));
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostConnectionsEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostConnectionsEndpoint.test.ts
index 36913933f0..9f79ce2047 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostConnectionsEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostConnectionsEndpoint.test.ts
@@ -34,6 +34,75 @@ function makeVault(): GhostConnectionsVault {
const G = 'cindy-gitlab';
const DECLS = new Map([['gitlab', { label: 'GitLab 实例', maxConnections: 2 }]]);
+describe('connection install target guard', () => {
+ it.each(['body', 'confirmation'] as const)('rejects a source replacement during %s without writing or notifying', async (transition) => {
+ const manager = new GhostConnectionManager({ vault: makeVault() });
+ const upsert = vi.spyOn(manager, 'upsert');
+ const onChanged = vi.fn();
+ const onAdded = vi.fn();
+ let current = true;
+ const confirmAddHost = vi.fn(async () => { current = false; return true; });
+ const result = await handleGhostConnectionsRequest({
+ method: 'POST', pathname: '/connections/gitlab', ghostId: G, decls: DECLS,
+ manager, onChanged, onAdded, isCurrent: () => current,
+ readBodyText: async () => {
+ if (transition === 'body') current = false;
+ return '{"host":"gitlab.example.com","token":"fake-old-token"}';
+ },
+ confirmAddHost,
+ });
+ expect(result).toEqual({ status: 403 });
+ expect(upsert).not.toHaveBeenCalled();
+ expect(manager.list(G, 'gitlab')).toEqual([]);
+ expect(onChanged).not.toHaveBeenCalled();
+ expect(onAdded).not.toHaveBeenCalled();
+ if (transition === 'body') expect(confirmAddHost).not.toHaveBeenCalled();
+ });
+
+ it('rejects a late default selection without changing the replacement connection', async () => {
+ const manager = new GhostConnectionManager({ vault: makeVault() });
+ const setDefault = vi.spyOn(manager, 'setDefault');
+ const onChanged = vi.fn();
+ let current = true;
+ expect(await handleGhostConnectionsRequest({
+ method: 'POST', pathname: '/connections/gitlab/default', ghostId: G, decls: DECLS,
+ manager, onChanged, isCurrent: () => current, confirmAddHost: async () => true,
+ readBodyText: async () => { current = false; return '{"connectionId":"old-id"}'; },
+ })).toEqual({ status: 403 });
+ expect(setDefault).not.toHaveBeenCalled();
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it('rejects connection deletion from an invalid install', async () => {
+ const manager = new GhostConnectionManager({ vault: makeVault() });
+ const remove = vi.spyOn(manager, 'remove');
+ const onChanged = vi.fn();
+ expect(await handleGhostConnectionsRequest({
+ method: 'DELETE', pathname: '/connections/gitlab/old-id', ghostId: G, decls: DECLS,
+ manager, onChanged, isCurrent: () => false, confirmAddHost: async () => true,
+ readBodyText: vi.fn(),
+ })).toEqual({ status: 403 });
+ expect(remove).not.toHaveBeenCalled();
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it('still confirms and writes for the unchanged current install', async () => {
+ const manager = new GhostConnectionManager({ vault: makeVault() });
+ const confirmAddHost = vi.fn(async () => true);
+ const onChanged = vi.fn();
+ const result = await handleGhostConnectionsRequest({
+ method: 'POST', pathname: '/connections/gitlab', ghostId: G, decls: DECLS,
+ manager, onChanged, isCurrent: () => true, confirmAddHost,
+ readBodyText: async () => '{"host":"gitlab.example.com","token":"fake-current-token"}',
+ });
+ expect(result.status).toBe(200);
+ expect(JSON.parse(result.body!)).toMatchObject({ ok: true });
+ expect(confirmAddHost).toHaveBeenCalledExactlyOnceWith('GitLab 实例', 'gitlab.example.com');
+ expect(manager.list(G, 'gitlab')).toHaveLength(1);
+ expect(onChanged).toHaveBeenCalledExactlyOnceWith('gitlab');
+ });
+});
+
function call(args: {
method: string;
pathname: string;
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostKvEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostKvEndpoint.test.ts
index 3129e4522f..d3499b8d0b 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostKvEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostKvEndpoint.test.ts
@@ -29,6 +29,47 @@ function call(args: {
}
describe('cindy-brain · ghostKvEndpoint(/kv 分派纯函数)', () => {
+ it.each(['PUT', 'POST'])('rejects a late %s body after its install target changes', async (method) => {
+ const store = memStore({ source: 'replacement' });
+ let current = true;
+ let finishBody!: (body: string) => void;
+ const body = new Promise<string>((resolve) => { finishBody = resolve; });
+ const pending = handleGhostKvRequest({
+ method, ghostId: 'demo', store, readBodyText: () => body,
+ isCurrent: () => current,
+ });
+ current = false;
+ finishBody('{"source":"old"}');
+ expect(await pending).toEqual({ status: 403 });
+ expect(store.write).not.toHaveBeenCalled();
+ expect(store.read('demo')).toEqual({ source: 'replacement' });
+ });
+
+ it('rejects a non-current request before reading either its body or stored data', async () => {
+ const store = memStore();
+ const readBodyText = vi.fn(async () => '{"source":"old"}');
+ for (const method of ['GET', 'PUT', 'POST']) {
+ expect(await handleGhostKvRequest({
+ method, ghostId: 'demo', store, readBodyText, isCurrent: () => false,
+ })).toEqual({ status: 403 });
+ }
+ expect(readBodyText).not.toHaveBeenCalled();
+ expect(store.read).not.toHaveBeenCalled();
+ expect(store.write).not.toHaveBeenCalled();
+ });
+
+ it('preserves a late body from the unchanged current install', async () => {
+ const store = memStore();
+ let finishBody!: (body: string) => void;
+ const body = new Promise<string>((resolve) => { finishBody = resolve; });
+ const pending = handleGhostKvRequest({
+ method: 'PUT', ghostId: 'demo', store, readBodyText: () => body, isCurrent: () => true,
+ });
+ finishBody('{"source":"current"}');
+ expect(await pending).toEqual({ status: 204 });
+ expect(store.write).toHaveBeenCalledExactlyOnceWith('demo', { source: 'current' });
+ });
+
it('GET → 200 + store 内容 JSON', async () => {
const store = memStore({ theme: 'dark' });
const out = await call({ method: 'GET', store });
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
index a061f958ad..760cd85e18 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
@@ -8,7 +8,7 @@ import { describe, expect, it, vi } from 'vitest';
import { GhostKvError } from '../../ghostKvStore.js';
import { GHOST_SECRET_VALUE_MAX_CHARS } from '../ghostSecretsEndpoint.js';
import { handleGhostOauthRequest, type GhostOauthEndpointManager } from '../ghostOauthEndpoint.js';
-import type { GhostOauthDecl } from '../../ghostOauthAccounts.js';
+import { GhostOauthAccountManager, type GhostOauthDecl } from '../../ghostOauthAccounts.js';
const GHOST = 'g-oauth';
const DECL: GhostOauthDecl = {
@@ -76,6 +76,128 @@ function call(params: {
});
}
+describe('OAuth credential install target guard', () => {
+ const mutations = [
+ ['PUT', '/oauth/acct/client', '{"clientId":"fake-old-client"}', 'setClientConfig'],
+ ['DELETE', '/oauth/acct/client', '', 'clearClientConfig'],
+ ['DELETE', '/oauth/acct/accounts/acc-1', '', 'disconnectAccount'],
+ ['POST', '/oauth/acct/default', '{"accountId":"acc-1"}', 'setDefaultAccount'],
+ ['POST', '/oauth/acct/insufficient-scopes', '{"scopes":["read.a"]}', 'reportInsufficientScopes'],
+ ] as const;
+
+ it.each(mutations)('rejects %s %s after waiting for the mutation lock', async (method, pathname, body, mutation) => {
+ const manager = fakeManager();
+ const onChanged = vi.fn();
+ let current = true;
+ const result = await handleGhostOauthRequest({
+ method, pathname, ghostId: GHOST, oauthSecrets: SECRETS, manager, onChanged,
+ readBodyText: async () => body, isCurrent: () => current,
+ withMutationLock: async (_ghostId, task) => { current = false; return task(); },
+ });
+ expect(result).toEqual({ status: 403 });
+ expect(manager[mutation]).not.toHaveBeenCalled();
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it.each([...mutations.filter(([method]) => method !== 'DELETE'),
+ ['POST', '/oauth/acct/connect', '{}', 'connectAccount'] as const,
+ ])('rejects a late body for %s %s', async (method, pathname, body, mutation) => {
+ const manager = fakeManager();
+ const onChanged = vi.fn();
+ let current = true;
+ const result = await handleGhostOauthRequest({
+ method, pathname, ghostId: GHOST, oauthSecrets: SECRETS, manager, onChanged,
+ isCurrent: () => current,
+ readBodyText: async () => { current = false; return body; },
+ });
+ expect(result).toEqual({ status: 403 });
+ expect(manager[mutation]).not.toHaveBeenCalled();
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it.each(mutations)('allows %s %s for the unchanged install', async (method, pathname, body, mutation) => {
+ const manager = fakeManager();
+ const onChanged = vi.fn();
+ const result = await handleGhostOauthRequest({
+ method, pathname, ghostId: GHOST, oauthSecrets: SECRETS, manager, onChanged,
+ isCurrent: () => true, readBodyText: async () => body,
+ withMutationLock: async (_ghostId, task) => task(),
+ });
+ expect(result.status).toBe(204);
+ expect(manager[mutation]).toHaveBeenCalledTimes(1);
+ expect(onChanged).toHaveBeenCalledExactlyOnceWith('acct');
+ });
+
+ it('rechecks the protocol target inside the connect manager commit boundary', async () => {
+ let current = true;
+ const write = vi.fn();
+ const manager = fakeManager({
+ connectAccount: vi.fn(async (_ghostId, _secretKey, _decl, opts) => {
+ current = false;
+ opts?.assertCurrent?.();
+ write();
+ return { ok: false, error: 'INVALID_CONFIG' } as const;
+ }),
+ });
+ expect(await handleGhostOauthRequest({
+ method: 'POST', pathname: '/oauth/acct/connect', ghostId: GHOST, oauthSecrets: SECRETS,
+ manager, readBodyText: async () => '{}', isCurrent: () => current,
+ })).toEqual({ status: 403 });
+ expect(write).not.toHaveBeenCalled();
+ });
+});
+
+describe('OAuth connect target identity', () => {
+ it('rejects a same-declaration replacement during body reading through the real manager', async () => {
+ const originalTarget = { revision: 'approved-org', storagePart: 'helper' };
+ const replacementTarget = { revision: 'approved-root', storagePart: 'helper' };
+ let currentTarget = originalTarget;
+ const store = vi.fn(() => true);
+ const openExternal = vi.fn();
+ const manager = new GhostOauthAccountManager({
+ vault: { read: () => null, store, remove: vi.fn() },
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal,
+ captureConnectTarget: () => currentTarget,
+ isConnectTargetCurrent: (_ghostId, _secretKey, _decl, expected) => expected === currentTarget,
+ });
+ const result = await handleGhostOauthRequest({
+ method: 'POST', pathname: '/oauth/acct/connect', ghostId: 'helper',
+ oauthSecrets: new Map([['acct', { ...DECL, clientId: 'fake-client' }]]),
+ manager,
+ readBodyText: async () => {
+ currentTarget = replacementTarget;
+ return JSON.stringify({ expectedConnectTarget: replacementTarget });
+ },
+ });
+ expect(result.status).toBe(200);
+ expect(JSON.parse(result.body ?? '{}')).toMatchObject({ ok: false, error: 'INVALID_CONFIG' });
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(store).not.toHaveBeenCalled();
+ });
+
+ it('captures the Host target before reading a body that replaces the instance', async () => {
+ const originalTarget = { revision: 'approved-org', storagePart: 'helper' };
+ const replacementTarget = { revision: 'approved-root', storagePart: 'helper' };
+ let currentTarget = originalTarget;
+ const captureConnectTarget = vi.fn(() => currentTarget);
+ const manager = fakeManager({ captureConnectTarget });
+ const result = await handleGhostOauthRequest({
+ method: 'POST', pathname: '/oauth/acct/connect', ghostId: 'helper', oauthSecrets: SECRETS,
+ manager,
+ readBodyText: async () => {
+ currentTarget = replacementTarget;
+ return JSON.stringify({ expectedConnectTarget: replacementTarget });
+ },
+ });
+ expect(result.status).toBe(200);
+ expect(captureConnectTarget).toHaveBeenCalledExactlyOnceWith('helper');
+ expect(manager.connectAccount).toHaveBeenCalledWith('helper', 'acct', DECL, {
+ expectedConnectTarget: originalTarget,
+ });
+ });
+});
+
describe('GET /oauth', () => {
it('回全部 oauth 凭证槽状态,零令牌字节', async () => {
const manager = fakeManager();
@@ -514,6 +636,7 @@ describe('tokenBroker 门控', () => {
pathname: string,
manager = fakeManager(),
body: Record<string, unknown> = {},
+ authorized = false,
) {
return handleGhostOauthRequest({
method,
@@ -522,6 +645,7 @@ describe('tokenBroker 门控', () => {
oauthSecrets: BROKERED_SECRETS,
manager,
ghostId,
+ isTokenBrokerAuthorized: () => authorized,
});
}
@@ -537,9 +661,18 @@ describe('tokenBroker 门控', () => {
expect(manager.clearClientConfig).not.toHaveBeenCalled();
});
- it('connect:官方前缀 id 放行;第三方 id 结构化拒(不触发授权流程)', async () => {
+ it('connect: missing grant denies even official-looking ids; authorized grant proceeds', async () => {
+ const deniedOfficial = fakeManager();
+ const denied = await callAs('xd-atlassian', 'POST', '/oauth/acct/connect', deniedOfficial);
+ expect(denied.status).toBe(200);
+ expect(JSON.parse(denied.body ?? '{}')).toMatchObject({
+ ok: false,
+ error: 'BROKER_FORBIDDEN',
+ });
+ expect(deniedOfficial.connectAccount).not.toHaveBeenCalled();
+
const okManager = fakeManager();
- const allowed = await callAs('xd-atlassian', 'POST', '/oauth/acct/connect', okManager);
+ const allowed = await callAs('xd-atlassian', 'POST', '/oauth/acct/connect', okManager, {}, true);
expect(allowed.status).toBe(200);
expect(okManager.connectAccount).toHaveBeenCalledTimes(1);
@@ -557,7 +690,7 @@ describe('tokenBroker 门控', () => {
const manager = fakeManager();
const selected = await callAs('xd-atlassian', 'POST', '/oauth/acct/connect', manager, {
clientId: 'global-cid',
- });
+ }, true);
expect(selected.status).toBe(200);
expect(manager.connectAccount).toHaveBeenCalledWith('xd-atlassian', 'acct', BROKERED, {
clientId: 'global-cid',
@@ -566,7 +699,7 @@ describe('tokenBroker 门控', () => {
const rejectedManager = fakeManager();
const rejected = await callAs('xd-atlassian', 'POST', '/oauth/acct/connect', rejectedManager, {
clientId: 'foreign-cid',
- });
+ }, true);
expect(rejected.status).toBe(400);
expect(rejectedManager.connectAccount).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
index 9f0840afef..5a847c21f1 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
@@ -39,6 +39,46 @@ function memVault(saved: Record<string, string> = {}): GhostSecretsVault & {
};
}
+describe('credential install target guard', () => {
+ it.each(['PUT', 'POST'])('rejects a late %s body without writing or notifying', async (method) => {
+ const vault = memVault({ api_key: 'fake-new-source' });
+ const onStored = vi.fn();
+ let current = true;
+ let finishBody!: (body: string) => void;
+ const body = new Promise<string>((resolve) => { finishBody = resolve; });
+ const pending = handleGhostSecretsRequest({
+ method, pathname: '/secrets/api_key', ghostId: 'demo', userSecretKeys: ['api_key'],
+ vault, onStored, readBodyText: () => body, isCurrent: () => current,
+ });
+ current = false;
+ finishBody('{"value":"fake-old-source"}');
+ expect(await pending).toEqual({ status: 403 });
+ expect(vault.data.api_key).toBe('fake-new-source');
+ expect(vault.store).not.toHaveBeenCalled();
+ expect(onStored).not.toHaveBeenCalled();
+ });
+
+ it('rejects an invalid install before a secret deletion', async () => {
+ const vault = memVault({ api_key: 'fake-new-source' });
+ expect(await handleGhostSecretsRequest({
+ method: 'DELETE', pathname: '/secrets/api_key', ghostId: 'demo', userSecretKeys: ['api_key'],
+ vault, readBodyText: vi.fn(), isCurrent: () => false,
+ })).toEqual({ status: 403 });
+ expect(vault.remove).not.toHaveBeenCalled();
+ });
+
+ it('still writes and notifies for the unchanged current install', async () => {
+ const vault = memVault();
+ const onStored = vi.fn();
+ expect(await handleGhostSecretsRequest({
+ method: 'PUT', pathname: '/secrets/api_key', ghostId: 'demo', userSecretKeys: ['api_key'],
+ vault, onStored, readBodyText: async () => '{"value":"fake-current"}', isCurrent: () => true,
+ })).toEqual({ status: 204 });
+ expect(vault.store).toHaveBeenCalledExactlyOnceWith('demo', 'api_key', 'fake-current');
+ expect(onStored).toHaveBeenCalledExactlyOnceWith('api_key');
+ });
+});
+
function call(args: {
method: string;
pathname: string;
diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
index a86ab8b6ea..e4acfb861a 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
@@ -16,7 +16,8 @@ import {
type InstalledGhost,
} from '../../../shared/ghost.js';
import { getActiveAppSession, type ActiveAppSession } from '../../appSessionState.js';
-import { ownerScopedGhostPartition } from '../ghostWebviewPartition.js';
+import { ownerScopedGhostPartition, ownerScopedGhostPartitionForInstalledGhost } from '../ghostWebviewPartition.js';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
import { GHOST_BOOT_PATH, ghostBootHtml, ghostFileMime, resolveGhostFilePath } from './ghostFiles.js';
import { handleGhostKvRequest, readBoundedBodyText } from './ghostKvEndpoint.js';
import { resolveHashRef as resolveBlobHashRef } from '../../cindy-media/blobStore.js';
@@ -111,30 +112,38 @@ export function sendToGhostLogic(ghostId: string, payload: unknown): boolean {
}
/** The remote page uses the same owner partition and running logic as desktop. */
-export async function invokeGhostMobileRelay(ghostId: string, operation: MobileRelayOperation): Promise<unknown> {
- const partition = ownerScopedGhostPartition(ghostId, getActiveAppSession());
+export async function invokeGhostMobileRelay(ghost: InstalledGhost, operation: MobileRelayOperation): Promise<unknown> {
+ const ghostId = installedGhostStoragePart(ghost);
+ const partition = ownerScopedGhostPartitionForInstalledGhost(ghost, getActiveAppSession());
if (!partition) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
+ const isCurrent = captureGhostProtocolTargetGuard(partition);
+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
const ownerSession = session.fromPartition(partition);
for (const [id, plugin] of logicWebContentsToGhost) {
if (plugin !== ghostId) continue;
const wc = webContents.fromId(id);
if (wc && !wc.isDestroyed() && wc.session === ownerSession) {
- return wc.executeJavaScript(mobilePageRelayScript(operation));
+ const result = await wc.executeJavaScript(mobilePageRelayScript(operation));
+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
+ return result;
}
}
throw new Error('PLUGIN_PAGE_UNAVAILABLE');
}
export async function fetchGhostMobilePage(ghost: InstalledGhost, pathname: string, method: string, body?: string, offset = 0, expectedRevision?: string) {
- const partition = ownerScopedGhostPartition(ghost.manifest.id, getActiveAppSession());
+ const partition = ownerScopedGhostPartitionForInstalledGhost(ghost, getActiveAppSession());
if (!partition) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
+ ensureGhostProtocolRegistered(ghost);
+ const isCurrent = captureGhostProtocolTargetGuard(partition);
+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
// Read only the requested immutable blob chunk. The desktop protocol buffers
// the whole file, which would repeat that work for every remote video chunk.
if (pathname.startsWith('/media/')) {
const match = /^\/media\/([a-f0-9]{64})(\.[a-z0-9]+)$/.exec(pathname);
const missing = { status: 404, mime: 'application/octet-stream', base64: '' };
if (!match || method !== 'GET' || !Number.isSafeInteger(offset) || offset < 0) return missing;
- if (!(await ghostCanReadMedia(match[1], ghost.manifest.id))) return missing;
+ if (!(await ghostCanReadMedia(match[1], installedGhostStoragePart(ghost)))) return missing;
let resolved: { absPath: string; mimeType: string };
try { resolved = resolveBlobHashRef(match[1], match[2]); } catch { return missing; }
const handle = await fs.open(resolved.absPath, nodeFs.constants.O_RDONLY | nodeFs.constants.O_NOFOLLOW);
@@ -144,12 +153,12 @@ export async function fetchGhostMobilePage(ghost: InstalledGhost, pathname: stri
const data = Buffer.alloc(Math.min(49_152, stat.size - offset));
const { bytesRead } = await handle.read(data, 0, data.length, offset);
if (bytesRead !== data.length) throw new Error('PLUGIN_MEDIA_CHANGED');
+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
return { status: 200, mime: resolved.mimeType, base64: data.toString('base64'), revision: match[1],
...(offset + bytesRead < stat.size ? { nextOffset: offset + bytesRead } : {}),
};
} finally { await handle.close(); }
}
- ensureGhostProtocolRegistered(ghost);
const file = /^\/(?:library|media)\//.test(pathname);
const response = await session.fromPartition(partition).fetch(`${GHOST_SCHEME}://${ghost.manifest.id}${pathname}`, { method, body,
...(file && offset ? { headers: { Range: `bytes=${offset}-` } } : {}),
@@ -179,6 +188,7 @@ export async function fetchGhostMobilePage(ghost: InstalledGhost, pathname: stri
} finally { await reader.cancel(); }
}
const remaining = Number(response.headers.get('content-length'));
+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');
return { status: response.status === 206 ? 200 : response.status, mime: response.headers.get('content-type') ?? 'application/json', base64: Buffer.concat(chunks).toString('base64'), ...(revision ? { revision } : {}),
...(file && remaining > total ? { nextOffset: offset + total } : {}),
};
@@ -240,15 +250,16 @@ export function setGhostAgentModelsProvider(
* adapter 反向依赖)。注入的是带"在装态守卫"的包装层——卸下后分区里
* 残留的 fetch 不能复活写出新文件。
*/
-let ghostKvStore: {
+interface GhostKvProtocolStore {
read(ghostId: string): Record<string, unknown>;
write(ghostId: string, value: Record<string, unknown>): void;
-} | null = null;
+ captureTarget(ghostId: string): unknown;
+ isTargetCurrent(ghostId: string, expectedTarget: unknown): boolean;
+}
-export function setGhostKvStore(store: {
- read(ghostId: string): Record<string, unknown>;
- write(ghostId: string, value: Record<string, unknown>): void;
-}): void {
+let ghostKvStore: GhostKvProtocolStore | null = null;
+
+export function setGhostKvStore(store: GhostKvProtocolStore): void {
ghostKvStore = store;
}
@@ -261,6 +272,7 @@ type GhostSecretsProtocolHandler = (args: {
method: string;
pathname: string;
readBodyText: () => Promise<string>;
+ isCurrent: () => boolean;
}) => Promise<{ status: number; body?: string }>;
let ghostSecretsHandler: GhostSecretsProtocolHandler | null = null;
@@ -279,6 +291,7 @@ type GhostOauthProtocolHandler = (args: {
method: string;
pathname: string;
readBodyText: () => Promise<string>;
+ isCurrent: () => boolean;
}) => Promise<{ status: number; body?: string }>;
let ghostOauthHandler: GhostOauthProtocolHandler | null = null;
@@ -298,6 +311,7 @@ type GhostConnectionsProtocolHandler = (args: {
method: string;
pathname: string;
readBodyText: () => Promise<string>;
+ isCurrent: () => boolean;
}) => Promise<{ status: number; body?: string }>;
let ghostConnectionsHandler: GhostConnectionsProtocolHandler | null = null;
@@ -308,12 +322,14 @@ export function setGhostConnectionsHandler(handler: GhostConnectionsProtocolHand
/** 该分区是否已挂过协议 handler(session 分区随 app 生命周期,挂一次即可)。 */
const partitionRegistered = new Set<string>();
-const partitionGhost = new Map<string, { dir: string; entry: string }>();
-type GhostProtocolOwnerIdentity = Pick<ActiveAppSession, 'mode' | 'dataOwnerId'>;
+const revokedPartitions = new Set<string>();
+const partitionGhost = new Map<string, { dir: string; entry: string; storagePart: string }>();
+const partitionTargetGuard = new Map<string, () => boolean>();
+type GhostProtocolOwnerIdentity = Pick<ActiveAppSession, 'mode' | 'dataOwnerId' | 'generation'>;
const partitionOwner = new Map<string, GhostProtocolOwnerIdentity>();
function ghostProtocolOwnerSnapshot(owner: ActiveAppSession): GhostProtocolOwnerIdentity {
- return { mode: owner.mode, dataOwnerId: owner.dataOwnerId };
+ return { mode: owner.mode, dataOwnerId: owner.dataOwnerId, generation: owner.generation };
}
function isSameGhostProtocolOwner(
@@ -324,7 +340,8 @@ function isSameGhostProtocolOwner(
}
function isGhostProtocolOwnerActive(owner: GhostProtocolOwnerIdentity): boolean {
- return isSameGhostProtocolOwner(owner, getActiveAppSession());
+ const current = getActiveAppSession();
+ return isSameGhostProtocolOwner(owner, current) && owner.generation === current.generation;
}
/**
@@ -336,11 +353,20 @@ export function ensureGhostProtocolRegistered(
ghost: InstalledGhost,
owner: ActiveAppSession = getActiveAppSession(),
): void {
- const partition = ownerScopedGhostPartition(ghost.manifest.id, owner);
+ const partition = ownerScopedGhostPartitionForInstalledGhost(ghost, owner);
if (!partition) throw new Error('ghost protocol requires an active data owner');
registerGhostProtocol(partition, ghost, ghostProtocolOwnerSnapshot(owner));
}
+export function revokeLegacyGhostProtocolPartition(ghostId: string): void {
+ const partition = ownerScopedGhostPartition(ghostId, getActiveAppSession());
+ if (!partition) return;
+ revokedPartitions.add(partition);
+ for (const registered of partitionRegistered) {
+ if (registered.startsWith(partition + ':receipt:')) revokedPartitions.add(registered);
+ }
+}
+
/**
* 意识页面(html 响应)统一佩戴的 CSP:脚本/样式/资源只许同源(= 自己的
* 安装目录),img 额外放行 data:/blob:/https:(远程图片),media 额外放行
@@ -350,6 +376,24 @@ export function ensureGhostProtocolRegistered(
const GHOST_HTML_CSP =
"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; media-src 'self' data: blob:";
+function createGhostProtocolTargetGuard(
+ ghostId: string,
+ partition: string,
+ owner: GhostProtocolOwnerIdentity,
+): () => boolean {
+ const store = ghostKvStore;
+ if (!store) return () => false;
+ const expectedTarget = store.captureTarget(ghostId);
+ return () => expectedTarget !== null && expectedTarget !== undefined &&
+ ghostKvStore === store && !revokedPartitions.has(partition) &&
+ isGhostProtocolOwnerActive(owner) &&
+ store.isTargetCurrent(ghostId, expectedTarget);
+}
+
+function captureGhostProtocolTargetGuard(partition: string): () => boolean {
+ return partitionTargetGuard.get(partition) ?? (() => false);
+}
+
function registerGhostProtocol(
partition: string,
ghost: InstalledGhost,
@@ -359,11 +403,19 @@ function registerGhostProtocol(
if (registeredOwner && !isSameGhostProtocolOwner(registeredOwner, owner)) {
throw new Error('ghost protocol partition already belongs to a different data owner');
}
- partitionGhost.set(partition, {
+ const binding = {
dir: ghost.dir,
entry: ghost.manifest.entry,
- });
- if (partitionRegistered.has(partition)) return;
+ storagePart: installedGhostStoragePart(ghost),
+ };
+ if (partitionRegistered.has(partition)) {
+ const registered = partitionGhost.get(partition);
+ if (!registered || registered.dir !== binding.dir || registered.entry !== binding.entry || registered.storagePart !== binding.storagePart) {
+ revokedPartitions.add(partition);
+ }
+ return;
+ }
+ const isRegistrationCurrent = createGhostProtocolTargetGuard(binding.storagePart, partition, owner);
// 注意:登记发生在全部挂载成功之后(函数末尾)——session.fromPartition 在
// app ready 前会 throw,若先登记后挂载,失败分区会被永久标记"已注册"而
// 实际无 handler,面板与电子脑一起哑火(review P0 的中毒模式)。
@@ -389,17 +441,17 @@ function registerGhostProtocol(
}
callback({ cancel: !allowed });
});
- ses.protocol.handle(SCHEME, async (request) => {
+ const handleRequest = async (request: Request): Promise<Response> => {
try {
// owner B 提交后,owner A 的旧 guest 仍可能短暂存活并新发请求。
- // 在 URL 路由、body 读取和任何 provider 调用前拒绝旧 Session;已经
- // 进入 handler 的请求不在这里取消或排空。
- if (!isGhostProtocolOwnerActive(owner)) {
+ // 在 URL 路由、body 读取和任何 provider 调用前拒绝旧 Session。
+ if (!isRegistrationCurrent()) {
return new Response(null, {
status: 403,
headers: { 'Cache-Control': 'no-store' },
});
}
+ const storagePart = binding.storagePart;
const url = new URL(request.url);
// 分区专属通道只认自己的 id,其它 host 一律 403(结构隔离的最后一道断言)。
if (url.host !== ghostId) return new Response(null, { status: 403 });
@@ -408,19 +460,19 @@ function registerGhostProtocol(
// 账本验归属(出生自本意识或挂本意识画廊),通过才从字节仓读——
// 查无此账与不属于你统一 404,不给沙箱探测面。
if (url.pathname.startsWith('/media/')) {
- return serveGhostMedia(ghostId, url.pathname.slice('/media/'.length), request.headers.get('range'));
+ return serveGhostMedia(storagePart, url.pathname.slice('/media/'.length), request.headers.get('range'));
}
// /library/<相对路径>:面板只读投影本意识的持久作品库文件(图片/视频/
// 导出物)。解析器由 cindy-brain/index 注入(binding 根 + vault 路径纪律,
// 与电子脑 read 同源校验);内容可变,Cache-Control 走 no-cache(与
// 内容寻址的 /media 长缓存不同)。失败统一折叠 404。
if (url.pathname.startsWith('/library/')) {
- return serveGhostLibraryFile(ghostId, decodeURIComponent(url.pathname.slice('/library/'.length)), request.headers.get('range'));
+ return serveGhostLibraryFile(storagePart, decodeURIComponent(url.pathname.slice('/library/'.length)), request.headers.get('range'));
}
// /gallery:本意识画廊清单(重启回放)。分区专属通道天然只答自己的账;
// 内容只有指纹地址与备注字符串,零文件字节。
if (url.pathname === '/gallery') {
- return serveGhostGallery(ghostId);
+ return serveGhostGallery(storagePart, ghostId);
}
// /wake:面板叫醒自己的电子脑(§4"确实有活才开门"的面板侧入口)。
// spawn 幂等(已在跑立即返回);沉睡/熔断由注入的 handler 拒绝。
@@ -428,7 +480,7 @@ function registerGhostProtocol(
// 只回状态字符串,不回任何细节。
if (url.pathname === '/wake') {
if (!ghostWakeHandler) return new Response(null, { status: 503 });
- const wake = await ghostWakeHandler(ghostId);
+ const wake = await ghostWakeHandler(storagePart);
return new Response(JSON.stringify(wake), {
status: 200,
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache' },
@@ -453,7 +505,7 @@ function registerGhostProtocol(
if (url.search) return new Response(null, { status: 400, headers });
if (!ghostAgentModelsProvider) return new Response(null, { status: 503, headers });
try {
- const result = await ghostAgentModelsProvider(ghostId);
+ const result = await ghostAgentModelsProvider(storagePart);
if (!isGhostProtocolOwnerActive(owner)) return new Response(null, { status: 403, headers });
return new Response(JSON.stringify(result), {
status: result.ok ? 200 : result.errorCode === 'PERMISSION_DENIED' ? 403 : 503,
@@ -482,7 +534,7 @@ function registerGhostProtocol(
return new Response(null, { status: 400 });
}
if (!ghostMediaModelsProvider) return new Response(null, { status: 503 });
- const result = await ghostMediaModelsProvider(ghostId, type);
+ const result = await ghostMediaModelsProvider(storagePart, type);
return new Response(JSON.stringify(result), {
status: result.ok ? 200 : result.errorCode === 'PERMISSION_DENIED' ? 403 : 503,
headers: {
@@ -496,13 +548,15 @@ function registerGhostProtocol(
// (ghostKvEndpoint,已单测),这里只做 Response 包装。
if (url.pathname === '/kv') {
if (!ghostKvStore) return new Response(null, { status: 503 });
+ const store = ghostKvStore;
const out = await handleGhostKvRequest({
method: request.method,
// 有界读取(readBoundedBodyText):content-length 预检 + 流式限额,
// 不受信 body 永不全量进主进程内存——沙箱允许死,主机不能被 OOM。
readBodyText: () => readBoundedBodyText(request),
- store: ghostKvStore,
- ghostId,
+ store,
+ ghostId: storagePart,
+ isCurrent: isRegistrationCurrent,
log,
});
return new Response(out.body ?? null, {
@@ -520,10 +574,11 @@ function registerGhostProtocol(
if (url.pathname === '/secrets' || url.pathname.startsWith('/secrets/')) {
if (!ghostSecretsHandler) return new Response(null, { status: 503 });
const out = await ghostSecretsHandler({
- ghostId,
+ ghostId: storagePart,
method: request.method,
pathname: url.pathname,
readBodyText: () => readBoundedBodyText(request),
+ isCurrent: isRegistrationCurrent,
});
return new Response(out.body ?? null, {
status: out.status,
@@ -541,10 +596,11 @@ function registerGhostProtocol(
if (url.pathname === '/oauth' || url.pathname.startsWith('/oauth/')) {
if (!ghostOauthHandler) return new Response(null, { status: 503 });
const out = await ghostOauthHandler({
- ghostId,
+ ghostId: storagePart,
method: request.method,
pathname: url.pathname,
readBodyText: () => readBoundedBodyText(request),
+ isCurrent: isRegistrationCurrent,
});
return new Response(out.body ?? null, {
status: out.status,
@@ -562,10 +618,11 @@ function registerGhostProtocol(
if (url.pathname === '/connections' || url.pathname.startsWith('/connections/')) {
if (!ghostConnectionsHandler) return new Response(null, { status: 503 });
const out = await ghostConnectionsHandler({
- ghostId,
+ ghostId: storagePart,
method: request.method,
pathname: url.pathname,
readBodyText: () => readBoundedBodyText(request),
+ isCurrent: isRegistrationCurrent,
});
return new Response(out.body ?? null, {
status: out.status,
@@ -578,7 +635,7 @@ function registerGhostProtocol(
});
}
if (url.pathname === GHOST_BOOT_PATH || url.pathname === '/') {
- const entry = partitionGhost.get(partition)?.entry;
+ const entry = binding.entry;
if (!entry) return new Response(null, { status: 404 });
return new Response(ghostBootHtml(entry), {
status: 200,
@@ -589,7 +646,7 @@ function registerGhostProtocol(
},
});
}
- const installDir = partitionGhost.get(partition)?.dir;
+ const installDir = binding.dir;
if (!installDir) return new Response(null, { status: 404 });
const filePath = resolveGhostFilePath(installDir, url.pathname);
if (!filePath) return new Response(null, { status: 403 });
@@ -609,8 +666,16 @@ function registerGhostProtocol(
log.error('cindy-ghost protocol error', { error: err instanceof Error ? err.message : String(err) });
return new Response(null, { status: 500 });
}
+ };
+ ses.protocol.handle(SCHEME, async (request) => {
+ const response = await handleRequest(request);
+ if (isRegistrationCurrent()) return response;
+ void response.body?.cancel().catch(() => undefined);
+ return new Response(null, { status: 403, headers: { 'Cache-Control': 'no-store' } });
});
partitionOwner.set(partition, owner);
+ partitionGhost.set(partition, binding);
+ partitionTargetGuard.set(partition, isRegistrationCurrent);
partitionRegistered.add(partition); // 全部挂载成功,才算注册完成
}
@@ -750,16 +815,16 @@ function mediaTypeForLibraryPath(relPath: string): string {
}
/** 画廊清单响应:[{src, caption}](新的在前;账本不可用时回空数组不报错)。 */
-async function serveGhostGallery(ghostId: string): Promise<Response> {
+async function serveGhostGallery(storagePart: string, protocolHost: string): Promise<Response> {
let items: Awaited<ReturnType<typeof listGhostGalleryFromLedger>> = [];
try {
- items = await listGhostGalleryFromLedger(ghostId);
+ items = await listGhostGalleryFromLedger(storagePart);
} catch (err) {
// 账本未就绪(登录早期等):回空墙,面板照常渲染空态,不给沙箱报错面。
- log.warn('ghost gallery list unavailable', { ghostId, error: err instanceof Error ? err.message : String(err) });
+ log.warn('ghost gallery list unavailable', { ghostId: storagePart, error: err instanceof Error ? err.message : String(err) });
}
const payload = items.map((it) => ({
- src: `${SCHEME}://${ghostId}/media/${it.hash}${it.ext}`,
+ src: `${SCHEME}://${protocolHost}/media/${it.hash}${it.ext}`,
caption: it.label ?? '',
}));
return new Response(JSON.stringify(payload), {
@@ -775,7 +840,7 @@ class ElectronSandboxHandle implements SandboxHandle {
constructor(private readonly ghost: InstalledGhost) {
const activeOwner = getActiveAppSession();
- const partition = ownerScopedGhostPartition(ghost.manifest.id, activeOwner);
+ const partition = ownerScopedGhostPartitionForInstalledGhost(ghost, activeOwner);
if (!partition) throw new Error('ghost sandbox requires an active data owner');
registerGhostProtocol(partition, ghost, ghostProtocolOwnerSnapshot(activeOwner));
this.win = new BrowserWindow({
@@ -797,7 +862,7 @@ class ElectronSandboxHandle implements SandboxHandle {
},
});
ghostWebContentsIds.add(this.win.webContents.id);
- logicWebContentsToGhost.set(this.win.webContents.id, ghost.manifest.id);
+ logicWebContentsToGhost.set(this.win.webContents.id, installedGhostStoragePart(ghost));
this.win.webContents.on('render-process-gone', (_event, details) => {
if (this.destroyed) return;
// 延迟一拍再收尸:不在 Chromium 事件分发中途销毁窗口(重入风险)。
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostConnectionsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostConnectionsEndpoint.ts
index ecc60b115b..b64245518b 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostConnectionsEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostConnectionsEndpoint.ts
@@ -30,6 +30,7 @@
*/
import { GhostKvError } from '../ghostKvStore.js';
+import { assertGhostProtocolTargetCurrent, GhostProtocolTargetChangedError } from './ghostProtocolTargetGuard.js';
import { GHOST_SECRET_VALUE_MAX_CHARS } from './ghostSecretsEndpoint.js';
import { normalizeGhostConnectionHost } from '../ghostConnections.js';
import type { GhostConnectionUpsertResult, GhostConnectionView } from '../ghostConnections.js';
@@ -62,6 +63,7 @@ export async function handleGhostConnectionsRequest(args: {
decls: ReadonlyMap<string, { label: string; maxConnections: number }>;
manager: GhostConnectionsEndpointManager;
ghostId: string;
+ isCurrent?: () => boolean;
/**
* 新增地址的主机受信确认(main 侧模态弹窗;index.ts 注入)。返回 false =
* 用户拒绝。弹窗抛错按拒绝收(fail-closed:确认不了就不扩白名单)。
@@ -74,6 +76,7 @@ export async function handleGhostConnectionsRequest(args: {
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}): Promise<GhostConnectionsRequestOutcome> {
const { method, pathname, readBodyText, decls, manager, ghostId, log } = args;
+ if (args.isCurrent?.() === false) return { status: 403 };
const notifyChanged = (declKey: string): void => {
try {
args.onChanged?.(declKey);
@@ -121,9 +124,11 @@ export async function handleGhostConnectionsRequest(args: {
try {
text = await readBodyText();
} catch (err) {
+ if (args.isCurrent?.() === false || err instanceof GhostProtocolTargetChangedError) return { status: 403 };
if (err instanceof GhostKvError && err.code === 'TOO_LARGE') return { status: 413 };
return { status: 400 };
}
+ if (args.isCurrent?.() === false) return { status: 403 };
let parsed: unknown;
try {
parsed = JSON.parse(text);
@@ -162,8 +167,10 @@ export async function handleGhostConnectionsRequest(args: {
log?.warn('ghost connections 受信确认弹窗异常(按拒绝收)', { ghostId, declKey, err: String(err) });
allowed = false;
}
+ assertGhostProtocolTargetCurrent(args.isCurrent);
if (!allowed) return json(200, { ok: false, error: 'CONFIRM_DENIED' });
}
+ assertGhostProtocolTargetCurrent(args.isCurrent);
const result = manager.upsert(ghostId, declKey, {
host,
token,
@@ -179,6 +186,7 @@ export async function handleGhostConnectionsRequest(args: {
}
return json(200, { ok: true, connection: result.connection });
} catch (err) {
+ if (err instanceof GhostProtocolTargetChangedError) return { status: 403 };
log?.warn('ghost connections 入库意外失败', { ghostId, declKey, err: String(err) });
return { status: 500 };
}
@@ -192,9 +200,11 @@ export async function handleGhostConnectionsRequest(args: {
try {
text = await readBodyText();
} catch (err) {
+ if (args.isCurrent?.() === false || err instanceof GhostProtocolTargetChangedError) return { status: 403 };
if (err instanceof GhostKvError && err.code === 'TOO_LARGE') return { status: 413 };
return { status: 400 };
}
+ if (args.isCurrent?.() === false) return { status: 403 };
let parsed: unknown;
try {
parsed = JSON.parse(text);
@@ -207,10 +217,12 @@ export async function handleGhostConnectionsRequest(args: {
: undefined;
if (typeof connectionId !== 'string' || connectionId.length === 0) return { status: 400 };
try {
+ assertGhostProtocolTargetCurrent(args.isCurrent);
if (!manager.setDefault(ghostId, declKey, connectionId)) return { status: 404 };
notifyChanged(declKey);
return { status: 204 };
} catch (err) {
+ if (err instanceof GhostProtocolTargetChangedError) return { status: 403 };
log?.warn('ghost connections 设默认连接意外失败', { ghostId, declKey, err: String(err) });
return { status: 500 };
}
@@ -220,10 +232,12 @@ export async function handleGhostConnectionsRequest(args: {
const connectionId = segments[1];
if (!connectionId) return { status: 404 };
try {
+ assertGhostProtocolTargetCurrent(args.isCurrent);
manager.remove(ghostId, declKey, connectionId);
notifyChanged(declKey);
return { status: 204 };
} catch (err) {
+ if (err instanceof GhostProtocolTargetChangedError) return { status: 403 };
log?.warn('ghost connections 删除连接意外失败', { ghostId, declKey, err: String(err) });
return { status: 500 };
}
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostKvEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostKvEndpoint.ts
index 96253756c1..d4705c0f63 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostKvEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostKvEndpoint.ts
@@ -10,7 +10,7 @@
* - 坏 JSON / 非 object → 400;超限 → 413;其它 method → 405;
* - 存储层意外错误 → 500(**不外泄 message**,细节走日志)。
*
- * 身份与隔离不在这层:ghostId 来自协议 handler 的分区绑定(主机派生,
+ * 身份与隔离不在这层:instanceKey 来自协议 handler 的分区绑定(主机派生,
* 不信自报),跨意识请求早在分区断网闸 + host 断言就被掐了。
*/
@@ -72,8 +72,8 @@ export async function readBoundedBodyText(request: BoundedBodySource): Promise<s
}
interface GhostKvEndpointStore {
- read(ghostId: string): Record<string, unknown>;
- write(ghostId: string, value: Record<string, unknown>): void;
+ read(instanceKey: string): Record<string, unknown>;
+ write(instanceKey: string, value: Record<string, unknown>): void;
}
export async function handleGhostKvRequest(args: {
@@ -82,15 +82,18 @@ export async function handleGhostKvRequest(args: {
readBodyText: () => Promise<string>;
store: GhostKvEndpointStore;
ghostId: string;
+ isCurrent?: () => boolean;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}): Promise<GhostKvRequestOutcome> {
- const { method, readBodyText, store, ghostId, log } = args;
+ const { method, readBodyText, store, ghostId: instanceKey, log } = args;
+ const isCurrent = args.isCurrent ?? (() => true);
+ if (!isCurrent()) return { status: 403 };
if (method === 'GET') {
try {
- return { status: 200, body: JSON.stringify(store.read(ghostId)) };
+ return { status: 200, body: JSON.stringify(store.read(instanceKey)) };
} catch (err) {
- log?.warn('ghost KV 读取意外失败', { ghostId, err: String(err) });
+ log?.warn('ghost KV 读取意外失败', { instanceKey, err: String(err) });
return { status: 500 };
}
}
@@ -100,12 +103,14 @@ export async function handleGhostKvRequest(args: {
try {
text = await readBodyText();
} catch (err) {
+ if (!isCurrent()) return { status: 403 };
// 有界读取器的超限断流 → 413;其它读流失败(中断等)→ 400。
if (err instanceof GhostKvError && err.code === 'TOO_LARGE') {
return { status: 413 };
}
return { status: 400 };
}
+ if (!isCurrent()) return { status: 403 };
// 体积双保险(readBodyText 已流式限额;这里兜非有界注入的调用方)
// 且先量再 parse:不给超限 payload 任何 JSON.parse 面。
if (Buffer.byteLength(text, 'utf8') > GHOST_KV_MAX_BYTES) {
@@ -121,14 +126,15 @@ export async function handleGhostKvRequest(args: {
return { status: 400 };
}
try {
- store.write(ghostId, value as Record<string, unknown>);
+ if (!isCurrent()) return { status: 403 };
+ store.write(instanceKey, value as Record<string, unknown>);
return { status: 204 };
} catch (err) {
if (err instanceof GhostKvError) {
// 存储层双保险的校验错(理论上上面已拦):按语义映射,不当 500。
return { status: err.code === 'TOO_LARGE' ? 413 : 400 };
}
- log?.warn('ghost KV 写入意外失败', { ghostId, err: String(err) });
+ log?.warn('ghost KV 写入意外失败', { instanceKey, err: String(err) });
return { status: 500 };
}
}
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
index 5ab29af614..c1a26f0876 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
@@ -28,8 +28,8 @@
* 产生的全部令牌只存在主机保险库与内存缓存,本端点没有任何读回动作。
*/
-import { isBrokerEligibleGhostId } from '../../../shared/ghost.js';
import { GhostKvError } from '../ghostKvStore.js';
+import { assertGhostProtocolTargetCurrent, GhostProtocolTargetChangedError } from './ghostProtocolTargetGuard.js';
import { GHOST_SECRET_VALUE_MAX_CHARS } from './ghostSecretsEndpoint.js';
import type {
GhostOauthAccountView,
@@ -46,32 +46,32 @@ export interface GhostOauthRequestOutcome {
/** 账号/凭证管理最小面(生产注入 GhostOauthAccountManager;测试喂假体)。 */
export interface GhostOauthEndpointManager {
/** 可用 = 用户自填或清单内置任一在场(decl 供内置回落判定)。 */
- clientConfigured(ghostId: string, secretKey: string, decl?: GhostOauthDecl): boolean;
+ clientConfigured(instanceKey: string, secretKey: string, decl?: GhostOauthDecl): boolean;
/** 用户是否自填过(UI 区分"内置应用身份 / 已自定义")。 */
- clientCustomized(ghostId: string, secretKey: string): boolean;
- setClientConfig(
- ghostId: string,
+ clientCustomized(instanceKey: string, secretKey: string): boolean;
+ setClientConfig(instanceKey: string,
secretKey: string,
clientId: string,
clientSecret?: string,
): boolean;
- clearClientConfig(ghostId: string, secretKey: string): void;
- listAccounts(ghostId: string, secretKey: string, decl?: GhostOauthDecl): GhostOauthAccountView[];
- connectAccount(
- ghostId: string,
+ clearClientConfig(instanceKey: string, secretKey: string): void;
+ listAccounts(instanceKey: string, secretKey: string, decl?: GhostOauthDecl): GhostOauthAccountView[];
+ captureConnectTarget?(instanceKey: string): unknown;
+ connectAccount(instanceKey: string,
secretKey: string,
decl: GhostOauthDecl,
opts?: {
scopes?: readonly string[];
clientId?: string;
deliveryHosts?: readonly string[];
+ expectedConnectTarget?: unknown;
+ assertCurrent?: () => void;
},
): Promise<GhostOauthConnectResult>;
- disconnectAccount(ghostId: string, secretKey: string, accountId: string): void;
- setDefaultAccount(ghostId: string, secretKey: string, accountId: string): boolean;
+ disconnectAccount(instanceKey: string, secretKey: string, accountId: string): void;
+ setDefaultAccount(instanceKey: string, secretKey: string, accountId: string): boolean;
/** 'unchanged' = 证据已在库未重写(调用方跳过广播);false = 无默认账号或写失败。 */
- reportInsufficientScopes(
- ghostId: string,
+ reportInsufficientScopes(instanceKey: string,
secretKey: string,
scopes: readonly string[],
declScopes: readonly string[],
@@ -90,24 +90,33 @@ export async function handleGhostOauthRequest(args: {
networkHosts?: readonly string[];
manager: GhostOauthEndpointManager;
ghostId: string;
+ isCurrent?: () => boolean;
/** Official prefix first; otherwise first-party resolver. Defaults to official-prefix only. */
- isTokenBrokerAuthorized?: (ghostId: string) => boolean;
+ isTokenBrokerAuthorized?: (instanceKey: string) => boolean;
/** Serialize credential/account persistence with package OAuth migration. */
- withMutationLock?: <T>(ghostId: string, task: () => Promise<T> | T) => Promise<T>;
+ withMutationLock?: <T>(instanceKey: string, task: () => Promise<T> | T) => Promise<T>;
/** Successful semantic persistence only; never receives credential values. */
onChanged?: (secretKey: string) => void;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}): Promise<GhostOauthRequestOutcome> {
- const { method, pathname, readBodyText, oauthSecrets, networkHosts, manager, ghostId, log } =
+ const { method, pathname, readBodyText, oauthSecrets, networkHosts, manager, ghostId: instanceKey, log } =
args;
- const runMutation = <T>(task: () => Promise<T> | T): Promise<T> =>
- args.withMutationLock?.(ghostId, task) ?? Promise.resolve(task());
+ if (args.isCurrent?.() === false) return { status: 403 };
+ const assertCurrent = (): void => assertGhostProtocolTargetCurrent(args.isCurrent);
+ const runMutation = async <T>(task: () => Promise<T> | T): Promise<T> => {
+ const guardedTask = () => {
+ assertCurrent();
+ return task();
+ };
+ const result = await (args.withMutationLock?.(instanceKey, guardedTask) ?? guardedTask());
+ assertCurrent();
+ return result;
+ };
const notifyChanged = (secretKey: string): void => {
try {
args.onChanged?.(secretKey);
} catch (err) {
- log?.warn('ghost oauth onChanged 通知失败(不影响入库结果)', {
- ghostId,
+ log?.warn('ghost oauth onChanged 通知失败(不影响入库结果)', { instanceKey,
secretKey,
err: String(err),
});
@@ -119,14 +128,14 @@ export async function handleGhostOauthRequest(args: {
try {
const list = Array.from(oauthSecrets.entries()).map(([key, keyDecl]) => ({
key,
- clientConfigured: manager.clientConfigured(ghostId, key, keyDecl),
+ clientConfigured: manager.clientConfigured(instanceKey, key, keyDecl),
// 自填与内置分开报:settingsHtml 据此显示"内置应用身份 / 已自定义"。
- clientCustom: manager.clientCustomized(ghostId, key),
- accounts: manager.listAccounts(ghostId, key, keyDecl),
+ clientCustom: manager.clientCustomized(instanceKey, key),
+ accounts: manager.listAccounts(instanceKey, key, keyDecl),
}));
return { status: 200, body: JSON.stringify(list) };
} catch (err) {
- log?.warn('ghost oauth 状态回查失败', { ghostId, err: String(err) });
+ log?.warn('ghost oauth 状态回查失败', { instanceKey, err: String(err) });
return { status: 500 };
}
}
@@ -147,10 +156,12 @@ export async function handleGhostOauthRequest(args: {
try {
text = await readBodyText();
} catch (err) {
+ if (args.isCurrent?.() === false || err instanceof GhostProtocolTargetChangedError) return { ok: false, status: 403 };
if (err instanceof GhostKvError && err.code === 'TOO_LARGE')
return { ok: false, status: 413 };
return { ok: false, status: 400 };
}
+ if (args.isCurrent?.() === false) return { ok: false, status: 403 };
try {
const parsed = JSON.parse(text) as unknown;
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
@@ -168,6 +179,7 @@ export async function handleGhostOauthRequest(args: {
if (decl.tokenBroker !== undefined) return { status: 405 };
if (method === 'PUT' || method === 'POST') {
const parsed = await readJsonBody();
+ if (args.isCurrent?.() === false) return { status: 403 };
if (!parsed.ok) return { status: parsed.status };
const body = parsed.body;
const clientId = typeof body.clientId === 'string' ? body.clientId.trim() : '';
@@ -182,23 +194,25 @@ export async function handleGhostOauthRequest(args: {
}
try {
if (!(await runMutation(() =>
- manager.setClientConfig(ghostId, secretKey, clientId, clientSecret)))) {
+ manager.setClientConfig(instanceKey, secretKey, clientId, clientSecret)))) {
return { status: 500 };
}
notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
- log?.warn('ghost oauth client 凭证入库意外失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError || args.isCurrent?.() === false) return { status: 403 };
+ log?.warn('ghost oauth client 凭证入库意外失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
}
if (method === 'DELETE') {
try {
- await runMutation(() => manager.clearClientConfig(ghostId, secretKey));
+ await runMutation(() => manager.clearClientConfig(instanceKey, secretKey));
notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
- log?.warn('ghost oauth client 凭证清除意外失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError || args.isCurrent?.() === false) return { status: 403 };
+ log?.warn('ghost oauth client 凭证清除意外失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
}
@@ -207,9 +221,9 @@ export async function handleGhostOauthRequest(args: {
if (action === 'connect' && segments.length === 2) {
if (method !== 'POST') return { status: 405 };
- // tokenBroker 第一方门控·连接闸。官方前缀命中照今天放行;否则问接线处判据。
+ // tokenBroker 第一方门控·连接闸。接线处按可信安装事实判定,缺省拒绝。
const brokerAuthorized =
- args.isTokenBrokerAuthorized?.(ghostId) ?? isBrokerEligibleGhostId(ghostId);
+ args.isTokenBrokerAuthorized?.(instanceKey) === true;
if (decl.tokenBroker !== undefined && !brokerAuthorized) {
return {
status: 200,
@@ -224,10 +238,14 @@ export async function handleGhostOauthRequest(args: {
// 清单的非空子集;clientId 仅 broker 模式可从默认/备用声明值中选择。
// (设置页"只读连接"这类降面授权)。无 body / 空 body = 申请全量声明面;
// 越界或形态不对 400(意识不能借连接动作扩权,manager 侧还有防御性重验)。
+ const connectTarget = manager.captureConnectTarget
+ ? { expectedConnectTarget: manager.captureConnectTarget(instanceKey) }
+ : {};
let scopesOverride: string[] | undefined;
let clientIdOverride: string | undefined;
try {
const text = await readBodyText();
+ assertCurrent();
if (text.trim().length > 0) {
const parsed = JSON.parse(text) as unknown;
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
@@ -262,26 +280,31 @@ export async function handleGhostOauthRequest(args: {
}
}
} catch (err) {
+ if (err instanceof GhostProtocolTargetChangedError || args.isCurrent?.() === false) return { status: 403 };
if (err instanceof GhostKvError && err.code === 'TOO_LARGE') return { status: 413 };
return { status: 400 };
}
try {
const opts = {
+ ...connectTarget,
+ ...(args.isCurrent ? { assertCurrent } : {}),
...(scopesOverride !== undefined ? { scopes: scopesOverride } : {}),
...(clientIdOverride !== undefined ? { clientId: clientIdOverride } : {}),
...(networkHosts?.length ? { deliveryHosts: networkHosts } : {}),
};
const result = await manager.connectAccount(
- ghostId,
+ instanceKey,
secretKey,
decl,
Object.keys(opts).length > 0 ? opts : undefined,
);
+ assertCurrent();
// 结构化透传(ok:false 也是 200——授权被拒/超时是业务态不是协议错;
// detail 可能含服务端错误摘录,已由引擎保证不含凭证字节)。
return { status: 200, body: JSON.stringify(result) };
} catch (err) {
- log?.warn('ghost oauth 授权流程意外失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError || args.isCurrent?.() === false) return { status: 403 };
+ log?.warn('ghost oauth 授权流程意外失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
}
@@ -289,6 +312,7 @@ export async function handleGhostOauthRequest(args: {
if (action === 'insufficient-scopes' && segments.length === 2) {
if (method !== 'POST') return { status: 405 };
const parsed = await readJsonBody();
+ if (args.isCurrent?.() === false) return { status: 403 };
if (!parsed.ok) return { status: parsed.status };
const rawScopes = parsed.body.scopes;
if (!Array.isArray(rawScopes) || rawScopes.length === 0 || rawScopes.length > 320) {
@@ -304,7 +328,7 @@ export async function handleGhostOauthRequest(args: {
}
try {
const stored = await runMutation(() =>
- manager.reportInsufficientScopes(ghostId, secretKey, scopes, decl.scopes ?? []),
+ manager.reportInsufficientScopes(instanceKey, secretKey, scopes, decl.scopes ?? []),
);
if (stored === false) return { status: 500 };
// 证据未变时不广播:插件在用户重连前会反复撞同一权限错误并 fire-and-forget
@@ -312,7 +336,8 @@ export async function handleGhostOauthRequest(args: {
if (stored === 'stored') notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
- log?.warn('ghost oauth 缺失 scope 证据入库失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError || args.isCurrent?.() === false) return { status: 403 };
+ log?.warn('ghost oauth 缺失 scope 证据入库失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
}
@@ -322,11 +347,12 @@ export async function handleGhostOauthRequest(args: {
const accountId = segments[2];
if (!accountId) return { status: 404 };
try {
- await runMutation(() => manager.disconnectAccount(ghostId, secretKey, accountId));
+ await runMutation(() => manager.disconnectAccount(instanceKey, secretKey, accountId));
notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
- log?.warn('ghost oauth 断开账号意外失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError || args.isCurrent?.() === false) return { status: 403 };
+ log?.warn('ghost oauth 断开账号意外失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
}
@@ -334,17 +360,19 @@ export async function handleGhostOauthRequest(args: {
if (action === 'default' && segments.length === 2) {
if (method !== 'POST') return { status: 405 };
const parsed = await readJsonBody();
+ if (args.isCurrent?.() === false) return { status: 403 };
if (!parsed.ok) return { status: parsed.status };
const accountId = parsed.body.accountId;
if (typeof accountId !== 'string' || accountId.length === 0) return { status: 400 };
try {
- if (!(await runMutation(() => manager.setDefaultAccount(ghostId, secretKey, accountId)))) {
+ if (!(await runMutation(() => manager.setDefaultAccount(instanceKey, secretKey, accountId)))) {
return { status: 404 };
}
notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
- log?.warn('ghost oauth 设默认账号意外失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError || args.isCurrent?.() === false) return { status: 403 };
+ log?.warn('ghost oauth 设默认账号意外失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
}
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostProtocolTargetGuard.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostProtocolTargetGuard.ts
new file mode 100644
index 0000000000..e4c38bf261
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostProtocolTargetGuard.ts
@@ -0,0 +1,9 @@
+export class GhostProtocolTargetChangedError extends Error {
+ constructor() {
+ super('Plugin request target changed');
+ }
+}
+
+export function assertGhostProtocolTargetCurrent(isCurrent?: () => boolean): void {
+ if (isCurrent?.() === false) throw new GhostProtocolTargetChangedError();
+}
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
index bbde4b7d53..2d0cbc3fde 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
@@ -36,6 +36,7 @@
import { GHOST_SECRET_VALUE_MAX_CHARS } from '../../../shared/ghost.js';
import { GhostKvError } from '../ghostKvStore.js';
+import { assertGhostProtocolTargetCurrent, GhostProtocolTargetChangedError } from './ghostProtocolTargetGuard.js';
/** 单条凭证值的字符上限(粘贴的 key/token 量级;超限 413)。 */
export { GHOST_SECRET_VALUE_MAX_CHARS };
@@ -48,12 +49,12 @@ export interface GhostSecretsRequestOutcome {
/** 保险库最小面(main 侧 providerSecretStore 注入;测试喂内存假体)。 */
export interface GhostSecretsVault {
- saved(ghostId: string, secretKey: string): boolean;
+ saved(instanceKey: string, secretKey: string): boolean;
/** 尾 4 位指纹(预截值;老键由真身懒回填);值太短不产时返回 null。 */
- tail(ghostId: string, secretKey: string): string | null;
+ tail(instanceKey: string, secretKey: string): string | null;
/** 返回 false = safeStorage 写失败(端点折叠 500)。store 内部连带截存指纹。 */
- store(ghostId: string, secretKey: string, value: string): boolean;
- remove(ghostId: string, secretKey: string): void;
+ store(instanceKey: string, secretKey: string, value: string): boolean;
+ remove(instanceKey: string, secretKey: string): void;
}
export async function handleGhostSecretsRequest(args: {
@@ -82,6 +83,7 @@ export async function handleGhostSecretsRequest(args: {
}>;
vault: GhostSecretsVault;
ghostId: string;
+ isCurrent?: () => boolean;
/**
* 入库成功(PUT/POST → 204)后的通知钩子(2026-07-14):调用方拿它广播
* "凭证已保存"的主机代言 tips。只报成功——失败面(400/413/500)设置页
@@ -90,7 +92,8 @@ export async function handleGhostSecretsRequest(args: {
onStored?: (secretKey: string) => void;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}): Promise<GhostSecretsRequestOutcome> {
- const { method, pathname, readBodyText, userSecretKeys, vault, ghostId, log } = args;
+ const { method, pathname, readBodyText, userSecretKeys, vault, ghostId: instanceKey, log } = args;
+ if (args.isCurrent?.() === false) return { status: 403 };
const identityKeys = args.identitySecretKeys ?? [];
const managedStates = args.managedSecretStates ?? [];
const managedKeys = managedStates.map(({ key }) => key);
@@ -102,9 +105,9 @@ export async function handleGhostSecretsRequest(args: {
if (method !== 'GET') return { status: 405 };
try {
const userList = userSecretKeys.map((key) => {
- const saved = vault.saved(ghostId, key);
+ const saved = vault.saved(instanceKey, key);
// 指纹只在"确实存了"时给(没存过的键即便留有孤儿指纹也不回)。
- const tail = saved ? vault.tail(ghostId, key) : null;
+ const tail = saved ? vault.tail(instanceKey, key) : null;
const hostState = hostCredentialStates.get(key);
const hostFields = hostState
? {
@@ -127,7 +130,7 @@ export async function handleGhostSecretsRequest(args: {
}));
return { status: 200, body: JSON.stringify([...userList, ...identityList, ...managedList]) };
} catch (err) {
- log?.warn('ghost secrets 状态回查失败', { ghostId, err: String(err) });
+ log?.warn('ghost secrets 状态回查失败', { instanceKey, err: String(err) });
return { status: 500 };
}
}
@@ -145,9 +148,11 @@ export async function handleGhostSecretsRequest(args: {
try {
text = await readBodyText();
} catch (err) {
+ if (args.isCurrent?.() === false || err instanceof GhostProtocolTargetChangedError) return { status: 403 };
if (err instanceof GhostKvError && err.code === 'TOO_LARGE') return { status: 413 };
return { status: 400 };
}
+ if (args.isCurrent?.() === false) return { status: 403 };
let parsed: unknown;
try {
parsed = JSON.parse(text);
@@ -161,17 +166,18 @@ export async function handleGhostSecretsRequest(args: {
if (typeof value !== 'string' || value.trim().length === 0) return { status: 400 };
if (value.length > GHOST_SECRET_VALUE_MAX_CHARS) return { status: 413 };
try {
- if (!vault.store(ghostId, secretKey, value.trim())) return { status: 500 };
+ assertGhostProtocolTargetCurrent(args.isCurrent);
+ if (!vault.store(instanceKey, secretKey, value.trim())) return { status: 500 };
} catch (err) {
- log?.warn('ghost secret 入库意外失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError) return { status: 403 };
+ log?.warn('ghost secret 入库意外失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
// 通知钩子在入库成功之外单独兜:提示挂了不能把真成功折叠成 500。
try {
args.onStored?.(secretKey);
} catch (err) {
- log?.warn('ghost secret onStored 通知失败(不影响入库结果)', {
- ghostId,
+ log?.warn('ghost secret onStored 通知失败(不影响入库结果)', { instanceKey,
secretKey,
err: String(err),
});
@@ -181,10 +187,12 @@ export async function handleGhostSecretsRequest(args: {
if (method === 'DELETE') {
try {
- vault.remove(ghostId, secretKey);
+ assertGhostProtocolTargetCurrent(args.isCurrent);
+ vault.remove(instanceKey, secretKey);
return { status: 204 };
} catch (err) {
- log?.warn('ghost secret 清除意外失败', { ghostId, secretKey, err: String(err) });
+ if (err instanceof GhostProtocolTargetChangedError) return { status: 403 };
+ log?.warn('ghost secret 清除意外失败', { instanceKey, secretKey, err: String(err) });
return { status: 500 };
}
}
diff --git a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts b/apps/desktop/src/main/cindy-brain/scheduleSlot.ts
index d3e2e70bfe..d7fbf312c9 100644
--- a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/scheduleSlot.ts
@@ -33,6 +33,8 @@
import { randomUUID } from 'node:crypto';
+import { hasDeliveryNamespace } from '../../shared/pluginIdentity.js';
+
import {
GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_MS,
GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS,
@@ -200,13 +202,27 @@ export class GhostScheduleSlot {
)
: undefined;
+ const logicalId = ghost.manifest.id;
+ const pending = ghost.namespaceState === 'pending' || !hasDeliveryNamespace(ghost);
+ const address = pending
+ ? `
+
+调用这个插件时只传 ghost_id「${logicalId}」,不要传 namespace。`
+ : ghost.namespace
+ ? `
+
+调用这个插件时使用 ghost_id「${logicalId}」,namespace 传「${ghost.namespace}」。`
+ : `
+
+调用这个插件时使用 ghost_id「${logicalId}」,namespace 传 null。`;
const draft: GhostScheduleDraftPush = {
requestId: this.deps.newRequestId?.() ?? randomUUID(),
- ghostId,
+ ghostId: logicalId,
+ ...(pending ? {} : { namespace: ghost.namespace ?? null }),
ghostName: ghost.manifest.name,
...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
name,
- prompt,
+ prompt: prompt + address,
...(intervalMs !== undefined ? { intervalMs } : {}),
};
const delivered = typeof request.mobilePageId === 'string'
diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.ts
index 3ff8bbb3b2..0ffa6733d9 100644
--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts
@@ -18,10 +18,14 @@ import matter from 'gray-matter';
import {
GHOST_SKILL_NAME_RE,
- isValidGhostId,
type GhostSkillItem,
type InstalledGhost,
} from '../../shared/ghost.js';
+import {
+ installedGhostStoragePart,
+ parsePluginInstallRelId,
+ parsePluginStoragePart,
+} from '../../shared/pluginIdentity.js';
import { parseAndValidateFrontmatter } from '../skillhub/frontmatterValidation.js';
import { sharedGlobalSkillsPaths } from '../maker-host/shared-global-skills.js';
@@ -273,7 +277,8 @@ function targetLooksGhostManaged(
if (splitAt <= 0) return false;
const ghostId = linkName.slice(0, splitAt);
const skillName = linkName.slice(splitAt + 2);
- if (!isValidGhostId(ghostId) || !GHOST_SKILL_NAME_RE.test(skillName)) return false;
+ const identity = parsePluginStoragePart(ghostId);
+ if (!identity || !GHOST_SKILL_NAME_RE.test(skillName)) return false;
// 目标结构必须命中**我们铺过的两种布局之一**,且布局里的 id 段必须等于链接名里
// 的 ghostId —— 单看"路径里有个段叫 cindy-brain"会把用户指向自己项目目录
@@ -283,15 +288,20 @@ function targetLooksGhostManaged(
// 新模型: .../<状态根名>/skill-snapshots/<ghostId>/<revision>/...
const segments = target.split(/[\\/]/).map((segment) => segment.toLowerCase());
const stateDirName = approvalStateDirName.toLowerCase();
- const idLower = ghostId.toLowerCase();
+ const idLower = identity.ghostId.toLowerCase();
const normalizedTarget = normalizeForCompare(target);
if (!managedRoots.some((root) => isSameOrInside(normalizedTarget, root))) return false;
return segments.some(
- (segment, index) =>
- (segment === 'cindy-brain' && segments[index + 1] === idLower) ||
- (segment === stateDirName &&
- segments[index + 1] === 'skill-snapshots' &&
- segments[index + 2] === idLower),
+ (segment, index) => {
+ if (segment === 'cindy-brain' && segments[index + 1] === idLower) return true;
+ if (segment !== stateDirName || segments[index + 1] !== 'skill-snapshots') return false;
+ if (segments[index + 2] === idLower) return true;
+ const relId = segments.slice(index + 2, index + 5).join('/');
+ const targetIdentity = parsePluginInstallRelId(relId);
+ return targetIdentity !== null && targetIdentity.ghostId === identity.ghostId &&
+ (targetIdentity.namespace === null ? identity.namespace === null
+ : identity.namespace === null || targetIdentity.namespace === identity.namespace);
+ },
);
}
@@ -365,7 +375,9 @@ export async function reconcileGhostSkillLinks(
a.name.localeCompare(b.name),
);
for (const item of sortedItems) {
- const linkName = ghostSkillLinkName(ghost.manifest.id, item.name);
+ const linkName = ghostSkillLinkName(
+ installedGhostStoragePart(ghost), item.name,
+ );
if (desired.has(linkName)) {
warnings.push(`技能链接名冲突 ${linkName},保留先到者`);
continue;
diff --git a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
index 66eac14d2c..d64dc5cb3d 100644
--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
@@ -46,6 +46,7 @@ import {
import { isGhostOwnerScopeUsable, type GhostOwnerScope } from './ghostOwnerScope.js';
import { getDbClient } from '../localDb/client/current.js';
import * as localDbSchema from '../localDb/schema.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
/** block 理由展示上限(超长截断,防意识用理由塞小作文)。 */
const BLOCK_REASON_MAX_CHARS = 200;
@@ -224,7 +225,7 @@ export class GhostSubscriptionGateway {
name: GhostDidEventName,
data: GhostDidEventData,
): void {
- const ghostId = ghost.manifest.id;
+ const ghostId = installedGhostStoragePart(ghost);
const e = this.entry(ghostId);
const ownerScope = this.captureOwnerScope();
if (!this.ownerScopeUsable(ownerScope)) {
@@ -292,23 +293,24 @@ export class GhostSubscriptionGateway {
private kickWake(ghost: InstalledGhost, e: SubEntry, ownerScope: unknown): void {
if (e.waking) return;
if (!this.ownerScopeUsable(ownerScope)) {
- this.invalidateOwner(ghost.manifest.id, e);
+ this.invalidateOwner(installedGhostStoragePart(ghost), e);
return;
}
e.waking = true;
void this.deps
.wake(ghost)
.then(() => {
+ if (this.entries.get(installedGhostStoragePart(ghost)) !== e) return;
if (!this.ownerScopeUsable(ownerScope)) {
- this.invalidateOwner(ghost.manifest.id, e);
+ this.invalidateOwner(installedGhostStoragePart(ghost), e);
return;
}
- this.flush(ghost.manifest.id, e, ownerScope);
+ this.flush(installedGhostStoragePart(ghost), e, ownerScope);
})
.catch((err) => {
// 唤醒失败缓冲保留(封顶丢最旧),下一条事件再试。
this.deps.log?.warn('ghost subscribe wake failed', {
- ghostId: ghost.manifest.id,
+ ghostId: installedGhostStoragePart(ghost),
error: err instanceof Error ? err.message : String(err),
});
})
@@ -376,7 +378,7 @@ export class GhostSubscriptionGateway {
for (const ghost of this.deps.listGhosts()) {
if (!ghost.enabled) continue;
if (!ghost.manifest.subscribe?.hooks?.includes('will-user-message')) continue;
- const ghostId = ghost.manifest.id;
+ const ghostId = installedGhostStoragePart(ghost);
const e = this.entry(ghostId);
if (e.hookFused) continue;
context ??= this.resolveMessageHookContext(input.sessionId, GHOST_HOOK_TIMEOUT_MS / 2);
@@ -405,7 +407,7 @@ export class GhostSubscriptionGateway {
if (rewritten && lastRewriteGhost) {
return {
action: 'rewrite',
- ghostId: lastRewriteGhost.manifest.id,
+ ghostId: installedGhostStoragePart(lastRewriteGhost),
ghostName: lastRewriteGhost.manifest.name,
text: currentText,
};
@@ -440,7 +442,7 @@ export class GhostSubscriptionGateway {
for (const ghost of this.deps.listGhosts()) {
if (!ghost.enabled) continue;
if (!ghost.manifest.subscribe?.hooks?.includes('will-assistant-message')) continue;
- const ghostId = ghost.manifest.id;
+ const ghostId = installedGhostStoragePart(ghost);
const e = this.entry(ghostId);
if (e.hookFused) continue;
context ??= this.resolveMessageHookContext(
@@ -475,7 +477,7 @@ export class GhostSubscriptionGateway {
if (renderGhost) {
return {
action: 'render',
- ghostId: renderGhost.manifest.id,
+ ghostId: installedGhostStoragePart(renderGhost),
ghostName: renderGhost.manifest.name,
html: renderHtml,
height: renderHeight,
@@ -485,7 +487,7 @@ export class GhostSubscriptionGateway {
if (lastRewriteGhost) {
return {
action: 'rewrite',
- ghostId: lastRewriteGhost.manifest.id,
+ ghostId: installedGhostStoragePart(lastRewriteGhost),
ghostName: lastRewriteGhost.manifest.name,
text: currentText,
};
@@ -504,7 +506,7 @@ export class GhostSubscriptionGateway {
ownerStamp?: unknown,
ownerScope?: unknown,
): Promise<HookVerdict | null> {
- const ghostId = ghost.manifest.id;
+ const ghostId = installedGhostStoragePart(ghost);
const hookId = this.deps.newHookId?.() ?? randomUUID();
// 超时按钩子分:入口(user-message)必须快(挡发送);出口(assistant-message)
// 是后台后置钩,容许长处理(见 GHOST_ASSISTANT_HOOK_TIMEOUT_MS)。
@@ -602,14 +604,14 @@ export class GhostSubscriptionGateway {
): void {
e.hookFails += 1;
this.deps.log?.warn('ghost hook failed (fail-open)', {
- ghostId: ghost.manifest.id,
+ ghostId: installedGhostStoragePart(ghost),
why,
fails: e.hookFails,
});
if (e.hookFails >= GHOST_HOOK_FUSE_THRESHOLD && !e.hookFused) {
e.hookFused = true;
this.deps.log?.warn('ghost hook fused: degraded to observe-only', {
- ghostId: ghost.manifest.id,
+ ghostId: installedGhostStoragePart(ghost),
});
this.deps.onHookFused?.(ghost, ownerStamp);
}
@@ -636,6 +638,13 @@ export class GhostSubscriptionGateway {
/** 意识停用/抽离时清态(缓冲、熔断、seq 全部归零;待决钩子按超时自然收口)。 */
dropGhost(ghostId: string): void {
+ const entry = this.entries.get(ghostId);
+ if (entry) entry.buffer.length = 0;
+ for (const [hookId, pending] of this.pendingHooks) {
+ if (pending.ghostId !== ghostId) continue;
+ this.pendingHooks.delete(hookId);
+ pending.resolve(null);
+ }
this.entries.delete(ghostId);
}
}
diff --git a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts
index 755dea96f8..b8cce816b8 100644
--- a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts
@@ -61,6 +61,7 @@ export interface WorkspaceSessionService {
export interface WorkspaceSlotDeps {
getGhost(id: string): InstalledGhost | null;
+ getMutationTarget(id: string): string | null;
/**
* 弹系统级选文件夹窗口;返回所选绝对路径,取消返回 null。
* 找不到可挂靠的 Cindy 窗口时应 reject(失败关闭,不弹无主对话框)。
@@ -144,6 +145,10 @@ export class GhostWorkspaceSlot {
if (!service) {
return fail('HOST_NOT_READY', '会话服务尚未准备好,请稍后再试');
}
+ const mutationTarget = this.deps.getMutationTarget(ghostId);
+ if (mutationTarget === null) {
+ return fail('PERMISSION_DENIED', '插件安装授权已失效,请重新发起工作区请求');
+ }
// 骚扰钳制:限速按尝试记账(spam 顺延窗口),再看全局在场标记。
const now = this.deps.now?.() ?? Date.now();
@@ -163,6 +168,13 @@ export class GhostWorkspaceSlot {
let dirAbs: string;
let sourceSessionId: string | undefined;
let callIsCurrent: (() => boolean) | undefined = shouldContinue;
+ const isCurrent = () => {
+ const current = this.deps.getGhost(ghostId);
+ return current?.enabled === true && current.manifest.workspace === true &&
+ this.deps.getMutationTarget(ghostId) === mutationTarget &&
+ (!callIsCurrent || callIsCurrent());
+ };
+ const cancelled = () => fail('CANCELLED', '插件或发起任务已变化,请重新发起工作区请求');
if (request.mode === 'pick') {
this.consentInFlight = true;
let picked: string | null;
@@ -182,7 +194,7 @@ export class GhostWorkspaceSlot {
} finally {
this.consentInFlight = false;
}
- if (shouldContinue && !shouldContinue()) return fail('CANCELLED', 'The originating page has closed.');
+ if (!isCurrent()) return cancelled();
if (picked === null) {
return fail('CANCELLED', '用户取消了选择');
}
@@ -220,9 +232,11 @@ export class GhostWorkspaceSlot {
&& current?.sessionInstanceId === ctx.sessionInstanceId;
};
const stat = await this.deps.statDir(request.dir);
+ if (!isCurrent()) return cancelled();
if (stat === 'not-found') return fail('DIR_NOT_FOUND', '目录不存在(只支持本机已存在的目录)');
if (stat === 'not-directory') return fail('NOT_DIRECTORY', '该路径不是目录');
const dirInfo = await this.deps.getSessionDirInfo(ctx.sessionId);
+ if (!isCurrent()) return cancelled();
// fail closed:快照读不到(查无会话/读失败)或远程(SSH)会话一律硬拒
// ——证明不了"本机工作区语境"就连确认卡也不发,防快照失败把远程会话
// 漏进确认卡路径(与管子契约"远程一律拒"一致)。
@@ -249,6 +263,7 @@ export class GhostWorkspaceSlot {
toolAutoReviewAction('plugin_workspace', { ghostId, dir: request.dir, title, focus: request.focus },
'Ensure a local draft task exists in this directory. This does not start an agent.'))
: undefined;
+ if (!isCurrent()) return cancelled();
confirmed = review?.verdict === 'allow' ? { ok: true }
: review?.verdict === 'block' ? { ok: false, message: review.reason ?? 'Automatic review denied this workspace request.' }
: await this.deps.confirmDir({
@@ -267,6 +282,7 @@ export class GhostWorkspaceSlot {
} finally {
this.consentInFlight = false;
}
+ if (!isCurrent()) return cancelled();
if (!confirmed.ok) {
return fail('CANCELLED', confirmed.message);
}
@@ -278,19 +294,18 @@ export class GhostWorkspaceSlot {
const name = path.basename(dirAbs) || dirAbs;
const ensure = async (): Promise<GhostPipeWorkspaceResult> => {
try {
- if (callIsCurrent && !callIsCurrent()) return fail('CANCELLED', 'The originating tool call has ended.');
+ if (!isCurrent()) return cancelled();
const existing = await service.findActiveSessionByWorkdir(dirAbs);
- if (callIsCurrent && !callIsCurrent()) return fail('CANCELLED', 'The originating tool call has ended.');
+ if (!isCurrent()) return cancelled();
if (existing) {
if (request.focus === true) service.focusSession(existing);
this.deps.log?.info('ghost workspace ensured (reused)', { ghostId, sessionId: existing });
return { ok: true, sessionId: existing, created: false, name };
}
- const sessionId = await service.createDraftSession({ dirAbs, title, ghostId,
+ const sessionId = await service.createDraftSession({ dirAbs, title, ghostId, shouldContinue: isCurrent,
...(sourceSessionId ? { sourceSessionId } : {}),
- ...(callIsCurrent ? { shouldContinue: callIsCurrent } : {}),
});
- if (!sessionId || (callIsCurrent && !callIsCurrent())) return fail('CANCELLED', 'The originating tool call has ended.');
+ if (!sessionId || !isCurrent()) return cancelled();
if (request.focus === true) service.focusSession(sessionId);
this.deps.log?.info('ghost workspace ensured (created)', { ghostId, sessionId });
return { ok: true, sessionId, created: true, name };
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
index 34ca5f5edc..5ddab9cb84 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts
@@ -75,6 +75,25 @@ describe('recordBlob(幂等入账)', () => {
});
describe('addRef / removeRefs(引用增删)', () => {
+ it('moves only the old physical ghost media ownership and remains safe to replay', async () => {
+ await seedBlob(HASH_A);
+ await seedBlob(HASH_B);
+ await ledger.addRef({ hash: HASH_A, refKind: 'ghost-gallery', refId: 'helper', originKind: 'ghost', originId: 'helper' }, db);
+ await ledger.addRef({ hash: HASH_B, refKind: 'ghost-grant', refId: 'helper', originKind: 'user' }, db);
+ await seedSession('session-1', 'active');
+ await ledger.addRef({ hash: HASH_B, refKind: 'message', refId: 'helper', originSessionId: 'session-1', originKind: 'tool', originId: 'helper' }, db);
+ await ledger.relocateGhostMediaRefs('helper', '_ns__acme__helper', db);
+ await ledger.relocateGhostMediaRefs('helper', '_ns__acme__helper', db);
+ expect(await ledger.ghostCanRead(HASH_A, 'helper', db)).toBe(false);
+ expect(await ledger.ghostCanRead(HASH_A, '_ns__acme__helper', db)).toBe(true);
+ expect(await ledger.ghostCanRead(HASH_B, 'helper', db)).toBe(false);
+ expect(await ledger.ghostCanRead(HASH_B, '_ns__acme__helper', db)).toBe(true);
+ expect(await ledger.listGhostGallery('helper', db)).toHaveLength(0);
+ expect(await ledger.listGhostGallery('_ns__acme__helper', db)).toHaveLength(1);
+ const messageRef = (await db.select().from(schema.mediaRefs).all()).find((row) => row.refKind === 'message');
+ expect(messageRef?.refId).toBe('helper');
+ });
+
it('未入账的指纹加引用被 FK 拒绝(先记 blob 后记 ref 的顺序由类型层保证)', async () => {
await expect(
ledger.addRef(
diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.ts
index d0ca909381..ba6adb554e 100644
--- a/apps/desktop/src/main/cindy-media/ledger.ts
+++ b/apps/desktop/src/main/cindy-media/ledger.ts
@@ -17,7 +17,7 @@
*/
import { randomUUID } from 'node:crypto';
-import { and, asc, desc, eq, exists, lt, ne, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, exists, inArray, lt, ne, or, sql } from 'drizzle-orm';
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
import { getDbClient } from '../localDb/client/current';
@@ -59,6 +59,24 @@ export async function withSessionMediaRefLock<T>(
}
}
+const ghostOwnedRefKinds = [
+ 'ghost-gallery', 'ghost-grant', 'ghost-tool-grant', 'ghost-deposit',
+] as const;
+
+export async function relocateGhostMediaRefs(
+ fromId: string,
+ toId: string,
+ db: LedgerDb = defaultDb(),
+): Promise<void> {
+ if (fromId === toId) return;
+ const ownedOrigin = and(eq(mediaRefs.originKind, 'ghost'), eq(mediaRefs.originId, fromId));
+ const ownedRef = and(inArray(mediaRefs.refKind, ghostOwnedRefKinds), eq(mediaRefs.refId, fromId));
+ await db.update(mediaRefs).set({
+ originId: sql`case when ${ownedOrigin} then ${toId} else ${mediaRefs.originId} end`,
+ refId: sql`case when ${ownedRef} then ${toId} else ${mediaRefs.refId} end`,
+ }).where(or(ownedOrigin, ownedRef)).run();
+}
+
/** Shared task reads use existing provenance; knowing a blob hash grants nothing. */
export async function sessionCanRead(hash: string, sessionId: string, db: LedgerDb = defaultDb()): Promise<boolean> {
const rows = await db.select({ one: sql`1` }).from(mediaRefs).where(and(
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
index 6aa3db7aea..f8c57f86b2 100644
--- a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
@@ -398,6 +398,18 @@ describe('multi-instance isolation', () => {
h.controller.open('b');
expect(winB.show).toHaveBeenCalled();
});
+ it('same ghostId in different namespaces get independent windows', () => {
+ const h = makeHarness(new Set(['helper', '_ns__acme__helper']));
+ h.controller.setDetached('helper', true);
+ h.controller.setDetached('_ns__acme__helper', true);
+ expect(h.created).toHaveLength(2);
+ expect(h.created[0].ghostId).toBe('helper');
+ expect(h.created[1].ghostId).toBe('_ns__acme__helper');
+ h.controller.setDetached('helper', false);
+ expect(h.created[0].win.isDestroyed()).toBe(true);
+ expect(h.created[1].win.isDestroyed()).toBe(false);
+ });
+
it('setDetached(false) on one ghost does not affect another', () => {
const h = makeHarness(new Set(['a', 'b']));
@@ -528,9 +540,35 @@ describe('reconcile', () => {
expect(h.created[0].win.isDestroyed()).toBe(true);
expect(h.entries().a).toEqual({ detached: false, lastOpen: false });
});
+ it('reconcile keeps a namespaced detached window and does not treat it as the root id', () => {
+ const h = makeHarness(new Set(['_ns__acme__helper']));
+ h.controller.setDetached('_ns__acme__helper', true);
+ const org = ghost('helper');
+ org.namespace = 'acme';
+ org.dir = '/fake/_ns/acme/helper';
+ h.controller.reconcile([org]);
+ expect(h.created[0].win.isDestroyed()).toBe(false);
+ expect(h.entries()['_ns__acme__helper']).toEqual({ detached: true, lastOpen: true });
+ });
+
});
describe('two-phase ready + sender guard', () => {
+ it('keeps a legacy organization window when a same-name root is installed separately', () => {
+ const h = makeHarness(new Set(['helper', '_root__helper']));
+ h.controller.setDetached('helper', true);
+ const oldWindow = h.created[0].win;
+ const org = ghost('helper');
+ org.namespace = 'acme';
+ org.dir = '/fake/helper';
+ const root = ghost('helper');
+ root.namespace = null;
+ root.dir = '/fake/_ns/_root/helper';
+ h.controller.reconcile([org, root]);
+ expect(oldWindow.isDestroyed()).toBe(false);
+ expect(h.entries().helper).toEqual({ detached: true, lastOpen: true });
+ expect(h.entries()['_root__helper']).toBeUndefined();
+ });
it('markRendererReady from correct sender succeeds', () => {
const h = makeHarness(new Set(['a']));
h.controller.prewarm('a');
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts
index c23dc5f4d9..6fd83e3c00 100644
--- a/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts
@@ -91,7 +91,7 @@ describe('ghost panel preload contract', () => {
expect(source).toContain("return ipcRenderer.invoke('maker:ghost-panel-window:open', ghostId);");
expect(source).toContain("return ipcRenderer.invoke('maker:ghost-panel-window:set-detached', ghostId, detached);");
expect(source).toContain("ipcRenderer.invoke('ghosts:reload', id)");
- expect(source).toContain("ipcRenderer.invoke('ghosts:set-enabled', id, enabled)");
+ expect(source).toContain("ipcRenderer.invoke('ghosts:set-enabled', id, enabled, expectedInstalledApproval)");
expect(source).toContain("return ipcRenderer.invoke('ghosts:clear-unread', id, seenAt);");
});
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts
index f65d767001..b147a832cf 100644
--- a/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts
@@ -67,6 +67,23 @@ describe('normalizeGhostPanelWindowsSettings', () => {
}),
).toEqual({ windows: { good: { detached: false, lastOpen: true } } });
});
+
+ it('企业实例 storage part 是合法键,斜杠目录 id 丢弃', () => {
+ expect(
+ normalizeGhostPanelWindowsSettings({
+ windows: {
+ '_ns__acme__helper': { detached: true, lastOpen: true },
+ '_ns/acme/helper': { detached: true, lastOpen: true },
+ helper: { detached: false, lastOpen: false },
+ },
+ }),
+ ).toEqual({
+ windows: {
+ '_ns__acme__helper': { detached: true, lastOpen: true },
+ helper: { detached: false, lastOpen: false },
+ },
+ });
+ });
});
describe('runtime state', () => {
diff --git a/apps/desktop/src/main/ghost-panel-window/controller.ts b/apps/desktop/src/main/ghost-panel-window/controller.ts
index 02a27f6324..b2387b7683 100644
--- a/apps/desktop/src/main/ghost-panel-window/controller.ts
+++ b/apps/desktop/src/main/ghost-panel-window/controller.ts
@@ -26,12 +26,11 @@ import {
GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL,
GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL,
GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL,
- GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL,
- GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL,
GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL,
} from '../../shared/ghostPanelWindow.js';
import type { SupportedLocale } from '../../shared/locale.js';
import type { InstalledGhost } from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
import type { GhostPanelWindowsSettings } from './settings-store.js';
interface ControllerLogger {
@@ -191,6 +190,7 @@ export class GhostPanelWindowsController {
return this.getState();
}
+
// ── 双阶段就绪 ──────────────────────────────────────────────────────
markRendererReady(sender: WebContents): void {
@@ -249,7 +249,7 @@ export class GhostPanelWindowsController {
// ── reconcile ──────────────────────────────────────────────────────
reconcile(ghosts: InstalledGhost[]): void {
- const byId = new Map(ghosts.map((g) => [g.manifest.id, g]));
+ const byId = new Map(ghosts.map((g) => [installedGhostStoragePart(g), g]));
const knownIds = new Set([
...Object.keys(this.deps.settings.read().windows),
...this.slots.keys(),
@@ -296,7 +296,7 @@ export class GhostPanelWindowsController {
/** 主窗口销毁时回收所有隐藏窗口;controller 仍可随下一扇主窗重新预热。 */
destroyAllWindows(): void {
- for (const [id, slot] of this.slots) {
+ for (const [, slot] of this.slots) {
this.clearTimeouts(slot);
if (!slot.win.isDestroyed()) {
slot.destroyingWindow = true;
diff --git a/apps/desktop/src/main/ghost-panel-window/ipc.ts b/apps/desktop/src/main/ghost-panel-window/ipc.ts
index a0056e66e5..5cd0c87d9f 100644
--- a/apps/desktop/src/main/ghost-panel-window/ipc.ts
+++ b/apps/desktop/src/main/ghost-panel-window/ipc.ts
@@ -15,7 +15,7 @@ import { MAKER_INVOKE } from '../maker-ipc/channels.js';
import { createLogger } from '../logger.js';
import { assertTrustedAppRendererEvent, isTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { throwIpcError } from '../utils/ipcValidate.js';
-import { isValidGhostId } from '../../shared/ghost.js';
+import { isValidPluginStoragePart } from '../../shared/pluginIdentity.js';
import {
GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL,
GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL,
@@ -36,7 +36,7 @@ export function registerGhostPanelWindowIpc(controller: GhostPanelWindowsControl
ipcMain.handle(MAKER_INVOKE.GHOST_PANEL_WINDOW_OPEN, (event, ghostId: unknown) => {
assertTrustedAppRendererEvent(event);
- if (!isValidGhostId(ghostId)) {
+ if (!isValidPluginStoragePart(ghostId)) {
throwIpcError('INVALID_PARAMS', 'ghostId must be a valid ghost id');
}
controller.open(ghostId);
@@ -46,7 +46,7 @@ export function registerGhostPanelWindowIpc(controller: GhostPanelWindowsControl
MAKER_INVOKE.GHOST_PANEL_WINDOW_SET_DETACHED,
(event, ghostId: unknown, detached: unknown) => {
assertTrustedAppRendererEvent(event);
- if (!isValidGhostId(ghostId)) {
+ if (!isValidPluginStoragePart(ghostId)) {
throwIpcError('INVALID_PARAMS', 'ghostId must be a valid ghost id');
}
if (typeof detached !== 'boolean') {
diff --git a/apps/desktop/src/main/ghost-panel-window/settings-store.ts b/apps/desktop/src/main/ghost-panel-window/settings-store.ts
index 92258a8fe0..2a3e2a320e 100644
--- a/apps/desktop/src/main/ghost-panel-window/settings-store.ts
+++ b/apps/desktop/src/main/ghost-panel-window/settings-store.ts
@@ -10,7 +10,7 @@ import { app } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
-import { isValidGhostId } from '../../shared/ghost.js';
+import { isValidPluginStoragePart } from '../../shared/pluginIdentity.js';
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
const log = desktopMakerLogger.child('ghost-panel-window-settings-store');
@@ -37,7 +37,7 @@ export function normalizeGhostPanelWindowsSettings(raw: unknown): GhostPanelWind
if (!rawWindows || typeof rawWindows !== 'object') return { windows: {} };
const windows: Record<string, GhostPanelWindowEntrySettings> = {};
for (const [id, entry] of Object.entries(rawWindows as Record<string, unknown>)) {
- if (!isValidGhostId(id)) continue;
+ if (!isValidPluginStoragePart(id)) continue;
if (!entry || typeof entry !== 'object') continue;
const e = entry as Record<string, unknown>;
if (typeof e.detached !== 'boolean' || typeof e.lastOpen !== 'boolean') continue;
diff --git a/apps/desktop/src/main/ghost-panel-window/window.ts b/apps/desktop/src/main/ghost-panel-window/window.ts
index d6f34c90e5..2a94cf832b 100644
--- a/apps/desktop/src/main/ghost-panel-window/window.ts
+++ b/apps/desktop/src/main/ghost-panel-window/window.ts
@@ -3,7 +3,7 @@
*
* 蓝本是 right-sidebar-window/window.ts,差异:
* - 按 ghostId 多实例:窗口位置记忆每插件一份
- * (ghost-panel-window-state-<id>.json,id 字符集 [a-z0-9-] 文件名安全);
+ * (ghost-panel-window-state-<id>.json,id 为 storage part,文件名安全);
* - webPreferences 按 electron-security-and-process-boundaries §3 显式带全量
* 安全项(该规则晚于主窗/RSB 窗,新窗口必须逐项写明,不吃默认值);
* - `webviewTag: true`:面板体就是 <webview>(cindy-ghost:// 分区)。附加闸/
diff --git a/apps/desktop/src/main/git-context/githubSetupIpc.ts b/apps/desktop/src/main/git-context/githubSetupIpc.ts
index 67ffa3cfb5..fc57f93a74 100644
--- a/apps/desktop/src/main/git-context/githubSetupIpc.ts
+++ b/apps/desktop/src/main/git-context/githubSetupIpc.ts
@@ -7,6 +7,11 @@ import { createGithubSetup } from './githubSetup.js';
import { getSharedGhCliTokenSource } from './ghCliTokenSource.js';
import { githubConnection } from './githubConnection.js';
import { readGhostSecret } from '../secrets/providerSecretStore.js';
+import {
+ createPluginLogicalIdentity,
+ pluginInstallStoragePart,
+ pluginNewInstallRelId,
+} from '../../shared/pluginIdentity.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { activeOwnerScopeKey } from '../appSessionState.js';
import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus.js';
@@ -24,9 +29,12 @@ export function registerGithubSetupIpc(invalidateStatuses: () => void): void {
}
};
const setup = createGithubSetup(root, changed);
- const unsubscribe = getGhostSetupChangeBus().subscribe('cindy-github', (event) => {
+ const cindyGithubRootInstance = pluginInstallStoragePart(
+ pluginNewInstallRelId(createPluginLogicalIdentity(null, 'cindy-github')),
+ );
+ const unsubscribes = ['cindy-github', cindyGithubRootInstance].map(id => getGhostSetupChangeBus().subscribe(id, (event) => {
if (event.source === 'secret') changed();
- });
+ }));
for (const [channel, handle] of [
[
'git-context:github-setup:connection',
@@ -37,7 +45,9 @@ export function registerGithubSetupIpc(invalidateStatuses: () => void): void {
const result = await githubConnection({
readGh: () => source.readToken(),
readFallback: () =>
- owner === activeOwnerScopeKey() ? readGhostSecret('cindy-github', 'github_pat') : null,
+ owner === activeOwnerScopeKey()
+ ? readGhostSecret(cindyGithubRootInstance, 'github_pat') ?? readGhostSecret('cindy-github', 'github_pat')
+ : null,
fetch: outboundFetch,
});
return owner === activeOwnerScopeKey() ? result : { status: 'missing' as const };
@@ -54,7 +64,7 @@ export function registerGithubSetupIpc(invalidateStatuses: () => void): void {
});
}
app.once('before-quit', () => {
- unsubscribe();
+ unsubscribes.forEach(unsubscribe => unsubscribe());
setup.cancel();
});
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/managed-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/managed-skills.test.ts
index bba89d5309..6e649eb964 100644
--- a/apps/desktop/src/main/maker-host/__tests__/managed-skills.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/managed-skills.test.ts
@@ -9,6 +9,7 @@ const state = vi.hoisted(() => ({
pending: false,
enabled: true,
verified: true,
+ organization: false,
}));
vi.mock('electron', () => ({ app: { getPath: () => state.root } }));
vi.mock('../../appSessionState.js', () => ({
@@ -31,6 +32,8 @@ vi.mock('../../cindy-brain/index.js', () => ({
listAvailableGhostsForAuthorization: () => [
{
enabled: state.enabled,
+ namespace: null,
+ dir: path.join(state.root, 'cindy-brain', '_ns', '_root', 'my-plugin'),
approvedSkillRoot: path.join(
state.root,
state.owner,
@@ -45,6 +48,13 @@ vi.mock('../../cindy-brain/index.js', () => ({
},
},
},
+ ...(state.organization ? [{
+ enabled: state.enabled,
+ namespace: 'acme',
+ dir: path.join(state.root, 'cindy-brain', 'my-plugin'),
+ approvedSkillRoot: path.join(state.root, state.owner, 'ghost-install-state', 'skill-snapshots', 'organization'),
+ manifest: { id: 'my-plugin', skill: { items: [{ name: 'demo', dir: 'skills/demo', description: 'Organization skill' }] } },
+ }] : []),
],
}));
import { listCindyManagedSkills, prepareCindyCodexSkills } from '../managed-skills.js';
@@ -65,6 +75,7 @@ beforeEach(async () => {
state.pending = false;
state.enabled = true;
state.verified = true;
+ state.organization = false;
await writeSkill(path.join(state.root, 'shared-system-skills'), 'learn', 'learn');
await writeSkill(
path.join(state.root, 'a', 'ghost-install-state', 'skill-snapshots', 'rev'),
@@ -79,6 +90,20 @@ afterEach(async () => {
});
describe('Cindy managed skill catalog', () => {
+ it('keeps same-name root and in-place organization skills distinct through Codex projection', async () => {
+ state.organization = true;
+ await writeSkill(path.join(state.root, 'a', 'ghost-install-state', 'skill-snapshots', 'organization'), 'demo', 'demo');
+ const skills = await listCindyManagedSkills();
+ expect(skills.map(skill => skill.claudeCommandName)).toEqual([
+ 'cindy:learn', 'cindy-plugin-_root__my-plugin:demo', 'cindy-plugin-my-plugin:demo',
+ ]);
+ const home = path.join(state.root, 'codex-home');
+ await prepareCindyCodexSkills(home);
+ for (const skill of skills) {
+ expect(await fs.realpath(path.join(home, 'skills', codexManagedSkillLinkName(skill.claudeCommandName), 'SKILL.md'))).toBe(skill.path);
+ }
+ });
+
it('uses verified sources and manifest names despite real-directory and foreign-link projection conflicts', async () => {
await writeSkill(path.join(state.root, 'managed-agent-skills', 'cindy'), 'learn', 'impostor');
const ghostRoot = path.join(state.root, 'a', 'ghost-install-state', 'agent-skills');
@@ -91,7 +116,7 @@ describe('Cindy managed skill catalog', () => {
const skills = await listCindyManagedSkills();
expect(skills.map((skill) => skill.claudeCommandName)).toEqual([
'cindy:learn',
- 'cindy-plugin-my-plugin:demo',
+ 'cindy-plugin-_root__my-plugin:demo',
]);
expect(skills.map((skill) => skill.path)).toEqual(
await Promise.all([
@@ -140,7 +165,7 @@ describe('Cindy managed skill catalog', () => {
it('revokes disabled plugin projections from default and independent Codex homes without deleting sources', async () => {
const homes = ['default', 'account-a', 'account-b'].map((name) => path.join(state.root, name));
- const linkName = codexManagedSkillLinkName('cindy-plugin-my-plugin:demo');
+ const linkName = codexManagedSkillLinkName('cindy-plugin-_root__my-plugin:demo');
const source = path.join(
state.root,
'a',
diff --git a/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts
index 54f11b6685..95c184e7e8 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piAuthEnv.test.ts
@@ -38,6 +38,7 @@ vi.mock('../custom-provider-header-secrets.js', () => ({
],
}));
vi.mock('../../secrets/providerSecretStore.js', () => ({
+ setMivoSecretAliasVerifier: vi.fn(),
readCustomProviderKey: (id: string) => (id === 'my-vllm' ? 'BYOM-KEY' : null),
}));
diff --git a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
index bf50917194..a3d8fe1607 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
@@ -63,6 +63,7 @@ vi.mock('../custom-provider-header-secrets.js', () => ({
],
}));
vi.mock('../../secrets/providerSecretStore.js', () => ({
+ setMivoSecretAliasVerifier: vi.fn(),
readCustomProviderKey: (providerId: string) =>
providerId === 'xai' ? 'legacy-custom-key' : null,
}));
diff --git a/apps/desktop/src/main/maker-host/managed-skills.ts b/apps/desktop/src/main/maker-host/managed-skills.ts
index b4540fd0af..b1d00c014c 100644
--- a/apps/desktop/src/main/maker-host/managed-skills.ts
+++ b/apps/desktop/src/main/maker-host/managed-skills.ts
@@ -12,6 +12,7 @@ import { builtInSkillDescriptors, sharedBuiltInSkillsRoot } from './built-in-ski
import { getGhostManager, listAvailableGhostsForAuthorization } from '../cindy-brain/index.js';
import { withSharedGlobalSkillProjectionMutation } from '../authBoundaryQuarantine.js';
import { prepareCodexGlobalSkillsLinks } from './codex-global-skills.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
/** Reconcile the selected app-server home, including independently routed accounts. */
export async function prepareCindyCodexSkills(codexHome: string): Promise<void> {
@@ -70,7 +71,7 @@ export const listCindyManagedSkills: NonNullable<AgentDeps['getManagedSkills']>
addSkill(
path.join(ghost.approvedSkillRoot, item.dir),
item.name,
- `cindy-plugin-${ghost.manifest.id}`,
+ `cindy-plugin-${installedGhostStoragePart(ghost)}`,
item.description,
);
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
index 5e342b0160..d6858f799d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationHost.test.ts
@@ -1,6 +1,6 @@
import { advanceSessionRewindGeneration, withSendToSessionLock } from '../sendToSessionLock';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { GhostSetupAssessment } from '../../../shared/ghost';
+import type { GhostSetupAssessment, InstalledGhost } from '../../../shared/ghost';
import type { BotAuthorizationCard } from '../../../shared/botAuthorization';
import type { initBotAuthorizationService } from '../botAuthorizationService';
@@ -12,6 +12,7 @@ const state = vi.hoisted(() => ({
login: vi.fn(async () => ({ ok: true })),
continued: vi.fn(),
visible: true,
+ ghost: null as InstalledGhost | null,
realService: false,
persistedCard: null as BotAuthorizationCard | null,
deps: null as unknown as Parameters<typeof initBotAuthorizationService>[0],
@@ -55,7 +56,7 @@ vi.mock('../../cindy-brain/index.js', () => ({
}));
vi.mock('../../cindy-brain/ghostVisibility.js', () => ({
classifyGhostVisibility: () => state.visible
- ? { ok: true, ghost: { manifest: { id: 'art', name: 'Art' } } }
+ ? { ok: true, ghost: state.ghost }
: { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR' },
}));
vi.mock('../../cindy-brain/ghostWorkdirPrefs.js', () => ({ isGhostDisabledForWorkdir: () => false }));
@@ -74,6 +75,10 @@ describe('authorization Host live plugin policy', () => {
state.assessment.mockReturnValue({ state: 'ready', revision: 1, groups: [] });
state.subscribe.mockClear();
state.visible = true;
+ state.ghost = { dir: '/fake/art', namespace: null,
+ manifest: { id: 'art', name: 'Art' },
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ } as InstalledGhost;
state.realService = false;
state.persistedCard = null;
state.save.mockClear();
@@ -87,6 +92,62 @@ describe('authorization Host live plugin policy', () => {
});
});
+ it.each(['move', 'replace'] as const)('rejects a stale adapter after its physical target changes by %s', async (change) => {
+ state.ghost = { ...state.ghost!, namespace: 'acme' };
+ const adapter = await state.deps.adapter('session', { kind: 'plugin', id: 'art', namespace: 'acme' });
+ state.ghost = change === 'move'
+ ? { ...state.ghost, dir: '/fake/_ns/acme/art' }
+ : { ...state.ghost, approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' } };
+ await expect(adapter.assess()).rejects.toThrow();
+ await expect(adapter.execute({ id: 'save', kind: 'inline_form' } as never,
+ undefined, 'synthetic-secret')).rejects.toThrow();
+ expect(state.execute).not.toHaveBeenCalled();
+ const current = await state.deps.adapter('session', { kind: 'plugin', id: 'art', namespace: 'acme' });
+ await expect(current.assess()).resolves.toMatchObject({ state: 'ready' });
+ });
+
+ it.each(['move', 'replace'] as const)('restores a moved card but rejects a changed approval (%s)', async (change) => {
+ state.realService = true;
+ state.ghost = { ...state.ghost!, namespace: 'acme' };
+ state.save.mockImplementation(async (_sessionId, message) => {
+ state.persistedCard = structuredClone(message.agentMeta.botAuthorization);
+ });
+ state.assessment.mockReturnValue({ state: 'required', revision: 1, groups: [{
+ id: 'account', mode: 'any_of', items: [{ ref: 'oauth:account', kind: 'oauth', label: 'Account', state: 'missing',
+ actions: [{ id: 'connect', kind: 'oauth_connect' }] }],
+ }] });
+ const service = initializeBotAuthorizationHost(async () => {});
+ const sender = { id: 1, isDestroyed: () => false, send: vi.fn() };
+ try {
+ await service.request('session', { kind: 'plugin', id: 'art', namespace: 'acme' });
+ const original = structuredClone(state.persistedCard!);
+ service.invalidatePlugin('art');
+ state.ghost = change === 'move' ? { ...state.ghost!, dir: '/fake/_ns/acme/art' }
+ : { ...state.ghost!, approval: { state: 'approved', revision: 'replacement' } };
+ const action = { kind: 'plugin_setup' as const, action: 'run_action' as const,
+ actionId: original.snapshot.steps[0]!.action!.id, expectedRevision: original.snapshot.revision };
+ expect(await service.resolve(original.snapshot.requestId, action, sender)).toBe(change === 'move');
+ expect(state.execute).not.toHaveBeenCalled();
+ const restored = state.persistedCard!;
+ if (change === 'replace') {
+ expect(restored.snapshot.terminal).toBe(true);
+ return;
+ }
+ expect(restored.snapshot.ghost.id).toBe('_ns__acme__art');
+ expect(restored.snapshot.revision).toBeGreaterThan(original.snapshot.revision);
+ expect(await service.resolve(restored.snapshot.requestId, { ...action, expectedRevision: restored.snapshot.revision }, sender)).toBe(true);
+ await vi.waitFor(() => expect(state.execute).toHaveBeenCalledTimes(1));
+ expect(state.execute).toHaveBeenCalledWith(expect.objectContaining({ ghostId: '_ns__acme__art' }));
+ expect(await service.resolve(restored.snapshot.requestId, {
+ kind: 'plugin_setup', action: 'cancel', expectedRevision: state.persistedCard!.snapshot.revision,
+ }, sender)).toBe(true);
+ expect(state.persistedCard!.snapshot.terminal).toBe(true);
+ } finally {
+ await service.dispose();
+ state.save.mockReset();
+ }
+ });
+
it('runs the real Host and card lifecycle: dynamic plugin login saves a card and completion resumes once', async () => {
state.realService = true;
state.save.mockImplementation(async (_sessionId, message) => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts
index 5606999ed6..98bb371b6a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botAuthorizationService.test.ts
@@ -58,6 +58,7 @@ function harness() {
card.sessionId === sessionId &&
card.target.kind === target.kind &&
card.target.id === target.id &&
+ (card.target.kind !== 'plugin' || card.target.namespace === (target.kind === 'plugin' ? target.namespace : undefined)) &&
!!card.target.reauthorize === !!target.reauthorize &&
!card.snapshot.terminal,
) ?? null,
@@ -105,6 +106,68 @@ async function flush() {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
describe('Bot authorization transcript lifecycle (Grok parity)', () => {
+ it('refreshes a legacy card before binding it to the current installation', async () => {
+ const h = harness();
+ await h.service.request('s', { kind: 'plugin', id: 'p' });
+ const old = structuredClone(h.card());
+ h.service.invalidatePlugin('service');
+ h.deps.adapter.mockImplementation(async () => ({ ...h.adapter, pluginApprovalToken: 'current' }));
+ const command = { kind: 'plugin_setup' as const, action: 'run_action' as const,
+ actionId: 'connect', expectedRevision: old.snapshot.revision };
+ try {
+ expect(await h.service.resolve(old.snapshot.requestId, command, h.sender)).toBe(true);
+ expect(h.card().pluginApprovalToken).toBe('current');
+ expect(h.card().snapshot.revision).toBeGreaterThan(old.snapshot.revision);
+ expect(h.adapter.execute).not.toHaveBeenCalled();
+ expect(await h.service.resolve(old.snapshot.requestId, { ...command,
+ expectedRevision: h.card().snapshot.revision }, h.sender)).toBe(true);
+ await flush();
+ expect(h.adapter.execute).toHaveBeenCalledOnce();
+ } finally { await h.service.dispose(); }
+ });
+ it.each(['same-process', 'restart'])('rejects an old durable card after same-key replacement (%s)', async (mode) => {
+ const h = harness();
+ let pluginApprovalToken = 'source-A';
+ h.deps.adapter.mockImplementation(async () => ({ ...h.adapter, pluginApprovalToken }));
+ await h.service.request('s', { kind: 'plugin', id: 'p', namespace: null });
+ const old = structuredClone(h.card());
+ h.service.invalidatePlugin('service');
+ pluginApprovalToken = 'source-B';
+ if (mode === 'restart') await h.service.dispose();
+ const current = mode === 'restart' ? new BotAuthorizationService(h.deps) : h.service;
+ try {
+ expect(await current.resolve(old.snapshot.requestId, {
+ kind: 'plugin_setup', action: 'run_action', actionId: 'connect', expectedRevision: old.snapshot.revision,
+ }, h.sender)).toBe(false);
+ await flush();
+ expect(h.adapter.execute).not.toHaveBeenCalled();
+ expect(h.card().snapshot).toMatchObject({ terminal: true });
+ } finally { await current.dispose(); }
+ });
+ it('does not merge concurrent OAuth flows for omitted, root and organization namespace', async () => {
+ const h = harness();
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => { release = resolve; });
+ h.adapter.execute = vi.fn(async () => { await pending; return { ok: true as const, waitingExternal: true }; });
+ try {
+ for (const fields of [{}, { namespace: null }, { namespace: 'acme' }]) {
+ await h.service.request('s', { kind: 'plugin', id: 'p', ...fields });
+ }
+ expect(h.stored.size).toBe(3);
+ for (const card of h.stored.values()) {
+ await h.service.resolve(card.snapshot.requestId, {
+ kind: 'plugin_setup', action: 'run_action', actionId: 'connect', expectedRevision: card.snapshot.revision,
+ }, h.sender);
+ }
+ await flush();
+ expect(h.adapter.execute).toHaveBeenCalledTimes(3);
+ release();
+ await flush();
+ } finally {
+ release();
+ await h.service.dispose();
+ }
+ });
it('dedicates the bridge to current plugin OAuth cards, without a fake Renderer sender', async () => {
const h = harness();
const context: RemoteOauthContext = { scope: 'tx', assertCurrent: vi.fn(), authorize: vi.fn(), finish: vi.fn() };
@@ -133,6 +196,26 @@ describe('Bot authorization transcript lifecycle (Grok parity)', () => {
expect(local.adapter.execute).not.toHaveBeenCalled();
} finally { await local.service.dispose(); }
});
+ it.each([
+ { namespace: undefined, instanceId: 'p' },
+ { namespace: null, instanceId: '_root__p' },
+ { namespace: 'acme', instanceId: '_ns__acme__p' },
+ ])('binds remote OAuth to the displayed $instanceId instance', async ({ namespace, instanceId }) => {
+ const fixture = harness();
+ fixture.adapter.identity.id = instanceId;
+ try {
+ await fixture.service.request('s', { kind: 'plugin', id: 'p',
+ ...(namespace === undefined ? {} : { namespace }) });
+ const card = fixture.card();
+ const binding = await fixture.service.bindRemoteOauth({ requestId: card.snapshot.requestId,
+ actionId: 'connect', expectedRevision: card.snapshot.revision });
+ expect(card.snapshot.ghost.id).toBe(instanceId);
+ expect(binding?.ghostId).toBe(card.snapshot.ghost.id);
+ expect(binding?.current()).toBe(true);
+ await fixture.service.dispose();
+ expect(binding?.current()).toBe(false);
+ } finally { await fixture.service.dispose(); }
+ });
it('returns the card without opening a browser or holding the model turn; duplicate requests reuse it', async () => {
const h = harness();
const result = await h.service.request('s', { kind: 'host', id: 'grok' });
@@ -142,6 +225,17 @@ describe('Bot authorization transcript lifecycle (Grok parity)', () => {
expect(h.stored.size).toBe(1);
await h.service.dispose();
});
+ it('keeps root and organization authorization cards separate for the same id', async () => {
+ const h = harness();
+ const root = await h.service.request('s', { kind: 'plugin', id: 'p', namespace: null });
+ const organization = await h.service.request('s', { kind: 'plugin', id: 'p', namespace: 'acme' });
+ expect(root).toMatchObject({ ok: false, errorCode: 'SETUP_REQUIRED' });
+ expect(organization).toMatchObject({ ok: false, errorCode: 'SETUP_REQUIRED' });
+ expect(h.stored.size).toBe(2);
+ expect([...h.stored.values()].map((card) => card.target.kind === 'plugin' ? card.target.namespace : undefined))
+ .toEqual([null, 'acme']);
+ await h.service.dispose();
+ });
it('an old unclicked card remains usable after the one-hour fallback expires', async () => {
const h = harness();
await h.service.request('s', { kind: 'plugin', id: 'p' });
@@ -154,6 +248,17 @@ describe('Bot authorization transcript lifecycle (Grok parity)', () => {
expect(h.card().snapshot.terminal).toBe(true);
await h.service.dispose();
});
+ it('does not merge concurrent legacy, root and organization authorization requests', async () => {
+ const h = harness();
+ try {
+ const requests = [undefined, null, 'acme'].map((namespace) =>
+ h.service.request('s', { kind: 'plugin', id: 'p', ...(namespace === undefined ? {} : { namespace }) }),
+ );
+ await Promise.all(requests);
+ expect(new Set(requests).size).toBe(3);
+ expect(h.stored.size).toBe(3);
+ } finally { await h.service.dispose(); }
+ });
it('watch timeout retains the card and late completion still resumes through the fallback listener', async () => {
const h = harness();
await h.service.request('s', { kind: 'plugin', id: 'p' });
@@ -434,6 +539,28 @@ describe('authorization completion races', () => {
expect(h.deps.resume).toHaveBeenCalledTimes(2);
await h.service.dispose();
});
+ it('does not share an OAuth flight between same-id plugins in different namespaces', async () => {
+ const h = harness();
+ const finish: Array<() => void> = [];
+ h.adapter.execute = vi.fn(async () => {
+ await new Promise<void>((resolve) => finish.push(resolve));
+ return { ok: true as const };
+ });
+ await h.service.request('s', { kind: 'plugin', id: 'p', namespace: null });
+ await h.service.request('s', { kind: 'plugin', id: 'p', namespace: 'acme' });
+ for (const card of h.stored.values()) {
+ await h.service.resolve(card.snapshot.requestId, {
+ kind: 'plugin_setup', action: 'run_action', actionId: 'connect',
+ expectedRevision: card.snapshot.revision,
+ }, h.sender);
+ }
+ await flush();
+ expect(h.adapter.execute).toHaveBeenCalledTimes(2);
+ h.setReady();
+ for (const settle of finish) settle();
+ await flush();
+ await h.service.dispose();
+ });
});
describe('authorization durable completion boundary', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
index 5b581aada8..38e0b0a4f7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -58,6 +58,13 @@ function fixture() {
const tasks = new Map<string, PluginTaskView>();
const copy = <T>(v: T): T => structuredClone(v);
const store: PluginTaskStore = {
+ relocatePlugin: async (from, to) => {
+ if (from === to) return;
+ for (const row of rows.values()) if (row.pluginId === from) {
+ row.pluginId = to;
+ row.revision++;
+ }
+ },
revokePlugin: async pluginId => {
for (const row of rows.values()) if (row.pluginId === pluginId && row.operation === 'create') {
row.payload = JSON.stringify({...JSON.parse(row.payload),ownershipRevoked:true});
@@ -154,6 +161,29 @@ function fixture() {
};
}
+it('serializes source archival behind creation and keeps old tasks inaccessible to the replacement', async () => {
+ const fixtureState = fixture();
+ let started!: () => void;
+ const entered = new Promise<void>(resolve => { started = resolve; });
+ let finish!: () => void;
+ const gate = new Promise<void>(resolve => { finish = resolve; });
+ fixtureState.deps.resolveRoute = async () => { started(); await gate; return fixtureState.route; };
+ const move = vi.spyOn(fixtureState.deps.store, 'relocatePlugin');
+ const creating = fixtureState.create();
+ await entered;
+ const archiving = fixtureState.service.relocatePlugin('p', 'archive');
+ expect(move).not.toHaveBeenCalled();
+ finish();
+ const task = await creating;
+ await archiving;
+ expect(move).toHaveBeenCalledWith('p', 'archive');
+ expect((await fixtureState.service.list('p')).items).toEqual([]);
+ await expect(fixtureState.service.get('p', task.taskId)).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });
+ expect(fixtureState.tasks.has(task.taskId)).toBe(true);
+ const replacement = await fixtureState.create();
+ expect(replacement.taskId).not.toBe(task.taskId);
+});
+
it.each(['completed','failed','cancelled','interrupted'] as const)('prefers a newly persisted %s terminal over stale inspection for getRun and listRuns', async status => {
for (const kind of ['getRun','listRuns'] as const) {
const f=fixture(),run=await f.send();
diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
index 6826451317..3c94560fcb 100644
--- a/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationHost.ts
@@ -24,7 +24,9 @@ import {
captureGhostMutationOwnerForMcp,
} from '../cindy-brain/index.js';
import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus.js';
+import { ghostInstallApprovalToken } from '../../shared/ghost.js';
import { classifyGhostVisibility } from '../cindy-brain/ghostVisibility.js';
+import { installedGhostStoragePart, installedGhostMutationTargetToken } from '../../shared/pluginIdentity.js';
import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
import {
getGrokAccessToken,
@@ -155,27 +157,34 @@ export function initializeBotAuthorizationHost(
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
- const validate = async () => {
+ const validate = async (expectedTarget?: string | null) => {
await assertSession(sessionId);
const result = classifyGhostVisibility(target.id, session?.workingDir ?? null, {
listGhosts: () => getGhostManager().list(),
isAvailableForActiveSession: isGhostAvailableForActiveSession,
isDisabledForWorkdir: isGhostDisabledForWorkdir,
- });
+ }, target.namespace);
if (!result.ok) throw new Error('Plugin is unavailable');
+ if (expectedTarget !== undefined && (expectedTarget === null ||
+ installedGhostMutationTargetToken(result.ghost, '') !== expectedTarget)) {
+ throw new Error('Authorization plugin instance changed');
+ }
return result.ghost;
};
const ghost = await validate();
+ const expectedTarget = installedGhostMutationTargetToken(ghost, '');
+ const instanceId = installedGhostStoragePart(ghost);
let reconnected = false;
return {
+ pluginApprovalToken: ghostInstallApprovalToken(ghost.approval),
identity: {
- id: target.id,
+ id: instanceId,
name: ghost.manifest.name,
...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
},
async assess() {
- await validate();
- const assessment = getGhostSetupAssessment(target.id);
+ await validate(expectedTarget);
+ const assessment = getGhostSetupAssessment(instanceId);
if (!target.reauthorize) return assessment;
const suggested = toReauthInteractionAssessment(assessment);
// A plugin-wide OAuth event (or successful action) cannot satisfy a
@@ -196,12 +205,12 @@ export function initializeBotAuthorizationHost(
return groups.length ? { ...assessment, state: 'required' as const, groups } : assessment;
},
subscribe: (wake) =>
- bus.subscribe(target.id, (event) => {
+ bus.subscribe(instanceId, (event) => {
if (event.source === 'oauth') reconnected = true;
wake();
}),
async execute(action, sender, value, onAuthorizationUrl, assertCurrent, beforeCommit) {
- await validate();
+ await validate(expectedTarget);
assertCurrent?.();
const release = acquireGhostMutationLeaseForMcp(captureGhostMutationOwnerForMcp());
try {
@@ -209,14 +218,14 @@ export function initializeBotAuthorizationHost(
if (value === undefined) return { ok: false, errorCode: 'INLINE_UNAVAILABLE' };
return await executeGhostSetupInlineAction({
sessionId,
- ghostId: target.id,
+ ghostId: instanceId,
action,
value,
});
}
const result = await executeGhostSetupAction({
sessionId,
- ghostId: target.id,
+ ghostId: instanceId,
action,
responseTarget: sender,
onAuthorizationUrl,
@@ -327,6 +336,7 @@ export function initializeBotAuthorizationHost(
!card.snapshot.terminal &&
card.target.kind === target.kind &&
card.target.id === target.id &&
+ (card.target.kind !== 'plugin' || card.target.namespace === (target.kind === 'plugin' ? target.namespace : undefined)) &&
!!card.target.reauthorize === !!target.reauthorize
)
return card;
diff --git a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts b/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts
index aa056ef0ce..ae78c50a25 100644
--- a/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botAuthorizationService.ts
@@ -1,4 +1,5 @@
import { randomUUID } from 'node:crypto';
+import { deliveryNamespaceFields } from '../../shared/pluginIdentity.js';
import { getRemoteOauthContext, notifyOauthCardClosed } from '../plugin-oauth/context.js';
import type { PluginOauthAction } from '@cindy/device-link';
import type { OauthCardBinding } from '../plugin-oauth/transactions.js';
@@ -65,6 +66,7 @@ export async function commitBotAuthorizationInput(
}
export interface BotAuthorizationAdapter {
+ pluginApprovalToken?: string;
identity: { id: string; name: string; iconDataUrl?: string };
assess(): Promise<GhostSetupAssessment>;
subscribe(wake: () => void): () => void;
@@ -128,7 +130,8 @@ export class BotAuthorizationService {
private requests = new Map<string, ReturnType<BotAuthorizationService['requestCard']>>();
request(sessionId: string, target: BotAuthorizationTarget, plan?: GhostSetupPlan) {
- const key = `${this.epoch}:${sessionId}:${target.kind}:${target.id}:${!!target.reauthorize}`;
+ const key = JSON.stringify([this.epoch, sessionId, target.kind, target.id,
+ target.kind === 'plugin' ? deliveryNamespaceFields(target) : null, !!target.reauthorize]);
const existing = this.requests.get(key);
if (existing) return existing;
const pending = this.requestCard(sessionId, target, plan).finally(() =>
@@ -156,6 +159,7 @@ export class BotAuthorizationService {
e.card.sessionId === sessionId &&
e.card.target.kind === target.kind &&
e.card.target.id === target.id &&
+ (e.card.target.kind !== 'plugin' || e.card.target.namespace === (target.kind === 'plugin' ? target.namespace : undefined)) &&
!!e.card.target.reauthorize === !!target.reauthorize,
);
if (existing) {
@@ -181,7 +185,9 @@ export class BotAuthorizationService {
validatePlan(plan, assessment) ?? defaultPlan(assessment),
);
if (!snapshot.steps.length) throw new Error('No supported authorization action');
- const card: BotAuthorizationCard = { v: 1, sessionId, target, snapshot, createdAt: Date.now() };
+ const card: BotAuthorizationCard = { v: 1, sessionId, target, snapshot, createdAt: Date.now(),
+ ...(target.kind === 'plugin' && adapter.pluginApprovalToken
+ ? { pluginApprovalToken: adapter.pluginApprovalToken } : {}) };
const entry = this.attach(card, adapter);
entry.assessmentFingerprint = JSON.stringify(assessment);
try {
@@ -270,6 +276,17 @@ export class BotAuthorizationService {
card.sessionId,
card.completionPending ? { ...card.target, reauthorize: false } : card.target,
);
+ if (card.target.kind === 'plugin' && card.pluginApprovalToken !== undefined &&
+ card.pluginApprovalToken !== adapter.pluginApprovalToken) {
+ if (epoch !== this.epoch) return null;
+ card.snapshot = { ...card.snapshot, terminal: true, revision: card.snapshot.revision + 1,
+ steps: card.snapshot.steps.map(step => ({ ...step, phase: 'cancelled', action: undefined })) };
+ await this.deps.save(card);
+ return null;
+ }
+ const needsApprovalBinding = card.target.kind === 'plugin' && card.pluginApprovalToken === undefined &&
+ adapter.pluginApprovalToken !== undefined;
+ if (needsApprovalBinding) card.pluginApprovalToken = adapter.pluginApprovalToken;
// A retained card can start a fresh flow; an old browser URL is never persisted.
const hadReopenAction = !!card.snapshot.reopenActionId;
card.snapshot = {
@@ -282,6 +299,7 @@ export class BotAuthorizationService {
const entry = this.attach(card, adapter);
entry.assessmentFingerprint = JSON.stringify(assessment);
if (!(await this.isVisible(entry))) return null;
+ if (needsApprovalBinding || card.snapshot.ghost.id !== adapter.identity.id) await this.refresh(entry, assessment);
// Broadcast a newer revision before accepting a stale reopen click. The
// retained card can then start a new flow without a generic action error.
if (hadReopenAction) await this.save(entry);
@@ -342,7 +360,7 @@ export class BotAuthorizationService {
if (!entry || entry.closed || entry.cancelled || entry.action || entry.card.target.kind !== 'plugin' ||
entry.card.snapshot.terminal || entry.card.snapshot.revision !== action.expectedRevision ||
!entry.card.snapshot.steps.some(s => s.action?.id === action.actionId && s.action.kind === 'oauth_connect')) return null;
- return { ghostId: entry.card.target.id, current: () => !entry.closed && !entry.cancelled && !entry.card.snapshot.terminal };
+ return { ghostId: entry.adapter.identity.id, current: () => !entry.closed && !entry.cancelled && !entry.card.snapshot.terminal };
}
async resolveRemoteOauth(action: PluginOauthAction): Promise<boolean> {
const binding = await this.bindRemoteOauth(action);
@@ -456,7 +474,9 @@ export class BotAuthorizationService {
assertCurrent();
},
};
- const key = `${entry.card.target.kind}:${entry.card.target.id}:${action.id}:${getRemoteOauthContext()?.scope ?? 'local'}`;
+ const key = JSON.stringify([entry.card.target.kind, entry.card.target.id,
+ entry.card.target.kind === 'plugin' ? deliveryNamespaceFields(entry.card.target) : null,
+ action.id, getRemoteOauthContext()?.scope ?? 'local']);
let flight = this.oauthFlights.get(key);
if (!flight) {
const listeners = new Set<(url: string) => void>([onUrl]);
@@ -635,6 +655,12 @@ export class BotAuthorizationService {
if (entry.expiry) clearTimeout(entry.expiry);
this.entries.delete(entry.card.snapshot.requestId);
}
+ invalidatePlugin(instanceId: string): void {
+ for (const entry of this.entries.values()) {
+ if (entry.card.target.kind === 'plugin' && entry.adapter.identity.id === instanceId) this.close(entry);
+ }
+ }
+
async dispose() {
this.epoch += 1;
this.deps.onDisposing?.();
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index 3b58373dda..75d1a30384 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -48,6 +48,7 @@ export interface PluginTaskStore {
discardUncreated(row: PluginTaskReceipt): Promise<void>;
save(row: PluginTaskReceipt): Promise<void>;
revokePlugin(pluginId: string): Promise<void>;
+ relocatePlugin(from: string, to: string): Promise<void>;
}
export class PluginTaskError extends Error {
constructor(
@@ -230,6 +231,10 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
});
};
return {
+ relocatePlugin: (from: string, to: string) => exclusive(async () => {
+ await deps.store.relocatePlugin(from, to);
+ deps.assertCurrent();
+ }),
// Host-only native lifecycle work shares send/cancel's drain. Do not use
// exclusive here: native close callbacks may enqueue receipt writes.
completeOperation,
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
index f82c943f23..686f1a0c1a 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
@@ -79,6 +79,12 @@ export function createPluginTaskStore(db: DbClient): PluginTaskStore {
sql`NOT EXISTS (SELECT 1 FROM ${sessions} WHERE ${sessions.id} = ${row.id})`,
));
},
+ relocatePlugin: async (from, to) => {
+ if (from === to) return;
+ await db.drizzle.update(table).set({
+ pluginId: to, revision: sql`${table.revision} + 1`,
+ }).where(eq(table.pluginId, from));
+ },
revokePlugin: async (pluginId) => {
// Keep the identity/request key so reinstall cannot replay or recreate old tasks.
await db.drizzle.update(table).set({
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c6f4fa87a2..65897ab204 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -11,7 +11,7 @@ import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';
import { createPluginTaskStore } from './pluginTaskStore.js';
import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
-import { showMobilePluginTaskPermission, setPluginTaskHandler, getPluginTaskSourceSessionId, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';
+import { showMobilePluginTaskPermission, setPluginTaskHandler, getPluginTaskSourceSessionId, setPluginTaskUninstaller, setPluginTaskRelocator, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';
import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';
import { createHash as pluginTaskConfigHash } from 'node:crypto';
import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';
@@ -241,11 +241,17 @@ import {
executeGhostSetupAction,
executeGhostSetupInlineAction,
bindGhostSetupConnectionAction,
+ findGhostForInstanceId,
+ ghostInstallMutationTargetFor,
getGhostManager,
getGhostPipeDispatcher,
getGhostSetupAssessment,
isGhostAvailableForActiveSession,
} from '../cindy-brain/index.js';
+import {
+ hasDeliveryNamespace,
+ installedGhostStoragePart,
+} from '../../shared/pluginIdentity.js';
import {
assertTrustedAppRendererEvent,
isTrustedAppRendererEvent,
@@ -2923,18 +2929,29 @@ const ghostSetupInteractionBridge = initGhostSetupInteractionBridge({
});
initGhostSetupCoordinator({
+ getTargetToken: ghostInstallMutationTargetFor,
remoteConnection: true,
changeBus: getGhostSetupChangeBus(),
bridge: ghostSetupInteractionBridge,
+ resolveStoreId: (ghostId) => {
+ const ghost = findGhostForInstanceId(ghostId);
+ return ghost ? installedGhostStoragePart(ghost) : ghostId;
+ },
assess: (ghostId) => getGhostSetupAssessment(ghostId),
validateTarget: (ghostId, tool, workingDir) => {
// Coordinator 的 UI 只消费 TARGET_UNAVAILABLE 状态;这里的 message 会随
// ensureReady 结果回到模型,因此与 ghost_info / ghost_call 共用同一口径。
- const visibility = classifyGhostVisibility(ghostId, workingDir ?? null, {
- listGhosts: () => getGhostManager().list(),
- isAvailableForActiveSession: isGhostAvailableForActiveSession,
- isDisabledForWorkdir: isGhostDisabledForWorkdir,
- });
+ const instance = findGhostForInstanceId(ghostId);
+ const visibility = classifyGhostVisibility(
+ instance?.manifest.id ?? ghostId,
+ workingDir ?? null,
+ {
+ listGhosts: () => getGhostManager().list(),
+ isAvailableForActiveSession: isGhostAvailableForActiveSession,
+ isDisabledForWorkdir: isGhostDisabledForWorkdir,
+ },
+ instance && hasDeliveryNamespace(instance) ? instance.namespace : undefined,
+ );
if (!visibility.ok) return visibility;
const ghost = visibility.ghost;
if (tool && !(ghost.manifest.tools ?? []).some((candidate) => candidate.name === tool)) {
@@ -2947,22 +2964,20 @@ initGhostSetupCoordinator({
return { ok: true };
},
getGhostIdentity: (ghostId) => {
- const ghost = getGhostManager()
- .list()
- .find((candidate) => candidate.manifest.id === ghostId);
- return ghost
- ? {
- id: ghostId,
- name: ghost.manifest.name,
- ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
- }
- : null;
+ const ghost = findGhostForInstanceId(ghostId);
+ if (!ghost) return null;
+ return {
+ id: installedGhostStoragePart(ghost),
+ name: ghost.manifest.name,
+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
+ };
},
- executeAction: ({ sessionId, ghostId, action, responseTarget }) =>
+ executeAction: ({ sessionId, ghostId, action, responseTarget, assertCurrent }) =>
executeGhostSetupAction({
sessionId,
ghostId,
action,
+ assertCurrent,
...(responseTarget ? { responseTarget } : {}),
}),
executeInlineAction: executeGhostSetupInlineAction,
@@ -12560,6 +12575,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
setPluginTaskHandler(handlePluginTask);
setPluginTaskUninstaller((pluginId, remove) => pluginTaskServiceForCurrentOwner!().withUninstall(pluginId, remove));
+ setPluginTaskRelocator((from, to) => pluginTaskServiceForCurrentOwner!().relocatePlugin(from, to));
// Local task UI only. The plugin and device-link protocols have no recovery operation.
const pluginWriteAccessFromHost = async (event: Electron.IpcMainInvokeEvent, taskId: unknown, retry: boolean) => {
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index d77613cc1d..07475636c8 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -257,7 +257,7 @@ vi.mock('../ghostAttachmentResolve.js', () => ({
}));
const { authorizeDesktopSessionPath, getCindyGhostsMcpDeps, getGhostRosterPrompt } = await import('../ghost');
-const { createCindyGhostsMcpServer } = await import('cindy-tools');
+const { createCindyGhostsMcpServer, handleGhostList, handleGhostInfo, handleGhostCall, handleGhostManual } = await import('cindy-tools');
const { setGhostDisabledForWorkdir, listDisabledGhostIdsForWorkdir, isGhostDisabledForWorkdir } =
await import('../../cindy-brain/ghostWorkdirPrefs');
import type { LiziMcpSessionContext } from '@cindy/mcps';
@@ -1205,9 +1205,44 @@ describe('connect_account shares Host live plugin policy', () => {
await deps.connectAccount!({ kind: 'host', id: 'grok' });
expect(authorizationRequestMock).toHaveBeenCalledTimes(2);
});
+ it('persists the installed instance identity for a bot connection', async () => {
+ isAuthorizationSessionMock.mockResolvedValue(true);
+ listMock.mockReturnValue([
+ { ...(chipGhost('art') as object), namespace: 'acme', dir: '/fake/_ns/acme/art' },
+ ]);
+ await makeDeps('claude-code', 'bot-session', 'bot-instance').connectAccount!({ kind: 'plugin', id: 'art' });
+ expect(authorizationRequestMock).toHaveBeenCalledWith('bot-session', {
+ kind: 'plugin', id: 'art', namespace: 'acme',
+ });
+ listMock.mockReturnValue([{ ...(chipGhost('art') as object), namespaceState: 'pending' as const }]);
+ await makeDeps('claude-code', 'bot-session', 'bot-instance').connectAccount!({ kind: 'plugin', id: 'art' });
+ expect(authorizationRequestMock).toHaveBeenLastCalledWith('bot-session', { kind: 'plugin', id: 'art' });
+ });
});
describe('connect_account ordinary task entry', () => {
+ it('selects an explicit root when an organization instance shares its id', async () => {
+ setupAssessmentMock.mockReturnValue(configured);
+ listMock.mockReturnValue([
+ { ...(chipGhost('art') as object), namespace: null },
+ { ...(chipGhost('art') as object), namespace: 'acme', dir: '/fake/_ns/acme/art' },
+ ]);
+ expect(await makeDeps().connectAccount!({ kind: 'plugin', id: 'art' }))
+ .toMatchObject({ ok: false, errorCode: 'GHOST_AMBIGUOUS' });
+ expect(await makeDeps().connectAccount!({ kind: 'plugin', id: 'art', namespace: null }))
+ .toMatchObject({ ok: true, status: 'ready' });
+ expect(ensureReadyMock).toHaveBeenCalledWith(expect.objectContaining({ ghostId: 'art' }));
+ });
+ it('rechecks a physically namespaced organization after its setup completes', async () => {
+ setupAssessmentMock.mockReturnValue(configured);
+ listMock.mockReturnValue([
+ { ...(chipGhost('art') as object), namespace: null },
+ { ...(chipGhost('art') as object), namespace: 'acme', dir: '/fake/_ns/acme/art' },
+ ]);
+ expect(await makeDeps().connectAccount!({ kind: 'plugin', id: 'art', namespace: 'acme' }))
+ .toMatchObject({ ok: true, status: 'ready' });
+ expect(ensureReadyMock).toHaveBeenCalledWith(expect.objectContaining({ ghostId: '_ns__acme__art' }));
+ });
it('keeps Host-derived GitHub login on its existing path without a cloud-only adapter', async () => {
listMock.mockReturnValue([chipGhost('cindy-github')]);
const signal = new AbortController().signal;
@@ -1290,6 +1325,62 @@ describe('connect_account ordinary task entry', () => {
});
describe('花名册 / ghost_list 过滤', () => {
+ it.each((['claude-code', 'codex', 'pi'] as const).flatMap(
+ (agentKind) => [true, false].map((pending) => ({ agentKind, pending })),
+ ))(
+ '$agentKind preserves a missing namespace through discovery, calls and manuals (pending=$pending)',
+ async ({ agentKind, pending: isPending }) => {
+ const pending = {
+ ...(chipGhost('art', ['tool'], {
+ manual: { items: [{ dir: 'docs', name: 'guide', description: 'Usage guide' }] },
+ }) as object),
+ dir: path.join(tmpUserData, 'art'),
+ ...(isPending ? { namespaceState: 'pending' as const } : {}),
+ };
+ listMock.mockReturnValue([pending]);
+ const deps = makeDeps(agentKind);
+ const listed = JSON.parse((await handleGhostList(deps)).content[0].text).ghosts[0];
+ const info = JSON.parse((await handleGhostInfo(deps, { ghost_id: 'art' })).content[0].text).ghost;
+ for (const discovered of [listed, info]) {
+ const target = {
+ ghost_id: discovered.id,
+ ...(Object.hasOwn(discovered, 'namespace') ? { namespace: discovered.namespace } : {}),
+ };
+ const called = JSON.parse((await handleGhostCall(deps, { ...target, tool: 'run' })).content[0].text);
+ expect(called).toMatchObject({ ok: true, result: 'done' });
+ const manual = JSON.parse((await handleGhostManual(deps, target)).content[0].text);
+ expect(manual).toMatchObject({ ok: true, manual: [{ name: 'guide' }] });
+ expect(discovered).not.toHaveProperty('namespace');
+ }
+ expect(deps.getRosterItems?.()[0]).not.toHaveProperty('namespace');
+ expect(getGhostRosterPrompt({ workingDir: WORKDIR })).not.toContain('"namespace"');
+ if (isPending) {
+ await expect(deps.getAwakeGhost('art', null)).resolves.toMatchObject({ ok: false, errorCode: 'GHOST_NOT_FOUND' });
+ }
+ expect(dispatchMock).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it('keeps explicit root and organization namespaces in discovery with same-name instances', async () => {
+ listMock.mockReturnValue([
+ { ...(chipGhost('art') as object), namespace: null, dir: path.join(tmpUserData, '_ns', '_root', 'art') },
+ { ...(chipGhost('art') as object), namespace: 'acme', dir: path.join(tmpUserData, '_ns', 'acme', 'art') },
+ ]);
+ const deps = makeDeps();
+ const listed = JSON.parse((await handleGhostList(deps)).content[0].text).ghosts;
+ expect(listed.map(({ namespace }: { namespace: string | null }) => namespace)).toEqual([null, 'acme']);
+ for (const discovered of listed) {
+ const target = { ghost_id: discovered.id, namespace: discovered.namespace };
+ const info = JSON.parse((await handleGhostInfo(deps, target)).content[0].text);
+ expect(info).toMatchObject({ ok: true, ghost: { id: 'art', namespace: discovered.namespace } });
+ expect(JSON.parse((await handleGhostCall(deps, { ...target, tool: 'run' })).content[0].text))
+ .toMatchObject({ ok: true, result: 'done' });
+ }
+ expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({ ghostId: '_root__art' }));
+ expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({ ghostId: '_ns__acme__art' }));
+ await expect(deps.getAwakeGhost('art')).resolves.toMatchObject({ ok: false, errorCode: 'GHOST_AMBIGUOUS' });
+ });
+
it('被禁用的意识不进花名册与现查清单;其余照常', async () => {
setGhostDisabledForWorkdir(WORKDIR, 'art', true);
const deps = makeDeps();
@@ -1530,18 +1621,19 @@ describe('Manual-only Ghost discovery and read gates', () => {
it.each(['claude-code', 'codex', 'pi'] as const)(
'%s discovers Manual-only plugins through both rosters, list and info',
async (agentKind) => {
- const ghost = manualOnlyGhost();
+ const ghost = { ...manualOnlyGhost(), namespace: null };
listMock.mockReturnValue([ghost, chipGhost('art')]);
const deps = makeDeps(agentKind);
const roster = deps.getRosterItems?.() ?? [];
expect(roster.map(({ id }) => id)).toEqual(['workflow-guide', 'art']);
expect(roster[0]).toEqual({
- id: 'workflow-guide', name: 'Workflow Guide', recall: ghost.manifest.whenToUse,
+ id: 'workflow-guide', namespace: null, name: 'Workflow Guide', recall: ghost.manifest.whenToUse,
});
const ghosts = await deps.listAwakeGhosts();
expect(ghosts).toHaveLength(2);
expect(ghosts[0]).toEqual({
...roster[0],
+ namespace: null,
tools: [],
manual: [{ name: 'workflow-guide', description: 'Build workflow' }],
setup: { state: 'ready', revision: 0, groups: [] },
@@ -1919,6 +2011,58 @@ describe('ghost_call 兜底拒绝', () => {
});
describe('session-context 宿主铸造', () => {
+ it.each([null, 'acme'])('pins namespace %s across revalidation when a twin exists', async (namespace) => {
+ listMock.mockReturnValue([
+ chipGhost('art', ['tool', 'session-context']),
+ {
+ ...(chipGhost('art', ['tool', 'session-context']) as object),
+ namespace: 'acme',
+ dir: path.join(tmpUserData, '_ns', 'acme', 'art'),
+ },
+ ]);
+ sessionSnapshotMock.mockResolvedValueOnce({
+ workingDir: WORKDIR,
+ permissionMode: 'auto',
+ planModeEnabled: true,
+ remoteHostId: null,
+ });
+
+ const result = await makeDeps().callGhostTool({
+ ghostId: 'art',
+ namespace,
+ tool: 'run',
+ args: {
+ session_context: {
+ session_id: 'forged',
+ workdir: '/tmp/forged',
+ workdir_is_local: true,
+ workdir_is_read_only: false,
+ },
+ },
+ });
+
+ expect(result).toMatchObject({ ok: true, result: 'done' });
+ expect(ensureReadyMock).toHaveBeenCalledWith(
+ expect.objectContaining({ ghostId: namespace === null ? 'art' : '_ns__acme__art' }),
+ );
+ expect(dispatchMock).toHaveBeenCalledTimes(1);
+ expect(dispatchMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ ghostId: namespace === null ? 'art' : '_ns__acme__art',
+ args: {
+ session_context: {
+ session_id: 's1',
+ workdir: WORKDIR,
+ workdir_is_local: true,
+ workdir_is_read_only: true,
+ },
+ },
+ }),
+ );
+ const dispatched = dispatchMock.mock.calls.at(0)?.at(0) as Record<string, unknown> | undefined;
+ expect(dispatched).not.toHaveProperty('namespace');
+ });
+
it('剥除上游伪造值,并按会话权限注入可信只读状态', async () => {
listMock.mockReturnValue([chipGhost('art', ['tool', 'session-context'])]);
sessionSnapshotMock.mockResolvedValueOnce({
@@ -2798,6 +2942,98 @@ describe('Full Access 插件文件交接', () => {
});
+describe('installation-bound directory grant memory', () => {
+ const lanes = [
+ { lane: 'dir', namespace: undefined, installDir: path.join(tmpUserData, 'art') },
+ { lane: 'save_dir', namespace: null, installDir: path.join(tmpUserData, '_ns', '_root', 'art') },
+ { lane: 'attachments-dir', namespace: 'acme', installDir: path.join(tmpUserData, '_ns', 'acme', 'art') },
+ ] as const;
+ const revision = '00000000-0000-4000-8000-000000000001';
+ const replacementRevision = '00000000-0000-4000-8000-000000000002';
+
+ function fixture(entry: typeof lanes[number], scenario: string) {
+ const target: InstalledGhost = {
+ ...(chipGhost('art') as InstalledGhost),
+ dir: entry.installDir,
+ approval: { state: 'approved', revision },
+ ...(entry.namespace !== undefined ? { namespace: entry.namespace } : {}),
+ };
+ listMock.mockReturnValue([target]);
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'ask', remoteHostId: null });
+ const directory = path.join(outsideDir, `${scenario}-${entry.lane}`);
+ fs.mkdirSync(directory, { recursive: true });
+ const deps = makeDeps('claude-code', `${scenario}-${entry.lane}`);
+ let requestNumber = 0;
+ const request = () => {
+ requestNumber += 1;
+ const file = path.join(directory, `file-${requestNumber}.png`);
+ if (entry.lane === 'attachments-dir') fs.writeFileSync(file, `${scenario}-${requestNumber}`);
+ return deps.callGhostTool({
+ ghostId: 'art',
+ ...(entry.namespace !== undefined ? { namespace: entry.namespace } : {}),
+ tool: 'run',
+ args: {},
+ ...(entry.lane === 'dir' ? { dir: directory } : {}),
+ ...(entry.lane === 'save_dir' ? { saveDir: directory } : {}),
+ ...(entry.lane === 'attachments-dir' ? { attachments: [file] } : {}),
+ });
+ };
+ const clearEffects = () => {
+ dispatchMock.mockClear();
+ dirDepositMock.mockClear();
+ saveDepositMock.mockClear();
+ grantAttachmentsMock.mockClear();
+ ledgerAddRefMock.mockClear();
+ };
+ const expectNoEffects = () => {
+ expect(dispatchMock).not.toHaveBeenCalled();
+ expect(dirDepositMock).not.toHaveBeenCalled();
+ expect(saveDepositMock).not.toHaveBeenCalled();
+ expect(grantAttachmentsMock).not.toHaveBeenCalled();
+ expect(ledgerAddRefMock).not.toHaveBeenCalled();
+ };
+ return { target, request, clearEffects, expectNoEffects };
+ }
+
+ it.each(lanes)('$lane remembers consent only for the approved installation', async (entry) => {
+ const { target, request, clearEffects, expectNoEffects } = fixture(entry, 'cached');
+ confirmRequestMock.mockResolvedValue({ confirmed: true, allowDirs: true });
+ expect(await request()).toMatchObject({ ok: true });
+ expect(await request()).toMatchObject({ ok: true });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(1);
+
+ target.approval = { state: 'approved', revision: replacementRevision };
+ confirmRequestMock.mockResolvedValue({ confirmed: false, allowDirs: false });
+ clearEffects();
+ expect(await request()).toMatchObject({ ok: false });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(2);
+ expectNoEffects();
+ });
+
+ it.each(lanes)('$lane rejects late consent without remembering or handing off files', async (entry) => {
+ const { target, request, expectNoEffects } = fixture(entry, 'pending');
+ let enterConfirmation!: () => void;
+ const entered = new Promise<void>((resolve) => { enterConfirmation = resolve; });
+ let finishConfirmation!: (decision: { confirmed: boolean; allowDirs: boolean }) => void;
+ confirmRequestMock.mockImplementationOnce(() => new Promise((resolve) => {
+ finishConfirmation = resolve;
+ enterConfirmation();
+ }));
+ const pending = request();
+ await entered;
+ Object.assign(target.approval, { revision: replacementRevision });
+ finishConfirmation({ confirmed: true, allowDirs: true });
+ expect(await pending).toMatchObject({ ok: false });
+ expectNoEffects();
+
+ target.approval = { state: 'approved', revision };
+ confirmRequestMock.mockResolvedValue({ confirmed: false, allowDirs: false });
+ expect(await request()).toMatchObject({ ok: false });
+ expect(confirmRequestMock).toHaveBeenCalledTimes(2);
+ expectNoEffects();
+ });
+});
+
describe('Host Auto review', () => {
it.each(['bypassPermissions', 'auto', 'ask'].flatMap((permissionMode) =>
[false, true].map((grantOnly) => ({ permissionMode, grantOnly })),
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 0631671c21..6dc15e46d5 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -80,10 +80,19 @@ import {
} from '../appSessionState.js';
import {
deriveGhostSessionContext,
+ ghostInstallApprovalToken,
type GhostSessionContextInjected,
type GhostSetupAssessment,
type InstalledGhost,
} from '../../shared/ghost.js';
+import {
+ findInstalledGhostByInstanceId,
+ installedGhostLogicalIdentity,
+ deliveryNamespaceFields,
+ installedGhostStoragePart,
+ pluginStoragePart,
+ resolveInstalledGhost,
+} from '../../shared/pluginIdentity.js';
import { withCardToken } from '../cindy-brain/cardService.js';
import { drainGhostCallMedia } from '../cindy-brain/ghostMediaLedger.js';
import {
@@ -99,7 +108,7 @@ import {
} from '../cindy-brain/index.js';
import { writeForgeScaffoldWithStableParent } from '../cindy-brain/forgeScaffoldCapability.js';
import { getGhostSetupCoordinator } from '../cindy-brain/ghostSetupCoordinator.js';
-import { classifyGhostVisibility } from '../cindy-brain/ghostVisibility.js';
+import { classifyGhostVisibility, classifyInstalledGhostVisibility } from '../cindy-brain/ghostVisibility.js';
import { readInstalledGhostManual } from '../cindy-brain/ghostManual.js';
import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forge.js';
@@ -500,6 +509,11 @@ export interface CindyGhostsHostDeps {
type GhostGrantApprovalSource = 'user' | 'full-access' | 'auto-review';
+type GhostGrantTarget = {
+ approvalToken: string;
+ isCurrent: () => boolean;
+};
+
/** 确认卡内嵌图片预览的文件体积上限(只是预览阈值,不是过户限制——超阈值
* 照样可过户,卡片上退化为文件名 + 路径 + 大小)。 */
const GRANT_PREVIEW_MAX_BYTES = 4 * 1024 * 1024;
@@ -537,11 +551,12 @@ const dirGrantMemory = new Set<string>();
function dirGrantMemoryKey(
sessionId: string,
ghostId: string,
+ approvalToken: string,
lane: string,
realPath: string,
): string {
const folded = process.platform === 'win32' ? realPath.toLowerCase() : realPath;
- return [sessionId, ghostId, lane, folded].join('\u0000');
+ return [sessionId, ghostId, approvalToken, lane, folded].join('\u0000');
}
/**
@@ -629,9 +644,7 @@ async function getForgeSessionFsGate(
function ghostDisplayName(ghostId: string): string {
if (ghostId === CINDY_FORGE_GRANT_ID) return 'Forge';
if (ghostId === CINDY_SESSION_FS_GRANT_ID) return 'Cindy';
- const g = getGhostManager()
- .list()
- .find((x) => x.manifest.id === ghostId);
+ const g = findInstalledGhostByInstanceId(getGhostManager().list(), ghostId);
return g?.manifest.name ?? ghostId;
}
@@ -651,6 +664,7 @@ function isInsideSessionWorkdir(targetAbs: string, workdirAbs: string | null): b
*/
async function requestGrantConfirm(params: {
ghostId: string;
+ target?: GhostGrantTarget;
sessionId: string | null;
sessionInstanceId: string | null;
lane: GhostGrantLane;
@@ -662,13 +676,18 @@ async function requestGrantConfirm(params: {
| { ok: true; approvalSource: GhostGrantApprovalSource; allowDirs?: boolean; isCurrent?: () => boolean }
| { ok: false; message: string }
> {
- let isCurrent: (() => boolean) | undefined;
+ const targetIsCurrent = params.target?.isCurrent;
+ let isCurrent = targetIsCurrent;
const expired = () => isCurrent?.() === false;
const denied = { ok: false as const, message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
+ if (expired()) return denied;
if (params.sessionId && params.sessionInstanceId && params.getLiveSessionGrantState) {
try {
const live = params.getLiveSessionGrantState(params.sessionId, params.sessionInstanceId);
- isCurrent = live?.isCurrent;
+ const sessionIsCurrent = live?.isCurrent;
+ isCurrent = targetIsCurrent
+ ? () => targetIsCurrent() && sessionIsCurrent?.() !== false
+ : sessionIsCurrent;
if (expired()) return denied;
// 远程会话的 workingDir 是另一台机器上的路径。即使档位为 Full Access,
// 也不能据此静默读取本机同名/任意路径;保留原确认边界。
@@ -846,6 +865,7 @@ async function requestMediaPathRevealConfirm(params: {
async function prepareLocalPathAttachments(params: {
urls: string[];
ghostId: string;
+ target: GhostGrantTarget;
workdirAbs: string | null;
sessionId: string | null;
sessionInstanceId: string | null;
@@ -856,7 +876,7 @@ async function prepareLocalPathAttachments(params: {
{ ok: true; resolved: Map<string, ResolvedGrantSource>; isCurrent?: () => boolean } | { ok: false; message: string }
> {
const resolved = new Map<string, ResolvedGrantSource>();
- let isCurrent: (() => boolean) | undefined;
+ let isCurrent = params.target.isCurrent;
// 超项数上限时不弹确认,直接交给 grant 流程报标准错(别让用户白点一次)。
if (params.urls.length > params.maxCount) return { ok: true, resolved };
const outside: Array<{
@@ -937,6 +957,7 @@ async function prepareLocalPathAttachments(params: {
dirGrantMemoryKey(
params.sessionId,
params.ghostId,
+ params.target.approvalToken,
'attachments-dir',
path.dirname(o.absPath),
),
@@ -975,6 +996,7 @@ async function prepareLocalPathAttachments(params: {
});
const confirm = await requestGrantConfirm({
ghostId: params.ghostId,
+ target: params.target,
sessionId: params.sessionId,
sessionInstanceId: params.sessionInstanceId,
lane: 'attachments',
@@ -982,7 +1004,7 @@ async function prepareLocalPathAttachments(params: {
getLiveSessionGrantState: params.getLiveSessionGrantState,
});
if (!confirm.ok) return confirm;
- isCurrent = confirm.isCurrent;
+ isCurrent = confirm.isCurrent ?? params.target.isCurrent;
if (isCurrent?.() === false) return { ok: false, message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
for (const o of needConfirm) {
// 人工确认记 user;Full Access 自动交接记 tool,不能伪装成用户点击。
@@ -1003,6 +1025,7 @@ async function prepareLocalPathAttachments(params: {
dirGrantMemoryKey(
params.sessionId,
params.ghostId,
+ params.target.approvalToken,
'attachments-dir',
path.dirname(o.absPath),
),
@@ -1029,6 +1052,7 @@ async function prepareLocalPathAttachments(params: {
*/
async function confirmDepositOutsideWorkdir(params: {
ghostId: string;
+ target: GhostGrantTarget;
sessionId: string | null;
sessionInstanceId: string | null;
lane: 'dir' | 'save_dir';
@@ -1040,6 +1064,7 @@ async function confirmDepositOutsideWorkdir(params: {
| { ok: true; userGranted: true; approvedRealPath: string; isCurrent?: () => boolean }
| { ok: false; message: string }
> {
+ if (!params.target.isCurrent()) return { ok: false, message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
if (!path.isAbsolute(params.dirAbs)) return { ok: true, userGranted: false };
let real: string;
let stat: fs.Stats;
@@ -1054,9 +1079,9 @@ async function confirmDepositOutsideWorkdir(params: {
// 会话内授权记忆:同一意识对同一真身路径同一通道,本会话允许过一次即放行。
if (
params.sessionId &&
- dirGrantMemory.has(dirGrantMemoryKey(params.sessionId, params.ghostId, params.lane, real))
+ dirGrantMemory.has(dirGrantMemoryKey(params.sessionId, params.ghostId, params.target.approvalToken, params.lane, real))
) {
- return { ok: true, userGranted: true, approvedRealPath: real };
+ return { ok: true, userGranted: true, approvedRealPath: real, isCurrent: params.target.isCurrent };
}
let item: GhostGrantFileItem;
@@ -1084,6 +1109,7 @@ async function confirmDepositOutsideWorkdir(params: {
const confirm = await requestGrantConfirm({
ghostId: params.ghostId,
+ target: params.target,
sessionId: params.sessionId,
sessionInstanceId: params.sessionInstanceId,
lane: params.lane,
@@ -1095,7 +1121,7 @@ async function confirmDepositOutsideWorkdir(params: {
// Full Access 是每次在实时档位上自动裁决,不伪造「用户确认过」的目录
// 记忆。这样热切回 ask/auto 后,同一路径的新过户会立刻恢复询问。
if (confirm.approvalSource === 'user' && params.sessionId) {
- dirGrantMemory.add(dirGrantMemoryKey(params.sessionId, params.ghostId, params.lane, real));
+ dirGrantMemory.add(dirGrantMemoryKey(params.sessionId, params.ghostId, params.target.approvalToken, params.lane, real));
}
if (confirm.approvalSource === 'user') {
log.info('ghost grant confirm: user approved outside-workdir deposit', {
@@ -1123,6 +1149,7 @@ type ManagedToolGrantCandidate = {
async function prepareManagedToolGrantSources(params: {
urls: string[];
ghostId: string;
+ target: GhostGrantTarget;
localResolved: Map<string, ResolvedGrantSource>;
maxCount: number;
sessionId: string | null;
@@ -1240,6 +1267,7 @@ async function prepareManagedToolGrantSources(params: {
const confirm = await requestGrantConfirm({
ghostId: params.ghostId,
+ target: params.target,
sessionId: params.sessionId,
sessionInstanceId: params.sessionInstanceId,
lane: 'attachments',
@@ -1271,6 +1299,7 @@ async function prepareManagedToolGrantSources(params: {
*/
async function grantAttachmentUrls(params: {
ghostId: string;
+ target: GhostGrantTarget;
urls: string[];
workdirAbs: string | null;
sessionId: string | null;
@@ -1282,6 +1311,7 @@ async function grantAttachmentUrls(params: {
const localGrant = await prepareLocalPathAttachments({
urls: params.urls,
ghostId,
+ target: params.target,
workdirAbs: params.workdirAbs,
sessionId: params.sessionId,
sessionInstanceId: params.sessionInstanceId,
@@ -1293,6 +1323,7 @@ async function grantAttachmentUrls(params: {
const managedToolGrant = await prepareManagedToolGrantSources({
urls: params.urls,
ghostId,
+ target: params.target,
localResolved: localGrant.resolved,
maxCount: params.maxCount,
sessionId: params.sessionId,
@@ -1301,7 +1332,7 @@ async function grantAttachmentUrls(params: {
});
if (!managedToolGrant.ok) return managedToolGrant;
// 保留两次预处理捕获的授权,不能用后取的快照替换先前代次。
- const isCurrent = () => localGrant.isCurrent?.() !== false && managedToolGrant.isCurrent?.() !== false;
+ const isCurrent = () => params.target.isCurrent() && localGrant.isCurrent?.() !== false && managedToolGrant.isCurrent?.() !== false;
const result = await grantAttachmentsToGhost(
{
isCurrent,
@@ -1589,7 +1620,7 @@ function visibleChipGhosts(
isGhostAvailableForActiveSession(ghost.manifest.id) &&
ghost.manifest.kind === 'chip' &&
(ghostHasTools(ghost) || ghostHasManual(ghost)) &&
- !isGhostDisabledForWorkdir(ghost.manifest.id, workdir),
+ !isGhostDisabledForWorkdir(installedGhostStoragePart(ghost), workdir),
);
}
@@ -1610,6 +1641,7 @@ export function getGhostRosterPrompt({ workingDir }: { workingDir?: string }): s
const recall = ghostRecall(ghost);
return {
id: ghost.manifest.id,
+ ...(ghost.namespaceState === 'pending' ? {} : deliveryNamespaceFields(ghost)),
name: ghost.manifest.name,
...(ghost.manifest.command ? { command: ghost.manifest.command } : {}),
...(recall ? { recall } : {}),
@@ -1622,17 +1654,18 @@ function toCindyGhostInfo(ghost: InstalledGhost): CindyGhostInfo {
const recall = ghostRecall(ghost);
let setup: CindyGhostInfo['setup'];
try {
- setup = getGhostSetupAssessment(ghost.manifest.id);
+ setup = getGhostSetupAssessment(installedGhostStoragePart(ghost));
} catch (error) {
// Discovery is best-effort per plugin. Keep this plugin discoverable
// without claiming it is ready; ghost_call retains the strict setup gate.
log.warn('ghost setup assessment omitted from discovery', {
- ghostId: ghost.manifest.id,
+ ghostId: installedGhostStoragePart(ghost),
errorType: error instanceof Error ? error.name : typeof error,
});
}
return {
id: ghost.manifest.id,
+ ...(ghost.namespaceState === 'pending' ? {} : deliveryNamespaceFields(ghost)),
name: ghost.manifest.name,
...(ghost.manifest.command ? { command: ghost.manifest.command } : {}),
...(recall ? { recall } : {}),
@@ -1679,10 +1712,11 @@ export function getCindyGhostsMcpDeps(
};
const marketTools = hostDeps.pluginMarket && createPluginMarketAgentTools({
market: hostDeps.pluginMarket,
- installedState: (ghostId) => {
- const visibility = classifyGhostVisibility(ghostId, resolveSessionContext()?.workingDir ?? null, ghostVisibilityDeps);
+ installedState: (ghostId, namespace) => {
+ const visibility = classifyGhostVisibility(ghostId, resolveSessionContext()?.workingDir ?? null, ghostVisibilityDeps, namespace);
+ const resolved = resolveInstalledGhost(getGhostManager().list(), ghostId, namespace);
return {
- exists: getGhostManager().list().some(ghost => ghost.manifest.id === ghostId),
+ exists: resolved.status === 'unique',
errorCode: visibility.ok ? null : visibility.errorCode,
};
},
@@ -1733,12 +1767,24 @@ export function getCindyGhostsMcpDeps(
if (signal?.aborted) return { ok: false, errorCode: 'SETUP_CANCELLED' };
const service = getBotAuthorizationService();
if (!service) return { ok: false, errorCode: 'HOST_NOT_READY' };
- return service.request(sessionId, target);
+ if (target.kind === 'host') return service.request(sessionId, target);
+ const visible = classifyGhostVisibility(
+ target.id, context?.workingDir ?? null, ghostVisibilityDeps, target.namespace,
+ );
+ if (!visible.ok) return visible;
+ return service.request(sessionId, {
+ kind: 'plugin',
+ id: visible.ghost.manifest.id,
+ ...(visible.ghost.namespaceState === 'pending' ? {} : deliveryNamespaceFields(visible.ghost)),
+ ...(target.reauthorize ? { reauthorize: true } : {}),
+ });
}
const workingDir = context?.workingDir ?? null;
- const visible = classifyGhostVisibility(target.id, workingDir, ghostVisibilityDeps);
+ const visible = classifyGhostVisibility(target.id, workingDir, ghostVisibilityDeps,
+ target.kind === 'plugin' ? target.namespace : undefined);
if (!visible.ok) return visible;
- const assessment = getGhostSetupAssessment(target.id);
+ const instanceId = installedGhostStoragePart(visible.ghost);
+ const assessment = getGhostSetupAssessment(instanceId);
if (assessment.state === 'ready' && assessment.groups.length === 0) {
// gh-cli and other Host-derived sources deliberately have no synchronous
// setup requirement. An empty assessment is not proof of platform login.
@@ -1753,14 +1799,18 @@ export function getCindyGhostsMcpDeps(
const coordinator = getGhostSetupCoordinator();
if (!coordinator) return { ok: false, errorCode: 'HOST_NOT_READY' };
const result = await coordinator.ensureReady({
- sessionId, ghostId: target.id, workingDir, signal,
+ sessionId, ghostId: instanceId, workingDir, signal,
...(target.reauthorize ? { reauthorize: true } : {}),
});
if (!result.ok) return result;
if (signal?.aborted) return { ok: false, errorCode: 'SETUP_CANCELLED' };
- const current = classifyGhostVisibility(target.id, workingDir, ghostVisibilityDeps);
+ const current = classifyGhostVisibility(target.id, workingDir, ghostVisibilityDeps,
+ target.namespace);
if (!current.ok) return current;
- const final = getGhostSetupAssessment(target.id);
+ if (installedGhostStoragePart(current.ghost) !== instanceId) {
+ return { ok: false, errorCode: 'GHOST_NOT_FOUND' };
+ }
+ const final = getGhostSetupAssessment(instanceId);
if (final.state !== 'ready') return { ok: false, errorCode: 'SETUP_REQUIRED' };
return { ok: true, status: 'ready', ghostId: target.id,
message: 'Host setup is ready. No plugin business operation was executed. Platform permissions are verified only by the requested operation.' };
@@ -1855,6 +1905,7 @@ export function getCindyGhostsMcpDeps(
const recall = ghostRecall(g);
return {
id: g.manifest.id,
+ ...(g.namespaceState === 'pending' ? {} : deliveryNamespaceFields(g)),
name: g.manifest.name,
...(g.manifest.command ? { command: g.manifest.command } : {}),
...(recall ? { recall } : {}),
@@ -1869,15 +1920,15 @@ export function getCindyGhostsMcpDeps(
return visibleChipGhosts(workdir)
.map(toCindyGhostInfo);
},
- async getAwakeGhost(ghostId) {
+ async getAwakeGhost(ghostId, namespace) {
const workdir = resolveSessionContext()?.workingDir ?? null;
- const visibility = classifyGhostVisibility(ghostId, workdir, ghostVisibilityDeps);
+ const visibility = classifyGhostVisibility(ghostId, workdir, ghostVisibilityDeps, namespace);
if (!visibility.ok) return visibility;
- const visible = visibleChipGhosts(workdir).find(
- (ghost) => ghost.manifest.id === ghostId,
+ const visible = visibleChipGhosts(workdir).some(
+ (ghost) => ghost === visibility.ghost || ghost.dir === visibility.ghost.dir,
);
if (visible) {
- return { ok: true, ghost: toCindyGhostInfo(visible) };
+ return { ok: true, ghost: toCindyGhostInfo(visibility.ghost) };
}
return {
ok: false,
@@ -1885,9 +1936,9 @@ export function getCindyGhostsMcpDeps(
message: GHOST_NO_AGENT_SURFACE_MESSAGE,
};
},
- async readGhostManual({ ghostId, path: manualPath }) {
+ async readGhostManual({ ghostId, namespace, path: manualPath }) {
const workdir = resolveSessionContext()?.workingDir ?? null;
- const visibility = classifyGhostVisibility(ghostId, workdir, ghostVisibilityDeps);
+ const visibility = classifyGhostVisibility(ghostId, workdir, ghostVisibilityDeps, namespace);
if (!visibility.ok) {
return {
ok: false,
@@ -1910,6 +1961,7 @@ export function getCindyGhostsMcpDeps(
},
async callGhostTool({
ghostId,
+ namespace,
tool,
args,
attachments,
@@ -1928,16 +1980,26 @@ export function getCindyGhostsMcpDeps(
ghostId,
sessionWorkdir,
ghostVisibilityDeps,
+ namespace,
);
if (!initialVisibility.ok) return initialVisibility;
- const target = initialVisibility.ghost;
+ const target = { ...initialVisibility.ghost };
+ const instanceId = installedGhostStoragePart(target);
+ const approvalToken = ghostInstallApprovalToken(target.approval);
+ const grantTarget: GhostGrantTarget = {
+ approvalToken,
+ isCurrent: () => {
+ const visibility = classifyInstalledGhostVisibility(target, sessionWorkdir, ghostVisibilityDeps);
+ return visibility.ok && ghostInstallApprovalToken(visibility.ghost.approval) === approvalToken;
+ },
+ };
// 媒体过户:显式 attachments 逐张落媒体总仓 + 记可读引用
// (人工确认 = ghost-grant;Host 工具代办 = ghost-tool-grant),指纹注入
// args.attachments 交给意识。任何一张失败整批拒(ATTACHMENT_INVALID),
// 不做半成品授权。全链路见 grantAttachmentUrls。
let mergedArgs = args;
// 文件交接的原授权要贯穿后续目录审批、上下文查询和最终派发。
- const handoffChecks: Array<() => boolean> = [];
+ const handoffChecks: Array<() => boolean> = [grantTarget.isCurrent];
const handoffExpired = () => handoffChecks.some((isCurrent) => !isCurrent());
const handoffDenied = { ok: false as const, errorCode: 'PERMISSION_DENIED' as const,
message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
@@ -1973,12 +2035,12 @@ export function getCindyGhostsMcpDeps(
const authorizationService = getBotAuthorizationService();
if (authorizationService && authorizationSessionId && await isBotAuthorizationSession(authorizationSessionId)) {
const service = authorizationService;
- const card = await service.request(authorizationSessionId, { kind: 'plugin', id: ghostId, ...(setupPlan && getGhostSetupAssessment(ghostId).reauthSuggest ? { reauthorize: true } : {}) }, setupPlan);
+ const card = await service.request(authorizationSessionId, { kind: 'plugin', id: target.manifest.id, ...deliveryNamespaceFields(target), ...(setupPlan && getGhostSetupAssessment(instanceId).reauthSuggest ? { reauthorize: true } : {}) }, setupPlan);
if (!card.ok) return card;
}
const setup = await setupCoordinator.ensureReady({
sessionId: ghostSetupInteractionSessionId(sessionContext),
- ghostId,
+ ghostId: instanceId,
...(!grantOnly ? { tool } : {}),
workingDir: sessionWorkdir,
...(setupPlan ? { plan: setupPlan } : {}),
@@ -1987,8 +2049,8 @@ export function getCindyGhostsMcpDeps(
// OAuth/settings may take minutes. Re-resolve mutable target facts after
// the waiter completes and before beginning the existing side effects.
- const refreshedVisibility = classifyGhostVisibility(
- ghostId,
+ const refreshedVisibility = classifyInstalledGhostVisibility(
+ target,
sessionWorkdir,
ghostVisibilityDeps,
);
@@ -2006,7 +2068,7 @@ export function getCindyGhostsMcpDeps(
}
let finalAssessment;
try {
- finalAssessment = getGhostSetupAssessment(ghostId);
+ finalAssessment = getGhostSetupAssessment(instanceId);
} catch {
return {
ok: false,
@@ -2027,14 +2089,14 @@ export function getCindyGhostsMcpDeps(
if (grantOnly) {
// Full pre-grant gate: confirm target, workdir, and setup readiness
// BEFORE grantAttachmentUrls creates durable ledger entries.
- const grantVisibility = classifyGhostVisibility(
- ghostId,
+ const grantVisibility = classifyInstalledGhostVisibility(
+ target,
sessionWorkdir,
ghostVisibilityDeps,
);
if (!grantVisibility.ok) return grantVisibility;
try {
- const grantOnlyAssessment = getGhostSetupAssessment(ghostId);
+ const grantOnlyAssessment = getGhostSetupAssessment(instanceId);
if (grantOnlyAssessment.state !== 'ready') {
return {
ok: false,
@@ -2051,7 +2113,8 @@ export function getCindyGhostsMcpDeps(
};
}
const grant = await grantAttachmentUrls({
- ghostId,
+ ghostId: instanceId,
+ target: grantTarget,
urls: attachments!,
workdirAbs: sessionWorkdir,
sessionId: sessionIdForConfirm,
@@ -2064,15 +2127,15 @@ export function getCindyGhostsMcpDeps(
}
// Post-grant revalidation: the grant process includes an async user
// confirmation step; re-check everything before returning success.
- const postGrantVisibility = classifyGhostVisibility(
- ghostId,
+ const postGrantVisibility = classifyInstalledGhostVisibility(
+ target,
sessionWorkdir,
ghostVisibilityDeps,
);
if (!postGrantVisibility.ok) return postGrantVisibility;
let postGrantAssessment: GhostSetupAssessment;
try {
- postGrantAssessment = getGhostSetupAssessment(ghostId);
+ postGrantAssessment = getGhostSetupAssessment(instanceId);
if (postGrantAssessment.state !== 'ready') {
return {
ok: false,
@@ -2105,7 +2168,8 @@ export function getCindyGhostsMcpDeps(
const attachmentUrls = [...new Set(attachments ?? [])];
if (attachmentUrls.length > 0) {
const grant = await grantAttachmentUrls({
- ghostId,
+ ghostId: instanceId,
+ target: grantTarget,
urls: attachmentUrls,
workdirAbs: sessionWorkdir,
sessionId: sessionIdForConfirm,
@@ -2127,7 +2191,8 @@ export function getCindyGhostsMcpDeps(
if (dir !== undefined) {
if (handoffExpired()) return handoffDenied;
const dirConfirm = await confirmDepositOutsideWorkdir({
- ghostId,
+ ghostId: instanceId,
+ target: grantTarget,
sessionId: sessionIdForConfirm,
sessionInstanceId: sessionInstanceIdForGrant,
lane: 'dir',
@@ -2141,7 +2206,7 @@ export function getCindyGhostsMcpDeps(
if (dirConfirm.isCurrent) handoffChecks.push(dirConfirm.isCurrent);
if (handoffExpired()) return handoffDenied;
const deposited = getDirDepositVault().deposit({
- ghostId,
+ ghostId: installedGhostStoragePart(target),
dirAbs: dirConfirm.userGranted ? dirConfirm.approvedRealPath : dir,
workdirAbs: sessionWorkdir,
userGranted: dirConfirm.userGranted,
@@ -2158,7 +2223,8 @@ export function getCindyGhostsMcpDeps(
if (saveDir !== undefined) {
if (handoffExpired()) return handoffDenied;
const saveConfirm = await confirmDepositOutsideWorkdir({
- ghostId,
+ ghostId: instanceId,
+ target: grantTarget,
sessionId: sessionIdForConfirm,
sessionInstanceId: sessionInstanceIdForGrant,
lane: 'save_dir',
@@ -2172,7 +2238,7 @@ export function getCindyGhostsMcpDeps(
if (saveConfirm.isCurrent) handoffChecks.push(saveConfirm.isCurrent);
if (handoffExpired()) return handoffDenied;
const saveDeposited = getSaveDepositVault().deposit({
- ghostId,
+ ghostId: installedGhostStoragePart(target),
dirAbs: saveConfirm.userGranted ? saveConfirm.approvedRealPath : saveDir,
workdirAbs: sessionWorkdir,
userGranted: saveConfirm.userGranted,
@@ -2194,8 +2260,8 @@ export function getCindyGhostsMcpDeps(
// Pre-dispatch revalidation: attachment grants and dir tickets may have
// taken time; confirm the target is still available before committing the
// callId and dispatching to the sandbox.
- const preDispatchVisibility = classifyGhostVisibility(
- ghostId,
+ const preDispatchVisibility = classifyInstalledGhostVisibility(
+ target,
sessionWorkdir,
ghostVisibilityDeps,
);
@@ -2209,7 +2275,7 @@ export function getCindyGhostsMcpDeps(
};
}
try {
- const preDispatchAssessment = getGhostSetupAssessment(ghostId);
+ const preDispatchAssessment = getGhostSetupAssessment(instanceId);
if (preDispatchAssessment.state !== 'ready') {
return {
ok: false,
@@ -2230,16 +2296,17 @@ export function getCindyGhostsMcpDeps(
// a same-ID plugin replacement removing the declaration during the await.
if (preDispatch.manifest.sessionContext === true) {
const ctx = await buildGhostSessionContext(sessionIdForConfirm, sessionWorkdir);
- const postCtxManifest = getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId)?.manifest;
+ const postCtxManifest = findInstalledGhostByInstanceId(
+ getGhostManager().list(),
+ instanceId,
+ )?.manifest;
if (postCtxManifest?.sessionContext === true) {
mergedArgs = { ...mergedArgs, session_context: ctx };
}
}
// Full revalidation after session-context await (DB query may take time)
- const postCtxVisibility = classifyGhostVisibility(
- ghostId,
+ const postCtxVisibility = classifyInstalledGhostVisibility(
+ target,
sessionWorkdir,
ghostVisibilityDeps,
);
@@ -2254,7 +2321,7 @@ export function getCindyGhostsMcpDeps(
}
let postCtxAssessment: GhostSetupAssessment;
try {
- postCtxAssessment = getGhostSetupAssessment(ghostId);
+ postCtxAssessment = getGhostSetupAssessment(instanceId);
if (postCtxAssessment.state !== 'ready') {
return {
ok: false,
@@ -2280,7 +2347,8 @@ export function getCindyGhostsMcpDeps(
const cardService = getGhostCardService();
const callSessionContext = resolveSessionContext();
cardService.registerCall(callId, {
- ghostId,
+ ghostId: instanceId,
+ logicalGhostId: pluginStoragePart(installedGhostLogicalIdentity(target)),
toolUseId: agentToolUseId ?? null,
// ALS 优先(codex 每单恢复)、闭包兜底(claude 建线期按 session 绑定)
// ——此前 claude 路径这里恒为 null,卡片只能靠 toolUseId 启发式锚定。
@@ -2293,7 +2361,7 @@ export function getCindyGhostsMcpDeps(
// GhostToolCallResult 与 CindyGhostCallResult 同构(错误码枚举一致),
// 原样透传;类型层若有漂移 tsc 会拦。
const result = await getGhostPipeDispatcher().callGhostTool({
- ghostId,
+ ghostId: instanceId,
tool,
args: mergedArgs,
callId,
@@ -2303,7 +2371,7 @@ export function getCindyGhostsMcpDeps(
// 收口取账(ghostMediaLedger):本次调用期间主机实际入库的媒体地址。
// 失败也 drain(清账防泄漏),但只在成功结果上附带——cindy-tools 层
// 在意识未声明媒体字段时以 xdt_media_produced 注入,兜底 IM/hook 送达。
- const producedMedia = drainGhostCallMedia(ghostId, callId);
+ const producedMedia = drainGhostCallMedia(instanceId, callId);
const finalized = withCardToken(result, cardService.finalizeCall(callId), callId);
if (!finalized.ok) return finalized;
// 附最后一道 gate(postCtx)的快照:它是派发前最新的 ready 判定。
diff --git a/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts b/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts
index ae20f85306..0d0a2f7477 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/agentTools.test.ts
@@ -39,6 +39,14 @@ function harness(ghostId = 'mail-suite', name = 'Google Gmail') {
}
describe('Agent plugin discovery and installation', () => {
+ it.each([undefined, null, 'acme'])('preserves delivery namespace %s', async (namespace) => {
+ const h = harness();
+ if (namespace !== undefined) h.detail.namespace = namespace;
+ const result = await h.tools.search('gmail');
+ const item = (result.items as Array<Record<string, unknown>>)[0];
+ expect('namespace' in item).toBe(namespace !== undefined);
+ expect(item.namespace).toBe(namespace);
+ });
it.each([['mail-suite', 'Google Gmail', 'gmail'], ['image-studio', 'Image creation', 'image']])(
'discovers and installs %s through the same catalog contract', async (id, name, query) => {
const h = harness(id, name);
@@ -54,6 +62,15 @@ describe('Agent plugin discovery and installation', () => {
},
);
+ it('returns the committed namespace for a namespaced install', async () => {
+ const h = harness();
+ h.market.install.mockResolvedValue({
+ ghost: { manifest: h.detail.manifest, enabled: true, namespace: 'acme' } as InstalledGhost,
+ });
+ expect(await h.tools.install({ pluginId: 'catalog-id', releaseId: 'release-1' }))
+ .toMatchObject({ ok: true, status: 'installed', ghost_id: 'mail-suite', namespace: 'acme' });
+ });
+
it.each([null, 'GHOST_ASLEEP', 'GHOST_DISABLED_IN_WORKDIR', 'GHOST_NOT_FOUND'])('preserves an existing installation and reports %s', async (errorCode) => {
const h = harness(); h.state.installed = true; h.state.errorCode = errorCode;
expect(await h.tools.install({ pluginId: 'catalog-id', releaseId: 'release-1' })).toMatchObject({ status: 'already-installed', plugin: { installed: true, availability: errorCode ?? 'available' } });
diff --git a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts
index ddbf540f9e..f3b685101f 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts
@@ -92,6 +92,35 @@ describe('PluginMarketApi', () => {
});
});
+ it('sends the client version on detail and download unchanged', async () => {
+ const fetcher = vi.fn()
+ .mockResolvedValueOnce({
+ schemaVersion: 2,
+ plugin: {
+ ...summary(PLUGIN_A, 'alpha'),
+ currentRelease: {
+ ...summary(PLUGIN_A, 'alpha').currentRelease,
+ manifest: {
+ schemaVersion: 2, id: 'alpha', name: 'alpha', version: '1.0.0', kind: 'chip',
+ entry: 'index.js', slots: ['tool'], tools: [{ name: 'help', description: 'Help' }],
+ },
+ },
+ },
+ })
+ .mockResolvedValueOnce({
+ url: 'https://downloads.example.test/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
+ const api = new PluginMarketApi(fetcher, () => '0.0.0-dev');
+ await api.detail(PLUGIN_A);
+ await api.download(PLUGIN_A, 'release-alpha');
+ expect(fetcher.mock.calls[0]?.[1]).toMatchObject({ headers: { 'x-cindy-version': '0.0.0-dev' } });
+ expect(fetcher.mock.calls[1]?.[1]).toMatchObject({ headers: { 'x-cindy-version': '0.0.0-dev' } });
+ expect(fetcher.mock.calls.map((call) => call[1]?.headers?.['x-cindy-version'])).toEqual(['0.0.0-dev', '0.0.0-dev']);
+ });
+
it('deduplicates removals by pluginId across pages keeping the first-seen notice', async () => {
const fetcher = pagedFetcher(
{
@@ -205,6 +234,31 @@ describe('PluginMarketApi', () => {
});
});
+ it('rejects a later page whose organization namespace conflicts with the first-page identity', async () => {
+ const fetcher = pagedFetcher(
+ {
+ plugins: [], nextCursor: PLUGIN_A,
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix: 'acme' },
+ },
+ {
+ plugins: [{ ...summary(PLUGIN_B, 'beta'), scope: 'organization',
+ organizationId: 'org-other', namespace: 'other' }],
+ nextCursor: null,
+ },
+ );
+ await expect(new PluginMarketApi(fetcher).listAll()).rejects.toThrow('namespace');
+ });
+
+ it('rejects conflicting organization facts across pages even with empty listings', async () => {
+ const fetcher = pagedFetcher(
+ { plugins: [], nextCursor: PLUGIN_A,
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme', pluginPrefix: 'acme' } },
+ { plugins: [], nextCursor: null,
+ currentOrganization: { organizationId: 'org-other', orgSlug: 'other', pluginPrefix: 'other' } },
+ );
+ await expect(new PluginMarketApi(fetcher).listAll()).rejects.toThrow('currentOrganization');
+ });
+
it('keeps a null currentOrganization as a personal-identity fact', async () => {
const fetcher = pagedFetcher({
plugins: [summary(PLUGIN_A, 'alpha')],
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger-ns-durability.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger-ns-durability.test.ts
new file mode 100644
index 0000000000..6f9270d2bc
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger-ns-durability.test.ts
@@ -0,0 +1,117 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const crash = vi.hoisted(() => ({
+ failMain: false,
+ writes: [] as string[],
+}));
+
+vi.mock('../../utils/atomicWriteFile.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../utils/atomicWriteFile.js')>();
+ return {
+ ...actual,
+ atomicWriteFileSync(filePath: string, contents: string) {
+ crash.writes.push(path.basename(filePath));
+ if (crash.failMain && path.basename(filePath) === 'ledger.v1.json') {
+ throw new Error('simulated crash after ns sidecar');
+ }
+ actual.atomicWriteFileSync(filePath, contents);
+ },
+ };
+});
+
+import {
+ NS_LEDGER_FILE,
+ PluginMarketLedger,
+ type PluginMarketInstallationRecord,
+} from '../ledger';
+
+const roots: string[] = [];
+
+afterEach(() => {
+ crash.failMain = false;
+ crash.writes = [];
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+function harness() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-ledger-ns-'));
+ roots.push(root);
+ const filePath = path.join(root, 'plugin-market', 'ledger.v1.json');
+ return { filePath, ledger: new PluginMarketLedger(filePath) };
+}
+
+function record(
+ overrides: Partial<PluginMarketInstallationRecord> = {},
+): PluginMarketInstallationRecord {
+ return {
+ pluginId: `c${'a'.repeat(24)}`,
+ ghostId: 'cindy-test',
+ releaseId: 'release-1',
+ version: '1.0.0',
+ sha256: 'b'.repeat(64),
+ scope: 'public',
+ organizationId: null,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-07-23T00:00:00.000Z',
+ ...overrides,
+ };
+}
+
+describe('PluginMarketLedger namespace write order', () => {
+ it('writes the ns sidecar before rewriting the main ledger', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(
+ record({ ghostId: 'helper', namespace: null, pluginId: `c${'a'.repeat(24)}` }),
+ );
+ crash.writes = [];
+ ledger.upsertInstallation(
+ record({
+ ghostId: 'helper',
+ namespace: 'acme',
+ pluginId: `c${'b'.repeat(24)}`,
+ scope: 'organization',
+ organizationId: 'org_1',
+ }),
+ );
+ expect(crash.writes).toEqual([
+ 'ledger.v1.pending.json',
+ 'ns-ledger.v1.json',
+ 'custom-ledger.v1.json',
+ 'ledger.v1.json',
+ ]);
+ });
+
+ it('keeps org provenance if the main ledger rewrite fails after the sidecar write', () => {
+ const { filePath, ledger } = harness();
+ ledger.upsertInstallation(
+ record({
+ ghostId: 'helper',
+ namespace: 'acme',
+ pluginId: `c${'b'.repeat(24)}`,
+ scope: 'organization',
+ organizationId: 'org_1',
+ }),
+ );
+ crash.failMain = true;
+ expect(() =>
+ ledger.upsertInstallation(
+ record({ ghostId: 'helper', namespace: null, pluginId: `c${'a'.repeat(24)}` }),
+ ),
+ ).toThrow(/simulated crash after ns sidecar/);
+ crash.failMain = false;
+ expect(ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })).toMatchObject({
+ namespace: 'acme',
+ pluginId: `c${'b'.repeat(24)}`,
+ });
+ expect(fs.existsSync(path.join(path.dirname(filePath), 'ledger.v1.pending.json'))).toBe(false);
+ const sidecar = JSON.parse(
+ fs.readFileSync(path.join(path.dirname(filePath), NS_LEDGER_FILE), 'utf8'),
+ ) as { installations: Record<string, { namespace?: string | null }> };
+ expect(sidecar.installations['_ns__acme__helper']).toMatchObject({ namespace: 'acme' });
+ });
+});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
index bb489d1f11..8621395428 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
@@ -5,9 +5,15 @@ import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import {
+ NS_LEDGER_FILE,
PluginMarketLedger,
+ ghostManifestDigest,
type PluginMarketInstallationRecord,
} from '../ledger';
+import { loadGhostFirstPartyFactsLoader } from '../../cindy-brain/ghostFirstPartyFacts';
+import { authorizeGhostTokenBroker } from '../../cindy-brain/ghostFirstPartyPrivilege';
+import { loadConnectionAudienceResolver } from '../../cindy-brain/connectionAudienceResolver';
+import type { GhostManifest } from '../../../shared/ghost';
const roots: string[] = [];
@@ -40,7 +46,177 @@ function record(
};
}
+function sameNameNamespaceHarness(rootInstalled = true) {
+ const h = harness();
+ h.ledger.upsertInstallation(record({
+ ghostId: 'helper', namespace: null, installed: rootInstalled,
+ }));
+ h.ledger.upsertInstallation(record({
+ ghostId: 'helper', namespace: 'acme', pluginId: `c${'b'.repeat(24)}`,
+ scope: 'organization', organizationId: 'org_1',
+ }));
+ return h;
+}
+
describe('PluginMarketLedger', () => {
+ it.each(['main', 'custom', 'namespaced'] as const)(
+ 'keeps namespace migration invalid instead of absent for a malformed target in %s',
+ (source) => {
+ const { filePath, ledger } = harness();
+ const target = record({ ghostId: 'helper', namespace: 'acme', scope: 'organization', organizationId: 'org-1' });
+ const targetPath = source === 'main' ? filePath : path.join(
+ path.dirname(filePath), source === 'custom' ? 'custom-ledger.v1.json' : NS_LEDGER_FILE,
+ );
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(targetPath, JSON.stringify({
+ schemaVersion: 1, installations: { _ns__acme__helper: { ...target, sha256: 42 } },
+ }));
+ expect(ledger.lookupInstallationsForNamespaceMigration('helper')).toEqual({ kind: 'invalid' });
+ expect(ledger.lookupInstallationsForNamespaceMigration('unrelated')).toEqual({ kind: 'absent' });
+ },
+ );
+
+ it('keeps every namespace migration candidate and rejects a malformed sibling', () => {
+ const { filePath, ledger } = sameNameNamespaceHarness();
+ expect(ledger.lookupInstallationsForNamespaceMigration('helper')).toMatchObject({
+ kind: 'found', records: [expect.objectContaining({ namespace: null }), expect.objectContaining({ namespace: 'acme' })],
+ });
+ const raw = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ raw.installations.helper.sha256 = 42;
+ fs.writeFileSync(filePath, JSON.stringify(raw));
+ expect(ledger.lookupInstallationsForNamespaceMigration('helper')).toEqual({ kind: 'invalid' });
+ });
+
+ it.each(['ledger.v1.json', 'custom-ledger.v1.json', NS_LEDGER_FILE].flatMap((fileName) =>
+ ['record', 'key'].map((damage) => ({ fileName, damage })),
+ ))('refuses whole-ledger rewrites with a damaged $damage in $fileName', ({ fileName, damage }) => {
+ const { filePath, ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'public-helper' }));
+ ledger.upsertInstallation(record({
+ ghostId: 'org-helper', scope: 'organization', organizationId: 'org-1',
+ }));
+ const ledgerPaths = [filePath, ...['custom-ledger.v1.json', NS_LEDGER_FILE].map((name) =>
+ path.join(path.dirname(filePath), name),
+ )];
+ const damagedPath = path.join(path.dirname(filePath), fileName);
+ const raw = JSON.parse(fs.readFileSync(damagedPath, 'utf8'));
+ raw.installations[damage === 'key' ? 'wrong-key' : '_ns__acme__broken'] = {
+ ...record({
+ ghostId: 'broken', namespace: 'acme', scope: 'organization', organizationId: 'org-1',
+ source: fileName === 'custom-ledger.v1.json' ? 'local-market' : 'market',
+ }),
+ ...(damage === 'record' ? { sha256: 42 } : {}),
+ };
+ fs.writeFileSync(damagedPath, JSON.stringify(raw));
+ const before = new Map(ledgerPaths.map((ledgerPath) => [ledgerPath, fs.readFileSync(ledgerPath, 'utf8')]));
+ const target = { ghostId: 'broken', namespace: 'acme' };
+ expect(ledger.lookupInstallationsForNamespaceMigration('broken')).toEqual({ kind: 'invalid' });
+ expect(ledger.lookupInstallationsForNamespaceMigration('public-helper')).toMatchObject({ kind: 'found' });
+ expect(ledger.installationsForGhost('broken')).toEqual([]);
+ expect(ledger.installationForGhost('org-helper')).toMatchObject({ scope: 'organization' });
+
+ for (const mutate of [
+ () => ledger.stampNamespaceIfAbsent('public-helper', null),
+ () => ledger.stampNamespaceIfAbsent('org-helper', 'acme'),
+ () => ledger.upsertInstallation(record({ ghostId: 'new-helper' })),
+ ]) {
+ expect(mutate).toThrow(/market ledger is unreadable/i);
+ for (const ledgerPath of ledgerPaths) {
+ expect(fs.readFileSync(ledgerPath, 'utf8')).toBe(before.get(ledgerPath));
+ }
+ expect(ledger.lookupInstallationsForNamespaceMigration('broken')).toEqual({ kind: 'invalid' });
+ expect(ledger.lookupInstallationForAuthorization(target)).toEqual({ kind: 'invalid' });
+ expect(ledger.lookupInstallationForOidc(target)).toEqual({ kind: 'invalid' });
+ }
+ expect(ledger.lookupInstallationForOidc('public-helper')).toMatchObject({ kind: 'found' });
+ });
+
+ it.each([false, true])('does not authorize a known root through an org sibling with a root tombstone=%s', (tombstone) => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'helper', namespace: 'acme', scope: 'organization', organizationId: 'org-1' }));
+ if (tombstone) ledger.upsertInstallation(record({ ghostId: 'helper', namespace: null, installed: false }));
+ const preciseRoot = ledger.lookupInstallationForAuthorization({ ghostId: 'helper', namespace: null });
+ expect(preciseRoot).toEqual(tombstone
+ ? { kind: 'found', record: expect.objectContaining({ namespace: null, installed: false }) }
+ : { kind: 'absent' });
+ expect(ledger.lookupInstallationForOidc('helper', null)).toEqual(preciseRoot);
+ expect(ledger.lookupInstallationForOidc({ ghostId: 'helper', namespace: null })).toEqual(preciseRoot);
+ expect(ledger.lookupInstallationForAuthorization({ ghostId: 'helper', namespace: 'acme' })).toMatchObject({ kind: 'found', record: { namespace: 'acme' } });
+ expect(ledger.lookupInstallationForAuthorization({ ghostId: 'helper', namespace: 'other' })).toEqual({ kind: 'absent' });
+ expect(ledger.lookupInstallationForAuthorization({ ghostId: 'helper' })).toMatchObject({ kind: 'found', record: { namespace: 'acme' } });
+ });
+
+ it('resolves an old unnamespaced organization row only for a pending target, not known root', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1' }));
+ expect(ledger.lookupInstallationForAuthorization({ ghostId: 'helper', namespace: null })).toEqual({ kind: 'absent' });
+ expect(ledger.lookupInstallationForAuthorization({ ghostId: 'helper' })).toMatchObject({ kind: 'found' });
+ });
+
+ it('keeps precise authorization fail-closed for malformed records and files', () => {
+ const { filePath, ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'helper', namespace: null }));
+ const raw = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ raw.installations.helper.sha256 = 42;
+ fs.writeFileSync(filePath, JSON.stringify(raw));
+ const target = { ghostId: 'helper', namespace: null };
+ expect(ledger.lookupInstallationForAuthorization(target)).toEqual({ kind: 'invalid' });
+ expect(ledger.lookupInstallationForOidc(target)).toEqual({ kind: 'invalid' });
+ expect(() => ledger.installationForAuthorization(target)).toThrow(/unreadable/);
+ fs.writeFileSync(filePath, '{');
+ expect(ledger.lookupInstallationForOidc(target)).toEqual({ kind: 'invalid' });
+ });
+
+ it.each([null, 'acme'])('grants enterprise Broker and OIDC only to the org copy of identical package bytes (namespace=%s)', (namespace) => {
+ const { ledger } = harness();
+ const manifest: GhostManifest = {
+ schemaVersion: 2, id: 'helper', name: 'Helper', version: '1.0.0', kind: 'chip', entry: 'main.js',
+ network: { hosts: ['service.test'], secrets: [{
+ key: 'identity', label: 'Identity', source: 'oidc-token',
+ inject: { header: 'Authorization', hosts: ['service.test'], format: 'Bearer {value}' },
+ }] },
+ };
+ const packageSha256 = 'a'.repeat(64);
+ const manifestDigest = ghostManifestDigest(manifest);
+ ledger.upsertInstallation(record({ ghostId: 'helper', namespace: 'acme', scope: 'organization',
+ organizationId: 'org-1', sha256: packageSha256, manifestDigest, rawManifestSha256: manifestDigest }));
+ const identity = { membershipId: 'member-1', membershipKind: 'org' as const, orgId: 'org-1', orgSlug: 'acme' };
+ const target = { ghostId: 'helper', namespace };
+ const factsLoader = loadGhostFirstPartyFactsLoader({
+ readInstalledBuiltin: () => false, readInstallOrigin: () => 'manual',
+ readInstallNamespace: () => namespace, readApprovedPackageSha256: () => packageSha256,
+ readMarketInstallation: () => ledger.installationForAuthorization(target),
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ });
+ expect(authorizeGhostTokenBroker('helper', factsLoader.load('helper', 'runtime', identity))).toBe(namespace !== null);
+ const resolver = loadConnectionAudienceResolver({
+ readInstalledManifestIdentity: () => ({ manifest, rawManifestSha256: manifestDigest,
+ legacyManifestDigest: manifestDigest, legacyManifestDigests: [manifestDigest] }),
+ readApprovedPackageSha256: () => packageSha256, readInstallNamespace: () => namespace,
+ readMarketInstallation: () => ledger.lookupInstallationForOidc(target),
+ });
+ expect(resolver.resolve('helper', identity) !== null).toBe(namespace !== null);
+ });
+ it('never falls back from an explicit root uninstall to a same-id organization sibling', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(record({ namespace: 'acme', scope: 'organization', organizationId: 'org-1' }));
+ expect(ledger.installationForLocalUninstall({ ghostId: 'cindy-test', namespace: null })).toBeNull();
+ expect(ledger.installationForLocalUninstall({ ghostId: 'cindy-test', namespace: 'acme' })).toMatchObject({ namespace: 'acme' });
+ ledger.upsertInstallation(record({ namespace: null, installed: false }));
+ expect(ledger.installationForLocalUninstall({ ghostId: 'cindy-test', namespace: null })).toBeNull();
+ });
+
+ it('retires only the unchanged provenance captured for local uninstall', () => {
+ const { ledger } = harness();
+ const original = record({ namespace: null });
+ ledger.upsertInstallation(original);
+ const replacement = record({ namespace: null, source: 'local-market', sourceKey: 'new-source' });
+ ledger.upsertInstallation(replacement);
+ ledger.markRemovedRecordIfUnchanged(original, 'user-1');
+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: true, sourceKey: 'new-source' });
+ ledger.markRemovedRecordIfUnchanged(replacement, 'user-1');
+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: false });
+ });
it('writes provenance atomically and reads it back', () => {
const { filePath, ledger } = harness();
ledger.upsertInstallation(record({
@@ -66,6 +242,50 @@ describe('PluginMarketLedger', () => {
).toEqual([]);
});
+ it('persists known namespace and drops invalid namespace records as unreadable', () => {
+ const { filePath, ledger } = harness();
+ ledger.upsertInstallation(record({ namespace: null }));
+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({ namespace: null });
+ ledger.upsertInstallation(record({ ghostId: 'org-helper', namespace: 'acme' }));
+ expect(ledger.installationForGhost('org-helper')).toMatchObject({ namespace: 'acme' });
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as {
+ schemaVersion: number;
+ installations: Record<string, Record<string, unknown>>;
+ defaultInstallOptOuts: Record<string, string[]>;
+ };
+ parsed.installations['cindy-test'] = {
+ ...parsed.installations['cindy-test'],
+ namespace: 'Bad Namespace',
+ };
+ fs.writeFileSync(filePath, JSON.stringify(parsed));
+ expect(ledger.installationForGhost('cindy-test')).toBeNull();
+ expect(ledger.installationForGhost('org-helper')).toMatchObject({ namespace: 'acme' });
+ });
+
+ it('stamps namespace onto a pre-namespace row and refuses to overwrite a known value', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'helper' }));
+ expect(ledger.stampNamespaceIfAbsent('helper', 'acme')).toBe(true);
+ expect(ledger.installationForGhost('helper')).toMatchObject({ namespace: 'acme' });
+ expect(ledger.stampNamespaceIfAbsent('helper', 'acme')).toBe(true);
+ expect(ledger.stampNamespaceIfAbsent('helper', null)).toBe(false);
+ expect(ledger.installationForGhost('helper')).toMatchObject({ namespace: 'acme' });
+ expect(ledger.stampNamespaceIfAbsent('missing', 'acme')).toBe(false);
+ });
+
+ it('stamps the installed record even when a removed record shares its ghost id', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'helper' }));
+ ledger.upsertInstallation(record({ ghostId: 'helper', pluginId: 'removed',
+ namespace: 'other', scope: 'organization', organizationId: 'org-other', installed: false }));
+ expect(ledger.hasInstalledRecordForGhostId('helper')).toBe(true);
+ expect(ledger.stampNamespaceIfAbsent('helper', 'acme')).toBe(true);
+ expect(ledger.installationsForGhost('helper')).toEqual(expect.arrayContaining([
+ expect.objectContaining({ installed: true, namespace: 'acme' }),
+ expect.objectContaining({ installed: false, namespace: 'other' }),
+ ]));
+ });
+
it('backfills raw manifest identity without changing legacy routing fields', () => {
const { ledger } = harness();
const legacy = record({ manifestDigest: 'c'.repeat(64) });
@@ -111,7 +331,7 @@ describe('PluginMarketLedger', () => {
it('records defaultInstall opt-out per authenticated user on removal', () => {
const { ledger } = harness();
ledger.upsertInstallation(record());
- ledger.markRemoved('cindy-test', 'user-a');
+ ledger.markRemovedRecord(ledger.installationForGhost('cindy-test')!, 'user-a');
expect(ledger.installationForGhost('cindy-test')?.installed).toBe(false);
expect(
@@ -125,11 +345,11 @@ describe('PluginMarketLedger', () => {
it('detaches a replacement source without creating or clearing explicit opt-out', () => {
const { ledger } = harness();
ledger.upsertInstallation(record());
- ledger.markRemoved('cindy-test', 'user-a');
+ ledger.markRemovedRecord(ledger.installationForGhost('cindy-test')!, 'user-a');
ledger.restoreInstallation(record());
expect(ledger.isDefaultInstallSuppressed('user-a', `c${'a'.repeat(24)}`)).toBe(true);
- ledger.markRemoved('cindy-test', null);
+ ledger.markRemovedRecord(ledger.installationForGhost('cindy-test')!, null);
expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: false });
expect(ledger.isDefaultInstallSuppressed('user-a', `c${'a'.repeat(24)}`)).toBe(true);
expect(ledger.isDefaultInstallSuppressed('user-b', `c${'a'.repeat(24)}`)).toBe(false);
@@ -142,7 +362,7 @@ describe('PluginMarketLedger', () => {
it('atomically reconnects an unchanged server record and clears its false opt-out', () => {
const { ledger } = harness();
ledger.upsertInstallation(record({ rawManifestSha256: 'd'.repeat(64) }));
- ledger.markRemoved('cindy-test', 'user-a');
+ ledger.markRemovedRecord(ledger.installationForGhost('cindy-test')!, 'user-a');
const disconnected = ledger.installationForGhost('cindy-test');
expect(disconnected).not.toBeNull();
if (!disconnected) return;
@@ -163,7 +383,7 @@ describe('PluginMarketLedger', () => {
scope: 'organization',
organizationId: 'org-a',
}));
- ledger.markRemoved('cindy-test', 'user-a');
+ ledger.markRemovedRecord(ledger.installationForGhost('cindy-test')!, 'user-a');
const disconnected = ledger.installationForGhost('cindy-test');
expect(disconnected).not.toBeNull();
if (!disconnected) return;
@@ -189,16 +409,12 @@ describe('PluginMarketLedger', () => {
});
});
- it('fails closed to an empty ledger for malformed or future data', () => {
+ it('refuses to rewrite a future ledger version', () => {
const { filePath, ledger } = harness();
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, '{"schemaVersion":99,"installations":{"x":{}}}');
- expect(ledger.read()).toEqual({
- schemaVersion: 1,
- installations: {},
- defaultInstallOptOuts: {},
- });
+ expect(() => ledger.read()).toThrow(/market ledger is unreadable/i);
expect(ledger.lookupInstallationForOidc('cindy-test')).toEqual({ kind: 'invalid' });
});
@@ -230,7 +446,7 @@ describe('PluginMarketLedger', () => {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, '{not-json');
- expect(ledger.installationForGhost('cindy-test')).toBeNull();
+ expect(() => ledger.installationForGhost('cindy-test')).toThrow(/market ledger is unreadable/i);
expect(ledger.lookupInstallationForOidc('cindy-test')).toEqual({ kind: 'invalid' });
});
@@ -239,7 +455,7 @@ describe('PluginMarketLedger', () => {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify({ schemaVersion: 1, installations: null }));
- expect(ledger.installationForGhost('cindy-test')).toBeNull();
+ expect(() => ledger.installationForGhost('cindy-test')).toThrow(/market ledger is unreadable/i);
expect(ledger.lookupInstallationForOidc('cindy-test')).toEqual({ kind: 'invalid' });
});
@@ -476,4 +692,142 @@ describe('PluginMarketLedger', () => {
const custom = JSON.parse(fs.readFileSync(customPath, 'utf8'));
expect(Object.keys(custom.installations)).toEqual(['cindy-custom']);
});
+
+ it('keeps same-name root and organization rows and writes the org row to the ns sidecar', () => {
+ const { filePath, ledger } = sameNameNamespaceHarness();
+ expect(ledger.installationForPlugin({ ghostId: 'helper', namespace: null })).toMatchObject({
+ namespace: null,
+ pluginId: `c${'a'.repeat(24)}`,
+ });
+ expect(ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })).toMatchObject({
+ namespace: 'acme',
+ pluginId: `c${'b'.repeat(24)}`,
+ });
+ expect(ledger.installationForGhost('helper')).toBeNull();
+ expect(ledger.installationsForGhost('helper')).toHaveLength(2);
+ expect(ledger.installationForAuthorization({ ghostId: 'helper' })).toMatchObject({ namespace: null });
+ expect(ledger.installationForAuthorization({ ghostId: '_ns/_root/helper' })).toMatchObject({ namespace: null });
+ expect(ledger.installationForAuthorization({ ghostId: '_root__helper' })).toMatchObject({ namespace: null });
+ expect(ledger.installationForAuthorization({ ghostId: '_ns__acme__helper' })).toMatchObject({ namespace: 'acme' });
+ const main = JSON.parse(fs.readFileSync(filePath, 'utf8')) as {
+ installations: Record<string, { namespace?: string | null }>;
+ };
+ expect(main.installations.helper).toMatchObject({ namespace: null });
+ const sidecar = JSON.parse(
+ fs.readFileSync(path.join(path.dirname(filePath), NS_LEDGER_FILE), 'utf8'),
+ ) as { installations: Record<string, { namespace?: string | null; ghostId: string }> };
+ expect(sidecar.installations['_ns__acme__helper']).toMatchObject({
+ ghostId: 'helper',
+ namespace: 'acme',
+ });
+ });
+
+ it('skips an uninstalled public row when a unique live organization row remains', () => {
+ const { ledger } = sameNameNamespaceHarness(false);
+ expect(ledger.installationForAuthorization({ ghostId: 'helper' })).toMatchObject({
+ namespace: 'acme',
+ installed: true,
+ });
+ expect(ledger.lookupInstallationForOidc('helper')).toMatchObject({
+ kind: 'found',
+ record: { namespace: 'acme', installed: true },
+ });
+ });
+
+ it('still returns the public tombstone when nothing remains installed', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(
+ record({ ghostId: 'helper', namespace: null, installed: false }),
+ );
+ expect(ledger.installationForAuthorization({ ghostId: 'helper' })).toMatchObject({
+ namespace: null,
+ installed: false,
+ });
+ });
+
+ it('keeps a unique organization row in the main ledger keyed by ghostId', () => {
+ const { filePath, ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'xd-feishu', namespace: 'xd' }));
+ expect(ledger.installationForGhost('xd-feishu')).toMatchObject({ namespace: 'xd' });
+ const main = JSON.parse(fs.readFileSync(filePath, 'utf8')) as {
+ installations: Record<string, { namespace?: string | null }>;
+ };
+ expect(main.installations['xd-feishu']).toMatchObject({ namespace: 'xd' });
+ expect(fs.existsSync(path.join(path.dirname(filePath), NS_LEDGER_FILE))).toBe(true);
+ const sidecar = JSON.parse(
+ fs.readFileSync(path.join(path.dirname(filePath), NS_LEDGER_FILE), 'utf8'),
+ ) as { installations: Record<string, unknown> };
+ expect(sidecar.installations).toEqual({});
+ });
+
+ it("does not wipe namespaced org rows when ns-ledger JSON is unreadable", () => {
+ const { filePath, ledger } = sameNameNamespaceHarness();
+ const nsPath = path.join(path.dirname(filePath), NS_LEDGER_FILE);
+ const before = fs.readFileSync(nsPath, "utf8");
+ fs.writeFileSync(nsPath, "{not-json");
+ expect(() => ledger.read()).toThrow(/market ledger is unreadable/i);
+ expect(() =>
+ ledger.upsertInstallation(record({ ghostId: "other", pluginId: `c${"c".repeat(24)}` })),
+ ).toThrow(/market ledger is unreadable/i);
+ expect(fs.readFileSync(nsPath, "utf8")).toBe("{not-json");
+ expect(ledger.lookupInstallationForOidc("helper")).toEqual({ kind: "invalid" });
+ fs.writeFileSync(nsPath, before);
+ expect(ledger.installationForPlugin({ ghostId: "helper", namespace: "acme" })).toMatchObject({
+ namespace: "acme",
+ pluginId: `c${"b".repeat(24)}`,
+ });
+ });
+
+ it.each(['ledger.v1.json', 'custom-ledger.v1.json'])(
+ 'does not overwrite a damaged %s during a later installation',
+ (name) => {
+ const { filePath, ledger } = harness();
+ ledger.upsertInstallation(record({ ghostId: 'kept' }));
+ const damagedPath = path.join(path.dirname(filePath), name);
+ fs.writeFileSync(damagedPath, '{corrupt');
+ expect(() => ledger.upsertInstallation(record({ ghostId: 'new' }))).toThrow(/market ledger is unreadable/i);
+ expect(fs.readFileSync(damagedPath, 'utf8')).toBe('{corrupt');
+ expect(ledger.lookupInstallationForOidc('kept')).toEqual({ kind: 'invalid' });
+ },
+ );
+
+});
+
+
+describe('backfill missing namespace from the server catalog', () => {
+ const pluginId = 'c' + 'd'.repeat(24);
+ function installedRow(overrides: Partial<PluginMarketInstallationRecord> = {}) {
+ const row = record({
+ pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-xd',
+ sha256: 'ab'.repeat(32), source: 'market', installed: true,
+ ...overrides,
+ });
+ delete row.namespace;
+ return row;
+ }
+ it('fills a missing namespace and does not overwrite or cross organizations', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(installedRow());
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'other', namespace: 'xd',
+ }])).toBe(0);
+ expect(ledger.installationForPlugin({ ghostId: 'xd-feishu' })).not.toHaveProperty('namespace');
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-xd',
+ }])).toBe(0);
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-xd', namespace: null,
+ }])).toBe(0);
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-xd', namespace: 'XD',
+ }])).toBe(0);
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-xd', namespace: 'xd',
+ }])).toBe(1);
+ expect(ledger.installationForPlugin({ ghostId: 'xd-feishu', namespace: 'xd' })).toMatchObject({ namespace: 'xd' });
+ expect(ledger.backfillMissingNamespacesFromCatalog([{
+ id: pluginId, ghostId: 'xd-feishu', scope: 'organization', organizationId: 'org-xd', namespace: 'other',
+ }])).toBe(0);
+ expect(ledger.installationForPlugin({ ghostId: 'xd-feishu', namespace: 'xd' })?.namespace).toBe('xd');
+ });
});
diff --git 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
index 74c45b93a4..45c7e42416 100644
--- 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
@@ -646,6 +646,7 @@ describe('PluginMarketService 自定义市场聚合', () => {
enabled: true,
});
expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('sourceChanged');
});
});
@@ -1719,6 +1720,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
manifestCap: ghostManifest('alpha'),
+ sourceChanged: true,
});
expect(h.ledger.installationForGhost('alpha')).toMatchObject({
pluginId: customMarketPluginId('team-lib', 'alpha'),
@@ -1980,6 +1982,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
manifestCap: ghostManifest('alpha', '2.0.0'),
+ sourceChanged: true,
});
expect(h.ledger.installationForGhost('alpha')).toMatchObject({
sourceKey: marketSourceKey({ type: 'local', path: dirB }),
@@ -2274,6 +2277,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
}, TEST_INSTALL_CONTEXT),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
+ expect(runtime.install.mock.calls[0]?.[1]).toHaveProperty('sourceChanged', true);
expect(h.ledger.installationForGhost('server-plugin')).toMatchObject({
pluginId: item.id,
source: 'market',
@@ -2312,6 +2316,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
manifestCap: ghostManifest('alpha'),
+ sourceChanged: true,
});
expect(h.ledger.installationForGhost('alpha')).toMatchObject({
pluginId: customMarketPluginId('team-lib', 'alpha'),
@@ -2373,6 +2378,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
updatedAt: '2026-07-30T02:00:00.000Z',
});
+ runtime.ghosts = [installedGhost(root, 'alpha')];
await expect(h.service.uninstall(pluginId)).resolves.toEqual({ ok: true });
expect(runtime.uninstall).toHaveBeenCalledWith('alpha', { skipMarketLedger: true });
expect(h.ledger.installationForGhost('alpha')?.installed).toBe(false);
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 8dde7e5599..23a060f382 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -19,6 +19,8 @@ const runtime = vi.hoisted(() => ({
manifest: Record<string, unknown>;
dir: string;
enabled: boolean;
+ namespace?: string | null;
+ namespaceState?: 'pending';
approval?: GhostInstallApproval;
trust?: GhostTrustInfo;
}>,
@@ -31,9 +33,22 @@ const runtime = vi.hoisted(() => ({
pendingCalls: false,
runningErrand: false,
cindyWork: false,
+ busyQueryIds: [] as string[],
generatedInstallDirs: [] as string[],
installOrigins: new Map<string, 'manual' | 'agent-forge'>(),
installOriginError: false,
+ authIdentity: { membershipKind: 'org', orgId: 'org-1', orgSlug: 'acme' } as {
+ membershipKind: 'org' | 'personal';
+ orgId: string | null;
+ orgSlug: string | null;
+ } | null,
+ authStateOverrides: {} as {
+ isAuthenticated?: boolean;
+ dataOwnerId?: string | null;
+ ownerGeneration?: number;
+ },
+ resumeOfflineResidents: vi.fn(),
+ reconcilePendingRootNamespaces: vi.fn(),
currentOrganization: null as {
organizationId: string;
pluginPrefix: string | null;
@@ -62,6 +77,14 @@ vi.mock('electron', () => ({
},
}));
vi.mock('../../authManager.js', () => ({
+ getAuthState: () => ({
+ user: runtime.authIdentity,
+ mode: runtime.session.mode,
+ dataOwnerId: runtime.session.dataOwnerId,
+ ownerGeneration: runtime.session.generation,
+ isAuthenticated: runtime.session.mode === 'cloud',
+ ...runtime.authStateOverrides,
+ }),
getCurrentUserId: vi.fn(() =>
runtime.session.mode === 'cloud' ? runtime.session.dataOwnerId : null,
),
@@ -81,6 +104,8 @@ vi.mock('../../logger.js', () => ({
}));
vi.mock('../../cindy-brain/index.js', () => ({
getGhostManager: () => ({
+ resumePendingResidentsOffline: runtime.resumeOfflineResidents,
+ reconcilePendingRootNamespaces: runtime.reconcilePendingRootNamespaces,
list: () =>
runtime.ghosts.map((ghost) => {
// Historical service tests used a production-looking placeholder path.
@@ -162,9 +187,18 @@ vi.mock('../../cindy-brain/index.js', () => ({
});
return installed;
},
- hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),
- hasRunningGhostErrand: vi.fn(() => runtime.runningErrand),
- hasRunningGhostCindyWork: vi.fn(() => runtime.cindyWork),
+ hasPendingGhostCalls: vi.fn((id: string) => {
+ runtime.busyQueryIds.push(id);
+ return runtime.pendingCalls;
+ }),
+ hasRunningGhostErrand: vi.fn((id: string) => {
+ runtime.busyQueryIds.push(id);
+ return runtime.runningErrand;
+ }),
+ hasRunningGhostCindyWork: vi.fn((id: string) => {
+ runtime.busyQueryIds.push(id);
+ return runtime.cindyWork;
+ }),
isBuiltinGhostRemovedByUser: (id: string) => runtime.builtinRemoved.has(id),
uninstallGhostAndCleanup: runtime.uninstall,
}));
@@ -173,6 +207,7 @@ vi.mock('../download.js', () => ({
}));
import type {
+ PluginDownloadResponse,
PluginRemovalNotice,
VisiblePluginDetail,
VisiblePluginSummary,
@@ -223,11 +258,16 @@ afterEach(() => {
runtime.pendingCalls = false;
runtime.runningErrand = false;
runtime.cindyWork = false;
+ runtime.busyQueryIds = [];
for (const dir of runtime.generatedInstallDirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
runtime.installOrigins.clear();
runtime.installOriginError = false;
+ runtime.authIdentity = { membershipKind: 'org', orgId: 'org-1', orgSlug: 'acme' };
+ runtime.authStateOverrides = {};
+ runtime.resumeOfflineResidents.mockClear();
+ runtime.reconcilePendingRootNamespaces.mockReset();
runtime.currentOrganization = null;
runtime.boundaryPending = false;
runtime.approvedInstallEvidence.mockReset();
@@ -398,12 +438,25 @@ function harness(items: VisiblePluginSummary[], removals: PluginRemovalNotice[]
},
} satisfies VisiblePluginDetail;
}),
- download: vi.fn(async () => ({
- url: 'https://downloads.test.invalid/plugin.cindy',
- expiresAt: '2099-01-01T00:00:00.000Z',
- sha256: 'a'.repeat(64),
- sizeBytes: 42,
- })),
+ download: vi.fn(async (pluginId?: string, releaseId?: string): Promise<PluginDownloadResponse> => {
+ const item = items.find((candidate) => candidate.id === pluginId);
+ const body: PluginDownloadResponse = {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ if (item && releaseId && Object.prototype.hasOwnProperty.call(item, 'namespace')) {
+ return {
+ ...body,
+ pluginId: item.id,
+ releaseId,
+ ghostId: item.ghostId,
+ namespace: item.namespace ?? null,
+ };
+ }
+ return body;
+ }),
};
runtime.inspect.mockImplementation(async () => {
const inspectedManifest = runtime.inspectedManifest ?? manifest(items[0]?.ghostId);
@@ -451,7 +504,273 @@ function mockUninstallDropsGhost(failFor?: string): void {
});
}
+function installOrganizationHelper(
+ rawManifest: Record<string, unknown> = manifest('helper'),
+ layout: 'legacy' | 'namespaced' = 'namespaced',
+): string {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-namespace-'));
+ roots.push(root);
+ const dir = layout === 'legacy'
+ ? path.join(root, 'helper')
+ : path.join(root, '_ns', 'acme', 'helper');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(rawManifest));
+ runtime.ghosts = [{ manifest: rawManifest, dir, namespace: 'acme', enabled: true }];
+ return dir;
+}
+
+function namespaceRecoveryHarness(
+ items: VisiblePluginSummary[],
+ catalogItem: VisiblePluginSummary,
+) {
+ const canonicalManifest = normalizedManifest(manifest('helper'));
+ installOrganizationHelper(canonicalManifest as unknown as Record<string, unknown>);
+ runtime.approvedInstallEvidence.mockReturnValue({
+ packageSha256: catalogItem.currentRelease.sha256,
+ approvedManifest: canonicalManifest,
+ legacyMigrated: false,
+ });
+ const h = harness(items);
+ const record = recordForTest(catalogItem, {
+ namespace: 'acme', manifestDigest: ghostManifestDigest(canonicalManifest),
+ });
+ h.ledger.upsertInstallation(record);
+ h.ledger.markRemovedRecord(record, 'user-1');
+ return h;
+}
+
describe('PluginMarketService migration and defaultInstall', () => {
+ it.each([
+ { namespace: undefined, evidence: 'matching' },
+ { namespace: 'acme', evidence: 'matching' },
+ { namespace: 'acme', evidence: 'write-failed' },
+ { namespace: 'acme', evidence: 'package-mismatch' },
+ { namespace: 'acme', evidence: 'manifest-mismatch' },
+ { namespace: 'acme', evidence: 'raw-mismatch' },
+ { namespace: 'acme', evidence: 'version-mismatch' },
+ { namespace: 'acme', evidence: 'missing' },
+ ] as const)('recovers a pending disconnected organization before root reconciliation ($namespace, $evidence)', async ({ namespace, evidence }) => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1',
+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID }, ...(namespace ? { namespace } : {}) });
+ const dir = installOrganizationHelper(manifest('helper'), 'legacy');
+ const h = harness([item]);
+ delete runtime.ghosts[0]!.namespace;
+ runtime.ghosts[0]!.namespaceState = 'pending';
+ const identitySha = crypto.createHash('sha256').update(fs.readFileSync(path.join(dir, 'ghost.json'))).digest('hex');
+ const record = recordForTest(item, {
+ installed: false, rawManifestSha256: evidence === 'raw-mismatch' ? 'b'.repeat(64) : identitySha,
+ version: evidence === 'version-mismatch' ? '0.9.0' : '1.0.0',
+ });
+ h.ledger.upsertInstallation(record);
+ runtime.approvedInstallEvidence.mockReturnValue(evidence === 'missing' ? null : {
+ packageSha256: evidence === 'package-mismatch' ? 'b'.repeat(64) : item.currentRelease.sha256,
+ approvedManifest: normalizedManifest(evidence === 'manifest-mismatch' ? { ...manifest('helper'), name: 'Changed' } : manifest('helper')),
+ legacyMigrated: false,
+ });
+ const restoredAtReconcile: boolean[] = [];
+ runtime.reconcilePendingRootNamespaces.mockImplementation(() => {
+ const restored = h.ledger.installationForGhost('helper')?.installed === true;
+ restoredAtReconcile.push(restored);
+ });
+ if (evidence === 'write-failed') {
+ vi.spyOn(h.ledger, 'restoreDisconnectedInstallation').mockImplementationOnce(() => {
+ throw Object.assign(new Error('ledger write denied'), { code: 'EACCES' });
+ });
+ }
+ await h.service.snapshot();
+ if (evidence === 'write-failed') {
+ expect(restoredAtReconcile).toEqual([false]);
+ expect(h.ledger.installationForGhost('helper')?.installed).toBe(false);
+ await h.service.snapshot();
+ }
+ const recovered = evidence === 'matching' || evidence === 'write-failed';
+ expect(restoredAtReconcile).toEqual(evidence === 'write-failed' ? [false, true] : [recovered]);
+ expect(h.ledger.installationForGhost('helper')?.installed).toBe(recovered);
+ expect(runtime.ghosts[0]!.dir).toBe(dir);
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(runtime.reconcilePendingRootNamespaces).toHaveBeenCalledTimes(evidence === 'write-failed' ? 2 : 1);
+ });
+
+ it.each(['before-snapshot', 'during-download'] as const)(
+ 'ignores a root tombstone for a trusted pre-S1 organization default (%s)',
+ async (stage) => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1', defaultInstall: true });
+ const h = harness([item]);
+ if (stage === 'before-snapshot') runtime.builtinRemoved.add(item.ghostId);
+ else h.api.download.mockImplementationOnce(async () => {
+ runtime.builtinRemoved.add(item.ghostId);
+ return { url: 'https://downloads.test.invalid/plugin.cindy', expiresAt: '2099-01-01T00:00:00.000Z', sha256: 'a'.repeat(64), sizeBytes: 42 };
+ });
+ runtime.install.mockImplementation(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ installOrganizationHelper(manifest('helper'));
+ return runtime.ghosts[0]!;
+ });
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledOnce();
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })).toMatchObject({ installed: true });
+ },
+ );
+
+ it.each(['legacy-root', 'isolated-root', 'in-place-org'] as const)(
+ 'projects explicit root identity only after binding a pre-S1 public entry (%s)',
+ async (layout) => {
+ const item = summary({ ghostId: 'helper' });
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-public-identity-'));
+ roots.push(root);
+ const dir = layout === 'isolated-root' ? path.join(root, '_ns', '_root', 'helper') : path.join(root, 'helper');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(manifest('helper')));
+ runtime.ghosts = [{ manifest: manifest('helper'), dir, namespace: layout === 'in-place-org' ? 'acme' : null, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, {
+ namespace: layout === 'in-place-org' ? 'acme' : null,
+ ...(layout === 'in-place-org' ? { scope: 'organization', organizationId: 'org-1' } : {}),
+ manifestDigest: ghostManifestDigest(manifest('helper')),
+ }));
+ const projected = [(await h.service.snapshot()).items[0]!, await h.service.detail(item.id)];
+ for (const result of projected) {
+ if (layout === 'in-place-org') {
+ expect(result.installState).toBe('not-installed');
+ expect(result).not.toHaveProperty('namespace');
+ } else {
+ expect(result).toMatchObject({ namespace: null, installState: 'installed' });
+ }
+ }
+ },
+ );
+
+ it.each([
+ [false, false], [false, true], [true, false], [true, true],
+ ])('binds an old-server organization first install to login identity (default=%s, root sibling=%s)', async (defaultInstall, rootSibling) => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1', defaultInstall });
+ runtime.currentOrganization = { organizationId: 'org-1', pluginPrefix: 'not-the-namespace' };
+ if (rootSibling) {
+ installRuntimeGhost(manifest('helper'));
+ runtime.ghosts[0]!.namespace = null;
+ }
+ const siblings = [...runtime.ghosts];
+ const h = harness([item]);
+ runtime.install.mockImplementation(async (_file, options) => {
+ expect(options).toMatchObject({ ghostId: 'helper', namespace: 'acme' });
+ expect(options).not.toHaveProperty('sourceChanged');
+ installOrganizationHelper(manifest('helper'));
+ const installed = runtime.ghosts[0]!;
+ runtime.ghosts = [...siblings, installed];
+ return installed;
+ });
+ if (defaultInstall) {
+ await h.service.snapshot();
+ } else {
+ await h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
+ }
+ expect(runtime.install).toHaveBeenCalledOnce();
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' }))
+ .toMatchObject({ installed: true, scope: 'organization', organizationId: 'org-1' });
+ expect(h.ledger.lookupInstallationForOidc({ ghostId: 'helper', namespace: 'acme' }).kind).toBe('found');
+ expect(h.ledger.lookupInstallationForOidc({ ghostId: 'helper', namespace: null }).kind).toBe('absent');
+ expect((await h.service.snapshot()).items[0]?.installState).toBe('installed');
+ expect(runtime.install).toHaveBeenCalledOnce();
+ expect(runtime.ghosts).toHaveLength(rootSibling ? 2 : 1);
+ });
+
+ it.each(['missing-user', 'missing-slug', 'invalid-slug', 'personal', 'wrong-org', 'wrong-owner', 'wrong-generation', 'unauthenticated'])(
+ 'rejects an old-server organization first install without trusted login identity (%s)', async (scenario) => {
+ if (scenario === 'missing-user') runtime.authIdentity = null;
+ if (scenario === 'missing-slug') runtime.authIdentity!.orgSlug = null;
+ if (scenario === 'invalid-slug') runtime.authIdentity!.orgSlug = '../acme';
+ if (scenario === 'personal') runtime.authIdentity!.membershipKind = 'personal';
+ if (scenario === 'wrong-org') runtime.authIdentity!.orgId = 'other-org';
+ if (scenario === 'wrong-owner') runtime.authStateOverrides.dataOwnerId = 'other-owner';
+ if (scenario === 'wrong-generation') runtime.authStateOverrides.ownerGeneration = 2;
+ if (scenario === 'unauthenticated') runtime.authStateOverrides.isAuthenticated = false;
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1' });
+ runtime.currentOrganization = { organizationId: 'org-1', pluginPrefix: 'acme' };
+ const h = harness([item]);
+ runtime.install.mockResolvedValue({ manifest: manifest('helper'), dir: '/userData/cindy-brain/helper', enabled: true });
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT))
+ .rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost('helper')).toBeNull();
+ },
+ );
+
+ it('compares old-server download identity to the original response, not the login namespace', async () => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1' });
+ const h = harness([item]);
+ h.api.download.mockResolvedValue({
+ pluginId: item.id, releaseId: item.currentRelease.id, ghostId: item.ghostId, namespace: 'acme',
+ url: 'https://downloads.test.invalid/plugin.cindy', expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: item.currentRelease.sha256, sizeBytes: item.currentRelease.sizeBytes,
+ });
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT))
+ .rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['organization', 'download'], ['namespace', 'download'], ['owner-generation', 'download'],
+ ['organization', 'commit'], ['namespace', 'commit'], ['owner-generation', 'commit'],
+ ])('rechecks trusted old-server install identity (%s, %s)', async (change, stage) => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1' });
+ const h = harness([item]);
+ const download = await h.api.download();
+ const changeIdentity = (): void => {
+ if (change === 'organization') runtime.authIdentity!.orgId = 'other-org';
+ else if (change === 'namespace') runtime.authIdentity!.orgSlug = 'other';
+ else runtime.authStateOverrides.ownerGeneration = 2;
+ };
+ runtime.install.mockImplementation(async (_file, options) => {
+ if (stage === 'commit') {
+ changeIdentity();
+ options.beforeCommitInLock?.();
+ }
+ return { manifest: manifest('helper'), dir: '/userData/cindy-brain/helper', enabled: true };
+ });
+ h.api.download.mockImplementationOnce(async () => {
+ if (stage === 'download') changeIdentity();
+ return download;
+ });
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT))
+ .rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).toHaveBeenCalledTimes(stage === 'download' ? 0 : 1);
+ expect(h.ledger.installationForGhost('helper')).toBeNull();
+ });
+
+ it.each([
+ ['PLUGIN_NAMESPACE_UNAVAILABLE', 503],
+ ['PLUGIN_NAMESPACE_CONFLICT', 409],
+ ])('keeps installed plugins when the market returns %s', async (code, status) => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1', namespace: 'acme' });
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, { namespace: 'acme', installed: true }));
+ const before = h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' });
+ h.api.listAll.mockRejectedValueOnce(Object.assign(new Error('请求失败 (' + status + ')'), { code, status }));
+ h.api.detail.mockRejectedValueOnce(Object.assign(new Error('请求失败 (' + status + ')'), { code, status }));
+ h.api.download.mockRejectedValueOnce(Object.assign(new Error('请求失败 (' + status + ')'), { code, status }));
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ unavailableReason: '请求失败 (' + status + ')',
+ });
+ await expect(h.service.detail(item.id)).rejects.toThrow('请求失败');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT)).rejects.toThrow();
+ expect(runtime.uninstall).not.toHaveBeenCalled();
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })).toEqual(before);
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: null })).toBeNull();
+ });
+
+ it('resumes eligible pending residents only when market discovery is unavailable', async () => {
+ const h = harness([]);
+ h.api.listAll.mockRejectedValueOnce(new Error('market offline'));
+ await h.service.snapshot();
+ expect(runtime.resumeOfflineResidents).toHaveBeenCalledOnce();
+ await h.service.snapshot();
+ expect(runtime.resumeOfflineResidents).toHaveBeenCalledOnce();
+ runtime.pluginApiBaseUrl = null;
+ await h.service.snapshot({ discoveryOnly: true });
+ expect(runtime.resumeOfflineResidents).toHaveBeenCalledOnce();
+ await h.service.snapshot();
+ expect(runtime.resumeOfflineResidents).toHaveBeenCalledTimes(2);
+ });
it('backfills the exact raw identity for an unchanged v0.1.61 v2 card record', async () => {
const rawManifest = {
schemaVersion: 2 as const,
@@ -956,6 +1275,44 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.api.listAll).not.toHaveBeenCalled();
});
+ it.each(['xd-probe', 'filo-probe'])('does not adopt a new Forge %s through legacy prefix recognition', async (id) => {
+ const installed = { manifest: manifest(id, '0.9.0'), namespace: 'acme',
+ dir: '/userData/cindy-brain/' + id, enabled: true };
+ runtime.ghosts = [installed];
+ runtime.installOrigins.set(id, 'agent-forge');
+ runtime.approvedInstallEvidence.mockReturnValue({ packageSha256: 'b'.repeat(64),
+ approvedManifest: installed.manifest, legacyMigrated: false });
+ const fixture = harness([summary({ ghostId: id, namespace: 'acme', scope: 'organization',
+ organizationId: 'org-1', defaultInstall: false })]);
+ await fixture.service.snapshot();
+ expect(fixture.ledger.installationForPlugin({ ghostId: id, namespace: 'acme' })).toBeNull();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it.each(['missing-evidence', 'new-manual', 'reused-name', 'legacy-forge', 'namespace-mismatch', 'manifest-mismatch'])(
+ 'does not adopt an installation without matching historical evidence (%s)', async (scenario) => {
+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-legacy-adoption-'));
+ roots.push(parent);
+ const dir = path.join(parent, 'xd-probe');
+ fs.mkdirSync(dir);
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(manifest('xd-probe', '0.9.0')));
+ const installed = { manifest: manifest('xd-probe', '0.9.0'), namespace: 'acme',
+ dir, enabled: true };
+ runtime.ghosts = [installed];
+ runtime.approvedInstallEvidence.mockReturnValue(scenario === 'missing-evidence' ? null : {
+ packageSha256: scenario === 'new-manual' || scenario === 'reused-name' ? 'b'.repeat(64) : null,
+ approvedManifest: normalizedManifest(manifest('xd-probe', scenario === 'manifest-mismatch' ? '0.8.0' : '0.9.0')),
+ legacyMigrated: scenario !== 'new-manual',
+ });
+ if (scenario === 'legacy-forge') runtime.installOrigins.set('xd-probe', 'agent-forge');
+ const fixture = harness([summary({ ghostId: 'xd-probe', namespace: scenario === 'namespace-mismatch' ? 'other' : 'acme',
+ scope: 'organization', organizationId: 'org-1', defaultInstall: false })]);
+ await fixture.service.snapshot();
+ expect(Object.values(fixture.ledger.read().installations)).toHaveLength(0);
+ expect(runtime.install).not.toHaveBeenCalled();
+ },
+ );
+
it('adopts and verifies one exact official legacy install without changing enable state', async () => {
runtime.ghosts = [
{
@@ -964,6 +1321,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
},
];
+ runtime.approvedInstallEvidence.mockReturnValue({ packageSha256: null,
+ approvedManifest: normalizedManifest(manifest()), legacyMigrated: true });
const h = harness([summary()]);
runtime.install.mockImplementation(async () => {
const ghost = {
@@ -998,6 +1357,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: false,
},
];
+ runtime.approvedInstallEvidence.mockReturnValue({ packageSha256: null,
+ approvedManifest: normalizedManifest(manifest('cindy-test', '0.9.0')), legacyMigrated: true });
const h = harness([summary()]);
runtime.install.mockImplementation(async () => {
const ghost = {
@@ -1064,7 +1425,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
updatedAt: '2026-08-01T00:00:00.000Z',
manifestDigest: ghostManifestDigest(canonicalManifest),
});
- h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');
const snapshot = await h.service.snapshot();
@@ -1121,7 +1482,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
updatedAt: '2026-08-01T00:00:00.000Z',
manifestDigest: ghostManifestDigest(canonicalManifest),
});
- h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');
const snapshot = await h.service.snapshot();
@@ -1135,6 +1496,38 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install).not.toHaveBeenCalled();
});
+ it('recovers a disconnected namespaced install beside a same-id public catalog entry', async () => {
+ const publicItem = summary({ ghostId: 'helper', namespace: null });
+ const orgItem = summary({
+ id: `c${'d'.repeat(24)}`,
+ ghostId: 'helper', namespace: 'acme', scope: 'organization', organizationId: 'org-1',
+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID },
+ });
+ const h = namespaceRecoveryHarness([publicItem, orgItem], orgItem);
+
+ const snapshot = await h.service.snapshot();
+
+ expect(h.ledger.installationForPlugin({ namespace: 'acme', ghostId: 'helper' }))
+ .toMatchObject({ installed: true, pluginId: orgItem.id });
+ expect(snapshot.items.find((item) => item.pluginId === orgItem.id)?.installState).toBe('installed');
+ expect(h.api.download).not.toHaveBeenCalled();
+ });
+
+ it('does not reconnect a namespaced install to a same-id catalog entry from another namespace', async () => {
+ const catalogItem = summary({
+ ghostId: 'helper', namespace: 'other', scope: 'organization', organizationId: 'org-1',
+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID },
+ });
+ const h = namespaceRecoveryHarness([
+ catalogItem, summary({ id: `c${'d'.repeat(24)}`, ghostId: 'helper', namespace: null }),
+ ], catalogItem);
+
+ await h.service.snapshot();
+
+ expect(h.ledger.installationForPlugin({ namespace: 'acme', ghostId: 'helper' }))
+ .toMatchObject({ installed: false });
+ });
+
it('keeps a disconnected route detached when a modern receipt names another manifest', async () => {
const canonicalManifest = normalizedManifest(manifest());
const item = summary({
@@ -1154,7 +1547,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
releaseId: RELEASE_ID,
manifestDigest: ghostManifestDigest(canonicalManifest),
}));
- h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');
const snapshot = await h.service.snapshot();
@@ -1182,7 +1575,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
manifestDigest: ghostManifestDigest(canonicalManifest),
rawManifestSha256: 'f'.repeat(64),
}));
- h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');
const snapshot = await h.service.snapshot();
@@ -1418,6 +1811,25 @@ describe('PluginMarketService migration and defaultInstall', () => {
manifestDigest: ghostManifestDigest(manifest()),
});
});
+ it('installs a namespaced default even when a public catalog entry shares the ghostId', async () => {
+ const publicItem = summary({ ghostId: 'helper', namespace: null });
+ const orgItem = summary({
+ id: 'c'.repeat(25), ghostId: 'helper', namespace: 'acme', scope: 'organization',
+ organizationId: 'org-1', defaultInstall: true,
+ });
+ const h = harness([publicItem, orgItem]);
+ runtime.install.mockImplementationOnce(async () => {
+ const ghost = { manifest: manifest('helper'), namespace: 'acme',
+ dir: '/userData/cindy-brain/_ns/acme/helper', enabled: true };
+ runtime.ghosts = [ghost];
+ return ghost;
+ });
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledWith(expect.any(String),
+ expect.objectContaining({ ghostId: 'helper', namespace: 'acme' }));
+ expect(h.ledger.installationForPlugin({ namespace: 'acme', ghostId: 'helper' }))
+ .toMatchObject({ installed: true, pluginId: orgItem.id });
+ });
it('installs a default package whose detail manifest contains normalized setup requirements', async () => {
const item = summary({ defaultInstall: true });
@@ -1443,6 +1855,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
items: [{ installState: 'installed', enabled: true }],
});
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('sourceChanged');
});
it('returns a Renderer snapshot before a default install download finishes', async () => {
@@ -1569,6 +1982,11 @@ describe('PluginMarketService migration and defaultInstall', () => {
version: '1.0.0',
consent: { mode: 'confirmed', key: expect.any(String) },
afterCommitInLock: expect.any(Function),
+ pluginId: item.id,
+ pendingMarketRecord: {
+ scope: 'public', organizationId: null, source: 'market', installed: true,
+ sha256: item.currentRelease.sha256,
+ },
});
});
@@ -1696,79 +2114,43 @@ describe('PluginMarketService migration and defaultInstall', () => {
version: '1.0.0',
consent: { mode: 'confirmed', key: expect.any(String) },
afterCommitInLock: expect.any(Function),
+ pluginId: item.id,
+ pendingMarketRecord: {
+ scope: 'public', organizationId: null, source: 'market', installed: true,
+ sha256: item.currentRelease.sha256,
+ },
});
// 安装入口用目录 summary 做 detail 身份绑定(防止把 A 的确认导向 B 的内容),
// 因此手动安装也会先取一次目录,但不做任何 listAll 之外的多余请求。
expect(h.api.listAll).toHaveBeenCalledTimes(1);
// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。
expect(ghost?.enabled).toBe(true);
- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
});
- it('passes a Host-built pendingMarketRecord only for organization server-market packages', async () => {
- const orgItem = summary({
- ghostId: 'acme-tool',
- scope: 'organization',
- organizationId: 'org-1',
- source: 'local-market',
- installed: false,
- } as Partial<VisiblePluginSummary> & { source: string; installed: boolean });
+ it.each([
+ { scope: 'organization', organizationId: 'org-1', ghostId: 'acme-tool', source: 'local-market', installed: false },
+ { scope: 'public', organizationId: null },
+ { scope: 'personal', organizationId: null },
+ ] as const)('passes a Host-built pendingMarketRecord for $scope server-market installs', async (overrides) => {
+ const item = summary(overrides);
runtime.install.mockResolvedValue({
- manifest: manifest('acme-tool'),
- dir: '/userData/cindy-brain/acme-tool',
+ manifest: manifest(item.ghostId),
+ dir: '/userData/cindy-brain/' + item.ghostId,
enabled: true,
});
- const orgHarness = harness([orgItem]);
- await orgHarness.service.install(orgItem.id, {
- ...reviewedInstallOptions(orgItem),
- expectedManifest: manifest('acme-tool'),
- }, TEST_INSTALL_CONTEXT);
+ const target = harness([item]);
+ await target.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
expect(runtime.install).toHaveBeenCalledWith(
expect.stringMatching(/\.cindy$/),
expect.objectContaining({
pendingMarketRecord: {
- scope: 'organization',
- organizationId: 'org-1',
- source: 'market',
- installed: true,
- sha256: orgItem.currentRelease.sha256,
+ scope: item.scope, organizationId: item.organizationId,
+ source: 'market', installed: true, sha256: item.currentRelease.sha256,
},
}),
);
- const pending = runtime.install.mock.calls[0]?.[1]?.pendingMarketRecord as {
- source: string;
- installed: boolean;
- sha256: string;
- };
- expect(pending.source).toBe('market');
- expect(pending.installed).toBe(true);
- // The pending ticket carries only the server Release hash. The approved
- // side is Host-bound later to inspect(package bytes), so the service cannot
- // mint a self-reported match.
- expect(pending.sha256).toBe(orgItem.currentRelease.sha256);
- expect(pending).not.toHaveProperty('approvedPackageSha256');
-
- runtime.install.mockReset();
- const publicItem = summary({ scope: 'public', organizationId: null });
- runtime.install.mockResolvedValue({
- manifest: manifest(),
- dir: '/userData/cindy-brain/cindy-test',
- enabled: true,
- });
- const publicHarness = harness([publicItem]);
- await publicHarness.service.install(publicItem.id, reviewedInstallOptions(publicItem), TEST_INSTALL_CONTEXT);
- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
-
- runtime.install.mockReset();
- const personalItem = summary({ scope: 'personal', organizationId: null });
- runtime.install.mockResolvedValue({
- manifest: manifest(),
- dir: '/userData/cindy-brain/cindy-test',
- enabled: true,
- });
- const personalHarness = harness([personalItem]);
- await personalHarness.service.install(personalItem.id, reviewedInstallOptions(personalItem), TEST_INSTALL_CONTEXT);
- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
+ expect(runtime.install.mock.calls[0]?.[1]?.pendingMarketRecord)
+ .not.toHaveProperty('approvedPackageSha256');
});
it('manual market install accepts the normalized setup manifest returned by detail', async () => {
@@ -1843,9 +2225,34 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install.mock.calls[0]?.[1]).toEqual({
ghostId: 'cindy-test',
version: '1.0.0',
+ pluginId: ordinary.id,
consent: { mode: 'confirmed', key: expect.any(String) },
afterCommitInLock: expect.any(Function),
+ pendingMarketRecord: {
+ scope: 'public', organizationId: null, source: 'market', installed: true,
+ sha256: ordinary.currentRelease.sha256,
+ },
+ });
+ });
+
+ it.each([
+ { scope: 'organization', organizationId: 'org-1', namespace: 'acme',
+ dir: '/userData/cindy-brain/_ns/acme/cindy-github' },
+ { scope: 'public', organizationId: null, namespace: null,
+ dir: '/userData/cindy-brain/cindy-github' },
+ ] as const)('limits cindy-github official trust to the root public install ($scope)', async ({ dir, ...identity }) => {
+ const github = summary({ ghostId: 'cindy-github', ...identity });
+ runtime.install.mockResolvedValue({
+ manifest: manifest('cindy-github'), namespace: identity.namespace, dir, enabled: true,
});
+ const h = harness([github]);
+ await h.service.install(github.id, reviewedInstallOptions(github), TEST_INSTALL_CONTEXT);
+ const options = runtime.install.mock.calls[0]?.[1];
+ if (identity.namespace === null) {
+ expect(options).toMatchObject({ officialCindyGithub: true });
+ } else {
+ expect(options).not.toHaveProperty('officialCindyGithub');
+ }
});
it('writes the v0.1.61 digest for a newly installed v2 card package', async () => {
@@ -1935,6 +2342,17 @@ describe('PluginMarketService migration and defaultInstall', () => {
updatedAt: '2026-08-07T00:00:00.000Z',
manifestDigest: digest,
});
+ h.ledger.upsertInstallation({
+ ...recordForTest(item), pluginId: 'c'.repeat(25), namespace: 'acme',
+ scope: 'organization', organizationId: 'org-1',
+ });
+ runtime.ghosts.unshift({
+ manifest: rawManifest,
+ namespace: 'acme',
+ dir: '/userData/cindy-brain/_ns/acme/cindy-github',
+ enabled: true,
+ trust: { level: 'unverified', publisherSigned: false, publisherVerified: false, reviewed: false },
+ });
runtime.install.mockResolvedValue({
manifest: rawManifest,
@@ -2222,7 +2640,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const snapshot = h.service.snapshot();
await vi.waitFor(() => expect(h.api.download).toHaveBeenCalledTimes(1));
runtime.ghosts = [];
- h.ledger.markRemoved('cindy-github', 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost('cindy-github')!, 'user-1');
releaseDownload.resolve();
await snapshot;
@@ -2919,6 +3337,152 @@ describe('PluginMarketService migration and defaultInstall', () => {
},
);
+ it('uses the namespaced storage part as the busy key', async () => {
+ const item = summary({
+ ghostId: 'helper',
+ namespace: 'acme',
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ installOrganizationHelper(oldManifest);
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item, { namespace: 'acme', scope: 'organization', organizationId: 'org-1' }),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ runtime.pendingCalls = true;
+ runtime.install.mockImplementation(async () => {
+ throw new Error('should not install while namespaced instance is busy');
+ });
+
+ await h.service.snapshot();
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(runtime.busyQueryIds).toContain('_ns__acme__helper');
+ expect(runtime.busyQueryIds).not.toContain('helper');
+ });
+
+ it('recognizes an in-place organization install when an older server omits namespace', async () => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1' });
+ const installedManifest = manifest('helper');
+ installOrganizationHelper(installedManifest, 'legacy');
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, {
+ namespace: 'acme',
+ manifestDigest: ghostManifestDigest(installedManifest),
+ }));
+
+ expect((await h.service.snapshot()).items[0]?.installState).toBe('installed');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { mode: 'manual', coexistingRoot: false },
+ { mode: 'manual', coexistingRoot: true },
+ { mode: 'automatic', coexistingRoot: false },
+ { mode: 'automatic', coexistingRoot: true },
+ ] as const)('updates the in-place organization instance for an older server ($mode, root=$coexistingRoot)', async ({ mode, coexistingRoot }) => {
+ const item = summary({
+ ghostId: 'helper', scope: 'organization', organizationId: 'org-1',
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest('helper');
+ const installDir = installOrganizationHelper(oldManifest, 'legacy');
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, {
+ namespace: 'acme', releaseId: 'release-1', version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ }));
+ const rootDir = path.join(path.dirname(installDir), '_ns', '_root', 'helper');
+ const rootGhost = { manifest: oldManifest, dir: rootDir, namespace: null, enabled: true };
+ const rootRecord = recordForTest(summary({ id: `c${'d'.repeat(24)}`, ghostId: 'helper' }), {
+ namespace: null, manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ if (coexistingRoot) {
+ fs.mkdirSync(rootDir, { recursive: true });
+ fs.writeFileSync(path.join(rootDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts.push(rootGhost);
+ h.ledger.upsertInstallation(rootRecord);
+ }
+ const updatedManifest = manifest('helper', '2.0.0');
+ runtime.install.mockImplementation(async (_filePath, options) => {
+ expect(options.namespace).toBe('acme');
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(updatedManifest));
+ const updated = { manifest: updatedManifest, dir: installDir, namespace: 'acme', enabled: true };
+ runtime.ghosts = runtime.ghosts.map((ghost) => ghost.dir === installDir ? updated : ghost);
+ return updated;
+ });
+
+ if (mode === 'manual') {
+ runtime.pendingCalls = true;
+ expect((await h.service.snapshot()).items[0]).toMatchObject({
+ namespace: 'acme', installState: 'update-available',
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+ runtime.pendingCalls = false;
+ await h.service.install(item.id, {
+ ...reviewedInstallOptions(item), expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }, TEST_INSTALL_CONTEXT);
+ } else {
+ expect((await h.service.snapshot()).items[0]).toMatchObject({
+ namespace: 'acme', installState: 'installed',
+ });
+ }
+ expect(runtime.install).toHaveBeenCalledOnce();
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })).toMatchObject({
+ releaseId: 'release-2', installed: true,
+ });
+ const installedRoot = h.ledger.installationForPlugin({ ghostId: 'helper', namespace: null });
+ if (coexistingRoot) {
+ expect(runtime.ghosts.find((ghost) => ghost.dir === rootDir)).toEqual(rootGhost);
+ expect(fs.readFileSync(path.join(rootDir, 'ghost.json'), 'utf8')).toBe(JSON.stringify(oldManifest));
+ expect(installedRoot).toMatchObject(rootRecord);
+ } else {
+ expect(installedRoot).toBeNull();
+ }
+ });
+
+ it.each([null, undefined] as const)('does not bind an ambiguous old organization response to either same-name instance (root namespace=%s)', async (rootNamespace) => {
+ runtime.authIdentity!.orgSlug = null;
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1' });
+ const root = manifest('helper');
+ const installRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-legacy-ambiguous-'));
+ roots.push(installRoot);
+ const rootDir = path.join(installRoot, 'helper');
+ const orgDir = path.join(installRoot, '_ns', 'acme', 'helper');
+ fs.mkdirSync(rootDir);
+ fs.mkdirSync(orgDir, { recursive: true });
+ fs.writeFileSync(path.join(rootDir, 'ghost.json'), JSON.stringify(root));
+ fs.writeFileSync(path.join(orgDir, 'ghost.json'), JSON.stringify(root));
+ runtime.ghosts = [
+ { manifest: root, dir: rootDir, ...(rootNamespace === undefined ? {} : { namespace: rootNamespace }), enabled: true },
+ { manifest: root, dir: orgDir, namespace: 'acme', enabled: true },
+ ];
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, { namespace: 'acme', manifestDigest: ghostManifestDigest(root) }));
+ expect((await h.service.snapshot()).items[0]?.installState).toBe('conflict');
+ expect(runtime.install).not.toHaveBeenCalled();
+ await expect(h.service.install(item.id, {
+ ...reviewedInstallOptions(item, true), expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }, TEST_INSTALL_CONTEXT)).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('does not claim a namespace from an unverified legacy market record', async () => {
+ const item = summary({ ghostId: 'helper', scope: 'organization', organizationId: 'org-1' });
+ const installedManifest = manifest('helper');
+ installOrganizationHelper(installedManifest, 'legacy');
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, { namespace: 'acme' }));
+
+ expect((await h.service.snapshot()).items[0]?.installState).toBe('conflict');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
it('does not re-check the server-selected organization upgrade against the client version', async () => {
const item = summary({
scope: 'organization',
@@ -3258,10 +3822,47 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
});
+ it.each([false, true])('does not track an unowned root uninstall through an org sibling (root tombstone: %s)', async (tombstone) => {
+ const item = summary({ ghostId: 'helper', namespace: 'acme', scope: 'organization', organizationId: 'org-1' });
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, { namespace: 'acme' }));
+ if (tombstone) {
+ h.ledger.upsertInstallation(recordForTest(summary({ ghostId: 'helper' }), { namespace: null, installed: false }));
+ }
+ installRuntimeGhost({ ...manifest('helper'), namespace: undefined });
+ runtime.ghosts[0]!.namespace = null;
+ expect(h.service.prepareLocalUninstallTracking('helper')).toBeNull();
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })?.installed).toBe(true);
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ });
+
+ it('does not track a local replacement with a stale provenance digest', () => {
+ const item = summary();
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item, { manifestDigest: 'f'.repeat(64) }));
+ installRuntimeGhost(manifest(item.ghostId));
+ expect(h.service.prepareLocalUninstallTracking(item.ghostId)).toBeNull();
+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(true);
+ });
+
+ it('does not retire a replacement route after local uninstall tracking was prepared', async () => {
+ const item = summary();
+ const h = harness([item]);
+ installRuntimeGhost(manifest(item.ghostId));
+ h.ledger.upsertInstallation(recordForTest(item, { manifestDigest: ghostManifestDigest(manifest(item.ghostId)) }));
+ const complete = h.service.prepareLocalUninstallTracking(item.ghostId);
+ expect(complete).not.toBeNull();
+ h.ledger.upsertInstallation(recordForTest(item, { pluginId: 'replacement-resource', source: 'local-market', sourceKey: 'replacement' }));
+ await complete?.();
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ pluginId: 'replacement-resource', installed: true });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', 'replacement-resource')).toBe(false);
+ });
+
it('records an opt-out only after a tracked local uninstall succeeds', async () => {
const item = summary({ defaultInstall: true });
const h = harness([item]);
h.ledger.upsertInstallation(recordForTest(item));
+ installRuntimeGhost(manifest(item.ghostId));
const complete = h.service.prepareLocalUninstallTracking(item.ghostId);
@@ -3295,7 +3896,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const item = summary({ defaultInstall: true });
const h = harness([item]);
h.ledger.upsertInstallation(recordForTest(item));
- runtime.ghosts = [ghostEntry(item.ghostId)];
+ installRuntimeGhost(manifest(item.ghostId));
const completeLocalUninstall = h.service.prepareLocalUninstallTracking(item.ghostId);
expect(completeLocalUninstall).not.toBeNull();
@@ -3333,6 +3934,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const item = summary({ defaultInstall: true });
const h = harness([item]);
h.ledger.upsertInstallation(recordForTest(item));
+ installRuntimeGhost(manifest(item.ghostId));
const complete = h.service.prepareLocalUninstallTracking(item.ghostId);
@@ -3346,6 +3948,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const item = summary({ defaultInstall: true });
const h = harness([item]);
h.ledger.upsertInstallation(recordForTest(item));
+ installRuntimeGhost(manifest(item.ghostId));
const complete = h.service.prepareLocalUninstallTracking(item.ghostId);
runtime.session = {
@@ -3396,6 +3999,71 @@ describe('PluginMarketService migration and defaultInstall', () => {
},
);
+ it('purges only the matching namespaced organization installation from a legacy notice', async () => {
+ const notice = removal({ ghostId: 'helper' });
+ const h = harness([], [notice]);
+ const orgDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-org-'));
+ const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-root-'));
+ roots.push(orgDir, rootDir);
+ fs.writeFileSync(path.join(orgDir, 'ghost.json'), JSON.stringify(manifest('helper')));
+ fs.writeFileSync(path.join(rootDir, 'ghost.json'), JSON.stringify(manifest('helper')));
+ runtime.ghosts = [
+ { ...ghostEntry('helper'), dir: rootDir, namespace: null },
+ { ...ghostEntry('helper'), dir: orgDir, namespace: 'acme' },
+ ];
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: 'acme', manifestDigest: ghostManifestDigest(manifest('helper')) }));
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: null, pluginId: 'other-plugin', scope: 'public', organizationId: null }));
+ await h.service.snapshot();
+ expect(runtime.uninstall).toHaveBeenCalledWith('_ns/acme/helper', { skipMarketLedger: true });
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })?.installed).toBe(false);
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: null })?.installed).toBe(true);
+ });
+
+ it('purges only the namespaced instance named by the notice', async () => {
+ const notice = removal({ ghostId: 'helper', namespace: 'acme' });
+ const h = harness([], [notice]);
+ const orgDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-org-'));
+ const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-root-'));
+ roots.push(orgDir, rootDir);
+ fs.writeFileSync(path.join(orgDir, 'ghost.json'), JSON.stringify(manifest('helper')));
+ fs.writeFileSync(path.join(rootDir, 'ghost.json'), JSON.stringify(manifest('helper')));
+ runtime.ghosts = [
+ { ...ghostEntry('helper'), dir: rootDir, namespace: null },
+ { ...ghostEntry('helper'), dir: orgDir, namespace: 'acme' },
+ ];
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: 'acme', manifestDigest: ghostManifestDigest(manifest('helper')) }));
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: null, pluginId: 'c' + 'd'.repeat(24), scope: 'public', organizationId: null }));
+ await h.service.snapshot();
+ expect(runtime.uninstall).toHaveBeenCalledWith('_ns/acme/helper', { skipMarketLedger: true });
+ expect(runtime.uninstall).not.toHaveBeenCalledWith('helper', expect.anything());
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })?.installed).toBe(false);
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: null })?.installed).toBe(true);
+ });
+
+ it('does not purge a namespaced organization for another organization', async () => {
+ const notice = removal({ ghostId: 'helper' });
+ const h = harness([], [notice]);
+ runtime.ghosts = [{ ...ghostEntry('helper'), namespace: 'acme' }];
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: 'acme', organizationId: 'other-org' }));
+ await h.service.snapshot();
+ expect(runtime.uninstall).not.toHaveBeenCalled();
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })?.installed).toBe(true);
+ });
+
+ it('does not guess a namespace for an ambiguous old notice or override an explicit namespace', async () => {
+ const notice = removal({ ghostId: 'helper' });
+ const h = harness([], [notice]);
+ runtime.ghosts = [{ ...ghostEntry('helper'), namespace: 'acme' }];
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: 'acme' }));
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: 'other' }));
+ h.ledger.upsertInstallation(removalRecord({ ghostId: 'helper', namespace: null }));
+ await h.service.snapshot();
+ expect(runtime.uninstall).not.toHaveBeenCalled();
+ h.api.listAll.mockResolvedValueOnce({ plugins: [], removals: [{ ...notice, namespace: 'unknown' }], currentOrganization: null });
+ await h.service.snapshot();
+ expect(runtime.uninstall).not.toHaveBeenCalled();
+ });
+
it('purges when the ledger provenance digest matches the installed package', async () => {
const notice = removal();
const h = harness([], [notice]);
@@ -3479,7 +4147,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const notice = removal();
const h = harness([], [notice]);
h.ledger.upsertInstallation(removalRecord());
- h.ledger.markRemoved(notice.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(notice.ghostId)!, 'user-1');
await h.service.snapshot();
@@ -3496,7 +4164,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
runtime.ghosts = [ghostEntry(notice.ghostId)];
mockUninstallDropsGhost();
h.ledger.upsertInstallation(removalRecord());
- h.ledger.markRemoved(notice.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(notice.ghostId)!, 'user-1');
h.ledger.upsertInstallation(removalRecord());
await h.service.snapshot();
@@ -3634,7 +4302,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.ledger.installationForGhost('third-party')).toBeNull();
});
- it('allows explicit replacement when a removed market record has an existing directory', async () => {
+ it.each([false, true])('archives an explicit local-to-server replacement with a removed ledger row=%s', async (removedRecord) => {
const item = summary();
const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-local-installed-'));
roots.push(installedDir);
@@ -3652,10 +4320,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
});
const h = harness([item]);
- h.ledger.upsertInstallation({
- ...recordForTest(item),
- installed: false,
- });
+ if (removedRecord) {
+ h.ledger.upsertInstallation({ ...recordForTest(item), installed: false });
+ }
await expect(
h.service.install(item.id, {
@@ -3666,6 +4333,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
ghost: { manifest: { id: item.ghostId } },
});
expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('manifestCap');
+ expect(runtime.install.mock.calls[0]?.[1]).toHaveProperty('sourceChanged', true);
expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
pluginId: item.id,
source: 'market',
@@ -3979,6 +4647,39 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);
expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);
});
+
+ it('does not uninstall a public sibling when the org instance is already gone', async () => {
+ const publicItem = summary({ ghostId: 'helper' });
+ const orgItem = summary({
+ id: `c${'d'.repeat(24)}`,
+ ghostId: 'helper',
+ namespace: 'acme',
+ scope: 'organization',
+ organizationId: 'org-1',
+ });
+ const h = harness([publicItem, orgItem]);
+ h.ledger.upsertInstallation(recordForTest(publicItem, { namespace: null }));
+ h.ledger.upsertInstallation(
+ recordForTest(orgItem, {
+ namespace: 'acme',
+ scope: 'organization',
+ organizationId: 'org-1',
+ }),
+ );
+ runtime.ghosts = [ghostEntry('helper')];
+
+ await expect(h.service.uninstall(orgItem.id)).resolves.toEqual({ ok: true });
+
+ expect(runtime.uninstall).not.toHaveBeenCalled();
+ expect(runtime.ghosts).toHaveLength(1);
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })?.installed).toBe(
+ false,
+ );
+ expect(h.ledger.installationForPlugin({ ghostId: 'helper', namespace: null })?.installed).toBe(
+ true,
+ );
+ });
+
});
function recordForTest(
@@ -4040,6 +4741,82 @@ function installRuntimeGhost(
}
describe('organization default Plugin takeover', () => {
+ it.each([
+ ['S1 verified namespace without token slug', 'acme', 'acme', undefined, 'old-prefix', 'helper', true],
+ ['S2-off pending legacy prefix', undefined, undefined, undefined, 'acme', 'acme-tool', true],
+ ['pending legacy cannot guess a natural name', undefined, undefined, 'acme', 'acme', 'helper', false],
+ ['pending legacy cannot guess a namespace', undefined, 'acme', 'acme', 'acme', 'acme-tool', false],
+ ['known organization cannot select root', 'acme', null, 'acme', 'acme', 'acme-tool', false],
+ ['known organization cannot select pending legacy', 'acme', undefined, 'acme', 'acme', 'acme-tool', false],
+ ['known namespace rejects conflicting verified slug', 'acme', 'acme', 'other', 'acme', 'acme-tool', false],
+ ['organization default cannot have root identity', null, null, 'acme', 'acme', 'acme-tool', false],
+ ] as const)('uses verified identity instead of guessing: %s', (_name, namespace, installedNamespace, orgSlug, pluginPrefix, ghostId, eligible) => {
+ const item = organizationDefaultSummary({ ghostId, ...(namespace !== undefined ? { namespace } : {}) });
+ const installed = {
+ manifest: manifest(ghostId), dir: '/unused', enabled: true,
+ ...(installedNamespace !== undefined ? { namespace: installedNamespace } : {}),
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ trust: { level: 'unverified', publisherSigned: false, publisherVerified: false, reviewed: false },
+ } satisfies InstalledGhost;
+ expect(organizationDefaultTakeoverEligibility({
+ summary: item, currentOrganization: { organizationId: 'org-1', pluginPrefix, ...(orgSlug ? { orgSlug } : {}) },
+ uniqueGhostId: true, installed, record: null, installOrigin: 'manual',
+ runtimeAvailable: true, optedOut: false, builtinRemoved: false, busy: false,
+ }).eligible).toBe(eligible);
+ });
+
+ it.each([null, 'old-prefix'])('allows verified natural namespace default takeover with prefix %s', (pluginPrefix) => {
+ const item = organizationDefaultSummary({ namespace: 'acme', ghostId: 'helper' });
+ const installed = {
+ manifest: manifest(item.ghostId), namespace: 'acme', dir: '/unused', enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ trust: { level: 'unverified', publisherSigned: false, publisherVerified: false, reviewed: false },
+ } satisfies InstalledGhost;
+ expect(organizationDefaultTakeoverEligibility({
+ summary: item, currentOrganization: { organizationId: 'org-1', orgSlug: 'acme', pluginPrefix },
+ uniqueGhostId: false, installed, record: null, installOrigin: 'manual',
+ runtimeAvailable: true, optedOut: false, builtinRemoved: true, busy: false,
+ })).toEqual({ eligible: true });
+ });
+
+ it('installs a namespaced organization default despite a root tombstone and public same-id listing', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary({ namespace: 'acme' });
+ const publicItem = summary({ id: 'c' + 'f'.repeat(24), ghostId: item.ghostId });
+ runtime.builtinRemoved.add(item.ghostId);
+ runtime.install.mockResolvedValue({
+ manifest: manifest(item.ghostId), namespace: 'acme',
+ dir: '/userData/cindy-brain/_ns/acme/acme-tool', enabled: true,
+ });
+ const h = harness([item, publicItem]);
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.any(String), expect.objectContaining({ namespace: 'acme', ghostId: item.ghostId }),
+ );
+ });
+
+ it('keeps an explicit root default uninstall suppressed by the root tombstone', async () => {
+ const item = summary({ ghostId: 'cindy-art', namespace: null, defaultInstall: true });
+ runtime.builtinRemoved.add(item.ghostId);
+ const h = harness([item]);
+ await h.service.snapshot();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('allows a namespaced approved manual takeover even if a public entry shares the id', () => {
+ const item = organizationDefaultSummary({ namespace: 'acme' });
+ const installed = {
+ manifest: manifest(item.ghostId), namespace: 'acme', dir: '/unused', enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ trust: { level: 'unverified', publisherSigned: false, publisherVerified: false, reviewed: false },
+ } satisfies InstalledGhost;
+ expect(organizationDefaultTakeoverEligibility({
+ summary: item, currentOrganization: { organizationId: 'org-1', pluginPrefix: 'acme' },
+ uniqueGhostId: false, installed, record: null, installOrigin: 'manual',
+ runtimeAvailable: true, optedOut: false, builtinRemoved: true, busy: false,
+ })).toEqual({ eligible: true });
+ });
+
it('re-downloads and replaces a same-release bad target record without writing opt-out', async () => {
setCurrentOrganization();
const item = organizationDefaultSummary();
@@ -4052,6 +4829,7 @@ describe('organization default Plugin takeover', () => {
manifestDigest: ghostManifestDigest(manifest(item.ghostId)),
});
runtime.install.mockImplementationOnce(async (_file, options) => {
+ expect(options.sourceChanged).toBe(true);
options.beforeCommitInLock?.();
expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: true });
expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
@@ -4298,8 +5076,9 @@ describe('organization default Plugin takeover', () => {
});
const h = harness([item]);
h.ledger.upsertInstallation(recordForTest(item));
- h.ledger.markRemoved(item.ghostId, null);
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, null);
runtime.install.mockImplementationOnce(async (_file, options) => {
+ expect(options.sourceChanged).toBe(true);
options.beforeCommitInLock?.();
const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
@@ -4328,7 +5107,7 @@ describe('organization default Plugin takeover', () => {
);
const h = harness([item]);
h.ledger.upsertInstallation(recordForTest(item));
- h.ledger.markRemoved(item.ghostId, null);
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, null);
await h.service.snapshot();
@@ -4371,7 +5150,7 @@ describe('organization default Plugin takeover', () => {
const item = organizationDefaultSummary();
const h = harness([item]);
h.ledger.upsertInstallation(recordForTest(item));
- h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');
installRuntimeGhost({ ...manifest(item.ghostId), description: 'Later local install' });
await h.service.snapshot();
@@ -4523,6 +5302,43 @@ describe('organization default Plugin takeover', () => {
).toBe(false);
});
+ it('does not take over a known root instance for an organization namespace', () => {
+ const item = organizationDefaultSummary({ namespace: 'acme' });
+ const installed = {
+ manifest: manifest(item.ghostId),
+ dir: '/not-read-for-cross-namespace',
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ } satisfies InstalledGhost;
+ expect(
+ organizationDefaultTakeoverEligibility({
+ summary: item,
+ currentOrganization: { organizationId: 'org-1', pluginPrefix: 'acme' },
+ uniqueGhostId: true,
+ installed,
+ record: {
+ ...recordForTest(item),
+ pluginId: `c${'d'.repeat(24)}`,
+ source: 'market',
+ scope: 'public',
+ organizationId: null,
+ namespace: null,
+ },
+ installOrigin: 'manual',
+ runtimeAvailable: true,
+ optedOut: false,
+ builtinRemoved: false,
+ busy: false,
+ }),
+ ).toEqual({ eligible: false, reason: 'cross-namespace' });
+ });
+
it('skips busy work without backoff and retries after it becomes idle', async () => {
setCurrentOrganization();
const item = organizationDefaultSummary();
@@ -4718,7 +5534,7 @@ describe('organization default Plugin takeover', () => {
const snapshot = h.service.snapshot();
await downloadStarted.promise;
- h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');
downloadGate.resolve();
await snapshot;
@@ -4877,6 +5693,30 @@ describe('market detail 响应身份绑定', () => {
h.api.detail.mockImplementation(async () => detail({ ...item, id: 'plg_other' }));
await expect(h.service.detail(item.id)).rejects.toThrow('[PRECONDITION_FAILED]');
});
+
+ it('rejects list/detail namespace drift and mismatched download identity', async () => {
+ const item = summary({ namespace: null });
+ const h = harness([item]);
+ h.api.detail.mockImplementationOnce(async () => detail({ ...item, namespace: 'acme' }));
+ await expect(h.service.detail(item.id)).rejects.toThrow('[PRECONDITION_FAILED]');
+
+ const enterprise = summary({ namespace: 'acme' });
+ const h2 = harness([enterprise]);
+ h2.api.download.mockResolvedValue({
+ pluginId: enterprise.id,
+ releaseId: enterprise.currentRelease.id,
+ ghostId: enterprise.ghostId,
+ namespace: null,
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
+ await expect(
+ h2.service.install(enterprise.id, reviewedInstallOptions(enterprise), TEST_INSTALL_CONTEXT),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
});
describe('Agent catalog discovery and install boundary', () => {
@@ -5016,7 +5856,7 @@ describe('PluginMarketService install consent', () => {
it('does not silently grow permissions after the user opted out of default install', async () => {
const { item, h } = upgradeFixture({ defaultInstall: true, nextCapabilities: ['notify', 'fs'] });
- h.ledger.markRemoved(item.ghostId, 'user-1');
+ h.ledger.markRemovedRecord(h.ledger.installationForGhost(item.ghostId)!, 'user-1');
h.ledger.upsertInstallation({
...recordForTest(item),
releaseId: 'release-1',
diff --git a/apps/desktop/src/main/plugin-market/__tests__/unstampedNamespaceRecovery.test.ts b/apps/desktop/src/main/plugin-market/__tests__/unstampedNamespaceRecovery.test.ts
new file mode 100644
index 0000000000..ae5399c99a
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/__tests__/unstampedNamespaceRecovery.test.ts
@@ -0,0 +1,112 @@
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { GhostManifest } from '../../../shared/ghost.js';
+import { createNamespaceMigrationHost } from '../../cindy-brain/pluginNamespaceMigrationHost.js';
+import { type NamespaceClassification } from '../../cindy-brain/pluginNamespaceMigration.js';
+import { ghostManifestDigest, type PluginMarketInstallationRecord } from '../ledger.js';
+
+const manifest = {
+ schemaVersion: 2, id: 'hello', name: 'Hello', version: '1.0.0', kind: 'chip', entry: 'main.js',
+} as GhostManifest;
+const digest = ghostManifestDigest(manifest);
+const packageSha256 = 'b'.repeat(64);
+const record: PluginMarketInstallationRecord = {
+ pluginId: 'plugin', ghostId: 'hello', releaseId: 'release', version: '1.0.0',
+ sha256: packageSha256, scope: 'organization', organizationId: 'org-acme',
+ namespace: 'acme', source: 'market', installed: true, updatedAt: '2026-01-01T00:00:00Z',
+ rawManifestSha256: digest,
+};
+const evidence = { packageSha256, approvedManifest: manifest, legacyMigrated: false };
+afterEach(() => vi.useRealTimers());
+
+const pending = { kind: 'pending', reason: 'awaiting-market-facts' } as const;
+const root = { kind: 'commit', namespace: null, basis: 'manual-after-sync' } as const;
+const disconnected = { ...record, installed: false };
+const disconnectedWithoutDigest = { ...disconnected, rawManifestSha256: undefined };
+const legacyEvidence = { ...evidence, packageSha256: null, legacyMigrated: true };
+const migrationCases: Array<{
+ name: string;
+ record: PluginMarketInstallationRecord;
+ additionalRecords?: PluginMarketInstallationRecord[];
+ evidence: { packageSha256: string | null; approvedManifest: GhostManifest; legacyMigrated: boolean } | null;
+ expected: NamespaceClassification;
+ unreadable?: boolean;
+ user?: { membershipKind: string; orgId?: string; orgSlug?: string | null };
+}> = [
+ { name: 'approved organization', record: disconnected, evidence, expected: pending },
+ { name: 'changed current organization', record: disconnected, evidence, user: { membershipKind: 'org', orgId: 'org-other', orgSlug: 'other' }, expected: pending },
+ { name: 'missing current organization slug', record: disconnected, evidence, user: { membershipKind: 'org', orgId: 'org-acme' }, expected: pending },
+ { name: 'current personal account', record: disconnected, evidence, user: { membershipKind: 'personal' }, expected: pending },
+ { name: 'pre-namespace organization', record: { ...disconnected, namespace: undefined }, evidence, expected: pending },
+ { name: 'migrated legacy digest', record: { ...disconnectedWithoutDigest, manifestDigest: digest }, evidence: legacyEvidence, expected: pending },
+ { name: 'migrated legacy without stored identity', record: disconnectedWithoutDigest, evidence: legacyEvidence, expected: pending },
+ { name: 'changed package', record: disconnected, evidence: { ...evidence, packageSha256: 'c'.repeat(64) }, expected: root },
+ { name: 'changed approved manifest', record: disconnected, evidence: { ...evidence, approvedManifest: { ...manifest, name: 'Other' } }, expected: root },
+ { name: 'changed raw identity', record: { ...disconnected, rawManifestSha256: 'c'.repeat(64) }, evidence, expected: root },
+ { name: 'changed version', record: { ...disconnected, version: '0.9.0' }, evidence, expected: root },
+ { name: 'ordinary removed public record', record: { ...disconnected, scope: 'public' as const, namespace: null, organizationId: null }, evidence, expected: root },
+ { name: 'custom source record', record: { ...disconnected, source: 'git-market' as const }, evidence, expected: root },
+ { name: 'unavailable approval evidence', record: disconnected, evidence: null, expected: pending },
+ { name: 'unreadable installed manifest', record: disconnected, evidence, unreadable: true, expected: pending },
+ { name: 'successfully recovered record', record, evidence, expected: { kind: 'commit', namespace: 'acme', basis: 'market-organization' } as const },
+ { name: 'active root beside same-byte disconnected organization', record: { ...record, scope: 'public', namespace: null, organizationId: null }, additionalRecords: [disconnected], evidence, expected: { kind: 'commit', namespace: null, basis: 'explicit-root' } },
+];
+
+describe.each([
+ { entry: 'classification', cases: migrationCases },
+ { entry: 'resident-timer', cases: migrationCases.filter((fixture) =>
+ fixture.name === 'approved organization' || fixture.name === 'changed package') },
+])('production namespace gate via $entry', ({ entry, cases }) => {
+ it.each(cases)('$name', async (fixture) => {
+ vi.useFakeTimers();
+ const records = [structuredClone(fixture.record), ...structuredClone(fixture.additionalRecords ?? [])];
+ if (records[0].namespace === undefined) delete records[0].namespace;
+ const originalRecords = structuredClone(records);
+ const observed: NamespaceClassification[] = [];
+ const manager = {
+ list: () => [{ manifest, namespaceState: 'pending' }],
+ approvedInstallEvidence: vi.fn(() => fixture.evidence),
+ readApprovedInstallOriginStrict: (): 'manual' => 'manual',
+ reconcilePendingRootNamespaces: vi.fn(async (syncCompleted: boolean) => {
+ observed.push(callbacks.classifyPendingNamespaceForGhost('hello', syncCompleted));
+ }),
+ };
+ const callbacks = createNamespaceMigrationHost({
+ getPluginMarketLedger: () => ({ lookupInstallationsForNamespaceMigration: () => ({ kind: 'found', records }) }),
+ getGhostManager: () => manager,
+ getAuthState: () => ({ isAuthenticated: true, user: fixture.user ?? { membershipKind: 'org', orgId: 'org-acme', orgSlug: 'acme' } }),
+ createOrganizationPrefixStore: () => ({ lookup: () => ({ kind: 'absent' }) }),
+ ownerScopedUserDataPath: (...parts: string[]) => path.join('owner', ...parts),
+ brainRootDir: () => path.resolve('brain-root'),
+ readInstalledGhostManifestSnapshot: () => fixture.unreadable
+ ? { ok: false }
+ : { ok: true, snapshot: { manifest, legacyManualIgnored: false, rawManifestSha256: digest, releasedLegacyDigestFormat: manifest, legacyDigestFormats: [manifest] } },
+ isAppSessionBoundaryPending: () => false,
+ activeOwnerScopeKey: () => 'owner',
+ offlineResidentIdsForActiveScope: () => new Set(['hello']),
+ pendingResidentMigrationRetryTimers: new Map(),
+ pendingResidentMigrationRetryAttempts: new Map(),
+ captureGhostMutationOwner: () => ({}),
+ beginGhostMutation: () => () => {},
+ setTimeout: (handler, timeoutMs) => setTimeout(handler, timeoutMs),
+ oauthLockExists: () => false,
+ hasPendingWork: () => false,
+ runtimeState: () => null,
+ nodeRuntimeRunning: () => false,
+ stopRuntime: () => {},
+ stopNodeRuntime: async () => {},
+ log: { warn: vi.fn() },
+ });
+ if (entry === 'resident-timer') {
+ callbacks.schedulePendingResidentMigrationRetry('hello');
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(manager.reconcilePendingRootNamespaces).toHaveBeenCalledExactlyOnceWith(true);
+ } else {
+ observed.push(callbacks.classifyPendingNamespaceForGhost('hello', true));
+ }
+ expect(observed).toEqual([fixture.expected]);
+ expect(callbacks.canResumePendingResidentOffline('hello')).toBe(fixture.expected === root);
+ expect(records).toEqual(originalRecords);
+ });
+});
diff --git a/apps/desktop/src/main/plugin-market/agentTools.ts b/apps/desktop/src/main/plugin-market/agentTools.ts
index 9758baf1d5..02da0bdff7 100644
--- a/apps/desktop/src/main/plugin-market/agentTools.ts
+++ b/apps/desktop/src/main/plugin-market/agentTools.ts
@@ -1,6 +1,7 @@
import type { GhostInstallConsentPrompt } from '../cindy-brain/ghostInstallConsent.js';
import type { PluginMarketService } from './service.js';
import type { PluginMarketItem } from '../../shared/pluginMarket.js';
+import { deliveryNamespaceFields } from '../../shared/pluginIdentity.js';
import { isIpcError } from '../../shared/ipc-errors.js';
import { throwIpcError } from '../utils/ipcValidate.js';
@@ -12,7 +13,7 @@ interface InstalledState {
export interface PluginMarketAgentDeps {
market: Pick<PluginMarketService, 'snapshot' | 'detail' | 'install'>;
- installedState(ghostId: string): InstalledState;
+ installedState(ghostId: string, namespace?: string | null): InstalledState;
/** Owner generation and caller identity are captured before discovery's first await. */
captureRead(): () => void;
/**
@@ -29,7 +30,7 @@ export interface PluginMarketAgentDeps {
function catalogItem(item: PluginMarketItem, installed: InstalledState) {
return {
- plugin_id: item.pluginId, ghost_id: item.ghostId, release_id: item.releaseId,
+ plugin_id: item.pluginId, ghost_id: item.ghostId, ...deliveryNamespaceFields(item), release_id: item.releaseId,
name: item.name, description: item.description, author: item.author,
version: item.version, scope: item.scope,
source: item.sourceType, marketplace: item.sourceMarketName,
@@ -52,7 +53,7 @@ export function createPluginMarketAgentTools(deps: PluginMarketAgentDeps) {
.toLocaleLowerCase().includes(needle));
return {
ok: true,
- items: matches.slice(0, 20).map(item => catalogItem(item, deps.installedState(item.ghostId))),
+ items: matches.slice(0, 20).map(item => catalogItem(item, deps.installedState(item.ghostId, item.namespace))),
has_more: matches.length > 20,
complete: !snapshot.unavailableReason && snapshot.unavailableCustomSourceNames.length === 0,
// Source errors can contain local paths or server responses; expose status only.
@@ -73,7 +74,7 @@ export function createPluginMarketAgentTools(deps: PluginMarketAgentDeps) {
if (detail.releaseId !== request.releaseId) {
throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
}
- const installed = deps.installedState(detail.ghostId);
+ const installed = deps.installedState(detail.ghostId, detail.namespace);
if (installed.exists) return {
ok: true, status: 'already-installed',
plugin: catalogItem(detail, installed),
@@ -82,7 +83,7 @@ export function createPluginMarketAgentTools(deps: PluginMarketAgentDeps) {
// Recheck at the service's final commit boundary, including concurrent local imports.
const assertCurrent = () => {
authority.assertCurrent();
- if (deps.installedState(detail.ghostId).exists) {
+ if (deps.installedState(detail.ghostId, detail.namespace).exists) {
throwIpcError('PRECONDITION_FAILED', 'Plugin appeared during installation; inspect it before continuing');
}
};
@@ -100,6 +101,7 @@ export function createPluginMarketAgentTools(deps: PluginMarketAgentDeps) {
// into a failure. The live check runs at package placement instead.
return {
ok: true, status: 'installed', ghost_id: result.ghost.manifest.id,
+ ...deliveryNamespaceFields(result.ghost),
name: result.ghost.manifest.name, version: result.ghost.manifest.version,
enabled: result.ghost.enabled,
next: 'Inspect ghost_info for the real tools and setup. Installation is not account connection or task completion.',
diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.ts
index ef2c98f991..16475e1448 100644
--- a/apps/desktop/src/main/plugin-market/api.ts
+++ b/apps/desktop/src/main/plugin-market/api.ts
@@ -1,4 +1,5 @@
import {
+ assertPluginListOrganizationNamespace,
CINDY_CLIENT_VERSION_HEADER,
parseGetPluginResponse,
parseListPluginsResponse,
@@ -79,6 +80,11 @@ export class PluginMarketApi {
// `currentOrganization` 并没有写进契约(PLAN §6 没有这一条),若它只在首页带,
// 逐页覆盖会让第二页的 null 把身份事实抹掉——多页目录的组织就永远缓存不到前缀。
// 两种服务端行为下这个写法都对,且结果确定。
+ if (currentOrganization && response.currentOrganization &&
+ (currentOrganization.organizationId !== response.currentOrganization.organizationId ||
+ currentOrganization.orgSlug !== response.currentOrganization.orgSlug)) {
+ throw new Error('Plugin 市场分页 currentOrganization 不一致');
+ }
currentOrganization ??= response.currentOrganization;
if (!response.nextCursor) {
// 在架优先(契约:通告与**任一页** plugins 有交集即作废)的作用域是
@@ -91,6 +97,7 @@ export class PluginMarketApi {
});
return false;
});
+ assertPluginListOrganizationNamespace(currentOrganization, plugins, removals);
return { plugins, removals, currentOrganization };
}
if (response.nextCursor === cursor) throw new Error('Plugin 市场分页游标未前进');
diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.ts
index 4973ef8099..607c296fde 100644
--- a/apps/desktop/src/main/plugin-market/install.ts
+++ b/apps/desktop/src/main/plugin-market/install.ts
@@ -14,6 +14,7 @@ import crypto from 'node:crypto';
import { app } from 'electron';
+import { authorDeclaredNamespaceReason } from '@cindy/plugin-protocol';
import {
ghostNetworkAuthorizationWithinCap,
ghostNodeSecretAuthorizationWithinCap,
@@ -74,6 +75,7 @@ export interface PackedCustomMarketPlugin {
}
type CustomMarketCommitHooks = {
+ sourceChanged?: boolean | (() => boolean);
expectedInstalledApproval?: string;
beforeCommit?: () => void | Promise<void>;
beforePackagePlacement?: () => void;
@@ -138,6 +140,10 @@ export async function packCustomMarketPlugin(input: {
// reason 会插值 ghost.json 里的未知字段值(不受长度约束的不可信内容),
// packed.message 会带 fs 错误自附的宿主绝对路径——进 IPC 前一律脱敏+截断,
// 完整原文只留 main 日志。
+ const reservedNamespace = authorDeclaredNamespaceReason(raw);
+ if (reservedNamespace) {
+ throwIpcError('GHOST_FILE_INVALID', sanitizeInstallDetail(reservedNamespace));
+ }
const validated = validateGhostManifest(raw);
if (!validated.ok) {
throwIpcError('GHOST_FILE_INVALID', sanitizeInstallDetail(validated.reason));
@@ -242,6 +248,8 @@ export async function commitCustomMarketPlugin(
ghostId: input.expectedGhostId,
version: input.expectedVersion,
consent: input.consent,
+ ...((typeof input.sourceChanged === 'function' ? input.sourceChanged() : input.sourceChanged)
+ ? { sourceChanged: true } : {}),
// 发现时读到的规范化 Manifest 是这次安装允许的能力上限。打包窗口
// 中目录若发生能力扩张,Host 会按真实包不一致直接拒绝。
manifestCap: packed.validatedManifest,
@@ -267,6 +275,7 @@ export async function commitCustomMarketPlugin(
}
export async function installCustomMarketPlugin(input: {
+ sourceChanged?: boolean | (() => boolean);
pluginDir: string;
expected?: GhostManifest;
/** 更新时把发起操作时读取的 Host receipt token 贯穿到最终安装出口。 */
@@ -331,6 +340,7 @@ export async function installCustomMarketPlugin(input: {
expectedGhostId: input.expectedGhostId,
expectedVersion: input.expectedVersion,
consent,
+ sourceChanged: input.sourceChanged,
expectedInstalledApproval: input.expectedInstalledApproval,
beforeCommit: input.beforeCommit,
beforePackagePlacement: input.beforePackagePlacement,
diff --git a/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts b/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts
index a3581d60e2..ce3e65af08 100644
--- a/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts
+++ b/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts
@@ -1,4 +1,5 @@
import type { GhostManifest } from '../../shared/ghost.js';
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
import type { InstalledGhostManifestSnapshot } from '../installedGhostManifest.js';
import {
ghostManifestDigest,
@@ -73,3 +74,38 @@ export function installedIdentityMatchesManifest(
): boolean {
return identity.legacyManifestDigests.includes(ghostManifestDigest(manifest));
}
+
+interface OrganizationInstallationEvidenceInput {
+ records: readonly PluginMarketInstallationRecord[];
+ evidence: { packageSha256: string | null; approvedManifest: GhostManifest; legacyMigrated: boolean } | null;
+ identity: InstalledMarketManifestIdentity | null;
+}
+
+function matchesApprovedOrganizationInstallation(
+ record: PluginMarketInstallationRecord,
+ input: OrganizationInstallationEvidenceInput,
+ allowLegacyReceiptWithoutStoredIdentity = false,
+): boolean {
+ const { evidence, identity } = input;
+ if (!evidence || !identity) return false;
+ if (record.scope !== 'organization' ||
+ (record.source !== 'market' && record.source !== 'legacy-adopted') ||
+ !record.organizationId ||
+ record.ghostId !== identity.manifest.id || record.version !== identity.manifest.version ||
+ (record.namespace !== undefined && !isValidPluginNamespace(record.namespace)) ||
+ (evidence.packageSha256 !== null && evidence.packageSha256 !== record.sha256) ||
+ (evidence.packageSha256 === null && !evidence.legacyMigrated) ||
+ !installedIdentityMatchesManifest(identity, evidence.approvedManifest)) return false;
+ return verifyInstalledMarketManifest(record, identity) ||
+ (record.rawManifestSha256 === undefined && record.manifestDigest === undefined &&
+ (evidence.packageSha256 === record.sha256 ||
+ (allowLegacyReceiptWithoutStoredIdentity && evidence.packageSha256 === null)));
+}
+
+export function hasVerifiedDisconnectedOrganizationInstallation(
+ input: OrganizationInstallationEvidenceInput,
+): boolean {
+ return input.records.some((record) => !record.installed &&
+ /^[a-f0-9]{64}$/.test(record.sha256) &&
+ matchesApprovedOrganizationInstallation(record, input, true));
+}
diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.ts
index e4b1f1fb7e..c235a4dd8e 100644
--- a/apps/desktop/src/main/plugin-market/ledger.ts
+++ b/apps/desktop/src/main/plugin-market/ledger.ts
@@ -1,17 +1,30 @@
import crypto from 'node:crypto';
+import fs from 'node:fs';
import path from 'node:path';
-import type { PluginScope } from '@cindy/plugin-protocol';
+import { isValidPluginNamespace, type PluginScope } from '@cindy/plugin-protocol';
import { ghostManifestToLegacyV2DigestFormat } from '../../shared/ghost.js';
+import {
+ hasDeliveryNamespace,
+ parsePluginInstallRelId,
+ parsePluginStoragePart,
+ pluginLedgerRecordKey,
+ PLUGIN_NS_INSTALL_ROOT,
+ PLUGIN_ROOT_INSTALL_DIR,
+ type PluginLogicalIdentity,
+} from '../../shared/pluginIdentity.js';
import {
atomicWriteFileSync,
readAtomicFileSync,
} from '../utils/atomicWriteFile.js';
const LEDGER_SCHEMA_VERSION = 1;
+export const LEDGER_PENDING_FILE = 'ledger.v1.pending.json';
/** 自定义市场溯源的独立账本文件名(与 ledger.v1.json 同目录)。 */
const CUSTOM_LEDGER_FILE = 'custom-ledger.v1.json';
+/** 同 ghostId 跨 namespace 共存时,企业记录进这个旧客户端不会碰的文件。 */
+export const NS_LEDGER_FILE = 'ns-ledger.v1.json';
/** 服务端市场安装的溯源来源(旧版本也认识的封闭集合)。 */
const SERVER_SOURCES = new Set(['market', 'legacy-adopted']);
@@ -24,6 +37,8 @@ export interface PluginMarketInstallationRecord {
sha256: string;
scope: PluginScope;
organizationId: string | null;
+ /** Missing is a pre-namespace record. null is root; a string is an organization. */
+ namespace?: string | null;
source: 'market' | 'legacy-adopted' | 'git-market' | 'local-market';
installed: boolean;
updatedAt: string;
@@ -49,6 +64,18 @@ export interface PluginMarketInstallationRecord {
rawManifestSha256?: string;
}
+export type PluginMarketAuthorizationTarget = { ghostId: string; namespace?: string | null };
+
+export type PluginMarketAuthorizationLookup =
+ | { kind: 'absent' }
+ | { kind: 'found'; record: PluginMarketInstallationRecord }
+ | { kind: 'invalid' };
+
+export type PluginMarketNamespaceMigrationLookup =
+ | { kind: 'absent' }
+ | { kind: 'found'; records: PluginMarketInstallationRecord[] }
+ | { kind: 'invalid' };
+
/** 递归按键排序的规范化 JSON(摘要必须与对象键序无关,两侧独立算也一致)。 */
function canonicalJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
@@ -84,6 +111,29 @@ interface PluginMarketLedgerData {
defaultInstallOptOuts: Record<string, string[]>;
}
+interface LedgerWriteJournal {
+ schemaVersion: typeof LEDGER_SCHEMA_VERSION;
+ targets: {
+ namespaced: string;
+ custom: string;
+ main: string;
+ };
+}
+
+function isLedgerSnapshotText(value: unknown): value is string {
+ if (typeof value !== 'string') return false;
+ try {
+ const parsed = JSON.parse(value) as Record<string, unknown>;
+ return parsed !== null && typeof parsed === 'object' &&
+ parsed.schemaVersion === LEDGER_SCHEMA_VERSION &&
+ parsed.installations !== null &&
+ typeof parsed.installations === 'object' &&
+ !Array.isArray(parsed.installations);
+ } catch {
+ return false;
+ }
+}
+
function emptyLedger(): PluginMarketLedgerData {
return {
schemaVersion: LEDGER_SCHEMA_VERSION,
@@ -92,6 +142,40 @@ function emptyLedger(): PluginMarketLedgerData {
};
}
+function isOrgNamespaceRecord(record: PluginMarketInstallationRecord): boolean {
+ return hasDeliveryNamespace(record) && record.namespace !== null;
+}
+
+function indexInstallation(
+ installations: Record<string, PluginMarketInstallationRecord>,
+ record: PluginMarketInstallationRecord,
+): void {
+ installations[pluginLedgerRecordKey(record)] = record;
+}
+
+function recordsForGhostId(
+ installations: Record<string, PluginMarketInstallationRecord>,
+ ghostId: string,
+): PluginMarketInstallationRecord[] {
+ return Object.values(installations).filter((record) => record.ghostId === ghostId);
+}
+
+function uniqueRecordForGhostId(
+ installations: Record<string, PluginMarketInstallationRecord>,
+ ghostId: string,
+): PluginMarketInstallationRecord | null {
+ const matches = recordsForGhostId(installations, ghostId);
+ return matches.length === 1 ? matches[0]! : null;
+}
+
+function uniqueInstalledRecordForGhostId(
+ installations: Record<string, PluginMarketInstallationRecord>,
+ ghostId: string,
+): PluginMarketInstallationRecord | null {
+ const matches = recordsForGhostId(installations, ghostId).filter((record) => record.installed);
+ return matches.length === 1 ? matches[0]! : null;
+}
+
function isCustomRecord(record: PluginMarketInstallationRecord): boolean {
return record.source === 'git-market' || record.source === 'local-market';
}
@@ -123,6 +207,9 @@ function validRecord(value: unknown): value is PluginMarketInstallationRecord {
record.scope === 'organization' ||
record.scope === 'personal') &&
(record.organizationId === null || typeof record.organizationId === 'string') &&
+ (record.namespace === undefined ||
+ record.namespace === null ||
+ isValidPluginNamespace(record.namespace)) &&
(record.source === 'market' ||
record.source === 'legacy-adopted' ||
record.source === 'git-market' ||
@@ -147,7 +234,7 @@ type InstallationsFileRead = {
function readInstallationsFile(filePath: string): InstallationsFileRead {
// 读失败与解析失败分开处理:文件不存在(ENOENT)才是空;文件在但读不到(文件锁/
// 权限/瞬时 I/O)或备份救不回来时由 readAtomicFileSync **上抛**——降级成空会让
- // 紧接着的写入把真实记录覆盖掉。只有"内容确实不是合法 JSON"才按空重建。
+ // 紧接着的写入把真实记录覆盖掉;损坏的文件也必须留给上层处理。
const text = readAtomicFileSync(filePath);
if (text === null) return { kind: 'absent', installations: {}, raw: null };
let parsed: unknown;
@@ -173,24 +260,29 @@ function readInstallationsFile(filePath: string): InstallationsFileRead {
return { kind: 'invalid', installations: {}, raw: value };
}
const installations: Record<string, PluginMarketInstallationRecord> = {};
- for (const [ghostId, record] of Object.entries(rawInstallations)) {
- if (validRecord(record) && record.ghostId === ghostId) installations[ghostId] = record;
+ for (const [key, record] of Object.entries(rawInstallations)) {
+ if (!validRecord(record)) continue;
+ const logicalKey = pluginLedgerRecordKey(record);
+ if (key !== record.ghostId && key !== logicalKey) continue;
+ installations[logicalKey] = record;
}
return { kind: 'ok', installations, raw: value };
}
+function rawEntryMentionsGhost(key: string, record: unknown, ghostId: string): boolean {
+ return key === ghostId || parsePluginStoragePart(key)?.ghostId === ghostId || Boolean(
+ record && typeof record === 'object' && !Array.isArray(record) &&
+ (record as { ghostId?: unknown }).ghostId === ghostId,
+ );
+}
+
function rawMentionsGhost(file: InstallationsFileRead, ghostId: string): boolean {
const installations = file.raw?.installations;
if (!installations || typeof installations !== 'object' || Array.isArray(installations)) {
return false;
}
- if (Object.prototype.hasOwnProperty.call(installations, ghostId)) return true;
- return Object.values(installations).some(
- (record) =>
- record &&
- typeof record === 'object' &&
- !Array.isArray(record) &&
- (record as { ghostId?: unknown }).ghostId === ghostId,
+ return Object.entries(installations).some(
+ ([key, record]) => rawEntryMentionsGhost(key, record, ghostId),
);
}
@@ -234,23 +326,71 @@ export class PluginMarketLedger {
return path.join(path.dirname(this.filePath()), CUSTOM_LEDGER_FILE);
}
- private readFiles(): { main: InstallationsFileRead; custom: InstallationsFileRead } {
+ private nsFilePath(): string {
+ return path.join(path.dirname(this.filePath()), NS_LEDGER_FILE);
+ }
+
+ private pendingFilePath(): string {
+ return path.join(path.dirname(this.filePath()), LEDGER_PENDING_FILE);
+ }
+
+ private recoverPendingWrite(): void {
+ const text = readAtomicFileSync(this.pendingFilePath());
+ if (text === null) return;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ throw new Error('Plugin market ledger pending write is unreadable');
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) ||
+ (parsed as Record<string, unknown>).schemaVersion !== LEDGER_SCHEMA_VERSION) {
+ throw new Error('Plugin market ledger pending write is unreadable');
+ }
+ const targets = (parsed as Record<string, unknown>).targets;
+ if (!targets || typeof targets !== 'object' || Array.isArray(targets)) {
+ throw new Error('Plugin market ledger pending write is unreadable');
+ }
+ const snapshot = targets as Record<string, unknown>;
+ if (!isLedgerSnapshotText(snapshot.namespaced) ||
+ !isLedgerSnapshotText(snapshot.custom) ||
+ !isLedgerSnapshotText(snapshot.main)) {
+ throw new Error('Plugin market ledger pending write is unreadable');
+ }
+ atomicWriteFileSync(this.nsFilePath(), snapshot.namespaced);
+ atomicWriteFileSync(this.customFilePath(), snapshot.custom);
+ atomicWriteFileSync(this.filePath(), snapshot.main);
+ try {
+ fs.unlinkSync(this.pendingFilePath());
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+
+ private readFiles(): {
+ main: InstallationsFileRead;
+ custom: InstallationsFileRead;
+ namespaced: InstallationsFileRead;
+ } {
+ this.recoverPendingWrite();
return {
main: readInstallationsFile(this.filePath()),
custom: readInstallationsFile(this.customFilePath()),
+ namespaced: readInstallationsFile(this.nsFilePath()),
};
}
private mergeInstallations(
main: InstallationsFileRead,
custom: InstallationsFileRead,
+ namespaced: InstallationsFileRead,
): PluginMarketLedgerData {
const installations: Record<string, PluginMarketInstallationRecord> = {};
- for (const [ghostId, record] of Object.entries(main.installations)) {
+ for (const [key, record] of Object.entries(main.installations)) {
// 主账本里的自定义记录是早期开发版写入的存量,一并纳入(下次写入时归位)。
- installations[ghostId] = record;
+ installations[key] = record;
}
- for (const [ghostId, record] of Object.entries(custom.installations)) {
+ for (const [key, record] of Object.entries(custom.installations)) {
if (!isCustomRecord(record)) continue; // 自定义账本只承载自定义溯源
// 两个文件出现同一 ghostId 只发生在降级窗口:旧版本只写主账本(比如降级后
// 卸载了自定义安装、又从服务端装了同 ghostId),custom 账本里留着它不认识、
@@ -258,8 +398,13 @@ export class PluginMarketLedger {
// 来源,并允许该来源提供更新 —— 必须按"实际安装状态 + 时间"消解,平手保
// 主账本(冲突本身即意味着旧版操作过主账本)。胜出后由任意一次写入按 source
// 归位,败方记录随整份重写被清掉。
- const existing = installations[ghostId];
- installations[ghostId] = existing ? preferRecord(existing, record) : record;
+ const existing = installations[key];
+ installations[key] = existing ? preferRecord(existing, record) : record;
+ }
+ for (const [key, record] of Object.entries(namespaced.installations)) {
+ if (!isOrgNamespaceRecord(record)) continue;
+ const existing = installations[key];
+ installations[key] = existing ? preferRecord(existing, record) : record;
}
const defaultInstallOptOuts: Record<string, string[]> = {};
@@ -276,12 +421,105 @@ export class PluginMarketLedger {
}
read(): PluginMarketLedgerData {
- const { main, custom } = this.readFiles();
- return this.mergeInstallations(main, custom);
+ const { main, custom, namespaced } = this.readFiles();
+ if (main.kind === 'invalid' || custom.kind === 'invalid' || namespaced.kind === 'invalid') {
+ throw new Error('Plugin market ledger is unreadable');
+ }
+ return this.mergeInstallations(main, custom, namespaced);
}
installationForGhost(ghostId: string): PluginMarketInstallationRecord | null {
- return this.read().installations[ghostId] ?? null;
+ return uniqueRecordForGhostId(this.read().installations, ghostId);
+ }
+
+ installationsForGhost(ghostId: string): PluginMarketInstallationRecord[] {
+ return recordsForGhostId(this.read().installations, ghostId);
+ }
+
+ lookupInstallationsForNamespaceMigration(ghostId: string): PluginMarketNamespaceMigrationLookup {
+ const { main, custom, namespaced } = this.readFiles();
+ for (const file of [main, custom, namespaced]) {
+ if (file.kind === 'invalid') return { kind: 'invalid' };
+ if (!rawMentionsGhost(file, ghostId)) continue;
+ const raw = file.raw!.installations as Record<string, unknown>;
+ if (Object.entries(raw).some(([key, record]) =>
+ rawEntryMentionsGhost(key, record, ghostId) &&
+ (!validRecord(record) || (key !== record.ghostId && key !== pluginLedgerRecordKey(record))),
+ )) return { kind: 'invalid' };
+ }
+ const records = recordsForGhostId(this.mergeInstallations(main, custom, namespaced).installations, ghostId);
+ return records.length > 0 ? { kind: 'found', records } : { kind: 'absent' };
+ }
+
+ installationForPlugin(plugin: {
+ ghostId: string;
+ namespace?: string | null;
+ }): PluginMarketInstallationRecord | null {
+ return this.read().installations[pluginLedgerRecordKey(plugin)] ?? null;
+ }
+
+ installationForLocalUninstall(plugin: {
+ ghostId: string;
+ namespace?: string | null;
+ }): PluginMarketInstallationRecord | null {
+ const record = this.installationForPlugin(plugin);
+ if (!record?.installed || record.ghostId !== plugin.ghostId) return null;
+ if (hasDeliveryNamespace(plugin) && hasDeliveryNamespace(record) &&
+ plugin.namespace !== record.namespace) return null;
+ if (hasDeliveryNamespace(plugin) && plugin.namespace === null && record.scope === 'organization') {
+ return null;
+ }
+ return record;
+ }
+
+ markRemovedRecordIfUnchanged(record: PluginMarketInstallationRecord, userId: string | null): boolean {
+ const current = this.installationForPlugin(record);
+ if (!current || canonicalJson(current) !== canonicalJson(record)) return false;
+ this.markRemovedRecord(current, userId);
+ return true;
+ }
+
+ installationForAuthorization(target: PluginMarketAuthorizationTarget): PluginMarketInstallationRecord | null {
+ const lookup = this.lookupInstallationForAuthorization(target);
+ if (lookup.kind === 'invalid') throw new Error('Plugin market ledger is unreadable');
+ return lookup.kind === 'found' ? lookup.record : null;
+ }
+
+ lookupInstallationForAuthorization(target: PluginMarketAuthorizationTarget): PluginMarketAuthorizationLookup {
+ const { main, custom, namespaced } = this.readFiles();
+ if (main.kind === 'invalid' || custom.kind === 'invalid' || namespaced.kind === 'invalid') {
+ return { kind: 'invalid' };
+ }
+ const merged = this.mergeInstallations(main, custom, namespaced).installations;
+ const precise = hasDeliveryNamespace(target);
+ const record = precise
+ ? merged[pluginLedgerRecordKey(target)] ?? null
+ : this.recordForLookup(merged, target.ghostId);
+ if (record) {
+ if (precise && (record.ghostId !== target.ghostId ||
+ (hasDeliveryNamespace(record) && record.namespace !== target.namespace) ||
+ (target.namespace === null && record.scope === 'organization'))) {
+ return { kind: 'absent' };
+ }
+ return { kind: 'found', record };
+ }
+ const mentionsUnparsedTarget = (file: InstallationsFileRead): boolean => {
+ if (!precise) return rawMentionsGhost(file, target.ghostId);
+ const raw = file.raw?.installations;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false;
+ return Object.entries(raw).some(([key, value]) => {
+ if (validRecord(value) && hasDeliveryNamespace(value) && value.namespace !== target.namespace) return false;
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return key === pluginLedgerRecordKey(target);
+ }
+ const candidate = value as { ghostId?: unknown; namespace?: unknown };
+ return key === pluginLedgerRecordKey(target) ||
+ (candidate.ghostId === target.ghostId &&
+ (!hasDeliveryNamespace(candidate) || candidate.namespace === target.namespace));
+ });
+ };
+ return [main, custom, namespaced].some(mentionsUnparsedTarget)
+ ? { kind: 'invalid' } : { kind: 'absent' };
}
/**
@@ -290,24 +528,78 @@ export class PluginMarketLedger {
* corruption as "no market record".
*/
lookupInstallationForOidc(
- ghostId: string,
- ): { kind: 'absent' } | { kind: 'found'; record: PluginMarketInstallationRecord } | { kind: 'invalid' } {
- const { main, custom } = this.readFiles();
- if (main.kind === 'invalid' || custom.kind === 'invalid') return { kind: 'invalid' };
- const record = this.mergeInstallations(main, custom).installations[ghostId];
- if (record) return { kind: 'found', record };
- if (rawMentionsGhost(main, ghostId) || rawMentionsGhost(custom, ghostId)) {
- return { kind: 'invalid' };
- }
- return { kind: 'absent' };
+ target: string | PluginMarketAuthorizationTarget,
+ namespace?: string | null,
+ ): PluginMarketAuthorizationLookup {
+ return this.lookupInstallationForAuthorization(typeof target === 'string'
+ ? { ghostId: target, ...(namespace !== undefined ? { namespace } : {}) }
+ : target);
}
upsertInstallation(record: PluginMarketInstallationRecord): void {
const data = this.read();
- data.installations[record.ghostId] = record;
+ this.putRecord(data, record);
this.write(data);
}
+ /**
+ * Stamp namespace onto a pre-namespace market row. Known namespace is never
+ * replaced; a mismatch leaves the existing value in place.
+ */
+ stampNamespaceIfAbsent(ghostId: string, namespace: string | null): boolean {
+ if (namespace !== null && !isValidPluginNamespace(namespace)) return false;
+ const data = this.read();
+ const current = uniqueInstalledRecordForGhostId(data.installations, ghostId);
+ if (!current) return false;
+ if (hasDeliveryNamespace(current)) {
+ return current.namespace === namespace;
+ }
+ this.replaceRecord(data, current, { ...current, namespace });
+ this.write(data);
+ return true;
+ }
+
+ /**
+ * An old client rewrites an installed market row without namespace.
+ * Fill that field from the server catalog only when pluginId, ghostId,
+ * scope, and organizationId already match, and only when the field is absent.
+ */
+ backfillMissingNamespacesFromCatalog(plugins: readonly {
+ id: string;
+ ghostId: string;
+ scope: PluginMarketInstallationRecord['scope'];
+ organizationId: string | null;
+ namespace?: string | null;
+ }[]): number {
+ const data = this.read();
+ let changed = 0;
+ for (const plugin of plugins) {
+ if (!hasDeliveryNamespace(plugin)) continue;
+ const namespace = plugin.namespace ?? null;
+ // An organization row with an explicit null is not root. Invalid slugs
+ // must not be written: the next read would treat the ledger as corrupt.
+ if (namespace === null) {
+ if (plugin.scope === 'organization') continue;
+ } else if (!isValidPluginNamespace(namespace)) continue;
+ const matches = Object.values(data.installations).filter((record) =>
+ record.installed &&
+ record.pluginId === plugin.id &&
+ record.ghostId === plugin.ghostId &&
+ record.scope === plugin.scope &&
+ record.organizationId === plugin.organizationId &&
+ !hasDeliveryNamespace(record));
+ if (matches.length !== 1) continue;
+ this.replaceRecord(data, matches[0]!, { ...matches[0]!, namespace });
+ changed += 1;
+ }
+ if (changed > 0) this.write(data);
+ return changed;
+ }
+
+ hasInstalledRecordForGhostId(ghostId: string): boolean {
+ return recordsForGhostId(this.read().installations, ghostId).some((record) => record.installed);
+ }
+
/**
* Add the serialization-exact manifest identity without changing
* routing order or any legacy field. Full-record comparison makes this a CAS:
@@ -319,12 +611,12 @@ export class PluginMarketLedger {
): boolean {
if (!/^[a-f0-9]{64}$/.test(rawManifestSha256)) return false;
const data = this.read();
- const current = data.installations[expected.ghostId];
+ const current = data.installations[pluginLedgerRecordKey(expected)];
if (!current || canonicalJson(current) !== canonicalJson(expected)) return false;
if (current.rawManifestSha256 !== undefined) {
return current.rawManifestSha256 === rawManifestSha256;
}
- data.installations[current.ghostId] = { ...current, rawManifestSha256 };
+ this.replaceRecord(data, current, { ...current, rawManifestSha256 });
this.write(data);
return true;
}
@@ -344,13 +636,13 @@ export class PluginMarketLedger {
return false;
}
const data = this.read();
- const current = data.installations[expected.ghostId];
+ const current = data.installations[pluginLedgerRecordKey(expected)];
if (!current || canonicalJson(current) !== canonicalJson(expected)) return false;
- data.installations[current.ghostId] = {
+ this.replaceRecord(data, current, {
...current,
manifestDigest,
rawManifestSha256,
- };
+ });
this.write(data);
return true;
}
@@ -361,7 +653,7 @@ export class PluginMarketLedger {
optOut?: { userId: string; suppressed: boolean },
): void {
const data = this.read();
- data.installations[record.ghostId] = record;
+ this.putRecord(data, record);
if (optOut) {
const suppressedPluginIds = data.defaultInstallOptOuts[optOut.userId] ?? [];
if (optOut.suppressed) {
@@ -395,7 +687,7 @@ export class PluginMarketLedger {
return false;
}
const data = this.read();
- const current = data.installations[expected.ghostId];
+ const current = data.installations[pluginLedgerRecordKey(expected)];
if (
!current
|| current.installed
@@ -404,7 +696,7 @@ export class PluginMarketLedger {
) {
return false;
}
- data.installations[current.ghostId] = {
+ this.replaceRecord(data, current, {
...current,
source:
current.scope === 'organization' && current.source === 'market'
@@ -413,7 +705,7 @@ export class PluginMarketLedger {
installed: true,
updatedAt: new Date().toISOString(),
...(rawManifestSha256 !== undefined ? { rawManifestSha256 } : {}),
- };
+ });
const remainingOptOuts = (data.defaultInstallOptOuts[userId] ?? []).filter(
(pluginId) => pluginId !== current.pluginId,
);
@@ -423,18 +715,19 @@ export class PluginMarketLedger {
return true;
}
- markRemoved(ghostId: string, userId: string | null): void {
+
+ markRemovedRecord(record: PluginMarketInstallationRecord, userId: string | null): void {
const data = this.read();
- const record = data.installations[ghostId];
- if (!record) return;
- data.installations[ghostId] = {
- ...record,
+ const current = data.installations[pluginLedgerRecordKey(record)];
+ if (!current) return;
+ this.replaceRecord(data, current, {
+ ...current,
installed: false,
updatedAt: new Date().toISOString(),
- };
+ });
if (userId) {
data.defaultInstallOptOuts[userId] = [
- ...new Set([...(data.defaultInstallOptOuts[userId] ?? []), record.pluginId]),
+ ...new Set([...(data.defaultInstallOptOuts[userId] ?? []), current.pluginId]),
];
}
this.write(data);
@@ -444,18 +737,106 @@ export class PluginMarketLedger {
return this.read().defaultInstallOptOuts[userId]?.includes(pluginId) ?? false;
}
+ private recordForLookup(
+ installations: Record<string, PluginMarketInstallationRecord>,
+ id: string,
+ ): PluginMarketInstallationRecord | null {
+ if (
+ id.startsWith(`${PLUGIN_NS_INSTALL_ROOT}/`) ||
+ id.startsWith(`${PLUGIN_NS_INSTALL_ROOT}__`) ||
+ id.startsWith(`${PLUGIN_ROOT_INSTALL_DIR}__`)
+ ) {
+ const parsed = parsePluginInstallRelId(id) ?? parsePluginStoragePart(id);
+ return parsed ? installations[pluginLedgerRecordKey(parsed)] ?? null : null;
+ }
+ const root = installations[id];
+ if (root && root.ghostId === id && !isOrgNamespaceRecord(root)) {
+ if (root.installed) return root;
+ return uniqueInstalledRecordForGhostId(installations, id) ?? root;
+ }
+ return uniqueRecordForGhostId(installations, id);
+ }
+
+ private putRecord(
+ data: PluginMarketLedgerData,
+ record: PluginMarketInstallationRecord,
+ ): void {
+ data.installations[pluginLedgerRecordKey(record)] = record;
+ }
+
+ private replaceRecord(
+ data: PluginMarketLedgerData,
+ previous: PluginMarketInstallationRecord,
+ next: PluginMarketInstallationRecord,
+ ): void {
+ const previousKey = pluginLedgerRecordKey(previous);
+ const nextKey = pluginLedgerRecordKey(next);
+ if (previousKey !== nextKey) delete data.installations[previousKey];
+ data.installations[nextKey] = next;
+ }
+
private write(data: PluginMarketLedgerData): void {
+ for (const file of Object.values(this.readFiles())) {
+ const raw = file.raw?.installations as Record<string, unknown> | undefined;
+ if (file.kind === 'invalid' || Object.entries(raw ?? {}).some(([key, record]) =>
+ !validRecord(record) || (key !== record.ghostId && key !== pluginLedgerRecordKey(record)),
+ )) {
+ throw new Error('Plugin market ledger is unreadable');
+ }
+ }
// 按 source 分仓落盘:主账本只出现旧版本认识的 source,自定义溯源全部进
// 独立文件。混写过的存量(早期开发版)由此在任意一次写入时自动归位。
+ // 同 ghostId 的企业记录在会与 root 或其他 namespace 撞车时写入 ns 账本,
+ // 避免旧客户端按 ghostId 键覆盖掉另一份身份。
+ // 撞车时企业行从 v1 搬到 sidecar:先把三份目标快照写进 durable journal,
+ // 再写 sidecar(只加不减)和 v1;任一中断都由下一次读取重放整组快照。
const server: Record<string, PluginMarketInstallationRecord> = {};
const custom: Record<string, PluginMarketInstallationRecord> = {};
- for (const [ghostId, record] of Object.entries(data.installations)) {
- if (isCustomRecord(record)) custom[ghostId] = record;
- else if (SERVER_SOURCES.has(record.source)) server[ghostId] = record;
+ const namespaced: Record<string, PluginMarketInstallationRecord> = {};
+ const byGhostId = new Map<string, PluginMarketInstallationRecord[]>();
+ for (const record of Object.values(data.installations)) {
+ const group = byGhostId.get(record.ghostId) ?? [];
+ group.push(record);
+ byGhostId.set(record.ghostId, group);
}
- atomicWriteFileSync(
- this.filePath(),
- `${JSON.stringify(
+ const place = (
+ record: PluginMarketInstallationRecord,
+ dest: Record<string, PluginMarketInstallationRecord>,
+ key: string,
+ ): void => {
+ dest[key] = record;
+ };
+ for (const group of byGhostId.values()) {
+ const orgRecords = group.filter(isOrgNamespaceRecord);
+ const rootRecords = group.filter((record) => !isOrgNamespaceRecord(record));
+ const collision = orgRecords.length > 0 && (rootRecords.length > 0 || orgRecords.length > 1);
+ if (!collision) {
+ for (const record of group) {
+ const dest = isCustomRecord(record) ? custom : SERVER_SOURCES.has(record.source) ? server : null;
+ if (dest) place(record, dest, record.ghostId);
+ }
+ continue;
+ }
+ for (const record of rootRecords) {
+ const dest = isCustomRecord(record) ? custom : SERVER_SOURCES.has(record.source) ? server : null;
+ if (dest) place(record, dest, record.ghostId);
+ }
+ for (const record of orgRecords) {
+ namespaced[pluginLedgerRecordKey(record)] = record;
+ }
+ }
+ const targets: LedgerWriteJournal['targets'] = {
+ namespaced: JSON.stringify(
+ { schemaVersion: LEDGER_SCHEMA_VERSION, installations: namespaced },
+ null,
+ 2,
+ ) + '\n',
+ custom: JSON.stringify(
+ { schemaVersion: LEDGER_SCHEMA_VERSION, installations: custom },
+ null,
+ 2,
+ ) + '\n',
+ main: JSON.stringify(
{
schemaVersion: LEDGER_SCHEMA_VERSION,
installations: server,
@@ -463,15 +844,19 @@ export class PluginMarketLedger {
},
null,
2,
- )}\n`,
- );
+ ) + '\n',
+ };
atomicWriteFileSync(
- this.customFilePath(),
- `${JSON.stringify(
- { schemaVersion: LEDGER_SCHEMA_VERSION, installations: custom },
- null,
- 2,
- )}\n`,
+ this.pendingFilePath(),
+ JSON.stringify({ schemaVersion: LEDGER_SCHEMA_VERSION, targets }, null, 2) + '\n',
);
+ atomicWriteFileSync(this.nsFilePath(), targets.namespaced);
+ atomicWriteFileSync(this.customFilePath(), targets.custom);
+ atomicWriteFileSync(this.filePath(), targets.main);
+ try {
+ fs.unlinkSync(this.pendingFilePath());
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
}
}
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 059bc4a4e5..4a9a356030 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -7,6 +7,7 @@ import {
isGhostInstallApprovalToken,
type GhostManifest,
} from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
import {
isPluginMarketCustomIconKey,
type PluginMarketSnapshot,
@@ -207,7 +208,7 @@ export function registerPluginMarketIpc(): void {
const previouslyInstalled = new Set(
getGhostManager()
.list()
- .map((g) => g.manifest.id),
+ .map((g) => installedGhostStoragePart(g)),
);
return invokePluginMarket(async () => {
const result = await service().install(
@@ -228,10 +229,10 @@ export function registerPluginMarketIpc(): void {
);
if (
getActiveAppSession().generation === owner.generation &&
- !previouslyInstalled.has(result.ghost.manifest.id)
+ !previouslyInstalled.has(installedGhostStoragePart(result.ghost))
) {
try {
- markGhostRecommendationInstalled(result.ghost.manifest.id);
+ markGhostRecommendationInstalled(installedGhostStoragePart(result.ghost));
} catch {
log.warn('ghost recommendation install history unavailable');
}
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 53ceb4754a..71d9f6efeb 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -4,6 +4,7 @@ import crypto from 'node:crypto';
import {
isValidPluginResourceId,
+ isValidPluginNamespace,
PLUGIN_PREFIX_PATTERN,
type PluginCurrentOrganization,
type PluginRemovalNotice,
@@ -44,7 +45,7 @@ import {
PLUGIN_MARKET_CUSTOM_ICON_SOURCE_TOKEN_LENGTH,
pluginMarketCustomIconProjectionToken,
} from '../../shared/pluginMarket.js';
-import { getCurrentUserId } from '../authManager.js';
+import { getAuthState, getCurrentUserId } from '../authManager.js';
import {
getGhostManager,
hasPendingGhostCalls,
@@ -75,7 +76,23 @@ import {
import {
readInstalledGhostManifestSnapshot,
} from '../installedGhostManifest.js';
-import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';
+import {
+ withGhostInstallLock,
+ withPluginDeliveryInstallLock,
+} from '../cindy-brain/ghostInstallLock.js';
+import {
+ createPluginLogicalIdentity,
+ deliveryNamespaceFields,
+ downloadIdentityMatchesPlugin,
+ findInstalledGhostByIdentity,
+ findInstalledGhostByInstanceId,
+ hasDeliveryNamespace,
+ installedGhostPhysicalRelId,
+ installedGhostStoragePart,
+ knownDeliveryNamespacesDiffer,
+ pluginLedgerRecordKey,
+ sameDeliveryNamespaceState,
+} from '../../shared/pluginIdentity.js';
import { ghostBrokerRedirectPortInstallError } from '../cindy-brain/ghostBrokerRedirectPort.js';
import {
isGhostInstallConsentRequiredError,
@@ -198,6 +215,127 @@ function defaultInstallSubject(owner: ActiveAppSession): string {
return subject;
}
+function installedGhostMatchingMarketPlugin(plugin: {
+ ghostId: string;
+ namespace?: string | null;
+}): InstalledGhost | undefined {
+ if (!isValidGhostId(plugin.ghostId)) {
+ return getGhostManager().list().find((ghost) => ghost.manifest.id === plugin.ghostId);
+ }
+ return findInstalledGhostByIdentity(
+ getGhostManager().list(),
+ createPluginLogicalIdentity(
+ hasDeliveryNamespace(plugin) ? plugin.namespace : null,
+ plugin.ghostId,
+ ),
+ );
+}
+
+
+function snapshotInstallation(
+ local: { installations: Readonly<Record<string, PluginMarketInstallationRecord>> },
+ plugin: { ghostId: string; namespace?: string | null },
+): PluginMarketInstallationRecord | undefined {
+ return local.installations[pluginLedgerRecordKey(plugin)];
+}
+
+function removalIdentity(
+ removal: PluginRemovalNotice,
+ installations: Readonly<Record<string, PluginMarketInstallationRecord>>,
+): PluginRemovalNotice | null {
+ if (hasDeliveryNamespace(removal) || removal.scope !== 'organization') return removal;
+ const matches = Object.values(installations).filter((record) =>
+ typeof record.namespace === 'string' &&
+ record.pluginId === removal.pluginId &&
+ record.ghostId === removal.ghostId &&
+ record.scope === 'organization' &&
+ record.organizationId === removal.organizationId,
+ );
+ if (matches.length > 1) return null;
+ return matches.length === 1 ? { ...removal, namespace: matches[0]!.namespace } : removal;
+}
+
+function snapshotGhost(
+ local: LocalInstallSnapshot,
+ plugin: { ghostId: string; namespace?: string | null },
+): InstalledGhost | undefined {
+ const ghosts = local.ghostsById.get(plugin.ghostId) ?? [];
+ if (!isValidGhostId(plugin.ghostId)) {
+ return ghosts[0];
+ }
+ return findInstalledGhostByIdentity(
+ ghosts,
+ createPluginLogicalIdentity(
+ hasDeliveryNamespace(plugin) ? plugin.namespace : null,
+ plugin.ghostId,
+ ),
+ );
+}
+
+function snapshotManifestIdentity(
+ local: LocalInstallSnapshot,
+ ghost: InstalledGhost | undefined,
+): InstalledMarketManifestIdentity | null {
+ if (!ghost) return null;
+ return local.manifestIdentityByStoragePart.get(installedGhostStoragePart(ghost)) ?? null;
+}
+
+function legacyOrganizationDeliveryTarget<T extends VisiblePluginSummary | VisiblePluginDetail>(
+ plugin: T,
+ local: LocalInstallSnapshot,
+): T {
+ if (hasDeliveryNamespace(plugin) || plugin.scope !== 'organization') return plugin;
+ const ghosts = local.ghostsById.get(plugin.ghostId) ?? [];
+ const records = local.installedRecordsByGhostId.get(plugin.ghostId) ?? [];
+ const matches = records.flatMap((record) => {
+ if (
+ !hasDeliveryNamespace(record) || record.namespace === null ||
+ (record.rawManifestSha256 === undefined && record.manifestDigest === undefined) ||
+ !serverRecordMatchesSummaryRoute(plugin, record)
+ ) return [];
+ return ghosts.filter((ghost) =>
+ hasDeliveryNamespace(ghost) && ghost.namespace === record.namespace &&
+ installedGhostPhysicalRelId(ghost) === plugin.ghostId &&
+ serverRecordMatchesInstalledGhost(plugin.id, ghost, record, snapshotManifestIdentity(local, ghost)),
+ );
+ });
+ if (matches.length !== 1) return plugin;
+ return { ...plugin, namespace: matches[0]!.namespace };
+}
+
+function trustedOrganizationNamespace(
+ plugin: VisiblePluginSummary | VisiblePluginDetail,
+ owner: ActiveAppSession,
+): string | undefined {
+ const auth = getAuthState();
+ if (
+ owner.mode !== 'cloud' || isAppSessionBoundaryPending() ||
+ !auth.isAuthenticated || auth.mode !== owner.mode ||
+ auth.dataOwnerId !== owner.dataOwnerId || auth.ownerGeneration !== owner.generation ||
+ auth.user?.membershipKind !== 'org' || auth.user.orgId !== plugin.organizationId ||
+ !isValidPluginNamespace(auth.user.orgSlug)
+ ) return undefined;
+ return auth.user.orgSlug;
+}
+
+function organizationDeliveryTarget<T extends VisiblePluginSummary | VisiblePluginDetail>(
+ plugin: T,
+ local: LocalInstallSnapshot,
+ owner = getActiveAppSession(),
+): T {
+ const target = legacyOrganizationDeliveryTarget(plugin, local);
+ if (hasDeliveryNamespace(target) || target.scope !== 'organization' ||
+ local.ghosts.some((ghost) => ghost.manifest.id === target.ghostId && !hasDeliveryNamespace(ghost))) {
+ return target;
+ }
+ const namespace = trustedOrganizationNamespace(target, owner);
+ if (namespace === undefined) return target;
+ const resolved = { ...target, namespace };
+ const installed = snapshotGhost(local, resolved);
+ if (installed && installedGhostPhysicalRelId(installed) === target.ghostId) return target;
+ return resolved;
+}
+
function recordFrom(
plugin: VisiblePluginSummary | VisiblePluginDetail,
source: PluginMarketInstallationRecord['source'],
@@ -216,6 +354,7 @@ function recordFrom(
updatedAt: new Date().toISOString(),
manifestDigest: identity.legacyManifestDigest,
rawManifestSha256: identity.rawManifestSha256,
+ ...deliveryNamespaceFields(plugin),
};
}
@@ -229,6 +368,7 @@ function assertDetailMatchesSummary(
detail.ghostId !== summary.ghostId ||
detail.scope !== summary.scope ||
detail.organizationId !== summary.organizationId ||
+ !sameDeliveryNamespaceState(detail, summary) ||
detail.defaultInstall !== summary.defaultInstall ||
detail.currentRelease.id !== summary.currentRelease.id ||
detail.currentRelease.version !== summary.currentRelease.version ||
@@ -265,17 +405,31 @@ export function organizationDefaultTakeoverEligibility(
!summary.defaultInstall ||
summary.scope !== 'organization' ||
!currentOrganization ||
- summary.organizationId !== currentOrganization.organizationId ||
- typeof prefix !== 'string' ||
- !PLUGIN_PREFIX_PATTERN.test(prefix) ||
- !summary.ghostId.startsWith(`${prefix}-`)
+ summary.organizationId !== currentOrganization.organizationId
) {
return { eligible: false, reason: 'not-current-organization-default' };
}
- if (!facts.uniqueGhostId) return { eligible: false, reason: 'duplicate-ghost-id' };
+ if (facts.record && knownDeliveryNamespacesDiffer(summary, facts.record)) {
+ return { eligible: false, reason: 'cross-namespace' };
+ }
+ if (hasDeliveryNamespace(summary)) {
+ if (typeof summary.namespace !== 'string' || !isValidPluginNamespace(summary.namespace) ||
+ (currentOrganization.orgSlug !== undefined && currentOrganization.orgSlug !== summary.namespace) ||
+ !hasDeliveryNamespace(installed) || installed.namespace !== summary.namespace) {
+ return { eligible: false, reason: 'cross-namespace' };
+ }
+ } else if (hasDeliveryNamespace(installed) || typeof prefix !== 'string' ||
+ !PLUGIN_PREFIX_PATTERN.test(prefix) || !summary.ghostId.startsWith(`${prefix}-`)) {
+ return { eligible: false, reason: 'not-current-organization-default' };
+ }
+ if (!facts.uniqueGhostId && !hasDeliveryNamespace(summary)) {
+ return { eligible: false, reason: 'duplicate-ghost-id' };
+ }
if (!facts.runtimeAvailable) return { eligible: false, reason: 'runtime-unavailable' };
if (facts.optedOut) return { eligible: false, reason: 'explicit-opt-out' };
- if (facts.builtinRemoved) return { eligible: false, reason: 'builtin-tombstone' };
+ if (facts.builtinRemoved && summary.namespace == null) {
+ return { eligible: false, reason: 'builtin-tombstone' };
+ }
if (facts.busy) return { eligible: false, reason: 'busy' };
if (installed.approval.state !== 'approved') {
return { eligible: false, reason: 'unapproved-install' };
@@ -320,6 +474,7 @@ function legacyRecordFrom(
updatedAt: new Date().toISOString(),
manifestDigest: identity.legacyManifestDigest,
rawManifestSha256: identity.rawManifestSha256,
+ ...deliveryNamespaceFields(plugin),
};
}
@@ -331,11 +486,13 @@ function ghostIdCounts(plugins: readonly VisiblePluginSummary[]): Map<string, nu
return counts;
}
-function isGhostBusy(ghostId: string): boolean {
+function isGhostBusy(plugin: { ghostId: string; namespace?: string | null }): boolean {
+ const ghost = installedGhostMatchingMarketPlugin(plugin);
+ const runtimeId = ghost ? installedGhostStoragePart(ghost) : plugin.ghostId;
return (
- hasPendingGhostCalls(ghostId) ||
- hasRunningGhostErrand(ghostId) ||
- hasRunningGhostCindyWork(ghostId)
+ hasPendingGhostCalls(runtimeId) ||
+ hasRunningGhostErrand(runtimeId) ||
+ hasRunningGhostCindyWork(runtimeId)
);
}
@@ -542,7 +699,8 @@ function serverRecordMatchesSummaryRoute(
record.pluginId === plugin.id &&
record.ghostId === plugin.ghostId &&
record.scope === plugin.scope &&
- record.organizationId === plugin.organizationId,
+ record.organizationId === plugin.organizationId &&
+ !knownDeliveryNamespacesDiffer(record, plugin),
);
}
@@ -553,6 +711,8 @@ function canBackfillOfficialCindyGithubTrust(
return (
record.installed &&
record.source === 'market' &&
+ record.scope === 'public' &&
+ record.namespace == null &&
record.manifestDigest !== undefined &&
installed.approval.state === 'approved' &&
(!isCindyOfficialTrustInfo(installed.trust) || !hasCindyOfficialTrustMetadata(installed.dir)) &&
@@ -598,21 +758,36 @@ function sameDisconnectedMarketInstallation(
/** Stable local facts reused while projecting one market catalog response. */
interface LocalInstallSnapshot {
- /** Installed Ghost runtime facts indexed once for one market operation. */
- ghostsById: ReadonlyMap<string, InstalledGhost>;
+ /** Installed Ghost runtime facts for one market operation. */
+ ghosts: readonly InstalledGhost[];
+ ghostsById: ReadonlyMap<string, readonly InstalledGhost[]>;
/** Parsed provenance records from one ledger read. */
installations: Readonly<Record<string, PluginMarketInstallationRecord>>;
- /** 每个已装插件的 locale 无关 Manifest 身份(一次快照只读一遍盘)。 */
- manifestIdentityByGhostId: ReadonlyMap<string, InstalledMarketManifestIdentity | null>;
+ installedRecordsByGhostId: ReadonlyMap<string, readonly PluginMarketInstallationRecord[]>;
+ /** locale 无关 Manifest 身份,按实例 storage part 索引。 */
+ manifestIdentityByStoragePart: ReadonlyMap<string, InstalledMarketManifestIdentity | null>;
}
/** 未登录浏览公开目录时不读本机账本 / 已装列表,避免带出上一账号的安装态。 */
const EMPTY_LOCAL_INSTALL_SNAPSHOT: LocalInstallSnapshot = {
+ ghosts: [],
ghostsById: new Map(),
installations: {},
- manifestIdentityByGhostId: new Map(),
+ installedRecordsByGhostId: new Map(),
+ manifestIdentityByStoragePart: new Map(),
};
+function indexByGhostId<T>(items: readonly T[], ghostId: (item: T) => string): Map<string, T[]> {
+ const indexed = new Map<string, T[]>();
+ for (const item of items) {
+ const id = ghostId(item);
+ const matches = indexed.get(id) ?? [];
+ matches.push(item);
+ indexed.set(id, matches);
+ }
+ return indexed;
+}
+
/**
* 清理通告 pending 汇总的 owner 隔离键。**故意不含 generation**:同一 owner
* 重新登录(换代)后,未消费的通知仍应展示,不随会话代际作废。
@@ -827,6 +1002,9 @@ export class PluginMarketService {
};
if (!options.discoveryOnly && !options.deferReconciliation) await reconcileCustomUpdates();
requireSameMarketOwner(owner);
+ if (!options.discoveryOnly) {
+ getGhostManager().resumePendingResidentsOffline?.();
+ }
const snapshot: PluginMarketSnapshot = {
items: this.withUpdateConsentHolds(
this.projectCustomItems(customDiscovery.entries, this.localInstallSnapshot(ledger)),
@@ -886,6 +1064,14 @@ export class PluginMarketService {
await this.backfillInstalledManifestIdentities(ledger, owner);
await this.adoptLegacyInstallations(plugins, ledger, owner);
await this.recoverDisconnectedMarketInstallations(plugins, ledger, owner);
+ ledger.backfillMissingNamespacesFromCatalog(plugins);
+ try {
+ await getGhostManager().reconcilePendingRootNamespaces?.(true);
+ } catch (error) {
+ log.warn('namespace migration market reconcile failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
await this.backfillOfficialCindyGithubTrust(ledger, owner);
// A snapshot is passive discovery: an empty runtime list can be caused by
// startup, an owner transition, or a transient filesystem view. Only an
@@ -1268,9 +1454,8 @@ export class PluginMarketService {
if (plugin.currentRelease.id !== options.expectedReleaseId) {
throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
}
- const existing = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ const target = organizationDeliveryTarget(plugin, this.localInstallSnapshot(ledger), owner);
+ const existing = installedGhostMatchingMarketPlugin(target);
return this.installDetail(
plugin,
{
@@ -1314,7 +1499,14 @@ export class PluginMarketService {
}
const installSubject = defaultInstallSubject(owner);
requireSameMarketOwner(owner);
- await uninstallGhostAndCleanup(record.ghostId, { skipMarketLedger: true });
+ const installed = installedGhostMatchingMarketPlugin(record);
+ // Instance missing: only close this ledger row. A bare ghostId fallback
+ // would uninstall a coexisting public sibling.
+ if (installed) {
+ await uninstallGhostAndCleanup(installedGhostPhysicalRelId(installed), {
+ skipMarketLedger: true,
+ });
+ }
// The package removal is already complete at this point. The session may
// have changed while the runtime was stopping, so ledger reconciliation
// must not turn a successful uninstall into an IPC failure. The ledger
@@ -1322,7 +1514,7 @@ export class PluginMarketService {
// serialized separately from the active-session check.
try {
await this.withCapturedLedgerMutation(ledger, () => {
- ledger.markRemoved(record.ghostId, installSubject);
+ ledger.markRemovedRecord(record, installSubject);
});
} catch (error) {
log.warn('market uninstall ledger reconciliation deferred', {
@@ -1338,7 +1530,7 @@ export class PluginMarketService {
* Captures the active owner and ledger before a local-page uninstall starts.
* The returned completion records opt-out only after the package was removed.
*/
- prepareLocalUninstallTracking(ghostId: string): (() => Promise<void>) | null {
+ prepareLocalUninstallTracking(target: string | InstalledGhost): (() => Promise<void>) | null {
let owner: ActiveAppSession;
try {
owner = captureMarketOwner();
@@ -1346,12 +1538,23 @@ export class PluginMarketService {
return null;
}
const ledger = this.ledgerForOwner(owner);
- const record = ledger.installationForGhost(ghostId);
- if (!record?.installed) return null;
+ const ghost = typeof target === 'string'
+ ? findInstalledGhostByInstanceId(getGhostManager().list(), target)
+ : target;
+ if (!ghost) return null;
+ const record = ledger.installationForLocalUninstall({
+ ghostId: ghost.manifest.id,
+ ...deliveryNamespaceFields(ghost),
+ });
+ if (!record) return null;
+ const identity = readInstalledMarketManifestIdentity(ghost.dir);
+ if (!identity || !verifyInstalledMarketManifest(record, identity, {
+ allowLegacyRecordWithoutDigest: true,
+ })) return null;
const installSubject = defaultInstallSubject(owner);
return async () => {
await this.withCapturedLedgerMutation(ledger, () => {
- ledger.markRemoved(ghostId, installSubject);
+ ledger.markRemovedRecordIfUnchanged(record, installSubject);
});
};
}
@@ -1507,11 +1710,9 @@ export class PluginMarketService {
if (releaseId !== options.expectedReleaseId) {
throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
}
- const existing = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ const existing = installedGhostMatchingMarketPlugin(plugin);
const sourceKey = marketSourceKey(discovered.config.source);
- const currentRecord = ledger.installationForGhost(plugin.ghostId);
+ const currentRecord = ledger.installationForPlugin(plugin);
// 选择时刻的已装 Manifest 身份:打包窗口内不能换掉当前包。raw 字段
// 存在时只认原始字节;旧记录由集中 legacy adapter 兼容核对。
const reviewInstalledIdentity = existing
@@ -1579,15 +1780,14 @@ export class PluginMarketService {
let replacedRoute: PluginMarketInstallationRecord | null = null;
let replacedRouteWasSuppressed = false;
let packageLanded = false;
+ let sourceChanged = false;
requireSameMarketOwner(owner);
const consentDecision: GhostInstallConsentDecision =
'rejection' in packed.inspected
? { mode: 'unprompted' }
: await obtainGhostInstallConsent(
consent,
- getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId),
+ installedGhostMatchingMarketPlugin(plugin),
packed.inspected.manifest,
packed.inspected.packageSha256,
);
@@ -1595,10 +1795,11 @@ export class PluginMarketService {
expectedGhostId: plugin.ghostId,
expectedVersion: plugin.version,
consent: consentDecision,
+ sourceChanged: () => sourceChanged,
beforeCommit: async () => {
requireSameMarketOwner(owner);
assertCurrent?.();
- if (automatic && isGhostBusy(plugin.ghostId)) {
+ if (automatic && isGhostBusy(plugin)) {
throw new SilentUpgradeBusyError('Plugin is busy');
}
// 所选来源必须**仍然存在且仍是同一个来源**:移除来源会先拿
@@ -1617,9 +1818,7 @@ export class PluginMarketService {
// 会把"更新"降级成"首装+带电启用";反向地,窗口内新装入的同 id
// 本地 .cindy 会被更新分支静默覆盖。判据与选择时刻同一份:
// 在场状态一致 + 已装内容摘要未变。
- const current = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ const current = installedGhostMatchingMarketPlugin(plugin);
if (Boolean(current) !== Boolean(existing)) {
throwIpcError(
'PRECONDITION_FAILED',
@@ -1644,15 +1843,23 @@ export class PluginMarketService {
}
// raw manifest 摘要不含 Host receipt;内容未变但批准态变化也必须拒绝。
assertCustomApprovalStateUnchanged(current ?? null);
+ const record = ledger.installationForPlugin(plugin);
+ const routeStillMatches = Boolean(current && record?.installed &&
+ record.pluginId === pluginId && record.sourceKey === sourceKey &&
+ currentIdentity && verifyInstalledMarketManifest(record, currentIdentity));
+ if (current && !routeStillMatches && options.allowSourceReplacement !== true) {
+ throwIpcError('PRECONDITION_FAILED', 'Installed Plugin source changed');
+ }
+ sourceChanged = Boolean(current && !routeStillMatches);
},
expectedInstalledApproval: options.expectedInstalledApproval,
beforePackagePlacement: () => {
requireSameMarketOwner(owner);
assertCurrent?.();
- if (automatic && isGhostBusy(plugin.ghostId)) {
+ if (automatic && isGhostBusy(plugin)) {
throw new SilentUpgradeBusyError('Plugin is busy');
}
- const record = ledger.installationForGhost(plugin.ghostId);
+ const record = ledger.installationForPlugin(plugin);
const routeStillMatches = Boolean(
existing &&
record?.installed &&
@@ -1684,7 +1891,9 @@ export class PluginMarketService {
// 同 id 的本地装入/卸载插不进来(否则复核仍会在落位前过期)。
withCommitLock: (fn) =>
this.withMutation(customMarketPluginId(ref.marketName, ref.ghostId), () =>
- this.withMutation(SOURCE_MUTATION_KEY, () => withGhostInstallLock(plugin.ghostId, fn)),
+ this.withMutation(SOURCE_MUTATION_KEY, () =>
+ withPluginDeliveryInstallLock({ ghostId: plugin.ghostId, namespace: null }, fn),
+ ),
),
// 溯源写入仍在上面那把 ghost 锁内(afterCommit 由 commit 段调用):
// 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。
@@ -1707,6 +1916,7 @@ export class PluginMarketService {
sha256: 'custom-unverified',
scope: 'public',
organizationId: null,
+ namespace: null,
source: sourceType === 'git' ? 'git-market' : 'local-market',
installed: true,
updatedAt: new Date().toISOString(),
@@ -1865,9 +2075,9 @@ export class PluginMarketService {
const { config, plugin } = entry;
const pluginId = customMarketPluginId(config.name, plugin.ghostId);
const releaseId = customMarketReleaseId(config.name, plugin.ghostId, plugin.version);
- const ghost = local.ghostsById.get(plugin.ghostId);
- const record = local.installations[plugin.ghostId];
- const identity = local.manifestIdentityByGhostId.get(plugin.ghostId) ?? null;
+ const ghost = snapshotGhost(local, plugin);
+ const record = snapshotInstallation(local, plugin);
+ const identity = snapshotManifestIdentity(local, ghost);
// pluginId + 来源指纹 + 安装时 manifest 摘要全部对上时,
// 该条目才是当前自动更新路由。其它同 id 条目仍可被用户显式选择替换。
const matchesUpdateRoute = Boolean(
@@ -1892,6 +2102,7 @@ export class PluginMarketService {
return {
pluginId,
ghostId: plugin.ghostId,
+ namespace: null,
// ghost.json 来自不受信市场仓库:双向控制符可把市场卡片上的署名/说明
// 显示成另一副样子(视觉欺骗),控制字符可撑破布局。展示投影一律剥掉
// (保留换行);市场名闸在 discover,这里补齐插件侧同一口径。
@@ -1974,6 +2185,26 @@ export class PluginMarketService {
ledger = this.ledgerForOwner(owner),
): Promise<PluginMarketInstallResult> {
requireSameMarketOwner(owner);
+ const serverPlugin = plugin;
+ const local = this.localInstallSnapshot(ledger);
+ const legacyTarget = legacyOrganizationDeliveryTarget(plugin, local);
+ plugin = organizationDeliveryTarget(plugin, local, owner);
+ const namespaceFromLogin = !hasDeliveryNamespace(legacyTarget) && hasDeliveryNamespace(plugin);
+ if (
+ plugin === serverPlugin && plugin.scope === 'organization' &&
+ !hasDeliveryNamespace(plugin) &&
+ (!local.ghosts.some((ghost) => ghost.manifest.id === plugin.ghostId && !hasDeliveryNamespace(ghost)) ||
+ local.ghosts.some((ghost) => ghost.manifest.id === plugin.ghostId &&
+ hasDeliveryNamespace(ghost) && ghost.namespace !== null))
+ ) {
+ throwIpcError('PRECONDITION_FAILED', 'Organization Plugin namespace is unavailable');
+ }
+ const assertInstallIdentityCurrent = (): void => {
+ requireSameMarketOwner(owner);
+ if (namespaceFromLogin && trustedOrganizationNamespace(serverPlugin, owner) !== plugin.namespace) {
+ throwIpcError('PRECONDITION_FAILED', 'Organization Plugin identity changed during the install');
+ }
+ };
if (owner.mode === 'local' && plugin.scope !== 'public') {
throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');
}
@@ -1985,10 +2216,8 @@ export class PluginMarketService {
if (brokerPortError) {
throwIpcError(brokerPortError.code, brokerPortError.reason);
}
- const existing = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId);
- const currentRecord = ledger.installationForGhost(plugin.ghostId);
+ const existing = installedGhostMatchingMarketPlugin(plugin);
+ const currentRecord = ledger.installationForPlugin(plugin);
const sourceReplacementMode = options.sourceReplacementMode ?? 'preserve-existing-source';
if (
sourceReplacementMode === 'organization-default-takeover' &&
@@ -2024,10 +2253,11 @@ export class PluginMarketService {
}
const download = await this.api.download(plugin.id, plugin.currentRelease.id);
- requireSameMarketOwner(owner);
+ assertInstallIdentityCurrent();
if (
download.sha256 !== plugin.currentRelease.sha256 ||
- download.sizeBytes !== plugin.currentRelease.sizeBytes
+ download.sizeBytes !== plugin.currentRelease.sizeBytes ||
+ !downloadIdentityMatchesPlugin(download, serverPlugin)
) {
throwIpcError('PRECONDITION_FAILED', 'Plugin release metadata changed');
}
@@ -2059,9 +2289,7 @@ export class PluginMarketService {
? { mode: 'unprompted' }
: await obtainGhostInstallConsent(
options.consent,
- getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId),
+ installedGhostMatchingMarketPlugin(plugin),
inspected.manifest,
inspected.packageSha256,
);
@@ -2077,7 +2305,12 @@ export class PluginMarketService {
? { expectedInstalledApproval: options.expectedInstalledApproval }
: {}),
sourceReplacementMode,
- beforeCommitInLock: options.beforeCommitInLock,
+ beforeCommitInLock: namespaceFromLogin
+ ? () => {
+ assertInstallIdentityCurrent();
+ options.beforeCommitInLock?.();
+ }
+ : options.beforeCommitInLock,
},
owner,
ledger,
@@ -2108,11 +2341,9 @@ export class PluginMarketService {
owner: ActiveAppSession,
ledger: PluginMarketLedger,
): Promise<InstalledGhost> {
- return withGhostInstallLock(plugin.ghostId, async () => {
- const installedNow = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === plugin.ghostId);
- const currentRecordNow = ledger.installationForGhost(plugin.ghostId);
+ return withPluginDeliveryInstallLock(plugin, async () => {
+ const installedNow = installedGhostMatchingMarketPlugin(plugin);
+ const currentRecordNow = ledger.installationForPlugin(plugin);
if (Boolean(installedNow) !== options.expectedInstalled) {
if (options.sourceReplacementMode === 'organization-default-takeover') {
throw new SilentOrganizationDefaultTakeoverSupersededError(
@@ -2155,19 +2386,22 @@ export class PluginMarketService {
}
}
requireSameMarketOwner(owner);
- const replacingSource = Boolean(
+ const sourceChanged = Boolean(
installedNow &&
- options.sourceReplacementMode === 'user-requested-source-change' &&
- currentRecordNow?.installed &&
+ (options.sourceReplacementMode === 'user-requested-source-change' ||
+ options.sourceReplacementMode === 'organization-default-takeover') &&
!serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow),
);
+ const replacingSource = sourceChanged &&
+ options.sourceReplacementMode === 'user-requested-source-change' &&
+ currentRecordNow?.installed === true;
let routeDetached = false;
let replacedRouteWasSuppressed = false;
let packageLanded = false;
const detachPreviousRoute = (): void => {
requireSameMarketOwner(owner);
options.beforeCommitInLock?.();
- if (!replacingSource || !currentRecordNow) return;
+ if (!replacingSource || !currentRecordNow?.installed) return;
replacedRouteWasSuppressed = this.detachMarketRouteForReplacement(
ledger,
currentRecordNow,
@@ -2177,20 +2411,20 @@ export class PluginMarketService {
};
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: plugin.ghostId,
+ pluginId: plugin.id,
version: plugin.currentRelease.version,
consent: options.consent,
- ...(plugin.ghostId === 'cindy-github' ? { officialCindyGithub: true } : {}),
- ...(plugin.scope === 'organization' && plugin.organizationId
- ? {
- pendingMarketRecord: {
- scope: plugin.scope,
- organizationId: plugin.organizationId,
- source: 'market',
- installed: true,
- sha256: plugin.currentRelease.sha256,
- },
- }
- : {}),
+ ...(sourceChanged ? { sourceChanged: true } : {}),
+ ...deliveryNamespaceFields(plugin),
+ ...(plugin.ghostId === 'cindy-github' && plugin.scope === 'public' &&
+ plugin.namespace == null ? { officialCindyGithub: true } : {}),
+ pendingMarketRecord: {
+ scope: plugin.scope,
+ organizationId: plugin.organizationId ?? null,
+ source: 'market',
+ installed: true,
+ sha256: plugin.currentRelease.sha256,
+ },
...(options.expectedInstalledApproval !== undefined
? { expectedInstalledApproval: options.expectedInstalledApproval }
: {}),
@@ -2237,20 +2471,23 @@ export class PluginMarketService {
}
}
- private toItem(
+ private serverMarketBinding(
plugin: VisiblePluginSummary,
- local = this.localInstallSnapshot(),
- ): PluginMarketItem {
- const ghost = local.ghostsById.get(plugin.ghostId);
- const record = local.installations[plugin.ghostId];
- const identity = local.manifestIdentityByGhostId.get(plugin.ghostId) ?? null;
+ local: LocalInstallSnapshot,
+ ) {
+ const target = organizationDeliveryTarget(plugin, local);
+ const ghost = snapshotGhost(local, target);
+ const record = snapshotInstallation(local, target);
+ const identity = snapshotManifestIdentity(local, ghost);
const matchesUpdateRoute = Boolean(
ghost
&& serverRecordMatchesInstalledGhost(plugin.id, ghost, record ?? null, identity)
&& serverRecordMatchesSummaryRoute(plugin, record ?? null),
);
- // 其它同 id 条目不进入自动更新,但仍可由用户显式选择替换。
- const conflict = Boolean(ghost && !matchesUpdateRoute);
+ const conflict = Boolean((ghost && !matchesUpdateRoute) ||
+ (!hasDeliveryNamespace(plugin) && plugin.scope === 'organization' &&
+ local.ghosts.some((candidate) => candidate.manifest.id === plugin.ghostId &&
+ hasDeliveryNamespace(candidate) && candidate.namespace !== null) && target === plugin));
const installState: PluginMarketItem['installState'] = conflict
? 'conflict'
: !matchesUpdateRoute
@@ -2258,9 +2495,22 @@ export class PluginMarketService {
: record?.releaseId === plugin.currentRelease.id
? 'installed'
: 'update-available';
+ const projectedTarget = matchesUpdateRoute && !hasDeliveryNamespace(target) &&
+ target.scope !== 'organization' && ghost && hasDeliveryNamespace(ghost) && ghost.namespace === null
+ ? { ...target, namespace: null }
+ : target;
+ return { target: projectedTarget, ghost, record, matchesUpdateRoute, installState };
+ }
+
+ private toItem(
+ plugin: VisiblePluginSummary,
+ local = this.localInstallSnapshot(),
+ ): PluginMarketItem {
+ const { target, ghost, matchesUpdateRoute, installState } = this.serverMarketBinding(plugin, local);
return {
pluginId: plugin.id,
ghostId: plugin.ghostId,
+ ...deliveryNamespaceFields(target),
name: plugin.name,
description: plugin.description,
author: plugin.author,
@@ -2295,18 +2545,16 @@ export class PluginMarketService {
await this.withMutation(candidate.pluginId, () =>
withGhostInstallLock(candidate.ghostId, async () => {
requireSameMarketOwner(owner);
- const record = ledger.installationForGhost(candidate.ghostId);
+ const record = ledger.installationForPlugin(candidate);
if (!record?.installed || record.rawManifestSha256 !== undefined) return;
- const installed = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === record.ghostId);
+ const installed = installedGhostMatchingMarketPlugin(record);
if (!installed) return;
const identity = readInstalledMarketManifestIdentity(installed.dir);
if (!identity) return;
const isServerRecord = record.source === 'market' || record.source === 'legacy-adopted';
const manager = getGhostManager();
- const approvalEvidence = manager.approvedInstallEvidence?.(record.ghostId) ?? null;
+ const approvalEvidence = manager.approvedInstallEvidence?.(installedGhostPhysicalRelId(installed)) ?? null;
// Pending or failed mutation recovery is projected as invalid. Never
// mint a baseline from that intermediate directory for any source.
if (installed.approval.state === 'invalid') return;
@@ -2371,34 +2619,47 @@ export class PluginMarketService {
const counts = ghostIdCounts(plugins);
const installations = ledger.read().installations;
for (const ghost of getGhostManager().list()) {
- if (installations[ghost.manifest.id]) continue;
+ if (installations[pluginLedgerRecordKey({
+ ghostId: ghost.manifest.id,
+ ...deliveryNamespaceFields(ghost),
+ })]) continue;
if (!isOfficialGhostId(ghost.manifest.id)) continue;
const matches = plugins.filter(
(plugin) =>
counts.get(plugin.ghostId) === 1 &&
plugin.scope !== 'personal' &&
- plugin.ghostId === ghost.manifest.id,
+ plugin.ghostId === ghost.manifest.id &&
+ !knownDeliveryNamespacesDiffer(plugin, ghost),
);
if (matches.length !== 1) continue;
const plugin = matches[0];
await this.withMutation(plugin.id, () =>
withGhostInstallLock(ghost.manifest.id, async () => {
requireSameMarketOwner(owner);
- if (ledger.installationForGhost(ghost.manifest.id)) return;
- const currentGhost = getGhostManager()
- .list()
- .find((candidate) => candidate.manifest.id === ghost.manifest.id);
- if (!currentGhost) return;
+ if (ledger.installationForPlugin({
+ ghostId: ghost.manifest.id,
+ ...deliveryNamespaceFields(ghost),
+ })) return;
+ const currentGhost = installedGhostMatchingMarketPlugin({
+ ghostId: ghost.manifest.id,
+ ...deliveryNamespaceFields(ghost),
+ });
+ if (!currentGhost || knownDeliveryNamespacesDiffer(plugin, currentGhost)) return;
+ const manager = getGhostManager();
+ const physicalId = installedGhostPhysicalRelId(currentGhost);
+ const evidence = manager.approvedInstallEvidence(physicalId);
+ if (!evidence?.legacyMigrated || evidence.packageSha256 !== null) return;
+ if (manager.readApprovedInstallOriginStrict(physicalId) === 'agent-forge') return;
const identity = readInstalledMarketManifestIdentity(currentGhost.dir);
- if (!identity) return;
+ if (!identity || !installedIdentityMatchesManifest(identity, evidence.approvedManifest)) return;
const record = legacyRecordFrom(plugin, currentGhost, identity);
const adopted = await this.withLedgerMutation(owner, () => {
- if (ledger.installationForGhost(record.ghostId)) return false;
+ if (ledger.installationForPlugin(record)) return false;
ledger.upsertInstallation(record);
return true;
});
if (!adopted) return;
- installations[record.ghostId] = record;
+ installations[pluginLedgerRecordKey(record)] = record;
log.info('legacy plugin adopted into market ledger', {
ghostId: ghost.manifest.id,
pluginId: plugin.id,
@@ -2427,8 +2688,11 @@ export class PluginMarketService {
): Promise<void> {
const pluginIdCounts = new Map<string, number>();
const ghostCounts = ghostIdCounts(plugins);
+ const identityCounts = new Map<string, number>();
for (const plugin of plugins) {
pluginIdCounts.set(plugin.id, (pluginIdCounts.get(plugin.id) ?? 0) + 1);
+ const key = pluginLedgerRecordKey(plugin);
+ identityCounts.set(key, (identityCounts.get(key) ?? 0) + 1);
}
const summariesById = new Map(plugins.map((plugin) => [plugin.id, plugin]));
const records = Object.values(ledger.read().installations);
@@ -2444,18 +2708,30 @@ export class PluginMarketService {
!isValidGhostId(record.ghostId) ||
!/^[a-f0-9]{64}$/.test(record.sha256) ||
pluginIdCounts.get(record.pluginId) !== 1 ||
- ghostCounts.get(record.ghostId) !== 1 ||
!summary ||
+ (ghostCounts.get(record.ghostId) !== 1 &&
+ !(hasDeliveryNamespace(record) && hasDeliveryNamespace(summary) &&
+ identityCounts.get(pluginLedgerRecordKey(record)) === 1)) ||
summary.ghostId !== record.ghostId ||
+ knownDeliveryNamespacesDiffer(summary, record) ||
summary.scope !== record.scope ||
summary.organizationId !== record.organizationId
) {
continue;
}
- const installed = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === record.ghostId);
+ const findRecoveryCandidate = (): InstalledGhost | undefined => {
+ const installed = installedGhostMatchingMarketPlugin(record);
+ if (installed) return installed;
+ const lookup = ledger.lookupInstallationsForNamespaceMigration(record.ghostId);
+ if (lookup.kind !== 'found' || lookup.records.length !== 1) return undefined;
+ const candidates = getGhostManager().list().filter((ghost) =>
+ ghost.manifest.id === record.ghostId && !hasDeliveryNamespace(ghost) &&
+ installedGhostPhysicalRelId(ghost) === record.ghostId,
+ );
+ return candidates.length === 1 ? candidates[0] : undefined;
+ };
+ const installed = findRecoveryCandidate();
if (!installed || installed.approval.state !== 'approved') continue;
try {
@@ -2463,11 +2739,9 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
await withGhostInstallLock(record.ghostId, async () => {
requireSameMarketOwner(owner);
- const lockedRecord = ledger.installationForGhost(record.ghostId);
+ const lockedRecord = ledger.installationForPlugin(record);
if (!sameDisconnectedMarketInstallation(lockedRecord, record)) return;
- const currentInstalled = getGhostManager()
- .list()
- .find((ghost) => ghost.manifest.id === record.ghostId);
+ const currentInstalled = findRecoveryCandidate();
if (
!currentInstalled ||
currentInstalled.approval.state !== 'approved' ||
@@ -2475,7 +2749,7 @@ export class PluginMarketService {
) {
return;
}
- const approvalEvidence = getGhostManager().approvedInstallEvidence(record.ghostId);
+ const approvalEvidence = getGhostManager().approvedInstallEvidence(installedGhostPhysicalRelId(currentInstalled));
if (!approvalEvidence) return;
if (
approvalEvidence.packageSha256 !== null &&
@@ -2575,11 +2849,12 @@ export class PluginMarketService {
ledger: PluginMarketLedger,
owner: ActiveAppSession,
): Promise<void> {
- const record = ledger.installationForGhost('cindy-github');
+ const record = ledger.installationForPlugin({ namespace: null, ghostId: 'cindy-github' });
requireSameMarketOwner(owner);
const installed = getGhostManager()
.list()
- .find((ghost) => ghost.manifest.id === 'cindy-github');
+ .find((ghost) => ghost.manifest.id === 'cindy-github' && ghost.namespace == null &&
+ ghost.namespaceState !== 'pending');
if (!record || !installed || !canBackfillOfficialCindyGithubTrust(record, installed)) return;
const tempPath = path.join(
app.getPath('temp'),
@@ -2601,10 +2876,11 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
await withGhostInstallLock('cindy-github', async () => {
requireSameMarketOwner(owner);
- const currentRecord = ledger.installationForGhost('cindy-github');
+ const currentRecord = ledger.installationForPlugin({ namespace: null, ghostId: 'cindy-github' });
const currentInstalled = getGhostManager()
.list()
- .find((ghost) => ghost.manifest.id === 'cindy-github');
+ .find((ghost) => ghost.manifest.id === 'cindy-github' && ghost.namespace == null &&
+ ghost.namespaceState !== 'pending');
if (
!currentRecord?.installed ||
currentRecord.source !== 'market' ||
@@ -2671,6 +2947,7 @@ export class PluginMarketService {
): string | null => {
if (!record) return 'ledger-record-missing';
if (record.pluginId !== removal.pluginId) return 'plugin-id-mismatch';
+ if (record.organizationId !== removal.organizationId) return 'organization-id-mismatch';
if (record.source !== 'market' && record.source !== 'legacy-adopted') {
return 'non-server-source';
}
@@ -2682,14 +2959,19 @@ export class PluginMarketService {
// runtime 在场判定与取名共用一次目录扫描(list 会读每个包的 manifest 与
// 图标),首个幸存候选时才建;清理会改目录,但每条清理都在自己的互斥段里
// 由账本复检把关,这张表只回答"清理前它在不在场、叫什么"。
- let ghostsById: Map<string, InstalledGhost> | null = null;
+ let removalGhosts: InstalledGhost[] | null = null;
const removedNames: Array<string | null> = [];
for (const removal of removals) {
if (removal.action !== 'purge') {
skip(removal, 'unsupported-action');
continue;
}
- const prefilterReason = ledgerGateReason(snapshot[removal.ghostId], removal);
+ const prefilterIdentity = removalIdentity(removal, snapshot);
+ if (!prefilterIdentity) {
+ skip(removal, 'ambiguous-namespace');
+ continue;
+ }
+ const prefilterReason = ledgerGateReason(snapshotInstallation({ installations: snapshot }, prefilterIdentity), removal);
if (prefilterReason) {
skip(removal, prefilterReason);
continue;
@@ -2697,16 +2979,19 @@ export class PluginMarketService {
try {
const removed = await this.withMutation(removal.pluginId, async () => {
requireSameMarketOwner(owner);
- const record = ledger.installationForGhost(removal.ghostId);
+ const current = ledger.read().installations;
+ const resolved = removalIdentity(removal, current);
+ if (!resolved) return skip(removal, 'ambiguous-namespace');
+ const record = snapshotInstallation({ installations: current }, resolved);
const reason = ledgerGateReason(record, removal);
if (reason) return skip(removal, reason);
- ghostsById ??= new Map(
- getGhostManager()
- .list()
- .map((ghost) => [ghost.manifest.id, ghost]),
- );
- const installed = ghostsById.get(removal.ghostId);
+ removalGhosts ??= getGhostManager().list();
+ const installed = snapshotGhost({
+ ...EMPTY_LOCAL_INSTALL_SNAPSHOT,
+ ghosts: removalGhosts,
+ ghostsById: indexByGhostId(removalGhosts, (ghost) => ghost.manifest.id),
+ }, resolved);
if (!installed) return skip(removal, 'runtime-not-installed');
// 溯源摘要闸:账本记录只证明"市场装过这个 ghostId",不证明现在占位的
// 还是那份包——本地 .cindy 可原位替换,替换不写市场账本。摘要对不上
@@ -2724,11 +3009,14 @@ export class PluginMarketService {
return skip(removal, 'manifest-digest-mismatch');
}
- await uninstallGhostAndCleanup(removal.ghostId, { skipMarketLedger: true });
+ await uninstallGhostAndCleanup(
+ installedGhostPhysicalRelId(installed),
+ { skipMarketLedger: true },
+ );
await this.withCapturedLedgerMutation(ledger, () => {
// userId=null 即不写退订(拍板:purge 对 defaultInstallOptOuts 只读,
// 不写也不清;重新上架后按用户既有退订状态决定是否自动装回)。
- ledger.markRemoved(removal.ghostId, null);
+ if (record) ledger.markRemovedRecord(record, null);
});
log.info('server plugin removal applied', {
pluginId: removal.pluginId,
@@ -2768,13 +3056,22 @@ export class PluginMarketService {
const uniqueGhostIds = new Set(
plugins.filter((plugin) => counts.get(plugin.ghostId) === 1).map((plugin) => plugin.ghostId),
);
+ const identityCounts = new Map<string, number>();
+ for (const plugin of plugins) {
+ const key = pluginLedgerRecordKey(plugin);
+ identityCounts.set(key, (identityCounts.get(key) ?? 0) + 1);
+ }
const ledgerData = ledger.read();
const local = this.localInstallSnapshot(ledger, ledgerData.installations);
for (const summary of plugins) {
- if (!summary.defaultInstall || !uniqueGhostIds.has(summary.ghostId)) continue;
+ const uniqueIdentity = uniqueGhostIds.has(summary.ghostId) ||
+ (hasDeliveryNamespace(summary) && identityCounts.get(pluginLedgerRecordKey(summary)) === 1);
+ if (!summary.defaultInstall ||
+ !uniqueIdentity) continue;
if (!isGhostAvailableForActiveSession(summary.ghostId)) continue;
if (ledgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)) continue;
- if (isBuiltinGhostRemovedByUser(summary.ghostId)) continue;
+ const target = organizationDeliveryTarget(summary, local, owner);
+ if (target.namespace == null && isBuiltinGhostRemovedByUser(summary.ghostId)) continue;
const state = this.toItem(summary, local).installState;
if (state !== 'not-installed' && state !== 'conflict') continue;
const takeoverRetryKey = this.automaticUpgradeRetryKey(
@@ -2785,7 +3082,7 @@ export class PluginMarketService {
const releaseKey = summary.currentRelease.id;
if (
state === 'conflict' &&
- (isGhostBusy(summary.ghostId) ||
+ (isGhostBusy(target) ||
this.shouldDeferAutomaticUpgrade(takeoverRetryKey, releaseKey))
) {
continue;
@@ -2799,11 +3096,12 @@ export class PluginMarketService {
return;
}
const freshLocal = this.localInstallSnapshot(ledger, freshLedgerData.installations);
+ const freshSummary = organizationDeliveryTarget(summary, freshLocal, owner);
const freshState = this.toItem(summary, freshLocal).installState;
if (freshState !== 'not-installed' && freshState !== 'conflict') {
return;
}
- const freshInstalled = freshLocal.ghostsById.get(summary.ghostId);
+ const freshInstalled = snapshotGhost(freshLocal, freshSummary);
let expectedInstalledApproval: string | undefined;
if (freshState === 'conflict') {
if (!freshInstalled) return;
@@ -2811,21 +3109,21 @@ export class PluginMarketService {
// 失败必须上抛,不能把异常降级成可接管的 manual。
const installOrigin =
freshInstalled.approval.state === 'approved'
- ? getGhostManager().readApprovedInstallOriginStrict(summary.ghostId)
+ ? getGhostManager().readApprovedInstallOriginStrict(installedGhostPhysicalRelId(freshInstalled))
: 'manual';
const eligibility = organizationDefaultTakeoverEligibility({
- summary,
+ summary: freshSummary,
currentOrganization,
- uniqueGhostId: uniqueGhostIds.has(summary.ghostId),
+ uniqueGhostId: uniqueIdentity,
installed: freshInstalled,
- record: freshLedgerData.installations[summary.ghostId] ?? null,
+ record: snapshotInstallation({ installations: freshLedgerData.installations }, freshSummary) ?? null,
installOrigin,
runtimeAvailable: isGhostAvailableForActiveSession(summary.ghostId),
optedOut: Boolean(
freshLedgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id),
),
builtinRemoved: isBuiltinGhostRemovedByUser(summary.ghostId),
- busy: isGhostBusy(summary.ghostId),
+ busy: isGhostBusy(freshSummary),
});
if (!eligibility.eligible) {
if (eligibility.reason === 'busy') {
@@ -2866,10 +3164,11 @@ export class PluginMarketService {
ledger,
commitLedgerData.installations,
);
+ const commitSummary = organizationDeliveryTarget(summary, commitLocal, owner);
if (freshState === 'not-installed') {
if (
!isGhostAvailableForActiveSession(summary.ghostId) ||
- isBuiltinGhostRemovedByUser(summary.ghostId) ||
+ (commitSummary.namespace == null && isBuiltinGhostRemovedByUser(summary.ghostId)) ||
this.toItem(summary, commitLocal).installState !== 'not-installed'
) {
throw new SilentDefaultInstallCancelledError(
@@ -2878,26 +3177,26 @@ export class PluginMarketService {
}
return;
}
- const commitInstalled = commitLocal.ghostsById.get(summary.ghostId);
+ const commitInstalled = snapshotGhost(commitLocal, commitSummary);
if (!commitInstalled || commitInstalled.approval.state !== 'approved') {
throw new SilentDefaultInstallCancelledError(
'Default Plugin install state changed',
);
}
const commitOrigin = getGhostManager().readApprovedInstallOriginStrict(
- summary.ghostId,
+ installedGhostPhysicalRelId(commitInstalled),
);
const eligibility = organizationDefaultTakeoverEligibility({
- summary,
+ summary: commitSummary,
currentOrganization,
- uniqueGhostId: uniqueGhostIds.has(summary.ghostId),
+ uniqueGhostId: uniqueIdentity,
installed: commitInstalled,
- record: commitLedgerData.installations[summary.ghostId] ?? null,
+ record: snapshotInstallation({ installations: commitLedgerData.installations }, commitSummary) ?? null,
installOrigin: commitOrigin,
runtimeAvailable: isGhostAvailableForActiveSession(summary.ghostId),
optedOut: false,
builtinRemoved: isBuiltinGhostRemovedByUser(summary.ghostId),
- busy: isGhostBusy(summary.ghostId),
+ busy: isGhostBusy(commitSummary),
});
if (!eligibility.eligible) {
if (eligibility.reason === 'busy') {
@@ -2965,13 +3264,13 @@ export class PluginMarketService {
let reconciled = true;
let local = this.localInstallSnapshot(ledger);
for (const summary of plugins) {
+ const { target, record, installState } = this.serverMarketBinding(summary, local);
const retryKey = this.automaticUpgradeRetryKey(owner, 'server', summary.id);
const releaseKey = summary.currentRelease.id;
- const record = local.installations[summary.ghostId];
if (
(record?.source !== 'market' && record?.source !== 'legacy-adopted') ||
- this.toItem(summary, local).installState !== 'update-available' ||
- isGhostBusy(summary.ghostId) ||
+ installState !== 'update-available' ||
+ isGhostBusy(target) ||
this.shouldDeferAutomaticUpgrade(retryKey, releaseKey) ||
this.isAutomaticUpgradeHeldForConsent(retryKey, releaseKey, releaseKey)
) {
@@ -2980,19 +3279,19 @@ export class PluginMarketService {
try {
await this.withMutation(summary.id, async () => {
requireSameMarketOwner(owner);
- if (isGhostBusy(summary.ghostId)) {
+ if (isGhostBusy(target)) {
throw new SilentUpgradeBusyError('Plugin is busy');
}
const freshLocal = this.localInstallSnapshot(ledger);
+ const fresh = this.serverMarketBinding(summary, freshLocal);
if (
- (freshLocal.installations[summary.ghostId]?.source !== 'market' &&
- freshLocal.installations[summary.ghostId]?.source !== 'legacy-adopted') ||
- this.toItem(summary, freshLocal).installState !== 'update-available'
+ (fresh.record?.source !== 'market' && fresh.record?.source !== 'legacy-adopted') ||
+ fresh.installState !== 'update-available'
) {
log.debug?.('Plugin update already reconciled', { pluginId: summary.id });
return;
}
- const freshInstalled = freshLocal.ghostsById.get(summary.ghostId);
+ const freshInstalled = fresh.ghost;
if (!freshInstalled) {
log.warn('default plugin upgrade skipped because the installed record disappeared', {
pluginId: summary.id,
@@ -3022,7 +3321,7 @@ export class PluginMarketService {
expectedInstalled: true,
expectedInstalledApproval: ghostInstallApprovalToken(freshInstalled.approval),
beforeCommitInLock: () => {
- if (isGhostBusy(summary.ghostId)) {
+ if (isGhostBusy(fresh.target)) {
throw new SilentUpgradeBusyError('Plugin is busy');
}
},
@@ -3064,10 +3363,10 @@ export class PluginMarketService {
const retryKey = this.automaticUpgradeRetryKey(owner, 'custom', projected.pluginId);
const releaseKey = projected.releaseId;
const contentKey = ghostManifestDigest(entry.plugin.manifest);
- const installed = local.ghostsById.get(projected.ghostId);
+ const installed = snapshotGhost(local, projected);
if (
projected.installState !== 'update-available' ||
- isGhostBusy(projected.ghostId) ||
+ isGhostBusy(projected) ||
installed?.approval.state !== 'approved' ||
this.shouldDeferAutomaticUpgrade(retryKey, releaseKey) ||
this.isAutomaticUpgradeHeldForConsent(retryKey, releaseKey, contentKey)
@@ -3123,12 +3422,15 @@ export class PluginMarketService {
installations = ledger.read().installations,
): LocalInstallSnapshot {
const ghosts = getGhostManager().list();
+ const records = Object.values(installations).filter((record) => record.installed);
return {
- ghostsById: new Map(ghosts.map((ghost) => [ghost.manifest.id, ghost])),
+ ghosts,
+ ghostsById: indexByGhostId(ghosts, (ghost) => ghost.manifest.id),
installations,
- manifestIdentityByGhostId: new Map(
+ installedRecordsByGhostId: indexByGhostId(records, (record) => record.ghostId),
+ manifestIdentityByStoragePart: new Map(
ghosts.map((ghost) => [
- ghost.manifest.id,
+ installedGhostStoragePart(ghost),
readInstalledMarketManifestIdentity(ghost.dir),
]),
),
@@ -3208,7 +3510,7 @@ export class PluginMarketService {
? ledger.isDefaultInstallSuppressed(installSubject, record.pluginId)
: false;
try {
- ledger.markRemoved(record.ghostId, tracksDefaultInstall ? installSubject : null);
+ ledger.markRemovedRecord(record, tracksDefaultInstall ? installSubject : null);
} catch (error) {
this.restoreMarketRouteAfterFailedReplacement(ledger, record, installSubject, wasSuppressed);
log.warn('failed to detach Plugin market route before replacement', {
diff --git a/apps/desktop/src/main/plugin-market/sources/discover.ts b/apps/desktop/src/main/plugin-market/sources/discover.ts
index 20443a4f74..0d92bac2a6 100644
--- a/apps/desktop/src/main/plugin-market/sources/discover.ts
+++ b/apps/desktop/src/main/plugin-market/sources/discover.ts
@@ -13,6 +13,7 @@
import fs from 'node:fs';
import path from 'node:path';
+import { authorDeclaredNamespaceReason } from '@cindy/plugin-protocol';
import { validateGhostManifest, type GhostManifest } from '../../../shared/ghost.js';
import { createLogger } from '../../logger.js';
import {
@@ -356,6 +357,7 @@ async function resolvePluginDir(
const errno = errnoOf(error);
return skippedBy(kind, manifestReadReason(kind, errno), errno);
}
+ if (authorDeclaredNamespaceReason(raw)) return { kind: 'invalid', reason: 'manifest-invalid' };
const validated = validateGhostManifest(raw);
if (!validated.ok) return { kind: 'invalid', reason: 'manifest-invalid' };
return {
diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts
index aaabc35e0f..3a7fe9375b 100644
--- a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts
+++ b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts
@@ -13,7 +13,7 @@ const action: PluginOauthAction = {
actionId: 'oauth_connect:account',
expectedRevision: 1,
};
-function fixture() {
+function fixture(ghostId = 'test-plugin') {
let now = Date.now(),
owner: string | null = 'membership:g1';
const identity = {
@@ -31,7 +31,7 @@ function fixture() {
identity: () => identity,
owner: () => owner,
available: () => true,
- bind: async () => ({ ghostId: 'test-plugin', current: () => true }),
+ bind: async () => ({ ghostId, current: () => true }),
request,
now: () => now,
});
@@ -49,7 +49,7 @@ function fixture() {
target,
peer: 'desktop',
action,
- ghostId: 'test-plugin',
+ ghostId,
invoke,
assertCurrent: () => {},
now: () => now,
@@ -70,19 +70,20 @@ function fixture() {
}
describe('signed OAuth transport with explicit peer trust', () => {
- it('authenticates before any side effect and encrypts all subsequent request/reply bodies', async () => {
- const f = fixture(),
- call = await authenticateOauthController(f.options);
- expect(f.request).not.toHaveBeenCalled();
+ it.each(['test-plugin', '_root__test-plugin', '_ns__' + 'a'.repeat(128) + '__test-plugin'])(
+ 'authenticates %s before side effects and encrypts subsequent bodies', async (ghostId) => {
+ const context = fixture(ghostId),
+ call = await authenticateOauthController(context.options);
+ expect(context.request).not.toHaveBeenCalled();
await expect(call({ op: 'capabilities' })).resolves.toMatchObject({
marker: 'synthetic-private-result',
});
- expect(JSON.stringify(f.invoke.mock.calls)).not.toContain('capabilities');
- const frame = f.invoke.mock.calls[1][0];
- expect(JSON.stringify(await f.host.request('desktop', frame))).not.toContain(
+ expect(JSON.stringify(context.invoke.mock.calls)).not.toContain('capabilities');
+ const frame = context.invoke.mock.calls[1][0];
+ expect(JSON.stringify(await context.host.request('desktop', frame))).not.toContain(
'synthetic-private-result',
);
- expect(f.request).toHaveBeenCalledTimes(1); // identical retry returns the cached ciphertext, without replaying work
+ expect(context.request).toHaveBeenCalledTimes(1); // identical retry returns the cached ciphertext, without replaying work
});
it('rejects the former raw v1 transport', async () => {
const f = fixture();
diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/connectionSubmission.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/connectionSubmission.test.ts
index 0acb190dad..6f4cf4d5cd 100644
--- a/apps/desktop/src/main/plugin-oauth/__tests__/connectionSubmission.test.ts
+++ b/apps/desktop/src/main/plugin-oauth/__tests__/connectionSubmission.test.ts
@@ -7,6 +7,8 @@ import { GhostSetupCoordinator } from '../../cindy-brain/ghostSetupCoordinator.j
import { GhostSetupInteractionBridge } from '../../cindy-brain/ghostSetupInteractionBridge.js';
import { GhostConnectionManager } from '../../cindy-brain/ghostConnections.js';
import { executeGhostSetupConnectionSubmission } from '../../cindy-brain/ghostSetupConnectionExecutor.js';
+import { createGhostProductionCallbacks } from '../../cindy-brain/__tests__/ghostProductionCallbacksFixture.js';
+import { withRemoteOauthContext } from '../context.js';
import { initializePluginOauthCards } from '../cards.js';
import { assistPluginOauth, type OauthControllerDeps } from '../controller.js';
import {
@@ -211,6 +213,31 @@ async function harness(fault?: 'vault' | 'owner' | 'manifest' | 'stale', configu
}
describe('authenticated exact-host connection form', () => {
+ it.each(['current', 'replacement', 'revoked'])('production connection binder checks its original receipt (%s)', async (state) => {
+ const h = await harness();
+ let token: string | null = 'original';
+ const action = { id: 'manage_connection:connection:service', kind: 'manage_connection' as const };
+ const manifest: GhostManifest = { schemaVersion: 3, id: 'demo', name: 'Demo', version: '1', kind: 'chip',
+ entry: 'main.js', network: { hosts: [], connections: [{ key: 'service', label: 'Service',
+ inject: { header: 'PRIVATE-TOKEN', format: '{value}' } }] } };
+ const load = createGhostProductionCallbacks<{
+ bindGhostSetupConnectionAction(args: { ghostId: string; actionId: string; onCommitted(): void }):
+ ((value: typeof input) => boolean) | null;
+ }>({ functions: ['bindGhostSetupConnectionAction'] });
+ const { bindGhostSetupConnectionAction } = load({
+ findGhostForInstanceId: () => ({ manifest }), installedGhostStoragePart: () => 'demo',
+ ghostInstallMutationTargetFor: () => token, executeGhostSetupConnectionSubmission,
+ getGhostConnectionManager: () => h.manager, getGhostSetupChangeBus: () => ({ emit() {} }),
+ getGhostSetupAssessment: () => ({ groups: [{ items: [{ kind: 'connection', ref: 'connection:service', actions: [action] }] }] }),
+ });
+ const submit = bindGhostSetupConnectionAction({ ghostId: 'demo', actionId: action.id, onCommitted: vi.fn() })!;
+ if (state !== 'current') token = state === 'replacement' ? 'replacement' : null;
+ const accepted = withRemoteOauthContext({ scope: 'test', assertCurrent: vi.fn(), authorize: vi.fn(),
+ submitConnection: async () => input, finish: vi.fn() }, () => submit(input));
+ expect(accepted).toBe(state === 'current');
+ expect(h.manager.resolveTokenByHost('demo', 'service', 'git.example.test')).toBe(state === 'current' ? input.token : null);
+ if (state !== 'current') expect(h.store).not.toHaveBeenCalled();
+ });
it('reopens an existing connection and replaces only its token after the signed submission commits', async () => {
const h = await harness(undefined, true);
const before = h.manager.list('demo', 'service');
diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/deviceCodeSessions.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/deviceCodeSessions.test.ts
index 89afe141fe..6411488714 100644
--- a/apps/desktop/src/main/plugin-oauth/__tests__/deviceCodeSessions.test.ts
+++ b/apps/desktop/src/main/plugin-oauth/__tests__/deviceCodeSessions.test.ts
@@ -20,7 +20,7 @@ afterEach(() => {
vi.useRealTimers();
});
-function setup() {
+function setup(instance = target) {
const registry = new LocalDeviceCodeSessions();
let clipboard = '';
let current = true;
@@ -40,7 +40,7 @@ function setup() {
const openExternal = vi.fn(async (_url: string) => {});
const close = registry.present(
scope,
- target,
+ instance,
{ userCode: 'TEST-CODE', authorizeUrl: 'https://github.com/login/device', expiresAt: 61_000 },
{
assertCurrent: () => {
@@ -64,7 +64,7 @@ function setup() {
stale: () => {
current = false;
},
- read: () => registry.handle(scope, { ...target, operation: 'read' }),
+ read: () => registry.handle(scope, { ...instance, operation: 'read' }),
};
}
@@ -91,6 +91,14 @@ it('returns only the display projection and supports repeated copy and exact reo
expect(h.clipboard()).toBe('');
});
+it('keeps long enterprise instance ids bound to the device-code display lease', async () => {
+ const instance = { ...target, ghostId: '_ns__' + 'a'.repeat(128) + '__cindy-github' };
+ const context = setup(instance);
+ expect(await context.read()).toMatchObject({ phase: 'ready' });
+ await context.registry.handle(scope, { ...instance, operation: 'copy' });
+ expect(context.copy).toHaveBeenCalledExactlyOnceWith('TEST-CODE');
+});
+
it.each(['deviceId', 'ghostId', 'requestId', 'actionId'] as const)(
'does not disclose another %s or accept its copy request',
async (field) => {
diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts
index 8560eb86e6..1e0e926297 100644
--- a/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts
+++ b/apps/desktop/src/main/plugin-oauth/__tests__/transport.test.ts
@@ -6,7 +6,7 @@ import path from 'node:path';
import { resolveOauthPeerIdentity } from '../identityResolver.js';
import { createHash } from 'node:crypto';
import { WebSocket, WebSocketServer } from 'ws';
-import { expect, it, vi } from 'vitest';
+import { expect, it, onTestFinished, vi } from 'vitest';
import { DeviceLinkClient, PLUGIN_OAUTH_CHANNEL, type Envelope } from '@cindy/device-link';
import type { GhostSetupAssessment } from '../../../shared/ghost.js';
import { GhostOauthAccountManager } from '../../cindy-brain/ghostOauthAccounts.js';
@@ -18,9 +18,8 @@ import { initializePluginOauthCards } from '../cards.js';
import { handleAssistPluginOauth } from '../localIpc.js';
import { invalidatePluginOauth, requestPluginOauth } from '../runtime.js';
-it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and cloud vault commit', async ({
- onTestFinished,
-}) => {
+it.each(['test-plugin', '_ns__' + 'a'.repeat(128) + '__test-plugin'])(
+ 'carries %s through DeviceLinkClient/WebSocket, loopback and cloud vault commit', async (ghostId) => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-oauth-transport-'));
onTestFinished(() => fs.rmSync(directory, { recursive: true, force: true }));
const identityStore = testOauthIdentityStore(directory);
@@ -143,7 +142,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
onAccountConnected: () => {
connected = true;
// Exercises card close/readiness racing with the controller's next status poll.
- bus.emit('test-plugin', { source: 'oauth', ref: 'account' });
+ bus.emit(ghostId, { source: 'oauth', ref: 'account' });
},
});
const assessment = (): GhostSetupAssessment => ({
@@ -172,7 +171,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
changeBus: bus,
assess: assessment,
validateTarget: () => ({ ok: true }),
- getGhostIdentity: () => ({ id: 'test-plugin', name: 'Provider' }),
+ getGhostIdentity: () => ({ id: ghostId, name: 'Provider' }),
executeAction: async () => {
const remote = getRemoteOauthContext()!;
const authorize = remote.authorize.bind(remote);
@@ -185,7 +184,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
return authorize(offer, signal);
});
const result = await account.connectAccount(
- 'test-plugin',
+ ghostId,
'account',
{
authorizeUrl: 'https://provider.example/authorize',
@@ -233,7 +232,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
});
const setup = coordinator.ensureReady({
sessionId: 'cloud-session',
- ghostId: 'test-plugin',
+ ghostId,
tool: 'read',
});
try {
@@ -283,7 +282,7 @@ it('carries a real setup card through DeviceLinkClient/WebSocket, loopback and c
},
{
deviceId: 'cloud',
- ghostId: 'test-plugin',
+ ghostId,
requestId: snapshot.requestId,
actionId: snapshot.steps[0].action!.id,
expectedRevision: snapshot.revision,
diff --git a/apps/desktop/src/main/plugin-oauth/deviceCodeSessions.ts b/apps/desktop/src/main/plugin-oauth/deviceCodeSessions.ts
index ab079ab260..8471c42257 100644
--- a/apps/desktop/src/main/plugin-oauth/deviceCodeSessions.ts
+++ b/apps/desktop/src/main/plugin-oauth/deviceCodeSessions.ts
@@ -1,5 +1,6 @@
import {
oauthId,
+ oauthGhostId,
PLUGIN_OAUTH_TTL_MS,
parseDeviceAuthorizationUrl,
parseAuthorizationUserCode,
@@ -32,7 +33,7 @@ function parseRequest(raw: unknown): PluginOauthDeviceCodeRequest {
if (
Object.keys(v).sort().join(',') !== 'actionId,deviceId,ghostId,operation,requestId' ||
!oauthId(v.deviceId) ||
- !oauthId(v.ghostId) ||
+ !oauthGhostId(v.ghostId) ||
!oauthId(v.requestId) ||
typeof v.actionId !== 'string' ||
!v.actionId ||
diff --git a/apps/desktop/src/main/plugin-oauth/localIpc.ts b/apps/desktop/src/main/plugin-oauth/localIpc.ts
index 2d739e021a..c721ca5467 100644
--- a/apps/desktop/src/main/plugin-oauth/localIpc.ts
+++ b/apps/desktop/src/main/plugin-oauth/localIpc.ts
@@ -1,6 +1,7 @@
import {
PLUGIN_OAUTH_CHANNEL,
oauthId,
+ oauthGhostId,
parsePluginOauthAction,
parsePluginSecretInput,
parsePluginSecretPresentation,
@@ -64,7 +65,7 @@ async function handleAuthorization(
const { deviceId, ghostId, ...rest } = raw as Record<string, unknown>;
const action = parsePluginOauthAction(rest);
const owner = deps.owner();
- if (!oauthId(deviceId) || !oauthId(ghostId) || !action || !owner) throw fail();
+ if (!oauthId(deviceId) || !oauthGhostId(ghostId) || !action || !owner) throw fail();
const slot = `${deviceId}:${action.requestId}`;
if (active.has(slot) || active.size >= 8) throw fail();
const peerCurrent = capturePluginOauthPeer(deviceId);
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/api.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/api.test.ts
index 58b49b737e..dca3634031 100644
--- a/apps/desktop/src/main/plugin-publisher/__tests__/api.test.ts
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/api.test.ts
@@ -26,6 +26,7 @@ describe('PluginPublisherApi', () => {
it('prepare / status / list use Connection JWT and skip Access Token refresh', async () => {
const fetchImpl = vi.fn(async (apiPath: string) => {
if (apiPath === '/api/publisher/uploads') return okPrepare();
+ if (apiPath.endsWith('/commit')) return { uploadId: 'upload-1', status: 'validating' };
if (apiPath.startsWith('/api/publisher/uploads/upload-1') && !apiPath.endsWith('/commit')) {
return {
uploadId: 'upload-1',
@@ -41,12 +42,14 @@ describe('PluginPublisherApi', () => {
return { releases: [], nextCursor: null };
});
const api = new PluginPublisherApi({
+ getClientVersion: () => '1.2.3',
getToken: async () => 'conn-token',
invalidateToken: vi.fn(),
fetchImpl: fetchImpl as never,
});
await api.prepare({ sizeBytes: 12, sha256: SHA });
+ await api.commit('upload-1');
await api.status('upload-1');
await api.listMine();
@@ -57,11 +60,14 @@ describe('PluginPublisherApi', () => {
expect(opts.skipAutoRefresh).toBe(true);
expect(opts.redactErrorDetails).toBe(true);
expect(opts.logLabel).toBe('/api/publisher');
+ expect(opts.headers).toEqual({ 'x-cindy-version': '1.2.3' });
+ expect(opts.allowedRedactedErrorCodes).toContain('PLUGIN_NAMESPACE_CLIENT_REQUIRED');
}
});
it('reads commit body.status so HTTP 202 expired is not success', async () => {
const api = new PluginPublisherApi({
+ getClientVersion: () => '1.2.3',
getToken: async () => 'conn-token',
invalidateToken: vi.fn(),
fetchImpl: (async () => ({ uploadId: 'upload-1', status: 'expired' })) as never,
@@ -83,6 +89,7 @@ describe('PluginPublisherApi', () => {
return { uploadId: 'upload-1', status: 'validating' };
});
const api = new PluginPublisherApi({
+ getClientVersion: () => '1.2.3',
getToken: async () => `token-${calls + 1}`,
invalidateToken,
fetchImpl: fetchImpl as never,
@@ -90,6 +97,9 @@ describe('PluginPublisherApi', () => {
await expect(api.commit('upload-1')).resolves.toMatchObject({ status: 'validating' });
expect(invalidateToken).toHaveBeenCalledTimes(1);
expect(fetchImpl).toHaveBeenCalledTimes(2);
+ for (const [, options] of fetchImpl.mock.calls as unknown as Array<[string, Record<string, unknown>]>) {
+ expect(options.headers).toEqual({ 'x-cindy-version': '1.2.3' });
+ }
});
it('reports an unknown bounded failure code once without forwarding its message', async () => {
@@ -128,6 +138,7 @@ describe('PluginPublisherApi', () => {
nextCursor: null,
});
const api = new PluginPublisherApi({
+ getClientVersion: () => '1.2.3',
getToken: async () => 'conn-token',
invalidateToken: vi.fn(),
unknownFailureCodeReporter: createUnknownFailureCodeReporter(onUnknownFailureCode),
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/host.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/host.test.ts
new file mode 100644
index 0000000000..513d7cc86b
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/host.test.ts
@@ -0,0 +1,225 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { PluginPublisherApiDeps } from '../api.js';
+import type { PluginPublisherOrchestratorDeps } from '../orchestrator.js';
+
+const mocks = vi.hoisted(() => ({
+ auth: vi.fn(), refresh: vi.fn(), authListener: vi.fn(),
+ owner: vi.fn(() => ({ dataOwnerId: 'member-1', ownerGeneration: 1 })),
+ create: vi.fn(), start: vi.fn(() => ({ transferId: 'transfer-1', uploadId: null })),
+ abort: vi.fn(), getToken: vi.fn(async () => 'connection-token'), invalidate: vi.fn(),
+ inspect: vi.fn(), listAll: vi.fn(),
+}));
+
+vi.mock('electron', () => ({ app: { getVersion: () => '1.0.0' } }));
+vi.mock('../../plugin-market/api.js', () => ({
+ PluginMarketApi: class { listAll = mocks.listAll; },
+}));
+vi.mock('../../appSessionState.js', () => ({ getActiveDataOwnerPushStamp: mocks.owner }));
+vi.mock('../../authManager.js', () => ({
+ getAuthState: mocks.auth, refresh: mocks.refresh, onAuthStateChange: mocks.authListener,
+}));
+vi.mock('../../cindy-brain/index.js', () => ({
+ getConnectionTokenProvider: () => ({ getToken: mocks.getToken, invalidate: mocks.invalidate }),
+ getGhostManager: () => ({ inspect: mocks.inspect }), sendToTrustedAppWindows: () => 1,
+}));
+vi.mock('../../cindy-brain/connectionAudienceResolver.js', () => ({
+ isReservedConnectionPluginSlug: () => false,
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));
+vi.mock('../../lifecycle.js', () => ({ onQuit: vi.fn() }));
+vi.mock('../api.js', () => ({
+ PluginPublisherApi: class {
+ constructor(public deps: PluginPublisherApiDeps) {}
+ },
+}));
+vi.mock('../orchestrator.js', () => ({
+ PluginPublisherOrchestrator: class {},
+ createPluginPublisherOrchestrator: mocks.create,
+}));
+
+function member(orgSlug: string | null | undefined = undefined) {
+ return {
+ isAuthenticated: true,
+ user: { id: 'member-1', membershipKind: 'org', orgId: 'org-1', orgName: 'Acme', orgSlug },
+ };
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ mocks.auth.mockReturnValue(member());
+ mocks.owner.mockReturnValue({ dataOwnerId: 'member-1', ownerGeneration: 1 });
+ mocks.refresh.mockResolvedValue(false);
+ mocks.listAll.mockResolvedValue({ plugins: [], removals: [], currentOrganization: null });
+ mocks.create.mockReturnValue({ start: mocks.start, abortAll: mocks.abort });
+});
+
+async function host() {
+ return import('../host.js');
+}
+
+function dependencies(): PluginPublisherOrchestratorDeps {
+ return mocks.create.mock.calls[0][0] as PluginPublisherOrchestratorDeps;
+}
+
+describe('publisher old-token organization compatibility', () => {
+ it('uses the validated S1 market namespace for the exact Auth organization when refresh keeps the claim absent', async () => {
+ mocks.listAll.mockResolvedValue({
+ plugins: [], removals: [],
+ currentOrganization: { organizationId: 'org-1', orgSlug: 'actual-org', pluginPrefix: 'legacy' },
+ });
+ const publisher = await host();
+ publisher.startPluginPublish('/tmp/legacy-helper.cindy');
+ expect(await dependencies().identity()).toEqual({
+ membershipId: 'member-1', orgSlug: 'actual-org', orgName: 'Acme',
+ });
+ expect(mocks.auth().user.orgSlug).toBeUndefined();
+ const api = dependencies().api as unknown as { deps: { getToken(): Promise<string> } };
+ await api.deps.getToken();
+ expect(mocks.getToken).toHaveBeenCalledWith({
+ membershipId: 'member-1', audience: 'actual-org:cindy-publisher',
+ });
+ expect(mocks.listAll).toHaveBeenCalledTimes(1);
+ expect(mocks.refresh).toHaveBeenCalledTimes(1);
+ });
+
+ it('provides the running app version to the publisher HTTP client', async () => {
+ (await host()).getPluginPublisherOrchestrator();
+ const api = dependencies().api as unknown as { deps: PluginPublisherApiDeps };
+ expect(api.deps.getClientVersion()).toBe('1.0.0');
+ });
+
+ it('rejects a valid market namespace for a foreign organization even with the same legal prefix', async () => {
+ mocks.listAll.mockResolvedValue({
+ plugins: [], removals: [],
+ currentOrganization: { organizationId: 'org-foreign', orgSlug: 'foreign', pluginPrefix: 'legacy' },
+ });
+ const publisher = await host();
+ publisher.startPluginPublish('/tmp/legacy-helper.cindy');
+ expect(await dependencies().identity()).toMatchObject({ orgSlug: null });
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ });
+
+ it.each(
+ ['refresh', 'market'].flatMap((phase) =>
+ ['membership', 'organization', 'owner'].map((change) => ({ phase, change })),
+ ),
+ )('rejects a late namespace after $change changes during $phase', async ({ phase, change }) => {
+ const publisher = await host();
+ const changeContext = () => {
+ const next = member(phase === 'refresh' ? 'actual-org' : undefined);
+ if (change === 'membership') next.user.id = 'member-2';
+ if (change === 'organization') next.user.orgId = 'org-2';
+ if (change === 'owner') mocks.owner.mockReturnValue({ dataOwnerId: 'member-1', ownerGeneration: 2 });
+ mocks.auth.mockReturnValue(next);
+ mocks.authListener.mock.calls[0][0]();
+ };
+ mocks.refresh.mockImplementation(async () => {
+ if (phase === 'refresh') changeContext();
+ return true;
+ });
+ mocks.listAll.mockImplementation(async () => {
+ changeContext();
+ return {
+ plugins: [], removals: [],
+ currentOrganization: { organizationId: 'org-1', orgSlug: 'actual-org', pluginPrefix: 'legacy' },
+ };
+ });
+ publisher.startPluginPublish('/tmp/legacy-helper.cindy');
+ expect(await dependencies().identity()).toBeNull();
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ expect(mocks.abort).toHaveBeenCalledTimes(1);
+ expect(mocks.listAll).toHaveBeenCalledTimes(phase === 'market' ? 1 : 0);
+ });
+
+ it('does not use a prefix as a namespace when the market row has no orgSlug', async () => {
+ mocks.listAll.mockResolvedValue({
+ plugins: [], removals: [], currentOrganization: { organizationId: 'org-1', pluginPrefix: 'xd' },
+ });
+ const publisher = await host();
+ publisher.startPluginPublish('/tmp/xd-helper.cindy');
+ expect(await dependencies().identity()).toMatchObject({ orgSlug: null });
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse the market identity cache after Auth organization changes without changing membership', async () => {
+ mocks.listAll.mockResolvedValue({
+ plugins: [], removals: [],
+ currentOrganization: { organizationId: 'org-1', orgSlug: 'actual-org', pluginPrefix: null },
+ });
+ const publisher = await host();
+ publisher.startPluginPublish('/tmp/helper.cindy');
+ expect(await dependencies().identity()).toMatchObject({ orgSlug: 'actual-org' });
+ const next = member();
+ next.user.orgId = 'org-2';
+ mocks.auth.mockReturnValue(next);
+ expect(publisher.currentPublisherIdentity()).toMatchObject({ orgSlug: null });
+ expect(await dependencies().identity()).toMatchObject({ orgSlug: null });
+ expect(mocks.listAll).toHaveBeenCalledTimes(2);
+ });
+
+ it('reports unavailable namespace rather than adopting identity on a failed market lookup', async () => {
+ mocks.listAll.mockRejectedValue(new Error('invalid market response'));
+ const publisher = await host();
+ publisher.startPluginPublish('/tmp/legacy-helper.cindy');
+ expect(await dependencies().identity()).toMatchObject({ orgSlug: null });
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ });
+
+ it.each([null, undefined])('keeps a real old organization membership with missing slug=%s', async (orgSlug) => {
+ mocks.auth.mockReturnValue(member(orgSlug));
+ expect((await host()).currentPublisherIdentity()).toEqual({
+ membershipId: 'member-1', orgSlug: null, orgName: 'Acme',
+ });
+ });
+
+ it('starts old legal-prefix publication and resolves only the real refreshed namespace', async () => {
+ const publisher = await host();
+ mocks.refresh.mockImplementation(async () => {
+ mocks.auth.mockReturnValue(member('actual-org'));
+ mocks.authListener.mock.calls[0][0]();
+ return true;
+ });
+ expect(publisher.startPluginPublish('/tmp/old-prefix-helper.cindy').transferId).toBe('transfer-1');
+ expect(await dependencies().identity()).toEqual({
+ membershipId: 'member-1', orgSlug: 'actual-org', orgName: 'Acme',
+ });
+ expect(mocks.refresh).toHaveBeenCalledTimes(1);
+ expect(mocks.abort).not.toHaveBeenCalled();
+ const api = dependencies().api as unknown as { deps: { getToken(): Promise<string> } };
+ await api.deps.getToken();
+ expect(mocks.getToken).toHaveBeenCalledWith({
+ membershipId: 'member-1', audience: 'actual-org:cindy-publisher',
+ });
+ });
+
+ it('preserves natural names with a true namespace without a prefix lookup or refresh', async () => {
+ mocks.auth.mockReturnValue(member('xd'));
+ mocks.inspect.mockResolvedValue({ canonicalManifest: { id: 'helper', name: 'Helper', version: '1.0.0' } });
+ const publisher = await host();
+ publisher.startPluginPublish('/tmp/helper.cindy');
+ expect(await dependencies().identity()).toMatchObject({ orgSlug: 'xd' });
+ expect(await dependencies().inspectPackage('/tmp/helper.cindy')).toMatchObject({ ghostId: 'helper' });
+ expect(publisher.publisherAudience('xd')).toBe('xd:cindy-publisher');
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ });
+
+ it('does not invent a namespace when refresh cannot provide one', async () => {
+ const publisher = await host();
+ publisher.startPluginPublish('/tmp/xd-helper.cindy');
+ expect(await dependencies().identity()).toEqual({
+ membershipId: 'member-1', orgSlug: null, orgName: 'Acme',
+ });
+ expect(() => publisher.publisherAudience(null as unknown as string)).toThrow();
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ });
+
+ it('still rejects personal membership and an explicitly invalid namespace', async () => {
+ const publisher = await host();
+ mocks.auth.mockReturnValue({ isAuthenticated: true, user: { ...member().user, membershipKind: 'personal' } });
+ expect(publisher.currentPublisherIdentity()).toBeNull();
+ mocks.auth.mockReturnValue(member('bad:slug'));
+ expect(publisher.currentPublisherIdentity()).toBeNull();
+ expect(() => publisher.publisherAudience('bad:slug')).toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
index 640d7e9266..c22830b673 100644
--- a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
@@ -80,6 +80,44 @@ const prepared = {
};
describe('PluginPublisherOrchestrator', () => {
+ it('waits for trusted identity refresh before inspecting and confirming an old legal prefix package', async () => {
+ const filePath = await packagePath();
+ let resolveIdentity!: (value: { membershipId: string; orgSlug: string; orgName: string }) => void;
+ const identity = new Promise<{ membershipId: string; orgSlug: string; orgName: string }>((resolve) => {
+ resolveIdentity = resolve;
+ });
+ const inspectPackage = vi.fn(async () => ({ ghostId: 'legacy-helper', name: 'Helper', version: '1.0.0' }));
+ const confirm = vi.fn(async () => false);
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare: vi.fn(), commit: vi.fn(), status: vi.fn() } as unknown as PluginPublisherApi,
+ identity: () => identity, inspectPackage, confirm,
+ });
+ const started = orch.start(filePath);
+ await Promise.resolve();
+ expect(inspectPackage).not.toHaveBeenCalled();
+ resolveIdentity({ membershipId: 'm1', orgSlug: 'actual-org', orgName: 'Acme' });
+ await vi.waitFor(() => expect(orch.snapshot(started.transferId)?.errorCode).toBe('CONFIRM_UNAVAILABLE'));
+ expect(inspectPackage).toHaveBeenCalledWith(filePath);
+ expect(confirm).toHaveBeenCalledWith(expect.objectContaining({
+ orgSlug: 'actual-org', ghostId: 'legacy-helper',
+ }), expect.any(AbortSignal));
+ });
+
+ it('reports missing namespace separately from non-organization membership and does not inspect or upload', async () => {
+ const filePath = await packagePath();
+ const inspectPackage = vi.fn(async () => ({ ghostId: 'legacy-helper', name: 'Helper', version: '1.0.0' }));
+ const prepare = vi.fn();
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare, commit: vi.fn(), status: vi.fn() } as unknown as PluginPublisherApi,
+ identity: async () => ({ membershipId: 'm1', orgSlug: null, orgName: 'Acme' }),
+ inspectPackage, confirm: vi.fn(async () => true),
+ });
+ const started = orch.start(filePath);
+ await vi.waitFor(() => expect(orch.snapshot(started.transferId)?.errorCode).toBe('PUBLISHER_IDENTITY_UNAVAILABLE'));
+ expect(inspectPackage).not.toHaveBeenCalled();
+ expect(prepare).not.toHaveBeenCalled();
+ });
+
it('caps pending confirmations per owner before opening another package', async () => {
const filePath = await packagePath();
const snapshots: PluginPublisherProgress[] = [];
@@ -690,6 +728,7 @@ describe('PluginPublisherOrchestrator', () => {
{ status: 503, code: 'INTERNAL_ERROR', expected: 'PUBLISH_UNSUPPORTED' },
{ status: 503, code: 'RATE_LIMIT_UNAVAILABLE', expected: 'RATE_LIMIT_UNAVAILABLE' },
{ status: 503, code: 'STORAGE_UNAVAILABLE', expected: 'STORAGE_UNAVAILABLE' },
+ { status: 409, code: 'PLUGIN_NAMESPACE_CLIENT_REQUIRED', expected: 'PLUGIN_NAMESPACE_CLIENT_REQUIRED' },
])('maps prepare $status/$code to $expected', async ({ status, code, expected }) => {
const filePath = await packagePath();
const snapshots: PluginPublisherProgress[] = [];
@@ -709,5 +748,8 @@ describe('PluginPublisherOrchestrator', () => {
orch.start(filePath);
const failed = await waitFor(snapshots, (progress) => progress.stage === 'failed');
expect(failed.errorCode).toBe(expected);
+ if (code === 'PLUGIN_NAMESPACE_CLIENT_REQUIRED') {
+ expect(failed.message).toBe('请更新 Cindy 后再发布此组织的插件');
+ }
});
});
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/registerIpc.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/registerIpc.test.ts
index 6fb830aca9..29be3fcc86 100644
--- a/apps/desktop/src/main/plugin-publisher/__tests__/registerIpc.test.ts
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/registerIpc.test.ts
@@ -9,6 +9,7 @@ const {
snapshotForOwnerMock,
cancelForOwnerMock,
trustedRendererMock,
+ publisherApiMock,
} = vi.hoisted(() => ({
handlers: new Map<string, Handler>(),
boundaryPendingMock: vi.fn(() => false),
@@ -20,6 +21,7 @@ const {
snapshotForOwnerMock: vi.fn(() => ({ transferId: 'transfer-1', stage: 'confirming' })),
cancelForOwnerMock: vi.fn(() => ({ cancelled: true })),
trustedRendererMock: vi.fn(),
+ publisherApiMock: vi.fn(() => ({ listMine: async () => ({ releases: [], nextCursor: null }) })),
}));
vi.mock('electron', () => ({
@@ -35,6 +37,7 @@ vi.mock('../../security/trustedAppRenderer.js', () => ({
assertTrustedAppRendererEvent: trustedRendererMock,
}));
vi.mock('../host.js', () => ({
+ createPluginPublisherApi: publisherApiMock,
currentPublisherIdentity: vi.fn(() => ({
membershipId: 'member-1',
orgSlug: 'acme',
@@ -45,19 +48,11 @@ vi.mock('../host.js', () => ({
snapshotForOwner: snapshotForOwnerMock,
cancelForOwner: cancelForOwnerMock,
})),
- publisherAudience: vi.fn((orgSlug: string) => `${orgSlug}:publisher`),
trackPublisherConfirmRequester: vi.fn(),
}));
vi.mock('../api.js', () => ({
- PluginPublisherApi: class {},
PluginPublisherApiError: class extends Error {},
}));
-vi.mock('../../cindy-brain/index.js', () => ({
- getConnectionTokenProvider: vi.fn(() => ({
- getToken: vi.fn(),
- invalidate: vi.fn(),
- })),
-}));
const { registerPluginPublisherIpc } = await import('../registerIpc.js');
@@ -78,9 +73,15 @@ beforeEach(() => {
snapshotForOwnerMock.mockClear();
cancelForOwnerMock.mockClear();
trustedRendererMock.mockClear();
+ publisherApiMock.mockClear();
});
describe('plugin-publisher IPC owner boundary', () => {
+ it('uses the shared Host HTTP client for publication-history requests', async () => {
+ await expect(handler('plugin-publisher:list-mine')(event, null)).resolves.toEqual({ releases: [], nextCursor: null });
+ expect(publisherApiMock).toHaveBeenCalledOnce();
+ });
+
it('fails closed when an untrusted Renderer submits a publish file path', async () => {
let caught: unknown;
try {
diff --git a/apps/desktop/src/main/plugin-publisher/api.ts b/apps/desktop/src/main/plugin-publisher/api.ts
index f70596bbb5..91e129e0ec 100644
--- a/apps/desktop/src/main/plugin-publisher/api.ts
+++ b/apps/desktop/src/main/plugin-publisher/api.ts
@@ -6,6 +6,7 @@
* body.status (expired is not a success).
*/
import {
+ CINDY_CLIENT_VERSION_HEADER,
parseCommitPluginMemberUploadResponse,
parseListMyPluginMemberReleasesResponse,
parsePluginMemberUploadStatusResponse,
@@ -41,6 +42,7 @@ export class PluginPublisherApiError extends Error {
}
export interface PluginPublisherApiDeps {
+ getClientVersion(): string;
getToken(): Promise<string>;
invalidateToken(): void;
unknownFailureCodeReporter?: UnknownFailureCodeReporter;
@@ -128,8 +130,10 @@ export class PluginPublisherApi {
'CONNECTION_UNAUTHORIZED',
'INVALID_CONNECTION_TOKEN',
'CONNECTION_TOKEN_EXPIRED',
+ 'PLUGIN_NAMESPACE_CLIENT_REQUIRED',
],
...options,
+ headers: { ...options.headers, [CINDY_CLIENT_VERSION_HEADER]: this.deps.getClientVersion() },
token,
skipAutoRefresh: true,
});
diff --git a/apps/desktop/src/main/plugin-publisher/host.ts b/apps/desktop/src/main/plugin-publisher/host.ts
index a7baad2c99..eb0b144ff3 100644
--- a/apps/desktop/src/main/plugin-publisher/host.ts
+++ b/apps/desktop/src/main/plugin-publisher/host.ts
@@ -4,10 +4,10 @@
* Identity is the current org membership. Audience is Host-minted
* `<orgSlug>:cindy-publisher` and never goes through the plugin resolver.
*/
-import type { WebContents } from 'electron';
+import { app, type WebContents } from 'electron';
import { getActiveDataOwnerPushStamp } from '../appSessionState.js';
-import { getAuthState, onAuthStateChange } from '../authManager.js';
+import { getAuthState, onAuthStateChange, refresh } from '../authManager.js';
import {
getConnectionTokenProvider,
getGhostManager,
@@ -16,6 +16,7 @@ import {
import { isReservedConnectionPluginSlug } from '../cindy-brain/connectionAudienceResolver.js';
import { createLogger } from '../logger.js';
import { onQuit } from '../lifecycle.js';
+import { PluginMarketApi } from '../plugin-market/api.js';
import { PluginPublisherApi } from './api.js';
import { PluginPublisherConfirmBridge } from './confirmBridge.js';
import {
@@ -23,7 +24,7 @@ import {
PluginPublisherOrchestrator,
type PluginPublisherSourceBinding,
} from './orchestrator.js';
-import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID, type PluginPublisherProgress } from './types.js';
+import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID, type PluginPublisherIdentity, type PluginPublisherProgress } from './types.js';
const log = createLogger('plugin-publisher');
const ORG_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
@@ -35,36 +36,72 @@ const trackedConfirmRequesters = new WeakSet<WebContents>();
let orchestratorSingleton: PluginPublisherOrchestrator | null = null;
let quitHooked = false;
let authHooked = false;
+let resolvedMarketIdentity: { contextKey: string; orgSlug: string } | null = null;
export function getPluginPublisherConfirmBridge(): PluginPublisherConfirmBridge {
return confirmBridge;
}
-export function currentPublisherIdentity(): {
- membershipId: string;
- orgSlug: string;
- orgName: string | null;
-} | null {
+function publisherIdentityContextKey(): string | null {
+ const state = getAuthState();
+ const user = state.isAuthenticated ? state.user : null;
+ if (!user || user.membershipKind !== 'org' || !user.orgId) return null;
+ const owner = getActiveDataOwnerPushStamp();
+ return JSON.stringify([user.id, user.orgId, owner.dataOwnerId, owner.ownerGeneration]);
+}
+
+export function currentPublisherIdentity(): PluginPublisherIdentity | null {
const state = getAuthState();
const user = state.isAuthenticated ? state.user : null;
if (!user || user.membershipKind !== 'org') return null;
- if (!user.orgSlug || !ORG_SLUG_RE.test(user.orgSlug)) return null;
+ if (user.orgSlug != null && !ORG_SLUG_RE.test(user.orgSlug)) return null;
+ const contextKey = publisherIdentityContextKey();
+ const marketOrgSlug = contextKey !== null && resolvedMarketIdentity?.contextKey === contextKey
+ ? resolvedMarketIdentity.orgSlug : null;
return {
membershipId: user.id,
- orgSlug: user.orgSlug,
+ orgSlug: user.orgSlug ?? marketOrgSlug,
orgName: user.orgName,
};
}
-export function publisherAudience(orgSlug: string): string {
+async function resolvePublisherIdentity(): Promise<PluginPublisherIdentity | null> {
+ const identity = currentPublisherIdentity();
+ if (!identity || identity.orgSlug !== null) return identity;
+ const contextKey = publisherIdentityContextKey();
+ const organizationId = getAuthState().user?.orgId;
+ if (contextKey === null || !organizationId) return identity;
+ await refresh();
+ if (publisherIdentityContextKey() !== contextKey) return null;
+ const refreshed = currentPublisherIdentity();
+ if (!refreshed || refreshed.membershipId !== identity.membershipId) return null;
+ if (refreshed.orgSlug !== null) return refreshed;
+ try {
+ const { currentOrganization } = await new PluginMarketApi(undefined, () => app.getVersion()).listAll();
+ if (publisherIdentityContextKey() !== contextKey) return null;
+ const current = currentPublisherIdentity();
+ if (!current || current.membershipId !== identity.membershipId) return null;
+ if (current.orgSlug !== null) return current;
+ if (currentOrganization?.organizationId !== organizationId ||
+ !currentOrganization.orgSlug || !ORG_SLUG_RE.test(currentOrganization.orgSlug)) return current;
+ resolvedMarketIdentity = { contextKey, orgSlug: currentOrganization.orgSlug };
+ return { ...current, orgSlug: currentOrganization.orgSlug };
+ } catch {
+ return publisherIdentityContextKey() === contextKey ? currentPublisherIdentity() : null;
+ }
+}
+
+export function publisherAudience(orgSlug: string | null): string {
+ if (!orgSlug || !ORG_SLUG_RE.test(orgSlug)) throw new Error('无法确认发布组织 namespace,请刷新登录后重试');
return `${orgSlug}:${PLUGIN_MEMBER_PUBLISHER_GHOST_ID}`;
}
-function createApi(): PluginPublisherApi {
+export function createPluginPublisherApi(): PluginPublisherApi {
return new PluginPublisherApi({
+ getClientVersion: () => app.getVersion(),
async getToken() {
- const identity = currentPublisherIdentity();
- if (!identity) throw new Error('需要组织身份才能发布插件');
+ const identity = await resolvePublisherIdentity();
+ if (!identity?.orgSlug) throw new Error('无法确认发布组织身份,请刷新登录后重试');
return getConnectionTokenProvider().getToken({
membershipId: identity.membershipId,
audience: publisherAudience(identity.orgSlug),
@@ -72,7 +109,7 @@ function createApi(): PluginPublisherApi {
},
invalidateToken() {
const identity = currentPublisherIdentity();
- if (!identity) return;
+ if (!identity?.orgSlug) return;
getConnectionTokenProvider().invalidate({
membershipId: identity.membershipId,
audience: publisherAudience(identity.orgSlug),
@@ -96,8 +133,8 @@ export function trackPublisherConfirmRequester(contents: WebContents): void {
export function getPluginPublisherOrchestrator(): PluginPublisherOrchestrator {
if (!orchestratorSingleton) {
orchestratorSingleton = createPluginPublisherOrchestrator({
- api: createApi(),
- identity: currentPublisherIdentity,
+ api: createPluginPublisherApi(),
+ identity: resolvePublisherIdentity,
async inspectPackage(filePath) {
const inspected = await getGhostManager().inspect(filePath);
if ('rejection' in inspected) {
@@ -142,11 +179,19 @@ export function getPluginPublisherOrchestrator(): PluginPublisherOrchestrator {
}
if (!authHooked) {
authHooked = true;
- let lastKey = publisherIdentityKey();
+ let lastIdentity = currentPublisherIdentity();
+ let lastContextKey = publisherIdentityContextKey();
onAuthStateChange(() => {
- const nextKey = publisherIdentityKey();
- if (nextKey === lastKey) return;
- lastKey = nextKey;
+ const nextIdentity = currentPublisherIdentity();
+ const nextContextKey = publisherIdentityContextKey();
+ const contextChanged = nextContextKey !== lastContextKey;
+ if (!contextChanged && publisherIdentityKey(nextIdentity) === publisherIdentityKey(lastIdentity)) return;
+ const namespaceEnriched = !contextChanged && lastIdentity?.orgSlug === null &&
+ nextIdentity?.orgSlug != null && nextIdentity.membershipId === lastIdentity.membershipId;
+ lastIdentity = nextIdentity;
+ lastContextKey = nextContextKey;
+ if (namespaceEnriched) return;
+ resolvedMarketIdentity = null;
orchestratorSingleton?.abortAll();
confirmBridge.cancelAll();
});
@@ -155,8 +200,7 @@ export function getPluginPublisherOrchestrator(): PluginPublisherOrchestrator {
return orchestratorSingleton;
}
-function publisherIdentityKey(): string {
- const identity = currentPublisherIdentity();
+function publisherIdentityKey(identity: PluginPublisherIdentity | null): string {
return identity ? `${identity.membershipId}:${identity.orgSlug}` : '';
}
diff --git a/apps/desktop/src/main/plugin-publisher/orchestrator.ts b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
index 7da6c113c5..508563cc3f 100644
--- a/apps/desktop/src/main/plugin-publisher/orchestrator.ts
+++ b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
@@ -32,6 +32,7 @@ import {
PLUGIN_PUBLISHER_POLL_TRANSIENT_BACKOFF_MS,
putDeadlineAtMs,
type PluginPublisherProgress,
+ type PluginPublisherIdentity,
type PluginPublisherStage,
type PluginPublisherStartResult,
} from './types.js';
@@ -56,7 +57,7 @@ export interface PluginPublisherOrchestratorDeps {
},
signal: AbortSignal,
): Promise<boolean>;
- identity(): { membershipId: string; orgSlug: string; orgName: string | null } | null;
+ identity(): PluginPublisherIdentity | null | Promise<PluginPublisherIdentity | null>;
owner?: () => ActiveAppSession;
now?: () => number;
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
@@ -337,11 +338,19 @@ export class PluginPublisherOrchestrator {
this.fail(record, 'INVALID_PARAMS', '只能发布 .cindy 插件包');
return;
}
- const identity = this.deps.identity();
+ const identity = await this.deps.identity();
+ if (signal.aborted || !sameActiveAppSessionOwner(record.owner, this.owner())) {
+ this.update(record, { stage: 'cancelled' });
+ return;
+ }
if (!identity) {
this.fail(record, 'NOT_ORG_MEMBER', '需要组织身份才能发布插件');
return;
}
+ if (!identity.orgSlug) {
+ this.fail(record, 'PUBLISHER_IDENTITY_UNAVAILABLE', '无法确认发布组织 namespace,请刷新登录后重试');
+ return;
+ }
await this.inspectGate.acquire(signal);
let inspected: { ghostId: string; name: string; version: string };
@@ -702,6 +711,7 @@ function isTerminalPublisherClientError(error: PluginPublisherApiError): boolean
}
function mapPublisherApiMessage(error: PluginPublisherApiError): string {
+ if (error.code === 'PLUGIN_NAMESPACE_CLIENT_REQUIRED') return '请更新 Cindy 后再发布此组织的插件';
if (error.status === 403 && error.code === 'FORBIDDEN') {
return '本企业未开启成员发布,请联系管理员';
}
diff --git a/apps/desktop/src/main/plugin-publisher/registerIpc.ts b/apps/desktop/src/main/plugin-publisher/registerIpc.ts
index 01eb0457fb..0058bf8382 100644
--- a/apps/desktop/src/main/plugin-publisher/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-publisher/registerIpc.ts
@@ -6,39 +6,17 @@ import {
} from '../appSessionState.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';
-import { PluginPublisherApi, PluginPublisherApiError } from './api.js';
+import { PluginPublisherApiError } from './api.js';
import {
currentPublisherIdentity,
+ createPluginPublisherApi,
getPluginPublisherConfirmBridge,
getPluginPublisherOrchestrator,
- publisherAudience,
trackPublisherConfirmRequester,
} from './host.js';
-import { getConnectionTokenProvider } from '../cindy-brain/index.js';
let registered = false;
-function publisherApi(): PluginPublisherApi {
- return new PluginPublisherApi({
- async getToken() {
- const identity = currentPublisherIdentity();
- if (!identity) throwIpcError('PERMISSION_DENIED', '需要组织身份才能查看发布');
- return getConnectionTokenProvider().getToken({
- membershipId: identity.membershipId,
- audience: publisherAudience(identity.orgSlug),
- });
- },
- invalidateToken() {
- const identity = currentPublisherIdentity();
- if (!identity) return;
- getConnectionTokenProvider().invalidate({
- membershipId: identity.membershipId,
- audience: publisherAudience(identity.orgSlug),
- });
- },
- });
-}
-
function mapListError(error: unknown): never {
if (error instanceof PluginPublisherApiError) {
if (error.status === 403 && error.code === 'FORBIDDEN') {
@@ -53,7 +31,7 @@ export function registerPluginPublisherIpc(): void {
if (registered) return;
registered = true;
- ipcMain.handle('plugin-publisher:start', (event, _filePath: unknown) => {
+ ipcMain.handle('plugin-publisher:start', (event) => {
assertTrustedAppRendererEvent(event);
// 临时 fail closed:Renderer 自报绝对路径不构成用户授权(XSS 可伪造)。下期重新
// 开放“我的发布”前,必须先由 Main 文件选择器签发一次性 grant,再由 start 消费;
@@ -93,7 +71,7 @@ export function registerPluginPublisherIpc(): void {
? (raw as { cursor: string }).cursor
: undefined;
try {
- return await publisherApi().listMine(cursor);
+ return await createPluginPublisherApi().listMine(cursor);
} catch (error) {
mapListError(error);
}
diff --git a/apps/desktop/src/main/plugin-publisher/types.ts b/apps/desktop/src/main/plugin-publisher/types.ts
index d14d7976b2..cfd9a3f957 100644
--- a/apps/desktop/src/main/plugin-publisher/types.ts
+++ b/apps/desktop/src/main/plugin-publisher/types.ts
@@ -6,6 +6,12 @@ import type {
export const PLUGIN_MEMBER_PUBLISHER_GHOST_ID = 'cindy-publisher';
+export interface PluginPublisherIdentity {
+ membershipId: string;
+ orgSlug: string | null;
+ orgName: string | null;
+}
+
export type PluginPublisherStage =
| 'confirming'
| 'hashing'
diff --git a/apps/desktop/src/main/routines/__tests__/rewriteRoutinePluginSource.test.ts b/apps/desktop/src/main/routines/__tests__/rewriteRoutinePluginSource.test.ts
new file mode 100644
index 0000000000..a052f62061
--- /dev/null
+++ b/apps/desktop/src/main/routines/__tests__/rewriteRoutinePluginSource.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ matchesRoutineEvent,
+ rewriteRoutinePluginSource,
+ type Routine,
+ type RoutineEvent,
+} from '@cindy/maker-scheduler';
+
+describe('rewriteRoutinePluginSource', () => {
+ it('does not deliver the replacement plugin events to routines of the archived source', () => {
+ const archive = 'arch_' + 'b'.repeat(32);
+ const routine = {
+ id: 'r1',
+ enabled: true,
+ triggers: [{
+ id: 't1', kind: 'event', sourceId: 'plugin:helper', eventType: 'mail', filters: [],
+ }],
+ } as unknown as Routine;
+ const event: RoutineEvent = { id: 'e1', type: 'mail', occurredAt: 1, data: {} };
+ const receiptKey = JSON.stringify(['plugin:helper', 'e1']);
+ const state = rewriteRoutinePluginSource({
+ version: 1,
+ routines: [routine],
+ runs: [],
+ receipts: { [receiptKey]: 5 },
+ next: {},
+ }, 'helper', archive);
+ expect(matchesRoutineEvent(state.routines[0]!, 'plugin:helper', event)).toEqual([]);
+ expect(matchesRoutineEvent(state.routines[0]!, `plugin:${archive}`, event)).toEqual(['t1']);
+ expect(state.receipts[JSON.stringify([`plugin:${archive}`, 'e1'])]).toBe(5);
+ expect(state.receipts[receiptKey]).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 38cda29512..f7210abc09 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -5,6 +5,7 @@ import { setTimeout as delay } from 'node:timers/promises';
import { app, BrowserWindow, ipcMain } from 'electron';
import {
RoutineEngine,
+ rewriteRoutinePluginSource,
type Routine,
type RoutineRun,
type RoutineInput,
@@ -462,3 +463,18 @@ export function disconnectRoutineSource(pluginId: string): void {
current.engine.removeSource(`plugin:${pluginId}`);
}
}
+
+/** Follow an archived plugin so the replacement does not inherit its event routines. */
+export async function relocateRoutinePluginSource(fromPart: string, toPart: string): Promise<void> {
+ if (fromPart === toPart) return;
+ const scope = activeOwnerScopeKey();
+ if (current?.scope === scope && !isAppSessionBoundaryPending()) {
+ await current.engine.relocatePluginSource(fromPart, toPart);
+ return;
+ }
+ const store = new RoutineFileStore(ownerScopedUserDataPath());
+ const state = await store.load();
+ if (!state) return;
+ const next = rewriteRoutinePluginSource(state, fromPart, toPart);
+ if (next !== state) await store.save(next);
+}
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
index de00e85aa3..9e1a2b5736 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
@@ -9,6 +9,7 @@ import { GhostCardService } from '../../cindy-brain/cardService.js';
import { GhostFsSlot } from '../../cindy-brain/fsSlot.js';
import { GhostPipeDispatcher } from '../../cindy-brain/pipeDispatcher.js';
import type { GhostPipeToolCall, InstalledGhost } from '../../../shared/ghost.js';
+import { installedGhostStoragePart, resolveInstalledGhost } from '../../../shared/pluginIdentity.js';
import { SchedulerScriptCapabilityBroker } from '../script-capability-broker';
const sendToSessionMock = vi.hoisted(() => vi.fn());
@@ -27,8 +28,12 @@ const callGhostToolMock = vi.hoisted(() =>
// cardService 账本:缺省 void spy(生命周期断言用);端到端用例转发到真实实例。
const registerCallMock = vi.hoisted(() => vi.fn());
const finalizeCallMock = vi.hoisted(() => vi.fn());
+const findAvailableGhostMock = vi.hoisted(() => vi.fn());
+const findTrustedXdGhostMock = vi.hoisted(() => vi.fn());
vi.mock('../../cindy-brain/index.js', () => ({
+ findAvailableGhostForAuthorization: findAvailableGhostMock,
+ findTrustedXdGhostForScript: findTrustedXdGhostMock,
getGhostPipeDispatcher: () => ({ callGhostTool: callGhostToolMock }),
getGhostCardService: () => ({ registerCall: registerCallMock, finalizeCall: finalizeCallMock }),
}));
@@ -77,6 +82,93 @@ describe('SchedulerScriptCapabilityBroker', () => {
callGhostToolMock.mockImplementation(async (request: unknown) => ({ ok: true, result: request }));
registerCallMock.mockReset();
finalizeCallMock.mockReset();
+ mockAvailableGhosts(['xd-atlassian', 'xd-feishu'].map((id) => ({
+ ...makeInstalledGhost(id), namespaceState: 'pending',
+ })), ['xd-atlassian', 'xd-feishu']);
+ });
+
+ it.each([
+ ['xd-atlassian', 'jira.get', { issue_key: 'DING-1' }, 'jira.read'],
+ ['xd-feishu', 'feishu.recent_chats', {}, 'feishu.read'],
+ ] as const)('binds %s to XD instead of a same-name root', async (id, method, params, capability) => {
+ const enterprise = { ...makeInstalledGhost(id), namespace: 'xd', dir: '/fake/ghosts/_ns/xd/' + id };
+ mockAvailableGhosts([{ ...makeInstalledGhost(id), namespace: null }, enterprise]);
+ await new SchedulerScriptCapabilityBroker().call(
+ { method, params }, new Set([capability]), { schedule: schedule() },
+ );
+ expect(callGhostToolMock).toHaveBeenCalledWith(expect.objectContaining({ ghostId: installedGhostStoragePart(enterprise) }));
+ expect(registerCallMock).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ ghostId: installedGhostStoragePart(enterprise) }));
+ expect(findTrustedXdGhostMock).toHaveBeenCalledWith(id);
+ expect(findAvailableGhostMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['xd-atlassian', 'xd-feishu'])('rejects a confirmed root impersonating %s before registration', async (id) => {
+ mockAvailableGhosts([{ ...makeInstalledGhost(id), namespace: null }]);
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ id === 'xd-atlassian'
+ ? { method: 'jira.get', params: { issue_key: 'DING-1' } }
+ : { method: 'feishu.recent_chats', params: {} },
+ new Set(['jira.read', 'feishu.read']), { schedule: schedule() },
+ )).rejects.toMatchObject({ code: 'GHOST_NOT_FOUND' });
+ expect(registerCallMock).not.toHaveBeenCalled();
+ expect(callGhostToolMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { namespace: 'other-org' },
+ {},
+ { namespace: null, namespaceState: 'pending' as const },
+ ])('rejects an unverified or foreign install: %j', async (identity) => {
+ mockAvailableGhosts([{ ...makeInstalledGhost('xd-atlassian'), ...identity }]);
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.get', params: { issue_key: 'DING-1' } },
+ new Set(['jira.read']), { schedule: schedule() },
+ )).rejects.toMatchObject({ code: 'GHOST_NOT_FOUND' });
+ expect(registerCallMock).not.toHaveBeenCalled();
+ expect(callGhostToolMock).not.toHaveBeenCalled();
+ });
+
+ it('preserves an approved pre-namespace XD install captured as pending', async () => {
+ mockAvailableGhosts([{ ...makeInstalledGhost('xd-atlassian'), namespaceState: 'pending' }], ['xd-atlassian']);
+ await new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.get', params: { issue_key: 'DING-1' } },
+ new Set(['jira.read']), { schedule: schedule() },
+ );
+ expect(callGhostToolMock).toHaveBeenCalledWith(expect.objectContaining({ ghostId: 'xd-atlassian' }));
+ });
+
+ it.each(['xd-atlassian', 'xd-feishu'])('does not authorize an approved pending ordinary root %s', async (id) => {
+ mockAvailableGhosts([{ ...makeInstalledGhost(id), namespaceState: 'pending' }]);
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ id === 'xd-atlassian'
+ ? { method: 'jira.get', params: { issue_key: 'DING-1' } }
+ : { method: 'feishu.recent_chats', params: {} },
+ new Set(['jira.read', 'feishu.read']), { schedule: schedule() },
+ )).rejects.toMatchObject({ code: 'GHOST_NOT_FOUND' });
+ expect(registerCallMock).not.toHaveBeenCalled();
+ expect(callGhostToolMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['legacy-unapproved', 'invalid'] as const)('rejects a pending install with %s approval', async (state) => {
+ mockAvailableGhosts([{
+ ...makeInstalledGhost('xd-atlassian'), namespaceState: 'pending', approval: { state },
+ }]);
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.get', params: { issue_key: 'DING-1' } },
+ new Set(['jira.read']), { schedule: schedule() },
+ )).rejects.toMatchObject({ code: 'GHOST_NOT_FOUND' });
+ expect(registerCallMock).not.toHaveBeenCalled();
+ expect(callGhostToolMock).not.toHaveBeenCalled();
+ });
+
+ it('checks the resolved manifest rather than trusting a mismatched lookup result', async () => {
+ findTrustedXdGhostMock.mockReturnValue({ ...makeInstalledGhost('other-plugin'), namespace: 'xd' });
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.get', params: { issue_key: 'DING-1' } },
+ new Set(['jira.read']), { schedule: schedule() },
+ )).rejects.toMatchObject({ code: 'GHOST_NOT_FOUND' });
+ expect(registerCallMock).not.toHaveBeenCalled();
+ expect(callGhostToolMock).not.toHaveBeenCalled();
});
it('maps Jira reads to the current xd-atlassian argument contract', async () => {
@@ -668,8 +760,7 @@ describe('SchedulerScriptCapabilityBroker', () => {
const { fsSlot } = wireRealChannel(tmp);
// 真实 dispatcher:资格审 + callId 配对 + 错误折叠全真,只有「意识进程」
// 本身由 sendToGhost 内联模拟(先经 fs 槽写盘,再 handleToolResult 交卷)。
- let dispatcher!: GhostPipeDispatcher;
- dispatcher = new GhostPipeDispatcher({
+ const dispatcher = new GhostPipeDispatcher({
getGhost: (id) => (id === 'xd-atlassian' ? makeInstalledGhost(id) : null),
runtimeStateOf: () => 'running',
spawn: async () => ({ ok: true }),
@@ -709,6 +800,57 @@ describe('SchedulerScriptCapabilityBroker', () => {
}
});
+ it('writes namespaced out_file through the real dispatcher, card service and fs slot', async () => {
+ const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-ns-pipe-'));
+ try {
+ const installed = { ...makeInstalledGhost('xd-atlassian'), namespace: 'xd', dir: path.join(tmp, '_ns', 'xd', 'xd-atlassian') };
+ mockAvailableGhosts([installed]);
+ const instanceId = installedGhostStoragePart(installed);
+ const { fsSlot } = wireRealChannel(tmp, installed);
+ let offPathResult: { ok: boolean } | undefined;
+ const dispatcher: GhostPipeDispatcher = new GhostPipeDispatcher({
+ getGhost: (id) => id === instanceId || id === installed.manifest.id ? installed : null,
+ runtimeStateOf: () => 'running',
+ spawn: async () => ({ ok: true }),
+ sendToGhost: (ghostId, payload) => {
+ void (async () => {
+ const outFile = (payload.args as Record<string, unknown>).out_file as string;
+ const result = await fsSlot.handleFsRequest(ghostId, {
+ op: 'write', root: 'workdir', callId: payload.callId, path: outFile, content: 'namespaced result',
+ });
+ offPathResult = await fsSlot.handleFsRequest(ghostId, {
+ op: 'write', root: 'workdir', callId: payload.callId, path: 'other.json', content: 'forbidden',
+ });
+ dispatcher.handleToolResult(ghostId, result.ok
+ ? { callId: payload.callId, ok: true, result: { saved_to: outFile } }
+ : { callId: payload.callId, ok: false, errorCode: 'INTERNAL', message: result.message });
+ })();
+ return true;
+ },
+ timeoutMs: 1_000,
+ });
+ callGhostToolMock.mockImplementation((request: unknown) => dispatcher.callGhostTool(
+ request as { ghostId: string; tool: string; args: Record<string, unknown> },
+ ));
+
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ { method: 'jira.get', params: { issue_key: 'DING-1', out_file: 'reports/result.json' } },
+ new Set(['jira.read']), { schedule: schedule({ workingDir: tmp }) },
+ )).resolves.toEqual({ saved_to: 'reports/result.json' });
+ expect(await fs.promises.readFile(path.join(tmp, 'reports/result.json'), 'utf8')).toBe('namespaced result');
+ expect(offPathResult).toMatchObject({ ok: false });
+ expect(fs.existsSync(path.join(tmp, 'other.json'))).toBe(false);
+ const callId = registerCallMock.mock.calls[0][0] as string;
+ expect(registerCallMock.mock.calls[0][1]).toMatchObject({ ghostId: instanceId });
+ expect(await fsSlot.handleFsRequest(instanceId, {
+ op: 'write', root: 'workdir', callId, path: 'reports/result.json', content: 'late result',
+ })).toMatchObject({ ok: false });
+ expect(await fs.promises.readFile(path.join(tmp, 'reports/result.json'), 'utf8')).toBe('namespaced result');
+ } finally {
+ await fs.promises.rm(tmp, { recursive: true, force: true });
+ }
+ });
+
it('传输层异常(callGhostTool reject)同样 finalize,旧 callId 立即失在途资格', async () => {
const tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'broker-reject-'));
try {
@@ -844,12 +986,29 @@ function makeInstalledGhost(id: string): InstalledGhost {
};
}
+function mockAvailableGhosts(ghosts: InstalledGhost[], trustedLegacyIds: string[] = []): void {
+ findAvailableGhostMock.mockReset();
+ findAvailableGhostMock.mockImplementation((id: string, namespace?: string | null) => {
+ const resolved = resolveInstalledGhost(ghosts, id, namespace);
+ return resolved.status === 'unique' ? resolved.ghost : null;
+ });
+ findTrustedXdGhostMock.mockReset();
+ findTrustedXdGhostMock.mockImplementation((id: string) => {
+ const explicit = resolveInstalledGhost(ghosts, id, 'xd');
+ if (explicit.status === 'unique') return explicit.ghost;
+ const legacy = resolveInstalledGhost(ghosts, id);
+ return legacy.status === 'unique' && trustedLegacyIds.includes(installedGhostStoragePart(legacy.ghost))
+ ? legacy.ghost
+ : null;
+ });
+}
+
/**
* 端到端 harness:真实 GhostCardService + 真实 GhostFsSlot,把 broker 的
* mock 边界(register/finalize)接到真实账本——用例只需替换意识行为
* (callGhostToolMock 的实现),其余链路全真。
*/
-function wireRealChannel(tmp: string): { cardService: GhostCardService; fsSlot: GhostFsSlot } {
+function wireRealChannel(tmp: string, installed = makeInstalledGhost('xd-atlassian')): { cardService: GhostCardService; fsSlot: GhostFsSlot } {
const cardService = new GhostCardService({
hasCardSlot: () => false,
sanitize: (html: string) => ({ ok: true, html }),
@@ -857,7 +1016,7 @@ function wireRealChannel(tmp: string): { cardService: GhostCardService; fsSlot:
broadcast: () => {},
});
const fsSlot = new GhostFsSlot({
- getGhost: (id) => (id === 'xd-atlassian' ? makeInstalledGhost(id) : null),
+ getGhost: (id) => id === installedGhostStoragePart(installed) ? installed : null,
dataRootDir: () => path.join(tmp, 'ghost-fs'),
callInfo: (callId) => cardService.callInfoOf(callId),
inFlightCallInfo: (callId) => cardService.inFlightCallInfoOf(callId),
diff --git a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
index a7a5c37aef..7b19c9602c 100644
--- a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
+++ b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
@@ -4,7 +4,12 @@ import { isAbsolute } from 'node:path';
import type { Schedule, ScriptCapability } from '@cindy/maker-scheduler';
import type { GhostToolCallResult } from '../../shared/ghost.js';
-import { getGhostCardService, getGhostPipeDispatcher } from '../cindy-brain/index.js';
+import { hasDeliveryNamespace, installedGhostStoragePart } from '../../shared/pluginIdentity.js';
+import {
+ findTrustedXdGhostForScript,
+ getGhostCardService,
+ getGhostPipeDispatcher,
+} from '../cindy-brain/index.js';
import { validateFsRelPath } from '../cindy-brain/fsSlot.js';
import { tryGetOrcaCollabService } from '../maker-ipc/register.js';
import type { ScriptCapabilityBroker, ScriptCapabilityCall } from './script-runner';
@@ -72,6 +77,15 @@ async function callGhostForScript(
active: Map<string, Set<string>>,
writePath: string | null,
): Promise<GhostToolCallResult> {
+ const ghost = findTrustedXdGhostForScript(request.ghostId);
+ const pendingLegacy = ghost?.namespaceState === 'pending'
+ && !hasDeliveryNamespace(ghost) && ghost.approval.state === 'approved';
+ // Unconfirmed still projects the last namespace. That is not a grant.
+ if (!ghost || ghost.manifest.id !== request.ghostId || ghost.namespaceState === 'unconfirmed' ||
+ (ghost.namespace !== 'xd' && !pendingLegacy)) {
+ fail('GHOST_NOT_FOUND', 'XD plugin ' + request.ghostId + ' is not available in the current session');
+ }
+ const ghostId = installedGhostStoragePart(ghost);
const callId = randomUUID();
// 登记值与 script-runner 的 spawn cwd 严格同源(同一字符串,不 trim 改写):
// POSIX 允许首尾空白的目录名,trim 后登记会让授权根与脚本实际 cwd 分叉
@@ -86,7 +100,7 @@ async function callGhostForScript(
const scriptWorkdir = writePath !== null && rawWorkdir.trim() && isAbsolute(rawWorkdir) ? rawWorkdir : null;
const cardService = getGhostCardService();
cardService.registerCall(callId, {
- ghostId: request.ghostId,
+ ghostId,
toolUseId: null,
sessionId: null,
scriptWorkdir,
@@ -100,7 +114,7 @@ async function callGhostForScript(
}
bucket.add(callId);
try {
- return await getGhostPipeDispatcher().callGhostTool({ ...request, callId });
+ return await getGhostPipeDispatcher().callGhostTool({ ...request, ghostId, callId });
} finally {
bucket.delete(callId);
if (bucket.size === 0) active.delete(runId);
diff --git a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
index a0b4ea865e..0eae2c4dc9 100644
--- a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
+++ b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts
@@ -51,6 +51,8 @@ import {
readCustomProviderKeyForMutation,
readGhostSecretStrict,
readGhostSecretTailFromIo,
+ migrateGhostSecrets,
+ setMivoSecretAliasVerifier,
resolveOwnerScopedSecretStorageKey,
setProviderSecretsClearedListener,
UNRECOVERABLE_PROVIDER_CREDENTIAL,
@@ -91,6 +93,47 @@ function createMemoryIo(): SecretStorageIo & { store: Map<string, string> } {
};
}
+describe('ghost secret relocation rollback', () => {
+ const source = ghostSecretStorageKey('helper', 'one');
+ const destination = ghostSecretStorageKey('_ns__acme__helper', 'one');
+ const secondSource = ghostSecretStorageKey('helper', 'two');
+ const secondDestination = ghostSecretStorageKey('_ns__acme__helper', 'two');
+
+ it('keeps the destination when restoring the only old copy fails', () => {
+ const io = createMemoryIo();
+ io.store.set(source, 'fake-one');
+ io.store.set(secondSource, 'fake-two');
+ const write = io.write;
+ const remove = io.remove;
+ io.write = (key, value) => key === source ? false : write(key, value);
+ io.remove = (key) => key === secondSource ? { success: false } : remove(key);
+ expect(() => migrateGhostSecrets('helper', '_ns__acme__helper', io)).toThrow();
+ expect(io.store.get(destination)).toBe('fake-one');
+ expect(io.store.has(source)).toBe(false);
+ expect(io.store.get(secondSource)).toBe('fake-two');
+ expect(io.store.has(secondDestination)).toBe(false);
+ });
+
+ it('rolls back the current write if removing its source fails', () => {
+ const io = createMemoryIo();
+ io.store.set(source, 'fake-one');
+ io.remove = (key) => key === source ? { success: false } : (io.store.delete(key), { success: true });
+ expect(() => migrateGhostSecrets('helper', '_ns__acme__helper', io)).toThrow();
+ expect(io.store.get(source)).toBe('fake-one');
+ expect(io.store.has(destination)).toBe(false);
+ });
+
+ it('does not delete a same-valued destination that predates a later rollback', () => {
+ const io = createMemoryIo();
+ io.store.set(source, 'fake-one');
+ io.store.set(destination, 'fake-one');
+ const undo = migrateGhostSecrets('helper', '_ns__acme__helper', io);
+ undo();
+ expect(io.store.get(source)).toBe('fake-one');
+ expect(io.store.get(destination)).toBe('fake-one');
+ });
+});
+
describe('providerSecrets registry', () => {
it('maps known providers to their stable storage keys', () => {
expect(providerSecretStorageKey('xd')).toBe('api_key');
@@ -153,6 +196,28 @@ describe('providerSecrets registry', () => {
expect(() => ghostSecretStorageKey('ok', 'k.ey')).toThrow(/illegal characters/);
});
+ it('企业实例 storage part 与 root 凭证键隔离,且不继承官方别名', () => {
+ expect(ghostSecretStorageKey('helper', 'token')).toBe('ghost_secret_helper_token');
+ expect(ghostSecretStorageKey('_ns__acme__helper', 'token')).toBe(
+ 'ghost_secret__ns__acme__helper_token',
+ );
+ expect(ghostSecretHintStorageKey('_ns__acme__helper', 'token')).toBe(
+ 'ghost_hint__ns__acme__helper_token',
+ );
+ expect(ghostSecretStorageKey('_ns__xd__xd-mivo', 'mivo_api_key', true)).toBe(
+ 'ghost_secret__ns__xd__xd-mivo_mivo_api_key',
+ );
+ expect(ghostSecretStorageKey('_ns__xd__xd-mivo', 'mivo_api_key', true)).not.toBe(
+ ghostSecretStorageKey('xd-mivo', 'mivo_api_key', true),
+ );
+ expect(ghostSecretStorageKey('_ns__acme__xd-mivo', 'mivo_api_key')).toBe(
+ 'ghost_secret__ns__acme__xd-mivo_mivo_api_key',
+ );
+ expect(ghostSecretStorageKey('_ns__acme__xd-mivo', 'mivo_api_key')).not.toBe(
+ ghostSecretStorageKey('xd-mivo', 'mivo_api_key', true),
+ );
+ });
+
it('官方别名:cindy-web-search 的凭证映射到历史 brave/tavily 存储键(老用户零迁移)', () => {
// 与「工具密钥」时代同一 .enc 文件:老用户已填 key 对意识立即生效,
// lizi_web_search MCP 也照读同一份。
@@ -164,7 +229,9 @@ describe('providerSecrets registry', () => {
});
it('官方别名:xd-mivo 的 mivo_api_key 映射到历史 mivo 存储键(老用户零迁移)', () => {
- expect(ghostSecretStorageKey('xd-mivo', 'mivo_api_key')).toBe(providerSecretStorageKey('mivo'));
+ expect(ghostSecretStorageKey('xd-mivo', 'mivo_api_key', true)).toBe(providerSecretStorageKey('mivo'));
+ expect(ghostSecretStorageKey('xd-mivo', 'mivo_api_key')).not.toBe(providerSecretStorageKey('mivo'));
+ expect(ghostSecretStorageKey('_ns__xd__xd-mivo', 'mivo_api_key')).not.toBe(providerSecretStorageKey('mivo'));
expect(ghostSecretStorageKey('xd-mivo', 'other_key')).toBe('ghost_secret_xd-mivo_other_key');
expect(ghostSecretStorageKey('third-party', 'mivo_api_key')).toBe('ghost_secret_third-party_mivo_api_key');
});
@@ -359,9 +426,21 @@ describe('readGhostSecretTailFromIo(尾指纹读取 + 老键懒回填)', () => {
});
it('官方别名键(xd-mivo 老用户)同样能懒回填', () => {
- io.store.set(ghostSecretStorageKey('xd-mivo', 'mivo_api_key'), 'mivo_legacy_key_9999');
+ setMivoSecretAliasVerifier((id) => id === 'xd-mivo');
+ io.store.set(ghostSecretStorageKey('xd-mivo', 'mivo_api_key', true), 'mivo_legacy_key_9999');
expect(readGhostSecretTailFromIo(io, 'xd-mivo', 'mivo_api_key')).toBe('9999');
expect(io.store.get(ghostSecretHintStorageKey('xd-mivo', 'mivo_api_key'))).toBe('9999');
+ setMivoSecretAliasVerifier(null);
+ });
+
+ it('a name-only Mivo cannot read the historical secret or its cached hint', () => {
+ io.store.set(ghostSecretStorageKey('xd-mivo', 'mivo_api_key', true), 'mivo_legacy_key_9999');
+ io.store.set(ghostSecretHintStorageKey('xd-mivo', 'mivo_api_key'), '9999');
+ setMivoSecretAliasVerifier(null);
+ expect(readGhostSecretTailFromIo(io, 'xd-mivo', 'mivo_api_key')).toBeNull();
+ setMivoSecretAliasVerifier((id) => id === 'xd-mivo');
+ expect(readGhostSecretTailFromIo(io, 'xd-mivo', 'mivo_api_key')).toBe('9999');
+ setMivoSecretAliasVerifier(null);
});
it('没存过 / 值太短不产指纹 → null 且不落回填键', () => {
diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.ts
index 0320d98347..b4e264b501 100644
--- a/apps/desktop/src/main/secrets/providerSecretStore.ts
+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts
@@ -38,6 +38,30 @@ import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';
const log = createLogger('providerSecretStore');
+let canUseMivoAlias: ((instanceKey: string) => boolean) | null = null;
+
+export function setMivoSecretAliasVerifier(verifier: ((instanceKey: string) => boolean) | null): void {
+ canUseMivoAlias = verifier;
+}
+
+function approvedGhostSecretStorageKey(instanceKey: string, secretKey: string): string {
+ return ghostSecretStorageKey(instanceKey, secretKey, canUseMivoAlias?.(instanceKey) === true);
+}
+
+function approvedGhostSecretHintKey(instanceKey: string, secretKey: string): string {
+ // The historical hint stays on the standard key only while the same install
+ // fact maps the secret onto the historical Mivo key. Otherwise the hint
+ // follows the non-alias key, so read, write, and delete stay together.
+ if (
+ instanceKey === 'xd-mivo' &&
+ secretKey === 'mivo_api_key' &&
+ canUseMivoAlias?.(instanceKey) !== true
+ ) {
+ return 'ghost_hint__local__' + instanceKey + '_' + secretKey;
+ }
+ return ghostSecretHintStorageKey(instanceKey, secretKey);
+}
+
/**
* 记录「本机这批 provider 密钥归属哪个账号」的标记键(非密钥,存同目录便于统一管理)。
* 用于账号边界:登录 / 冷启动确立 userId 后,若 owner 与之不同(同机换账号),清掉
@@ -210,9 +234,11 @@ const electronSecretIo: SecretStorageIo = {
.readdirSync(secretDir())
.filter((f) => f.startsWith(prefix) && f.endsWith('.enc'))
.map((f) => f.slice(prefix.length, -'.enc'.length));
- } catch {
- // 目录不存在(尚无任何密钥落盘)等 → 空列表。
- return [];
+ } catch (err) {
+ if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT') {
+ return [];
+ }
+ throw err;
}
},
};
@@ -680,12 +706,12 @@ export function readCustomMcpToken(mcpId: string): string | null {
* 不存在 / safeStorage 不可用 / 读失败均返回 null。与 renderer 经通用
* safe-storage IPC 写入的 .enc 文件字节级互通。凭证值从不进日志(只记 id)。
*/
-export function readGhostSecret(ghostId: string, secretKey: string): string | null {
+export function readGhostSecret(instanceKey: string, secretKey: string): string | null {
try {
- return electronSecretIo.read(ghostSecretStorageKey(ghostId, secretKey));
+ return electronSecretIo.read(approvedGhostSecretStorageKey(instanceKey, secretKey));
} catch (err) {
log.warn(
- { ghostId, secretKey, err: err instanceof Error ? err.message : String(err) },
+ { ghostId: instanceKey, secretKey, err: err instanceof Error ? err.message : String(err) },
'read ghost secret failed',
);
return null;
@@ -697,9 +723,9 @@ export function readGhostSecret(ghostId: string, secretKey: string): string | nu
* normal null result, while keychain, IO, and decrypt failures remain errors
* so the durable coordinator can retry instead of memoizing a false no-op.
*/
-export function readGhostSecretStrict(ghostId: string, secretKey: string): string | null {
+export function readGhostSecretStrict(instanceKey: string, secretKey: string): string | null {
const physicalKey = resolveOwnerScopedSecretStorageKey(
- ghostSecretStorageKey(ghostId, secretKey),
+ approvedGhostSecretStorageKey(instanceKey, secretKey),
);
if (!physicalKey) return null;
const filepath = path.join(secretDir(), `${physicalKey}.enc`);
@@ -725,10 +751,10 @@ export function readGhostSecretStrict(ghostId: string, secretKey: string): strin
* 调用方(ghosts:setup-status)让 invoke reject,renderer 侧 fail-open。
* 键名走 ghostSecretStorageKey(官方别名同 read 侧)。
*/
-export function ghostSecretSaved(ghostId: string, secretKey: string): boolean {
+export function ghostSecretSaved(instanceKey: string, secretKey: string): boolean {
try {
const physicalKey = resolveOwnerScopedSecretStorageKey(
- ghostSecretStorageKey(ghostId, secretKey),
+ approvedGhostSecretStorageKey(instanceKey, secretKey),
);
if (!physicalKey) return false;
fs.statSync(path.join(secretDir(), `${physicalKey}.enc`));
@@ -745,20 +771,20 @@ export function ghostSecretSaved(ghostId: string, secretKey: string): boolean {
* 键名走 ghostSecretStorageKey(官方别名同 read 侧),与 renderer 写入的
* .enc 文件字节级互通。凭证值从不进日志(只记 id)。
*/
-export function storeGhostSecret(ghostId: string, secretKey: string, value: string): boolean {
+export function storeGhostSecret(instanceKey: string, secretKey: string, value: string): boolean {
try {
- const ok = electronSecretIo.write(ghostSecretStorageKey(ghostId, secretKey), value);
+ const ok = electronSecretIo.write(approvedGhostSecretStorageKey(instanceKey, secretKey), value);
if (ok) {
// 入库即截尾 4 位指纹(分键保管,读路径永不碰明文);值太短不产指纹,
// 且要清掉旧值可能留下的指纹。指纹写失败不连坐主凭证(best-effort)。
try {
const tail = deriveGhostSecretTail(value);
- const hintKey = ghostSecretHintStorageKey(ghostId, secretKey);
+ const hintKey = approvedGhostSecretHintKey(instanceKey, secretKey);
if (tail) electronSecretIo.write(hintKey, tail);
else electronSecretIo.remove(hintKey);
} catch (err) {
log.warn(
- { ghostId, secretKey, err: err instanceof Error ? err.message : String(err) },
+ { ghostId: instanceKey, secretKey, err: err instanceof Error ? err.message : String(err) },
'store ghost secret tail failed',
);
}
@@ -766,7 +792,7 @@ export function storeGhostSecret(ghostId: string, secretKey: string, value: stri
return ok;
} catch (err) {
log.warn(
- { ghostId, secretKey, err: err instanceof Error ? err.message : String(err) },
+ { ghostId: instanceKey, secretKey, err: err instanceof Error ? err.message : String(err) },
'store ghost secret failed',
);
return false;
@@ -782,22 +808,21 @@ export function storeGhostSecret(ghostId: string, secretKey: string, value: stri
* io 可注入以便单测;生产走 electronSecretIo 包装。
*/
export function readGhostSecretTailFromIo(
- io: SecretStorageIo,
- ghostId: string,
+ io: SecretStorageIo, instanceKey: string,
secretKey: string,
): string | null {
try {
- const hintKey = ghostSecretHintStorageKey(ghostId, secretKey);
+ const hintKey = approvedGhostSecretHintKey(instanceKey, secretKey);
const existing = io.read(hintKey);
if (existing !== null) return existing;
- const value = io.read(ghostSecretStorageKey(ghostId, secretKey));
+ const value = io.read(approvedGhostSecretStorageKey(instanceKey, secretKey));
if (value === null) return null;
const tail = deriveGhostSecretTail(value);
if (tail) io.write(hintKey, tail);
return tail;
} catch (err) {
log.warn(
- { ghostId, secretKey, err: err instanceof Error ? err.message : String(err) },
+ { ghostId: instanceKey, secretKey, err: err instanceof Error ? err.message : String(err) },
'read ghost secret tail failed',
);
return null;
@@ -805,18 +830,20 @@ export function readGhostSecretTailFromIo(
}
/** readGhostSecretTailFromIo 的生产入口(默认 safeStorage IO)。 */
-export function readGhostSecretTail(ghostId: string, secretKey: string): string | null {
- return readGhostSecretTailFromIo(electronSecretIo, ghostId, secretKey);
+export function readGhostSecretTail(instanceKey: string, secretKey: string): string | null {
+ return readGhostSecretTailFromIo(electronSecretIo, instanceKey, secretKey);
}
/** 清除某意识的单条 network 槽凭证(/secrets DELETE 用;幂等,连同尾指纹)。 */
-export function removeGhostSecret(ghostId: string, secretKey: string): void {
+export function removeGhostSecret(instanceKey: string, secretKey: string): void {
try {
- electronSecretIo.remove(ghostSecretStorageKey(ghostId, secretKey));
- electronSecretIo.remove(ghostSecretHintStorageKey(ghostId, secretKey));
+ electronSecretIo.remove(approvedGhostSecretStorageKey(instanceKey, secretKey));
+ electronSecretIo.remove(approvedGhostSecretHintKey(instanceKey, secretKey));
+ // Older builds wrote untrusted Mivo hints under a third key. Delete covers it too.
+ electronSecretIo.remove('ghost_hint__local__' + instanceKey + '_' + secretKey);
} catch (err) {
log.warn(
- { ghostId, secretKey, err: err instanceof Error ? err.message : String(err) },
+ { ghostId: instanceKey, secretKey, err: err instanceof Error ? err.message : String(err) },
'remove ghost secret failed',
);
}
@@ -824,23 +851,109 @@ export function removeGhostSecret(ghostId: string, secretKey: string): void {
/**
* 清掉某意识名下的全部 network 槽凭证(卸载意识时调用;幂等)。
- * 按 `ghost_secret_<ghostId>_` 前缀扫 io.list(),不依赖清单里的 secrets
+ * 按 `ghost_secret_<instanceKey>_` 前缀扫 io.list(),不依赖清单里的 secrets
* 声明——旧版本声明过、新版本删掉的孤儿键也一并清。
*/
-export function removeGhostSecrets(ghostId: string): void {
- const prefixes = [`${GHOST_SECRET_PREFIX}${ghostId}_`, `${GHOST_SECRET_HINT_PREFIX}${ghostId}_`];
+export function removeGhostSecrets(instanceKey: string): void {
+ const prefixes = [
+ `${GHOST_SECRET_PREFIX}${instanceKey}_`,
+ `${GHOST_SECRET_HINT_PREFIX}${instanceKey}_`,
+ `ghost_hint__local__${instanceKey}_`,
+ ];
try {
for (const key of electronSecretIo.list()) {
if (prefixes.some((prefix) => key.startsWith(prefix))) electronSecretIo.remove(key);
}
} catch (err) {
log.warn(
- { ghostId, err: err instanceof Error ? err.message : String(err) },
+ { ghostId: instanceKey, err: err instanceof Error ? err.message : String(err) },
'remove ghost secrets failed',
);
}
}
+function ghostSecretRelocationPrefixes(fromGhostId: string, toGhostId: string): Array<[string, string]> {
+ return [
+ [`${GHOST_SECRET_PREFIX}${fromGhostId}_`, `${GHOST_SECRET_PREFIX}${toGhostId}_`],
+ [`${GHOST_SECRET_HINT_PREFIX}${fromGhostId}_`, `${GHOST_SECRET_HINT_PREFIX}${toGhostId}_`],
+ [`ghost_hint__local__${fromGhostId}_`, `${GHOST_SECRET_HINT_PREFIX}${toGhostId}_`],
+ ];
+}
+
+/** Rename ghost_secret_/ghost_hint_ keys after a physical relocate. Conflicts fail closed. */
+export function assertGhostSecretsCanRelocate(fromGhostId: string, toGhostId: string): void {
+ if (fromGhostId === toGhostId) return;
+ for (const key of electronSecretIo.list()) {
+ for (const [sourcePrefix, destinationPrefix] of ghostSecretRelocationPrefixes(fromGhostId, toGhostId)) {
+ if (!key.startsWith(sourcePrefix)) continue;
+ const destination = `${destinationPrefix}${key.slice(sourcePrefix.length)}`;
+ const value = electronSecretIo.read(key);
+ if (value === null) throw new Error('relocate source secret is unreadable');
+ const existing = electronSecretIo.read(destination);
+ if (existing !== null && existing !== value) {
+ throw new Error('relocate secret destination already exists');
+ }
+ }
+ }
+}
+
+export function migrateGhostSecrets(
+ fromGhostId: string,
+ toGhostId: string,
+ io: SecretStorageIo = electronSecretIo,
+): () => void {
+ if (fromGhostId === toGhostId) return () => {};
+ const pairs = ghostSecretRelocationPrefixes(fromGhostId, toGhostId);
+ const moves: Array<{ from: string; to: string; value: string; destinationExisted: boolean }> = [];
+ for (const key of io.list()) {
+ for (const [fromPrefix, toPrefix] of pairs) {
+ if (!key.startsWith(fromPrefix)) continue;
+ const dest = `${toPrefix}${key.slice(fromPrefix.length)}`;
+ const value = io.read(key);
+ if (value === null) throw new Error('relocate source secret is unreadable');
+ const existing = io.read(dest);
+ if (existing !== null && existing !== value) {
+ throw new Error(`relocate secret destination already exists: ${dest}`);
+ }
+ moves.push({ from: key, to: dest, value, destinationExisted: existing !== null });
+ break;
+ }
+ }
+ const attempted: typeof moves = [];
+ const rollback = () => {
+ let failure: unknown;
+ for (const move of [...attempted].reverse()) {
+ try {
+ const sourceRestored = io.read(move.from) === move.value || io.write(move.from, move.value);
+ if (!sourceRestored) throw new Error('failed to restore relocated secret: ' + move.from);
+ if (!move.destinationExisted && !io.remove(move.to).success) {
+ throw new Error('failed to remove relocated secret: ' + move.to);
+ }
+ } catch (error) {
+ failure ??= error;
+ }
+ }
+ if (failure) throw failure;
+ };
+ try {
+ for (const move of moves) {
+ attempted.push(move);
+ if (io.read(move.to) !== move.value && !io.write(move.to, move.value)) {
+ throw new Error(`failed to write relocated secret: ${move.to}`);
+ }
+ if (!io.remove(move.from).success) {
+ throw new Error(`failed to remove relocated secret: ${move.from}`);
+ }
+ }
+ } catch (error) {
+ try { rollback(); } catch (rollbackError) {
+ void rollbackError;
+ }
+ throw error;
+ }
+ return rollback;
+}
+
export const genericOAuthSecretIo = {
read(providerId: string): string | null {
try {
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index 88ba90e9c7..fdd57be5db 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -32,7 +32,8 @@ import {
LOGIN_CAPTCHA_PAGE_PATH,
LOGIN_CAPTCHA_PARTITION,
} from '../shared/webviewPartition';
-import { GHOST_PARTITION_PREFIX } from '../shared/ghost';
+import { GHOST_PARTITION_PREFIX, ghostInstallApprovalToken, type GhostPanelMediaTarget } from '../shared/ghost';
+import { installedGhostStoragePart } from '../shared/pluginIdentity';
import { getActiveAppSession, type AppSessionMode } from './appSessionState.js';
import {
matchesElectronInput,
@@ -47,6 +48,7 @@ import {
resolveGhostWebviewAttach,
} from './cindy-brain/index.js';
import { classifyGhostPanelNavigation } from './cindy-brain/previewGate.js';
+import { ghostMediaHandoverDragScript, ghostMediaHandoverTargetTracker } from './cindy-brain/ghostMediaHandoverTargetTracker.js';
import { registerGhostWebContents } from './cindy-brain/runtime/electronSandboxAdapter.js';
import {
attributeRsbNativePopupSurface,
@@ -177,7 +179,7 @@ export function authorizeGhostWebviewAttach(
webPreferences: Record<string, unknown>,
params: Record<string, string>,
resolver: GhostWebviewAttachResolver = resolveGhostWebviewAttach,
-): { id: string; owner: { mode: AppSessionMode; dataOwnerId: string } } | null {
+): { id: string; instanceId: string; owner: { mode: AppSessionMode; dataOwnerId: string }; isCurrent(): boolean } | null {
let resolved: ReturnType<GhostWebviewAttachResolver> = null;
try {
resolved = resolver(params.partition, params.src);
@@ -186,13 +188,38 @@ export function authorizeGhostWebviewAttach(
}
if (!resolved) return null;
+ const partitionClaim = params.partition;
+ const entryUrl = params.src;
+ const generation = getActiveAppSession().generation;
+ const instanceId = installedGhostStoragePart(resolved.ghost);
+ const approval = ghostInstallApprovalToken(resolved.ghost.approval);
+ const directory = resolved.ghost.dir;
+ const version = resolved.ghost.manifest.version;
+ const owner = resolved.owner;
+
// Electron 在触发 will-attach-webview 前已经把 params.partition 复制进
// webPreferences.partition,之后创建 guest 时读取的是后者。两边都必须由
// Main 的核准结果覆盖,否则只改 attribute dict 不会改变真实 session。
params.partition = resolved.partition;
webPreferences.partition = resolved.partition;
applyGhostWebviewHardening(webPreferences, params);
- return { id: resolved.ghost.manifest.id, owner: resolved.owner };
+ return {
+ id: resolved.ghost.manifest.id,
+ instanceId,
+ owner: resolved.owner,
+ isCurrent: () => {
+ const active = getActiveAppSession();
+ if (active.generation !== generation || active.mode !== owner.mode || active.dataOwnerId !== owner.dataOwnerId) return false;
+ try {
+ const current = resolver(partitionClaim, entryUrl);
+ return current !== null && current.owner.mode === owner.mode && current.owner.dataOwnerId === owner.dataOwnerId
+ && installedGhostStoragePart(current.ghost) === instanceId && current.ghost.dir === directory
+ && current.ghost.manifest.version === version && ghostInstallApprovalToken(current.ghost.approval) === approval;
+ } catch {
+ return false;
+ }
+ },
+ };
}
/**
@@ -806,7 +833,14 @@ export function installBrowserGuestHandlers(
interface GhostGuestNavigationHandlers {
gesture?: typeof noteGhostUserGesture;
- preview: typeof handleGhostPreviewNavigation;
+ preview: (
+ ghostId: string,
+ url: string,
+ hostContents: WebContents,
+ guestContents: WebContents,
+ isOwnerActive: () => boolean,
+ instanceId?: string,
+ ) => void;
external: typeof handleGhostExternalLinkNavigation;
}
@@ -834,11 +868,17 @@ export function installGhostGuestNavigationHandlers(
preview: handleGhostPreviewNavigation,
external: handleGhostExternalLinkNavigation,
},
+ instanceId?: string,
+ isAttachCurrent?: () => boolean,
): void {
+ if (instanceId && isAttachCurrent) {
+ installGhostMediaHandoverSource(hostContents, guestContents, { ghostId, instanceId }, () => isOwnerActive() && isAttachCurrent());
+ }
guestContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ const isCurrent = () => isOwnerActive() && (!isAttachCurrent || isAttachCurrent());
const noteGesture = () => {
- if (!isOwnerActive()) return;
- (handlers.gesture ?? noteGhostUserGesture)(ghostId);
+ if (!isCurrent()) return;
+ (handlers.gesture ?? noteGhostUserGesture)(instanceId ?? ghostId);
};
guestContents.on('before-mouse-event', (_event, mouse) => {
if (mouse.type === 'mouseDown') noteGesture();
@@ -849,7 +889,7 @@ export function installGhostGuestNavigationHandlers(
guestContents.on('will-navigate', (event, url) => {
// owner commit 后、Renderer 卸载旧 guest 前仍可能收到导航事件。旧页
// 不能借新 owner 的同名插件声明或授权代开外链。
- if (!isOwnerActive()) {
+ if (!isCurrent()) {
event.preventDefault();
return;
}
@@ -857,13 +897,44 @@ export function installGhostGuestNavigationHandlers(
if (nav === 'allow') return;
event.preventDefault();
if (nav === 'preview') {
- handlers.preview(ghostId, url, hostContents, guestContents, isOwnerActive);
+ handlers.preview(ghostId, url, hostContents, guestContents, isCurrent, instanceId);
} else if (nav === 'external') {
- handlers.external(ghostId, url, hostContents, guestContents, isOwnerActive);
+ handlers.external(ghostId, url, hostContents, guestContents, isCurrent, instanceId);
}
});
}
+export function installGhostMediaHandoverSource(
+ hostContents: WebContents,
+ guestContents: WebContents,
+ target: GhostPanelMediaTarget & { instanceId: string },
+ isAttachCurrent: () => boolean,
+): void {
+ let sourceToken: string | null = null;
+ const revoke = () => {
+ if (sourceToken) ghostMediaHandoverTargetTracker.revoke(sourceToken);
+ sourceToken = null;
+ };
+ const isCurrent = () => !hostContents.isDestroyed() && !guestContents.isDestroyed() && isAttachCurrent();
+ guestContents.on('dom-ready', () => {
+ revoke();
+ if (!isCurrent()) return;
+ const token = ghostMediaHandoverTargetTracker.register({ ...target, isCurrent });
+ sourceToken = token;
+ void guestContents.executeJavaScript(ghostMediaHandoverDragScript(token)).catch(() => {
+ ghostMediaHandoverTargetTracker.revoke(token);
+ if (sourceToken === token) sourceToken = null;
+ });
+ });
+ guestContents.on('did-navigate', revoke);
+ guestContents.on('render-process-gone', revoke);
+ guestContents.once('destroyed', () => {
+ revoke();
+ hostContents.removeListener('destroyed', revoke);
+ });
+ hostContents.once('destroyed', revoke);
+}
+
export function installWebviewHardener(): void {
app.on('web-contents-created', (_event, contents) => {
// will-attach → did-attach 对同一个 guest 同步成对触发;用闭包变量把
@@ -946,6 +1017,9 @@ export function installWebviewHardener(): void {
guestContents,
ghostId,
() => isGhostGuestOwnerActive(authorized.owner),
+ undefined,
+ authorized.instanceId,
+ authorized.isCurrent,
);
return;
}
diff --git a/apps/desktop/src/preload/__tests__/ghostInspectTarget.test.ts b/apps/desktop/src/preload/__tests__/ghostInspectTarget.test.ts
new file mode 100644
index 0000000000..37e4eea226
--- /dev/null
+++ b/apps/desktop/src/preload/__tests__/ghostInspectTarget.test.ts
@@ -0,0 +1,45 @@
+import fs from 'node:fs';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+
+function inspectBridge(invoke: ReturnType<typeof vi.fn>) {
+ const source = fs.readFileSync(new URL('../preload.ts', import.meta.url), 'utf8');
+ const ast = ts.createSourceFile('preload.ts', source, ts.ScriptTarget.Latest, true);
+ let initializer: ts.Expression | undefined;
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isPropertyAssignment(node) &&
+ node.name.getText(ast) === 'inspect' &&
+ node.initializer.getText(ast).includes('ghosts:inspect')
+ )
+ initializer = node.initializer;
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ if (!initializer) throw new Error('Ghost inspect bridge missing');
+ const compiled = ts.transpileModule('const inspect = ' + initializer.getText(ast), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ return new Function('ipcRenderer', compiled + ';return inspect;')({ invoke }) as (
+ path: string,
+ target?: { expectedInstalledInstanceId: string; expectedInstalledApproval: string },
+ ) => Promise<unknown>;
+}
+
+describe('Ghost inspect receiver bridge', () => {
+ it('preserves a legacy one-argument call', async () => {
+ const invoke = vi.fn();
+ await inspectBridge(invoke)('/tmp/plugin.cindy');
+ expect(invoke).toHaveBeenCalledExactlyOnceWith('ghosts:inspect', '/tmp/plugin.cindy');
+ });
+
+ it('forwards the exact instance and receipt token, not a privilege flag', async () => {
+ const invoke = vi.fn();
+ const target = {
+ expectedInstalledInstanceId: '_ns__xd__helper',
+ expectedInstalledApproval: 'approved:receipt',
+ };
+ await inspectBridge(invoke)('/tmp/plugin.cindy', target);
+ expect(invoke).toHaveBeenCalledExactlyOnceWith('ghosts:inspect', '/tmp/plugin.cindy', target);
+ });
+});
diff --git a/apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts b/apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts
new file mode 100644
index 0000000000..9e6112f14b
--- /dev/null
+++ b/apps/desktop/src/preload/__tests__/ghostPanelMedia.test.ts
@@ -0,0 +1,86 @@
+import fs from 'node:fs';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+
+function loadResolvePanelMedia(invoke: ReturnType<typeof vi.fn>, filename = 'preload.ts', method = 'resolvePanelMedia') {
+ const source = fs.readFileSync(new URL('../' + filename, import.meta.url), 'utf8');
+ const ast = ts.createSourceFile('preload.ts', source, ts.ScriptTarget.Latest, true);
+ let initializer: ts.Expression | undefined;
+ const visit = (node: ts.Node): void => {
+ if (ts.isPropertyAssignment(node) && node.name.getText(ast) === 'ghosts' && ts.isObjectLiteralExpression(node.initializer)) {
+ const property = node.initializer.properties.find((candidate) =>
+ ts.isPropertyAssignment(candidate) && candidate.name.getText(ast) === method);
+ if (property && ts.isPropertyAssignment(property)) initializer = property.initializer;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ if (!initializer) throw new Error(method + ' bridge not found');
+ const compiled = ts.transpileModule('const resolvePanelMedia = ' + initializer.getText(ast), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ }).outputText;
+ return new Function('ipcRenderer', 'mutationErrorForGhostPanel', compiled + '\nreturn resolvePanelMedia;')({ invoke }, () => null) as
+ (...args: unknown[]) => Promise<unknown>;
+}
+
+describe('Ghost panel media IPC bridge', () => {
+ it('declares the optional instance in the renderer API contract', () => {
+ const source = fs.readFileSync(new URL('../../renderer/vite-env.d.ts', import.meta.url), 'utf8');
+ const ast = ts.createSourceFile('vite-env.d.ts', source, ts.ScriptTarget.Latest, true);
+ let signature: ts.FunctionTypeNode | undefined;
+ const visit = (node: ts.Node): void => {
+ if (ts.isPropertySignature(node) && node.name.getText(ast) === 'resolvePanelMedia'
+ && node.type && ts.isFunctionTypeNode(node.type)) {
+ signature = node.type;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ expect(signature).toBeDefined();
+ expect(signature?.parameters).toHaveLength(4);
+ const instance = signature?.parameters[2];
+ expect(instance?.name.getText(ast)).toBe('instanceId');
+ expect(instance?.questionToken).toBeDefined();
+ expect(instance?.type?.kind).toBe(ts.SyntaxKind.StringKeyword);
+ const sourceToken = signature?.parameters[3];
+ expect(sourceToken?.name.getText(ast)).toBe('sourceToken');
+ expect(sourceToken?.questionToken).toBeDefined();
+ expect(sourceToken?.type?.kind).toBe(ts.SyntaxKind.StringKeyword);
+ });
+
+});
+
+describe.each(['preload.ts', 'ghostPanelWindowPreload.ts', 'sidebarWindowPreload.ts'])('%s media bridge', (filename) => {
+ it('forwards the confirmed install approval while preserving calls without it', async () => {
+ const invoke = vi.fn().mockResolvedValue({ ok: true });
+ const setEnabled = loadResolvePanelMedia(invoke, filename, 'setEnabled');
+ for (const approval of [undefined, 'approved:00000000-0000-4000-8000-000000000001']) {
+ await setEnabled('helper', false, approval);
+ expect(invoke).toHaveBeenLastCalledWith('ghosts:set-enabled', 'helper', false, approval);
+ }
+ });
+ it('retains the legacy argument layout', async () => {
+ const result = { url: 'cindy-media://blobs/image.png' };
+ const invoke = vi.fn().mockResolvedValue(result);
+ expect(await loadResolvePanelMedia(invoke, filename)('cindy-ghost://helper/media/image.png')).toBe(result);
+ expect(invoke).toHaveBeenCalledExactlyOnceWith(
+ 'ghosts:resolve-panel-media', 'cindy-ghost://helper/media/image.png', undefined,
+ );
+ });
+
+ it.each(['menu', 'attach'] as const)('forwards the physical instance for %s', async (purpose) => {
+ const invoke = vi.fn().mockResolvedValue({});
+ await loadResolvePanelMedia(invoke, filename)('cindy-ghost://helper/media/image.png', purpose, '_ns__acme__helper');
+ expect(invoke).toHaveBeenCalledExactlyOnceWith(
+ 'ghosts:resolve-panel-media', 'cindy-ghost://helper/media/image.png', purpose, '_ns__acme__helper',
+ );
+ });
+
+ it('forwards the opaque drag source without declaring an instance', async () => {
+ const invoke = vi.fn().mockResolvedValue({});
+ await loadResolvePanelMedia(invoke, filename)('cindy-ghost://helper/preview/image.png', 'attach', undefined, 'opaque-source');
+ expect(invoke).toHaveBeenCalledExactlyOnceWith(
+ 'ghosts:resolve-panel-media', 'cindy-ghost://helper/preview/image.png', 'attach', undefined, 'opaque-source',
+ );
+ });
+});
diff --git a/apps/desktop/src/preload/ghostPanelWindowPreload.ts b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
index 68972e2dde..c2463f8aaa 100644
--- a/apps/desktop/src/preload/ghostPanelWindowPreload.ts
+++ b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
@@ -20,7 +20,7 @@ import { contextBridge, ipcRenderer } from 'electron';
import { createAppearanceSnapshotBridge } from './appearanceSnapshot';
import type { LocalThemesResult } from '../shared/local-themes';
import type { GhostPanelWindowsState } from '../shared/ghostPanelWindow';
-import { isValidGhostId } from '../shared/ghost';
+import { isValidPluginStoragePart } from '../shared/pluginIdentity';
import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from '../shared/locale';
import {
GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL,
@@ -54,7 +54,7 @@ function onPayload<T>(channel: string, cb: (payload: T) => void): Unsub {
const currentGhostPanelId = (() => {
const raw = new URLSearchParams(window.location.search).get('ghostPanelWindow');
- return isValidGhostId(raw) ? raw : null;
+ return isValidPluginStoragePart(raw) ? raw : null;
})();
function mutationErrorForGhostPanel(id: string): Error | null {
@@ -240,19 +240,25 @@ contextBridge.exposeInMainWorld('electronAPI', {
return ipcRenderer.invoke('ghosts:reload', id);
},
/** 启用/停用(面板错误态「关闭」按钮)。 */
- setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> => {
+ setEnabled: (id: string, enabled: boolean, expectedInstalledApproval?: string): Promise<{ ok: true }> => {
const error = mutationErrorForGhostPanel(id);
if (error) return Promise.reject(error);
- return ipcRenderer.invoke('ghosts:set-enabled', id, enabled);
+ return ipcRenderer.invoke('ghosts:set-enabled', id, enabled, expectedInstalledApproval);
},
/** 解析面板媒体 URI → cindy-media:// 地址(右键菜单 / 拖拽引渡)。 */
resolvePanelMedia: (
uri: string,
purpose?: 'attach' | 'menu',
+ instanceId?: string,
+ sourceToken?: string,
): Promise<
| { url: string; kind?: 'image' }
| { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string }
- > => ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose),
+ > => sourceToken !== undefined
+ ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId, sourceToken)
+ : instanceId === undefined
+ ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose)
+ : ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId),
/** 运行时状态快照(面板崩溃/熔断错误态接管)。 */
runtimeStates: (): Promise<{ states: Record<string, string> }> =>
ipcRenderer.invoke('ghosts:runtime-states'),
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f8616a0ba6..b7d3c6f3e6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1301,6 +1301,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
opts: {
expectedPackageSha256: string;
expectedInstalledApproval: string;
+ expectedInstalledInstanceId: string;
},
): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),
cindyPrefsSync: (
@@ -1361,13 +1362,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('ghosts:pick-file'),
inspect: (
lizFilePath: string,
+ opts?: { expectedInstalledInstanceId: string; expectedInstalledApproval: string },
): Promise<{
manifest: unknown;
trust: unknown;
packageSha256: string;
unsupportedSlots: string[];
iconDataUrl?: string;
- }> => ipcRenderer.invoke('ghosts:inspect', lizFilePath),
+ }> => opts === undefined
+ ? ipcRenderer.invoke('ghosts:inspect', lizFilePath)
+ : ipcRenderer.invoke('ghosts:inspect', lizFilePath, opts),
uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),
/** 详情页「导出 .cindy」:main 打包安装目录 → 系统保存对话框落盘。 */
export: (
@@ -1380,8 +1384,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
fanOutRetirementOpen((id: unknown) => { if (typeof id === 'string') callback(id); }),
acknowledgeRetirement: (id: string): Promise<{ ok: true }> =>
ipcRenderer.invoke('ghosts:acknowledge-retirement', id),
- setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> =>
- ipcRenderer.invoke('ghosts:set-enabled', id, enabled),
+ setEnabled: (id: string, enabled: boolean, expectedInstalledApproval?: string): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('ghosts:set-enabled', id, enabled, expectedInstalledApproval),
requestTaskApproval: (id: string): Promise<{ granted: boolean }> =>
ipcRenderer.invoke('ghosts:request-task-approval', id),
/** 目录级禁用清单(插件页项目范围视图;sendSync 保证切换同帧渲染)。 */
@@ -1482,6 +1486,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
resolvePanelMedia: (
uri: string,
purpose?: 'attach' | 'menu',
+ instanceId?: string,
+ sourceToken?: string,
): Promise<
| { url: string; kind?: 'image' }
| {
@@ -1493,7 +1499,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
ext: string;
mimeType: string;
}
- > => ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose),
+ > => sourceToken !== undefined
+ ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId, sourceToken)
+ : instanceId === undefined
+ ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose)
+ : ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId),
runtimeStates: (): Promise<{ states: Record<string, string> }> =>
ipcRenderer.invoke('ghosts:runtime-states'),
reload: (id: string): Promise<{ state: string }> => ipcRenderer.invoke('ghosts:reload', id),
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
index a77638ac14..04b5408650 100644
--- a/apps/desktop/src/preload/sidebarWindowPreload.ts
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -290,12 +290,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('ghosts:open-retirement', id),
acknowledgeRetirement: (id: string): Promise<{ ok: true }> =>
ipcRenderer.invoke('ghosts:acknowledge-retirement', id),
- setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> =>
- ipcRenderer.invoke('ghosts:set-enabled', id, enabled),
+ setEnabled: (id: string, enabled: boolean, expectedInstalledApproval?: string): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('ghosts:set-enabled', id, enabled, expectedInstalledApproval),
resolvePanelMedia: (
uri: string,
purpose?: 'attach' | 'menu',
- ): Promise<unknown> => ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose),
+ instanceId?: string,
+ sourceToken?: string,
+ ): Promise<unknown> => sourceToken !== undefined
+ ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId, sourceToken)
+ : instanceId === undefined
+ ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose)
+ : ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId),
runtimeStates: (): Promise<{ states: Record<string, string> }> =>
ipcRenderer.invoke('ghosts:runtime-states'),
onChanged: (cb: (payload: unknown) => void): (() => void) => onPayload('ghosts:changed', cb),
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
index ad7b930eae..66c75eae25 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
@@ -173,10 +173,10 @@ describe('ChatInput session switch focus contract', () => {
'const handleComposerSuggestionSelect = useCallback(',
);
- expect(pluginPageSource).toContain('pendingGhostId: ghost.manifest.id');
+ expect(pluginPageSource).toContain('pendingGhostId: installedGhostStoragePart(ghost)');
expect(pluginPageSource.match(/focusAtEnd: true/g)).toHaveLength(1);
expect(
- chatInputSource.match(/placeGhostAtComposerStart\(editor, ghost, installedGhosts\)/g),
+ chatInputSource.match(/placeGhostAtComposerStart\(editor, ghost, ghostsForCommand\)/g),
).toHaveLength(1);
expect(
chatInputSource.match(
@@ -187,7 +187,8 @@ describe('ChatInput session switch focus contract', () => {
expect(capabilitySelectionBlock).toContain("selectedItem.type === 'plugin-command'");
expect(capabilitySelectionBlock).toContain('!ghost?.enabled');
- expect(capabilitySelectionBlock).toContain('composerGhostsRef.current.find(');
+ expect(capabilitySelectionBlock).toContain('findInstalledGhostByInstanceId(');
+ expect(capabilitySelectionBlock).toContain('composerGhostsRef.current,');
expect(capabilitySelectionBlock).toContain(
'placeGhostAtComposerStart(editor, ghost, composerGhostsRef.current);',
);
@@ -208,7 +209,7 @@ describe('ChatInput session switch focus contract', () => {
'worktreeCreationStore.clear(newSession.id);',
);
- expect(chatInputSource).toContain('findGhostByCommand(eligibleGhosts, ghostCommandWord)');
+ expect(chatInputSource).toContain('findGhostByCommand(eligibleGhosts, ghostCommandToken.word, ghostCommandToken.namespace)');
expect(chatInputSource).toContain('onAccepted: markRecentPluginUsage');
expect(successfulSendBlock).toContain('markRecentPluginUsage();');
// 本机首条 / worktree 首条 / 远程普通首条直接发送 / 远程视图交接 四处受理点。
diff --git a/apps/desktop/src/renderer/__tests__/collectGhostCallsByUserTurn.test.ts b/apps/desktop/src/renderer/__tests__/collectGhostCallsByUserTurn.test.ts
index b4a589c283..fe56e30659 100644
--- a/apps/desktop/src/renderer/__tests__/collectGhostCallsByUserTurn.test.ts
+++ b/apps/desktop/src/renderer/__tests__/collectGhostCallsByUserTurn.test.ts
@@ -25,6 +25,26 @@ const ghostCall = (clientId: string, ghostId: string, toolName = 'mcp__cindy__gh
}) as ChatMessage;
describe('collectGhostCallsByUserTurn', () => {
+ it('does not merge root and organization calls with the same ghost id', () => {
+ const root = { ...ghostCall('t1', 'helper'), toolInput: { ghost_id: 'helper', namespace: null, tool: 'run' } };
+ const organization = { ...ghostCall('t2', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };
+ const map = collectGhostCallsByUserTurn([user('u1'), root, organization]);
+ expect([...(map.get('u1') ?? [])].sort()).toEqual(['_ns__acme__helper', 'helper']);
+ });
+
+ it('keeps legacy unqualified calls and ignores malformed namespace inputs', () => {
+ const legacy = ghostCall('legacy', 'helper');
+ const malformed = { ...ghostCall('bad', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'bad namespace', tool: 'run' } };
+ expect([...(collectGhostCallsByUserTurn([user('u1'), legacy]).get('u1') ?? [])]).toEqual(['helper']);
+ expect(collectGhostCallsByUserTurn([user('u1'), malformed]).has('u1')).toBe(false);
+ });
+ it('attributes a valid encoded instance id without an extra namespace', () => {
+ const encoded = ghostCall('org', '_ns__acme__helper');
+ expect([...(collectGhostCallsByUserTurn([user('u1'), encoded]).get('u1') ?? [])])
+ .toEqual(['_ns__acme__helper']);
+ const invalid = { ...encoded, toolInput: { ghost_id: '_ns__acme__helper', namespace: 'globex', tool: 'run' } };
+ expect(collectGhostCallsByUserTurn([user('u1'), invalid]).has('u1')).toBe(false);
+ });
it('把 ghost_call 归到其所在 turn 的 user 消息名下', () => {
const map = collectGhostCallsByUserTurn([user('u1'), ghostCall('t1', 'art')]);
expect([...(map.get('u1') ?? [])]).toEqual(['art']);
diff --git a/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts b/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts
index b49f7b6fc9..396bb8e651 100644
--- a/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts
@@ -54,6 +54,14 @@ function itemsOf(messages: ChatMessage[], snap?: GhostCardSnapshot): RenderItem[
}
describe('ghost_card · settled 配对', () => {
+ it('keeps the card store physical id for a namespaced settled call', () => {
+ const call = { ...mkGhostCall('org', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };
+ const cards = itemsOf([call, mkResult('result-org', 'tu-org', { xdt_card_id: 'org-card' })],
+ snapshot({ 'org-card': readyEntry('_ns__acme__helper') }));
+ expect(cards.find((item) => item.type === 'ghost_card')).toMatchObject({
+ ghostId: '_ns__acme__helper', callId: 'org-card', settled: true,
+ });
+ });
it('xdt_card_id + ready → ghost_card item,自身媒体被抑制', () => {
const items = itemsOf(
[
@@ -144,6 +152,66 @@ describe('ghost_card · in-flight 锚定', () => {
...over,
});
+ it('does not claim a root card for an enterprise call sharing its ghost id', () => {
+ const call = { ...mkGhostCall('org', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };
+ const cards = itemsOf([call], snapshot({ 'root-card': readyEntry('helper') }, [
+ live('root-card', { ghostId: 'helper' }),
+ ]));
+ expect(cards.some((item) => item.type === 'ghost_card')).toBe(false);
+ });
+
+ it('claims an enterprise card by physical id and retains its identity', () => {
+ const call = { ...mkGhostCall('org', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };
+ const cards = itemsOf([call], snapshot({ 'org-card': readyEntry('_ns__acme__helper') }, [
+ live('org-card', { ghostId: '_ns__acme__helper' }),
+ ]));
+ expect(cards.find((item) => item.type === 'ghost_card')).toMatchObject({
+ ghostId: '_ns__acme__helper', callId: 'org-card', settled: false,
+ });
+ });
+
+ it('claims an encoded enterprise call without a toolUseId only for its matching live card', () => {
+ const call = { ...mkGhostCall('org', '_ns__acme__helper'), toolUseId: undefined };
+ const cards = itemsOf([call], snapshot({ 'org-card': readyEntry('_ns__acme__helper') }, [
+ live('org-card', { ghostId: '_ns__acme__helper' }),
+ ]));
+ expect(cards).toEqual(expect.arrayContaining([
+ expect.objectContaining({ type: 'ghost_card', ghostId: '_ns__acme__helper', callId: 'org-card' }),
+ ]));
+ });
+
+ it('uses exact tool-use correlation for an in-place namespace stamp', () => {
+ const call = { ...mkGhostCall('org', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };
+ const cards = itemsOf([call], snapshot({ 'org-card': readyEntry('helper') }, [
+ live('org-card', { ghostId: 'helper', toolUseId: 'tu-org' }),
+ ]));
+ expect(cards.find((item) => item.type === 'ghost_card')).toMatchObject({
+ ghostId: 'helper', callId: 'org-card', settled: false,
+ });
+ });
+
+ it('matches an in-place organization card without a tool-use id but never anchors it to root', () => {
+ const card = live('org-card', { ghostId: 'helper', logicalGhostId: '_ns__acme__helper' });
+ const cards = snapshot({ 'org-card': readyEntry('helper') }, [card]);
+ const organization = { ...mkGhostCall('org', 'helper'), toolUseId: undefined,
+ toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };
+ const root = { ...mkGhostCall('root', 'helper'), toolUseId: undefined,
+ toolInput: { ghost_id: 'helper', namespace: null, tool: 'run' } };
+ expect(itemsOf([organization], cards).find((item) => item.type === 'ghost_card'))
+ .toMatchObject({ callId: 'org-card', settled: false });
+ expect(itemsOf([root], cards).some((item) => item.type === 'ghost_card')).toBe(false);
+ const implicitRoot = { ...root, toolInput: { ghost_id: 'helper', tool: 'run' } };
+ expect(itemsOf([implicitRoot], cards).some((item) => item.type === 'ghost_card')).toBe(false);
+ });
+
+ it('ignores malformed plugin ids instead of crashing the message stream', () => {
+ const call = { ...mkGhostCall('invalid'), toolInput: { ghost_id: 'invalid id', namespace: 'acme', tool: 'run' } };
+ const cards = itemsOf([call], snapshot({ 'org-card': readyEntry('_ns__acme__helper') }, [
+ live('org-card', { ghostId: '_ns__acme__helper' }),
+ ]));
+ expect(cards.some((item) => item.type === 'ghost_card')).toBe(false);
+ });
+
it('renders a Pi card before its tool returns and restores the settled card from old history', () => {
const sessionId = 'pi-card-regression';
const content = { toolUseId: 'tu-pi', toolName: 'cindy_mcp_call_tool', input: {
@@ -225,6 +293,42 @@ describe('ghost_card · in-flight 锚定', () => {
});
describe('ghost_card · 媒体回锚(xdt_anchor_card_id)', () => {
+ it.each([[undefined, null, 'helper'], [null, undefined, '_root__helper'],
+ ['acme', 'acme', '_ns__archive__helper'], [null, null, '_archive_helper'],
+ [undefined, undefined, '_root__helper']] as const)(
+ 'rejects ambiguous or archived owners (%s → %s, %s)', (openedNamespace, polledNamespace, physicalKey) => {
+ const call = (id: string, namespace: string | null | undefined) => ({ ...mkGhostCall(id, 'helper'),
+ toolInput: { ghost_id: 'helper', ...(namespace === undefined ? {} : { namespace }), tool: id } });
+ const items = itemsOf([call('submit', openedNamespace), mkResult('submitted', 'tu-submit', { xdt_card_id: 'card' }),
+ call('poll', polledNamespace), mkResult('polled', 'tu-poll', { xdt_anchor_card_id: 'card', xdt_image_urls: [IMG] })],
+ snapshot({ card: readyEntry(physicalKey) }));
+ const card = items.find((item) => item.type === 'ghost_card');
+ expect(card && card.type === 'ghost_card' ? card.media : undefined).toBeUndefined();
+ expect(items.some((item) => item.type === 'tool_media')).toBe(true);
+ },
+ );
+ it.each([[null, '_root__helper'], ['acme', 'helper'], ['acme', '_ns__acme__helper']] as const)(
+ 'anchors same-instance media for namespace %s with physical owner %s', (namespace, physicalKey) => {
+ const call = (id: string) => ({ ...mkGhostCall(id, 'helper'),
+ toolInput: { ghost_id: 'helper', namespace, tool: id } });
+ const items = itemsOf([call('submit'), mkResult('submitted', 'tu-submit', { xdt_card_id: 'card' }),
+ call('poll'), mkResult('polled', 'tu-poll', { xdt_anchor_card_id: 'card', xdt_image_urls: [IMG] })],
+ snapshot({ card: readyEntry(physicalKey) }));
+ const card = items.find((item) => item.type === 'ghost_card');
+ expect(card && card.type === 'ghost_card' ? card.media?.map((media) => media.url) : []).toEqual([IMG]);
+ expect(items.some((item) => item.type === 'tool_media')).toBe(false);
+ },
+ );
+ it('does not attach enterprise media to a root card with the same id', () => {
+ const rootCall = { ...mkGhostCall('root', 'helper'), toolInput: { ghost_id: 'helper', namespace: null, tool: 'run' } };
+ const orgPoll = { ...mkGhostCall('org', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'poll' } };
+ const items = itemsOf([rootCall, mkResult('root-result', 'tu-root', { xdt_card_id: 'root-card' }),
+ orgPoll, mkResult('org-result', 'tu-org', { xdt_anchor_card_id: 'root-card', xdt_image_urls: [IMG] })],
+ snapshot({ 'root-card': readyEntry('helper') }));
+ expect(items.some((item) => item.type === 'tool_media')).toBe(true);
+ const card = items.find((item) => item.type === 'ghost_card');
+ expect(card && card.type === 'ghost_card' ? card.media : undefined).toBeUndefined();
+ });
const VIDEO = `cindy-media://blobs/${'c'.repeat(64)}.mp4`;
// 提交调用(开卡)+ 轮询调用(出媒体带锚)的标准两段式消息流。
const submitAndPoll = (pollBody: Record<string, unknown>, pollGhostId = 'xd-mivo') => [
diff --git a/apps/desktop/src/renderer/__tests__/ghostCardStore.test.ts b/apps/desktop/src/renderer/__tests__/ghostCardStore.test.ts
index ad21f6fd30..7ab26e51c7 100644
--- a/apps/desktop/src/renderer/__tests__/ghostCardStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostCardStore.test.ts
@@ -48,6 +48,13 @@ const push = (callId: string, over: Partial<Parameters<typeof ingestCardPush>[0]
});
describe('ghostCardStore', () => {
+ it('preserves the logical identity of an in-place plugin on its live card', () => {
+ ingestCardPush(push('org', { ghostId: 'helper', logicalGhostId: '_ns__acme__helper' }));
+ expect(getGhostCardSnapshot().liveCards[0]).toMatchObject({
+ ghostId: 'helper', logicalGhostId: '_ns__acme__helper',
+ });
+ });
+
it('推送入库:ready 条目 + 活卡登记;换海报只刷内容不重复登记', () => {
ingestCardPush(push('c1', { toolUseId: 'tu1' }));
let snap = getGhostCardSnapshot();
diff --git a/apps/desktop/src/renderer/__tests__/ghostCommand.test.ts b/apps/desktop/src/renderer/__tests__/ghostCommand.test.ts
index 1e02bf8b97..dba00bb67b 100644
--- a/apps/desktop/src/renderer/__tests__/ghostCommand.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostCommand.test.ts
@@ -11,17 +11,27 @@ import {
COMMAND_TOOLS_JSON_MAX_BYTES,
commandDirectiveSegments,
expandGhostCommand,
+ findGhostByCommand,
mentionDirectiveSegments,
+ formatGhostCommandInsertion,
+ formatGhostCommandToken,
+ parseGhostCommandToken,
parseGhostCommandWord,
splitGhostDirective,
} from '../cindy-brain/ghostCommand';
import type { InstalledGhost } from '../../shared/ghost';
-function ghost(command: string | undefined, enabled = true): InstalledGhost {
+function ghost(
+ command: string | undefined,
+ enabled = true,
+ opts: { id?: string; namespace?: string | null } = {},
+): InstalledGhost {
+ const id = opts.id ?? 'art';
+ const namespace = opts.namespace;
return {
manifest: {
schemaVersion: 2,
- id: 'art',
+ id,
name: '画图',
version: '1.0.0',
kind: 'chip',
@@ -29,8 +39,9 @@ function ghost(command: string | undefined, enabled = true): InstalledGhost {
tools: [{ name: 'gen_image', description: 'x' }],
...(command !== undefined ? { command } : {}),
},
- dir: '/fake',
+ dir: namespace ? `/fake/_ns/${namespace}/${id}` : '/fake',
enabled,
+ ...(namespace !== undefined ? { namespace } : {}),
} as InstalledGhost;
}
@@ -43,6 +54,19 @@ describe('parseGhostCommandWord', () => {
expect(parseGhostCommandWord('$ 画图')).toBeNull();
});
+ it('optional /namespace qualifier is not part of the command word', () => {
+ expect(parseGhostCommandWord('$draw/acme a cat')).toBe('draw');
+ expect(parseGhostCommandToken('$draw/acme a cat')).toEqual({ word: 'draw', namespace: 'acme' });
+ expect(parseGhostCommandToken('$draw/@root a cat')).toEqual({ word: 'draw', namespace: '@root' });
+ expect(parseGhostCommandToken('$画图/acme 一只猫')).toEqual({ word: '画图', namespace: 'acme' });
+ expect(parseGhostCommandToken('$draw')).toEqual({ word: 'draw', namespace: null });
+ expect(parseGhostCommandToken('$draw/')).toBeNull();
+ expect(parseGhostCommandToken('$draw/ACME')).toBeNull();
+ const longNs = 'o' + 'r'.repeat(126) + 'g';
+ expect(longNs).toHaveLength(128);
+ expect(parseGhostCommandToken('$draw/' + longNs + ' a cat')).toEqual({ word: 'draw', namespace: longNs });
+ });
+
it('全角变体触发符同权(中文输入法 Shift+4 产出 ¥ 不必切半角)', () => {
expect(parseGhostCommandWord('¥画图 一只猫')).toBe('画图'); // U+FFE5 全角人民币
expect(parseGhostCommandWord('$画图 一只猫')).toBe('画图'); // U+FF04 全角美元
@@ -52,6 +76,15 @@ describe('parseGhostCommandWord', () => {
});
});
+describe('formatGhostCommandToken', () => {
+ it('qualifies organization instances and leaves root unqualified', () => {
+ expect(formatGhostCommandToken(ghost('draw'))).toBe('draw');
+ expect(formatGhostCommandToken(ghost('draw', true, { namespace: null }))).toBe('draw');
+ expect(formatGhostCommandToken(ghost('draw', true, { namespace: 'acme' }))).toBe('draw/acme');
+ expect(formatGhostCommandInsertion(ghost('draw', true, { namespace: 'acme' }))).toBe('$draw/acme');
+ });
+});
+
describe('expandGhostCommand', () => {
it('命中已唤醒意识 → 追加机器指令(原文保留)', () => {
const out = expandGhostCommand('$画图 一只猫', [ghost('画图')]);
@@ -84,6 +117,71 @@ describe('expandGhostCommand', () => {
it('未提及意识的普通消息零改动', () => {
expect(expandGhostCommand('画一张猫', [ghost('画图')])).toBe('画一张猫');
});
+
+ it('$draw/acme selects the namespaced instance; bare $draw stays unique-or-ambiguous', () => {
+ const root = ghost('draw', true, { id: 'art', namespace: null });
+ const org = ghost('draw', true, { id: 'art', namespace: 'acme' });
+ const qualified = expandGhostCommand('$draw/acme a cat', [root, org]);
+ expect(qualified).toContain('[插件指令]');
+ expect(qualified).toContain('ghost_id: art');
+ expect(qualified).toContain('namespace: acme');
+ const split = splitGhostDirective(qualified);
+ expect(split?.directive).toMatchObject({ kind: 'command', ghostId: 'art', namespace: 'acme', command: 'draw' });
+ expect(findGhostByCommand([root, org], 'draw', 'acme')).toBe(org);
+ expect(findGhostByCommand([root, org], 'draw')).toBeNull();
+ const ambiguous = expandGhostCommand('$draw a cat', [root, org]);
+ expect(ambiguous).toContain('存在多个实例');
+ expect(expandGhostCommand('$draw/globex a cat', [root, org])).toBe('$draw/globex a cat');
+ });
+ it('preserves a selected root and an in-place organization identity with the same command', () => {
+ const root = ghost('draw', true, { id: 'art', namespace: null });
+ const org = { ...ghost('draw', true, { id: 'art', namespace: 'acme' }), dir: '/fake/art' };
+ expect(formatGhostCommandInsertion(root, [root, org])).toBe('$draw/@root');
+ expect(expandGhostCommand('$draw/@root a cat', [root, org])).toContain('id: art');
+ expect(expandGhostCommand('$draw/@root a cat', [root, org])).toContain('namespace:null');
+ expect(expandGhostCommand('$draw/@root a cat', [root, org])).not.toContain('存在多个实例');
+ expect(expandGhostCommand('$draw/acme a cat', [root, org])).toContain('ghost_id: art');
+ expect(expandGhostCommand('$draw/acme a cat', [root, org])).toContain('namespace: acme');
+ });
+
+ it.each([
+ {
+ form: 'embedded tools',
+ tools: [{ name: 'gen_image', description: 'x' }],
+ toolsJson: '[{"name":"gen_image","description":"x"}]',
+ },
+ {
+ form: 'oversized tool fallback',
+ tools: [{
+ name: 'gen_image',
+ description: 'x',
+ parameters: { blob: 'y'.repeat(COMMAND_TOOLS_JSON_MAX_BYTES) },
+ }],
+ toolsJson: undefined,
+ },
+ ])('uses the manifest id for new root-qualified commands with $form', ({ tools, toolsJson }) => {
+ const root = ghost('draw', true, { id: 'art', namespace: null });
+ root.dir = '/fake/_ns/_root/art';
+ root.manifest = { ...root.manifest, tools };
+ const org = ghost('draw', true, { id: 'art', namespace: 'acme' });
+ const text = '$draw/@root a cat';
+ const out = expandGhostCommand(text, [root, org]);
+ expect(out).toContain('ghost_call 必须显式传 namespace:null');
+ const split = splitGhostDirective(out);
+ expect(split).toMatchObject({
+ body: text,
+ directive: { kind: 'command', command: 'draw/@root', ghostId: 'art' },
+ });
+ if (split?.directive.kind === 'command') {
+ expect(split.directive.toolsJson).toBe(toolsJson);
+ expect(commandDirectiveSegments(split.directive).map((segment) => segment.text).join(''))
+ .toBe(split.directive.raw);
+ }
+ expect(splitGhostDirective(expandGhostCommand('$draw a cat', [root]))?.directive)
+ .toMatchObject({ kind: 'command', command: 'draw', ghostId: 'art', namespace: null });
+ expect(splitGhostDirective(expandGhostCommand('$draw/acme a cat', [root, org]))?.directive)
+ .toMatchObject({ kind: 'command', command: 'draw', ghostId: 'art', namespace: 'acme' });
+ });
});
describe('语言提及软提示已移除(2026-07-14 定案:不再追加、不再出胶囊)', () => {
@@ -109,6 +207,17 @@ describe('语言提及软提示已移除(2026-07-14 定案:不再追加、不再
});
describe('splitGhostDirective(召唤卡片渲染层解析,与生成端同模板 round-trip)', () => {
+ it('parses the exact previously persisted direct-tool hint in both command forms', () => {
+ for (const tools of [undefined, [{ name: 'gen_image', description: 'x' }]]) {
+ const current = expandGhostCommand('$画图 一只猫', [
+ { ...ghost('画图'), manifest: { ...ghost('画图').manifest, tools } },
+ ]);
+ const prior = current.replace('若指令带 /@root,ghost_call 必须显式传 namespace:null。', '');
+ expect(prior).not.toBe(current);
+ expect(splitGhostDirective(prior)).toMatchObject({ body: '$画图 一只猫', directive: { kind: 'command', ghostId: 'art' } });
+ expect(splitGhostDirective(current)).toMatchObject({ body: '$画图 一只猫', directive: { kind: 'command', ghostId: 'art' } });
+ }
+ });
it('硬指令 round-trip:expand → split 还原正文与结构化字段', () => {
const text = '$画图 用nano 画一张 心动小镇';
const out = expandGhostCommand(text, [ghost('画图')]);
@@ -344,3 +453,31 @@ describe('硬指令内嵌工具清单(显式点名免 ghost_list,2026-07-16)', (
expect(splitGhostDirective(`${out}\n\n后面还有话`)).toBeNull();
});
});
+
+describe('pending upgrade commands', () => {
+ it('omits namespace for a unique pending install', () => {
+ const pending = { ...ghost('feishu', true, { id: 'xd-feishu' }), namespaceState: 'pending' as const };
+ const out = expandGhostCommand('$feishu check', [pending]);
+ expect(out).toContain('(id: xd-feishu)');
+ expect(out).not.toContain('ghost_id:');
+ expect(out).not.toContain(', namespace:');
+ const split = splitGhostDirective(out);
+ expect(split?.directive).toMatchObject({ kind: 'command', ghostId: 'xd-feishu' });
+ if (split?.directive.kind === 'command') expect(split.directive.namespace).toBeUndefined();
+ });
+
+ it('writes namespace for a confirmed root and an organization instance', () => {
+ const rootGhost = ghost('draw', true, { id: 'art', namespace: null });
+ const org = ghost('draw', true, { id: 'art', namespace: 'acme' });
+ expect(expandGhostCommand('$draw x', [rootGhost])).toContain('namespace: null');
+ expect(expandGhostCommand('$draw/acme x', [rootGhost, org])).toContain('namespace: acme');
+ });
+
+ it('stays ambiguous when a pending install shares a command with an organization install', () => {
+ const pending = { ...ghost('run', true, { id: 'helper' }), namespaceState: 'pending' as const };
+ const org = ghost('run', true, { id: 'helper', namespace: 'acme' });
+ const out = expandGhostCommand('$run x', [pending, org]);
+ expect(out).toContain('存在多个实例');
+ expect(out).not.toContain('ghost_id:');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts b/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts
index ced4acc8e9..bccae71492 100644
--- a/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts
@@ -49,7 +49,7 @@ const doc = (...paras: PMNode[]) => schema.nodes.doc.create(null, paras);
function makeGhost(
command: string,
- opts: { enabled?: boolean; icon?: string; id?: string } = {},
+ opts: { enabled?: boolean; icon?: string; id?: string; namespace?: string | null } = {},
): InstalledGhost {
const manifest: GhostManifest = {
schemaVersion: 2,
@@ -66,6 +66,7 @@ function makeGhost(
enabled: opts.enabled ?? true,
approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
...(opts.icon ? { iconDataUrl: opts.icon } : {}),
+ ...(opts.namespace !== undefined ? { namespace: opts.namespace } : {}),
};
}
@@ -79,6 +80,15 @@ describe('findGhostCommandMatch — 位置语义与发送期同源', () => {
expect(m?.ghost.manifest.id).toBe('ghost-画图');
});
+ it('`$draw/acme` covers the qualifier and selects that namespace', () => {
+ const root = makeGhost('draw', { id: 'art', namespace: null });
+ const org = makeGhost('draw', { id: 'art', namespace: 'acme' });
+ const m = findGhostCommandMatch(doc(p(txt('$draw/acme a cat'))), [root, org]);
+ expect(m).toMatchObject({ from: 1, to: 11 });
+ expect(m?.ghost.namespace).toBe('acme');
+ expect(findGhostCommandMatch(doc(p(txt('$draw a cat'))), [root, org])).toBeNull();
+ });
+
it('全角触发符(¥/$)同权命中', () => {
expect(findGhostCommandMatch(doc(p(txt('¥画图 猫'))), [画图])).not.toBeNull();
expect(findGhostCommandMatch(doc(p(txt('$画图 猫'))), [画图])).not.toBeNull();
diff --git a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
index cc502fa202..a6a1db4d4c 100644
--- a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
@@ -86,6 +86,15 @@ describe('placeGhostAtComposerStart', () => {
expect(editor.state.selection.to).toBe(editor.state.doc.content.size - 1);
});
+ it('qualifies a namespaced Plugin command', () => {
+ const editor = editorWith('keep going');
+ const selected = ghost('draw', 'art');
+ selected.namespace = 'acme';
+ selected.dir = '/tmp/_ns/acme/art';
+ expect(placeGhostAtComposerStart(editor, selected, [selected])).toBe(true);
+ expect(editor.getText()).toBe('$draw/acme keep going');
+ });
+
it('replaces an existing Plugin command instead of stacking commands', () => {
const current = ghost('mivo');
const selected = ghost('feishu');
diff --git a/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx b/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx
index b2a69752e8..73fa8babd6 100644
--- a/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/ghostSummonChip.test.tsx
@@ -20,9 +20,16 @@ import i18n from '@/i18n';
import { GhostFulfillmentContext, GhostSummonCard } from '@/components/chat/GhostSummonCard';
import type { GhostDirectiveDisplay } from '@/cindy-brain/ghostCommand';
import type { HostCapabilityDirectiveDisplay } from '@/cindy-brain/hostCapabilityInvocation';
+import type { InstalledGhost } from '../../shared/ghost';
+import { collectGhostCallsByUserTurn } from '@/components/chat/MessageStream';
+import type { ChatMessage } from '@/lib/makerChatStore';
+
+const { installedGhostsMock } = vi.hoisted(() => ({
+ installedGhostsMock: vi.fn(() => [] as InstalledGhost[]),
+}));
vi.mock('@/cindy-brain/useInstalledGhosts', () => ({
- useInstalledGhosts: () => [],
+ useInstalledGhosts: () => installedGhostsMock(),
}));
const commandDirective: GhostDirectiveDisplay = {
@@ -72,12 +79,167 @@ beforeEach(async () => {
afterEach(() => {
cleanup();
+ installedGhostsMock.mockReturnValue([]);
vi.useRealTimers();
// biome-ignore lint/performance/noDelete: 还原 jsdom 默认(无 matchMedia)。
delete (window as { matchMedia?: unknown }).matchMedia;
});
describe('GhostSummonCard(chip 形态)', () => {
+ it('does not attach a newly installed root version to an ambiguous historical bare id', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'New Root', version: '99' },
+ dir: '/tmp/helper', namespace: null, iconDataUrl: 'data:image/png;base64,AAAA' },
+ ] as InstalledGhost[]);
+ const { container } = render(
+ <GhostSummonCard directive={{ kind: 'semantic', ghostIds: ['helper'] }} />,
+ );
+ expect(screen.queryByText('v99')).toBeNull();
+ expect(container.querySelector('img[src="data:image/png;base64,AAAA"]')).toBeNull();
+ });
+
+ it('renders an organization semantic call instead of its same-id root neighbor', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'Root', version: '1' }, dir: '/tmp/helper', namespace: null },
+ { manifest: { id: 'helper', name: 'Organization', version: '2' }, dir: '/tmp/_ns/acme/helper', namespace: 'acme' },
+ ] as InstalledGhost[]);
+ const messages = [
+ { clientId: 'm1', role: 'user', content: 'help' },
+ { clientId: 'call', role: 'tool_use', toolName: 'mcp__cindy__ghost_call', toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } },
+ ] as ChatMessage[];
+ const fulfilled = collectGhostCallsByUserTurn(messages);
+ render(
+ <GhostFulfillmentContext.Provider value={fulfilled}>
+ <GhostSummonCard directive={{ kind: 'semantic', ghostIds: [...(fulfilled.get('m1') ?? [])] }} messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('Organization')).toBeTruthy();
+ expect(screen.queryByText('Root')).toBeNull();
+ });
+
+ it('resolves the logical organization after an in-place namespace stamp', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'Organization', version: '2' }, dir: '/tmp/helper', namespace: 'acme' },
+ ] as InstalledGhost[]);
+ render(
+ <GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['_ns__acme__helper'])}>
+ <GhostSummonCard directive={{ kind: 'semantic', ghostIds: ['_ns__acme__helper'] }} messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('Organization')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { expanded: false }));
+ expect(screen.getByText('v2')).toBeTruthy();
+ });
+
+ it('counts an explicit organization command after its in-place install relocates', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'Root', version: '1' }, dir: '/tmp/helper', namespace: null },
+ { manifest: { id: 'helper', name: 'Organization', version: '2' }, dir: '/tmp/_ns/acme/helper', namespace: 'acme' },
+ ] as InstalledGhost[]);
+ render(
+ <GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['_ns__acme__helper'])}>
+ <GhostSummonCard directive={{ kind: 'command', command: 'draw', name: 'Organization', ghostId: 'helper', raw: '' }} commandNamespace='acme' messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('已调用')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { expanded: false }));
+ expect(screen.getByText('v2')).toBeTruthy();
+ });
+
+ it('counts a legacy bare call when an in-place organization is the only matching install', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'Organization', version: '2' }, dir: '/tmp/helper', namespace: 'acme' },
+ ] as InstalledGhost[]);
+ render(
+ <GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['helper'])}>
+ <GhostSummonCard directive={{ kind: 'command', command: 'draw', name: 'Organization', ghostId: 'helper', raw: '' }} commandNamespace='acme' messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('已调用')).toBeTruthy();
+ });
+
+ it('does not claim a bare call for an organization when root also exists', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'Root', version: '1' }, dir: '/tmp/helper', namespace: null },
+ { manifest: { id: 'helper', name: 'Organization', version: '2' }, dir: '/tmp/_ns/acme/helper', namespace: 'acme' },
+ ] as InstalledGhost[]);
+ render(
+ <GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['helper'])}>
+ <GhostSummonCard directive={{ kind: 'command', command: 'draw', name: 'Organization', ghostId: 'helper', raw: '' }} commandNamespace='acme' messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('已完成')).toBeTruthy();
+ expect(screen.queryByText('已调用')).toBeNull();
+ });
+
+ it('does not mark a root command as called by an organization of the same id', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'Root', version: '1' }, dir: '/tmp/helper', namespace: null },
+ { manifest: { id: 'helper', name: 'Organization', version: '2' }, dir: '/tmp/_ns/acme/helper', namespace: 'acme' },
+ ] as InstalledGhost[]);
+ render(
+ <GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['_ns__acme__helper'])}>
+ <GhostSummonCard directive={{ kind: 'command', command: 'draw', name: 'Root', ghostId: 'helper', raw: '' }} messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('已完成')).toBeTruthy();
+ expect(screen.queryByText('已调用')).toBeNull();
+ });
+ it('resolves an explicit root command without attributing an organization call to it', () => {
+ installedGhostsMock.mockReturnValue([
+ { manifest: { id: 'helper', name: 'Root', version: '1' }, dir: '/tmp/helper', namespace: null },
+ { manifest: { id: 'helper', name: 'Organization', version: '2' }, dir: '/tmp/_ns/acme/helper', namespace: 'acme' },
+ ] as InstalledGhost[]);
+ const directive = { kind: 'command', command: 'draw/@root', name: 'Root', ghostId: 'helper', raw: '' } as const;
+ const { rerender } = render(
+ <GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['_ns__acme__helper'])}>
+ <GhostSummonCard directive={directive} commandNamespace='@root' messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('已完成')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { expanded: false }));
+ expect(screen.getByText('v1')).toBeTruthy();
+ rerender(
+ <GhostFulfillmentContext.Provider value={fulfillmentOf('m1', ['helper'])}>
+ <GhostSummonCard directive={directive} commandNamespace='@root' messageClientId='m1' />
+ </GhostFulfillmentContext.Provider>,
+ );
+ expect(screen.getByText('已调用')).toBeTruthy();
+ });
+ it('resolves a namespaced $command instance id to the live install version', () => {
+ installedGhostsMock.mockReturnValue([
+ {
+ manifest: {
+ schemaVersion: 2,
+ id: 'art',
+ name: 'Art',
+ version: '2.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ command: 'draw',
+ tools: [{ name: 'run', description: 'Run.' }],
+ },
+ dir: '/tmp/_ns/acme/art',
+ namespace: 'acme',
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ } as InstalledGhost,
+ ]);
+ render(
+ <GhostSummonCard
+ directive={{
+ kind: 'command',
+ command: 'draw',
+ name: 'Art',
+ ghostId: '_ns__acme__art',
+ raw: '[插件指令] 用户显式点名插件 Art(id: _ns__acme__art)',
+ }}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', { expanded: false }));
+ expect(screen.getByText('v2.0.0')).toBeTruthy();
+ });
+
it('renders the seal chip with plugin name and no overline/prompt slot', () => {
render(<GhostSummonCard directive={commandDirective} running />);
expect(screen.getByText('XD Feishu')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx b/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx
index 37d68b989a..47c4795a6f 100644
--- a/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/pluginRecommendationRecovery.test.tsx
@@ -6,6 +6,7 @@ import { act, renderHook } from '@testing-library/react';
import ts from 'typescript';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { pluginSuggestionComposerText } from '../features/cc-agent/pluginHomeSuggestions';
+import { findInstalledGhostByInstanceId, installedGhostStoragePart } from '../../shared/pluginIdentity';
// Execute the production callbacks without mounting the unrelated full desktop shell.
function compile(source: string, bindings: Record<string, unknown>) {
@@ -31,7 +32,7 @@ describe('plugin recommendation recovery', () => {
expect(block).not.toContain('handleSend');
const suggestion = { id: 'one', pluginId: 'mail', prompt: 'Review my mail' };
const ghost = { manifest: { id: 'mail', name: 'Mail', command }, enabled: true };
- const fillComposerWithSuggestion = vi.fn((_text: string) => true);
+ const fillComposerWithSuggestion = vi.fn((text: string) => text.length > 0);
const markUsed = vi.fn(async () => ({ ids: ['mail'] }));
vi.stubGlobal('electronAPI', {});
Object.assign(window, {
@@ -50,6 +51,7 @@ describe('plugin recommendation recovery', () => {
filterGhostsForWorkdir: (ghosts: unknown[]) => ghosts,
fillComposerWithSuggestion,
pluginSuggestionComposerText,
+ installedGhostStoragePart,
i18n: { language: 'en' },
t: () => 'Use plugin mail via ghost_info and ghost_call',
isRemoteProjectDraft: false,
@@ -76,6 +78,82 @@ describe('plugin recommendation recovery', () => {
},
);
+ it('fills the selected organization recommendation rather than the same-name root plugin', async () => {
+ const source = readFileSync(resolve(__dirname, '../features/cc-agent/NewMakerDraftRoute.tsx'), 'utf8');
+ const block = source.slice(source.indexOf(' const runPluginSuggestion ='), source.indexOf(' const handlePluginSuggestion ='));
+ const suggestion = { id: 'plugin:_ns__acme__helper:task', pluginId: '_ns__acme__helper', prompt: 'Org task' };
+ const root = { manifest: { id: 'helper', name: 'Root', command: 'root' }, dir: '/ghosts/helper', enabled: true };
+ const org = { manifest: { id: 'helper', name: 'Org', command: 'org' }, dir: '/ghosts/_ns/acme/helper', namespace: 'acme', enabled: true };
+ const fillComposerWithSuggestion = vi.fn(() => true);
+ const markUsed = vi.fn(async () => ({ ids: ['_ns__acme__helper'] }));
+ Object.assign(window, { electronAPI: { ghosts: { listSync: () => ({ ghosts: [root, org] }), markUsed } } });
+ const run = compile(block + String.fromCharCode(10) + 'return runPluginSuggestion;', {
+ useCallback: (callback: unknown) => callback,
+ sendInFlightRef: { current: false },
+ pluginSuggestionFlight: { current: false },
+ pluginSuggestionMounted: { current: true },
+ currentPluginSuggestionContext: { current: { generation: 1, dataOwnerId: 'owner', targetKey: 'local' } },
+ readPluginRecommendationSnapshot: () => ({ ownerId: 'owner' }),
+ buildHomeTaskCatalog: () => [suggestion],
+ filterGhostsForWorkdir: (ghosts: unknown[]) => ghosts,
+ fillComposerWithSuggestion,
+ pluginSuggestionComposerText,
+ installedGhostStoragePart,
+ i18n: { language: 'en' },
+ t: () => 'Use Org',
+ isRemoteProjectDraft: false,
+ isDeviceLinkDraft: false,
+ navigate: vi.fn(),
+ toast: { error: vi.fn() },
+ });
+ await run({ suggestion, ownerId: 'owner', targetKey: 'local', workingDir: '/project' });
+ expect(fillComposerWithSuggestion).toHaveBeenCalledWith('$org/acme Org task');
+ expect(markUsed).toHaveBeenCalledWith('_ns__acme__helper');
+ });
+
+ it('retains project scope for the recommended organization alongside its root sibling', () => {
+ const source = readFileSync(resolve(__dirname, '../features/plugin/GhostPluginPage.tsx'), 'utf8');
+ const block = source.slice(source.indexOf(' const [scopeDir, setScopeDir]'), source.indexOf(' const [recentGhostIds, setRecentGhostIds]'));
+ const workdirPrefsSync = vi.fn(() => ({ disabled: ['_ns__acme__helper'] }));
+ vi.stubGlobal('electronAPI', { ghosts: { workdirPrefsSync } });
+ const useScope = compile('return function useScope() { ' + block + '\nreturn {scopeDir, effectiveEnabled}; }', {
+ useState, useRef, useEffect, useCallback, findInstalledGhostByInstanceId,
+ recommendation: { nonce: 'org', workingDir: '/project', suggestion: { pluginId: '_ns__acme__helper' } },
+ ghosts: [
+ { manifest: { id: 'helper' }, dir: '/ghosts/helper', namespace: null, enabled: true },
+ { manifest: { id: 'helper' }, dir: '/ghosts/_ns/acme/helper', namespace: 'acme', enabled: true },
+ ],
+ });
+ const { result } = renderHook(() => useScope());
+ expect(workdirPrefsSync).toHaveBeenCalledWith('/project');
+ expect(result.current.scopeDir).toBe('/project');
+ expect(result.current.effectiveEnabled('_ns__acme__helper', true)).toBe(false);
+ expect(result.current.effectiveEnabled('helper', true)).toBe(true);
+ });
+
+ it('names the organization instance in commandless suggestion previews and composer text', () => {
+ const root = { manifest: { id: 'helper', name: 'Root' }, dir: '/ghosts/helper', namespace: null };
+ const org = { manifest: { id: 'helper', name: 'Org' }, dir: '/ghosts/_ns/acme/helper', namespace: 'acme' };
+ const translate = (_key: string, options?: Record<string, unknown>) => 'Use ' + options?.id;
+ expect(pluginSuggestionComposerText('Org task', org, translate)).toBe('Org task\n\nUse helper namespace:acme');
+ expect(pluginSuggestionComposerText('Root task', root, translate)).toBe('Root task\n\nUse helper');
+ });
+
+ it('uses the logical namespace for a legacy flat organization instance', () => {
+ const flatOrg = { manifest: { id: 'helper', name: 'Org' }, dir: '/ghosts/helper', namespace: 'acme' };
+ const translate = (_key: string, options?: Record<string, unknown>) => 'Use ' + options?.id;
+ expect(pluginSuggestionComposerText('Org task', flatOrg, translate)).toBe(
+ 'Org task\n\nUse helper namespace:acme',
+ );
+ });
+
+ it('qualifies a selected root command when a namespaced sibling shares it', () => {
+ const root = { manifest: { id: 'helper', name: 'Root', command: 'draw' }, namespace: null };
+ const org = { manifest: { id: 'helper', name: 'Org', command: 'draw' }, namespace: 'acme' };
+ expect(pluginSuggestionComposerText('Root task', root, () => '', [root, org])).toBe('$draw/@root Root task');
+ expect(pluginSuggestionComposerText('Org task', org, () => '', [root, org])).toBe('$draw/acme Org task');
+ });
+
it('loads project overrides on entry and clears them when choosing global scope', () => {
const source = readFileSync(
resolve(__dirname, '../features/plugin/GhostPluginPage.tsx'),
@@ -94,6 +172,7 @@ describe('plugin recommendation recovery', () => {
useRef,
useEffect,
useCallback,
+ findInstalledGhostByInstanceId,
recommendation: { nonce: 'one', workingDir: '/project', suggestion: { pluginId: 'mail' } },
ghosts: [{ manifest: { id: 'mail' }, enabled: true }],
},
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx
index a845475491..5f0f7243ec 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx
@@ -37,6 +37,7 @@ import { Ghost } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { GhostManifest } from '../../shared/ghost';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity';
import { WINDOW_NO_DRAG_STYLE } from '../components/layout/windowDrag';
import { restoreGhostPanel } from '../lib/ghostPanelBubbleState';
import { useGhostPanelRestoreMode } from '../hooks/useGhostPanelRestoreMode';
@@ -233,6 +234,7 @@ function useBubbleDrag({
interface BubbleProps {
manifest: GhostManifest;
+ instanceId: string;
iconDataUrl: string | undefined;
/** 渲染基准位(已按锚点排布 + clamp)。 */
pos: { x: number; y: number };
@@ -241,7 +243,7 @@ interface BubbleProps {
}
/** 展开出的子气泡:不可拖(位置由幽灵球锚定),点击恢复对应面板。 */
-function Bubble({ manifest, iconDataUrl, pos, registerEl }: BubbleProps): ReactNode {
+function Bubble({ manifest, instanceId, iconDataUrl, pos, registerEl }: BubbleProps): ReactNode {
const { t } = useTranslation();
const [imgBroken, setImgBroken] = useState(false);
/** 点击后进入"缩没退场"态:播 .ghost-bubble-exit,计时器到点才 restore。 */
@@ -256,7 +258,7 @@ function Bubble({ manifest, iconDataUrl, pos, registerEl }: BubbleProps): ReactN
// 展开的"过程感":幽灵先跳走、圆圈再渐隐(共 EXIT_MS),到点才真正恢复
// 面板(面板侧再接宽度展开,见 ghostPanels.tsx 的 ghost-panel-enter)。
setExiting(true);
- exitTimerRef.current = window.setTimeout(() => restoreGhostPanel(manifest.id), EXIT_MS);
+ exitTimerRef.current = window.setTimeout(() => restoreGhostPanel(instanceId), EXIT_MS);
};
const name = manifest.panel?.title ?? manifest.name;
@@ -264,7 +266,7 @@ function Bubble({ manifest, iconDataUrl, pos, registerEl }: BubbleProps): ReactN
<button
ref={(el) => registerEl?.(el)}
type="button"
- data-testid={`ghost-panel-bubble-${manifest.id}`}
+ data-testid={`ghost-panel-bubble-${instanceId}`}
data-ghost-bubble-layer
aria-label={t('ghostPanelBubble.restoreAria', { name })}
title={t('ghostPanelBubble.restoreAria', { name })}
@@ -415,7 +417,7 @@ export function GhostPanelBubbleLayer(): ReactNode {
// 拖幽灵球的每一步把展开中的子气泡一起带走(同一条零 React 热路径)。
const onStackDragMove = (x: number, y: number) => {
minimized.forEach((g, index) => {
- const el = childElsRef.current.get(g.manifest.id);
+ const el = childElsRef.current.get(installedGhostStoragePart(g));
if (!el) return;
const p = stackChildPos({ x, y }, index, minimized.length);
placeBubbleEl(el, p.x, p.y);
@@ -437,13 +439,15 @@ export function GhostPanelBubbleLayer(): ReactNode {
{expanded
? minimized.map((g, index) => (
<Bubble
- key={g.manifest.id}
+ key={installedGhostStoragePart(g)}
manifest={g.manifest}
+ instanceId={installedGhostStoragePart(g)}
iconDataUrl={g.iconDataUrl}
pos={stackChildPos(anchor, index, minimized.length)}
registerEl={(el) => {
- if (el) childElsRef.current.set(g.manifest.id, el);
- else childElsRef.current.delete(g.manifest.id);
+ const id = installedGhostStoragePart(g);
+ if (el) childElsRef.current.set(id, el);
+ else childElsRef.current.delete(id);
}}
/>
))
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPanelRestoreEntry.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPanelRestoreEntry.tsx
index 835970268a..2e7404cb86 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostPanelRestoreEntry.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostPanelRestoreEntry.tsx
@@ -11,6 +11,7 @@ import {
import { useGhostPanelRestoreMode } from '@/hooks/useGhostPanelRestoreMode';
import { cn } from '@/lib/utils';
import type { InstalledGhost } from '../../shared/ghost';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity';
import { restoreGhostPanel } from '../lib/ghostPanelBubbleState';
import { useMinimizedGhostPanels } from './useMinimizedGhostPanels';
@@ -91,7 +92,7 @@ export function GhostPanelRestoreEntry({
data-testid="ghost-panel-restore-entry"
aria-label={ariaLabel}
title={label}
- onClick={() => restoreGhostPanel(single.manifest.id)}
+ onClick={() => restoreGhostPanel(installedGhostStoragePart(single))}
className={className}
>
{content}
@@ -122,8 +123,8 @@ export function GhostPanelRestoreEntry({
const name = panelName(ghost);
return (
<DropdownMenuItem
- key={ghost.manifest.id}
- onSelect={() => restoreGhostPanel(ghost.manifest.id)}
+ key={installedGhostStoragePart(ghost)}
+ onSelect={() => restoreGhostPanel(installedGhostStoragePart(ghost))}
className="gap-2.5"
>
<GhostEntryIcon ghost={ghost} size={18} />
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
index da21ebd826..ba0aefe732 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
@@ -6,7 +6,8 @@ import type { WebviewTag } from 'electron';
import { useAuth } from '@/contexts/AuthContext';
import { cn } from '@/lib/utils';
-import { GHOST_SCHEME, ghostPartition, type InstalledGhost } from '../../shared/ghost';
+import { GHOST_SCHEME, ghostInstallApprovalToken, type InstalledGhost } from '../../shared/ghost';
+import { installedGhostLogicalIdentity, installedGhostWebviewPartitionClaim, pluginStoragePart } from '../../shared/pluginIdentity';
import {
buildGhostPluginSettingsThemeCss,
buildGhostSettingsThemeCss,
@@ -143,7 +144,9 @@ function SettingsWebviewBody({
const [generation, setGeneration] = useState(0);
const hostRef = useRef<HTMLDivElement | null>(null);
const { manifest } = ghost;
- const partitionClaim = ghostPartition(manifest.id);
+ const settingsHeightKey = pluginStoragePart(installedGhostLogicalIdentity(ghost));
+ const partitionClaim = installedGhostWebviewPartitionClaim(ghost);
+ const approvalToken = ghostInstallApprovalToken(ghost.approval);
const settingsHtml = manifest.settingsHtml;
const fixedHeight = manifest.settingsHeight;
const buildSettingsThemeCss =
@@ -151,7 +154,7 @@ function SettingsWebviewBody({
// 仅复用同 owner、同插件版本的高度;账号文字和菜单由新 guest 实时渲染。
const [autoHeight, setAutoHeight] = useState(
() =>
- loadGhostSettingsHeight(dataOwnerId, manifest.id, manifest.version) ??
+ loadGhostSettingsHeight(dataOwnerId, settingsHeightKey, manifest.version) ??
AUTO_HEIGHT_PLACEHOLDER,
);
@@ -196,7 +199,7 @@ function SettingsWebviewBody({
.then((h: unknown) => {
if (disposed || typeof h !== 'number' || !Number.isFinite(h)) return;
const clamped = Math.max(AUTO_HEIGHT_MIN, Math.min(AUTO_HEIGHT_MAX, Math.ceil(h)));
- saveGhostSettingsHeight(dataOwnerId, manifest.id, manifest.version, clamped);
+ saveGhostSettingsHeight(dataOwnerId, settingsHeightKey, manifest.version, clamped);
setAutoHeight((cur) => (cur === clamped ? cur : clamped));
})
.catch(() => {})
@@ -286,6 +289,8 @@ function SettingsWebviewBody({
fixedHeight,
dataOwnerId,
partitionClaim,
+ settingsHeightKey,
+ approvalToken,
hostAccount,
]);
@@ -333,6 +338,7 @@ export function GhostSettingsWebview({
const { mode, dataOwnerId } = useAuth();
const ownerKey = `${mode}:${dataOwnerId ?? ''}`;
const { manifest } = ghost;
+ const settingsHeightKey = pluginStoragePart(installedGhostLogicalIdentity(ghost));
if (!manifest.settingsHtml) return null;
return (
<div
@@ -363,7 +369,7 @@ export function GhostSettingsWebview({
{t('ccAgent.gitContext.pr.setup.account.otherMethods')}
</summary>
<SettingsWebviewBody
- key={JSON.stringify([ownerKey, manifest.id, manifest.version, reloadKey])}
+ key={JSON.stringify([ownerKey, settingsHeightKey, manifest.version, reloadKey])}
ghost={ghost}
appearance={appearance}
dataOwnerId={dataOwnerId}
@@ -372,7 +378,7 @@ export function GhostSettingsWebview({
</details>
) : ghost.enabled ? (
<SettingsWebviewBody
- key={JSON.stringify([ownerKey, manifest.id, manifest.version, reloadKey])}
+ key={JSON.stringify([ownerKey, settingsHeightKey, manifest.version, reloadKey])}
ghost={ghost}
appearance={appearance}
dataOwnerId={dataOwnerId}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
index 6d007c17d5..80aabd362d 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
@@ -96,6 +96,26 @@ function renderSettings(settingsHeight?: number, measuredHeight?: number) {
}
describe('GhostSettingsWebview layout ownership', () => {
+ it('recreates the settings guest when a same-version source gets a new receipt', () => {
+ const { ghost, view } = renderSettings();
+ const approved = { ...ghost, approval: { state: 'approved' as const, revision: 'receipt-a' } };
+ view.rerender(<GhostSettingsWebview ghost={approved} />);
+ const original = view.container.querySelector('webview');
+ view.rerender(<GhostSettingsWebview ghost={{ ...approved, approval: { state: 'approved', revision: 'receipt-b' } }} />);
+ const replacement = view.container.querySelector('webview');
+ expect(replacement).not.toBe(original);
+ expect(original?.isConnected).toBe(false);
+ expect(replacement?.getAttribute('src')).toBe(original?.getAttribute('src'));
+ view.rerender(<GhostSettingsWebview ghost={{ ...approved, approval: { state: 'approved', revision: 'receipt-b' } }} />);
+ expect(view.container.querySelector('webview')).toBe(replacement);
+ });
+ it('keeps an in-place settings page on its physical WebView partition', () => {
+ const { ghost, view, webview } = renderSettings();
+ expect(webview.getAttribute('partition')).toBe('cindy-ghost-example-settings-layout');
+ view.rerender(<GhostSettingsWebview ghost={{ ...ghost, dir: '/ghosts/example-settings-layout', instanceKey: 'example-settings-layout', namespace: 'acme' }} />);
+ expect(view.container.querySelector('webview')?.getAttribute('partition'))
+ .toBe('cindy-ghost-example-settings-layout');
+ });
it('keeps account status visible and the plugin form collapsed without a duplicate title', () => {
const { ghost, view } = renderSettings();
view.rerender(
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMainViews.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMainViews.test.ts
index 63f3b3bcd9..2d98249ccf 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMainViews.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMainViews.test.ts
@@ -74,4 +74,22 @@ describe('projectGhostMainViews', () => {
['z-id', 'globe'],
]);
});
+
+ it('gives same-name plugins distinct instance ids for routing', () => {
+ const projection = projectGhostMainViews(
+ [
+ ghost('helper', { dir: '/plugins/helper', namespace: null }),
+ ghost('helper', {
+ dir: '/plugins/_ns/acme/helper',
+ namespace: 'acme',
+ }),
+ ],
+ { locale: 'en', isSidebarVisible: () => true },
+ );
+ expect(projection.routeCapable.map((item) => item.instanceId).sort()).toEqual([
+ '_ns__acme__helper',
+ 'helper',
+ ]);
+ });
+
});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandover.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandover.test.ts
new file mode 100644
index 0000000000..1f9e4d67a8
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandover.test.ts
@@ -0,0 +1,78 @@
+/** @vitest-environment jsdom */
+
+import type { TFunction } from 'i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ getDraft: vi.fn(), saveDraft: vi.fn(), success: vi.fn(), error: vi.fn() }));
+vi.mock('@/lib/composerDraftStore', () => ({ getDraft: mocks.getDraft, saveDraft: mocks.saveDraft }));
+vi.mock('@/lib/toast', () => ({ toast: { success: mocks.success, error: mocks.error } }));
+
+import { GHOST_MEDIA_HANDOVER_MIME } from '../../../shared/ghost';
+import { attachGhostMediaToSession, getGhostMediaHandoverFromDataTransfer } from '../ghostMediaHandover';
+
+const uri = 'cindy-ghost://helper/preview/' + 'a'.repeat(64) + '.png';
+const translate = ((key: string) => key) as TFunction;
+
+function transfer(entries: Record<string, string>): DataTransfer {
+ return { types: Object.keys(entries), getData: (type: string) => entries[type] ?? '' } as unknown as DataTransfer;
+}
+
+describe('Ghost media handover', () => {
+ afterEach(() => { vi.clearAllMocks(); vi.unstubAllGlobals(); });
+
+ it('uses the opaque source token, not a self-reported instance', async () => {
+ const source = getGhostMediaHandoverFromDataTransfer(transfer({
+ 'text/uri-list': uri,
+ [GHOST_MEDIA_HANDOVER_MIME]: JSON.stringify({ uri, sourceToken: 'opaque-source', instanceId: 'helper' }),
+ }));
+ expect(source).toEqual({ uri, sourceToken: 'opaque-source' });
+ const resolvePanelMedia = vi.fn().mockResolvedValue({ kind: 'video', absPath: '/blobs/video.mp4', name: 'video.mp4', ext: '.mp4', size: 42, mimeType: 'video/mp4' });
+ const cacheMediaForSession = vi.fn();
+ vi.stubGlobal('electronAPI', { ghosts: { resolvePanelMedia }, cacheMediaForSession });
+ await attachGhostMediaToSession(source!, 'session', translate);
+ expect(resolvePanelMedia).toHaveBeenCalledExactlyOnceWith(uri, 'attach', undefined, 'opaque-source');
+ expect(cacheMediaForSession).not.toHaveBeenCalled();
+ expect(mocks.saveDraft).toHaveBeenCalledWith('session', expect.objectContaining({
+ attachments: [expect.objectContaining({ category: 'file', path: '/blobs/video.mp4' })],
+ }), { preserveRemoteOptimisticRecovery: true });
+ });
+
+ it('retains the old root API and the image cache attachment path', async () => {
+ const source = getGhostMediaHandoverFromDataTransfer(transfer({ 'text/uri-list': '# comment' + String.fromCharCode(10) + uri }));
+ expect(source).toEqual({ uri, sourceToken: '' });
+ const resolvePanelMedia = vi.fn().mockResolvedValue({ url: 'cindy-media://blobs/image.png' });
+ const cacheMediaForSession = vi.fn().mockResolvedValue({ name: 'image.png', ext: '.png', size: 42, mimeType: 'image/png', url: 'cindy-media://cache/image.png' });
+ vi.stubGlobal('electronAPI', { ghosts: { resolvePanelMedia }, cacheMediaForSession });
+ await attachGhostMediaToSession(uri, 'session', translate);
+ expect(resolvePanelMedia).toHaveBeenCalledExactlyOnceWith(uri);
+ expect(cacheMediaForSession).toHaveBeenCalledExactlyOnceWith({ url: 'cindy-media://blobs/image.png', sessionId: 'session' });
+ expect(mocks.saveDraft).toHaveBeenCalledWith('session', expect.objectContaining({
+ attachments: [expect.objectContaining({ category: 'image', url: 'cindy-media://cache/image.png' })],
+ }), { preserveRemoteOptimisticRecovery: true });
+ });
+
+ it.each(['broken-json', '{}', JSON.stringify({ sourceToken: 42 }), JSON.stringify({ sourceToken: '' })])('does not downgrade malformed Cindy MIME %s to a legacy URI', async (payload) => {
+ const source = getGhostMediaHandoverFromDataTransfer(transfer({ 'text/uri-list': uri, [GHOST_MEDIA_HANDOVER_MIME]: payload }));
+ expect(source?.sourceToken).toBe('');
+ const resolvePanelMedia = vi.fn().mockRejectedValue(new Error('NOT_FOUND'));
+ vi.stubGlobal('electronAPI', { ghosts: { resolvePanelMedia } });
+ await attachGhostMediaToSession(source!, 'session', translate);
+ expect(resolvePanelMedia).toHaveBeenCalledExactlyOnceWith(uri, 'attach', undefined, '');
+ expect(mocks.saveDraft).not.toHaveBeenCalled();
+ expect(mocks.error).toHaveBeenCalledOnce();
+ });
+
+ it('ignores unrelated drops and retains plain text fallback', () => {
+ expect(getGhostMediaHandoverFromDataTransfer(transfer({ 'text/plain': 'hello' }))).toBeNull();
+ expect(getGhostMediaHandoverFromDataTransfer(transfer({ 'text/plain': uri }))).toEqual({ uri, sourceToken: '' });
+ });
+
+ it('does not treat a deleted source MIME as a legacy root attachment request', async () => {
+ const source = getGhostMediaHandoverFromDataTransfer(transfer({ 'text/uri-list': uri }));
+ const resolvePanelMedia = vi.fn().mockRejectedValue(new Error('NOT_FOUND'));
+ vi.stubGlobal('electronAPI', { ghosts: { resolvePanelMedia } });
+ await attachGhostMediaToSession(source!, 'session', translate);
+ expect(resolvePanelMedia).toHaveBeenCalledExactlyOnceWith(uri, 'attach', undefined, '');
+ expect(mocks.saveDraft).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandoverDrag.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandoverDrag.test.ts
new file mode 100644
index 0000000000..8a01aaad58
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandoverDrag.test.ts
@@ -0,0 +1,43 @@
+/** @vitest-environment jsdom */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { GHOST_MEDIA_HANDOVER_MIME } from '../../../shared/ghost';
+import { GhostMediaHandoverTargetTracker, ghostMediaHandoverDragScript } from '../../../main/cindy-brain/ghostMediaHandoverTargetTracker';
+import { getGhostMediaHandoverFromDataTransfer } from '../ghostMediaHandover';
+
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('@/lib/composerDraftStore', () => ({ getDraft: vi.fn(), saveDraft: vi.fn() }));
+
+describe.each(['helper', '_ns__acme__helper'])('Main-injected Ghost drag source %s', (instanceId) => {
+ it.each([
+ ['a', 'href', 'preview', '.png'],
+ ['img', 'src', 'media', '.png'],
+ ['video', 'src', 'media', '.mp4'],
+ ['div', 'data-uri', 'media', '.png'],
+ ])('carries the registered source for a default %s drag without an author API', (tag, attribute, shape, ext) => {
+ const tracker = new GhostMediaHandoverTargetTracker();
+ const token = tracker.register({ ghostId: 'helper', instanceId, isCurrent: () => true });
+ const addEventListener = vi.fn();
+ new Function('window', ghostMediaHandoverDragScript(token))({ addEventListener });
+ expect(addEventListener).toHaveBeenCalledWith('dragstart', expect.any(Function), true);
+ const listener = addEventListener.mock.calls[0][1] as (event: unknown) => void;
+ const uri = 'cindy-ghost://helper/' + shape + '/' + 'a'.repeat(64) + ext;
+ const target = document.createElement(tag);
+ target.setAttribute(attribute, uri);
+ const values: Record<string, string> = tag === 'div' ? { 'text/uri-list': uri } : {};
+ const dataTransfer = {
+ get types() { return Object.keys(values); },
+ getData: (type: string) => values[type] ?? '',
+ setData: (type: string, value: string) => { values[type] = value; },
+ };
+ listener({ isTrusted: false, target, dataTransfer });
+ expect(values[GHOST_MEDIA_HANDOVER_MIME]).toBeUndefined();
+ listener({ isTrusted: true, target, dataTransfer });
+ const source = getGhostMediaHandoverFromDataTransfer(dataTransfer as unknown as DataTransfer);
+ expect(source).toEqual({ uri, sourceToken: token });
+ expect(tracker.resolve(source?.sourceToken, source?.uri)).toEqual({ ghostId: 'helper', instanceId });
+ tracker.revoke(token);
+ expect(tracker.resolve(source?.sourceToken, source?.uri)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandoverEntryPoints.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandoverEntryPoints.test.ts
new file mode 100644
index 0000000000..d8bbea9d59
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostMediaHandoverEntryPoints.test.ts
@@ -0,0 +1,54 @@
+/** @vitest-environment jsdom */
+
+import fs from 'node:fs';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+vi.mock('@/lib/composerDraftStore', () => ({ getDraft: vi.fn(), saveDraft: vi.fn() }));
+
+import { GHOST_MEDIA_HANDOVER_MIME } from '../../../shared/ghost';
+import { getGhostMediaHandoverFromDataTransfer } from '../ghostMediaHandover';
+
+function loadDropBranch(filename: string, attach: ReturnType<typeof vi.fn>) {
+ const source = fs.readFileSync(new URL(filename, import.meta.url), 'utf8');
+ const ast = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ let statements = '';
+ const visit = (node: ts.Node): void => {
+ if (ts.isBlock(node)) {
+ const position = node.statements.findIndex((statement) => ts.isVariableStatement(statement)
+ && statement.declarationList.declarations.some((declaration) => declaration.initializer
+ && ts.isCallExpression(declaration.initializer)
+ && declaration.initializer.expression.getText(ast) === 'getGhostMediaHandoverFromDataTransfer'));
+ if (position >= 0) {
+ statements = node.statements[position].getText(ast) + String.fromCharCode(10) + node.statements[position + 1].getText(ast);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ expect(statements).not.toBe('');
+ const compiled = ts.transpileModule(statements, {}).outputText;
+ return (dataTransfer: DataTransfer) => new Function(
+ 'e', 'event', 'storageKey', 'sessionId', 'attachmentScope', 'NEW_MAKER_DRAFT_KEY', 't',
+ 'getGhostMediaHandoverFromDataTransfer', 'attachGhostMediaToSession', compiled,
+ )({ dataTransfer, preventDefault: vi.fn(), stopPropagation: vi.fn() }, { dataTransfer }, 'draft', 'session', 'group', 'maker-draft', vi.fn(), getGhostMediaHandoverFromDataTransfer, attach);
+}
+
+describe.each([
+ ['../../components/new-chat/ChatInput.tsx', 'draft'],
+ ['../../features/cc-agent/CCAgentSessionView.tsx', 'session'],
+ ['../../features/cc-agent/NewMakerDraftRoute.tsx', 'maker-draft'],
+ ['../../features/bots/BotGroupChatView.tsx', 'group'],
+])('%s Ghost drop branch', (filename, session) => {
+ it.each(['media', 'preview'])('hands the %s source token intact to the shared attachment chain', (shape) => {
+ const uri = 'cindy-ghost://helper/' + shape + '/' + 'a'.repeat(64) + '.png';
+ const values: Record<string, string> = {
+ 'text/uri-list': uri,
+ [GHOST_MEDIA_HANDOVER_MIME]: JSON.stringify({ uri, sourceToken: 'opaque-source' }),
+ };
+ const attach = vi.fn();
+ loadDropBranch(filename, attach)({ types: Object.keys(values), getData: (type: string) => values[type] ?? '' } as unknown as DataTransfer);
+ expect(attach).toHaveBeenCalledExactlyOnceWith({ uri, sourceToken: 'opaque-source' }, session, expect.any(Function));
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
index 1b53dee7b7..922c54d29f 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
@@ -1,9 +1,13 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
-import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';
+import {
+ ghostInstallApprovalToken,
+ type GhostManifest,
+ type InstalledGhost,
+} from '../../../shared/ghost';
import {
__resetGhostPanelBubbleStateForTest,
getGhostPanelBubbleState,
@@ -17,9 +21,11 @@ import {
} from '../../panels/registry';
import {
__resetGhostPanelsForTest,
+ ensureGhostPanelsRegistered,
pickGhostPanelMediaUri,
syncGhostPanelRegistrations,
} from '../ghostPanels';
+import { __resetInstalledGhostsStoreForTest } from '../useInstalledGhosts';
// 仓库同款 i18n mock:t 返回 key(带参拼上,便于断言)。
vi.mock('react-i18next', () => ({
@@ -32,7 +38,13 @@ vi.mock('react-i18next', () => ({
// 面板体是 webview 供片,jsdom 渲不了也不该渲 —— 置空,只测宿主壳(标准头/关闭链路)。
vi.mock('../ghostPanelBody', async (importOriginal) => ({
...(await importOriginal<typeof import('../ghostPanelBody')>()),
- GhostChipPanelBody: () => null,
+ GhostChipPanelBody: ({ ghost: installed }: { ghost: InstalledGhost }) => (
+ <div
+ data-testid="ghost-body"
+ data-dir={installed.dir}
+ data-approval={ghostInstallApprovalToken(installed.approval)}
+ />
+ ),
GhostPanelError: () => null,
}));
@@ -55,10 +67,30 @@ function ghost(id: string, panel?: GhostManifest['panel'] | null, enabled = true
};
}
+function bridgeGhosts(initial: InstalledGhost[], setEnabled = vi.fn()) {
+ let roster = initial;
+ const listeners = new Set<(event: { ghosts: InstalledGhost[] }) => void>();
+ const api = {
+ setEnabled,
+ listSync: vi.fn(() => ({ ghosts: roster })),
+ onChanged: vi.fn((listener: (event: { ghosts: InstalledGhost[] }) => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }),
+ change(next: InstalledGhost[]) {
+ roster = next;
+ listeners.forEach((listener) => listener({ ghosts: next }));
+ },
+ };
+ (window as unknown as { electronAPI: unknown }).electronAPI = { ghosts: api };
+ return api;
+}
+
afterEach(() => {
cleanup();
__resetPanelRegistryForTest();
__resetGhostPanelsForTest();
+ __resetInstalledGhostsStoreForTest();
__resetGhostPanelBubbleStateForTest();
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
});
@@ -92,13 +124,53 @@ describe('syncGhostPanelRegistrations · 注册表与已装清单对齐', () =>
expect(hasPanelKind('ghost:b')).toBe(false);
});
- it('同步时对齐气泡状态:卸载删条目、停用强制还原(不留死角)', () => {
- minimizeGhostPanel('gone');
- minimizeGhostPanel('disabled');
- syncGhostPanelRegistrations([ghost('disabled', undefined, false)]);
- const bubbles = getGhostPanelBubbleState();
- expect(bubbles.gone).toBeUndefined();
- expect(bubbles.disabled?.minimized).not.toBe(true);
+ it.each(['approval', 'directory', 'manifest'] as const)('广播更新 %s 后使用当前实例,不替换面板组件', (field) => {
+ const installed = ghost('demo');
+ const api = bridgeGhosts([installed]);
+ ensureGhostPanelsRegistered();
+ const Component = getPanelKind('ghost:demo')!.Component;
+ render(<ConfirmDialogProvider><Component paneId="pane-1" /></ConfirmDialogProvider>);
+ const updated: InstalledGhost = {
+ ...installed,
+ ...(field === 'approval'
+ ? { approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' } }
+ : {}),
+ ...(field === 'directory' ? { dir: '/other/demo' } : {}),
+ ...(field === 'manifest'
+ ? { manifest: { ...installed.manifest, panel: { ...installed.manifest.panel!, title: 'updated title' } } }
+ : {}),
+ };
+ act(() => {
+ syncGhostPanelRegistrations([updated]);
+ api.change([updated]);
+ });
+ expect(getPanelKind('ghost:demo')!.Component).toBe(Component);
+ expect(screen.getByTestId('ghost-body').getAttribute('data-dir')).toBe(updated.dir);
+ expect(screen.getByTestId('ghost-body').getAttribute('data-approval'))
+ .toBe(ghostInstallApprovalToken(updated.approval));
+ if (field === 'manifest') expect(screen.getByText('updated title')).toBeTruthy();
+ expect(api.listSync).toHaveBeenCalledTimes(1);
+ });
+
+ it('同名 root / 组织面板各自消费物理实例,清单移除后不显示旧实例', () => {
+ const root = { ...ghost('helper'), namespace: null };
+ const organization = { ...ghost('helper'), namespace: 'acme', dir: '/fake/_ns/acme/helper' };
+ const api = bridgeGhosts([root, organization]);
+ ensureGhostPanelsRegistered();
+ const Root = getPanelKind('ghost:helper')!.Component;
+ const Organization = getPanelKind('ghost:_ns__acme__helper')!.Component;
+ render(
+ <ConfirmDialogProvider>
+ <Root paneId="root" />
+ <Organization paneId="organization" />
+ </ConfirmDialogProvider>,
+ );
+ expect(screen.getAllByTestId('ghost-body').map((element) => element.getAttribute('data-dir')))
+ .toEqual([root.dir, organization.dir]);
+ act(() => api.change([root]));
+ expect(screen.getAllByTestId('ghost-body')).toHaveLength(1);
+ expect(screen.getByTestId('ghost-body').getAttribute('data-dir')).toBe(root.dir);
+ expect(api.listSync).toHaveBeenCalledTimes(1);
});
it('同步时对齐气泡状态:卸载删条目、停用强制还原(不留死角)', () => {
@@ -154,19 +226,22 @@ describe('syncGhostPanelRegistrations · 停用即休眠', () => {
});
describe('GhostPanel · 标准头关闭按钮(二次确认后停用插件)', () => {
- function renderPanel(setEnabled: ReturnType<typeof vi.fn>): void {
- (window as unknown as { electronAPI: unknown }).electronAPI = {
- ghosts: { setEnabled },
- };
- syncGhostPanelRegistrations([ghost('demo')]);
+ function renderPanel(
+ setEnabled: ReturnType<typeof vi.fn>,
+ installed = ghost('demo'),
+ otherGhosts: InstalledGhost[] = [],
+ ) {
+ const api = bridgeGhosts([installed, ...otherGhosts], setEnabled);
+ syncGhostPanelRegistrations([installed, ...otherGhosts]);
const def = getPanelKind('ghost:demo');
if (!def) throw new Error('面板未注册');
const Component = def.Component;
- render(
+ const view = render(
<ConfirmDialogProvider>
<Component paneId="pane-1" />
</ConfirmDialogProvider>,
);
+ return { api, view };
}
it('点关闭 → 弹确认框;确认后 setEnabled(id, false)', async () => {
@@ -177,7 +252,7 @@ describe('GhostPanel · 标准头关闭按钮(二次确认后停用插件)', ()
await screen.findByText('ghostPanel.disableConfirm.title:{"name":"demo 意识"}');
expect(setEnabled).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'ghostPanel.disableConfirm.confirm' }));
- await waitFor(() => expect(setEnabled).toHaveBeenCalledWith('demo', false));
+ await waitFor(() => expect(setEnabled).toHaveBeenCalledWith('demo', false, ghostInstallApprovalToken(ghost('demo').approval)));
expect(setEnabled).toHaveBeenCalledTimes(1);
});
@@ -194,4 +269,93 @@ describe('GhostPanel · 标准头关闭按钮(二次确认后停用插件)', ()
);
expect(setEnabled).not.toHaveBeenCalled();
});
+
+ it('原实例卸载后取消旧确认,不关闭仍在场的组织同名实例', async () => {
+ const setEnabled = vi.fn().mockResolvedValue({ ok: true });
+ const organization = { ...ghost('demo'), namespace: 'acme', dir: '/fake/_ns/acme/demo' };
+ const { api } = renderPanel(setEnabled, { ...ghost('demo'), namespace: null }, [organization]);
+ fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));
+ const staleConfirm = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });
+
+ act(() => api.change([organization]));
+
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'ghostPanel.disableConfirm.confirm' })).toBeNull());
+ fireEvent.click(staleConfirm);
+ expect(setEnabled).not.toHaveBeenCalled();
+ });
+
+ it.each(['approval', 'directory', 'namespace', 'disabled', 'panel'] as const)(
+ '原实例 %s 变更后取消旧确认,新确认仍可用',
+ async (field) => {
+ const setEnabled = vi.fn().mockResolvedValue({ ok: true });
+ const installed = ghost('demo');
+ const { api } = renderPanel(setEnabled, installed);
+ fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));
+ const staleConfirm = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });
+ const updated: InstalledGhost = {
+ ...installed,
+ ...(field === 'approval' ? { approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' } } : {}),
+ ...(field === 'directory' ? { dir: '/other/demo' } : {}),
+ ...(field === 'namespace' ? { namespace: 'acme' } : {}),
+ ...(field === 'disabled' ? { enabled: false } : {}),
+ ...(field === 'panel' ? { manifest: { ...installed.manifest, panel: { html: 'panel.html', position: 'tab' } } } : {}),
+ };
+
+ act(() => api.change([updated]));
+
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'ghostPanel.disableConfirm.confirm' })).toBeNull());
+ fireEvent.click(staleConfirm);
+ expect(setEnabled).not.toHaveBeenCalled();
+
+ if (field === 'disabled' || field === 'panel') act(() => api.change([installed]));
+ fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' }));
+ const confirmed = field === 'disabled' || field === 'panel' ? installed : updated;
+ await waitFor(() => expect(setEnabled).toHaveBeenCalledExactlyOnceWith('demo', false, ghostInstallApprovalToken(confirmed.approval)));
+ },
+ );
+
+ it('面板卸载但全局确认宿主保留时取消旧确认', async () => {
+ const setEnabled = vi.fn().mockResolvedValue({ ok: true });
+ const { view } = renderPanel(setEnabled);
+ fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));
+ const staleConfirm = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });
+
+ view.rerender(<ConfirmDialogProvider><div /></ConfirmDialogProvider>);
+
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'ghostPanel.disableConfirm.confirm' })).toBeNull());
+ fireEvent.click(staleConfirm);
+ expect(setEnabled).not.toHaveBeenCalled();
+ });
+
+ it('安装身份未变化的清单刷新不取消用户确认', async () => {
+ const setEnabled = vi.fn().mockResolvedValue({ ok: true });
+ const installed = ghost('demo');
+ const { api } = renderPanel(setEnabled, installed);
+ fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));
+ await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });
+
+ act(() => api.change([{ ...installed, manifest: { ...installed.manifest } }]));
+
+ fireEvent.click(screen.getByRole('button', { name: 'ghostPanel.disableConfirm.confirm' }));
+ await waitFor(() => expect(setEnabled).toHaveBeenCalledExactlyOnceWith('demo', false, ghostInstallApprovalToken(installed.approval)));
+ });
+
+ it.each(['uninstall', 'approval'] as const)('确认恢复前原实例 %s 不执行旧关闭', async (change) => {
+ const setEnabled = vi.fn().mockResolvedValue({ ok: true });
+ const installed = ghost('demo');
+ const { api } = renderPanel(setEnabled, installed);
+ fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));
+ const confirmButton = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });
+
+ await act(async () => {
+ fireEvent.click(confirmButton);
+ api.change(change === 'uninstall' ? [] : [{
+ ...installed,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' },
+ }]);
+ });
+
+ expect(setEnabled).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
index 0c9cc4ebf4..b1d1c08978 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
@@ -104,6 +104,7 @@ describe('ghostPluginViewModel', () => {
const items = [
{
id: 'xd-mivo',
+ ghostId: 'xd-mivo',
name: 'XD Mivo',
description: 'media',
version: '1',
@@ -117,6 +118,7 @@ describe('ghostPluginViewModel', () => {
},
{
id: 'lizi-mivo',
+ ghostId: 'lizi-mivo',
name: 'Lizi Mivo',
description: 'media',
version: '1',
@@ -130,6 +132,7 @@ describe('ghostPluginViewModel', () => {
},
{
id: 'slack',
+ ghostId: 'slack',
name: 'Cindy Slack',
description: 'messages',
version: '1',
@@ -222,11 +225,26 @@ describe('ghostPluginViewModel', () => {
});
});
+ it('uses the physical storage part as the instance id', () => {
+ const item = toGhostPluginListItem(
+ installed({
+ manifest: manifest({ id: 'helper' }),
+ namespace: 'acme',
+ dir: '/tmp/cindy-brain/_ns/acme/helper',
+ }),
+ );
+ expect(item).toMatchObject({
+ id: '_ns__acme__helper',
+ ghostId: 'helper',
+ });
+ });
+
it('maps install-record facts onto the list item', () => {
const item = toGhostPluginListItem(installed());
expect(item).toMatchObject({
id: 'xd-mivo',
+ ghostId: 'xd-mivo',
name: 'XD Mivo',
enabled: true,
canUse: true,
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsHeight.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsHeight.test.ts
index 4700ed4052..ddfc80c6a6 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsHeight.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsHeight.test.ts
@@ -35,6 +35,20 @@ describe('settings height cache', () => {
expect(loadGhostSettingsHeight('owner-a', 'g1', '2.0.0')).toBeNull();
});
+ it('keeps an in-place organization height stored under the logical key', () => {
+ saveGhostSettingsHeight('owner-a', '_ns__xd__xd-feishu', '1.0.0', 280);
+ pruneGhostSettingsHeights('owner-a', ['_ns__xd__xd-feishu']);
+ expect(loadGhostSettingsHeight('owner-a', '_ns__xd__xd-feishu', '1.0.0')).toBe(280);
+ });
+
+ it('keeps same-name root and organization heights separate', () => {
+ saveGhostSettingsHeight('owner-a', 'helper', '1.0.0', 240);
+ saveGhostSettingsHeight('owner-a', '_ns__acme__helper', '1.0.0', 320);
+ pruneGhostSettingsHeights('owner-a', ['helper', '_ns__acme__helper']);
+ expect(loadGhostSettingsHeight('owner-a', 'helper', '1.0.0')).toBe(240);
+ expect(loadGhostSettingsHeight('owner-a', '_ns__acme__helper', '1.0.0')).toBe(320);
+ });
+
it('isolates owners and plugins without claiming unowned legacy data', () => {
localStorage.setItem('ghostSettings.snapshot.g1', JSON.stringify(legacySnapshot));
saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', 240);
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
index 2e9e2d1400..0e6be4fbc4 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
@@ -1,7 +1,7 @@
/** @vitest-environment jsdom */
import { fireEvent, render, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('../ghostPanelTheme', () => ({
createGhostThemeInjector: () => ({
@@ -28,9 +28,43 @@ const manifest: GhostManifest = {
};
describe('GhostWebviewBody', () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it.each(['panel.html', 'main-view.html'])('recreates %s on a same-version receipt replacement', (html) => {
+ const ghost = { manifest, dir: '/plugins/workspace', approval: { state: 'approved' as const, revision: 'receipt-a' } };
+ const { container, rerender } = render(<GhostWebviewBody ghost={ghost} html={html} />);
+ const original = container.querySelector('webview');
+ rerender(<GhostWebviewBody ghost={{ ...ghost, approval: { state: 'approved', revision: 'receipt-b' } }} html={html} />);
+ const replacement = container.querySelector('webview');
+ expect(replacement).not.toBe(original);
+ expect(original?.isConnected).toBe(false);
+ expect(replacement?.getAttribute('src')).toBe('cindy-ghost://workspace/' + html);
+ rerender(<GhostWebviewBody ghost={{ ...ghost, approval: { state: 'approved', revision: 'receipt-b' } }} html={html} />);
+ expect(container.querySelector('webview')).toBe(replacement);
+ });
+
+ it.each([
+ ['/plugins/workspace', undefined, 'workspace'],
+ ['/plugins/workspace', null, 'workspace'],
+ ['/plugins/workspace', 'acme', 'workspace'],
+ ['/plugins/_ns/acme/workspace', 'acme', '_ns__acme__workspace'],
+ ] as const)('passes the physical instance for context menus at %s', async (dir, namespace, instanceId) => {
+ const resolvePanelMedia = vi.fn(async () => { throw new Error('not-owned'); });
+ vi.stubGlobal('electronAPI', { ghosts: { resolvePanelMedia } });
+ const { container } = render(
+ <GhostWebviewBody ghost={{ manifest, dir, ...(namespace === undefined ? {} : { namespace }) }} html={manifest.mainView?.html} />,
+ );
+ const webview = container.querySelector('webview') as HTMLElement;
+ const uri = 'cindy-ghost://workspace/media/' + 'a'.repeat(64) + '.png';
+ const event = new Event('context-menu');
+ Object.defineProperty(event, 'params', { value: { mediaType: 'image', srcURL: uri, x: 10, y: 20 } });
+ fireEvent(webview, event);
+ await waitFor(() => expect(resolvePanelMedia).toHaveBeenCalledExactlyOnceWith(uri, 'menu', instanceId));
+ });
+
it('keeps the existing per-plugin partition and approved cindy-ghost entry shape', async () => {
const { container } = render(
- <GhostWebviewBody manifest={manifest} html={manifest.mainView?.html} />,
+ <GhostWebviewBody ghost={{ manifest, dir: '/plugins/workspace' }} html={manifest.mainView?.html} />,
);
await waitFor(() => expect(container.querySelector('webview')).not.toBeNull());
@@ -42,7 +76,7 @@ describe('GhostWebviewBody', () => {
it('shows the recoverable error state when the main document fails to load', async () => {
const { container, getByRole } = render(
- <GhostWebviewBody manifest={manifest} html={manifest.mainView?.html} />,
+ <GhostWebviewBody ghost={{ manifest, dir: '/plugins/workspace' }} html={manifest.mainView?.html} />,
);
const webview = await waitFor(() => {
const node = container.querySelector('webview');
@@ -63,7 +97,7 @@ describe('GhostWebviewBody', () => {
it('ignores aborted navigation and subframe load failures', async () => {
const { container, queryByRole } = render(
- <GhostWebviewBody manifest={manifest} html={manifest.mainView?.html} />,
+ <GhostWebviewBody ghost={{ manifest, dir: '/plugins/workspace' }} html={manifest.mainView?.html} />,
);
const webview = await waitFor(() => {
const node = container.querySelector('webview');
@@ -86,4 +120,57 @@ describe('GhostWebviewBody', () => {
expect(queryByRole('button', { name: 'settings.ghosts.panelError.reload' })).toBeNull();
expect(container.querySelector('webview')).toBe(webview);
});
+
+ it('isolates an in-place namespaced plugin from a later root partition', async () => {
+ const inPlace = {
+ ...manifest,
+ id: 'xd-feishu',
+ settingsHtml: 'settings.html',
+ } satisfies GhostManifest;
+ const { container } = render(
+ <GhostWebviewBody
+ ghost={{ manifest: inPlace, namespace: 'xd', dir: '/userData/cindy-brain/xd-feishu' }}
+ html={inPlace.settingsHtml}
+ />,
+ );
+ const webview = await waitFor(() => {
+ const node = container.querySelector('webview');
+ expect(node).not.toBeNull();
+ return node as HTMLElement;
+ });
+ expect(webview.getAttribute('partition')).toBe('cindy-ghost-xd-feishu');
+ expect(webview.getAttribute('src')).toBe('cindy-ghost://xd-feishu/settings.html');
+ });
+
+ it('keeps the physical partition when an in-place install gains a namespace', async () => {
+ const root = { manifest, dir: '/plugins/workspace' };
+ const { container, rerender } = render(
+ <GhostWebviewBody ghost={root} html={manifest.mainView?.html} />,
+ );
+ const previous = container.querySelector('webview');
+ expect(previous?.getAttribute('partition')).toBe('cindy-ghost-workspace');
+
+ rerender(<GhostWebviewBody ghost={{ ...root, namespace: 'acme' }} html={manifest.mainView?.html} />);
+ const current = container.querySelector('webview');
+ expect(current).toBe(previous);
+ expect(current?.getAttribute('partition')).toBe('cindy-ghost-workspace');
+ expect(current?.getAttribute('src')).toBe('cindy-ghost://workspace/main-view.html');
+ });
+
+ it('uses the namespaced storage part when the install directory is under _ns', async () => {
+ const orgManifest = { ...manifest, id: 'helper' } satisfies GhostManifest;
+ const { container } = render(
+ <GhostWebviewBody
+ ghost={{ manifest: orgManifest, namespace: 'acme', dir: '/userData/cindy-brain/_ns/acme/helper' }}
+ html={orgManifest.mainView?.html}
+ />,
+ );
+ const webview = await waitFor(() => {
+ const node = container.querySelector('webview');
+ expect(node).not.toBeNull();
+ return node as HTMLElement;
+ });
+ expect(webview.getAttribute('partition')).toBe('cindy-ghost-_ns__acme__helper');
+ expect(webview.getAttribute('src')).toBe('cindy-ghost://helper/main-view.html');
+ });
});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts
index 3b73725df7..2c3f40f876 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { GHOST_OFFICIAL_ID_PREFIXES } from '../../../shared/ghost';
+import { GHOST_OFFICIAL_ID_PREFIX } from '../../../shared/ghost';
import i18n from '../../i18n';
import { ghostInstallErrorKey } from '../installErrorKey';
@@ -60,7 +60,7 @@ describe('ghostInstallErrorKey', () => {
expect(rawMessage).toEqual(expect.any(String));
expect(rawMessage).toContain('{{reservedGhostIdPrefixes}}');
// 渲染结果排除默认变量漏接或插值失效。
- expect(message).toContain(GHOST_OFFICIAL_ID_PREFIXES.join(' / '));
+ expect(message).toContain(GHOST_OFFICIAL_ID_PREFIX);
expect(message).not.toContain('{{reservedGhostIdPrefixes}}');
},
);
@@ -76,7 +76,7 @@ describe('ghostInstallErrorKey', () => {
expect(rawMessage).toEqual(expect.any(String));
expect(rawMessage).toContain('{{reservedGhostIdPrefixes}}');
// 渲染结果排除默认变量漏接或插值失效。
- expect(message).toContain(GHOST_OFFICIAL_ID_PREFIXES.join(' / '));
+ expect(message).toContain(GHOST_OFFICIAL_ID_PREFIX);
expect(message).not.toContain('{{reservedGhostIdPrefixes}}');
},
);
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
index 92bf87b1fd..64ff5c5d8e 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
@@ -3,7 +3,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { toast } from '@/lib/toast';
-import { installGhostFromFile } from '../installFlow';
+import { installGhostFromFile, pickAndUpdateGhost } from '../installFlow';
vi.mock('@/lib/toast', () => ({
toast: { success: vi.fn(), error: vi.fn() },
@@ -27,22 +27,24 @@ function setupWindow(manifest: object, installed: object[] = []) {
const update = vi.fn(async () => ({
ghost: { manifest, dir: '/tmp/installed', enabled: true },
}));
+ const inspect = vi.fn(async () => ({
+ manifest,
+ packageSha256: 'a'.repeat(64),
+ unsupportedSlots: [],
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ }));
Object.defineProperty(globalThis, 'window', {
value: {
electronAPI: {
appVersion: '1.0.0',
ghosts: {
- inspect: vi.fn(async () => ({
- manifest,
- packageSha256: 'a'.repeat(64),
- unsupportedSlots: [],
- trust: {
- level: 'unverified',
- publisherSigned: false,
- publisherVerified: false,
- reviewed: false,
- },
- })),
+ inspect,
+ pickFile: vi.fn(async () => ({ filePath: '/tmp/node.cindy' })),
listSync: vi.fn(() => ({ ghosts: installed })),
install,
update,
@@ -51,7 +53,7 @@ function setupWindow(manifest: object, installed: object[] = []) {
},
configurable: true,
});
- return { install, update };
+ return { install, update, inspect };
}
afterEach(() => {
@@ -60,6 +62,55 @@ afterEach(() => {
});
describe('installFlow · 本地包安装', () => {
+ it.each(['node-ghost', '_ns__xd__node-ghost'])(
+ 'binds local update inspect and commit to %s',
+ async (instanceId) => {
+ const namespace = instanceId === 'node-ghost' ? null : 'xd';
+ const installed = {
+ manifest: baseManifest,
+ namespace,
+ dir: namespace ? '/tmp/brain/_ns/xd/node-ghost' : '/tmp/brain/node-ghost',
+ approval: { state: 'approved', revision: 'selected-receipt' },
+ };
+ const { inspect, update } = setupWindow(baseManifest, [installed]);
+ await pickAndUpdateGhost(instanceId, { t: ((key: string) => key) as never });
+ const target = {
+ expectedInstalledInstanceId: instanceId,
+ expectedInstalledApproval: 'approved:selected-receipt',
+ };
+ expect(inspect).toHaveBeenCalledWith('/tmp/node.cindy', target);
+ expect(update).toHaveBeenCalledWith('/tmp/node.cindy', {
+ ...target,
+ expectedPackageSha256: 'a'.repeat(64),
+ });
+ },
+ );
+
+ it('does not silently rebind an update after inspect to a replaced receipt', async () => {
+ const installed = [
+ {
+ manifest: baseManifest,
+ dir: '/tmp/brain/node-ghost',
+ namespace: null,
+ approval: { state: 'approved', revision: 'original-receipt' },
+ },
+ ];
+ const { inspect, update } = setupWindow(baseManifest, installed);
+ const original = inspect.getMockImplementation()!;
+ inspect.mockImplementation(async () => {
+ installed[0] = {
+ ...installed[0],
+ approval: { state: 'approved', revision: 'replacement-receipt' },
+ };
+ return original();
+ });
+ await pickAndUpdateGhost('node-ghost', { t: ((key: string) => key) as never });
+ expect(update).toHaveBeenCalledWith(
+ '/tmp/node.cindy',
+ expect.objectContaining({ expectedInstalledApproval: 'approved:original-receipt' }),
+ );
+ });
+
it('直接启用安装,并把真实包摘要交给 Main', async () => {
const { install } = setupWindow(baseManifest);
@@ -98,7 +149,10 @@ describe('installFlow · 本地包安装', () => {
it('同 id 已安装时直接原位更新,并绑定当前安装 receipt', async () => {
const installed = {
manifest: { ...baseManifest, version: '0.9.0' },
- dir: '/tmp/installed',
+ dir: '/tmp/brain/node-ghost',
+ instanceKey: 'node-ghost',
+ namespace: null,
+ namespaceState: 'confirmed' as const,
enabled: false,
approval: {
state: 'approved',
@@ -115,9 +169,98 @@ describe('installFlow · 本地包安装', () => {
expect(update).toHaveBeenCalledWith('/tmp/node.cindy', {
expectedPackageSha256: 'a'.repeat(64),
expectedInstalledApproval: 'approved:00000000-0000-4000-8000-000000000001',
+ expectedInstalledInstanceId: 'node-ghost',
});
});
+
+ it('updates a new root install instead of starting another one', async () => {
+ const installed = {
+ manifest: { ...baseManifest, version: '0.9.0' },
+ dir: '/tmp/brain/_ns/_root/node-ghost',
+ instanceKey: '_root__node-ghost',
+ namespace: null,
+ namespaceState: 'confirmed' as const,
+ approval: { state: 'approved', revision: 'root-receipt' },
+ };
+ const { install, update } = setupWindow(baseManifest, [installed]);
+ await installGhostFromFile('/tmp/node.cindy', { t: ((key: string) => key) as never });
+ expect(install).not.toHaveBeenCalled();
+ expect(update).toHaveBeenCalledWith('/tmp/node.cindy', expect.objectContaining({
+ expectedInstalledInstanceId: '_root__node-ghost',
+ }));
+ });
+
+ it('updates a pending legacy directory', async () => {
+ const installed = {
+ manifest: { ...baseManifest, version: '0.9.0' },
+ dir: '/tmp/brain/node-ghost',
+ instanceKey: 'node-ghost',
+ namespaceState: 'pending' as const,
+ approval: { state: 'approved', revision: 'legacy-receipt' },
+ };
+ const { install, update } = setupWindow(baseManifest, [installed]);
+ await installGhostFromFile('/tmp/node.cindy', { t: ((key: string) => key) as never });
+ expect(install).not.toHaveBeenCalled();
+ expect(update).toHaveBeenCalledWith('/tmp/node.cindy', expect.objectContaining({
+ expectedInstalledInstanceId: 'node-ghost',
+ }));
+ });
+
+ it('installs a new root beside an organization instance', async () => {
+ const installed = {
+ manifest: baseManifest,
+ dir: '/tmp/brain/_ns/xd/node-ghost',
+ instanceKey: '_ns__xd__node-ghost',
+ namespace: 'xd',
+ namespaceState: 'confirmed' as const,
+ approval: { state: 'approved', revision: 'org-receipt' },
+ };
+ const { install, update } = setupWindow(baseManifest, [installed]);
+ await installGhostFromFile('/tmp/node.cindy', { t: ((key: string) => key) as never });
+ expect(update).not.toHaveBeenCalled();
+ expect(install).toHaveBeenCalled();
+ });
+
+ it('installs a new root beside an in-place confirmed organization plugin', async () => {
+ const installed = {
+ manifest: { ...baseManifest, id: 'xd-feishu', name: 'Feishu' },
+ dir: '/tmp/brain/xd-feishu',
+ instanceKey: 'xd-feishu',
+ namespace: 'xd',
+ namespaceState: 'confirmed' as const,
+ approval: { state: 'approved', revision: 'org-receipt' },
+ };
+ const { install, update } = setupWindow({ ...baseManifest, id: 'xd-feishu', name: 'Feishu' }, [installed]);
+ await installGhostFromFile('/tmp/xd-feishu.cindy', { t: ((key: string) => key) as never });
+ expect(update).not.toHaveBeenCalled();
+ expect(install).toHaveBeenCalled();
+ });
+
+ it('still updates only the instance named by the detail page', async () => {
+ const root = {
+ manifest: baseManifest,
+ dir: '/tmp/brain/_ns/_root/node-ghost',
+ instanceKey: '_root__node-ghost',
+ namespace: null,
+ namespaceState: 'confirmed' as const,
+ approval: { state: 'approved', revision: 'root-receipt' },
+ };
+ const org = {
+ manifest: baseManifest,
+ dir: '/tmp/brain/_ns/xd/node-ghost',
+ instanceKey: '_ns__xd__node-ghost',
+ namespace: 'xd',
+ namespaceState: 'confirmed' as const,
+ approval: { state: 'approved', revision: 'org-receipt' },
+ };
+ const { update } = setupWindow(baseManifest, [root, org]);
+ await pickAndUpdateGhost('_ns__xd__node-ghost', { t: ((key: string) => key) as never });
+ expect(update).toHaveBeenCalledWith('/tmp/node.cindy', expect.objectContaining({
+ expectedInstalledInstanceId: '_ns__xd__node-ghost',
+ expectedInstalledApproval: 'approved:org-receipt',
+ }));
+ });
it('本地包不由客户端按 minCindyVersion 二次拦截', async () => {
const incompatibleManifest = { ...baseManifest, minCindyVersion: '2.0.0' };
const { install } = setupWindow(incompatibleManifest);
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/useMinimizedGhostPanels.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/useMinimizedGhostPanels.test.ts
index ac6a51ee52..5c449443b0 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/useMinimizedGhostPanels.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/useMinimizedGhostPanels.test.ts
@@ -53,4 +53,19 @@ describe('selectMinimizedGhostPanels', () => {
).map((item) => item.manifest.id),
).toEqual(['ready']);
});
+
+ it('企业实例按 storage part 认最小化,不和 root 同名抢条目', () => {
+ const rootGhost = ghost('helper');
+ const orgGhost = { ...ghost('helper'), namespace: 'acme', dir: '/fake/_ns/acme/helper' };
+ expect(
+ selectMinimizedGhostPanels(
+ [rootGhost, orgGhost],
+ {
+ helper: { minimized: false },
+ '_ns__acme__helper': { minimized: true },
+ },
+ {},
+ ).map((item) => [item.namespace ?? null, item.manifest.id]),
+ ).toEqual([['acme', 'helper']]);
+ });
});
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostCardStore.ts b/apps/desktop/src/renderer/cindy-brain/ghostCardStore.ts
index 4a98f5def9..fa7724f9be 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostCardStore.ts
+++ b/apps/desktop/src/renderer/cindy-brain/ghostCardStore.ts
@@ -39,6 +39,7 @@ export type GhostCardEntry =
export interface GhostLiveCard {
callId: string;
ghostId: string;
+ logicalGhostId?: string;
/** agent 侧 tool_use id(claude 路径推送里带;codex 为 null → 启发式锚定)。 */
toolUseId: string | null;
receivedAt: number;
@@ -79,6 +80,7 @@ function sweepLive(now: number): void {
export function ingestCardPush(payload: {
callId: string;
ghostId: string;
+ logicalGhostId?: string;
toolUseId: string | null;
html: string;
animatedHtml?: string | null;
@@ -119,7 +121,13 @@ export function ingestCardPush(payload: {
} else {
liveCards = [
...liveCards,
- { callId: payload.callId, ghostId: payload.ghostId, toolUseId: payload.toolUseId, receivedAt: now },
+ {
+ callId: payload.callId,
+ ghostId: payload.ghostId,
+ ...(payload.logicalGhostId !== undefined ? { logicalGhostId: payload.logicalGhostId } : {}),
+ toolUseId: payload.toolUseId,
+ receivedAt: now,
+ },
];
}
bump();
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts b/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts
index e68c60c259..218ea2ed2c 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts
+++ b/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useAuth } from '@/contexts/AuthContext';
import type { GhostMainViewIcon, GhostManifest, InstalledGhost } from '../../shared/ghost';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity';
import { useInstalledGhosts } from './useInstalledGhosts';
import {
readMainViewSidebarVisible,
@@ -12,6 +13,8 @@ import {
export interface GhostMainViewItem {
ghostId: string;
+ /** Physical instance id used in /apps/:id. Root stays ghostId; new org installs use storage part. */
+ instanceId: string;
title: string;
icon: GhostMainViewIcon;
manifest: GhostManifest;
@@ -35,7 +38,7 @@ export function projectGhostMainViews(
isSidebarVisible,
}: {
locale: string | undefined;
- isSidebarVisible: (ghostId: string) => boolean;
+ isSidebarVisible: (instanceId: string) => boolean;
},
): GhostMainViewProjection {
const declared = ghosts
@@ -44,6 +47,7 @@ export function projectGhostMainViews(
const { manifest } = installedGhost;
return {
ghostId: manifest.id,
+ instanceId: installedGhostStoragePart(installedGhost),
title: manifest.mainView?.title ?? manifest.name,
icon: manifest.mainView?.icon ?? 'puzzle',
manifest,
@@ -53,12 +57,12 @@ export function projectGhostMainViews(
.sort(
(left, right) =>
left.title.localeCompare(right.title, locale, { sensitivity: 'base' }) ||
- left.ghostId.localeCompare(right.ghostId),
+ left.instanceId.localeCompare(right.instanceId),
);
const routeCapable = declared.filter(
({ installedGhost }) => installedGhost.enabled && installedGhost.approval.state === 'approved',
);
- const sidebarVisible = routeCapable.filter(({ ghostId }) => isSidebarVisible(ghostId));
+ const sidebarVisible = routeCapable.filter(({ instanceId }) => isSidebarVisible(instanceId));
return { declared, routeCapable, sidebarVisible };
}
@@ -74,7 +78,7 @@ export function useGhostMainViews(): GhostMainViewProjection {
() =>
projectGhostMainViews(ghosts, {
locale,
- isSidebarVisible: (ghostId) => readMainViewSidebarVisible(dataOwnerId, ghostId),
+ isSidebarVisible: (instanceId) => readMainViewSidebarVisible(dataOwnerId, instanceId),
}),
[dataOwnerId, ghosts, locale, visibilityRevision],
);
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.ts b/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.ts
index 6b7ad5ccb4..c22c1627e1 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.ts
+++ b/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.ts
@@ -20,6 +20,7 @@
*/
import type { TFunction } from 'i18next';
+import { GHOST_MEDIA_HANDOVER_MIME, type GhostMediaHandover } from '../../shared/ghost';
import { getMimeType, type AttachedFile } from '@/lib/fileTypes';
import { getDraft, saveDraft } from '@/lib/composerDraftStore';
@@ -48,18 +49,41 @@ export function getGhostMediaUriFromDataTransfer(dt: DataTransfer): string | nul
return null;
}
+export function getGhostMediaHandoverFromDataTransfer(dt: DataTransfer): GhostMediaHandover | null {
+ const uri = getGhostMediaUriFromDataTransfer(dt);
+ const raw = dt.getData(GHOST_MEDIA_HANDOVER_MIME);
+ if (!raw && !Array.from(dt.types).includes(GHOST_MEDIA_HANDOVER_MIME)) return uri ? { uri, sourceToken: '' } : null;
+ try {
+ const payload = raw.length <= 4096 ? JSON.parse(raw) as unknown : null;
+ if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
+ const source = payload as Record<string, unknown>;
+ if (typeof source.uri === 'string' && GHOST_MEDIA_URI_RE.test(source.uri)
+ && typeof source.sourceToken === 'string' && source.sourceToken.length > 0
+ && source.sourceToken.length <= 128) {
+ return { uri: source.uri, sourceToken: source.sourceToken };
+ }
+ }
+ } catch {
+ return { uri: uri ?? '', sourceToken: '' };
+ }
+ return { uri: uri ?? '', sourceToken: '' };
+}
+
/**
* 把意识面板拖来的媒体落为会话附件(托盘可见,发送仍由用户决定)。
* 失败 toast 即止——drop 已被本链路消费,不回落文件链路。
*/
export async function attachGhostMediaToSession(
- uri: string,
+ source: string | GhostMediaHandover,
sessionId: string,
t: TFunction,
): Promise<void> {
try {
// main 过闸:归属/形状/mime 任一不过统一 NOT_FOUND。
- const resolved = await window.electronAPI.ghosts.resolvePanelMedia(uri);
+ const { uri, sourceToken } = typeof source === 'string' ? { uri: source } : source;
+ const resolved = sourceToken === undefined
+ ? await window.electronAPI.ghosts.resolvePanelMedia(uri)
+ : await window.electronAPI.ghosts.resolvePanelMedia(uri, 'attach', undefined, sourceToken);
if (resolved.kind === 'video') {
// 视频:不复制字节,直接以指纹仓磁盘路径落 file 类别附件(与从系统
// 拖 .mp4 进聊天完全同款——发送时路径透传给 agent)。托盘移除 file
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
index de7a9704ec..625b8de0cd 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
@@ -12,7 +12,8 @@ import {
} from '@/components/ui/dropdown-menu';
import { toast } from '@/lib/toast';
-import { GHOST_SCHEME, ghostPartition, type GhostManifest } from '../../shared/ghost';
+import { GHOST_SCHEME, ghostInstallApprovalToken, type InstalledGhost } from '../../shared/ghost';
+import { installedGhostStoragePart, installedGhostWebviewPartitionClaim } from '../../shared/pluginIdentity';
import { createGhostThemeInjector, observeHostTheme } from './ghostPanelTheme';
import {
clearGhostUnread,
@@ -35,18 +36,20 @@ import {
* 「关闭意识」(转沉睡,面板收起,可到设置里再唤醒)。
*/
export function GhostPanelError({
- manifest,
+ ghost,
state,
onReload,
}: {
- manifest: GhostManifest;
+ ghost: Pick<InstalledGhost, 'manifest' | 'dir' | 'namespace'> & Partial<Pick<InstalledGhost, 'approval'>>;
state: string;
/** 重载动作;缺省走 ghosts:reload(离屏沙箱路径),面板 webview 路径传本地重挂载。 */
onReload?: () => void;
}): ReactNode {
const { t } = useTranslation();
+ const { manifest } = ghost;
+ const instanceId = installedGhostStoragePart(ghost);
const reload =
- onReload ?? (() => void window.electronAPI.ghosts.reload(manifest.id).catch(() => {}));
+ onReload ?? (() => void window.electronAPI.ghosts.reload(instanceId).catch(() => {}));
return (
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-4">
<CircleAlert size={22} className="text-[var(--error-fg)]" />
@@ -71,7 +74,7 @@ export function GhostPanelError({
compact
type="button"
onClick={() =>
- void window.electronAPI.ghosts.setEnabled(manifest.id, false).catch(() => {})
+ void window.electronAPI.ghosts.setEnabled(instanceId, false, ghostInstallApprovalToken(ghost.approval)).catch(() => {})
}
>
{t('settings.ghosts.panelError.close')}
@@ -188,15 +191,19 @@ export function pickGhostPanelMediaUri(
* webview 崩溃 = 本地错误接管态(重载 = 原地重挂载,不经主机)。
*/
export function GhostWebviewBody({
- manifest,
+ ghost,
html,
onHostNode,
}: {
- manifest: GhostManifest;
+ ghost: Pick<InstalledGhost, 'manifest' | 'dir' | 'namespace'> & Partial<Pick<InstalledGhost, 'approval'>>;
html: string | undefined;
onHostNode?: (node: HTMLDivElement | null) => void;
}): ReactNode {
+ const { manifest } = ghost;
+ const instanceId = installedGhostStoragePart(ghost);
+ const approvalToken = ghostInstallApprovalToken(ghost.approval);
const [crashed, setCrashed] = useState(false);
+ const partitionClaim = installedGhostWebviewPartitionClaim(ghost);
const [generation, setGeneration] = useState(0);
const [mediaMenu, setMediaMenu] = useState<GhostPanelMediaMenuState | null>(null);
const hostRef = useRef<HTMLDivElement | null>(null);
@@ -213,7 +220,7 @@ export function GhostWebviewBody({
const host = hostRef.current;
if (!host) return;
const webview = document.createElement('webview') as WebviewTag;
- webview.setAttribute('partition', ghostPartition(manifest.id));
+ webview.setAttribute('partition', partitionClaim);
webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${html}`);
webview.setAttribute('style', 'display:flex;flex:1 1 auto;width:100%;height:100%;');
let disposed = false;
@@ -250,7 +257,7 @@ export function GhostWebviewBody({
// (OOPIF 命中测试按根帧算;Windows 实测 2077 > 面板宽,叠加 rect 会把
// 菜单顶出屏外),直接用,不要再加 webview 偏移。
const pos = { x: e.params.x, y: e.params.y };
- void window.electronAPI.ghosts.resolvePanelMedia(uri, 'menu').then(
+ void window.electronAPI.ghosts.resolvePanelMedia(uri, 'menu', instanceId).then(
({ url, kind }) => {
if (disposed) return;
// 焦点还在 guest 里,不挪回宿主的话 Esc/方向键进不了菜单
@@ -286,12 +293,12 @@ export function GhostWebviewBody({
};
// version 入依赖:原位更新换版后 webview 重挂载,面板立刻跑新代码
// (供片协议直读安装目录,不重挂会一直渲染旧版缓存的页面)。
- }, [crashed, generation, manifest.id, manifest.version, manifest.resolvedLocale, html]);
+ }, [crashed, generation, instanceId, approvalToken, partitionClaim, manifest.id, manifest.version, manifest.resolvedLocale, html]);
if (crashed) {
return (
<GhostPanelError
- manifest={manifest}
+ ghost={ghost}
state="crashed"
onReload={() => {
setGeneration((g) => g + 1);
@@ -316,7 +323,12 @@ export function GhostWebviewBody({
* 芯片型意识面板 wrapper。未读清零刻意留在 panel 生命周期,main-view
* 即使展示同一个插件也不能误清 panel 的 badge。
*/
-export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): ReactNode {
+export function GhostChipPanelBody({
+ ghost,
+}: {
+ ghost: Pick<InstalledGhost, 'manifest' | 'dir' | 'namespace'> & Partial<Pick<InstalledGhost, 'approval'>>;
+}): ReactNode {
+ const { manifest } = ghost;
/**
* 面板体挂载 = 未读已读(badge 槽的 explicit 清零)。
*
@@ -335,15 +347,20 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
* 用户根本没看到内容(codex review)。
* 两层都满足的那一刻 effect 重跑并清零,语义正是「他看的时候才算看过」。
*/
- const unread = useGhostUnread(manifest.id);
+ const unreadId = installedGhostStoragePart(ghost);
+ const unread = useGhostUnread(unreadId);
const foreground = useHostWindowForeground();
const { ref: observeHost, visible } = useElementVisible();
useEffect(() => {
if (!unread || !foreground || !visible) return;
- clearGhostUnread(manifest.id);
- }, [manifest.id, unread, foreground, visible]);
+ clearGhostUnread(unreadId);
+ }, [unreadId, unread, foreground, visible]);
return (
- <GhostWebviewBody manifest={manifest} html={manifest.panel?.html} onHostNode={observeHost} />
+ <GhostWebviewBody
+ ghost={ghost}
+ html={manifest.panel?.html}
+ onHostNode={observeHost}
+ />
);
}
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
index 9bf3c853b5..c38abe2690 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
@@ -2,7 +2,12 @@ import { useEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
-import { ghostPanelKind, type GhostManifest, type InstalledGhost } from '../../shared/ghost';
+import { ghostInstallApprovalToken, ghostPanelKind, type InstalledGhost } from '../../shared/ghost';
+import {
+ installedGhostLogicalIdentity,
+ installedGhostStoragePart,
+ pluginStoragePart,
+} from '../../shared/pluginIdentity';
import { minimizeGhostPanel, reconcileGhostPanelBubbles } from '../lib/ghostPanelBubbleState';
import { toast } from '../lib/toast';
import { usePanelMaximize } from '../layout/panelMaximize';
@@ -19,6 +24,7 @@ import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';
import { ghostInstallErrorKey } from './installErrorKey';
import { pruneGhostSettingsHeights } from './ghostSettingsHeight';
import { useGhostRuntimeState } from './runtimeStates';
+import { readInstalledGhostsSnapshot, useInstalledGhosts } from './useInstalledGhosts';
import { getDataOwnerGeneration } from '../contexts/dataOwnerGeneration';
/**
@@ -55,8 +61,12 @@ const PANEL_ENTER_ARMED_AT = Date.now() + 1500;
const PANEL_EXIT_MS = 180;
/** 意识面板宿主:标准头(PanelChrome)+ 沙箱自绘面板体(崩溃时错误接管)。 */
-function GhostPanel({ manifest }: PanelComponentProps & { manifest: GhostManifest }): ReactNode {
- const kind = ghostPanelKind(manifest.id);
+function GhostPanel({
+ ghost,
+}: PanelComponentProps & { ghost: InstalledGhost }): ReactNode {
+ const { manifest } = ghost;
+ const instanceId = installedGhostStoragePart(ghost);
+ const kind = ghostPanelKind(instanceId);
const fillContainer = usePaneFill();
const atWindowTop = usePaneAtWindowTop();
// 宽度由引擎下发(fraction × 可用宽,缝把手可拖);兜底用清单 minWidth。
@@ -74,7 +84,7 @@ function GhostPanel({ manifest }: PanelComponentProps & { manifest: GhostManifes
if (!maximizeEnabled && isMaximized) maximize?.toggle(kind);
}, [maximizeEnabled, isMaximized, maximize, kind]);
// 沙箱崩了 → 面板原地进入错误接管态。
- const runtimeState = useGhostRuntimeState(manifest.id);
+ const runtimeState = useGhostRuntimeState(instanceId);
const broken = runtimeState === 'crashed' || runtimeState === 'fused';
// 挂载即定(useState 初始化跑一次):启动首屏后出现的面板播宽度展开。
const [enter] = useState(() => Date.now() >= PANEL_ENTER_ARMED_AT);
@@ -88,11 +98,11 @@ function GhostPanel({ manifest }: PanelComponentProps & { manifest: GhostManifes
if (closing) return;
const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;
if (reduced || isMaximized) {
- minimizeGhostPanel(manifest.id);
+ minimizeGhostPanel(instanceId);
return;
}
setClosing(true);
- closeTimerRef.current = window.setTimeout(() => minimizeGhostPanel(manifest.id), PANEL_EXIT_MS);
+ closeTimerRef.current = window.setTimeout(() => minimizeGhostPanel(instanceId), PANEL_EXIT_MS);
};
// 标准头「关闭」= 二次确认后停用整个插件(setEnabled false):面板、工具、
// 沙箱一并休眠,与插件页全局开关同一条链路(ghosts:changed 广播回来时
@@ -100,17 +110,36 @@ function GhostPanel({ manifest }: PanelComponentProps & { manifest: GhostManifes
// 身份卡 systemButtons 控制——它是宿主给用户的退路,不是作者可关的能力。
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
+ const closeAbortRef = useRef<AbortController | null>(null);
+ const approvalToken = ghostInstallApprovalToken(ghost.approval);
+ useEffect(
+ () => () => closeAbortRef.current?.abort(),
+ [instanceId, ghost.dir, ghost.namespace, approvalToken],
+ );
const beginClose = async (): Promise<void> => {
- const approved = await confirm({
- title: t('ghostPanel.disableConfirm.title', { name: manifest.name }),
- description: t('ghostPanel.disableConfirm.body'),
- confirmText: t('ghostPanel.disableConfirm.confirm'),
- });
- if (!approved) return;
+ if (closeAbortRef.current) return;
+ const abort = new AbortController();
+ closeAbortRef.current = abort;
try {
- await window.electronAPI?.ghosts?.setEnabled(manifest.id, false);
+ const approved = await confirm({
+ title: t('ghostPanel.disableConfirm.title', { name: manifest.name }),
+ description: t('ghostPanel.disableConfirm.body'),
+ confirmText: t('ghostPanel.disableConfirm.confirm'),
+ }, abort.signal);
+ if (!approved || abort.signal.aborted) return;
+ const current = readInstalledGhostsSnapshot().find(
+ (candidate) => installedGhostStoragePart(candidate) === instanceId,
+ );
+ if (
+ !current?.enabled || !current.manifest.panel || current.manifest.panel.position === 'tab' ||
+ current.dir !== ghost.dir || current.namespace !== ghost.namespace ||
+ ghostInstallApprovalToken(current.approval) !== approvalToken
+ ) return;
+ await window.electronAPI?.ghosts?.setEnabled(instanceId, false, approvalToken);
} catch (error) {
toast.error(t(ghostInstallErrorKey(extractIpcError(error)?.code)));
+ } finally {
+ if (closeAbortRef.current === abort) closeAbortRef.current = null;
}
};
return (
@@ -145,23 +174,22 @@ function GhostPanel({ manifest }: PanelComponentProps & { manifest: GhostManifes
onMinimize={minimizeEnabled ? beginMinimize : undefined}
onDetach={
detachEnabled
- ? () => void window.electronAPI?.ghostPanelWindow?.setDetached(manifest.id, true)
+ ? () => void window.electronAPI?.ghostPanelWindow?.setDetached(instanceId, true)
: undefined
}
onClose={() => void beginClose()}
/>
{broken ? (
- <GhostPanelError manifest={manifest} state={runtimeState} />
+ <GhostPanelError ghost={ghost} state={runtimeState} />
) : (
- <GhostChipPanelBody manifest={manifest} />
+ <GhostChipPanelBody ghost={ghost} />
)}
</section>
</div>
);
}
-/** 已注册意识面板:kind → 清单指纹(内容没变就不重注册,避免组件身份变化触发无谓重挂载)。 */
-const registeredFingerprints = new Map<string, string>();
+const registeredKinds = new Set<string>();
/**
* 把注册表与"当前已装清单"对齐:新装的注册、卸下的注销、没变的不动。
@@ -176,29 +204,36 @@ export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {
// 注意用全量清单(含沉睡)——沉睡只是不注册面板,高度仍可复用。
pruneGhostSettingsHeights(
getDataOwnerGeneration().dataOwnerId,
- ghosts.map((g) => g.manifest.id),
+ ghosts.map((g) => pluginStoragePart(installedGhostLogicalIdentity(g))),
);
// 气泡状态对齐(与高度 prune 不同:停用/失格的要强制还原,不只清卸载)——
// 气泡是"面板不可见 + 唯一恢复入口",失格后必须回停靠,不留死角。
reconcileGhostPanelBubbles(ghosts);
const seen = new Set<string>();
- for (const { manifest, enabled } of ghosts) {
+ for (const ghost of ghosts) {
+ const { manifest, enabled } = ghost;
if (!manifest.panel) continue; // 无面板的意识(未来纯工具卡)不进注册表
if (manifest.panel.position === 'tab') continue; // 页签形态由插件页承载(面板收束)
if (enabled === false) continue; // 停用 = 休眠,不注册(注销走下方 seen 差集)
- const kind = ghostPanelKind(manifest.id);
+ const instanceId = installedGhostStoragePart(ghost);
+ const kind = ghostPanelKind(instanceId);
seen.add(kind);
- const fingerprint = JSON.stringify(manifest);
- if (registeredFingerprints.get(kind) === fingerprint) continue;
- registeredFingerprints.set(kind, fingerprint);
- const Component = (props: PanelComponentProps): ReactNode => (
- <GhostPanel {...props} manifest={manifest} />
- );
+ if (registeredKinds.has(kind)) continue;
+ registeredKinds.add(kind);
+ const Component = (props: PanelComponentProps): ReactNode => {
+ const installed = useInstalledGhosts().find(
+ (candidate) => installedGhostStoragePart(candidate) === instanceId,
+ );
+ if (!installed?.enabled || !installed.manifest.panel || installed.manifest.panel.position === 'tab') {
+ return null;
+ }
+ return <GhostPanel {...props} ghost={installed} />;
+ };
registerPanelKind({ kind, Component, collapseMemory: 'global' });
}
- for (const kind of [...registeredFingerprints.keys()]) {
+ for (const kind of registeredKinds) {
if (seen.has(kind)) continue;
- registeredFingerprints.delete(kind);
+ registeredKinds.delete(kind);
unregisterPanelKind(kind);
}
}
@@ -216,7 +251,7 @@ export function ensureGhostPanelsRegistered(): void {
// 视同"没装任何意识",不是错误。
const api = window.electronAPI?.ghosts;
if (!api) return;
- syncGhostPanelRegistrations(api.listSync().ghosts);
+ syncGhostPanelRegistrations(readInstalledGhostsSnapshot());
}
/**
@@ -241,5 +276,5 @@ export function useGhostPanelsSync(): number {
/** 仅测试用:允许用例重复走首帧注册路径。 */
export function __resetGhostPanelsForTest(): void {
initialSynced = false;
- registeredFingerprints.clear();
+ registeredKinds.clear();
}
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostWorkdirFilter.ts b/apps/desktop/src/renderer/cindy-brain/ghostWorkdirFilter.ts
index b6dda41e34..0b24ea781d 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostWorkdirFilter.ts
+++ b/apps/desktop/src/renderer/cindy-brain/ghostWorkdirFilter.ts
@@ -14,6 +14,7 @@
*/
import type { InstalledGhost } from '../../shared/ghost';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity';
/** 该 workdir 下被禁用的 ghostId 集合;无 workdir / 查询异常 = 空集。 */
export function getWorkdirDisabledGhostIds(workdir: string | null | undefined): Set<string> {
@@ -36,6 +37,6 @@ export function filterGhostsForWorkdir(
): InstalledGhost[] {
const disabled = getWorkdirDisabledGhostIds(workdir);
if (disabled.size === 0) return ghosts;
- const filtered = ghosts.filter((g) => !disabled.has(g.manifest.id));
+ const filtered = ghosts.filter((g) => !disabled.has(installedGhostStoragePart(g)));
return filtered.length === ghosts.length ? ghosts : filtered;
}
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index 607bb152ac..8823af9855 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -7,6 +7,11 @@ import {
type GhostManifest,
type InstalledGhost,
} from '../../shared/ghost';
+import {
+ findInstalledGhostByInstanceId,
+ findInstalledRootGhostForFileImport,
+ installedGhostStoragePart,
+} from '../../shared/pluginIdentity';
import { ghostInstallErrorKey } from './installErrorKey';
/**
@@ -32,11 +37,21 @@ async function showInstallError(error: unknown, deps: InstallFlowDeps): Promise<
toast.error(deps.t(ghostInstallErrorKey(code)));
}
-/** 同 id 已装清单查询(sendSync,极小)。 */
+/** 详情页更新按实例键精确查找。 */
function findInstalled(id: string): InstalledGhost | null {
try {
const { ghosts } = window.electronAPI.ghosts.listSync();
- return ghosts.find((g) => g.manifest.id === id) ?? null;
+ return findInstalledGhostByInstanceId(ghosts, id) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/** 拖入或双击只更新 root,不选中同名企业实例。 */
+function findInstalledRootForFile(ghostId: string): InstalledGhost | null {
+ try {
+ const { ghosts } = window.electronAPI.ghosts.listSync();
+ return findInstalledRootGhostForFileImport(ghosts, ghostId);
} catch {
return null;
}
@@ -54,6 +69,7 @@ async function runUpdate(
const { ghost } = await window.electronAPI.ghosts.update(lizFilePath, {
expectedPackageSha256: packageSha256,
expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
+ expectedInstalledInstanceId: installedGhostStoragePart(installed),
});
toast.success(
t('settings.ghosts.toast.updated', {
@@ -86,7 +102,7 @@ export async function installGhostFromFile(
// 1.5) 同 id 已装 → 转更新分支(拖入/双击/装入按钮选到新版包时不再报
// "已经注入",直接原位更新)。
- const installed = findInstalled(manifest.id);
+ const installed = findInstalledRootForFile(manifest.id);
if (installed) {
await runUpdate(lizFilePath, packageSha256, installed, deps);
return;
@@ -102,7 +118,7 @@ export async function installGhostFromFile(
});
toast.success(t('settings.ghosts.toast.installed', { name: ghost.manifest.name }));
if (willOpenPanel) {
- deps.openPluginPanel?.(ghost.manifest.id);
+ deps.openPluginPanel?.(installedGhostStoragePart(ghost));
}
} catch (err) {
await showInstallError(err, deps);
@@ -118,23 +134,40 @@ export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDe
const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);
if (!picked || 'canceled' in picked) return;
+ const installed = findInstalled(expectedId);
let manifest: GhostManifest;
let packageSha256: string;
try {
- const inspected = await window.electronAPI.ghosts.inspect(picked.filePath);
+ const inspected = await window.electronAPI.ghosts.inspect(
+ picked.filePath,
+ installed
+ ? {
+ expectedInstalledInstanceId: installedGhostStoragePart(installed),
+ expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
+ }
+ : undefined,
+ );
manifest = inspected.manifest;
packageSha256 = inspected.packageSha256;
} catch (err) {
await showInstallError(err, deps);
return;
}
- if (manifest.id !== expectedId) {
+ if (installed && manifest.id !== installed.manifest.id) {
+ toast.error(
+ t('settings.ghosts.errors.updateIdMismatch', {
+ id: manifest.id,
+ expected: installed.manifest.id,
+ }),
+ );
+ return;
+ }
+ if (!installed && manifest.id !== expectedId) {
toast.error(
t('settings.ghosts.errors.updateIdMismatch', { id: manifest.id, expected: expectedId }),
);
return;
}
- const installed = findInstalled(expectedId);
if (!installed) {
// 详情页开着的意识刚被别处抽离——极端竞态,按通用错误提示。
toast.error(t('settings.ghosts.errors.generic'));
diff --git a/apps/desktop/src/renderer/cindy-brain/useMinimizedGhostPanels.ts b/apps/desktop/src/renderer/cindy-brain/useMinimizedGhostPanels.ts
index 8ffd57f784..59b4402151 100644
--- a/apps/desktop/src/renderer/cindy-brain/useMinimizedGhostPanels.ts
+++ b/apps/desktop/src/renderer/cindy-brain/useMinimizedGhostPanels.ts
@@ -1,6 +1,7 @@
import { useMemo } from 'react';
import type { InstalledGhost } from '../../shared/ghost';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity';
import type { GhostPanelWindowsState } from '../../shared/ghostPanelWindow';
import {
useGhostPanelBubbleState,
@@ -23,8 +24,8 @@ export function selectMinimizedGhostPanels(
ghost.enabled !== false &&
ghost.manifest.panel !== undefined &&
ghost.manifest.panel.position !== 'tab' &&
- bubbles[ghost.manifest.id]?.minimized === true &&
- windows[ghost.manifest.id]?.detached !== true,
+ bubbles[installedGhostStoragePart(ghost)]?.minimized === true &&
+ windows[installedGhostStoragePart(ghost)]?.detached !== true,
);
}
diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
index 98e102a92e..34a112db8c 100644
--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
@@ -80,7 +80,13 @@ import { extractDisplayParam } from '@/lib/agent-actions/actionPresentation';
import { SUPPORTED_IMAGE_EXTS, extractExt } from '@/lib/fileTypes';
import { toLocalFileUrl, resolveToolFilePath } from '@/lib/localPathResolver';
import { isBrowserOpenablePath } from '../../../shared/browserOpenableExts';
-import { isGhostCallToolName } from '../../../shared/ghost';
+import { isGhostCallToolName, isValidGhostId } from '../../../shared/ghost';
+import {
+ createPluginLogicalIdentity,
+ findInstalledGhostByIdentity,
+ findInstalledGhostByInstanceId,
+} from '../../../shared/pluginIdentity';
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';
import { toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';
import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';
@@ -798,7 +804,14 @@ export function AgentActionRow({
const ghostInfo = useMemo(() => {
if (!isGhostCallToolName(toolName) || !inp) return null;
const gid = typeof inp.ghost_id === 'string' ? inp.ghost_id : '';
- const hit = installedGhosts.find((g) => g.manifest.id === gid);
+ const namespace = inp.namespace;
+ const identity = isValidGhostId(gid) &&
+ (namespace === null || (typeof namespace === 'string' && isValidPluginNamespace(namespace)))
+ ? createPluginLogicalIdentity(namespace, gid)
+ : null;
+ const hit = identity
+ ? findInstalledGhostByIdentity(installedGhosts, identity)
+ : namespace === undefined ? findInstalledGhostByInstanceId(installedGhosts, gid) : undefined;
return {
name: hit?.manifest.name ?? (gid || 'ghost'),
tool: typeof inp.tool === 'string' ? inp.tool : '',
diff --git a/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx b/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx
index 0495b1cfe9..0835b57609 100644
--- a/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx
@@ -47,6 +47,15 @@ import {
type HostCapabilityDirectiveDisplay,
} from '@/cindy-brain/hostCapabilityInvocation';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { isValidGhostId } from '../../../shared/ghost';
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
+import {
+ findInstalledGhostByIdentity,
+ findInstalledGhostByInstanceId,
+ installedGhostLogicalIdentity,
+ parsePluginInstanceId,
+ pluginStoragePart,
+} from '../../../shared/pluginIdentity';
/**
* 「提及 → 兑现」关联(方案 2):Map<userMessageClientId, Set<被召唤 ghostId>>。
@@ -248,6 +257,7 @@ export function GhostSummonCard({
directive,
running,
messageClientId,
+ commandNamespace,
className,
}: {
directive: GhostSummonDisplay;
@@ -255,6 +265,7 @@ export function GhostSummonCard({
running?: boolean;
/** 本条用户消息的 clientId(查"提及 → 兑现"关联;状态文字与软提示升级用)。 */
messageClientId?: string;
+ commandNamespace?: string;
/** 外层附加样式:UserMessage 在气泡内嵌时用它加分隔线与间距。 */
className?: string;
}) {
@@ -263,11 +274,41 @@ export function GhostSummonCard({
// 头像按 ghostId 实时查已装清单:消息文本里只固化 id/名字,头像跟随当前
// 安装状态(意识被卸下后自然回退幽灵图标,不缓存失效数据)。
const installedGhosts = useInstalledGhosts();
+ const ghostByInstanceId = (ghostId: string) => {
+ if (isValidGhostId(ghostId)) return undefined;
+ const physical = findInstalledGhostByInstanceId(installedGhosts, ghostId);
+ if (physical) return physical;
+ const identity = parsePluginInstanceId(ghostId);
+ return identity ? findInstalledGhostByIdentity(installedGhosts, identity) : undefined;
+ };
+ const commandIdentity = directive.kind === 'command' &&
+ typeof commandNamespace === 'string' &&
+ (commandNamespace === '@root' || isValidPluginNamespace(commandNamespace)) &&
+ isValidGhostId(directive.ghostId)
+ ? { namespace: commandNamespace === '@root' ? null : commandNamespace, ghostId: directive.ghostId }
+ : null;
+ const commandInstanceId = commandIdentity ? pluginStoragePart(commandIdentity) : null;
+ const ghostForDirective = (ghostId: string) => commandIdentity && ghostId === commandIdentity.ghostId
+ ? findInstalledGhostByIdentity(installedGhosts, commandIdentity)
+ : ghostByInstanceId(ghostId);
const iconByGhostId = (ghostId: string): string | null =>
- installedGhosts.find((g) => g.manifest.id === ghostId)?.iconDataUrl ?? null;
+ ghostByInstanceId(ghostId)?.iconDataUrl ?? null;
// 「提及 → 兑现」:本条消息触发的那一轮,AI 真召唤了哪些意识。
const fulfillment = useContext(GhostFulfillmentContext);
const fulfilledIds = messageClientId ? fulfillment.get(messageClientId) : undefined;
+ const isFulfilled = (ghostId: string) => {
+ if (!fulfilledIds) return false;
+ if (commandIdentity && commandInstanceId) {
+ if (fulfilledIds.has(commandInstanceId)) return true;
+ const matches = installedGhosts.filter((ghost) => ghost.manifest.id === commandIdentity.ghostId);
+ const match = matches.length === 1 ? matches[0] : undefined;
+ return Boolean(match && fulfilledIds.has(commandIdentity.ghostId) &&
+ installedGhostLogicalIdentity(match).namespace === commandIdentity.namespace);
+ }
+ if (fulfilledIds.has(ghostId)) return true;
+ const ghost = ghostForDirective(ghostId);
+ return ghost ? fulfilledIds.has(pluginStoragePart(installedGhostLogicalIdentity(ghost))) : false;
+ };
// 软提示的兑现子集(方案 2):AI 真调了才算,只提及没调的不升级(不撒谎)。
const fulfilled =
directive.kind === 'mention' && fulfilledIds
@@ -341,9 +382,9 @@ export function GhostSummonCard({
: directive.kind === 'mention'
? fulfilled
: directive.ghostIds.map((id) => {
- const g = installedGhosts.find((x) => x.manifest.id === id);
+ const g = ghostByInstanceId(id);
return {
- name: g?.manifest.name ?? id,
+ name: g?.manifest.name ?? parsePluginInstanceId(id)?.ghostId ?? id,
ghostId: id,
...(g?.manifest.command ? { command: g.manifest.command } : {}),
};
@@ -352,7 +393,7 @@ export function GhostSummonCard({
if (cardGhosts.length === 0) return null;
// 命中已装意识时取实时安装态(头像/版本号);已卸下则都不显示,
// 与消息文本里固化的 id/名字解耦(不缓存失效数据)。
- const installedGhost = installedGhosts.find((g) => g.manifest.id === cardGhosts[0].ghostId);
+ const installedGhost = ghostForDirective(cardGhosts[0].ghostId);
// 版本号统一 v 前缀展示(身份卡 version 是自由字符串,作者已带 v 时不重复);
// 多意识并列时不展示(版本归属不明)。
const versionLabel =
@@ -376,7 +417,7 @@ export function GhostSummonCard({
// 查兑现关联,AI 最终没调的只说「已完成」,不替 AI 撒谎。
const anyFulfilled = isHostCapability
? false
- : !isCommand || cardGhosts.some((g) => Boolean(fulfilledIds?.has(g.ghostId)));
+ : !isCommand || cardGhosts.some((g) => isFulfilled(g.ghostId));
// Host capability selection is not a ghost_call fulfillment event. Until
// Host MCP fulfillment is tracked separately, report only the fact we know:
// the user selected this route. Do not show a success tick or "已调用".
diff --git a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
index 32929fde03..876737c585 100644
--- a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
@@ -48,6 +48,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { findInstalledGhostByInstanceId } from '../../../shared/pluginIdentity';
import {
getGhostCardSnapshot,
listSpawnCards,
@@ -779,7 +780,7 @@ export function GhostToolCard({
}): ReactNode {
const { t } = useTranslation();
const installedGhosts = useInstalledGhosts();
- const ghost = installedGhosts.find((g) => g.manifest.id === ghostId);
+ const ghost = findInstalledGhostByInstanceId(installedGhosts, ghostId);
const name = ghost?.manifest.name ?? ghostId;
const icon = ghost?.iconDataUrl ?? null;
// 主机主题变量块(白名单 token → :root):注进 srcDoc 头部,意识可选用
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 8eac63e999..611d8d15d5 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -129,6 +129,9 @@ import {
import { SHARE_MESSAGE_ATTR, SHARE_SESSION_ATTR } from '@/lib/shareConversationImage';
import { ShareMessageCheckbox } from './ShareMessageCheckbox';
import { isShareableMessage, useShareSelectionActive } from './shareSelectionStore';
+import { parsePluginInstanceId, pluginStoragePart } from '../../../shared/pluginIdentity';
+import { isValidGhostId } from '../../../shared/ghost';
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
// perf-baseline: 大 session 切换 first-paint 性能基线,保留用于回归监测。
// 历史:commit ffff3603 (render-window 首引入) 因 687 条 session first-paint
@@ -785,7 +788,9 @@ export function collectGhostCallsByUserTurn(
m.toolInput &&
typeof (m.toolInput as Record<string, unknown>).ghost_id === 'string'
) {
- const gid = (m.toolInput as Record<string, unknown>).ghost_id as string;
+ const input = m.toolInput as Record<string, unknown>;
+ const gid = ghostCardInstanceId(input.ghost_id as string, input.namespace);
+ if (!gid) continue;
const set = out.get(currentUserClientId) ?? new Set<string>();
set.add(gid);
out.set(currentUserClientId, set);
@@ -1466,6 +1471,17 @@ function isRenderTurnBoundary(message: ChatMessage): boolean {
);
}
+function ghostCardInstanceId(ghostId: string, namespace: unknown): string | null {
+ if (!isValidGhostId(ghostId)) {
+ const identity = parsePluginInstanceId(ghostId);
+ return identity && namespace === undefined ? pluginStoragePart(identity) : null;
+ }
+ if (namespace === null || namespace === undefined) return ghostId;
+ return typeof namespace === 'string' && isValidPluginNamespace(namespace)
+ ? pluginStoragePart({ namespace, ghostId })
+ : null;
+}
+
export function buildRenderItems(
allMessages: ChatMessage[],
taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>,
@@ -2057,6 +2073,7 @@ export function buildRenderItems(
if (!ghostCards || !isGhostCallToolName(toolName)) return;
const inp = (msg.toolInput ?? null) as Record<string, unknown> | null;
const ghostIdFromInput = typeof inp?.ghost_id === 'string' ? inp.ghost_id : '';
+ const candidateGhostId = ghostCardInstanceId(ghostIdFromInput, inp?.namespace);
const toolFromInput = typeof inp?.tool === 'string' ? inp.tool : '';
if (result !== undefined) {
const cardId = extractGhostCardId(result);
@@ -2070,7 +2087,7 @@ export function buildRenderItems(
type: 'ghost_card',
key: `ghostcard-${msg.clientId}`,
callId: cardId,
- ghostId: ghostIdFromInput || entry.ghostId,
+ ghostId: entry.ghostId,
tool: toolFromInput,
toolCall: msg,
settled: true,
@@ -2094,13 +2111,15 @@ export function buildRenderItems(
typeof msg.toolUseId === 'string' &&
lc.toolUseId === msg.toolUseId,
) ??
- (ghostIdFromInput
+ (candidateGhostId
? ghostCards.liveCards.find(
(lc) =>
!claimedLiveCallIds.has(lc.callId) &&
!settledCardIds.has(lc.callId) &&
lc.toolUseId === null &&
- lc.ghostId === ghostIdFromInput,
+ ((lc.logicalGhostId ?? lc.ghostId) === candidateGhostId ||
+ (lc.logicalGhostId === undefined && inp?.namespace === undefined &&
+ lc.ghostId === candidateGhostId)),
)
: undefined);
if (!live) return;
@@ -2111,7 +2130,7 @@ export function buildRenderItems(
type: 'ghost_card',
key: `ghostcard-${msg.clientId}`,
callId: live.callId,
- ghostId: ghostIdFromInput || live.ghostId,
+ ghostId: live.ghostId,
tool: toolFromInput,
toolCall: msg,
settled: false,
@@ -2134,9 +2153,18 @@ export function buildRenderItems(
const anchor = extractAnchorCardId(result);
const inp = (msg.toolInput ?? null) as Record<string, unknown> | null;
const ghostIdFromInput = typeof inp?.ghost_id === 'string' ? inp.ghost_id : '';
+ const candidateGhostId = ghostCardInstanceId(ghostIdFromInput, inp?.namespace);
const target = anchor ? ghostCardItemByCallId.get(anchor) : undefined;
- const sameGhostTarget =
- target && ghostIdFromInput && target.ghostId === ghostIdFromInput ? target : undefined;
+ const targetInput = target?.toolCall.toolInput as Record<string, unknown> | undefined;
+ const targetGhostId = typeof targetInput?.ghost_id === 'string'
+ ? ghostCardInstanceId(targetInput.ghost_id, targetInput.namespace)
+ : null;
+ const physicalOwnerMatches = target && (target.ghostId === ghostIdFromInput ||
+ ((inp?.namespace !== undefined || !isValidGhostId(ghostIdFromInput)) &&
+ ghostCardInstanceId(target.ghostId, undefined) === candidateGhostId));
+ const sameGhostTarget = target && candidateGhostId !== null && candidateGhostId === targetGhostId &&
+ inp?.namespace === targetInput?.namespace && physicalOwnerMatches
+ ? target : undefined;
// 音频入卡令牌(audioInCard)= 意识的**待验证声明**:锚到的同意识卡
// 确实 ready 且 html 真含对应 data-ghost-audio 插槽(播放器已由卡内
// 受信桥渲染)才压掉基座音频卡,防同一首歌双播放器;验证不过(远程
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index f708a5549d..cccad55539 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -108,7 +108,7 @@ import { buildSessionMessageDeepLink } from '@/lib/deepLink';
import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import { insertSessionLinkIntoComposer } from '@/lib/composerActionsBus';
import { MENTION_TOKEN_SPLIT, parseMentionToken } from '@/lib/mentionRefFormat';
-import { parseGhostCommandWord, splitGhostDirective } from '@/cindy-brain/ghostCommand';
+import { ghostCommandTokenLength, parseGhostCommandToken, splitGhostDirective } from '@/cindy-brain/ghostCommand';
import { splitHostCapabilityDirective } from '@/cindy-brain/hostCapabilityInvocation';
import {
GhostFulfillmentContext,
@@ -957,10 +957,10 @@ export function UserMessage({
// $指令 开头且确认命中意识时,气泡正文渲剥掉指令 token 的余文($token 的
// 语义由气泡内的召唤标注行承载,正文不重复报幕);普通消息里的 $word 不受
// 影响。2026-07-29 起取消「卡片即消息」合并形态:正文永远回归文字气泡。
- const ghostCmdWord =
- ghostDirective?.kind === 'command' ? parseGhostCommandWord(bubbleBody) : null;
+ const ghostCmd =
+ ghostDirective?.kind === 'command' ? parseGhostCommandToken(bubbleBody) : null;
// 触发符恒为 1 个字符($ 或全角变体),token = 触发符 + 指令词。
- const ghostCmdToken = ghostCmdWord ? bubbleBody.slice(0, 1 + ghostCmdWord.length) : null;
+ const ghostCmdToken = ghostCmd ? bubbleBody.slice(0, 1 + ghostCommandTokenLength(ghostCmd)) : null;
const ghostPromptBody = ghostCmdToken ? bubbleBody.slice(ghostCmdToken.length).trim() : '';
// 软提示兑现(语义调用):本条消息触发的那一轮 AI 真调了被提及的意识时,
// 升级为与硬指令同形态的召唤标注行。判据来自 GhostFulfillmentContext
@@ -1523,6 +1523,7 @@ export function UserMessage({
下方有正文/引用时加分隔线,单独成泡时不加。 */
<GhostSummonCard
directive={ghostChipDisplay}
+ commandNamespace={ghostCmd?.namespace ?? undefined}
running={Boolean(sessionRunning) && Boolean(isLastUserMessage)}
{...(messageClientId ? { messageClientId } : {})}
className={
diff --git a/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
index 1fc5ac2c6e..af4b4ae0fe 100644
--- a/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
@@ -35,18 +35,21 @@ import { getGhostPanelWindowGhostId } from '@/lib/ghostPanelWindow';
import { createLogger } from '@/lib/logger';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
-import type { GhostManifest } from '../../../shared/ghost';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
const log = createLogger('GhostPanelWindowLayout');
/** 面板�?+ 崩溃接管(与停靠形�?GhostPanel 同一分支逻辑,不含标准�?�?*/
-function PanelBody({ manifest }: { manifest: GhostManifest }) {
- const runtimeState = useGhostRuntimeState(manifest.id);
+function PanelBody({ ghost }: { ghost: InstalledGhost }) {
+ const { manifest } = ghost;
+ const instanceId = installedGhostStoragePart(ghost);
+ const runtimeState = useGhostRuntimeState(instanceId);
const broken = runtimeState === 'crashed' || runtimeState === 'fused';
return broken ? (
- <GhostPanelError manifest={manifest} state={runtimeState} />
+ <GhostPanelError ghost={ghost} state={runtimeState} />
) : (
- <GhostChipPanelBody manifest={manifest} />
+ <GhostChipPanelBody ghost={ghost} />
);
}
@@ -57,7 +60,7 @@ export function GhostPanelWindowLayout() {
const isMac = window.electronAPI?.platform === 'darwin';
const ghostId = getGhostPanelWindowGhostId();
const ghosts = useInstalledGhosts();
- const ghost = ghostId ? ghosts.find((g) => g.manifest.id === ghostId) : undefined;
+ const ghost = ghostId ? ghosts.find((g) => installedGhostStoragePart(g) === ghostId) : undefined;
// 停用/卸载的瞬�?main �?reconcile 会收�?这里只兜住收窗前的一两帧�?
const manifest = ghost && ghost.enabled !== false ? ghost.manifest : undefined;
const title = manifest?.panel?.title ?? manifest?.name ?? '';
@@ -80,7 +83,8 @@ export function GhostPanelWindowLayout() {
};
const disableAndClose = async (): Promise<void> => {
- if (!ghostId || !manifest) return;
+ if (!ghostId || !manifest || !ghost) return;
+ const approvalToken = ghostInstallApprovalToken(ghost.approval);
const approved = await confirm({
title: t('ghostPanel.disableConfirm.title', { name: manifest.name }),
description: t('ghostPanel.disableConfirm.body'),
@@ -89,7 +93,7 @@ export function GhostPanelWindowLayout() {
await window.electronAPI.ghostPanelWindow.resolveCloseRequest(approved);
if (!approved) return;
try {
- await window.electronAPI.ghosts.setEnabled(ghostId, false);
+ await window.electronAPI.ghosts.setEnabled(ghostId, false, approvalToken);
} catch (error) {
toast.error(t(ghostInstallErrorKey(extractIpcError(error)?.code)));
}
@@ -127,7 +131,7 @@ export function GhostPanelWindowLayout() {
return window.electronAPI.ghostPanelWindow.onCloseRequested(() => {
void disableAndClose();
});
- }, [ghostId, manifest, confirm, t, window.electronAPI.ghostPanelWindow]);
+ }, [ghostId, ghost, manifest, confirm, t, window.electronAPI.ghostPanelWindow]);
useEffect(() => {
if (!minimizeEnabled) return;
@@ -198,8 +202,8 @@ export function GhostPanelWindowLayout() {
{/* 面板�?manifest 在场即挂 webview;不在�?收窗前瞬�?�?URL)给占位�?*/}
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">
- {manifest ? (
- <PanelBody manifest={manifest} />
+ {ghost && manifest ? (
+ <PanelBody ghost={ghost} />
) : (
<div className="flex flex-1 items-center justify-center">
<span className="text-13 text-[var(--text-tertiary)]">
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
index ea04fd1bfc..23f9db5241 100644
--- a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
+++ b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
@@ -13,6 +13,9 @@ const mocks = vi.hoisted(() => ({
ghostVisibilityListener: null as ((payload: { visible: boolean }) => void) | null,
ghostMinimizeListener: null as (() => void) | null,
ghostMinimizeEnabled: true,
+ confirm: vi.fn(() => Promise.resolve(false)),
+ ghostCloseListener: null as (() => void) | null,
+ ghostApprovalRevision: '00000000-0000-4000-8000-000000000001',
sidebarShellVisible: undefined as boolean | undefined,
sidebarShellSessionId: undefined as string | null | undefined,
sidebarLightboxSessionId: undefined as string | undefined,
@@ -96,6 +99,7 @@ vi.mock('@/cindy-brain/useInstalledGhosts', () => ({
useInstalledGhosts: () => [
{
enabled: true,
+ approval: { state: 'approved', revision: mocks.ghostApprovalRevision },
manifest: {
id: 'test-ghost',
name: 'Test Ghost',
@@ -110,7 +114,7 @@ vi.mock('@/cindy-brain/useInstalledGhosts', () => ({
],
}));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
- useConfirmDialog: () => ({ confirm: vi.fn(() => Promise.resolve(false)) }),
+ useConfirmDialog: () => ({ confirm: mocks.confirm }),
}));
vi.mock('@/hooks/useAppShortcut', () => ({ useAppShortcut: vi.fn() }));
vi.mock('@/hooks/useCloseWindowShortcut', () => ({ useCloseShortcutShellOwner: vi.fn() }));
@@ -154,6 +158,9 @@ describe('reusable auxiliary window chrome', () => {
mocks.ghostVisibilityListener = null;
mocks.ghostMinimizeListener = null;
mocks.ghostMinimizeEnabled = true;
+ mocks.confirm.mockReset().mockResolvedValue(false);
+ mocks.ghostCloseListener = null;
+ mocks.ghostApprovalRevision = '00000000-0000-4000-8000-000000000001';
mocks.sidebarShellVisible = undefined;
mocks.sidebarShellSessionId = undefined;
mocks.sidebarLightboxSessionId = undefined;
@@ -195,7 +202,10 @@ describe('reusable auxiliary window chrome', () => {
mocks.ghostVisibilityListener = listener;
return vi.fn();
}),
- onCloseRequested: vi.fn(() => vi.fn()),
+ onCloseRequested: vi.fn((listener) => {
+ mocks.ghostCloseListener = listener;
+ return vi.fn();
+ }),
onMinimizeRequested: vi.fn((listener) => {
mocks.ghostMinimizeListener = listener;
return vi.fn();
@@ -210,6 +220,19 @@ describe('reusable auxiliary window chrome', () => {
afterEach(() => cleanup());
+ it('keeps the detached close bound to the approval shown before confirmation', async () => {
+ let confirmClose!: (confirmed: boolean) => void;
+ mocks.confirm.mockReturnValue(new Promise<boolean>((resolve) => { confirmClose = resolve; }));
+ const view = render(<GhostPanelWindowLayout />);
+ act(() => mocks.ghostCloseListener?.());
+ mocks.ghostApprovalRevision = '00000000-0000-4000-8000-000000000002';
+ view.rerender(<GhostPanelWindowLayout />);
+ await act(async () => confirmClose(true));
+ expect(window.electronAPI.ghosts.setEnabled).toHaveBeenCalledExactlyOnceWith(
+ 'test-ghost', false, 'approved:00000000-0000-4000-8000-000000000001',
+ );
+ });
+
it('remounts right-sidebar controls when the cached window is hidden', async () => {
render(<SidebarWindowLayout />);
const controlsBeforeHide = screen.getByTestId('window-controls');
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index c287af015a..db213523bf 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -189,15 +189,17 @@ import { SlashCommandPalette } from './SlashCommandPalette';
import {
expandGhostCommand,
findGhostByCommand,
- parseGhostCommandWord,
+ formatGhostCommandToken,
+ parseGhostCommandToken,
} from '@/cindy-brain/ghostCommand';
+import { findInstalledGhostByInstanceId, installedGhostStoragePart } from '../../../shared/pluginIdentity';
import { filterGhostsForWorkdir, getWorkdirDisabledGhostIds } from '@/cindy-brain/ghostWorkdirFilter';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
import { useRemoteComposerGhosts } from '@/cindy-brain/useRemoteComposerGhosts';
import { projectGhostComposerEntries, type GhostCommandSource } from '../../../shared/ghostComposer';
import {
attachGhostMediaToSession,
- getGhostMediaUriFromDataTransfer,
+ getGhostMediaHandoverFromDataTransfer,
} from '@/cindy-brain/ghostMediaHandover';
import { AtMentionPanel, type AtPanelState } from './AtMentionPanel';
import { MentionChipNode, type MentionChipAttrs } from './MentionChipNode';
@@ -3104,7 +3106,11 @@ export function ChatInput({
const ghostsForCommand = pluginsForMenu;
const pluginAvailableIds = useMemo(
() =>
- new Set(ghostsForCommand.filter((ghost) => ghost.enabled).map((ghost) => ghost.manifest.id)),
+ new Set(
+ ghostsForCommand
+ .filter((ghost) => ghost.enabled)
+ .map((ghost) => installedGhostStoragePart(ghost)),
+ ),
[ghostsForCommand],
);
// 统一建议面板的插件条目(旧 `+` 菜单口径的并集):可用项可选,无指令或
@@ -3113,7 +3119,8 @@ export function ChatInput({
return pluginsForMenu.map((ghost) => {
const hasCommand = !!ghost.manifest.command;
const hasComposerEntry = hasCommand;
- const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasComposerEntry;
+ const instanceId = installedGhostStoragePart(ghost);
+ const selectable = pluginAvailableIds.has(instanceId) && hasComposerEntry;
const entryKey = ghost.manifest.command ?? '';
return {
item: {
@@ -3121,19 +3128,19 @@ export function ChatInput({
name: ghost.manifest.name,
relPath:
ghost.manifest.command ??
- `cindy://plugin/${ghost.manifest.id}`,
- pluginId: ghost.manifest.id,
+ `cindy://plugin/${instanceId}`,
+ pluginId: instanceId,
...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
sourceLabel: entryKey,
_nameLower: `${ghost.manifest.name} ${entryKey}`.toLowerCase(),
- _relPathLower: `${entryKey} ${ghost.manifest.id}`.toLowerCase(),
+ _relPathLower: `${entryKey} ${instanceId}`.toLowerCase(),
},
...(selectable
? {}
: {
disabled: true,
disabledReason: t(
- !pluginAvailableIds.has(ghost.manifest.id)
+ !pluginAvailableIds.has(instanceId)
? 'extraDirs.pluginDisabled'
: ghost.hasSkill
? 'extraDirs.pluginAgentInvoked'
@@ -4122,9 +4129,7 @@ export function ChatInput({
if (!draft) return;
if (draft.pendingGhostId) {
- const ghost = ghostsForCommand.find(
- (candidate) => candidate.manifest.id === draft.pendingGhostId,
- );
+ const ghost = findInstalledGhostByInstanceId(ghostsForCommand, draft.pendingGhostId);
if (!ghost) return;
saveComposerDraft(
storageKey,
@@ -4135,7 +4140,7 @@ export function ChatInput({
},
{ silent: true },
);
- placeGhostAtComposerStart(editor, ghost, installedGhosts);
+ placeGhostAtComposerStart(editor, ghost, ghostsForCommand);
return;
}
@@ -4149,7 +4154,7 @@ export function ChatInput({
{ silent: true },
);
focusComposerEndNextFrame(editor);
- }, [editor, ghostsForCommand, installedGhosts, storageKey, deviceLinkDeviceId, remoteHostId]);
+ }, [editor, ghostsForCommand, storageKey, deviceLinkDeviceId, remoteHostId]);
// browser-comment-chip:挂载 / 会话切换时从草稿恢复评论胶囊。
useEffect(() => {
@@ -4410,8 +4415,8 @@ export function ChatInput({
(g) =>
({
kind: 'desktop',
- name: g.manifest.command!,
- description: `${g.manifest.name} · ${t('settings.ghosts.commandPaletteTag')}`,
+ name: formatGhostCommandToken(g, ghostsForCommand)!,
+ description: `${g.manifest.name} · ${t('settings.ghosts.commandPaletteTag')}${g.namespace ? ` · ${g.namespace}` : ''}`,
}) as UnifiedCommand,
);
}, [ghostsForCommand, isGhostSigil, t]);
@@ -5037,8 +5042,9 @@ export function ChatInput({
if (selectedItem.type === 'file-picker') return;
if (selectedItem.type === 'plugin-command') {
if (!selectedItem.pluginId) return;
- const ghost = composerGhostsRef.current.find(
- (candidate) => candidate.manifest.id === selectedItem.pluginId,
+ const ghost = findInstalledGhostByInstanceId(
+ composerGhostsRef.current,
+ selectedItem.pluginId,
);
if (!ghost?.enabled) return;
@@ -5544,8 +5550,10 @@ export function ChatInput({
installedGhostsRef.current,
workingDirRef.current,
);
- const ghostCommandWord = parseGhostCommandWord(text);
- const usedGhost = ghostCommandWord ? findGhostByCommand(eligibleGhosts, ghostCommandWord) : null;
+ const ghostCommandToken = parseGhostCommandToken(text);
+ const usedGhost = ghostCommandToken
+ ? findGhostByCommand(eligibleGhosts, ghostCommandToken.word, ghostCommandToken.namespace)
+ : null;
const routedText = expandGhostCommand(text, eligibleGhosts);
const sendSnapshot = captureComposerSendSnapshot(
editor.getJSON(),
@@ -5574,7 +5582,7 @@ export function ChatInput({
const markRecentPluginUsage = () => {
if (!usedGhost || recentUsageMarked || sourceRemoteGhosts) return;
recentUsageMarked = true;
- void window.electronAPI.ghosts.markUsed(usedGhost.manifest.id).catch((error) => {
+ void window.electronAPI.ghosts.markUsed(installedGhostStoragePart(usedGhost)).catch((error) => {
log.warn(
'failed to persist recent Plugin usage:',
error instanceof Error ? error.message : String(error),
@@ -8822,7 +8830,7 @@ export function ChatInput({
// main 验归属后,图片落图片附件、视频落路径引用的 file 附件(托盘可见)。
// 键用 storageKey(= draftKey ?? sessionId):新建会话草稿态没有
// sessionId,附件落草稿命名空间,发送时 rehomeDraftAttachments 迁移。
- const ghostMediaUri = getGhostMediaUriFromDataTransfer(e.dataTransfer);
+ const ghostMediaUri = getGhostMediaHandoverFromDataTransfer(e.dataTransfer);
if (ghostMediaUri) {
if (storageKey) void attachGhostMediaToSession(ghostMediaUri, storageKey, t);
return;
diff --git a/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts b/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts
index f604f40043..bf3eeceffd 100644
--- a/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts
@@ -27,6 +27,8 @@ import type { Node as PMNode } from '@tiptap/pm/model';
import {
findGhostByCommand,
findGhostByCommandIncludingDisabled,
+ ghostCommandTokenLength,
+ parseGhostCommandToken,
} from '@/cindy-brain/ghostCommand';
import type { GhostCommandSource } from '../../../shared/ghostComposer';
@@ -41,9 +43,6 @@ interface GhostCommandPluginState {
/** 触发符字符集——与 ChatInput 的 GHOST_SIGIL_CHARS / COMMAND_RE 同一套。 */
const SIGILS = new Set(['$', '$', '¥', '¥']);
-/** 指令词形状:紧跟触发符的连续非空白,≤32 字符(同 COMMAND_RE)。 */
-const WORD_RE = /^(\S{1,32})/;
-
/**
* 头像 data URL 白名单形状:只接受 base64 图片,其它一律回退幽灵图标。
* 值要进内联 style 的 `url("...")`,这里顺带排除了引号/括号/空白等能破坏
@@ -91,11 +90,11 @@ export function findGhostCommandMatch(
if (first) {
const i = first.index;
if (!SIGILS.has(text[i])) return null;
- const word = WORD_RE.exec(text.slice(i + 1))?.[1];
+ const token = parseGhostCommandToken(text.slice(i));
// `$` 后直接空白 / 节点结束(相邻 text 节点会被 ProseMirror 合并,
// 词不可能续在下个节点里)→ 无指令词。
- if (!word) return null;
- const after = i + 1 + word.length;
+ if (!token) return null;
+ const after = i + 1 + ghostCommandTokenLength(token);
if (after < text.length) {
// 命中 32 字符上限但 run 未断 → 超长,发送期同样不匹配。
if (!/\s/.test(text[after])) return null;
@@ -106,8 +105,8 @@ export function findGhostCommandMatch(
if (next && next.type.name !== 'hardBreak') return null;
}
const ghost = options.includeDisabled
- ? findGhostByCommandIncludingDisabled(ghosts, word)
- : findGhostByCommand(ghosts, word);
+ ? findGhostByCommandIncludingDisabled(ghosts, token.word, token.namespace)
+ : findGhostByCommand(ghosts, token.word, token.namespace);
if (!ghost) return null;
return { from: childPos + i, to: childPos + after, ghost };
}
diff --git a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx
index bbb4833a47..c685614932 100644
--- a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx
@@ -22,6 +22,7 @@ import {
import { InlineReferenceChip } from '@/components/chat/InlineReferenceChip';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { findInstalledGhostByInstanceId } from '../../../shared/pluginIdentity';
import { GhostPluginIcon } from '@/features/plugin/GhostPluginIcon';
import { parseSessionDeepLinkHref } from '@/lib/deepLink';
@@ -85,7 +86,7 @@ function MentionIcon({ attrs }: { attrs: MentionChipAttrs }) {
function PluginCapabilityIcon({ attrs }: { attrs: MentionChipAttrs }) {
const installedGhosts = useInstalledGhosts();
const pluginId = attrs.pluginId?.trim() || attrs.label;
- const ghost = installedGhosts.find((candidate) => candidate.manifest.id === pluginId);
+ const ghost = findInstalledGhostByInstanceId(installedGhosts, pluginId);
return (
<GhostPluginIcon
diff --git a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts
index fb235e5d80..7677b9e70e 100644
--- a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts
@@ -11,6 +11,7 @@
import type { Editor } from '@tiptap/core';
import type { GhostCommandSource } from '../../../shared/ghostComposer';
+import { formatGhostCommandInsertion } from '../../cindy-brain/ghostCommand';
import { findGhostCommandMatch } from './GhostCommandDecoration';
/** Match popover selection timing: close first, then focus the final editable position. */
@@ -25,8 +26,8 @@ export function placeGhostAtComposerStart(
ghost: GhostCommandSource,
installedRoster: readonly GhostCommandSource[],
): boolean {
- const command = ghost.manifest.command;
- if (!command || editor.isDestroyed || !editor.isEditable) return false;
+ const insertion = formatGhostCommandInsertion(ghost, installedRoster);
+ if (!insertion || editor.isDestroyed || !editor.isEditable) return false;
const { doc } = editor.state;
// 替换识别看完整已安装命令集:旧 Plugin 即使已停用或被当前
@@ -41,18 +42,18 @@ export function placeGhostAtComposerStart(
? doc.textBetween(match.to, Math.min(match.to + 1, doc.content.size), '\n', '\n')
: '';
transaction.insertText(
- `$${command}${nextCharacter && /\s/u.test(nextCharacter) ? '' : ' '}`,
+ `${insertion}${nextCharacter && /\s/u.test(nextCharacter) ? '' : ' '}`,
match.from,
match.to,
);
} else {
const firstBlock = doc.firstChild;
if (firstBlock?.isTextblock) {
- transaction.insertText(`$${command} `, 1);
+ transaction.insertText(`${insertion} `, 1);
} else {
const paragraphType = editor.state.schema.nodes.paragraph;
if (!paragraphType) return false;
- transaction.insert(0, paragraphType.create(null, editor.state.schema.text(`$${command} `)));
+ transaction.insert(0, paragraphType.create(null, editor.state.schema.text(`${insertion} `)));
}
}
diff --git a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
index 7ca138e52f..742b6a6caa 100644
--- a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx
@@ -44,7 +44,7 @@ export const MAIN_VIEW_ICONS: Record<GhostMainViewIcon, LucideIcon> = {
export function GhostMainViewNavEntries({ variant }: { variant: 'row' | 'rail' }) {
const { sidebarVisible } = useGhostMainViews();
return sidebarVisible.map((item) => (
- <GhostMainViewNavEntry key={item.ghostId} item={item} variant={variant} />
+ <GhostMainViewNavEntry key={item.instanceId} item={item} variant={variant} />
));
}
@@ -59,7 +59,7 @@ export function GhostMainViewNavEntry({
const { t } = useTranslation();
const navigate = useNavigate();
const activeMatch = useMatch('/apps/:ghostId');
- const active = activeMatch?.params.ghostId === item.ghostId;
+ const active = activeMatch?.params.ghostId === item.instanceId;
const Icon = MAIN_VIEW_ICONS[item.icon];
const icon = (
<Icon
@@ -69,9 +69,9 @@ export function GhostMainViewNavEntry({
className="shrink-0"
/>
);
- const open = () => navigate(`/apps/${encodeURIComponent(item.ghostId)}`);
+ const open = () => navigate(`/apps/${encodeURIComponent(item.instanceId)}`);
const openDetails = () =>
- navigate(`/settings?tab=ghosts&ghost=${encodeURIComponent(item.ghostId)}`);
+ navigate(`/settings?tab=ghosts&ghost=${encodeURIComponent(item.instanceId)}`);
if (variant === 'rail') {
return (
diff --git a/apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx b/apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx
index 71e70bae5d..cc3398676e 100644
--- a/apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx
@@ -50,8 +50,8 @@ export function SidebarNavigationCustomize({ onDone }: SidebarNavigationCustomiz
const { dataOwnerId } = useAuth();
const prefs = useSidebarNavigationPrefs(dataOwnerId);
const { sidebarVisible } = useGhostMainViews();
- const appIds = sidebarVisible.map((item) => item.ghostId);
- const apps = new Map(sidebarVisible.map((item) => [item.ghostId, item]));
+ const appIds = sidebarVisible.map((item) => item.instanceId);
+ const apps = new Map(sidebarVisible.map((item) => [item.instanceId, item]));
const [initial] = useState<CustomizeDraft>(() => ({
order: resolveSidebarNavigationOrder(prefs.order, appIds),
visible: new Set(prefs.visible),
diff --git a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
index d32bf7aa3b..99a071a2c5 100644
--- a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
@@ -194,7 +194,7 @@ function useSidebarNavigationEntries(): {
const prefs = useSidebarNavigationPrefs(dataOwnerId);
const { sidebarVisible } = useGhostMainViews();
const rosterReady = useInstalledGhosts().length > 0;
- const sidebarGhostIds = sidebarVisible.map((item) => item.ghostId).join('\n');
+ const sidebarGhostIds = sidebarVisible.map((item) => item.instanceId).join('\n');
// Plugins entering the sidebar for the first time start in More, flagged as new.
// Wait for the account and its installed roster: both are per data owner.
useEffect(() => {
@@ -207,8 +207,8 @@ function useSidebarNavigationEntries(): {
}
}, [dataOwnerId, sidebarGhostIds, rosterReady]);
const unseenGhostIds = useSidebarUnseenApps(dataOwnerId);
- const apps = new Map(sidebarVisible.map((item) => [item.ghostId, item]));
- const order = resolveSidebarNavigationOrder(prefs.order, sidebarVisible.map((item) => item.ghostId));
+ const apps = new Map(sidebarVisible.map((item) => [item.instanceId, item]));
+ const order = resolveSidebarNavigationOrder(prefs.order, sidebarVisible.map((item) => item.instanceId));
const isVisible = (id: SidebarNavigationEntryId) => ghostIdOfEntry(id) === null
? prefs.visible.includes(id as SidebarNavigationItemId)
: prefs.appsAtTop.includes(id as SidebarNavigationAppEntryId);
@@ -286,7 +286,7 @@ function SidebarNavigationMoreMenu({
if (app) {
const AppIcon = MAIN_VIEW_ICONS[app.icon];
const manageLabel = t('settings.ghosts.page.manageAria', { name: app.manifest.name });
- const ghostId = encodeURIComponent(app.ghostId);
+ const ghostId = encodeURIComponent(app.instanceId);
return (
<DropdownMenuItem
key={id}
diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
index 68e28ca03e..dece6e5274 100644
--- a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx
@@ -7,6 +7,7 @@ import { describe, expect, it, vi } from 'vitest';
const items = [
{
ghostId: 'alpha',
+ instanceId: 'alpha',
title: 'Alpha',
icon: 'puzzle',
manifest: { id: 'alpha', name: 'Alpha Plugin' },
@@ -14,6 +15,7 @@ const items = [
},
{
ghostId: 'workspace',
+ instanceId: 'workspace',
title: 'Workspace',
icon: 'globe',
manifest: { id: 'workspace', name: 'Workspace Plugin' },
diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarNavigationCustomize.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarNavigationCustomize.test.tsx
index 53307e4106..6a5f4f9d14 100644
--- a/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarNavigationCustomize.test.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarNavigationCustomize.test.tsx
@@ -13,7 +13,7 @@ import {
setSidebarNavigationPrefs,
} from '../sidebarNavigationPrefs';
-type MainViewMock = { ghostId: string; title: string; icon: 'globe' };
+type MainViewMock = { ghostId: string; instanceId: string; title: string; icon: 'globe' };
const OWNER = 'owner-1';
const PREFS_KEY = `sidebar-navigation:v2.owner.${OWNER}`;
const mainViewsMock = vi.hoisted(() => ({
@@ -25,7 +25,7 @@ const visibilityMock = vi.hoisted(() => ({
async () => true,
),
}));
-const SITES: MainViewMock = { ghostId: 'xd-sites', title: '站点', icon: 'globe' };
+const SITES: MainViewMock = { ghostId: 'xd-sites', instanceId: 'xd-sites', title: '站点', icon: 'globe' };
vi.mock('@/cindy-brain/ghostMainViews', () => ({
useGhostMainViews: () => ({
@@ -246,6 +246,28 @@ describe('sidebar navigation customization', () => {
'false',
);
});
+ it.each([
+ { label: 'short', namespace: 'acme' },
+ { label: 'maximum-length', namespace: 'a'.repeat(128) },
+ ])('saves independent placement and order for same-name root and enterprise instances with $label namespace', ({ namespace }) => {
+ const root = { ...SITES, instanceId: '_root__xd-sites', title: 'Root sites' };
+ const organization = { ...SITES, instanceId: '_ns__' + namespace + '__xd-sites', title: 'Enterprise sites' };
+ const organizationEntryId = `app:${organization.instanceId}` as const;
+ mainViewsMock.routeCapable = [root, organization];
+ mainViewsMock.sidebarVisible = [root, organization];
+ const savedOrder = ['app:_root__xd-sites', organizationEntryId, ...defaults().order] as const;
+ setSidebarNavigationPrefs(OWNER, { order: [...savedOrder], visible: [...defaults().visible],
+ appsAtTop: ['app:_root__xd-sites'] });
+ render(<SidebarNavigationCustomize onDone={() => {}} />);
+ expect(screen.getByRole('checkbox', { name: 'Root sites' }).getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByRole('checkbox', { name: 'Enterprise sites' }).getAttribute('aria-checked')).toBe('false');
+ fireEvent.click(screen.getByRole('checkbox', { name: 'Root sites' }));
+ fireEvent.click(screen.getByRole('checkbox', { name: 'Enterprise sites' }));
+ fireEvent.click(screen.getByRole('button', { name: 'sidebar.navigation.customize.done' }));
+ navigationTesting.resetPrefsCache();
+ expect(getSidebarNavigationPrefs(OWNER)).toEqual({ order: [...savedOrder],
+ visible: [...defaults().visible], appsAtTop: [organizationEntryId] });
+ });
it('leaves out plugins switched off in their own settings and keeps their saved place', () => {
mainViewsMock.routeCapable = [SITES];
@@ -262,7 +284,7 @@ describe('sidebar navigation customization', () => {
});
it('drops every plugin placement on reset, including ones switched off for now', () => {
- const off = { ghostId: 'off', title: 'Off', icon: 'globe' as const };
+ const off = { ghostId: 'off', instanceId: 'off', title: 'Off', icon: 'globe' as const };
mainViewsMock.routeCapable = [SITES, off];
mainViewsMock.sidebarVisible = [SITES];
setSidebarNavigationPrefs(OWNER, {
diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.bots.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.bots.test.tsx
index db677fe248..6f69920e4e 100644
--- a/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.bots.test.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.bots.test.tsx
@@ -14,7 +14,7 @@ import {
const OWNER = 'owner-1';
const searchMock = vi.hoisted(() => ({ query: '', lockedProjectKey: null as string | null }));
-type MainViewMock = { ghostId: string; title: string; icon: 'globe'; manifest: { name: string } };
+type MainViewMock = { ghostId: string; instanceId: string; title: string; icon: 'globe'; manifest: { name: string } };
const mainViewsMock = vi.hoisted(() => ({
routeCapable: [] as MainViewMock[],
sidebarVisible: [] as MainViewMock[],
@@ -25,7 +25,7 @@ vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: authMo
const installedMock = vi.hoisted(() => ({ ghosts: [{ manifest: { id: 'bundled' } }] as unknown[] }));
vi.mock('@/cindy-brain/useInstalledGhosts', () => ({ useInstalledGhosts: () => installedMock.ghosts }));
const SITES: MainViewMock = {
- ghostId: 'xd-sites', title: '站点', icon: 'globe', manifest: { name: 'XD Sites' },
+ ghostId: 'xd-sites', instanceId: 'xd-sites', title: '站点', icon: 'globe', manifest: { name: 'XD Sites' },
};
vi.mock('react-i18next', () => ({
@@ -326,16 +326,6 @@ describe('Sidebar teammate return action', () => {
openMore();
expect(screen.queryByRole('menuitem', { name: /站点/ })).toBeNull();
});
- it('keeps a plugin without a top-level placement in More and opens its page', () => {
- seedKnownPlugins(['xd-sites']);
- mainViewsMock.routeCapable = [SITES];
- mainViewsMock.sidebarVisible = [SITES];
- render(<Harness initialPath="/cc-agent" />);
- expect(screen.queryByRole('button', { name: '站点' })).toBeNull();
- openMore();
- fireEvent.click(screen.getByRole('menuitem', { name: /站点/ }));
- expect(screen.getByTestId('location').textContent).toBe('/apps/xd-sites');
- });
it('leaves a plugin out of the sidebar and More once its own switch is off', () => {
mainViewsMock.routeCapable = [SITES];
render(<Harness initialPath="/cc-agent" />);
@@ -355,20 +345,43 @@ describe('Sidebar teammate return action', () => {
}));
expect(screen.queryByRole('button', { name: '站点' })).toBeNull();
});
- it('keeps the plugin manage action on its More item', () => {
- seedKnownPlugins(['xd-sites']);
- mainViewsMock.routeCapable = [SITES];
- mainViewsMock.sidebarVisible = [SITES];
+ it.each(['xd-sites', '_root__xd-sites', '_ns__acme__xd-sites'])(
+ 'opens the page and manage action for the exact %s instance in More', (instanceId) => {
+ seedKnownPlugins([instanceId]);
+ const sites = { ...SITES, instanceId };
+ mainViewsMock.routeCapable = [sites];
+ mainViewsMock.sidebarVisible = [sites];
render(<Harness initialPath="/cc-agent" />);
+ expect(screen.queryByRole('button', { name: '站点' })).toBeNull();
openMore();
const item = screen.getByRole('menuitem', { name: /站点/ });
const manage = within(item).getByRole('button', { name: 'settings.ghosts.page.manageAria: XD Sites' });
fireEvent.click(manage);
- expect(screen.getByTestId('location').textContent).toBe('/settings?tab=ghosts&ghost=xd-sites');
+ expect(screen.getByTestId('location').textContent).toBe('/settings?tab=ghosts&ghost=' + instanceId);
// The flag is one-shot: the next plain selection opens the plugin page again.
openMore();
fireEvent.click(screen.getByRole('menuitem', { name: /站点/ }));
- expect(screen.getByTestId('location').textContent).toBe('/apps/xd-sites');
+ expect(screen.getByTestId('location').textContent).toBe('/apps/' + instanceId);
+ });
+ it('keeps same-name root and enterprise arrivals separate in More', () => {
+ const root = { ...SITES, instanceId: '_root__xd-sites', title: 'Root sites' };
+ const organization = { ...SITES, instanceId: '_ns__acme__xd-sites', title: 'Enterprise sites' };
+ seedKnownPlugins([root.instanceId]);
+ mainViewsMock.routeCapable = [root, organization];
+ mainViewsMock.sidebarVisible = [root, organization];
+ render(<Harness initialPath="/cc-agent" />);
+ fireEvent.pointerDown(screen.getByRole('button', { name: 'sidebar.navigation.more · sidebar.navigation.new' }), {
+ button: 0,
+ ctrlKey: false,
+ });
+ const rootEntry = screen.getByRole('menuitem', { name: /Root sites/ });
+ const orgEntry = screen.getByRole('menuitem', { name: /Enterprise sites/ });
+ expect(rootEntry.textContent).not.toContain('sidebar.navigation.new');
+ expect(orgEntry.textContent).toContain('sidebar.navigation.new');
+ fireEvent.click(orgEntry);
+ expect(screen.getByTestId('location').textContent).toBe('/apps/' + organization.instanceId);
+ expect(JSON.parse(localStorage.getItem('sidebar-navigation:apps:v1')!)[OWNER].known)
+ .toEqual([root.instanceId, organization.instanceId]);
});
it('lists only unchecked entries and Customize in More', () => {
render(<Harness initialPath="/cc-agent" />);
@@ -540,8 +553,8 @@ describe('Narrow rail navigation', () => {
});
it('lays out plugin main views in the saved order and keeps hidden ones in More', () => {
- const other: MainViewMock = { ghostId: 'other', title: 'Other', icon: 'globe', manifest: { name: 'Other' } };
- const off: MainViewMock = { ghostId: 'off', title: 'Off', icon: 'globe', manifest: { name: 'Off' } };
+ const other: MainViewMock = { ghostId: 'other', instanceId: 'other', title: 'Other', icon: 'globe', manifest: { name: 'Other' } };
+ const off: MainViewMock = { ghostId: 'off', instanceId: 'off', title: 'Off', icon: 'globe', manifest: { name: 'Off' } };
seedKnownPlugins(['xd-sites', 'other']);
mainViewsMock.routeCapable = [SITES, other, off];
mainViewsMock.sidebarVisible = [SITES, other];
@@ -615,7 +628,7 @@ describe('Narrow rail navigation', () => {
});
describe('Plugins joining the sidebar', () => {
- const NEWCOMER: MainViewMock = { ghostId: 'newcomer', title: 'Newcomer', icon: 'globe', manifest: { name: 'Newcomer' } };
+ const NEWCOMER: MainViewMock = { ghostId: 'newcomer', instanceId: 'newcomer', title: 'Newcomer', icon: 'globe', manifest: { name: 'Newcomer' } };
const renderNav = () => render(
<MainViewHistoryProvider>
<MemoryRouter initialEntries={['/cc-agent']}>
diff --git a/apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts b/apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts
index 40246eb5dc..6a4e8dadf2 100644
--- a/apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts
+++ b/apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts
@@ -40,7 +40,7 @@ export type SidebarNavigationAppEntryId = `app:${string}`;
export type SidebarNavigationEntryId = SidebarNavigationItemId | SidebarNavigationAppEntryId;
const APP_ENTRY_PREFIX = 'app:';
-const MAX_APP_ENTRY_LENGTH = APP_ENTRY_PREFIX.length + 128;
+const MAX_APP_ENTRY_LENGTH = APP_ENTRY_PREFIX.length + 256;
export function appEntryId(ghostId: string): SidebarNavigationAppEntryId {
return `${APP_ENTRY_PREFIX}${ghostId}`;
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index 69c4119002..fdf20a7fa2 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -19,7 +19,7 @@ import { ArrowLeft, CircleAlert, RefreshCcw, Settings2, Sparkles } from 'lucide-
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
-import { attachGhostMediaToSession, getGhostMediaUriFromDataTransfer } from '@/cindy-brain/ghostMediaHandover';
+import { attachGhostMediaToSession, getGhostMediaHandoverFromDataTransfer } from '@/cindy-brain/ghostMediaHandover';
import { ChatImageView } from '@/components/chat/ChatImageView';
import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
import { ShareSelectionBar } from '@/components/chat/ShareSelectionBar';
@@ -497,7 +497,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const dropAttachments = (event: DragEvent) => {
// .cindy / .cshare drops belong to the window-level import; only clear the hint.
if (isGlobalDropIntercepted(event.nativeEvent)) return;
- const ghostMediaUri = getGhostMediaUriFromDataTransfer(event.dataTransfer);
+ const ghostMediaUri = getGhostMediaHandoverFromDataTransfer(event.dataTransfer);
if (ghostMediaUri) {
void attachGhostMediaToSession(ghostMediaUri, attachmentScope, t);
return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 835b283bf0..f3b07ba9dc 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -307,7 +307,7 @@ import { hasSplitGroupSessionType } from './splitGroupDnd';
import { splitGroupStore } from './splitGroupStore';
import {
attachGhostMediaToSession,
- getGhostMediaUriFromDataTransfer,
+ getGhostMediaHandoverFromDataTransfer,
} from '@/cindy-brain/ghostMediaHandover';
import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';
import {
@@ -4993,7 +4993,7 @@ export function CCAgentSessionView({
// 意识面板拖来的产物(cindy-ghost:// 媒体地址,不带 files):落在聊天区
// 任意位置都算数,与 ChatInput 自己的 onDrop 同一条引渡链路——
// main 验归属后图片落图片附件、视频落路径引用的 file 附件(托盘可见)。
- const ghostMediaUri = getGhostMediaUriFromDataTransfer(e.dataTransfer);
+ const ghostMediaUri = getGhostMediaHandoverFromDataTransfer(e.dataTransfer);
if (ghostMediaUri) {
if (sessionId) void attachGhostMediaToSession(ghostMediaUri, sessionId, t);
return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 199d233026..c7265f911a 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -192,6 +192,7 @@ import {
type HomeTaskSuggestion,
} from './pluginHomeSuggestions';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
import {
startPendingPluginSuggestion,
takePendingPluginSuggestion,
@@ -215,7 +216,7 @@ import { cn } from '@/lib/utils';
import { InvisibleWindowDragStrip } from '@/components/layout/windowDrag';
import {
attachGhostMediaToSession,
- getGhostMediaUriFromDataTransfer,
+ getGhostMediaHandoverFromDataTransfer,
} from '@/cindy-brain/ghostMediaHandover';
import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';
import { classifyUnclassifiedDroppedItems, getDroppedFileItems } from '@/lib/fileDrop';
@@ -5345,7 +5346,7 @@ export function NewMakerDraftRoute() {
new Map(
(isDeviceLinkDraft ? [] : filterGhostsForWorkdir(installedGhosts, effectiveWorkingDir))
.filter((g) => g.enabled)
- .map((g) => [g.manifest.id, g]),
+ .map((g) => [installedGhostStoragePart(g), g]),
),
[isDeviceLinkDraft, effectiveWorkingDir, installedGhosts],
);
@@ -5354,7 +5355,7 @@ export function NewMakerDraftRoute() {
const ghost = suggestion.pluginId
? usableSuggestionGhosts.get(suggestion.pluginId)
: undefined;
- return ghost ? pluginSuggestionComposerText(suggestion.prompt, ghost, t) : suggestion.prompt;
+ return ghost ? pluginSuggestionComposerText(suggestion.prompt, ghost, t, [...usableSuggestionGhosts.values()]) : suggestion.prompt;
},
[t, usableSuggestionGhosts],
);
@@ -5427,15 +5428,16 @@ export function NewMakerDraftRoute() {
toast.info(t('newChat.pluginSuggestions.changed'));
return;
}
- const ghost = window.electronAPI.ghosts
- .listSync()
- .ghosts.find((g) => g.manifest.id === suggestion.pluginId);
+ const installedGhosts = window.electronAPI.ghosts.listSync().ghosts;
+ const ghost = installedGhosts.find((g) => installedGhostStoragePart(g) === suggestion.pluginId);
+ const usableGhosts = filterGhostsForWorkdir(installedGhosts, request.workingDir)
+ .filter((g) => g.enabled);
const usable =
- ghost && ghost.enabled && filterGhostsForWorkdir([ghost], request.workingDir).length > 0;
+ ghost && usableGhosts.includes(ghost);
if (!usable) {
let route: string;
if (ghost) {
- route = `/plugins?ghost=${encodeURIComponent(ghost.manifest.id)}`;
+ route = `/plugins?ghost=${encodeURIComponent(installedGhostStoragePart(ghost))}`;
} else {
const market = await window.electronAPI.pluginMarket.snapshot();
if (!stillCurrent() || readPluginRecommendationSnapshot().ownerId !== request.ownerId)
@@ -5458,8 +5460,8 @@ export function NewMakerDraftRoute() {
// 填进输入框而不是直接发送;ChatInput 发送时会自己展开 $command。无指令插件发送时
// 识别不出所用插件,所以选中插件建议并成功填入即记一次最近使用(有指令的插件发送时
// 还会再记一次,只刷新时间,不影响排序语义)。
- if (fillComposerWithSuggestion(pluginSuggestionComposerText(suggestion.prompt, ghost, t))) {
- void window.electronAPI.ghosts.markUsed(ghost.manifest.id).catch(() => undefined);
+ if (fillComposerWithSuggestion(pluginSuggestionComposerText(suggestion.prompt, ghost, t, usableGhosts))) {
+ void window.electronAPI.ghosts.markUsed(installedGhostStoragePart(ghost)).catch(() => undefined);
}
} catch {
if (pluginSuggestionMounted.current)
@@ -5544,7 +5546,7 @@ export function NewMakerDraftRoute() {
setPageDragOver(false);
// .cindy / .cshare 已被窗口级 capture 接管(装入 / 导入链路),不当附件消费。
if (isGlobalDropIntercepted(e.nativeEvent)) return;
- const ghostMediaUri = getGhostMediaUriFromDataTransfer(e.dataTransfer);
+ const ghostMediaUri = getGhostMediaHandoverFromDataTransfer(e.dataTransfer);
if (ghostMediaUri) {
e.preventDefault();
e.stopPropagation();
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts
index b2faefc671..f51112f723 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/pendingPluginSuggestion.test.ts
@@ -30,6 +30,17 @@ describe('installation continuation', () => {
);
expect(takePendingPluginSuggestion(nonce, 'a', 'local')).toBeNull();
});
+ it('rebinds a logical root suggestion to its physical install instance', () => {
+ const nonce = startPendingPluginSuggestion({
+ ...request,
+ suggestion: { ...request.suggestion, id: 'plugin:test:one' },
+ });
+ expect(readyPendingPluginSuggestion(nonce, 'a', '_root__test')).toBe(nonce);
+ expect(getPendingPluginSuggestion()?.suggestion).toMatchObject({
+ id: 'plugin:_root__test:one',
+ pluginId: '_root__test',
+ });
+ });
it('ignores completion after cancellation or after another selection', () => {
const old = startPendingPluginSuggestion(request);
cancelPendingPluginSuggestion(old);
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/pluginHomeSuggestions.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/pluginHomeSuggestions.test.ts
index 4f856c6159..c72ec44d3f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/pluginHomeSuggestions.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/pluginHomeSuggestions.test.ts
@@ -23,6 +23,19 @@ function random(seed: number) {
}
describe('host plugin recommendation selection', () => {
+ it('keeps same-name instances as separate recommendations', () => {
+ const snapshot = {
+ ...empty,
+ sources: [
+ { ghostId: 'helper', name: 'Root', enabled: true, items: [task] },
+ { ghostId: '_ns__acme__helper', name: 'Org', enabled: true, items: [task] },
+ ],
+ };
+ const catalog = buildHomeTaskCatalog(snapshot, 'en', t).filter((entry) => entry.pluginId?.includes('helper'));
+ expect(catalog.map((entry) => entry.id)).toEqual([
+ 'plugin:helper:one', 'plugin:_ns__acme__helper:one',
+ ]);
+ });
it('includes curated installation tasks and respects an explicit empty author catalog', () => {
expect(buildHomeTaskCatalog(empty, 'en', t).filter((x) => x.needsInstall)).toHaveLength(3);
const snapshot = {
diff --git a/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts b/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts
index 3df837342b..6abc47feab 100644
--- a/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/pendingPluginSuggestion.ts
@@ -1,4 +1,5 @@
import type { HomeTaskSuggestion } from './pluginHomeSuggestions';
+import { parsePluginInstanceId } from '../../../shared/pluginIdentity';
export interface PluginSuggestionRequest {
suggestion: HomeTaskSuggestion;
@@ -38,15 +39,31 @@ export function readyPendingPluginSuggestion(
ownerId: string | null,
ghostId: string,
): string | null {
+ const suggestionPluginId = pending?.suggestion.pluginId;
+ const suggestionIdentity =
+ typeof suggestionPluginId === 'string' ? parsePluginInstanceId(suggestionPluginId) : null;
+ const installedIdentity = parsePluginInstanceId(ghostId);
if (
!pending ||
pending.nonce !== nonce ||
pending.ownerId !== ownerId ||
- pending.suggestion.pluginId !== ghostId ||
+ typeof suggestionPluginId !== 'string' ||
+ !suggestionIdentity ||
+ !installedIdentity ||
+ suggestionIdentity.namespace !== installedIdentity.namespace ||
+ suggestionIdentity.ghostId !== installedIdentity.ghostId ||
pending.phase !== 'setup'
)
return null;
- pending = { ...pending, phase: 'ready' };
+ const pluginPrefix = `plugin:${suggestionPluginId}:`;
+ const suggestion = {
+ ...pending.suggestion,
+ pluginId: ghostId,
+ id: pending.suggestion.id.startsWith(pluginPrefix)
+ ? `plugin:${ghostId}:${pending.suggestion.id.slice(pluginPrefix.length)}`
+ : pending.suggestion.id,
+ };
+ pending = { ...pending, suggestion, phase: 'ready' };
publish();
return pending.nonce;
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts b/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts
index fe9f54b605..5842741481 100644
--- a/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/pluginHomeSuggestions.ts
@@ -1,5 +1,7 @@
import { localizeGhostRecommendation, type GhostRecommendation } from '@cindy/plugin-protocol';
import type { HomePluginRecommendationsSnapshot } from '../../../shared/homePluginRecommendations';
+import { hasDeliveryNamespace } from '../../../shared/pluginIdentity';
+import { formatGhostCommandInsertion } from '../../cindy-brain/ghostCommand';
import {
HOME_SUGGESTION_CATALOG,
homeSuggestionLabelKey,
@@ -174,10 +176,16 @@ export function nextHomeTaskBatch(
*/
export function pluginSuggestionComposerText(
prompt: string,
- ghost: { manifest: { id: string; name: string; command?: string } },
+ ghost: { manifest: { id: string; name: string; command?: string }; dir?: string; namespace?: string | null },
t: (key: string, options?: Record<string, unknown>) => string,
+ roster: readonly { manifest: { command?: string }; namespace?: string | null }[] = [],
): string {
return ghost.manifest.command
- ? `$${ghost.manifest.command} ${prompt}`
- : `${prompt}\n\n${t('newChat.pluginSuggestions.usePlugin', { name: ghost.manifest.name, id: ghost.manifest.id })}`;
+ ? `${formatGhostCommandInsertion(ghost, roster)} ${prompt}`
+ : `${prompt}\n\n${t('newChat.pluginSuggestions.usePlugin', {
+ name: ghost.manifest.name,
+ id: hasDeliveryNamespace(ghost) && typeof ghost.namespace === 'string'
+ ? ghost.manifest.id + ' namespace:' + ghost.namespace
+ : ghost.manifest.id,
+ })}`;
}
diff --git a/apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx b/apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx
index 288a8a37e6..fd3a03aa76 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx
@@ -4,14 +4,17 @@ import { useNavigate, useParams } from 'react-router-dom';
import { useGhostMainViews } from '@/cindy-brain/ghostMainViews';
import { GhostPanelError, GhostWebviewBody } from '@/cindy-brain/ghostPanelBody';
import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
/** Route boundary that resolves only an approved, enabled manifest main-view entry. */
export function GhostMainViewHost() {
const { ghostId = '' } = useParams<{ ghostId: string }>();
const navigate = useNavigate();
const { routeCapable } = useGhostMainViews();
- const item = routeCapable.find((candidate) => candidate.ghostId === ghostId);
- const runtimeState = useGhostRuntimeState(ghostId);
+ const item = routeCapable.find((candidate) => candidate.instanceId === ghostId);
+ const runtimeState = useGhostRuntimeState(
+ item ? item.instanceId : ghostId,
+ );
useEffect(() => {
if (!item) navigate('/plugins', { replace: true });
@@ -19,7 +22,7 @@ export function GhostMainViewHost() {
if (!item) return <div className="h-full w-full bg-content-area" />;
- const { manifest } = item;
+ const { manifest, installedGhost } = item;
const broken = runtimeState === 'crashed' || runtimeState === 'fused';
return (
<section
@@ -27,9 +30,9 @@ export function GhostMainViewHost() {
aria-label={item.title}
>
{broken ? (
- <GhostPanelError manifest={manifest} state={runtimeState} />
+ <GhostPanelError ghost={installedGhost} state={runtimeState} />
) : (
- <GhostWebviewBody key={manifest.id} manifest={manifest} html={manifest.mainView?.html} />
+ <GhostWebviewBody key={installedGhostStoragePart(installedGhost)} ghost={installedGhost} html={manifest.mainView?.html} />
)}
</section>
);
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPagePanelHost.tsx b/apps/desktop/src/renderer/features/plugin/GhostPagePanelHost.tsx
index 0806717dcb..8772214581 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPagePanelHost.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPagePanelHost.tsx
@@ -14,6 +14,7 @@ import { GhostChipPanelBody, GhostPanelError } from '@/cindy-brain/ghostPanelBod
import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import type { InstalledGhost } from '../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
/**
* 面板收束(设计定稿):插件小侧边只从插件页进入,同一时刻至多一个,
@@ -30,7 +31,7 @@ export function GhostPagePanelHost({
}) {
const { t } = useTranslation();
const { manifest } = ghost;
- const runtimeState = useGhostRuntimeState(manifest.id);
+ const runtimeState = useGhostRuntimeState(installedGhostStoragePart(ghost));
const broken = runtimeState === 'crashed' || runtimeState === 'fused';
const width = Math.max(manifest.panel?.minWidth ?? 320, 320);
return (
@@ -58,9 +59,9 @@ export function GhostPagePanelHost({
</div>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
{broken ? (
- <GhostPanelError manifest={manifest} state={runtimeState} />
+ <GhostPanelError ghost={ghost} state={runtimeState} />
) : (
- <GhostChipPanelBody manifest={manifest} />
+ <GhostChipPanelBody ghost={ghost} />
)}
</div>
</aside>
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index dcccf7f5ae..97104727a1 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -45,8 +45,8 @@ import { Switch } from '@/components/ui/switch';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import {
- isOfficialGhostId,
ghostTrustLabelKey,
+ isUserInstallReservedGhostId,
type GhostPermissionItem,
type GhostToolDecl,
type InstalledGhost,
@@ -141,7 +141,7 @@ export function GhostPluginDetailView({
// Local imports with the same id cannot use the host gh credential. Match the
// official receipt before advertising that connection in this plugin's UI.
const hasGithubConnection =
- detail.id === 'cindy-github' &&
+ detail.ghostId === 'cindy-github' &&
Boolean(ghost) &&
ghost?.trust?.level === 'cindy-official' &&
ghost.trust.publisherSigned &&
@@ -156,7 +156,7 @@ export function GhostPluginDetailView({
detail.hasTaskPreferences;
const summary = hasGithubConnection
? t('ccAgent.gitContext.pr.setup.account.summary')
- : ghostPluginSummary(detail.description, detail.id);
+ : ghostPluginSummary(detail.description, detail.ghostId);
/**
* 「从 .cindy 文件更新」是否可用。官方保留前缀(cindy- / filo- / xd-)在**非 dev
* 构建**上会被 Main 的用户装入通道以 GHOST_ID_RESERVED 直接拒绝(见
@@ -168,7 +168,7 @@ export function GhostPluginDetailView({
* 会多隐藏一次入口——方向保守(少一个入口 vs 给用户一个必失败按钮),可接受。
* 普通第三方插件不受影响。
*/
- const localUpdateAvailable = import.meta.env.DEV || !isOfficialGhostId(detail.id);
+ const localUpdateAvailable = import.meta.env.DEV || !isUserInstallReservedGhostId(detail.ghostId);
const hasAdditionalActions = localUpdateAvailable || onExport !== undefined;
useLayoutEffect(() => {
@@ -842,7 +842,7 @@ export function DetailsSection({
{
key: 'identifier',
label: t('settings.ghosts.detail.infoId'),
- value: detail.id,
+ value: detail.ghostId,
monospace: true,
},
...(detail.contents.length > 0
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 136015c8b8..41f879188d 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -82,10 +82,16 @@ import { resolveSystemLocale } from '../../../shared/locale';
import {
ghostInstallApprovalToken,
ghostPanelKind,
- isOfficialGhostId,
+ isUserInstallReservedGhostId,
type GhostSetupStatus,
type InstalledGhost,
} from '../../../shared/ghost';
+import {
+ createPluginLogicalIdentity,
+ findInstalledGhostByIdentity,
+ findInstalledGhostByInstanceId,
+ installedGhostStoragePart,
+} from '../../../shared/pluginIdentity';
import type {
PluginMarketDetail,
PluginMarketInstallOptions,
@@ -137,6 +143,8 @@ import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker'
import {
canOfferMarketInstall,
ghostReapprovalRoute,
+ marketItemForInstalledGhost,
+ marketItemMatchesInstalledGhost,
marketReviewTargetsInstalledGhost,
pluginPresentationOrigin,
pluginUpdateForInstalledVersion,
@@ -153,12 +161,29 @@ import './plugin-motion.css';
const PLUGIN_CATALOG_TOOLBAR_CLASS =
'plugin-catalog-toolbar mb-5 flex items-center justify-between gap-4';
type PluginPresentationFilter = 'all' | PluginPresentationOrigin;
+
type PresentedGhostPluginItem = GhostPluginListItem & {
origin: PluginPresentationOrigin;
/** 市场存在更新时的市场记录;列表卡片据此显示更新徽标与直达入口。 */
marketUpdate: PluginMarketItem | null;
};
+function findInstalledRetirementReplacement(
+ ghosts: readonly InstalledGhost[],
+ marketItems: readonly PluginMarketItem[],
+ target: { ghostId: string; marketId: string } | undefined,
+): InstalledGhost | undefined {
+ if (!target) return undefined;
+ const marketItem = marketItems.find((item) => item.pluginId === target.marketId);
+ if (marketItem) {
+ return ghosts.find((ghost) => marketItemMatchesInstalledGhost(marketItem, ghost));
+ }
+ return findInstalledGhostByIdentity(
+ ghosts,
+ createPluginLogicalIdentity(null, target.ghostId),
+ );
+}
+
/** 推荐区来源过滤:本地装的必然在已安装区,不设「本地」档(设计定稿)。 */
const RECOMMENDED_FILTERS: readonly PluginPresentationFilter[] = [
'all',
@@ -614,7 +639,9 @@ export function GhostPluginPage({
}, []);
useEffect(() => {
if (!recommendation) return;
- const target = ghosts.find((g) => g.manifest.id === recommendation.suggestion.pluginId);
+ const target = recommendation.suggestion.pluginId
+ ? findInstalledGhostByInstanceId(ghosts, recommendation.suggestion.pluginId)
+ : undefined;
handlePickScope(target?.enabled ? recommendation.workingDir : null);
}, [recommendation?.nonce, handlePickScope]);
const effectiveEnabled = useCallback(
@@ -697,15 +724,6 @@ export function GhostPluginPage({
[marketSnapshot?.customSourceNames],
);
const [addMarketplaceOpen, setAddMarketplaceOpen] = useState(false);
- const marketByGhostId = useMemo(() => {
- const map = new Map<string, PluginMarketItem>();
- for (const item of marketItems) {
- // 非当前路由的同 id 条目只出现在「可替换」市场卡片,
- // 不得投影成已装卡片的普通更新。
- if (item.installState !== 'conflict') map.set(item.ghostId, item);
- }
- return map;
- }, [marketItems]);
const allInstalledItems = useMemo<PresentedGhostPluginItem[]>(
() =>
ghosts
@@ -717,7 +735,7 @@ export function GhostPluginPage({
!ghosts.some((candidate) => candidate.manifest.id === 'xd-mivo'),
)
.map((ghost) => {
- const marketItem = marketByGhostId.get(ghost.manifest.id) ?? null;
+ const marketItem = marketItemForInstalledGhost(marketItems, ghost);
const presentation = marketPresentationForInstalledGhost(ghost, marketItem);
return {
...toGhostPluginListItem(ghost, presentation),
@@ -727,7 +745,7 @@ export function GhostPluginPage({
marketUpdate: ghost.retirement ? null : pluginUpdateForInstalledVersion(marketItem),
};
}),
- [ghosts, marketByGhostId],
+ [ghosts, marketItems],
);
const installedItems = useMemo(
() =>
@@ -889,19 +907,19 @@ export function GhostPluginPage({
(updatableInstalledItems.length > 0 &&
(currentRoundKey === '' || ignoredRound !== currentRoundKey));
const selectedGhost = selectedId
- ? (ghosts.find((ghost) => ghost.manifest.id === selectedId) ?? null)
+ ? (findInstalledGhostByInstanceId(ghosts, selectedId) ?? null)
: null;
const selectedPresentation = selectedGhost
? marketPresentationForInstalledGhost(
selectedGhost,
- marketByGhostId.get(selectedGhost.manifest.id),
+ marketItemForInstalledGhost(marketItems, selectedGhost),
)
: null;
const selectedDetail = selectedGhost
? toGhostPluginDetail(selectedGhost, selectedPresentation)
: null;
- const selectedMarketInstall = selectedDetail
- ? (marketByGhostId.get(selectedDetail.id) ?? null)
+ const selectedMarketInstall = selectedGhost
+ ? marketItemForInstalledGhost(marketItems, selectedGhost)
: null;
const selectedMarketUpdate = selectedDetail
? pluginUpdateForInstalledVersion(selectedMarketInstall)
@@ -913,10 +931,10 @@ export function GhostPluginPage({
// ── 面板收束:页面独占的插件面板宿主;停用/卸载/换形态自动失效 ──
const openPanelGhost = useMemo(() => {
if (!openPanelId) return null;
- const ghost = ghosts.find((candidate) => candidate.manifest.id === openPanelId);
+ const ghost = findInstalledGhostByInstanceId(ghosts, openPanelId) ?? null;
if (!ghost) return null;
if (ghost.manifest.panel?.position !== 'tab') return null;
- if (!effectiveEnabled(ghost.manifest.id, ghost.enabled)) return null;
+ if (!effectiveEnabled(installedGhostStoragePart(ghost), ghost.enabled)) return null;
return ghost;
}, [effectiveEnabled, ghosts, openPanelId]);
useEffect(() => {
@@ -1004,9 +1022,11 @@ export function GhostPluginPage({
// 目录详情用于发现与能力展示;点击更新后由 Main 下载并校验真实包后直接落位。
const handleMarketUpdate = useCallback(
- async (ghostId: string) => {
- const marketItem = marketByGhostId.get(ghostId);
- const installedGhost = ghosts.find((ghost) => ghost.manifest.id === ghostId) ?? null;
+ async (instanceId: string) => {
+ const installedGhost = findInstalledGhostByInstanceId(ghosts, instanceId) ?? null;
+ const marketItem = installedGhost
+ ? marketItemForInstalledGhost(marketItems, installedGhost)
+ : null;
if (
!marketItem ||
!marketReviewTargetsInstalledGhost(marketItem, installedGhost?.approval.state)
@@ -1062,7 +1082,7 @@ export function GhostPluginPage({
ghosts,
isMarketBusyLeaseActive,
installMarketPackage,
- marketByGhostId,
+ marketItems,
refreshMarket,
releaseMarketBusy,
showPluginMarketActionError,
@@ -1085,15 +1105,19 @@ export function GhostPluginPage({
* 完整安装记录,不新增能力确认。
*/
const handleRecoverInstall = useCallback(
- async (ghostId: string) => {
- if (ghosts.find((ghost) => ghost.manifest.id === ghostId)?.builtin) return;
- if (ghostReapprovalRoute(marketByGhostId.get(ghostId)) === 'market') {
- await handleMarketUpdate(ghostId);
+ async (instanceId: string) => {
+ const installedGhost = findInstalledGhostByInstanceId(ghosts, instanceId) ?? null;
+ if (installedGhost?.builtin) return;
+ if (
+ ghostReapprovalRoute(installedGhost ? marketItemForInstalledGhost(marketItems, installedGhost) : null) ===
+ 'market'
+ ) {
+ await handleMarketUpdate(instanceId);
return;
}
- await pickAndUpdateGhost(ghostId, { t });
+ await pickAndUpdateGhost(instanceId, { t });
},
- [ghosts, handleMarketUpdate, marketByGhostId, t],
+ [ghosts, handleMarketUpdate, marketItems, t],
);
const handleUpdateFromFile = useCallback(async () => {
@@ -1146,9 +1170,9 @@ export function GhostPluginPage({
await installGhostFromFile(picked.filePath, {
t,
// 已在插件页:tab 型插件安装后原地打开面板。
- openPluginPanel: (ghostId) => {
+ openPluginPanel: (instanceId) => {
setSelectedId(null);
- setOpenPanelId(ghostId);
+ setOpenPanelId(instanceId);
},
});
}, [t]);
@@ -1203,7 +1227,7 @@ export function GhostPluginPage({
const handleUseGhost = useCallback(
async (id: string, displayName: string) => {
- const ghost = ghosts.find((candidate) => candidate.manifest.id === id);
+ const ghost = findInstalledGhostByInstanceId(ghosts, id) ?? null;
if (!ghost) return;
if (!ghost.manifest.command || ghost.retirement) return;
// 使用前置门:点击时现查配置就绪度(main 侧确定性判定),未就绪先
@@ -1233,7 +1257,7 @@ export function GhostPluginPage({
attachments: existing?.attachments ?? [],
quotes: existing?.quotes ?? [],
browserComments: existing?.browserComments ?? [],
- ...(ghost.manifest.command ? { pendingGhostId: ghost.manifest.id } : {}),
+ ...(ghost.manifest.command ? { pendingGhostId: installedGhostStoragePart(ghost) } : {}),
focusAtEnd: existing?.focusAtEnd === true,
});
resetDraftWorkspaceTargets();
@@ -1415,13 +1439,13 @@ export function GhostPluginPage({
marketDetail.installState === 'conflict';
try {
let installedGhost =
- ghosts.find((ghost) => ghost.manifest.id === marketDetail.ghostId) ?? null;
+ ghosts.find((ghost) => marketItemMatchesInstalledGhost(marketDetail, ghost)) ?? null;
if (isUpdate && !installedGhost) {
try {
installedGhost =
window.electronAPI.ghosts
.listSync()
- .ghosts.find((ghost) => ghost.manifest.id === marketDetail.ghostId) ?? null;
+ .ghosts.find((ghost) => marketItemMatchesInstalledGhost(marketDetail, ghost)) ?? null;
} catch {
// bridge 不可用或状态切换时保持 null;下面按状态变化安全终止。
}
@@ -1450,7 +1474,7 @@ export function GhostPluginPage({
isStillActive: () => isMarketBusyLeaseActive(marketBusyLease),
});
if (!ghost || !isMarketBusyLeaseActive(marketBusyLease)) return;
- if (continueRecommendation(pendingNonce, ghost.manifest.id)) return;
+ if (continueRecommendation(pendingNonce, installedGhostStoragePart(ghost))) return;
// 市场首装装完即开(2026-07-26 定案),toast 用"已安装";更新路径如实
// 用"已更新"(生效状态未被改变),并留在当前页方便连续更新多个插件。
toast.success(
@@ -1467,7 +1491,7 @@ export function GhostPluginPage({
setMarketDetail((current) =>
current?.pluginId === marketDetail.pluginId ? null : current,
);
- setSelectedId(ghost.manifest.id);
+ setSelectedId(installedGhostStoragePart(ghost));
} else {
await refreshVisibleMarketDetail(marketDetail.pluginId).catch(() => undefined);
}
@@ -1537,7 +1561,7 @@ export function GhostPluginPage({
// Market details render first; selecting a hidden notice does not make it read.
if (marketDetail || !selectedGhost?.retirement?.unread) return;
void window.electronAPI.ghosts
- .acknowledgeRetirement(selectedGhost.manifest.id)
+ .acknowledgeRetirement(installedGhostStoragePart(selectedGhost))
.catch(() => toast.error(t('settings.ghosts.retirement.saveFailed')));
}, [marketDetail, selectedGhost?.manifest.id, selectedGhost?.retirement?.unread, t]);
@@ -1546,19 +1570,24 @@ export function GhostPluginPage({
selectedGhost?.retirement && featureRetirementById(selectedGhost.retirement.id);
const target = descriptor?.replacement;
if (!target || !selectedGhost?.retirement?.eligible) return;
- const replacement = window.electronAPI.ghosts
- .listSync()
- .ghosts.find((ghost) => ghost.manifest.id === target.ghostId);
+ const replacement = findInstalledRetirementReplacement(
+ window.electronAPI.ghosts.listSync().ghosts,
+ marketItems,
+ target,
+ );
if (replacement) {
+ const replacementId = installedGhostStoragePart(replacement);
if (replacement.enabled) {
- setSelectedId(replacement.manifest.id);
+ setSelectedId(replacementId);
handlePrimaryAction(toGhostPluginListItem(replacement));
} else {
const lease = acquireMarketBusy(target.marketId);
if (!lease) return;
try {
- await window.electronAPI.ghosts.setEnabled(target.ghostId, true);
- if (isMarketBusyLeaseActive(lease)) setSelectedId(target.ghostId);
+ await window.electronAPI.ghosts.setEnabled(
+ replacementId, true, ghostInstallApprovalToken(replacement.approval),
+ );
+ if (isMarketBusyLeaseActive(lease)) setSelectedId(replacementId);
} catch (error) {
if (isMarketBusyLeaseActive(lease)) await showPluginMarketActionError(error);
} finally {
@@ -1576,7 +1605,7 @@ export function GhostPluginPage({
// key 纳入 owner 代际:双保险。即便将来某条路径漏了上面的清空,换身份也会
// 强制卸载重建宿主(webview 连同它的 DOM/内存态一起丢),不会跨账号复用。
<GhostPagePanelHost
- key={`${panelOwnerKey}:${openPanelGhost.manifest.id}`}
+ key={`${panelOwnerKey}:${installedGhostStoragePart(openPanelGhost)}`}
ghost={openPanelGhost}
onClose={() => setOpenPanelId(null)}
/>
@@ -1611,13 +1640,13 @@ export function GhostPluginPage({
return (
<RetiredFeatureDetail
ghost={selectedGhost}
- replacement={ghosts.find((ghost) => ghost.manifest.id === target?.ghostId)}
+ replacement={findInstalledRetirementReplacement(ghosts, marketItems, target)}
busy={marketBusyId !== null}
onBack={() => setSelectedId(null)}
onReplace={() => void handleReplaceRetiredFeature()}
onDismiss={() => {
void window.electronAPI.ghosts
- .acknowledgeRetirement(selectedGhost.manifest.id)
+ .acknowledgeRetirement(installedGhostStoragePart(selectedGhost))
.then(() => setSelectedId(null))
.catch(() => toast.error(t('settings.ghosts.retirement.saveFailed')));
}}
@@ -1638,7 +1667,7 @@ export function GhostPluginPage({
panelStatus={panelStatus}
enabledOverride={
selectedGhost
- ? effectiveEnabled(selectedGhost.manifest.id, selectedGhost.enabled)
+ ? effectiveEnabled(installedGhostStoragePart(selectedGhost), selectedGhost.enabled)
: undefined
}
onBack={() => {
@@ -1657,10 +1686,8 @@ export function GhostPluginPage({
updateVersion={selectedMarketUpdate?.version}
updateBusy={(selectedMarketUpdate !== null && marketBusyId !== null) || batchRunning}
onUninstall={() => void handleUninstall()}
- // 官方保留前缀(cindy-/filo-/xd-)的插件走本地装入会被拒,
- // 导出产物无法重装,不提供导出项。
onExport={
- selectedGhost && !isOfficialGhostId(selectedDetail.id)
+ selectedGhost && !isUserInstallReservedGhostId(selectedDetail.ghostId)
? () => void handleExport()
: undefined
}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
index 8c371f0464..ed301eacc5 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostMainViewHost.test.tsx
@@ -2,6 +2,7 @@
import { render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { InstalledGhost } from '../../../../shared/ghost';
const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
@@ -25,7 +26,9 @@ vi.mock('@/cindy-brain/runtimeStates', () => ({
useGhostRuntimeState: () => mocks.runtimeState,
}));
vi.mock('@/cindy-brain/ghostPanelBody', () => ({
- GhostWebviewBody: ({ html }: { html?: string }) => <div data-testid="webview">{html}</div>,
+ GhostWebviewBody: ({ html, ghost }: { html?: string; ghost: InstalledGhost }) => (
+ <div data-testid="webview" data-dir={ghost.dir}>{html}</div>
+ ),
GhostPanelError: ({ state }: { state: string }) => <div data-testid="error">{state}</div>,
}));
vi.mock('@/features/cc-agent/useRegisterCCAgentSidebar', () => ({
@@ -60,6 +63,7 @@ beforeEach(() => {
mocks.routeCapable = [
{
ghostId: 'workspace',
+ instanceId: 'workspace',
title: 'Workspace',
manifest,
installedGhost: {
@@ -86,6 +90,71 @@ describe('GhostMainViewHost', () => {
expect(mocks.navigate).toHaveBeenCalledWith('/plugins', { replace: true });
});
+ it('does not resolve an absent physical route to a same-name organization instance', () => {
+ mocks.routeCapable = [{
+ ghostId: 'workspace',
+ instanceId: '_ns__acme__workspace',
+ title: 'Organization Workspace',
+ manifest,
+ installedGhost: {
+ manifest,
+ namespace: 'acme',
+ dir: '/plugins/_ns/acme/workspace',
+ enabled: true,
+ approval: { state: 'approved', revision: 'organization-revision' },
+ },
+ }];
+ render(<GhostMainViewHost />);
+
+ expect(screen.queryByTestId('webview')).toBeNull();
+ expect(mocks.navigate).toHaveBeenCalledWith('/plugins', { replace: true });
+ });
+
+ it('leaves the route when its original instance is disabled instead of switching to its twin', () => {
+ const organization = {
+ ghostId: 'workspace',
+ instanceId: '_ns__acme__workspace',
+ title: 'Organization Workspace',
+ manifest,
+ installedGhost: {
+ manifest,
+ namespace: 'acme',
+ dir: '/plugins/_ns/acme/workspace',
+ enabled: true,
+ approval: { state: 'approved', revision: 'organization-revision' },
+ },
+ };
+ mocks.routeCapable.push(organization);
+ const { rerender } = render(<GhostMainViewHost />);
+ expect(screen.getByTestId('webview').getAttribute('data-dir')).toBe('/plugins/workspace');
+
+ mocks.routeCapable = [organization];
+ rerender(<GhostMainViewHost />);
+
+ expect(screen.queryByTestId('webview')).toBeNull();
+ expect(mocks.navigate).toHaveBeenCalledWith('/plugins', { replace: true });
+ });
+
+ it.each([
+ ['workspace', 'acme', '/plugins/workspace'],
+ ['_ns__acme__workspace', 'acme', '/plugins/_ns/acme/workspace'],
+ ['_root__workspace', null, '/plugins/_ns/_root/workspace'],
+ ] as const)('opens the physical route %s without changing its namespace', (instanceId, namespace, dir) => {
+ mocks.ghostId = instanceId;
+ mocks.routeCapable = [{
+ ghostId: 'workspace',
+ instanceId,
+ title: 'Workspace',
+ manifest,
+ installedGhost: { manifest, namespace, dir, enabled: true,
+ approval: { state: 'approved', revision: 'revision' } },
+ }];
+ render(<GhostMainViewHost />);
+
+ expect(screen.getByTestId('webview').getAttribute('data-dir')).toBe(dir);
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
it('unmounts the webview and replaces the route when capability is revoked in place', () => {
const { rerender } = render(<GhostMainViewHost />);
expect(screen.getByTestId('webview')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index 777c4cca72..7e95b4857f 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -163,6 +163,7 @@ describe('shouldOpenInstalledDetailAfterMarketSuccess', () => {
const commandPlugin: GhostPluginListItem = {
id: 'filo-google',
+ ghostId: 'filo-google',
name: 'Filo Google',
description: 'Google services',
version: '1.0.0',
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index d31c67e182..539afcbafe 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -6,6 +6,7 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
import type { InstalledGhost } from '../../../../shared/ghost';
const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
@@ -97,7 +98,7 @@ import {
ToolDescriptionChip,
ToolsSection,
} from '../GhostPluginDetailView';
-import type { GhostPluginDetail } from '../lib/ghostPluginViewModel';
+import { toGhostPluginDetail, type GhostPluginDetail } from '../lib/ghostPluginViewModel';
const permissions: GhostPermissionItem[] = [
{
@@ -136,6 +137,7 @@ const permissions: GhostPermissionItem[] = [
const detail: GhostPluginDetail = {
id: 'builtin.example',
+ ghostId: 'builtin.example',
name: 'Example',
description: 'Example plugin',
version: '1.2.3',
@@ -198,7 +200,7 @@ describe('Ghost plugin detail sections', () => {
ghost={
{ manifest: { id: 'cindy-github' }, enabled: true, trust: { level: 'unverified' } } as any
}
- detail={{ ...detail, id: 'cindy-github', hasSettingsUi: true }}
+ detail={{ ...detail, id: 'cindy-github', ghostId: 'cindy-github', hasSettingsUi: true }}
panelStatus={null}
onBack={vi.fn()}
onToggle={vi.fn()}
@@ -211,9 +213,12 @@ describe('Ghost plugin detail sections', () => {
);
expect(verify).not.toHaveBeenCalled();
});
- it.each([{ status: 'missing' }, { status: 'auth', source: 'token' }])(
- 'connects GitHub from $status and reloads the installed plugin settings after authorization',
- async (connection) => {
+ it.each([
+ { layout: 'legacy', connection: { status: 'missing' } },
+ { layout: 'root', connection: { status: 'auth', source: 'token' } },
+ ])(
+ 'connects GitHub in $layout layout and reloads settings after authorization',
+ async ({ layout, connection }) => {
vi.stubGlobal(
'ResizeObserver',
class {
@@ -230,16 +235,19 @@ describe('Ghost plugin detail sections', () => {
startGithubSetup: async () => ({ phase: 'connected' }),
},
});
+ const ghost: InstalledGhost = {
+ manifest: { schemaVersion: 3, minCindyVersion: '0.1.0', kind: 'chip',
+ id: 'cindy-github', name: 'GitHub', version: '1.0.0', entry: 'main.js', settingsHtml: 'settings.html' },
+ dir: path.join('plugins', ...(layout === 'root' ? ['_ns', '_root'] : []), 'cindy-github'),
+ namespace: null,
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ trust: { ...detail.trust, publisherName: 'Cindy Plugin Market' },
+ };
const { unmount } = render(
<GhostPluginDetailView
- ghost={
- {
- manifest: { id: 'cindy-github' },
- enabled: true,
- trust: { ...detail.trust, publisherName: 'Cindy Plugin Market' },
- } as any
- }
- detail={{ ...detail, id: 'cindy-github', hasSettingsUi: true }}
+ ghost={ghost}
+ detail={toGhostPluginDetail(ghost)}
panelStatus={null}
onBack={vi.fn()}
onToggle={vi.fn()}
@@ -695,13 +703,11 @@ describe('Ghost plugin detail sections', () => {
disconnect() {}
},
);
- // packaged 构建上 Main 会对 cindy- / filo- / xd- 前缀直接 GHOST_ID_RESERVED,
- // 把这个必失败动作留在菜单里等于让用户选完文件才吃错误。
// vitest 默认 DEV=true,这里显式模拟打包产物(DEV=false)。
vi.stubEnv('DEV', false);
// 显式标注类型:JSX prop 位置的内联展开会让 tsc 现推一个巨大的匿名类型,
// desktop 的 typecheck 本就贴着 CI 的 4GB 堆上限跑,能省则省。
- const officialDetail: GhostPluginDetail = { ...detail, id: 'cindy-art' };
+ const officialDetail: GhostPluginDetail = { ...detail, id: 'cindy-art', ghostId: 'cindy-art' };
render(
<GhostPluginDetailView
ghost={null}
@@ -730,42 +736,48 @@ describe('Ghost plugin detail sections', () => {
vi.unstubAllEnvs();
});
- it('keeps the local .cindy update entry for ordinary third-party plugins', async () => {
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- },
- );
- // 同样是打包产物,但非保留前缀:Main 不会拒,入口必须留着。
- vi.stubEnv('DEV', false);
- render(
- <GhostPluginDetailView
- ghost={null}
- detail={detail}
- panelStatus={null}
- onBack={vi.fn()}
- onToggle={vi.fn()}
- onUse={vi.fn()}
- onUpdate={vi.fn()}
- onUpdateFromFile={vi.fn()}
- onUninstall={vi.fn()}
- toggleDisabled={false}
- />,
- );
+ it.each(['builtin.example', 'xd-ordinary', 'filo-ordinary'])(
+ 'keeps the local .cindy update entry actionable for ordinary root %s',
+ async (ghostId) => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ vi.stubEnv('DEV', false);
+ const onUpdateFromFile = vi.fn();
+ const ordinaryDetail: GhostPluginDetail = { ...detail, id: ghostId, ghostId };
+ render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={ordinaryDetail}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={onUpdateFromFile}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
- fireEvent.pointerDown(
- screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
- { button: 0, ctrlKey: false },
- );
- expect(
- screen.getByRole('menuitem', { name: 'settings.ghosts.detail.updateFromFile' }),
- ).toBeTruthy();
- expect(screen.getByRole('separator')).toBeTruthy();
- vi.unstubAllEnvs();
- });
+ fireEvent.pointerDown(
+ screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
+ { button: 0, ctrlKey: false },
+ );
+ const updateItem = screen.getByRole('menuitem', {
+ name: 'settings.ghosts.detail.updateFromFile',
+ });
+ expect(screen.getByRole('separator')).toBeTruthy();
+ fireEvent.click(updateItem);
+ expect(onUpdateFromFile).toHaveBeenCalledOnce();
+ vi.unstubAllEnvs();
+ },
+ );
it('renders an export menu item only when onExport is provided', async () => {
vi.stubGlobal(
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
index a880c2d517..d87469884d 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
@@ -3,8 +3,10 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, useNavigate } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
import type { PluginMarketDetail } from '../../../../shared/pluginMarket';
+import type { InstalledGhost } from '../../../../shared/ghost';
import { __resetInstalledGhostsStoreForTest } from '@/cindy-brain/useInstalledGhosts';
import {
cancelPendingPluginSuggestion,
@@ -15,7 +17,8 @@ import {
} from '@/features/cc-agent/pendingPluginSuggestion';
import { GhostPluginPage } from '../GhostPluginPage';
-const { auth, translation } = vi.hoisted(() => ({
+const { auth, translation, pickAndUpdateGhost } = vi.hoisted(() => ({
+ pickAndUpdateGhost: vi.fn(),
auth: { user: { membershipKind: 'personal' }, mode: 'local', dataOwnerId: 'navigation-owner' },
translation: {
t: (key: string) => key,
@@ -30,6 +33,10 @@ vi.mock('../GhostPagePanelHost', () => ({
}));
vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => auth }));
+vi.mock('@/cindy-brain/installFlow', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/cindy-brain/installFlow')>()),
+ pickAndUpdateGhost,
+}));
vi.mock('react-i18next', async (importOriginal) => ({
...(await importOriginal<typeof import('react-i18next')>()),
useTranslation: () => translation,
@@ -87,6 +94,7 @@ beforeEach(() => {
cancelPendingPluginSuggestion();
__resetInstalledGhostsStoreForTest();
loadDetail.mockReset().mockResolvedValue(detail);
+ pickAndUpdateGhost.mockReset().mockResolvedValue(undefined);
vi.stubGlobal('electronAPI', {
platform: 'win32',
sidebarSettings: {
@@ -118,6 +126,7 @@ afterEach(() => {
cancelPendingPluginSuggestion();
__resetInstalledGhostsStoreForTest();
vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
});
function RetirementNavigation() {
@@ -149,6 +158,54 @@ async function openFromCatalog() {
}
describe('plugin page return navigation', () => {
+ it.each(['xd-ordinary', 'filo-ordinary'])(
+ 'updates an ordinary root %s from a local file and offers export in packaged builds',
+ async (ghostId) => {
+ vi.stubEnv('DEV', false);
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const installed: InstalledGhost = {
+ manifest: { ...detail.manifest, id: ghostId, name: ghostId },
+ dir: '/tmp/brain/' + ghostId,
+ namespace: null,
+ enabled: true,
+ approval: { state: 'approved', revision: 'ordinary-root-revision' },
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ };
+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });
+ window.electronAPI.pluginMarket.snapshot = async () => ({
+ items: [],
+ unavailableReason: null,
+ customSourceNames: [],
+ unavailableCustomSourceNames: [],
+ });
+ render(page('/plugins?ghost=' + ghostId));
+ await screen.findByRole('button', { name: 'settings.ghosts.detail.backToList' });
+ fireEvent.pointerDown(
+ screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
+ { button: 0, ctrlKey: false },
+ );
+ expect(
+ screen.getByRole('menuitem', { name: 'settings.ghosts.detail.exportPackage' }),
+ ).toBeTruthy();
+ fireEvent.click(
+ screen.getByRole('menuitem', { name: 'settings.ghosts.detail.updateFromFile' }),
+ );
+ expect(pickAndUpdateGhost).toHaveBeenCalledWith(ghostId, { t: translation.t });
+ },
+ );
+
it.each(['button', 'Escape'] as const)(
'%s cancels the recommendation and restores the catalog scroll position',
async (method) => {
@@ -305,18 +362,70 @@ describe('retirement migration from the original plugin', () => {
expect(document.querySelector('webview')).toBeNull();
});
- it('enables an existing replacement without reinstalling it', async () => {
- const bridge = installFixture([old, replacement]);
+ it.each(['legacy', 'root'] as const)('enables the %s replacement without reinstalling it', async (layout) => {
+ const instanceId = layout === 'root' ? '_root__baguette-simulator' : 'baguette-simulator';
+ const installed = { ...replacement, namespace: null,
+ dir: path.join('plugins', ...(layout === 'root' ? ['_ns', '_root'] : []), 'baguette-simulator') };
+ const bridge = installFixture([old, installed]);
+ vi.mocked(bridge.ghosts.setEnabled).mockImplementation(async (id) => {
+ if (id !== instanceId) throw new Error('[NOT_FOUND] Wrong plugin instance');
+ return { ok: true };
+ });
render(page('/plugins?retired=ios-simulator'));
fireEvent.click(
await screen.findByRole('button', { name: 'settings.ghosts.retirement.enable' }),
);
await waitFor(() =>
- expect(bridge.ghosts.setEnabled).toHaveBeenCalledWith('baguette-simulator', true),
+ expect(bridge.ghosts.setEnabled).toHaveBeenCalledWith(instanceId, true,
+ 'approved:' + installed.approval.revision),
);
expect(loadDetail).not.toHaveBeenCalled();
});
+ it('enables the market-matched organization replacement instead of its root sibling', async () => {
+ const root = { ...replacement, namespace: null, enabled: true, dir: 'plugins/baguette-simulator' };
+ const organization = {
+ ...replacement,
+ namespace: 'acme',
+ enabled: false,
+ dir: 'plugins/_ns/acme/baguette-simulator',
+ };
+ const bridge = installFixture([old, root, organization]);
+ const marketReplacement = {
+ ...detail,
+ pluginId: 'cb93909aaa6ac600bbc2f6b8a',
+ ghostId: 'baguette-simulator',
+ name: 'Baguette',
+ namespace: 'acme',
+ scope: 'organization' as const,
+ organizationId: 'org-acme',
+ installState: 'installed' as const,
+ enabled: false,
+ manifest: replacement.manifest,
+ };
+ bridge.pluginMarket.snapshot = async () => ({
+ items: [marketReplacement],
+ unavailableReason: null,
+ customSourceNames: [],
+ unavailableCustomSourceNames: [],
+ });
+ vi.mocked(bridge.ghosts.setEnabled).mockImplementation(async (id) => {
+ if (id !== '_ns__acme__baguette-simulator') throw new Error('[NOT_FOUND] Wrong plugin instance');
+ return { ok: true };
+ });
+ render(page('/plugins?retired=ios-simulator'));
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'settings.ghosts.retirement.enable' }),
+ );
+ await waitFor(() =>
+ expect(bridge.ghosts.setEnabled).toHaveBeenCalledWith(
+ '_ns__acme__baguette-simulator',
+ true,
+ 'approved:' + organization.approval.revision,
+ ),
+ );
+ });
+
it('opens an enabled replacement panel from the retirement notice', async () => {
installFixture([old, {
...replacement, enabled: true,
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
index f7117dcc99..49a106c703 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
@@ -14,12 +14,14 @@ vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
let installedGhosts: Array<{
manifest: GhostManifest;
approval?: GhostInstallApproval;
+ namespace?: string | null;
+ dir?: string;
}> = [];
vi.mock('@/cindy-brain/useInstalledGhosts', () => ({
readInstalledGhostsSnapshot: () =>
installedGhosts.map((ghost) => ({
...ghost,
- dir: 'C:/test/ghost',
+ dir: ghost.dir ?? `C:/test/${ghost.manifest.id}`,
enabled: true,
approval: ghost.approval ?? {
state: 'approved',
@@ -277,6 +279,101 @@ describe('updateAllController', () => {
expect(toast.success).toHaveBeenCalledTimes(1);
});
+
+ it('updates the physical root when a namespaced twin shares the ghostId', async () => {
+ const namespacedApproval = {
+ state: 'approved' as const,
+ revision: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
+ };
+ installedGhosts = [
+ {
+ manifest: manifest({ version: '9.0.0' }),
+ namespace: 'xd',
+ dir: 'C:/test/_ns/xd/ghost-a',
+ approval: namespacedApproval,
+ },
+ { manifest: manifest({ version: '1.0.0' }), dir: 'C:/test/ghost-a' },
+ ];
+
+ startUpdateAllBatch([marketItem()]);
+ await waitForFinishedBatch();
+
+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
+ status: 'done',
+ fromVersion: '1.0.0',
+ });
+ expect(installMock).toHaveBeenCalledTimes(1);
+ expect(installMock.mock.calls[0]?.[1]).toMatchObject({
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
+ });
+ });
+
+ it('updates the namespaced instance for an organization market row', async () => {
+ const namespacedApproval = {
+ state: 'approved' as const,
+ revision: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
+ };
+ installedGhosts = [
+ { manifest: manifest({ version: '1.0.0' }), dir: 'C:/test/ghost-a' },
+ {
+ manifest: manifest({ version: '9.0.0' }),
+ namespace: 'xd',
+ dir: 'C:/test/_ns/xd/ghost-a',
+ approval: namespacedApproval,
+ },
+ ];
+ detailMock.mockResolvedValue(
+ detail({
+ pluginId: 'plugin-org',
+ namespace: 'xd',
+ scope: 'organization',
+ version: '9.1.0',
+ releaseId: 'release-org',
+ }),
+ );
+
+ startUpdateAllBatch([
+ marketItem({
+ pluginId: 'plugin-org',
+ namespace: 'xd',
+ scope: 'organization',
+ version: '9.1.0',
+ releaseId: 'release-org',
+ }),
+ ]);
+ await waitForFinishedBatch();
+
+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
+ status: 'done',
+ fromVersion: '9.0.0',
+ });
+ expect(installMock.mock.calls[0]).toEqual([
+ 'plugin-org',
+ {
+ expectedReleaseId: 'release-org',
+ expectedManifest: manifest({ version: '9.1.0' }),
+ expectedInstalledApproval: 'approved:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
+ allowSourceReplacement: false,
+ },
+ ]);
+ });
+
+ it('skips a public update when only a namespaced twin is installed', async () => {
+ installedGhosts = [
+ {
+ manifest: manifest({ version: '9.0.0' }),
+ namespace: 'xd',
+ dir: 'C:/test/_ns/xd/ghost-a',
+ },
+ ];
+
+ startUpdateAllBatch([marketItem()]);
+ await waitForFinishedBatch();
+
+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');
+ expect(installMock).not.toHaveBeenCalled();
+ });
+
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;
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
index a3b3e1f0cf..2a3aa4528f 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
@@ -49,8 +49,8 @@ describe('buildUpdateAllRows', () => {
marketItem({ pluginId: 'p4', ghostId: 'g4', version: '0.2.0' }),
],
new Map([
- ['g1', '1.0.0'],
- ['g4', '0.1.0'],
+ ['p1', '1.0.0'],
+ ['p4', '0.1.0'],
]),
);
@@ -61,6 +61,12 @@ describe('buildUpdateAllRows', () => {
toVersion: '2.0.0',
status: 'pending',
});
+ expect(rows[0]).not.toHaveProperty('namespace');
+ const namespaced = buildUpdateAllRows(
+ [marketItem({ pluginId: 'org-helper', ghostId: 'helper', namespace: 'xd' })],
+ new Map([['org-helper', '1.0.0']]),
+ );
+ expect(namespaced[0]).toMatchObject({ ghostId: 'helper', namespace: 'xd' });
});
});
@@ -107,6 +113,12 @@ describe('updateRoundKey', () => {
expect(
updateRoundKey([...a, marketItem({ ghostId: 'g9', installState: 'installed' })]),
).toBe(updateRoundKey(a));
+ const sameGhost = [
+ marketItem({ pluginId: 'public-helper', ghostId: 'helper', version: '1.1.0' }),
+ marketItem({ pluginId: 'org-helper', ghostId: 'helper', version: '1.1.0' }),
+ ];
+ expect(updateRoundKey(sameGhost)).toContain('public-helper');
+ expect(updateRoundKey(sameGhost)).toContain('org-helper');
});
});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts
index 0b7dd0a4b9..146be1ff4c 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import i18n from '../../../../i18n';
-import { GHOST_OFFICIAL_ID_PREFIXES } from '../../../../../shared/ghost';
+import { GHOST_OFFICIAL_ID_PREFIX } from '../../../../../shared/ghost';
import { pluginMarketErrorKey } from '../pluginMarketErrorKey';
function serializedIpcError(code: string): Error {
@@ -64,7 +64,7 @@ describe('pluginMarketErrorKey', () => {
// The raw resource check excludes a missing locale being hidden by English fallback.
expect(rawMessage).toEqual(expect.any(String));
// These assertions exclude a broken defaultVariables path leaving a literal placeholder.
- expect(message).toContain(GHOST_OFFICIAL_ID_PREFIXES.join(' / '));
+ expect(message).toContain(GHOST_OFFICIAL_ID_PREFIX);
expect(message).not.toContain('{{');
// This excludes the market channel silently falling back to its generic retry toast.
expect(message).not.toBe(i18n.getFixedT(locale)('settings.ghosts.market.errors.generic'));
diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
index c53f31b335..02aa597a38 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
@@ -4,6 +4,9 @@ import {
canOfferMarketInstall,
ghostReapprovalRoute,
marketReviewTargetsInstalledGhost,
+ findInstalledGhostForMarketItem,
+ marketItemForInstalledGhost,
+ marketItemMatchesInstalledGhost,
orderPluginCatalogItems,
pluginPresentationOrigin,
pluginUpdateForInstalledVersion,
@@ -205,6 +208,80 @@ describe('orderPluginCatalogItems', () => {
});
});
+describe('market instance identity', () => {
+ type InstalledIdentity = Parameters<typeof marketItemMatchesInstalledGhost>[1];
+ const root = { manifest: { id: 'helper' }, dir: '/ghosts/helper' };
+ const knownRoot = { ...root, namespace: null };
+ const rootWithoutDirectory = { manifest: { id: 'helper' }, namespace: null };
+ const freshRoot = { ...knownRoot, dir: '/ghosts/_ns/_root/helper' };
+ const namespaced = {
+ ...root,
+ namespace: 'xd',
+ dir: '/ghosts/_ns/xd/helper',
+ };
+ const inPlace = { ...root, namespace: 'xd' };
+ const publicRow = { ghostId: 'helper' };
+ const explicitRoot = { ...publicRow, namespace: null };
+ const organizationRow = { ...publicRow, namespace: 'xd' };
+
+ it.each([
+ ['organization row', [namespaced, root], organizationRow, namespaced],
+ ['legacy row', [namespaced, root], publicRow, root],
+ ['legacy stamped row', [inPlace], publicRow, inPlace],
+ ['no physical root', [namespaced], publicRow, undefined],
+ ['fresh root beside stamped twin', [inPlace, freshRoot], explicitRoot, freshRoot],
+ ['fresh root alone', [freshRoot], explicitRoot, freshRoot],
+ ['stamped twin is not root', [inPlace], explicitRoot, undefined],
+ ['known root for legacy row', [namespaced, knownRoot], publicRow, knownRoot],
+ ['known root for explicit row', [namespaced, knownRoot], explicitRoot, knownRoot],
+ ['unstamped install is not organization', [root], organizationRow, undefined],
+ ['root without directory', [rootWithoutDirectory], explicitRoot, rootWithoutDirectory],
+ ['known namespace mismatch without directory', [{ manifest: { id: 'helper' }, namespace: 'xd' }], explicitRoot, undefined],
+ ] as const)('binds only the intended instance for %s', (_label, ghosts, item, expected) => {
+ expect(findInstalledGhostForMarketItem<InstalledIdentity>(ghosts, item)).toBe(expected);
+ for (const ghost of ghosts) {
+ expect(marketItemMatchesInstalledGhost(item, ghost)).toBe(ghost === expected);
+ }
+ });
+});
+
+describe('marketItemForInstalledGhost', () => {
+ const pending = { manifest: { id: 'helper' }, dir: '/ghosts/helper' };
+ const stampedInPlace = { ...pending, namespace: 'xd' };
+
+ it('keeps a pending legacy install local when a same-name organization market item is not installed', () => {
+ const organization = { ...marketItem('organization', 'helper', 'not-installed'),
+ scope: 'organization' as const, namespace: 'xd' };
+ expect(marketItemForInstalledGhost([organization], pending)).toBeNull();
+ expect(pluginPresentationOrigin(marketItemForInstalledGhost([organization], pending))).toBe('local');
+ });
+
+ it('does not let an uninstalled organization listing shadow a verified root route', () => {
+ const organization = { ...marketItem('organization', 'helper', 'not-installed'),
+ scope: 'organization' as const, namespace: 'xd' };
+ const root = { ...marketItem('root', 'helper', 'installed'), namespace: null };
+ expect(marketItemForInstalledGhost([organization, root], pending)).toBe(root);
+ expect(pluginPresentationOrigin(marketItemForInstalledGhost([organization, root], pending))).toBe('public');
+ });
+
+ it('does not use an unverified root route even when it points to the same directory', () => {
+ const root = marketItem('root', 'helper', 'not-installed');
+ expect(marketItemForInstalledGhost([root], pending)).toBeNull();
+ });
+
+ it('keeps a verified legacy market route for an in-place stamped organization plugin', () => {
+ const legacy = marketItem('legacy', 'helper', 'update-available');
+ expect(marketItemForInstalledGhost([legacy], stampedInPlace)).toBe(legacy);
+ });
+
+ it('requires logical identity for a known-namespace installed route', () => {
+ const organization = { ...marketItem('organization', 'helper', 'installed'),
+ scope: 'organization' as const, namespace: 'xd' };
+ expect(marketItemForInstalledGhost([organization], pending)).toBeNull();
+ expect(marketItemForInstalledGhost([organization], stampedInPlace)).toBe(organization);
+ });
+});
+
describe('canOfferMarketInstall', () => {
it('hides install for signed-out browsing and local account-managed plugins', () => {
expect(canOfferMarketInstall('signed-out', 'cindy-test')).toBe(false);
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index e316bd62bd..a1fa649ff4 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -15,7 +15,9 @@ import {
type GhostToolDecl,
type InstalledGhost,
} from '../../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../../shared/pluginIdentity';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
+import { marketItemMatchesInstalledGhost } from './pluginMarketPresentation';
/**
* cindy 详单里**可钉后端**的类目 —— 详情页给每个申请到的动作渲染一行模型选择。
@@ -29,7 +31,10 @@ import type { PluginMarketItem } from '../../../../shared/pluginMarket';
const PINNABLE_CINDY_CATEGORIES = ['image', 'video', 'text', 'embed'] as const;
export interface GhostPluginListItem {
+ /** Instance key (storage part). Use this for enable/uninstall/panel IPC. */
id: string;
+ /** Logical plugin id from the manifest. */
+ ghostId: string;
name: string;
description: string;
version: string;
@@ -107,7 +112,7 @@ export interface GhostPluginMarketPresentation {
export function marketPresentationForInstalledGhost(
ghost: Pick<InstalledGhost, 'manifest' | 'iconDataUrl'>,
marketItem:
- | Pick<
+ | (Pick<
PluginMarketItem,
| 'ghostId'
| 'installState'
@@ -117,13 +122,14 @@ export function marketPresentationForInstalledGhost(
| 'author'
| 'icon'
| 'sourceType'
- >
+ > &
+ Pick<PluginMarketItem, 'namespace'>)
| null
| undefined,
): GhostPluginMarketPresentation | null {
if (
!marketItem ||
- marketItem.ghostId !== ghost.manifest.id ||
+ !marketItemMatchesInstalledGhost(marketItem, ghost) ||
marketItem.installState !== 'installed' ||
marketItem.version !== ghost.manifest.version
) {
@@ -168,7 +174,7 @@ export function filterGhostPluginItems<T extends GhostPluginListItem>(
): T[] {
const normalizedQuery = query.trim().toLocaleLowerCase();
return items.filter((item) =>
- `${item.name} ${item.description} ${item.id}`.toLocaleLowerCase().includes(normalizedQuery),
+ `${item.name} ${item.description} ${item.ghostId} ${item.id}`.toLocaleLowerCase().includes(normalizedQuery),
);
}
@@ -269,7 +275,8 @@ export function toGhostPluginListItem(
iconDataUrl: ghost.iconDataUrl,
};
return {
- id: manifest.id,
+ id: installedGhostStoragePart(ghost),
+ ghostId: manifest.id,
name: display.name,
description: display.description,
version: manifest.version,
diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
index 16cb2f963e..23c60865ef 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
@@ -6,6 +6,12 @@
* An installed Ghost without a matching market record remains local.
*/
import { isCindyAccountGhostId, type GhostInstallApproval } from '../../../../shared/ghost';
+import {
+ createPluginLogicalIdentity,
+ findInstalledGhostByIdentity,
+ hasDeliveryNamespace,
+ installedGhostStoragePart,
+} from '../../../../shared/pluginIdentity';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
export type PluginPresentationOrigin = 'public' | 'organization' | 'local' | 'custom';
@@ -75,6 +81,54 @@ export function ghostReapprovalRoute(
: 'local-package';
}
+/**
+ * Bind a market row to the installed instance it is allowed to update.
+ *
+ * An explicit namespace must hit that logical identity. A legacy row
+ * (missing namespace) binds the physical root, including an
+ * in-place stamped plugin whose storage part is still the bare ghostId. It must
+ * not fall through to a `_ns/...` twin.
+ */
+export function findInstalledGhostForMarketItem<
+ T extends {
+ manifest: { id: string };
+ dir?: string;
+ namespace?: string | null;
+ },
+>(ghosts: readonly T[], item: Pick<PluginMarketItem, 'ghostId' | 'namespace'>): T | undefined {
+ const sameId = ghosts.filter((ghost) => ghost.manifest.id === item.ghostId);
+ if (sameId.length === 0) return undefined;
+ if (hasDeliveryNamespace(item)) {
+ return findInstalledGhostByIdentity(
+ sameId,
+ createPluginLogicalIdentity(item.namespace, item.ghostId),
+ );
+ }
+ return sameId.find((ghost) => installedGhostStoragePart(ghost) === item.ghostId);
+}
+
+/** True when this market row is the update/origin route for this installed instance. */
+export function marketItemMatchesInstalledGhost(
+ item: Pick<PluginMarketItem, 'ghostId' | 'namespace'>,
+ ghost: { manifest: { id: string }; dir?: string; namespace?: string | null },
+): boolean {
+ if (item.ghostId !== ghost.manifest.id) return false;
+ if (hasDeliveryNamespace(item) && hasDeliveryNamespace(ghost)) {
+ return item.namespace === ghost.namespace;
+ }
+ if (hasDeliveryNamespace(item) && item.namespace !== null) return false;
+ return installedGhostStoragePart(ghost) === item.ghostId;
+}
+
+export function marketItemForInstalledGhost(
+ items: readonly PluginMarketItem[],
+ ghost: { manifest: { id: string }; dir?: string; namespace?: string | null },
+): PluginMarketItem | null {
+ return items.find((item) =>
+ (item.installState === 'installed' || item.installState === 'update-available') &&
+ marketItemMatchesInstalledGhost(item, ghost)) ?? null;
+}
+
/**
* Keeps the complete catalog in server order while rendering an installed card
* for market records already owned by this client. Local-only installs have no
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
index cef61442b6..1f5699e137 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
@@ -17,7 +17,9 @@ import {
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
import { ghostInstallApprovalToken } from '../../../../shared/ghost';
import { extractIpcError } from '@/utils/ipcError';
+import { deliveryNamespaceFields } from '../../../../shared/pluginIdentity';
import { pluginMarketErrorKey } from './pluginMarketErrorKey';
+import { findInstalledGhostForMarketItem } from './pluginMarketPresentation';
import {
batchSummary,
buildUpdateAllRows,
@@ -114,13 +116,17 @@ function maybeFinishToast(): void {
export function startUpdateAllBatch(marketUpdates: readonly PluginMarketItem[]): void {
if (state.running) return;
- const installedVersionById = new Map(
- readInstalledGhostsSnapshot().map((ghost) => [ghost.manifest.id, ghost.manifest.version]),
+ const installed = readInstalledGhostsSnapshot();
+ const installedVersionByPluginId = new Map(
+ marketUpdates.map((item) => [
+ item.pluginId,
+ findInstalledGhostForMarketItem(installed, item)?.manifest.version ?? '',
+ ]),
);
finishToastShown = false;
batchOwner = getDataOwnerGeneration();
const generation = beginGeneration();
- emit({ rows: buildUpdateAllRows(marketUpdates, installedVersionById), running: false });
+ emit({ rows: buildUpdateAllRows(marketUpdates, installedVersionByPluginId), running: false });
void runQueue(generation);
}
@@ -153,8 +159,9 @@ async function runQueue(generation: number): Promise<void> {
patchRow(generation, next.pluginId, { status: 'skipped' });
continue;
}
- const installed = readInstalledGhostsSnapshot().find(
- (ghost) => ghost.manifest.id === next.ghostId,
+ const installed = findInstalledGhostForMarketItem(
+ readInstalledGhostsSnapshot(),
+ detail,
);
if (!installed) {
patchRow(generation, next.pluginId, { status: 'skipped' });
@@ -220,14 +227,19 @@ export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[]
const installStateByPluginId = new Map(
marketItems.map((item) => [item.pluginId, item.installState]),
);
- const installedById = new Map(
- readInstalledGhostsSnapshot().map((ghost) => [ghost.manifest.id, ghost.manifest]),
- );
+ const marketByPluginId = new Map(marketItems.map((item) => [item.pluginId, item]));
+ const installedGhosts = readInstalledGhostsSnapshot();
let rows = state.rows;
let changed = false;
for (const row of state.rows) {
if (row.status !== 'pending') continue;
- const installed = installedById.get(row.ghostId);
+ const installed = findInstalledGhostForMarketItem(
+ installedGhosts,
+ marketByPluginId.get(row.pluginId) ?? {
+ ghostId: row.ghostId,
+ ...deliveryNamespaceFields(row),
+ },
+ );
if (!installed) {
rows = updateRow(rows, row.pluginId, { status: 'skipped' });
changed = true;
@@ -240,8 +252,8 @@ export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[]
) {
rows = updateRow(rows, row.pluginId, { status: 'skipped' });
changed = true;
- } else if (installed.version !== row.fromVersion) {
- rows = updateRow(rows, row.pluginId, { fromVersion: installed.version });
+ } else if (installed.manifest.version !== row.fromVersion) {
+ rows = updateRow(rows, row.pluginId, { fromVersion: installed.manifest.version });
changed = true;
}
}
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
index 5bf72dbffd..40c9d21e68 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
@@ -1,12 +1,13 @@
/**
* Pure state model for the "update all plugins" batch flow.
*
- * Inputs: market items and installed Ghost manifests.
+ * Inputs: market items and installed versions keyed by market pluginId.
* Outputs: serially consumable rows whose transitions the dialog renders;
* no IPC here so the batch policy stays unit-testable.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
*/
+import { deliveryNamespaceFields } from '../../../../shared/pluginIdentity';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
/**
@@ -23,6 +24,8 @@ export type UpdateAllRowStatus =
export interface UpdateAllRow {
pluginId: string;
ghostId: string;
+ /** Present when the market row carried a known namespace; omitted stays legacy. */
+ namespace?: string | null;
name: string;
fromVersion: string;
toVersion: string;
@@ -34,15 +37,16 @@ export interface UpdateAllRow {
/** 从市场快照萃取可更新行;顺序即执行顺序(与列表快照顺序一致,稳定)。 */
export function buildUpdateAllRows(
marketItems: readonly PluginMarketItem[],
- installedVersionById: ReadonlyMap<string, string>,
+ installedVersionByPluginId: ReadonlyMap<string, string>,
): UpdateAllRow[] {
return marketItems
.filter((item) => item.installState === 'update-available')
.map((item) => ({
pluginId: item.pluginId,
ghostId: item.ghostId,
+ ...deliveryNamespaceFields(item),
name: item.name,
- fromVersion: installedVersionById.get(item.ghostId) ?? '',
+ fromVersion: installedVersionByPluginId.get(item.pluginId) ?? '',
toVersion: item.version,
status: 'pending' as const,
}));
@@ -103,7 +107,7 @@ export function ignoredRoundStorageKey(
export function updateRoundKey(marketItems: readonly PluginMarketItem[]): string {
return marketItems
.filter((item) => item.installState === 'update-available')
- .map((item) => `${item.ghostId}@${item.version}`)
+ .map((item) => `${item.pluginId}@${item.version}`)
.sort()
.join('|');
}
diff --git a/apps/desktop/src/renderer/i18n/index.ts b/apps/desktop/src/renderer/i18n/index.ts
index 69ebb1e19b..1a0ee927a0 100644
--- a/apps/desktop/src/renderer/i18n/index.ts
+++ b/apps/desktop/src/renderer/i18n/index.ts
@@ -23,7 +23,7 @@ import jaCommon from './locales/ja/common.json';
import jaAiRename from './locales/ja/aiRename.json';
import koCommon from './locales/ko/common.json';
import koAiRename from './locales/ko/aiRename.json';
-import { GHOST_OFFICIAL_ID_PREFIXES } from '../../shared/ghost';
+import { GHOST_OFFICIAL_ID_PREFIX } from '../../shared/ghost';
import { DEFAULT_LOCALE } from '../../shared/locale';
export {
@@ -105,12 +105,11 @@ void i18n.use(initReactI18next).init({
//
// pronoun:伙伴文案里指代该伙伴的第三人称。具体视图可按当前伙伴传入;这里给
// 一个通用兜底,避免漏传时把 `{{pronoun}}` 原样显示给用户。
- // 保留前缀同样只读 shared/ghost.ts 的正本。错误文案不各自枚举,
- // 新增前缀后所有装入入口会自动展示完整列表。
+ // 用户装入通道只保留 cindy-。官方运行时前缀仍在 GHOST_OFFICIAL_ID_PREFIXES。
defaultVariables: {
appName: BRAND_NAME,
pronoun: '这位伙伴',
- reservedGhostIdPrefixes: GHOST_OFFICIAL_ID_PREFIXES.join(' / '),
+ reservedGhostIdPrefixes: GHOST_OFFICIAL_ID_PREFIX,
},
},
parseMissingKeyHandler(key: string, defaultValue?: string) {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 85c4bac16e..f2e779ea26 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6066,7 +6066,7 @@
"installed": "Installed",
"replace": "Replace",
"replaceAria": "Replace {{name}} with this marketplace version",
- "replaceDescription": "A plugin with the same ID is already installed. Continuing will replace it with this marketplace version and keep its data.",
+ "replaceDescription": "A plugin with the same ID is already installed. Continuing switches its source. Existing data is kept separately; the new source does not inherit accounts or secrets and must be connected again.",
"unavailable": "The plugin market is temporarily unavailable. Installed plugins remain available.",
"customSourcesUnavailable": "These custom marketplaces are temporarily unavailable: {{names}}. Other marketplaces are unaffected.",
"authenticationRequired": "Sign in to Cindy to view the plugin market.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index b6bad0aad2..dbf2810849 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6040,7 +6040,7 @@
"installed": "インストール済み",
"replace": "置き換え",
"replaceAria": "{{name}} をこのマーケット版で置き換える",
- "replaceDescription": "同じ ID のプラグインがすでにインストールされています。続行するとこのマーケット版で置き換え、プラグインのデータは保持されます。",
+ "replaceDescription": "同じ ID のプラグインがすでにインストールされています。続行すると提供元が切り替わります。元のデータは別に保持されますが、アカウントやシークレットは引き継がれず、再接続が必要です。",
"unavailable": "プラグインマーケットを一時的に利用できません。インストール済みプラグインは引き続き利用できます。",
"customSourcesUnavailable": "次のカスタムマーケットは一時的に利用できません:{{names}}。他のマーケットには影響しません。",
"authenticationRequired": "プラグインマーケットを表示するには Cindy にログインしてください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 9fd2e7cdff..0a8db6b210 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6040,7 +6040,7 @@
"installed": "설치됨",
"replace": "교체",
"replaceAria": "{{name}}을(를) 이 마켓 버전으로 교체",
- "replaceDescription": "같은 ID의 플러그인이 이미 설치되어 있습니다. 계속하면 이 마켓 버전으로 교체하고 플러그인 데이터는 유지됩니다.",
+ "replaceDescription": "같은 ID의 플러그인이 이미 설치되어 있습니다. 계속하면 제공자가 변경됩니다. 기존 데이터는 별도로 보관되며 새 제공자는 계정과 비밀 키를 이어받지 않으므로 다시 연결해야 합니다.",
"unavailable": "플러그인 마켓을 일시적으로 사용할 수 없습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",
"customSourcesUnavailable": "다음 사용자 지정 마켓을 일시적으로 사용할 수 없습니다: {{names}}. 다른 마켓에는 영향을 주지 않습니다.",
"authenticationRequired": "플러그인 마켓을 보려면 Cindy에 로그인하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index df03560a58..8b6e006a57 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6040,7 +6040,7 @@
"installed": "已安装",
"replace": "替换",
"replaceAria": "使用此市场版本替换 {{name}}",
- "replaceDescription": "已安装相同标识的插件;继续安装会用此市场版本替换,并保留插件数据。",
+ "replaceDescription": "已安装相同标识的插件;继续安装会切换来源。原来源的数据将隔离保留,新来源不会继承原账号和密钥,需要重新连接。",
"unavailable": "插件市场暂时不可用;已安装插件仍可正常管理和使用。",
"customSourcesUnavailable": "以下自定义市场暂时不可用:{{names}}。其他市场不受影响。",
"authenticationRequired": "登录 Cindy 后才能查看插件市场。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 45c9354004..e26391c6a1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6132,7 +6132,7 @@
"customSourcesUnavailable": "以下自訂市場暫時無法存取:{{names}},其他市場不受影響。",
"replace": "取代",
"replaceAria": "以此市場版本取代 {{name}}",
- "replaceDescription": "已安裝相同 ID 的插件,繼續將以市場版本取代,原有資料會保留。"
+ "replaceDescription": "已安裝相同 ID 的插件;繼續安裝會切換來源。原來源的資料將隔離保留,新來源不會繼承原帳號和金鑰,需要重新連接。"
},
"install": "安裝插件…",
"empty": "還沒有安裝任何插件",
diff --git a/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts b/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
index 44c6763682..e658114255 100644
--- a/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
+++ b/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
@@ -18,6 +18,7 @@
import { useSyncExternalStore } from 'react';
import { GHOST_PANEL_KIND_PREFIX, type InstalledGhost } from '../../shared/ghost';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity';
const STORAGE_KEY = 'xdt:ghostPanelBubble:v1';
@@ -143,12 +144,12 @@ export function setGhostPanelBubblePosition(ghostId: string, x: number, y: numbe
* 卸载删条目;失去气泡资格(停用/无 panel/tab 形态/身份卡关按钮)强制还原。
*/
export function reconcileGhostPanelBubbles(
- ghosts: readonly Pick<InstalledGhost, 'manifest' | 'enabled'>[],
+ ghosts: readonly Pick<InstalledGhost, 'manifest' | 'enabled' | 'namespace'>[],
): void {
const cur = ensureLoaded();
const ids = Object.keys(cur);
if (ids.length === 0) return;
- const byId = new Map(ghosts.map((g) => [g.manifest.id, g]));
+ const byId = new Map(ghosts.map((g) => [installedGhostStoragePart(g), g]));
let changed = false;
const next: GhostPanelBubbleMap = { ...cur };
for (const id of ids) {
diff --git a/apps/desktop/src/renderer/lib/ghostPanelWindow.ts b/apps/desktop/src/renderer/lib/ghostPanelWindow.ts
index 5f2e4dd423..beac9b9731 100644
--- a/apps/desktop/src/renderer/lib/ghostPanelWindow.ts
+++ b/apps/desktop/src/renderer/lib/ghostPanelWindow.ts
@@ -3,10 +3,10 @@
*
* 与 sidebarWindow.ts 同款:main 的窗口工厂在启动 URL 上带
* `?ghostPanelWindow=<ghostId>`,renderer 启动时读一次;身份在窗口生命周期内
- * 不变。id 过校验(isValidGhostId)才算数,野值视同普通窗口。
+ * 不变。id 过校验(isValidPluginStoragePart)才算数,野值视同普通窗口。
*/
-import { isValidGhostId } from '../../shared/ghost';
+import { isValidPluginStoragePart } from '../../shared/pluginIdentity';
let cached: string | null | undefined;
@@ -14,7 +14,7 @@ let cached: string | null | undefined;
export function getGhostPanelWindowGhostId(): string | null {
if (cached === undefined) {
const raw = new URLSearchParams(window.location.search).get('ghostPanelWindow');
- cached = isValidGhostId(raw) ? raw : null;
+ cached = isValidPluginStoragePart(raw) ? raw : null;
}
return cached;
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f1f147440e..f14fb96da6 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1337,6 +1337,7 @@ interface ElectronAPI {
opts: {
expectedPackageSha256: string;
expectedInstalledApproval: string;
+ expectedInstalledInstanceId: string;
},
) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
/**
@@ -1397,7 +1398,10 @@ interface ElectronAPI {
/** 系统文件选择框(.cindy 过滤),只选不装;取消返回 { canceled: true }。 */
pickFile: () => Promise<{ canceled: true } | { filePath: string }>;
/** 只验不装:读出清单、签名信任等级与 icon data URL,供安装编排使用。 */
- inspect: (lizFilePath: string) => Promise<{
+ inspect: (
+ lizFilePath: string,
+ opts?: { expectedInstalledInstanceId: string; expectedInstalledApproval: string },
+ ) => Promise<{
manifest: import('../shared/ghost').GhostManifest;
trust: import('../shared/ghost').GhostTrustInfo;
/** 本次检查的整包指纹;安装/更新时回传,防止确认后文件被替换。 */
@@ -1415,7 +1419,7 @@ interface ElectronAPI {
openRetirement: (id: string) => Promise<{ ok: true }>;
onRetirementOpen: (callback: (id: string) => void) => () => void;
acknowledgeRetirement: (id: string) => Promise<{ ok: true }>;
- setEnabled: (id: string, enabled: boolean) => Promise<{ ok: true }>;
+ setEnabled: (id: string, enabled: boolean, expectedInstalledApproval?: string) => Promise<{ ok: true }>;
requestTaskApproval: (id: string) => Promise<{ granted: boolean }>;
/** 目录级禁用清单(插件页项目范围视图;sendSync 切换同帧渲染)。 */
workdirPrefsSync: (workdir: string) => { disabled: string[] };
@@ -1459,6 +1463,8 @@ interface ElectronAPI {
resolvePanelMedia: (
uri: string,
purpose?: 'attach' | 'menu',
+ instanceId?: string,
+ sourceToken?: string,
) => Promise<
| { url: string; kind?: 'image' }
| {
@@ -1478,6 +1484,7 @@ interface ElectronAPI {
callback: (payload: {
callId: string;
ghostId: string;
+ logicalGhostId?: string;
toolUseId: string | null;
/** 静态版(settle 后 / 历史回放;与落库一致)。 */
html: string;
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 4d279d1251..bf0e43d396 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -32,6 +32,7 @@ import {
ghostWebviewEntryPaths,
isGhostCallToolName,
isValidGhostId,
+ isValidNewGhostId,
isOfficialGhostId,
isUserInstallReservedGhostId,
isBrokerEligibleGhostId,
@@ -103,6 +104,13 @@ describe('ghost · id 规则', () => {
}
});
+ it('新建 id 必须以字母开头,已装的数字开头 id 仍合法', () => {
+ expect(isValidGhostId('1tool')).toBe(true);
+ expect(isValidNewGhostId('1tool')).toBe(false);
+ expect(isValidNewGhostId('tool')).toBe(true);
+ expect(isValidNewGhostId('Tool')).toBe(false);
+ });
+
it('非法:大写/下划线/路径字符/连字符开头/超长/非字符串', () => {
for (const id of [
'Hello',
@@ -122,6 +130,7 @@ describe('ghost · id 规则', () => {
it('panelKind 前缀拼接', () => {
expect(ghostPanelKind('hello')).toBe('ghost:hello');
+ expect(ghostPanelKind('_ns__acme__hello')).toBe('ghost:_ns__acme__hello');
});
it('内容清单:面板/代码/能力槽按序列出,panel 槽不重复', () => {
@@ -142,9 +151,11 @@ describe('ghost · id 规则', () => {
it('沙箱分区名:拼接与解析互逆,非意识分区/非法 id 解析为 null', () => {
expect(ghostPartition('art')).toBe('cindy-ghost-art');
expect(parseGhostPartition('cindy-ghost-art')).toBe('art');
+ expect(parseGhostPartition('cindy-ghost-_ns__acme__helper')).toBe('_ns__acme__helper');
expect(parseGhostPartition('persist:xdmaker-browser-app')).toBeNull();
expect(parseGhostPartition('cindy-ghost-')).toBeNull();
expect(parseGhostPartition('cindy-ghost-BAD_ID')).toBeNull();
+ expect(parseGhostPartition('cindy-ghost-_ns/acme/helper')).toBeNull();
expect(parseGhostPartition(undefined)).toBeNull();
});
});
@@ -1890,6 +1901,17 @@ describe('ghost · layoutWithGhostPanel(装入即停靠)', () => {
m.panel = { html: 'panel.html', position: 'tab' };
expect(layoutWithGhostPanel(createDefaultLayout(), m)).toBeNull();
});
+ it('企业实例用 storage part 作为 panelKind,不与 root 同名面板撞车', () => {
+ const m = manifest();
+ const rootLayout = layoutWithGhostPanel(createDefaultLayout(), m);
+ expect(rootLayout).not.toBeNull();
+ const next = layoutWithGhostPanel(rootLayout!, m, '_ns__acme__hello');
+ expect(next).not.toBeNull();
+ const split = next!.content as SplitNode;
+ const kinds = split.children.map((c) => (c.node.type === 'pane' ? c.node.panelKind : '?'));
+ expect(kinds).toEqual(expect.arrayContaining(['ghost:hello', 'ghost:_ns__acme__hello', 'chat-main']));
+ });
+
});
describe('ghost · keywords(语义触发扩展词表)', () => {
@@ -2897,7 +2919,7 @@ describe('ghost · 官方保留 id 前缀', () => {
expect(isOfficialGhostId('web-search')).toBe(false);
});
- it('四个官方 id 谓词对本阶段同一组输入返回完全相同的结果', () => {
+ it('历史官方名字谓词不决定普通导入准入', () => {
const cases: ReadonlyArray<readonly [id: string, expected: boolean]> = [
['cindy-art', true],
['filo-google', true],
@@ -2910,12 +2932,12 @@ describe('ghost · 官方保留 id 前缀', () => {
];
const predicates = [
isOfficialGhostId,
- isUserInstallReservedGhostId,
isBrokerEligibleGhostId,
isFirstPartyHostPrivilegeGhostId,
];
// 期望值写死,避免用任一被测谓词或同一前缀表反推 expected 后让错误实现自证正确。
for (const [id, expected] of cases) {
+ expect(isUserInstallReservedGhostId(id)).toBe(id === 'cindy-art');
for (const predicate of predicates) {
expect(predicate(id), `${predicate.name}(${JSON.stringify(id)})`).toBe(expected);
}
diff --git a/apps/desktop/src/shared/__tests__/pluginIdentity.test.ts b/apps/desktop/src/shared/__tests__/pluginIdentity.test.ts
new file mode 100644
index 0000000000..c61a2ceb94
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/pluginIdentity.test.ts
@@ -0,0 +1,458 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createPluginLogicalIdentity,
+ deliveryNamespaceFields,
+ downloadIdentityMatchesPlugin,
+ findConflictingGhostCommand,
+ findInstalledGhostByIdentity,
+ findInstalledGhostByInstanceId,
+ findInstalledRootGhostForFileImport,
+ findInstalledGhostForLocalUpdate,
+ findInstalledGhostForDeliveryTarget,
+ isGhostInstanceId,
+ formatInstalledGhostAmbiguity,
+ resolveInstalledGhost,
+ resolvePluginInstanceQuery,
+ knownDeliveryNamespacesDiffer,
+ parsePluginInstallRelId,
+ parsePluginInstanceId,
+ parsePluginStoragePart,
+ pluginInstallRelId,
+ pluginInstanceInstallRelId,
+ pluginNewInstallRelId,
+ pluginInstallStoragePart,
+ pluginLedgerRecordKey,
+ pluginStoragePart,
+ isValidPluginStoragePart,
+ installedGhostLogicalIdentity,
+ installedGhostPhysicalKeys,
+ installedGhostPhysicalRelId,
+ installedGhostMutationTargetToken,
+ installedGhostStoragePart,
+ resolvePluginLibraryStorageKey,
+ resolvePluginNamespaceState,
+ sameDeliveryNamespaceState,
+ organizationMarketPlacementError,
+ blockedInstanceRegistryMarketError,
+} from '../pluginIdentity.js';
+
+describe('plugin logical identity', () => {
+ it('gives new roots distinct physical directories and keys without changing legacy keys', () => {
+ const identity = createPluginLogicalIdentity(null, 'helper');
+ const legacy = { manifest: { id: 'helper' }, namespace: null, dir: '/ghosts/helper' };
+ const fresh = { ...legacy, dir: '/ghosts/_ns/_root/helper' };
+ expect(pluginNewInstallRelId(identity)).toBe('_ns/_root/helper');
+ expect(parsePluginInstallRelId('_ns/_root/helper')).toEqual(identity);
+ expect(parsePluginStoragePart('_root__helper')).toEqual(identity);
+ expect(pluginInstallStoragePart('_ns/_root/helper')).toBe('_root__helper');
+ expect(pluginInstanceInstallRelId('_root__helper')).toBe('_ns/_root/helper');
+ expect(installedGhostPhysicalKeys(legacy)).toEqual({ relId: 'helper', storagePart: 'helper' });
+ expect(installedGhostPhysicalKeys(fresh)).toEqual({ relId: '_ns/_root/helper', storagePart: '_root__helper' });
+ expect(installedGhostPhysicalKeys({ ...fresh, dir: 'C:\\ghosts\\_ns\\_root\\helper' }))
+ .toEqual({ relId: '_ns/_root/helper', storagePart: '_root__helper' });
+ expect(resolvePluginLibraryStorageKey('_ns/_root/helper')).toBe('_root__helper');
+ expect(findInstalledGhostByInstanceId([fresh], '_ns/_root/helper')).toBe(fresh);
+ expect(findInstalledGhostByInstanceId([fresh], '_root__helper')).toBe(fresh);
+ expect(findInstalledGhostByInstanceId([legacy], '_root__helper')).toBeUndefined();
+ expect(findInstalledGhostByInstanceId([legacy], '_ns/_root/helper')).toBeUndefined();
+ expect(parsePluginInstallRelId('_ns/_root/../helper')).toBeNull();
+ expect(parsePluginStoragePart('_root__helper__extra')).toBeNull();
+ expect(() => createPluginLogicalIdentity('_root', 'helper')).toThrow();
+ });
+ it.each(['_root/helper', '_ns/_root', '_ns/_root/helper/extra'])('rejects unsupported root directory %s', (relId) => {
+ expect(parsePluginInstallRelId(relId)).toBeNull();
+ expect(parsePluginInstanceId(relId)).toBeNull();
+ expect(pluginInstanceInstallRelId(relId)).toBeNull();
+ });
+ it('keeps missing namespace as legacy instead of silently mapping it to root', () => {
+ expect(resolvePluginNamespaceState({})).toEqual({ kind: 'legacy' });
+ expect(resolvePluginNamespaceState({ namespace: null })).toEqual({
+ kind: 'known',
+ namespace: null,
+ });
+ });
+
+ it('rejects malformed identity components', () => {
+ expect(() => createPluginLogicalIdentity('Bad Namespace', 'helper')).toThrow();
+ expect(() => createPluginLogicalIdentity(null, 'Bad Ghost Id')).toThrow();
+ });
+
+ it('keeps missing namespace off persisted records and detects known conflicts', () => {
+ expect(deliveryNamespaceFields({})).toEqual({});
+ expect(deliveryNamespaceFields({ namespace: null })).toEqual({ namespace: null });
+ expect(knownDeliveryNamespacesDiffer({ namespace: null }, { namespace: 'acme' })).toBe(true);
+ expect(knownDeliveryNamespacesDiffer({ ghostId: 'helper' }, { namespace: 'acme' })).toBe(false);
+ expect(sameDeliveryNamespaceState({}, { namespace: null })).toBe(false);
+ });
+
+ it('binds additive download identity to the selected plugin', () => {
+ const plugin = {
+ id: "c" + "p".repeat(24),
+ ghostId: 'helper',
+ namespace: 'acme' as string | null,
+ currentRelease: { id: 'release-1' },
+ };
+ const cases: [Parameters<typeof downloadIdentityMatchesPlugin>[0], boolean][] = [
+ [{}, false],
+ [{ pluginId: plugin.id, releaseId: 'release-1', ghostId: 'helper' }, false],
+ [{ pluginId: plugin.id, releaseId: 'release-1', ghostId: 'helper', namespace: 'acme' }, true],
+ [{ pluginId: plugin.id, releaseId: 'release-1', ghostId: 'helper', namespace: null }, false],
+ ];
+ const legacyPlugin = { id: plugin.id, ghostId: 'helper', currentRelease: plugin.currentRelease };
+ expect(downloadIdentityMatchesPlugin({}, legacyPlugin)).toBe(true);
+ for (const [download, expected] of cases) {
+ expect(downloadIdentityMatchesPlugin(download, plugin)).toBe(expected);
+ }
+ });
+
+ it('encodes filesystem-safe install directories without moving root installs', () => {
+ const root = createPluginLogicalIdentity(null, 'helper');
+ const enterprise = createPluginLogicalIdentity('acme', 'helper');
+ expect(pluginInstallRelId(root)).toBe('helper');
+ expect(pluginInstallRelId(enterprise)).toBe('_ns/acme/helper');
+ expect(parsePluginInstallRelId('helper')).toEqual(root);
+ expect(parsePluginInstallRelId('_ns/acme/helper')).toEqual(enterprise);
+ expect(parsePluginInstallRelId('_ns/../helper')).toBeNull();
+ expect(
+ findInstalledGhostByIdentity(
+ [
+ { manifest: { id: 'helper' } },
+ { manifest: { id: 'helper' }, namespace: 'acme' },
+ ],
+ enterprise,
+ ),
+ ).toEqual({ manifest: { id: 'helper' }, namespace: 'acme' });
+ });
+
+ it('resolves omitted namespace only when the ghostId is unique', () => {
+ const root = { manifest: { id: 'helper' }, namespace: null };
+ const enterprise = { manifest: { id: 'helper' }, namespace: 'acme' };
+ expect(resolveInstalledGhost([root], 'helper')).toEqual({ status: 'unique', ghost: root });
+ expect(resolveInstalledGhost([root, enterprise], 'helper').status).toBe('ambiguous');
+ expect(resolveInstalledGhost([root, enterprise], 'helper', null)).toEqual({
+ status: 'unique',
+ ghost: root,
+ });
+ expect(resolveInstalledGhost([root, enterprise], 'helper', 'acme')).toEqual({
+ status: 'unique',
+ ghost: enterprise,
+ });
+ expect(formatInstalledGhostAmbiguity('helper', [root, enterprise])).toContain('root/helper');
+ });
+
+ it('reports an illegal namespace as missing instead of throwing', () => {
+ expect(resolveInstalledGhost([], 'helper', 'Bad_Slug')).toEqual({ status: 'missing' });
+ expect(resolveInstalledGhost([], 'helper', '../acme')).toEqual({ status: 'missing' });
+ });
+
+ it('addresses a pending legacy install with namespace null without treating it as a delivery root', () => {
+ const pending = { manifest: { id: 'helper' }, namespaceState: 'pending' as const };
+ const enterprise = { manifest: { id: 'helper' }, namespace: 'acme' };
+ const root = { manifest: { id: 'helper' }, namespace: null };
+ expect(resolveInstalledGhost([pending], 'helper')).toEqual({ status: 'unique', ghost: pending });
+ expect(resolveInstalledGhost([pending], 'helper', null)).toEqual({ status: 'missing' });
+ expect(resolveInstalledGhost([pending, enterprise], 'helper', null)).toEqual({
+ status: 'unique', ghost: pending,
+ });
+ expect(resolveInstalledGhost([pending, root], 'helper', null)).toEqual({ status: 'unique', ghost: root });
+ expect(findInstalledGhostForDeliveryTarget([pending], { ghostId: 'helper', namespace: null }))
+ .toBeUndefined();
+ });
+
+ it('binds local updates to the selected instance even when approval states are identical', () => {
+ const root = { manifest: { id: 'helper' }, dir: '/ghosts/helper', approval: { state: 'invalid' as const } };
+ const enterprise = {
+ manifest: { id: 'helper' }, dir: '/ghosts/_ns/acme/helper', namespace: 'acme',
+ approval: { state: 'invalid' as const },
+ };
+ expect(findInstalledGhostForLocalUpdate([root, enterprise], 'helper', '_ns__acme__helper', 'invalid'))
+ .toBe(enterprise);
+ expect(findInstalledGhostForLocalUpdate([root, enterprise], 'helper', 'helper', 'invalid')).toBe(root);
+ expect(findInstalledGhostForLocalUpdate([root, enterprise], 'helper', '_ns__acme__helper', 'legacy-unapproved'))
+ .toBeUndefined();
+ expect(findInstalledGhostForLocalUpdate([root, enterprise], 'other', 'helper', 'invalid'))
+ .toBeUndefined();
+ });
+
+ it('does not let a delivery target inherit a same-name instance from another namespace', () => {
+ const root = { manifest: { id: 'helper' }, namespace: null };
+ const enterprise = { manifest: { id: 'helper' }, namespace: 'acme' };
+ const cases = [
+ [[root], { ghostId: 'helper' }, root],
+ [[root, enterprise], { ghostId: 'helper' }, undefined],
+ [[root, enterprise], { ghostId: 'helper', namespace: 'acme' }, enterprise],
+ [[root, enterprise], { ghostId: 'helper', namespace: null }, root],
+ ] as const;
+ for (const [ghosts, target, expected] of cases) {
+ expect(findInstalledGhostForDeliveryTarget(ghosts, target)).toEqual(expected);
+ }
+ });
+
+ it('encodes vault-safe storage parts without moving root files', () => {
+ const root = createPluginLogicalIdentity(null, 'helper');
+ const enterprise = createPluginLogicalIdentity('acme', 'helper');
+ expect(pluginStoragePart(root)).toBe('helper');
+ expect(pluginStoragePart(enterprise)).toBe('_ns__acme__helper');
+ expect(parsePluginStoragePart('helper')).toEqual(root);
+ expect(parsePluginStoragePart('_ns__acme__helper')).toEqual(enterprise);
+ expect(parsePluginStoragePart('_ns__/helper')).toBeNull();
+ expect(parsePluginStoragePart('_ns__acme__helper__extra')).toBeNull();
+ expect(isValidPluginStoragePart('_ns__acme__helper')).toBe(true);
+ expect(isValidPluginStoragePart('../helper')).toBe(false);
+ expect(pluginStoragePart(root)).not.toBe(pluginStoragePart(enterprise));
+ const cases = [
+ [{}, '_ns/acme/helper', '_ns__acme__helper'],
+ [{ dir: '/userData/cindy-brain/helper' }, 'helper', 'helper'],
+ [{ dir: '/userData/cindy-brain/_ns/acme/helper' }, '_ns/acme/helper', '_ns__acme__helper'],
+ ] as const;
+ for (const [physical, relId, storagePart] of cases) {
+ const ghost = { manifest: { id: 'helper' }, namespace: 'acme', ...physical };
+ expect(installedGhostPhysicalRelId(ghost)).toBe(relId);
+ expect(installedGhostStoragePart(ghost)).toBe(storagePart);
+ }
+ });
+
+ it('binds mutation tickets to the owner, physical installation and approval', () => {
+ const ghost = {
+ manifest: { id: 'helper' },
+ dir: '/userData/cindy-brain/helper',
+ namespace: 'acme',
+ approval: { state: 'approved' as const, revision: 'receipt-1' },
+ };
+ const token = installedGhostMutationTargetToken(ghost, 'owner-1');
+ expect(token).toBe(JSON.stringify([
+ 'owner-1', ghost.dir, 'helper', 'approved:receipt-1', { namespace: 'acme' },
+ ]));
+ expect(installedGhostMutationTargetToken({ ...ghost }, 'owner-1')).toBe(token);
+ expect(installedGhostMutationTargetToken(ghost, 'owner-2')).not.toBe(token);
+ for (const changed of [
+ { ...ghost, dir: '/other/cindy-brain/helper' },
+ { ...ghost, dir: '/userData/cindy-brain/_ns/acme/helper' },
+ { ...ghost, approval: { state: 'approved' as const, revision: 'receipt-2' } },
+ { ...ghost, namespace: null },
+ ]) {
+ expect(installedGhostMutationTargetToken(changed, 'owner-1')).not.toBe(token);
+ }
+ });
+
+ it('keeps legacy, root and organization distinct in mutation tickets', () => {
+ const ghost = {
+ manifest: { id: 'helper' }, dir: '/userData/cindy-brain/helper',
+ approval: { state: 'approved' as const, revision: 'receipt-1' },
+ };
+ const namespaces = [{}, { namespace: null }, { namespace: 'acme' }];
+ const tokens = namespaces.map((namespace) =>
+ installedGhostMutationTargetToken({ ...ghost, ...namespace }, 'owner-1'));
+ expect(new Set(tokens).size).toBe(3);
+ for (const state of ['legacy-unapproved', 'invalid'] as const) {
+ expect(installedGhostMutationTargetToken({ ...ghost, approval: { state } }, 'owner-1')).toBeNull();
+ }
+ });
+
+ it('addresses an in-place install by its instance key, not a logical alias', () => {
+ const stamped = {
+ manifest: { id: 'helper' }, namespace: 'acme',
+ dir: '/userData/cindy-brain/helper',
+ instanceKey: 'helper',
+ };
+ expect(findInstalledGhostByInstanceId([stamped], 'helper')).toBe(stamped);
+ expect(findInstalledGhostByInstanceId([stamped], '_ns/acme/helper')).toBeUndefined();
+ expect(findInstalledGhostByInstanceId([stamped], '_ns__acme__helper')).toBeUndefined();
+ });
+
+ it('resolves UI instance ids by physical storage part first', () => {
+ const root = {
+ manifest: { id: 'helper' },
+ namespace: null,
+ dir: '/userData/cindy-brain/helper',
+ };
+ const enterprise = {
+ manifest: { id: 'helper' },
+ namespace: 'acme',
+ dir: '/userData/cindy-brain/_ns/acme/helper',
+ };
+ const inPlace = {
+ manifest: { id: 'xd-feishu' },
+ namespace: 'xd',
+ dir: '/userData/cindy-brain/xd-feishu',
+ };
+ const ghosts = [root, enterprise, inPlace];
+
+ expect(isGhostInstanceId('helper')).toBe(true);
+ expect(isGhostInstanceId('_ns__acme__helper')).toBe(true);
+ expect(isGhostInstanceId('_ns/acme/helper')).toBe(true);
+ expect(isGhostInstanceId('../helper')).toBe(false);
+ expect(parsePluginInstanceId('helper')).toEqual({ namespace: null, ghostId: 'helper' });
+ expect(parsePluginInstanceId('_ns/acme/helper')).toEqual({ namespace: 'acme', ghostId: 'helper' });
+ expect(parsePluginInstanceId('_ns__acme__helper')).toEqual({
+ namespace: 'acme',
+ ghostId: 'helper',
+ });
+ expect(findInstalledGhostByInstanceId(ghosts, 'helper')).toBe(root);
+ expect(findInstalledGhostByInstanceId(ghosts, '_ns__acme__helper')).toBe(enterprise);
+ expect(findInstalledGhostByInstanceId(ghosts, 'xd-feishu')).toBe(inPlace);
+ });
+
+ it('does not derive physical mutation keys from an in-place logical identity', () => {
+ const inPlace = {
+ manifest: { id: 'xd-feishu' },
+ namespace: 'xd',
+ dir: '/userData/cindy-brain/xd-feishu',
+ };
+ expect(pluginInstallRelId(installedGhostLogicalIdentity(inPlace))).toBe('_ns/xd/xd-feishu');
+ expect(pluginStoragePart(installedGhostLogicalIdentity(inPlace))).toBe('_ns__xd__xd-feishu');
+ expect(installedGhostPhysicalKeys(inPlace)).toEqual({
+ relId: 'xd-feishu',
+ storagePart: 'xd-feishu',
+ });
+ expect(
+ installedGhostPhysicalKeys({
+ manifest: { id: 'helper' },
+ namespace: 'acme',
+ dir: '/userData/cindy-brain/_ns/acme/helper',
+ }),
+ ).toEqual({
+ relId: '_ns/acme/helper',
+ storagePart: '_ns__acme__helper',
+ });
+ });
+
+
+ it('uses JSON-safe ledger keys that distinguish same-name identities', () => {
+ expect(pluginLedgerRecordKey({ ghostId: 'helper' })).toBe('helper');
+ expect(pluginLedgerRecordKey({ ghostId: 'helper', namespace: null })).toBe('helper');
+ expect(pluginLedgerRecordKey({ ghostId: 'helper', namespace: 'acme' })).toBe(
+ '_ns__acme__helper',
+ );
+ });
+
+ it('only treats the same command as a conflict inside one namespace', () => {
+ const root = { manifest: { id: 'helper', command: 'Draw' }, namespace: null as string | null };
+ const org = {
+ manifest: { id: 'helper', command: 'draw' },
+ namespace: 'acme',
+ dir: '/brain/_ns/acme/helper',
+ };
+ expect(
+ findConflictingGhostCommand([root], 'Draw', { incomingNamespace: 'acme' }),
+ ).toBeUndefined();
+ expect(findConflictingGhostCommand([root], 'Draw', { incomingNamespace: null })).toBe(root);
+ expect(
+ findConflictingGhostCommand([root, org], 'Draw', {
+ incomingNamespace: 'acme',
+ exemptPhysicalRelId: '_ns/acme/helper',
+ }),
+ ).toBeUndefined();
+ const legacy = { manifest: { id: 'old', command: 'Draw' } };
+ expect(findConflictingGhostCommand([legacy], 'draw', { incomingNamespace: null })).toBe(
+ legacy,
+ );
+ });
+
+ it('canonicalizes library keys to the physical storage part', () => {
+ expect(resolvePluginLibraryStorageKey('helper')).toBe('helper');
+ expect(resolvePluginLibraryStorageKey('_ns/acme/helper')).toBe('_ns__acme__helper');
+ expect(resolvePluginLibraryStorageKey('_ns__acme__helper')).toBe('_ns__acme__helper');
+ expect(
+ resolvePluginLibraryStorageKey('_ns/xd/xd-feishu', {
+ manifest: { id: 'xd-feishu' },
+ dir: '/brain/xd-feishu',
+ namespace: 'xd',
+ }),
+ ).toBe('xd-feishu');
+ expect(resolvePluginLibraryStorageKey('not a plugin')).toBeNull();
+ });
+
+});
+
+describe('plugin instance query', () => {
+ it('treats a bare ghost id as ambiguous when two instances share it', () => {
+ const root = { manifest: { id: 'helper' }, namespace: null, dir: '/ghosts/helper', instanceKey: 'helper' };
+ const org = {
+ manifest: { id: 'helper' }, namespace: 'acme', dir: '/ghosts/_ns/acme/helper', instanceKey: '_ns__acme__helper',
+ };
+ expect(resolvePluginInstanceQuery([root, org], 'helper')).toMatchObject({ status: 'unique', ghost: root });
+ expect(resolvePluginInstanceQuery([root, org], 'helper', null)).toMatchObject({ status: 'unique', ghost: root });
+ expect(resolvePluginInstanceQuery([root, org], 'helper', 'acme')).toMatchObject({ status: 'unique', ghost: org });
+ expect(resolvePluginInstanceQuery([root, org], '_ns__acme__helper')).toMatchObject({ status: 'unique', ghost: org });
+ const namedRoot = { ...root, instanceKey: '_root__helper', dir: '/ghosts/_ns/_root/helper' };
+ const namedOrg = { ...org, instanceKey: '_ns__acme__helper' };
+ expect(resolvePluginInstanceQuery([namedRoot, namedOrg], 'helper').status).toBe('ambiguous');
+ expect(resolvePluginInstanceQuery([namedRoot, namedOrg], '_root__helper')).toMatchObject({ status: 'unique', ghost: namedRoot });
+ });
+});
+
+describe('organization market placement', () => {
+ it('allows a namespaced organization install', () => {
+ expect(organizationMarketPlacementError({
+ scope: 'organization',
+ requestedNamespace: 'acme',
+ installedRelId: '_ns/acme/helper',
+ })).toBeNull();
+ });
+
+ it('refuses to retarget an organization directory at root', () => {
+ expect(organizationMarketPlacementError({
+ scope: 'public',
+ requestedNamespace: null,
+ installedRelId: '_ns/acme/helper',
+ })).toBe('不能把企业插件更新成 root');
+ });
+
+ it('refuses a new root install for an organization plugin', () => {
+ expect(organizationMarketPlacementError({
+ scope: 'organization',
+ requestedNamespace: null,
+ installedRelId: null,
+ })).toBe('企业插件缺少 namespace,不能按 root 安装');
+ });
+
+ it('allows a public root install', () => {
+ expect(organizationMarketPlacementError({
+ scope: 'public',
+ requestedNamespace: null,
+ installedRelId: 'helper',
+ })).toBeNull();
+ });
+});
+
+describe('blocked instance registry', () => {
+ it('refuses every market install and update while the registry is blocked', () => {
+ expect(blockedInstanceRegistryMarketError(true)).toBe('插件注册表暂不可用,市场安装和更新已暂停,请稍后重试');
+ expect(blockedInstanceRegistryMarketError(false)).toBeNull();
+ });
+});
+
+describe('findInstalledRootGhostForFileImport', () => {
+ const ghost = (overrides: Record<string, unknown>) => ({
+ manifest: { id: 'helper' },
+ ...overrides,
+ });
+
+ it('updates a confirmed or unconfirmed root and a pending legacy directory', () => {
+ const fresh = ghost({ namespace: null, namespaceState: 'confirmed', instanceKey: '_root__helper' });
+ const legacy = ghost({ namespaceState: 'pending', instanceKey: 'helper' });
+ const unconfirmed = ghost({ namespace: null, namespaceState: 'unconfirmed', instanceKey: '_root__helper' });
+ expect(findInstalledRootGhostForFileImport([fresh], 'helper')).toBe(fresh);
+ expect(findInstalledRootGhostForFileImport([legacy], 'helper')).toBe(legacy);
+ expect(findInstalledRootGhostForFileImport([unconfirmed], 'helper')).toBe(unconfirmed);
+ });
+
+ it('does not select a confirmed or namespaced organization install', () => {
+ const named = ghost({
+ manifest: { id: 'xd-feishu' },
+ namespace: 'xd',
+ namespaceState: 'confirmed',
+ instanceKey: 'xd-feishu',
+ });
+ const relocated = ghost({ namespace: 'xd', namespaceState: 'confirmed', instanceKey: '_ns__xd__helper' });
+ expect(findInstalledRootGhostForFileImport([named], 'xd-feishu')).toBeNull();
+ expect(findInstalledRootGhostForFileImport([relocated], 'helper')).toBeNull();
+ });
+
+ it('returns null when two roots would match', () => {
+ const fresh = ghost({ namespace: null, namespaceState: 'confirmed', instanceKey: '_root__helper' });
+ const legacy = ghost({ namespaceState: 'pending', instanceKey: 'helper' });
+ expect(findInstalledRootGhostForFileImport([fresh, legacy], 'helper')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts b/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts
index 4d26778a37..55987457e1 100644
--- a/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts
+++ b/apps/desktop/src/shared/__tests__/sidebarSettings.test.ts
@@ -1,10 +1,18 @@
import { describe, expect, it } from 'vitest';
-import { isSidebarLegacyRendererOwnerClaim, isSidebarSettingsSnapshot } from '../sidebarSettings';
+import { isSidebarGhostId, isSidebarLegacyRendererOwnerClaim, isSidebarSettingsSnapshot } from '../sidebarSettings';
const OWNER_STAMP = { dataOwnerId: 'owner-a', ownerGeneration: 1 };
describe('sidebar settings snapshot validation', () => {
+ it('accepts new root storage keys without accepting paths or malformed keys', () => {
+ expect(isSidebarGhostId('_root__helper')).toBe(true);
+ for (const invalid of ['_root__', '_root__Helper', '_root__../helper', '_ns/_root/helper']) {
+ expect(isSidebarGhostId(invalid)).toBe(false);
+ }
+ expect(isSidebarSettingsSnapshot({ ...OWNER_STAMP, pinnedOrderIsAuthoritative: false,
+ pinnedOrder: [], hiddenProjectKeys: [], hiddenMainViewGhostIds: ['_root__helper'] })).toBe(true);
+ });
it.each([true, false])(
'accepts an empty snapshot when authority is %s',
(pinnedOrderIsAuthoritative) => {
@@ -89,6 +97,24 @@ describe('sidebar settings snapshot validation', () => {
hiddenMainViewGhostIds: ['XD Sites'],
}),
).toBe(false);
+ expect(
+ isSidebarSettingsSnapshot({
+ ...OWNER_STAMP,
+ pinnedOrderIsAuthoritative: false,
+ pinnedOrder: [],
+ hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: ['_ns__acme__helper'],
+ }),
+ ).toBe(true);
+ expect(
+ isSidebarSettingsSnapshot({
+ ...OWNER_STAMP,
+ pinnedOrderIsAuthoritative: false,
+ pinnedOrder: [],
+ hiddenProjectKeys: [],
+ hiddenMainViewGhostIds: ['_ns/acme/helper'],
+ }),
+ ).toBe(false);
});
});
diff --git a/apps/desktop/src/shared/botAuthorization.ts b/apps/desktop/src/shared/botAuthorization.ts
index e4ef4adf36..41a374bbee 100644
--- a/apps/desktop/src/shared/botAuthorization.ts
+++ b/apps/desktop/src/shared/botAuthorization.ts
@@ -1,4 +1,5 @@
import type { GhostSetupAllowedAction, GhostSetupStepPhase, GhostSetupErrorCode } from './ghost.js';
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
export interface AuthorizationSnapshot {
remoteOauth?: true;
reopenActionId?: string;
@@ -22,10 +23,11 @@ export interface AuthorizationSnapshot {
/** Stored presentation and opaque target only; never store an OAuth URL or a credential. */
export type BotAuthorizationTarget =
- | { kind: 'plugin'; id: string; reauthorize?: boolean }
+ | { kind: 'plugin'; id: string; namespace?: string | null; reauthorize?: boolean }
| { kind: 'host'; id: 'grok'; reauthorize?: boolean };
export interface BotAuthorizationCard {
v: 1;
+ pluginApprovalToken?: string;
/** Authorization was verified; continuation has not been durably finalized yet. */
completionPending?: true;
sessionId: string;
@@ -38,12 +40,17 @@ export function readBotAuthorizationCard(value: unknown): BotAuthorizationCard |
const v = value as Partial<BotAuthorizationCard>;
if (
v.v !== 1 ||
+ (v.pluginApprovalToken !== undefined && (v.target?.kind !== 'plugin' ||
+ typeof v.pluginApprovalToken !== 'string' || v.pluginApprovalToken.length === 0)) ||
typeof v.sessionId !== 'string' ||
typeof v.createdAt !== 'number' ||
!v.target ||
!['plugin', 'host'].includes(v.target.kind) ||
typeof v.target.id !== 'string' ||
(v.target.kind === 'host' && v.target.id !== 'grok') ||
+ ('namespace' in v.target &&
+ (v.target.kind !== 'plugin' ||
+ (v.target.namespace !== null && !isValidPluginNamespace(v.target.namespace)))) ||
!v.snapshot ||
v.snapshot.kind !== 'plugin_setup' ||
typeof v.snapshot.requestId !== 'string' ||
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 821f9b92b0..cbd62fc8f1 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -10,6 +10,7 @@ import {
type GhostManifestLocales,
} from '@cindy/plugin-protocol';
import { findSplitChildByPanelKind, insertRootSplitPane, type Layout } from './layoutTree';
+import { PLUGIN_STORAGE_PART_RE } from './pluginStoragePartPattern.js';
import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './locale';
/**
@@ -65,11 +66,12 @@ export function ghostPartition(id: string): string {
return `${GHOST_PARTITION_PREFIX}${id}`;
}
-/** 从 Renderer claim 解析意识 id;不是合法 claim 返回 null。 */
+
+/** 从 Renderer claim 解析实例 storage part;不是合法 claim 返回 null。 */
export function parseGhostPartition(partition: unknown): string | null {
if (typeof partition !== 'string' || !partition.startsWith(GHOST_PARTITION_PREFIX)) return null;
const id = partition.slice(GHOST_PARTITION_PREFIX.length);
- return isValidGhostId(id) ? id : null;
+ return PLUGIN_STORAGE_PART_RE.test(id) ? id : null;
}
/**
@@ -846,9 +848,9 @@ export interface GhostSecretOauthDecl {
* 可选:XDT server token broker 的 provider slug(2026-07-14,xd-atlassian
* 意识化前置)。声明后 code 换 token 与 refresh 不直连 tokenUrl,改经主机
* 调 XDT server 的授权 broker(带登录 JWT;client secret 在服务端,不随包
- * 分发)。必须同时声明 redirectPort,并与 clientSecret 互斥。静态官方前缀照旧
- * 放行;其余资格由装入来源与当前组织事实共同判定。校验层保持纯函数不感知
- * 装入语境,门控在装入闸与连接闸。
+ * 分发)。必须同时声明 redirectPort,并与 clientSecret 互斥。资格按可信安装
+ * 事实判定,名称前缀不放行。校验层保持纯函数不感知装入语境,门控在装入闸
+ * 与连接闸。
*/
tokenBroker?: string;
/**
@@ -887,9 +889,9 @@ export const GHOST_OAUTH_BOUNCE_PATH_RE = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)
* 只在 networkSlot 请求 GitHub API 时注入,不进入插件、Renderer、KV 或日志。
* - 'oidc-token':值 = Cindy 为当前企业 Membership 签发的短时 Connection
* JWT。当前组织的可信市场安装,或企业作者通过 ghost_forge_install 明确安装且
- * id 命中本组织登记前缀时可签发;手动导入默认不取得该资格。点名例外:
- * ghostId 精确等于 mivo-canvas 的组织成员本地安装,在已装清单声明的精确
- * oidc-token host 仅为 mivo-canvas.dsworks.cn 时可签发;其它本地插件、其它精确 host 仍不签发,已有市场记录(含 installed:false)仍走 digest。市场账本损坏不得当成无记录。
+ * id 命中本组织登记前缀时可签发;手动导入默认不取得该资格。临时例外,只对 root 实例生效:
+ * ghostId 精确等于 mivo-canvas、namespace 为 null 或尚未确认的旧 root 安装,在已装清单声明的精确
+ * oidc-token host 仅为 mivo-canvas.dsworks.cn 时可签发;企业 namespace 下的同名插件、其它本地插件、其它精确 host 仍不签发,已有市场记录(含 installed:false)仍走 digest。市场账本损坏不得当成无记录。
* Host 根据当前组织和插件 id 推导 audience,插件不能声明或读取。
* 令牌只在 networkSlot 发请求时注入,且永不进入 Node Worker。
*
@@ -1604,8 +1606,17 @@ export interface InstalledGhost {
/** Host receipt fact, not a manifest declaration. Missing means tasks need confirmation. */
taskCapabilityApproved?: true;
manifest: GhostManifest;
- /** 安装目录绝对路径(userData/brain/<id>)。 */
+ /** 安装目录绝对路径(userData/brain/<id> 或 userData/brain/_ns/<org>/<id>)。 */
dir: string;
+ /**
+ * Host-verified install namespace. Missing is not a confirmed identity.
+ * null is confirmed root; a string is a confirmed organization slug.
+ */
+ namespace?: string | null;
+ /** Registry confirmation. Pending and unconfirmed must not receive new privileges. */
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+ /** Stable storage key. Absent only on projections built before the registry loads. */
+ instanceKey?: string;
/**
* 是否启用。停用 = 面板与能力休眠(不注册、不渲染),但插件仍装着、
* 布局位置保留;重新启用即恢复。批准安装的真身在 Host receipt 中;
@@ -1707,6 +1718,12 @@ export function isValidGhostId(id: unknown): id is string {
return typeof id === 'string' && GHOST_ID_RE.test(id);
}
+/** New author ids must start with a letter. Installed legacy ids may start with a digit. */
+const NEW_GHOST_ID_RE = /^[a-z][a-z0-9-]{0,31}$/;
+export function isValidNewGhostId(id: unknown): id is string {
+ return typeof id === 'string' && NEW_GHOST_ID_RE.test(id);
+}
+
/**
* 官方意识历史 id 前缀常量:`cindy-`。完整保留集合与用户装入通道判定以
* `GHOST_OFFICIAL_ID_PREFIXES` 为准;官方市场可安装命中保留前缀的插件,
@@ -1736,23 +1753,23 @@ export function isOfficialGhostId(id: string): boolean {
/**
* 用户装入通道(拖入 / 选文件 / forge 转交 / 自定义市场)是否拒装该 id。
- * 当前与 `isOfficialGhostId` 等价;本批不放宽组织前缀。
+ * 仅保留 Cindy 平台前缀;XD/Filo 名字可普通导入,运行时资格另验可信来源。
*/
export function isUserInstallReservedGhostId(id: string): boolean {
- return isOfficialGhostId(id);
+ return id.startsWith(GHOST_OFFICIAL_ID_PREFIX);
}
/**
- * 该 id 是否命中 `oauth.tokenBroker` 的静态官方前缀资格。
- * 非官方资格由运行时 first-party 判据增量放行,不改这张静态表。
+ * 保留命名空间谓词,与 `isOfficialGhostId` 同口径。
+ * **不是** tokenBroker 授权:运行时资格见 ghostFirstPartyPrivilege。
*/
export function isBrokerEligibleGhostId(id: string): boolean {
return isOfficialGhostId(id);
}
/**
- * 该 id 能否拿宿主原语:OAuth 端口回收、身份头像代下载。
- * 仅认静态官方前缀;本轮不随 Broker 资格放宽。
+ * 保留命名空间谓词,与 `isOfficialGhostId` 同口径。
+ * **不是** 宿主原语授权:端口回收 / 头像代下载见 ghostFirstPartyPrivilege。
*/
export function isFirstPartyHostPrivilegeGhostId(id: string): boolean {
return isOfficialGhostId(id);
@@ -2874,10 +2891,14 @@ export function ghostWebviewEntryPaths(manifest: GhostManifest): string[] {
* - 否则停在聊天区左侧,宽度占比/最小宽取清单声明。
* 卸下时**不做**逆操作 —— 树数据保留正是"重装复活"的记忆来源(§6 规则 5)。
*/
-export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): Layout | null {
+export function layoutWithGhostPanel(
+ layout: Layout,
+ manifest: GhostManifest,
+ instanceId: string = manifest.id,
+): Layout | null {
if (!manifest.panel) return null;
if (manifest.panel.position === 'tab') return null;
- const kind = ghostPanelKind(manifest.id);
+ const kind = ghostPanelKind(instanceId);
if (findSplitChildByPanelKind(layout, kind)) return null;
// 停靠位置(相对主聊天窗):按 chat-main 的实际下标定插入点,不写死
// 序号(未来树形态变化不至于错位)。停靠恒在聊天区左侧(2026-07-25 Lizi
@@ -2893,7 +2914,7 @@ export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): L
const result = insertRootSplitPane(
layout,
{
- id: `ghost-${manifest.id}`,
+ id: `ghost-${instanceId}`,
panelKind: kind,
...(manifest.panel.minWidth !== undefined ? { minWidth: manifest.panel.minWidth } : {}),
},
@@ -6640,6 +6661,17 @@ export type GhostPipeWorkspaceResult =
message: string;
};
+export const GHOST_MEDIA_HANDOVER_MIME = 'application/x-cindy-ghost-handover';
+
+export interface GhostMediaHandover {
+ uri: string;
+ sourceToken?: string;
+}
+
+export interface GhostPanelMediaTarget {
+ ghostId: string;
+ instanceId?: string;
+}
/**
* 上行:preview 槽——请主机在右侧栏内置浏览器打开一个预览标签页。
* url 必须命中身份卡 preview.hosts 白名单(ghostPreviewUrlAllowed);
@@ -6725,6 +6757,11 @@ export interface GhostScheduleDraftPush {
/** 本次请求 id(renderer 去重用:重复推送不叠开多个面板)。 */
requestId: string;
ghostId: string;
+ /**
+ * 已知身份才带上。待迁移、或还没有 namespace 字段的旧安装省略。
+ * 不写入调度存储:给任务表加列是不可回退的 migration,这里只跟着打开面板的推送走。
+ */
+ namespace?: string | null;
/** 插件展示名(主机填,用于面板上的来源标注)。 */
ghostName: string;
iconDataUrl?: string;
diff --git a/apps/desktop/src/shared/ghostComposer.ts b/apps/desktop/src/shared/ghostComposer.ts
index 1a04636747..e50178d135 100644
--- a/apps/desktop/src/shared/ghostComposer.ts
+++ b/apps/desktop/src/shared/ghostComposer.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
import type { InstalledGhost } from './ghost';
+import { installedGhostStoragePart } from './pluginIdentity';
export const GHOST_COMPOSER_LIST_CHANNEL = 'ghosts:composer-list';
@@ -20,6 +21,13 @@ const ghostComposerEntrySchema = z.object({
.optional(),
}),
enabled: z.boolean(),
+ /** Absent on old peers. null is an explicit root instance. */
+ namespace: z.string().min(1).nullable().optional(),
+ /**
+ * Physical instance key. Absent on old peers; never a filesystem path.
+ * In-place migrated installs keep their original key, which can differ from manifest.id.
+ */
+ instanceKey: z.string().min(1).max(167).optional(),
hasSkill: z.boolean().optional(),
iconDataUrl: z.string().optional(),
});
@@ -28,7 +36,7 @@ export const ghostComposerListSchema = z.array(ghostComposerEntrySchema);
export type GhostComposerEntry = z.infer<typeof ghostComposerEntrySchema>;
/** Shared structural input for command placement, decoration and send-time expansion. */
-export type GhostCommandSource = Pick<GhostComposerEntry, 'manifest' | 'enabled' | 'iconDataUrl'>;
+export type GhostCommandSource = Pick<GhostComposerEntry, 'manifest' | 'enabled' | 'iconDataUrl' | 'namespace' | 'instanceKey'>;
export function projectGhostComposerEntries(
ghosts: readonly InstalledGhost[],
@@ -42,23 +50,30 @@ export function projectGhostComposerEntries(
(ghost.manifest.id !== 'cindy-mivo' ||
!ghosts.some((item) => item.manifest.id === 'xd-mivo')),
)
- .map(({ manifest, enabled, iconDataUrl }) => ({
- manifest: {
- id: manifest.id,
- name: manifest.name,
- ...(manifest.command ? { command: manifest.command } : {}),
- ...(manifest.tools
- ? {
- tools: manifest.tools.map(({ name, description, parameters }) => ({
- name,
- description,
- ...(parameters ? { parameters } : {}),
- })),
- }
- : {}),
- },
- enabled: enabled && !disabled.has(manifest.id),
- hasSkill: !!manifest.skill,
- ...(iconDataUrl ? { iconDataUrl } : {}),
- }));
+ .map((ghost) => {
+ const { manifest, enabled, iconDataUrl, namespace } = ghost;
+ // Directory disablement is stored by storage part, not the bare manifest id.
+ const instanceKey = installedGhostStoragePart(ghost);
+ return {
+ manifest: {
+ id: manifest.id,
+ name: manifest.name,
+ ...(manifest.command ? { command: manifest.command } : {}),
+ ...(manifest.tools
+ ? {
+ tools: manifest.tools.map(({ name, description, parameters }) => ({
+ name,
+ description,
+ ...(parameters ? { parameters } : {}),
+ })),
+ }
+ : {}),
+ },
+ enabled: enabled && !disabled.has(instanceKey),
+ instanceKey,
+ hasSkill: !!manifest.skill,
+ ...(namespace !== undefined ? { namespace } : {}),
+ ...(iconDataUrl ? { iconDataUrl } : {}),
+ };
+ });
}
diff --git a/apps/desktop/src/shared/pluginIdentity.ts b/apps/desktop/src/shared/pluginIdentity.ts
new file mode 100644
index 0000000000..f7895ffaec
--- /dev/null
+++ b/apps/desktop/src/shared/pluginIdentity.ts
@@ -0,0 +1,584 @@
+import { isValidPluginNamespace } from '@cindy/plugin-protocol';
+import { ghostInstallApprovalToken, ghostPartition, isValidGhostId, type GhostInstallApproval } from './ghost.js';
+
+interface InstalledGhostIdentitySource {
+ manifest: { id: string };
+ dir?: string;
+ namespace?: string | null;
+ /** Registry instance key. Storage uses this and never a path-derived alias. */
+ instanceKey?: string;
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+}
+
+function isGhostIdValue(value: string): boolean {
+ return isValidGhostId(value);
+}
+
+/**
+ * A missing namespace is an old wire protocol state, not the root namespace.
+ * Once an installation is committed, callers must use a known identity with
+ * namespace === null for root or a non-empty namespace for an organization.
+ */
+type PluginNamespaceState =
+ | { kind: 'legacy' }
+ | { kind: 'known'; namespace: string | null };
+
+export interface PluginLogicalIdentity {
+ namespace: string | null;
+ ghostId: string;
+}
+
+export function resolvePluginNamespaceState(raw: unknown): PluginNamespaceState {
+ if (typeof raw !== 'object' || raw === null || !hasDeliveryNamespace(raw)) {
+ return { kind: 'legacy' };
+ }
+ const namespace = (raw as { namespace?: unknown }).namespace;
+ if (namespace === null) return { kind: 'known', namespace: null };
+ if (!isValidPluginNamespace(namespace)) {
+ throw new Error('插件 namespace 不合法');
+ }
+ return { kind: 'known', namespace };
+}
+
+export function createPluginLogicalIdentity(
+ namespace: string | null,
+ ghostId: string,
+): PluginLogicalIdentity {
+ if (namespace !== null && !isValidPluginNamespace(namespace)) {
+ throw new Error('插件 namespace 不合法');
+ }
+ if (!isValidGhostId(ghostId)) throw new Error('插件 ghostId 不合法');
+ return { namespace, ghostId };
+}
+
+export function hasDeliveryNamespace<T extends object>(
+ value: T,
+): value is T & { namespace: string | null } {
+ return Object.prototype.hasOwnProperty.call(value, 'namespace');
+}
+
+/** Persist only a known identity. Missing stays legacy and is not written as root. */
+export function deliveryNamespaceFields(
+ value: object,
+): { namespace: string | null } | Record<string, never> {
+ return hasDeliveryNamespace(value) ? { namespace: value.namespace } : {};
+}
+
+export function knownDeliveryNamespacesDiffer(
+ left: object,
+ right: object,
+): boolean {
+ return (
+ hasDeliveryNamespace(left) &&
+ hasDeliveryNamespace(right) &&
+ left.namespace !== right.namespace
+ );
+}
+
+export function sameDeliveryNamespaceState(left: object, right: object): boolean {
+ if (hasDeliveryNamespace(left) !== hasDeliveryNamespace(right)) return false;
+ if (!hasDeliveryNamespace(left) || !hasDeliveryNamespace(right)) return true;
+ return left.namespace === right.namespace;
+}
+
+export function downloadIdentityMatchesPlugin(
+ download: {
+ pluginId?: string;
+ releaseId?: string;
+ ghostId?: string;
+ namespace?: string | null;
+ },
+ plugin: {
+ id: string;
+ ghostId: string;
+ namespace?: string | null;
+ currentRelease: { id: string };
+ },
+): boolean {
+ const pluginHasNamespace = hasDeliveryNamespace(plugin);
+ const downloadComplete =
+ download.pluginId !== undefined &&
+ download.releaseId !== undefined &&
+ download.ghostId !== undefined &&
+ hasDeliveryNamespace(download);
+ // A detail that already carries namespace must not accept a download that
+ // omits identity. Missing detail namespace stays compatible with old downloads.
+ if (pluginHasNamespace && !downloadComplete) return false;
+ const hasDownloadIdentity =
+ download.pluginId !== undefined ||
+ download.releaseId !== undefined ||
+ download.ghostId !== undefined ||
+ hasDeliveryNamespace(download);
+ if (!hasDownloadIdentity) return true;
+ return (
+ download.pluginId === plugin.id &&
+ download.releaseId === plugin.currentRelease.id &&
+ download.ghostId === plugin.ghostId &&
+ sameDeliveryNamespaceState(download, plugin)
+ );
+}
+
+/** Organization-scoped installs live under this reserved content/state root. */
+export const PLUGIN_NS_INSTALL_ROOT = '_ns';
+export const PLUGIN_ROOT_INSTALL_DIR = '_root';
+export const PLUGIN_ROOT_INSTALL_ROOT = `${PLUGIN_NS_INSTALL_ROOT}/${PLUGIN_ROOT_INSTALL_DIR}`;
+
+/** Archive ids are not namespaces and are not directory keys. */
+const ARCHIVE_INSTANCE_KEY_RE = /^arch_[a-f0-9]{32}$/;
+
+export function isArchiveInstanceKey(value: unknown): value is string {
+ return typeof value === 'string' && ARCHIVE_INSTANCE_KEY_RE.test(value);
+}
+
+export function isPluginInstanceKey(value: unknown): value is string {
+ return typeof value === 'string' && (
+ isValidGhostId(value) ||
+ isValidPluginStoragePart(value)
+ );
+}
+
+/** Posix-style relative id: `helper` or `_ns/acme/helper`. Safe for directories. */
+export function pluginInstallRelId(identity: PluginLogicalIdentity): string {
+ if (identity.namespace === null) return identity.ghostId;
+ return `${PLUGIN_NS_INSTALL_ROOT}/${identity.namespace}/${identity.ghostId}`;
+}
+
+export function pluginNewInstallRelId(identity: PluginLogicalIdentity): string {
+ return `${PLUGIN_NS_INSTALL_ROOT}/${identity.namespace ?? PLUGIN_ROOT_INSTALL_DIR}/${identity.ghostId}`;
+}
+
+export function pluginInstallStoragePart(relId: string): string {
+ const identity = parsePluginInstallRelId(relId);
+ if (!identity) throw new Error('插件安装目录不合法');
+ return relId.startsWith(`${PLUGIN_ROOT_INSTALL_ROOT}/`)
+ ? `${PLUGIN_ROOT_INSTALL_DIR}__${identity.ghostId}`
+ : pluginStoragePart(identity);
+}
+
+export function parsePluginInstallRelId(value: string): PluginLogicalIdentity | null {
+ if (isGhostIdValue(value)) return { namespace: null, ghostId: value };
+ const parts = value.split('/');
+ if (
+ parts.length === 3 &&
+ parts[0] === PLUGIN_NS_INSTALL_ROOT &&
+ (parts[1] === PLUGIN_ROOT_INSTALL_DIR || isValidPluginNamespace(parts[1])) &&
+ isValidGhostId(parts[2])
+ ) {
+ return { namespace: parts[1] === PLUGIN_ROOT_INSTALL_DIR ? null : parts[1], ghostId: parts[2] };
+ }
+ return null;
+}
+
+export function isValidPluginInstallRelId(value: unknown): value is string {
+ return typeof value === 'string' && parsePluginInstallRelId(value) !== null;
+}
+
+/**
+ * Flat filesystem/vault/session id.
+ * Root stays `helper`; organization instances use `_ns__<namespace>__<ghostId>`.
+ * Double underscore is unambiguous because neither namespace nor ghostId contains `_`.
+ * Do not persist pluginInstallRelId (`/`) as a vault or file name.
+ */
+export function pluginStoragePart(identity: PluginLogicalIdentity): string {
+ if (identity.namespace === null) return identity.ghostId;
+ return `${PLUGIN_NS_INSTALL_ROOT}__${identity.namespace}__${identity.ghostId}`;
+}
+
+export function parsePluginStoragePart(value: string): PluginLogicalIdentity | null {
+ if (isGhostIdValue(value)) return { namespace: null, ghostId: value };
+ const rootPrefix = `${PLUGIN_ROOT_INSTALL_DIR}__`;
+ if (value.startsWith(rootPrefix) && isValidGhostId(value.slice(rootPrefix.length))) {
+ return { namespace: null, ghostId: value.slice(rootPrefix.length) };
+ }
+ const prefix = `${PLUGIN_NS_INSTALL_ROOT}__`;
+ if (!value.startsWith(prefix)) return null;
+ const rest = value.slice(prefix.length);
+ const sep = rest.indexOf('__');
+ if (sep <= 0 || sep + 2 >= rest.length) return null;
+ if (rest.indexOf('__', sep + 2) !== -1) return null;
+ const namespace = rest.slice(0, sep);
+ const ghostId = rest.slice(sep + 2);
+ try {
+ return createPluginLogicalIdentity(namespace, ghostId);
+ } catch {
+ return null;
+ }
+}
+
+export function isValidPluginStoragePart(value: unknown): value is string {
+ return typeof value === 'string' && parsePluginStoragePart(value) !== null;
+}
+
+/** Runtime / UI instance id: helper, _ns/acme/helper, or _ns__acme__helper. */
+export function parsePluginInstanceId(value: string): PluginLogicalIdentity | null {
+ return parsePluginInstallRelId(value) ?? parsePluginStoragePart(value);
+}
+
+export function pluginInstanceInstallRelId(value: string): string | null {
+ if (parsePluginInstallRelId(value)) return value;
+ const identity = parsePluginStoragePart(value);
+ if (!identity) return null;
+ return value.startsWith(PLUGIN_ROOT_INSTALL_DIR + '__')
+ ? pluginNewInstallRelId(identity) : pluginInstallRelId(identity);
+}
+
+/** Runtime / UI instance id: storage part or install rel id. */
+export function isGhostInstanceId(value: unknown): value is string {
+ return typeof value === 'string' && parsePluginInstanceId(value) !== null;
+}
+
+export function installedGhostPhysicalRelId(ghost: InstalledGhostIdentitySource): string {
+ if (typeof ghost.dir === 'string') {
+ const fromDir = parseInstallRelIdFromDir(ghost.dir, ghost.manifest.id);
+ if (fromDir) return fromDir;
+ }
+ return pluginInstallRelId(installedGhostLogicalIdentity(ghost));
+}
+
+function parseInstallRelIdFromDir(dir: string, ghostId: string): string | null {
+ const normalized = dir.replace(/\\/g, '/').replace(/\/+$/, '');
+ const marker = `/${PLUGIN_NS_INSTALL_ROOT}/`;
+ const at = normalized.lastIndexOf(marker);
+ if (at >= 0) {
+ const rest = normalized.slice(at + marker.length);
+ const slash = rest.indexOf('/');
+ if (
+ slash > 0 &&
+ rest.slice(slash + 1) === ghostId &&
+ rest.indexOf('/', slash + 1) === -1
+ ) {
+ return parsePluginInstallRelId(`${PLUGIN_NS_INSTALL_ROOT}/${rest}`)
+ ? `${PLUGIN_NS_INSTALL_ROOT}/${rest}` : null;
+ }
+ }
+ if (normalized === ghostId || normalized.endsWith(`/${ghostId}`)) return ghostId;
+ return null;
+}
+
+export function installedGhostStoragePart(ghost: InstalledGhostIdentitySource): string {
+ if (ghost.instanceKey && isPluginInstanceKey(ghost.instanceKey)) return ghost.instanceKey;
+ return installedGhostPhysicalKeys(ghost).storagePart;
+}
+
+/** Renderer WebView attach claim. Main matches the physical instance key, not the logical one. */
+export function installedGhostWebviewPartitionClaim(ghost: InstalledGhostIdentitySource): string {
+ return ghostPartition(installedGhostStoragePart(ghost));
+}
+
+/**
+ * Library / vault keys are storage parts. Prefer the installed ghost so an
+ * in-place stamp keeps the original directory; otherwise canonicalize an IPC
+ * instance id (`helper`, `_ns/acme/helper`, `_ns__acme__helper`).
+ */
+export function resolvePluginLibraryStorageKey(
+ instanceId: string,
+ ghost?: InstalledGhostIdentitySource | null,
+): string | null {
+ if (ghost) return installedGhostStoragePart(ghost);
+ const relId = pluginInstanceInstallRelId(instanceId);
+ return relId ? pluginInstallStoragePart(relId) : null;
+}
+
+/**
+ * Directory and vault/runtime keys for an already-installed ghost.
+ *
+ * After an in-place namespace stamp the logical identity is namespaced, but the
+ * plugin still lives at the original root directory. Deriving keys from
+ * `installedGhostLogicalIdentity` stops/uninstalls `_ns/<ns>/<id>` while OAuth,
+ * KV and the runtime stay on `<id>`.
+ */
+export function installedGhostPhysicalKeys(
+ ghost: InstalledGhostIdentitySource,
+): { relId: string; storagePart: string } {
+ const relId = installedGhostPhysicalRelId(ghost);
+ return { relId, storagePart: pluginInstallStoragePart(relId) };
+}
+
+export function installedGhostMutationTargetToken(
+ ghost: InstalledGhostIdentitySource & { dir: string; approval: GhostInstallApproval },
+ ownerScopeKey: string,
+): string | null {
+ if (ghost.approval.state !== 'approved') return null;
+ return JSON.stringify([
+ ownerScopeKey,
+ ghost.dir,
+ installedGhostStoragePart(ghost),
+ ghostInstallApprovalToken(ghost.approval),
+ deliveryNamespaceFields(ghost),
+ ]);
+}
+
+export function installedGhostLogicalIdentity(
+ ghost: InstalledGhostIdentitySource,
+): PluginLogicalIdentity {
+ return createPluginLogicalIdentity(
+ hasDeliveryNamespace(ghost) ? ghost.namespace : null,
+ ghost.manifest.id,
+ );
+}
+
+export function findInstalledGhostByIdentity<T extends {
+ manifest: { id: string };
+ namespace?: string | null;
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+}>(ghosts: readonly T[], identity: PluginLogicalIdentity): T | undefined {
+ const rel = pluginInstallRelId(identity);
+ return ghosts.find(
+ (ghost) => ghost.namespaceState !== 'pending' &&
+ pluginInstallRelId(installedGhostLogicalIdentity(ghost)) === rel,
+ );
+}
+
+/**
+ * Resolve a UI/IPC instance id to the installed ghost that owns that physical
+ * directory. Prefer storage-part equality so in-place migrated plugins keep
+ * their original directory key instead of a logical namespaced identity.
+ */
+/**
+ * Exact instance key or the content path of that same install.
+ * Does not fall through to a logical namespace alias.
+ */
+
+/**
+ * Local file import updates a root install of this ghost id, never an
+ * organization instance. Pending legacy directories have no namespace field
+ * and stay on the update path; Main still rejects an organization package.
+ * Confirmed or unconfirmed root uses namespace null. More than one match
+ * is not a root update.
+ */
+export function findInstalledRootGhostForFileImport<
+ T extends {
+ manifest: { id: string };
+ namespace?: string | null;
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+ },
+>(ghosts: readonly T[], ghostId: string): T | null {
+ const matches = ghosts.filter((ghost) => {
+ if (ghost.manifest.id !== ghostId) return false;
+ if ((ghost.namespaceState === 'confirmed' || ghost.namespaceState === 'unconfirmed') &&
+ ghost.namespace === null) return true;
+ return ghost.namespaceState === 'pending' && !hasDeliveryNamespace(ghost);
+ });
+ return matches.length === 1 ? matches[0]! : null;
+}
+
+export function findInstalledGhostByInstanceId<T extends InstalledGhostIdentitySource>(
+ ghosts: readonly T[],
+ instanceId: string,
+): T | undefined {
+ return ghosts.find((ghost) =>
+ ghost.instanceKey === instanceId ||
+ installedGhostStoragePart(ghost) === instanceId ||
+ installedGhostPhysicalRelId(ghost) === instanceId);
+}
+
+/**
+ * The only logical/instance resolver.
+ * An omitted namespace matches only when ghostId is unique.
+ * Anything that is not a bare ghost id is an instance key.
+ */
+export function resolvePluginInstanceQuery<T extends {
+ manifest: { id: string };
+ dir?: string;
+ namespace?: string | null;
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+ instanceKey?: string;
+}>(
+ ghosts: readonly T[],
+ id: string,
+ namespace?: string | null,
+): InstalledGhostIdentityResolve<T> {
+ if (namespace !== undefined) return resolveInstalledGhost(ghosts, id, namespace);
+ const byKey = findInstalledGhostByInstanceId(ghosts, id);
+ if (byKey) return { status: 'unique', ghost: byKey };
+ if (!isValidGhostId(id)) return { status: 'missing' };
+ return resolveInstalledGhost(ghosts, id);
+}
+
+export function findInstalledGhostForLocalUpdate<T extends {
+ manifest: { id: string };
+ dir?: string;
+ namespace?: string | null;
+ approval: GhostInstallApproval;
+}>(ghosts: readonly T[], ghostId: string, instanceId: string, approvalToken: string): T | undefined {
+ if (!isValidPluginStoragePart(instanceId)) return undefined;
+ const ghost = findInstalledGhostByInstanceId(ghosts, instanceId);
+ return ghost?.manifest.id === ghostId && installedGhostStoragePart(ghost) === instanceId &&
+ ghostInstallApprovalToken(ghost.approval) === approvalToken ? ghost : undefined;
+}
+
+type InstalledGhostIdentityResolve<T> =
+ | { status: 'missing' }
+ | { status: 'unique'; ghost: T }
+ | { status: 'ambiguous'; candidates: T[] };
+
+function listInstalledGhostsByGhostId<T extends { manifest: { id: string } }>(
+ ghosts: readonly T[],
+ ghostId: string,
+): T[] {
+ return ghosts.filter((ghost) => ghost.manifest.id === ghostId);
+}
+
+/**
+ * `namespace === undefined` means the caller omitted it: unique ghostId is
+ * allowed, two or more same-name instances are ambiguous.
+ * `null` means root; a string means that organization.
+ */
+function isPendingLegacyGhost(ghost: {
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+}): boolean {
+ return ghost.namespaceState === 'pending';
+}
+
+export function resolveInstalledGhost<
+ T extends {
+ manifest: { id: string };
+ namespace?: string | null;
+ namespaceState?: 'confirmed' | 'unconfirmed' | 'pending';
+ },
+>(
+ ghosts: readonly T[],
+ ghostId: string,
+ namespace?: string | null,
+): InstalledGhostIdentityResolve<T> {
+ if (namespace !== undefined) {
+ let identity;
+ try {
+ identity = createPluginLogicalIdentity(namespace, ghostId);
+ } catch {
+ return { status: 'missing' };
+ }
+ const ghost = findInstalledGhostByIdentity(ghosts, identity);
+ if (ghost) return { status: 'unique', ghost };
+ // A pending upgrade install has no confirmed namespace. namespace null is
+ // the only address in the ambiguity candidate list, and it must not be
+ // stolen from a real root install.
+ if (namespace === null) {
+ const sameName = ghosts.filter((candidate) => candidate.manifest.id === ghostId);
+ const pending = sameName.filter((candidate) =>
+ isPendingLegacyGhost(candidate) && !hasDeliveryNamespace(candidate));
+ // A lone pending install is not root. null selects it only when an
+ // ambiguity candidate labeled it that way beside another instance.
+ if (sameName.length > 1 && pending.length === 1) return { status: 'unique', ghost: pending[0]! };
+ if (sameName.length > 1 && pending.length > 1) return { status: 'ambiguous', candidates: pending };
+ }
+ return { status: 'missing' };
+ }
+ const candidates = listInstalledGhostsByGhostId(ghosts, ghostId);
+ if (candidates.length === 0) return { status: 'missing' };
+ if (candidates.length === 1) return { status: 'unique', ghost: candidates[0]! };
+ return { status: 'ambiguous', candidates };
+}
+
+/**
+ * Pick the installed instance a delivery/install target should update.
+ * Known namespace (including root null) matches that identity only.
+ * Omitted namespace is allowed only when ghostId is unique; two same-name
+ * instances must not silently share consent or an update.
+ */
+export function findInstalledGhostForDeliveryTarget<
+ T extends { manifest: { id: string }; namespace?: string | null },
+>(ghosts: readonly T[], target: { ghostId: string; namespace?: string | null }): T | undefined {
+ if (hasDeliveryNamespace(target)) {
+ return findInstalledGhostByIdentity(
+ ghosts,
+ createPluginLogicalIdentity(target.namespace, target.ghostId),
+ );
+ }
+ const resolved = resolveInstalledGhost(ghosts, target.ghostId);
+ return resolved.status === 'unique' ? resolved.ghost : undefined;
+}
+
+function installedGhostNamespaceLabel(ghost: { namespace?: string | null }): string | null {
+ return hasDeliveryNamespace(ghost) ? ghost.namespace : null;
+}
+
+export function formatInstalledGhostAmbiguity(
+ ghostId: string,
+ candidates: readonly { namespace?: string | null }[],
+): string {
+ const labels = candidates.map((candidate) => {
+ const namespace = installedGhostNamespaceLabel(candidate);
+ return namespace === null ? `root/${ghostId}` : `${namespace}/${ghostId}`;
+ });
+ return `插件 ${ghostId} 存在多个实例(${labels.join('、')})。请指定 namespace:null 表示 root,字符串表示企业 orgSlug。`;
+}
+
+/** JSON-safe ledger / map key. Root and legacy stay `ghostId`; org uses storage part. */
+export function pluginLedgerRecordKey(plugin: {
+ ghostId: string;
+ namespace?: string | null;
+}): string {
+ if (hasDeliveryNamespace(plugin) && plugin.namespace !== null) {
+ return pluginStoragePart(createPluginLogicalIdentity(plugin.namespace, plugin.ghostId));
+ }
+ return plugin.ghostId;
+}
+
+/**
+ * Same slash-command in a different known namespace may coexist.
+ * A legacy (unstamped) holder still conflicts with everyone.
+ */
+export function findConflictingGhostCommand<
+ T extends {
+ manifest: { id: string; command?: string };
+ dir?: string;
+ namespace?: string | null;
+ },
+>(
+ ghosts: readonly T[],
+ command: string,
+ opts: {
+ incomingNamespace: string | null;
+ exemptPhysicalRelId?: string;
+ },
+): T | undefined {
+ const fold = command.toLowerCase();
+ return ghosts.find((ghost) => {
+ if (ghost.manifest.command === undefined) return false;
+ if (ghost.manifest.command.toLowerCase() !== fold) return false;
+ if (opts.exemptPhysicalRelId !== undefined) {
+ const rel = installedGhostPhysicalRelId(ghost);
+ if (rel === opts.exemptPhysicalRelId) return false;
+ }
+ if (!hasDeliveryNamespace(ghost)) return true;
+ return ghost.namespace === opts.incomingNamespace;
+ });
+}
+
+export function listGhostsByCommand<
+ T extends { enabled?: boolean; manifest: { command?: string } },
+>(ghosts: readonly T[], word: string, enabledOnly = true): T[] {
+ const fold = word.toLowerCase();
+ return ghosts.filter((ghost) => {
+ if (enabledOnly && ghost.enabled === false) return false;
+ return ghost.manifest.command !== undefined && ghost.manifest.command.toLowerCase() === fold;
+ });
+}
+
+
+/**
+ * A blocked instance registry must not invent a root install for an
+ * organization plugin, or rewrite an organization directory as root.
+ * Returns a user-facing reason, or null when the placement may proceed.
+ */
+export function organizationMarketPlacementError(input: {
+ scope?: string | null;
+ requestedNamespace: string | null;
+ installedRelId?: string | null;
+}): string | null {
+ if (input.requestedNamespace !== null) return null;
+ const installed = input.installedRelId ? parsePluginInstallRelId(input.installedRelId) : null;
+ if (installed?.namespace) {
+ return '不能把企业插件更新成 root';
+ }
+ if (input.scope === 'organization') {
+ return '企业插件缺少 namespace,不能按 root 安装';
+ }
+ return null;
+}
+
+/** Market install and update both wait until the instance registry can be read. */
+export function blockedInstanceRegistryMarketError(blocked: boolean): string | null {
+ return blocked ? '插件注册表暂不可用,市场安装和更新已暂停,请稍后重试' : null;
+}
diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.ts
index 1e9bf286b2..579fd39ae5 100644
--- a/apps/desktop/src/shared/pluginMarket.ts
+++ b/apps/desktop/src/shared/pluginMarket.ts
@@ -15,6 +15,8 @@ export type PluginMarketItemSource = 'server' | 'git-market' | 'local-market';
export interface PluginMarketItem {
pluginId: string;
ghostId: string;
+ /** Host-verified namespace. Missing is legacy wire; null is root. */
+ namespace?: string | null;
name: string;
description: string | null;
author: string | null;
diff --git a/apps/desktop/src/shared/pluginStoragePartPattern.ts b/apps/desktop/src/shared/pluginStoragePartPattern.ts
new file mode 100644
index 0000000000..1eb3ecffc2
--- /dev/null
+++ b/apps/desktop/src/shared/pluginStoragePartPattern.ts
@@ -0,0 +1,8 @@
+/**
+ * Flat instance storage key.
+ * ghost.ts and pluginIdentity.ts both accept this shape. Neither file can
+ * import the other, so the pattern lives here.
+ * Root: helper. New root: _root__helper. Organization: _ns__<namespace>__<id>.
+ */
+export const PLUGIN_STORAGE_PART_RE =
+ /^(?:[a-z0-9][a-z0-9-]{0,31}|_root__[a-z0-9][a-z0-9-]{0,31}|_ns__[a-z0-9](?:[a-z0-9-]{0,126}[a-z0-9])?__[a-z0-9][a-z0-9-]{0,31})$/;
diff --git a/apps/desktop/src/shared/providerSecrets.ts b/apps/desktop/src/shared/providerSecrets.ts
index 6d5a0f562f..9d97b0541d 100644
--- a/apps/desktop/src/shared/providerSecrets.ts
+++ b/apps/desktop/src/shared/providerSecrets.ts
@@ -230,10 +230,20 @@ const GHOST_SECRET_STORAGE_ALIASES: Record<string, Record<string, string>> = {
* ghostId 规则 /^[a-z0-9][a-z0-9-]{0,31}$/、secretKey 规则 /^[a-z][a-z0-9_]{0,31}$/
* (validateGhostManifest 已把关),此处按惯例在键名构造点再断言一次。
*/
-export function ghostSecretStorageKey(ghostId: string, secretKey: string): string {
+function ghostSecretAliasOwner(ghostId: string, allowMivoAlias: boolean): string {
+ // Only the legacy bare id may hold the historical Mivo key. A namespaced
+ // xd-mivo instance is a different install and must not share it.
+ if (allowMivoAlias && ghostId === 'xd-mivo') return 'xd-mivo';
+ return ghostId;
+}
+
+export function ghostSecretStorageKey(ghostId: string, secretKey: string, allowMivoAlias = false): string {
assertSafeKeyPart(ghostId, 'ghostId');
assertSafeKeyPart(secretKey, 'secretKey');
- const alias = GHOST_SECRET_STORAGE_ALIASES[ghostId]?.[secretKey];
+ const aliasOwner = ghostSecretAliasOwner(ghostId, allowMivoAlias);
+ const alias = ghostId === 'xd-mivo' && !allowMivoAlias
+ ? undefined
+ : GHOST_SECRET_STORAGE_ALIASES[aliasOwner]?.[secretKey];
if (alias) return alias;
return `${GHOST_SECRET_PREFIX}${ghostId}_${secretKey}`;
}
@@ -242,8 +252,8 @@ export function ghostSecretStorageKey(ghostId: string, secretKey: string): strin
* 意识凭证「尾 4 位指纹」的 safeStorage 键名前缀。指纹在**入库那一刻**由
* deriveGhostSecretTail 截取、与密文分键保管——读路径(/secrets GET)只回
* 这个预截好的指纹,从头到尾不存在"读明文再现场截"的环节,只写通道的
- * 结构保持干净。前缀与 ghost_secret_ 平行且零碰撞(ghostId 不含下划线,
- * ghost_secret_ 命名空间内第一个 `_` 前必是 ghostId,拼不出 hint_ 开头)。
+ * 结构保持干净。前缀与 ghost_secret_ 平行且零碰撞(root ghostId 不含下划线;
+ * 企业实例使用 `_ns__<namespace>__<ghostId>` storage part,仍拼不出 hint_ 开头)。
* 账号切换清理(clearAll)与卸载清理(removeGhostSecrets)都要连它一起扫。
*/
export const GHOST_SECRET_HINT_PREFIX = 'ghost_hint_';
diff --git a/apps/desktop/src/shared/sidebarSettings.ts b/apps/desktop/src/shared/sidebarSettings.ts
index 5adc14a4ce..0efeb31791 100644
--- a/apps/desktop/src/shared/sidebarSettings.ts
+++ b/apps/desktop/src/shared/sidebarSettings.ts
@@ -1,13 +1,13 @@
import { isDataOwnerPushStamp, type DataOwnerPushStamp } from './dataOwnerPush.js';
import { projectKeyComparisonKey } from './projectKeys.js';
+import { isValidPluginStoragePart } from './pluginIdentity.js';
export const SIDEBAR_PINNED_ORDER_MAX_ENTRIES = 10_000;
export const SIDEBAR_PINNED_ORDER_ENTRY_MAX_LENGTH = 4_096;
export const SIDEBAR_HIDDEN_MAIN_VIEW_MAX_ENTRIES = 1_000;
-/** Matches the Ghost manifest id grammar without importing the large runtime contract. */
export function isSidebarGhostId(value: unknown): value is string {
- return typeof value === 'string' && /^[a-z0-9][a-z0-9-]{0,31}$/.test(value);
+ return typeof value === 'string' && isValidPluginStoragePart(value);
}
export interface SidebarSettingsSnapshot extends DataOwnerPushStamp {
diff --git a/apps/mobile/src/__tests__/composerPlugins.test.ts b/apps/mobile/src/__tests__/composerPlugins.test.ts
index 4f876753d5..89578786da 100644
--- a/apps/mobile/src/__tests__/composerPlugins.test.ts
+++ b/apps/mobile/src/__tests__/composerPlugins.test.ts
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
import { appendComposerPluginTrigger, detectComposerPluginTrigger, filterComposerPlugins, placeComposerPlugin } from '@/session/composerPlugins';
import { textComposerDocument, composerDocumentProjectedText, serializeComposerDocument, type ComposerDocument } from '@/session/composerDocument';
import { expandGhostCommand, parseGhostCommandWord } from '@cindy/maker-shared/ghost-command';
+import { composerPluginListSchema } from '@/session/remoteComposerPlugins';
const art = { manifest: { id: 'art', name: 'Art', command: 'art' }, enabled: true };
const old = { manifest: { id: 'old', name: 'Old', command: 'old' }, enabled: false };
@@ -161,4 +162,39 @@ describe('mobile composer plugin selection', () => {
{ type: 'text', text: '$art ' }, atom, quote, { type: 'text', text: 'ar' },
]);
});
+
+ it('keeps desktop namespace and instanceKey, and qualifies same-name commands', () => {
+ const parsed = composerPluginListSchema.parse([
+ { manifest: { id: 'draw', name: 'Root', command: 'draw' }, enabled: true, namespace: null, instanceKey: 'draw' },
+ { manifest: { id: 'draw', name: 'Org', command: 'draw' }, enabled: true, namespace: 'acme', instanceKey: '_ns__acme__draw' },
+ ]);
+ expect(parsed.map((plugin) => [plugin.namespace, plugin.instanceKey])).toEqual([
+ [null, 'draw'],
+ ['acme', '_ns__acme__draw'],
+ ]);
+ const rootText = composerDocumentProjectedText(placeComposerPlugin(textComposerDocument('a cat'), parsed[0], parsed));
+ const orgText = composerDocumentProjectedText(placeComposerPlugin(textComposerDocument('a cat'), parsed[1], parsed));
+ expect(rootText).toBe('$draw/@root a cat');
+ expect(orgText).toBe('$draw/acme a cat');
+ const rootDirective = expandGhostCommand(rootText, parsed);
+ const orgDirective = expandGhostCommand(orgText, parsed);
+ expect(rootDirective).toContain('namespace: null');
+ expect(rootDirective).not.toContain('存在多个实例');
+ expect(orgDirective).toContain('namespace: acme');
+ expect(orgDirective).toContain('ghost_id: draw');
+ expect(orgDirective).not.toContain('存在多个实例');
+ });
+ it('keeps an old desktop list without namespace on the unqualified command', () => {
+ const parsed = composerPluginListSchema.parse([
+ { manifest: { id: 'art', name: 'Art', command: 'art' }, enabled: true },
+ ]);
+ expect(parsed[0].namespace).toBeUndefined();
+ expect(parsed[0].instanceKey).toBeUndefined();
+ const text = composerDocumentProjectedText(placeComposerPlugin(textComposerDocument('draw'), parsed[0], parsed));
+ expect(text).toBe('$art draw');
+ const directive = expandGhostCommand(text, parsed);
+ expect(directive).toContain('(id: art)');
+ expect(directive).not.toContain('ghost_id:');
+ expect(directive).not.toContain('namespace: ');
+ });
});
diff --git a/apps/mobile/src/__tests__/pluginInvocations.test.ts b/apps/mobile/src/__tests__/pluginInvocations.test.ts
index e3dbde9cf3..bada37d947 100644
--- a/apps/mobile/src/__tests__/pluginInvocations.test.ts
+++ b/apps/mobile/src/__tests__/pluginInvocations.test.ts
@@ -10,6 +10,27 @@ const msg = (id: string, role: RemoteMessage['role'], content: unknown, extra: P
const call = (id: string, name = 'mcp__cindy__ghost_call', input: unknown = { ghost_id: 'art', tool: 'generate' }) =>
msg(id, 'tool_use', { toolName: name, toolUseId: id, input }, { toolUseId: id });
describe('plugin annotations on user messages', () => {
+ it('keeps root and organization calls with the same id independent, even after projection', () => {
+ const rows = [msg('u', 'user', 'Use both'),
+ call('root', undefined, { ghost_id: 'helper', namespace: null, tool: 'root_tool' }),
+ msg('done', 'tool_result', 'done', { toolUseId: 'root' }),
+ call('org', undefined, { ghost_id: 'helper', namespace: 'acme', tool: 'org_tool' })];
+ expect(normalizeRemoteMessages(rows)[0].pluginInvocations).toMatchObject([
+ { id: 'helper', namespace: null, tools: ['root_tool'], hasPendingCalls: false },
+ { id: 'helper', namespace: 'acme', tools: ['org_tool'], hasPendingCalls: true },
+ ]);
+ for (const namespace of [null, 'acme']) {
+ const tool = namespace === null ? 'root_tool' : 'org_tool';
+ const projected = projectLargeSettledToolInputs([
+ msg('u2', 'user', 'Use plugin'),
+ call('big', undefined, { ghost_id: 'helper', namespace, tool, args: { data: 'x'.repeat(40_000) } }),
+ msg('result', 'tool_result', 'done', { toolUseId: 'big' }),
+ ]);
+ expect(normalizeRemoteMessages(projected)[0].pluginInvocations).toMatchObject([
+ { id: 'helper', namespace, tools: [tool], hasPendingCalls: false },
+ ]);
+ }
+ });
it('retains call identity when large arguments are released after completion', () => {
const source = [msg('u', 'user', 'Draw'), call('c', undefined, { ghost_id: 'art', tool: 'generate', args: { data: 'x'.repeat(40_000) } }), msg('r', 'tool_result', 'done', { toolUseId: 'c' })];
const projected = projectLargeSettledToolInputs(source);
diff --git a/apps/mobile/src/__tests__/pluginPage.test.ts b/apps/mobile/src/__tests__/pluginPage.test.ts
index 873086754f..351a6d6228 100644
--- a/apps/mobile/src/__tests__/pluginPage.test.ts
+++ b/apps/mobile/src/__tests__/pluginPage.test.ts
@@ -61,6 +61,7 @@ describe("mobile plugin page transport", () => {
TextDecoder,
Request,
Response,
+ Blob,
fetch,
});
},
@@ -134,6 +135,15 @@ describe("mobile plugin page transport", () => {
await expect(window.fetch("https://evil.invalid/steal")).rejects.toThrow(
"PLUGIN_ORIGIN_DENIED",
);
+ const gallery = window.fetch("cindy-ghost://practice/gallery");
+ const galleryRequest = JSON.parse(messages.at(-1)!);
+ expect(galleryRequest).toMatchObject({ type: "fetch", path: "/gallery", pageId: "page" });
+ window.dispatchEvent(new window.MessageEvent("message", { data: JSON.stringify({
+ type: "reply", id: galleryRequest.id,
+ result: { status: 200, mime: "application/json", base64: "W10=" },
+ }) }));
+ expect(await (await gallery).json()).toEqual([]);
+ await expect(window.fetch("cindy-ghost://_root__practice/gallery")).rejects.toThrow("PLUGIN_ORIGIN_DENIED");
window.document.getElementById("saved")!.textContent = "Unsaved draft";
window.dispatchEvent(
new window.MessageEvent("message", {
diff --git a/apps/mobile/src/__tests__/remoteResources.test.ts b/apps/mobile/src/__tests__/remoteResources.test.ts
index 764a836d27..1128f88577 100644
--- a/apps/mobile/src/__tests__/remoteResources.test.ts
+++ b/apps/mobile/src/__tests__/remoteResources.test.ts
@@ -167,6 +167,13 @@ describe('remote resource discovery', () => {
});
describe('remote resource response boundaries', () => {
+ it('retains maximum-length namespace instance refs while bounding malformed ids', () => {
+ const id = '_ns__' + 'a'.repeat(128) + '__' + 'p'.repeat(32);
+ const item = (value: string) => ({ ref: { collectionId: 'plugins', kind: 'plugin', id: value },
+ display: { title: 'Plugin' }, links: [], revision: '1' });
+ expect(normalizeRemoteCollectionItems({ items: [item(id), item('x'.repeat(257))] }, 'plugins')
+ .map((entry) => entry.ref.id)).toEqual([id]);
+ });
it('keeps valid additive items and drops malformed or cross-collection items', () => {
expect(normalizeRemoteCollectionItems({ items: [
{
diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.ts
index 5d970987b9..988407e3fe 100644
--- a/apps/mobile/src/device-link/remoteResources.ts
+++ b/apps/mobile/src/device-link/remoteResources.ts
@@ -4,6 +4,7 @@ import {
REMOTE_RESOURCE_LIST_CHANNEL,
REMOTE_RESOURCE_MANIFEST_CHANNEL,
REMOTE_RESOURCE_PROTOCOL_VERSION,
+ parseRemoteResourceRef,
resolveRemoteText,
type RemoteActionInvokeResponse,
type RemoteCollectionDescriptor,
@@ -135,11 +136,7 @@ function normalizeRemoteText(value: unknown, max = MAX_REMOTE_TEXT_CHARS): Remot
}
function normalizeRemoteRef(value: unknown): RemoteResourceRef | null {
- const record = recordOf(value);
- const collectionId = boundedString(record?.collectionId, MAX_REMOTE_ID_CHARS);
- const kind = boundedString(record?.kind, MAX_REMOTE_ID_CHARS);
- const id = boundedString(record?.id, MAX_REMOTE_ID_CHARS);
- return collectionId && kind && id ? { collectionId, kind, id } : null;
+ return parseRemoteResourceRef(value);
}
function normalizeRemoteStatus(value: unknown): RemoteResourceStatus | null {
diff --git a/apps/mobile/src/plugins/PluginPage.tsx b/apps/mobile/src/plugins/PluginPage.tsx
index 3c6a2f39e8..0eb7f85a37 100644
--- a/apps/mobile/src/plugins/PluginPage.tsx
+++ b/apps/mobile/src/plugins/PluginPage.tsx
@@ -497,14 +497,14 @@ export function PluginPage({
try {
url = new URL(
message.url,
- `cindy-ghost://${pluginId}/${documentRef.current?.entry ?? ""}`,
+ `cindy-ghost://${documentRef.current?.pluginId}/${documentRef.current?.entry ?? ""}`,
);
} catch {
return;
}
if (
url.protocol === "cindy-ghost:" &&
- url.hostname === pluginId &&
+ url.hostname === documentRef.current?.pluginId &&
url.pathname.startsWith("/preview/")
) {
await call("media:open", { url: url.href });
diff --git a/apps/mobile/src/session/PluginInvocationHeader.tsx b/apps/mobile/src/session/PluginInvocationHeader.tsx
index 727a797f9f..f071b3b465 100644
--- a/apps/mobile/src/session/PluginInvocationHeader.tsx
+++ b/apps/mobile/src/session/PluginInvocationHeader.tsx
@@ -16,13 +16,14 @@ const SUMMON_CYCLE_MS = 2400;
export function PluginInvocationHeader({ plugins, running, deviceId, sessionId, showCompletionBadge = true }: {
plugins: readonly PluginInvocation[]; running: boolean; deviceId?: string; sessionId: string; showCompletionBadge?: boolean;
}) {
- return <View>{plugins.map((plugin) => <PluginInvocationRow key={plugin.id} plugin={plugin} running={running && plugin.hasPendingCalls} deviceId={deviceId} sessionId={sessionId} showCompletionBadge={showCompletionBadge} />)}</View>;
+ return <View>{plugins.map((plugin) => <PluginInvocationRow key={JSON.stringify([plugin.id, plugin.namespace === undefined ? false : plugin.namespace])} plugin={plugin} running={running && plugin.hasPendingCalls} deviceId={deviceId} sessionId={sessionId} showCompletionBadge={showCompletionBadge} />)}</View>;
}
function PluginInvocationRow({ plugin, running, deviceId, sessionId, showCompletionBadge }: {
plugin: PluginInvocation; running: boolean; deviceId?: string; sessionId: string; showCompletionBadge: boolean;
}) {
- const identity = useSessionPluginResource(deviceId, sessionId, plugin.id, 'plugin-identities', 'plugin');
+ const resourceId = plugin.namespace === undefined ? plugin.id : JSON.stringify([plugin.namespace, plugin.id]);
+ const identity = useSessionPluginResource(deviceId, sessionId, resourceId, 'plugin-identities', 'plugin');
const name = identity.title || plugin.name;
const icon = (identity.blocks?.find((block) => block.id === 'icon')?.data as { url?: unknown } | undefined)?.url;
const iconUrl = typeof icon === 'string' && icon.length <= 256_000 && /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(icon) ? icon : undefined;
diff --git a/apps/mobile/src/session/composerPlugins.ts b/apps/mobile/src/session/composerPlugins.ts
index 7bd2773718..9909949a65 100644
--- a/apps/mobile/src/session/composerPlugins.ts
+++ b/apps/mobile/src/session/composerPlugins.ts
@@ -1,4 +1,9 @@
-import type { GhostCommandSource } from '@cindy/maker-shared/ghost-command';
+import {
+ formatGhostCommandInsertion,
+ ghostCommandTokenLength,
+ parseGhostCommandToken,
+ type GhostCommandSource,
+} from '@cindy/maker-shared/ghost-command';
import {
composerDocumentProjectedText,
normalizeComposerDocument,
@@ -41,7 +46,8 @@ export function placeComposerPlugin(
plugin: GhostCommandSource,
roster: readonly GhostCommandSource[],
): ComposerDocument {
- if (!plugin.manifest.command || !plugin.enabled) return document;
+ const insertion = formatGhostCommandInsertion(plugin, roster);
+ if (!insertion || !plugin.enabled) return document;
let normalized = normalizeComposerDocument(document);
const text = composerDocumentProjectedText(normalized);
const trigger = detectComposerPluginTrigger(text);
@@ -64,14 +70,15 @@ export function placeComposerPlugin(
if (node.type !== 'text') break;
leadingText += node.text;
}
- const match = /^\s*[$$¥¥](\S{1,32})(?=\s|$)/u.exec(leadingText);
- const replace = match && roster.some((entry) =>
- entry.manifest.command?.toLowerCase() === match[1].toLowerCase());
- const end = replace ? match[0].length : 0;
+ const leadingSpace = leadingText.match(/^\s*/u)?.[0].length ?? 0;
+ const token = parseGhostCommandToken(leadingText.slice(leadingSpace));
+ const replace = !!token && roster.some((entry) =>
+ entry.manifest.command?.toLowerCase() === token.word.toLowerCase());
+ const end = replace && token ? leadingSpace + 1 + ghostCommandTokenLength(token) : 0;
const nextCharacter = leadingText[end];
const nodes: ComposerDocument['nodes'] = [{
type: 'text',
- text: '$' + plugin.manifest.command + (nextCharacter && /\s/u.test(nextCharacter) ? '' : ' '),
+ text: insertion + (nextCharacter && /\s/u.test(nextCharacter) ? '' : ' '),
}];
let remaining = end;
for (const node of normalized.nodes) {
diff --git a/apps/mobile/src/session/messageToolPayloadProjection.ts b/apps/mobile/src/session/messageToolPayloadProjection.ts
index 13cb480b01..4eddeb8fde 100644
--- a/apps/mobile/src/session/messageToolPayloadProjection.ts
+++ b/apps/mobile/src/session/messageToolPayloadProjection.ts
@@ -89,9 +89,9 @@ export function projectLargeSettledToolInputs(
...message,
content: {
input: /(?:^|:|__)ghost_call$/.test(tool.toolName) && tool.input && typeof tool.input === 'object'
- ? Object.fromEntries(['ghost_id', 'tool', 'grant_only'].flatMap((key) => {
+ ? Object.fromEntries(['ghost_id', 'namespace', 'tool', 'grant_only'].flatMap((key) => {
const value = (tool.input as Record<string, unknown>)[key];
- return typeof value === 'boolean' || (typeof value === 'string' && value.length <= 256) ? [[key, value]] : [];
+ return (key === 'namespace' && value === null) || typeof value === 'boolean' || (typeof value === 'string' && value.length <= 256) ? [[key, value]] : [];
})) : null,
mobilePayloadProjected: true,
toolName: tool.toolName,
diff --git a/apps/mobile/src/session/pluginInvocations.ts b/apps/mobile/src/session/pluginInvocations.ts
index 95cf1efa80..7b78820e11 100644
--- a/apps/mobile/src/session/pluginInvocations.ts
+++ b/apps/mobile/src/session/pluginInvocations.ts
@@ -3,6 +3,7 @@ import type { RemoteMessage } from './types';
export interface PluginInvocation {
id: string;
+ namespace?: string | null;
name: string;
tools: string[];
hasPendingCalls: boolean;
@@ -11,6 +12,10 @@ export interface PluginInvocation {
const record = (value: unknown): Record<string, unknown> | undefined =>
value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
const text = (value: unknown) => typeof value === 'string' && value.length <= 256 ? value : undefined;
+const pluginNamespace = (value: unknown): string | null | undefined =>
+ value === null ? null : typeof value === 'string' && value.length <= 128 ? value : undefined;
+const identityKey = (id: string, namespace: string | null | undefined) =>
+ JSON.stringify([id, namespace === undefined ? false : namespace]);
/** Read only the documented MCP text envelope, never arbitrary nested plugin data. */
function infoName(raw: string | undefined, id: string): string | undefined {
@@ -45,11 +50,12 @@ export function collectPluginInvocations(
for (const message of messages) {
if (message.role !== 'tool_use') continue;
const tool = parseMessageToolUse(message);
- const id = text(record(tool.input)?.ghost_id);
+ const input = record(tool.input);
+ const id = text(input?.ghost_id);
if (!id || !/(?:^|:|__)ghost_info$/.test(tool.toolName)) continue;
const raw = pairing.resultContentFor(message, tool);
const name = infoName(raw, id);
- if (name) names.set(id, name);
+ if (name) names.set(identityKey(id, pluginNamespace(input?.namespace)), name);
}
const turns = new Map<string, PluginInvocation[]>();
let owner: string | undefined;
@@ -64,9 +70,13 @@ export function collectPluginInvocations(
const input = record(tool.input);
const id = text(input?.ghost_id);
if (!id || input?.grant_only === true) continue;
+ const namespace = pluginNamespace(input?.namespace);
const calls = turns.get(owner) ?? [];
- let plugin = calls.find((call) => call.id === id);
- if (!plugin) { plugin = { id, name: names.get(id) ?? id, tools: [], hasPendingCalls: false }; calls.push(plugin); }
+ let plugin = calls.find((call) => call.id === id && call.namespace === namespace);
+ if (!plugin) {
+ plugin = { id, ...(namespace !== undefined ? { namespace } : {}), name: names.get(identityKey(id, namespace)) ?? id, tools: [], hasPendingCalls: false };
+ calls.push(plugin);
+ }
// Known IDs must pair exactly: an adjacent result may belong to another
// concurrent plugin. Legacy ID-less calls retain the existing pairing fallback.
const settled = tool.toolUseId
diff --git a/apps/mobile/src/session/remoteComposerPlugins.ts b/apps/mobile/src/session/remoteComposerPlugins.ts
index a0842be807..cedc0fd070 100644
--- a/apps/mobile/src/session/remoteComposerPlugins.ts
+++ b/apps/mobile/src/session/remoteComposerPlugins.ts
@@ -13,6 +13,13 @@ export const composerPluginListSchema = z.array(z.object({
})).optional(),
}),
enabled: z.boolean(),
+ /** Absent on old peers. null is an explicit root instance. */
+ namespace: z.string().min(1).nullable().optional(),
+ /**
+ * Physical instance key. Absent on old peers; never a filesystem path.
+ * In-place migrated installs keep their original key, which can differ from manifest.id.
+ */
+ instanceKey: z.string().min(1).max(167).optional(),
iconDataUrl: z.string().optional(),
}));
export type ComposerPlugin = z.infer<typeof composerPluginListSchema>[number];
diff --git a/docs/dev-rules/plugin-library-storage.md b/docs/dev-rules/plugin-library-storage.md
index 1e1a2bf77c..923690d1f9 100644
--- a/docs/dev-rules/plugin-library-storage.md
+++ b/docs/dev-rules/plugin-library-storage.md
@@ -55,6 +55,8 @@ backups)对插件不可达——路径语法段首不许点,协议层天然
实际撤 grant。自动 open 失败要把 drift 记进 session,同盘归位后仅 `status` 也须恢复。合法 default
首次创建仍可 mkdir。被 rename 走的原件仍在旧目录,不称已删除。同一磁盘对象归位后既有 `open`/`status`
恢复,删后重建的同路径是 `binding-moved` 不是原盘回归。Windows st_ino=0 检不出同路径重建,已知限制。
+ 既有 Library meta 的插件身份与当前物理实例不一致时不得打开;namespace 物理搬迁
+ 必须随数据同步更新 meta 身份,恢复重试可重复执行但不得认领其它插件的库。
插件侧同样语义写进了 FORGE_GUIDE。
2. **卸载不删**:uninstall 只标 orphaned + 作废会话;binding 保留(用户亲选
事实不因重装消失)。删除 = 设置页独立破坏性确认 + `trashGhostLibrary`
@@ -63,6 +65,9 @@ backups)对插件不可达——路径语法段首不许点,协议层天然
3. **owner 隔离**:会话绑定 `activeOwnerScopeKey` 每请求比对;切换在途由
`interruptGhostCallsForAccountBoundary` 的 `disposeAll` 收口(在途写入随串行
链归属原 owner)。根解析每次经 binding store 现解。
+ Host 的 bind/unbind/relocate/revert-default 与换源归档共用安装变更队列,复制及 binding
+ 提交必须在同一队列操作内完成;排队前捕获安装目标,出队后复核,目标变化时拒绝旧操作。
+ owner mutation 租约只稳定账号归属,不能替代此互斥队列。
4. **路径纪律**:相对路径四层校验(`isSafeGhostRelativePath` →
`validateLibraryRelPath` → `isInsideDir` → realpath 祖先收敛),目标 lstat
不穿透 symlink。写入 = staging + fsync + rename + dev/ino identity 复验
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index ffda2d5955..29d469f549 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -45,10 +45,81 @@
- `.cindy` 是以 `ghost.json` 为身份卡的插件包,现行唯一形态为 `kind: 'chip'`。
- 代码目录与运行时使用 `cindy-brain` / `Ghost` 命名,**不得重新引入已退役的 cartridge
声明型兼容层**。
-- `cindy-` / `filo-` / `xd-` 是官方保留 id 前缀,第三方插件不得占用;前缀正本见
- `apps/desktop/src/shared/ghost.ts` 的 `GHOST_OFFICIAL_ID_PREFIXES`。
-
-### 1.1 Manifest v3 直接能力声明
+- `cindy-` 保留为平台官方命名;`filo-` / `xd-` 可作为普通插件名称,名称本身不授予特权。
+ 旧官方资格只从升级时真实旧安装的可信批准与来源事实保留,换源后清除。企业 XD 宿主
+ 能力核对 namespace、当前组织与已批准包来源,不要求名称带 `xd-`。保留命名判据见
+ `apps/desktop/src/shared/ghost.ts` 的 `isUserInstallReservedGhostId`。
+
+### 1.1 服务端阶段与安装身份
+
+客户端同时承接 S1、S2 关闭和 S2 开启,不根据是否收到 namespace 判断阶段,也不自造阶段开关。
+S1 和 S2 关闭时保留旧认领与发布入口,由服务端执行命名准入;S2 开启后同一客户端可以
+安装和运行自然命名的企业实例。namespace 缺失是旧协议待确认状态,只有显式 null 才是 root。
+通过安装入口新装的 root 插件使用 `_ns/_root/<id>` 和 `_root__<id>` 数据键,企业新实例使用
+`_ns/<namespace>/<id>`;`_root` 仅是目录保留名,root 的 namespace 仍为 null。
+旧安装只原位确认 namespace,保留原目录与数据键;更新时也不搬迁。安装同名 root 不停旧企业插件,
+不搬旧数据、凭证或界面引用。内置种子沿用既有布局。
+namespace 迁移读取市场账本时区分缺失与损坏,损坏证据不能作为 root 或手动来源的依据。
+普通账本写回也不得过滤并删除坏行,避免后续迁移把损坏事实误判为无记录。
+断连的企业市场记录仍匹配原批准内容时保持 pending;恢复失败或常驻重试不能把它认作手动 root。
+已完成迁移的旧 Forge 安装保留 namespace 与批准修订号;降级丢失 namespace 后,只在原批准、
+Forge 来源及当前组织分类都吻合时恢复,不能据此认领普查后新装的实例。
+同来源 Forge 更新先持久化原/新批准修订的桥接证据,提交和回滚都保留该旧实例的恢复资格。
+旧组织身份缺少 orgSlug 时,发布先刷新已验签身份;仍缺失则从当前服务端市场的
+currentOrganization 核对同组织、同 membership 与 owner 后补齐,不能把前缀当成 namespace。
+
+安装、调用、项目启停、OAuth、媒体归属和卸载必须使用 Main 核准的实例键,不能用 URL host
+或裸插件名选取同名实例。调度器只绑定可信 XD 企业实例;旧调用没有明确实例且同名候选
+不唯一时,不默认选择 root。OAuth 连接在开始时绑定批准版本、owner 和实例,最终写入
+仍在凭证锁内复核,身份变更后旧流程不得把账号写给替代实例。
+面板和逻辑页的内存 session 绑定 owner 代次、批准版本及目录,协议注册事实不可原位复用。
+旧页即使尚未被 Renderer 销毁,也不能在替换后发起新请求;异步响应返回前再次核对绑定。
+外部请求保留 namespace 缺失/null/组织三态;选定实例后的内部复核、订阅队列、下载和
+外链导航按物理实例定位,不再用裸名字重新选择。文件确认记忆及授权卡 adapter 绑定安装
+身份,不能跨实例复用授权;身份或批准变化使旧卡失效,恢复卡先更新实例与交互版本。
+普通 Setup 的 Connection 和 Secret 表单在创建时绑定安装批准版本,最终写入再次核对;
+相同物理键和 manifest 不代表相同安装。持久 Bot 授权卡保存批准绑定,恢复时批准变化则
+终结旧卡;缺少绑定的旧卡先绑定当前安装并提高交互版本,旧提交不能直接执行。
+同批准版本的合法物理位置变化仍刷新卡片身份后恢复,不按换源处理。
+新 root 技能快照的断链回收识别 `_ns/_root/<id>`,仍须核对受管根、root 身份和插件 ID,
+不得覆盖真实目录或删除外来链接。
+历史交互卡及手机插件资源只按持久化的物理实例键定位,实例消失后不得回退到同名逻辑身份。
+手机 relay 和资源 fetch 复用该实例实际运行的批准版本分区,不能仅按 manifest id 构造分区。
+手机资源 ref 使用物理实例键;PluginPageDocument.pluginId 仍是协议 host(manifest id),
+不能拿资源 ref 拼协议 URL。资源 id 独立允许至 256 字符,覆盖最长 namespace 实例键,
+手机列表与 Host 请求复用同一 ref parser;collection、kind 等其它标识仍保持原上限。
+
+旧集成账号导入只允许仍有历史来源资格或可信内置资格的已批准原物理实例;
+换源清除资格后,保留的旧凭证文件不得再次导入。OAuth 导入还须核对原提供方路径:
+Google 直连仅使用确切的 Google token endpoint,Atlassian 仅使用原 jira broker。
+面板关闭请求携带用户确认时的批准版本,Main 在停止运行时前及安装变更队列内复核;
+迟到的确认不得停用替代安装。
+
+同来源更新延续原实例与数据。真正换源时,安装事务把旧密钥、OAuth、连接、KV、私有文件、
+Library、媒体、卡片归属、偏好、亲选目录、errand 会话映射及普通任务回执隔离归档;新来源不能自动继承。
+任务回执的实例键在既有任务写入队列中归档,保留原任务、消息、成果和请求身份,并增加修订号使旧写入失效。
+换源不继承旧任务能力批准;新来源即使重新获批也不能读取归档任务。同来源更新和原位 namespace 确认保留原归属。
+旧包回滚时恢复旧数据和任务归属;中断恢复依据
+receipt 的提交版本选择归档或还原,恢复未完成前保持隔离。普通升级迁移不属于换源,
+不要求旧插件重新授权。归档不会把历史任务和面板改指向一个可运行的归档插件。
+归档恢复与安装、卸载共用变更队列,并在回调前后核对 owner、journal 和 receipt;
+归档与卸载统一先取得安装变更队列,再取得任务写入队列;任务存储就绪后重试未完成恢复。
+换源归档的暂存上传除搬目录,还迁移库 meta、任务 manifest 和
+未完成 intent 的实例归属,保留原任务、owner、校验和与文件字节;失败可按日志重放。
+旧恢复任务不能覆盖后续重装。损坏批准的本地包仍可明确重装恢复,但不继承旧来源资格。
+有在途工具、文件请求、网络请求或 AI 工作时先等待,网络请求从异步凭证准备起计入在途;
+网络响应及媒体落仓全程复核入口绑定的安装批准与 owner。异步用户确认绑定原安装目标,不让晚到的结果
+重建原键或授权给替代实例。资源迁移幂等重放现有安装日志,
+中途失败保留日志与隔离,不能靠只存于内存的回滚闭包认定恢复完成。
+已有安装/更新恢复日志时,后续更新或卸载不得覆盖该日志或解除隔离;已有卸载日志按原意图续跑。
+
+Library 目录重命名必须有持久、owner 绑定的事务证据,重放校验原目录与授权根的文件身份
+及绑定代次。目标目录已存在但没有本事务证据时仍拒绝,不得把它当作自己的已完成重命名。
+换源归档及其预检严格读取 Library binding;读取失败、损坏配置或无效记录必须拒绝,不能按默认位置继续。
+Library 请求同时绑定迁移代次和安装批准,根解析、排队及开库之后都复核;迁移结束清旗标
+不恢复旧请求的资格,避免延迟请求在归档后重建原目录或阻断回滚。
+
+### 1.2 Manifest v3 直接能力声明
- 新插件统一使用 `schemaVersion: 3`,并填写插件实际依赖的首个 Cindy 正式版本作为
`minCindyVersion`。Manifest schema 不设置统一的 Cindy 版本下限;具体版本只属于插件包元数据。
@@ -159,10 +230,13 @@
策略为 `exempt`,不向用户确认。豁免只绑当前用户对该条目的默认下发资格:目录仍标
`defaultInstall`、但用户已退订后再自行从市场安装的,扩权更新必须确认。
- 市场安装账本是后续更新来源的唯一事实:服务端市场按 `pluginId + releaseId` 路由,
+ 任一来源账本文件存在却损坏时,读写都必须拒绝,不得把其它来源的记录当成完整视图重写并覆盖损坏文件。
自定义市场还必须匹配 `sourceKey`;已装目录的原始 `ghost.json` 字节 SHA-256 必须与账本
一致。旧记录缺少 raw 字段时,Host 只能按已发布的 legacy digest 编码核对同一份受限读取
的字节,命中后原地补字段且不改 `updatedAt`;raw 字段已经存在但不匹配时必须 fail closed,
不得用当前目录覆盖基线。`manifestDigest` 保留旧语义供降级客户端读取,不能改写成 raw SHA。
+ 无账本的旧前缀认领还须具备已完成历史迁移、无包哈希的批准回执及匹配的已批准 manifest;
+ Forge、现代重装回执和已知 namespace 不匹配的安装不能仅凭前缀自动认领。
同 id 来源冲突或目录漂移通常不得被自动覆盖,只能由用户显式选择替换来源。唯一受控例外是:
当前组织下发 `defaultInstall`、组织与合法非空前缀都精确匹配、同 ghost id 在目录中唯一时,
可以接管无有效市场来源的普通本地安装,或修复同一目标 `pluginId` 的坏 market / legacy-adopted
@@ -310,10 +384,7 @@
且安装目录 `ghost.json` 的 raw SHA(旧记录迁移前为集中 legacy digest)与记录一致;
Manifest 与身份必须来自同一次受限读取,禁止分两次读取后分别校验与消费;或企业作者显式使用 `ghost_forge_install`
安装、在提交前核对插件 id 与精确注入域名,且插件 id 命中当前组织前缀。手动导入不取得
- Forge 作者资格。另有一条点名例外:`ghostId` 精确等于 `mivo-canvas` 的组织成员本地安装,
- 在已装 manifest 声明的精确 `oidc-token` host 仅为 `mivo-canvas.dsworks.cn` 时可解析 audience;其它本地插件、个人账号、
- 通配 host、其它精确 host 仍不签发。若该插件已有市场 organization 记录(含 `installed:false` 的卸载残留),不得走白名单捷径,必须仍走
- digest 校验。市场账本损坏、schema 不认或该 ghostId 记录校验失败时 fail-closed,不得当成「无记录」走例外。Host 根据当前组织和插件 id 推导 audience。
+ Forge 作者资格。另有一条临时例外,计划在 XD 企业市场版 `mivo-canvas` 上线并发布一次性数据迁移后删除,只对 root 实例生效:`ghostId` 精确等于 `mivo-canvas`;已装 manifest 声明的精确 `oidc-token` host 只有 `mivo-canvas.dsworks.cn`;只在组织身份校验之后且没有市场记录时生效,已有 organization 记录(含 `installed:false`)仍走 digest,市场账本损坏、schema 不认或记录校验失败时 fail-closed,不得当成「无记录」;实例 namespace 必须为 null,或是尚未写入 namespace 的旧 root 安装。`_ns/xd/mivo-canvas` 这类企业实例、其它本地插件、个人账号、通配 host 和其它精确 host 仍不签发。Host 根据当前组织和插件 id 推导 audience。
插件和 Node Worker 都不能读取或保存令牌。声明必须固定使用
`Authorization: Bearer {value}` 并显式列出非空 `inject.hosts`;其中只允许精确域名,
不允许通配。实际目标必须精确命中这份可信 manifest 声明的服务域名才会签发和注入。它没有用户输入、`url`、`exchange` 或
@@ -519,6 +590,33 @@
文件(包已丢失就无从恢复)。安全方向是对的,落地方式把一次内部机制升级变成了全量
用户故障。
+
+### 5.1 实例注册表
+
+每个数据所有者一份 `plugin-instances.v2.json`。记录包含 `instanceKey`、目录 `contentRelId`、`ghostId`、`namespace`、`namespaceState`、`pluginId`、`source`、receipt 修订和包 sha。旧的 `plugin-instances.v1.json` 只在第一次加载时读一次并导入,之后留在磁盘上,不再写入。
+
+`instanceKey` 由安装目录推出,不另分配:旧 root 是 `helper`,新 root 是 `_root__helper`,企业是 `_ns__<namespace>__<ghostId>`。注册表丢失或损坏时按目录重建,KV、密钥和 OAuth 仍挂在这个键上。
+
+`namespaceState`:
+
+- `confirmed`:身份已确认,可以按该 namespace 使用 Broker、OIDC 等新权限。
+- `pending`:这次升级普查时已经存在、receipt 还没有 namespace 的旧安装。按升级前的规则继续运行,不停用。
+- `unconfirmed`:曾经确认过的 namespace 被旧客户端抹掉,或证据不够。不给新权限,等市场同步或 Forge 自测的正面证据再确认。
+
+市场同步补写账本 namespace 的条件只有一条:该行已安装,pluginId、ghostId、scope、organizationId 都与服务端目录一致,而且行上没有 namespace 字段。只补缺失,不覆盖已有值。非法 slug 不写。组织行上的显式 null 也不写成 root。
+
+### 5.2 迁移中按名称判断归属的唯一例外
+
+升级普查里、来源是 Forge 自测(agent-forge)的旧安装,如果 ghostId 以当前组织登记的前缀加连字符开头,就归到当前组织的 orgSlug。这是唯一允许按名称判断归属的例外。
+
+旧 Forge 安装没有市场 pluginId 或其他归属证据。旧客户端本来就按这个前缀给 Forge 自测安装发 Connection 权限,所以按同一前缀迁到当前 orgSlug 不会扩大权限。
+
+- 只对这次升级普查时已经存在的旧安装生效。普查之后新装的 Forge 插件在安装时已经绑定 namespace,不走这条规则。
+- 前缀按当前组织 id 从组织前缀记录查出。ghostId 以前缀加连字符开头时,namespace 取当前 token 的 orgSlug,不是前缀本身。orgSlug 和前缀可以不同。
+- 当前 token 没有合法 orgSlug 时保持待迁移,不写成 root。
+- 当前组织的前缀对不上这个 ghostId 时保持待迁移,插件按旧规则继续运行,不报错。作者以后登录前缀匹配的组织,再完成迁移。
+- 归属一旦写入注册表并确认,再切换组织也不会改这条记录。
+
## 6. 作者契约与编写手册同步
`FORGE_GUIDE` 是 agent 替用户编写插件的**唯一教材**,由 `ghost_forge_guide` 现拿现读。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index a6670a7482..9b061e90cf 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -98,8 +98,9 @@ Chat Server 新增只读 `/conversations/:roomId/execution-failures`:按成员
## Desktop 远程新建菜单
同账号控制端通过新增只读 `ghosts:composer-list(workingDir?)` 异步取得执行主机的插件菜单。
-响应仅含名称、ID、指令、工具声明、图标、Skill 存在标记与目录过滤后的启用状态,不传安装路径、
-批准记录、配置或凭证。无项目时不传参数;共享任务访客不开放此通道。
+响应仅含名称、ID、实例键、namespace、指令、工具声明、图标、Skill 存在标记与目录过滤后的启用状态,
+不传安装路径、批准记录、配置或凭证。目录禁用按实例键匹配,不用裸 ID;旧主机可以不带实例键和 namespace。
+无项目时不传参数;共享任务访客不开放此通道。
远程清单按序列化后的 UTF-8 字节限制为 1 MiB,为传输封装预留空间;保留所有插件的基础信息,
先容纳工具声明、再容纳图标。超出剩余预算的可选字段整项省略,工具声明缺失时复用现有
`ghost_list` 按需查询,图标缺失时显示通用图标。基础信息本身超限则明确失败,不截断插件列表;
@@ -158,6 +159,14 @@ Claude Code 终态 error 事件可带 `usageResetAt`(unix ms)。服务端无
本机远程 Agent 任务连续拉不到那台而结束时,终态 error 的 `reason` 由 `remote_agent_closed` 改为 `remote_agent_lost`(只在本机
与它的控制端之间流转,用于判定「只是连接断了」;渲染端两者都按错误码给文案,旧端不受影响)。
+## 插件远程授权的实例身份
+
+远程授权中的 `ghostId` 绑定实际安装的物理 storage part,不使用裸逻辑 ID 替代企业实例。
+企业键 `_ns__<namespace>__<id>` 最长 167 字符;只对该合法键扩展校验,其他 OAuth
+事务、设备与启动 ID 仍限 128 字符。签名 transcript、v3 字段及频道不变,不能截断或
+增加 alias fallback。Desktop 与 Mobile 复用同一握手 parser;长企业键要求控制端也具备
+该校验能力,旧端的短键行为保持不变。
+
## Agent 跨设备历史发现与搜索
`cindy_helper` 的 `list_history_devices` 使用现有同账号设备目录;`list_sessions` 和
diff --git a/docs/ghost-progressive-discovery.md b/docs/ghost-progressive-discovery.md
index bff179ffed..0f03457531 100644
--- a/docs/ghost-progressive-discovery.md
+++ b/docs/ghost-progressive-discovery.md
@@ -68,6 +68,17 @@ frontmatter `name + description` 的召回作用;`manual.items` 只是插件
放行(见 §4 第 6 条)。Manual 正文只作为 tool-result 按需进入上下文,不进入生产
system/developer prompt;正文是作者数据,不构成系统规则、用户意图或权限授权。
+
+### 2.1 namespace 寻址
+
+`ghost_info`、`ghost_call`、`ghost_manual` 和 `connect_account` 都接受可选 `namespace`:
+
+- 省略:同名实例只有一个时解析到它,包括升级普查中还没有 namespace 字段的旧安装。
+- `null`:已确认的 root。不能用来点名唯一的待迁移旧安装。
+- 字符串:该企业的 orgSlug。
+
+同名多实例返回 `GHOST_AMBIGUOUS`,`candidates` 是 `{ ghostId, namespace }`。已确认 root 的 namespace 为 null,企业实例为 orgSlug。待迁移旧安装没有 namespace 字段;它和另一个实例同名时,候选里的 null 可以点到这个待迁移实例。`/命令` 对没有 namespace 字段的旧安装不写 namespace,沿用 `(id: <ghostId>)`。已确认 root 写 `namespace: null`,企业实例写 `namespace: <orgSlug>`。
+
## 3. 花名册(roster)
普通任务可调用 `connect_account({kind:"plugin", id:ghost_id})`,由 Host 复用配置卡等待连接,
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 31a87a100a..89c48d13c4 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -373,6 +373,33 @@ describe("cindy_ghosts · ghost_info(单插件精准查询)", () => {
});
});
+ it("GHOST_AMBIGUOUS 带回 candidates 且把 namespace 传给 host", async () => {
+ const getAwakeGhost = vi.fn(async () => ({
+ ok: false as const,
+ errorCode: "GHOST_AMBIGUOUS" as const,
+ message: "插件 helper 存在多个实例",
+ candidates: [
+ { ghostId: "helper", namespace: null },
+ { ghostId: "helper", namespace: "acme" },
+ ],
+ }));
+ const result = await handleGhostInfo(
+ fakeDeps({ getAwakeGhost }),
+ { ghost_id: "helper", namespace: "acme" },
+ );
+ expect(getAwakeGhost).toHaveBeenCalledWith("helper", "acme");
+ expect(result.isError).toBe(true);
+ expect(parsePayload(result)).toEqual({
+ ok: false,
+ errorCode: "GHOST_AMBIGUOUS",
+ message: "插件 helper 存在多个实例",
+ candidates: [
+ { ghostId: "helper", namespace: null },
+ { ghostId: "helper", namespace: "acme" },
+ ],
+ });
+ });
+
it.each([
["GHOST_ASLEEP", "目标插件未启用"],
["GHOST_DISABLED_IN_WORKDIR", "当前工作目录已停用"],
@@ -1239,14 +1266,14 @@ describe("cindy_ghosts · server 构建", () => {
expect(infoDescription).toContain("完全没有目标线索时才用 ghost_list");
expect(infoDescription).toContain("不要缓存");
expect(infoDescription).toContain(
- "GHOST_NOT_FOUND(不存在、已卸载、当前账号不可用或未提供工具和手册)",
+ "GHOST_AMBIGUOUS",
);
expect(infoDescription).toContain("GHOST_DISABLED_IN_WORKDIR");
- expect(infoDescription).toContain("INTERNAL(内部查询失败)");
+ expect(infoDescription).toContain("INTERNAL");
const manualDescription =
server._registeredTools.ghost_manual?.description ?? "";
expect(server._registeredTools.ghost_list?.description).toContain(
- "manual 轻量索引",
+ "namespace",
);
expect(server._registeredTools.ghost_info?.description).toContain(
"需要长文时用 ghost_manual",
@@ -1764,6 +1791,17 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
const GHOST_ROSTER_CACHE_PREFIX_BUDGET_CHARS = 8_000;
describe("formatGhostRoster(花名册快照:JSONL 召回数据源)", () => {
+ it('preserves root and organization identities in both prompt and tool roster', async () => {
+ const { buildGhostRosterPrompt, formatGhostRoster } = await import('../ghost/mcpServer');
+ const items = [
+ { id: 'helper', namespace: null, name: 'Root' },
+ { id: 'helper', namespace: 'acme', name: 'Organization' },
+ ];
+ for (const roster of [formatGhostRoster(items), buildGhostRosterPrompt(items)]) {
+ expect(roster).toContain('"namespace":null');
+ expect(roster).toContain('"namespace":"acme"');
+ }
+ });
it("固定字段序列化;折叠/截断/空清单/条数/预算", async () => {
const { formatGhostRoster } = await import("../ghost/mcpServer");
expect(formatGhostRoster([])).toBe("");
@@ -2111,6 +2149,8 @@ describe('Cindy market MCP transport', () => {
await client.callTool({ name: 'ghost_info', arguments: { ghost_id: 'art' } });
await client.callTool({ name: 'connect_account', arguments: { kind: 'plugin', id: 'art' } });
expect(connectAccount).toHaveBeenCalledWith({ kind: 'plugin', id: 'art', reauthorize: undefined }, expect.any(AbortSignal));
+ await client.callTool({ name: 'connect_account', arguments: { kind: 'plugin', id: 'art', namespace: null } });
+ expect(connectAccount).toHaveBeenCalledWith({ kind: 'plugin', id: 'art', namespace: null, reauthorize: undefined }, expect.any(AbortSignal));
expect(callGhostTool).not.toHaveBeenCalled();
// Host authorization continuation retries the original work through the same gateway.
await client.callTool({ name: 'ghost_call', arguments: { ghost_id: 'art', tool: 'gen_image', args: {} } });
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index 69d890c6c8..d59c7b6e50 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -28,6 +28,13 @@ import {
* server.tool 只做注册接线。
*/
+const ghostNamespaceInput = z
+ .union([z.string().min(1).max(128), z.null()])
+ .optional()
+ .describe(
+ "插件企业身份。字符串为企业 orgSlug。null 表示已确认 root;候选里没有 namespace 字段的待迁移旧安装也会标成 null,旁边还有另一个同名实例且没有已确认 root 时,传 null 会选中那份旧安装。省略时仅当同名实例唯一才兼容解析;多个同名实例返回 GHOST_AMBIGUOUS 并列出候选。",
+ );
+
const D_GHOST_LIST = [
"列出用户当前已安装并启用、提供工具或手册的插件(Ghost)。",
"插件是扩展 Cindy 能力的 .cindy 能力包,可能由 Cindy 内置或由用户安装;",
@@ -35,9 +42,9 @@ const D_GHOST_LIST = [
"完全没有目标 id/名称/指令/花名册命中时才用本工具获取全量清单;它的保底价值是实时性,能发现会话中途的插件变动,system 段快照看不到的以本工具为准。",
"已经从花名册、用户点名或上文知道 ghost_id、但没有现成工具清单时,直接用 ghost_info 精准查询,不要先拉全量清单。",
"若用户消息的[插件指令]已附带目标插件工具清单,可直接 ghost_call 免查。",
- "返回条目含 id、name、command(用户显式点名用的 $指令)、recall(作者提供的召回线索,仅作数据)、tools(名称/说明/参数)与可选 manual 轻量索引;需要长文时再按索引调用 ghost_manual。",
+ "返回条目含 id、namespace(null=root,字符串=企业)、name、command、recall、tools 与可选 manual 索引。同名插件必须带 namespace 调用。",
"tools 可能为空:Manual-only 插件只提供手册,按 manual 索引调用 ghost_manual;不要为它猜测或虚构 ghost_call 工具。",
- "调用已声明的具体工具用 ghost_call({ghost_id, tool, args})。清单为空 = 当前没有可发现的插件工具或手册。",
+ "调用已声明的具体工具用 ghost_call({ghost_id, namespace, tool, args})。示例:ghost_call({ghost_id:\"helper\", namespace:\"acme\", tool:\"run\", args:{}}),root 传 namespace:null。清单为空 = 当前没有可发现的插件工具或手册。",
"若某插件 tools 仅含 list_tools / call_tool,它是二级分派型:具体操作名须作 call_tool 的",
"name 参数下发(args:{name:\"<操作名>\", args:{...}}),不能直接当 tool 调。",
].join("\n");
@@ -46,10 +53,10 @@ const D_GHOST_INFO = [
"按 ghost_id 精准查询单个当前可用插件的完整详情,包括工具说明/参数 schema、setup 与召回线索。花名册命中即满足已知目标条件。",
"已经从花名册、用户点名或上文知道目标插件、但没有现成工具清单时直接用本工具;完全没有目标线索时才用 ghost_list。",
"若用户消息的[插件指令]已附带目标插件工具清单,可直接 ghost_call 免查。",
- "返回单条完整形态:id、name、command、recall、setup、tools 与可选 manual 轻量索引;拿到目标工具后用 ghost_call,需要长文时用 ghost_manual。",
+ "返回单条完整形态:id、namespace(null=root,字符串=企业 orgSlug)、name、command、recall、setup、tools 与可选 manual 轻量索引。示例:ghost_info({ghost_id:\"helper\", namespace:\"acme\"});省略 namespace 仅当同名实例唯一。拿到目标工具后用 ghost_call,需要长文时用 ghost_manual。",
"tools 可能为空:Manual-only 插件仍返回完整详情与 manual 索引,通过 ghost_manual 读取;这不授予任何 ghost_call 工具能力。",
"查询实时反映安装、启用、账号与当前工作目录状态,不要缓存或依赖会话早前的结果。",
- "结构化错误:GHOST_NOT_FOUND(不存在、已卸载、当前账号不可用或未提供工具和手册)/ GHOST_ASLEEP(未启用)/ GHOST_DISABLED_IN_WORKDIR(当前工作目录停用)/ INTERNAL(内部查询失败)。按 message 停手改道;需要查看全量时用 ghost_list。",
+ "结构化错误:GHOST_NOT_FOUND / GHOST_AMBIGUOUS(同名多实例,candidates 为 {ghostId, namespace}。已确认 root 的 namespace 是 null;没有 namespace 字段的待迁移旧安装在候选里也会标成 null。旁边还有另一个同名实例、且没有已确认 root 时,传 namespace:null 会选中那份旧安装。按候选补 namespace 后重试,不要改选公开版) / GHOST_ASLEEP / GHOST_DISABLED_IN_WORKDIR / INTERNAL。升级普查中的旧插件没有 namespace 字段,省略 namespace 且同名唯一时才能解析。",
].join("\n");
const D_GHOST_MANUAL = [
@@ -267,7 +274,7 @@ function toHostSetupPlan(input: GhostSetupPlanInput): CindyGhostSetupPlan {
* 作者字段只进入 JSONL 数据块;固定前导/尾注不混入作者内容。
*/
export function formatGhostRoster(
- items: Array<Pick<CindyGhostInfo, "id" | "name" | "command" | "recall">>,
+ items: Array<Pick<CindyGhostInfo, "id" | "name" | "command" | "recall" | "namespace">>,
): string {
if (items.length === 0) return "";
const lines = [...items]
@@ -278,6 +285,7 @@ export function formatGhostRoster(
value.replace(/\s+/g, " ").trim();
return JSON.stringify({
id: normalize(g.id),
+ ...(g.namespace !== undefined ? { namespace: g.namespace } : {}),
name: normalize(g.name).slice(0, 64),
command: g.command ? normalize(g.command).slice(0, 32) : "",
recall: g.recall
@@ -301,7 +309,7 @@ export function formatGhostRoster(
/** 构造宿主注入 system/developer 段;行格式与 ghost_list 花名册共用。 */
export function buildGhostRosterPrompt(
- items: Array<Pick<CindyGhostInfo, "id" | "name" | "command" | "recall">>,
+ items: Array<Pick<CindyGhostInfo, "id" | "name" | "command" | "recall" | "namespace">>,
): string {
return formatGhostRoster(items);
}
@@ -682,7 +690,7 @@ export async function handleGhostList(
ghosts,
hint:
ghosts.length > 0
- ? "按 manual 索引用 ghost_manual 读取手册;有工具时用 ghost_call({ghost_id, tool, args}) 调用已声明工具;清单实时,勿缓存。"
+ ? "按 manual 索引用 ghost_manual 读取手册;有工具时用 ghost_call({ghost_id, namespace, tool, args}) 调用已声明工具。同名插件必须带 namespace(null=root)。清单实时,勿缓存。"
: "当前没有已启用的插件。用户可在主界面侧边栏「插件」中安装或启用插件。",
});
} catch (err) {
@@ -700,10 +708,10 @@ export async function handleGhostList(
/** ghost_info 的 handler 主体(导出供单测)。 */
export async function handleGhostInfo(
deps: CindyGhostsMcpDeps,
- input: { ghost_id: string },
+ input: { ghost_id: string; namespace?: string | null },
): Promise<McpTextResult> {
try {
- const result = await deps.getAwakeGhost(input.ghost_id);
+ const result = await deps.getAwakeGhost(input.ghost_id, input.namespace);
if (!result.ok) {
deps.logger?.warn("ghost_info rejected", {
ghostId: input.ghost_id.slice(0, 64),
@@ -717,6 +725,7 @@ export async function handleGhostInfo(
result.errorCode === "GHOST_NOT_FOUND"
? `${result.message};不要重复重试同一目标;可调用 ghost_list 回查当前可用插件,或改用其它可用方式完成。`
: result.message,
+ ...("candidates" in result && result.candidates ? { candidates: result.candidates } : {}),
},
true,
);
@@ -747,11 +756,12 @@ export async function handleGhostInfo(
/** ghost_manual 的 handler 主体(导出供单测)。 */
export async function handleGhostManual(
deps: CindyGhostsMcpDeps,
- input: { ghost_id: string; path?: string },
+ input: { ghost_id: string; namespace?: string | null; path?: string },
): Promise<McpTextResult> {
try {
const result = await deps.readGhostManual({
ghostId: input.ghost_id,
+ ...(input.namespace !== undefined ? { namespace: input.namespace } : {}),
...(input.path !== undefined ? { path: input.path } : {}),
});
return textResult(result, !result.ok);
@@ -896,6 +906,7 @@ export async function handleGhostCall(
deps: CindyGhostsMcpDeps,
input: {
ghost_id: string;
+ namespace?: string | null;
tool: string;
args?: Record<string, unknown>;
attachments?: string[];
@@ -910,6 +921,7 @@ export async function handleGhostCall(
try {
const result = await deps.callGhostTool({
ghostId: input.ghost_id,
+ ...(input.namespace !== undefined ? { namespace: input.namespace } : {}),
tool: input.tool,
args: input.args ?? {},
...(signal ? { signal } : {}),
@@ -1252,11 +1264,11 @@ export function createCindyGhostsMcpServer(
if (deps.connectAccount) server.tool(
"connect_account",
"Request an account connection for an installed plugin in the current conversation: kind=plugin and its real ghost_id. The Host presents its supported setup card, including protected manual connection forms, without calling a plugin business tool. Use reauthorize=true when the user asks to reconnect, replace a token, update authorization, or reconfigure an existing connection; saved configuration must not skip that request. Ordinary tasks wait until setup completes or is cancelled; teammate tasks may return a pending card immediately, then the Host resumes them after authorization. Follow the returned status and do not infer provider access from setup readiness. Only if the Host reports no supported setup action, follow the installed plugin's documented login method on the machine running the task. Never request credentials in chat or tool arguments. Built-in Grok login (kind=host, id=grok) remains available only in teammate conversations and does not authorize X or change your model. Do not invent connectors, URLs or credentials.",
- { kind: z.enum(["host", "plugin"]), id: z.string().min(1).max(256), reauthorize: z.boolean().optional().describe("Reopen supported setup for an explicit reconnect, token replacement, authorization update or reconfiguration request, or a known authorization/scope failure") },
- async ({ kind, id, reauthorize }, extra) => {
- if (kind === "host" && id !== "grok") return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, errorCode: "UNSUPPORTED_CONNECTION" }) }], isError: true };
+ { kind: z.enum(["host", "plugin"]), id: z.string().min(1).max(256), namespace: ghostNamespaceInput, reauthorize: z.boolean().optional().describe("Reopen supported setup for an explicit reconnect, token replacement, authorization update or reconfiguration request, or a known authorization/scope failure") },
+ async ({ kind, id, namespace, reauthorize }, extra) => {
+ if (kind === "host" && (id !== "grok" || namespace !== undefined)) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, errorCode: "UNSUPPORTED_CONNECTION" }) }], isError: true };
try {
- const result = await deps.connectAccount!(kind === "host" ? { kind, id: "grok", reauthorize } : { kind, id, reauthorize }, extra.signal);
+ const result = await deps.connectAccount!(kind === "host" ? { kind, id: "grok", reauthorize } : { kind, id, ...(namespace !== undefined ? { namespace } : {}), reauthorize }, extra.signal);
return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };
} catch {
return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, errorCode: "CONNECTION_UNAVAILABLE" }) }], isError: true };
@@ -1271,6 +1283,7 @@ export function createCindyGhostsMcpServer(
D_GHOST_INFO,
{
ghost_id: z.string().describe("目标插件 id(来自花名册、用户点名、上文或 ghost_list)"),
+ namespace: ghostNamespaceInput,
},
async (input) => handleGhostInfo(deps, input),
);
@@ -1282,6 +1295,7 @@ export function createCindyGhostsMcpServer(
ghost_id: z
.string()
.describe("目标插件 id(来自花名册、ghost_info 或 ghost_list)"),
+ namespace: ghostNamespaceInput,
path: z
.string()
.max(1024)
@@ -1298,6 +1312,7 @@ export function createCindyGhostsMcpServer(
D_GHOST_CALL,
{
ghost_id: z.string().describe("目标插件 id(来自 ghost_info / ghost_list 或用户消息附带的工具清单)"),
+ namespace: ghostNamespaceInput,
tool: z.string().describe("工具名(来自 ghost_info / ghost_list 该插件的 tools)"),
args: z
.record(z.string(), z.unknown())
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index b34fa92d46..176d4c7a4c 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -122,6 +122,8 @@ export interface CindyGhostSetupPlan {
/** ghost_info / ghost_list 共用的单段意识条目。 */
export interface CindyGhostInfo {
id: string;
+ /** null is root; a string is the organization slug. Omitted only on legacy hosts. */
+ namespace?: string | null;
name: string;
/** 显式触发指令(用户敲 /<command> 点名调用);未声明则省略。 */
command?: string;
@@ -141,6 +143,7 @@ export interface CindyGhostInfo {
/** ghost_call 的结构化失败分类(host 侧产生,总机原样透传给 agent)。 */
export type CindyGhostCallErrorCode =
| 'GHOST_NOT_FOUND' // 未装入或已抽离
+ | 'GHOST_AMBIGUOUS' // 同名多实例,需指定 namespace
| 'GHOST_ASLEEP' // 沉睡中(用户可在主界面侧边栏「插件」中唤醒)
| 'GHOST_RETIRED' // 功能已下线,不可唤醒或重试
| 'GHOST_DISABLED_IN_WORKDIR' // 用户在当前工作目录停用了该意识(不要重试)
@@ -155,13 +158,13 @@ export type CindyGhostCallErrorCode =
export type CindyGhostInfoErrorCode = Extract<
CindyGhostCallErrorCode,
- 'GHOST_NOT_FOUND' | 'GHOST_ASLEEP' | 'GHOST_DISABLED_IN_WORKDIR' | 'GHOST_RETIRED'
+ 'GHOST_NOT_FOUND' | 'GHOST_AMBIGUOUS' | 'GHOST_ASLEEP' | 'GHOST_DISABLED_IN_WORKDIR' | 'GHOST_RETIRED'
>;
/** host 可见性判序回调(getAwakeGhost)的返回:只产可见性错误,不产 INTERNAL。 */
export type CindyGhostInfoHostResult =
| { ok: true; ghost: CindyGhostInfo }
- | { ok: false; errorCode: CindyGhostInfoErrorCode; message: string };
+ | { ok: false; errorCode: CindyGhostInfoErrorCode; message: string; candidates?: Array<{ ghostId: string; namespace: string | null }> };
/** ghost_info 给模型的 wire 结果:host 结果之上,handler 兜底 catch 可产 INTERNAL。 */
export type CindyGhostInfoResult =
@@ -355,7 +358,7 @@ export interface CindyGhostsMcpDeps {
searchMarket?(query: string): Promise<Record<string, unknown>>;
installMarket?(request: { pluginId: string; releaseId: string }, signal?: AbortSignal): Promise<Record<string, unknown>>;
/** Host-owned connection card. No URLs or credentials may be supplied by the model. */
- connectAccount?(target: { kind: 'plugin'; id: string; reauthorize?: boolean } | { kind: 'host'; id: 'grok'; reauthorize?: boolean }, signal?: AbortSignal): Promise<Record<string, unknown>>;
+ connectAccount?(target: { kind: 'plugin'; id: string; namespace?: string | null; reauthorize?: boolean } | { kind: 'host'; id: 'grok'; reauthorize?: boolean }, signal?: AbortSignal): Promise<Record<string, unknown>>;
/** Cindy Core 原生媒体调用器;能力本身不依赖任何插件。 */
callMedia?(request: CindyMediaToolRequest): Promise<Record<string, unknown>>;
/**
@@ -367,12 +370,13 @@ export interface CindyGhostsMcpDeps {
* 按 id 现查单个当前可用插件;与 ghost_call 共享同一可见性判定。
* 判序:不存在 → 未登录 → 当前工作目录停用 → 未启用。
*/
- getAwakeGhost(ghostId: string): Promise<CindyGhostInfoHostResult>;
+ getAwakeGhost(ghostId: string, namespace?: string | null): Promise<CindyGhostInfoHostResult>;
/**
* 读取已声明的随包手册;Host 每次调用都重新执行插件可见性判定,且不启动沙箱。
*/
readGhostManual(request: {
ghostId: string;
+ namespace?: string | null;
path?: string;
}): Promise<CindyGhostManualResult>;
/**
@@ -381,6 +385,7 @@ export interface CindyGhostsMcpDeps {
*/
callGhostTool(request: {
ghostId: string;
+ namespace?: string | null;
tool: string;
args: Record<string, unknown>;
/** Host-only cancellation from the MCP request; never enters plugin args. */
@@ -445,7 +450,7 @@ export interface CindyGhostsMcpDeps {
* 会话内工具定义恒定(prompt 缓存安全);装/卸/唤醒/沉睡在新会话生效,
* 实时清单仍以 ghost_list 为准。缺省 = 不注入(描述与今日基线一致)。
*/
- getRosterItems?(): Array<Pick<CindyGhostInfo, 'id' | 'name' | 'command' | 'recall'>>;
+ getRosterItems?(): Array<Pick<CindyGhostInfo, 'id' | 'name' | 'command' | 'recall' | 'namespace'>>;
/** 意识编写手册(markdown,随主机版本走;agent 写意识前先读)。 */
forgeGuide(): Promise<string>;
/**
diff --git a/packages/device-link/src/__tests__/pluginAuthorization.test.ts b/packages/device-link/src/__tests__/pluginAuthorization.test.ts
index 0fa4f33ff4..8b40732c65 100644
--- a/packages/device-link/src/__tests__/pluginAuthorization.test.ts
+++ b/packages/device-link/src/__tests__/pluginAuthorization.test.ts
@@ -5,6 +5,23 @@ import {
parsePluginAuthorizationResult,
} from "../pluginAuthorization.js";
import { parsePluginOauthRequest } from "../pluginOauth.js";
+import { parsePluginOauthHelloReply } from "../pluginOauthAuthentication.js";
+
+it.each([
+ { field: "ghostId", value: "_ns__" + "a".repeat(128) + "__p", accepted: true },
+ { field: "ghostId", value: "_ns__" + "a".repeat(128) + "__" + "p".repeat(32), accepted: true },
+ { field: "ghostId", value: "_ns__" + "a".repeat(129) + "__p", accepted: false },
+ { field: "ghostId", value: "_ns__" + "a".repeat(128) + "__" + "p".repeat(33), accepted: false },
+ { field: "ghostId", value: "p".repeat(129), accepted: false },
+ { field: "ghostId", value: "_ns__" + "a".repeat(128) + "__/p", accepted: false },
+ { field: "id", value: "_ns__" + "a".repeat(128) + "__p", accepted: false },
+ { field: "bootId", value: "_ns__" + "a".repeat(128) + "__p", accepted: false },
+])("bounds the signed OAuth $field without enlarging other identities: $accepted", ({ field, value, accepted }) => {
+ const reply = { version: 3, id: "transaction", bootId: "boot", ghostId: "p",
+ publicKey: "a".repeat(59), signature: "s".repeat(86), expiresAtMs: 1000, [field]: value };
+ if (accepted) expect(parsePluginOauthHelloReply(reply)).toEqual(reply);
+ else expect(() => parsePluginOauthHelloReply(reply)).toThrow("OAUTH_BRIDGE_UNAVAILABLE");
+});
function loopback() {
const callbackUrl = "http://127.0.0.1:45678/callback";
diff --git a/packages/device-link/src/__tests__/remoteResources.test.ts b/packages/device-link/src/__tests__/remoteResources.test.ts
index e40f426b6d..c6fc78b01e 100644
--- a/packages/device-link/src/__tests__/remoteResources.test.ts
+++ b/packages/device-link/src/__tests__/remoteResources.test.ts
@@ -64,6 +64,15 @@ describe('remote resource request parsing', () => {
.toBeNull();
});
+ it('accepts namespaced physical resource keys without relaxing other identifier bounds', () => {
+ const ref = { collectionId: 'plugins', kind: 'plugin', id: '_ns__' + 'a'.repeat(128) + '__' + 'p'.repeat(32) };
+ expect(parseRemoteResourceGetRequest({ client, ref })?.ref).toEqual(ref);
+ expect(parseRemoteActionInvokeRequest({ client, collectionId: 'plugins', resourceRef: ref,
+ actionId: 'enable', input: {} })?.resourceRef).toEqual(ref);
+ expect(parseRemoteResourceGetRequest({ client, ref: { ...ref, id: 'x'.repeat(257) } })).toBeNull();
+ expect(parseRemoteResourceGetRequest({ client, ref: { ...ref, collectionId: 'x'.repeat(161) } })).toBeNull();
+ });
+
it('passes a bounded optional search query through resource reads', () => {
const ref = { collectionId: 'teammates', kind: 'bot', id: 'settings:bot-1/memory' };
expect(parseRemoteResourceGetRequest({ client, ref, query: '咖啡' })).toEqual({
diff --git a/packages/device-link/src/pluginOauth.ts b/packages/device-link/src/pluginOauth.ts
index 2dcd95d986..10eb06c592 100644
--- a/packages/device-link/src/pluginOauth.ts
+++ b/packages/device-link/src/pluginOauth.ts
@@ -52,6 +52,11 @@ function exact(v: Record<string, unknown>, keys: string[]) {
export function oauthId(v: unknown): v is string {
return typeof v === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(v);
}
+export function oauthGhostId(value: unknown): value is string {
+ return oauthId(value) ||
+ (typeof value === "string" &&
+ /^_ns__[a-z0-9](?:[a-z0-9-]{0,126}[a-z0-9])?__[a-z0-9][a-z0-9-]{0,31}$/.test(value));
+}
export function parsePluginOauthAction(
value: unknown,
): PluginOauthAction | null {
diff --git a/packages/device-link/src/pluginOauthAuthentication.ts b/packages/device-link/src/pluginOauthAuthentication.ts
index 66d321a9c8..53a9394505 100644
--- a/packages/device-link/src/pluginOauthAuthentication.ts
+++ b/packages/device-link/src/pluginOauthAuthentication.ts
@@ -1,5 +1,6 @@
import {
oauthId,
+ oauthGhostId,
parsePluginOauthAction,
type PluginOauthAction,
} from "./pluginOauth.js";
@@ -118,7 +119,8 @@ export function parsePluginOauthHelloReply(
]);
if (
v.version !== 3 ||
- ![v.id, v.bootId, v.ghostId].every(oauthId) ||
+ ![v.id, v.bootId].every(oauthId) ||
+ !oauthGhostId(v.ghostId) ||
!oauthPublicKey(v.publicKey) ||
!Number.isSafeInteger(v.expiresAtMs) ||
typeof v.signature !== "string" ||
diff --git a/packages/device-link/src/remoteResources.ts b/packages/device-link/src/remoteResources.ts
index 37f37b1603..ce6b8303ed 100644
--- a/packages/device-link/src/remoteResources.ts
+++ b/packages/device-link/src/remoteResources.ts
@@ -227,6 +227,7 @@ export interface RemoteResourceChangedPayload {
}
const MAX_ID_CHARS = 160;
+const MAX_RESOURCE_ID_CHARS = 256;
const MAX_CURSOR_CHARS = 1_024;
const MAX_QUERY_CHARS = 1_000;
const MAX_LOCALE_CHARS = 64;
@@ -284,7 +285,7 @@ export function parseRemoteResourceRef(value: unknown): RemoteResourceRef | null
if (!record) return null;
const collectionId = boundedText(record.collectionId, MAX_ID_CHARS);
const kind = boundedText(record.kind, MAX_ID_CHARS);
- const id = boundedText(record.id, MAX_ID_CHARS);
+ const id = boundedText(record.id, MAX_RESOURCE_ID_CHARS);
return collectionId && kind && id ? { collectionId, kind, id } : null;
}
diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.ts
index c602aad87f..9be7edceb1 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -768,4 +768,28 @@ describe('routine check configuration', () => {
expect(f.engine.history(routine.id)[0]).toMatchObject({ resultText: 'No changes' });
} finally { await f.engine.stop(); }
});
+ it('drops a live plugin source on archive instead of retargeting it', async () => {
+ const f = await fixture();
+ f.engine.registerSource({
+ id: 'plugin:helper',
+ name: 'Helper',
+ status: 'listening',
+ events: [{ type: 'mail', name: 'Mail', fields: [] }],
+ });
+ await f.engine.createOnce('bot', {
+ name: 'watch',
+ prompt: 'read mail',
+ enabled: true,
+ triggers: [{ id: 't1', kind: 'event', sourceId: 'plugin:helper', eventType: 'mail', filters: [] }],
+ }, 'a'.repeat(16));
+ const archive = 'arch_' + 'a'.repeat(32);
+ await f.engine.relocatePluginSource('helper', archive);
+ const ids = f.engine.listSources().map((source) => source.id);
+ expect(ids).not.toContain('plugin:helper');
+ expect(ids).not.toContain('plugin:' + archive);
+ expect(f.engine.list('bot')[0]?.triggers).toEqual([
+ expect.objectContaining({ sourceId: 'plugin:' + archive }),
+ ]);
+ await f.engine.stop();
+ });
});
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index e8b2a48432..6e217cc352 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -39,6 +39,49 @@ export interface RoutineState {
pausedBotIds?: string[];
}
+
+/** Move event subscriptions off a plugin instance onto its archive key. */
+export function rewriteRoutinePluginSource(
+ state: RoutineState,
+ fromPart: string,
+ toPart: string,
+): RoutineState {
+ const fromId = `plugin:${fromPart}`;
+ const toId = `plugin:${toPart}`;
+ if (fromId === toId) return state;
+ let changed = false;
+ const routines = state.routines.map((routine) => {
+ let routineChanged = false;
+ const triggers = routine.triggers.map((trigger) => {
+ if (trigger.kind !== "event" || trigger.sourceId !== fromId) return trigger;
+ routineChanged = true;
+ changed = true;
+ return { ...trigger, sourceId: toId };
+ });
+ return routineChanged ? { ...routine, triggers } : routine;
+ });
+ const receipts: Record<string, number> = {};
+ for (const [key, timestamp] of Object.entries(state.receipts)) {
+ let nextKey = key;
+ try {
+ const parts: unknown = JSON.parse(key);
+ if (
+ Array.isArray(parts) && parts.length === 2 &&
+ parts[0] === fromId && typeof parts[1] === "string"
+ ) {
+ nextKey = JSON.stringify([toId, parts[1]]);
+ changed = true;
+ }
+ } catch {
+ // Malformed receipt keys stay untouched.
+ }
+ const previous = receipts[nextKey];
+ receipts[nextKey] = previous === undefined ? timestamp : Math.max(previous, timestamp);
+ }
+ if (!changed) return state;
+ return { ...state, routines, receipts };
+}
+
export interface RoutineEngineDeps {
load(): Promise<RoutineState | null>;
save(state: RoutineState): Promise<void>;
@@ -196,6 +239,19 @@ export class RoutineEngine {
this.notifyChanged();
}
+ /** Archived plugins must not keep receiving events published for the replacement. */
+ async relocatePluginSource(fromPart: string, toPart: string): Promise<void> {
+ if (fromPart === toPart) return;
+ const fromId = `plugin:${fromPart}`;
+ await this.change((state) => {
+ const next = rewriteRoutinePluginSource(state, fromPart, toPart);
+ if (next === state) return;
+ state.routines = next.routines;
+ state.receipts = next.receipts;
+ });
+ if (this.sources.delete(fromId)) this.notifyChanged();
+ }
+
async put(botId: string, raw: RoutineInput, id?: string, expectedRevision?: number): Promise<Routine> {
return this.writeRoutine(botId, raw, { id, expectedRevision });
}
diff --git a/packages/maker-shared/src/ghostCommand.ts b/packages/maker-shared/src/ghostCommand.ts
index 7ba5047ce9..b054d7fd5b 100644
--- a/packages/maker-shared/src/ghostCommand.ts
+++ b/packages/maker-shared/src/ghostCommand.ts
@@ -28,33 +28,118 @@ export interface GhostCommandSource {
manifest: { id: string; name: string; command?: string; tools?: GhostToolDecl[] };
enabled: boolean;
iconDataUrl?: string;
+ /** Absent on old peers. null is an explicit root instance. */
+ namespace?: string | null;
+ /** Physical instance key. Absent on old peers; never a filesystem path. */
+ instanceKey?: string;
+}
+
+function hasDeliveryNamespace<T extends object>(
+ value: T,
+): value is T & { namespace: string | null } {
+ return Object.prototype.hasOwnProperty.call(value, 'namespace');
+}
+
+function installedGhostNamespaceLabel(ghost: { namespace?: string | null }): string | null {
+ return hasDeliveryNamespace(ghost) ? ghost.namespace : null;
+}
+
+function formatInstalledGhostAmbiguity(
+ ghostId: string,
+ candidates: readonly { namespace?: string | null }[],
+): string {
+ const labels = candidates.map((candidate) => {
+ const namespace = installedGhostNamespaceLabel(candidate);
+ return namespace === null ? `root/${ghostId}` : `${namespace}/${ghostId}`;
+ });
+ return `插件 ${ghostId} 存在多个实例(${labels.join('、')})。请指定 namespace:null 表示 root,字符串表示企业 orgSlug。`;
+}
+
+function listGhostsByCommand<
+ T extends { enabled?: boolean; manifest: { command?: string } },
+>(ghosts: readonly T[], word: string, enabledOnly = true): T[] {
+ const fold = word.toLowerCase();
+ return ghosts.filter((ghost) => {
+ if (enabledOnly && ghost.enabled === false) return false;
+ return ghost.manifest.command !== undefined && ghost.manifest.command.toLowerCase() === fold;
+ });
}
/**
- * `$` 后紧跟指令词(与 ghost.json command 约束同宽:无空白,≤32 字符)。
+ * `$` 后紧跟指令词(与 ghost.json command 约束同宽:无空白、不含 `/`,≤32 字符),可选 `/namespace`(与协议 orgSlug 同宽,最长 128)。
* 触发符同时认全角变体($ U+FF04 / ¥ U+00A5 / ¥ U+FFE5):中文输入法下
* Shift+4 产出的是 ¥,不切输入法也能触发——与 ChatInput 的
* GHOST_SIGIL_CHARS 是同一字符集,两端必须保持一致。
*/
-const COMMAND_RE = /^[$$¥¥](\S{1,32})(?:\s|$)/;
+const COMMAND_RE =
+ /^[$$¥¥]([^/\s]{1,32})(?:\/(@root|[a-z0-9](?:[a-z0-9-]{0,126}[a-z0-9])?))?(?:\s|$)/;
+
+export interface GhostCommandToken {
+ word: string;
+ /** null = unqualified `$draw`; a slug selects `$draw/acme`. */
+ namespace: string | null;
+}
/** 解析消息开头的意识指令词;非 `$`(含全角变体)开头或形状不合返回 null。 */
-export function parseGhostCommandWord(text: string): string | null {
+export function parseGhostCommandToken(text: string): GhostCommandToken | null {
const m = COMMAND_RE.exec(text);
- return m ? m[1] : null;
+ return m ? { word: m[1]!, namespace: m[2] ?? null } : null;
+}
+
+export function ghostCommandTokenLength(token: GhostCommandToken): number {
+ return token.word.length + (token.namespace ? 1 + token.namespace.length : 0);
+}
+
+/** 解析消息开头的意识指令词;限定符 `/ns` 不计入返回值。 */
+export function parseGhostCommandWord(text: string): string | null {
+ return parseGhostCommandToken(text)?.word ?? null;
+}
+
+/** Palette / insertion token: `draw` or `draw/acme`. */
+export function formatGhostCommandToken(ghost: {
+ manifest: { command?: string };
+ namespace?: string | null;
+}, roster: readonly { manifest: { command?: string }; namespace?: string | null }[] = []): string | null {
+ const command = ghost.manifest.command;
+ if (!command) return null;
+ if (ghost.namespace === null && roster.some((other) =>
+ other !== ghost && other.manifest.command?.toLowerCase() === command.toLowerCase())) {
+ return command + '/@root';
+ }
+ return hasDeliveryNamespace(ghost) && ghost.namespace
+ ? `${command}/${ghost.namespace}`
+ : command;
+}
+
+export function formatGhostCommandInsertion(ghost: {
+ manifest: { command?: string };
+ namespace?: string | null;
+}, roster?: readonly { manifest: { command?: string }; namespace?: string | null }[]): string | null {
+ const token = formatGhostCommandToken(ghost, roster);
+ return token ? `$${token}` : null;
+}
+
+function listGhostsMatchingCommandToken<
+ T extends GhostCommandSource & { namespace?: string | null },
+>(
+ ghosts: readonly T[],
+ token: GhostCommandToken,
+ enabledOnly: boolean,
+): T[] {
+ const matches = listGhostsByCommand(ghosts, token.word, enabledOnly);
+ if (token.namespace === null) return matches;
+ if (token.namespace === '@root') return matches.filter((ghost) => ghost.namespace === null);
+ return matches.filter((ghost) => ghost.namespace === token.namespace);
}
/** 按指令词(大小写折叠)找已唤醒的意识;找不到 → null(消息原样发送)。 */
-export function findGhostByCommand<T extends GhostCommandSource>(
- ghosts: T[],
+export function findGhostByCommand<T extends GhostCommandSource & { namespace?: string | null }>(
+ ghosts: readonly T[],
word: string,
+ namespace: string | null = null,
): T | null {
- const fold = word.toLowerCase();
- return (
- ghosts.find(
- (g) => g.enabled && g.manifest.command !== undefined && g.manifest.command.toLowerCase() === fold,
- ) ?? null
- );
+ const matches = listGhostsMatchingCommandToken(ghosts, { word, namespace }, true);
+ return matches.length === 1 ? matches[0]! : null;
}
/**
@@ -63,18 +148,15 @@ export function findGhostByCommand<T extends GhostCommandSource>(
* 仅用于编辑器内替换旧 `$command` 的结构识别;真正发送仍必须走
* findGhostByCommand,所以停用 Plugin 不会因此被误调用。
*/
-export function findGhostByCommandIncludingDisabled<T extends GhostCommandSource>(
- ghosts: T[],
+export function findGhostByCommandIncludingDisabled<
+ T extends GhostCommandSource & { namespace?: string | null },
+>(
+ ghosts: readonly T[],
word: string,
+ namespace: string | null = null,
): T | null {
- const fold = word.toLowerCase();
- return (
- ghosts.find(
- (ghost) =>
- ghost.manifest.command !== undefined &&
- ghost.manifest.command.toLowerCase() === fold,
- ) ?? null
- );
+ const matches = listGhostsMatchingCommandToken(ghosts, { word, namespace }, false);
+ return matches.length === 1 ? matches[0]! : null;
}
// ---------------------------------------------------------------------------
@@ -92,9 +174,11 @@ export interface GhostDirectiveSegment {
injected: boolean;
}
-const DIRECT_GHOST_TOOL_HINT =
+const PRE_ROOT_GHOST_TOOL_HINT =
'插件本身不会作为独立 MCP server/resource 出现;ghost_call 的完整工具名是 mcp__cindy__ghost_call。' +
'不得查询 MCP resources、插件文件、ghost.json、宿主进程或本地 API,直接调用 cindy 总机工具。';
+const DIRECT_GHOST_TOOL_HINT = PRE_ROOT_GHOST_TOOL_HINT +
+ '若指令带 /@root,ghost_call 必须显式传 namespace:null。';
/**
* 硬指令追加段——分段形态(单一事实源):发送文本 = 各段 text 相连;
@@ -111,6 +195,8 @@ export function commandDirectiveSegments(d: {
command: string;
name: string;
ghostId: string;
+ /** Present only on newly sent directives. Historical parsers omit it. */
+ namespace?: string | null;
toolsJson?: string;
}): GhostDirectiveSegment[] {
const head: GhostDirectiveSegment[] = [
@@ -118,9 +204,15 @@ export function commandDirectiveSegments(d: {
{ text: `$${d.command}`, injected: true },
{ text: ' 显式点名插件「', injected: false },
{ text: d.name, injected: true },
- { text: '」(id: ', injected: false },
+ { text: d.namespace !== undefined ? '」(ghost_id: ' : '」(id: ', injected: false },
{ text: d.ghostId, injected: true },
];
+ if (d.namespace !== undefined) {
+ head.push(
+ { text: ', namespace: ', injected: false },
+ { text: d.namespace === null ? 'null' : d.namespace, injected: true },
+ );
+ }
if (d.toolsJson === undefined) {
return [
...head,
@@ -149,10 +241,16 @@ export function commandDirectiveSegments(d: {
}
/** 硬指令追加段的纯文本(发送用,由分段拼接;旧形态,无工具清单)。 */
-const buildCommandDirective = (command: string, name: string, id: string): string =>
- commandDirectiveSegments({ command, name, ghostId: id })
- .map((s) => s.text)
- .join('');
+const buildCommandDirective = (
+ command: string,
+ name: string,
+ id: string,
+ namespace?: string | null,
+): string =>
+ commandDirectiveSegments({
+ command, name, ghostId: id,
+ ...(namespace !== undefined ? { namespace } : {}),
+ }).map((s) => s.text).join('');
/** 硬指令追加段的纯文本(发送用;新形态,内嵌工具清单)。 */
const buildCommandToolsDirective = (
@@ -160,10 +258,12 @@ const buildCommandToolsDirective = (
name: string,
id: string,
toolsJson: string,
+ namespace?: string | null,
): string =>
- commandDirectiveSegments({ command, name, ghostId: id, toolsJson })
- .map((s) => s.text)
- .join('');
+ commandDirectiveSegments({
+ command, name, ghostId: id, toolsJson,
+ ...(namespace !== undefined ? { namespace } : {}),
+ }).map((s) => s.text).join('');
/** 直达规则补强前的插件模板,只用于解析已经落库的历史消息。 */
const buildPreviousPluginCommandDirective = (command: string, name: string, id: string): string =>
@@ -302,17 +402,37 @@ const buildMentionDirective = (roster: string): string => `${MENTION_HEAD}${rost
* (agent 免 ghost_list 直接调),超体积闸回落"先 ghost_list"旧形态;
* - 未命中(没这个指令 / 意识沉睡 / 非 `$` 开头)原样返回——绝不吞掉用户的字。
*/
-export function expandGhostCommand(text: string, ghosts: GhostCommandSource[]): string {
- const word = parseGhostCommandWord(text);
- if (!word) return text;
- const ghost = findGhostByCommand(ghosts, word);
+function buildAmbiguousCommandDirective(
+ command: string,
+ ghosts: readonly (GhostCommandSource & { namespace?: string | null })[],
+): string {
+ return (
+ `[插件指令] 用户以 $` + command + ` 显式点名插件,但` +
+ formatInstalledGhostAmbiguity(ghosts[0]?.manifest.id ?? command, ghosts) +
+ '不得自行挑选其中一个。'
+ );
+}
+
+export function expandGhostCommand(text: string, ghosts: readonly GhostCommandSource[]): string {
+ const token = parseGhostCommandToken(text);
+ if (!token) return text;
+ const matches = listGhostsMatchingCommandToken(ghosts, token, true);
+ if (matches.length > 1) {
+ return text + '\n\n' + buildAmbiguousCommandDirective(token.word, matches);
+ }
+ const ghost = matches[0];
if (!ghost) return text;
- const { id, name, command } = ghost.manifest;
+ const { name, command } = ghost.manifest;
+ const id = ghost.manifest.id;
+ // Pending upgrades have no namespace field. Omit it so the host resolves a unique legacy id.
+ // Explicit null is a confirmed root and must not be sent for those installs.
+ const namespace = hasDeliveryNamespace(ghost) ? ghost.namespace : undefined;
+ const commandToken = token.namespace === '@root' ? token.word + '/@root' : command as string;
const toolsJson = buildGhostToolsJson(ghost.manifest.tools);
const directive =
toolsJson !== null
- ? buildCommandToolsDirective(command as string, name, id, toolsJson)
- : buildCommandDirective(command as string, name, id);
+ ? buildCommandToolsDirective(commandToken, name, id, toolsJson, namespace)
+ : buildCommandDirective(commandToken, name, id, namespace);
return `${text}\n\n${directive}`;
}
@@ -327,6 +447,8 @@ export type GhostDirectiveDisplay =
command: string;
name: string;
ghostId: string;
+ /** Logical namespace. null is root. Absent on directives sent before this field. */
+ namespace?: string | null;
/** 指令内嵌的工具清单 JSON(新形态才有;卡片重建分段时须原样带上)。 */
toolsJson?: string;
raw: string;
@@ -345,15 +467,48 @@ const P2 = '\u0002';
const P3 = '\u0003';
const P4 = String.fromCharCode(4);
+const P5 = String.fromCharCode(5);
+
+const LOGICAL_COMMAND_DIRECTIVE_RE = new RegExp(
+ `\n\n(${escapeRegExp(buildCommandDirective(P1, P2, P3, P5))
+ .replace(P1, '(\\S{1,161})')
+ .replace(P2, '(.+?)')
+ .replace(P3, '(.+?)')
+ .replace(P5, '(\\S{1,128})')})$`,
+);
+
+const LOGICAL_COMMAND_TOOLS_DIRECTIVE_RE = new RegExp(
+ `\n\n(${escapeRegExp(buildCommandToolsDirective(P1, P2, P3, P4, P5))
+ .replace(P1, '(\\S{1,161})')
+ .replace(P2, '(.+?)')
+ .replace(P3, '(.+?)')
+ .replace(P4, '(.+)')
+ .replace(P5, '(\\S{1,128})')})$`,
+);
+
+function namespaceFromCapture(value: string): string | null {
+ return value === 'null' ? null : value;
+}
+
/** 由生成模板反推的解析正则——锚定消息末尾,只认完整模板(旧形态)。 */
const COMMAND_DIRECTIVE_RE = new RegExp(
`\\n\\n(${escapeRegExp(buildCommandDirective(P1, P2, P3))
- .replace(P1, '(\\S{1,32})')
+ .replace(P1, '(\\S{1,161})')
.replace(P2, '(.+?)')
.replace(P3, '(.+?)')})$`,
);
+function preRootCommandRegex(pattern: RegExp): RegExp {
+ const rootHint = escapeRegExp(DIRECT_GHOST_TOOL_HINT.slice(PRE_ROOT_GHOST_TOOL_HINT.length))
+ .replaceAll('/', '\\/');
+ return new RegExp(pattern.source.replace(rootHint, ''));
+}
+
+const PRE_ROOT_COMMAND_DIRECTIVE_RE = preRootCommandRegex(COMMAND_DIRECTIVE_RE);
+const PRE_ROOT_LOGICAL_COMMAND_DIRECTIVE_RE = preRootCommandRegex(LOGICAL_COMMAND_DIRECTIVE_RE);
+const PRE_ROOT_LOGICAL_COMMAND_TOOLS_DIRECTIVE_RE = preRootCommandRegex(LOGICAL_COMMAND_TOOLS_DIRECTIVE_RE);
+
/** 直达规则补强前的插件硬指令解析器。 */
const PREVIOUS_PLUGIN_COMMAND_DIRECTIVE_RE = new RegExp(
`\\n\\n(${escapeRegExp(buildPreviousPluginCommandDirective(P1, P2, P3))
@@ -376,12 +531,14 @@ const LEGACY_COMMAND_DIRECTIVE_RE = new RegExp(
* 不可能撞上占位符)。 */
const COMMAND_TOOLS_DIRECTIVE_RE = new RegExp(
`\\n\\n(${escapeRegExp(buildCommandToolsDirective(P1, P2, P3, P4))
- .replace(P1, '(\\S{1,32})')
+ .replace(P1, '(\\S{1,161})')
.replace(P2, '(.+?)')
.replace(P3, '(.+?)')
.replace(P4, '(.+)')})$`,
);
+const PRE_ROOT_COMMAND_TOOLS_DIRECTIVE_RE = preRootCommandRegex(COMMAND_TOOLS_DIRECTIVE_RE);
+
/** 直达规则补强前、带内嵌工具清单的插件硬指令解析器。 */
const PREVIOUS_PLUGIN_COMMAND_TOOLS_DIRECTIVE_RE = new RegExp(
`\\n\\n(${escapeRegExp(buildPreviousPluginCommandToolsDirective(P1, P2, P3, P4))
@@ -416,8 +573,25 @@ export function splitGhostDirective(
content: string,
): { body: string; directive: GhostDirectiveDisplay } | null {
// 新形态(内嵌工具清单)优先;两个 command 模板尾部文案不同,互不误伤。
+ const logicalTools = LOGICAL_COMMAND_TOOLS_DIRECTIVE_RE.exec(content)
+ ?? PRE_ROOT_LOGICAL_COMMAND_TOOLS_DIRECTIVE_RE.exec(content);
+ if (logicalTools) {
+ return {
+ body: content.slice(0, logicalTools.index),
+ directive: {
+ kind: 'command',
+ raw: logicalTools[1],
+ command: logicalTools[2],
+ name: logicalTools[3],
+ ghostId: logicalTools[4],
+ namespace: namespaceFromCapture(logicalTools[5] ?? ''),
+ toolsJson: logicalTools[6],
+ },
+ };
+ }
for (const pattern of [
COMMAND_TOOLS_DIRECTIVE_RE,
+ PRE_ROOT_COMMAND_TOOLS_DIRECTIVE_RE,
PREVIOUS_PLUGIN_COMMAND_TOOLS_DIRECTIVE_RE,
LEGACY_COMMAND_TOOLS_DIRECTIVE_RE,
]) {
@@ -436,8 +610,24 @@ export function splitGhostDirective(
};
}
}
+ const logical = LOGICAL_COMMAND_DIRECTIVE_RE.exec(content)
+ ?? PRE_ROOT_LOGICAL_COMMAND_DIRECTIVE_RE.exec(content);
+ if (logical) {
+ return {
+ body: content.slice(0, logical.index),
+ directive: {
+ kind: 'command',
+ raw: logical[1],
+ command: logical[2],
+ name: logical[3],
+ ghostId: logical[4],
+ namespace: namespaceFromCapture(logical[5] ?? ''),
+ },
+ };
+ }
for (const pattern of [
COMMAND_DIRECTIVE_RE,
+ PRE_ROOT_COMMAND_DIRECTIVE_RE,
PREVIOUS_PLUGIN_COMMAND_DIRECTIVE_RE,
LEGACY_COMMAND_DIRECTIVE_RE,
]) {
diff --git a/packages/plugin-protocol/src/__tests__/delivery.test.ts b/packages/plugin-protocol/src/__tests__/delivery.test.ts
index db12284218..8468a94670 100644
--- a/packages/plugin-protocol/src/__tests__/delivery.test.ts
+++ b/packages/plugin-protocol/src/__tests__/delivery.test.ts
@@ -690,4 +690,119 @@ describe('plugin delivery contract', () => {
});
expect(response).not.toHaveProperty('currentOrganization');
});
+
+ const namespacePlugin = {
+ id: pluginId,
+ ghostId: validManifest.id,
+ name: validManifest.name,
+ description: null,
+ author: null,
+ scope: 'organization' as const,
+ organizationId: 'org-1',
+ defaultInstall: false,
+ currentRelease: {
+ id: 'release-org',
+ version: validManifest.version,
+ sha256: 'a'.repeat(64),
+ sizeBytes: 1024,
+ publishedAt: '2026-07-19T00:00:00.000Z',
+ },
+ };
+
+ it('keeps enterprise namespace distinct from root and validates detail identity', () => {
+ const response = parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: {
+ ...namespacePlugin,
+ namespace: 'acme',
+ defaultInstall: true,
+ currentRelease: {
+ ...namespacePlugin.currentRelease,
+ id: 'release-namespace',
+ manifest: { ...validManifest, namespace: 'acme' },
+ },
+ },
+ });
+ expect(response.plugin.namespace).toBe('acme');
+ expect(response.plugin.currentRelease.manifest.namespace).toBe('acme');
+ });
+
+ it('rejects omitted organization namespace when currentOrganization.orgSlug is present', () => {
+ expect(() =>
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [namespacePlugin],
+ nextCursor: null,
+ currentOrganization: { organizationId: 'org-1', orgSlug: 'acme', pluginPrefix: null },
+ }),
+ ).toThrow(PluginProtocolError);
+ expect(
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [namespacePlugin],
+ nextCursor: null,
+ currentOrganization: { organizationId: 'org-1', pluginPrefix: null },
+ }).plugins[0],
+ ).not.toHaveProperty('namespace');
+ expect(
+ parseListPluginsResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugins: [{ ...namespacePlugin, namespace: 'acme' }],
+ nextCursor: null,
+ currentOrganization: { organizationId: 'org-1', orgSlug: 'acme', pluginPrefix: null },
+ }).plugins[0]?.namespace,
+ ).toBe('acme');
+ });
+
+ it('rejects a namespace that disagrees with scope or manifest', () => {
+ const plugin = {
+ ...namespacePlugin,
+ scope: 'public',
+ organizationId: null,
+ currentRelease: {
+ ...namespacePlugin.currentRelease,
+ id: 'release-root',
+ manifest: { ...validManifest, namespace: 'acme' },
+ },
+ };
+ expect(() =>
+ parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: { ...plugin, namespace: 'acme' },
+ }),
+ ).toThrow(PluginProtocolError);
+ expect(() =>
+ parseGetPluginResponse({
+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,
+ plugin: {
+ ...plugin,
+ scope: 'organization',
+ organizationId: 'org-1',
+ namespace: 'acme',
+ currentRelease: {
+ ...plugin.currentRelease,
+ manifest: { ...validManifest, namespace: 'other' },
+ },
+ },
+ }),
+ ).toThrow(PluginProtocolError);
+ });
+
+ it('accepts additive download identity while preserving legacy responses', () => {
+ const legacy = {
+ url: 'https://example.com/plugin.cindy?signature=example',
+ expiresAt: '2026-07-19T00:05:00.000Z',
+ sha256: 'c'.repeat(64),
+ sizeBytes: 1024,
+ };
+ const response = parsePluginDownloadResponse({
+ ...legacy,
+ pluginId,
+ releaseId: 'release-namespace',
+ ghostId: validManifest.id,
+ namespace: 'acme',
+ });
+ expect(response.namespace).toBe('acme');
+ expect(parsePluginDownloadResponse(legacy)).not.toHaveProperty('namespace');
+ });
});
diff --git a/packages/plugin-protocol/src/__tests__/fixtures/namespace.ts b/packages/plugin-protocol/src/__tests__/fixtures/namespace.ts
new file mode 100644
index 0000000000..7290cdf8f0
--- /dev/null
+++ b/packages/plugin-protocol/src/__tests__/fixtures/namespace.ts
@@ -0,0 +1,23 @@
+/**
+ * Copied from cindy-server packages/plugin-protocol/src/__tests__/fixtures/namespace.ts
+ * at 57850ca2 (S1 merge). The repos do not share this package; keep the sample in sync by hand.
+ */
+/** Reusable wire examples: same ghostId remains distinct by pluginId and namespace. */
+export const namespaceFixtures = (['public', 'organization', 'personal'] as const).map((scope, index) => {
+ const namespace = scope === 'organization' ? 'acme' : null;
+ const id = `c${String(index + 1).repeat(24)}`;
+ const releaseId = `release-${index}`;
+ const sha256 = 'a'.repeat(64);
+ const sizeBytes = 1024;
+ return {
+ plugin: {
+ id, ghostId: 'x-manager', namespace, scope,
+ organizationId: scope === 'organization' ? 'org-example' : null,
+ name: 'Example', description: null, author: null, defaultInstall: false,
+ currentRelease: { id: releaseId, version: '1.0.0', sha256, sizeBytes, publishedAt: '2026-09-07T00:00:00.000Z', icon: null,
+ manifest: { schemaVersion: 2 as const, id: 'x-manager', name: 'Example', version: '1.0.0', kind: 'chip' as const, entry: 'index.js', slots: [], namespace },
+ },
+ },
+ download: { pluginId: id, releaseId, ghostId: 'x-manager', namespace, sha256, sizeBytes, url: 'https://packages.example.test/package.cindy', expiresAt: '2026-09-07T00:05:00.000Z' },
+ };
+});
diff --git a/packages/plugin-protocol/src/__tests__/namespace.test.ts b/packages/plugin-protocol/src/__tests__/namespace.test.ts
new file mode 100644
index 0000000000..3b95fd6509
--- /dev/null
+++ b/packages/plugin-protocol/src/__tests__/namespace.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+import {
+ AUTHOR_DECLARED_NAMESPACE_REASON,
+ authorDeclaredNamespaceReason,
+ authorManifestDeclaresNamespace,
+} from '../delivery.js';
+
+describe('author namespace reservation', () => {
+ it.each([null, 'xd', '', 42])('rejects own namespace %s before v2 normalization', (namespace) => {
+ expect(authorManifestDeclaresNamespace({ id: 'example', namespace })).toBe(true);
+ expect(authorDeclaredNamespaceReason({ id: 'example', namespace })).toBe(
+ AUTHOR_DECLARED_NAMESPACE_REASON,
+ );
+ });
+
+ it('allows author packages that omit the field', () => {
+ expect(authorManifestDeclaresNamespace({ id: 'example' })).toBe(false);
+ expect(authorDeclaredNamespaceReason({ id: 'example' })).toBeNull();
+ });
+});
diff --git a/packages/plugin-protocol/src/__tests__/namespaceDelivery.test.ts b/packages/plugin-protocol/src/__tests__/namespaceDelivery.test.ts
new file mode 100644
index 0000000000..0e35dae8df
--- /dev/null
+++ b/packages/plugin-protocol/src/__tests__/namespaceDelivery.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+import { parseGetPluginResponse, parseListPluginsResponse, parsePluginDownloadResponse } from '../delivery.js';
+import { namespaceFixtures } from './fixtures/namespace.js';
+
+describe('namespace delivery contract', () => {
+ it.each(namespaceFixtures)('preserves $plugin.scope identity without changing schema 2', ({ plugin, download }) => {
+ const parsed = parseGetPluginResponse({ schemaVersion: 2, plugin }).plugin;
+ expect(parsed.namespace).toBe(plugin.namespace);
+ expect(parsed.currentRelease.manifest.namespace).toBe(plugin.namespace);
+ expect(parsePluginDownloadResponse(download)).toEqual(download);
+ expect(parseListPluginsResponse({ schemaVersion: 2, plugins: [plugin], nextCursor: null }).plugins[0]?.namespace).toBe(plugin.namespace);
+ });
+
+ it('rejects manifest and scope identity contradictions', () => {
+ const { plugin } = namespaceFixtures[1]!;
+ expect(() => parseGetPluginResponse({ schemaVersion: 2, plugin: { ...plugin, namespace: null } })).toThrow();
+ expect(() => parseGetPluginResponse({ schemaVersion: 2, plugin: { ...plugin, namespace: 'different' } })).toThrow();
+ expect(() => parseGetPluginResponse({ schemaVersion: 2, plugin: { ...plugin, namespace: '' } })).toThrow();
+ });
+
+ it('preserves missing fields as legacy, not root', () => {
+ const { plugin } = namespaceFixtures[1]!;
+ const { namespace: _namespace, ...legacy } = plugin;
+ const { namespace: _manifestNamespace, ...manifest } = plugin.currentRelease.manifest;
+ const parsed = parseGetPluginResponse({
+ schemaVersion: 2,
+ plugin: { ...legacy, currentRelease: { ...legacy.currentRelease, manifest } },
+ }).plugin;
+ expect(parsed).not.toHaveProperty('namespace');
+ expect(parsed.currentRelease.manifest).not.toHaveProperty('namespace');
+ expect(() => parseGetPluginResponse({ schemaVersion: 2, plugin: legacy })).toThrow();
+ });
+
+ it('rejects contradictory current organization facts', () => {
+ expect(() => parseListPluginsResponse({
+ schemaVersion: 2,
+ plugins: [namespaceFixtures[1]!.plugin],
+ nextCursor: null,
+ currentOrganization: { organizationId: 'org-example', orgSlug: 'different', pluginPrefix: 'oldprefix' },
+ })).toThrow();
+ });
+
+ it('rejects omitted organization namespace when currentOrganization.orgSlug is present', () => {
+ const { namespace: _namespace, ...legacy } = namespaceFixtures[1]!.plugin;
+ expect(() => parseListPluginsResponse({
+ schemaVersion: 2,
+ plugins: [legacy],
+ nextCursor: null,
+ currentOrganization: { organizationId: 'org-example', orgSlug: 'acme', pluginPrefix: 'oldprefix' },
+ })).toThrow();
+ expect(parseListPluginsResponse({
+ schemaVersion: 2,
+ plugins: [legacy],
+ nextCursor: null,
+ currentOrganization: { organizationId: 'org-example', pluginPrefix: 'oldprefix' },
+ }).plugins[0]).not.toHaveProperty('namespace');
+ });
+
+ it('does not accept incomplete download identity', () => {
+ const { namespace: _namespace, ...missing } = namespaceFixtures[0]!.download;
+ expect(() => parsePluginDownloadResponse(missing)).toThrow();
+ });
+
+ it('keeps orgSlug separate from prefix and binds purge to pluginId', () => {
+ const parsed = parseListPluginsResponse({
+ schemaVersion: 2,
+ plugins: [],
+ nextCursor: null,
+ currentOrganization: { organizationId: 'org-example', orgSlug: 'acme', pluginPrefix: 'oldprefix' },
+ removals: [{
+ pluginId: namespaceFixtures[1]!.plugin.id,
+ ghostId: 'x-manager',
+ scope: 'organization',
+ organizationId: 'org-example',
+ namespace: 'acme',
+ action: 'purge',
+ removedAt: '2026-09-07T00:00:00.000Z',
+ }],
+ });
+ expect(parsed.currentOrganization).toEqual({
+ organizationId: 'org-example',
+ orgSlug: 'acme',
+ pluginPrefix: 'oldprefix',
+ });
+ expect(parsed.removals[0]?.namespace).toBe('acme');
+ });
+});
diff --git a/packages/plugin-protocol/src/delivery.ts b/packages/plugin-protocol/src/delivery.ts
index 7970d37daa..202bd3895e 100644
--- a/packages/plugin-protocol/src/delivery.ts
+++ b/packages/plugin-protocol/src/delivery.ts
@@ -14,7 +14,14 @@ import {
string,
} from './internal/parse.js';
import { isValidPluginResourceId } from './internal/pluginResourceId.js';
-
+import { isValidPluginNamespace, parseOptionalNamespace } from './internal/namespace.js';
+
+export {
+ AUTHOR_DECLARED_NAMESPACE_REASON,
+ authorDeclaredNamespaceReason,
+ authorManifestDeclaresNamespace,
+ isValidPluginNamespace,
+} from './internal/namespace.js';
export { PluginProtocolError } from './internal/parse.js';
export { isValidPluginResourceId } from './internal/pluginResourceId.js';
@@ -40,6 +47,8 @@ export const PLUGIN_PREFIX_PATTERN = /^[a-z0-9]{2,16}$/;
export interface PluginCurrentOrganization {
/** 当前组织的稳定 ID。 */
organizationId: string;
+ /** Auth 永久组织 slug;旧服务端缺失时保持 undefined。 */
+ orgSlug?: string;
/**
* 已登记前缀原样保留,不带尾连字符。
* `null` 表示当前是组织身份,但该组织尚未登记前缀;
@@ -81,7 +90,7 @@ export interface PluginReleaseSummary {
/** 详情响应中的客户端兼容 Release;在摘要基础上包含已校验的完整 manifest。 */
export interface PluginReleaseDetail extends PluginReleaseSummary {
/** 已通过 `validateGhostManifest` 规范化的当前 manifest。 */
- manifest: GhostManifest;
+ manifest: GhostManifest & { namespace?: string | null };
}
/** Plugin 列表项;只含市场展示和版本对账所需的摘要。 */
@@ -99,6 +108,7 @@ export interface VisiblePluginSummary {
/** Plugin 的来源范围。 */
scope: PluginScope;
/** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */
+ namespace?: string | null;
organizationId: string | null;
/** 对当前请求身份计算后的默认安装值,不表示强制安装或强制启用。 */
defaultInstall: boolean;
@@ -121,6 +131,7 @@ export interface VisiblePluginDetail {
/** Plugin 的来源范围。 */
scope: PluginScope;
/** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */
+ namespace?: string | null;
organizationId: string | null;
/** 对当前请求身份计算后的默认安装值,不表示强制安装或强制启用。 */
defaultInstall: boolean;
@@ -143,6 +154,7 @@ export interface PluginRemovalNotice {
/** 被清理 Plugin 的来源范围;当前服务端只对 organization 下发通告。 */
scope: PluginScope;
/** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */
+ namespace?: string | null;
organizationId: string | null;
/** 处置动作。 */
action: PluginRemovalAction;
@@ -177,6 +189,10 @@ export interface GetPluginResponse {
/** 当前 Release 的短期私有下载凭证;不重复携带 HTTP envelope 版本。 */
export interface PluginDownloadResponse {
+ pluginId?: string;
+ releaseId?: string;
+ ghostId?: string;
+ namespace?: string | null;
/** 短期 HTTPS 下载地址。 */
url: string;
/** 下载地址过期时间,格式为带毫秒的 UTC ISO 8601。 */
@@ -244,7 +260,13 @@ function parseReleaseDetail(value: unknown, ghostId: string, path: string): Plug
if (summary.version !== validatedManifest.manifest.version) {
throw new PluginProtocolError(`${path}.version 与 manifest.version 不一致`);
}
- return { ...summary, manifest: validatedManifest.manifest };
+ return {
+ ...summary,
+ manifest: {
+ ...validatedManifest.manifest,
+ ...parseOptionalNamespace(object(raw.manifest, `${path}.manifest`), `${path}.manifest`),
+ },
+ };
}
function parseScope(value: unknown, path: string): PluginScope {
@@ -268,6 +290,17 @@ function parseScopedOrganizationId(
return value as string | null;
}
+function parseScopedNamespace(raw: Record<string, unknown>, scope: PluginScope, path: string) {
+ const identity = parseOptionalNamespace(raw, path);
+ if (
+ 'namespace' in identity &&
+ (scope === 'organization' ? identity.namespace === null : identity.namespace !== null)
+ ) {
+ throw new PluginProtocolError(`${path}.namespace 与 scope 不一致`);
+ }
+ return identity;
+}
+
function parseVisiblePluginBase(
value: unknown,
path: string,
@@ -279,6 +312,7 @@ function parseVisiblePluginBase(
description: string | null;
author: string | null;
scope: PluginScope;
+ namespace?: string | null;
organizationId: string | null;
defaultInstall: boolean;
} {
@@ -287,6 +321,7 @@ function parseVisiblePluginBase(
if (!isValidGhostId(raw.ghostId)) throw new PluginProtocolError(`${path}.ghostId 不合法`);
const scope = parseScope(raw.scope, path);
const organizationId = parseScopedOrganizationId(scope, raw.organizationId, path);
+ const identity = parseScopedNamespace(raw, scope, path);
if (typeof raw.defaultInstall !== 'boolean') {
throw new PluginProtocolError(`${path}.defaultInstall 必须是 boolean`);
}
@@ -299,6 +334,7 @@ function parseVisiblePluginBase(
raw.description === null ? null : string(raw.description, `${path}.description`, 300),
author: raw.author === null ? null : string(raw.author, `${path}.author`),
scope,
+ ...identity,
organizationId,
defaultInstall: raw.defaultInstall,
};
@@ -306,24 +342,17 @@ function parseVisiblePluginBase(
function parseVisiblePluginSummary(value: unknown, index: number): VisiblePluginSummary {
const path = `plugins[${index}]`;
- const parsed = parseVisiblePluginBase(value, path);
+ const { raw, ...base } = parseVisiblePluginBase(value, path);
return {
- id: parsed.id,
- ghostId: parsed.ghostId,
- name: parsed.name,
- description: parsed.description,
- author: parsed.author,
- scope: parsed.scope,
- organizationId: parsed.organizationId,
- defaultInstall: parsed.defaultInstall,
- currentRelease: parseReleaseSummary(parsed.raw.currentRelease, `${path}.currentRelease`),
+ ...base,
+ currentRelease: parseReleaseSummary(raw.currentRelease, `${path}.currentRelease`),
};
}
function parseVisiblePluginDetail(value: unknown, path: string): VisiblePluginDetail {
- const parsed = parseVisiblePluginBase(value, path);
+ const { raw, ...parsed } = parseVisiblePluginBase(value, path);
const currentRelease = parseReleaseDetail(
- parsed.raw.currentRelease,
+ raw.currentRelease,
parsed.ghostId,
`${path}.currentRelease`,
);
@@ -332,6 +361,9 @@ function parseVisiblePluginDetail(value: unknown, path: string): VisiblePluginDe
`${path}.currentRelease.manifest 的 oidc-token 仅允许 organization scope`,
);
}
+ if (parsed.namespace !== currentRelease.manifest.namespace) {
+ throw new PluginProtocolError(`${path}.namespace 与有效 manifest 不一致`);
+ }
const manifestDescription = currentRelease.manifest.description ?? null;
const manifestAuthor = currentRelease.manifest.author ?? null;
if (parsed.name !== currentRelease.manifest.name) {
@@ -346,14 +378,7 @@ function parseVisiblePluginDetail(value: unknown, path: string): VisiblePluginDe
throw new PluginProtocolError(`${path}.author 与 currentRelease.manifest.author 不一致`);
}
return {
- id: parsed.id,
- ghostId: parsed.ghostId,
- name: parsed.name,
- description: parsed.description,
- author: parsed.author,
- scope: parsed.scope,
- organizationId: parsed.organizationId,
- defaultInstall: parsed.defaultInstall,
+ ...parsed,
currentRelease,
};
}
@@ -366,6 +391,7 @@ function parseRemovalNotice(value: unknown, path: string): PluginRemovalNotice |
if (!isValidGhostId(raw.ghostId)) throw new PluginProtocolError(`${path}.ghostId 不合法`);
const scope = parseScope(raw.scope, path);
const organizationId = parseScopedOrganizationId(scope, raw.organizationId, path);
+ const identity = parseScopedNamespace(raw, scope, path);
const action = string(raw.action, `${path}.action`, 64);
const removedAt = isoDate(raw.removedAt, `${path}.removedAt`);
// 未知动作是未来扩展位:结构校验通过后跳过该条而不是拒绝整个响应,
@@ -375,6 +401,7 @@ function parseRemovalNotice(value: unknown, path: string): PluginRemovalNotice |
pluginId: raw.pluginId,
ghostId: raw.ghostId,
scope,
+ ...identity,
organizationId,
action: action as PluginRemovalAction,
removedAt,
@@ -402,18 +429,25 @@ function parseCurrentOrganization(value: unknown): PluginCurrentOrganization | n
'response.currentOrganization.organizationId',
128,
);
+ const orgSlug =
+ Object.prototype.hasOwnProperty.call(raw, 'orgSlug')
+ ? { orgSlug: raw.orgSlug as string }
+ : {};
+ if ('orgSlug' in orgSlug && !isValidPluginNamespace(orgSlug.orgSlug)) {
+ throw new PluginProtocolError('currentOrganization.orgSlug 不合法');
+ }
// 「对象在、但省略了 pluginPrefix key」是畸形响应,不能规范化成 null:
// 那会把「未登记前缀」和「取不到组织」混成一种,上层再也分不开。
if (!Object.prototype.hasOwnProperty.call(raw, 'pluginPrefix')) {
throw new PluginProtocolError('response.currentOrganization.pluginPrefix 缺失');
}
if (raw.pluginPrefix === null) {
- return { organizationId, pluginPrefix: null };
+ return { organizationId, ...orgSlug, pluginPrefix: null };
}
if (typeof raw.pluginPrefix !== 'string' || !PLUGIN_PREFIX_PATTERN.test(raw.pluginPrefix)) {
throw new PluginProtocolError('response.currentOrganization.pluginPrefix 不合法');
}
- return { organizationId, pluginPrefix: raw.pluginPrefix };
+ return { organizationId, ...orgSlug, pluginPrefix: raw.pluginPrefix };
}
/**
@@ -430,15 +464,38 @@ export function parseListPluginsResponse(value: unknown): ListPluginsResponse {
throw new PluginProtocolError(`response.schemaVersion 必须为 ${PLUGIN_API_SCHEMA_VERSION}`);
}
if (!Array.isArray(raw.plugins)) throw new PluginProtocolError('response.plugins 必须是数组');
+ const plugins = raw.plugins.map(parseVisiblePluginSummary);
+ const removals = parseRemovals(raw.removals);
+ const currentOrganization = parseCurrentOrganization(raw.currentOrganization);
+ assertPluginListOrganizationNamespace(currentOrganization, plugins, removals);
return {
schemaVersion: PLUGIN_API_SCHEMA_VERSION,
- plugins: raw.plugins.map(parseVisiblePluginSummary),
+ plugins,
nextCursor: nextCursor(raw.nextCursor, 'response.nextCursor'),
- removals: parseRemovals(raw.removals),
- currentOrganization: parseCurrentOrganization(raw.currentOrganization),
+ removals,
+ currentOrganization,
};
}
+export function assertPluginListOrganizationNamespace(
+ currentOrganization: PluginCurrentOrganization | null,
+ plugins: readonly VisiblePluginSummary[],
+ removals: readonly PluginRemovalNotice[],
+): void {
+ if (currentOrganization?.orgSlug !== undefined) {
+ for (const item of [...plugins, ...removals]) {
+ if (item.scope !== 'organization') continue;
+ if (
+ item.namespace === undefined ||
+ item.organizationId !== currentOrganization.organizationId ||
+ item.namespace !== currentOrganization.orgSlug
+ ) {
+ throw new PluginProtocolError('response 企业 namespace 与 currentOrganization 不一致');
+ }
+ }
+ }
+}
+
/**
* 解析并规范化单个 Plugin 详情响应。
*
@@ -471,7 +528,27 @@ export function parsePluginDownloadResponse(value: unknown): PluginDownloadRespo
) {
throw new PluginProtocolError('response.sizeBytes 必须是正整数');
}
+ const identity = parseOptionalNamespace(raw, 'response');
+ const hasIdentity = ['pluginId', 'releaseId', 'ghostId', 'namespace'].some((key) =>
+ Object.prototype.hasOwnProperty.call(raw, key),
+ );
+ if (
+ hasIdentity &&
+ (!isValidPluginResourceId(raw.pluginId) ||
+ !isValidGhostId(raw.ghostId) ||
+ !('namespace' in identity))
+ ) {
+ throw new PluginProtocolError('response 下载身份不完整或不合法');
+ }
return {
+ ...(hasIdentity
+ ? {
+ pluginId: raw.pluginId as string,
+ releaseId: string(raw.releaseId, 'response.releaseId', 128),
+ ghostId: raw.ghostId as string,
+ ...identity,
+ }
+ : {}),
url: httpsUrl(raw.url, 'response.url'),
expiresAt: isoDate(raw.expiresAt, 'response.expiresAt'),
sha256: sha256(raw.sha256, 'response.sha256'),
diff --git a/packages/plugin-protocol/src/internal/namespace.ts b/packages/plugin-protocol/src/internal/namespace.ts
new file mode 100644
index 0000000000..4966de03c4
--- /dev/null
+++ b/packages/plugin-protocol/src/internal/namespace.ts
@@ -0,0 +1,34 @@
+import { PluginProtocolError } from './parse.js';
+
+/** Permanent organization slugs and generated org-* identifiers. */
+export function isValidPluginNamespace(value: unknown): value is string {
+ return typeof value === 'string' && /^[a-z0-9](?:[a-z0-9-]{0,126}[a-z0-9])?$/.test(value);
+}
+
+export const AUTHOR_DECLARED_NAMESPACE_REASON = 'ghost.json 不允许作者声明 namespace';
+
+/** Authors cannot claim platform identity, including an explicit null. */
+export function authorManifestDeclaresNamespace(value: unknown): boolean {
+ return Boolean(
+ value &&
+ typeof value === 'object' &&
+ !Array.isArray(value) &&
+ Object.prototype.hasOwnProperty.call(value, 'namespace'),
+ );
+}
+
+export function authorDeclaredNamespaceReason(value: unknown): string | null {
+ return authorManifestDeclaresNamespace(value) ? AUTHOR_DECLARED_NAMESPACE_REASON : null;
+}
+
+/** Missing is an old protocol, never an implicit root namespace. */
+export function parseOptionalNamespace(
+ raw: Record<string, unknown>,
+ path: string,
+): { namespace?: string | null } {
+ if (!Object.prototype.hasOwnProperty.call(raw, 'namespace')) return {};
+ if (raw.namespace !== null && !isValidPluginNamespace(raw.namespace)) {
+ throw new PluginProtocolError(`${path}.namespace 不合法`);
+ }
+ return { namespace: raw.namespace as string | null };
+}