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。

Merge branch 'main' (e78f44ae5) into redo/plugin-approval-receipt-migration

Yuewei-LL0026124fcebd
diff --cc apps/desktop/src/main/cindy-brain/GhostManager.ts
index d802f7a49d,a06150626a..c231e69bef
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@@ -104,9 -44,57 +104,51 @@@ export const MAX_BASIC_ZIP_ENTRIES = 25
export const MAX_NODE_ZIP_ENTRIES = 2_048;
/** 停用标记文件名(安装目录内;存在即停用)。 */
const DISABLED_MARKER_FILE = '.disabled';
- /** 宿主保留的安装信任镜像文件名;插件包不得自行携带。 */
- const TRUST_METADATA_FILE = '.cindy-trust.json';
+ /** 安装时由主机写入的信任快照与权限 receipt;作者包不能提供。 */
+ export const TRUST_METADATA_FILE = '.cindy-trust.json';
+
+ /** 只有宿主安装/播种路径可以写入的 Cindy 官方身份。 */
+ export const CINDY_OFFICIAL_GHOST_TRUST: GhostTrustInfo = Object.freeze({
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Cindy Plugin Market',
+ });
+
+ export type GhostHostTrustOverride = 'cindy-official';
+
+ /**
+ * 判断一个已投影的 trust 是否确实来自完整官方 receipt。
+ *
+ * 这是 gh-cli 凭证路径的共同安全谓词:不能只看 level,否则残缺或被篡改
+ * 的 `.cindy-trust.json` 可能被误当成官方插件。其它 trust level 仍保留其
+ * 原有兼容字段语义;只有官方 level 要求这组不可缺省的完整字段。
+ */
+ export function isCindyOfficialTrustInfo(
+ trust: GhostTrustInfo | null | undefined,
+ ): boolean {
+ return (
+ trust?.level === CINDY_OFFICIAL_GHOST_TRUST.level &&
+ trust.publisherSigned === CINDY_OFFICIAL_GHOST_TRUST.publisherSigned &&
+ trust.publisherVerified === CINDY_OFFICIAL_GHOST_TRUST.publisherVerified &&
+ trust.reviewed === CINDY_OFFICIAL_GHOST_TRUST.reviewed &&
+ trust.publisherName === CINDY_OFFICIAL_GHOST_TRUST.publisherName
+ );
+ }
+
+ /** 完整校验官方 Host receipt;只看 level 会把损坏 receipt 误当成已回填。 */
+ export function hasCindyOfficialTrustMetadata(dir: string): boolean {
+ try {
+ const bytes = readBoundedFileNoFollowSync(path.join(dir, TRUST_METADATA_FILE), 64 * 1024);
+ if (bytes === null) return false;
+ const raw = JSON.parse(bytes.toString('utf8')) as Record<string, unknown>;
+ return isCindyOfficialTrustInfo(raw as unknown as GhostTrustInfo);
+ } catch {
+ return false;
+ }
+ }
-interface GhostInstalledHostMetadata {
- trust: GhostTrustInfo;
- /** Legacy receipt retained only for backward-compatible metadata reads. */
- approvedAtResourceProviderTool?: string;
-}
-
/** 注入式日志接口 —— manager 不直接依赖 main/logger,单测零 electron。 */
export interface GhostManagerLogger {
info(message: string, meta?: Record<string, unknown>): void;
@@@ -166,250 -125,14 +208,250 @@@ export type InstallRejection
export type UninstallRejection =
| { code: 'invalid-id'; reason: string }
| { code: 'not-installed'; reason: string }
+ | { code: 'approval-required'; reason: string }
| { code: 'io'; reason: string };
+export type UninstallResult = { ok: true } | { rejection: UninstallRejection };
+
+export interface GhostUninstallOptions {
+ notify?: boolean;
+ /**
+ * User-initiated removal records a builtin tombstone by default. Host
+ * reconciliation may explicitly skip it when removing a currently ineligible
+ * seed; that is lifecycle cleanup, not a durable user uninstall decision.
+ */
+ recordBuiltinTombstone?: boolean;
+}
+
+interface InstalledReapprovalProjection {
+ manifest: GhostManifest;
+ trust: GhostTrustInfo;
+ localeResources: Record<string, GhostManifestLocaleResource>;
+ iconDataUrl?: string;
+ skillContentSha256: Record<string, string>;
+}
+
+export interface LegacyGhostApprovalProjection {
+ manifest: GhostManifest;
+ enabled: boolean;
+ trust: GhostTrustInfo;
+ localeResources: Record<string, GhostManifestLocaleResource>;
+ iconDataUrl?: string;
+ skillContentSha256: Record<string, string>;
+}
+
+export function hashLegacyGhostApprovalProjection(
+ projection: LegacyGhostApprovalProjection,
+): string {
+ return crypto
+ .createHash('sha256')
+ .update(
+ JSON.stringify({
+ version: 1,
+ manifest: projection.manifest,
+ enabled: projection.enabled,
+ trust: projection.trust,
+ localeResources: projection.localeResources,
+ iconDataUrl: projection.iconDataUrl ?? null,
+ skillContentSha256: projection.skillContentSha256,
+ }),
+ )
+ .digest('hex');
+}
+
+function sameLegacyApprovalDirectoryIdentity(expected: fs.Stats, current: fs.Stats): boolean {
+ if (!current.isDirectory() || current.isSymbolicLink()) return false;
+ if (expected.dev !== 0 || expected.ino !== 0 || current.dev !== 0 || current.ino !== 0) {
+ return expected.dev === current.dev && expected.ino === current.ino;
+ }
+ return expected.birthtimeMs === current.birthtimeMs && expected.ctimeMs === current.ctimeMs;
+}
+
+function sameLegacyApprovalCanonicalPath(left: string, right: string): boolean {
+ const fold = (value: string): string =>
+ process.platform === 'win32' ? value.toLowerCase() : value;
+ return fold(path.resolve(left)) === fold(path.resolve(right));
+}
+
+function assertStableLegacyApprovalDirectory(
+ dir: string,
+ expectedStats: fs.Stats,
+ expectedRealPath: string,
+): void {
+ const currentStats = fs.lstatSync(dir);
+ const currentRealPath = fs.realpathSync(dir);
+ if (
+ !sameLegacyApprovalDirectoryIdentity(expectedStats, currentStats) ||
+ !sameLegacyApprovalCanonicalPath(expectedRealPath, currentRealPath)
+ ) {
+ throw new Error('legacy approval directory changed while reading');
+ }
+}
+
+function readLegacyDisabledMarkerForApproval(dir: string): boolean {
+ const marker = path.join(dir, DISABLED_MARKER_FILE);
+ try {
+ const kind = classifyGhostDirEntrySync(marker);
+ if (kind === 'file') return true;
+ throw new Error('legacy disabled marker is not a regular file');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
+ throw error;
+ }
+}
+
+function readLegacyLocaleResourcesForApproval(
+ dir: string,
+ realDir: string,
+ manifest: GhostManifest,
+): Record<string, GhostManifestLocaleResource> {
+ const resources: Record<string, GhostManifestLocaleResource> = {};
+ for (const localePath of Object.values(manifest.locales ?? {})) {
+ if (!localePath) continue;
+ const absPath = resolveGhostContentPathSync(dir, localePath, {
+ expect: 'file',
+ label: 'legacy locale',
+ });
+ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {
+ containWithin: realDir,
+ });
+ if (bytes === null) throw new Error(`legacy locale missing or oversized: ${localePath}`);
+ let raw: unknown;
+ try {
+ raw = JSON.parse(bytes.toString('utf8'));
+ } catch (error) {
+ throw new Error(
+ `legacy locale is not valid JSON: ${localePath}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+ const validated = validateGhostManifestLocaleResource(raw, manifest);
+ if (!validated.ok) throw new Error(`legacy locale invalid: ${localePath}`);
+ resources[localePath] = validated.resource;
+ }
+ return resources;
+}
+
+function readLegacyIconDataUrlForApproval(
+ dir: string,
+ realDir: string,
+ manifest: GhostManifest,
+): string | undefined {
+ if (manifest.icon === undefined) return undefined;
- const iconPath = resolveGhostContentPathSync(dir, manifest.icon, {
- expect: 'file',
- label: 'legacy icon',
- });
- const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {
- containWithin: realDir,
- });
- if (bytes === null) {
- throw new Error(`legacy icon missing or oversized: ${manifest.icon}`);
- }
- const iconDataUrl = buildIconDataUrl(manifest.icon, bytes);
- if (iconDataUrl === null) {
- throw new Error(`legacy icon has unsupported mime type: ${manifest.icon}`);
++ try {
++ const iconPath = resolveGhostContentPathSync(dir, manifest.icon, {
++ expect: 'file',
++ label: 'legacy icon',
++ });
++ const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {
++ containWithin: realDir,
++ });
++ if (bytes === null) return undefined;
++ return buildIconDataUrl(manifest.icon, bytes) ?? undefined;
++ } catch {
++ // Icon data is presentation-only. A broken optional icon must not make an
++ // otherwise valid legacy approval ineligible for zero-operation migration.
++ return undefined;
+ }
- return iconDataUrl;
+}
+
+/**
+ * Read the complete legacy approval fact once. Recovery freezes only its digest,
+ * then both the pre-rename gate and receipt backfill re-read this same projection.
+ */
+export async function readLegacyGhostApprovalProjection(
+ dir: string,
+ id: string,
+): Promise<{ projection: LegacyGhostApprovalProjection; sha256: string }> {
+ const dirStats = fs.lstatSync(dir);
+ if (!dirStats.isDirectory() || dirStats.isSymbolicLink()) {
+ throw new Error('legacy approval source is not a real directory');
+ }
+ const realDir = fs.realpathSync(dir);
+ assertStableLegacyApprovalDirectory(dir, dirStats, realDir);
+ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {
+ expect: 'file',
+ label: 'legacy manifest',
+ });
+ const rawBytes = readBoundedFileNoFollowSync(manifestPath, GHOST_MANIFEST_MAX_BYTES, {
+ containWithin: realDir,
+ });
+ if (rawBytes === null) throw new Error('legacy manifest is missing or oversized');
+ let raw: unknown;
+ try {
+ raw = JSON.parse(rawBytes.toString('utf8'));
+ } catch (error) {
+ throw new Error(`invalid manifest JSON: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ const validated = validateGhostManifest(raw);
+ if (!validated.ok) throw new Error(`invalid manifest: ${validated.reason}`);
+ if (validated.manifest.id !== id) throw new Error('manifest id != install dir name');
+
+ const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ };
+ const projection: LegacyGhostApprovalProjection = {
+ manifest: validated.manifest,
+ enabled: !readLegacyDisabledMarkerForApproval(dir),
+ trust,
+ localeResources: readLegacyLocaleResourcesForApproval(dir, realDir, validated.manifest),
+ skillContentSha256: await hashApprovedSkillContent(validated.manifest, dir),
+ };
+ const iconDataUrl = readLegacyIconDataUrlForApproval(dir, realDir, validated.manifest);
+ if (iconDataUrl !== undefined) projection.iconDataUrl = iconDataUrl;
+ assertStableLegacyApprovalDirectory(dir, dirStats, realDir);
+ return { projection, sha256: hashLegacyGhostApprovalProjection(projection) };
+}
+
+function hashInstalledReapprovalProjection(
+ projection: InstalledReapprovalProjection,
+): string {
+ return crypto
+ .createHash('sha256')
+ .update(
+ JSON.stringify({
+ version: 1,
+ manifest: projection.manifest,
+ trust: projection.trust,
+ localeResources: projection.localeResources,
+ iconDataUrl: projection.iconDataUrl ?? null,
+ skillContentSha256: projection.skillContentSha256,
+ }),
+ )
+ .digest('hex');
+}
+
+/**
+ * `runExclusiveMutation` 回调内唯一可用的嵌套 mutation capability。
+ * capability 在回调结束后立即失效,避免调用者绕过串行 lane 或复用旧 owner 上下文。
+ */
+export interface GhostExclusiveMutation {
+ writeDisabledMarker(id: string): void;
+ publishTrustedBundledSeed(
+ id: string,
+ sourceDir: string,
+ options: { disabled: boolean },
+ ): Promise<void>;
+ approveTrustedBundledInstall(
+ manifest: GhostManifest,
+ markerEnabled: boolean,
+ options: { sourceDir: string },
+ ): Promise<boolean>;
+ removeInstallApproval(id: string): Promise<boolean>;
+ uninstall(id: string, options?: GhostUninstallOptions): Promise<UninstallResult>;
+}
+
/**
- * 意识仓库的 main 端管理者:一个意识一个子目录(rootDir/<id>/),目录即事实。
+ * 插件仓库的 main 端管理者:一个插件一个内容目录(rootDir/<id>/),Host
+ * receipt 才是 manifest / trust / enabled / revision 的授权事实。
*
* 设计要点:
- * - **目录即注册表**:没有额外的 DB / 索引文件,list() 每次实扫磁盘 ——
- * 装了什么打开文件夹一目了然,坏一个目录只影响那一个意识(跳过 + warn);
+ * - **目录只证明在装**:list() 实扫内容目录,但批准状态来自安装根之外的
+ * receipt;旧安装没有 receipt 时保持不可运行,更新需完整重新确认;
* - **装载先落 staging 再切正式**(对齐 skillhub/installService 的做法):
* 解压全程发生在 `.cindy-installing-*` 临时目录,校验全过才 rename 到
* rootDir/<id>,任何一步失败都不会留下半截安装;
@@@ -2558,14 -668,11 +2647,22 @@@ export class GhostManager
async install(
lizFilePath: string,
- opts?: { initiallyEnabled?: boolean; expectedPackageSha256?: string },
+ opts?: {
+ initiallyEnabled?: boolean;
+ expectedPackageSha256?: string;
+ trustOverride?: GhostHostTrustOverride;
+ },
+ ) {
+ return this.runExclusiveMutation(() => this.installUnlocked(lizFilePath, opts));
+ }
+
+ private async installUnlocked(
+ lizFilePath: string,
- opts?: { initiallyEnabled?: boolean; expectedPackageSha256?: string },
++ opts?: {
++ initiallyEnabled?: boolean;
++ expectedPackageSha256?: string;
++ trustOverride?: GhostHostTrustOverride;
++ },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
// 装入初始启用态由 UI 层决定(装入确认框勾选,默认沉睡);缺省 true
// 保持既有调用方(测试等)语义不变。
@@@ -2584,22 -691,13 +2681,25 @@@
},
};
}
- const { manifest, iconDataUrl, allEntries, prefix } = parsed;
+ const {
+ manifest,
+ approvedManifest,
+ localeResources,
+ trust,
+ packageSha256,
+ iconDataUrl,
+ allEntries,
+ prefix,
+ } = parsed;
+ const clearBuiltinTombstoneOnCommit =
+ this.options.isTrustedBundledId?.(manifest.id) === true &&
+ this.options.clearBuiltinTombstone !== undefined;
+ const trust = opts?.trustOverride === 'cindy-official'
+ ? CINDY_OFFICIAL_GHOST_TRUST
+ : parsed.trust;
// 4) 目标目录冲突检查
- const root = this.options.getRootDir();
+ const root = this.contentRootDir();
const finalDir = path.join(root, manifest.id);
if (await pathExists(finalDir)) {
return { rejection: { code: 'already-installed', reason: `意识 ${manifest.id} 已装入` } };
@@@ -2763,14 -765,7 +2863,22 @@@
*/
async update(
lizFilePath: string,
- opts: { expectedInstalledApproval: string; expectedPackageSha256?: string },
- opts?: { expectedPackageSha256?: string; trustOverride?: GhostHostTrustOverride },
++ opts: {
++ expectedInstalledApproval: string;
++ expectedPackageSha256?: string;
++ trustOverride?: GhostHostTrustOverride;
++ },
+ ) {
+ return this.runExclusiveMutation(() => this.updateUnlocked(lizFilePath, opts));
+ }
+
+ private async updateUnlocked(
+ lizFilePath: string,
- opts: { expectedInstalledApproval: string; expectedPackageSha256?: string },
++ opts: {
++ expectedInstalledApproval: string;
++ expectedPackageSha256?: string;
++ trustOverride?: GhostHostTrustOverride;
++ },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
const parsed = await this.parse(lizFilePath);
if ('rejection' in parsed) return parsed;
@@@ -2785,44 -780,18 +2893,47 @@@
},
};
}
- const { manifest, iconDataUrl, allEntries, prefix } = parsed;
+ const {
+ manifest,
+ approvedManifest,
+ localeResources,
+ trust,
+ packageSha256,
+ iconDataUrl,
+ allEntries,
+ prefix,
+ } = parsed;
+ const trust = opts?.trustOverride === 'cindy-official'
+ ? CINDY_OFFICIAL_GHOST_TRUST
+ : parsed.trust;
- const root = this.options.getRootDir();
+ const root = this.contentRootDir();
const finalDir = path.join(root, manifest.id);
- if (!(await pathExists(finalDir))) {
- return { rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` } };
+ if (!this.isRealDirChild(root, manifest.id)) {
+ return {
+ rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` },
+ };
+ }
+ const approvalResult = this.readApproval(manifest.id);
+ const actualApproval = approvalTokenFor(approvalResult);
+ if (actualApproval !== opts.expectedInstalledApproval) {
+ return {
+ rejection: {
+ code: 'state-changed',
+ reason: '插件批准状态在确认后发生了变化,请重新检查权限',
+ },
+ };
}
- // 延续当前唤醒/沉睡状态。
- const enabled = !fs.existsSync(path.join(finalDir, DISABLED_MARKER_FILE));
+ // 延续当前唤醒/沉睡状态。旧安装尚无 receipt 时只在完整重新确认后
+ // 采用原 `.disabled` 镜像;损坏 receipt 一律保持停用。
+ const enabled =
+ approvalResult.state === 'approved'
+ ? // 读时合并后的有效值:receipt 可能因状态根短暂不可写而停在陈旧的 enabled=true,
+ // 用户的停用镜像不能被一次更新静默冲掉。
+ this.effectiveEnabled(finalDir, approvalResult.receipt.enabled)
+ : approvalResult.state === 'legacy-unapproved'
+ ? !this.isDisabledMarkerPresentSync(finalDir)
+ : false;
// 指令查重同 install,但豁免自己(新版本沿用/改名自己的指令都合法)。
if (manifest.command !== undefined) {
diff --cc apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index cafc7f718f,0406ab8a0b..047d3238b8
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@@ -5,14 -5,8 +5,14 @@@ import path from 'node:path'
import JSZip from 'jszip';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { InstalledGhost } from '../../../shared/ghost';
-import { CINDY_OFFICIAL_GHOST_TRUST, GhostManager } from '../GhostManager';
+import {
+ GHOST_SKILL_MD_MAX_BYTES,
+ ghostInstallApprovalToken,
+ validateGhostManifest,
+ type InstalledGhost,
+} from '../../../shared/ghost';
- import { GhostManager, readLegacyGhostApprovalProjection } from '../GhostManager';
++import { CINDY_OFFICIAL_GHOST_TRUST, GhostManager, readLegacyGhostApprovalProjection } from '../GhostManager';
+import { hashApprovedSkillContent } from '../ghostInstallReceipt';
/** 每个用例独立的临时仓库根 + 源文件目录(规则 23:测试路径一律 os.tmpdir)。 */
let workDir: string;
@@@ -165,2468 -90,202 +165,2492 @@@ async function expectRejection
expect((result as { rejection: { code: string } }).rejection.code).toBe(code);
}
-describe('GhostManager · install', () => {
- it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
- const manifest = {
- ...goodManifest(),
- name: 'Base name',
- description: 'Base description',
- locales: {
- en: 'locales/en.json',
- 'zh-CN': 'locales/zh-CN.json',
- },
- };
- const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({
- name,
- description,
- tools: { do_thing: { description: toolDescription } },
+async function updateGhost(
+ cindyPath: string,
+ id = 'hello',
+): ReturnType<GhostManager['update']> {
+ const installed = manager.list().find((ghost) => ghost.manifest.id === id);
+ return manager.update(cindyPath, {
+ expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval),
+ });
+}
+
+describe('hashApprovedSkillContent · item.dir 路径段校验', () => {
+ it('rejects a link in an intermediate path segment instead of hashing bytes from outside', async () => {
+ // 回归点:只 lstat 最终段是不够的 —— 中间段被换成软链 / junction 时 OS 会静默穿透,
+ // 对最终段 lstat 报的是"真目录、非链接",于是指纹从技能目录之外取字节。首次批准
+ // 那条路径的指纹是现算的,外部内容会被钉成"批准字节"再复制成快照,而 frontmatter
+ // 一致性校验只看 name/description(manifest 里公开可抄),拦不住。所以这里必须抛错,
+ // 不能返回一个哈希。
+ const validated = validateGhostManifest({
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
});
- const cindy = await makeCindy('localized.cindy', manifest, {
- 'locales/en.json': locale('English name', 'English description', 'English tool'),
- 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),
+ if (!validated.ok) throw new Error(validated.reason);
+
+ const base = path.join(workDir, 'plugin');
+ const evil = path.join(workDir, 'evil');
+ await fs.promises.mkdir(path.join(base, 'skills', 'demo'), { recursive: true });
+ await fs.promises.mkdir(path.join(evil, 'demo'), { recursive: true });
+ await fs.promises.writeFile(
+ path.join(base, 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
+ );
+ await fs.promises.writeFile(
+ path.join(evil, 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',
+ );
+
+ // 正常结构先能算出来,确认用例本身走到了目标代码。
+ await expect(hashApprovedSkillContent(validated.manifest, base)).resolves.toHaveProperty(
+ 'skills/demo',
+ );
+
+ // 把**中间段** skills 换成指向外部的链接。
+ await fs.promises.rm(path.join(base, 'skills'), { recursive: true, force: true });
+ try {
+ await fs.promises.symlink(
+ evil,
+ path.join(base, 'skills'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+
+ await expect(hashApprovedSkillContent(validated.manifest, base)).rejects.toThrow(
+ /path segment is a link/,
+ );
+ });
+});
+
+describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {
+ /** 带 skill 槽的旧布局清单 + 配套 SKILL.md(frontmatter 与声明逐字一致)。 */
+ const legacySkillManifest = (id = 'skilled'): Record<string, unknown> => ({
+ ...goodManifest(id),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ });
+ const legacySkillFiles = (): Record<string, string> => ({
+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
+ });
+
+ it('市场/本地旧安装无感迁移:升级后仍启用、列 approved、写下迁移台账', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ // 迁移前:没有 receipt → 一律 fail closed(这正是 #1080 被回滚的现场)。
+ expect(manager.list()[0]).toMatchObject({ enabled: false, approval: { state: 'legacy-unapproved' } });
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['hello']);
+ // 迁移后:用户什么都没做,插件照旧可用。
+ expect(manager.list()[0]).toMatchObject({
+ enabled: true,
+ approval: { state: 'approved' },
});
- const result = await manager.install(cindy);
- expect(result).toMatchObject({
- ghost: {
- manifest: {
- name: '中文名称',
- description: '中文说明',
- resolvedLocale: 'zh-CN',
- tools: [{ name: 'do_thing', description: '中文工具' }],
- },
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ });
+
+ it('未批准或 receipt 损坏的插件不展示可变 trust 镜像', async () => {
+ const forgedTrust = {
+ level: 'cindy-official' as const,
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Forged publisher',
+ reviewerName: 'Forged reviewer',
+ };
+ await writeLegacyInstall('legacy', goodManifest('legacy'), { trust: forgedTrust });
+ await writeLegacyInstall('invalid', goodManifest('invalid'), { trust: forgedTrust });
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(
+ path.join(workDir, 'ghosts-install-state', 'invalid.json'),
+ JSON.stringify({ schemaVersion: 1, id: 'invalid' }),
+ );
+
+ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));
+ expect(byId.legacy).toMatchObject({
+ approval: { state: 'legacy-unapproved' },
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ });
+ expect(byId.invalid).toMatchObject({
+ approval: { state: 'invalid' },
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
},
});
+ expect(byId.legacy.trust).not.toHaveProperty('publisherName');
+ expect(byId.invalid.trust).not.toHaveProperty('reviewerName');
+ });
- hostLocale = 'ja';
- expect(manager.list()[0].manifest).toMatchObject({
- name: 'English name',
- description: 'English description',
- resolvedLocale: 'ja',
- tools: [{ name: 'do_thing', description: 'English tool' }],
+ it('旧安装的停用态被保留:.disabled 镜像 → receipt.enabled=false', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ await manager.migrateLegacyApprovalsOnce();
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'approved' },
});
- hostLocale = 'fr-FR';
- expect(manager.list()[0].manifest).toMatchObject({
- name: 'English name',
- resolvedLocale: 'en',
+ });
+
+ it('信任镜像被保留;缺失时保守降级为 unverified 而不是让迁移失败', async () => {
+ await writeLegacyInstall('trusted', goodManifest('trusted'), {
+ trust: {
+ level: 'verified-publisher',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: false,
+ publisherName: 'Acme',
+ },
});
+ await writeLegacyInstall('bare', goodManifest('bare'), { trust: 'omit' });
+ await manager.migrateLegacyApprovalsOnce();
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g]));
+ expect(byId.trusted.trust).toMatchObject({ level: 'verified-publisher', publisherName: 'Acme' });
+ expect(byId.trusted.enabled).toBe(true);
+ // 信任文件缺失不阻断迁移:插件照旧可用,只是展示为 unverified(旧模型读同一文件也如此)。
+ expect(byId.bare.trust).toMatchObject({ level: 'unverified' });
+ expect(byId.bare.enabled).toBe(true);
});
- it('已安装 locale 或其父目录被替换为目录外软链时拒绝读取并回退基础清单', async () => {
- hostLocale = 'en';
- const manifest = {
- ...goodManifest(),
- name: 'Base name',
- locales: { en: 'locales/en.json' },
+ it('skill 槽旧安装迁移后:快照建好、字节指纹钉住、对账认可挂链', async () => {
+ await writeLegacyInstall('skilled', legacySkillManifest(), { files: legacySkillFiles() });
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['skilled']);
+ const ghost = manager.list()[0];
+ expect(ghost).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ expect(ghost.approvedSkillRoot).toBeTruthy();
+ // 迁移出的快照必须能被技能对账认可(字节与 receipt 指纹逐字节对上),否则技能链断。
+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);
+ });
+
+ it('全局一次性:台账落地后,新出现的无 receipt 目录不再被迁移(fail closed)', async () => {
+ await writeLegacyInstall('first', goodManifest('first'));
+ await manager.migrateLegacyApprovalsOnce();
+ expect(manager.list().find((g) => g.manifest.id === 'first')?.approval.state).toBe('approved');
+
+ // 台账已在。此后再冒出一个没有 receipt 的目录(可能是删了 receipt 想骗迁移,或
+ // 真的新拷进来的旧目录)——迁移不再触发,它保持 fail closed。删 receipt 想"从可变
+ // 安装目录重建授权"这条路被这道门堵死。
+ await writeLegacyInstall('second', goodManifest('second'));
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });
+ expect(manager.list().find((g) => g.manifest.id === 'second')?.approval.state).toBe(
+ 'legacy-unapproved',
+ );
+ });
+
+ it('迁移绝不改动安装目录三文件(回滚到旧客户端仍按安装目录判定,§5 兜底第 4 条)', async () => {
+ const dir = await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const before = {
+ manifest: await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'),
+ disabled: fs.existsSync(path.join(dir, '.disabled')),
+ trust: await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8'),
};
- const locale = (name: string) => JSON.stringify({
- name,
- tools: { do_thing: { description: 'Localized tool' } },
- });
- const cindy = await makeCindy('localized-symlink.cindy', manifest, {
- 'locales/en.json': locale('Packaged name'),
- });
- await manager.install(cindy);
- const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');
- const outsidePath = path.join(workDir, 'outside-locale.json');
- await fs.promises.writeFile(outsidePath, locale('Outside name'));
- await fs.promises.rm(localePath);
- try {
- await fs.promises.symlink(outsidePath, localePath, 'file');
- } catch {
- return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。
- }
+ await manager.migrateLegacyApprovalsOnce();
+ expect(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8')).toBe(before.manifest);
+ expect(fs.existsSync(path.join(dir, '.disabled'))).toBe(before.disabled);
+ expect(await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8')).toBe(before.trust);
+ });
- expect(manager.list()[0].manifest).toMatchObject({
- name: 'Base name',
- resolvedLocale: 'en',
- tools: [{ name: 'do_thing', description: '做点事' }],
+ it('manifest 不合法的旧目录不迁移,保持 fail closed,不写出坏 receipt', async () => {
+ const dir = path.join(rootDir, 'broken');
+ await fs.promises.mkdir(dir, { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), '{ not valid json');
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.failed).toEqual(['broken']);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'broken.json'))).toBe(false);
+ });
+
+ it('随包种子 id 跳过迁移(交给 provisioning 的逐字节对账补批准)', async () => {
+ const seededManager = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ isTrustedBundledId: (id) => id === 'hello',
});
+ await writeLegacyInstall('hello', goodManifest());
+ const outcome = await seededManager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [], retryPending: [] });
+ // 没有替它写 receipt:provisioning 才是随包插件的批准入口。
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ });
- const localesDir = path.dirname(localePath);
- const outsideLocalesDir = path.join(workDir, 'outside-locales');
- await fs.promises.rm(localesDir, { recursive: true, force: true });
- await fs.promises.mkdir(outsideLocalesDir);
- await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));
- await fs.promises.symlink(
- outsideLocalesDir,
- localesDir,
- process.platform === 'win32' ? 'junction' : 'dir',
- );
- expect(manager.list()[0].manifest).toMatchObject({
- name: 'Base name',
- resolvedLocale: 'en',
+ it('瞬时状态根 IO 不封门:台账停在 in-progress,下次启动自动续跑治愈', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ // 第一轮:receipt 落盘的 rename 吃一次 EACCES(模拟杀软/句柄占用的环境抖动)。
+ const realRename = fs.promises.rename;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith(`${path.sep}hello.json`)) {
+ renameSpy.mockRestore();
+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
+ err.code = 'EACCES';
+ throw err;
+ }
+ return realRename(from, to);
});
+ const first = await manager.migrateLegacyApprovalsOnce();
+ // 瞬时错不算"内容无效":不进 failed(那会写进 completed 台账永久封门),
+ // 记 retryPending、台账停在 in-progress。
+ expect(first.retryPending).toEqual(['hello']);
+ expect(first.failed).toEqual([]);
+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ pendingIds?: string[];
+ };
+ expect(ledger.state).toBe('in-progress');
+ expect(ledger.pendingIds).toEqual(['hello']);
+
+ // 第二轮(下次启动):环境恢复,自动续跑治愈,不需要用户操作。
+ const second = await manager.migrateLegacyApprovalsOnce();
+ expect(second.migrated).toEqual(['hello']);
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ const finalLedger = JSON.parse(
+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),
+ ) as { state?: string };
+ expect(finalLedger.state).toBe('completed');
});
- it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {
- const manifest = {
- ...goodManifest(),
- locales: { en: 'locales/en.json' },
+ it('读 legacy ghost.json 的瞬时 IO(EACCES)判瞬时、不永久封门(P1 回归)', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ const realOpenSync = fs.openSync;
+ // 只让 <root>/hello/ghost.json 的单句柄安全读取吃一次 EACCES(模拟杀软/句柄占用),
+ // 其余照常。
+ const spy = vi
+ .spyOn(fs, 'openSync')
+ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {
+ if (typeof p === 'string' && p.endsWith(path.join('hello', 'ghost.json'))) {
+ spy.mockRestore();
+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
+ err.code = 'EACCES';
+ throw err;
+ }
+ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);
+ }) as typeof fs.openSync);
+
+ const first = await manager.migrateLegacyApprovalsOnce();
+ // 修复前:readFileSync 的错被包成无 code 的 new Error → 误判确定性 failed →
+ // 写进 completed 台账永久封门。修复后:保留 errno → 判瞬时 → retryPending + in-progress。
+ expect(first.retryPending).toEqual(['hello']);
+ expect(first.failed).toEqual([]);
+ const ledger = JSON.parse(fs.readFileSync(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
};
- const missing = await makeCindy('locale-missing.cindy', manifest);
- await expectRejection(await manager.install(missing), 'file-invalid');
+ expect(ledger.state).toBe('in-progress');
- const invalid = await makeCindy('locale-invalid.cindy', manifest, {
- 'locales/en.json': '{ nope',
+ // 下轮环境恢复:自动续跑治愈,不需要用户重新确认。
+ const second = await manager.migrateLegacyApprovalsOnce();
+ expect(second.migrated).toEqual(['hello']);
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ });
+
+ it('legacy .disabled marker IO errors stay pending instead of becoming disabled', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ const markerPath = path.join(rootDir, 'hello', '.disabled');
+ const realLstatSync = fs.lstatSync;
+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {
+ if (path.resolve(String(target)) === path.resolve(markerPath)) {
+ spy.mockRestore();
+ throw Object.assign(new Error('EIO: marker temporarily unreadable'), { code: 'EIO' });
+ }
+ return realLstatSync(target, options as never);
});
- await expectRejection(await manager.install(invalid), 'file-invalid');
- const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {
- 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),
+ const first = await manager.migrateLegacyApprovalsOnce();
+ expect(first).toMatchObject({ migrated: [], failed: [], retryPending: ['hello'] });
+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({
+ state: 'in-progress',
+ pendingIds: ['hello'],
});
- await expectRejection(await manager.install(unknownTool), 'file-invalid');
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'legacy-unapproved' } });
- // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。
- hostLocale = 'en';
- const partial = await makeCindy('locale-partial.cindy', manifest, {
- 'locales/en.json': JSON.stringify({ name: 'English partial' }),
+ const second = await manager.migrateLegacyApprovalsOnce();
+ expect(second.migrated).toEqual(['hello']);
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ });
+
+ it('已有 receipt 瞬时不可读时不从可变安装目录重铸,保留原批准并持久重试', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');
+ // 模拟 #1080 历史状态没有 ledger;receipt 本身只是在本轮被 AV/权限瞬时锁住。
+ await fs.promises.rm(migrationLedgerPath());
+ const realOpenSync = fs.openSync;
+ const openSpy = vi.spyOn(fs, 'openSync');
+ openSpy.mockImplementation((target, ...args) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {
+ openSpy.mockRestore();
+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
+ }
+ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);
});
- expect(await manager.install(partial)).toMatchObject({
- ghost: {
- manifest: {
- name: 'English partial',
- resolvedLocale: 'en',
- tools: [{ name: 'do_thing', description: '做点事' }],
- },
- },
+
+ const first = await manager.migrateLegacyApprovalsOnce();
+
+ expect(first).toEqual({ migrated: [], skipped: [], failed: [], retryPending: ['hello'] });
+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);
+ expect(
+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),
+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });
+
+ await manager.migrateLegacyApprovalsOnce();
+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);
+ expect(
+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })
+ .state,
+ ).toBe('completed');
+ });
+
+ it('首轮迁移治愈损坏/旧 schema 的 receipt(格式升级不落到用户重新确认)', async () => {
+ // issue #1243 验收第 4 条的实现形态:schema/编码 bump 后的旧 receipt 判 invalid,
+ // 但**首轮迁移**会把它当"已判损坏"从安装目录 backfill 重建 —— 一次内部格式变更
+ // 不变成用户重新确认。v1 receipt 从未随任何构建发布,所以不需要专门的 v1 读取器;
+ // 未来的 bump 走 §5 的「按旧编码核对 → 原地升级」,见规则文档。
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const stateDir = path.join(workDir, 'ghosts-install-state');
+ await fs.promises.mkdir(stateDir, { recursive: true });
+ // 一份 schemaVersion 过时的 receipt(读取器判 invalid)。
+ await fs.promises.writeFile(
+ path.join(stateDir, 'hello.json'),
+ JSON.stringify({ schemaVersion: 1, id: 'hello', legacy: true }),
+ );
+ expect(manager.list()[0].approval.state).toBe('invalid');
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['hello']);
+ // 治愈后为有效批准;用户的停用决定(.disabled)照旧保留。
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'approved' },
});
+ });
- const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {
- 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),
+ it('修复 #1080 历史 mixed 状态:有效 receipt 不封死其余 legacy/旧 schema 插件', async () => {
+ await manager.install(await makeCindy('approved.cindy', goodManifest('approved')));
+ const approvedReceiptPath = path.join(workDir, 'ghosts-install-state', 'approved.json');
+ const approvedReceiptBefore = await fs.promises.readFile(approvedReceiptPath, 'utf8');
+
+ // Fixture 模拟曾短暂合入后回滚的 #1080:部分插件已有 v2 receipt,但当时没有
+ // legacy migration ledger;同 owner 下其余旧安装仍无 receipt。删除 ledger 只是
+ // 构造这份历史状态,不代表安装根攻击者能操作状态根。
+ await fs.promises.rm(migrationLedgerPath());
+ await writeLegacyInstall('legacy', goodManifest('legacy'));
+ await writeLegacyInstall('old-schema', goodManifest('old-schema'), { disabled: true });
+ await fs.promises.writeFile(
+ path.join(workDir, 'ghosts-install-state', 'old-schema.json'),
+ JSON.stringify({ schemaVersion: 1, id: 'old-schema', legacy: true }),
+ );
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+
+ expect(outcome.migrated).toEqual(['legacy', 'old-schema']);
+ expect(await fs.promises.readFile(approvedReceiptPath, 'utf8')).toBe(approvedReceiptBefore);
+ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));
+ expect(byId.approved.approval.state).toBe('approved');
+ expect(byId.legacy).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ expect(byId['old-schema']).toMatchObject({
+ enabled: false,
+ approval: { state: 'approved' },
});
- await expectRejection(await manager.install(aliasedManifest), 'file-invalid');
});
- it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {
- const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });
- const result = await manager.install(cindy);
- expect('ghost' in result).toBe(true);
- const { ghost } = result as { ghost: InstalledGhost };
- expect(ghost.manifest.id).toBe('hello');
- expect(ghost.dir).toBe(path.join(rootDir, 'hello'));
- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);
+ it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const before = await fs.promises.readFile(
+ path.join(workDir, 'ghosts-install-state', 'hello.json'),
+ 'utf8',
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual([]);
+ expect(await fs.promises.readFile(path.join(workDir, 'ghosts-install-state', 'hello.json'), 'utf8')).toBe(
+ before,
+ );
+ });
- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);
- expect(onChanged).toHaveBeenCalledTimes(1);
- expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);
+ it('声明的 locale 文件损坏 → fail closed(装入天然不含坏 locale,读到即装入后损坏)', async () => {
+ hostLocale = 'en';
+ await writeLegacyInstall(
+ 'hello',
+ { ...goodManifest(), name: 'Base', locales: { en: 'locales/en.json' } },
+ { files: { 'locales/en.json': '{ broken json' } },
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ // 装入流程逐个校验声明的 locale、不合格拒装,所以旧安装不会带坏 locale;迁移时
+ // 读到坏 locale 只能是装入后损坏,属 §5 的"自相矛盾 → fail closed",不写坏 receipt。
+ expect(outcome.failed).toEqual(['hello']);
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
});
+});
- it('本地包仅自报 cindy-github 不会获得官方 trust;Host override 才能写官方 receipt', async () => {
- const local = await makeCindy('github-local.cindy', goodManifest('cindy-github'));
- const localResult = await manager.install(local);
- expect(localResult).toMatchObject({ ghost: { trust: { level: 'unverified' } } });
- await fs.promises.rm(path.join(rootDir, 'cindy-github'), { recursive: true, force: true });
+describe('GhostManager · owner 受管根路径', () => {
+ it('允许 userData 祖先通过 symlink/junction 重定位', async () => {
+ const physicalUserData = path.join(workDir, 'physical-user-data');
+ const linkedUserData = path.join(workDir, 'linked-user-data');
+ await fs.promises.mkdir(path.join(physicalUserData, 'owners', 'owner-a'), { recursive: true });
+ try {
+ await fs.promises.symlink(
+ physicalUserData,
+ linkedUserData,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
- const officialResult = await manager.install(local, { trustOverride: 'cindy-official' });
- expect(officialResult).toMatchObject({ ghost: { trust: { level: 'cindy-official' } } });
- const receipt = JSON.parse(
- await fs.promises.readFile(path.join(rootDir, 'cindy-github', '.cindy-trust.json'), 'utf8'),
- ) as { level?: unknown };
- expect(receipt.level).toBe('cindy-official');
- expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);
- expect(manager.list()[0].trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);
+ const relocated = new GhostManager({
+ getRootDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'cindy-brain'),
+ getStateDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'ghost-install-state'),
+ });
+
+ expect(relocated.list()).toEqual([]);
});
- it('残缺的官方 receipt 不会被投影为可用的官方 trust', async () => {
- const local = await makeCindy('github-incomplete-receipt.cindy', goodManifest('cindy-github'));
- await manager.install(local, { trustOverride: 'cindy-official' });
- const metadataPath = path.join(rootDir, 'cindy-github', '.cindy-trust.json');
- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;
- delete metadata.publisherName;
- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
+ it('允许全新 owner 的多层受管根尚未创建', () => {
+ const freshOwner = path.join(workDir, 'owners', 'fresh-owner');
+ const fresh = new GhostManager({
+ getRootDir: () => path.join(freshOwner, 'cindy-brain'),
+ getStateDir: () => path.join(freshOwner, 'ghost-install-state'),
+ });
- expect(manager.list()[0]?.trust).toBeUndefined();
+ expect(fresh.list()).toEqual([]);
});
- it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {
- const cindy = await makeCindy('at-resource.cindy', atResourceManifest());
- const installed = await manager.install(cindy);
+ it('仍拒绝受管根本身是 symlink/junction', async () => {
+ const outside = path.join(workDir, 'outside-root');
+ const linkedRoot = path.join(workDir, 'linked-root');
+ await fs.promises.mkdir(outside, { recursive: true });
+ try {
+ await fs.promises.symlink(outside, linkedRoot, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return;
+ }
- const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');
- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;
+ expect(
+ () =>
+ new GhostManager({
+ getRootDir: () => linkedRoot,
+ getStateDir: () => path.join(workDir, 'state-root'),
+ }),
+ ).toThrow(/ghost content root is not a real directory/);
+ });
+});
- delete metadata.approvedAtResourceProvider;
- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
- expect(manager.list()[0].manifest.tools).toEqual([
- { name: 'do_thing', description: '做点事' },
- ]);
+describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命名空间', () => {
+ it('中途崩溃后按 pendingIds 续跑:已迁的跳过、剩余补迁、台账推进到 completed', async () => {
+ // 复现真实崩溃现场:首轮迁移在 aaa 写完 receipt(receipt 首写自动落账被
+ // in-progress 台账挡住)、bbb 还没动笔时进程死掉。
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await writeLegacyInstall('bbb', goodManifest('bbb'));
+ await manager.migrateLegacyApprovalsOnce();
+ // 手工把状态倒回"崩溃时刻":台账退回 in-progress、bbb 的 receipt 消失。
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['aaa', 'bbb'],
+ }),
+ );
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'bbb.json'));
- metadata.approvedAtResourceProvider = { tool: 'other_tool' };
- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ // bbb 被续跑补迁;aaa 已有 receipt,计入 migrated(它就是迁移铸出的)。
+ expect(outcome.migrated).toEqual(['bbb']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId).toEqual({ aaa: 'approved', bbb: 'approved' });
+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ migratedIds: string[];
+ };
+ expect(ledger.state).toBe('completed');
+ expect(ledger.migratedIds).toEqual(['aaa', 'bbb']);
});
- it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {
- const cindy = await makeCindy('hello.cindy', goodManifest());
- const result = await manager.install(cindy, { initiallyEnabled: false });
- expect('ghost' in result).toBe(true);
- expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);
+ it('续跑只认动笔前钉死的清单:清单外的无 receipt 目录不被重铸', async () => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ // 迁移窗口期间新装再删 receipt 的插件(不在 pendingIds 里)骗不到续跑。
+ await writeLegacyInstall('ccc', goodManifest('ccc'));
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['aaa'],
+ }),
+ );
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['aaa']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId.aaa).toBe('approved');
+ expect(byId.ccc).toBe('legacy-unapproved');
+ expect(
+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })
+ .state,
+ ).toBe('completed');
+ });
+
+ it('receipt 首写的自动落账不覆盖 in-progress 台账(崩溃门不被焊死)', async () => {
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['zzz'],
+ }),
+ );
+ // 迁移窗口内经正常装入流程写 receipt(内部有"缺台账即补写 completed"的守卫)。
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ };
+ expect(ledger.state).toBe('in-progress');
+ });
+
+ it('台账存在但读不出:门保守关死,不迁也不重写', async () => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(migrationLedgerPath(), '{ not valid json');
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{ not valid json');
+ });
+
+ it.each([
+ ['empty pendingIds', []],
+ ['non-string pending id', [null]],
+ ['path-traversal pending id', ['../x']],
+ ['mixed valid and invalid pending ids', ['aaa', '../x']],
+ ])('非法 in-progress 台账(%s)保守关门且不被重写成 completed', async (_label, pendingIds) => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });
+ const raw = JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds,
+ });
+ await fs.promises.writeFile(migrationLedgerPath(), raw);
+
+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({
+ migrated: [],
+ skipped: [],
+ failed: [],
+ retryPending: [],
+ });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe(raw);
+ });
+
+ it('启用失败的回滚按"镜像先前是否在盘上",不吞掉旧客户端的停用决定', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 旧客户端只写镜像:receipt.enabled=true + .disabled 在盘 → 读时合并 = 停用。
+ const marker = path.join(rootDir, 'hello', '.disabled');
+ await fs.promises.writeFile(marker, '');
+ expect(manager.list()[0].enabled).toBe(false);
+
+ // receipt 落盘的 rename 失败(状态根抖动):启用必须整体失败且镜像原样放回。
+ const realRename = fs.promises.rename;
+ const spy = vi
+ .spyOn(fs.promises, 'rename')
+ .mockImplementation(async (from, to) => {
+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');
+ return realRename(from, to);
+ });
+ try {
+ const result = await manager.setEnabled('hello', true);
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(fs.existsSync(marker)).toBe(true);
+ expect(manager.list()[0].enabled).toBe(false);
+ });
+
+ it('进程内隔离按状态根命名空间:A 账号的隔离不污染 B,切回 A 仍生效', async () => {
+ let stateDir = path.join(workDir, 'owner-a-state');
+ const owned = new GhostManager({
+ getRootDir: () => rootDir,
+ getStateDir: () => stateDir,
+ getLocale: () => hostLocale,
+ });
+ await owned.install(await makeCindy('a.cindy', goodManifest()));
+ // 撤销失败 → A 的进程内隔离。
+ const realRm = fs.promises.rm;
+ const spy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, opts) => {
+ if (String(target).endsWith('hello.json')) throw new Error('EACCES');
+ return realRm(target as never, opts as never);
+ });
+ try {
+ await owned.removeInstallApproval('hello');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(owned.list()[0].approval.state).toBe('invalid');
+
+ // 切到 B 账号(状态根变了):同 id 不被 A 的隔离污染 —— B 没有 receipt,
+ // 如实是 legacy-unapproved 而不是 invalid。
+ stateDir = path.join(workDir, 'owner-b-state');
+ expect(owned.list()[0].approval.state).toBe('legacy-unapproved');
+
+ // 切回 A:隔离仍在(盘上那份陈旧 receipt 不得复活)。
+ stateDir = path.join(workDir, 'owner-a-state');
+ expect(owned.list()[0].approval.state).toBe('invalid');
+ });
+
+ it('安装根下的 junction 不算已装插件:迁移不迁它,list 不列它', async () => {
+ await writeLegacyInstall('real', goodManifest('real'));
+ const outside = path.join(workDir, 'outside-plugin');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'ghost.json'), JSON.stringify(goodManifest('planted')));
+ try {
+ fs.symlinkSync(outside, path.join(rootDir, 'planted'), 'junction');
+ } catch {
+ return; // 环境建不了链接则跳过;判据逻辑平台无关。
+ }
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['real']);
+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['real']);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'planted.json'))).toBe(false);
+ });
+});
+
+describe('GhostManager · 从已装目录重新确认(本地包第三条恢复路径)', () => {
+ it('批准丢失后不用原始 .cindy:inspect 出全量清单,确认后开 receipt、恢复可用', async () => {
+ // 场景:迁移已跑过(ledger 在),之后 receipt 又被删 —— 一次性门不再迁移,
+ // 本地包用户没有市场路线;第三条路必须能不找文件恢复。
+ await writeLegacyInstall('hello', goodManifest());
+ await manager.migrateLegacyApprovalsOnce();
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ expect(inspected.manifest.id).toBe('hello');
+ expect(inspected.manifestSha256).toMatch(/^[a-f0-9]{64}$/);
+
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ // 启停镜像同步维护(回滚到旧客户端不错位)。
+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);
+ });
+
+ it('重新确认要求立即启用时,删除停用镜像失败必须拒绝且不提交批准', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ const marker = path.join(rootDir, 'hello', '.disabled');
+ const realRm = fs.promises.rm;
+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
+ if (path.resolve(String(target)) === path.resolve(marker)) {
+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });
+ }
+ return realRm(target, options);
+ });
+ try {
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'legacy-unapproved' },
+ });
+ expect(fs.existsSync(marker)).toBe(true);
+ } finally {
+ rmSpy.mockRestore();
+ }
+ });
+
+ it('重新确认要求立即启用时,receipt 提交失败必须恢复原停用镜像', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ const marker = path.join(rootDir, 'hello', '.disabled');
+ const realRename = fs.promises.rename;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');
+ return realRename(from, to);
+ });
+ try {
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'legacy-unapproved' },
+ });
+ expect(fs.existsSync(marker)).toBe(true);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ });
+
+ it('重新确认不跟随确认后被换成 junction 的安装目录写删停用镜像', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ const dir = path.join(rootDir, 'hello');
+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-outside-'));
+ const outsideMarker = path.join(outside, '.disabled');
+ await fs.promises.writeFile(outsideMarker, 'sentinel');
+ const probe = path.join(workDir, 'reapprove-junction-probe');
+ try {
+ await fs.promises.symlink(outside, probe, process.platform === 'win32' ? 'junction' : 'dir');
+ await fs.promises.rm(probe, { force: true });
+ } catch {
+ await fs.promises.rm(outside, { recursive: true, force: true });
+ return;
+ }
+ const realInspect = manager.inspectInstalledReapproval.bind(manager);
+ const inspectSpy = vi.spyOn(manager, 'inspectInstalledReapproval').mockImplementation(async (ghostId) => {
+ const result = await realInspect(ghostId);
+ await fs.promises.rm(dir, { recursive: true, force: true });
+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');
+ return result;
+ });
+ try {
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('state-changed');
+ expect(await fs.promises.readFile(outsideMarker, 'utf8')).toBe('sentinel');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ } finally {
+ inspectSpy.mockRestore();
+ await fs.promises.rm(outside, { recursive: true, force: true });
+ }
+ });
+
+ it('重新确认 receipt 失败回滚前目录被换成 junction 时不得写入外部目标', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ const dir = path.join(rootDir, 'hello');
+ const displaced = path.join(rootDir, 'hello-displaced');
+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-rollback-'));
+ let linkCreated = false;
+ const realRename = fs.promises.rename;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith('hello.json')) {
+ await realRename(dir, displaced);
+ try {
+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');
+ linkCreated = true;
+ } catch {
+ await realRename(displaced, dir);
+ }
+ throw new Error('state root unwritable');
+ }
+ return realRename(from, to);
+ });
+ try {
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ if (linkCreated) expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);
+ } finally {
+ renameSpy.mockRestore();
+ await fs.promises.rm(outside, { recursive: true, force: true });
+ }
+ });
+
+ it('确认间隙 ghost.json 被换 → 拒(确认卡展示的与批准的必须是同一份字节)', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+
+ // 攻击窗口:用户看的是权限集 A,confirm 落地前清单被换成声明更多权限的 B。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'ghost.json'),
+ JSON.stringify({ ...goodManifest(), name: 'Changed after review' }),
+ );
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('state-changed');
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ });
+
+ it.each(['skill', 'locale', 'icon', 'trust'] as const)(
+ '确认间隙 %s 批准投影被换 → 拒绝重新确认',
+ async (kind) => {
+ const manifest = {
+ ...goodManifest(),
+ author: 'Original author',
+ icon: 'assets/icon.png',
+ locales: { en: 'locales/en.json' },
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ };
+ await writeLegacyInstall('hello', manifest, {
+ files: {
+ 'assets/icon.png': 'ORIGINAL ICON',
+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),
+ 'skills/demo/SKILL.md':
+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',
+ },
+ });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+
+ if (kind === 'skill') {
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',
+ );
+ } else if (kind === 'locale') {
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'locales', 'en.json'),
+ JSON.stringify({ name: 'Replaced name' }),
+ );
+ } else if (kind === 'icon') {
+ await fs.promises.writeFile(path.join(rootDir, 'hello', 'assets', 'icon.png'), 'REPLACED ICON');
+ } else {
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', '.cindy-trust.json'),
+ JSON.stringify({
+ level: 'verified-publisher',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Different publisher',
+ }),
+ );
+ }
+
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('state-changed');
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ },
+ );
+
+ it('随包插件拒走人工重新确认(由启动对账自动补批准)', async () => {
+ const guarded = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: (id) => id === 'hello',
+ });
+ await writeLegacyInstall('hello', goodManifest());
+ const inspected = await guarded.inspectInstalledReapproval('hello');
+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');
+ });
+
+ it('已是 approved 的插件拒重复确认(不给覆盖既有批准开口子)', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ expect('rejection' in inspected && inspected.rejection.code).toBe('state-changed');
+ });
+
+ it('信任镜像自称 cindy-official 一律封顶拒收(非随包目录不可能合法持有官方档)', async () => {
+ await writeLegacyInstall('hello', goodManifest(), {
+ trust: {
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ },
+ });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ expect(inspected.trust.level).toBe('unverified');
+ });
+});
+
+describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
+ it('P0-3:停用在 receipt 写失败时仍然生效,且跨实例(重启)持久', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ expect(manager.list()[0].enabled).toBe(true);
+
+ // 状态根不可写(AV/权限/磁盘故障):receipt 的 rename 提交失败。
+ const realRename = fs.promises.rename;
+ const renameSpy = vi
+ .spyOn(fs.promises, 'rename')
+ .mockImplementation(async (from, to) => {
+ if (String(to).includes('ghosts-install-state')) {
+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ // 停用必须永远能成功:镜像已落盘,如实返回 ok,而不是 io + 回滚镜像(fail open)。
+ expect(await manager.setEnabled('hello', false)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(false);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ // "重启"(新实例,内存态清零):镜像在盘上,停用不复活。
+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
+ expect(restarted.list()[0].enabled).toBe(false);
+ // 启用方向照旧要求 receipt 写成功(此时状态根已恢复可写)。
+ expect(await manager.setEnabled('hello', true)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(true);
+ });
+
+ it('P0-5:嵌套 skill dir(祖先包含子项)装入/快照/校验全通,不撞 COPYFILE_EXCL', async () => {
+ const nested = {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [
+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },
+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },
+ ],
+ },
+ };
+ const files = {
+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',
+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',
+ };
+ const result = await manager.install(await makeCindy('nested.cindy', nested, files));
+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));
+ const ghost = manager.list()[0];
+ expect(ghost.approval.state).toBe('approved');
+ // 两个 item 的字节指纹都能对上(嵌套项的根就在祖先拷出的快照树里)。
+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);
+ });
+
+ it('P0-5:嵌套 skill dir 的旧安装迁移同样成功(存量兼容红线)', async () => {
+ await writeLegacyInstall(
+ 'skilled',
+ {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [
+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },
+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },
+ ],
+ },
+ },
+ {
+ files: {
+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',
+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',
+ },
+ },
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['skilled']);
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ });
+
+ it('P0-2:安装根为空/未诞生时不落台账,legacy 恢复流程随后搬入仍可迁移', async () => {
+ // 首轮:根目录还不存在(owner 命名空间刚建立,旧目录尚未被恢复流程搬入)。
+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({
+ migrated: [],
+ skipped: [],
+ failed: [],
+ retryPending: [],
+ });
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+ // 恢复流程把旧布局目录搬进来 → 门还开着,照常迁移。
+ await writeLegacyInstall('hello', goodManifest());
+ const second = await manager.migrateLegacyApprovalsOnce();
+ expect(second.migrated).toEqual(['hello']);
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ });
+
+ it('P0-2:首个 receipt 写入即自动落台账 —— "装插件→删 receipt"骗不到迁移', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 新模型首次活动(装入写 receipt)时台账已经落了,不等下一轮 reconcile。
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ // 攻击:改写安装目录 manifest 扩权,再删掉 receipt,指望迁移按新 manifest 重铸批准。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'ghost.json'),
+ JSON.stringify({
+ ...goodManifest(),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 's', name: 's', description: 's' }] },
+ }),
+ );
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ });
+
+ it('P0-2:首次批准先提交 migration ledger,落账失败时不留下有效 receipt', async () => {
+ const renameTargets: string[] = [];
+ const realRename = fs.promises.rename;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ const target = String(to);
+ renameTargets.push(target);
+ if (target.endsWith('.legacy-migration.json')) {
+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ const result = await manager.install(await makeCindy('a.cindy', goodManifest()));
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ } finally {
+ renameSpy.mockRestore();
+ }
+
+ expect(renameTargets.some((target) => target.endsWith('.legacy-migration.json'))).toBe(true);
+ expect(renameTargets.some((target) => target.endsWith(`${path.sep}hello.json`))).toBe(false);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ // Ledger commit failed before the receipt became visible, so the install
+ // transaction rolls back the final directory as well; no ghost is listed.
+ expect(manager.list()).toEqual([]);
+ });
+
+ it('首次批准与目录回滚同时失败时保留 install journal,不让迁移收编未提交字节', async () => {
+ const finalDir = path.join(rootDir, 'hello');
+ const pendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');
+ const realRename = fs.promises.rename;
+ const realRm = fs.promises.rm;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith('.legacy-migration.json')) {
+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });
+ }
+ return realRename(from as never, to as never);
+ });
+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
+ if (path.resolve(String(target)) === path.resolve(finalDir)) {
+ throw Object.assign(new Error('EBUSY: installed directory locked'), { code: 'EBUSY' });
+ }
+ return realRm(target, options);
+ });
+ try {
+ await expect(manager.install(await makeCindy('a.cindy', goodManifest()))).resolves.toMatchObject(
+ { rejection: { code: 'io' } },
+ );
+ } finally {
+ renameSpy.mockRestore();
+ rmSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(pendingPath)).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+
+ const migration = await manager.migrateLegacyApprovalsOnce();
+ expect(migration.migrated).toEqual([]);
+ expect(migration.skipped).toContain('hello');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ });
+ expect(recovered.list()).toEqual([]);
+ expect(fs.existsSync(finalDir)).toBe(false);
+ expect(fs.existsSync(pendingPath)).toBe(false);
+ });
+
+ it('P0-2:安装根读失败(EACCES 类)本轮放弃且不落台账,不把迁移永久封死', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ const realReaddir = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((dir: never, opts: never) => {
+ if (String(dir) === rootDir) {
+ throw Object.assign(new Error('EACCES: install root locked'), { code: 'EACCES' });
+ }
+ return realReaddir(dir, opts);
+ }) as never);
+ try {
+ await expect(manager.migrateLegacyApprovalsOnce()).rejects.toThrow(/EACCES/);
+ } finally {
+ spy.mockRestore();
+ }
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+ // 环境恢复后下一轮照常迁移。
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['hello']);
+ });
+
+ it('P0-2:恢复旁路只补给定 id,台账门对其余目录照常生效', async () => {
+ // 台账已落(首轮迁移空跑一个插件)。
+ await writeLegacyInstall('first', goodManifest('first'));
+ await manager.migrateLegacyApprovalsOnce();
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ // 恢复流程搬入两个目录,但只把 recovered 声明为其中一个。
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ await writeLegacyInstall('planted', goodManifest('planted'));
+ const out = await manager.backfillRecoveredLegacyGhosts(
+ ['recovered'],
+ await recoveredProjectionOptions('recovered'),
+ );
+ expect(out.migrated).toEqual(['recovered']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId.recovered).toBe('approved');
+ expect(byId.planted).toBe('legacy-unapproved');
+ });
+
- it.each(['manifest', 'disabled', 'trust', 'locale', 'icon', 'skill'] as const)(
++ it.each(['manifest', 'disabled', 'trust', 'locale', 'skill'] as const)(
+ '恢复 backfill 在 %s 批准投影漂移时保持 fail closed',
+ async (kind) => {
+ const manifest = {
+ ...goodManifest('recovered'),
+ icon: 'assets/icon.png',
+ locales: { en: 'locales/en.json' },
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ };
+ await writeLegacyInstall('recovered', manifest, {
+ files: {
+ 'assets/icon.png': 'ORIGINAL ICON',
+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),
+ 'skills/demo/SKILL.md':
+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',
+ },
+ });
+ const expected = await recoveredProjectionOptions('recovered');
+ const dir = path.join(rootDir, 'recovered');
+ if (kind === 'manifest') {
+ await fs.promises.writeFile(
+ path.join(dir, 'ghost.json'),
+ JSON.stringify({
+ ...manifest,
+ tools: [
+ { name: 'do_thing', description: '做点事' },
+ { name: 'new_thing', description: 'New privileged tool' },
+ ],
+ }),
+ );
+ } else if (kind === 'disabled') {
+ await fs.promises.writeFile(path.join(dir, '.disabled'), '');
+ } else if (kind === 'trust') {
+ await fs.promises.writeFile(
+ path.join(dir, '.cindy-trust.json'),
+ JSON.stringify({
+ level: 'verified-publisher',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: false,
+ }),
+ );
+ } else if (kind === 'locale') {
+ await fs.promises.writeFile(
+ path.join(dir, 'locales', 'en.json'),
+ JSON.stringify({ name: 'Replaced name' }),
+ );
- } else if (kind === 'icon') {
- await fs.promises.writeFile(path.join(dir, 'assets', 'icon.png'), 'REPLACED ICON');
+ } else {
+ await fs.promises.writeFile(
+ path.join(dir, 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',
+ );
+ }
+
+ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);
+ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),
+ ).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ },
+ );
+
- it('fails closed when the legacy icon cannot be read during approval freezing', async () => {
++ it('keeps legacy approval backfill eligible when the optional icon cannot be read', async () => {
+ await writeLegacyInstall(
+ 'recovered',
+ {
+ ...goodManifest('recovered'),
+ icon: 'assets/icon.png',
+ },
+ {
+ files: {
+ 'assets/icon.png': 'ORIGINAL ICON',
+ },
+ },
+ );
+ const realOpenSync = fs.openSync;
+ const spy = vi
+ .spyOn(fs, 'openSync')
+ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {
+ if (
+ typeof p === 'string' &&
+ p.endsWith(path.join('recovered', 'assets', 'icon.png'))
+ ) {
+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
+ err.code = 'EACCES';
+ throw err;
+ }
+ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);
+ }) as typeof fs.openSync);
+
+ try {
- await expect(
- readLegacyGhostApprovalProjection(path.join(rootDir, 'recovered'), 'recovered'),
- ).rejects.toThrow(/EACCES: permission denied/i);
++ const result = await readLegacyGhostApprovalProjection(path.join(rootDir, 'recovered'), 'recovered');
++ expect(result.projection.iconDataUrl).toBeUndefined();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('恢复 backfill 不跟随被换成 junction 的插件根目录', async () => {
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ const expected = await recoveredProjectionOptions('recovered');
+ const installedDir = path.join(rootDir, 'recovered');
+ const externalDir = path.join(workDir, 'external-recovered');
+ await fs.promises.rename(installedDir, externalDir);
+ await fs.promises.symlink(externalDir, installedDir, 'junction');
+
+ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);
+ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json'))).toBe(false);
+ });
+
+ it('closes the recovery ledger when a queued id is already approved', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['hello'],
+ }),
+ );
+
+ await expect(
+ manager.backfillRecoveredLegacyGhosts(
+ ['hello'],
+ { expectedApprovalProjectionSha256ById: {} },
+ ),
+ ).resolves.toEqual({
+ migrated: [],
+ failed: [],
+ });
+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({
+ state: 'completed',
+ });
+ });
+
+ it('keeps a target-only legacy recovery without a frozen projection fail closed', async () => {
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+
+ await expect(
+ manager.backfillRecoveredLegacyGhosts(
+ ['recovered'],
+ { expectedApprovalProjectionSha256ById: {} },
+ ),
+ ).resolves.toEqual({
+ migrated: [],
+ failed: ['recovered'],
+ });
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),
+ ).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ });
+
+ it('恢复旁路遇到 unreadable receipt 同样只排队重试,不重铸批准', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');
+ await fs.promises.rm(migrationLedgerPath());
+ const realOpenSync = fs.openSync;
+ const openSpy = vi.spyOn(fs, 'openSync');
+ openSpy.mockImplementation((target, ...args) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {
+ openSpy.mockRestore();
+ throw Object.assign(new Error('EIO: receipt temporarily unreadable'), { code: 'EIO' });
+ }
+ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);
+ });
+
+ expect(
+ await manager.backfillRecoveredLegacyGhosts(
+ ['hello'],
+ await recoveredProjectionOptions('hello'),
+ ),
+ ).toEqual({
+ migrated: [],
+ failed: [],
+ });
+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);
+ expect(
+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),
+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });
+ });
+
+ it('persists transient recovered-legacy backfill failures in the migration work queue', async () => {
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ const realRename = fs.promises.rename;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith(`${path.sep}recovered.json`)) {
+ renameSpy.mockRestore();
+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
+ err.code = 'EACCES';
+ throw err;
+ }
+ return realRename(from, to);
+ });
+
+ const expected = await recoveredProjectionOptions('recovered');
+ const first = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);
+ expect(first).toEqual({ migrated: [], failed: [] });
+ const pendingLedger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ pendingIds?: string[];
+ };
+ expect(pendingLedger.state).toBe('in-progress');
+ expect(pendingLedger.pendingIds).toEqual(['recovered']);
+
+ const second = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);
+ expect(second.migrated).toEqual(['recovered']);
+ const completedLedger = JSON.parse(
+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),
+ ) as { state?: string; pendingIds?: string[] };
+ expect(completedLedger.state).toBe('completed');
+ expect(completedLedger.pendingIds).toBeUndefined();
+ });
+
+ it('persists recovered ids before the first receipt write starts', async () => {
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ const realRename = fs.promises.rename;
+ let queueSeenBeforeReceipt = false;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith(`${path.sep}recovered.json`)) {
+ const ledger = JSON.parse(
+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),
+ ) as { state?: string; pendingIds?: string[] };
+ queueSeenBeforeReceipt =
+ ledger.state === 'in-progress' && ledger.pendingIds?.includes('recovered') === true;
+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
+ err.code = 'EACCES';
+ throw err;
+ }
+ return realRename(from, to);
+ });
+
+ try {
+ await manager.backfillRecoveredLegacyGhosts(
+ ['recovered'],
+ await recoveredProjectionOptions('recovered'),
+ );
+ } finally {
+ renameSpy.mockRestore();
+ }
+ expect(queueSeenBeforeReceipt).toBe(true);
+ });
+
+ it('does not overwrite an existing recovery queue when the migration ledger is unreadable', async () => {
+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });
+ const originalLedger = {
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['existing'],
+ };
+ await fs.promises.writeFile(migrationLedgerPath(), JSON.stringify(originalLedger));
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ const realReadFileSync = fs.readFileSync;
+ const readSpy = vi.spyOn(fs, 'readFileSync').mockImplementation((target, options) => {
+ if (path.resolve(String(target)) === path.resolve(migrationLedgerPath())) {
+ throw Object.assign(new Error('EIO: ledger temporarily unreadable'), { code: 'EIO' });
+ }
+ return realReadFileSync(target, options as never);
+ });
+
+ try {
+ await expect(
+ manager.backfillRecoveredLegacyGhosts(
+ ['recovered'],
+ await recoveredProjectionOptions('recovered'),
+ ),
+ ).rejects.toThrow(
+ /ledger exists but is unreadable/,
+ );
+ } finally {
+ readSpy.mockRestore();
+ }
+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toEqual(
+ originalLedger,
+ );
+ });
+
+ it('P1-6:重新确认拒绝与已装插件撞名的指令', async () => {
+ await manager.install(
+ await makeCindy('holder.cindy', chipManifestWithCommand('holder', 'draw')),
+ );
+ await writeLegacyInstall('clasher', chipManifestWithCommand('clasher', 'Draw'));
+ const inspected = await manager.inspectInstalledReapproval('clasher');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ const result = await manager.reapproveInstalled('clasher', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('command-conflict');
+ });
+
+ it('P1-6:声明 tokenBroker 的目录拒走已装目录重新确认', async () => {
+ await writeLegacyInstall('brokered', {
+ ...goodManifest('brokered'),
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'token',
+ source: 'oauth',
+ oauth: { tokenBroker: 'github' },
+ },
+ ],
+ },
+ });
+ const inspected = await manager.inspectInstalledReapproval('brokered');
+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');
+ });
+
+ it('P1-7:重新确认的启停默认值取镜像读数,不重置用户停用偏好', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ expect(inspected.previouslyEnabled).toBe(false);
+ });
+
+ it('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const realRename = fs.promises.rename;
+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ // staging→final 与 backup→final 都失败(Windows 文件锁/AV 的典型形态)。
+ if (path.resolve(String(to)) === path.resolve(finalDir)) {
+ throw Object.assign(new Error('EPERM: dir locked'), { code: 'EPERM' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ const bumped = await makeCindy('b.cindy', { ...goodManifest(), version: '1.0.1' });
+ const result = await updateGhost(bumped);
+ expect('rejection' in result).toBe(true);
+ if (!('rejection' in result)) return;
+ expect(result.rejection.code).toBe('io');
+ expect(result.rejection.code === 'io' && result.rejection.rollbackFailed).toBe(true);
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ ).toBe(true);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
+
+describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {
+ const pendingMarkerPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);
+ const receiptPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `${id}.json`);
+ /** 在同一组根上新建 manager —— 构造期跑一次崩溃恢复扫描。 */
+ const freshManager = () =>
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+
+ it('崩溃的装入(有 finalDir、无 receipt、有 install 标记)被恢复删除,不被迁移收编', async () => {
+ // install 在 rename(staging→final) 之后、写 receipt 之前崩溃:finalDir 完整、无
+ // receipt、无 ledger。若不处理,迁移会把它(崩溃窗口内可能被改过 manifest)当 legacy
+ // 批准掉。事务标记让恢复识别它是"未完成安装"并删除。
+ await writeLegacyInstall('hello', goodManifest());
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256: 'a'.repeat(64) }),
+ );
+
+ const recovered = freshManager(); // 构造期恢复:删掉未完成安装
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ const outcome = await recovered.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual([]); // 目录已被删,迁移无对象
+ });
+
+ it('keeps a committed builtin restore successful and retries tombstone clearing from its journal', async () => {
+ trustedBundledIds.add('hello');
+ const clearBuiltinTombstone = vi
+ .fn<(id: string) => void>()
+ .mockImplementationOnce(() => {
+ throw new Error('state root temporarily unavailable');
+ })
+ .mockImplementation(() => undefined);
+ const restoringManager = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: (id) => trustedBundledIds.has(id),
+ clearBuiltinTombstone,
+ });
+
+ const installed = await restoringManager.install(
+ await makeCindy('builtin-restore.cindy', goodManifest()),
+ );
+
+ expect('ghost' in installed).toBe(true);
+ expect(restoringManager.list()[0]).toMatchObject({ approval: { state: 'approved' } });
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(JSON.parse(await fs.promises.readFile(pendingMarkerPath(), 'utf8'))).toMatchObject({
+ kind: 'install',
+ clearBuiltinTombstone: true,
+ });
+
+ const recoveredAfterClearFailure = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: (id) => trustedBundledIds.has(id),
+ clearBuiltinTombstone,
+ });
+
+ expect(clearBuiltinTombstone).toHaveBeenCalledTimes(2);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(recoveredAfterClearFailure.list()[0]).toMatchObject({
+ approval: { state: 'approved' },
+ });
+ });
+
+ it('install 恢复必须用 packageSha256 证明旧 receipt 属于这次安装', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ await fs.promises.rm(finalDir, { recursive: true, force: true });
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(finalDir, 'ghost.json'),
+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),
+ );
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'install',
+ packageSha256: 'f'.repeat(64),
+ }),
+ );
+
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+ expect(fs.existsSync(finalDir)).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('非法 pending marker 会阻断 orphan backup 启发式,不删除待人工恢复的 backup', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-abcdef12';
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: '..\\outside',
+ }),
+ );
+
+ const recovered = freshManager();
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('invalid pending marker filename blocks orphan-backup heuristics', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.rename(finalDir, backupDir);
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');
+ const invalidMarker = path.join(path.dirname(pendingMarkerPath()), '.pending-BAD!.json');
+ await fs.promises.writeFile(invalidMarker, '{}');
+
+ const recovered = freshManager();
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(invalidMarker)).toBe(true);
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('pending marker JSON 为 null 时按 invalid 保留现场,不让构造期恢复崩溃', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.rename(finalDir, backupDir);
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');
+ await fs.promises.writeFile(pendingMarkerPath(), 'null');
+
+ const recovered = freshManager();
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('状态根 journal 扫描 EACCES 时跳过全部恢复启发式,任何现场都不动', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const stateRoot = path.dirname(pendingMarkerPath());
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.mkdir(stagingDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realReaddirSync = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
+ if (path.resolve(String(target)) === path.resolve(stateRoot)) {
+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });
+ }
+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);
+ }) as typeof fs.readdirSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ // 未提交 update 已先移除 final;backup 不可读时保留整笔 journal,
+ // 因而此刻 final 仍缺失,等待下次可读时再由 recovery 收敛。
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(stagingDir)).toBe(true);
+ });
+
+ it('journal root unreadable blocks the whole owner even when installed ids cannot be enumerated yet', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const stateRoot = path.dirname(pendingMarkerPath());
+ const realReaddirSync = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
+ const resolved = path.resolve(String(target));
+ if (resolved === path.resolve(stateRoot) || resolved === path.resolve(rootDir)) {
+ throw Object.assign(new Error('EACCES: managed root locked'), { code: 'EACCES' });
+ }
+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);
+ }) as typeof fs.readdirSync);
+
+ let recovered: GhostManager;
+ try {
+ recovered = freshManager();
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('pending marker 读取 EACCES 时保留 marker/final/backup,不降级到 orphan cleanup', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realReadFileSync = fs.readFileSync;
+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(pendingMarkerPath())) {
+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });
+ }
+ return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.readFileSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ });
+
+ it('已提交 install 的 receipt 瞬时不可读时保留 final/receipt/journal 等待重试', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ }).packageSha256;
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256 }),
+ );
+ const realOpenSync = fs.openSync;
+ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {
+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
+ }
+ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);
+ }) as typeof fs.openSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('已提交 update 的 receipt lstat EACCES 时保留 final/backup/receipt/journal', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ }).packageSha256;
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256,
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realOpenSync = fs.openSync;
+ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {
+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
+ }
+ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);
+ }) as typeof fs.openSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('update backup lstat EACCES 时保留整笔 journal,不清 marker 继续猜恢复', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realLstatSync = fs.lstatSync;
+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(backupDir)) {
+ throw Object.assign(new Error('EACCES: backup locked'), { code: 'EACCES' });
+ }
+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.lstatSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('动态 owner 根切换时,首次读取会先恢复新 owner 的 pending mutation', async () => {
+ const rootA = rootDir;
+ const rootB = path.join(workDir, 'ghosts-b');
+ const stateA = path.join(workDir, 'state-a');
+ const stateB = path.join(workDir, 'state-b');
+ let activeRoot = rootA;
+ let activeState = stateA;
+ const backupName = '.cindy-updating-hello-abcdef12';
+ const finalDir = path.join(rootB, 'hello');
+ await fs.promises.mkdir(path.join(rootB, backupName), { recursive: true });
+ await fs.promises.writeFile(path.join(rootB, backupName, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(rootB, backupName, 'main.js'), 'old');
+ await fs.promises.mkdir(stateB, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(stateB, '.pending-hello.json'),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: backupName,
+ }),
+ );
+ const owned = new GhostManager({
+ getRootDir: () => activeRoot,
+ getStateDir: () => activeState,
+ getLocale: () => hostLocale,
+ });
+ activeRoot = rootB;
+ activeState = stateB;
+ expect(owned.list().map((ghost) => ghost.manifest.id)).toEqual(['hello']);
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(path.join(rootB, backupName))).toBe(false);
+ });
+
+ it('排队中的 mutation 在 owner 代际变化后拒绝执行', async () => {
+ const rootA = rootDir;
+ const rootB = path.join(workDir, 'ghosts-b');
+ const stateA = path.join(workDir, 'state-a');
+ const stateB = path.join(workDir, 'state-b');
+ let activeRoot = rootA;
+ let activeState = stateA;
+ let ownerGeneration = 0;
+ const owned = new GhostManager({
+ getRootDir: () => activeRoot,
+ getStateDir: () => activeState,
+ getOwnerContextKey: () => `owner:${ownerGeneration}`,
+ getLocale: () => hostLocale,
+ });
+
+ let markStarted!: () => void;
+ let releaseFirst!: () => void;
+ const started = new Promise<void>((resolve) => {
+ markStarted = resolve;
+ });
+ const first = owned.runExclusiveMutation(async () => {
+ markStarted();
+ await new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ });
+ await started;
+
+ const second = owned.runExclusiveMutation(async () => {
+ await fs.promises.mkdir(activeRoot, { recursive: true });
+ await fs.promises.writeFile(path.join(activeRoot, 'queued-write'), 'must not run');
+ });
+ const rejected = expect(second).rejects.toThrow(/owner context changed/);
+ activeRoot = rootB;
+ activeState = stateB;
+ ownerGeneration += 1;
+ releaseFirst();
+
+ await first;
+ await rejected;
+ expect(fs.existsSync(path.join(rootA, 'queued-write'))).toBe(false);
+ expect(fs.existsSync(path.join(rootB, 'queued-write'))).toBe(false);
+ });
+
+ it('执行中的独占 mutation 钉住 owner 内容根与状态根,不把后半段写进新 owner', async () => {
+ const rootA = path.join(workDir, 'owned-a');
+ const rootB = path.join(workDir, 'owned-b');
+ const stateA = path.join(workDir, 'owned-state-a');
+ const stateB = path.join(workDir, 'owned-state-b');
+ let activeRoot = rootA;
+ let activeState = stateA;
+ let ownerGeneration = 0;
+ const owned = new GhostManager({
+ getRootDir: () => activeRoot,
+ getStateDir: () => activeState,
+ getOwnerContextKey: () => `owner:${ownerGeneration}`,
+ getLocale: () => hostLocale,
+ });
+ await owned.install(await makeCindy('owned.cindy', goodManifest()));
+ await fs.promises.mkdir(path.join(rootB, 'hello'), { recursive: true });
+ await fs.promises.writeFile(path.join(rootB, 'hello', 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(rootB, 'hello', 'main.js'), 'owner-b');
+
+ await owned.runExclusiveMutation(async (mutation) => {
+ activeRoot = rootB;
+ activeState = stateB;
+ ownerGeneration += 1;
+ expect(await mutation.uninstall('hello', { notify: false })).toEqual({ ok: true });
+ });
+
+ expect(fs.existsSync(path.join(rootA, 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(stateA, 'hello.json'))).toBe(false);
+ expect(fs.existsSync(path.join(rootB, 'hello', 'main.js'))).toBe(true);
+ expect(owned.list().find((ghost) => ghost.manifest.id === 'hello')?.approval.state).toBe(
+ 'legacy-unapproved',
+ );
+ });
+
+ it('未提交的更新(新字节+旧 receipt+update 标记)回滚到 backup,不固化成按旧批准跑新代码', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-abcdef12';
+
+ // 模拟 staging→final 之后、写 receipt 之前崩溃:旧字节挪到 backup,新字节在 final,
+ // receipt 仍是旧的。标记的 packageSha256 与旧 receipt 不同 = 未提交。
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.mkdir(finalDir);
+ await fs.promises.writeFile(
+ path.join(finalDir, 'ghost.json'),
+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),
+ );
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: backupName,
+ }),
+ );
+
+ freshManager(); // 构造期恢复:未提交 → 回滚到 backup
+ const restored = JSON.parse(await fs.promises.readFile(path.join(finalDir, 'ghost.json'), 'utf8'));
+ expect(restored.version).toBe('1.0.0'); // 旧字节搬回
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ // receipt 一字未动,与回滚后的旧字节自洽(不是"新字节 + 旧 receipt"的错位)。
+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);
+ });
+
+ it('已提交的更新(标记 packageSha256 == receipt)保留新字节,只回收陈旧 backup', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const committedReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ revision: string;
+ };
+ const backupName = '.cindy-updating-hello-abcdef34';
+ await fs.promises.mkdir(path.join(rootDir, backupName));
+ await fs.promises.writeFile(path.join(rootDir, backupName, 'stale.txt'), 'old');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: committedReceipt.packageSha256,
+ receiptRevision: committedReceipt.revision,
+ backupDirName: backupName,
+ phase: 'published',
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false); // 陈旧 backup 回收
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true); // 新版保留
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('approved');
+ });
+
+ it('same-hash backed-up update restores the only backup instead of deleting it', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');
+ const receipt = JSON.parse(receiptBefore) as { packageSha256: string };
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-acde0011';
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: receipt.packageSha256,
+ oldPackageSha256: receipt.packageSha256,
+ receiptRevision: '11111111-1111-4111-8111-111111111111',
+ backupDirName: backupName,
+ phase: 'backed-up',
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);
+ });
+
+ it('same-hash backed-up update rolls back a final whose receipt revision is still old', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ };
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-acde0022';
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.mkdir(finalDir);
+ await fs.promises.writeFile(path.join(finalDir, 'new.txt'), 'uncommitted');
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: receipt.packageSha256,
+ oldPackageSha256: receipt.packageSha256,
+ receiptRevision: '22222222-2222-4222-8222-222222222222',
+ backupDirName: backupName,
+ phase: 'backed-up',
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(path.join(finalDir, 'new.txt'))).toBe(false);
+ expect(fs.existsSync(path.join(finalDir, 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('legacy install marker with an old same-hash receipt and no final stays isolated', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ };
+ await fs.promises.rm(path.join(rootDir, 'hello'), { recursive: true, force: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'install',
+ packageSha256: receipt.packageSha256,
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(manager.list()).toEqual([]);
+ });
+
+ it('卸载先撤批准再删目录:删目录失败时不留"孤立 approved receipt + 目录在"(防借尸还魂)', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ expect(manager.list()[0].approval.state).toBe('approved');
+ // 让内容目录的 rm 失败(模拟句柄占用),但放行 receipt/快照的 rm。
+ const realRm = fs.promises.rm;
+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation((async (p: fs.PathLike, ...rest: unknown[]) => {
+ if (String(p) === path.join(rootDir, 'hello')) {
+ rmSpy.mockRestore();
+ const err = new Error('EBUSY: resource busy') as NodeJS.ErrnoException;
+ err.code = 'EBUSY';
+ throw err;
+ }
+ return (realRm as (...a: unknown[]) => Promise<void>)(p, ...rest);
+ }) as typeof fs.promises.rm);
+
+ const res = await manager.uninstall('hello');
+ await expectRejection(res, 'io');
+ // 关键:撤批准在删目录之前 —— receipt 已没了,目录还在但 fail closed(list 报
+ // legacy-unapproved),不会被这份 receipt 授权。孤立标记留给启动恢复收尾。
+ expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('卸载崩在撤批准之后、删目录之前:恢复据 uninstall 标记删净残留目录', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 模拟崩溃现场:receipt 已撤(revoke 先行),目录还在,uninstall 标记在。
+ await fs.promises.rm(receiptPath(), { force: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),
+ );
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+
+ freshManager(); // 构造期恢复
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('卸载崩在撤批准之前:恢复据 uninstall 标记把 receipt 与目录都删净', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 崩在写标记之后、撤批准之前:receipt 与目录都还在。
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),
+ );
+ expect(fs.existsSync(receiptPath())).toBe(true);
+
+ freshManager();
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('setEnabled 不跟随非真目录:<id> 是普通文件时按未装入拒,不越安装根写标记', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ await fs.promises.writeFile(path.join(rootDir, 'foo'), 'not a dir');
+ const result = await manager.setEnabled('foo', false);
+ await expectRejection(result, 'not-installed');
+ });
+
+ it('setEnabled 不跟随 junction:<id> 是指向外部的链接时拒,不在外部目标写/删 .disabled', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const dir = path.join(rootDir, 'hello');
+ const outside = path.join(workDir, 'outside-target');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.rm(dir, { recursive: true, force: true });
+ try {
+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return; // 无 symlink 权限(Windows 未开发者模式):生产守卫仍由 classify 钉死。
+ }
+ const result = await manager.setEnabled('hello', false);
+ await expectRejection(result, 'not-installed');
+ // 关键:没有往 junction 目标(安装根之外)写 .disabled。
+ expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);
+ });
+});
+
+describe('GhostManager · update pre-rename recovery', () => {
+ it('marker 落盘但尚未 rename 时保留旧 final 与 receipt', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');
+ await fs.promises.mkdir(stagingDir, { recursive: true });
+ const stateReceiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
+ const statePendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');
+ const receipt = JSON.parse(await fs.promises.readFile(stateReceiptPath, 'utf8')) as {
+ packageSha256?: string;
+ };
+ await fs.promises.writeFile(
+ statePendingPath,
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: '.cindy-updating-hello-deadbeef',
+ phase: 'prepared',
+ oldPackageSha256: receipt.packageSha256,
+ }),
+ );
+
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(stateReceiptPath)).toBe(true);
+ expect(fs.existsSync(statePendingPath)).toBe(false);
+ expect(fs.existsSync(stagingDir)).toBe(false);
+ });
+});
+
+describe('GhostManager · install', () => {
+ it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
+ const manifest = {
+ ...goodManifest(),
+ name: 'Base name',
+ description: 'Base description',
+ locales: {
+ en: 'locales/en.json',
+ 'zh-CN': 'locales/zh-CN.json',
+ },
+ };
+ const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({
+ name,
+ description,
+ tools: { do_thing: { description: toolDescription } },
+ });
+ const cindy = await makeCindy('localized.cindy', manifest, {
+ 'locales/en.json': locale('English name', 'English description', 'English tool'),
+ 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),
+ });
+ const result = await manager.install(cindy);
+ expect(result).toMatchObject({
+ ghost: {
+ manifest: {
+ name: '中文名称',
+ description: '中文说明',
+ resolvedLocale: 'zh-CN',
+ tools: [{ name: 'do_thing', description: '中文工具' }],
+ },
+ },
+ });
+
+ hostLocale = 'ja';
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'English name',
+ description: 'English description',
+ resolvedLocale: 'ja',
+ tools: [{ name: 'do_thing', description: 'English tool' }],
+ });
+ hostLocale = 'fr-FR';
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'English name',
+ resolvedLocale: 'en',
+ });
+ });
+
+ it('installed locale symlinks cannot replace the Host-approved locale snapshot', async () => {
+ hostLocale = 'en';
+ const manifest = {
+ ...goodManifest(),
+ name: 'Base name',
+ locales: { en: 'locales/en.json' },
+ };
+ const locale = (name: string) => JSON.stringify({
+ name,
+ tools: { do_thing: { description: 'Localized tool' } },
+ });
+ const cindy = await makeCindy('localized-symlink.cindy', manifest, {
+ 'locales/en.json': locale('Packaged name'),
+ });
+ await manager.install(cindy);
+ const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');
+ const outsidePath = path.join(workDir, 'outside-locale.json');
+ await fs.promises.writeFile(outsidePath, locale('Outside name'));
+ await fs.promises.rm(localePath);
+ try {
+ await fs.promises.symlink(outsidePath, localePath, 'file');
+ } catch {
+ return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。
+ }
+
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'Packaged name',
+ resolvedLocale: 'en',
+ tools: [{ name: 'do_thing', description: 'Localized tool' }],
+ });
+
+ const localesDir = path.dirname(localePath);
+ const outsideLocalesDir = path.join(workDir, 'outside-locales');
+ await fs.promises.rm(localesDir, { recursive: true, force: true });
+ await fs.promises.mkdir(outsideLocalesDir);
+ await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));
+ await fs.promises.symlink(
+ outsideLocalesDir,
+ localesDir,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'Packaged name',
+ resolvedLocale: 'en',
+ });
+ });
+
+ it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {
+ const manifest = {
+ ...goodManifest(),
+ locales: { en: 'locales/en.json' },
+ };
+ const missing = await makeCindy('locale-missing.cindy', manifest);
+ await expectRejection(await manager.install(missing), 'file-invalid');
+
+ const invalid = await makeCindy('locale-invalid.cindy', manifest, {
+ 'locales/en.json': '{ nope',
+ });
+ await expectRejection(await manager.install(invalid), 'file-invalid');
+
+ const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {
+ 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),
+ });
+ await expectRejection(await manager.install(unknownTool), 'file-invalid');
+
+ // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。
+ hostLocale = 'en';
+ const partial = await makeCindy('locale-partial.cindy', manifest, {
+ 'locales/en.json': JSON.stringify({ name: 'English partial' }),
+ });
+ expect(await manager.install(partial)).toMatchObject({
+ ghost: {
+ manifest: {
+ name: 'English partial',
+ resolvedLocale: 'en',
+ tools: [{ name: 'do_thing', description: '做点事' }],
+ },
+ },
+ });
+
+ const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {
+ 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),
+ });
+ await expectRejection(await manager.install(aliasedManifest), 'file-invalid');
+ });
+
+ it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {
+ const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });
+ const result = await manager.install(cindy);
+ expect('ghost' in result).toBe(true);
+ const { ghost } = result as { ghost: InstalledGhost };
+ expect(ghost.manifest.id).toBe('hello');
+ expect(ghost.dir).toBe(path.join(rootDir, 'hello'));
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);
+
+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);
+ });
+
+ it('returns the quarantined projection when install journal cleanup fails', async () => {
+ const store = (
+ manager as unknown as {
+ receiptStore: { clearPendingMutation(id: string): Promise<void> };
+ }
+ ).receiptStore;
+ const clearSpy = vi
+ .spyOn(store, 'clearPendingMutation')
+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));
+ let result: Awaited<ReturnType<GhostManager['install']>>;
+ try {
+ result = await manager.install(await makeCindy('valid.cindy', goodManifest()));
+ } finally {
+ clearSpy.mockRestore();
+ }
+ expect('ghost' in result).toBe(true);
+ if (!('ghost' in result)) throw new Error('expected committed install projection');
+ expect(result.ghost).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ });
+ expect(recovered.list()[0]).toMatchObject({ approval: { state: 'approved' } });
+ });
+
++ it('本地包仅自报 cindy-github 不会获得官方 trust;Host override 才能写官方 receipt', async () => {
++ const local = await makeCindy('github-local.cindy', goodManifest('cindy-github'));
++ const localResult = await manager.install(local);
++ expect(localResult).toMatchObject({ ghost: { trust: { level: 'unverified' } } });
++ await fs.promises.rm(path.join(rootDir, 'cindy-github'), { recursive: true, force: true });
++
++ const officialResult = await manager.install(local, { trustOverride: 'cindy-official' });
++ expect(officialResult).toMatchObject({ ghost: { trust: { level: 'cindy-official' } } });
++ const receipt = JSON.parse(
++ await fs.promises.readFile(path.join(rootDir, 'cindy-github', '.cindy-trust.json'), 'utf8'),
++ ) as { level?: unknown };
++ expect(receipt.level).toBe('cindy-official');
++ expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);
++ expect(manager.list()[0].trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);
++ });
++
++ it('残缺的官方 receipt 不会被投影为可用的官方 trust', async () => {
++ const local = await makeCindy('github-incomplete-receipt.cindy', goodManifest('cindy-github'));
++ await manager.install(local, { trustOverride: 'cindy-official' });
++ const metadataPath = path.join(rootDir, 'cindy-github', '.cindy-trust.json');
++ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;
++ delete metadata.publisherName;
++ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
++
++ expect(manager.list()[0]?.trust).toBeUndefined();
++ });
++
+ it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {
+ const cindy = await makeCindy('at-resource.cindy', atResourceManifest());
+ const installed = await manager.install(cindy);
+
+ const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');
+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;
+
+ delete metadata.approvedAtResourceProvider;
+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
+ expect(manager.list()[0].manifest.tools).toEqual([
+ { name: 'do_thing', description: '做点事' },
+ ]);
+
+ metadata.approvedAtResourceProvider = { tool: 'other_tool' };
+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
+ });
+
+ it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {
+ const cindy = await makeCindy('hello.cindy', goodManifest());
+ const result = await manager.install(cindy, { initiallyEnabled: false });
+ expect('ghost' in result).toBe(true);
+ expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);
expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
// 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。
expect(onChanged).toHaveBeenCalledTimes(1);
diff --cc apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
index de8205c7e5,be23e1c6bd..cd7cd17f54
--- a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
@@@ -4,15 -4,8 +4,16 @@@ import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { provisionBuiltinGhosts } from '../builtinGhostProvisioner.js';
+import {
+ fingerprintDirContent,
+ isTrustedBuiltinSeedSource,
+ PROVISIONING_STATE_FILE,
+ provisionBuiltinGhosts,
+ readBuiltinTombstones,
+ recordBuiltinTombstone,
+ renameBuiltinTombstone,
+} from '../builtinGhostProvisioner.js';
+ import { isGhostInstallLockHeld } from '../ghostInstallLock.js';
const tempDirs: string[] = [];
diff --cc apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 70a796a64b,2055c9c636..fa54557c04
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@@ -1289,15 -697,33 +1290,42 @@@ describe('scaffoldGhostDir', () =>
});
describe('FORGE_GUIDE', () => {
+ it('documents installed-directory isolation and the structured refusal', () => {
+ expect(FORGE_GUIDE).toContain('已安装插件目录');
+ expect(FORGE_GUIDE).toContain('SOURCE_IS_INSTALLED_PLUGIN');
+ // 脚手架侧的同一禁区也要写进手册,否则 agent 会先把骨架建进安装目录再撞墙。
+ expect(FORGE_GUIDE).toContain('也不能落在已安装插件目录或 Host 状态目录内');
+ expect(FORGE_GUIDE).toContain('复制/迁出');
+ expect(FORGE_GUIDE).toContain('junction');
+ });
+
+ it('写死 whenToUse 发现面与二级分派 RULES 契约', () => {
+ expect(FORGE_GUIDE).toContain('给模型做插件发现与判断的唯一字段');
+ expect(FORGE_GUIDE).toContain(`最多 ${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字符`);
+ expect(FORGE_GUIDE).toContain('花名册 → `ghost_info` → `ghost_call`');
+ expect(FORGE_GUIDE).toContain(
+ '禁止塞入"必须/不得"式行为规则、工具调用顺序、参数协议、错误码与重试策略',
+ );
+ expect(FORGE_GUIDE).toContain(
+ '"whenToUse": "管理项目时找我;必须先调用 list_tools(category=project),再调用 call_tool;遇到 INVALID_ARGS 不得改用其它工具"',
+ );
+ expect(FORGE_GUIDE).toContain(
+ '"whenToUse": "需要查询、创建或更新项目、任务、成员、迭代与发布状态时找我"',
+ );
+ expect(FORGE_GUIDE).toContain(
+ '`list_tools(category)` 返回工具明细时,必须在同一份结果里一并下发该类目的',
+ );
+ expect(FORGE_GUIDE).toContain(
+ '传 category 返回该类目下所有操作的名称、说明与该类目 RULES',
+ );
+ expect(FORGE_GUIDE).toContain('`rules: [规则键]`');
+ expect(FORGE_GUIDE).toContain('参数 schema **和本次自纠必需的规则**');
+ expect(FORGE_GUIDE).not.toContain('这是你影响 AI 行为的**唯一合法通道**');
+ expect(FORGE_GUIDE).not.toContain('description(花名册自述)');
+ expect(FORGE_GUIDE).not.toContain('选错会拖累所有会话');
+ expect(FORGE_GUIDE).not.toContain('所有意识的工具清单会一起被你一家撑爆');
+ });
+
it('向量检索示例按请求维度回放,不把回执 dim 当作请求判据', () => {
expect(FORGE_GUIDE).toContain('const requestedDim = undefined');
expect(FORGE_GUIDE).toContain('requestedDim 来自这次请求而不是回执');
diff --cc apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index 8b764bde11,37ab2baf44..8a5696a029
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@@ -59,15 -59,24 +59,36 @@@ describe('market Ghost session boundary
expect(body).toContain('releaseMutation?.();');
});
+ it('fails owner-scoped plugin reads closed while an account boundary is pending', () => {
+ const start = source.indexOf('function availableGhosts(): InstalledGhost[] {');
+ const end = source.indexOf('\n}', start);
+ const body = source.slice(start, end);
+ expect(body).toContain('if (isAppSessionBoundaryPending()) return [];');
+ expect(source).toContain(
+ 'return availableGhosts().find((ghost) => ghost.manifest.id === id) ?? null;',
+ );
+ expect(source.match(/getGhost: findAvailableGhost/g)?.length ?? 0).toBeGreaterThanOrEqual(3);
+ expect(source).toContain('return findAvailableGhost(id)?.manifest.name ?? null;');
+ });
++
+ it('runs the final market callback before both initial install and update placement', () => {
+ const installStart = source.indexOf(
+ 'async function installOrUpdateMarketGhostPackageLocked(',
+ );
+ const installEnd = source.indexOf(
+ '\n}\n\ntype GhostUninstallLedgerCompletion',
+ installStart,
+ );
+ const body = source.slice(installStart, installEnd);
+ const initialBranch = body.slice(
+ body.indexOf('if (!installed) {'),
+ body.indexOf('const runtime = getGhostRuntime();'),
+ );
+
+ expect(initialBranch.indexOf('expected.beforeCommitInLock?.();')).toBeGreaterThan(-1);
+ expect(initialBranch.indexOf('expected.beforeCommitInLock?.();')).toBeLessThan(
+ initialBranch.indexOf('return installAndDock('),
+ );
+ expect(body.match(/expected\.beforeCommitInLock\?\.\(\);/g)).toHaveLength(2);
+ });
});
diff --cc apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index f83b1175e8,6fb124f530..5a0da60818
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@@ -9,14 -8,12 +9,19 @@@ import
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
+import {
+ classifyGhostDirEntry,
+ classifyGhostDirEntrySync,
+ collectGhostContentFiles,
+ hashGhostContentFiles,
+ resolveGhostContentPathSync,
+} from './ghostContentTree.js';
import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
+ import {
+ CINDY_OFFICIAL_GHOST_TRUST,
+ hasCindyOfficialTrustMetadata,
+ } from './GhostManager.js';
+ import { withGhostInstallLock } from './ghostInstallLock.js';
/**
* builtinGhostProvisioner — 内置意识的启动播种(第一方可信通道)。
@@@ -586,100 -368,65 +591,153 @@@ export async function provisionBuiltinG
continue;
}
- const installedDir = path.join(repoRootDir, id);
- const installedExists =
- isRealDirectoryPath(installedDir) &&
- (() => {
- try {
- return classifyGhostDirEntrySync(path.join(installedDir, GHOST_MANIFEST_FILE)) === 'file';
- } catch {
- return false;
+ await withGhostInstallLock(id, async () => {
+ const installedDir = path.join(repoRootDir, id);
- const installedExists = fs.existsSync(path.join(installedDir, GHOST_MANIFEST_FILE));
++ const installedExists =
++ isRealDirectoryPath(installedDir) &&
++ (() => {
++ try {
++ return classifyGhostDirEntrySync(path.join(installedDir, GHOST_MANIFEST_FILE)) === 'file';
++ } catch {
++ return false;
++ }
++ })();
+
+ // 3) 受众:不命中 → 回收"播种装的"(seeded 台账内),手动装的不动。
+ if (!matchesAudience(config.get(id)?.audience, identity)) {
+ if (seeded.has(id) && installedExists) {
+ markApplyStart();
+ await deps.beforeRemove?.(id);
+ await fs.promises.rm(installedDir, { recursive: true, force: true });
+ seeded.delete(id);
+ outcome.removed.push(id);
+ log?.info('builtin ghost removed: audience no longer matches', { id });
+ } else {
+ outcome.skipped.push(id);
}
- })();
+ return;
+ }
- // 3) 受众:不命中 → 回收"播种装的"(seeded 台账内),手动装的不动。
- if (!matchesAudience(config.get(id)?.audience, identity)) {
- if (seeded.has(id) && installedExists) {
+ // 4) 指纹比对(忽略点开头文件:`.disabled` 是用户状态不是内容)。
++ const seedFingerprint = await fingerprintDirContent(seedDir);
++ if (seedFingerprint.hasNonRegularEntry) {
++ throw new Error('builtin seed contains a link or non-regular entry');
++ }
+ if (installedExists) {
- const seedHash = await hashDirContent(seedDir);
- const installedHash = await hashDirContent(installedDir);
- if (seedHash === installedHash) {
++ const installedFingerprint = await fingerprintDirContent(installedDir);
++ if (
++ !installedFingerprint.hasNonRegularEntry &&
++ seedFingerprint.hash === installedFingerprint.hash
++ ) {
++ outcome.approved.push(manifest);
++ outcome.approvedSourceDirs[id] = seedDir;
+ if (id === 'cindy-github' && !hasCindyOfficialTrustMetadata(installedDir)) {
+ // receipt 与官方字节必须在同一把安装锁内、经同一次 staging swap
+ // 原子落位;不能在 hash 后单独给可能已被替换的目录补 trust。
- const wasDisabled = fs.existsSync(path.join(installedDir, '.disabled'));
++ const wasDisabled = classifyGhostDirEntrySync(path.join(installedDir, '.disabled')) === 'file';
+ markApplyStart();
+ await swapInSeed(seedDir, installedDir, repoRootDir, id, {
+ disabled: wasDisabled,
+ trust: CINDY_OFFICIAL_GHOST_TRUST,
+ });
+ }
+ outcome.skipped.push(id);
+ return;
+ }
- const wasDisabled = fs.existsSync(path.join(installedDir, '.disabled'));
++ const wasDisabled = classifyGhostDirEntrySync(path.join(installedDir, '.disabled')) === 'file';
markApplyStart();
- await deps.beforeRemove?.(id);
- await fs.promises.rm(installedDir, { recursive: true, force: true });
- seeded.delete(id);
- outcome.removed.push(id);
- log?.info('builtin ghost removed: audience no longer matches', { id });
- } else {
- outcome.skipped.push(id);
++ seeded.add(id);
++ if (!writeState(repoRootDir, { removed: [...tombstones], seeded: [...seeded].sort() }, log)) {
++ seeded.delete(id);
++ throw new Error('builtin seeded ledger could not be persisted before replacement');
++ }
++ ownershipClaimPersisted = true;
++ await deps.beforeReplace?.(id);
+ await swapInSeed(seedDir, installedDir, repoRootDir, id, {
+ disabled: wasDisabled,
+ ...(id === 'cindy-github' ? { trust: CINDY_OFFICIAL_GHOST_TRUST } : {}),
+ });
- seeded.add(id);
++ outcome.approved.push(manifest);
++ outcome.approvedSourceDirs[id] = seedDir;
+ outcome.updated.push(manifest);
+ log?.info('builtin ghost updated to bundled content', { id, version: manifest.version });
+ return;
}
- continue;
- }
++ {
+ // 4) 指纹比对(忽略点开头文件:`.disabled` 是用户状态不是内容)。
+ // 种子是随应用发布的第一方输入,出现链接/FIFO/设备节点属于打包事故:
+ // 必须整颗 fail closed,不能在复制时静默丢掉条目后批准一个残缺安装。
+ const seedFingerprint = await fingerprintDirContent(seedDir);
+ if (seedFingerprint.hasNonRegularEntry) {
+ throw new Error('builtin seed contains a link or non-regular entry');
+ }
+ if (installedExists) {
+ const installedFingerprint = await fingerprintDirContent(installedDir);
+ // 安装侧含非普通条目 = 一律判不一致,走重新播种把目录换回随包字节。
+ // 否则它既修不回来(判成相同就跳过播种),随后 hashApprovedDirectory 又会因
+ // 非普通条目抛错、批准被撤销,插件每次启动都卡在不可用。
+ if (
+ !installedFingerprint.hasNonRegularEntry &&
+ seedFingerprint.hash === installedFingerprint.hash
+ ) {
+ outcome.approved.push(manifest);
+ outcome.approvedSourceDirs[id] = seedDir;
+ outcome.skipped.push(id);
- continue;
++ return;
+ }
+ const wasDisabled = (() => {
+ try {
+ classifyGhostDirEntrySync(path.join(installedDir, '.disabled'));
+ return true;
+ } catch {
+ return false;
+ }
+ })();
+ markApplyStart();
+ // Claim seeded ownership durably before exchanging bytes. If the process
+ // dies after the swap but before the end-of-pass ledger write, the next
+ // reconciliation still knows this id is eligible for audience cleanup.
+ seeded.add(id);
+ if (!writeState(repoRootDir, { removed: [...tombstones], seeded: [...seeded].sort() }, log)) {
+ seeded.delete(id);
+ throw new Error('builtin seeded ledger could not be persisted before replacement');
+ }
+ ownershipClaimPersisted = true;
+ await deps.beforeReplace?.(id);
+ if (deps.publishSeed) await deps.publishSeed(id, seedDir, { disabled: wasDisabled });
+ else await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: wasDisabled });
+ outcome.approved.push(manifest);
+ outcome.approvedSourceDirs[id] = seedDir;
+ outcome.updated.push(manifest);
+ log?.info('builtin ghost updated to bundled content', { id, version: manifest.version });
+ } else {
markApplyStart();
+ await swapInSeed(seedDir, installedDir, repoRootDir, id, {
+ disabled: false,
+ ...(id === 'cindy-github' ? { trust: CINDY_OFFICIAL_GHOST_TRUST } : {}),
+ });
seeded.add(id);
+ if (!writeState(repoRootDir, { removed: [...tombstones], seeded: [...seeded].sort() }, log)) {
+ seeded.delete(id);
+ throw new Error('builtin seeded ledger could not be persisted before install');
+ }
+ ownershipClaimPersisted = true;
+ if (deps.publishSeed) await deps.publishSeed(id, seedDir, { disabled: false });
+ else await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: false });
+ outcome.approved.push(manifest);
+ outcome.approvedSourceDirs[id] = seedDir;
outcome.installed.push(manifest);
log?.info('builtin ghost installed', { id, version: manifest.version });
+ }
+ });
} catch (err) {
+ // Existing ownership must survive a failed audience/orphan cleanup so the
+ // next reconciliation retries instead of permanently forgetting an
+ // installed approved plugin. Likewise, once a new ownership claim was
+ // durably committed before publish/replace, keep it: the mutation may
+ // have partially changed bytes or approval state before throwing.
+ if (!ownedBeforeAttempt && !ownershipClaimPersisted) seeded.delete(id);
outcome.skipped.push(id);
log?.warn('builtin ghost provisioning failed', {
id,
diff --cc apps/desktop/src/main/cindy-brain/index.ts
index 73e433e0b4,a6ed7f75b7..38d3d6347a
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@@ -15,8 -17,8 +17,9 @@@ import
GHOST_MANIFEST_FILE,
GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,
GHOST_NOTIFY_MIN_INTERVAL_MS,
+ isGhostInstallApprovalToken,
diffGhostPermissionItems,
+ ghostAppContextLocale,
ghostPermissionBaselineKey,
unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
@@@ -54,7 -50,8 +57,9 @@@ import
import { getLayoutStore } from '../layout/index.js';
import {
GhostManager,
+ type GhostExclusiveMutation,
+ isCindyOfficialTrustInfo,
+ type GhostHostTrustOverride,
type InstallRejection,
type UninstallRejection,
} from './GhostManager.js';
@@@ -3933,23 -3667,11 +4007,27 @@@ async function installOrUpdateMarketGho
'下载包清单与市场 Release 不一致',
);
}
+ const trustOverride: GhostHostTrustOverride | undefined =
+ expected.officialCindyGithub === true && expected.ghostId === 'cindy-github'
+ ? 'cindy-official'
+ : undefined;
requireGhostAvailableForActiveSession(expected.ghostId);
+ /**
+ * 「审阅过的」与「真要装的」权限必须一致(2026-08-03,codex review P1)。
+ *
+ * 装入确认框渲染的是**来源方给的 manifest**(服务端市场 = release manifest,
+ * 自定义市场 = 抓到的 ghost.json),而真正落地的是 `.cindy` 包里的 ghost.json。
+ * 两者本该同一份,但来源方的投影层可能与客户端的清单契约漂移——`cindy-protocol`
+ * 那份平行校验器就已经缺了 `confirm` 槽;新登记的槽(如 `badge`)在它眼里是
+ * 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着
+ * 它装进来,用户**从没审过就多出一个常驻能力面**。
+ *
+ * 这里按权限项逐项比对。包里多出来的权限先暂停落位,由 Renderer 按真实包
+ * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。
+ * 卡点落在 inspect 之后、任何落地动作之前,所以等待复核时磁盘上什么都没动。
+ * (token broker 授权校验由下方 rejectUnauthorizedTokenBroker(canonicalManifest) 统一执行,
+ * 原 receipt 分支在此处的硬中止已被本可恢复复核取代,见约束文档 §11 整合任务①。)
+ */
const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
if (expected.reviewedManifest) {
const baselineManifest = expected.permissionBaselineManifest ?? null;
@@@ -4022,17 -3747,10 +4103,18 @@@
getGhostErrandSlot().clearGhost(expected.ghostId);
let result: Awaited<ReturnType<typeof manager.update>>;
try {
- // 与首装分支同一口径:钉住 inspect 时校验过的包字节(见上)。
+ // 与首装分支同一口径:钉住 inspect 时校验过的包字节。receipt 模型下更新必须
+ // 绑定 receipt token(决策 A:与 main 的 sha 钉扎叠加),否则并发批准变更绕不过去。
+ if (!expected.expectedInstalledApproval) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state was not bound to the market update',
+ );
+ }
result = await manager.update(cindyFilePath, {
expectedPackageSha256: inspected.packageSha256,
+ expectedInstalledApproval: expected.expectedInstalledApproval,
+ ...(trustOverride ? { trustOverride } : {}),
});
} catch (error) {
spawnIfResident(installed);
@@@ -5227,14 -4975,9 +5358,15 @@@ export function registerGhostIpc(): voi
) {
throwIpcError('INVALID_PARAMS', 'expectedPackageSha256 must come from ghosts:inspect');
}
+ if (!isGhostInstallApprovalToken(expectedInstalledApproval)) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'expectedInstalledApproval must come from ghosts:list',
+ );
+ }
const inspected = await manager.inspect(lizFilePath);
if ('rejection' in inspected) throwInstallError(inspected.rejection);
+ assertGhostSupportsCurrentCindy(inspected.canonicalManifest);
if (inspected.packageSha256 !== expectedPackageSha256) {
throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');
}
diff --cc apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
index c060e88fd2,5b7ff343fa..3a1d802cc1
--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
@@@ -40,7 -43,8 +43,9 @@@ import
type GhostSubscribeTopic,
type InstalledGhost,
} from '../../shared/ghost.js';
+import { isGhostOwnerScopeUsable, type GhostOwnerScope } from './ghostOwnerScope.js';
+ import { getDbClient } from '../localDb/client/current.js';
+ import * as localDbSchema from '../localDb/schema.js';
/** block 理由展示上限(超长截断,防意识用理由塞小作文)。 */
const BLOCK_REASON_MAX_CHARS = 200;
@@@ -89,9 -133,9 +134,10 @@@ export interface GhostSubscriptionGatew
now(): number;
/** 钩子熔断回调(通知 renderer + 日志;每意识只触发一次)。 */
onHookFused?(ghost: InstalledGhost, ownerStamp?: unknown): void;
+ ownerScope?: GhostOwnerScope;
/** hookId 生成(测试注入固定序列;缺省 randomUUID)。 */
newHookId?(): string;
+ resolveMessageHookContext?(sessionId: string): MessageHookContext | Promise<MessageHookContext>;
log?: {
info(msg: string, meta?: Record<string, unknown>): void;
warn(msg: string, meta?: Record<string, unknown>): void;
@@@ -308,8 -293,8 +367,10 @@@ export class GhostSubscriptionGateway
input: { sessionId: string; text: string },
ownerStamp?: unknown,
): Promise<GhostScreenResult> {
+ const ownerScope = this.captureOwnerScope();
+ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };
+ let context: MessageHookContext | Promise<MessageHookContext> | undefined =
+ userHookContext.getStore();
let currentText = input.text;
let rewritten = false;
let lastRewriteGhost: InstalledGhost | null = null;
@@@ -323,8 -309,7 +385,8 @@@
const verdict = await this.askOne(ghost, e, 'will-user-message', {
sessionId: input.sessionId,
text: currentText,
- }, ownerStamp, ownerScope);
- }, context, ownerStamp);
++ }, context, ownerStamp, ownerScope);
+ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };
if (verdict?.action === 'block') {
const reason = (verdict.reason ?? '').slice(0, BLOCK_REASON_MAX_CHARS);
this.deps.log?.info('ghost hook blocked user message', { ghostId, sessionId: input.sessionId });
@@@ -367,8 -352,8 +429,10 @@@
input: { sessionId: string; text: string },
ownerStamp?: unknown,
): Promise<GhostAssistantScreenResult> {
+ const ownerScope = this.captureOwnerScope();
+ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };
+ let context: MessageHookContext | Promise<MessageHookContext> | undefined =
+ assistantHookContext.getStore();
let currentText = input.text;
let lastRewriteGhost: InstalledGhost | null = null;
let renderGhost: InstalledGhost | null = null;
@@@ -384,8 -373,7 +452,8 @@@
const verdict = await this.askOne(ghost, e, 'will-assistant-message', {
sessionId: input.sessionId,
text: currentText,
- }, ownerStamp, ownerScope);
- }, context, ownerStamp);
++ }, context, ownerStamp, ownerScope);
+ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };
if (verdict?.action === 'rewrite' && typeof verdict.text === 'string') {
const next = verdict.text.slice(0, GHOST_HOOK_REWRITE_MAX_CHARS).trim();
// 空改写(意识把正文清空)视为无意义,忽略此次 rewrite 保原文。
@@@ -435,9 -420,9 +500,10 @@@
ghost: InstalledGhost,
e: SubEntry,
hookName: 'will-user-message' | 'will-assistant-message',
- input: { sessionId: string; text: string },
+ input: GhostMessageHookData,
+ context: MessageHookContext | Promise<MessageHookContext>,
ownerStamp?: unknown,
+ ownerScope?: unknown,
): Promise<HookVerdict | null> {
const ghostId = ghost.manifest.id;
const hookId = this.deps.newHookId?.() ?? randomUUID();
@@@ -457,23 -447,20 +528,33 @@@
let deliverFailure: string | null = null;
void (async () => {
+ const capturedOwner = ownerScope ?? this.captureOwnerScope();
+ if (!this.ownerScopeUsable(capturedOwner)) {
+ this.invalidateOwner(ghostId, e);
+ return;
+ }
// 常驻意识正常在跑;崩溃恢复窗口内兜底拉一次。
if (!this.deps.isRunning(ghostId)) {
- await this.deps.wake(ghost);
+ const wokeBeforeDeadline = await Promise.race([
+ this.deps.wake(ghost).then(() => true),
+ verdictPromise.then(() => false),
+ ]);
+ if (!wokeBeforeDeadline) return;
+ if (!this.ownerScopeUsable(capturedOwner)) {
+ this.invalidateOwner(ghostId, e);
+ return;
+ }
+ }
+ if (!this.ownerScopeUsable(capturedOwner)) {
+ this.invalidateOwner(ghostId, e);
+ return;
}
+ const resolvedContext = context instanceof Promise ? await context : context;
+ if (!this.pendingHooks.has(hookId)) return;
+ const data: GhostMessageHookData = {
+ ...input,
+ ...(resolvedContext.model ? { model: resolvedContext.model } : {}),
+ };
this.deps.sendToGhost(ghostId, {
type: 'event',
name: hookName,
diff --cc apps/desktop/src/main/mcp-integrations/ghost.ts
index 1747603359,2c7bf0311b..067e938318
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@@ -62,13 -66,10 +66,14 @@@ import
getGhostManager,
getGhostPipeDispatcher,
getGhostSetupAssessment,
+ ghostForgeForbiddenRootDirs,
+ captureGhostMutationOwnerForMcp,
+ acquireGhostMutationLeaseForMcp,
isGhostAvailableForActiveSession,
} from '../cindy-brain/index.js';
+import { writeForgeScaffoldWithStableParent } from '../cindy-brain/forgeScaffoldCapability.js';
import { getGhostSetupCoordinator } from '../cindy-brain/ghostSetupCoordinator.js';
+ import { classifyGhostVisibility } from '../cindy-brain/ghostVisibility.js';
import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forge.js';
import { workdirWriteVerdict } from '../cindy-brain/fsSlot.js';
diff --cc apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
index 3946801e4b,ffd9cbc724..0121040c1a
--- 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
@@@ -86,11 -71,17 +89,18 @@@ vi.mock('../download.js', () => (
import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';
- import { ghostPermissionBaselineKey, type GhostManifest } from '../../../shared/ghost';
++import { GHOST_ICON_MAX_BYTES, ghostPermissionBaselineKey, type GhostManifest } from '../../../shared/ghost';
+ import {
+ customMarketPluginId,
+ customMarketReleaseId,
+ marketSourceKey,
+ pluginMarketCustomIconProjectionToken,
+ pluginMarketCustomIconSourceToken,
+ } from '../../../shared/pluginMarket';
-import { GHOST_ICON_MAX_BYTES, type GhostManifest } from '../../../shared/ghost';
+import type { MarketSourceConfig } from '../../../shared/pluginMarket';
- import { customMarketPluginId, customMarketReleaseId, marketSourceKey } from '../../../shared/pluginMarket';
import { PluginMarketLedger, ghostManifestDigest } from '../ledger';
import { PluginMarketService } from '../service';
+ import { MarketSourceManager } from '../sources';
import { MarketSourceStore } from '../sources/store';
import type { PluginMarketApi } from '../api';
@@@ -446,123 -1049,30 +1069,147 @@@ describe('PluginMarketService 自定义
});
});
+ it('requires full review for an unapproved custom update and carries its receipt token to commit', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const installedManifest = ghostManifest('alpha', '1.0.0');
+ const installedDir = path.join(root, 'installed-alpha');
+ fs.mkdirSync(installedDir, { recursive: true });
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));
+ runtime.ghosts = [
+ {
+ manifest: installedManifest,
+ dir: installedDir,
+ enabled: true,
+ approval: { state: 'legacy-unapproved' },
+ },
+ ];
+ h.ledger.upsertInstallation({
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
+ ghostId: 'alpha',
+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(installedManifest),
+ });
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('alpha', '2.0.0'),
+ dir: installedDir,
+ enabled: true,
+ });
+ const pluginId = customMarketPluginId('team-lib', 'alpha');
+ const reviewed = await h.service.detail(pluginId);
+
+ await expect(
+ h.service.install(pluginId, {
+ expectedReleaseId: reviewed.releaseId,
+ expectedManifest: reviewed.manifest,
+ expectedInstalledApproval: 'legacy-unapproved',
+ }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(runtime.install).not.toHaveBeenCalled();
+
+ await h.service.install(pluginId, {
+ expectedReleaseId: reviewed.releaseId,
+ expectedManifest: reviewed.manifest,
+ expectedInstalledApproval: 'legacy-unapproved',
+ allowPermissionExpansion: true,
+ reviewedBaseline: ghostPermissionBaselineKey(installedManifest as GhostManifest),
+ });
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ expectedInstalledApproval: 'legacy-unapproved' }),
+ );
+ });
+
+ it('rejects a custom update when the receipt changes during packaging', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const installedManifest = ghostManifest('alpha');
+ const installedDir = path.join(root, 'installed-alpha');
+ fs.mkdirSync(installedDir, { recursive: true });
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));
+ h.ledger.upsertInstallation({
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
+ ghostId: 'alpha',
+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(installedManifest),
+ });
+ const calls = { n: 0 };
+ runtime.listSequence = () => {
+ calls.n += 1;
+ return [
+ {
+ manifest: installedManifest,
+ dir: installedDir,
+ enabled: true,
+ approval:
+ calls.n >= 2
+ ? { state: 'invalid' as const }
+ : {
+ state: 'approved' as const,
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ },
+ ];
+ };
+ const pluginId = customMarketPluginId('team-lib', 'alpha');
+ const reviewed = await h.service.detail(pluginId);
+
+ await expect(
+ h.service.install(pluginId, {
+ expectedReleaseId: reviewed.releaseId,
+ expectedManifest: reviewed.manifest,
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('custom market 即使自报 cindy-github 也不会获得 server-market 官方标记', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-github-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/github', id: 'cindy-github' }]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('cindy-github'),
+ dir: '/ghosts/cindy-github',
+ enabled: true,
+ });
+ const pluginId = customMarketPluginId('team-lib', 'cindy-github');
+ const reviewed = await h.service.detail(pluginId);
+
+ await h.service.install(pluginId, {
+ expectedReleaseId: customMarketReleaseId('team-lib', 'cindy-github', '1.0.0'),
+ expectedManifest: reviewed.manifest,
+ });
+
+ expect(runtime.install.mock.calls[0]?.[1]).toEqual({
+ ghostId: 'cindy-github',
+ version: '1.0.0',
+ });
+ });
+
it('rejects install when the reviewed release no longer matches', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
diff --cc apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index b0bb1f60bb,c20a2a57c4..0d0ca26ace
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@@ -52,18 -56,12 +58,21 @@@ vi.mock('../../logger.js', () => (
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
vi.mock('../../cindy-brain/index.js', () => ({
- getGhostManager: () => ({ list: () => runtime.ghosts }),
+ getGhostManager: () => ({
+ list: () =>
+ runtime.ghosts.map((ghost) => ({
+ ...ghost,
+ approval: ghost.approval ?? {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ })),
+ }),
isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),
installOrUpdateMarketGhostPackage: runtime.install,
+ hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),
+ hasRunningGhostErrand: vi.fn(() => runtime.runningErrand),
+ hasRunningGhostCindyWork: vi.fn(() => runtime.cindyWork),
isBuiltinGhostRemovedByUser: (id: string) => runtime.builtinRemoved.has(id),
uninstallGhostAndCleanup: runtime.uninstall,
}));
diff --cc apps/desktop/src/main/plugin-market/registerIpc.ts
index b75f07c27d,e87be5c89d..6a3a0eb799
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@@ -3,7 -3,8 +3,8 @@@ import os from 'node:os'
import { ipcMain, type WebContents } from 'electron';
import { isIpcError } from '../../shared/ipc-errors.js';
-import type { GhostManifest } from '../../shared/ghost.js';
+import { isGhostInstallApprovalToken, type GhostManifest } from '../../shared/ghost.js';
+ import { isPluginMarketCustomIconKey } from '../../shared/pluginMarket.js';
import {
sendToTrustedAppWindows,
setGhostUninstallLedgerPreparer,
diff --cc apps/desktop/src/main/plugin-market/service.ts
index 79f5eccd75,8d5054dcab..dd57b7b863
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@@ -11,9 -12,11 +12,13 @@@ import
import { app, dialog } from 'electron';
import {
+ diffGhostPermissionItems,
+ diffInstalledGhostPermissionItems,
+ GHOST_ICON_MAX_BYTES,
+ ghostInstallApprovalToken,
ghostPermissionBaselineKey,
+ ghostIconMimeType,
+ isSafeGhostRelativePath,
isOfficialGhostId,
validateGhostManifest,
type GhostManifest,
@@@ -1089,7 -1421,9 +1467,8 @@@ export class PluginMarketService
reviewedManifest?.manifest,
options.allowPermissionExpansion,
options.reviewedBaseline,
+ options.silentBaselineMismatch,
);
-
const download = await this.api.download(plugin.id, plugin.currentRelease.id);
requireSameMarketOwner(owner);
if (
@@@ -1116,14 -1450,11 +1495,14 @@@
plugin,
{
expectedInstalled: options.expectedInstalled,
+ ...(options.expectedInstalledApproval !== undefined
+ ? { expectedInstalledApproval: options.expectedInstalledApproval }
+ : {}),
- ...(reviewedManifest?.ok
- ? { reviewedManifest: reviewedManifest.manifest }
- : {}),
+ ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),
allowPermissionExpansion: options.allowPermissionExpansion,
reviewedBaseline: options.reviewedBaseline,
+ beforeCommitInLock: options.beforeCommitInLock,
+ silentBaselineMismatch: options.silentBaselineMismatch,
},
owner,
ledger,
@@@ -1139,12 -1470,7 +1518,10 @@@
plugin,
{
expectedInstalled: options.expectedInstalled,
+ ...(options.expectedInstalledApproval !== undefined
+ ? { expectedInstalledApproval: options.expectedInstalledApproval }
+ : {}),
- ...(reviewedManifest?.ok
- ? { reviewedManifest: reviewedManifest.manifest }
- : {}),
+ ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),
allowPermissionExpansion: options.allowPermissionExpansion,
reviewedBaseline: options.reviewedBaseline,
approvedPackageSha256: error.review.packageSha256,
@@@ -1169,7 -1497,8 +1548,9 @@@
reviewedBaseline?: string;
approvedPackageSha256?: string;
approvedPackageBaseline?: string | null;
+ expectedInstalledApproval?: string;
+ beforeCommitInLock?: () => void;
+ silentBaselineMismatch?: boolean;
expectedInstalled: boolean;
},
owner: ActiveAppSession,
@@@ -1221,11 -1535,9 +1603,10 @@@
? installedGhostRawManifest(installedNow.dir)
: null;
const permissionBaselineManifest =
+ installedNow?.approval.state === 'approved' &&
installedRawManifest &&
currentRecordNow?.installed &&
- (currentRecordNow.source === 'market' ||
- currentRecordNow.source === 'legacy-adopted') &&
+ (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&
currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)
? installedRawManifest
: null;
@@@ -1248,9 -1559,7 +1628,10 @@@
: {}),
}
: {}),
+ ...(options.expectedInstalledApproval !== undefined
+ ? { expectedInstalledApproval: options.expectedInstalledApproval }
+ : {}),
+ ...(options.beforeCommitInLock ? { beforeCommitInLock: options.beforeCommitInLock } : {}),
});
await this.withCapturedLedgerMutation(ledger, () => {
ledger.upsertInstallation(recordFrom(plugin, 'market', installed));
@@@ -1264,16 -1573,26 +1645,24 @@@
reviewedManifest: GhostManifest | undefined,
allowPermissionExpansion: boolean | undefined,
reviewedBaseline: string | undefined,
+ silentBaselineMismatch = false,
): void {
- if (
- !installed ||
- !reviewedManifest ||
- diffGhostPermissionItems(installed, reviewedManifest).added.length === 0
- ) {
- return;
- }
+ if (!installed || !reviewedManifest) return;
+ const requiresFullReview =
+ installed.approval.state !== 'approved' ||
+ diffInstalledGhostPermissionItems(installed, reviewedManifest).added.length > 0;
+ if (!requiresFullReview) return;
if (allowPermissionExpansion !== true) {
throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
}
+ if (
+ silentBaselineMismatch &&
+ reviewedBaseline !== undefined &&
+ ghostPermissionBaselineKey(installed) !== reviewedBaseline
+ ) {
+ throw new SilentUpgradeStaleBaselineError('Installed Plugin permissions changed');
+ }
- assertReviewedBaselineFresh(installed, reviewedBaseline);
+ assertReviewedBaselineFresh(installed.manifest, reviewedBaseline);
}
private requireConfigured(): void {
diff --cc apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 9763d5c121,0eb1b898e4..375139ae94
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@@ -36,14 -32,9 +36,13 @@@ vi.mock('../../security/trustedAppRende
assertTrustedAppRendererEvent,
}));
- vi.mock('../../authManager', () => ({
- getCurrentDataOwnerId: vi.fn(() => 'local-v1'),
- }));
+ const getCurrentDataOwnerId = vi.fn((): string | null => 'local-v1');
+ vi.mock('../../authManager', () => ({ getCurrentDataOwnerId }));
+vi.mock('../../appSessionState', () => ({
+ isAppSessionBoundaryPending: vi.fn(() => false),
+}));
+
const ensureReady = vi.fn();
const getRawDb = vi.fn(() => ({ id: 'db' }));
vi.mock('../../localDb', () => ({
diff --cc apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
index 6baf385e1a,fdac202496..062997cdb4
--- a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
+++ b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
@@@ -10,8 -11,9 +11,10 @@@ import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ BoundedFileReadChangedError,
+ BoundedFileReadUncertainError,
GHOST_MANIFEST_MAX_BYTES,
+ readBoundedFileFollowLinks,
readBoundedFileNoFollow,
readBoundedFileNoFollowSync,
} from '../readBoundedFile';
@@@ -260,35 -379,15 +427,38 @@@ describe('readBoundedFileNoFollowSync'
expect(readBoundedFileNoFollowSync(big, 1024)).toBeNull();
});
- it.runIf(process.platform !== 'win32')('符号链接:O_NOFOLLOW 拒于 open,回退闸拒于 lstat', async () => {
- const target = path.join(workDir, 'target.json');
- await fs.promises.writeFile(target, '{"ok":true}');
- const link = path.join(workDir, 'link.json');
- await fs.promises.symlink(target, link);
- expect(() => readBoundedFileNoFollowSync(link, 1024)).toThrow();
- expect(readBoundedFileNoFollowSync(link, 1024, { noFollowFlag: null })).toBeNull();
- });
+ it.runIf(process.platform !== 'win32')(
+ '符号链接:O_NOFOLLOW 拒于 open,回退闸拒于 lstat',
+ async () => {
+ const target = path.join(workDir, 'target.json');
+ await fs.promises.writeFile(target, '{"ok":true}');
+ const link = path.join(workDir, 'link.json');
+ await fs.promises.symlink(target, link);
+ expect(() => readBoundedFileNoFollowSync(link, 1024)).toThrow();
+ expect(readBoundedFileNoFollowSync(link, 1024, { noFollowFlag: null })).toBeNull();
+ },
+ );
});
+
+describe('readBoundedFileNoFollowSync mutation guard', () => {
+ it('rejects a file that changes while being read', async () => {
+ const file = path.join(workDir, 'mutating.json');
+ await fs.promises.writeFile(file, '{"ok":1}');
+ const realReadSync = fs.readSync;
+ let mutated = false;
+ const spy = vi.spyOn(fs, 'readSync').mockImplementation(((fd, buffer, offset, length, position) => {
+ const bytesRead = (realReadSync as typeof fs.readSync)(fd, buffer, offset, length, position);
+ if (!mutated && bytesRead > 0) {
+ mutated = true;
+ fs.writeFileSync(file, '{"ok":2,"mutated":true}');
+ }
+ return bytesRead;
+ }) as typeof fs.readSync);
+
+ try {
+ expect(() => readBoundedFileNoFollowSync(file, 1024)).toThrow(/changed while being read/);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
diff --cc apps/desktop/src/main/utils/readBoundedFile.ts
index e2da81b72c,ae4bb5de03..4570e553ff
--- a/apps/desktop/src/main/utils/readBoundedFile.ts
+++ b/apps/desktop/src/main/utils/readBoundedFile.ts
@@@ -52,33 -93,24 +93,43 @@@ function sameInode(a: fs.BigIntStats, b
return a.dev === b.dev && a.ino === b.ino;
}
+function sameStableFileState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {
+ if (!after.isFile()) return false;
+ if (before.dev !== 0n && before.ino !== 0n && after.dev !== 0n && after.ino !== 0n) {
- if (!sameInode(before, after)) return false;
++ return sameHandleVersion(before, after);
+ }
+ return (
++ before.mode === after.mode &&
+ before.size === after.size &&
+ before.mtimeNs === after.mtimeNs &&
+ before.ctimeNs === after.ctimeNs
+ );
+}
+
+function changedWhileReadingError(): NodeJS.ErrnoException {
+ const error = new Error('source file changed while being read') as NodeJS.ErrnoException;
+ error.code = 'EIO';
+ return error;
+}
+
+ /** 同一打开句柄在读取前后是否仍是同一内容版本。 */
+ function sameHandleVersion(a: fs.BigIntStats, b: fs.BigIntStats): boolean {
+ return (
+ a.dev === b.dev &&
+ a.ino === b.ino &&
+ a.mode === b.mode &&
+ a.size === b.size &&
+ a.mtimeNs === b.mtimeNs &&
+ a.ctimeNs === b.ctimeNs
+ );
+ }
+
/**
* 在已打开句柄上循环读满已校验的长度。网络盘/FUSE 上单次 read() 不保证填满
- * 请求区间,单次读会把合法文件截断成解析失败。EOF 早于已校验长度(并发截断)
- * 时按实际读到的字节返回,交由上层解析/校验自然拒绝。
+ * 请求区间,单次读会把合法文件截断成解析失败。EOF 提前时这里只返回实际字节;
+ * 调用方随后用句柄版本复核(及可选复读)拒绝并发截断或改写。
*/
- async function readToLength(
- handle: fs.promises.FileHandle,
- size: number,
- ): Promise<Buffer> {
+ async function readToLength(handle: fs.promises.FileHandle, size: number): Promise<Buffer> {
const buffer = Buffer.alloc(size);
let offset = 0;
while (offset < size) {
@@@ -167,16 -190,29 +226,35 @@@ export async function readBoundedFileNo
if (!(await verifyStillWithinRoot(stat, filePath, options.containWithin))) return null;
}
const bytes = await readToLength(handle, Number(stat.size));
- const finalStat = await handle.stat({ bigint: true });
- if (options?.rejectHardLinks && finalStat.nlink !== 1n) {
+ const after = await handle.stat({ bigint: true });
++ if (options?.rejectHardLinks && after.nlink !== 1n) {
+ if (options.verifyContentStability) throw new BoundedFileReadChangedError();
+ return null;
+ }
- if (!sameHandleVersion(stat, finalStat)) {
+ if (bytes.byteLength !== Number(stat.size) || !sameStableFileState(stat, after)) {
+ if (options?.verifyContentStability) throw new BoundedFileReadChangedError();
- return null;
+ throw changedWhileReadingError();
+ }
+ if (options?.containWithin !== undefined) {
+ if (!(await verifyStillWithinRoot(after, filePath, options.containWithin))) {
++ if (options?.verifyContentStability) throw new BoundedFileReadChangedError();
+ throw changedWhileReadingError();
+ }
}
- return bytes;
+ if (options?.verifyContentStability) {
+ const verificationBytes = await readToLength(handle, Number(stat.size));
+ const verificationStat = await handle.stat({ bigint: true });
+ if (
+ (options.rejectHardLinks && verificationStat.nlink !== 1n) ||
- !sameHandleVersion(finalStat, verificationStat) ||
++ !sameStableFileState(after, verificationStat) ||
+ bytes.length !== verificationBytes.length ||
+ !bytes.equals(verificationBytes)
+ ) {
+ throw new BoundedFileReadChangedError();
+ }
+ return { bytes, stat: verificationStat };
+ }
- return { bytes, stat: finalStat };
++ return { bytes, stat: after };
} finally {
await handle.close();
}
diff --cc apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx
index 853b6c2fd1,17ffe36c6b..f5f2ddd7e5
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx
@@@ -202,7 -202,14 +202,14 @@@ describe('GhostPermissionDiffView(更�
render(<GhostPermissionDiffView diff={diffGhostPermissionItems(prev, next)} />);
// 真正的权限变化(新增网络域名)仍在折叠区之外,第一屏就能看到。
expect(screen.getByText(/perm\.networkHost:.*api\.example\.com/)).toBeTruthy();
- expect(screen.getByText('settings.ghosts.perm.added')).toBeTruthy();
+ expect(screen.getAllByText('settings.ghosts.perm.added')).toHaveLength(2);
+ // 新增 network 槽后 code 项的主机固定说明换版本(codeDetail → codeDetailNetwork):
+ // 指纹含 detailKey 后这算权限面变化,但同 key 配对成一条「更新」行,
+ // 不渲染成「移除+新增」两条误导用户。
+ expect(screen.getByText('settings.ghosts.perm.updated')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.perm.code')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.perm.codeDetailNetwork')).toBeTruthy();
+ expect(screen.queryByText('settings.ghosts.perm.removed')).toBeNull();
// 4 条工具行收进一个折叠组,原文默认不渲染。
expect(screen.getByText(/perm\.itemCount:.*"count":4/)).toBeTruthy();
expect(screen.queryByText('新说明 A(整段接口文档)')).toBeNull();
diff --cc apps/desktop/src/shared/ghost.ts
index b6add2641c,ac104918e2..1bbc324075
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@@ -1641,47 -1626,6 +1668,47 @@@ function formatGhostQuotaSize(bytes: nu
* 顺序即展示顺序:Cindy 代办 → 注册工具 → 聊天指令 → 面板 → 订阅/卡片 →
* 可执行代码(先能力后载体,与权限展示契约一致)。
*/
+/**
+ * 权限投影的规范化指纹:两份 manifest「用户在确认卡上看到的权限内容」是否逐字
+ * 相同的唯一判据。
+ *
+ * **只比 `key` 是不够的**:同一个 key 下还有会呈现给用户、并构成授权语义的字段 ——
+ * `labelArgs`(preview 的 hosts、工具名等)、`detail`(作者自由文本,OAuth scopes /
+ * node secret 绑定方式等都经它展示)、`detailKey`/`detailArgs`。市场确认拿服务端
+ * 清单给用户看、拿下载包装入,两份清单在这些字段上不同而 key 相同时,用户看的是 A、
+ * receipt 钉的是 B。字段序列化按固定字段序 + labelArgs/detailArgs 键排序,与对象
+ * 构造顺序无关。
+ */
+function ghostPermissionProjectionTuple(item: GhostPermissionItem): unknown[] {
+ const sortRecord = (record: Record<string, string> | undefined): [string, string][] =>
+ Object.entries(record ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ return [
+ item.key,
+ item.kind,
+ item.labelKey,
+ sortRecord(item.labelArgs),
+ item.detail ?? null,
- item.detailKey ?? null,
++ permissionDetailKeyForFingerprint(item) || null,
+ sortRecord(item.detailArgs),
+ ];
+}
+
+function ghostPermissionProjectionKey(item: GhostPermissionItem): string {
+ return JSON.stringify(ghostPermissionProjectionTuple(item));
+}
+
+export function ghostPermissionProjectionFingerprint(manifest: GhostManifest): string {
+ return JSON.stringify(
+ ghostPermissionItems(manifest)
+ .map(ghostPermissionProjectionTuple)
+ .sort((a, b) => {
+ const ka = JSON.stringify(a);
+ const kb = JSON.stringify(b);
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
+ }),
+ );
+}
+
export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItem[] {
const items: GhostPermissionItem[] = [];
for (const [category, actions] of Object.entries(manifest.cindy ?? {})) {
@@@ -2055,8 -2013,38 +2096,33 @@@ export interface GhostPermissionDiff
}
/**
+ * 权限审阅基线指纹:同一份 manifest 推导出的完整用户可见权限投影。
+ * 与 diffGhostPermissionItems 同口径(按稳定 key 对齐、任一展示字段变化算差异),
+ * 权限条目指纹:key + 作者自由文本 detail + 主机固定说明(detailKey + detailArgs,
+ * args 按键序稳定化)。detailKey/detailArgs 必须在内:同一 key 的固定说明会随
+ * 声明变化(cindy text.oneshot 声明 oneshotModel、network secret 的 identity
+ * 形态),只看 key+detail 会把"说明/成本面变了"漏判成"权限面没变",更新时
+ * 用户看不到重新确认。
+ */
+ function permissionDetailKeyForFingerprint(item: GhostPermissionItem): string {
+ // cindy-github 从存量 PAT(source:user)升级为 Host 优先 gh-cli 时,凭证仍由
+ // Main 只注入同一个 network secret key 与同一组目标;变化的是设置页/权限
+ // 页对“凭证从哪里来”的说明,不是插件获得了新权限。两档共用历史 key 的
+ // 同时也必须共用审阅指纹,否则升级会被误判成扩权并要求存量用户重新确认。
+ // gh-cli 的 manifest 校验只允许官方 cindy-github,因此这个兼容等价不会
+ // 放宽其它插件;其它 detailKey/detailArgs 变化仍按新说明完整性规则复核。
+ if (
+ item.detailKey === 'networkSecretGhostInputDetail' ||
+ item.detailKey === 'networkSecretGhCliDetail'
+ ) {
+ return 'networkSecretGithubCredentialDetail';
+ }
+ return item.detailKey ?? '';
+ }
+
-function ghostPermissionItemFingerprint(item: GhostPermissionItem): string {
- const args = item.detailArgs
- ? Object.entries(item.detailArgs).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
- : [];
- return JSON.stringify([item.key, item.detail ?? '', permissionDetailKeyForFingerprint(item), args]);
-}
-
+ /**
+ * 权限审阅基线指纹:同一份 manifest 推导出的权限条目集合(条目指纹见上)。
+ * 与 diffGhostPermissionItems 同口径(按 key 对齐、指纹变化算差异),
* 所以"指纹相同"等价于"权限面没变",可安全沿用先前的审阅结论。
*
* renderer 审阅时记录基线并随安装请求回传,main 在安装锁内用**当前**已装
diff --cc docs/dev-rules/plugin-approval-main-merge-2026-08-09.md
index 0000000000,0000000000..a4a431dc14
new file mode 100644
--- /dev/null
+++ b/docs/dev-rules/plugin-approval-main-merge-2026-08-09.md
@@@ -1,0 -1,0 +1,75 @@@
++# Plugin Approval PR Main Merge Strategy (2026-08-09)
++
++This note records the merge decisions for PR #1916 after merging `origin/main` at
++`e78f44ae5`. It is a decision record, not a replacement for the authoritative
++security rules.
++
++## Invariants
++
++- Host-owned approval receipts remain the only runtime authorization fact. Mutable
++ install-directory trust mirrors are migration or display inputs only.
++- A durable owner boundary is published before local session publication. Missing,
++ malformed, pending, mismatched, or durability-uncertain state fails closed.
++- Every owner-bound Ghost, Agent, broker, slot, skill-link, and IPC consumer must
++ use the same durable owner and in-process owner generation.
++- Passive shared-userData instances are read-only for the global projection. They
++ must not sweep links, publish a different owner, or turn a primary owner's
++ projection into another account's projection.
++- Content and manifest reads keep no-follow, containment, handle identity, and
++ post-read stability checks. A main-branch convenience path must not reintroduce
++ path-based TOCTOU reads.
++- Existing approved plugins remain compatible without reinstall or reapproval.
++ New security checks may reject only malformed or untrusted state, not a valid
++ historical receipt that can be migrated equivalently.
++
++## Conflict decisions
++
++- **Trust and GhostManager:** retain main's complete official-trust validation and
++ the PR's rule that a mutable `.cindy-trust.json` cannot mint approval. Keep the
++ PR's receipt, approval projection, journal, owner, and failure-closed paths.
++- **Bounded reads:** combine the PR's no-follow/stable-read implementation with
++ main's optional non-blocking, hard-link, and stat-returning APIs. No caller may
++ downgrade a stability or containment failure into an approved projection.
++- **Built-in provisioning:** retain the PR's seed fingerprint, link-free checks,
++ durable tombstone/seed ledger, and rollback semantics; wrap the complete per-id
++ installed-directory exchange in main's Ghost install lock. Locking does not
++ replace owner lease or the durable provisioning state machine.
++- **Market install/update:** retain `expectedInstalledApproval`, reviewed manifest
++ and baseline checks, and the receipt token at the final commit. Also retain
++ main's `beforeCommitInLock` callback and stale-baseline behavior, executing the
++ callback while the per-Ghost lock is held and the owner lease remains held.
++- **Permission fingerprints:** use main's `detailKey/detailArgs` projection for
++ user-visible permission explanations, while preserving the PR's stable approval
++ baseline and `diffInstalledGhostPermissionItems` behavior. Normalize equivalent
++ GitHub credential detail keys only where the existing compatibility rule says the
++ capability is unchanged.
++- **Auth cold start:** retain the PR's account-free recovery for local and
++ signed-out exits. Incorporate main's same-owner cold-start fast path and delayed
++ teardown only when `shouldTeardownColdStartRuntime` proves a real owner change;
++ never dispose a newly-created same-owner runtime as an account switch.
++- **Subscription hooks:** retain the PR's captured owner validation before and after
++ wake. Incorporate main's deadline-aware wake and resolved context payload, but
++ discard the result if the hook was cancelled or the durable owner changed.
++- **Tests and documentation:** keep the union of security regression tests and main
++ behavioral tests. A source-contract test may supplement, but never replace,
++ behavioral coverage for authorization, locking, recovery, or filesystem state.
++
++## Do not accept during conflict resolution
++
++- Direct authorization from install-directory mirrors, renderer-provided tokens,
++ mutable manifests, or a stale in-memory session.
++- A fast return that leaves an old global skill projection visible to local,
++ signed-out, or passive sessions.
++- A path-based read/write that drops no-follow, containment, identity, or stability
++ validation because main added a convenience helper.
++- A lock-only solution that omits the owner lease, or an owner lease that omits the
++ per-Ghost mutation lock where both are required.
++- A test-only weakening, skipped test, or branch-specific assertion that hides a
++ conflict instead of expressing the merged behavior.
++
++## Post-merge gate
++
++After all conflicts are resolved: inspect the complete diff, verify no unmerged
++entries, run targeted plugin/auth/Forge tests, run all workspace typechecks, run the
++full `pnpm test:unit` gate, then perform an independent review before committing or
++ pushing the merge result.