Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 减少插件扫描与 Learn 列表检查的主进程阻塞 (#6441)
DavidShenXD5611cfe4bfaa
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 4896499fba..4e252b1b8d 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -668,7 +668,7 @@ import { rehydrateCloseSuppression } from './maker-host/rehydrateCloseSuppressioimport {builtInSkillDescriptors,} from './maker-host/built-in-skills.js';-import { isCindyLearnSkillEnabled } from './skillhub/activationPreferences';+import { isCindyLearnSkillEnabled, isCindyLearnSkillEnabledForCommandListing } from './skillhub/activationPreferences';// Maker Core 一阶段重构(新链路)—— 静态 import 避免 dynamic import 触发 vite chunking// 让 imageProtocol 等需要 app.ready 前注册的模块跑在错误时机。getMaker() 是 lazy 的,// 静态 import 不会触发 Maker / Agent 的实例化。@@ -6293,6 +6293,7 @@ const registerIpcHandlers = () => {getGoalController,getLearnController,isLearnEnabled: isCindyLearnSkillEnabled,+ isLearnEnabledForListing: isCindyLearnSkillEnabledForCommandListing,remoteInvoke: (deviceId, channel, args) =>deviceLinkHandleInvoke(deviceLinkIpcDeps(), deviceId, channel, args),});diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex b8572ed0ee..db0c3da2a7 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -833,9 +833,11 @@ export class GhostManager {return listed;}- private receiptFact(relId: string): PluginInstanceReceiptFact | null | undefined {- const recovery = this.receiptStore.readForRecovery(relId);- if (recovery.state === 'invalid' || recovery.state === 'unreadable') return undefined;+ private receiptFact(+ relId: string,+ recovery = this.receiptStore.read(relId),+ ): PluginInstanceReceiptFact | null | undefined {+ if (recovery.state === 'invalid') return undefined;if (recovery.state !== 'approved') return null;const receipt = recovery.receipt;return {@@ -1926,14 +1928,17 @@ export class GhostManager {* 调 receiptStore.read() 会让隔离在某条路径上失效,那类"同一判定散落多处"的分叉* 正是本 PR 前几轮反复出问题的原因。*/- private readApproval(id: string): GhostInstallReceiptReadResult {+ private readApproval(+ id: string,+ readReceipt = (relId: string) => this.receiptStore.read(relId),+ ): GhostInstallReceiptReadResult {if (this.recoveryBlockedApprovalNamespaces.has(this.approvalNamespaceKey())) {return { state: 'invalid', reason: 'ghost mutation journal namespace is unreadable' };}if (this.untrustedApprovals.has(this.isolationKey(id))) {return { state: 'invalid', reason: '批准状态已被判定不可信(撤销失败)' };}- return this.receiptStore.read(id);+ return readReceipt(id);}/**@@ -2573,11 +2578,26 @@ export class GhostManager {return true;}- /** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */+ /** Synchronous first-frame projection; share disk reads only within this call. */list(): InstalledGhost[] {this.ensureCurrentOwnerContextSync();- this.syncInstanceRegistry();- const result = this.projectListedEntries(this.listContentEntries());+ const entries = this.listContentEntries();+ const receipts = new Map<string, GhostInstallReceiptReadResult>();+ const readReceipt = (relId: string): GhostInstallReceiptReadResult => {+ let receipt = receipts.get(relId);+ if (!receipt) {+ receipt = this.receiptStore.read(relId);+ receipts.set(relId, receipt);+ }+ return receipt;+ };+ // Registry facts and the list projection consume the same validated bytes.+ // No cache survives this synchronous scan; isolation checks still run below.+ this.instanceRegistryService.sync({+ listContentEntries: () => entries,+ receiptFact: (relId) => this.receiptFact(relId, readReceipt(relId)),+ });+ const result = this.projectListedEntries(entries, readReceipt);result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));return result;}@@ -2603,13 +2623,16 @@ export class GhostManager {return ghost && installedGhostStoragePart(ghost) === instanceKey ? ghost : undefined;}- private projectListedEntries(listedDirs: Array<{ relId: string; dir: string }>): InstalledGhost[] {+ private projectListedEntries(+ listedDirs: Array<{ relId: string; dir: string }>,+ readReceipt?: (relId: string) => GhostInstallReceiptReadResult,+ ): InstalledGhost[] {const result: InstalledGhost[] = [];for (const listed of listedDirs) {const { relId, dir } = listed;const identity = parsePluginInstallRelId(relId);if (!identity) continue;- const approvalResult = this.readApproval(relId);+ const approvalResult = this.readApproval(relId, readReceipt);if (approvalResult.state === 'approved') {const receipt = approvalResult.receipt;const localizedManifest = this.localizeApprovedManifest(receipt);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 5b53a2ea12..5c7ccb51f2 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -104,6 +104,28 @@ function goodManifest(id = 'hello'): Record<string, unknown> {}describe('GhostManager enable revision boundary', () => {+ // Regression: one list() used two validated receipt reads per plugin. Unit+ // coverage also rejects a cross-call cache: the next scan must see revocation.+ it('reads each receipt once per scan and observes changed approval on the next scan', async () => {+ await manager.install(await makeCindy('scan.cindy', goodManifest()));+ const read = vi.spyOn(GhostInstallReceiptStore.prototype, 'readForRecovery');+ try {+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(read).toHaveBeenCalledTimes(1);+ read.mockClear();+ const receiptPath = path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json');+ const receipt = JSON.parse(fs.readFileSync(receiptPath, 'utf8'));+ receipt.enabled = false;+ fs.writeFileSync(receiptPath, JSON.stringify(receipt));+ expect(manager.list()[0]).toMatchObject({ enabled: false, approval: { state: 'approved' } });+ expect(read).toHaveBeenCalledTimes(1);+ fs.writeFileSync(receiptPath, '{invalid');+ expect(manager.list()[0]).toMatchObject({ enabled: false, approval: { state: 'invalid' } });+ } finally {+ read.mockRestore();+ }+ });+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];diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex df3c30c0ef..9e47dd457f 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -119,6 +119,64 @@ describe('GhostInstallReceiptStore cleanup', () => {});}+ // Unit regression: repeated store.read() must reuse only icon format validation.+ // Existing receipt tests do not cover unchanged revision/path with replaced icon+ // bytes. A same-length invalid replacement must fail, and enabled stays fresh.+ it('reuses unchanged icon validation while checking changed bytes and approval state', () => {+ const receipt = createSetupReceipt();+ const icon = 'data:image/png;base64,' + Buffer.from(workDir).toString('base64');+ const receiptPath = path.join(stateRoot, 'hello.json');+ const persist = (iconDataUrl: string, enabled = true) => {+ fs.writeFileSync(receiptPath, JSON.stringify({ ...receipt, iconDataUrl, enabled }));+ };+ const regexTest = vi.spyOn(RegExp.prototype, 'test');+ const iconChecks = (value: string) => regexTest.mock.calls.filter(([input]) => input === value).length;++ persist(icon);+ expect(store.read('hello')).toMatchObject({ state: 'approved', receipt: { iconDataUrl: icon } });+ expect(store.read('hello')).toMatchObject({ state: 'approved', receipt: { iconDataUrl: icon } });+ expect(iconChecks(icon)).toBe(1);++ const originalStat = fs.statSync(receiptPath);+ const invalidIcon = icon.slice(0, -1) + '!';+ persist(invalidIcon);+ fs.utimesSync(receiptPath, originalStat.atime, originalStat.mtime);+ expect(store.read('hello')).toMatchObject({ state: 'invalid' });+ expect(iconChecks(invalidIcon)).toBe(1);++ const replacement = icon.replace('image/png', 'image/gif');+ persist(replacement);+ expect(store.read('hello')).toMatchObject({ state: 'approved', receipt: { iconDataUrl: replacement } });+ persist(replacement, false);+ expect(store.read('hello')).toMatchObject({ state: 'approved', receipt: { enabled: false } });+ expect(iconChecks(replacement)).toBe(1);++ fs.writeFileSync(receiptPath, JSON.stringify({ ...receipt, iconDataUrl: replacement, trust: null }));+ expect(store.read('hello')).toMatchObject({ state: 'invalid' });+ });++ // Unit resource regression: read() must evict validated strings at both cache+ // budgets; eviction only causes revalidation, never changes approval results.+ it.each([+ { budget: 'entry count', count: 70, payloadSize: 32 },+ { budget: 'retained bytes', count: 7, payloadSize: 700 * 1024 },+ ])('revalidates evicted icons after exceeding the $budget budget', ({ count, payloadSize }) => {+ const receipt = createSetupReceipt();+ const receiptPath = path.join(stateRoot, 'hello.json');+ const prefix = 'data:image/png;base64,' + Buffer.from(workDir).toString('base64').replace(/=+$/, '');+ const firstIcon = prefix + 'A'.repeat(payloadSize) + '0';+ const regexTest = vi.spyOn(RegExp.prototype, 'test');+ for (let index = 0; index < count; index++) {+ fs.writeFileSync(receiptPath, JSON.stringify({+ ...receipt, iconDataUrl: prefix + 'A'.repeat(payloadSize) + index,+ }));+ expect(store.read('hello').state).toBe('approved');+ }+ fs.writeFileSync(receiptPath, JSON.stringify({ ...receipt, iconDataUrl: firstIcon }));+ expect(store.read('hello')).toMatchObject({ state: 'approved', receipt: { iconDataUrl: firstIcon } });+ expect(regexTest.mock.calls.filter(([input]) => input === firstIcon)).toHaveLength(2);+ });+it('removes a regular receipt and managed snapshot tree', async () => {const receipt = path.join(stateRoot, 'hello.json');const snapshot = path.join(stateRoot, 'skill-snapshots', 'hello', 'revision');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.tsindex a45d8d280d..0ca73cfdd0 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts@@ -17,6 +17,10 @@ const load = createGhostProductionCallbacks<{'getGhostCardActionDispatcher', 'resolveMobilePluginMedia', 'setGhostEnabledForUser'],initialize: 'let cardActionDispatcherSingleton = null;' });+const loadUsageBinding = createGhostProductionCallbacks<{+ bindPluginUsage: (ghost: InstalledGhost) => Promise<void>;+}>({ functions: ['bindPluginUsage'] });+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: {} },@@ -117,3 +121,47 @@ describe('production plugin instance boundaries', () => {expect(fixture.send).toHaveBeenLastCalledWith('_root__helper', expect.any(Object));});});++describe('usage binding instance revalidation', () => {+ // Unit regression: a market refresh used to rescan every plugin once per+ // binding. Read the committed target inside the lock and retain fallback for+ // missing registry entries, without binding a same-name replacement instance.+ it.each(['indexed', 'fallback', 'removed', 'owner-changed'] as const)(+ 'revalidates the committed installation with %s state', async (state) => {+ const { organization, root } = harness();+ const committed: InstalledGhost = {+ ...organization, approval: { state: 'approved', revision: 'committed' },+ };+ let locked = false;+ let scope = 'owner-a';+ const list = vi.fn(() => state === 'removed' ? [root] : [committed, root]);+ const findInstalledInstance = vi.fn((key: string) => {+ expect(locked).toBe(true);+ expect(key).toBe(installedGhostStoragePart(organization));+ return state === 'indexed' ? committed : undefined;+ });+ const bind = vi.fn(async () => {});+ const api = loadUsageBinding({+ activeOwnerScopeKey: () => scope,+ currentPluginUsageService: () => ({ bind }),+ isAppSessionBoundaryPending: () => false,+ getGhostManager: () => ({ list, findInstalledInstance }),+ findInstalledGhostByInstanceId,+ readPluginUsageIdentity: (ghost: InstalledGhost) => ghost.approval,+ withGhostInstallLock: async (_id: string, callback: () => Promise<void>) => {+ locked = true;+ if (state === 'owner-changed') scope = 'owner-b';+ await callback();+ },+ log: { warn: vi.fn() },+ });+ await api.bindPluginUsage(organization);+ if (state === 'removed' || state === 'owner-changed') {+ expect(bind).not.toHaveBeenCalled();+ } else {+ expect(bind).toHaveBeenCalledExactlyOnceWith(committed.approval, undefined);+ }+ expect(list).toHaveBeenCalledTimes(state === 'indexed' || state === 'owner-changed' ? 0 : 1);+ },+ );+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.tsindex e3c18f84e8..99e0857feb 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts@@ -169,12 +169,15 @@ function fixture(namespace: string | null = null) {},localDeviceId: () => 'controller-a',trustIdentity: vi.fn(async () => {}),- identity: async () => ({- ...identity,- ...identity.key.descriptor,- observedAtMs: Date.now(),- expiresAtMs: Date.now() + 60_000,- }),+ identity: async () => {+ const observedAtMs = Date.now();+ return {+ ...identity,+ ...identity.key.descriptor,+ observedAtMs,+ expiresAtMs: observedAtMs + 60_000,+ };+ },invoke: async (_device: string, channel: string, args: unknown[]) => {wire.push(args);const result =@@ -251,7 +254,12 @@ describe('original remote plugin settings', () => {expect(ses.setPermissionCheckHandler).toHaveBeenCalled();},);- it('writes a new key only to B through the signed encrypted exchange, then reads B status', async () => {+ it('writes a new key only to B through the signed encrypted exchange, then reads B status', async ({ onTestFinished }) => {+ // Unit regression: the real handshake/write must work when each clock read advances 1 ms.+ // The wall-clock fixture previously missed this boundary and intermittently failed in CI.+ let now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now++);+ onTestFinished(() => clock.mockRestore());const f = fixture(),{ fetch } = await f.open();const value = 'synthetic-new-key-only-for-fixture';diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 46fef52f75..56bbe4b535 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -85,6 +85,32 @@ export function assertManagedPluginParentSync(* 校验 —— 只认前缀会让被改写的 receipt 把任意字符串塞进 renderer 的 img src。*/const ICON_DATA_URL_RE = /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/;+const MAX_CACHED_ICON_DATA_URLS = 64;+const MAX_CACHED_ICON_DATA_URL_BYTES = 4 * 1024 * 1024;+const validatedIconDataUrls = new Set<string>();+let cachedIconDataUrlBytes = 0;++/** Only immutable, fully validated icon strings are reused, never receipt approval. */+function isValidIconDataUrl(value: unknown): value is string {+ if (typeof value !== 'string') return false;+ if (validatedIconDataUrls.has(value)) {+ validatedIconDataUrls.delete(value);+ validatedIconDataUrls.add(value);+ return true;+ }+ const bytes = Buffer.byteLength(value, 'utf8');+ if (bytes > MAX_ICON_DATA_URL_BYTES || !ICON_DATA_URL_RE.test(value)) return false;+ while (validatedIconDataUrls.size >= MAX_CACHED_ICON_DATA_URLS ||+ cachedIconDataUrlBytes + bytes > MAX_CACHED_ICON_DATA_URL_BYTES) {+ const oldest = validatedIconDataUrls.values().next().value;+ if (oldest === undefined) break;+ validatedIconDataUrls.delete(oldest);+ cachedIconDataUrlBytes -= Buffer.byteLength(oldest, 'utf8');+ }+ validatedIconDataUrls.add(value);+ cachedIconDataUrlBytes += bytes;+ return true;+}/*** 一次明确批准的插件安装事实;只允许 Host 写入安装目录之外的状态根。@@ -251,8 +277,7 @@ export class GhostInstallReceiptStore {return path.resolve(this.getRootDir());}- private assertPathParentSync(absPath: string, createMissing = false): boolean {- const root = this.rootDir();+ private assertPathParentSync(absPath: string, createMissing = false, root = this.rootDir()): boolean {return assertManagedPluginParentSync(root,path.relative(root, absPath).split(path.sep).join('/'),@@ -309,14 +334,17 @@ export class GhostInstallReceiptStore {/** Recovery must not confuse transient state-root IO with missing/corrupt approval state. */readForRecovery(id: string): GhostInstallReceiptRecoveryReadResult {- const receiptPath = this.receiptPath(id);+ // Bind path construction and all containment checks to one resolved owner+ // root for this read. Each call still opens and validates the actual bytes.+ const root = this.rootDir();+ const receiptPath = this.receiptPath(id, root);let bytes: Buffer | null;try {- if (!this.assertPathParentSync(receiptPath)) {+ if (!this.assertPathParentSync(receiptPath, false, root)) {return { state: 'missing' };}bytes = readBoundedFileNoFollowSync(receiptPath, MAX_RECEIPT_BYTES, {- containWithin: this.realRootDirSync(),+ containWithin: fs.realpathSync(root),});} catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') {@@ -996,9 +1024,9 @@ export class GhostInstallReceiptStore {return { state: 'ok', ids, blocked };}- private receiptPath(id: string): string {+ private receiptPath(id: string, root = this.rootDir()): string {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`);+ return path.join(root, ...id.split('/').slice(0, -1), `${id.split('/').at(-1)}.json`);}private async ensureSkillSnapshot(@@ -1352,9 +1380,7 @@ function validateReceipt(}if (value.iconDataUrl !== undefined &&- (typeof value.iconDataUrl !== 'string' ||- Buffer.byteLength(value.iconDataUrl, 'utf8') > MAX_ICON_DATA_URL_BYTES ||- !ICON_DATA_URL_RE.test(value.iconDataUrl))+ !isValidIconDataUrl(value.iconDataUrl)) {return { ok: false, reason: 'receipt iconDataUrl 不合法' };}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 1634ffdec3..11cdf29000 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -3098,7 +3098,10 @@ async function bindPluginUsage(ghost: InstalledGhost, previousRevision?: string)await withGhostInstallLock(ghost.manifest.id, async () => {if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending()) return;// A fallback bind can wait behind update/uninstall. Read the final committed identity.- const installed = findInstalledGhostByInstanceId(getGhostManager().list(), installedGhostStoragePart(ghost));+ const manager = getGhostManager();+ const instanceKey = installedGhostStoragePart(ghost);+ const installed = manager.findInstalledInstance(instanceKey)+ ?? findInstalledGhostByInstanceId(manager.list(), instanceKey);const identity = installed && readPluginUsageIdentity(installed);if (identity) await service.bind(identity, previousRevision);});diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.tsindex 08126d1826..6a3aefe16b 100644--- a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts@@ -195,7 +195,7 @@ export class PluginInstanceRegistryService {return parsePluginInstallRelId(relId)?.ghostId === relId;}- sync(): PluginInstanceRegistry {+ sync(scan: Pick<PluginInstanceRegistryServiceDeps, 'listContentEntries' | 'receiptFact'> = this.deps): PluginInstanceRegistry {this.deps.ensureOwner();const store = this.deps.registryStore();const opened = this.open(store);@@ -204,9 +204,9 @@ export class PluginInstanceRegistryService {let registry = opened.registry;let dirty = false;const present = new Set<string>();- for (const listed of this.deps.listContentEntries()) {+ for (const listed of scan.listContentEntries()) {present.add(listed.relId);- const fact = this.deps.receiptFact(listed.relId);+ const fact = scan.receiptFact(listed.relId);if (fact === undefined) continue;const existing = findInstanceByContentRelId(registry, listed.relId);if (!existing) {diff --git a/apps/desktop/src/main/commands/__tests__/builtinsRemoteRouting.test.ts b/apps/desktop/src/main/commands/__tests__/builtinsRemoteRouting.test.tsindex 0193d59957..786ab3c8b3 100644--- a/apps/desktop/src/main/commands/__tests__/builtinsRemoteRouting.test.ts+++ b/apps/desktop/src/main/commands/__tests__/builtinsRemoteRouting.test.ts@@ -38,6 +38,7 @@ function sentPayloads(): Payload[] {function makeHarness(overrides?: {remoteInvoke?: (deviceId: string, channel: string, args: unknown[]) => Promise<unknown>;isLearnEnabled?: () => boolean;+ isLearnEnabledForListing?: () => boolean;}) {const registry = new DesktopCommandRegistry();const goalController = { setGoal: vi.fn(), clearGoal: vi.fn() };@@ -47,6 +48,7 @@ function makeHarness(overrides?: {getGoalController: () => goalController as never,getLearnController: () => learnController as never,isLearnEnabled: overrides?.isLearnEnabled ?? (() => true),+ isLearnEnabledForListing: overrides?.isLearnEnabledForListing,remoteInvoke,});return { registry, goalController, learnController, remoteInvoke };@@ -98,6 +100,21 @@ describe('/learn SSH fallback', () => {);});+ it('lists Learn from its preference and checks availability only on execution', async () => {+ // Unit regression: task switches must not hash bundled Skills for display;+ // a visible command still cannot execute when its integrity gate rejects it.+ const enabled = vi.fn(() => false);+ const { registry, learnController } = makeHarness({+ isLearnEnabled: enabled,+ isLearnEnabledForListing: () => true,+ });+ expect(registry.list()).toContainEqual(expect.objectContaining({ name: 'learn' }));+ expect(enabled).not.toHaveBeenCalled();+ await expect(registry.execute('learn', { sessionId: 'ssh-session' })).rejects.toThrow('unknown command');+ expect(enabled).toHaveBeenCalledTimes(1);+ expect(learnController.startLearn).not.toHaveBeenCalled();+ });+it('keeps the remote fallback when only the controlling host disabled Learn', async () => {const { registry, learnController, remoteInvoke } = makeHarness({isLearnEnabled: () => false,diff --git a/apps/desktop/src/main/commands/builtins.ts b/apps/desktop/src/main/commands/builtins.tsindex dd9eebd5cc..ca2ea30295 100644--- a/apps/desktop/src/main/commands/builtins.ts+++ b/apps/desktop/src/main/commands/builtins.ts@@ -343,6 +343,7 @@ export interface BuiltinDesktopCommandDeps {getLearnController: () => LearnController | null;/** Learn Skill 的设备/profile 开关;SSH 兼容入口与 Skill 使用同一开关。 */isLearnEnabled: () => boolean;+ isLearnEnabledForListing?: () => boolean;/*** device-link 隧道 invoke(控制端 → 被控端)。ctx.deviceId 存在(远程会话)时,* /goal /learn /cmd 的业务体经它路由到被控端执行 —— 与 renderer 的@@ -703,6 +704,8 @@ export function registerBuiltinDesktopCommands(// preference. Keep the compatibility route and let remote learn:start// enforce the controlled host's effective setting.isVisible: (ctx) => Boolean(ctx?.deviceId) || deps.isLearnEnabled(),+ isVisibleForListing: (ctx) => Boolean(ctx?.deviceId)+ || (deps.isLearnEnabledForListing ?? deps.isLearnEnabled)(),execute: async (ctx) => {const arg = (ctx.args ?? '').trim();if (!arg && !ctx.sessionId) {diff --git a/apps/desktop/src/main/commands/registry.ts b/apps/desktop/src/main/commands/registry.tsindex b72a2f4dab..8894614340 100644--- a/apps/desktop/src/main/commands/registry.ts+++ b/apps/desktop/src/main/commands/registry.ts@@ -58,6 +58,8 @@ export interface DesktopCommandDefinition {description: string;/** Optional dynamic gate for commands backed by a user-toggleable capability. */isVisible?: (ctx?: Pick<DesktopCommandContext, 'deviceId'>) => boolean;+ /** Lightweight display-only check; execute always rechecks isVisible. */+ isVisibleForListing?: (ctx?: Pick<DesktopCommandContext, 'deviceId'>) => boolean;/*** 主入口 —— 命中此命令时由 main 执行。* 同步/异步皆可; 抛错由调用方 catch + 上报, 不会自动 swallow。@@ -82,7 +84,7 @@ export class DesktopCommandRegistry {*/list(ctx?: Pick<DesktopCommandContext, 'deviceId'>): DesktopCommandMeta[] {return Array.from(this.commands.values())- .filter((c) => c.isVisible?.(ctx) !== false)+ .filter((c) => (c.isVisibleForListing ?? c.isVisible)?.(ctx) !== false).map((c) => ({kind: 'desktop' as const,name: c.name,diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex ef420b3fc7..32a7659a96 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -15,6 +15,8 @@ import {type InstalledGhost,} from '../../../shared/ghost.js';const runtime = vi.hoisted(() => ({+ listScans: 0,+ onList: undefined as (() => void) | undefined,confirmLegacyLibraryReattach: vi.fn<(plugin: unknown) => Promise<boolean>>(async () => false),ghosts: [] as Array<{manifest: Record<string, unknown>;@@ -109,8 +111,10 @@ vi.mock('../../cindy-brain/index.js', () => ({getGhostManager: () => ({resumePendingResidentsOffline: runtime.resumeOfflineResidents,reconcilePendingRootNamespaces: runtime.reconcilePendingRootNamespaces,- list: () =>- runtime.ghosts.map((ghost) => {+ list: () => {+ runtime.listScans++;+ runtime.onList?.();+ return runtime.ghosts.map((ghost) => {// Historical service tests used a production-looking placeholder path.// Materialize only that fixture shape so raw-byte identity is exercised;// explicit missing/unreadable temp-path cases remain untouched.@@ -139,7 +143,8 @@ vi.mock('../../cindy-brain/index.js', () => ({reviewed: false,},};- }),+ });+ },approvedInstallEvidence: runtime.approvedInstallEvidence,inspect: runtime.inspect,readApprovedInstallOriginStrict: (ghostId: string) => {@@ -253,6 +258,8 @@ function deferred(): { promise: Promise<void>; resolve: () => void } {}afterEach(() => {+ runtime.listScans = 0;+ runtime.onList = undefined;runtime.ghosts = [];runtime.confirmLegacyLibraryReattach.mockReset();runtime.confirmLegacyLibraryReattach.mockImplementation(async () => false);@@ -997,6 +1004,47 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBeUndefined();});+ // Regression: ineligible legacy records caused one full scan per record on+ // every market refresh. Unit budget uses scan count, not machine-dependent time.+ it('uses a constant number of scans for unchanged records that cannot be backfilled', async () => {+ const first = summary();+ const items = [first];+ const h = harness(items);+ runtime.ghosts = [ghostEntry(first.ghostId)];+ h.ledger.upsertInstallation(recordForTest(first));+ const one = await h.service.snapshot();+ expect(one.items[0]?.installState).toBe('installed');+ const singleScans = runtime.listScans;+ runtime.listScans = 0;+ const second = summary({ id: `c${'b'.repeat(24)}`, ghostId: 'cindy-other' });+ items.push(second);+ runtime.ghosts.push(ghostEntry(second.ghostId));+ h.ledger.upsertInstallation(recordForTest(second));+ const two = await h.service.snapshot();+ expect(two.items.map(item => item.installState)).toEqual(['installed', 'installed']);+ expect(h.ledger.installationForGhost(second.ghostId)?.rawManifestSha256).toBeUndefined();+ expect(runtime.listScans).toBe(singleScans);+ });++ // A microtask-only refresh starved main's native message pump. This unit+ // checks an event-loop turn between scans without timing assertions or sleep.+ it('lets a queued event run between market reconciliation scans', async () => {+ const h = harness([]);+ let eventRan = false;+ let eventBeforeNextScan = false;+ let queued: ReturnType<typeof setImmediate> | undefined;+ runtime.onList = () => {+ if (runtime.listScans === 1) queued = setImmediate(() => { eventRan = true; });+ if (runtime.listScans === 2) eventBeforeNextScan = eventRan;+ };+ try {+ expect((await h.service.snapshot()).items).toEqual([]);+ expect(eventBeforeNextScan).toBe(true);+ } finally {+ if (queued) clearImmediate(queued);+ }+ });+it('backfills a pre-digest server record only from matching modern receipt evidence', async () => {const rawManifest = manifest();const bytes = Buffer.from(`${JSON.stringify(rawManifest, null, 2)}\n`);@@ -4971,6 +5019,36 @@ function installRuntimeGhost(}describe('organization default Plugin takeover', () => {+ // Regression: an unresolved namespace repeatedly failed default installation+ // and restarted the full startup sync every minute. Existing migration tests+ // cover successful stamps, not this persistent wait (unit).+ it('waits for namespace migration without downloading or reporting a startup failure', async () => {+ setCurrentOrganization();+ const item = organizationDefaultSummary({ namespace: 'acme' });+ const dir = installRuntimeGhost(manifest(item.ghostId));+ runtime.ghosts[0]!.namespaceState = 'pending';+ const h = harness([item]);+ const onDefaultReconciliationOutcome = vi.fn();+ runtime.install.mockRejectedValue(new Error('[PRECONDITION_FAILED] namespace migration is pending'));+ for (let i = 0; i < 2; i++) {+ await h.service.snapshot({ onDefaultReconciliationOutcome });+ }+ expect(onDefaultReconciliationOutcome.mock.calls).toEqual([['completed'], ['completed']]);+ expect(h.api.download).not.toHaveBeenCalled();+ expect(h.api.detail).not.toHaveBeenCalled();+ expect(runtime.ghosts[0]?.enabled).toBe(true);++ // No persistent suppression: a later successful migration is visible.+ delete runtime.ghosts[0]!.namespaceState;+ runtime.ghosts[0]!.namespace = 'acme';+ h.ledger.upsertInstallation(recordForTest(item, {+ namespace: 'acme',+ rawManifestSha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(dir, 'ghost.json'))).digest('hex'),+ }));+ expect((await h.service.snapshot()).items[0]?.installState).toBe('installed');+ expect(runtime.reconcilePendingRootNamespaces).toHaveBeenCalledTimes(3);+ });+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],diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 8d507889dd..f0acc568ed 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -1,6 +1,7 @@import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';+import { setImmediate as yieldToEventLoop } from 'node:timers/promises';import {isValidPluginResourceId,@@ -240,15 +241,22 @@ function defaultInstallSubject(owner: ActiveAppSession): string {return subject;}-function installedGhostMatchingMarketPlugin(plugin: {- ghostId: string;- namespace?: string | null;-}): InstalledGhost | undefined {+async function yieldMarketReconciliation(owner: ActiveAppSession): Promise<void> {+ // Promise-only stages otherwise chain synchronous filesystem work in one+ // main-process turn. Let native input run between scans and recheck the owner.+ await yieldToEventLoop();+ requireSameMarketOwner(owner);+}++function installedGhostMatchingMarketPlugin(+ plugin: { ghostId: string; namespace?: string | null },+ ghosts: readonly InstalledGhost[] = getGhostManager().list(),+): InstalledGhost | undefined {if (!isValidGhostId(plugin.ghostId)) {- return getGhostManager().list().find((ghost) => ghost.manifest.id === plugin.ghostId);+ return ghosts.find((ghost) => ghost.manifest.id === plugin.ghostId);}return findInstalledGhostByIdentity(- getGhostManager().list(),+ ghosts,createPluginLogicalIdentity(hasDeliveryNamespace(plugin) ? plugin.namespace : null,plugin.ghostId,@@ -511,8 +519,11 @@ function ghostIdCounts(plugins: readonly VisiblePluginSummary[]): Map<string, nureturn counts;}-function isGhostBusy(plugin: { ghostId: string; namespace?: string | null }): boolean {- const ghost = installedGhostMatchingMarketPlugin(plugin);+function isGhostBusy(+ plugin: { ghostId: string; namespace?: string | null },+ ghosts?: readonly InstalledGhost[],+): boolean {+ const ghost = installedGhostMatchingMarketPlugin(plugin, ghosts);const runtimeId = ghost ? installedGhostStoragePart(ghost) : plugin.ghostId;return (hasPendingGhostCalls(runtimeId) ||@@ -1027,7 +1038,10 @@ export class PluginMarketService {options.onDefaultReconciliationOutcome?.(outcome);return outcome;};- if (!options.discoveryOnly && !options.deferReconciliation) await reconcileCustomUpdates();+ if (!options.discoveryOnly && !options.deferReconciliation) {+ await reconcileCustomUpdates();+ await yieldMarketReconciliation(owner);+ }requireSameMarketOwner(owner);if (!options.discoveryOnly) {getGhostManager().resumePendingResidentsOffline?.();@@ -1092,8 +1106,11 @@ export class PluginMarketService {if (!options.discoveryOnly) {this.rememberCurrentOrganization(currentOrganization);await this.backfillInstalledManifestIdentities(ledger, owner);+ await yieldMarketReconciliation(owner);await this.adoptLegacyInstallations(plugins, ledger, owner);+ await yieldMarketReconciliation(owner);await this.recoverDisconnectedMarketInstallations(plugins, ledger, owner);+ await yieldMarketReconciliation(owner);ledger.backfillMissingNamespacesFromCatalog(plugins);try {await getGhostManager().reconcilePendingRootNamespaces?.(true);@@ -1102,6 +1119,7 @@ export class PluginMarketService {error: error instanceof Error ? error.message : String(error),});}+ await yieldMarketReconciliation(owner);// Only an exact delivered release proves a legacy installation's reporting endpoint.if (catalogServerRoot === getClientEndpoint('pluginApiBaseUrl').replace(/\/+$/, '')) {let rebound = false;@@ -1125,7 +1143,9 @@ export class PluginMarketService {}if (rebound) await refreshPluginUsageBindings();}+ await yieldMarketReconciliation(owner);await this.backfillOfficialCindyGithubTrust(ledger, owner);+ await yieldMarketReconciliation(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// explicit uninstall may turn that absence into installed=false/opt-out.@@ -1139,6 +1159,7 @@ export class PluginMarketService {// 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。// 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。let completed = true;+ await yieldMarketReconciliation(owner);try {if (!(await this.applyDefaultInstalls(plugins, currentOrganization, owner, ledger))) {completed = false;@@ -1149,6 +1170,7 @@ export class PluginMarketService {error: error instanceof Error ? error.message : String(error),});}+ await yieldMarketReconciliation(owner);try {if (!(await this.applyAutomaticUpgrades(plugins, customDiscovery.entries, owner, ledger))) {completed = false;@@ -1163,7 +1185,10 @@ export class PluginMarketService {options.onDefaultReconciliationOutcome?.(outcome);return outcome;};- if (!options.discoveryOnly && !options.deferReconciliation) await reconcileMarketInstallations();+ if (!options.discoveryOnly && !options.deferReconciliation) {+ await reconcileMarketInstallations();+ await yieldMarketReconciliation(owner);+ }requireSameMarketOwner(owner);const local = this.localInstallSnapshot(ledger);const serverItems = plugins.map((plugin) => this.toItem(plugin, local));@@ -2647,61 +2672,22 @@ export class PluginMarketService {const candidates = Object.values(ledger.read().installations).filter((record) => record.installed && record.rawManifestSha256 === undefined,);+ if (candidates.length === 0) return;+ const ghosts = getGhostManager().list();for (const candidate of candidates) {+ await yieldMarketReconciliation(owner);+ // Reject unchanged, ineligible records using one scan for the whole pass.+ // A candidate that can write is checked again after acquiring the locks.+ if (!this.manifestIdentityForBackfill(candidate, installedGhostMatchingMarketPlugin(candidate, ghosts))) continue;await this.withMutation(candidate.pluginId, () =>withGhostInstallLock(candidate.ghostId, async () => {requireSameMarketOwner(owner);const record = ledger.installationForPlugin(candidate);if (!record?.installed || record.rawManifestSha256 !== undefined) return;const installed = installedGhostMatchingMarketPlugin(record);- if (!installed) return;- const identity = readInstalledMarketManifestIdentity(installed.dir);+ const identity = this.manifestIdentityForBackfill(record, installed);if (!identity) return;- const isServerRecord = record.source === 'market' || record.source === 'legacy-adopted';- const manager = getGhostManager();- 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;- // An approved server state with no readable evidence can also be a- // pending mutation journal. Only genuine legacy-unapproved installs- // may use the legacy digest without receipt evidence.- if (isServerRecord && installed.approval.state === 'approved' && !approvalEvidence) {- return;- }- const approvedManifestMatches = Boolean(- approvalEvidence &&- installedIdentityMatchesManifest(identity, approvalEvidence.approvedManifest),- );- if (- isServerRecord &&- approvalEvidence &&- !approvedManifestMatches- ) {- return;- }- if (- isServerRecord &&- approvalEvidence?.packageSha256 !== null &&- approvalEvidence?.packageSha256 !== undefined &&- approvalEvidence.packageSha256 !== record.sha256- ) {- return;- }- if (isServerRecord && approvalEvidence?.packageSha256 === null) {- if (!approvalEvidence.legacyMigrated) return;- }- const legacyDigestMatches = legacyManifestIdentityMatches(record, identity);- const strongReceiptCanFillMissingLegacyDigest = Boolean(- isServerRecord &&- record.manifestDigest === undefined &&- approvalEvidence &&- approvalEvidence.packageSha256 === record.sha256 &&- approvedManifestMatches,- );- if (!legacyDigestMatches && !strongReceiptCanFillMissingLegacyDigest) return;-const backfilled = await this.withLedgerMutation(owner, () =>ledger.backfillRawManifestSha256(record, identity.rawManifestSha256),);@@ -2717,6 +2703,34 @@ export class PluginMarketService {}}+ private manifestIdentityForBackfill(+ record: PluginMarketInstallationRecord,+ installed: InstalledGhost | undefined,+ ): InstalledMarketManifestIdentity | null {+ if (!installed || installed.approval.state === 'invalid') return null;+ const identity = readInstalledMarketManifestIdentity(installed.dir);+ if (!identity) return null;+ const isServerRecord = record.source === 'market' || record.source === 'legacy-adopted';+ const approvalEvidence = getGhostManager().approvedInstallEvidence?.(installedGhostPhysicalRelId(installed)) ?? null;+ // Unavailable approval evidence may be an unfinished mutation. Only genuine+ // legacy-unapproved installs can use the legacy digest without a receipt.+ if (isServerRecord && installed.approval.state === 'approved' && !approvalEvidence) return null;+ const approvedManifestMatches = Boolean(+ approvalEvidence && installedIdentityMatchesManifest(identity, approvalEvidence.approvedManifest),+ );+ if (isServerRecord && approvalEvidence) {+ if (!approvedManifestMatches) return null;+ if (approvalEvidence.packageSha256 !== null && approvalEvidence.packageSha256 !== record.sha256) return null;+ if (approvalEvidence.packageSha256 === null && !approvalEvidence.legacyMigrated) return null;+ }+ const legacyDigestMatches = legacyManifestIdentityMatches(record, identity);+ const strongReceiptCanFillMissingLegacyDigest = Boolean(+ isServerRecord && record.manifestDigest === undefined && approvalEvidence &&+ approvalEvidence.packageSha256 === record.sha256 && approvedManifestMatches,+ );+ return legacyDigestMatches || strongReceiptCanFillMissingLegacyDigest ? identity : null;+ }+private async adoptLegacyInstallations(plugins: readonly VisiblePluginSummary[],ledger: PluginMarketLedger,@@ -3180,6 +3194,12 @@ export class PluginMarketService {if (target.namespace == null && isBuiltinGhostRemovedByUser(summary.ghostId)) continue;const state = this.toItem(summary, local).installState;if (state !== 'not-installed' && state !== 'conflict') continue;+ // Migration runs before this pass. A still-pending bare instance blocks+ // placement; downloading it again cannot resolve the missing identity.+ // Leave it to migration / the next normal sync, not startup's fast retry.+ if (local.ghostsById.get(summary.ghostId)?.some((ghost) =>+ ghost.namespaceState === 'pending' && installedGhostPhysicalRelId(ghost) === summary.ghostId,+ )) continue;const takeoverRetryKey = this.automaticUpgradeRetryKey(owner,'organization-default',@@ -3188,7 +3208,7 @@ export class PluginMarketService {const releaseKey = summary.currentRelease.id;if (state === 'conflict' &&- (isGhostBusy(target) ||+ (isGhostBusy(target, local.ghosts) ||this.shouldDeferAutomaticUpgrade(takeoverRetryKey, releaseKey))) {continue;@@ -3229,7 +3249,7 @@ export class PluginMarketService {freshLedgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id),),builtinRemoved: isBuiltinGhostRemovedByUser(summary.ghostId),- busy: isGhostBusy(freshSummary),+ busy: isGhostBusy(freshSummary, freshLocal.ghosts),});if (!eligibility.eligible) {if (eligibility.reason === 'busy') {@@ -3302,7 +3322,7 @@ export class PluginMarketService {runtimeAvailable: isGhostAvailableForActiveSession(summary.ghostId),optedOut: false,builtinRemoved: isBuiltinGhostRemovedByUser(summary.ghostId),- busy: isGhostBusy(commitSummary),+ busy: isGhostBusy(commitSummary, commitLocal.ghosts),});if (!eligibility.eligible) {if (eligibility.reason === 'busy') {@@ -3376,7 +3396,7 @@ export class PluginMarketService {if ((record?.source !== 'market' && record?.source !== 'legacy-adopted') ||installState !== 'update-available' ||- isGhostBusy(target) ||+ isGhostBusy(target, local.ghosts) ||this.shouldDeferAutomaticUpgrade(retryKey, releaseKey) ||this.isAutomaticUpgradeHeldForConsent(retryKey, releaseKey, releaseKey)) {@@ -3385,11 +3405,11 @@ export class PluginMarketService {try {await this.withMutation(summary.id, async () => {requireSameMarketOwner(owner);- if (isGhostBusy(target)) {- throw new SilentUpgradeBusyError('Plugin is busy');- }const freshLocal = this.localInstallSnapshot(ledger);const fresh = this.serverMarketBinding(summary, freshLocal);+ if (isGhostBusy(fresh.target, freshLocal.ghosts)) {+ throw new SilentUpgradeBusyError('Plugin is busy');+ }if ((fresh.record?.source !== 'market' && fresh.record?.source !== 'legacy-adopted') ||fresh.installState !== 'update-available'@@ -3472,7 +3492,7 @@ export class PluginMarketService {const installed = snapshotGhost(local, projected);if (projected.installState !== 'update-available' ||- isGhostBusy(projected) ||+ isGhostBusy(projected, local.ghosts) ||installed?.approval.state !== 'approved' ||this.shouldDeferAutomaticUpgrade(retryKey, releaseKey) ||this.isAutomaticUpgradeHeldForConsent(retryKey, releaseKey, contentKey)diff --git a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.tsindex 3061d67478..b1a73e53b2 100644--- a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts@@ -63,10 +63,49 @@ describe('Skill activation preferences', () => {const descriptors = (await import('../../maker-host/built-in-skills')).builtInSkillDescriptors(root, root);const learn = descriptors.find((descriptor) => descriptor.name === 'learn')!;expect(prefs.isCindyLearnSkillEnabled()).toBe(true);+ expect(prefs.isCindyLearnSkillEnabledForCommandListing()).toBe(true);await prefs.setCindySkillEnabled(learn.absolutePath, false);expect(prefs.isCindyLearnSkillEnabled()).toBe(false);+ expect(prefs.isCindyLearnSkillEnabledForCommandListing()).toBe(false);await prefs.setCindySkillEnabled(learn.absolutePath, true);expect(prefs.isCindyLearnSkillEnabled()).toBe(true);+ expect(prefs.isCindyLearnSkillEnabledForCommandListing()).toBe(true);+ });+ // Unit regression: the command listing must follow the current Learn toggle.+ // Existing toggle coverage had no historical profile key alongside shared Learn.+ it('shows reenabled shared Learn despite a historical profile disable', async () => {+ const prefs = await import('../activationPreferences');+ const descriptors = (await import('../../maker-host/built-in-skills')).builtInSkillDescriptors(root, root);+ const learn = descriptors.find((descriptor) => descriptor.name === 'learn')!;+ const historical = path.join(root, 'system-skills', 'learn');+ try {+ await prefs.setCindySkillEnabled(historical, false);+ await prefs.setCindySkillEnabled(learn.absolutePath, false);+ expect(prefs.isCindyLearnSkillEnabledForCommandListing()).toBe(false);+ await prefs.setCindySkillEnabled(learn.absolutePath, true);+ expect(prefs.isCindyLearnSkillEnabled()).toBe(true);+ expect(prefs.isCindyLearnSkillEnabledForCommandListing()).toBe(true);+ expect(prefs.isCindySkillEnabled(historical)).toBe(false);+ } finally {+ await prefs.setCindySkillEnabled(historical, true);+ await prefs.setCindySkillEnabled(learn.absolutePath, true);+ }+ });+ // Unit: listing is a preference projection; only execution checks Skill bytes.+ // The toggle-only cases cannot distinguish this from a full integrity scan.+ it('defers built-in Learn validity checks until execution', async () => {+ const prefs = await import('../activationPreferences');+ const descriptors = (await import('../../maker-host/built-in-skills')).builtInSkillDescriptors(root, root);+ const learn = descriptors.find((descriptor) => descriptor.name === 'learn')!;+ const skillFile = path.join(learn.absolutePath, 'SKILL.md');+ const original = fs.readFileSync(skillFile);+ try {+ fs.writeFileSync(skillFile, '# Changed Learn\n');+ expect(prefs.isCindyLearnSkillEnabledForCommandListing()).toBe(true);+ expect(prefs.isCindyLearnSkillEnabled()).toBe(false);+ } finally {+ fs.writeFileSync(skillFile, original);+ }});it('keeps built-in activation intent across immutable bundle revisions', async () => {const prefs = await import('../activationPreferences');diff --git a/apps/desktop/src/main/skillhub/activationPreferences.ts b/apps/desktop/src/main/skillhub/activationPreferences.tsindex 3b6bad9100..e70ae30c77 100644--- a/apps/desktop/src/main/skillhub/activationPreferences.ts+++ b/apps/desktop/src/main/skillhub/activationPreferences.ts@@ -110,6 +110,14 @@ export function isCindyLearnSkillEnabled(): boolean {return descriptor ? isCindySkillEnabled(descriptor.absolutePath) : false;}+/** Listing reads user intent; execution checks the current Skill's integrity. */+export function isCindyLearnSkillEnabledForCommandListing(): boolean {+ // Use the same active path as execution, without enumerating or hashing files.+ // A retired profile copy must not veto an explicitly reenabled shared copy.+ const source = path.join(sharedBuiltInSkillsRoot(app.getPath('appData')), '.active', BUILT_IN_LEARN_SKILL_NAME);+ return !readDisabledSkillPathsForListing().includes(skillActivationKey(source));+}+export interface SkillActivationSnapshot { key: string; revision?: string; aliases: string[] }export function snapshotSkillActivation(source: string): SkillActivationSnapshot | null {