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(plugin): harden manual compatibility checks

fmfsaisaid9313949c414
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 5e69f590d8..919726004c 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -210,7 +210,26 @@ export class GhostManager {
});
continue;
}
- const v = validateGhostManifest(raw);
+ let v = validateGhostManifest(raw);
+ if (
+ !v.ok &&
+ typeof raw === 'object' &&
+ raw !== null &&
+ !Array.isArray(raw) &&
+ Object.prototype.hasOwnProperty.call(raw, 'manual')
+ ) {
+ const withoutLegacyManual = { ...(raw as Record<string, unknown>) };
+ delete withoutLegacyManual.manual;
+ const legacyCompatible = validateGhostManifest(withoutLegacyManual);
+ if (legacyCompatible.ok) {
+ this.options.log?.warn('ghost legacy manual metadata ignored', {
+ dir,
+ manifestId: legacyCompatible.manifest.id,
+ reason: v.reason,
+ });
+ v = legacyCompatible;
+ }
+ }
if (!v.ok) {
this.options.log?.warn('ghost dir skipped: invalid manifest', { dir, reason: v.reason });
continue;
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index fadee1c2b7..404e66abac 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -353,6 +353,19 @@ describe('GhostManager · install', () => {
await expectRejection(await manager.install(cindy), 'file-invalid');
});
+ it.each([
+ ['string', 'notes'],
+ ['object', { note: 'legacy metadata', nested: { arbitrary: true } }],
+ ])('新包携带旧式 %s manual metadata 时 inspect/install 仍严格拒绝', async (label, manual) => {
+ const cindy = await makeCindy(`legacy-manual-${label}.cindy`, {
+ ...goodManifest(),
+ manual,
+ });
+ await expectRejection(await manager.inspect(cindy), 'file-invalid');
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ });
+
it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {
const manifest = {
...goodManifest(),
@@ -513,6 +526,69 @@ describe('GhostManager · list', () => {
await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));
expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);
});
+
+ it('升级后忽略历史安装中的任意 manual metadata,保留启用状态且不放宽其它字段', async () => {
+ const warn = vi.fn();
+ manager = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ log: { info: vi.fn(), warn },
+ });
+ const fixtures = [
+ { id: 'legacy-string', manual: 'notes', enabled: true },
+ {
+ id: 'legacy-object',
+ manual: { note: 'old metadata', nested: { arbitrary: true } },
+ enabled: false,
+ },
+ ];
+ for (const fixture of fixtures) {
+ const dir = path.join(rootDir, fixture.id);
+ await fs.promises.mkdir(dir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(dir, 'ghost.json'),
+ JSON.stringify({ ...goodManifest(fixture.id), manual: fixture.manual }),
+ );
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// legacy');
+ if (!fixture.enabled) await fs.promises.writeFile(path.join(dir, '.disabled'), '');
+ }
+ const invalidDir = path.join(rootDir, 'broken-other-field');
+ await fs.promises.mkdir(invalidDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(invalidDir, 'ghost.json'),
+ JSON.stringify({
+ ...goodManifest('broken-other-field'),
+ schemaVersion: 1,
+ manual: 'notes',
+ }),
+ );
+
+ const installed = manager.list();
+ expect(
+ installed.map(({ manifest, enabled }) => ({
+ id: manifest.id,
+ enabled,
+ manual: manifest.manual,
+ })),
+ ).toEqual([
+ { id: 'legacy-object', enabled: false, manual: undefined },
+ { id: 'legacy-string', enabled: true, manual: undefined },
+ ]);
+ expect(warn).toHaveBeenCalledTimes(3);
+ expect(warn).toHaveBeenCalledWith(
+ 'ghost legacy manual metadata ignored',
+ expect.objectContaining({ manifestId: 'legacy-string' }),
+ );
+ expect(warn).toHaveBeenCalledWith(
+ 'ghost legacy manual metadata ignored',
+ expect.objectContaining({ manifestId: 'legacy-object' }),
+ );
+ expect(warn).toHaveBeenCalledWith(
+ 'ghost dir skipped: invalid manifest',
+ expect.objectContaining({ dir: invalidDir }),
+ );
+ });
});
describe('GhostManager · setEnabled(启用/停用)', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 5e32306a53..0c01bd3e01 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1224,6 +1224,58 @@ describe('packGhostDir · manual 渐进披露手册', () => {
}
});
+ it('隐藏 Markdown 与隐藏目录沿用打包过滤规则,不入包也不触发变化误报', async () => {
+ const manifest = {
+ ...GOOD_MANIFEST,
+ manual: { items: [{ dir: 'manual', name: 'overview', description: '总览' }] },
+ };
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(manifest),
+ 'main.js': '// brain',
+ 'manual/MANUAL.md': '# 总览',
+ 'manual/visible.md': '# 可见正文',
+ 'manual/.draft.md': '# 草稿',
+ 'manual/.draft/hidden.md': '# 隐藏目录正文',
+ });
+ const packed = await packGhostDir(dir);
+ expect(packed.ok, JSON.stringify(packed)).toBe(true);
+ if (!packed.ok) return;
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));
+ expect(zip.file('manual/MANUAL.md')).not.toBeNull();
+ expect(zip.file('manual/visible.md')).not.toBeNull();
+ expect(zip.file('manual/.draft.md')).toBeNull();
+ expect(zip.file('manual/.draft/hidden.md')).toBeNull();
+ });
+
+ it('MANUAL.md 入口必须逐字匹配,大小写不敏感文件系统也不能用 manual.md 冒充', async () => {
+ const manifest = {
+ ...GOOD_MANIFEST,
+ manual: { items: [{ dir: 'manual', name: 'overview', description: '总览' }] },
+ };
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(manifest),
+ 'main.js': '// brain',
+ 'manual/manual.md': '# 错误大小写入口',
+ });
+ const lowercaseEntry = path.join(dir, 'manual/manual.md');
+ const uppercaseEntry = path.join(dir, 'manual/MANUAL.md');
+ const originalLstat = fs.promises.lstat.bind(fs.promises);
+ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(
+ ((target: fs.PathLike, options?: fs.StatOptions) => {
+ if (String(target) === uppercaseEntry) {
+ return originalLstat(lowercaseEntry, options as never);
+ }
+ return originalLstat(target, options as never);
+ }) as typeof fs.promises.lstat,
+ );
+
+ expect(await packGhostDir(dir)).toMatchObject({
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ });
+ expect(lstatSpy.mock.calls.some(([target]) => String(target) === uppercaseEntry)).toBe(false);
+ });
+
it('制品中的 C0、DEL、反斜杠文件名和非法目录名在 Forge 侧直接拒绝', async () => {
if (process.platform === 'win32') return;
const manifest = {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostManual.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostManual.test.ts
index bd89f9ae6d..d7ff8725d6 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostManual.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostManual.test.ts
@@ -296,10 +296,14 @@ describe('readInstalledGhostManual', () => {
await write('docs/physical-dir/MANUAL.md', '# 入口');
await write('docs/physical-dir/references/flow.md', '# 流程');
const originalLstat = fs.promises.lstat.bind(fs.promises);
- vi.spyOn(fs.promises, 'lstat').mockImplementation(async (target) => {
- if (String(target).endsWith(path.join('references', 'blocked.md'))) throw fsError(code);
- return originalLstat(target);
- });
+ vi.spyOn(fs.promises, 'lstat').mockImplementation(
+ ((target: fs.PathLike, options?: fs.StatOptions) => {
+ if (String(target).endsWith(path.join('references', 'blocked.md'))) {
+ return Promise.reject(fsError(code));
+ }
+ return originalLstat(target, options as never);
+ }) as typeof fs.promises.lstat,
+ );
const result = await readInstalledGhostManual(ghost(), 'logical-name/references/blocked.md');
expect(result).toMatchObject({
ok: false,
@@ -316,12 +320,14 @@ describe('readInstalledGhostManual', () => {
await write('docs/physical-dir/MANUAL.md', '# 入口');
await write('docs/physical-dir/references/flow.md', '# 流程');
const originalLstat = fs.promises.lstat.bind(fs.promises);
- vi.spyOn(fs.promises, 'lstat').mockImplementation(async (target) => {
- if (String(target).endsWith(path.join('references', 'missing.md'))) {
- throw fsError('ENOTDIR');
- }
- return originalLstat(target);
- });
+ vi.spyOn(fs.promises, 'lstat').mockImplementation(
+ ((target: fs.PathLike, options?: fs.StatOptions) => {
+ if (String(target).endsWith(path.join('references', 'missing.md'))) {
+ return Promise.reject(fsError('ENOTDIR'));
+ }
+ return originalLstat(target, options as never);
+ }) as typeof fs.promises.lstat,
+ );
const requested = 'logical-name/references/missing.md';
const result = await readInstalledGhostManual(ghost(), requested);
expect(result).toMatchObject({
@@ -350,16 +356,18 @@ describe('readInstalledGhostManual', () => {
it('请求的中间父段是特殊文件时仍归 MANUAL_UNAVAILABLE', async () => {
await write('docs/physical-dir/MANUAL.md', '# 入口');
const originalLstat = fs.promises.lstat.bind(fs.promises);
- vi.spyOn(fs.promises, 'lstat').mockImplementation(async (target) => {
- if (String(target).endsWith(path.join('physical-dir', 'special-parent'))) {
- return {
- isSymbolicLink: () => false,
- isDirectory: () => false,
- isFile: () => false,
- } as fs.Stats;
- }
- return originalLstat(target);
- });
+ vi.spyOn(fs.promises, 'lstat').mockImplementation(
+ ((target: fs.PathLike, options?: fs.StatOptions) => {
+ if (String(target).endsWith(path.join('physical-dir', 'special-parent'))) {
+ return Promise.resolve({
+ isSymbolicLink: () => false,
+ isDirectory: () => false,
+ isFile: () => false,
+ } as fs.Stats);
+ }
+ return originalLstat(target, options as never);
+ }) as typeof fs.promises.lstat,
+ );
const result = await readInstalledGhostManual(ghost(), 'logical-name/special-parent/child.md');
expect(result).toMatchObject({
ok: false,
@@ -401,16 +409,18 @@ describe('readInstalledGhostManual', () => {
}
const originalLstat = fs.promises.lstat.bind(fs.promises);
- vi.spyOn(fs.promises, 'lstat').mockImplementation(async (target) => {
- if (String(target).endsWith(path.join('physical-dir', 'special.md'))) {
- return {
- isSymbolicLink: () => false,
- isDirectory: () => false,
- isFile: () => false,
- } as fs.Stats;
- }
- return originalLstat(target);
- });
+ vi.spyOn(fs.promises, 'lstat').mockImplementation(
+ ((target: fs.PathLike, options?: fs.StatOptions) => {
+ if (String(target).endsWith(path.join('physical-dir', 'special.md'))) {
+ return Promise.resolve({
+ isSymbolicLink: () => false,
+ isDirectory: () => false,
+ isFile: () => false,
+ } as fs.Stats);
+ }
+ return originalLstat(target, options as never);
+ }) as typeof fs.promises.lstat,
+ );
const special = await readInstalledGhostManual(ghost(), 'logical-name/special.md');
expect(special).toMatchObject({
ok: false,
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index d9a10ac4b2..4b3b1abebb 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -689,9 +689,6 @@ async function buildGhostPackage(
if (manifest.panel?.html) mustExist.push(manifest.panel.html);
if (manifest.settingsHtml) mustExist.push(manifest.settingsHtml);
for (const item of manifest.skill?.items ?? []) mustExist.push(`${item.dir}/SKILL.md`);
- for (const item of manifest.manual?.items ?? []) {
- mustExist.push(`${item.dir}/${GHOST_MANUAL_ENTRY_FILE}`);
- }
for (const rel of mustExist) {
try {
// lstat 与收集侧(walk 的 Dirent)同一语义:声明的入口若是符号链接,
@@ -748,18 +745,24 @@ async function buildGhostPackage(
const validateManualDir = async (
currentDir: string,
relativeDir: string,
+ preloadedEntries?: fs.Dirent[],
): Promise<Exclude<ForgePackResult, { ok: true }> | null> => {
let entries: fs.Dirent[];
- try {
- entries = await fs.promises.readdir(currentDir, { withFileTypes: true });
- } catch {
- return {
- ok: false,
- errorCode: 'ENTRY_MISSING',
- message: `读取手册目录失败:${item.dir}${relativeDir ? `/${relativeDir}` : ''}`,
- };
+ if (preloadedEntries) {
+ entries = preloadedEntries;
+ } else {
+ try {
+ entries = await fs.promises.readdir(currentDir, { withFileTypes: true });
+ } catch {
+ return {
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ message: `读取手册目录失败:${item.dir}${relativeDir ? `/${relativeDir}` : ''}`,
+ };
+ }
}
for (const entry of entries) {
+ if (shouldSkip(entry.name)) continue;
const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
const logicalPath = `${item.dir}/${relativePath}`;
const absolutePath = path.join(currentDir, entry.name);
@@ -826,7 +829,25 @@ async function buildGhostPackage(
}
return null;
};
- const manualError = await validateManualDir(unitRoot, '');
+ let rootEntries: fs.Dirent[];
+ try {
+ rootEntries = await fs.promises.readdir(unitRoot, { withFileTypes: true });
+ } catch {
+ return {
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ message: `读取手册目录失败:${item.dir}`,
+ };
+ }
+ const manualEntry = rootEntries.find((entry) => entry.name === GHOST_MANUAL_ENTRY_FILE);
+ if (!manualEntry?.isFile() || manualEntry.isSymbolicLink()) {
+ return {
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ message: `清单声明的文件不存在:${item.dir}/${GHOST_MANUAL_ENTRY_FILE}`,
+ };
+ }
+ const manualError = await validateManualDir(unitRoot, '', rootEntries);
if (manualError) return manualError;
}