Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(skills): align nested discovery with review findings

Zhang Yunjin7db9f6ec65e9
diff --git a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
index fbfa2587d9..79660fb721 100644
--- a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
+++ b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
@@ -154,6 +154,20 @@ describe('prepareSharedGlobalSkillLinks', () => {
expect(await sameRealPath(path.join(paths.claudeSkillsDir, 'nested'), nested)).toBe(true);
});
+ it('prefers a direct Skill over a same-named nested namespace Skill', async () => {
+ const root = await makeTmpDir();
+ const homeDir = path.join(root, 'home');
+ const paths = sharedGlobalSkillsPaths(homeDir);
+ const direct = await writeSkill(paths.sharedSkillsDir, 'same-name');
+ const nested = await writeSkill(paths.sharedSkillsDir, path.join('@scope', 'same-name'));
+
+ const result = await prepareSharedGlobalSkillLinks({ homeDir });
+
+ expect(result.changed).toBe(true);
+ expect(await sameRealPath(path.join(paths.claudeSkillsDir, 'same-name'), direct)).toBe(true);
+ expect(await sameRealPath(path.join(paths.claudeSkillsDir, 'same-name'), nested)).toBe(false);
+ });
+
it('resolves a project root for a nested project Skill path', () => {
const projectRoot = path.join(os.tmpdir(), 'cindy-nested-project-root', 'repo');
const skillPath = path.join(projectRoot, '.agents', 'skills', '@scope', 'nested');
@@ -594,6 +608,35 @@ describe('prepareSharedProjectSkillLinks', () => {
expect(result.warnings.some((warning) => warning.includes('user-link'))).toBe(true);
expect(await fs.readlink(userLink)).toBe(externalTarget);
});
+
+ it('does not treat a deeper broken link as a moved project Skill link', async () => {
+ const root = await makeTmpDir();
+ const workingDir = path.join(root, 'checkout');
+ const paths = sharedProjectSkillsPaths(workingDir);
+ await writeSkill(paths.claudeSkillsDir, 'deep-link');
+ const userLink = path.join(paths.sharedSkillsDir, 'deep-link');
+ const externalTarget = path.join(
+ root,
+ 'archive',
+ '.claude',
+ 'skills',
+ 'group',
+ 'sub',
+ 'deep-link',
+ );
+ await fs.mkdir(paths.sharedSkillsDir, { recursive: true });
+ await fs.symlink(
+ externalTarget,
+ userLink,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+
+ const result = await prepareSharedProjectSkillLinks({ workingDir });
+
+ expect(result.changed).toBe(false);
+ expect(result.warnings.some((warning) => warning.includes('deep-link'))).toBe(true);
+ expect(await fs.readlink(userLink)).toBe(externalTarget);
+ });
});
describe('projectWorkingDirFromSkillPath', () => {
diff --git a/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts b/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts
index 79919f63da..219bad0040 100644
--- a/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts
+++ b/apps/desktop/src/main/learn-host/__tests__/skillsIndex.test.ts
@@ -136,6 +136,40 @@ describe('listInstalledSkills — symlink 跟随', () => {
}
});
+ it('sorts nested Skills deterministically before truncating at the cap', async () => {
+ const fs = await import('node:fs');
+ const path = await import('node:path');
+ const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'learn-skills-idx-cap-'));
+ const root = path.join(tmpHome, '.agents', 'skills');
+ // Two namespaces, created in reverse name order so readdir order cannot be
+ // relied on; 101 entries exercises SKILLS_INDEX_MAX = 100.
+ const names: string[] = [];
+ for (let index = 100; index >= 0; index -= 1) {
+ const name = `skill-${String(index).padStart(3, '0')}`;
+ names.push(name);
+ const dir = path.join(root, index % 2 === 0 ? 'zz-ns' : 'aa-ns', name);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: cap\n---\nBody`,
+ 'utf8',
+ );
+ }
+
+ const homeSpy = vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
+ try {
+ const { listInstalledSkills } = await import('../skillsIndex');
+ const { entries, truncatedCount } = await listInstalledSkills();
+
+ expect(entries).toHaveLength(100);
+ expect(truncatedCount).toBe(1);
+ expect(entries.map((entry) => entry.name)).toEqual(names.sort().slice(0, 100));
+ } finally {
+ homeSpy.mockRestore();
+ fs.rmSync(tmpHome, { recursive: true, force: true });
+ }
+ });
+
it('does not descend through a symlinked namespace', async () => {
const fs = await import('node:fs');
const path = await import('node:path');
diff --git a/apps/desktop/src/main/learn-host/skillsIndex.ts b/apps/desktop/src/main/learn-host/skillsIndex.ts
index 91c56c65e6..bc72040e37 100644
--- a/apps/desktop/src/main/learn-host/skillsIndex.ts
+++ b/apps/desktop/src/main/learn-host/skillsIndex.ts
@@ -117,14 +117,22 @@ export async function listInstalledSkills(): Promise<{ entries: InstalledSkillEn
} catch {
continue;
}
- for (const nested of nestedEntries) {
+ for (const nested of nestedEntries.sort((a, b) => a.name.localeCompare(b.name))) {
if (nested.name.startsWith('.') || /\.bak\.\d+$/.test(nested.name)) continue;
+ // Direct Skills win over nested Skills with the same leaf name; keep the
+ // first namespace when names collide, matching the other scanners.
+ if (skillTargets.some((target) => path.basename(target.dir) === nested.name)) continue;
const nestedPath = path.join(entry.path, nested.name);
if (!(await isDirectoryEntry(nested, nestedPath))) continue;
const nestedSkillFile = await findSkillMd(nestedPath);
if (nestedSkillFile) skillTargets.push({ dir: nestedPath, skillFile: nestedSkillFile });
}
}
+ // Truncation must be deterministic: sort before applying SKILLS_INDEX_MAX.
+ skillTargets.sort((a, b) => {
+ const byName = path.basename(a.dir).localeCompare(path.basename(b.dir));
+ return byName !== 0 ? byName : a.dir.localeCompare(b.dir);
+ });
} catch {
return { entries: [], truncatedCount: 0 };
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts b/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts
index a2f28d6c59..c9d2b8b367 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts
@@ -182,6 +182,31 @@ describe('pi remote file ops command hygiene', () => {
.rejects.toThrow('remote stat returned an invalid response');
});
+ it('lstat classifies symlinks without following them', async () => {
+ const { calls, host } = fakeHost('SYMLINK\n');
+ const ops = createRemotePiFileOps(host);
+
+ await expect(ops.lstat!('/link')).resolves.toEqual({ isSymbolicLink: true });
+ expect(calls[0].cmd).not.toContain('stat -L');
+ expect(calls[0].cmd).toContain('%F');
+ expect(calls[0].cmd).toContain('-- "$P"');
+ });
+
+ it('lstat classifies real entries and missing paths', async () => {
+ const real = fakeHost('OTHER\n');
+ await expect(createRemotePiFileOps(real.host).lstat!('/dir'))
+ .resolves.toEqual({ isSymbolicLink: false });
+
+ const missing = fakeHost('MISSING\n');
+ await expect(createRemotePiFileOps(missing.host).lstat!('/gone')).resolves.toBeNull();
+ });
+
+ it('lstat rejects malformed successful responses', async () => {
+ const { host } = fakeHost('unexpected remote output');
+ await expect(createRemotePiFileOps(host).lstat!('/x'))
+ .rejects.toThrow('remote lstat returned an invalid response');
+ });
+
it('hashes the complete remote file in place without transferring its contents', async () => {
const digest = 'a'.repeat(64);
const { calls, host } = makeHostExec(`${digest}\n`);
diff --git a/apps/desktop/src/main/maker-host/pi-remote-transport.ts b/apps/desktop/src/main/maker-host/pi-remote-transport.ts
index 1c5885bbdc..736d7ae5ed 100644
--- a/apps/desktop/src/main/maker-host/pi-remote-transport.ts
+++ b/apps/desktop/src/main/maker-host/pi-remote-transport.ts
@@ -236,6 +236,47 @@ fi
throw new Error('remote stat returned an invalid response');
},
+ async lstat(file: string): Promise<{ isSymbolicLink: boolean } | null> {
+ // No `-L`: the only question is whether the namespace entry itself is a
+ // link, so a broken link still reports `symbolic link` instead of ENOENT.
+ const script = `
+P=${shellQuote(file)}
+case "$P" in '$HOME'/*) H=$(printf '%s' "$HOME"); [ "\${P#\\$HOME}" != "$P" ] && P="\${H}\${P#\\$HOME}";; esac
+if stat -c '%F' / >/dev/null 2>&1; then
+ RESULT=$(LC_ALL=C stat -c '%F' -- "$P" 2>&1)
+else
+ RESULT=$(LC_ALL=C stat -f '%HT' -- "$P" 2>&1)
+fi
+STATUS=$?
+if [ "$STATUS" -ne 0 ]; then
+ case "$RESULT" in
+ *': No such file or directory') printf 'MISSING\\n' ;;
+ *': Permission denied') printf 'EACCES' >&2; exit 1 ;;
+ *) exit 1 ;;
+ esac
+else
+ case "$RESULT" in
+ 'symbolic link'|'Symbolic Link') printf 'SYMLINK\\n' ;;
+ *) printf 'OTHER\\n' ;;
+ esac
+fi
+`;
+ const result = await remoteHost.exec(`bash -c ${shellQuote(script)}`, {
+ timeoutMs: 10_000,
+ label: 'pi-remote-lstat',
+ });
+ if (result.exitCode !== 0) {
+ const code = result.stderr.trim();
+ const reason = /^E[A-Z0-9]+$/.test(code) ? `: ${code}` : '';
+ throw new Error(`remote lstat failed (exit ${result.exitCode})${reason}`);
+ }
+ const kind = result.stdout.trim();
+ if (kind === 'SYMLINK') return { isSymbolicLink: true };
+ if (kind === 'OTHER') return { isSymbolicLink: false };
+ if (kind === 'MISSING') return null;
+ throw new Error('remote lstat returned an invalid response');
+ },
+
readFile: (file, maxBytes = 1_048_576) => readBounded(file, maxBytes, false),
readFileTail: (file, maxBytes) => readBounded(file, maxBytes, true),
diff --git a/apps/desktop/src/main/maker-host/shared-global-skills.ts b/apps/desktop/src/main/maker-host/shared-global-skills.ts
index 3a7a4998b9..76de0abd1d 100644
--- a/apps/desktop/src/main/maker-host/shared-global-skills.ts
+++ b/apps/desktop/src/main/maker-host/shared-global-skills.ts
@@ -188,6 +188,9 @@ async function listSkillEntries(
return skills;
}
+ // Direct Skills win over nested Skills with the same leaf name, matching the
+ // `/` panel's priority; collect them before walking namespaces.
+ const namespaces: string[] = [];
for (const ent of entries.sort((a, b) => a.name.localeCompare(b.name))) {
if (ent.name.startsWith('.')) continue;
if (/\.bak\.\d+$/.test(ent.name)) continue;
@@ -201,18 +204,22 @@ async function listSkillEntries(
}
// Direct symlinked Skills remain supported; a symlinked namespace is not walked.
if (isSymlink || !ent.isDirectory() || shouldPruneSkillScanDirectory(ent.name)) continue;
+ namespaces.push(skillPath);
+ }
- // At most one namespace/author level: <root>/<namespace>/<skill>.
+ // At most one namespace/author level: <root>/<namespace>/<skill>.
+ for (const namespacePath of namespaces) {
let namespaceEntries;
try {
- namespaceEntries = await fsp.readdir(skillPath, { withFileTypes: true });
+ namespaceEntries = await fsp.readdir(namespacePath, { withFileTypes: true });
} catch {
continue;
}
for (const nested of namespaceEntries.sort((a, b) => a.name.localeCompare(b.name))) {
if (nested.name.startsWith('.')) continue;
if (/\.bak\.\d+$/.test(nested.name)) continue;
- const nestedPath = path.join(skillPath, nested.name);
+ if (skills.some((skill) => skill.name === nested.name)) continue;
+ const nestedPath = path.join(namespacePath, nested.name);
if (!(await hasSkillFile(nestedPath))) continue;
const nestedIsSymlink = nested.isSymbolicLink()
|| (nested.isDirectory() && isSymlinkDirectory(nestedPath));
@@ -240,8 +247,11 @@ function matchesManagedSkillTargetShape(
if (!leaf || !equalsName(leaf, skillName)) return false;
for (let index = 0; index + 2 < segments.length; index += 1) {
const isDiscoveryRoot = discoveryRoots.some((root) => equalsName(segments[index], root));
- // Flat and nested skills both live below `<discovery-root>/skills/<...>/<leaf>`.
- if (isDiscoveryRoot && equalsName(segments[index + 1], 'skills')) return true;
+ if (!isDiscoveryRoot || !equalsName(segments[index + 1], 'skills')) continue;
+ // Only the shapes this module projects: flat `<skills>/<leaf>` and one
+ // namespace level `<skills>/<namespace>/<leaf>`. Deeper paths are not ours.
+ const levelsBelowSkills = segments.length - (index + 2);
+ if (levelsBelowSkills === 1 || levelsBelowSkills === 2) return true;
}
return false;
}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index f4caa86fa8..60d4113c0e 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -256,6 +256,12 @@ export interface PiNativeModelSpec {
*/
export interface RemoteAgentFileOps {
stat(file: string): Promise<{ isFile: boolean } | null>;
+ /**
+ * lstat without following symlinks, used to keep namespace traversal inside
+ * the discovery root. Absent on older hosts; callers must treat a missing
+ * implementation as "cannot verify" and stay conservative.
+ */
+ lstat?(file: string): Promise<{ isSymbolicLink: boolean } | null>;
/** Missing/unreadable directories return an empty array. */
listDir(dir: string): Promise<string[]>;
/** Bounded UTF-8 read used for remote runtime metadata such as SKILL.md. */
diff --git a/packages/maker-core/src/agents/shared/palette-scanner.ts b/packages/maker-core/src/agents/shared/palette-scanner.ts
index 9d36d791df..e3ed4db2fc 100644
--- a/packages/maker-core/src/agents/shared/palette-scanner.ts
+++ b/packages/maker-core/src/agents/shared/palette-scanner.ts
@@ -335,6 +335,9 @@ async function scanClaudeSkillDirs(
&& !/\.bak\.\d+$/.test(entry.name))
.sort((a, b) => a.name.localeCompare(b.name))) {
const nestedDir = path.join(subDir, nested.name);
+ // Direct Skills win over nested Skills with the same leaf name, matching
+ // the Desktop `/` panel; keep the first namespace when names collide.
+ if (results.some((result) => result.name === nested.name)) continue;
const nestedFile = await findSkillFile(nestedDir);
if (nestedFile) await addSkill(nestedDir, nested.name, nestedFile);
}
diff --git a/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts b/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts
index 3ea1024f64..517ee911d1 100644
--- a/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts
+++ b/packages/maker-core/src/agents/shared/remote-skill-scanner.test.ts
@@ -20,6 +20,13 @@ function fakeRemoteFiles(files: Record<string, string>): RemoteAgentFileOps {
.filter(Boolean),
)];
},
+ async lstat(candidate) {
+ if (fileNames.has(candidate)) return { isSymbolicLink: false };
+ const prefix = candidate.endsWith('/') ? candidate : `${candidate}/`;
+ return [...fileNames].some((file) => file.startsWith(prefix))
+ ? { isSymbolicLink: false }
+ : null;
+ },
async readFile(file, maxBytes) {
const value = files[file];
if (value === undefined) throw new Error('missing');
@@ -68,6 +75,45 @@ describe('remote Skill scanners', () => {
expect(claude.skills.map((skill) => skill.name)).toEqual(['claude-nested']);
});
+ it('does not walk a symlinked namespace when the host exposes lstat', async () => {
+ const fileOps: RemoteAgentFileOps = {
+ ...fakeRemoteFiles({
+ '$HOME/.claude/skills/@scope/nested/SKILL.md': '---\ndescription: Nested\n---',
+ }),
+ async lstat(candidate) {
+ return { isSymbolicLink: candidate === '$HOME/.claude/skills/@scope' };
+ },
+ };
+
+ const result = await scanRemoteClaudeSkills({ fileOps });
+
+ expect(result.skills).toEqual([]);
+ });
+
+ it('does not walk namespaces when the host cannot report symlinks', async () => {
+ const fileOps = fakeRemoteFiles({
+ '$HOME/.claude/skills/@scope/nested/SKILL.md': '---\ndescription: Nested\n---',
+ });
+ delete fileOps.lstat;
+
+ const result = await scanRemoteClaudeSkills({ fileOps });
+
+ expect(result.skills).toEqual([]);
+ });
+
+ it('prefers a direct remote Skill over a same-named nested Skill', async () => {
+ const fileOps = fakeRemoteFiles({
+ '$HOME/.claude/skills/same-name/SKILL.md': '---\ndescription: Direct\n---',
+ '$HOME/.claude/skills/@scope/same-name/SKILL.md': '---\ndescription: Nested\n---',
+ });
+
+ const result = await scanRemoteClaudeSkills({ fileOps });
+
+ expect(result.skills).toEqual([
+ expect.objectContaining({ name: 'same-name', description: 'Direct' }),
+ ]);
+ });
+
it('discovers Pi global, project, and ancestor Skills only through the Git boundary', async () => {
const fileOps = fakeRemoteFiles({
'$HOME/.agents/skills/global/SKILL.md': '---\ndescription: Global\n---',
diff --git a/packages/maker-core/src/agents/shared/remote-skill-scanner.ts b/packages/maker-core/src/agents/shared/remote-skill-scanner.ts
index 9483bee7b9..74a96a1859 100644
--- a/packages/maker-core/src/agents/shared/remote-skill-scanner.ts
+++ b/packages/maker-core/src/agents/shared/remote-skill-scanner.ts
@@ -64,6 +64,21 @@ async function existingSkillFile(
return null;
}
+async function isSymlinkedNamespace(
+ fileOps: RemoteAgentFileOps,
+ directory: string,
+): Promise<boolean> {
+ // Older hosts do not expose lstat. Treat an unverifiable namespace as a link
+ // and skip it rather than following it outside the discovery root.
+ if (!fileOps.lstat) return true;
+ try {
+ const stat = await fileOps.lstat(directory);
+ return stat ? stat.isSymbolicLink : true;
+ } catch {
+ return true;
+ }
+}
+
async function scanSkillDirectories(input: {
fileOps: RemoteAgentFileOps;
root: string;
@@ -98,6 +113,7 @@ async function scanSkillDirectories(input: {
continue;
}
if (shouldPruneSkillScanDirectory(name)) continue;
+ if (await isSymlinkedNamespace(input.fileOps, skillDir)) continue;
// At most one namespace/author level: <root>/<namespace>/<skill>.
const nestedNames = (await input.fileOps.listDir(skillDir))
@@ -105,6 +121,9 @@ async function scanSkillDirectories(input: {
&& !/\.bak\.\d+$/.test(nested))
.sort((a, b) => a.localeCompare(b));
for (const nestedName of nestedNames) {
+ // Direct Skills win over nested Skills with the same leaf name; keep the
+ // first namespace when names collide.
+ if (found.some((skill) => skill.name === nestedName)) continue;
const nestedFile = await existingSkillFile(
input.fileOps,
path.posix.join(skillDir, nestedName),