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): preserve legacy manual installs across readers

fmfsaisai19b64b9c1952
diff --git a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts b/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts
new file mode 100644
index 0000000000..0c2f937a44
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts
@@ -0,0 +1,83 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ parseInstalledGhostManifest,
+ readInstalledGhostManifest,
+} from '../installedGhostManifest.js';
+
+const roots: string[] = [];
+
+function manifest(id = 'legacy-plugin'): Record<string, unknown> {
+ return {
+ schemaVersion: 2,
+ id,
+ name: 'Legacy plugin',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'run', description: 'Run the plugin' }],
+ };
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('installed ghost manifest compatibility', () => {
+ it('keeps valid Manual manifests strict and does not strip them', () => {
+ const raw = {
+ ...manifest(),
+ manual: {
+ items: [{ dir: 'manual/guide', name: 'guide', description: 'How to use it' }],
+ },
+ };
+
+ const parsed = parseInstalledGhostManifest(raw);
+
+ expect(parsed).toEqual({ ok: true, manifest: raw, legacyManualIgnored: false });
+ });
+
+ it.each([
+ ['string', 'sensitive legacy notes'],
+ ['object', { arbitrary: 'sensitive legacy metadata' }],
+ ])('ignores a legacy top-level manual %s while preserving the manifest', (_kind, manual) => {
+ const parsed = parseInstalledGhostManifest({ ...manifest(), manual });
+
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ expect(parsed.legacyManualIgnored).toBe(true);
+ expect(parsed.manifest).not.toHaveProperty('manual');
+ expect(JSON.stringify(parsed)).not.toContain('sensitive');
+ });
+
+ it('does not hide invalid fields unrelated to legacy manual', () => {
+ const parsed = parseInstalledGhostManifest({
+ ...manifest(),
+ name: 42,
+ manual: 'legacy notes',
+ });
+
+ expect(parsed.ok).toBe(false);
+ });
+
+ it('reads an installed ghost.json through the bounded compatibility path', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-manifest-'));
+ roots.push(root);
+ fs.writeFileSync(
+ path.join(root, 'ghost.json'),
+ JSON.stringify({ ...manifest(), manual: { marker: 'legacy metadata' } }),
+ );
+
+ const parsed = readInstalledGhostManifest(root, 64 * 1024);
+
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ expect(parsed.manifest.id).toBe('legacy-plugin');
+ expect(parsed.manifest).not.toHaveProperty('manual');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
index 2c4fb77b01..c4d3a96e8d 100644
--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
@@ -1198,6 +1198,46 @@ describe('legacy Ghost plugin recovery', () => {
);
});
+ it('recovers legacy manual metadata from shared and owner-scoped roots without weakening other validation', async () => {
+ const root = await tempRoot();
+ const ownerId = 'cloud-a';
+ const ownerKey = dataOwnerStorageKey(ownerId);
+ await writeGhostDirWithManifest(
+ path.join(root, 'brain', 'legacy-string'),
+ 'legacy-string',
+ { manual: 'old notes' },
+ );
+ await writeGhostDirWithManifest(
+ path.join(root, 'owners', ownerKey, 'brain', 'legacy-object'),
+ 'legacy-object',
+ { manual: { arbitrary: 'old metadata' } },
+ );
+ await writeGhostDirWithManifest(
+ path.join(root, 'brain', 'invalid-other-field'),
+ 'invalid-other-field',
+ { manual: 'old notes', name: 42 },
+ );
+
+ expect(
+ getLegacyGhostRecoveryStatus(
+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },
+ root,
+ ),
+ ).toEqual({ state: 'partial', legacyPluginCount: 2, canRetry: true });
+
+ await expect(
+ recoverLegacyGhostPlugins(
+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },
+ realFsDeps(root),
+ ),
+ ).resolves.toMatchObject({ status: 'migrated', moved: 2, conflicts: 0 });
+ const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');
+ await expect(fs.access(path.join(targetRoot, 'legacy-string'))).resolves.toBeUndefined();
+ await expect(fs.access(path.join(targetRoot, 'legacy-object'))).resolves.toBeUndefined();
+ await expect(fs.access(path.join(root, 'brain', 'invalid-other-field'))).resolves.toBeUndefined();
+ await expect(fs.access(path.join(targetRoot, 'invalid-other-field'))).rejects.toThrow();
+ });
+
it('removes a newly created empty target when every plugin rename fails', async () => {
const root = await tempRoot();
const ownerId = 'cloud-a';
@@ -1881,6 +1921,14 @@ async function writeGhostDirAtPath(
dir: string,
id: string,
command?: string,
+): Promise<void> {
+ await writeGhostDirWithManifest(dir, id, command === undefined ? {} : { command });
+}
+
+async function writeGhostDirWithManifest(
+ dir: string,
+ id: string,
+ extra: Record<string, unknown>,
): Promise<void> {
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(
@@ -1894,7 +1942,7 @@ async function writeGhostDirAtPath(
entry: 'main.js',
slots: ['tool'],
tools: [{ name: 'do_thing', description: 'Do something' }],
- ...(command === undefined ? {} : { command }),
+ ...extra,
}),
'utf-8',
);
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index fe7fb195d3..34161f4c94 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -31,6 +31,7 @@ import {
readBoundedFileNoFollowSync,
} from '../utils/readBoundedFile.js';
import { checkSkillMdConsistency } from './skillSlot.js';
+import { parseInstalledGhostManifest } from '../installedGhostManifest.js';
import {
decodeGhostManualMarkdown,
ghostManualLogicalPathForEntry,
@@ -210,24 +211,13 @@ export class GhostManager {
});
continue;
}
- 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', {
- code: 'LEGACY_MANUAL_METADATA_IGNORED',
- manifestId: legacyCompatible.manifest.id,
- });
- v = legacyCompatible;
- }
+ const parsedInstalled = parseInstalledGhostManifest(raw);
+ const v = parsedInstalled;
+ if (parsedInstalled.ok && parsedInstalled.legacyManualIgnored) {
+ this.options.log?.warn('ghost legacy manual metadata ignored', {
+ code: 'LEGACY_MANUAL_METADATA_IGNORED',
+ manifestId: parsedInstalled.manifest.id,
+ });
}
if (!v.ok) {
this.options.log?.warn('ghost dir skipped: invalid manifest', { dir, reason: v.reason });
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index ca8ba3ccb5..e407b7187c 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -22,7 +22,6 @@ import {
GHOST_CARD_HEIGHT_MAX,
GHOST_CARD_HEIGHT_MIN,
GHOST_INSTALL_MANIFEST_MAX_BYTES,
- GHOST_MANIFEST_FILE,
GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,
GHOST_NOTIFY_MIN_INTERVAL_MS,
diffGhostPermissionItems,
@@ -34,7 +33,6 @@ import {
isOfficialGhostId,
isValidGhostId,
layoutWithGhostPanel,
- validateGhostManifest,
type GhostHostNoticeKey,
type GhostImageAspectRatio,
type GhostManifest,
@@ -244,7 +242,7 @@ import { GhostFsSlot } from './fsSlot.js';
import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
import { getDirDepositVault, getSaveDepositVault, isPathInsideDir } from './dirDeposit.js';
-import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
+import { readInstalledGhostManifest } from '../installedGhostManifest.js';
import {
ghostManifestDigest,
PluginMarketLedger,
@@ -2063,17 +2061,8 @@ function readInstalledGhostManifestDigest(ghostId: string): string | null {
.list()
.find((candidate) => candidate.manifest.id === ghostId);
if (!ghost) return null;
- try {
- const bytes = readBoundedFileNoFollowSync(
- path.join(ghost.dir, GHOST_MANIFEST_FILE),
- GHOST_INSTALL_MANIFEST_MAX_BYTES,
- );
- if (bytes === null) return null;
- const validated = validateGhostManifest(JSON.parse(bytes.toString('utf8')) as unknown);
- return validated.ok ? ghostManifestDigest(validated.manifest) : null;
- } catch {
- return null;
- }
+ const parsed = readInstalledGhostManifest(ghost.dir, GHOST_INSTALL_MANIFEST_MAX_BYTES);
+ return parsed.ok ? ghostManifestDigest(parsed.manifest) : null;
}
/** Resolve Connection metadata only from a trusted organization market install. */
diff --git a/apps/desktop/src/main/installedGhostManifest.ts b/apps/desktop/src/main/installedGhostManifest.ts
new file mode 100644
index 0000000000..42f04906b2
--- /dev/null
+++ b/apps/desktop/src/main/installedGhostManifest.ts
@@ -0,0 +1,46 @@
+import path from 'node:path';
+
+import { validateGhostManifest, type GhostManifest } from '../shared/ghost.js';
+import { readBoundedFileNoFollowSync } from './utils/readBoundedFile.js';
+
+export type InstalledGhostManifestParse =
+ | { ok: true; manifest: GhostManifest; legacyManualIgnored: boolean }
+ | { ok: false; reason: string };
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
+}
+
+/**
+ * Installed directories may contain a pre-manual top-level `manual` metadata
+ * field. Keep this compatibility rule confined to reads of already-installed
+ * manifests; package/Forge validation remains strict via validateGhostManifest.
+ */
+export function parseInstalledGhostManifest(raw: unknown): InstalledGhostManifestParse {
+ const strict = validateGhostManifest(raw);
+ if (strict.ok) return { ok: true, manifest: strict.manifest, legacyManualIgnored: false };
+ if (!isPlainObject(raw) || !Object.prototype.hasOwnProperty.call(raw, 'manual')) {
+ return { ok: false, reason: strict.reason };
+ }
+ const withoutLegacyManual = { ...raw };
+ delete withoutLegacyManual.manual;
+ const compatible = validateGhostManifest(withoutLegacyManual);
+ return compatible.ok
+ ? { ok: true, manifest: compatible.manifest, legacyManualIgnored: true }
+ : { ok: false, reason: compatible.reason };
+}
+
+export function readInstalledGhostManifest(
+ dir: string,
+ maxBytes: number,
+): InstalledGhostManifestParse {
+ try {
+ const bytes = readBoundedFileNoFollowSync(path.join(dir, 'ghost.json'), maxBytes);
+ if (bytes === null) return { ok: false, reason: 'manifest is not a bounded regular file' };
+ return parseInstalledGhostManifest(JSON.parse(bytes.toString('utf8')) as unknown);
+ } catch {
+ return { ok: false, reason: 'manifest could not be read' };
+ }
+}
diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.ts
index 520467aaf3..39f66d6688 100644
--- a/apps/desktop/src/main/ownerNamespaceMigration.ts
+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts
@@ -7,10 +7,10 @@ import path from 'node:path';
import { dataOwnerStorageKey, type AppSessionMode } from './appSessionState.js';
import { createLogger } from './logger.js';
import {
- GHOST_MANIFEST_FILE,
isOfficialGhostId,
- validateGhostManifest,
+ GHOST_INSTALL_MANIFEST_MAX_BYTES,
} from '../shared/ghost.js';
+import { readInstalledGhostManifest } from './installedGhostManifest.js';
import {
NO_LEGACY_GHOST_RECOVERY,
type LegacyGhostRecoveryStatus,
@@ -654,13 +654,7 @@ function readValidLegacyGhostDir(
dir: string,
expectedId: string,
): Pick<LegacyGhostDir, 'command'> | null {
- let raw: unknown;
- try {
- raw = JSON.parse(fsSync.readFileSync(path.join(dir, GHOST_MANIFEST_FILE), 'utf-8'));
- } catch {
- return null;
- }
- const parsed = validateGhostManifest(raw);
+ const parsed = readInstalledGhostManifest(dir, GHOST_INSTALL_MANIFEST_MAX_BYTES);
if (!parsed.ok || parsed.manifest.id !== expectedId) return null;
return { command: parsed.manifest.command ?? null };
}
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
index 4e6eb43574..5b43f7977e 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
@@ -2068,6 +2068,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
);
expect(source).not.toMatch(/fs\.promises\.readFile\(/);
expect(source).not.toMatch(/readFileSync\(/);
- expect(source).toMatch(/readBoundedFileNoFollowSync/);
+ expect(source).toMatch(/readInstalledGhostManifest/);
});
});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 492673adc9..0061fe817b 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -1016,13 +1016,17 @@ describe('PluginMarketService migration and defaultInstall', () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
- const installed = manifest(item.ghostId, '1.0.0', ['notify', 'fs']);
+ const installed = {
+ ...manifest(item.ghostId, '1.0.0', ['notify', 'fs']),
+ manual: { arbitrary: 'legacy metadata' },
+ };
+ const normalizedInstalled = manifest(item.ghostId, '1.0.0', ['notify', 'fs']);
const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-ghost-'));
roots.push(installedDir);
fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installed));
runtime.ghosts = [
{
- manifest: { ...installed, name: 'Localized Test Plugin' },
+ manifest: { ...normalizedInstalled, name: 'Localized Test Plugin' },
dir: installedDir,
enabled: true,
},
@@ -1037,14 +1041,17 @@ describe('PluginMarketService migration and defaultInstall', () => {
...recordForTest(item),
releaseId: 'release-1',
version: '1.0.0',
- manifestDigest: ghostManifestDigest(installed),
+ manifestDigest: ghostManifestDigest(normalizedInstalled),
});
await h.service.install(item.id, reviewedInstallOptions(item));
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
- permissionBaselineManifest: installed,
+ permissionBaselineManifest: expect.objectContaining({ id: installed.id }),
});
+ expect(runtime.install.mock.calls[0]?.[1]?.permissionBaselineManifest).not.toHaveProperty(
+ 'manual',
+ );
});
it('keeps a stale official record out of automatic updates but allows explicit replacement', async () => {
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 2e40fb964b..744b45cab2 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -70,8 +70,8 @@ import { throwIpcError } from '../utils/ipcValidate.js';
import {
GHOST_MANIFEST_MAX_BYTES,
readBoundedFileNoFollowWithStat,
- readBoundedFileNoFollowSync,
} from '../utils/readBoundedFile.js';
+import { readInstalledGhostManifest } from '../installedGhostManifest.js';
import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';
import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';
import { PluginMarketApi } from './api.js';
@@ -293,20 +293,8 @@ function stripDirectionalControls(text: string): string {
/* eslint-enable no-control-regex */
function installedGhostRawManifest(dir: string): GhostManifest | null {
- try {
- // 安装目录也可能被外部进程/同步盘改动,且本函数每次市场快照都会执行:
- // 与市场目录同一把单句柄限量闸,拒链接、超限即拒,不让无界字节进快照路径。
- const bytes = readBoundedFileNoFollowSync(
- path.join(dir, 'ghost.json'),
- GHOST_MANIFEST_MAX_BYTES,
- );
- if (bytes === null) return null;
- const raw = JSON.parse(bytes.toString('utf8')) as unknown;
- const validated = validateGhostManifest(raw);
- return validated.ok ? validated.manifest : null;
- } catch {
- return null;
- }
+ const parsed = readInstalledGhostManifest(dir, GHOST_MANIFEST_MAX_BYTES);
+ return parsed.ok ? parsed.manifest : null;
}
function installedGhostRawManifestDigest(dir: string): string | null {