Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): harden built-in skill reads
xd-boboed96f6066b15
diff --git a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.pyindex 69a9a29341..84df6e2309 100644--- a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py+++ b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py@@ -154,11 +154,145 @@ def _block_value(lines, start, style):return "\n".join(paragraphs), cursor+def _split_mapping_entry(value):+ """Find a block-mapping colon without mistaking quotes/flows/URLs for it."""+ stack = []+ quote = None+ escaped = False+ index = 0+ while index < len(value):+ char = value[index]+ if quote == '"':+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ quote = None+ elif quote == "'":+ if char == "'" and index + 1 < len(value) and value[index + 1] == "'":+ index += 1+ elif char == "'":+ quote = None+ elif char in {'"', "'"}:+ quote = char+ elif char in "[{":+ stack.append("]" if char == "[" else "}")+ elif char in "]}":+ if not stack or stack.pop() != char:+ raise FrontmatterError(f"Mismatched flow delimiter '{char}'")+ elif char == ":" and not stack and (+ index + 1 == len(value) or value[index + 1].isspace()+ ):+ return value[:index], value[index + 1 :]+ index += 1+ if quote is not None or escaped:+ raise FrontmatterError("Unterminated quoted scalar")+ if stack:+ raise FrontmatterError(f"Unterminated flow collection, expected '{stack[-1]}'")+ return None+++def _validate_nested_entry(text, line_number):+ sequence_entry = text == "-" or text.startswith("- ") or text.startswith("-\t")+ value = text[1:].lstrip() if sequence_entry else text+ if not value or value.startswith("#"):+ return True, False, "sequence" if sequence_entry else "scalar"++ mapping_entry = _split_mapping_entry(value)+ if mapping_entry is not None:+ raw_key, raw_value = mapping_entry+ if not raw_key.strip():+ raise FrontmatterError(f"Missing mapping key on line {line_number}")+ key = _parse_scalar(raw_key.strip())+ if not isinstance(key, (str, int, float, bool)):+ raise FrontmatterError(f"Invalid mapping key on line {line_number}")+ scalar_value = raw_value.lstrip()+ if not scalar_value or scalar_value.startswith("#"):+ return True, False, "sequence" if sequence_entry else "mapping"+ block_match = BLOCK_SCALAR_RE.match(scalar_value)+ if block_match:+ return True, True, "sequence" if sequence_entry else "mapping"+ _parse_scalar(scalar_value)+ # A sequence item may start a mapping whose sibling keys are indented+ # beneath the dash even when this first key already has a value.+ return sequence_entry, False, "sequence" if sequence_entry else "mapping"++ block_match = BLOCK_SCALAR_RE.match(value)+ if block_match:+ return True, True, "sequence" if sequence_entry else "scalar"+ _parse_scalar(value)+ return False, False, "sequence" if sequence_entry else "scalar"+++def _parse_nested_block(lines, start):+ """Validate an indented YAML subset and retain only its collection type.++ The bundled tools inspect only top-level fields, but nested metadata still+ has to be structurally valid. This walks every nested entry, validates its+ scalar/flow syntax, and enforces indentation transitions without adding a+ third-party YAML dependency.+ """+ cursor = start+ indent_levels = []+ previous_allows_child = True+ block_scalar_indent = None+ collection = None++ while cursor < len(lines):+ line = lines[cursor]+ if not line.strip():+ cursor += 1+ continue+ if line.startswith("\t"):+ raise FrontmatterError(f"Nested values must use space indentation on line {cursor + 1}")+ indent = len(line) - len(line.lstrip(" "))+ stripped = line[indent:]+ if indent == 0:+ break+ if stripped.startswith("#"):+ cursor += 1+ continue++ if block_scalar_indent is not None:+ if indent > block_scalar_indent:+ cursor += 1+ continue+ block_scalar_indent = None++ if not indent_levels:+ indent_levels.append([indent, None])+ collection = [] if stripped == "-" or stripped.startswith(("- ", "-\t")) else {}+ elif indent > indent_levels[-1][0]:+ if not previous_allows_child:+ raise FrontmatterError(f"Unexpected indentation on line {cursor + 1}")+ indent_levels.append([indent, None])+ elif indent < indent_levels[-1][0]:+ while indent_levels and indent < indent_levels[-1][0]:+ indent_levels.pop()+ if not indent_levels or indent != indent_levels[-1][0]:+ raise FrontmatterError(f"Inconsistent indentation on line {cursor + 1}")++ previous_allows_child, is_block_scalar, entry_kind = _validate_nested_entry(+ stripped,+ cursor + 1,+ )+ if indent_levels[-1][1] is None:+ indent_levels[-1][1] = entry_kind+ elif indent_levels[-1][1] != entry_kind:+ raise FrontmatterError(f"Mixed collection types on line {cursor + 1}")+ if is_block_scalar:+ block_scalar_indent = indent+ cursor += 1++ return collection, cursor++def parse_frontmatter(frontmatter_text):"""Parse top-level Skill fields without requiring PyYAML.- Nested values are retained as opaque dictionaries because the bundled- validator only needs top-level key names plus scalar name/description.+ Nested values are validated and retained as opaque collections because the+ bundled tools only inspect top-level key names plus scalar name/description."""lines = frontmatter_text.splitlines()result = {}@@ -184,13 +318,8 @@ def parse_frontmatter(frontmatter_text):continueif not raw_value.strip() or raw_value.lstrip().startswith("#"):- cursor = index + 1- while cursor < len(lines) and (- not lines[cursor].strip() or lines[cursor][:1].isspace()- ):- cursor += 1- result[key] = {} if cursor > index + 1 else None- index = cursor+ value, index = _parse_nested_block(lines, index + 1)+ result[key] = valuecontinueresult[key] = _parse_scalar(raw_value)diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.tsindex a9238d1d99..8011bce045 100644--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts@@ -14,7 +14,9 @@ const showMessageBox = vi.fn();vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));const assertTrustedAppRendererEvent = vi.fn();const isTrustedAppRendererWindow = vi.fn();-const publishServiceOptions = vi.hoisted(() => ({ onProgress: null as null | ((event: unknown) => void) }));+const publishServiceOptions = vi.hoisted(() => ({+ onProgress: null as null | ((event: unknown) => void),+}));vi.mock('../publishService', () => ({SkillPublishService: class {constructor(options: { onProgress: (event: unknown) => void }) {@@ -65,7 +67,10 @@ vi.mock('../../authManager', () => ({ getCurrentDataOwnerId }));const ownerState = { generation: 1, pending: false };vi.mock('../../appSessionState', () => ({activeOwnerScopeKey: () => `cloud:owner:${ownerState.generation}`,- getActiveDataOwnerPushStamp: () => ({ dataOwnerId: 'owner', ownerGeneration: ownerState.generation }),+ getActiveDataOwnerPushStamp: () => ({+ dataOwnerId: 'owner',+ ownerGeneration: ownerState.generation,+ }),isAppSessionBoundaryPending: vi.fn(() => ownerState.pending),}));@@ -164,12 +169,13 @@ describe('registerSkillhubIpc usage handlers', () => {showMessageBox.mockResolvedValue({ response: 0 });showOpenDialog.mockResolvedValue({ canceled: true, filePaths: [] });getAllowedProjectRoots.mockResolvedValue(['/repo', '/old', '/new']);- resolveExistingSkillPathForGrant.mockImplementation((candidate: string) => (- candidate.includes('/authorized/demo') ? '/physical/demo' : null- ));- isExistingSkillPathGranted.mockImplementation((candidate: string, roots: Set<string>) => (- roots.has('/physical/demo') && candidate.includes('/authorized/demo')- ));+ resolveExistingSkillPathForGrant.mockImplementation((candidate: string) =>+ candidate.includes('/authorized/demo') ? '/physical/demo' : null,+ );+ isExistingSkillPathGranted.mockImplementation(+ (candidate: string, roots: Set<string>) =>+ roots.has('/physical/demo') && candidate.includes('/authorized/demo'),+ );const { registerSkillhubIpc } = await import('../registerIpc');registerSkillhubIpc({getMaker: () => ({ listAgentSkills }) as never,@@ -187,16 +193,29 @@ describe('registerSkillhubIpc usage handlers', () => {const utility = { webContents: { send: vi.fn() } };const navigated = { webContents: { send: vi.fn() } };const destroyed = { webContents: { send: vi.fn() } };- vi.mocked(BrowserWindow.getAllWindows).mockReturnValueOnce([trusted, utility, navigated, destroyed] as never);+ vi.mocked(BrowserWindow.getAllWindows).mockReturnValueOnce([+ trusted,+ utility,+ navigated,+ destroyed,+ ] as never);isTrustedAppRendererWindow.mockImplementation((win) => win === trusted);registerSkillhubIpc({getMaker: () => ({ listAgentSkills }) as never,- getManagedSkillRoots, getAllowedProjectRoots, marketService: marketService as never,+ getManagedSkillRoots,+ getAllowedProjectRoots,+ marketService: marketService as never,});- const feedback = { phase: 'scan-result', name: 'review-helper', status: 'rejected', rejectionReason: 'Private feedback' };+ const feedback = {+ phase: 'scan-result',+ name: 'review-helper',+ status: 'rejected',+ rejectionReason: 'Private feedback',+ };publishServiceOptions.onProgress!(feedback);expect(trusted.webContents.send).toHaveBeenCalledWith('skillhub:publish-progress', {- ...feedback, ownerStamp: { dataOwnerId: 'owner', ownerGeneration: 1 },+ ...feedback,+ ownerStamp: { dataOwnerId: 'owner', ownerGeneration: 1 },});for (const win of [utility, navigated, destroyed]) {expect(isTrustedAppRendererWindow).toHaveBeenCalledWith(win);@@ -229,20 +248,27 @@ describe('registerSkillhubIpc usage handlers', () => {registerSkillhubIpc({getMaker: () => ({ listAgentSkills }) as never,getManagedSkillRoots,- getBuiltInSkills: () => [{- name: 'cindy-skill-creator',- absolutePath: builtInRoot,- nativeClaudePath: '/tmp/claude-home/skills/cindy-skill-creator',- }],+ getBuiltInSkills: () => [+ {+ name: 'cindy-skill-creator',+ absolutePath: builtInRoot,+ nativeClaudePath: '/tmp/claude-home/skills/cindy-skill-creator',+ },+ ],getAllowedProjectRoots,marketService: marketService as never,publishService: { publish, cancel } as never,});const event = { sender: { id: 12 } };- await expect(handlers.get('skillhub:publish')!(event, {- absolutePath: builtInFile,- })).resolves.toMatchObject({ success: false, message: expect.stringContaining('cannot be published') });+ await expect(+ handlers.get('skillhub:publish')!(event, {+ absolutePath: builtInFile,+ }),+ ).resolves.toMatchObject({+ success: false,+ message: expect.stringContaining('cannot be published'),+ });expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith(event);expect(publish).not.toHaveBeenCalled();});@@ -252,49 +278,89 @@ describe('registerSkillhubIpc usage handlers', () => {{ channel: 'skillhub:list-published-versions', field: 'name', method: 'listPublishedVersions' },] as const)('$channel private review boundary', ({ channel, field, method }) => {it('rejects an untrusted sender before accessing the service', async () => {- assertTrustedAppRendererEvent.mockImplementationOnce(() => { throw new Error('PERMISSION_DENIED'); });- await expect(handlers.get(channel)!({}, { [field]: 'review-helper' })).rejects.toThrow('PERMISSION_DENIED');+ assertTrustedAppRendererEvent.mockImplementationOnce(() => {+ throw new Error('PERMISSION_DENIED');+ });+ await expect(handlers.get(channel)!({}, { [field]: 'review-helper' })).rejects.toThrow(+ 'PERMISSION_DENIED',+ );expect(marketService[method]).not.toHaveBeenCalled();});- it.each([null, [], {}, { value: 3 }, { value: '' }, { value: 'a'.repeat(129) },- { value: 'valid', version: 3 }, { value: 'valid', version: 'v'.repeat(129) },- { value: 'valid', catalogScope: 'invalid' }, { value: 'bad\0name' },+ it.each([+ null,+ [],+ {},+ { value: 3 },+ { value: '' },+ { value: 'a'.repeat(129) },+ { value: 'valid', version: 3 },+ { value: 'valid', version: 'v'.repeat(129) },+ { value: 'valid', catalogScope: 'invalid' },+ { value: 'bad\0name' },])('rejects malformed parameters %j without a service request', async (input) => {const params = input && !Array.isArray(input) ? { ...input, [field]: input.value } : input;await expect(handlers.get(channel)!({}, params)).rejects.toThrow('INVALID_PARAMS');expect(marketService[method]).not.toHaveBeenCalled();});- it.each([undefined, 'team', 'market'] as const)('preserves catalog selection %s for trusted reads', async (catalogScope) => {- const result = { success: true, rejectionReason: 'Private feedback' };- marketService[method].mockResolvedValueOnce(result);- const event = { sender: { id: 11 } };- expect(await handlers.get(channel)!(event, { [field]: 'review-helper', version: '1.0.1', catalogScope })).toEqual(result);- expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith(event);- if (method === 'getScanStatus') {- expect(marketService[method]).toHaveBeenCalledWith({ slug: 'review-helper', version: '1.0.1', ...(catalogScope ? { catalogScope } : {}) });- } else {- expect(marketService[method]).toHaveBeenCalledWith('review-helper', catalogScope);- }- });+ it.each([undefined, 'team', 'market'] as const)(+ 'preserves catalog selection %s for trusted reads',+ async (catalogScope) => {+ const result = { success: true, rejectionReason: 'Private feedback' };+ marketService[method].mockResolvedValueOnce(result);+ const event = { sender: { id: 11 } };+ expect(+ await handlers.get(channel)!(event, {+ [field]: 'review-helper',+ version: '1.0.1',+ catalogScope,+ }),+ ).toEqual(result);+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith(event);+ if (method === 'getScanStatus') {+ expect(marketService[method]).toHaveBeenCalledWith({+ slug: 'review-helper',+ version: '1.0.1',+ ...(catalogScope ? { catalogScope } : {}),+ });+ } else {+ expect(marketService[method]).toHaveBeenCalledWith('review-helper', catalogScope);+ }+ },+ );- it.each(['generation', 'boundary'] as const)('drops a private response across an account %s change', async (transition) => {- let resolve!: (value: unknown) => void;- marketService[method].mockImplementationOnce(() => new Promise((done) => { resolve = done; }));- const request = handlers.get(channel)!({}, { [field]: 'review-helper' });- if (transition === 'generation') ownerState.generation += 1;- else ownerState.pending = true;- resolve({ success: true, rejectionReason: 'Private feedback', versions: [{ rejectionReason: 'Private feedback' }] });- const result = await request;- expect(result).toMatchObject({ success: false });- expect(JSON.stringify(result)).not.toContain('Private feedback');- });+ it.each(['generation', 'boundary'] as const)(+ 'drops a private response across an account %s change',+ async (transition) => {+ let resolve!: (value: unknown) => void;+ marketService[method].mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ );+ const request = handlers.get(channel)!({}, { [field]: 'review-helper' });+ if (transition === 'generation') ownerState.generation += 1;+ else ownerState.pending = true;+ resolve({+ success: true,+ rejectionReason: 'Private feedback',+ versions: [{ rejectionReason: 'Private feedback' }],+ });+ const result = await request;+ expect(result).toMatchObject({ success: false });+ expect(JSON.stringify(result)).not.toContain('Private feedback');+ },+ );it('preserves the empty-version shorthand for the latest release', async () => {marketService[method].mockResolvedValueOnce({ success: true });- expect(await handlers.get(channel)!({}, { [field]: 'review-helper', version: '' })).toEqual({ success: true });- if (method === 'getScanStatus') expect(marketService[method]).toHaveBeenCalledWith({ slug: 'review-helper' });+ expect(await handlers.get(channel)!({}, { [field]: 'review-helper', version: '' })).toEqual({+ success: true,+ });+ if (method === 'getScanStatus')+ expect(marketService[method]).toHaveBeenCalledWith({ slug: 'review-helper' });});});@@ -308,12 +374,14 @@ describe('registerSkillhubIpc usage handlers', () => {}),};scanAllSkills.mockResolvedValueOnce({- skills: [{- absolutePath: '/physical/demo',- discoveredPath: '/repo/.pi/skills/authorized/demo',- scope: 'project',- projectRoot: '/repo',- }],+ skills: [+ {+ absolutePath: '/physical/demo',+ discoveredPath: '/repo/.pi/skills/authorized/demo',+ scope: 'project',+ projectRoot: '/repo',+ },+ ],sources: [],});readSkillContent.mockResolvedValue({ success: true, content: 'demo' });@@ -333,16 +401,41 @@ describe('registerSkillhubIpc usage handlers', () => {expect(sender.once).toHaveBeenCalledWith('destroyed', expect.any(Function));const calls = [- ['skillhub:read-skill', { mdPath: '/repo/.pi/skills/authorized/demo/SKILL.md' }, readSkillContent],- ['skillhub:list-children', { dirPath: '/repo/.pi/skills/authorized/demo' }, listSkillFolderChildren],- ['skillhub:read-sibling-file', { filePath: '/repo/.pi/skills/authorized/demo/notes.md' }, readSkillSiblingFile],- ['skillhub:read-raw', { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' }, readSkillRawFile],- ['skillhub:write-file', { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md', content: '# Demo' }, writeSkillFile],- ['skillhub:rename-local', { absolutePath: '/repo/.pi/skills/authorized/demo', newName: 'renamed' }, renameLocalSkill],+ [+ 'skillhub:read-skill',+ { mdPath: '/repo/.pi/skills/authorized/demo/SKILL.md' },+ readSkillContent,+ ],+ [+ 'skillhub:list-children',+ { dirPath: '/repo/.pi/skills/authorized/demo' },+ listSkillFolderChildren,+ ],+ [+ 'skillhub:read-sibling-file',+ { filePath: '/repo/.pi/skills/authorized/demo/notes.md' },+ readSkillSiblingFile,+ ],+ [+ 'skillhub:read-raw',+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },+ readSkillRawFile,+ ],+ [+ 'skillhub:write-file',+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md', content: '# Demo' },+ writeSkillFile,+ ],+ [+ 'skillhub:rename-local',+ { absolutePath: '/repo/.pi/skills/authorized/demo', newName: 'renamed' },+ renameLocalSkill,+ ],] as const;for (const [channel, params, delegated] of calls) {await handlers.get(channel)?.({ sender }, params);- if (channel === 'skillhub:rename-local') expect(delegated).toHaveBeenCalledWith(params, expect.any(Function));+ if (channel === 'skillhub:rename-local')+ expect(delegated).toHaveBeenCalledWith(params, expect.any(Function));else expect(delegated).toHaveBeenCalledWith(params);}@@ -350,13 +443,19 @@ describe('registerSkillhubIpc usage handlers', () => {{ sender: { id: 22 } },{ filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },);- expect(wrongSender).toMatchObject({ success: false, error: expect.stringContaining('latest SkillHub scan') });+ expect(wrongSender).toMatchObject({+ success: false,+ error: expect.stringContaining('latest SkillHub scan'),+ });const unscannedPath = await handlers.get('skillhub:write-file')?.({ sender },{ filePath: '/other/.pi/skills/unscanned/SKILL.md', content: '# Injected' },);- expect(unscannedPath).toMatchObject({ success: false, error: expect.stringContaining('latest SkillHub scan') });+ expect(unscannedPath).toMatchObject({+ success: false,+ error: expect.stringContaining('latest SkillHub scan'),+ });scanAllSkills.mockRejectedValueOnce(new Error('scan failed'));await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });@@ -377,60 +476,94 @@ describe('registerSkillhubIpc usage handlers', () => {it('grants read-only access to a Main-attested built-in with no discovery alias', async () => {const builtInRoot = path.join(fixtureRoot, 'shared-system-skills', 'learn');const builtInFile = path.join(builtInRoot, 'SKILL.md');+ const builtInNotes = path.join(builtInRoot, 'notes.md');fs.mkdirSync(builtInRoot, { recursive: true });fs.writeFileSync(builtInFile, '# Learn\n');+ fs.writeFileSync(builtInNotes, 'notes\n');+ const attestedRoot = fs.realpathSync.native(builtInRoot);const sender = { id: 18, on: vi.fn(), once: vi.fn() };resolveExistingSkillPathForGrant.mockReturnValue(null);isExistingSkillPathGranted.mockReturnValue(false);scanAllSkills.mockResolvedValueOnce({- skills: [{- id: 'builtin:learn',- kind: 'skill',- name: 'learn',- absolutePath: builtInRoot,- discoveredPath: builtInRoot,- discoveryPaths: [builtInRoot],- scope: 'global',- builtIn: true,- }],+ skills: [+ {+ id: 'builtin:learn',+ kind: 'skill',+ name: 'learn',+ absolutePath: builtInRoot,+ discoveredPath: builtInRoot,+ discoveryPaths: [builtInRoot],+ scope: 'global',+ builtIn: true,+ },+ ],sources: [],});readSkillContent.mockResolvedValue({ success: true, content: 'Learn' });+ listSkillFolderChildren.mockResolvedValue({ success: true, entries: [] });+ readSkillSiblingFile.mockResolvedValue({ success: true, content: 'notes' });+ readSkillRawFile.mockResolvedValue({ success: true, content: '# Learn\n' });const { registerSkillhubIpc } = await import('../registerIpc');registerSkillhubIpc({getMaker: () => ({ listAgentSkills }) as never,getManagedSkillRoots,- getBuiltInSkills: () => [{- name: 'learn',- absolutePath: builtInRoot,- nativeClaudePath: '/tmp/claude-home/skills/learn',- }],+ getBuiltInSkills: () => [+ {+ name: 'learn',+ absolutePath: builtInRoot,+ nativeClaudePath: '/tmp/claude-home/skills/learn',+ },+ ],getAllowedProjectRoots,marketService: marketService as never,publishService: { publish, cancel } as never,});await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });- await expect(handlers.get('skillhub:read-skill')?.(- { sender },- { mdPath: builtInFile },- )).resolves.toMatchObject({ success: true, content: 'Learn' });- expect(readSkillContent).toHaveBeenCalledWith({ mdPath: builtInFile });+ await expect(+ handlers.get('skillhub:read-skill')?.({ sender }, { mdPath: builtInFile }),+ ).resolves.toMatchObject({ success: true, content: 'Learn' });+ await handlers.get('skillhub:list-children')?.({ sender }, { dirPath: builtInRoot });+ await handlers.get('skillhub:read-sibling-file')?.({ sender }, { filePath: builtInNotes });+ await handlers.get('skillhub:read-raw')?.({ sender }, { filePath: builtInFile });+ expect(readSkillContent).toHaveBeenCalledWith({ mdPath: builtInFile, attestedRoot });+ expect(listSkillFolderChildren).toHaveBeenCalledWith({+ dirPath: builtInRoot,+ attestedRoot,+ });+ expect(readSkillSiblingFile).toHaveBeenCalledWith({+ filePath: builtInNotes,+ attestedRoot,+ });+ expect(readSkillRawFile).toHaveBeenCalledWith({+ filePath: builtInFile,+ attestedRoot,+ });- await expect(handlers.get('skillhub:write-file')?.(- { sender },- { filePath: builtInFile, content: '# changed' },- )).resolves.toMatchObject({ success: false, error: expect.stringContaining('read-only') });+ await expect(+ handlers.get('skillhub:write-file')?.(+ { sender },+ { filePath: builtInFile, content: '# changed' },+ ),+ ).resolves.toMatchObject({ success: false, error: expect.stringContaining('read-only') });expect(writeSkillFile).not.toHaveBeenCalled();});it.each(['unchanged', 'grant-wait', 'mutation-wait', 'boundary-pending'] as const)(- 'guards local rename at its original owner generation: %s', async (transition) => {+ 'guards local rename at its original owner generation: %s',+ async (transition) => {const sender = { id: 71, on: vi.fn(), once: vi.fn() };- scanAllSkills.mockResolvedValueOnce({ skills: [{- absolutePath: '/physical/demo', discoveredPath: '/repo/.pi/skills/authorized/demo',- scope: 'project', projectRoot: '/repo',- }], sources: [] });+ scanAllSkills.mockResolvedValueOnce({+ skills: [+ {+ absolutePath: '/physical/demo',+ discoveredPath: '/repo/.pi/skills/authorized/demo',+ scope: 'project',+ projectRoot: '/repo',+ },+ ],+ sources: [],+ });await handlers.get('skillhub:scan')!({ sender }, { projects: [] });const mutate = vi.fn();renameLocalSkill.mockImplementationOnce(async (_params, canMutate: () => boolean) => {@@ -440,13 +573,18 @@ describe('registerSkillhubIpc usage handlers', () => {mutate();return { success: true, newAbsolutePath: '/physical/renamed' };});- if (transition === 'grant-wait') getAllowedProjectRoots.mockImplementationOnce(async () => {- ownerState.generation += 1;- return ['/repo'];- });- const result = await handlers.get('skillhub:rename-local')!({ sender }, {- absolutePath: '/repo/.pi/skills/authorized/demo', newName: 'renamed',- });+ if (transition === 'grant-wait')+ getAllowedProjectRoots.mockImplementationOnce(async () => {+ ownerState.generation += 1;+ return ['/repo'];+ });+ const result = await handlers.get('skillhub:rename-local')!(+ { sender },+ {+ absolutePath: '/repo/.pi/skills/authorized/demo',+ newName: 'renamed',+ },+ );expect(result).toMatchObject({ success: transition === 'unchanged' });expect(mutate).toHaveBeenCalledTimes(transition === 'unchanged' ? 1 : 0);if (transition === 'grant-wait') {@@ -458,12 +596,14 @@ describe('registerSkillhubIpc usage handlers', () => {it('revokes project scan grants after the last active project session disappears', async () => {const sender = { id: 12, on: vi.fn(), once: vi.fn() };scanAllSkills.mockResolvedValueOnce({- skills: [{- absolutePath: '/physical/demo',- discoveredPath: '/repo/.pi/skills/authorized/demo',- scope: 'project',- projectRoot: '/repo',- }],+ skills: [+ {+ absolutePath: '/physical/demo',+ discoveredPath: '/repo/.pi/skills/authorized/demo',+ scope: 'project',+ projectRoot: '/repo',+ },+ ],sources: [],});readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });@@ -472,36 +612,43 @@ describe('registerSkillhubIpc usage handlers', () => {{ sender },{ projects: [{ projectRoot: '/repo', hash: 'repo' }] },);- await expect(handlers.get('skillhub:read-raw')?.(- { sender },- { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },- )).resolves.toMatchObject({ success: true });+ await expect(+ handlers.get('skillhub:read-raw')?.(+ { sender },+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },+ ),+ ).resolves.toMatchObject({ success: true });getAllowedProjectRoots.mockResolvedValue([]);- await expect(handlers.get('skillhub:read-raw')?.(- { sender },- { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },- )).resolves.toMatchObject({ success: false });+ await expect(+ handlers.get('skillhub:read-raw')?.(+ { sender },+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },+ ),+ ).resolves.toMatchObject({ success: false });expect(readSkillRawFile).toHaveBeenCalledTimes(1);});it('does not let an older concurrent scan overwrite the latest sender grant', async () => {let resolveOlder!: (value: unknown) => void;let resolveNewer!: (value: unknown) => void;- const older = new Promise((resolve) => { resolveOlder = resolve; });- const newer = new Promise((resolve) => { resolveNewer = resolve; });- scanAllSkills- .mockReturnValueOnce(older)- .mockReturnValueOnce(newer);+ const older = new Promise((resolve) => {+ resolveOlder = resolve;+ });+ const newer = new Promise((resolve) => {+ resolveNewer = resolve;+ });+ scanAllSkills.mockReturnValueOnce(older).mockReturnValueOnce(newer);resolveExistingSkillPathForGrant.mockImplementation((candidate: string) => {if (candidate.includes('/old-skill')) return '/physical/old-skill';if (candidate.includes('/new-skill')) return '/physical/new-skill';return null;});- isExistingSkillPathGranted.mockImplementation((candidate: string, roots: Set<string>) => (- (candidate.includes('/old-skill') && roots.has('/physical/old-skill'))- || (candidate.includes('/new-skill') && roots.has('/physical/new-skill'))- ));+ isExistingSkillPathGranted.mockImplementation(+ (candidate: string, roots: Set<string>) =>+ (candidate.includes('/old-skill') && roots.has('/physical/old-skill')) ||+ (candidate.includes('/new-skill') && roots.has('/physical/new-skill')),+ );readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });const sender = { id: 33, on: vi.fn(), once: vi.fn() };const scan = handlers.get('skillhub:scan');@@ -509,54 +656,70 @@ describe('registerSkillhubIpc usage handlers', () => {const olderRequest = scan?.({ sender }, { projects: [{ projectRoot: '/old', hash: 'old' }] });const newerRequest = scan?.({ sender }, { projects: [{ projectRoot: '/new', hash: 'new' }] });resolveNewer({- skills: [{ absolutePath: '/physical/new-skill', discoveredPath: '/new/.pi/skills/new-skill' }],+ skills: [+ { absolutePath: '/physical/new-skill', discoveredPath: '/new/.pi/skills/new-skill' },+ ],sources: [],});await newerRequest;resolveOlder({- skills: [{ absolutePath: '/physical/old-skill', discoveredPath: '/old/.pi/skills/old-skill' }],+ skills: [+ { absolutePath: '/physical/old-skill', discoveredPath: '/old/.pi/skills/old-skill' },+ ],sources: [],});await olderRequest;- await expect(handlers.get('skillhub:read-raw')?.(- { sender },- { filePath: '/new/.pi/skills/new-skill/SKILL.md' },- )).resolves.toMatchObject({ success: true });- await expect(handlers.get('skillhub:read-raw')?.(- { sender },- { filePath: '/old/.pi/skills/old-skill/SKILL.md' },- )).resolves.toMatchObject({ success: false });+ await expect(+ handlers.get('skillhub:read-raw')?.(+ { sender },+ { filePath: '/new/.pi/skills/new-skill/SKILL.md' },+ ),+ ).resolves.toMatchObject({ success: true });+ await expect(+ handlers.get('skillhub:read-raw')?.(+ { sender },+ { filePath: '/old/.pi/skills/old-skill/SKILL.md' },+ ),+ ).resolves.toMatchObject({ success: false });});it('revokes a sender scan grant when the active data owner changes', async () => {const sender = { id: 34, on: vi.fn(), once: vi.fn() };scanAllSkills.mockResolvedValueOnce({- skills: [{- absolutePath: '/physical/demo',- discoveredPath: '/repo/.pi/skills/authorized/demo',- }],+ skills: [+ {+ absolutePath: '/physical/demo',+ discoveredPath: '/repo/.pi/skills/authorized/demo',+ },+ ],sources: [],});readSkillRawFile.mockResolvedValue({ success: true, content: 'raw' });await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });- await expect(handlers.get('skillhub:read-raw')?.(- { sender },- { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },- )).resolves.toMatchObject({ success: true });+ await expect(+ handlers.get('skillhub:read-raw')?.(+ { sender },+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },+ ),+ ).resolves.toMatchObject({ success: true });getCurrentDataOwnerId.mockReturnValue('local-v2');- await expect(handlers.get('skillhub:read-raw')?.(- { sender },- { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },- )).resolves.toMatchObject({ success: false });+ await expect(+ handlers.get('skillhub:read-raw')?.(+ { sender },+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },+ ),+ ).resolves.toMatchObject({ success: false });getCurrentDataOwnerId.mockReturnValue('local-v1');- await expect(handlers.get('skillhub:read-raw')?.(- { sender },- { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },- )).resolves.toMatchObject({ success: false });+ await expect(+ handlers.get('skillhub:read-raw')?.(+ { sender },+ { filePath: '/repo/.pi/skills/authorized/demo/SKILL.md' },+ ),+ ).resolves.toMatchObject({ success: false });});it('rejects renderer-provided project roots outside Main-owned active projects', async () => {@@ -689,9 +852,7 @@ describe('registerSkillhubIpc usage handlers', () => {const readyClient = { id: 'ready-client' };const firstSnapshot = { client: firstClient, userId: 'local-v1', clientEpoch: 1 };const readySnapshot = { client: readyClient, userId: 'local-v1', clientEpoch: 2 };- getCurrentDbClientSnapshot- .mockReturnValueOnce(firstSnapshot)- .mockReturnValue(readySnapshot);+ getCurrentDbClientSnapshot.mockReturnValueOnce(firstSnapshot).mockReturnValue(readySnapshot);getLocalSkillUsageSummary.mockRejectedValueOnce(new Error('localDb not ready: pending')).mockResolvedValueOnce({ success: true, summary: { totalUseCount: 1 }, refreshing: false });@@ -763,7 +924,10 @@ describe('registerSkillhubIpc usage handlers', () => {});const handler = handlers.get('skillhub:get-usage-diagnosis-context');- const result = await handler?.({}, { name: 'word-doc', mdPath: 'C:\\skills\\word-doc\\SKILL.md' });+ const result = await handler?.(+ {},+ { name: 'word-doc', mdPath: 'C:\\skills\\word-doc\\SKILL.md' },+ );expect(readSkillRawFile).toHaveBeenCalledWith({ filePath: 'C:\\skills\\word-doc\\SKILL.md' });expect(getLocalSkillUsageDiagnosisContext).toHaveBeenCalledWith({@@ -855,12 +1019,23 @@ describe('registerSkillhubIpc usage handlers', () => {fs.writeFileSync(path.join(source, 'SKILL.md'), 'local skill');const absolutePath = fs.realpathSync.native(source);getAllowedProjectRoots.mockResolvedValue([project]);- scanAllSkills.mockResolvedValue({ skills: [{- kind: 'skill', scope: 'project', name: 'local', absolutePath,- discoveredPath: source, projectRoot: project,- }], sources: [] });+ scanAllSkills.mockResolvedValue({+ skills: [+ {+ kind: 'skill',+ scope: 'project',+ name: 'local',+ absolutePath,+ discoveredPath: source,+ projectRoot: project,+ },+ ],+ sources: [],+ });const event = { sender: { id: 71, on: vi.fn(), once: vi.fn() } };- await handlers.get('skillhub:scan')!(event, { projects: [{ projectRoot: project, hash: 'fixture' }] });+ await handlers.get('skillhub:scan')!(event, {+ projects: [{ projectRoot: project, hash: 'fixture' }],+ });return { event, absolutePath, project };}@@ -868,27 +1043,36 @@ describe('registerSkillhubIpc usage handlers', () => {const root = fs.mkdtempSync(path.join(fixtureRoot, 'shared-aliases-'));const projects = [path.join(root, 'project-a'), path.join(root, 'project-b')];const source = physicalProjectSkill- ? path.join(projects[0]!, '.agents', 'skills', 'foo') : path.join(root, 'external', 'foo');+ ? path.join(projects[0]!, '.agents', 'skills', 'foo')+ : path.join(root, 'external', 'foo');fs.mkdirSync(source, { recursive: true });fs.writeFileSync(path.join(source, 'SKILL.md'), 'fixture');const absolutePath = fs.realpathSync.native(source);- const aliases = [path.join(root, 'home', '.agents', 'skills', 'global-alias'),- ...projects.map((project) => path.join(project, '.agents', 'skills', 'project-alias'))];+ const aliases = [+ path.join(root, 'home', '.agents', 'skills', 'global-alias'),+ ...projects.map((project) => path.join(project, '.agents', 'skills', 'project-alias')),+ ];for (const alias of aliases) {fs.mkdirSync(path.dirname(alias), { recursive: true });fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');}const records = aliases.map((alias, index) => ({- id: `entry-${index}`, kind: 'skill', name: 'foo', absolutePath,+ id: `entry-${index}`,+ kind: 'skill',+ name: 'foo',+ absolutePath,scope: index === 0 ? 'global' : 'project',- discoveredPath: alias, discoveryPaths: [alias],+ discoveredPath: alias,+ discoveryPaths: [alias],...(index > 0 ? { projectRoot: projects[index - 1] } : {}),}));if (physicalProjectSkill) records[1]!.discoveryPaths.push(source);getAllowedProjectRoots.mockResolvedValue(projects);scanAllSkills.mockResolvedValue({ skills: records, sources: [] });const event = { sender: { id: 71, on: vi.fn(), once: vi.fn() } };- await handlers.get('skillhub:scan')!(event, { projects: projects.map((projectRoot, index) => ({ projectRoot, hash: `p${index}` })) });+ await handlers.get('skillhub:scan')!(event, {+ projects: projects.map((projectRoot, index) => ({ projectRoot, hash: `p${index}` })),+ });return { absolutePath, aliases, records, projects, event };}@@ -896,70 +1080,125 @@ describe('registerSkillhubIpc usage handlers', () => {const { absolutePath, aliases, projects, event } = await scanSharedAliases(false);installServiceMocks.uninstall.mockResolvedValueOnce({ success: true });await handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-2' });- expect(installServiceMocks.uninstall).toHaveBeenCalledWith(absolutePath,- expect.objectContaining({ operationPath: aliases[2], aliases: [aliases[2]], linkOnly: true }), expect.any(Function));- await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'unknown' }))- .rejects.toThrow('PRECONDITION_FAILED');+ expect(installServiceMocks.uninstall).toHaveBeenCalledWith(+ absolutePath,+ expect.objectContaining({ operationPath: aliases[2], aliases: [aliases[2]], linkOnly: true }),+ expect.any(Function),+ );+ await expect(+ handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'unknown' }),+ ).rejects.toThrow('PRECONDITION_FAILED');getAllowedProjectRoots.mockResolvedValue([projects[0]]);- await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-2' }))- .rejects.toThrow('PERMISSION_DENIED');- await expect(handlers.get('skillhub:set-enabled')!(event, { absolutePath, skillId: 'entry-2', enabled: false }))- .rejects.toThrow('PERMISSION_DENIED');+ await expect(+ handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-2' }),+ ).rejects.toThrow('PERMISSION_DENIED');+ await expect(+ handlers.get('skillhub:set-enabled')!(event, {+ absolutePath,+ skillId: 'entry-2',+ enabled: false,+ }),+ ).rejects.toThrow('PERMISSION_DENIED');});it('persists discovered aliases across scopes when disabling a physical Skill', async () => {const { absolutePath, aliases, event } = await scanSharedAliases(false);- await handlers.get('skillhub:set-enabled')!(event, { absolutePath, skillId: 'entry-2', enabled: false });- expect(setCindySkillEnabled).toHaveBeenCalledWith(absolutePath, false, expect.any(Function), aliases);+ await handlers.get('skillhub:set-enabled')!(event, {+ absolutePath,+ skillId: 'entry-2',+ enabled: false,+ });+ expect(setCindySkillEnabled).toHaveBeenCalledWith(+ absolutePath,+ false,+ expect.any(Function),+ aliases,+ );});it('captures differently named discovery links across scopes for physical Skill removal', async () => {const { absolutePath, aliases, event } = await scanSharedAliases(true);installServiceMocks.uninstall.mockResolvedValueOnce({ success: true });await handlers.get('skillhub:uninstall')!(event, { absolutePath, skillId: 'entry-1' });- expect(installServiceMocks.uninstall).toHaveBeenCalledWith(absolutePath,- expect.objectContaining({ operationPath: absolutePath, aliases: expect.arrayContaining(aliases), linkOnly: false }), expect.any(Function));+ expect(installServiceMocks.uninstall).toHaveBeenCalledWith(+ absolutePath,+ expect.objectContaining({+ operationPath: absolutePath,+ aliases: expect.arrayContaining(aliases),+ linkOnly: false,+ }),+ expect.any(Function),+ );});it('requires native confirmation for direct uninstall and never mutates on cancellation', async () => {const { event, absolutePath } = await scanLocalFixture();showMessageBox.mockResolvedValueOnce({ response: 1 });- expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath }))- .toEqual({ success: false, errorCode: 'CANCELLED', message: '' });+ expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({+ success: false,+ errorCode: 'CANCELLED',+ message: '',+ });expect(installServiceMocks.uninstall).not.toHaveBeenCalled();- expect(showMessageBox).toHaveBeenCalledWith(expect.any(Object), expect.objectContaining({- defaultId: 1, cancelId: 1, detail: expect.stringContaining(absolutePath),- }));+ expect(showMessageBox).toHaveBeenCalledWith(+ expect.any(Object),+ expect.objectContaining({+ defaultId: 1,+ cancelId: 1,+ detail: expect.stringContaining(absolutePath),+ }),+ );});- it.each(['owner', 'reload', 'source', 'project'])('revokes confirmation when %s changes while native dialog is open', async (change) => {- const { event, absolutePath } = await scanLocalFixture();- let approve!: (value: { response: number }) => void;- showMessageBox.mockImplementationOnce(() => new Promise((resolve) => { approve = resolve; }));- const pending = handlers.get('skillhub:uninstall')!(event, { absolutePath });- const rejected = expect(pending).rejects.toThrow();- await vi.waitFor(() => expect(showMessageBox).toHaveBeenCalledOnce());- expect(installServiceMocks.uninstall).not.toHaveBeenCalled();- if (change === 'owner') getCurrentDataOwnerId.mockReturnValue('another-owner');- if (change === 'project') getAllowedProjectRoots.mockResolvedValue([]);- if (change === 'reload') event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation');- if (change === 'source') {- fs.renameSync(absolutePath, `${absolutePath}-old`);- fs.mkdirSync(absolutePath);- fs.writeFileSync(path.join(absolutePath, 'SKILL.md'), 'replacement');- }- approve({ response: 0 });- await rejected;- expect(installServiceMocks.uninstall).not.toHaveBeenCalled();- });+ it.each(['owner', 'reload', 'source', 'project'])(+ 'revokes confirmation when %s changes while native dialog is open',+ async (change) => {+ const { event, absolutePath } = await scanLocalFixture();+ let approve!: (value: { response: number }) => void;+ showMessageBox.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ approve = resolve;+ }),+ );+ const pending = handlers.get('skillhub:uninstall')!(event, { absolutePath });+ const rejected = expect(pending).rejects.toThrow();+ await vi.waitFor(() => expect(showMessageBox).toHaveBeenCalledOnce());+ expect(installServiceMocks.uninstall).not.toHaveBeenCalled();+ if (change === 'owner') getCurrentDataOwnerId.mockReturnValue('another-owner');+ if (change === 'project') getAllowedProjectRoots.mockResolvedValue([]);+ if (change === 'reload')+ event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation');+ if (change === 'source') {+ fs.renameSync(absolutePath, `${absolutePath}-old`);+ fs.mkdirSync(absolutePath);+ fs.writeFileSync(path.join(absolutePath, 'SKILL.md'), 'replacement');+ }+ approve({ response: 0 });+ await rejected;+ expect(installServiceMocks.uninstall).not.toHaveBeenCalled();+ },+ );it('does not queue repeated native uninstall dialogs from one renderer', async () => {const { event, absolutePath } = await scanLocalFixture();let cancel!: (value: { response: number }) => void;- showMessageBox.mockImplementationOnce(() => new Promise((resolve) => { cancel = resolve; }));+ showMessageBox.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ cancel = resolve;+ }),+ );const pending = handlers.get('skillhub:uninstall')!(event, { absolutePath });await vi.waitFor(() => expect(showMessageBox).toHaveBeenCalledOnce());- await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath })).rejects.toThrow('PRECONDITION_FAILED');+ await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath })).rejects.toThrow(+ 'PRECONDITION_FAILED',+ );expect(showMessageBox).toHaveBeenCalledOnce();cancel({ response: 1 });await pending;@@ -967,65 +1206,119 @@ describe('registerSkillhubIpc usage handlers', () => {it('refreshes the Codex cwd cache after uninstalling a granted project skill', async () => {const { event, absolutePath, project } = await scanLocalFixture();- installServiceMocks.uninstall.mockResolvedValueOnce({ success: true, projectWorkingDir: project });+ installServiceMocks.uninstall.mockResolvedValueOnce({+ success: true,+ projectWorkingDir: project,+ });listAgentSkills.mockResolvedValueOnce({ skills: [] });- expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({ success: true });- expect(listAgentSkills).toHaveBeenCalledWith('codex', { workingDir: project, forceReload: true });- expect(installServiceMocks.uninstall).toHaveBeenCalledWith(absolutePath,- expect.objectContaining({ sourcePath: absolutePath, linkOnly: false }), expect.any(Function));+ expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({+ success: true,+ });+ expect(listAgentSkills).toHaveBeenCalledWith('codex', {+ workingDir: project,+ forceReload: true,+ });+ expect(installServiceMocks.uninstall).toHaveBeenCalledWith(+ absolutePath,+ expect.objectContaining({ sourcePath: absolutePath, linkOnly: false }),+ expect.any(Function),+ );});it('allows toggling an unregistered local Skill and rejects another renderer', async () => {const { event, absolutePath } = await scanLocalFixture();const handler = handlers.get('skillhub:set-enabled')!;expect(await handler(event, { absolutePath, enabled: false })).toEqual({ cindyEnabled: false });- expect(setCindySkillEnabled).toHaveBeenCalledWith(absolutePath, false, expect.any(Function), expect.any(Array));- await expect(handler({ sender: { id: 72 } }, { absolutePath, enabled: false }))- .rejects.toThrow('PRECONDITION_FAILED');+ expect(setCindySkillEnabled).toHaveBeenCalledWith(+ absolutePath,+ false,+ expect.any(Function),+ expect.any(Array),+ );+ await expect(handler({ sender: { id: 72 } }, { absolutePath, enabled: false })).rejects.toThrow(+ 'PRECONDITION_FAILED',+ );expect(setCindySkillEnabled).toHaveBeenCalledTimes(1);});- it.each(['destroyed', 'reload'] as const)('revokes window cleanup grants and reissues them after a fresh scan (%s)', async (lifecycle) => {- const { event, absolutePath } = await scanLocalFixture();- installServiceMocks.uninstall.mockResolvedValueOnce({ success: true, cleanupToken: 'receipt' });- await handlers.get('skillhub:uninstall')!(event, { absolutePath });- if (lifecycle === 'destroyed') {- event.sender.once.mock.calls.find(([name]) => name === 'destroyed')![1]();- } else {- event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation');- }- await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).rejects.toThrow('PRECONDITION_FAILED');- expect(installServiceMocks.retryUninstallCleanup).not.toHaveBeenCalled();- installServiceMocks.listPendingUninstallCleanups.mockReturnValue([{ token: 'receipt', name: 'example' }]);- installServiceMocks.retryUninstallCleanup.mockResolvedValueOnce(true);- expect(await handlers.get('skillhub:scan')!(event, {})).toMatchObject({- success: true, pendingCleanups: [{ token: 'receipt', name: 'example' }],- });- expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({ complete: true });- });+ it.each(['destroyed', 'reload'] as const)(+ 'revokes window cleanup grants and reissues them after a fresh scan (%s)',+ async (lifecycle) => {+ const { event, absolutePath } = await scanLocalFixture();+ installServiceMocks.uninstall.mockResolvedValueOnce({+ success: true,+ cleanupToken: 'receipt',+ });+ await handlers.get('skillhub:uninstall')!(event, { absolutePath });+ if (lifecycle === 'destroyed') {+ event.sender.once.mock.calls.find(([name]) => name === 'destroyed')![1]();+ } else {+ event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation');+ }+ await expect(+ handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt'),+ ).rejects.toThrow('PRECONDITION_FAILED');+ expect(installServiceMocks.retryUninstallCleanup).not.toHaveBeenCalled();+ installServiceMocks.listPendingUninstallCleanups.mockReturnValue([+ { token: 'receipt', name: 'example' },+ ]);+ installServiceMocks.retryUninstallCleanup.mockResolvedValueOnce(true);+ expect(await handlers.get('skillhub:scan')!(event, {})).toMatchObject({+ success: true,+ pendingCleanups: [{ token: 'receipt', name: 'example' }],+ });+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({+ complete: true,+ });+ },+ );it('issues independent recovery grants to two scanned windows and rejects account changes', async () => {const { event } = await scanLocalFixture();const second = { sender: { id: event.sender.id + 1, once: vi.fn(), on: vi.fn() } };- installServiceMocks.listPendingUninstallCleanups.mockReturnValue([{ token: 'receipt', name: 'example' }]);- installServiceMocks.retryUninstallCleanup.mockImplementation(async (_token, canMutate) => canMutate());+ installServiceMocks.listPendingUninstallCleanups.mockReturnValue([+ { token: 'receipt', name: 'example' },+ ]);+ installServiceMocks.retryUninstallCleanup.mockImplementation(async (_token, canMutate) =>+ canMutate(),+ );await handlers.get('skillhub:scan')!(event, {});await handlers.get('skillhub:scan')!(second, {});- expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({ complete: true });- expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(second, 'receipt')).toEqual({ complete: true });+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).toEqual({+ complete: true,+ });+ expect(await handlers.get('skillhub:retry-uninstall-cleanup')!(second, 'receipt')).toEqual({+ complete: true,+ });await handlers.get('skillhub:scan')!(event, {});getCurrentDataOwnerId.mockReturnValue('other-owner');- await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt')).rejects.toThrow('PRECONDITION_FAILED');+ await expect(+ handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'receipt'),+ ).rejects.toThrow('PRECONDITION_FAILED');});it('withholds a late cleanup receipt when its window reloads during uninstall', async () => {const { event, absolutePath } = await scanLocalFixture();installServiceMocks.uninstall.mockImplementationOnce(async () => {- event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation');+ event.sender.on.mock.calls.find(([name]) => name === 'did-start-navigation');return { success: true, cleanupToken: 'late-receipt' };});- expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({ success: true });- await expect(handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'late-receipt')).rejects.toThrow('PRECONDITION_FAILED');+ expect(await handlers.get('skillhub:uninstall')!(event, { absolutePath })).toEqual({+ success: true,+ });+ await expect(+ handlers.get('skillhub:retry-uninstall-cleanup')!(event, 'late-receipt'),+ ).rejects.toThrow('PRECONDITION_FAILED');});it('rejects direct uninstall of a plugin snapshot even when the scanned UI claims it is removable', async () => {@@ -1037,17 +1330,29 @@ describe('registerSkillhubIpc usage handlers', () => {fs.mkdirSync(path.dirname(alias), { recursive: true });fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');getManagedSkillRoots.mockReturnValue([stateRoot]);- scanAllSkills.mockResolvedValue({ skills: [{- kind: 'skill', scope: 'global', name: 'plugin--skill', canUninstall: true,- absolutePath: source, discoveredPath: alias, discoveryPaths: [alias],- }], sources: [] });+ scanAllSkills.mockResolvedValue({+ skills: [+ {+ kind: 'skill',+ scope: 'global',+ name: 'plugin--skill',+ canUninstall: true,+ absolutePath: source,+ discoveredPath: alias,+ discoveryPaths: [alias],+ },+ ],+ sources: [],+ });const event = { sender: { id: 73, on: vi.fn(), once: vi.fn() } };await handlers.get('skillhub:scan')!(event, {});- await expect(handlers.get('skillhub:uninstall')!(event, { absolutePath: source }))- .rejects.toThrow('PRECONDITION_FAILED');+ await expect(+ handlers.get('skillhub:uninstall')!(event, { absolutePath: source }),+ ).rejects.toThrow('PRECONDITION_FAILED');expect(installServiceMocks.uninstall).not.toHaveBeenCalled();- await expect(handlers.get('skillhub:set-enabled')!(event, { absolutePath: source, enabled: false }))- .rejects.toThrow('PRECONDITION_FAILED');+ await expect(+ handlers.get('skillhub:set-enabled')!(event, { absolutePath: source, enabled: false }),+ ).rejects.toThrow('PRECONDITION_FAILED');expect(setCindySkillEnabled).not.toHaveBeenCalled();expect(fs.existsSync(alias)).toBe(true);getManagedSkillRoots.mockReturnValue([]);diff --git a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanner.test.tsindex c84f68a73c..c9834317cf 100644--- a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts@@ -57,16 +57,7 @@ function createSymlinkedSkill() {fs.mkdirSync(path.dirname(exposedDir), { recursive: true });fs.writeFileSync(path.join(actualDir, 'SKILL.md'),- [- '---',- 'name: lark-drive',- '---',- '',- '# Lark Drive',- '',- 'Original content',- '',- ].join('\n'),+ ['---', 'name: lark-drive', '---', '', '# Lark Drive', '', 'Original content', ''].join('\n'),'utf-8',);fs.mkdirSync(path.join(actualDir, 'references'));@@ -87,26 +78,52 @@ describe('scanAllSkills', () => {tempRoots.push(root);const builtIn = path.join(root, 'user-data', 'system-skills', 'cindy-skill-creator');const userSkill = path.join(root, 'home', '.agents', 'skills', 'cindy-skill-creator');- for (const [skillPath, description] of [[builtIn, 'Cindy copy'], [userSkill, 'User copy']] as const) {+ for (const [skillPath, description] of [+ [builtIn, 'Cindy copy'],+ [userSkill, 'User copy'],+ ] as const) {fs.mkdirSync(skillPath, { recursive: true });- fs.writeFileSync(path.join(skillPath, 'SKILL.md'), `---\nname: cindy-skill-creator\ndescription: ${description}\n---\nBody\n`);+ fs.writeFileSync(+ path.join(skillPath, 'SKILL.md'),+ `---\nname: cindy-skill-creator\ndescription: ${description}\n---\nBody\n`,+ );}- const maker = { listCustomizations: vi.fn(async () => ({ errors: [], items: [{- engine: 'codex' as const,- kind: 'skill',- scope: 'user',- name: 'cindy-skill-creator',- description: 'User copy',- absolutePath: userSkill,- mdPath: path.join(userSkill, 'SKILL.md'),- files: [],- }] })) } as unknown as Maker;+ const maker = {+ listCustomizations: vi.fn(async () => ({+ errors: [],+ items: [+ {+ engine: 'codex' as const,+ kind: 'skill',+ scope: 'user',+ name: 'cindy-skill-creator',+ description: 'User copy',+ absolutePath: userSkill,+ mdPath: path.join(userSkill, 'SKILL.md'),+ files: [],+ },+ ],+ })),+ } as unknown as Maker;- const result = await scanAllSkills({}, maker, [], [{- name: 'cindy-skill-creator',- absolutePath: builtIn,- nativeClaudePath: path.join(root, 'user-data', 'claude-home', 'skills', 'cindy-skill-creator'),- }]);+ const result = await scanAllSkills(+ {},+ maker,+ [],+ [+ {+ name: 'cindy-skill-creator',+ absolutePath: builtIn,+ nativeClaudePath: path.join(+ root,+ 'user-data',+ 'claude-home',+ 'skills',+ 'cindy-skill-creator',+ ),+ },+ ],+ );expect(result.skills).toHaveLength(2);expect(result.skills.find((skill) => skill.builtIn)).toMatchObject({@@ -128,7 +145,10 @@ describe('scanAllSkills', () => {tempRoots.push(root);const builtIn = path.join(root, 'shared-system-skills', 'learn');fs.mkdirSync(builtIn, { recursive: true });- fs.writeFileSync(path.join(builtIn, 'SKILL.md'), '---\nname: learn\ndescription: Learn\n---\nBody\n');+ fs.writeFileSync(+ path.join(builtIn, 'SKILL.md'),+ '---\nname: learn\ndescription: Learn\n---\nBody\n',+ );const items = (['codex', 'pi'] as const).map((engine) => ({engine,kind: 'skill' as const,@@ -143,11 +163,18 @@ describe('scanAllSkills', () => {listCustomizations: vi.fn(async () => ({ errors: [], items })),} as unknown as Maker;- const result = await scanAllSkills({}, maker, [], [{- name: 'learn',- absolutePath: builtIn,- nativeClaudePath: path.join(root, 'claude-home', 'skills', 'learn'),- }]);+ const result = await scanAllSkills(+ {},+ maker,+ [],+ [+ {+ name: 'learn',+ absolutePath: builtIn,+ nativeClaudePath: path.join(root, 'claude-home', 'skills', 'learn'),+ },+ ],+ );expect(result.skills).toHaveLength(1);expect(result.skills[0]).toMatchObject({@@ -162,7 +189,10 @@ describe('scanAllSkills', () => {it('projects the registry slug joined by physical path without replacing native directory names', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-registry-slug-'));tempRoots.push(root);- const paths = [path.join(root, '.agents', 'skills', 'Foo'), path.join(root, '.claude', 'skills', 'foo')];+ const paths = [+ path.join(root, '.agents', 'skills', 'Foo'),+ path.join(root, '.claude', 'skills', 'foo'),+ ];for (const skillPath of paths) {fs.mkdirSync(skillPath, { recursive: true });fs.writeFileSync(path.join(skillPath, 'SKILL.md'), '---\nname: fixture\n---\nFixture');@@ -172,16 +202,27 @@ describe('scanAllSkills', () => {{ skillName: 'foo', installPath: paths[0], entry },{ skillName: 'different-skill', installPath: paths[1], entry },]);- const maker = { listCustomizations: vi.fn(async () => ({ errors: [], items: paths.map((absolutePath) => ({- engine: 'claude-code', kind: 'skill', scope: 'user', name: 'fixture', absolutePath,- mdPath: path.join(absolutePath, 'SKILL.md'), files: [],- })) })) } as unknown as Maker;+ const maker = {+ listCustomizations: vi.fn(async () => ({+ errors: [],+ items: paths.map((absolutePath) => ({+ engine: 'claude-code',+ kind: 'skill',+ scope: 'user',+ name: 'fixture',+ absolutePath,+ mdPath: path.join(absolutePath, 'SKILL.md'),+ files: [],+ })),+ })),+ } as unknown as Maker;const result = await scanAllSkills({}, maker);expect(result.skills).toHaveLength(2);for (const [index, skillPath] of paths.entries()) {const physical = fs.realpathSync(skillPath);expect(result.skills.find((skill) => skill.absolutePath === physical)).toMatchObject({- name: path.basename(physical), registryEntry: entry,+ name: path.basename(physical),+ registryEntry: entry,registrySkillName: index === 0 ? 'foo' : 'different-skill',});}@@ -197,10 +238,22 @@ describe('scanAllSkills', () => {fs.mkdirSync(path.dirname(alias), { recursive: true });fs.writeFileSync(path.join(source, 'SKILL.md'), '---\nname: example\n---\nExample');fs.symlinkSync(source, alias, process.platform === 'win32' ? 'junction' : 'dir');- const maker = { listCustomizations: vi.fn(async () => ({ errors: [], items: [{- engine: 'pi', kind: 'skill', scope: 'user', name: 'example', absolutePath: alias,- mdPath: path.join(alias, 'SKILL.md'), files: [],- }] })) } as unknown as Maker;+ const maker = {+ listCustomizations: vi.fn(async () => ({+ errors: [],+ items: [+ {+ engine: 'pi',+ kind: 'skill',+ scope: 'user',+ name: 'example',+ absolutePath: alias,+ mdPath: path.join(alias, 'SKILL.md'),+ files: [],+ },+ ],+ })),+ } as unknown as Maker;const result = await scanAllSkills({}, maker, [stateRoot]);expect(result.skills).toHaveLength(1);expect(result.skills[0]).toMatchObject({ managedByPlugin: true, canUninstall: false });@@ -228,9 +281,12 @@ describe('scanAllSkills', () => {})),} as unknown as Maker;- const result = await scanAllSkills({- projects: [{ projectRoot, hash: 'abcd1234' }],- }, maker);+ const result = await scanAllSkills(+ {+ projects: [{ projectRoot, hash: 'abcd1234' }],+ },+ maker,+ );expect(maker.listCustomizations).toHaveBeenCalledWith({workingDirs: [projectRoot],@@ -310,22 +366,24 @@ describe('scanAllSkills', () => {})),} as unknown as Maker;- const result = await scanAllSkills({- projects: [- { projectRoot: firstRoot, hash: 'first123' },- { projectRoot: secondRoot, hash: 'second456' },- ],- }, maker);+ const result = await scanAllSkills(+ {+ projects: [+ { projectRoot: firstRoot, hash: 'first123' },+ { projectRoot: secondRoot, hash: 'second456' },+ ],+ },+ maker,+ );expect(result.skills).toHaveLength(2);expect(result.skills.map((skill) => skill.projectHash).sort()).toEqual(['first123','second456',]);- expect(result.skills.map((skill) => skill.projectRoot).sort()).toEqual([- firstRoot,- secondRoot,- ].sort());+ expect(result.skills.map((skill) => skill.projectRoot).sort()).toEqual(+ [firstRoot, secondRoot].sort(),+ );});it('maps a canonical scanner workingDir back to the original symlink project root', async () => {@@ -340,23 +398,28 @@ describe('scanAllSkills', () => {const maker = {listCustomizations: vi.fn(async () => ({errors: [],- items: [{- engine: 'pi',- kind: 'skill',- scope: 'repo',- name: 'pi-demo',- absolutePath: skillDir,- mdPath: path.join(skillDir, 'SKILL.md'),- workingDir: canonicalRoot,- runtimeStatus: 'discovered',- files: [],- }],+ items: [+ {+ engine: 'pi',+ kind: 'skill',+ scope: 'repo',+ name: 'pi-demo',+ absolutePath: skillDir,+ mdPath: path.join(skillDir, 'SKILL.md'),+ workingDir: canonicalRoot,+ runtimeStatus: 'discovered',+ files: [],+ },+ ],})),} as unknown as Maker;- const result = await scanAllSkills({- projects: [{ projectRoot, hash: 'linked123' }],- }, maker);+ const result = await scanAllSkills(+ {+ projects: [{ projectRoot, hash: 'linked123' }],+ },+ maker,+ );expect(result.skills[0]).toMatchObject({scope: 'project',@@ -392,18 +455,23 @@ describe('scanAllSkills', () => {})),} as unknown as Maker;- const result = await scanAllSkills({- projects: [- { projectRoot, hash: 'real1234' },- { projectRoot: linkedRoot, hash: 'link5678' },- ],- }, maker);+ const result = await scanAllSkills(+ {+ projects: [+ { projectRoot, hash: 'real1234' },+ { projectRoot: linkedRoot, hash: 'link5678' },+ ],+ },+ maker,+ );- expect(result.skills.map((skill) => skill.projectHash).sort()).toEqual(['link5678', 'real1234']);- expect(result.skills.map((skill) => skill.projectRoot).sort()).toEqual([- linkedRoot,- projectRoot,- ].sort());+ expect(result.skills.map((skill) => skill.projectHash).sort()).toEqual([+ 'link5678',+ 'real1234',+ ]);+ expect(result.skills.map((skill) => skill.projectRoot).sort()).toEqual(+ [linkedRoot, projectRoot].sort(),+ );realpathSyncSpy.mockRestore();});@@ -412,9 +480,12 @@ describe('scanAllSkills', () => {listCustomizations: vi.fn(async () => ({ errors: [], items: [] })),} as unknown as Maker;- await scanAllSkills({- projects: [{ projectRoot: 'relative/project', hash: 'badroot' }],- }, maker);+ await scanAllSkills(+ {+ projects: [{ projectRoot: 'relative/project', hash: 'badroot' }],+ },+ maker,+ );expect(maker.listCustomizations).toHaveBeenCalledWith({workingDirs: [],@@ -491,23 +562,28 @@ describe('scanAllSkills', () => {const maker = {listCustomizations: vi.fn(async () => ({errors: [],- items: [{- engine: 'pi',- kind: 'skill',- scope: 'repo',- name: 'pi-demo',- absolutePath: skillDir,- mdPath: path.join(skillDir, 'SKILL.md'),- workingDir: projectRoot,- runtimeStatus: 'discovered',- files: [],- }],+ items: [+ {+ engine: 'pi',+ kind: 'skill',+ scope: 'repo',+ name: 'pi-demo',+ absolutePath: skillDir,+ mdPath: path.join(skillDir, 'SKILL.md'),+ workingDir: projectRoot,+ runtimeStatus: 'discovered',+ files: [],+ },+ ],})),} as unknown as Maker;- const result = await scanAllSkills({- projects: [{ projectRoot, hash: 'pi123456' }],- }, maker);+ const result = await scanAllSkills(+ {+ projects: [{ projectRoot, hash: 'pi123456' }],+ },+ maker,+ );expect(result.skills[0]).toMatchObject({engine: 'pi',@@ -534,12 +610,63 @@ describe('scanAllSkills', () => {entries: [{ name: 'SKILL.md', kind: 'file' }],});await expect(readSkillRawFile({ filePath: skillMd })).resolves.toMatchObject({ success: true });- await expect(writeSkillFile({ filePath: skillMd, content: '# Updated Pi Demo\n' })).resolves.toEqual({+ await expect(+ writeSkillFile({ filePath: skillMd, content: '# Updated Pi Demo\n' }),+ ).resolves.toEqual({success: true,});expect(fs.readFileSync(skillMd, 'utf-8')).toBe('# Updated Pi Demo\n');});+ it('allows attested built-in reads outside discovery roots without following escaping children', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-attested-built-in-'));+ tempRoots.push(root);+ const builtInRoot = path.join(root, 'shared-system-skills', 'learn');+ const skillMd = path.join(builtInRoot, 'SKILL.md');+ const notes = path.join(builtInRoot, 'notes.txt');+ const outside = path.join(root, 'outside.txt');+ fs.mkdirSync(builtInRoot, { recursive: true });+ fs.writeFileSync(skillMd, '---\nname: learn\n---\n\n# Learn\n', 'utf-8');+ fs.writeFileSync(notes, 'notes\n', 'utf-8');+ fs.writeFileSync(outside, 'private\n', 'utf-8');++ await expect(+ readSkillContent({ mdPath: skillMd, attestedRoot: builtInRoot }),+ ).resolves.toMatchObject({+ success: true,+ content: '\n# Learn\n',+ });+ await expect(+ listSkillFolderChildren({ dirPath: builtInRoot, attestedRoot: builtInRoot }),+ ).resolves.toMatchObject({+ success: true,+ entries: expect.arrayContaining([{ name: 'SKILL.md', kind: 'file' }]),+ });+ await expect(+ readSkillSiblingFile({ filePath: notes, attestedRoot: builtInRoot }),+ ).resolves.toMatchObject({+ success: true,+ content: 'notes\n',+ });+ await expect(+ readSkillRawFile({ filePath: skillMd, attestedRoot: builtInRoot }),+ ).resolves.toMatchObject({+ success: true,+ content: expect.stringContaining('# Learn'),+ });++ if (canLinkFile) {+ const escape = path.join(builtInRoot, 'escape.txt');+ fs.symlinkSync(outside, escape, 'file');+ await expect(+ readSkillSiblingFile({ filePath: escape, attestedRoot: builtInRoot }),+ ).resolves.toMatchObject({+ success: false,+ error: 'path is not under a recognized skills directory',+ });+ }+ });+it('filters sensitive entries from the initial skill files snapshot', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-scan-files-'));tempRoots.push(root);@@ -592,10 +719,12 @@ describe('skill file access', () => {fs.writeFileSync(outsideMd, '# Outside\n', 'utf-8');fs.symlinkSync(outsideMd, exposedMd, 'file');- await expect(writeSkillFile({- filePath: exposedMd,- content: '# Changed\n',- })).resolves.toEqual({+ await expect(+ writeSkillFile({+ filePath: exposedMd,+ content: '# Changed\n',+ }),+ ).resolves.toEqual({success: false,error: 'refusing to write through a symbolic link',});@@ -611,37 +740,48 @@ describe('skill file access', () => {const targetSkill = path.join(skillRoot, 'target');const aliasSkill = path.join(skillRoot, 'alias');fs.mkdirSync(targetSkill, { recursive: true });- fs.writeFileSync(path.join(targetSkill, 'SKILL.md'), '---\nname: target\n---\n# Target\n', 'utf-8');+ fs.writeFileSync(+ path.join(targetSkill, 'SKILL.md'),+ '---\nname: target\n---\n# Target\n',+ 'utf-8',+ );fs.symlinkSync(targetSkill, aliasSkill, process.platform === 'win32' ? 'junction' : 'dir');const maker = {listCustomizations: vi.fn(async () => ({errors: [],- items: [{- engine: 'pi',- kind: 'skill',- scope: 'repo',- name: 'target',- absolutePath: aliasSkill,- mdPath: path.join(aliasSkill, 'SKILL.md'),- workingDir: projectRoot,- runtimeStatus: 'discovered',- files: [],- }],+ items: [+ {+ engine: 'pi',+ kind: 'skill',+ scope: 'repo',+ name: 'target',+ absolutePath: aliasSkill,+ mdPath: path.join(aliasSkill, 'SKILL.md'),+ workingDir: projectRoot,+ runtimeStatus: 'discovered',+ files: [],+ },+ ],})),} as unknown as Maker;- const scanned = await scanAllSkills({- projects: [{ projectRoot, hash: 'pi-alias' }],- }, maker);+ const scanned = await scanAllSkills(+ {+ projects: [{ projectRoot, hash: 'pi-alias' }],+ },+ maker,+ );expect(scanned.skills[0]).toMatchObject({absolutePath: fs.realpathSync(targetSkill),discoveredPath: aliasSkill,});- await expect(renameLocalSkill({- absolutePath: scanned.skills[0].discoveredPath,- newName: 'renamed-alias',- })).resolves.toMatchObject({ success: false });+ await expect(+ renameLocalSkill({+ absolutePath: scanned.skills[0].discoveredPath,+ newName: 'renamed-alias',+ }),+ ).resolves.toMatchObject({ success: false });expect(fs.existsSync(aliasSkill)).toBe(true);expect(fs.existsSync(path.join(skillRoot, 'renamed-alias'))).toBe(false);expect(fs.readFileSync(path.join(targetSkill, 'SKILL.md'), 'utf-8')).toBe(@@ -659,10 +799,12 @@ describe('skill file access', () => {fs.writeFileSync(outsideMd, '---\nname: outside\n---\n# Outside\n', 'utf-8');fs.symlinkSync(outsideMd, path.join(skillDir, 'SKILL.md'), 'file');- await expect(renameLocalSkill({- absolutePath: skillDir,- newName: 'renamed-linked-md',- })).resolves.toMatchObject({ success: false });+ await expect(+ renameLocalSkill({+ absolutePath: skillDir,+ newName: 'renamed-linked-md',+ }),+ ).resolves.toMatchObject({ success: false });expect(fs.existsSync(skillDir)).toBe(true);expect(fs.existsSync(path.join(skillRoot, 'renamed-linked-md'))).toBe(false);expect(fs.readFileSync(outsideMd, 'utf-8')).toBe('---\nname: outside\n---\n# Outside\n');@@ -682,11 +824,21 @@ describe('skill file access', () => {const exposedSkillMd = path.join(exposedSkill, 'SKILL.md');const exposedNotes = path.join(exposedSkill, 'notes.txt');- await expect(readSkillContent({ mdPath: exposedSkillMd })).resolves.toMatchObject({ success: false });- await expect(listSkillFolderChildren({ dirPath: exposedSkill })).resolves.toMatchObject({ success: false });- await expect(readSkillSiblingFile({ filePath: exposedNotes })).resolves.toMatchObject({ success: false });- await expect(readSkillRawFile({ filePath: exposedSkillMd })).resolves.toMatchObject({ success: false });- await expect(writeSkillFile({ filePath: exposedSkillMd, content: '# Changed\n' })).resolves.toMatchObject({ success: false });+ await expect(readSkillContent({ mdPath: exposedSkillMd })).resolves.toMatchObject({+ success: false,+ });+ await expect(listSkillFolderChildren({ dirPath: exposedSkill })).resolves.toMatchObject({+ success: false,+ });+ await expect(readSkillSiblingFile({ filePath: exposedNotes })).resolves.toMatchObject({+ success: false,+ });+ await expect(readSkillRawFile({ filePath: exposedSkillMd })).resolves.toMatchObject({+ success: false,+ });+ await expect(+ writeSkillFile({ filePath: exposedSkillMd, content: '# Changed\n' }),+ ).resolves.toMatchObject({ success: false });expect(fs.readFileSync(path.join(outsideSkill, 'SKILL.md'), 'utf-8')).toBe('# Outside\n');});@@ -704,17 +856,24 @@ describe('skill file access', () => {const exposedSkill = path.join(exposedRoot, '.pi', 'skills', 'escape');const exposedSkillMd = path.join(exposedSkill, 'SKILL.md');- await expect(readSkillContent({ mdPath: exposedSkillMd })).resolves.toMatchObject({ success: false });- await expect(listSkillFolderChildren({ dirPath: exposedSkill })).resolves.toMatchObject({ success: false });- await expect(writeSkillFile({- filePath: exposedSkillMd,- content: '# Changed\n',- })).resolves.toMatchObject({ success: false });+ await expect(readSkillContent({ mdPath: exposedSkillMd })).resolves.toMatchObject({+ success: false,+ });+ await expect(listSkillFolderChildren({ dirPath: exposedSkill })).resolves.toMatchObject({+ success: false,+ });+ await expect(+ writeSkillFile({+ filePath: exposedSkillMd,+ content: '# Changed\n',+ }),+ ).resolves.toMatchObject({ success: false });expect(fs.readFileSync(path.join(nestedSkill, 'SKILL.md'), 'utf-8')).toBe('# Outside\n');});it('follows a supported skill path symlink across detail, files panel, and editor access', async () => {- const { actualSkillMd, exposedDir, exposedPricingJson, exposedSkillMd } = createSymlinkedSkill();+ const { actualSkillMd, exposedDir, exposedPricingJson, exposedSkillMd } =+ createSymlinkedSkill();const grantedRoot = resolveExistingSkillPathForGrant(exposedDir);expect(grantedRoot).toBe(fs.realpathSync.native(exposedDir));@@ -744,15 +903,21 @@ describe('skill file access', () => {content: '{"tier":"internal"}\n',});fs.writeFileSync(path.join(exposedDir, '.env'), 'TOKEN=secret\n', 'utf-8');- await expect(readSkillSiblingFile({ filePath: path.join(exposedDir, '.env') })).resolves.toMatchObject({+ await expect(+ readSkillSiblingFile({ filePath: path.join(exposedDir, '.env') }),+ ).resolves.toMatchObject({success: false,error: 'path is excluded from SkillHub packages',});- await expect(readSkillRawFile({ filePath: path.join(exposedDir, '.env') })).resolves.toMatchObject({+ await expect(+ readSkillRawFile({ filePath: path.join(exposedDir, '.env') }),+ ).resolves.toMatchObject({success: false,error: 'path is excluded from SkillHub packages',});- await expect(writeSkillFile({ filePath: path.join(exposedDir, '.env'), content: 'TOKEN=changed\n' })).resolves.toEqual({+ await expect(+ writeSkillFile({ filePath: path.join(exposedDir, '.env'), content: 'TOKEN=changed\n' }),+ ).resolves.toEqual({success: false,error: 'path is excluded from SkillHub packages',});@@ -761,7 +926,9 @@ describe('skill file access', () => {content: expect.stringContaining('Original content'),});- await expect(writeSkillFile({ filePath: exposedSkillMd, content: '# Updated\n' })).resolves.toEqual({+ await expect(+ writeSkillFile({ filePath: exposedSkillMd, content: '# Updated\n' }),+ ).resolves.toEqual({success: true,});@@ -772,21 +939,41 @@ describe('skill file access', () => {const { exposedDir } = createSymlinkedSkill();fs.writeFileSync(path.join(exposedDir, '.cca-bindings.json'), '{"task":"demo"}\n', 'utf-8');fs.mkdirSync(path.join(exposedDir, '.cca-state', 'task'), { recursive: true });- fs.writeFileSync(path.join(exposedDir, '.cca-state', 'task', 'current-goal.md'), 'goal\n', 'utf-8');+ fs.writeFileSync(+ path.join(exposedDir, '.cca-state', 'task', 'current-goal.md'),+ 'goal\n',+ 'utf-8',+ );fs.writeFileSync(path.join(exposedDir, '.env'), 'TOKEN=secret\n', 'utf-8');fs.writeFileSync(path.join(exposedDir, '.envrc'), 'export TOKEN=secret\n', 'utf-8');fs.writeFileSync(path.join(exposedDir, '.npmrc'), '//registry/:_authToken=secret\n', 'utf-8');- fs.writeFileSync(path.join(exposedDir, '.netrc'), 'machine example.com password secret\n', 'utf-8');+ fs.writeFileSync(+ path.join(exposedDir, '.netrc'),+ 'machine example.com password secret\n',+ 'utf-8',+ );fs.writeFileSync(path.join(exposedDir, '.pypirc'), '[pypi]\npassword=secret\n', 'utf-8');fs.writeFileSync(path.join(exposedDir, '.DS_Store'), 'metadata', 'utf-8');fs.mkdirSync(path.join(exposedDir, '.ssh'), { recursive: true });fs.writeFileSync(path.join(exposedDir, '.ssh', 'id_rsa'), 'private key\n', 'utf-8');fs.mkdirSync(path.join(exposedDir, '.aws'), { recursive: true });- fs.writeFileSync(path.join(exposedDir, '.aws', 'credentials'), 'aws_secret_access_key=secret\n', 'utf-8');+ fs.writeFileSync(+ path.join(exposedDir, '.aws', 'credentials'),+ 'aws_secret_access_key=secret\n',+ 'utf-8',+ );fs.mkdirSync(path.join(exposedDir, '.docker'), { recursive: true });- fs.writeFileSync(path.join(exposedDir, '.docker', 'config.json'), '{"auths":{"example.com":{}}}\n', 'utf-8');+ fs.writeFileSync(+ path.join(exposedDir, '.docker', 'config.json'),+ '{"auths":{"example.com":{}}}\n',+ 'utf-8',+ );fs.mkdirSync(path.join(exposedDir, '.gem'), { recursive: true });- fs.writeFileSync(path.join(exposedDir, '.gem', 'credentials'), ':rubygems_api_key: secret\n', 'utf-8');+ fs.writeFileSync(+ path.join(exposedDir, '.gem', 'credentials'),+ ':rubygems_api_key: secret\n',+ 'utf-8',+ );fs.mkdirSync(path.join(exposedDir, '.config', 'gcloud'), { recursive: true });fs.writeFileSync(path.join(exposedDir, '.config', 'gcloud', 'application_default_credentials.json'),@@ -796,11 +983,19 @@ describe('skill file access', () => {fs.mkdirSync(path.join(exposedDir, '.kube'), { recursive: true });fs.writeFileSync(path.join(exposedDir, '.kube', 'config'), 'token: secret\n', 'utf-8');fs.mkdirSync(path.join(exposedDir, '.config', 'gh'), { recursive: true });- fs.writeFileSync(path.join(exposedDir, '.config', 'gh', 'hosts.yml'), 'oauth_token: secret\n', 'utf-8');+ fs.writeFileSync(+ path.join(exposedDir, '.config', 'gh', 'hosts.yml'),+ 'oauth_token: secret\n',+ 'utf-8',+ );fs.mkdirSync(path.join(exposedDir, '.azure'), { recursive: true });fs.writeFileSync(path.join(exposedDir, '.azure', 'accessTokens.json'), '[]\n', 'utf-8');fs.mkdirSync(path.join(exposedDir, '.config', 'tool'), { recursive: true });- fs.writeFileSync(path.join(exposedDir, '.config', 'tool', 'settings.json'), '{"fixture":true}\n', 'utf-8');+ fs.writeFileSync(+ path.join(exposedDir, '.config', 'tool', 'settings.json'),+ '{"fixture":true}\n',+ 'utf-8',+ );fs.mkdirSync(path.join(exposedDir, 'node_modules', 'pkg'), { recursive: true });const result = await listSkillFolderChildren({ dirPath: exposedDir });@@ -825,41 +1020,64 @@ describe('skill file access', () => {]),);- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gcloud') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gcloud') }),+ ).resolves.toMatchObject({success: true,entries: [],});- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.docker') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.docker') }),+ ).resolves.toMatchObject({success: true,entries: [],});- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.gem') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.gem') }),+ ).resolves.toMatchObject({success: true,entries: [],});- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.kube') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.kube') }),+ ).resolves.toMatchObject({success: true,entries: [],});- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gh') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'gh') }),+ ).resolves.toMatchObject({success: true,entries: [],});- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.azure') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.azure') }),+ ).resolves.toMatchObject({success: true,entries: [],});- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config') }),+ ).resolves.toMatchObject({success: true,entries: [{ name: 'tool', kind: 'dir' }],});- await expect(listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'tool') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(exposedDir, '.config', 'tool') }),+ ).resolves.toMatchObject({success: true,entries: [{ name: 'settings.json', kind: 'file' }],});- await expect(readSkillSiblingFile({- filePath: path.join(exposedDir, '.config', 'gcloud', 'application_default_credentials.json'),- })).resolves.toMatchObject({+ await expect(+ readSkillSiblingFile({+ filePath: path.join(+ exposedDir,+ '.config',+ 'gcloud',+ 'application_default_credentials.json',+ ),+ }),+ ).resolves.toMatchObject({success: false,error: 'path is excluded from SkillHub packages',});@@ -876,13 +1094,21 @@ describe('skill file access', () => {'utf-8',);fs.mkdirSync(path.join(commandDir, '.config', 'tool'), { recursive: true });- fs.writeFileSync(path.join(commandDir, '.config', 'tool', 'settings.json'), '{"fixture":true}\n', 'utf-8');+ fs.writeFileSync(+ path.join(commandDir, '.config', 'tool', 'settings.json'),+ '{"fixture":true}\n',+ 'utf-8',+ );- await expect(listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'gcloud') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'gcloud') }),+ ).resolves.toMatchObject({success: true,entries: [],});- await expect(listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'tool') })).resolves.toMatchObject({+ await expect(+ listSkillFolderChildren({ dirPath: path.join(commandDir, '.config', 'tool') }),+ ).resolves.toMatchObject({success: true,entries: [{ name: 'settings.json', kind: 'file' }],});diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.tsindex 50b5cf37fa..12b8acc4c1 100644--- a/apps/desktop/src/main/skillhub/registerIpc.ts+++ b/apps/desktop/src/main/skillhub/registerIpc.ts@@ -2,7 +2,12 @@ import fs from 'node:fs';import { t } from '../i18n.js';import { throwIpcError } from '../utils/ipcValidate';import { setCindySkillEnabled } from './activationPreferences';-import { inspectLocalSkillTarget, isLocalSkillTargetCurrent, isPluginManagedSkillPath, type LocalSkillTarget } from './localSkillTarget';+import {+ inspectLocalSkillTarget,+ isLocalSkillTargetCurrent,+ isPluginManagedSkillPath,+ type LocalSkillTarget,+} from './localSkillTarget';import { tryAcquireSkillInstallLock } from './installLock';import { randomUUID } from 'node:crypto';import path from 'node:path';@@ -10,14 +15,21 @@ import type { Maker } from '@cindy/maker-core';import type { BuiltInSkillDescriptor } from '../maker-host/built-in-skills';import { BrowserWindow, dialog, ipcMain } from 'electron';import { getCurrentDataOwnerId } from '../authManager';-import { activeOwnerScopeKey, getActiveDataOwnerPushStamp, isAppSessionBoundaryPending } from '../appSessionState';+import {+ activeOwnerScopeKey,+ getActiveDataOwnerPushStamp,+ isAppSessionBoundaryPending,+} from '../appSessionState';import { ensureReady as ensureLocalDbReady } from '../localDb';import {getCurrentDbClientSnapshot,type CurrentDbClientSnapshot,} from '../localDb/client/current.js';import { createLogger } from '../logger';-import { assertTrustedAppRendererEvent, isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';+import {+ assertTrustedAppRendererEvent,+ isTrustedAppRendererWindow,+} from '../security/trustedAppRenderer.js';import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';import { isSkillhubCatalogScope } from '../../shared/skillhubCatalog.js';import { computeFolderHashDetailed } from './folderHash';@@ -57,13 +69,15 @@ interface LocalImportGrant {expiresAt: number;}+interface ScannedSkillGrantEntry {+ root: string;+ projectRootKey?: string;+ builtIn?: boolean;+}+interface ScannedSkillGrant {ownerId: string;- entries: Array<{- root: string;- projectRootKey?: string;- builtIn?: boolean;- }>;+ entries: ScannedSkillGrantEntry[];}/** Bound authenticated review reads without changing native/team catalog selection. */@@ -76,10 +90,16 @@ function reviewReadParams(value: unknown, nameField: 'name' | 'slug') {// Existing scan callers may use an empty optional version to request the latest release.const version = params.version === '' ? undefined : params.version;const catalogScope = params.catalogScope;- const validText = (text: unknown): text is string => typeof text === 'string'- && text.trim().length > 0 && text.length <= 128 && !/[\u0000-\u001f\u007f]/.test(text);- if (!validText(slug) || (version !== undefined && !validText(version))- || (catalogScope !== undefined && !isSkillhubCatalogScope(catalogScope))) {+ const validText = (text: unknown): text is string =>+ typeof text === 'string' &&+ text.trim().length > 0 &&+ text.length <= 128 &&+ !/[\u0000-\u001f\u007f]/.test(text);+ if (+ !validText(slug) ||+ (version !== undefined && !validText(version)) ||+ (catalogScope !== undefined && !isSkillhubCatalogScope(catalogScope))+ ) {throwIpcError('INVALID_PARAMS', 'Invalid Skill review request');}return {@@ -152,11 +172,14 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const cleanupGrantKey = (senderId: number, token: string) => `${senderId}:${token}`;const cleanupGrants = new Map<string, { ownerId: string | null; senderId: number }>();const scannedSkillRootsBySender = new Map<number, ScannedSkillGrant>();- const localSkillsBySender = new Map<number, Array<{- skill: import('./scanner').Skill;- target: LocalSkillTarget | null;- physicalIdentity: string;- }>>();+ const localSkillsBySender = new Map<+ number,+ Array<{+ skill: import('./scanner').Skill;+ target: LocalSkillTarget | null;+ physicalIdentity: string;+ }>+ >();const physicalIdentity = (source: string): string => {const st = fs.statSync(source);return JSON.stringify([fs.realpathSync.native(source), st.dev, st.ino]);@@ -164,24 +187,40 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const broadcastLocalChange = () => {for (const win of BrowserWindow.getAllWindows()) {if (!win.isDestroyed()) {- try { win.webContents.send('skillhub:local-state-changed'); } catch { /* Window closed. */ }+ try {+ win.webContents.send('skillhub:local-state-changed');+ } catch {+ /* Window closed. */+ }}}};- const requireLocalSkill = async (event: Electron.IpcMainInvokeEvent, source: string, skillId?: string) => {+ const requireLocalSkill = async (+ event: Electron.IpcMainInvokeEvent,+ source: string,+ skillId?: string,+ ) => {assertTrustedAppRendererEvent(event);- if (typeof source !== 'string' || !path.isAbsolute(source)) throwIpcError('INVALID_PARAMS', 'Invalid Skill');- if (skillId !== undefined && (typeof skillId !== 'string' || !skillId)) throwIpcError('INVALID_PARAMS', 'Invalid Skill identity');+ if (typeof source !== 'string' || !path.isAbsolute(source))+ throwIpcError('INVALID_PARAMS', 'Invalid Skill');+ if (skillId !== undefined && (typeof skillId !== 'string' || !skillId))+ throwIpcError('INVALID_PARAMS', 'Invalid Skill identity');const ownerId = getCurrentDataOwnerId();const grant = scannedSkillRootsBySender.get(event.sender.id);- const record = localSkillsBySender.get(event.sender.id)?.find(({ skill }) =>- skill.absolutePath === source && (skillId === undefined || skill.id === skillId));+ const record = localSkillsBySender+ .get(event.sender.id)+ ?.find(+ ({ skill }) =>+ skill.absolutePath === source && (skillId === undefined || skill.id === skillId),+ );if (!record || !ownerId || grant?.ownerId !== ownerId || isAppSessionBoundaryPending()) {throwIpcError('PRECONDITION_FAILED', 'Refresh the Skill list and retry');}if (record.skill.scope === 'project') {const roots = await options.getAllowedProjectRoots();- if (!roots.some((root) => projectRootKey(root) === projectRootKey(record.skill.projectRoot))) {+ if (+ !roots.some((root) => projectRootKey(root) === projectRootKey(record.skill.projectRoot))+ ) {throwIpcError('PERMISSION_DENIED', 'Project is no longer available');}}@@ -193,7 +232,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {for (const alias of record.skill.discoveryPaths ?? [record.skill.discoveredPath]) {if (physicalIdentity(alias) !== record.physicalIdentity) throw new Error('changed');}- } catch { throwIpcError('PRECONDITION_FAILED', 'Skill source changed; refresh and retry'); }+ } catch {+ throwIpcError('PRECONDITION_FAILED', 'Skill source changed; refresh and retry');+ }return record;};const scanGenerationBySender = new Map<number, number>();@@ -204,14 +245,20 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {if (scanGrantCleanupRegistered.has(event.sender)) return;scanGrantCleanupRegistered.add(event.sender);const revokeWindowGrants = () => {- cleanupGenerationBySender.set(event.sender, (cleanupGenerationBySender.get(event.sender) ?? 0) + 1);+ cleanupGenerationBySender.set(+ event.sender,+ (cleanupGenerationBySender.get(event.sender) ?? 0) + 1,+ );for (const [token, grant] of cleanupGrants) {if (grant.senderId !== event.sender.id) continue;cleanupGrants.delete(token);}scannedSkillRootsBySender.delete(event.sender.id);localSkillsBySender.delete(event.sender.id);- scanGenerationBySender.set(event.sender.id, (scanGenerationBySender.get(event.sender.id) ?? 0) + 1);+ scanGenerationBySender.set(+ event.sender.id,+ (scanGenerationBySender.get(event.sender.id) ?? 0) + 1,+ );};event.sender.once('destroyed', () => {revokeWindowGrants();@@ -230,9 +277,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const entries: ScannedSkillGrant['entries'] = [];const seenEntries = new Set<string>();for (const skill of skills) {- const skillProjectRootKey = skill.scope === 'project'- ? projectRootKey(skill.projectRoot)- : undefined;+ const skillProjectRootKey =+ skill.scope === 'project' ? projectRootKey(skill.projectRoot) : undefined;if (skill.scope === 'project' && !skillProjectRootKey) continue;// discoveredPath preserves an allowed lexical alias when absolutePath was// canonicalized through a parent-directory symlink.@@ -268,9 +314,20 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const records = skills.flatMap((skill) => {if (skill.kind !== 'skill') return [];try {- return [{ skill, physicalIdentity: physicalIdentity(skill.absolutePath),- target: inspectLocalSkillTarget(skill.absolutePath, skill.discoveryPaths ?? [skill.discoveredPath], options.getManagedSkillRoots()) }];- } catch { return []; }+ return [+ {+ skill,+ physicalIdentity: physicalIdentity(skill.absolutePath),+ target: inspectLocalSkillTarget(+ skill.absolutePath,+ skill.discoveryPaths ?? [skill.discoveredPath],+ options.getManagedSkillRoots(),+ ),+ },+ ];+ } catch {+ return [];+ }});const aliasesByIdentity = new Map<string, Set<string>>();for (const record of records) {@@ -288,79 +345,83 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {localSkillsBySender.set(event.sender.id, records);};- const hasScannedSkillGrant = (+ const findScannedSkillGrant = async (event: Electron.IpcMainInvokeEvent,targetPath: string,- ): Promise<boolean> => {+ ): Promise<ScannedSkillGrantEntry | null> => {assertTrustedAppRendererEvent(event);const grant = scannedSkillRootsBySender.get(event.sender.id);const ownerId = getCurrentDataOwnerId();- if (- !grant- || !ownerId- || isAppSessionBoundaryPending()- || grant.ownerId !== ownerId- ) {+ if (!grant || !ownerId || isAppSessionBoundaryPending() || grant.ownerId !== ownerId) {if (grant) scannedSkillRootsBySender.delete(event.sender.id);- return Promise.resolve(false);+ return null;}- const matchingEntries = grant.entries.filter(({ root, builtIn }) => (+ const matchingEntries = grant.entries.filter(({ root, builtIn }) =>builtIn? isSameOrInside(realPathOrResolved(targetPath), root)- : isExistingSkillPathGranted(targetPath, new Set([root]))- ));- if (matchingEntries.length === 0) return Promise.resolve(false);- if (matchingEntries.some(({ projectRootKey: key }) => !key)) return Promise.resolve(true);+ : isExistingSkillPathGranted(targetPath, new Set([root])),+ );+ const globalEntry = matchingEntries.find(({ projectRootKey: key }) => !key);+ if (globalEntry) return globalEntry;- return options.getAllowedProjectRoots()- .then((roots) => {- const allowedKeys = new Set(- roots.map(projectRootKey).filter((key): key is string => key !== null),- );- return matchingEntries.some(({ projectRootKey: key }) => (- key !== undefined && allowedKeys.has(key)- ));- })- .catch(() => false);+ try {+ const roots = await options.getAllowedProjectRoots();+ const allowedKeys = new Set(+ roots.map(projectRootKey).filter((key): key is string => key !== null),+ );+ return (+ matchingEntries.find(+ ({ projectRootKey: key }) => key !== undefined && allowedKeys.has(key),+ ) ?? null+ );+ } catch {+ return null;+ }};const scanGrantDenied = () => ({success: false as const,- error: 'path was not granted by this renderer\'s latest SkillHub scan',+ error: "path was not granted by this renderer's latest SkillHub scan",});const normalizePathForCompare = (value: string): string => {- const withoutWindowsNamespace = process.platform === 'win32'- ? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')- : value;+ const withoutWindowsNamespace =+ process.platform === 'win32'+ ? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')+ : value;const normalized = path.resolve(withoutWindowsNamespace);return process.platform === 'win32' ? normalized.toLowerCase() : normalized;};const realPathOrResolved = (value: string): string => {- try { return normalizePathForCompare(fs.realpathSync.native(value)); }- catch { return normalizePathForCompare(value); }+ try {+ return normalizePathForCompare(fs.realpathSync.native(value));+ } catch {+ return normalizePathForCompare(value);+ }};const isSameOrInside = (candidate: string, root: string): boolean => {const relative = path.relative(root, candidate);- return relative === '' || (- relative !== '..'- && !relative.startsWith(`..${path.sep}`)- && !path.isAbsolute(relative)+ return (+ relative === '' ||+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));};const configuredBuiltInRoot = (source: string): string | null => {const physicalSource = realPathOrResolved(source);- const descriptor = (options.getBuiltInSkills?.() ?? []).find((skill) => (- realPathOrResolved(skill.absolutePath) === physicalSource- ));+ const descriptor = (options.getBuiltInSkills?.() ?? []).find(+ (skill) => realPathOrResolved(skill.absolutePath) === physicalSource,+ );return descriptor ? realPathOrResolved(descriptor.absolutePath) : null;};- const isBuiltInSkillPath = (targetPath: string): boolean => (+ const isBuiltInSkillPath = (targetPath: string): boolean =>(options.getBuiltInSkills?.() ?? []).some((skill) => {const root = realPathOrResolved(skill.absolutePath);- return isSameOrInside(normalizePathForCompare(targetPath), normalizePathForCompare(skill.absolutePath))- || isSameOrInside(realPathOrResolved(targetPath), root);- })- );+ return (+ isSameOrInside(+ normalizePathForCompare(targetPath),+ normalizePathForCompare(skill.absolutePath),+ ) || isSameOrInside(realPathOrResolved(targetPath), root)+ );+ });const sweepLocalImportGrants = () => {const now = Date.now();@@ -397,7 +458,8 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const stampedPayload = { ...payload, ownerStamp: getActiveDataOwnerPushStamp() };for (const win of BrowserWindow.getAllWindows()) {try {- if (isTrustedAppRendererWindow(win)) win.webContents.send('skillhub:publish-progress', stampedPayload);+ if (isTrustedAppRendererWindow(win))+ win.webContents.send('skillhub:publish-progress', stampedPayload);} catch {// Window teardown can race with background scan reconciliation.}@@ -412,9 +474,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {}}};- const publishService = options.publishService ?? new SkillPublishService({- onProgress: broadcastPublishProgress,- });+ const publishService =+ options.publishService ??+ new SkillPublishService({+ onProgress: broadcastPublishProgress,+ });let usageRefreshBroadcastPromise: Promise<void> | null = null;const captureUsageDbSnapshot = (): CurrentDbClientSnapshot => {if (isAppSessionBoundaryPending()) {@@ -427,11 +491,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const assertUsageDbSnapshotCurrent = (snapshot: CurrentDbClientSnapshot): void => {const current = getCurrentDbClientSnapshot();if (- isAppSessionBoundaryPending()- || !current- || current.client !== snapshot.client- || current.clientEpoch !== snapshot.clientEpoch- || current.userId !== snapshot.userId+ isAppSessionBoundaryPending() ||+ !current ||+ current.client !== snapshot.client ||+ current.clientEpoch !== snapshot.clientEpoch ||+ current.userId !== snapshot.userId) {throw new Error('localDb not ready: app session switched during Skill usage query');}@@ -442,15 +506,18 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {usageRefreshBroadcastPromise = promise;void promise.catch((err) => {- log.warn('[skillhub:usage-refresh] failed:', err instanceof Error ? err.message : String(err));+ log.warn(+ '[skillhub:usage-refresh] failed:',+ err instanceof Error ? err.message : String(err),+ );}).finally(() => {const current = getCurrentDbClientSnapshot();if (- !isAppSessionBoundaryPending()- && current?.client === snapshot.client- && current.clientEpoch === snapshot.clientEpoch- && current.userId === snapshot.userId+ !isAppSessionBoundaryPending() &&+ current?.client === snapshot.client &&+ current.clientEpoch === snapshot.clientEpoch &&+ current.userId === snapshot.userId) {broadcastUsageAnalyticsRefreshed();}@@ -463,10 +530,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {// 本 handler 只负责 join registry / 补 SkillhubSkill 字段 (id / projectHash)。ipcMain.handle('skillhub:scan',- async (- event,- params: { projects?: import('./scanner').ProjectInput[] },- ) => {+ async (event, params: { projects?: import('./scanner').ProjectInput[] }) => {assertTrustedAppRendererEvent(event);ensureScanGrantCleanup(event);const scanGeneration = (scanGenerationBySender.get(event.sender.id) ?? 0) + 1;@@ -490,14 +554,17 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {options.getBuiltInSkills?.() ?? [],);if (- scanGenerationBySender.get(event.sender.id) === scanGeneration- && !isAppSessionBoundaryPending()- && getCurrentDataOwnerId() === scanOwnerId+ scanGenerationBySender.get(event.sender.id) === scanGeneration &&+ !isAppSessionBoundaryPending() &&+ getCurrentDataOwnerId() === scanOwnerId) {rememberScannedSkillRoots(event, scanOwnerId, result.skills);const pendingCleanups = installService.listPendingUninstallCleanups();for (const { token } of pendingCleanups) {- cleanupGrants.set(cleanupGrantKey(event.sender.id, token), { ownerId: scanOwnerId, senderId: event.sender.id });+ cleanupGrants.set(cleanupGrantKey(event.sender.id, token), {+ ownerId: scanOwnerId,+ senderId: event.sender.id,+ });}return { success: true, ...result, pendingCleanups };}@@ -513,53 +580,57 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {// Read a single .md's markdown body (frontmatter stripped) for the detail// view. Path validation lives in the scanner module to keep this channel// from devolving into a generic file-read API.- ipcMain.handle(- 'skillhub:read-skill',- async (event, params: { mdPath: string }) => {- if (!await hasScannedSkillGrant(event, params.mdPath)) return scanGrantDenied();- return readSkillContent(params);- },- );+ ipcMain.handle('skillhub:read-skill', async (event, params: { mdPath: string }) => {+ const grant = await findScannedSkillGrant(event, params.mdPath);+ if (!grant) return scanGrantDenied();+ return readSkillContent({+ mdPath: params.mdPath,+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),+ });+ });// Lazy-list children of a subfolder inside a skill. The FILES panel only// ships a one-level-deep listing in the scan result; expanding a folder// calls back into here for its contents.- ipcMain.handle(- 'skillhub:list-children',- async (event, params: { dirPath: string }) => {- if (!await hasScannedSkillGrant(event, params.dirPath)) return scanGrantDenied();- return listSkillFolderChildren(params);- },- );+ ipcMain.handle('skillhub:list-children', async (event, params: { dirPath: string }) => {+ const grant = await findScannedSkillGrant(event, params.dirPath);+ if (!grant) return scanGrantDenied();+ return listSkillFolderChildren({+ dirPath: params.dirPath,+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),+ });+ });// Read a sibling file inside a skill folder for in-pane preview. Used// when the user clicks a non-SKILL.md file in the FILES list.- ipcMain.handle(- 'skillhub:read-sibling-file',- async (event, params: { filePath: string }) => {- if (!await hasScannedSkillGrant(event, params.filePath)) return scanGrantDenied();- return readSkillSiblingFile(params);- },- );+ ipcMain.handle('skillhub:read-sibling-file', async (event, params: { filePath: string }) => {+ const grant = await findScannedSkillGrant(event, params.filePath);+ if (!grant) return scanGrantDenied();+ return readSkillSiblingFile({+ filePath: params.filePath,+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),+ });+ });// ── v0.2.2: in-app md edit ──────────────────────────────────────────────// read-raw returns the file verbatim (frontmatter intact) so the editor// can round-trip without losing YAML. Path whitelist covers all three// kinds (skills / commands / agents) since the editor is opened on a// .md across kind boundaries.- ipcMain.handle(- 'skillhub:read-raw',- async (event, params: { filePath: string }) => {- if (!await hasScannedSkillGrant(event, params.filePath)) return scanGrantDenied();- return readSkillRawFile(params);- },- );+ ipcMain.handle('skillhub:read-raw', async (event, params: { filePath: string }) => {+ const grant = await findScannedSkillGrant(event, params.filePath);+ if (!grant) return scanGrantDenied();+ return readSkillRawFile({+ filePath: params.filePath,+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),+ });+ });// write-file: atomic tmp+rename, file-must-exist (no creation), 1MB cap,// realpath check defends against symlink-out-of-tree. See scanner module.ipcMain.handle('skillhub:write-file',async (event, params: { filePath: string; content: string }) => {- if (!await hasScannedSkillGrant(event, params.filePath)) return scanGrantDenied();+ if (!(await findScannedSkillGrant(event, params.filePath))) return scanGrantDenied();if (isBuiltInSkillPath(params.filePath)) {return { success: false, error: 'Cindy built-in Skills are read-only' };}@@ -586,8 +657,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {'skillhub:rename-local',async (event, params: { absolutePath: string; newName: string }) => {const ownerScope = activeOwnerScopeKey();- const canMutate = () => ownerScope === activeOwnerScopeKey() && !isAppSessionBoundaryPending();- if (!await hasScannedSkillGrant(event, params.absolutePath)) return scanGrantDenied();+ const canMutate = () =>+ ownerScope === activeOwnerScopeKey() && !isAppSessionBoundaryPending();+ if (!(await findScannedSkillGrant(event, params.absolutePath))) return scanGrantDenied();if (isBuiltInSkillPath(params.absolutePath)) {return { success: false, error: 'Cindy built-in Skills are read-only' };}@@ -629,7 +701,10 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {'skillhub:info',async (_event, { name, catalogScope }: { name: string; catalogScope?: unknown }) => {try {- return await marketService.info(name, isSkillhubCatalogScope(catalogScope) ? catalogScope : undefined);+ return await marketService.info(+ name,+ isSkillhubCatalogScope(catalogScope) ? catalogScope : undefined,+ );} catch (err) {const message = err instanceof Error ? err.message : String(err);const code = (err as { code?: string }).code;@@ -648,7 +723,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {return await marketService.getPublishedFiles({name: params.name,...(params.version !== undefined ? { version: params.version } : {}),- ...(isSkillhubCatalogScope(params.catalogScope) ? { catalogScope: params.catalogScope } : {}),+ ...(isSkillhubCatalogScope(params.catalogScope)+ ? { catalogScope: params.catalogScope }+ : {}),});} catch (err) {return skillhubIpcError(err);@@ -658,13 +735,18 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {ipcMain.handle('skillhub:read-published-file',- async (_event, params: { name: string; path: string; version?: string; catalogScope?: unknown }) => {+ async (+ _event,+ params: { name: string; path: string; version?: string; catalogScope?: unknown },+ ) => {try {return await marketService.readPublishedFile({name: params.name,path: params.path,...(params.version !== undefined ? { version: params.version } : {}),- ...(isSkillhubCatalogScope(params.catalogScope) ? { catalogScope: params.catalogScope } : {}),+ ...(isSkillhubCatalogScope(params.catalogScope)+ ? { catalogScope: params.catalogScope }+ : {}),});} catch (err) {return skillhubIpcError(err);@@ -672,29 +754,32 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {},);- ipcMain.handle(- 'skillhub:list-published-versions',- async (event, params: unknown) => {- assertTrustedAppRendererEvent(event);- const { slug, catalogScope } = reviewReadParams(params, 'name');- const ownerScope = activeOwnerScopeKey();- try {- assertReviewOwnerCurrent(ownerScope);- const result = await marketService.listPublishedVersions(slug, catalogScope);- assertReviewOwnerCurrent(ownerScope);- return result;- } catch (err) {- return skillhubIpcError(err);- }- },- );+ ipcMain.handle('skillhub:list-published-versions', async (event, params: unknown) => {+ assertTrustedAppRendererEvent(event);+ const { slug, catalogScope } = reviewReadParams(params, 'name');+ const ownerScope = activeOwnerScopeKey();+ try {+ assertReviewOwnerCurrent(ownerScope);+ const result = await marketService.listPublishedVersions(slug, catalogScope);+ assertReviewOwnerCurrent(ownerScope);+ return result;+ } catch (err) {+ return skillhubIpcError(err);+ }+ });ipcMain.handle('skillhub:update-published',- async (_event, { name, fields }: {- name: string;- fields: Parameters<SkillhubMarketService['updatePublished']>[1];- }) => {+ async (+ _event,+ {+ name,+ fields,+ }: {+ name: string;+ fields: Parameters<SkillhubMarketService['updatePublished']>[1];+ },+ ) => {try {return await marketService.updatePublished(name, fields);} catch (err) {@@ -703,31 +788,31 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {},);- ipcMain.handle(- 'skillhub:delete-published',- async (_event, { name }: { name: string }) => {- try {- return await marketService.deletePublished(name);- } catch (err) {- return skillhubIpcError(err);- }- },- );+ ipcMain.handle('skillhub:delete-published', async (_event, { name }: { name: string }) => {+ try {+ return await marketService.deletePublished(name);+ } catch (err) {+ return skillhubIpcError(err);+ }+ });- ipcMain.handle(- 'skillhub:unpublish-published',- async (_event, { name }: { name: string }) => {- try {- return await marketService.unpublishPublished(name);- } catch (err) {- return skillhubIpcError(err);- }- },- );+ ipcMain.handle('skillhub:unpublish-published', async (_event, { name }: { name: string }) => {+ try {+ return await marketService.unpublishPublished(name);+ } catch (err) {+ return skillhubIpcError(err);+ }+ });ipcMain.handle('skillhub:set-published-visibility',- async (_event, params: Omit<Parameters<SkillhubMarketService['setPublishedVisibility']>[0], 'previousCatalogScope'> & { previousCatalogScope?: unknown }) => {+ async (+ _event,+ params: Omit<+ Parameters<SkillhubMarketService['setPublishedVisibility']>[0],+ 'previousCatalogScope'+ > & { previousCatalogScope?: unknown },+ ) => {try {const { previousCatalogScope, ...fields } = params;return await marketService.setPublishedVisibility({@@ -753,24 +838,21 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {);// 拉当前用户所属一级部门(PublishDialog 打开前触发,按需获取)- ipcMain.handle(- 'skillhub:get-my-depts',- async () => {- log.debug('get-my-depts requested');- try {- const result = await marketService.getMyDepts();- log.debug('get-my-depts succeeded', {- deptCount: result.ids.length,- hasNames: result.names.length > 0,- });- return result;- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- log.warn('get-my-depts failed', message);- return { success: false, error: message, ids: [], names: [] };- }- },- );+ ipcMain.handle('skillhub:get-my-depts', async () => {+ log.debug('get-my-depts requested');+ try {+ const result = await marketService.getMyDepts();+ log.debug('get-my-depts succeeded', {+ deptCount: result.ids.length,+ hasNames: result.names.length > 0,+ });+ return result;+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ log.warn('get-my-depts failed', message);+ return { success: false, error: message, ids: [], names: [] };+ }+ });// Market 分类列表 — 若 broker / 网络不可用,降级空数组ipcMain.handle(@@ -790,37 +872,31 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {);// 拉当前用户所属团队列表(PublishDialog 选多团队可见时触发)- ipcMain.handle(- 'skillhub:list-user-teams',- async () => {- try {- return await marketService.listUserTeams();- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- log.warn('list-user-teams failed', message);- return { success: false, error: message, teams: [] };- }- },- );+ ipcMain.handle('skillhub:list-user-teams', async () => {+ try {+ return await marketService.listUserTeams();+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ log.warn('list-user-teams failed', message);+ return { success: false, error: message, teams: [] };+ }+ });// 查询发布后的安全扫描状态(renderer 轮询用)- ipcMain.handle(- 'skillhub:get-scan-status',- async (event, params: unknown) => {- assertTrustedAppRendererEvent(event);- const request = reviewReadParams(params, 'slug');- const ownerScope = activeOwnerScopeKey();- try {- assertReviewOwnerCurrent(ownerScope);- const result = await marketService.getScanStatus(request);- assertReviewOwnerCurrent(ownerScope);- return result;- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- return { success: false, error: message, status: 'unknown' };- }- },- );+ ipcMain.handle('skillhub:get-scan-status', async (event, params: unknown) => {+ assertTrustedAppRendererEvent(event);+ const request = reviewReadParams(params, 'slug');+ const ownerScope = activeOwnerScopeKey();+ try {+ assertReviewOwnerCurrent(ownerScope);+ const result = await marketService.getScanStatus(request);+ assertReviewOwnerCurrent(ownerScope);+ return result;+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return { success: false, error: message, status: 'unknown' };+ }+ });ipcMain.handle('skillhub:stop-scan-poll', () => {publishService.stopScanPoll();@@ -868,12 +944,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {// 仅查 snapshot 是否存在 — DetailView 状态机判断"hash 不一致但本地无快照"用,// 一次 fs.stat,比上面的 diff IPC 轻得多,适合每次进 detail 都打。- ipcMain.handle(- 'skillhub:has-snapshot',- (_event, { name }: { name: string }) => {- return { success: true, exists: snapshotExists(name) };- },- );+ ipcMain.handle('skillhub:has-snapshot', (_event, { name }: { name: string }) => {+ return { success: true, exists: snapshotExists(name) };+ });// 读取单个 skill 的本地真实使用表现。只返回派生统计;原始 transcript 内容仍留在// Claude/Codex 自己的 JSONL 文件里,不复制进 Cindy DB。@@ -951,16 +1024,17 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {);// 发布 skill(renderer 点"发布"按钮时触发)- ipcMain.handle(- 'skillhub:publish',- async (event, params: PublishParams) => {- assertTrustedAppRendererEvent(event);- if (isBuiltInSkillPath(params.absolutePath)) {- return { success: false as const, errorCode: 'INTERNAL' as const, message: 'Cindy built-in Skills cannot be published' };- }- return publishService.publish(params);- },- );+ ipcMain.handle('skillhub:publish', async (event, params: PublishParams) => {+ assertTrustedAppRendererEvent(event);+ if (isBuiltInSkillPath(params.absolutePath)) {+ return {+ success: false as const,+ errorCode: 'INTERNAL' as const,+ message: 'Cindy built-in Skills cannot be published',+ };+ }+ return publishService.publish(params);+ });// 取消当前发布(renderer 点"取消"时触发)ipcMain.handle('skillhub:cancel-publish', () => {@@ -969,51 +1043,45 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {});// ── Local import (zip / SKILL.md) ────────────────────────────────────────- ipcMain.handle(- 'skillhub:pick-local',- async (event) => {- assertTrustedAppRendererEvent(event);- const owner = BrowserWindow.fromWebContents(event.sender);- if (!owner || owner.isDestroyed()) {- return { success: false, errorCode: 'INTERNAL', message: '无法打开文件选择器' };- }- const picked = await dialog.showOpenDialog(owner, {- properties: ['openFile'],- filters: [{ name: 'Skill package', extensions: ['zip', 'md'] }],- });- const filePath = picked.filePaths[0];- if (picked.canceled || !filePath) {- return { success: true, canceled: true };- }+ ipcMain.handle('skillhub:pick-local', async (event) => {+ assertTrustedAppRendererEvent(event);+ const owner = BrowserWindow.fromWebContents(event.sender);+ if (!owner || owner.isDestroyed()) {+ return { success: false, errorCode: 'INTERNAL', message: '无法打开文件选择器' };+ }+ const picked = await dialog.showOpenDialog(owner, {+ properties: ['openFile'],+ filters: [{ name: 'Skill package', extensions: ['zip', 'md'] }],+ });+ const filePath = picked.filePaths[0];+ if (picked.canceled || !filePath) {+ return { success: true, canceled: true };+ }- const inspected = await importLocalSkill.inspectLocalSkill({ filePath });- if (!inspected.success) return inspected;+ const inspected = await importLocalSkill.inspectLocalSkill({ filePath });+ if (!inspected.success) return inspected;- sweepLocalImportGrants();- makeRoomForLocalImportGrant();- const grantToken = randomUUID();- localImportGrants.set(grantToken, {- filePath,- senderId: event.sender.id,- expiresAt: Date.now() + LOCAL_IMPORT_GRANT_TTL_MS,- });- return {- success: true,- canceled: false,- grantToken,- name: inspected.name,- description: inspected.description,- version: inspected.version,- };- },- );+ sweepLocalImportGrants();+ makeRoomForLocalImportGrant();+ const grantToken = randomUUID();+ localImportGrants.set(grantToken, {+ filePath,+ senderId: event.sender.id,+ expiresAt: Date.now() + LOCAL_IMPORT_GRANT_TTL_MS,+ });+ return {+ success: true,+ canceled: false,+ grantToken,+ name: inspected.name,+ description: inspected.description,+ version: inspected.version,+ };+ });ipcMain.handle('skillhub:import-local',- async (- event,- params: { grantToken?: unknown; installPath?: unknown; force?: unknown },- ) => {+ async (event, params: { grantToken?: unknown; installPath?: unknown; force?: unknown }) => {assertTrustedAppRendererEvent(event);sweepLocalImportGrants();if (@@ -1059,7 +1127,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const publicParams: import('./installService').InstallParams = {name: params.name,...(params.version !== undefined ? { version: params.version } : {}),- ...(isSkillhubCatalogScope(params.catalogScope) ? { catalogScope: params.catalogScope } : {}),+ ...(isSkillhubCatalogScope(params.catalogScope)+ ? { catalogScope: params.catalogScope }+ : {}),...(params.force !== undefined ? { force: params.force } : {}),...(params.installPath !== undefined ? { installPath: params.installPath } : {}),...(params.skipBackup !== undefined ? { skipBackup: params.skipBackup } : {}),@@ -1080,49 +1150,71 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {);// 取消正在进行的 install(按 name 索引)+ ipcMain.handle('skillhub:cancel-install', (_event, { name }: { name: string }) => {+ const ok = installService.cancelInstall(name);+ return { success: ok };+ });+ipcMain.handle(- 'skillhub:cancel-install',- (_event, { name }: { name: string }) => {- const ok = installService.cancelInstall(name);- return { success: ok };+ 'skillhub:set-enabled',+ async (event, params: { absolutePath: string; skillId?: string; enabled: boolean }) => {+ if (typeof params?.enabled !== 'boolean')+ throwIpcError('INVALID_PARAMS', 'Invalid Skill state');+ const record = await requireLocalSkill(event, params.absolutePath, params.skillId);+ const { skill } = record;+ if (+ skill.managedByPlugin ||+ isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Manage this Skill in its plugin');+ }+ const discoveryPaths = (localSkillsBySender.get(event.sender.id) ?? [])+ .filter((item) => item.physicalIdentity === record.physicalIdentity)+ .flatMap((item) => item.skill.discoveryPaths ?? [item.skill.discoveredPath]);+ const ownerId = getCurrentDataOwnerId();+ const canMutate = () => {+ if (+ ownerId !== getCurrentDataOwnerId() ||+ isAppSessionBoundaryPending() ||+ isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())+ )+ return false;+ try {+ return (+ physicalIdentity(skill.absolutePath) === record.physicalIdentity &&+ (skill.discoveryPaths ?? [skill.discoveredPath]).every(+ (alias) => physicalIdentity(alias) === record.physicalIdentity,+ )+ );+ } catch {+ return false;+ }+ };+ const release = tryAcquireSkillInstallLock(skill.name, 'market-uninstall');+ if (!release) throwIpcError('PRECONDITION_FAILED', 'Skill is being changed; retry shortly');+ try {+ await setCindySkillEnabled(skill.absolutePath, params.enabled, canMutate, discoveryPaths);+ } catch {+ throwIpcError('INTERNAL', 'Could not save Skill state; retry');+ } finally {+ release();+ }+ broadcastLocalChange();+ return { cindyEnabled: params.enabled };},);- ipcMain.handle('skillhub:set-enabled', async (event, params: { absolutePath: string; skillId?: string; enabled: boolean }) => {- if (typeof params?.enabled !== 'boolean') throwIpcError('INVALID_PARAMS', 'Invalid Skill state');- const record = await requireLocalSkill(event, params.absolutePath, params.skillId);- const { skill } = record;- if (skill.managedByPlugin || isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())) {- throwIpcError('PRECONDITION_FAILED', 'Manage this Skill in its plugin');- }- const discoveryPaths = (localSkillsBySender.get(event.sender.id) ?? [])- .filter((item) => item.physicalIdentity === record.physicalIdentity)- .flatMap((item) => item.skill.discoveryPaths ?? [item.skill.discoveredPath]);- const ownerId = getCurrentDataOwnerId();- const canMutate = () => {- if (ownerId !== getCurrentDataOwnerId() || isAppSessionBoundaryPending()- || isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots())) return false;- try {- return physicalIdentity(skill.absolutePath) === record.physicalIdentity- && (skill.discoveryPaths ?? [skill.discoveredPath]).every((alias) => physicalIdentity(alias) === record.physicalIdentity);- } catch { return false; }- };- const release = tryAcquireSkillInstallLock(skill.name, 'market-uninstall');- if (!release) throwIpcError('PRECONDITION_FAILED', 'Skill is being changed; retry shortly');- try {- await setCindySkillEnabled(skill.absolutePath, params.enabled, canMutate, discoveryPaths);- } catch { throwIpcError('INTERNAL', 'Could not save Skill state; retry'); }- finally { release(); }- broadcastLocalChange();- return { cindyEnabled: params.enabled };- });-// Main resolves the exact scanned entity; no arbitrary renderer path deletion.ipcMain.handle('skillhub:uninstall',async (event, { absolutePath, skillId }: { absolutePath: string; skillId?: string }) => {const { target, skill } = await requireLocalSkill(event, absolutePath, skillId);- if (skill.builtIn || !target || !isLocalSkillTargetCurrent(target) || isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots())) {+ if (+ skill.builtIn ||+ !target ||+ !isLocalSkillTargetCurrent(target) ||+ isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots())+ ) {throwIpcError('PRECONDITION_FAILED', 'Skill cannot be uninstalled; refresh and retry');}const ownerId = getCurrentDataOwnerId();@@ -1141,28 +1233,53 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {title: t('skillhub.detail.uninstallDialog.title').replace('{{name}}', () => skill.name),message: t('skillhub.detail.uninstallDialog.title').replace('{{name}}', () => skill.name),detail: [- t(target.linkOnly ? 'skillhub.management.unlinkDescription' : 'skillhub.management.trashDescription'),- t(skill.scope === 'project' ? 'skillhub.management.projectScope' : 'skillhub.management.globalScope')- .replace('{{project}}', () => skill.projectRoot ?? ''),- t('skillhub.management.sharedImpact'), target.operationPath,+ t(+ target.linkOnly+ ? 'skillhub.management.unlinkDescription'+ : 'skillhub.management.trashDescription',+ ),+ t(+ skill.scope === 'project'+ ? 'skillhub.management.projectScope'+ : 'skillhub.management.globalScope',+ ).replace('{{project}}', () => skill.projectRoot ?? ''),+ t('skillhub.management.sharedImpact'),+ target.operationPath,].join('\n\n'),- buttons: [t('skillhub.detail.uninstallDialog.confirm'), t('skillhub.detail.uninstallDialog.cancel')],- defaultId: 1, cancelId: 1, noLink: true,+ buttons: [+ t('skillhub.detail.uninstallDialog.confirm'),+ t('skillhub.detail.uninstallDialog.cancel'),+ ],+ defaultId: 1,+ cancelId: 1,+ noLink: true,}));- } catch { throwIpcError('INTERNAL', 'Could not confirm Skill uninstall; retry'); }- finally { uninstallConfirmations.delete(event.sender.id); }+ } catch {+ throwIpcError('INTERNAL', 'Could not confirm Skill uninstall; retry');+ } finally {+ uninstallConfirmations.delete(event.sender.id);+ }if (response !== 0) return { success: false, errorCode: 'CANCELLED', message: '' };const current = await requireLocalSkill(event, absolutePath, skillId);- const approvalCurrent = () => !parent.isDestroyed()- && cleanupGeneration === (cleanupGenerationBySender.get(event.sender) ?? 0)- && ownerId === getCurrentDataOwnerId() && !isAppSessionBoundaryPending();- if (!approvalCurrent() || current.target?.identity !== target.identity- || JSON.stringify(current.target.aliases) !== JSON.stringify(target.aliases)) {+ const approvalCurrent = () =>+ !parent.isDestroyed() &&+ cleanupGeneration === (cleanupGenerationBySender.get(event.sender) ?? 0) &&+ ownerId === getCurrentDataOwnerId() &&+ !isAppSessionBoundaryPending();+ if (+ !approvalCurrent() ||+ current.target?.identity !== target.identity ||+ JSON.stringify(current.target.aliases) !== JSON.stringify(target.aliases)+ ) {throwIpcError('PRECONDITION_FAILED', 'Skill confirmation expired; refresh and retry');}- const result = await installService.uninstall(absolutePath, target,- () => approvalCurrent()- && !isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots()));+ const result = await installService.uninstall(+ absolutePath,+ target,+ () =>+ approvalCurrent() &&+ !isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots()),+ );if (!result.success) {// A failed trash/preparation can still leave durable rollback work.broadcastLocalChange();@@ -1174,9 +1291,15 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {if (!approvalCurrent()) {return { success: true };}- cleanupGrants.set(cleanupGrantKey(event.sender.id, result.cleanupToken), { ownerId, senderId: event.sender.id });+ cleanupGrants.set(cleanupGrantKey(event.sender.id, result.cleanupToken), {+ ownerId,+ senderId: event.sender.id,+ });}- return { success: true, ...(result.cleanupToken ? { cleanupToken: result.cleanupToken } : {}) };+ return {+ success: true,+ ...(result.cleanupToken ? { cleanupToken: result.cleanupToken } : {}),+ };},);@@ -1184,9 +1307,12 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {assertTrustedAppRendererEvent(event);const key = cleanupGrantKey(event.sender.id, token);const grant = cleanupGrants.get(key);- const canMutate = () => !!grant && grant.ownerId === getCurrentDataOwnerId()- && cleanupGrants.get(key) === grant- && grant.senderId === event.sender.id && !isAppSessionBoundaryPending();+ const canMutate = () =>+ !!grant &&+ grant.ownerId === getCurrentDataOwnerId() &&+ cleanupGrants.get(key) === grant &&+ grant.senderId === event.sender.id &&+ !isAppSessionBoundaryPending();if (!canMutate()) throwIpcError('PRECONDITION_FAILED', 'Cleanup is no longer available');const complete = await installService.retryUninstallCleanup(token, canMutate);if (complete) cleanupGrants.delete(key);@@ -1208,7 +1334,13 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {{items,}: {- items: Array<{ name: string; absolutePath: string; version: string; authorId: string; folderHash?: string }>;+ items: Array<{+ name: string;+ absolutePath: string;+ version: string;+ authorId: string;+ folderHash?: string;+ }>;},) => {return reconcileMineRegistry(items);@@ -1216,19 +1348,16 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {);// ── SkillHub Registry IPC(v0.6 重构新增) ────────────────────────────────- ipcMain.handle(- 'skillhub:registry:get-by-name',- async (_event, { name }: { name: string }) => {- try {- const manifest = await registryService.readManifest(name);- return { success: true, manifest };- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- log.error('[skillhub:registry:get-by-name] failed:', err);- return { success: false, error: message };- }- },- );+ ipcMain.handle('skillhub:registry:get-by-name', async (_event, { name }: { name: string }) => {+ try {+ const manifest = await registryService.readManifest(name);+ return { success: true, manifest };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ log.error('[skillhub:registry:get-by-name] failed:', err);+ return { success: false, error: message };+ }+ });}function isLocalDbNotReady(err: unknown): boolean {@@ -1236,7 +1365,9 @@ function isLocalDbNotReady(err: unknown): boolean {return /localDb not ready/i.test(message);}-async function ensureSkillUsageLocalDbReady(): Promise<{ success: true } | { success: false; error: string }> {+async function ensureSkillUsageLocalDbReady(): Promise<+ { success: true } | { success: false; error: string }+> {if (isAppSessionBoundaryPending()) {return { success: false, error: 'localDb not ready: app session is switching' };}diff --git a/apps/desktop/src/main/skillhub/scanner.ts b/apps/desktop/src/main/skillhub/scanner.tsindex 7ee400753f..818a066602 100644--- a/apps/desktop/src/main/skillhub/scanner.ts+++ b/apps/desktop/src/main/skillhub/scanner.ts@@ -118,9 +118,7 @@ export interface Skill {}export type SourceStatus =- | { state: 'ok'; count: number }- | { state: 'missing' }- | { state: 'error'; message: string };+ { state: 'ok'; count: number } | { state: 'missing' } | { state: 'error'; message: string };export interface SourceReport {kind: SkillKind;@@ -179,10 +177,7 @@ function realPathOrNormalized(value: string): string {}function normalizeSkillEntityPath(c: AgentCustomization): AgentCustomization {- if (- c.kind === 'skill' &&- path.basename(c.absolutePath).toLowerCase() === 'skill.md'- ) {+ if (c.kind === 'skill' && path.basename(c.absolutePath).toLowerCase() === 'skill.md') {return {...c,absolutePath: path.dirname(c.absolutePath),@@ -192,7 +187,10 @@ function normalizeSkillEntityPath(c: AgentCustomization): AgentCustomization {return c;}-function filterSkillPackageFileEntries(rootDir: string, entries: SkillFileEntry[]): SkillFileEntry[] {+function filterSkillPackageFileEntries(+ rootDir: string,+ entries: SkillFileEntry[],+): SkillFileEntry[] {return entries.filter((entry) => {const childPath = path.join(rootDir, entry.name);return !isIgnoredSkillPackagePath(skillPackageRelPath(rootDir, childPath, entry.name));@@ -214,9 +212,13 @@ function readBuiltInCustomization(descriptor: BuiltInSkillDescriptor): AgentCust} catch (error) {parseError = error instanceof Error ? error.message : String(error);}- const files = fs.readdirSync(descriptor.absolutePath, { withFileTypes: true })+ const files = fs+ .readdirSync(descriptor.absolutePath, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))- .map((entry) => ({ name: entry.name, kind: entry.isDirectory() ? 'dir' as const : 'file' as const }));+ .map((entry) => ({+ name: entry.name,+ kind: entry.isDirectory() ? ('dir' as const) : ('file' as const),+ }));return {engine: 'claude-code',kind: 'skill',@@ -308,7 +310,10 @@ export async function scanAllSkills(const HIDDEN_SCOPES = new Set(['system', 'admin']);const isBackupPath = (p: string) => /\.bak\.\d+$/.test(path.basename(p));const isGenericPath = (p: string) => /\/\.agents\/skills\//.test(p.replace(/\\/g, '/'));- const seenItems = new Map<string, { winner: AgentCustomization; all: AgentCustomization[]; realPath: string }>();+ const seenItems = new Map<+ string,+ { winner: AgentCustomization; all: AgentCustomization[]; realPath: string }+ >();for (const item of listed.items) {const c = normalizeSkillEntityPath(item);if (HIDDEN_SCOPES.has(c.scope)) continue;@@ -341,10 +346,11 @@ export async function scanAllSkills(// used as fallback cwd. If the workingDir doesn't map to a tracked project,// treat the skill as global — it's effectively user-level.const rawScope = normalizeScope(engine, c.scope);- const scope: SkillScope = (rawScope === 'project' && !projectHash) ? 'global' : rawScope;- const urlKey = scope === 'global'- ? `${c.kind}:global:${canonicalName}`- : `${c.kind}:project:${projectHash}:${canonicalName}`;+ const scope: SkillScope = rawScope === 'project' && !projectHash ? 'global' : rawScope;+ const urlKey =+ scope === 'global'+ ? `${c.kind}:global:${canonicalName}`+ : `${c.kind}:project:${projectHash}:${canonicalName}`;return { c, all, realPath, engine, project, projectHash, canonicalName, scope, urlKey };});const identityCounts = new Map<string, number>();@@ -353,75 +359,75 @@ export async function scanAllSkills(identityCounts.set(identity, (identityCounts.get(identity) ?? 0) + 1);}- const skills: Skill[] = candidates.map(({- c,- all,- realPath,- engine,- project,- projectHash,- canonicalName,- scope,- urlKey,- }) => {- const builtIn = builtInRealPaths.has(realPath);- const hasIdentityCollision = (identityCounts.get(`${engine}:${urlKey}`) ?? 0) > 1;- // Pi entries are new to this SkillHub projection. Give them a path-derived- // identity even when currently unique, so adding/removing a same-name source- // never changes the surviving Pi entry's React/storage identity.- const sourceKey = engine === 'pi' || hasIdentityCollision- ? createHash('sha256').update(realPath).digest('hex')- : undefined;- const id = `${engine}:${urlKey}${sourceKey ? `:source:${sourceKey}` : ''}`;-- const engineSet = new Map<Skill['engine'], Skill['linkedEngines'][number]>();- for (const item of all) {- const eng = item.engine;- if (!engineSet.has(eng)) {- engineSet.set(eng, {- engine: eng,- label: eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : 'Pi',- ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),- });+ const skills: Skill[] = candidates.map(+ ({ c, all, realPath, engine, project, projectHash, canonicalName, scope, urlKey }) => {+ const builtIn = builtInRealPaths.has(realPath);+ const hasIdentityCollision = (identityCounts.get(`${engine}:${urlKey}`) ?? 0) > 1;+ // Pi entries are new to this SkillHub projection. Give them a path-derived+ // identity even when currently unique, so adding/removing a same-name source+ // never changes the surviving Pi entry's React/storage identity.+ const sourceKey =+ engine === 'pi' || hasIdentityCollision+ ? createHash('sha256').update(realPath).digest('hex')+ : undefined;+ const id = `${engine}:${urlKey}${sourceKey ? `:source:${sourceKey}` : ''}`;++ const engineSet = new Map<Skill['engine'], Skill['linkedEngines'][number]>();+ for (const item of all) {+ const eng = item.engine;+ if (!engineSet.has(eng)) {+ engineSet.set(eng, {+ engine: eng,+ label: eng === 'claude-code' ? 'Claude' : eng === 'codex' ? 'Codex' : 'Pi',+ ...(item.runtimeStatus ? { runtimeStatus: item.runtimeStatus } : {}),+ });+ }}- }- const linkedEngines = builtIn- ? Array.from(discoveredEnginesByRealPath.get(realPath)?.values() ?? [])- : Array.from(engineSet.values());-- const skill: Skill = {- id,- urlKey,- ...(sourceKey ? { sourceKey } : {}),- ...(hasIdentityCollision ? { requiresSourceKey: true } : {}),- engine,- linkedEngines,- kind: c.kind as SkillKind,- scope,- name: canonicalName,- description: c.description,- absolutePath: realPath,- discoveredPath: c.absolutePath,- mdPath: c.mdPath ?? realPath,- files: c.kind === 'skill'- ? filterSkillPackageFileEntries(realPath, (c.files ?? []) as SkillFileEntry[])- : [],- frontmatter: c.frontmatter,- parseError: c.parseError,- registryEntry: null, // 下面 join 阶段填- ...(c.kind === 'skill' ? (() => {- const discoveryPaths = [...new Set(all.map((item) => item.absolutePath))];- const target = inspectLocalSkillTarget(realPath, discoveryPaths, managedSkillRoots);- return { cindyEnabled: isCindySkillEnabled(realPath), discoveryPaths,- ...(builtIn ? { builtIn: true } : {}),- managedByPlugin: isPluginManagedSkillPath(realPath, managedSkillRoots),- canUninstall: !builtIn && target !== null, uninstallLinkOnly: target?.linkOnly ?? false };- })() : {}),- ...(project ? { projectRoot: project.projectRoot } : {}),- ...(projectHash ? { projectHash } : {}),- };- return skill;- });+ const linkedEngines = builtIn+ ? Array.from(discoveredEnginesByRealPath.get(realPath)?.values() ?? [])+ : Array.from(engineSet.values());++ const skill: Skill = {+ id,+ urlKey,+ ...(sourceKey ? { sourceKey } : {}),+ ...(hasIdentityCollision ? { requiresSourceKey: true } : {}),+ engine,+ linkedEngines,+ kind: c.kind as SkillKind,+ scope,+ name: canonicalName,+ description: c.description,+ absolutePath: realPath,+ discoveredPath: c.absolutePath,+ mdPath: c.mdPath ?? realPath,+ files:+ c.kind === 'skill'+ ? filterSkillPackageFileEntries(realPath, (c.files ?? []) as SkillFileEntry[])+ : [],+ frontmatter: c.frontmatter,+ parseError: c.parseError,+ registryEntry: null, // 下面 join 阶段填+ ...(c.kind === 'skill'+ ? (() => {+ const discoveryPaths = [...new Set(all.map((item) => item.absolutePath))];+ const target = inspectLocalSkillTarget(realPath, discoveryPaths, managedSkillRoots);+ return {+ cindyEnabled: isCindySkillEnabled(realPath),+ discoveryPaths,+ ...(builtIn ? { builtIn: true } : {}),+ managedByPlugin: isPluginManagedSkillPath(realPath, managedSkillRoots),+ canUninstall: !builtIn && target !== null,+ uninstallLinkOnly: target?.linkOnly ?? false,+ };+ })()+ : {}),+ ...(project ? { projectRoot: project.projectRoot } : {}),+ ...(projectHash ? { projectHash } : {}),+ };+ return skill;+ },+ );// ── join registry ──────────────────────────────────────────────────────────let registryEntries: Awaited<ReturnType<typeof registryService.listAllInstalls>>;@@ -466,10 +472,12 @@ export async function scanAllSkills(// Maintenance uses the same mutation protocol as install/uninstall and// revalidates each registry/source snapshot after acquiring the lease.- void Promise.all(registryEntries.map((record) => {- const key = path.normalize(record.installPath);- return reconcileScannedInstall(record, !liveRealPaths.has(registryLiveKeys.get(key) ?? key));- }));+ void Promise.all(+ registryEntries.map((record) => {+ const key = path.normalize(record.installPath);+ return reconcileScannedInstall(record, !liveRealPaths.has(registryLiveKeys.get(key) ?? key));+ }),+ );// ── sources[] 兼容 (renderer 只存不读) ─────────────────────────────────────const sources: SourceReport[] = listed.errors.map((e) => ({@@ -488,12 +496,12 @@ export async function scanAllSkills(* `.claude/{skills,commands,agents}/` layout so the IPC can't be coerced* into a generic file reader.*/-export async function readSkillContent(params: { mdPath: string }): Promise<{+export async function readSkillContent(params: { mdPath: string; attestedRoot?: string }): Promise<{success: boolean;content?: string;error?: string;}> {- const { mdPath } = params;+ const { mdPath, attestedRoot } = params;if (!mdPath || !path.isAbsolute(mdPath)) {return { success: false, error: 'mdPath must be an absolute path' };}@@ -504,11 +512,11 @@ export async function readSkillContent(params: { mdPath: string }): Promise<{return { success: false, error: 'only .md files may be read via this channel' };}- const resolvedMdPath = resolveAllowedExistingSkillPath(mdPath);+ const resolvedMdPath = resolveReadableExistingSkillPath(mdPath, attestedRoot);if (!resolvedMdPath) {return { success: false, error: 'path is not under a recognized skills directory' };}- if (isIgnoredSkillFilePath(mdPath)) {+ if (isIgnoredSkillFilePath(attestedRoot ? resolvedMdPath : mdPath, attestedRoot)) {return { success: false, error: 'path is excluded from SkillHub packages' };}@@ -535,23 +543,26 @@ export async function readSkillContent(params: { mdPath: string }): Promise<{*/const PREVIEW_SIZE_CAP = 1024 * 1024; // 1 MB-export async function readSkillSiblingFile(params: { filePath: string }): Promise<{+export async function readSkillSiblingFile(params: {+ filePath: string;+ attestedRoot?: string;+}): Promise<{success: boolean;content?: string;error?: string;}> {- const { filePath } = params;+ const { filePath, attestedRoot } = params;if (!filePath || !path.isAbsolute(filePath)) {return { success: false, error: 'filePath must be an absolute path' };}- const resolvedFilePath = resolveAllowedExistingSkillPath(filePath);+ const resolvedFilePath = resolveReadableExistingSkillPath(filePath, attestedRoot);if (!resolvedFilePath) {return { success: false, error: 'path is not under a recognized skills directory' };}try {- if (isIgnoredSkillFilePath(filePath)) {+ if (isIgnoredSkillFilePath(attestedRoot ? resolvedFilePath : filePath, attestedRoot)) {return { success: false, error: 'path is excluded from SkillHub packages' };}@@ -560,7 +571,10 @@ export async function readSkillSiblingFile(params: { filePath: string }): Promisreturn { success: false, error: 'path is not a file' };}if (stat.size > PREVIEW_SIZE_CAP) {- return { success: false, error: `文件超过 ${Math.round(PREVIEW_SIZE_CAP / 1024)} KB,无法在面板中预览` };+ return {+ success: false,+ error: `文件超过 ${Math.round(PREVIEW_SIZE_CAP / 1024)} KB,无法在面板中预览`,+ };}const content = fs.readFileSync(resolvedFilePath, 'utf-8');return { success: true, content };@@ -579,17 +593,20 @@ export async function readSkillSiblingFile(params: { filePath: string }): Promis* — only paths within a skill folder are accepted, so commands / agents* (single .md files) can't trigger directory traversal here.*/-export async function listSkillFolderChildren(params: { dirPath: string }): Promise<{+export async function listSkillFolderChildren(params: {+ dirPath: string;+ attestedRoot?: string;+}): Promise<{success: boolean;entries?: SkillFileEntry[];error?: string;}> {- const { dirPath } = params;+ const { dirPath, attestedRoot } = params;if (!dirPath || !path.isAbsolute(dirPath)) {return { success: false, error: 'dirPath must be an absolute path' };}- const resolvedDirPath = resolveAllowedExistingSkillPath(dirPath);+ const resolvedDirPath = resolveReadableExistingSkillPath(dirPath, attestedRoot);if (!resolvedDirPath) {return { success: false, error: 'path is not under a recognized skills directory' };}@@ -599,11 +616,14 @@ export async function listSkillFolderChildren(params: { dirPath: string }): Promif (!stat.isDirectory()) {return { success: false, error: 'path is not a directory' };}- const skillRoot = findSkillRootForPath(dirPath);+ const listedDirPath = attestedRoot ? resolvedDirPath : dirPath;+ const skillRoot = attestedRoot+ ? fs.realpathSync.native(attestedRoot)+ : findSkillRootForPath(dirPath);const entries: SkillFileEntry[] = fs.readdirSync(resolvedDirPath, { withFileTypes: true }).filter((s) => {- const childPath = path.join(dirPath, s.name);+ const childPath = path.join(listedDirPath, s.name);return !isIgnoredSkillPackagePath(skillPackageRelPath(skillRoot, childPath, s.name));}).map((s) => ({@@ -628,12 +648,13 @@ export async function listSkillFolderChildren(params: { dirPath: string }): Prom// readSkillContent for view (frontmatter stripped) and readRawFile here for// edit (frontmatter intact). Writes are gated by SKILL_PATH_WHITELIST.-const EDIT_SIZE_CAP_READ = 256 * 1024; // 256 KB read cap (matches detail-view edit-button gate)+const EDIT_SIZE_CAP_READ = 256 * 1024; // 256 KB read cap (matches detail-view edit-button gate)const EDIT_SIZE_CAP_WRITE = 1024 * 1024; // 1 MB write cap (defensive against paste-of-binary)// 统一白名单:所有引擎的 skill/command/agent 目录共用。// 新增引擎时只需在此 regex 加一个分支。-const SKILL_PATH_WHITELIST = /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills|pi\/skills)|codex-home\/skills)\//;+const SKILL_PATH_WHITELIST =+ /\/(\.(claude\/(skills|commands|agents)|agents\/skills|codex\/skills|pi\/skills)|codex-home\/skills)\//;function isLexicallyAllowedSkillPath(absolutePath: string): boolean {// path.resolve 解析 .. 和 . 段,防止遍历绕过白名单@@ -643,10 +664,9 @@ function isLexicallyAllowedSkillPath(absolutePath: string): boolean {function isPathWithin(root: string, candidate: string): boolean {const relative = path.relative(root, candidate);- return relative === '' || (- relative !== '..'- && !relative.startsWith(`..${path.sep}`)- && !path.isAbsolute(relative)+ return (+ relative === '' ||+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)));}@@ -676,16 +696,35 @@ function resolveAllowedExistingSkillPath(absolutePath: string): string | null {try {const realProjectRoot = fs.realpathSync.native(lexicalProjectRoot);const realSkillRoot = fs.realpathSync.native(lexicalSkillRoot);- if (- !isPathWithin(realProjectRoot, realSkillRoot)- || !isPathWithin(realSkillRoot, realTarget)- ) return null;+ if (!isPathWithin(realProjectRoot, realSkillRoot) || !isPathWithin(realSkillRoot, realTarget))+ return null;} catch {return null;}return realTarget;}+/**+ * Read-only built-ins can live outside the user-facing discovery whitelist.+ * Main may pass an attested physical root from the sender's latest scan; keep+ * every final target physically contained by that root so child symlinks+ * cannot turn this into a generic file-read primitive.+ */+function resolveReadableExistingSkillPath(+ absolutePath: string,+ attestedRoot?: string,+): string | null {+ if (!attestedRoot) return resolveAllowedExistingSkillPath(absolutePath);+ if (!path.isAbsolute(attestedRoot)) return null;+ try {+ const realRoot = fs.realpathSync.native(attestedRoot);+ const realTarget = fs.realpathSync.native(path.resolve(absolutePath));+ return isPathWithin(realRoot, realTarget) ? realTarget : null;+ } catch {+ return null;+ }+}+/*** Canonicalize a path previously surfaced by SkillHub discovery for an IPC* grant. This deliberately reuses the same lexical whitelist and physical@@ -711,7 +750,10 @@ export function isExistingSkillPathGranted(function findSkillRootForPath(absolutePath: string): string | null {const norm = path.resolve(absolutePath).replace(/\\/g, '/');- const markerMatch = /\/(?:\.claude\/(?:skills|commands|agents)|\.agents\/skills|\.codex\/skills|\.pi\/skills|codex-home\/skills)\//.exec(norm);+ const markerMatch =+ /\/(?:\.claude\/(?:skills|commands|agents)|\.agents\/skills|\.codex\/skills|\.pi\/skills|codex-home\/skills)\//.exec(+ norm,+ );if (!markerMatch) return null;const afterMarker = norm.slice((markerMatch.index ?? 0) + markerMatch[0].length);@@ -721,23 +763,39 @@ function findSkillRootForPath(absolutePath: string): string | null {return norm.slice(0, (markerMatch.index ?? 0) + markerMatch[0].length) + skillName;}-function skillPackageRelPath(rootDir: string | null, childPath: string, fallbackName: string): string {+function skillPackageRelPath(+ rootDir: string | null,+ childPath: string,+ fallbackName: string,+): string {if (!rootDir) return fallbackName;const rel = path.relative(rootDir, childPath).split(path.sep).join('/');return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : fallbackName;}-function isIgnoredSkillFilePath(filePath: string): boolean {- const skillRoot = findSkillRootForPath(filePath);- return isIgnoredSkillPackagePath(skillPackageRelPath(skillRoot, filePath, path.basename(filePath)));+function isIgnoredSkillFilePath(filePath: string, attestedRoot?: string): boolean {+ let skillRoot = attestedRoot ?? findSkillRootForPath(filePath);+ if (attestedRoot) {+ try {+ skillRoot = fs.realpathSync.native(attestedRoot);+ } catch {+ return true;+ }+ }+ return isIgnoredSkillPackagePath(+ skillPackageRelPath(skillRoot, filePath, path.basename(filePath)),+ );}-export async function readSkillRawFile(params: { filePath: string }): Promise<{+export async function readSkillRawFile(params: {+ filePath: string;+ attestedRoot?: string;+}): Promise<{success: boolean;content?: string;error?: string;}> {- const { filePath } = params;+ const { filePath, attestedRoot } = params;if (!filePath || !path.isAbsolute(filePath)) {return { success: false, error: 'filePath must be an absolute path' };}@@ -745,18 +803,21 @@ export async function readSkillRawFile(params: { filePath: string }): Promise<{if (path.normalize(filePath).split(path.sep).includes('..')) {return { success: false, error: 'filePath contains traversal segments' };}- const resolvedFilePath = resolveAllowedExistingSkillPath(filePath);+ const resolvedFilePath = resolveReadableExistingSkillPath(filePath, attestedRoot);if (!resolvedFilePath) {return { success: false, error: 'path is not under a recognized skills directory' };}- if (isIgnoredSkillFilePath(filePath)) {+ if (isIgnoredSkillFilePath(attestedRoot ? resolvedFilePath : filePath, attestedRoot)) {return { success: false, error: 'path is excluded from SkillHub packages' };}try {const stat = fs.statSync(resolvedFilePath);if (!stat.isFile()) return { success: false, error: 'path is not a file' };if (stat.size > EDIT_SIZE_CAP_READ) {- return { success: false, error: `文件超过 ${Math.round(EDIT_SIZE_CAP_READ / 1024)} KB,请用外部编辑器` };+ return {+ success: false,+ error: `文件超过 ${Math.round(EDIT_SIZE_CAP_READ / 1024)} KB,请用外部编辑器`,+ };}const content = fs.readFileSync(resolvedFilePath, 'utf-8');return { success: true, content };@@ -808,7 +869,10 @@ export async function writeSkillFile(params: { filePath: string; content: string}const byteLen = Buffer.byteLength(content, 'utf-8');if (byteLen > EDIT_SIZE_CAP_WRITE) {- return { success: false, error: `内容超过 ${Math.round(EDIT_SIZE_CAP_WRITE / 1024)} KB,拒绝写入` };+ return {+ success: false,+ error: `内容超过 ${Math.round(EDIT_SIZE_CAP_WRITE / 1024)} KB,拒绝写入`,+ };}// Atomic write: tmp + rename. fsync the tmp file before rename so a crash// mid-write doesn't leave a half-written file at the target path.@@ -825,7 +889,11 @@ export async function writeSkillFile(params: { filePath: string; content: stringreturn { success: true };} catch (err) {// Best-effort tmp cleanup — ignore failures.- try { fs.unlinkSync(tmpPath); } catch { /* noop */ }+ try {+ fs.unlinkSync(tmpPath);+ } catch {+ /* noop */+ }return { success: false, error: err instanceof Error ? err.message : String(err) };}}@@ -838,10 +906,13 @@ export async function writeSkillFile(params: { filePath: string; content: string** 仅支持 kind=skill (folder-shaped). command/agent 是单 .md 文件,本期不需要。*/-export async function renameLocalSkill(params: {- absolutePath: string;- newName: string;-}, canMutate: () => boolean = () => true): Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }> {+export async function renameLocalSkill(+ params: {+ absolutePath: string;+ newName: string;+ },+ canMutate: () => boolean = () => true,+): Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }> {const { absolutePath, newName } = params;if (!absolutePath || !path.isAbsolute(absolutePath)) {@@ -917,7 +988,8 @@ export async function renameLocalSkill(params: {let releaseShared: SkillMutationRelease | null = null;try {releaseShared = await acquireSharedSkillMutationLease([oldName, newName]);- if (!releaseShared) return { success: false, error: 'Skill is busy; retry after the current operation' };+ if (!releaseShared)+ return { success: false, error: 'Skill is busy; retry after the current operation' };await renameSkillWithActivation(absolutePath, newAbsolutePath, () => {if (!canMutate()) throw new Error('Skill mutation context changed');// Recheck after waiting for the preferences lock; never replace a new entity.@@ -926,25 +998,40 @@ export async function renameLocalSkill(params: {throw new Error('Skill changed; refresh and retry');}const currentMd = fs.lstatSync(oldSkillMd);- if (currentMd.isSymbolicLink() || currentMd.dev !== skillMdStat.dev || currentMd.ino !== skillMdStat.ino) {+ if (+ currentMd.isSymbolicLink() ||+ currentMd.dev !== skillMdStat.dev ||+ currentMd.ino !== skillMdStat.ino+ ) {throw new Error('Skill content changed; refresh and retry');}const parsed = matter(fs.readFileSync(oldSkillMd, 'utf-8'));- const data = (parsed.data && typeof parsed.data === 'object' ? parsed.data : {}) as Record<string, unknown>;+ const data = (parsed.data && typeof parsed.data === 'object' ? parsed.data : {}) as Record<+ string,+ unknown+ >;data.name = newName;const next = matter.stringify(parsed.content, data);fs.renameSync(absolutePath, newAbsolutePath);renamed = true;const fd = fs.openSync(tmpPath, 'w');- try { fs.writeSync(fd, next); fs.fsyncSync(fd); }- finally { fs.closeSync(fd); }+ try {+ fs.writeSync(fd, next);+ fs.fsyncSync(fd);+ } finally {+ fs.closeSync(fd);+ }fs.renameSync(newSkillMd, backupPath);backedUp = true;fs.renameSync(tmpPath, newSkillMd);});// packageIgnore excludes this reserved backup from browsing, hashes,// snapshots and ZIPs even if Windows keeps it locked after commit.- try { fs.unlinkSync(backupPath); } catch { /* Do not roll back committed preferences. */ }+ try {+ fs.unlinkSync(backupPath);+ } catch {+ /* Do not roll back committed preferences. */+ }return { success: true, newAbsolutePath };} catch (err) {if (renamed) {@@ -952,10 +1039,17 @@ export async function renameLocalSkill(params: {// Keep the original file until preferences commit, so even a full disk// can roll back with renames instead of writing the contents again.if (backedUp) fs.renameSync(backupPath, newSkillMd);- try { fs.unlinkSync(tmpPath); } catch { /* No staging file after a completed switch. */ }+ try {+ fs.unlinkSync(tmpPath);+ } catch {+ /* No staging file after a completed switch. */+ }fs.renameSync(newAbsolutePath, absolutePath);} catch (rollbackError) {- return { success: false, error: `Skill rename and rollback failed: ${String(rollbackError)}` };+ return {+ success: false,+ error: `Skill rename and rollback failed: ${String(rollbackError)}`,+ };}}return { success: false, error: `Skill rename failed: ${String(err)}` };