Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(skillhub): preserve catalog scope boundaries (#3826)
bobo2779e9999d4c
diff --git a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts b/apps/desktop/src/main/learn-host/__tests__/controller.test.tsindex a847861975..37e11e9d08 100644--- a/apps/desktop/src/main/learn-host/__tests__/controller.test.ts+++ b/apps/desktop/src/main/learn-host/__tests__/controller.test.ts@@ -1350,12 +1350,13 @@ describe('LearnController 状态机', () => {it('Claude-only 本地 skill 也算已装:注入原文、diff 有基线、标记 personal', async () => {const claudeDir = path.join('/', 'claude', 'skills', 'my-skill');let diffOldDir: string | null | undefined;+ const fetchHubSkill = vi.fn(async () => ({+ name: 'my-skill',+ description: 'upstream',+ content: '# upstream skill',+ }));const h = makeHarness({- fetchHubSkill: async () => ({- name: 'my-skill',- description: 'upstream',- content: '# upstream skill',- }),+ fetchHubSkill,search: async () => ({ hits: [], sessions: {}, nextCursor: null, vectorUsed: false }) as never,collectProfile: async () => ({ block: '', used: false }),resolveInstalledSkillDirs: (name) => [path.join('/', 'installed', name), path.join('/', 'claude', 'skills', name)],@@ -1369,6 +1370,8 @@ describe('LearnController 状态机', () => {h.setScan(goodScan());const { runId } = await h.controller.startLearn({ input: '', sourceKind: 'hub', hubSlug: 'my-skill' });await h.waitForStatus(runId, 'distilling');+ expect(fetchHubSkill).toHaveBeenCalledWith('my-skill', 'market');+ expect(h.store.get(runId)?.hubCatalogScope).toBe('market');expect(h.session.sent[0]).toContain('# local Claude skill');expect(h.store.get(runId)!.usedSessionEvidence).toBe(true);diff --git a/apps/desktop/src/main/learn-host/controller.ts b/apps/desktop/src/main/learn-host/controller.tsindex 95d54784c8..c1de599f6f 100644--- a/apps/desktop/src/main/learn-host/controller.ts+++ b/apps/desktop/src/main/learn-host/controller.ts@@ -364,7 +364,7 @@ export class LearnController {...(dataOwnerId ? { dataOwnerId } : {}),input,...(req.hubSlug ? { hubSlug: req.hubSlug } : {}),- ...(req.hubCatalogScope ? { hubCatalogScope: req.hubCatalogScope } : {}),+ ...(req.sourceKind === 'hub' ? { hubCatalogScope: req.hubCatalogScope ?? 'market' } : {}),...(req.originSessionId ? { originSessionId: req.originSessionId } : {}),usedSessionEvidence: false,createdAt: this.now(),@@ -397,7 +397,7 @@ export class LearnController {let referenceFilesOmissions: Array<{ path: string; reason: string }> | undefined;let evidenceQuery = run.input;if (run.sourceKind === 'hub' && run.hubSlug && this.deps.fetchHubSkill) {- const hub = await this.deps.fetchHubSkill(run.hubSlug, run.hubCatalogScope);+ const hub = await this.deps.fetchHubSkill(run.hubSlug, run.hubCatalogScope ?? 'market');if (!hub) throw new LearnError('NOT_FOUND', `hub skill ${run.hubSlug} not found`);// fetch 的网络 await 期间可能被 cancel(cleanup 已删 staging):此处不设门// 的话 writeReferenceFiles 会把 _reference/ 整个重建成孤儿目录(自查)。@@ -520,7 +520,7 @@ export class LearnController {const cleanMessage =run.sourceKind === 'hub'- ? `/learn hub:${run.hubCatalogScope ? `${run.hubCatalogScope}:` : ''}${run.hubSlug}`+ ? `/learn hub:${run.hubCatalogScope ?? 'market'}:${run.hubSlug}`: run.sourceKind === 'session'? '/learn (distill current conversation)': `/learn ${run.input}`;@@ -964,7 +964,7 @@ export class LearnController {const provenance: LearnProvenance = {method: 'learn',sourceKind: run.sourceKind,- ...(run.hubSlug ? { sourceRef: `${run.hubCatalogScope ? `${run.hubCatalogScope}:` : ''}${run.hubSlug}` } : {}),+ ...(run.hubSlug ? { sourceRef: `${run.hubCatalogScope ?? 'market'}:${run.hubSlug}` } : {}),usedSessionEvidence: run.usedSessionEvidence,personal: run.usedSessionEvidence, // 硬规则:含 session 证据 ⇒ personal,不可配置learnedAt: Math.floor(this.now() / 1000),diff --git a/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts b/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.tsindex 9b485e2eac..6a14cac92f 100644--- a/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/autoSyncService.test.ts@@ -6,7 +6,7 @@ import { net } from 'electron';import { getCurrentUserId } from '../../authManager';import type { StoredInstall } from '../registry/types';import { registryService } from '../registry';-import { SkillhubAutoSyncService } from '../autoSyncService';+import { parseAutoSyncConfig, SkillhubAutoSyncService } from '../autoSyncService';import type { install as installFn } from '../installService';type InstallResult = Awaited<ReturnType<typeof installFn>>;@@ -82,18 +82,20 @@ function installEntry(version: string, overrides: Partial<StoredInstall> = {}):updatedAt: 1,origin: 'installed',autoSynced: true,+ catalogScope: 'market',+ catalogScopeMigrated: true,...overrides,};}function makeService(options: {userId?: string | null;- configSkills?: Array<string | { name: string; version?: string; enabled?: boolean }>;+ configSkills?: Array<string | { name: string; version?: string; enabled?: boolean; catalogScope?: 'market' | 'team' }>;installs?: Array<{ skillName: string; installPath: string; entry: StoredInstall }>;listAllInstallsImpl?: () => Promise<Array<{ skillName: string; installPath: string; entry: StoredInstall }>>;- fetchConfigImpl?: () => Promise<Array<{ name: string; version?: string; enabled?: boolean }>>;- syncResults?: Array<{ name: string; exists: boolean; latestVersion?: string }>;- syncResponses?: Array<{ success: boolean; results?: Array<{ name: string; exists: boolean; latestVersion?: string }>; error?: string }>;+ fetchConfigImpl?: () => Promise<Array<{ name: string; version?: string; enabled?: boolean; catalogScope?: 'market' | 'team' }>>;+ syncResults?: Array<{ name: string; exists: boolean; latestVersion?: string; catalogScope?: 'market' | 'team' }>;+ syncResponses?: Array<{ success: boolean; results?: Array<{ name: string; exists: boolean; latestVersion?: string; catalogScope?: 'market' | 'team' }>; error?: string }>;syncSuccess?: boolean;installImpl?: typeof installFn;installResults?: Array<SuccessfulInstallResult | FailedInstallResult>;@@ -248,8 +250,8 @@ describe('SkillhubAutoSyncService', () => {expect(listIgnoredSkills).toHaveBeenCalledTimes(2);expect(recordCandidateSkills).toHaveBeenCalledWith('user-1', ['alpha'], { replace: true });- expect(syncMarket).toHaveBeenCalledWith({ slugs: ['alpha'] });- expect(install).toHaveBeenCalledWith({ name: 'alpha', autoSync: true }, expect.any(Function));+ expect(syncMarket).toHaveBeenCalledWith({ skills: [{ slug: 'alpha', catalogScope: 'market' }] });+ expect(install).toHaveBeenCalledWith({ name: 'alpha', catalogScope: 'market', autoSync: true }, expect.any(Function));});it('continues with non-ignored skills when only part of the config is ignored', async () => {@@ -261,8 +263,8 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();- expect(syncMarket).toHaveBeenCalledWith({ slugs: ['beta'] });- expect(install).toHaveBeenCalledWith({ name: 'beta', autoSync: true }, expect.any(Function));+ expect(syncMarket).toHaveBeenCalledWith({ skills: [{ slug: 'beta', catalogScope: 'market' }] });+ expect(install).toHaveBeenCalledWith({ name: 'beta', catalogScope: 'market', autoSync: true }, expect.any(Function));});it('records empty fallback candidates without replacing previous remote candidates when the config fetch fails', async () => {@@ -310,7 +312,24 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();- expect(install).toHaveBeenCalledWith({ name: 'alpha', autoSync: true }, expect.any(Function));+ expect(install).toHaveBeenCalledWith({ name: 'alpha', catalogScope: 'market', autoSync: true }, expect.any(Function));+ });++ it('keeps the configured team catalog scope through sync and install', async () => {+ const { service, syncMarket, install } = makeService({+ configSkills: [{ name: 'alpha', catalogScope: 'team' }],+ syncResults: [{ name: 'alpha', catalogScope: 'team', exists: true, latestVersion: '1.2.3' }],+ });++ await service.runOnceAfterLogin();++ expect(syncMarket).toHaveBeenCalledWith({+ skills: [{ slug: 'alpha', catalogScope: 'team' }],+ });+ expect(install).toHaveBeenCalledWith(+ { name: 'alpha', catalogScope: 'team', autoSync: true },+ expect.any(Function),+ );});it('continues auto-sync after deleting a corrupt pending cleanup store', async () => {@@ -324,7 +343,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();- expect(install).toHaveBeenCalledWith({ name: 'alpha', autoSync: true }, expect.any(Function));+ expect(install).toHaveBeenCalledWith({ name: 'alpha', catalogScope: 'market', autoSync: true }, expect.any(Function));expect(fs.existsSync(storePath)).toBe(false);expect(loggerMocks.warn).toHaveBeenCalledWith('parse pending cancellation cleanup store failed',@@ -342,7 +361,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();- expect(install).toHaveBeenCalledWith({ name: 'alpha', autoSync: true }, expect.any(Function));+ expect(install).toHaveBeenCalledWith({ name: 'alpha', catalogScope: 'market', autoSync: true }, expect.any(Function));expect(loggerMocks.warn).toHaveBeenCalledWith('read pending cancellation cleanup store failed',{ error: expect.any(String) },@@ -477,7 +496,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledWith(- { name: 'alpha', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: false },+ { name: 'alpha', catalogScope: 'market', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: false },expect.any(Function),);});@@ -500,7 +519,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledWith(- { name: 'alpha', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: false },+ { name: 'alpha', catalogScope: 'market', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: false },expect.any(Function),);} finally {@@ -519,7 +538,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledWith(- { name: 'alpha', autoSync: true, version: '1.1.0' },+ { name: 'alpha', catalogScope: 'market', autoSync: true, version: '1.1.0' },expect.any(Function),);});@@ -552,7 +571,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledWith(- { name: 'alpha', autoSync: true, installPath, version: '1.1.0', force: true, skipBackup: false },+ { name: 'alpha', catalogScope: 'market', autoSync: true, installPath, version: '1.1.0', force: true, skipBackup: false },expect.any(Function),);});@@ -611,7 +630,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();- expect(install).toHaveBeenCalledWith({ name: 'alpha', autoSync: true }, expect.any(Function));+ expect(install).toHaveBeenCalledWith({ name: 'alpha', catalogScope: 'market', autoSync: true }, expect.any(Function));expect(loggerMocks.warn).toHaveBeenCalledWith('user-owned global skill registry entry is missing on disk',{ slug: 'alpha', origin: 'published', installPath },@@ -681,7 +700,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledWith(- { name: 'alpha', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: false },+ { name: 'alpha', catalogScope: 'market', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: false },expect.any(Function),);});@@ -716,7 +735,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();- expect(install).toHaveBeenCalledWith({ name: 'alpha', autoSync: true }, expect.any(Function));+ expect(install).toHaveBeenCalledWith({ name: 'alpha', catalogScope: 'market', autoSync: true }, expect.any(Function));});it('skips a whitelisted skill when the local version already matches SkillHub', async () => {@@ -749,7 +768,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledWith(- { name: 'alpha', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: true },+ { name: 'alpha', catalogScope: 'market', autoSync: true, installPath, version: '1.2.3', force: true, skipBackup: true },expect.any(Function),);expect(loggerMocks.warn).toHaveBeenCalledWith(@@ -804,8 +823,8 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledTimes(2);- expect(install).toHaveBeenNthCalledWith(1, { name: 'alpha', autoSync: true }, expect.any(Function));- expect(install).toHaveBeenNthCalledWith(2, { name: 'beta', autoSync: true }, expect.any(Function));+ expect(install).toHaveBeenNthCalledWith(1, { name: 'alpha', catalogScope: 'market', autoSync: true }, expect.any(Function));+ expect(install).toHaveBeenNthCalledWith(2, { name: 'beta', catalogScope: 'market', autoSync: true }, expect.any(Function));expect(loggerMocks.warn).toHaveBeenCalledWith('auto install/update failed',{ slug: 'alpha', version: '1.0.0', errorCode: 'INTERNAL', message: 'boom' },@@ -1142,7 +1161,7 @@ describe('SkillhubAutoSyncService', () => {await service.runOnceAfterLogin();expect(install).toHaveBeenCalledWith(- { name: 'alpha', autoSync: true, installPath, version: '2.0.0', force: true, skipBackup: false },+ { name: 'alpha', catalogScope: 'market', autoSync: true, installPath, version: '2.0.0', force: true, skipBackup: false },expect.any(Function),);expect(cleanupInstall).toHaveBeenCalledWith({@@ -1218,3 +1237,32 @@ describe('SkillhubAutoSyncService', () => {expect(install).toHaveBeenCalledTimes(2);});});++describe('parseAutoSyncConfig', () => {+ it('preserves explicit catalog scopes and defaults legacy string entries to market', () => {+ expect(parseAutoSyncConfig({ skills: [+ 'public-skill',+ { slug: 'team-skill', catalogScope: 'team' },+ { name: 'scope-alias', scope: 'market' },+ ] })).toEqual([+ { name: 'public-skill', catalogScope: 'market' },+ { name: 'team-skill', catalogScope: 'team' },+ { name: 'scope-alias', catalogScope: 'market' },+ ]);+ });++ it('rejects entries with an invalid explicit catalog scope', () => {+ expect(parseAutoSyncConfig({ skills: [+ { slug: 'wrong-scope', catalogScope: 'native' },+ ] })).toEqual([]);+ });++ it('uses the first catalog scope when config repeats a slug for the single global install slot', () => {+ expect(parseAutoSyncConfig({ skills: [+ { slug: 'shared-name', catalogScope: 'team' },+ { slug: 'shared-name', catalogScope: 'market' },+ ] })).toEqual([+ { name: 'shared-name', catalogScope: 'team' },+ ]);+ });+});diff --git a/apps/desktop/src/main/skillhub/__tests__/identityPolicy.test.ts b/apps/desktop/src/main/skillhub/__tests__/identityPolicy.test.tsnew file mode 100644index 0000000000..7947872cf5--- /dev/null+++ b/apps/desktop/src/main/skillhub/__tests__/identityPolicy.test.ts@@ -0,0 +1,51 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({ boundaryPending: false, user: null as unknown }));++vi.mock('../../appSessionState.js', () => ({+ isAppSessionBoundaryPending: () => state.boundaryPending,+}));++vi.mock('../../authManager', () => ({+ getAuthState: () => ({ user: state.user }),+}));++vi.mock('../../serverApiClient', () => ({+ ServerApiError: class ServerApiError extends Error {+ constructor(+ public readonly code: string,+ public readonly statusCode: number,+ message: string,+ ) {+ super(message);+ }+ },+}));++describe('SkillHub identity write policy', () => {+ beforeEach(() => {+ state.boundaryPending = false;+ state.user = { membershipKind: 'personal' };+ vi.resetModules();+ });++ it('fails closed while the application session owner boundary is pending', async () => {+ state.boundaryPending = true;+ const { assertSkillhubVisibilityAllowed, assertSkillhubWriteAllowed } = await import('../identityPolicy');++ expect(() => assertSkillhubWriteAllowed()).toThrow(expect.objectContaining({+ code: 'PRECONDITION_FAILED',+ statusCode: 409,+ }));+ expect(() => assertSkillhubVisibilityAllowed('public')).toThrow(expect.objectContaining({+ code: 'PRECONDITION_FAILED',+ statusCode: 409,+ }));+ });++ it('allows a stable signed-in personal session', async () => {+ const { assertSkillhubWriteAllowed } = await import('../identityPolicy');++ expect(() => assertSkillhubWriteAllowed()).not.toThrow();+ });+});diff --git a/apps/desktop/src/main/skillhub/__tests__/marketService.test.ts b/apps/desktop/src/main/skillhub/__tests__/marketService.test.tsindex 0c95073c54..38299db443 100644--- a/apps/desktop/src/main/skillhub/__tests__/marketService.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/marketService.test.ts@@ -305,13 +305,13 @@ describe('SkillhubMarketService', () => {updateRegistryCatalogScope,});- await service.setPublishedVisibility({ name: 'demo', visibility: 'shared' });- await service.setPublishedVisibility({ name: 'demo', visibility: 'private' });+ await service.setPublishedVisibility({ name: 'demo', visibility: 'shared', previousCatalogScope: 'market' });+ await service.setPublishedVisibility({ name: 'demo', visibility: 'private', previousCatalogScope: 'team' });await service.setPublishedVisibility({ name: 'demo', visibility: 'public' });- expect(updateRegistryCatalogScope).toHaveBeenNthCalledWith(1, 'demo', 'team');- expect(updateRegistryCatalogScope).toHaveBeenNthCalledWith(2, 'demo', undefined);- expect(updateRegistryCatalogScope).toHaveBeenNthCalledWith(3, 'demo', undefined);+ expect(updateRegistryCatalogScope).toHaveBeenNthCalledWith(1, 'demo', 'team', 'market');+ expect(updateRegistryCatalogScope).toHaveBeenNthCalledWith(2, 'demo', undefined, 'team');+ expect(updateRegistryCatalogScope).toHaveBeenNthCalledWith(3, 'demo', undefined, undefined);});it('maps categories and user departments into renderer result shapes', async () => {diff --git a/apps/desktop/src/main/skillhub/autoSyncService.ts b/apps/desktop/src/main/skillhub/autoSyncService.tsindex 2b6f6dbd4b..9384deb9fd 100644--- a/apps/desktop/src/main/skillhub/autoSyncService.ts+++ b/apps/desktop/src/main/skillhub/autoSyncService.ts@@ -17,6 +17,7 @@ import { SkillhubMarketService } from './marketService';import { listIgnoredAutoSyncSkills, recordAutoSyncCandidateSkills } from './autoSyncPreferences';import { registryService } from './registry';import type { StoredInstall } from './registry/types';+import { skillhubCatalogKey, type SkillhubCatalogScope } from '../../shared/skillhubCatalog';const log = createLogger('skillhub:autoSync');@@ -44,11 +45,14 @@ interface SyncResultItem {name: string;exists: boolean;latestVersion?: string;+ catalogScope?: SkillhubCatalogScope;}interface AutoSyncSkill {name: string;version?: string;+ /** Product config must identify the catalog that owns this slug. */+ catalogScope?: SkillhubCatalogScope;}interface AutoSyncConfigResult {@@ -60,7 +64,9 @@ interface AutoSyncDeps {getCurrentUserId: () => string | null;fetchConfig: () => Promise<AutoSyncSkill[] | AutoSyncConfigResult>;listAllInstalls: () => Promise<ListedInstall[]>;- syncMarket: (params: { slugs?: string[] }) => Promise<{ success: boolean; results?: SyncResultItem[]; error?: string }>;+ syncMarket: (params: {+ skills?: Array<{ slug: string; catalogScope: SkillhubCatalogScope }>;+ }) => Promise<{ success: boolean; results?: SyncResultItem[]; error?: string }>;detectClaudeSkillConflict: (slug: string, expectedSharedPath: string) => Promise<ClaudeSkillConflict | null>;install: InstallFn;cancelInstall: (name: string) => boolean;@@ -183,7 +189,11 @@ export class SkillhubAutoSyncService {return false;});if (enabledSkills.length === 0) return;- const slugs = enabledSkills.map((skill) => skill.name);+ const refs = enabledSkills.map((skill) => ({+ slug: skill.name,+ catalogScope: skill.catalogScope ?? ('market' as const),+ }));+ const slugs = refs.map(({ slug }) => slug);const localInstalls = await this.deps.listAllInstalls().catch((err) => {log.warn('list local installs failed', {@@ -192,10 +202,10 @@ export class SkillhubAutoSyncService {throw err;});const autoSyncSlugs = new Set(slugs);- const relevantInstalls = buildRelevantInstallMap(localInstalls, autoSyncSlugs);+ const relevantInstalls = buildRelevantInstallMap(localInstalls, refs, autoSyncSlugs);const blockedGlobalInstalls = buildBlockedGlobalInstallMap(localInstalls, autoSyncSlugs);- const sync = await this.deps.syncMarket({ slugs }).catch((err) => {+ const sync = await this.deps.syncMarket({ skills: refs }).catch((err) => {log.warn('market sync failed', {error: err instanceof Error ? err.message : String(err),});@@ -208,11 +218,15 @@ export class SkillhubAutoSyncService {this.assertAuthUnchanged();- const marketByName = new Map((sync.results ?? []).map((item) => [item.name, item]));+ const marketByName = new Map((sync.results ?? []).map((item) => [+ skillhubCatalogKey(item.name, item.catalogScope ?? 'market'),+ item,+ ]));const failedSlugs: string[] = [];for (const skill of enabledSkills) {const slug = skill.name;- const local = relevantInstalls.get(slug);+ const catalogScope = skill.catalogScope ?? 'market';+ const local = relevantInstalls.get(skillhubCatalogKey(slug, catalogScope));let localInstallPathExists = false;if (!local) {const blocked = blockedGlobalInstalls.get(slug);@@ -235,7 +249,7 @@ export class SkillhubAutoSyncService {localInstallPathExists = await this.deps.pathExists(local.installPath);}- const market = marketByName.get(slug);+ const market = marketByName.get(skillhubCatalogKey(slug, catalogScope));const targetVersion = skill.version ?? market?.latestVersion;if (!market?.exists || !targetVersion) {log.warn('whitelisted skill is unavailable in SkillHub', { slug });@@ -267,13 +281,14 @@ export class SkillhubAutoSyncService {const params: installService.InstallParams = local? {name: slug,+ catalogScope,autoSync: true,installPath: local.installPath,version: targetVersion,force: true,skipBackup: !localInstallPathExists,}- : { name: slug, autoSync: true, ...(skill.version ? { version: targetVersion } : {}) };+ : { name: slug, catalogScope, autoSync: true, ...(skill.version ? { version: targetVersion } : {}) };const previousInstall = local && localInstallPathExists ? local : undefined;this.assertAuthUnchanged();@@ -475,7 +490,7 @@ export class SkillhubAutoSyncService {export const skillhubAutoSyncService = new SkillhubAutoSyncService();function defaultAutoSyncSkills(): AutoSyncSkill[] {- return DEFAULT_SKILLHUB_AUTO_SYNC_SLUGS.map((name) => ({ name }));+ return DEFAULT_SKILLHUB_AUTO_SYNC_SLUGS.map((name) => ({ name, catalogScope: 'market' }));}async function pathExists(p: string): Promise<boolean> {@@ -626,7 +641,7 @@ function parseListedInstall(value: unknown): ListedInstall | undefined {};}-function parseAutoSyncConfig(value: unknown): AutoSyncSkill[] | null {+export function parseAutoSyncConfig(value: unknown): AutoSyncSkill[] | null {if (!value || typeof value !== 'object') return null;const rawSkills = (value as { skills?: unknown }).skills;if (!Array.isArray(rawSkills)) return null;@@ -635,7 +650,12 @@ function parseAutoSyncConfig(value: unknown): AutoSyncSkill[] | null {const skills: AutoSyncSkill[] = [];for (const raw of rawSkills) {const skill = parseAutoSyncSkill(raw);- if (!skill || seen.has(skill.name)) continue;+ if (!skill) continue;+ // Global discovery has exactly one ~/.agents/skills/<slug> slot. Preserve+ // the historical first-entry-wins behavior when a remote config repeats a+ // slug with different catalog scopes instead of scheduling two installs+ // that would target the same directory.+ if (seen.has(skill.name)) continue;seen.add(skill.name);skills.push(skill);}@@ -645,15 +665,25 @@ function parseAutoSyncConfig(value: unknown): AutoSyncSkill[] | null {function parseAutoSyncSkill(value: unknown): AutoSyncSkill | null {if (typeof value === 'string') {const name = normalizeSkillName(value);- return name ? { name } : null;+ return name ? { name, catalogScope: 'market' } : null;}if (!value || typeof value !== 'object') return null;- const obj = value as { name?: unknown; slug?: unknown; enabled?: unknown; version?: unknown };+ const obj = value as {+ name?: unknown;+ slug?: unknown;+ enabled?: unknown;+ version?: unknown;+ catalogScope?: unknown;+ scope?: unknown;+ };if (obj.enabled === false) return null;const name = normalizeSkillName(obj.name ?? obj.slug);if (!name) return null;const version = typeof obj.version === 'string' && obj.version.trim() ? obj.version.trim() : undefined;- return { name, ...(version ? { version } : {}) };+ const rawScope = obj.catalogScope ?? obj.scope;+ if (rawScope !== undefined && rawScope !== 'team' && rawScope !== 'market') return null;+ const catalogScope = rawScope === 'team' || rawScope === 'market' ? rawScope : 'market';+ return { name, catalogScope, ...(version ? { version } : {}) };}function normalizeSkillName(value: unknown): string | null {@@ -662,14 +692,21 @@ function normalizeSkillName(value: unknown): string | null {return name ? name : null;}-function buildRelevantInstallMap(installs: ListedInstall[], autoSyncSlugs: Set<string>): Map<string, ListedInstall> {+function buildRelevantInstallMap(+ installs: ListedInstall[],+ refs: Array<{ slug: string; catalogScope: SkillhubCatalogScope }>,+ autoSyncSlugs: Set<string>,+): Map<string, ListedInstall> {const result = new Map<string, ListedInstall>();const globalRoot = path.join(os.homedir(), '.agents', 'skills');+ const configuredKeys = new Set(refs.map(({ slug, catalogScope }) => skillhubCatalogKey(slug, catalogScope)));for (const install of installs) {if (!isAutoSyncedGlobalInstall(install, autoSyncSlugs)) continue;if (!isGlobalSkillInstall(globalRoot, install)) continue;- if (!result.has(install.skillName)) result.set(install.skillName, install);+ const key = skillhubCatalogKey(install.skillName, install.entry.catalogScope);+ if (!configuredKeys.has(key)) continue;+ if (!result.has(key)) result.set(key, install);}return result;}diff --git a/apps/desktop/src/main/skillhub/identityPolicy.ts b/apps/desktop/src/main/skillhub/identityPolicy.tsindex 8a48986ebe..2555cc7969 100644--- a/apps/desktop/src/main/skillhub/identityPolicy.ts+++ b/apps/desktop/src/main/skillhub/identityPolicy.ts@@ -2,6 +2,7 @@ import { deriveSkillhubIdentityPolicy } from '../../shared/skillhubIdentityPolicimport { getAuthState } from '../authManager';import { ServerApiError } from '../serverApiClient';import type { SkillhubPublishVisibility } from '../../shared/skillhubIdentityPolicy';+import { isAppSessionBoundaryPending } from '../appSessionState.js';export function currentSkillhubIdentityPolicy() {return deriveSkillhubIdentityPolicy(getAuthState().user);@@ -12,6 +13,13 @@ function skillhubWritePolicyError(): ServerApiError {}export function assertSkillhubWriteAllowed(): void {+ if (isAppSessionBoundaryPending()) {+ throw new ServerApiError(+ 'PRECONDITION_FAILED',+ 409,+ 'App session is switching; retry after the owner boundary settles',+ );+ }const policy = currentSkillhubIdentityPolicy();if (policy.canWrite) return;throw skillhubWritePolicyError();@@ -20,8 +28,8 @@ export function assertSkillhubWriteAllowed(): void {export function assertSkillhubVisibilityAllowed(visibility: 'private' | 'shared' | 'public',): void {+ assertSkillhubWriteAllowed();const policy = currentSkillhubIdentityPolicy();- if (!policy.canWrite) throw skillhubWritePolicyError();const clientVisibility: SkillhubPublishVisibility = visibility === 'shared'? 'DEPARTMENT_SCOPED': visibility.toUpperCase() as SkillhubPublishVisibility;diff --git a/apps/desktop/src/main/skillhub/marketService.ts b/apps/desktop/src/main/skillhub/marketService.tsindex c86c37ad2f..03afd2c1d0 100644--- a/apps/desktop/src/main/skillhub/marketService.ts+++ b/apps/desktop/src/main/skillhub/marketService.ts@@ -45,7 +45,11 @@ export interface SkillhubMarketServiceOptions {fetch?: SkillhubMarketFetcher;assertWriteAllowed?: () => void | Promise<void>;assertVisibilityAllowed?: (visibility: 'private' | 'shared' | 'public') => void | Promise<void>;- updateRegistryCatalogScope?: (name: string, scope: SkillhubCatalogScope | undefined) => Promise<void>;+ updateRegistryCatalogScope?: (+ name: string,+ scope: SkillhubCatalogScope | undefined,+ previousScope: SkillhubCatalogScope | undefined,+ ) => Promise<void>;}export interface ListMarketParams {@@ -73,6 +77,8 @@ export interface UpdatePublishedFields {export interface SetPublishedVisibilityParams {name: string;visibility: 'private' | 'shared' | 'public';+ /** Catalog containing the currently visible version before this mutation. */+ previousCatalogScope?: SkillhubCatalogScope;teamSlug?: string;visibleSlugs?: string[];}@@ -94,7 +100,11 @@ export class SkillhubMarketService {private readonly fetch: SkillhubMarketFetcher;private readonly assertWriteAllowed: () => void | Promise<void>;private readonly assertVisibilityAllowed: (visibility: 'private' | 'shared' | 'public') => void | Promise<void>;- private readonly updateRegistryCatalogScope: (name: string, scope: SkillhubCatalogScope | undefined) => Promise<void>;+ private readonly updateRegistryCatalogScope: (+ name: string,+ scope: SkillhubCatalogScope | undefined,+ previousScope: SkillhubCatalogScope | undefined,+ ) => Promise<void>;constructor(options: SkillhubMarketServiceOptions = {}) {this.fetch = options.fetch ?? skillhubApiFetch;@@ -237,7 +247,7 @@ export class SkillhubMarketService {return { success: true as const, result };}- async setPublishedVisibility({ name, visibility, teamSlug, visibleSlugs }: SetPublishedVisibilityParams) {+ async setPublishedVisibility({ name, visibility, previousCatalogScope, teamSlug, visibleSlugs }: SetPublishedVisibilityParams) {await this.assertWriteAllowed();await this.assertVisibilityAllowed(visibility);const result = await this.fetch<SkillVisibilityUpdateResult>(@@ -255,7 +265,7 @@ export class SkillhubMarketService {// the native record even while the old catalog visibility remains active.const targetVisibility = result.requestedVisibility ?? result.visibility;const catalogScope = targetVisibility === 'shared' ? 'team' as const : undefined;- await this.updateRegistryCatalogScope(name, catalogScope).catch((err) => {+ await this.updateRegistryCatalogScope(name, catalogScope, previousCatalogScope).catch((err) => {log.warn(`[visibility] registry catalog scope update failed name=${name}:`, err);});return { success: true as const, result };diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.tsindex 1be72a5a9b..8ecb725eac 100644--- a/apps/desktop/src/main/skillhub/registerIpc.ts+++ b/apps/desktop/src/main/skillhub/registerIpc.ts@@ -377,7 +377,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {// ── SkillHub market broker IPC ───────────────────────────────────────────ipcMain.handle('skillhub:sync',- async (_event, params: { slugs?: string[] } | undefined) => {+ async (_event, params: { skills?: unknown; slugs?: string[] } | undefined) => {try {return await marketService.sync(params);} catch (err) {@@ -497,9 +497,13 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {ipcMain.handle('skillhub:set-published-visibility',- async (_event, params: Parameters<SkillhubMarketService['setPublishedVisibility']>[0]) => {+ async (_event, params: Omit<Parameters<SkillhubMarketService['setPublishedVisibility']>[0], 'previousCatalogScope'> & { previousCatalogScope?: unknown }) => {try {- return await marketService.setPublishedVisibility(params);+ const { previousCatalogScope, ...fields } = params;+ return await marketService.setPublishedVisibility({+ ...fields,+ ...(isSkillhubCatalogScope(previousCatalogScope) ? { previousCatalogScope } : {}),+ });} catch (err) {return skillhubIpcError(err);}diff --git a/apps/desktop/src/main/skillhub/registry/__tests__/manifestIO.test.ts b/apps/desktop/src/main/skillhub/registry/__tests__/manifestIO.test.tsindex 62da9edfb3..a1061a5fc5 100644--- a/apps/desktop/src/main/skillhub/registry/__tests__/manifestIO.test.ts+++ b/apps/desktop/src/main/skillhub/registry/__tests__/manifestIO.test.ts@@ -54,7 +54,6 @@ import type { StoredManifest } from '../types.js';function makeManifest(skillName: string, overrides?: Partial<StoredManifest>): StoredManifest {return {schemaVersion: 1,- catalogScopeMigrated: true,skillName,installs: {[path.normalize(`/home/sam/.claude/skills/${skillName}`)]: {@@ -64,6 +63,7 @@ function makeManifest(skillName: string, overrides?: Partial<StoredManifest>): SinstalledAt: 1714000000,updatedAt: 1714000000,catalogScope: 'team',+ catalogScopeMigrated: true,},},...overrides,@@ -92,7 +92,7 @@ describe('manifestIO', () => {expect(result).toBeNull();});- it('旧 registry 原子回填 authorId 与历史 XD 目录作用域并剥离 isMine', async () => {+ it('旧 registry 读取保持纯 IO,不在未加锁路径写回迁移', async () => {const root = manifestsRoot();fs.mkdirSync(root, { recursive: true });// 模拟一份只含 isMine 没 authorId 的老数据@@ -116,17 +116,12 @@ describe('manifestIO', () => {);const result = await readFile('legacy-skill');expect(result).not.toBeNull();- expect(result!.catalogScopeMigrated).toBe(true);const installEntry = result!.installs[path.normalize('/home/sam/.claude/skills/legacy-skill')];- expect(installEntry.authorId).toBe('');- expect(installEntry.catalogScope).toBe('team');- expect((installEntry as unknown as Record<string, unknown>).isMine).toBeUndefined();+ expect(installEntry.authorId).toBeUndefined();+ expect(installEntry.catalogScope).toBeUndefined();+ expect((installEntry as unknown as Record<string, unknown>).isMine).toBe(true);const persisted = JSON.parse(fs.readFileSync(path.join(root, 'legacy-skill.json'), 'utf-8'));- expect(persisted.installs[path.normalize('/home/sam/.claude/skills/legacy-skill')]).toMatchObject({- authorId: '',- catalogScope: 'team',- });- expect(persisted.catalogScopeMigrated).toBe(true);+ expect(persisted).toEqual(legacyManifest);});it('skillName 字段不符 → 抛 RegistryError CORRUPTED', async () => {diff --git a/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts b/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.tsindex 0894ae129c..e46bf21529 100644--- a/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts+++ b/apps/desktop/src/main/skillhub/registry/__tests__/registryService.test.ts@@ -103,9 +103,8 @@ describe('addInstall', () => {const manifest = expectManifest(await readManifest('my-skill'));expect(manifest.skillName).toBe('my-skill');expect(manifest.schemaVersion).toBe(1);- expect(manifest.catalogScopeMigrated).toBe(true);const normalizedPath = path.normalize(globalPath);- expect(manifest.installs[normalizedPath]).toEqual(entry);+ expect(manifest.installs[normalizedPath]).toEqual({ ...entry, catalogScopeMigrated: true });});it('同 (name, path) 重复 addInstall → 覆盖(不报错)', async () => {@@ -168,6 +167,51 @@ describe('addInstall', () => {});});+describe('catalog scope migration', () => {+ it('migrates and persists a released-client entry while holding the service lock', async () => {+ fs.mkdirSync(path.dirname(manifestPath('legacy-skill')), { recursive: true });+ const installPath = path.join('/projects/legacy', '.agents', 'skills', 'legacy-skill');+ fs.writeFileSync(manifestPath('legacy-skill'), JSON.stringify({+ schemaVersion: 1,+ skillName: 'legacy-skill',+ installs: { [installPath]: makeEntry({ catalogScope: undefined, catalogScopeMigrated: undefined }) },+ }));++ const manifest = expectManifest(await readManifest('legacy-skill'));++ expect(manifest.installs[installPath]).toMatchObject({+ catalogScope: 'team',+ catalogScopeMigrated: true,+ });+ expect(readJson(manifestPath('legacy-skill'))).toEqual(manifest);+ expect(readJson(backupManifestPath('legacy-skill'))).toEqual(manifest);+ });++ it('migrates each downgrade-written entry even when an old top-level marker remains', async () => {+ fs.mkdirSync(path.dirname(manifestPath('downgrade-skill')), { recursive: true });+ const nativePath = path.join('/projects/native', '.agents', 'skills', 'downgrade-skill');+ const downgradedPath = path.join('/projects/old-client', '.agents', 'skills', 'downgrade-skill');+ fs.writeFileSync(manifestPath('downgrade-skill'), JSON.stringify({+ schemaVersion: 1,+ catalogScopeMigrated: true,+ skillName: 'downgrade-skill',+ installs: {+ [nativePath]: makeEntry({ catalogScope: undefined, catalogScopeMigrated: true }),+ [downgradedPath]: makeEntry({ catalogScope: undefined, catalogScopeMigrated: undefined }),+ },+ }));++ const manifest = expectManifest(await readManifest('downgrade-skill'));++ expect(manifest.installs[nativePath].catalogScope).toBeUndefined();+ expect(manifest.installs[downgradedPath]).toMatchObject({+ catalogScope: 'team',+ catalogScopeMigrated: true,+ });+ expect(manifest).not.toHaveProperty('catalogScopeMigrated');+ });+});+describe('updateInstall', () => {it('存在的 entry → 部分更新', async () => {await addInstall(@@ -194,13 +238,24 @@ describe('updateInstall', () => {it('可见性迁移可清除目录作用域且不会被旧数据迁移再次回填', async () => {await addInstall('my-skill', globalPath, makeEntry({ catalogScope: 'market' }));- await updateCatalogScopeForSkill('my-skill', undefined);+ await updateCatalogScopeForSkill('my-skill', undefined, 'market');expect((await getInstall('my-skill', globalPath))?.catalogScope).toBeUndefined();- expect((await readManifest('my-skill'))?.catalogScopeMigrated).toBe(true);+ expect((await getInstall('my-skill', globalPath))?.catalogScopeMigrated).toBe(true);expect((await getInstall('my-skill', globalPath))?.catalogScope).toBeUndefined();});+ it('可见性迁移只更新来源目录相同的安装记录', async () => {+ const teamPath = path.join('/projects/team', '.agents', 'skills', 'my-skill');+ await addInstall('my-skill', globalPath, makeEntry({ catalogScope: 'market' }));+ await addInstall('my-skill', teamPath, makeEntry({ catalogScope: 'team' }));++ await updateCatalogScopeForSkill('my-skill', undefined, 'market');++ expect((await getInstall('my-skill', globalPath))?.catalogScope).toBeUndefined();+ expect((await getInstall('my-skill', teamPath))?.catalogScope).toBe('team');+ });+it('不存在的 installPath → 抛 REGISTRY_IO_FAILED', async () => {await expect(updateInstall('my-skill', '/nonexistent/path', { version: '2' }),@@ -241,6 +296,24 @@ describe('listAllInstalls', () => {expect(result).toEqual([]);});+ it('does not trust an unlocked directory-scan snapshot before migration writeback', async () => {+ await addInstall('my-skill', globalPath, makeEntry({ version: '2', catalogScope: 'market' }));+ const manifestIO = await import('../manifestIO.js');+ vi.spyOn(manifestIO, 'listAllFiles').mockResolvedValue([{+ skillName: 'my-skill',+ manifest: {+ schemaVersion: 1,+ skillName: 'my-skill',+ installs: { [globalPath]: makeEntry({ version: '1' }) },+ },+ }]);++ const installs = await listAllInstalls();++ expect(installs).toHaveLength(1);+ expect(installs[0]?.entry.version).toBe('2');+ });+it('跨多个 manifest 文件展平所有 install', async () => {const pathA = path.join('/home/sam/.claude/skills/skill-a');const pathB1 = path.join('/projects/p1/.claude/skills/skill-b');diff --git a/apps/desktop/src/main/skillhub/registry/manifestIO.ts b/apps/desktop/src/main/skillhub/registry/manifestIO.tsindex 1e0a508a0d..3195826023 100644--- a/apps/desktop/src/main/skillhub/registry/manifestIO.ts+++ b/apps/desktop/src/main/skillhub/registry/manifestIO.ts@@ -8,7 +8,6 @@ import path from 'node:path';import { app } from 'electron';import { RegistryError, type StoredManifest } from './types.js';import { sanitizeSkillName } from './derivations.js';-import { migrateStoredManifest } from './migrations.js';import { createLogger, maskPath } from '../../logger';@@ -44,9 +43,7 @@ export async function readFile(skillName: string): Promise<StoredManifest | null`manifest 文件 skillName 字段 "${parsed.skillName}" 与传入参数 "${skillName}" 不符`,);}- const migrated = migrateStoredManifest(parsed);- if (migrated.changed) await writeFileAtomic(skillName, migrated.manifest);- return migrated.manifest;+ return parsed;} catch (err) {if (err instanceof RegistryError) throw err;const code = (err as NodeJS.ErrnoException).code;diff --git a/apps/desktop/src/main/skillhub/registry/migrations.ts b/apps/desktop/src/main/skillhub/registry/migrations.tsindex 17c75f35fe..42f31d8747 100644--- a/apps/desktop/src/main/skillhub/registry/migrations.ts+++ b/apps/desktop/src/main/skillhub/registry/migrations.ts@@ -9,9 +9,11 @@ export function migrateStoredManifest(manifest: StoredManifest): {manifest: StoredManifest;changed: boolean;} {- let changed = false;+ const legacyManifest = manifest as StoredManifest & { catalogScopeMigrated?: unknown };+ let changed = 'catalogScopeMigrated' in legacyManifest;+ const baseManifest = { ...legacyManifest };+ delete baseManifest.catalogScopeMigrated;const installs: Record<string, StoredInstall> = {};- const shouldBackfillCatalogScope = manifest.catalogScopeMigrated !== true;for (const [installPath, rawEntry] of Object.entries(manifest.installs ?? {})) {const entry = { ...rawEntry } as StoredInstall & { isMine?: unknown };@@ -23,16 +25,15 @@ export function migrateStoredManifest(manifest: StoredManifest): {delete entry.isMine;changed = true;}- if (shouldBackfillCatalogScope && !entry.catalogScope) {- entry.catalogScope = 'team';+ if (entry.catalogScopeMigrated !== true) {+ if (!entry.catalogScope) entry.catalogScope = 'team';+ entry.catalogScopeMigrated = true;changed = true;}installs[installPath] = entry;}- if (shouldBackfillCatalogScope) changed = true;-return changed- ? { manifest: { ...manifest, catalogScopeMigrated: true, installs }, changed: true }+ ? { manifest: { ...baseManifest, installs }, changed: true }: { manifest, changed: false };}diff --git a/apps/desktop/src/main/skillhub/registry/registryService.ts b/apps/desktop/src/main/skillhub/registry/registryService.tsindex 11a3ddea68..7e3bcf93ba 100644--- a/apps/desktop/src/main/skillhub/registry/registryService.ts+++ b/apps/desktop/src/main/skillhub/registry/registryService.ts@@ -96,7 +96,11 @@ async function listBackupSkillNames(): Promise<string[]> {async function readManifestWithBackup(skillName: string): Promise<StoredManifest | null> {const manifest = await manifestIO.readFile(skillName);- if (manifest) return manifest;+ if (manifest) {+ const migrated = migrateStoredManifest(manifest);+ if (migrated.changed) await writeManifestWithBackup(skillName, migrated.manifest);+ return migrated.manifest;+ }// 短期兼容:用户可能降级到旧版后再升回新版。旧版 orphan cleanup 在// ~/.agents 实体目录 + ~/.claude symlink 场景下可能误删主 registry 文件。@@ -127,16 +131,15 @@ export async function addInstall(if (!existing) {manifest = {schemaVersion: 1,- catalogScopeMigrated: true,skillName,- installs: { [normalizedPath]: entry },+ installs: { [normalizedPath]: { ...entry, catalogScopeMigrated: true } },};} else {manifest = {...existing,installs: {...existing.installs,- [normalizedPath]: entry,+ [normalizedPath]: { ...entry, catalogScopeMigrated: true },},};}@@ -237,8 +240,12 @@ export async function listAllInstalls(): Promise<Array<{ skillName: string; installPath: string; entry: StoredInstall }>> {const filesByName = new Map<string, StoredManifest>();- for (const { skillName, manifest } of await manifestIO.listAllFiles()) {- filesByName.set(skillName, manifest);+ for (const { skillName } of await manifestIO.listAllFiles()) {+ const manifest = await withLock(skillName, () => readManifestWithBackup(skillName)).catch((err) => {+ log.warn(`read registry manifest failed for ${skillName}:`, err);+ return null;+ });+ if (manifest) filesByName.set(skillName, manifest);}for (const skillName of await listBackupSkillNames()) {if (filesByName.has(skillName)) continue;@@ -257,14 +264,22 @@ export async function listAllInstalls(): Promise<return result;}-/** Re-point every local install of a slug after the server moves it between catalogs. */+/** Re-point installs from one catalog after the server moves that record. */export async function updateCatalogScopeForSkill(skillName: string,catalogScope: StoredInstall['catalogScope'],+ previousCatalogScope: StoredInstall['catalogScope'],): Promise<void> {- const installs = (await listAllInstalls()).filter((item) => item.skillName === skillName);- await Promise.all(installs.map(({ installPath }) => updateInstall(skillName, installPath, {- catalogScope,- updatedAt: Math.floor(Date.now() / 1000),- })));+ await withLock(skillName, async () => {+ const existing = await readManifestWithBackup(skillName);+ if (!existing) return;+ const updatedAt = Math.floor(Date.now() / 1000);+ let changed = false;+ const installs = Object.fromEntries(Object.entries(existing.installs).map(([installPath, entry]) => {+ if (entry.catalogScope !== previousCatalogScope) return [installPath, entry];+ changed = true;+ return [installPath, { ...entry, catalogScope, updatedAt }];+ }));+ if (changed) await writeManifestWithBackup(skillName, { ...existing, installs });+ });}diff --git a/apps/desktop/src/main/skillhub/registry/types.ts b/apps/desktop/src/main/skillhub/registry/types.tsindex 9c2b4bc558..2bc5c1b273 100644--- a/apps/desktop/src/main/skillhub/registry/types.ts+++ b/apps/desktop/src/main/skillhub/registry/types.ts@@ -30,6 +30,8 @@ export interface StoredInstall {autoSynced?: boolean;/** Catalog used for detail/download; absent on older registry entries. */catalogScope?: SkillhubCatalogScope;+ /** This entry has resolved the pre-Cindy-Hub missing-scope migration. */+ catalogScopeMigrated?: true;/** /learn 蒸馏产物的溯源(仅 origin='learned' 时存在)。* provenance.personal=true ⇒ 含本地会话衍生内容。当前不拦截发布 ——* 作为将来「发布前泛化」流程(另行独立 PR)的判定依据保留。 */@@ -38,8 +40,6 @@ export interface StoredInstall {export interface StoredManifest {schemaVersion: 1;- /** catalogScope 缺省值迁移标记。旧客户端忽略并在 spread 写回时保留。 */- catalogScopeMigrated?: true;/** 自校验:必须等于文件名(去 .json)。不一致即抛 RegistryCorruptedError。 */skillName: string;/** key = path.normalize 后的绝对 installPath。 */diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 2cd9ffd28f..ba6db62a51 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -3092,6 +3092,7 @@ contextBridge.exposeInMainWorld('electronAPI', {setPublishedVisibility: (params: {name: string;visibility: 'private' | 'shared' | 'public';+ previousCatalogScope?: 'market' | 'team';teamSlug?: string;visibleSlugs?: string[];}): Promise<{diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsxindex 1f77db6c27..9c9134a563 100644--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx@@ -1919,10 +1919,7 @@ export function SkillhubDetailView() {className="inline-flex h-5 shrink-0 items-center text-[var(--error-fg-strong)] hover:opacity-70 transition-opacity"onClick={async () => {if (!entry?.name) return;- const res = await window.electronAPI.skillhub.listPublishedVersions(- entry.name,- entry.registryEntry?.catalogScope,- );+ const res = await window.electronAPI.skillhub.listPublishedVersions(entry.name);if (!res.success || !res.versions) {setScanResult({ status: 'rejected', gates: [] });return;diff --git a/apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx b/apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsxindex d6459f5abf..910b7de979 100644--- a/apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx+++ b/apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx@@ -104,10 +104,16 @@ export function VisibilityEditorDialog({setSaving(true);try {const visibility = tier === 'team' ? 'shared' as const : tier;+ const previousCatalogScope = currentTier === 'public'+ ? 'market' as const+ : currentTier === 'team'+ ? 'team' as const+ : undefined;// 归属由服务端根据当前 membership 固定,客户端只修改可见性。const visRes = await window.electronAPI.skillhub.setPublishedVisibility({name: skillName,visibility,+ previousCatalogScope,});if (!visRes.success) {toast.error(marketActionErrorMessage(visRes.error, visRes.errorCode));diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.tsindex 8c9239c26c..ad19f89020 100644--- a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts@@ -25,7 +25,7 @@ import { useTranslation } from 'react-i18next';import { i18n } from '@/i18n';import { CATEGORY_ALL, type MarketCategory } from '../../../../shared/skillhubCategory';-import type { SkillhubCatalogScope } from '../../../../shared/skillhubCatalog';+import { skillhubCatalogKey, type SkillhubCatalogScope } from '../../../../shared/skillhubCatalog';import type { HubPublishedVisibility } from '../lib/marketVisibility';import { filterAvailableMarketItems } from '../lib/marketDetailViewModel';@@ -179,7 +179,7 @@ export function formatMarketRelativeTime(iso: string, translate: TFunction, nowMreturn translate('skillhub.marketCard.relativeTime.years', { count: year });}-interface LocalSkillEntry {+export interface LocalSkillEntry {/** 版本号字符串来自 registryEntry.version;null = 无 registry 记录。 */version: string | null;absolutePath: string;@@ -188,13 +188,46 @@ interface LocalSkillEntry {hasRegistryEntry: boolean;}-interface LocalSkillGroup {+export interface LocalSkillGroup {global?: LocalSkillEntry;projects: LocalSkillEntry[];}-interface LocalSkillIndex {- byName: Map<string, LocalSkillGroup>;+export interface LocalSkillIndex {+ /** Registry-backed installs are independent for each remote catalog record. */+ byCatalogKey: Map<string, LocalSkillGroup>;+ /** User-authored local folders have no remote scope and only back owned items. */+ untrackedByName: Map<string, LocalSkillGroup>;+}++function addLocalEntry(+ index: Map<string, LocalSkillGroup>,+ key: string,+ scope: 'global' | 'project',+ entry: LocalSkillEntry,+): void {+ let group = index.get(key);+ if (!group) {+ group = { global: undefined, projects: [] };+ index.set(key, group);+ }+ if (scope === 'global') group.global = entry;+ else group.projects.push(entry);+}++export function localGroupForItem(+ item: { name: string; isMine: boolean; catalogScope?: SkillhubCatalogScope },+ index: LocalSkillIndex,+): LocalSkillGroup | undefined {+ const tracked = index.byCatalogKey.get(skillhubCatalogKey(item.name, item.catalogScope));+ if (!item.isMine) return tracked;+ const untracked = index.untrackedByName.get(item.name);+ if (!tracked) return untracked;+ if (!untracked) return tracked;+ return {+ global: tracked.global ?? untracked.global,+ projects: [...tracked.projects, ...untracked.projects],+ };}export function deriveCardState(@@ -221,7 +254,7 @@ function mapServerToView(installingNames: Set<string>,translate: TFunction,): MarketSkill {- const group = localIndex.byName.get(item.name);+ const group = localGroupForItem(item, localIndex);// 优先用 global entry 作为"主安装"信息(版本、路径);没有 global 时回落到第一个 project entry。const primary = group?.global ?? group?.projects[0];// mine:只要本地同名目录存在就算有副本(自己发布的 skill 不写 registry)。@@ -331,10 +364,12 @@ export function useMarketList(// 本地扫描结果用来派生 cardState。useSkillhub 是模块级 store,跨组件共享。const { skills: localSkills } = useSkillhub();- // 折成 name → { global?, projects[] } index。区分安装位置,cardState 只看 global。+ // Registry-backed installs use catalog+name; untracked local folders are a+ // separate fallback for owned items only.const localIndex: LocalSkillIndex = {- byName: (() => {- const m = new Map<string, LocalSkillGroup>();+ ...(() => {+ const byCatalogKey = new Map<string, LocalSkillGroup>();+ const untrackedByName = new Map<string, LocalSkillGroup>();for (const s of localSkills) {if (s.kind !== 'skill') continue;const entry: LocalSkillEntry = {@@ -342,18 +377,13 @@ export function useMarketList(absolutePath: s.absolutePath,hasRegistryEntry: s.registryEntry !== null,};- let group = m.get(s.name);- if (!group) {- group = { global: undefined, projects: [] };- m.set(s.name, group);- }- if (s.scope === 'global') {- group.global = entry;- } else {- group.projects.push(entry);- }+ const index = s.registryEntry ? byCatalogKey : untrackedByName;+ const key = s.registryEntry+ ? skillhubCatalogKey(s.name, s.registryEntry.catalogScope)+ : s.name;+ addLocalEntry(index, key, s.scope, entry);}- return m;+ return { byCatalogKey, untrackedByName };})(),};@@ -535,17 +565,17 @@ export function useMarketList(}, [enabled, sortBy, searchQuery, catalogScope, visibility, categoryFilter, fetchPage, reloadTick]);// 当本地扫描结果或 installing 集合变化时,只重新派生 cardState/installedVersion,不重发请求。- // 依赖键用 (name, version, installing) 序列化字符串,避免对象引用变化导致每次都跑。+ // Include catalog scope so a same-slug install moving between catalogs remaps immediately.const localKey = localSkills.filter((s) => s.kind === 'skill')- .map((s) => `${s.name}@${s.registryEntry?.version ?? '?'}@${s.registryEntry !== null ? 'R' : '_'}@${s.absolutePath}`)+ .map((s) => `${s.name}@${s.registryEntry?.catalogScope ?? 'native'}@${s.registryEntry?.version ?? '?'}@${s.registryEntry !== null ? 'R' : '_'}@${s.absolutePath}`).join('|');const installingKey = Array.from(installingNames).sort().join(',');useEffect(() => {setState((prev) => {if (prev.items.length === 0) return prev;const remapped = prev.items.map((it) => {- const group = localIndex.byName.get(it.name);+ const group = localGroupForItem(it, localIndex);const primary = group?.global ?? group?.projects[0];const isReallyInstalled = !!primary && (it.isMine || primary.hasRegistryEntry);const hasAnyInstall = !!group && (diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.tsindex 537278c544..82694e5c3f 100644--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.ts+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';-import { deriveCardState } from '../../hooks/useMarketList';+import { deriveCardState, localGroupForItem, type LocalSkillIndex } from '../../hooks/useMarketList';+import { skillhubCatalogKey } from '../../../../../shared/skillhubCatalog';const item = (over: Record<string, unknown> = {}) => ({name: 'x',@@ -39,3 +40,26 @@ describe('deriveCardState — isMine 按目录判已装', () => {expect(deriveCardState(item({ isMine: true }), grp(undefined), true)).toBe('installing');});});++describe('market install catalog matching', () => {+ const entry = (version: string) => ({+ version,+ absolutePath: `/p/${version}`,+ hasRegistryEntry: true,+ });+ const index: LocalSkillIndex = {+ byCatalogKey: new Map([+ [skillhubCatalogKey('same', 'market'), { global: entry('1.0.0'), projects: [] }],+ [skillhubCatalogKey('same', 'team'), { global: entry('2.0.0'), projects: [] }],+ ]),+ untrackedByName: new Map(),+ };++ it('keeps same-slug market and team installs independent', () => {+ expect(localGroupForItem({ name: 'same', isMine: false, catalogScope: 'market' }, index)?.global?.version)+ .toBe('1.0.0');+ expect(localGroupForItem({ name: 'same', isMine: false, catalogScope: 'team' }, index)?.global?.version)+ .toBe('2.0.0');+ expect(localGroupForItem({ name: 'same', isMine: false }, index)).toBeUndefined();+ });+});diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.tsindex cefb93d94e..872cd84b04 100644--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts@@ -25,6 +25,11 @@ describe('market route scope', () => {expect(localDetailSource).not.toContain('marketManagePath');});+ it('reads rejected management versions from the native record', () => {+ expect(localDetailSource).toContain('listPublishedVersions(entry.name)');+ expect(localDetailSource).not.toContain('listPublishedVersions(entry.name, entry.registryEntry?.catalogScope)');+ });+it('keeps Clone wording for acquisition actions', () => {const marketCardSource = readFileSync(resolve(skillhubDir, 'components/MarketCard.tsx'), 'utf8');expect(marketCardSource).toContain('Clone');@@ -116,6 +121,7 @@ describe('market management copy and errors', () => {expect(editorSource).not.toContain('PublisherPicker');expect(editorSource).not.toContain('fields.teamSlug');expect(editorSource).toContain('identityPolicy.ownerType');+ expect(editorSource).toContain('previousCatalogScope,');});it('does not expose an extra published status pill in the market preview panel', () => {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 4d18210cd7..908797554a 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3280,6 +3280,7 @@ interface ElectronAPI {setPublishedVisibility: (params: {name: string;visibility: 'private' | 'shared' | 'public';+ previousCatalogScope?: 'market' | 'team';teamSlug?: string;visibleSlugs?: string[];}) => Promise<{diff --git a/apps/mobile/src/__tests__/desktopSlashCommands.test.ts b/apps/mobile/src/__tests__/desktopSlashCommands.test.tsindex 832b50280f..d9381f9b21 100644--- a/apps/mobile/src/__tests__/desktopSlashCommands.test.ts+++ b/apps/mobile/src/__tests__/desktopSlashCommands.test.ts@@ -80,6 +80,17 @@ describe('buildLearnStartRequest(语义对齐桌面 builtins.ts 的 /learn)', ()input: '按我们团队习惯改',sourceKind: 'hub',hubSlug: 'deploy-checklist',+ hubCatalogScope: 'market',+ originSessionId: 's-1',+ });+ });++ it('hub:<scope>:<slug> 保留目录作用域', () => {+ expect(buildLearnStartRequest('hub:team:deploy-checklist 精简', 's-1')).toEqual({+ input: '精简',+ sourceKind: 'hub',+ hubSlug: 'deploy-checklist',+ hubCatalogScope: 'team',originSessionId: 's-1',});});diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex e2da4dff09..559e0af62c 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -128,6 +128,7 @@ export interface MobileLearnStartRequest {input: string;sourceKind: 'freetext' | 'session' | 'hub';hubSlug?: string;+ hubCatalogScope?: 'market' | 'team';originSessionId?: string;}diff --git a/apps/mobile/src/session/desktopSlashCommands.ts b/apps/mobile/src/session/desktopSlashCommands.tsindex 8cbcb06816..9f421010f6 100644--- a/apps/mobile/src/session/desktopSlashCommands.ts+++ b/apps/mobile/src/session/desktopSlashCommands.ts@@ -61,20 +61,22 @@ export function parseMobileDesktopCommand(}/**- * `/learn [hub:<slug>] [要求]` → learn:start 请求。语义对齐桌面 builtins.ts:- * - `hub:<slug>` 前缀 → hub 蒸馏(slug 规则 [a-z0-9-],与市场一致);+ * `/learn [hub:[market|team:]<slug>] [要求]` → learn:start 请求。语义对齐桌面 builtins.ts:+ * - `hub:<slug>` 前缀 → 公开目录 hub 蒸馏(slug 规则 [a-z0-9-],与市场一致);+ * - `hub:<scope>:<slug>` → 显式目录 hub 蒸馏;* - 有参数 → freetext;无参数 → 蒸馏当前会话(session)。* 移动端总在会话内触发,originSessionId 恒有值,因此裸 /learn 不需要桌面* 草稿态的 usage 报错分支。*/export function buildLearnStartRequest(args: string, sessionId: string): MobileLearnStartRequest {const arg = args.trim();- const hubMatch = /^hub:([a-z0-9][a-z0-9-]*)\s*/.exec(arg);+ const hubMatch = /^hub:(?:(market|team):)?([a-z0-9][a-z0-9-]*)\s*/.exec(arg);if (hubMatch) {return {input: arg.slice(hubMatch[0].length).trim(),sourceKind: 'hub',- hubSlug: hubMatch[1],+ hubSlug: hubMatch[2],+ hubCatalogScope: (hubMatch[1] as 'market' | 'team' | undefined) ?? 'market',originSessionId: sessionId,};}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex da42d0cd4d..269c21afa8 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -38,10 +38,15 @@### Skill Hub 目录与管理契约- `scope=market|team` 是公开与组织目录的通用读取上下文;列表得到的 scope 必须贯穿详情、- 文件、版本、扫描、下载、Learn 和批量同步。同 slug 在不同 scope 下是两条独立记录。+ 文件、版本、扫描、下载、Learn 和批量同步。同 slug 在不同 scope 下是两条独立远端记录;+ 但全局 Skill 发现路径仍按 slug 只有一个安装槽,自动同步配置重复同一 slug 时由首个有效项+ 选定该安装槽的目录来源,不得尝试把两个 scope 同时安装到同一路径。+- Desktop 与 Mobile 的 `/learn hub:<slug>` 兼容语法统一归一为 `market`;目录来源明确时使用+ `/learn hub:<scope>:<slug>`,并把 scope 原样传入 Learn 请求和后续文件读取。- 单条详情、批量同步等原生管理读取省略 scope,不得把省略值当成 `market`。本地 registry对已发布旧版客户端遗留且缺少 scope 的安装记录一次性回填为 `team`;新记录显式保存- 来源目录,原生管理记录则以已迁移标记保留缺省 scope。+ 来源目录,原生管理记录则以逐条迁移标记保留缺省 scope。迁移状态不得只存在 manifest+ 顶层,否则降级客户端新增的无 scope 条目在再次升级时无法被识别。- `isMine` 表示归属当前个人或组织,逐 Skill 写权限只看服务端 `canManage`,客户端不得用账号级写能力与 `isMine` 推导管理权。- 作者标签通过 `tags: string[]` 传标签名称;`source=platform` 的治理标签只展示和筛选,