Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge origin/main into redo/plugin-approval-receipt-migration
Yuewei-LL685da573db95
diff --cc apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex c86f4fbcff,c4d3a96e8d..1b36e08154--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@@ -2189,6 -1198,46 +2189,48 @@@ describe('legacy Ghost plugin recovery');});+ it('recovers legacy manual metadata from shared and owner-scoped roots without weakening other validation', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDirWithManifest(+ path.join(root, 'brain', 'legacy-string'),+ 'legacy-string',+ { manual: 'old notes' },+ );+ await writeGhostDirWithManifest(+ path.join(root, 'owners', ownerKey, 'brain', 'legacy-object'),+ 'legacy-object',+ { manual: { arbitrary: 'old metadata' } },+ );+ await writeGhostDirWithManifest(+ path.join(root, 'brain', 'invalid-other-field'),+ 'invalid-other-field',+ { manual: 'old notes', name: 42 },+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),- ).toEqual({ state: 'partial', legacyPluginCount: 2, canRetry: true });++ // Legacy manual metadata is ignored only for compatibility. The manifest++ // with an invalid known field remains visible as a fail-closed conflict.++ ).toEqual({ state: 'partial', legacyPluginCount: 3, canRetry: true });++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),- ).resolves.toMatchObject({ status: 'migrated', moved: 2, conflicts: 0 });++ ).resolves.toMatchObject({ status: 'partial', moved: 2, conflicts: 1 });+ const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');+ await expect(fs.access(path.join(targetRoot, 'legacy-string'))).resolves.toBeUndefined();+ await expect(fs.access(path.join(targetRoot, 'legacy-object'))).resolves.toBeUndefined();+ await expect(fs.access(path.join(root, 'brain', 'invalid-other-field'))).resolves.toBeUndefined();+ await expect(fs.access(path.join(targetRoot, 'invalid-other-field'))).rejects.toThrow();+ });+it('removes a newly created empty target when every plugin rename fails', async () => {const root = await tempRoot();const ownerId = 'cloud-a';diff --cc apps/desktop/src/main/cindy-brain/GhostManager.tsindex 1e74f1963b,34161f4c94..dff5e578b9--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@@ -12,11 -10,11 +12,13 @@@ importGHOST_ICON_MAX_BYTES,GHOST_INSTALL_MANIFEST_MAX_BYTES,GHOST_SLOTS,+ GHOST_MANUAL_ENTRY_FILE,+ GHOST_MANUAL_MD_MAX_BYTES,GHOST_SKILL_MD_MAX_BYTES,ghostLocalePathFor,+ ghostInstallApprovalToken,ghostIconMimeType,+ isOfficialGhostId,isValidGhostId,resolveGhostManifestLocale,validateGhostManifest,@@@ -28,26 -26,16 +30,31 @@@type InstalledGhost,} from '../../shared/ghost.js';import { verifyGhostZipSignatures, type GhostTrustRegistry } from './ghostSignature.js';+import { isPathInsideDir } from './dirDeposit.js';import {- readBoundedFileFollowLinks,- readBoundedFileNoFollowSync,-} from '../utils/readBoundedFile.js';+ classifyGhostDirEntry,+ classifyGhostDirEntrySync,+ collectGhostContentFiles,+ hashGhostContentBuffers,+ hashGhostContentFiles,+ resolveGhostContentPathSync,+ type GhostDirEntryKind,+} from './ghostContentTree.js';+import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';import { checkSkillMdConsistency } from './skillSlot.js';+import {+ createGhostInstallReceipt,+ GhostInstallReceiptStore,+ hashApprovedSkillContent,+ readLegacyInstallTrust,+ type GhostInstallReceipt,+ type GhostInstallReceiptReadResult,+} from './ghostInstallReceipt.js';+ import { parseInstalledGhostManifest } from '../installedGhostManifest.js';+ import {+ decodeGhostManualMarkdown,+ ghostManualLogicalPathForEntry,+ } from './ghostManualValidation.js';/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */export const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;@@@ -217,246 -137,8 +230,249 @@@ export interface GhostPackageCommitPrepexport 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;+ try {+ const iconPath = resolveGhostContentPathSync(dir, manifest.icon, {+ expect: 'file',+ label: 'legacy icon',+ });+ const bytes = readBoundedFileNoFollowSync(iconPath, GHOST_ICON_MAX_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;+ }+}++/**+ * 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);++ // Installed legacy manifests may carry the pre-manual top-level metadata++ // field. Keep the compatibility rule identical across discovery and the++ // approval projection freeze; all other manifest validation stays strict.++ const validated = parseInstalledGhostManifest(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;+ trust?: typeof CINDY_OFFICIAL_GHOST_TRUST;+ },+ ): Promise<void>;+ approveTrustedBundledInstall(+ manifest: GhostManifest,+ markerEnabled: boolean,+ options: { sourceDir: string },+ ): Promise<boolean>;+ removeInstallApproval(id: string): Promise<boolean>;+ uninstall(id: string, options?: GhostUninstallOptions): Promise<UninstallResult>;+}+/*** 区分“包本身坏了”和“包使用了更新版 Cindy 才认识的契约”。*@@@ -667,1700 -288,36 +683,1707 @@@ export class GhostManager}/**- * 启用 / 停用一张意识。停用不删任何东西,只在安装目录里放一个 `.disabled`- * 标记文件(目录即事实:打开文件夹一眼可见);启用即删掉标记。幂等。+ * 启动一次性:恢复装入/更新的"目录已 rename、receipt 还没写"崩溃现场。构造期同步跑+ * (目录极小,与 resolveGhostRepoRoot 的启动期迁移同一先例)。+ *+ * **事务标记(状态根内)是权威判据**:装入/更新在 rename 动盘前落标记、写完 receipt+ * 清标记,标记带本次 `packageSha256`。恢复时同步读 receipt,`receipt.packageSha256 ===+ * marker.packageSha256` 即"已提交":+ * - install 未提交 → finalDir 是不完整安装,删掉(否则迁移会把它当 legacy 收编,而+ * 崩溃窗口内 manifest 可能已被同权限进程改写 = 用户确认 A 却授权 B);已提交 → 保留;+ * - update 未提交 → 回滚到 backup(旧字节+旧 receipt 自洽);已提交 → 回收陈旧 backup。+ * 这修掉了"final 在位就删 backup"把"新字节+旧 receipt"固化成"按旧批准跑新代码"的洞。+ *+ * 无标记的孤儿 `.cindy-updating-*`(journal 之前的崩溃残留)沿用原启发式兜底:final+ * 缺位且唯一 backup → 搬回(§5 插件不得凭空消失);final 在位 → 陈旧 backup 回收。+ * `.cindy-installing-*` staging 残留一律回收(从未发布)。*/- async setEnabled(- id: string,- enabled: boolean,- ): Promise<{ ok: true } | { rejection: UninstallRejection }> {- if (!isValidGhostId(id)) {- return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };+ private recoverInterruptedMutationsSync(): void {+ const root = this.contentRootDir();++ // 1) 标记驱动恢复(权威)。+ const handledBackupNames = new Set<string>();+ const blockedMutationIds = new Set<string>();+ const pendingScan = this.receiptStore.listPendingMutationIdsSync();+ if (pendingScan.state === 'unreadable') {+ this.recoveryBlockedApprovalNamespaces.add(this.approvalNamespaceKey());+ this.quarantineAllInstalledApprovalsSync();+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost mutation journal root unreadable; skipped all recovery heuristics',+ { error: pendingScan.reason },+ );+ return;}- const dir = path.join(this.options.getRootDir(), id);- if (!(await pathExists(dir))) {- return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };+ let recoveryHeuristicsBlocked = false;+ if (pendingScan.blocked) {+ this.recoveryBlockedApprovalNamespaces.add(this.approvalNamespaceKey());+ this.quarantineAllInstalledApprovalsSync();+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'invalid ghost mutation journal marker blocks orphan-backup heuristics',+ );+ } else {+ // The journal namespace is authoritative again. Known pending ids still+ // receive per-id isolation below if their individual recovery fails.+ this.recoveryBlockedApprovalNamespaces.delete(this.approvalNamespaceKey());}- const marker = path.join(dir, DISABLED_MARKER_FILE);+ for (const id of pendingScan.ids) {+ const markerResult = this.receiptStore.readPendingMutationSync(id);+ const finalDir = path.join(root, id);+ if (markerResult.state === 'missing') continue;+ // A pending transaction means the receipt cannot authorize finalDir until+ // recovery proves commit/rollback and clears the marker.+ this.untrustedApprovals.add(this.isolationKey(id));+ if (markerResult.state !== 'valid') {+ blockedMutationIds.add(id);+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost mutation journal unavailable; left for manual/next-launch recovery',+ { id, state: markerResult.state, reason: markerResult.reason },+ );+ continue;+ }+ const marker = markerResult.mutation;+ try {+ if (marker.kind === 'uninstall') {+ // 卸载崩在半途:把批准与内容目录都删净(幂等,顺序无关)。撤批准已在卸载时+ // 先行,这里兜住"receipt 或目录仍残留"的任意组合 —— 收尾后该 id 干净消失。+ this.untrustedApprovals.add(this.isolationKey(id));+ if (marker.builtinTombstone) {+ if (!this.options.recordBuiltinTombstone) {+ throw new Error('builtin uninstall recovery has no tombstone writer');+ }+ this.options.recordBuiltinTombstone(id);+ }+ this.receiptStore.removeSync(id);+ if (this.recoveryEntryKind(finalDir) === 'directory') {+ fs.rmSync(finalDir, { recursive: true, force: true });+ }+ } else {+ const approval = this.receiptStore.readForRecovery(id);+ if (approval.state === 'unreadable') {+ blockedMutationIds.add(id);+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost approval receipt unreadable during recovery; journal retained',+ { id, kind: marker.kind, reason: approval.reason },+ );+ continue;+ }+ if (marker.kind === 'install') {+ // 未提交装入(无已批准 receipt)= 不完整安装,删 finalDir;有已批准 receipt = 完整+ // 安装,保留(绝不删有有效批准的插件)。只删真目录,junction/链接跳过(避免穿透)。+ const finalKind = this.recoveryEntryKind(finalDir);+ const receiptCommitted =+ approval.state === 'approved' &&+ (marker.receiptRevision !== undefined+ ? approval.receipt.revision === marker.receiptRevision+ : approval.receipt.packageSha256 === marker.packageSha256);+ const committed = receiptCommitted && finalKind === 'directory';+ if (receiptCommitted && finalKind !== 'directory') {+ throw new Error('committed install receipt has no published directory');+ }+ if (committed && marker.clearBuiltinTombstone) {+ if (!this.options.clearBuiltinTombstone) {+ throw new Error('builtin install recovery has no tombstone clearer');+ }+ this.options.clearBuiltinTombstone(id);+ }+ if (!committed && finalKind === 'directory') {+ fs.rmSync(finalDir, { recursive: true, force: true });+ }+ } else {+ handledBackupNames.add(marker.backupDirName);+ const backupPath = path.join(root, marker.backupDirName);+ const backupKind = this.recoveryEntryKind(backupPath);+ const finalKind = this.recoveryEntryKind(finalDir);+ const committed =+ approval.state === 'approved' &&+ finalKind === 'directory' &&+ (marker.receiptRevision !== undefined+ ? approval.receipt.revision === marker.receiptRevision+ : approval.receipt.packageSha256 === marker.packageSha256 &&+ (marker.oldPackageSha256 !== undefined+ ? marker.oldPackageSha256 !== marker.packageSha256+ : marker.phase === 'published'));+ if (committed) {+ if (backupKind === 'directory') {+ fs.rmSync(backupPath, { recursive: true, force: true }); // 陈旧旧字节+ } else if (backupKind !== 'missing') {+ throw new Error('managed update backup is not a real directory');+ }+ } else {+ // 回滚:finalDir 可能是未提交新字节,删;backup 若在则搬回(旧字节+旧 receipt)。+ if (+ marker.receiptRevision !== undefined &&+ approval.state === 'approved' &&+ approval.receipt.revision === marker.receiptRevision &&+ finalKind !== 'directory'+ ) {+ throw new Error('committed update receipt has no published directory');+ }+ // A prepared (or legacy phase-less) marker with no backup means the+ // process crashed before final -> backup. Preserve the old final and+ // receipt instead of deleting valid installed bytes.+ if (backupKind === 'missing' && finalKind === 'directory') {+ if (marker.phase === 'prepared') {+ this.receiptStore.clearPendingMutationSync(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ continue;+ }+ // A legacy v1 marker has no phase information. Preserve the+ // marker and block heuristics rather than guessing whether the+ // final bytes are old or newly published.+ throw new Error('managed update final present without backup at an unknown phase');+ }+ if (finalKind === 'directory') {+ fs.rmSync(finalDir, { recursive: true, force: true });+ } else if (finalKind !== 'missing') {+ throw new Error('managed update final is not a real directory');+ }+ if (backupKind === 'directory') {+ fs.renameSync(backupPath, finalDir);+ } else if (backupKind === 'missing') {+ // Neither side is available; keep the journal and receipt for a+ // later retry rather than deleting authorization state.+ throw new Error('managed update final and backup are both missing');+ } else {+ throw new Error('managed update backup is not a real directory');+ }+ }+ }+ }+ this.receiptStore.clearPendingMutationSync(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ } catch (err) {+ // 动盘失败:留着标记,下次启动幂等重试。+ blockedMutationIds.add(id);+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'interrupted ghost mutation recovery failed; left for next launch',+ {+ id,+ kind: marker?.kind,+ error: err instanceof Error ? err.message : String(err),+ },+ );+ }+ }++ // Any unreadable/invalid journal means the state-root view is not authoritative.+ // Do not run unjournaled backup/staging heuristics in that condition.+ if (recoveryHeuristicsBlocked) return;++ // 2) 无标记的孤儿 backup + staging 残留。+ let entries: fs.Dirent[];try {- if (enabled) {- await fs.promises.rm(marker, { force: true });- } else {- await fs.promises.writeFile(marker, '');+ entries = fs.readdirSync(root, { withFileTypes: true });+ } catch {+ return; // 根目录还不存在 = 没装过任何插件+ }+ const backups = entries.filter(+ (entry) => entry.name.startsWith('.cindy-updating-') && !handledBackupNames.has(entry.name),+ );+ for (const entry of backups) {+ const match = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(entry.name);+ if (!match || !isValidGhostId(match[1])) continue;+ const id = match[1];+ if (blockedMutationIds.has(id)) continue;+ const backupPath = path.join(root, entry.name);+ try {+ if (classifyGhostDirEntrySync(backupPath) !== 'directory') continue;+ } catch {+ continue;+ }+ const finalDir = path.join(root, id);+ // 按解析后的 id 精确比对,不能用前缀 startsWith:合法 id 允许带 `-`,+ // `.cindy-updating-foo-<hex>` 是 `.cindy-updating-foo-bar-<hex>` 的前缀,+ // 若用前缀匹配,foo 与 foo-bar 同时留有 backup 时,foo 的唯一 backup 会被+ // 误统计成多个而判为"多备份,留待人工",崩溃后 foo 持续消失(评审 P1)。+ const siblings = backups.filter((other) => {+ const otherMatch = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(other.name);+ return otherMatch !== null && otherMatch[1] === id;+ });+ let finalKind: GhostDirEntryKind | 'missing';+ try {+ finalKind = classifyGhostDirEntrySync(finalDir);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ finalKind = 'missing';+ } else {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'interrupted-update final path unreadable; backup left untouched',+ { id, backup: entry.name, error: err instanceof Error ? err.message : String(err) },+ );+ continue;+ }+ }+ if (finalKind === 'directory') {+ try {+ fs.rmSync(backupPath, { recursive: true, force: true });+ } catch (err) {+ this.options.log?.warn('stale ghost update backup cleanup failed', {+ id,+ backup: entry.name,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ continue;+ }+ if (finalKind !== 'missing') {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'interrupted-update final path is not a directory; backup left untouched',+ { id, backup: entry.name, finalKind },+ );+ continue;+ }+ if (siblings.length !== 1) {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'multiple interrupted-update backups for one ghost; left untouched for manual recovery',+ {+ id,+ backups: siblings.map((other) => other.name),+ },+ );+ continue;+ }+ try {+ fs.renameSync(backupPath, finalDir);+ this.options.log?.info('ghost restored from interrupted update backup', { id });+ } catch (err) {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost interrupted-update recovery failed; plugin stays missing until manual recovery',+ {+ id,+ backup: entry.name,+ error: err instanceof Error ? err.message : String(err),+ },+ );+ }+ }+ for (const entry of entries) {+ if (!entry.name.startsWith('.cindy-installing-')) continue;+ try {+ fs.rmSync(path.join(root, entry.name), { recursive: true, force: true });+ } catch {+ // staging 残留清不掉只占磁盘,不影响正确性;下次启动再试。+ }+ }+ }++ /** `<root>/<id>` 是否真目录(非链接/junction;判据同 ghostContentTree,避免穿透删除)。 */+ private isRealDirChild(root: string, id: string): boolean {+ try {+ return classifyGhostDirEntrySync(path.join(root, id)) === 'directory';+ } catch {+ return false;+ }+ }++ /** Recovery distinguishes a missing path from transiently unreadable state. */+ private recoveryEntryKind(absPath: string): GhostDirEntryKind | 'missing' {+ try {+ return classifyGhostDirEntrySync(absPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ throw error;+ }+ }++ /**+ * 从 `.cindy` 包的内存投影算技能字节指纹(P0-8)。+ *+ * 批准基线必须取自**用户确认过、且不可再被本机进程改写**的来源。旧写法在+ * staging→final 发布之后才从 finalDir 首读 —— publish 与首次 hash 之间被换掉的+ * SKILL.md 正文/辅助文件会同时成为 receipt 指纹与快照,后续校验全自洽,篡改被+ * 洗成批准事实。包投影(JSZip 内存条目)在 inspect 时已被 packageSha256 钉住、+ * 与用户确认的是同一份字节;据它算指纹后,发布后的目录漂移会在快照落盘对账时+ * 如实 fail closed(拒装),而不是被钉进批准。+ */+ private async hashSkillContentFromPackage(+ manifest: GhostManifest,+ allEntries: JSZip.JSZipObject[],+ prefix: string,+ ): Promise<Record<string, string>> {+ const items = manifest.skill?.items ?? [];+ if (items.length === 0) return {};+ const result: Record<string, string> = {};+ for (const item of items) {+ const itemPrefix = `${item.dir}/`;+ const files: { path: string; bytes: Buffer }[] = [];+ for (const entry of allEntries) {+ if (entry.dir) continue;+ const rel = entry.name.slice(prefix.length);+ if (!rel.startsWith(itemPrefix)) continue;+ files.push({ path: rel.slice(itemPrefix.length), bytes: await entry.async('nodebuffer') });+ }+ result[item.dir] = hashGhostContentBuffers(files);+ }+ return result;+ }++ /** Forge 等 Host 能力必须排除的受管根(内容根 + 批准状态根)。 */+ managedRootDirs(): string[] {+ return [this.contentRootDir(), this.receiptStore.rootDir()];+ }++ approvalStateRoot(): string {+ return this.receiptStore.rootDir();+ }++ /**+ * 启停投影:receipt 为主,安装目录 `.disabled` 镜像**只往停用方向覆盖**(读时合并)。+ *+ * 为什么在读侧合并而不是只信 receipt:停用必须永远能成功(规则 §3 收敛方向不对称)。+ * 状态根不可写时 `setEnabled(false)` 仍能写镜像;若 list() 只读 receipt,那次停用会在+ * 重启后静默复活 —— fail open。镜像只能把启停态往下拉,不能往上翻(重新启用只有+ * setEnabled(true) 成功写 receipt 一条路),与随包对账的合并规则同向。+ */+ private effectiveEnabled(dir: string, receiptEnabled: boolean): boolean {+ return receiptEnabled && !this.isDisabledMarkerPresentSync(dir);+ }++ /** Compatibility marker reads fail closed and never follow a link/non-regular entry. */+ private isDisabledMarkerPresentSync(dir: string): boolean {+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ try {+ // A regular marker means disabled; any non-regular entry also fails closed.+ classifyGhostDirEntrySync(marker);+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ return true;+ }+ }++ private writeDisabledMarkerSync(dir: string): void {+ if (classifyGhostDirEntrySync(dir) !== 'directory') {+ throw new Error('ghost disabled marker parent is not a real directory');+ }+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ fs.writeFileSync(marker, '');+ }++ /**+ * 读批准状态的**唯一入口**:进程内隔离优先于磁盘上的 receipt。+ *+ * 所有消费方(list / setEnabled / update 的 token 比对)都必须走这里 —— 各自直接+ * 调 receiptStore.read() 会让隔离在某条路径上失效,那类"同一判定散落多处"的分叉+ * 正是本 PR 前几轮反复出问题的原因。+ */+ private readApproval(id: string): GhostInstallReceiptReadResult {+ if (this.recoveryBlockedApprovalNamespaces.has(this.approvalNamespaceKey())) {+ return { state: 'invalid', reason: 'ghost mutation journal namespace is unreadable' };+ }+ if (this.untrustedApprovals.has(this.isolationKey(id))) {+ return { state: 'invalid', reason: '批准状态已被判定不可信(撤销失败)' };+ }+ return this.receiptStore.read(id);+ }++ /**+ * 技能链接对账前重新核验批准快照。+ *+ * `list()` 是首帧同步 API,不能在里面流式重算目录摘要;因此由异步 reconciler+ * 对每个准备挂链的插件调用本入口。receipt revision 若已变化、快照缺失/不可读、+ * 含非普通条目或字节不符一律 false,让对账器撤掉已有链接并拒绝新建。+ */+ async verifyApprovedSkillSnapshot(ghost: InstalledGhost): Promise<boolean> {+ this.ensureCurrentOwnerContextSync();+ if (+ ghost.approval.state !== 'approved' ||+ !ghost.manifest.skill?.items.length ||+ !ghost.approvedSkillRoot+ ) {+ return false;+ }+ const current = this.readApproval(ghost.manifest.id);+ if (current.state !== 'approved' || current.receipt.revision !== ghost.approval.revision) {+ return false;+ }+ const expectedRoot = this.receiptStore.skillSnapshotRoot(+ current.receipt.id,+ current.receipt.revision,+ );+ if (path.resolve(ghost.approvedSkillRoot) !== path.resolve(expectedRoot)) {+ return false;+ }+ return this.receiptStore.skillSnapshotMatchesReceipt(current.receipt, expectedRoot);+ }++ /**+ * Serialize content-directory and approval-receipt mutations as one Host transaction lane.+ * The owner generation and both roots are captured after queue wait and remain fixed for the+ * whole callback, so a concurrent session commit cannot redirect later awaits into another+ * owner's namespace.+ */+ async runExclusiveMutation<T>(+ operation: (mutation: GhostExclusiveMutation) => Promise<T>,+ ): Promise<T> {+ this.ensureCurrentOwnerContextSync();+ const queuedOwnerContextKey = this.ownerContextKey;+ const previous = this.mutationTail;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ this.mutationTail = previous.then(() => gate);+ await previous;+ let capabilityActive = true;+ try {+ const currentOwnerContextKey = this.currentOwnerContextKey();+ if (+ this.ownerContextKey !== queuedOwnerContextKey ||+ currentOwnerContextKey !== queuedOwnerContextKey+ ) {+ throw new Error('ghost owner context changed while mutation was queued');+ }+ const contentRoot = this.resolveContentRoot();+ const stateRoot = this.resolveStateRoot();+ this.assertDisjointRoots(contentRoot, stateRoot);+ this.activeMutationContext = {+ ownerContextKey: currentOwnerContextKey,+ contentRoot,+ stateRoot,+ };+ const assertCapabilityActive = (): void => {+ if (+ !capabilityActive ||+ this.activeMutationContext?.ownerContextKey !== currentOwnerContextKey+ ) {+ throw new Error('ghost exclusive mutation capability is no longer active');+ }+ };+ const mutation: GhostExclusiveMutation = {+ writeDisabledMarker: (id) => {+ assertCapabilityActive();+ if (!isValidGhostId(id) || !this.isRealDirChild(this.contentRootDir(), id)) {+ throw new Error('ghost disabled marker target is not a managed plugin directory');+ }+ this.writeDisabledMarkerSync(path.join(this.contentRootDir(), id));+ },+ publishTrustedBundledSeed: async (id, sourceDir, options) => {+ assertCapabilityActive();+ await this.publishTrustedBundledSeedUnlocked(id, sourceDir, options);+ },+ approveTrustedBundledInstall: async (manifest, markerEnabled, options) => {+ assertCapabilityActive();+ return this.approveTrustedBundledInstallUnlocked(manifest, markerEnabled, options);+ },+ removeInstallApproval: async (id) => {+ assertCapabilityActive();+ return this.removeInstallApprovalUnlocked(id);+ },+ uninstall: async (id, options = {}) => {+ assertCapabilityActive();+ return this.uninstallUnlocked(id, options);+ },+ };+ return await operation(mutation);+ } finally {+ capabilityActive = false;+ this.activeMutationContext = null;+ release();+ }+ }++ /**+ * 一次性 legacy backfill 迁移(docs/dev-rules/plugin-security-and-authoring.md 第 5 节+ * 红线的落地)。#1080 把授权事实从可变安装目录搬到 Host receipt,升级前装的插件没有+ * receipt —— 若不迁移,它们会一律落到 `legacy-unapproved`、被列停用、要用户逐个重新+ * 确认(这正是 #1080 被回滚的原因)。这里从旧的三份事实源(`ghost.json` /+ * `.cindy-trust.json` / `.disabled`)重建等价 receipt,让存量插件升级后**无感可用**。+ *+ * 三条不变量:+ * - **全局一次性**:状态根有迁移 ledger 即视为已迁过,此后缺 receipt 一律 fail closed,+ * 不再迁。理由见 `GhostLegacyMigrationLedger` 头注释(否则删 receipt 就能骗一次+ * "从可变安装目录重建授权")。+ * - **不扩权、不等于新确认**:receipt 权限集 = 当前 `ghost.json` 声明,等价于旧模型+ * 无条件授权的那一组;此后任何 manifest/权限变化照旧走完整确认(update 流程不变)。+ * - **只写状态根、绝不动安装目录**:三份旧文件原样保留,因此回滚到旧客户端时它照旧+ * 从安装目录判定启停,不会错位(§5 兜底第 4 条 回滚余地)。+ *+ * 随包种子 id 跳过 —— 它们走 provisioning 的 `approveTrustedBundledInstall`(有权威+ * 字节可比,是更强的迁移形态)。+ */+ async migrateLegacyApprovalsOnce(): Promise<{+ migrated: string[];+ skipped: string[];+ failed: string[];+ retryPending: string[];+ }> {+ return this.runExclusiveMutation(() => this.migrateLegacyApprovalsUnlocked());+ }++ private async migrateLegacyApprovalsUnlocked(): Promise<{+ migrated: string[];+ skipped: string[];+ failed: string[];+ retryPending: string[];+ }> {+ const result = {+ migrated: [] as string[],+ skipped: [] as string[],+ failed: [] as string[],+ retryPending: [] as string[],+ };+ // 一次性门(状态机见 GhostLegacyMigrationLedger 头注释),判据缺一不可:+ // 1) 台账 completed(或存在但读不出)= 迁过,不再迁;in-progress = 上一轮中途+ // 崩溃,按钉死的 pendingIds 续跑 —— receipt 首写自动落台账的守卫(见+ // receiptStore.write)只在"完全没有台账"时动笔,不会把 in-progress 焊死。+ // 2) 首轮必须先扫描完整安装根,不能因**任意一个**有效 receipt 提前关门。#1080+ // 曾经写出 receipt 却没有 migration ledger;那类历史 mixed 状态里 A 已批准、B+ // 仍是 legacy,提前 completed 会让 B 永久失效。新代码通过 receipt 提交前先写+ // ledger 保证不再自然产生这种状态;能删 ledger 的状态根写者本就能伪造 receipt,+ // 不属于安装根可变这一条威胁模型新增的能力。+ // 之所以"安装根为空/未诞生时不落台账":为 owner 命名空间的 legacy 恢复流程留门+ // (它会在之后才把旧目录搬进来);这个留门被"装一个插件→删 receipt"利用的路由+ // 第 2 道判据 + receipt 首写自动落台账挡住。+ if (this.receiptStore.migrationDoorClosed()) {+ if (this.receiptStore.hasMigrationLedger() && !this.receiptStore.readMigrationLedger()) {+ // 台账存在但读不出:门保守关死(成因与保守方向见 migrationDoorClosed 注释),+ // 但这必须可观测 —— 它意味着状态根被外力改写过。+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'legacy migration ledger unreadable; migration door kept closed',+ { path: this.receiptStore.rootDir() },+ );+ }+ return result;+ }+ const resumeLedger = this.receiptStore.readMigrationLedger();+ const resumePending =+ resumeLedger?.state === 'in-progress' ? new Set(resumeLedger.pendingIds ?? []) : null;+ const resumeApprovalProjectionDigest =+ resumeLedger?.recoveryApprovalProjectionSha256ById ?? undefined;++ const root = this.contentRootDir();+ let entries: fs.Dirent[] = [];+ try {+ entries = fs.readdirSync(root, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ // 安装根未诞生:全新用户,或 legacy 恢复流程还没把旧目录搬进来。没有可迁+ // 对象,也**不写台账** —— 门要给随后搬入的旧目录留着(见头注释)。+ // (in-progress 续跑轮走不到这里出 ENOENT 的话,门保持 in-progress,下轮再试。)+ return result;+ }+ // EACCES/EIO 等真实故障:本轮放弃且不改台账,下次启动重试。吞掉错误照写+ // 台账会把迁移永久封死在一次环境抖动上。+ throw err;+ }++ // 先收候选、后动笔:in-progress 台账必须在**首个 backfill 之前**原子落盘,+ // 否则第一份 receipt 的自动落账守卫就会把门写成 completed,中途崩溃即焊死。+ const candidates: string[] = [];+ const blockedByPendingJournal: string[] = [];+ const unreadableReceiptIds: string[] = [];+ const preMigrated: string[] = [];+ let sawApprovedNonBundledInstall = false;+ // 续跑只对白名单内、且本轮仍可观察到的对象建重试队列;已消失的目录视为+ // 已被卸载/清理,不应把全局迁移门永久卡在一个不存在的 id 上。+ const pendingForRetry = new Set<string>();+ for (const entry of entries) {+ const id = entry.name;+ if (id.startsWith('.') || !isValidGhostId(id)) continue;+ // 判据走 ghostContentTree(lstat 分类),不信 Dirent 类型位:根子项是 junction/+ // 链接时一律不进迁移,也与 §3「只有真目录才算安装」同向。+ if (classifyGhostDirEntrySync(path.join(root, id)) !== 'directory') continue;+ // 随包种子交给 provisioning,不在迁移范围。+ if (this.options.isTrustedBundledId?.(id)) {+ result.skipped.push(id);+ continue;+ }+ // 续跑轮只认动笔前钉死的清单:清单外的 id(迁移窗口期间新装再删 receipt 的)+ // 骗不到续跑重铸,保持 fail closed。+ if (resumePending && !resumePending.has(id)) {+ result.skipped.push(id);+ continue;+ }+ const approval = this.receiptStore.readForRecovery(id);+ if (approval.state === 'approved') {+ sawApprovedNonBundledInstall = true;+ // 首轮:迁移前不该有,防御性跳过。续跑轮:上一轮崩溃前已写出的 receipt,+ // 计入 migrated 让最终台账如实反映"这些是迁移铸出的"。+ (resumePending ? preMigrated : result.skipped).push(id);+ pendingForRetry.delete(id);+ continue;+ }+ if (approval.state === 'unreadable') {+ // 暂时读不动批准事实不等于 legacy。尤其不能把它放进普通 pendingIds:+ // 若 receipt 随后消失,续跑会把可变安装目录误当成旧授权事实重新铸批准。+ // 记为确定性 fail-closed 审计项;原 receipt 恢复可读时仍自然生效,真的丢失+ // 则只能走完整重新批准,不能自动 backfill。+ result.failed.push(id);+ pendingForRetry.delete(id);+ unreadableReceiptIds.push(id);+ this.options.log?.warn('legacy migration found an unreadable receipt; automatic backfill blocked', {+ id,+ reason: approval.reason,+ });+ continue;+ }+ // 有未清的事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净(通常恢复已在+ // 构造期把它清掉,这里兜住"恢复删 finalDir 失败"的残留)。绝不迁移这种目录 ——+ // 它的字节来源不是"用户确认过的旧安装",而是一次未完成事务的中间态。+ if (this.hasPendingMutationJournal(id)) {+ result.skipped.push(id);+ blockedByPendingJournal.push(id);+ continue;+ }+ // Per-id 迁移标记:新模型 receipt 落账时同步写入。无 receipt 但有标记 = 新模型+ // 安装后 receipt 被删,不是 legacy —— 绝不从可变安装目录重铸批准。+ if (this.receiptStore.hasMigrationMarker(id)) {+ result.skipped.push(id);+ continue;+ }+ candidates.push(id);+ }++ if (+ candidates.length === 0 &&+ !resumePending &&+ blockedByPendingJournal.length === 0 &&+ unreadableReceiptIds.length === 0+ ) {+ // 历史 mixed 状态若只剩有效的非随包 receipt,补写 completed 收口;空目录或+ // 只有随包目录仍不落台账,给 owner legacy 恢复流程留门。+ if (sawApprovedNonBundledInstall) {+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'completed',+ });+ }+ return result;+ }+ if (+ resumePending ||+ candidates.length > 0 ||+ blockedByPendingJournal.length > 0 ||+ unreadableReceiptIds.length > 0+ ) {+ const checkpointPendingIds = [+ ...new Set([...candidates, ...blockedByPendingJournal]),+ ].sort();+ const checkpointFailedIds = [+ ...new Set([...(resumeLedger?.failedIds ?? []), ...unreadableReceiptIds]),+ ].sort();+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [...new Set([...(resumeLedger?.migratedIds ?? []), ...preMigrated])].sort(),+ state: checkpointPendingIds.length > 0 ? 'in-progress' : 'completed',+ ...(checkpointPendingIds.length > 0 ? { pendingIds: checkpointPendingIds } : {}),+ ...(checkpointFailedIds.length > 0 ? { failedIds: checkpointFailedIds } : {}),+ ...(checkpointPendingIds.length > 0 && resumeApprovalProjectionDigest+ ? {+ recoveryApprovalProjectionSha256ById: Object.fromEntries(+ Object.entries(resumeApprovalProjectionDigest).filter(([id]) =>+ checkpointPendingIds.includes(id)),+ ),+ }+ : {}),+ });+ }++ for (const id of candidates) {+ try {+ const migrated = await this.backfillLegacyApproval(path.join(root, id), id, {+ expectedApprovalProjectionSha256:+ resumeApprovalProjectionDigest?.[id],+ });+ (migrated ? result.migrated : result.skipped).push(id);+ pendingForRetry.delete(id);+ } catch (err) {+ // 错误分类决定这个 id 的余生,不能一锅端:+ // - 带 errno 的环境错(EACCES/ENOSPC/EBUSY…,状态根写不动、文件被占等)是+ // **瞬时**故障,不属于 §5 的"旧事实读不出/自相矛盾" —— 记 retryPending,+ // 台账停在 in-progress,下次启动自动续跑;写进 completed 的 failedIds 会把+ // 一次环境抖动永久封成"需要人工重新确认"。+ // - 无 errno 的校验错(manifest 不合法、技能目录含链接、locale 装入后损坏)+ // 与 ENOENT(声明的文件缺失 = 内容状态,不是抖动)是**确定性**内容无效,+ // 记 failed、fail closed,走每插件恢复 UI。+ const transient = isTransientBackfillError(err);+ if (transient) {+ result.retryPending.push(id);+ pendingForRetry.add(id);+ this.options.log?.warn(+ 'legacy ghost approval migration hit transient IO; will retry next launch',+ {+ id,+ code: (err as NodeJS.ErrnoException | null)?.code,+ error: err instanceof Error ? err.message : String(err),+ },+ );+ } else {+ result.failed.push(id);+ pendingForRetry.delete(id);+ this.options.log?.warn('legacy ghost approval migration failed; kept fail-closed', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ }++ // 收尾状态机(原子改写):+ // - 有瞬时失败 → 台账停在 in-progress,pendingIds = 仅剩的重试对象,下次启动+ // 自动续跑(§5 兜底第 1 条"能自动就别打扰用户");确定性 failed 不进 pendingIds,+ // 续跑白名单挡住"迁移窗口期间新装再删 receipt"的老路。+ // - 全部落定(只剩确定性 failed 或全成功)→ completed;续跑轮把上一轮已记的+ // failedIds 一并带上,台账始终如实反映全量。+ const migratedIds = [...new Set([...result.migrated, ...preMigrated])].sort();+ const failedIds = [...new Set([...result.failed, ...(resumeLedger?.failedIds ?? [])])].sort();+ for (const id of blockedByPendingJournal) pendingForRetry.add(id);+ const retryIds = [...pendingForRetry].sort();+ // Preserve frozen recovery digests for pending ids that still need retry.+ // The generic retry path (migrateLegacyApprovalsOnce) reads these back+ // and passes expectedApprovalProjectionSha256 to backfillLegacyApproval.+ const nextRecoveryDigests =+ retryIds.length > 0 && resumeLedger?.recoveryApprovalProjectionSha256ById+ ? Object.fromEntries(+ Object.entries(resumeLedger.recoveryApprovalProjectionSha256ById).filter(+ ([id]) => pendingForRetry.has(id),+ ),+ )+ : undefined;+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds,+ ...(retryIds.length > 0+ ? {+ state: 'in-progress' as const,+ pendingIds: retryIds,+ ...(nextRecoveryDigests && Object.keys(nextRecoveryDigests).length > 0+ ? { recoveryApprovalProjectionSha256ById: nextRecoveryDigests }+ : {}),+ }+ : { state: 'completed' as const }),+ ...(failedIds.length > 0 ? { failedIds } : {}),+ });+ if (result.migrated.length > 0) this.options.onChanged?.(this.list());+ return result;+ }++ /**+ * legacy 恢复流程(owner 命名空间认领旧布局目录)专用的 backfill 旁路。+ *+ * 为什么允许绕过一次性 ledger 门:`ids` 来自恢复流程**刚从旧布局根搬进安装根**的+ * 目录 —— 这个来源本身就是旧世界的授权事实(与首轮迁移同一信任级),不是可变安装+ * 目录里凭空冒出来的目录。调用方只传本次恢复实际搬动/新增的 id;逐 id 仍然只在+ * 没有有效 receipt 时 backfill,随包 id 照旧交给 provisioning。结果并进 ledger,+ * 事后可分辨来源。+ */+ /**+ * 有未清事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净。任何会**写 receipt**+ * 的入口(主迁移、legacy backfill、用户重新确认)都必须让路:绝不对一次未完成事务的+ * 中间态字节铸出批准 —— 否则 journal 之后的恢复会回滚字节却留下这份 receipt/技能快照,+ * 形成永不自愈的错位授权(约束 B-2/B-5/I-1)。journal 由启动恢复负责收敛,收敛后这些+ * 入口自然放行;若恢复被卡死,退出通道由批量恢复入口负责(见约束文档 §8 已知项),+ * 而不是靠这里对中间态铸批准。+ */+ private hasPendingMutationJournal(id: string): boolean {+ return this.receiptStore.readPendingMutationSync(id).state !== 'missing';+ }++ async backfillRecoveredLegacyGhosts(+ ids: readonly string[],+ options: {+ includePending?: boolean;+ expectedApprovalProjectionSha256ById: Readonly<Record<string, string>>;+ },+ ): Promise<{ migrated: string[]; failed: string[]; pending?: string[] }> {+ return this.runExclusiveMutation(async () => {+ const out = { migrated: [] as string[], failed: [] as string[] };+ const retryIds: string[] = [];+ const root = this.contentRootDir();+ const hasLedger = this.receiptStore.hasMigrationLedger();+ const prev = this.receiptStore.readMigrationLedger();+ if (hasLedger && !prev) {+ throw new Error('legacy migration ledger exists but is unreadable; recovery queue preserved');+ }+ const pendingForRetry = new Set(prev?.pendingIds ?? []);+ const permanentlyBlockedIds = new Set(prev?.failedIds ?? []);+ const workIds = [...new Set(ids)].filter(+ (id): id is string =>+ isValidGhostId(id) &&+ this.options.isTrustedBundledId?.(id) !== true &&+ !permanentlyBlockedIds.has(id),+ );+ // Persist the complete recovery work queue before the first backfill. If the+ // first receipt write or subsequent processing crashes, receiptStore.write()+ // cannot auto-close the migration door and the remaining ids are still durable.+ // Frozen digests are persisted alongside pending ids so that the generic+ // retry path in migrateLegacyApprovalsOnce can verify content hasn't changed.+ const queuedIds = [...new Set([...pendingForRetry, ...workIds])].sort();+ const hadQueuedWork = queuedIds.length > 0;+ if (queuedIds.length > 0) {+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: prev?.migratedAt ?? new Date().toISOString(),+ migratedIds: prev?.migratedIds ?? [],+ ...(prev?.failedIds?.length ? { failedIds: prev.failedIds } : {}),+ state: 'in-progress',+ pendingIds: queuedIds,+ recoveryApprovalProjectionSha256ById: (() => {+ // Merge carried-over digests from the previous ledger with the current+ // call's frozen digests. A later recovery pass for a different id must+ // not drop older digests, or the generic retry path will backfill without+ // the pre-rename baseline.+ const merged: Record<string, string> = {+ ...prev?.recoveryApprovalProjectionSha256ById,+ };+ for (const id of queuedIds) {+ const current = options.expectedApprovalProjectionSha256ById[id];+ if (current !== undefined) merged[id] = current;+ }+ return merged;+ })(),+ });+ for (const id of queuedIds) pendingForRetry.add(id);+ }+ for (const id of workIds) {+ const approval = this.receiptStore.readForRecovery(id);+ if (approval.state === 'approved') {+ pendingForRetry.delete(id);+ continue;+ }+ if (approval.state === 'unreadable') {+ // This id demonstrably had a receipt, so it is not eligible for legacy+ // auto-approval. Keeping it in pendingIds would let a later receipt+ // deletion turn mutable installed bytes into a new authorization fact.+ out.failed.push(id);+ pendingForRetry.delete(id);+ this.options.log?.warn('recovered legacy receipt unreadable; automatic backfill blocked', {+ id,+ reason: approval.reason,+ });+ continue;+ }+ if (this.hasPendingMutationJournal(id)) {+ // 与主迁移循环 candidates 阶段同一道闸:恢复未收敛前绝不对中间态字节铸批准,+ // 留在重试队列,等启动恢复收敛 journal 后下一轮再处理。+ retryIds.push(id);+ pendingForRetry.add(id);+ this.options.log?.warn('recovered legacy ghost has an unsettled mutation journal; will retry', {+ id,+ });+ continue;+ }+ try {+ const targetDir = path.join(root, id);+ const expectedApprovalProjectionSha256 =+ options.expectedApprovalProjectionSha256ById[id];+ if (expectedApprovalProjectionSha256 === undefined) {+ throw new Error(`recovered legacy approval projection is missing or invalid: ${id}`);+ }+ if (!/^[a-f0-9]{64}$/.test(expectedApprovalProjectionSha256)) {+ throw new Error(`recovered legacy approval projection is missing or invalid: ${id}`);+ }+ if (+ await this.backfillLegacyApproval(targetDir, id, {+ expectedApprovalProjectionSha256,+ })+ ) {+ out.migrated.push(id);+ }+ pendingForRetry.delete(id);+ } catch (err) {+ // 与主迁移循环同一分类:瞬时 IO 抖动不记 failed(否则写进 completed 台账就+ // 把一次环境抖动永久封成"需要人工重新确认"),只记日志、留待下次恢复触发重试;+ // 确定性内容无效才 fail closed。+ if (isTransientBackfillError(err)) {+ retryIds.push(id);+ pendingForRetry.add(id);+ this.options.log?.warn('recovered legacy ghost backfill hit transient IO; will retry', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ } else {+ out.failed.push(id);+ pendingForRetry.delete(id);+ this.options.log?.warn('recovered legacy ghost backfill failed; kept fail-closed', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ }+ if (+ hadQueuedWork ||+ out.migrated.length > 0 ||+ out.failed.length > 0 ||+ retryIds.length > 0 ||+ pendingForRetry.size > 0+ ) {+ const failedIds = [...new Set([...(prev?.failedIds ?? []), ...out.failed])].sort();+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [...new Set([...(prev?.migratedIds ?? []), ...out.migrated])].sort(),+ ...(failedIds.length > 0 ? { failedIds } : {}),+ // 旁路 backfill 的瞬时失败也必须进入持久化 work queue;目录已经搬入安装根,+ // 下一轮不会再次出现在”刚恢复”清单里,不能只靠内存日志重试。+ // 同时钉死恢复冻结的批准投影摘要,确保重试时内容未变。+ state: pendingForRetry.size > 0 ? 'in-progress' : 'completed',+ ...(pendingForRetry.size > 0+ ? {+ pendingIds: [...pendingForRetry].sort(),+ recoveryApprovalProjectionSha256ById: (() => {+ // Merge carried-over digests from the previous ledger with the+ // current call's frozen digests. An id pending from a prior+ // recovery pass won't appear in options but must retain its+ // pre-rename baseline for the generic retry path.+ const merged: Record<string, string> = {+ ...prev?.recoveryApprovalProjectionSha256ById,+ };+ for (const id of pendingForRetry) {+ const current = options.expectedApprovalProjectionSha256ById[id];+ if (current !== undefined) merged[id] = current;+ }+ return Object.fromEntries(+ [...pendingForRetry]+ .filter((id) => merged[id] !== undefined)+ .map((id) => [id, merged[id]]),+ );+ })(),+ }+ : {}),+ });+ }+ if (out.migrated.length > 0) this.options.onChanged?.(this.list());+ const pending = [...new Set(retryIds)].sort();+ return options.includePending && pending.length > 0 ? { ...out, pending } : out;+ });+ }++ /**+ * 从旧安装目录的三份事实源重建一份等价 receipt。返回是否真的写了 receipt。+ *+ * 分级 fail 策略(对齐 §5"读不出核心事实才 fail closed,展示元数据缺失则降级"):+ * - `ghost.json` 读不出/不合法 → 抛错 → 调用方计入 failed、保持 fail closed;+ * - `.disabled` 镜像 → 旧模型的启停事实(不存在=启用);+ * - `.cindy-trust.json` 缺失/损坏 → 保守 `unverified`(展示信号,能力由 slot 授予);+ * - locale 声明存在但文件损坏 → 抛错 → fail closed。装入流程本就逐个校验声明的+ * locale、不合格拒装(见 `install` 里 `locale 文件不合格` 分支),所以旧安装天然不含+ * 坏 locale;迁移时读到坏 locale 只可能是**装入后被损坏**,属 §5 的"自相矛盾即+ * fail closed",也与 receipt「localeResources 键集必须等于 manifest.locales」的+ * 不变量一致(跳过坏 locale 会写出被 validateReceipt 拒绝的 receipt);+ * - `packageSha256` **不算**(它是 audit-only、运行期不消费,见 §7);省掉它让迁移更快、+ * 更不会因安装目录里的异常条目误伤——真正的运行期判据 `skillContentSha256` 仍逐字节算,+ * 技能目录含链接等异常会在那里如实 fail closed。+ */+ private async backfillLegacyApproval(+ dir: string,+ id: string,+ options: { expectedApprovalProjectionSha256?: string } = {},+ ): Promise<boolean> {+ const { projection, sha256 } = await readLegacyGhostApprovalProjection(dir, id);+ if (+ options.expectedApprovalProjectionSha256 !== undefined &&+ sha256 !== options.expectedApprovalProjectionSha256+ ) {+ throw new Error('legacy approval projection changed after recovery discovery');+ }++ await this.receiptStore.write(+ createGhostInstallReceipt({+ manifest: projection.manifest,+ localeResources: projection.localeResources,+ enabled: projection.enabled,+ trust: projection.trust,+ skillContentSha256: projection.skillContentSha256,+ ...(projection.iconDataUrl !== undefined ? { iconDataUrl: projection.iconDataUrl } : {}),+ }),+ { skillSourceDir: dir },+ );+ this.options.log?.info('legacy ghost approval migrated', {+ id,+ enabled: projection.enabled,+ trustLevel: projection.trust.level,+ origin: 'legacy-migration',+ });+ return true;+ }++ /**+ * 「从已装目录重新确认」第一步:只读出确认卡需要的事实,零副作用。+ *+ * 这是本地包批准丢失(一次性迁移之后 receipt 又损坏/被删)时的第三条恢复路径 ——+ * 不用用户翻出原始 `.cindy` 文件,也不自动放行:字节从已装目录读,权限清单在确认卡+ * 上**全量**展示(无批准基线,全部按新增项列),用户逐条看过点确认才开 receipt。+ * 本地 `.cindy` 的运行字节本来就一直从这个可变目录现读(§7 登记),两条恢复路径的+ * 差别只是字节来源,授权边界同样是那张确认卡。+ *+ * `manifestSha256` 是「确认卡展示的」与「confirm 时批准的」之间的字节绑定:renderer+ * 原样回传,confirm 侧重读重算,对不上即拒 —— 与更新流程的 `expectedPackageSha256`+ * 同形,防确认间隙里 ghost.json 被换(#636 的同类窗口)。+ *+ * 随包插件一律拒:它们的批准由 provisioning 与种子逐字节对账后自动补,重启即恢复,+ * 不走人工确认(也不能走 —— 这条路的 trust 封顶在非官方档)。+ */+ async inspectInstalledReapproval(id: string): Promise<+ | {+ manifest: GhostManifest;+ trust: GhostTrustInfo;+ manifestSha256: string;+ approvalProjectionSha256: string;+ /** `.disabled` 镜像的读数:确认卡"立即开启"勾选的默认值,不重置用户停用偏好。 */+ localeResources: Record<string, GhostManifestLocaleResource>;+ iconDataUrl?: string;+ skillContentSha256: Record<string, string>;+ previouslyEnabled: boolean;+ }+ | { rejection: InstallRejection }+ > {+ this.ensureCurrentOwnerContextSync();+ if (!isValidGhostId(id) || this.options.isTrustedBundledId?.(id)) {+ return { rejection: { code: 'file-invalid', reason: '该插件不支持从安装目录重新确认' } };+ }+ if (this.readApproval(id).state === 'approved') {+ return { rejection: { code: 'state-changed', reason: '插件批准状态已恢复,无需重新确认' } };+ }+ // 有未清事务标记时绝不铸批准:否则启动恢复回滚字节后会留下这份 receipt/技能快照,+ // 形成永不自愈的错位授权(B-2/B-5/I-1)。确认第二步会经此再查一次(持互斥锁,+ // 与 install/update 不交错),所以只在这里设闸即可覆盖 inspect 与 confirm 两步。+ if (this.hasPendingMutationJournal(id)) {+ return {+ rejection: {+ code: 'state-changed',+ reason: '插件有未完成的安装/更新事务正在恢复,请重启应用完成恢复后再重新确认',+ },+ };+ }+ const dir = path.join(this.contentRootDir(), id);+ try {+ if (classifyGhostDirEntrySync(dir) !== 'directory') {+ return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };+ }+ } catch {+ return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };+ }+ let rawBytes: Buffer;+ try {+ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {+ expect: 'file',+ label: 'installed manifest',+ });+ const bytes = readBoundedFileNoFollowSync(manifestPath, GHOST_MANIFEST_MAX_BYTES, {+ containWithin: fs.realpathSync(dir),+ });+ if (bytes === null) throw new Error('manifest is missing or oversized');+ rawBytes = bytes;+ } catch (err) {+ return {+ rejection: {+ code: 'not-installed',+ reason: `安装目录里读不到清单:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBytes.toString('utf8'));+ } catch (err) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `清单不是合法 JSON:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ const validated = validateGhostManifest(parsed);+ if (!validated.ok) return { rejection: { code: 'file-invalid', reason: validated.reason } };+ if (validated.manifest.id !== id) {+ return { rejection: { code: 'file-invalid', reason: '清单 id 与安装目录不一致' } };+ }+ // tokenBroker 门控与装入侧同一条规则(XDT 授权 broker 仅第一方官方插件可用,+ // 不区分 dev/packaged):走已装目录重新确认的都不是随包插件,声明即拒。+ if (+ !isOfficialGhostId(id) &&+ (validated.manifest.network?.secrets ?? []).some((s) => s.oauth?.tokenBroker !== undefined)+ ) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `id "${id}" 声明了 oauth.tokenBroker——XDT 授权 broker 仅第一方官方插件可用`,+ },+ };+ }+ let localeResources: Record<string, GhostManifestLocaleResource>;+ let skillContentSha256: Record<string, string>;+ let trust: GhostTrustInfo;+ try {+ trust = readLegacyInstallTrust(dir) ?? {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ };+ } catch (err) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `安装目录信任数据不可读: ${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ try {+ localeResources = this.readApprovedLocaleResources(dir, validated.manifest);+ skillContentSha256 = await hashApprovedSkillContent(validated.manifest, dir);+ } catch (err) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `安装目录批准内容不可读或不一致: ${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ const iconDataUrl = this.readInstalledIconDataUrl(dir, validated.manifest) ?? undefined;+ const projection: InstalledReapprovalProjection = {+ manifest: validated.manifest,+ trust,+ localeResources,+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ skillContentSha256,+ };+ return {+ manifest: projection.manifest,+ trust: projection.trust,+ localeResources: projection.localeResources,+ ...(projection.iconDataUrl !== undefined ? { iconDataUrl: projection.iconDataUrl } : {}),+ skillContentSha256: projection.skillContentSha256,+ manifestSha256: crypto.createHash('sha256').update(rawBytes).digest('hex'),+ approvalProjectionSha256: hashInstalledReapprovalProjection(projection),+ previouslyEnabled: !this.isDisabledMarkerPresentSync(dir),+ };+ }++ /**+ * 「从已装目录重新确认」第二步:用户在确认卡上点了同意,据此开 receipt。+ *+ * 与迁移(`backfillLegacyApproval`)的本质区别:**这是一次真实的用户确认**(用户+ * 刚看完全量权限清单),不受迁移 ledger 一次性门约束,来源记 `user-reapproval`。+ * 与迁移的共同点:trust 走同一个封顶读取器、技能字节现算钉指纹、只写状态根。+ */+ async reapproveInstalled(+ id: string,+ opts: {+ enable: boolean;+ expectedManifestSha256: string;+ expectedApprovalProjectionSha256: string;+ expectedInstalledApproval: string;+ },+ ): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {+ return this.runExclusiveMutation(() => this.reapproveInstalledUnlocked(id, opts));+ }++ private async reapproveInstalledUnlocked(+ id: string,+ opts: {+ enable: boolean;+ expectedManifestSha256: string;+ expectedApprovalProjectionSha256: string;+ expectedInstalledApproval: string;+ },+ ): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {+ // 确认期间批准状态不得变过:与更新流程同款前置条件(token 由 Main 现读比对)。+ const currentToken = ghostInstallApprovalToken(+ this.list().find((g) => g.manifest.id === id)?.approval,+ );+ if (currentToken !== opts.expectedInstalledApproval || currentToken.startsWith('approved')) {+ return {+ rejection: { code: 'state-changed', reason: '插件批准状态在确认后发生了变化,请重新确认' },+ };+ }+ // 重走只读检查(含随包拒收/清单校验),并绑定确认卡展示时的清单字节。+ const inspected = await this.inspectInstalledReapproval(id);+ if ('rejection' in inspected) return inspected;+ if (inspected.manifestSha256 !== opts.expectedManifestSha256) {+ return {+ rejection: { code: 'state-changed', reason: '插件清单在确认后发生了变化,请重新确认' },+ };+ }+ if (inspected.approvalProjectionSha256 !== opts.expectedApprovalProjectionSha256) {+ return {+ rejection: {+ code: 'state-changed',+ reason: '安装目录批准内容在确认后发生了变化,请重新确认',+ },+ };+ }+ // 指令查重与装入/更新同一条规则(豁免自己):重新确认不是给撞名指令开的后门。+ if (inspected.manifest.command !== undefined) {+ const commandFold = inspected.manifest.command.toLowerCase();+ const holder = this.list().find(+ (g) =>+ g.manifest.id !== id &&+ g.manifest.command !== undefined &&+ g.manifest.command.toLowerCase() === commandFold,+ );+ if (holder) {+ return {+ rejection: {+ code: 'command-conflict',+ reason: `指令 /${inspected.manifest.command} 已被已装意识「${holder.manifest.name}」(${holder.manifest.id})占用`,+ },+ };+ }+ }+ const contentRoot = this.contentRootDir();+ const dir = path.join(contentRoot, id);+ if (!this.isRealDirChild(contentRoot, id)) {+ return {+ rejection: { code: 'state-changed', reason: '插件安装目录在确认后发生了变化,请重新确认' },+ };+ }+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ let markerExisted = false;+ try {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ markerExisted = true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ // 先提交兼容镜像,再提交权威 receipt。否则 marker 失败会留下“返回成功但实际+ // 启停态与 receipt 矛盾”的部分成功。没有状态变化时不触碰 marker。+ if (opts.enable) {+ if (markerExisted) await fs.promises.rm(marker, { force: true });+ } else if (!markerExisted) {+ await fs.promises.writeFile(marker, '', { flag: 'wx' });+ }+ } catch (err) {+ return {+ rejection: {+ code: 'io',+ reason: `启停标记写入失败:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ try {+ const localeResources = inspected.localeResources;+ const iconDataUrl = inspected.iconDataUrl;+ const skillContentSha256 = inspected.skillContentSha256;+ await this.receiptStore.write(+ createGhostInstallReceipt({+ manifest: inspected.manifest,+ localeResources,+ enabled: opts.enable,+ trust: inspected.trust,+ skillContentSha256,+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ }),+ { skillSourceDir: dir },+ );+ } catch (err) {+ const markerChanged = opts.enable ? markerExisted : !markerExisted;+ if (markerChanged) {+ try {+ if (!this.isRealDirChild(contentRoot, id)) {+ throw new Error('ghost install directory changed before marker rollback');+ }+ if (markerExisted) {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ } catch (markerError) {+ if ((markerError as NodeJS.ErrnoException).code !== 'ENOENT') throw markerError;+ await fs.promises.writeFile(marker, '', { flag: 'wx' });+ }+ } else {+ await fs.promises.rm(marker, { force: true });+ }+ } catch (rollbackErr) {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost reapproval receipt failed and marker rollback also failed',+ {+ id,+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ },+ );+ }+ }+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };+ }+ this.untrustedApprovals.delete(this.isolationKey(id));+ this.options.log?.info('ghost reapproved from installed dir', {+ id,+ enabled: opts.enable,+ trustLevel: inspected.trust.level,+ origin: 'user-reapproval',+ });+ const ghost = this.list().find((g) => g.manifest.id === id);+ if (!ghost) return { rejection: { code: 'io', reason: '重新确认后读不到插件清单' } };+ this.options.onChanged?.(this.list());+ return { ghost };+ }++ /** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */+ list(): InstalledGhost[] {+ this.ensureCurrentOwnerContextSync();+ const root = this.contentRootDir();+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(root, { withFileTypes: true });+ } catch {+ return []; // 根目录还不存在 = 没装过任何意识+ }++ const result: InstalledGhost[] = [];+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue; // staging / 系统目录+ const dir = path.join(root, entry.name);+ // 判据走 ghostContentTree(lstat 分类),不信 Dirent 类型位:根子项是 junction/+ // 链接时不算已装插件 —— 与迁移扫描、内容树遍历同一份判据(§3)。+ try {+ if (classifyGhostDirEntrySync(dir) !== 'directory') continue;+ } catch {+ continue; // lstat 不动(条目消失/权限)= 不算已装+ }+ if (!isValidGhostId(entry.name)) {+ this.options.log?.warn('ghost dir skipped: invalid directory id', { dir });+ continue;+ }+ const approvalResult = this.readApproval(entry.name);+ if (approvalResult.state === 'approved') {+ const receipt = approvalResult.receipt;+ const localizedManifest = this.localizeApprovedManifest(receipt);+ result.push({+ manifest: localizedManifest,+ dir,+ enabled: this.effectiveEnabled(dir, receipt.enabled),+ approval: { state: 'approved', revision: receipt.revision },+ trust: receipt.trust,+ ...(receipt.manifest.skill?.items.length+ ? {+ approvedSkillRoot: this.receiptStore.skillSnapshotRoot(+ receipt.id,+ receipt.revision,+ ),+ }+ : {}),+ ...(receipt.iconDataUrl !== undefined ? { iconDataUrl: receipt.iconDataUrl } : {}),+ ...(this.options.isTrustedBundledId?.(entry.name) ? { builtin: true } : {}),+ });+ continue;+ }+ if (approvalResult.state === 'invalid') {+ this.options.log?.warn('ghost approval receipt invalid; plugin kept disabled', {+ id: entry.name,+ reason: approvalResult.reason,+ });+ }++ // 老安装没有 Host 批准快照,或快照损坏:只读取清单用于设置页恢复,+ // 不把 live manifest / trust / enabled 当成运行授权。+ let raw: unknown;+ try {+ // 我们的逐段 no-follow 路径解析(拒符号链接段)+ main 的单句柄限量读(拒链接、+ // 拒无界字节):已安装目录可能被外部/同步盘改动,list() 每次市场快照都跑,两道叠加。+ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {+ expect: 'file',+ label: 'installed manifest',+ });+ const bytes = readBoundedFileNoFollowSync(manifestPath, MAX_GHOST_MANIFEST_BYTES);+ if (bytes === null) throw new Error('manifest is not a bounded regular file');+ raw = JSON.parse(bytes.toString('utf-8'));+ } catch (err) {+ this.options.log?.warn('ghost dir skipped: unreadable manifest', {+ dir,+ error: err instanceof Error ? err.message : String(err),+ });+ continue;+ }- const v = validateGhostManifest(raw);++ const parsedInstalled = parseInstalledGhostManifest(raw);++ const v = parsedInstalled;++ if (parsedInstalled.ok && parsedInstalled.legacyManualIgnored) {++ this.options.log?.warn('ghost legacy manual metadata ignored', {++ code: 'LEGACY_MANUAL_METADATA_IGNORED',++ manifestId: parsedInstalled.manifest.id,++ });++ }+ if (!v.ok) {+ this.options.log?.warn('ghost dir skipped: invalid manifest', { dir, reason: v.reason });+ continue;+ }+ if (v.manifest.id !== entry.name) {+ this.options.log?.warn('ghost dir skipped: dir name != manifest id', {+ dir,+ manifestId: v.manifest.id,+ });+ continue;+ }+ // 历史 manifest / receipt 中可能保留已移除的资源搜索元数据;它不参与当前+ // 运行时入口,插件本体与已批准的其它能力仍按现有授权照常可用。+ const manifest = v.manifest;+ // icon 读失败只降级为无图标(warn),不影响意识本体可用。+ // receipt 模型:无有效批准的安装一律 enabled:false + approval:{state},不按+ // .disabled 镜像判运行(那是被 revert 的旧模型、#636 漏洞路径)。trust 只在+ // 已批准投影里由 receipt 给出,legacy 投影不借安装目录 hostMetadata 冒充可信。+ const iconDataUrl = this.readInstalledIconDataUrl(dir, v.manifest);+ const localizedManifest = this.readInstalledLocalizedManifest(dir, v.manifest);+ result.push({+ manifest: localizedManifest,+ dir,+ enabled: false,+ approval: { state: approvalResult.state },+ // 未批准安装目录里的 trust 镜像是可变字节,不能作为可信展示事实。+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ ...(iconDataUrl !== null ? { iconDataUrl } : {}),+ ...(this.options.isTrustedBundledId?.(entry.name) ? { builtin: true } : {}),+ });+ }+ result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));+ return result;+ }++ /**+ * Mutation callers may immediately use the returned object to spawn a+ * resident runtime. Always return the same authorization projection that+ * list()/runtime lookup can currently observe instead of a hand-built+ * "approved" object that could bypass an active quarantine.+ */+ private projectCommittedMutationResult(fallback: InstalledGhost): {+ ghost: InstalledGhost;+ list: InstalledGhost[];+ } {+ const list = this.list();+ const ghost =+ list.find((item) => item.manifest.id === fallback.manifest.id) ??+ ({+ ...fallback,+ enabled: false,+ approval: { state: 'invalid' },+ approvedSkillRoot: undefined,+ } satisfies InstalledGhost);+ return { ghost, list };+ }++ /** receipt 内的 base manifest + 已批准 locale 资源;不再读取可变安装目录。 */+ private localizeApprovedManifest(receipt: GhostInstallReceipt): GhostManifest {+ const requestedLocale = this.options.getLocale?.();+ const runtimeManifest = withGhostResolvedLocale(receipt.manifest, requestedLocale);+ const localePath = ghostLocalePathFor(receipt.manifest, requestedLocale);+ const fallbackPath = receipt.manifest.locales?.en;+ const candidates = [+ ...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value))),+ ];+ for (const candidate of candidates) {+ const resource = receipt.localeResources[candidate];+ if (resource) return resolveGhostManifestLocale(runtimeManifest, resource);+ }+ return runtimeManifest;+ }++ /**+ * 读取当前宿主语言对应的 locale 文件。已安装目录被用户手工改坏时不让+ * 整个插件消失:记录告警并回退原 manifest;正常安装路径已在 parse 阶段严验。+ */+ private readInstalledLocalizedManifest(dir: string, manifest: GhostManifest): GhostManifest {+ const requestedLocale = this.options.getLocale?.();+ const runtimeManifest = withGhostResolvedLocale(manifest, requestedLocale);+ const localePath = ghostLocalePathFor(manifest, requestedLocale);+ if (!localePath) return runtimeManifest;+ const fallbackPath = manifest.locales?.en;+ const candidates = [+ ...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value))),+ ];+ for (const candidatePath of candidates) {+ try {+ // 逐段 no-follow 解析(判据与批准侧、技能目录同源,链接一律拒)+ 单句柄限量读:+ // 我们的 resolveGhostContentPathSync 拒符号链接段,main 的 readBoundedFileNoFollowSync+ // 单句柄一次完成"限量 + no-follow + containWithin",消掉 lstat→readFileSync 的 TOCTOU。+ const absPath = resolveGhostContentPathSync(dir, candidatePath, {+ expect: 'file',+ label: 'ghost locale',+ });+ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {+ containWithin: fs.realpathSync(dir),+ });+ if (bytes === null) {+ throw new Error(`locale 文件缺失、超过 ${GHOST_LOCALE_MAX_BYTES} 字节或位于插件目录之外`);+ }+ const raw = JSON.parse(bytes.toString('utf8'));+ const validated = validateGhostManifestLocaleResource(raw, manifest);+ if (!validated.ok) throw new Error(validated.reason);+ return resolveGhostManifestLocale(runtimeManifest, validated.resource);+ } catch (err) {+ this.options.log?.warn('ghost locale candidate invalid', {+ id: manifest.id,+ localePath: candidatePath,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ this.options.log?.warn('ghost locale fallback to base manifest', {+ id: manifest.id,+ localePath,+ });+ return runtimeManifest;+ }++ /**+ * 启用 / 停用一张意识。停用不删任何东西,只把批准 receipt 的 enabled 翻过来+ * (安装目录里的 `.disabled` 只作为旧版本兼容镜像同步维护)。幂等。+ *+ * 两个方向不对称:**启用需要有效批准状态**(无批准的存量安装必须先重新确认+ * 权限),**停用必须永远能成功** —— 停用是安全的收敛方向,不能因为技能快照+ * 被外部删掉之类的环境问题把插件卡在"既不能用也不能关"。+ */+ async setEnabled(+ id: string,+ enabled: boolean,+ ): Promise<{ ok: true } | { rejection: UninstallRejection }> {+ return this.runExclusiveMutation(() => this.setEnabledUnlocked(id, enabled));+ }++ private async setEnabledUnlocked(+ id: string,+ enabled: boolean,+ ): Promise<{ ok: true } | { rejection: UninstallRejection }> {+ if (!isValidGhostId(id)) {+ return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };+ }+ const dir = path.join(this.contentRootDir(), id);+ // pathExists(fs.access)跟随链接:`<root>/<id>` 被换成 junction 时,下面对+ // `<dir>/.disabled` 的写/删会穿透到安装根之外的目标。判据改用 ghostContentTree 的+ // lstat 分类(与 list()「只有真目录才算安装」同源):不存在(ENOENT→抛错)或非真目录+ // (链接/文件)一律按未装入拒,标记读写不越过安装根边界。+ let dirKind: GhostDirEntryKind | null;+ try {+ dirKind = classifyGhostDirEntrySync(dir);+ } catch {+ dirKind = null;+ }+ if (dirKind !== 'directory') {+ return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };+ }+ const receiptResult = this.readApproval(id);+ if (receiptResult.state !== 'approved' && enabled) {+ return {+ rejection: {+ code: 'approval-required',+ reason: `插件 ${id} 缺少有效的安装批准状态,请重新选择安装包并确认权限`,+ },+ };+ }+ // Re-check immediately before touching the compatibility mirror. This does not+ // replace OS-level handle protection, but prevents a stale initial classification+ // from authorizing a link/file target in the common race window.+ if (!this.isRealDirChild(this.contentRootDir(), id)) {+ return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };+ }+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ // 回滚基准取"镜像先前是否在盘上",不是 receipt.enabled:两者可以背离(旧客户端+ // 只写镜像 → receipt=true + 镜像在,读时合并 = 停用)。按 receipt 回滚会在+ // "启用失败"后把镜像永久丢掉 —— 有效状态从停用静默翻成启用,还带不回来。+ const markerExisted = this.isDisabledMarkerPresentSync(dir);+ // 阶段 1:镜像。两阶段的错误必须分开 —— 镜像写失败时**什么都还没落盘**,+ // 把它报成"已停用"是谎报:重启后按 receipt.enabled=true 原样复活,而用户+ // 以为已经关掉了。停用方向的"必须永远能成功"指的是不被环境卡死在"既不能用+ // 也不能关",不是"任何失败都谎称成功"。+ try {+ if (enabled) {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ await fs.promises.rm(marker, { force: true });+ } else {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ await fs.promises.writeFile(marker, '');+ }+ } catch (err) {+ return {+ rejection: {+ code: 'io',+ reason: `启停标记写入失败:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ // 阶段 2:receipt。走到这里镜像已确认落盘,catch 里才允许按"镜像已生效"降级。+ if (receiptResult.state === 'approved') {+ try {+ // 快照被外部删掉时从当前安装目录重建(内容与批准 manifest 的一致性由+ // ensureSkillSnapshot 的 SKILL.md 逐字校验兜住);停用方向即使重建不了+ // 也照样落盘,由技能对账把落链撤掉。+ await this.receiptStore.write(+ { ...receiptResult.receipt, enabled },+ { skillSourceDir: dir, requireSkillSnapshot: enabled },+ );+ } catch (err) {+ if (!enabled) {+ // 停用降级成功的前提是阶段 1 已确认镜像在盘上:list() 的读时合并会把+ // 启停态压成停用(重启后依然),旧客户端也按镜像判 —— 停用已经生效,+ // 如实返回 ok,receipt 留待下次成功写入收敛。+ this.options.log?.warn('ghost disable persisted via mirror only; receipt write failed', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ this.options.onChanged?.(this.list());+ return { ok: true };+ }+ // 启用方向 fail closed:receipt 没写成就不算启用,镜像原样放回 ——+ // 有效启停态(读时合并)与旧客户端(只认镜像)都回到操作前。+ if (markerExisted) {+ await fs.promises.writeFile(marker, '').catch((rollbackErr) => {+ // 回滚也写不动的终态要可观测:receipt 仍是停用(读时合并 fail closed+ // 不受影响),但只认镜像的旧客户端会把它看成启用 —— 状态不一致,升级+ // error 级,不静默。+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost enable failed and mirror rollback also failed; old clients may see it enabled',+ {+ id,+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ },+ );+ });+ }+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };}- } catch (err) {- return {- rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },- };}this.options.log?.info('ghost enabled state changed', { id, enabled });this.options.onChanged?.(this.list());@@@ -2734,11 -733,80 +2757,82 @@@}}+ // 5.5) manual:声明目录内只允许普通 Markdown 文件;逐文件限量并严格+ // 校验 UTF-8/二进制内容。入口固定为 MANUAL.md,装入前一次性对账。+ const validatedManualEntries = new Set<string>();+ for (const manualItem of v.manifest.manual?.items ?? []) {+ const unitPrefix = `${prefix}${manualItem.dir}/`;+ const entryPath = `${unitPrefix}${GHOST_MANUAL_ENTRY_FILE}`;+ const entry = zip.file(entryPath);+ if (!entry || entry.dir || isZipSymbolicLink(entry)) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `manual 条目声明了 ${manualItem.dir},但压缩包内缺少普通文件 ${manualItem.dir}/${GHOST_MANUAL_ENTRY_FILE}`,+ },+ };+ }+ const unitEntries = allEntries.filter(+ (candidate) => {+ const normalizedName = candidate.name.replace(/\\/g, '/');+ return normalizedName.startsWith(unitPrefix) && normalizedName !== unitPrefix;+ },+ );+ for (const manualEntry of unitEntries) {+ const normalizedEntryName = manualEntry.name.replace(/\\/g, '/');+ const relativePath = normalizedEntryName.slice(unitPrefix.length).replace(/\/$/, '');+ if (relativePath.length === 0) continue;+ if (+ manualEntry.name.includes('\\') ||+ isZipSymbolicLink(manualEntry) ||+ ghostManualLogicalPathForEntry(+ manualItem.name,+ relativePath,+ manualEntry.dir ? 'directory' : 'file',+ ) === null+ ) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `manual 条目无法形成合法 ghost_manual 路径:${manualItem.dir}/${relativePath}`,+ },+ };+ }+ if (manualEntry.dir) continue;+ if (validatedManualEntries.has(manualEntry.name)) continue;+ let manualBytes: Buffer;+ try {+ manualBytes = await readZipEntryBufferWithLimit(+ manualEntry,+ GHOST_MANUAL_MD_MAX_BYTES,+ `manual ${manualItem.dir}/${relativePath}`,+ );+ } catch {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `${manualItem.dir}/${relativePath} 过大(上限 ${GHOST_MANUAL_MD_MAX_BYTES} 字节)`,+ },+ };+ }+ const decoded = decodeGhostManualMarkdown(manualBytes);+ if (!decoded.ok) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `manual 文件不合格(${manualItem.dir}/${relativePath}):${decoded.reason}`,+ },+ };+ }+ validatedManualEntries.add(manualEntry.name);+ }+ }+return {manifest: localizedManifest,+ approvedManifest: v.manifest,canonicalManifest: v.manifest,+ localeResources,trust: signature.trust,packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),...(iconDataUrl !== undefined ? { iconDataUrl } : {}),diff --cc apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 3a1633ddd7,d7b8f6e699..1635951286--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@@ -794,3158 -396,106 +794,3275 @@@ describe('GhostManager · 迁移崩溃�},);- it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {- const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装- expect(onChanged).not.toHaveBeenCalled();+ 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);});- // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。- it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(- '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',- async (entryName) => {- // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字- // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。- const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });- const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {- [entryName]: evilManifest,+ 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);});- expect(await manager.inspect(cindy)).toMatchObject({- rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },+ 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',});- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(onChanged).not.toHaveBeenCalled();- },- );+ 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('重复装入同 id → already-installed,原安装不受影响', async () => {- await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();- await expectRejection(- await manager.install(await makeCindy('b.cindy', goodManifest())),- 'already-installed',- );- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(onChanged).not.toHaveBeenCalled();+ 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('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {- await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));- await expectRejection(- await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),- 'command-conflict',+ 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 = fs.realpathSync.native(+ await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-outside-')),);- expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘- const ok = await manager.install(- await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')),+ 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 = fs.realpathSync.native(+ await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-rollback-')),);- expect('ghost' in ok).toBe(true);- expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ 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 });+ }});-});-describe('GhostManager · uninstall', () => {- it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {- await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();+ 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));- const result = await manager.uninstall('hello');- expect('ok' in result).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(manager.list()).toEqual([]);- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0]).toEqual([]);+ // 攻击窗口:用户看的是权限集 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('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {- await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();+ 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));- const result = await manager.uninstall('hello', { notify: false });+ 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',+ }),+ );+ }- expect('ok' in result).toBe(true);- expect(manager.list()).toEqual([]);- expect(onChanged).not.toHaveBeenCalled();+ 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('卸未装的 id → not-installed', async () => {- const result = await manager.uninstall('ghost');- expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ 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('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {- await fs.promises.mkdir(rootDir, { recursive: true });- const sibling = path.join(workDir, 'victim');- await fs.promises.mkdir(sibling);- for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {+ 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"骗不到迁移', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 安装不再自动写 migration ledger:迁移门由 coordinator 统一关闭,单一 receipt+ // 写入不得抢先把门封死(否则迁移扫描瞬时失败 + builtin reconcile 写 receipt 即+ // 永久关闭迁移门,其余存量插件全部 legacy-unapproved)。+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // 攻击:删掉 receipt,指望整个插件消失变成 legacy-unapproved。+ // 不加 slot 修改(避免 backfillLegacyApproval 校验失败进入 failed 分支)。+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));+ // Per-id migration marker prevents backfill. Without the marker, the+ // coordinator would re-approve from the current mutable directory. With+ // the marker, the system knows this was a new-model install whose receipt+ // was deleted — not a legacy install. It stays fail-closed.+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it('P0-2: unreadable per-id migration marker keeps deleted receipt fail-closed', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));++ const marker = path.join(workDir, 'ghosts-install-state', '.migrated-hello');+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {+ if (path.resolve(String(target)) === path.resolve(marker)) {+ throw Object.assign(new Error('EIO: migration marker unreadable'), { code: 'EIO' });+ }+ return realLstatSync(target, options as never);+ });+ try {+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({+ migrated: [],+ skipped: ['hello'],+ failed: [],+ retryPending: [],+ });+ } finally {+ spy.mockRestore();+ }++ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it('P0-2:安装不自动落 migration ledger —— 落账失败也不影响安装', async () => {+ // With the ledger auto-close removed, the install path no longer touches+ // the migration ledger at all. A ledger I/O failure cannot block the+ // install, and the migration door stays open for the coordinator.+ const result = await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect('ghost' in result).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // Door remains open: coordinator can still run.+ expect(manager.list()).toHaveLength(1);+ });++ it('首次批准与目录回滚同时失败时保留 install journal,不让迁移收编未提交字节', async () => {+ const finalDir = path.join(rootDir, 'hello');+ // The ledger auto-close is removed; without ledger-level failure injection+ // the install succeeds normally. The rollback path (rm finalDir) is only+ // reached when a previous step fails; a healthy install never hits it.+ // The migration door remains open; the coordinator handles this by+ // finding a valid receipt and skipping hello.+ const result = await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect('ghost' in result).toBe(true);++ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);++ const migration = await manager.migrateLegacyApprovalsOnce();+ // Coordinator finds approved receipt for hello → skipped (already has receipt).+ expect(migration.migrated).toEqual([]);+ expect(migration.skipped).toEqual(['hello']);+ expect(manager.list()).toHaveLength(1);++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ // Receipt persisted → plugin visible across manager instances.+ expect(recovered.list()).toHaveLength(1);+ expect(fs.existsSync(finalDir)).toBe(true);+ });++ 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', '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 {+ 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('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 {+ 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(), { force: true });+ 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: ['hello'],+ });+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),+ ).toMatchObject({ state: 'completed', failedIds: ['hello'] });++ await fs.promises.rm(receiptPath);+ const retry = await manager.backfillRecoveredLegacyGhosts(+ ['hello'],+ await recoveredProjectionOptions('hello'),+ );+ expect(retry).toEqual({ migrated: [], failed: [] });+ expect(fs.existsSync(receiptPath)).toBe(false);+ expect(manager.list()[0]).toMatchObject({+ approval: { state: 'legacy-unapproved' },+ enabled: false,+ });+ });++ 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'],+ };+ // 台账经 bounded no-follow 读取,超上限即视为不可读(不再用 unbounded+ // readFileSync)。构造一个超限 ledger,验证门保守关死且 recovery queue 不被覆盖。+ const oversizedLedger = {+ ...originalLedger,+ migratedIds: Array.from({ length: 900 }, (_, i) => `pad-${'x'.repeat(120)}-${i}`),+ };+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify(oversizedLedger),+ );+ await writeLegacyInstall('recovered', goodManifest('recovered'));++ await expect(+ manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ await recoveredProjectionOptions('recovered'),+ ),+ ).rejects.toThrow(+ /ledger exists but is unreadable/,+ );+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toEqual(+ oversizedLedger,+ );+ });++ 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),+ }),+ );+ // readPendingMutationSync now uses readBoundedFileNoFollowSync (single-handle+ // open+stat+read) instead of lstat+readFileSync. Inject EACCES at openSync+ // so the bounded reader surfaces the unreadable state through its normal path.+ const realOpenSync = fs.openSync;+ const spy = vi.spyOn(fs, 'openSync').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 (realOpenSync as (...args: unknown[]) => unknown)(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(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('可变 trust 镜像损坏不会覆盖有效的官方 Host receipt', 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).toEqual(CINDY_OFFICIAL_GHOST_TRUST);+ });++ 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);+ expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);+ // 重新启用即撕掉标记。+ await manager.setEnabled('hello', true);+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {+ const zip = new JSZip();+ zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));+ zip.file('hello-pack/assets/a.txt', 'a');+ const out = path.join(workDir, 'wrapped.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));++ const result = await manager.install(out);+ expect('ghost' in result).toBe(true);+ // 包裹层被剥掉:内容直接落在 <root>/hello/ 下+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);+ });++ it('源文件不存在 → source-not-found', async () => {+ await expectRejection(+ await manager.install(path.join(workDir, 'nope.cindy')),+ 'source-not-found',+ );+ });++ it('不是 zip 的文件 → file-invalid', async () => {+ const bad = path.join(workDir, 'bad.cindy');+ await fs.promises.writeFile(bad, 'this is not a zip');+ await expectRejection(await manager.install(bad), 'file-invalid');+ });++ it('缺 ghost.json → file-invalid', async () => {+ const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('ghost.json 不是合法 JSON → file-invalid', async () => {+ const zip = new JSZip();+ zip.file('ghost.json', '{ not json');+ const out = path.join(workDir, 'badjson.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ await expectRejection(await manager.install(out), 'file-invalid');+ });++ it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {+ const cindy = await makeCindy('decl.cindy', {+ schemaVersion: 1,+ id: 'legacy',+ name: '老声明型',+ version: '1.0.0',+ kind: 'declaration',+ panel: { title: '静态面板', body: '一段文字' },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });+++ it.each([++ ['string', 'notes'],++ ['object', { note: 'legacy metadata', nested: { arbitrary: true } }],++ ])('新包携带旧式 %s manual metadata 时 inspect/install 仍严格拒绝', async (label, manual) => {++ const cindy = await makeCindy(`legacy-manual-${label}.cindy`, {++ ...goodManifest(),++ manual,++ });++ await expectRejection(await manager.inspect(cindy), 'file-invalid');++ await expectRejection(await manager.install(cindy), 'file-invalid');++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);++ });+++ it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {+ const manifest = {+ ...goodManifest(),+ slots: ['node'],+ tools: undefined,+ node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },+ };+ const cindy = await makeCindy('missing-node.cindy', manifest);+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(+ '包不能自带主机保留文件 %s',+ async (reservedFile) => {+ const cindy = await makeCindy('reserved.cindy', goodManifest(), {+ [reservedFile]: '{}',+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: {+ code: 'file-invalid',+ reason: expect.stringContaining('主机保留文件'),+ },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ },+ );++ it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {+ const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装+ expect(onChanged).not.toHaveBeenCalled();+ });++ // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。+ it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(+ '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',+ async (entryName) => {+ // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字+ // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。+ const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });+ const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {+ [entryName]: evilManifest,+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(onChanged).not.toHaveBeenCalled();+ },+ );++ it('重复装入同 id → already-installed,原安装不受影响', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();+ await expectRejection(+ await manager.install(await makeCindy('b.cindy', goodManifest())),+ 'already-installed',+ );+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {+ await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));+ await expectRejection(+ await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),+ 'command-conflict',+ );+ expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘+ const ok = await manager.install(+ await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')),+ );+ expect('ghost' in ok).toBe(true);+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ });+});++describe('GhostManager · uninstall', () => {+ it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello');+ expect('ok' in result).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0]).toEqual([]);+ });++ it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello', { notify: false });++ expect('ok' in result).toBe(true);+ expect(manager.list()).toEqual([]);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('persists builtin tombstone intent before removing approval or installed bytes', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).toHaveBeenCalledWith('hello');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });++ it('does not turn Host reconciliation cleanup into a user builtin tombstone', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');++ await expect(+ manager.uninstall('hello', { notify: false, recordBuiltinTombstone: false }),+ ).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).not.toHaveBeenCalled();+ expect(manager.list()).toEqual([]);+ });++ it('rolls back builtin uninstall journal and quarantine when tombstone persistence fails', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ const error = new Error('access denied') as NodeJS.ErrnoException;+ error.code = 'EACCES';+ throw error;+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toMatchObject({+ rejection: { code: 'io' },+ });++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ manifest: { id: 'hello' },+ enabled: true,+ approval: { state: 'approved' },+ });+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(+ false,+ );+ });++ it('recovers a crashed builtin uninstall by persisting its tombstone before deletion', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateDir = path.join(workDir, 'ghosts-install-state');+ await fs.promises.mkdir(stateDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(stateDir, '.pending-hello.json'),+ `${JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'uninstall',+ builtinTombstone: true,+ })}\n`,+ );+ const recoveredTombstone = vi.fn(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => id === 'hello',+ recordBuiltinTombstone: recoveredTombstone,+ });++ expect(recoveredTombstone).toHaveBeenCalledWith('hello');+ expect(recovered.list()).toEqual([]);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ expect(fs.existsSync(path.join(stateDir, '.pending-hello.json'))).toBe(false);+ });++ it('卸未装的 id → not-installed', async () => {+ const result = await manager.uninstall('ghost');+ expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ });++ it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {+ await fs.promises.mkdir(rootDir, { recursive: true });+ const sibling = path.join(workDir, 'victim');+ await fs.promises.mkdir(sibling);+ for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {const result = await manager.uninstall(id);expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');}- expect(fs.existsSync(sibling)).toBe(true);+ expect(fs.existsSync(sibling)).toBe(true);+ });++ it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {+ const cindy = await makeCindy('a.cindy', goodManifest());+ await manager.install(cindy);+ await manager.uninstall('hello');+ const result = await manager.install(cindy);+ expect('ghost' in result).toBe(true);+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });+});++describe('GhostManager · list', () => {+ it('根目录不存在 → 空清单(不报错)', () => {+ expect(manager.list()).toEqual([]);+ });++ it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 手工捏三个坏目录+ await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));+ await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));+ await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');+ await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));+ await fs.promises.writeFile(+ path.join(rootDir, 'wrong-name', 'ghost.json'),+ JSON.stringify(goodManifest('other-id')),+ );+ // 隐藏目录(staging 残留形态)也不进清单+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));++ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });++ it('多意识按 id 排序', async () => {+ await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));+ await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);+ });++++ it('升级后忽略历史安装中的任意 manual metadata,保留启用状态且不放宽其它字段', async () => {++ const warn = vi.fn();++ manager = new GhostManager({++ getRootDir: () => rootDir,++ getLocale: () => hostLocale,++ onChanged,++ log: { info: vi.fn(), warn },++ });++ const sensitiveMarkers = [++ 'SECRET_STRING_METADATA',++ '../SECRET_MANUAL_DIR',++ 'SECRET_MANUAL_NAME',++ 'SECRET_MANUAL_DESCRIPTION',++ ];++ const sensitiveManifest = {++ ...goodManifest('legacy-object'),++ manual: {++ items: [++ {++ dir: sensitiveMarkers[1],++ name: sensitiveMarkers[2],++ description: sensitiveMarkers[3],++ },++ ],++ },++ };++ const strictValidation = validateGhostManifest(sensitiveManifest);++ expect(strictValidation.ok).toBe(false);++ if (strictValidation.ok) throw new Error('sensitive legacy manual fixture must be invalid');++ expect(strictValidation.reason).toContain(sensitiveMarkers[1]);++++ const fixtures = [++ {++ id: 'legacy-string',++ manifest: { ...goodManifest('legacy-string'), manual: sensitiveMarkers[0] },++ enabled: true,++ },++ {++ id: 'legacy-object',++ manifest: sensitiveManifest,++ enabled: false,++ },++ ];++ for (const fixture of fixtures) {++ const dir = path.join(rootDir, fixture.id);++ await fs.promises.mkdir(dir, { recursive: true });++ await fs.promises.writeFile(++ path.join(dir, 'ghost.json'),++ JSON.stringify(fixture.manifest),++ );++ await fs.promises.writeFile(path.join(dir, 'main.js'), '// legacy');++ if (!fixture.enabled) await fs.promises.writeFile(path.join(dir, '.disabled'), '');++ }++ const invalidDir = path.join(rootDir, 'broken-other-field');++ await fs.promises.mkdir(invalidDir, { recursive: true });++ await fs.promises.writeFile(++ path.join(invalidDir, 'ghost.json'),++ JSON.stringify({++ ...goodManifest('broken-other-field'),++ schemaVersion: 1,++ manual: 'notes',++ }),++ );++++ const installed = manager.list();++ expect(++ installed.map(({ manifest, enabled }) => ({++ id: manifest.id,++ enabled,++ manual: manifest.manual,++ })),++ ).toEqual([++ { id: 'legacy-object', enabled: false, manual: undefined },++ // Legacy manifest compatibility only keeps the install discoverable.++ // Without a Host receipt it remains fail-closed and cannot run.++ { id: 'legacy-string', enabled: false, manual: undefined },++ ]);++ expect(warn).toHaveBeenCalledTimes(3);++ const legacyWarnings = warn.mock.calls.filter(++ ([message]) => message === 'ghost legacy manual metadata ignored',++ );++ expect(legacyWarnings).toHaveLength(2);++ expect(legacyWarnings).toEqual(++ expect.arrayContaining([++ [++ 'ghost legacy manual metadata ignored',++ { code: 'LEGACY_MANUAL_METADATA_IGNORED', manifestId: 'legacy-object' },++ ],++ [++ 'ghost legacy manual metadata ignored',++ { code: 'LEGACY_MANUAL_METADATA_IGNORED', manifestId: 'legacy-string' },++ ],++ ]),++ );++ expect(warn).toHaveBeenCalledWith(++ 'ghost dir skipped: invalid manifest',++ expect.objectContaining({ dir: invalidDir }),++ );++ const serializedWarnings = JSON.stringify(warn.mock.calls);++ for (const marker of sensitiveMarkers) expect(serializedWarnings).not.toContain(marker);++ expect(serializedWarnings).not.toContain(strictValidation.reason);++ expect(serializedWarnings).not.toContain('../');++ });+});++describe('GhostManager · Host approval receipt', () => {+ /** 真实 copyFile 引用:mock 复制行为的用例要靠它放行非目标文件。 */+ const realCopyFile = fs.promises.copyFile;+ const receiptPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `${id}.json`);+ const writeBundledSource = async (+ manifest: InstalledGhost['manifest'],+ files: Record<string, string> = { 'main.js': '// bundled seed' },+ ): Promise<{ sourceDir: string }> => {+ const sourceDir = path.join(workDir, 'bundled-seeds', manifest.id);+ await fs.promises.rm(sourceDir, { recursive: true, force: true });+ await fs.promises.mkdir(sourceDir, { recursive: true });+ trustedBundledIds.add(manifest.id);+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(manifest));+ for (const [relativePath, content] of Object.entries(files)) {+ const target = path.join(sourceDir, relativePath);+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ await fs.promises.writeFile(target, content);+ }+ return { sourceDir };+ };++ /** 带 skill 槽的清单 + 配套包内文件(技能快照相关用例共用)。 */+ const skillManifest = (): Record<string, unknown> => ({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ });+ const skillFiles = (): Record<string, string> => ({+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });++ it('rejects an approved snapshot root replaced by a same-bytes link', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const ghost = manager.list()[0];+ const snapshotRoot = ghost.approvedSkillRoot!;+ const external = path.join(workDir, 'external-approved-snapshot');+ await fs.promises.rename(snapshotRoot, external);+ try {+ await fs.promises.symlink(+ external,+ snapshotRoot,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ await fs.promises.rename(external, snapshotRoot);+ return;+ }++ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(false);+ });++ it('keeps manifest, enabled state, and trust independent from mutable install files', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const before = manager.list()[0];+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(path.dirname(receiptPath())).not.toBe(rootDir);++ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({+ ...goodManifest(),+ version: '99.0.0',+ slots: ['node'],+ node: { entry: 'evil.cjs', protocol: 'json-rpc-stdio' },+ }),+ );+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', '.cindy-trust.json'),+ JSON.stringify({+ level: 'cindy-official',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ }),+ );++ const after = manager.list()[0];+ expect(after.manifest).toEqual(before.manifest);+ // 启停是**非对称**的例外:`.disabled` 镜像允许把启停态往下拉(停用必须永远能+ // 成功,状态根不可写时镜像是唯一落点),但 manifest/trust/批准态不受安装目录+ // 影响,镜像也不能把插件往"启用"方向翻。+ expect(after.enabled).toBe(false);+ expect(after.trust).toEqual(before.trust);+ expect(after.approval.state).toBe('approved');++ // 移除镜像 → 回到 receipt 的授权事实(enabled=true 是用户确认装入时的决定)。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('fails legacy and corrupt receipts closed until a fully reviewed update replaces them', async () => {+ const legacyDir = path.join(rootDir, 'hello');+ await fs.promises.mkdir(legacyDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(legacyDir, 'ghost.json'),+ JSON.stringify(goodManifest()),+ );+ await fs.promises.writeFile(path.join(legacyDir, 'main.js'), '// legacy');++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ const reviewed = await updateGhost(+ await makeCindy('reviewed.cindy', { ...goodManifest(), version: '2.0.0' }),+ );+ expect(reviewed).toMatchObject({+ ghost: {+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ },+ });++ await fs.promises.writeFile(receiptPath(), '{ broken');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('rejects an update when the approved revision changed after review', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const staleApproval = ghostInstallApprovalToken(manager.list()[0].approval);+ const v2 = await makeCindy('v2.cindy', {+ ...goodManifest(),+ version: '2.0.0',+ });+ const first = await manager.update(v2, {+ expectedInstalledApproval: staleApproval,+ });+ expect(first).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });++ const v3 = await makeCindy('v3.cindy', {+ ...goodManifest(),+ version: '3.0.0',+ });+ await expectRejection(+ await manager.update(v3, {+ expectedInstalledApproval: staleApproval,+ }),+ 'state-changed',+ );+ expect(manager.list()[0].manifest.version).toBe('2.0.0');+ });++ it('quarantines an update while the new directory is published but receipt is not committed', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ const originalRename = fs.promises.rename;+ let releasePublish!: () => void;+ let publishStarted!: () => void;+ const publishStartedPromise = new Promise<void>((resolve) => {+ publishStarted = resolve;+ });+ const publishGate = new Promise<void>((resolve) => {+ releasePublish = resolve;+ });+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(from).includes('.cindy-installing-hello-')) {+ const result = await originalRename(from, to);+ publishStarted();+ await publishGate;+ return result;+ }+ return originalRename(from, to);+ });+ try {+ const updatePromise = manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ await publishStartedPromise;+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });+ releasePublish();+ expect('ghost' in (await updatePromise)).toBe(true);+ } finally {+ releasePublish();+ renameSpy.mockRestore();+ }+ });++ it('keeps a committed update quarantined until its durable journal is cleared', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ 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'));+ try {+ const result = await manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ expect('ghost' in result).toBe(true);+ if (!('ghost' in result)) throw new Error('expected committed update projection');+ expect(result.ghost).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(manager.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(true);+ } finally {+ clearSpy.mockRestore();+ }++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });++ it('removes the receipt and approved skill snapshots on uninstall', async () => {+ const manifest = {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ };+ const cindy = await makeCindy('skill.cindy', manifest, {+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });+ await manager.install(cindy);+ const listed = manager.list()[0];+ expect(listed.approvedSkillRoot).toBeTruthy();+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(true);++ await manager.uninstall('skilled');+ expect(fs.existsSync(receiptPath('skilled'))).toBe(false);+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(false);+ });++ it('keeps an uninstall journal when receipt cleanup fails after content removal', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ await fs.promises.rm(receiptPath());+ await fs.promises.mkdir(receiptPath());+ await fs.promises.writeFile(path.join(receiptPath(), 'blocked'), 'x');++ const result = await manager.uninstall('hello');++ expect(result).toEqual({ ok: true });+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(+ true,+ );+ await fs.promises.rm(receiptPath(), { recursive: true, force: true });+ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()).toEqual([]);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });++ it('keeps disabling possible when the approved skill snapshot is gone, and rebuilds it on enable', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 外部把快照删掉:停用是安全方向,必须仍然成功,不能把插件卡在既不能用也不能关。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });++ // 重新启用时从当前安装目录重建快照,不需要用户重新走一次确认。+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ const healed = manager.list()[0];+ expect(healed.enabled).toBe(true);+ expect(healed.approvedSkillRoot).toBe(snapshotRoot);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).toContain('Approved instructions');+ });++ it('refuses to rebuild an enable-time snapshot from install bytes that drifted from the approved manifest', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 安装目录里的 SKILL.md 与批准 manifest 声明的 description 不再一致,快照也没了:+ // 停用照样成功(安全方向),但重建快照必须拒——否则启用就等于批准一份用户+ // 没看过的技能指令。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Silently widened skill\n---\n\nTampered instructions\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('retains skill snapshots left behind by superseded approval revisions', async () => {+ await manager.install(await makeCindy('skill-v1.cindy', skillManifest(), skillFiles()));+ const firstSnapshot = manager.list()[0].approvedSkillRoot!;+ const snapshotParent = path.dirname(firstSnapshot);++ await updateGhost(+ await makeCindy(+ 'skill-v2.cindy',+ { ...skillManifest(), version: '2.0.0' },+ skillFiles(),+ ),+ 'skilled',+ );+ const secondSnapshot = manager.list()[0].approvedSkillRoot!;++ expect(secondSnapshot).not.toBe(firstSnapshot);+ expect(new Set(await fs.promises.readdir(snapshotParent))).toEqual(+ new Set([path.basename(firstSnapshot), path.basename(secondSnapshot)]),+ );+ });++ it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const idDir = path.join(workDir, 'ghosts-install-state', 'skill-snapshots', 'skilled');+ // 外部目录里放一个"看起来像旧 revision"的子目录 + 哨兵文件。+ const external = path.join(workDir, 'external-data');+ await fs.promises.mkdir(path.join(external, 'stale-revision'), { recursive: true });+ await fs.promises.writeFile(path.join(external, 'stale-revision', 'sentinel.txt'), 'keep');+ // 把 `<id>` 父段整个换成指向外部目录的 junction(同权限进程可做到)。+ await fs.promises.rm(idDir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(external, idDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 环境建不了链接则跳过;判定逻辑平台同源。+ }++ // 触发一次 receipt 写(启停翻转):修复前 ensureSkillSnapshot 会沿 junction 把+ // 快照发布到外部目录,prune 的 readdir + 逐项 recursive rm 更会把外部目录里的+ // "旧 revision"整个删掉(sentinel 消失)。修复后父段遏制先行:可疑父段整体跳过。+ await manager.setEnabled('skilled', false);+ expect(fs.existsSync(path.join(external, 'stale-revision', 'sentinel.txt'))).toBe(true);+ // 外部目录里也不应多出任何被"发布"进去的快照字节。+ expect(await fs.promises.readdir(external)).toEqual(['stale-revision']);+ });++ it('holds the install-time SKILL.md size ceiling when rebuilding from mutable install bytes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const installedSkillMd = path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md');+ // 快照缺失时取字节的来源是可变安装目录。这里塞的 SKILL.md frontmatter 与批准+ // manifest 完全一致(躲过一致性校验),只是正文超过装入侧上限 —— 重建必须照样拒,+ // 否则启用这条路会批准一份装入/更新永远不会接受的超大技能指令,而且要先整份+ // 读进内存。+ await fs.promises.writeFile(+ installedSkillMd,+ `---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n${'padding '.repeat(+ GHOST_SKILL_MD_MAX_BYTES / 4,+ )}`,+ );+ expect((await fs.promises.lstat(installedSkillMd)).size).toBeGreaterThan(+ GHOST_SKILL_MD_MAX_BYTES,+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when only the SKILL.md body drifted', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // frontmatter 的 name/description 一字未动,只改正文 —— 一致性校验看不出来,+ // 但这份指令会被主 Agent 以用户全部权限执行,必须靠批准时点的字节指纹拦住。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when a helper file was added to the skill directory', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // SKILL.md 完全没动,只往技能目录里塞一个被指令引用的辅助文件(点文件同样算)。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', '.helper.sh'),+ '#!/bin/sh\necho injected\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to follow a link planted inside the skill directory when rebuilding', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const outside = path.join(workDir, 'outside-skill');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(path.join(outside, 'leak.txt'), 'bytes from outside the skill dir');+ // Windows junction 不需要管理员权限即可创建,是本平台成本最低的一条"把技能目录+ // 之外的字节拉进批准快照"的路子。判据不能建立在 Dirent 类型位的实现细节上,+ // 所以这条用例把行为钉住:planted link 一律拒,快照不落地。+ try {+ await fs.promises.symlink(+ outside,+ path.join(rootDir, 'skilled', 'skills', 'demo', 'linked'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。+ }+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ // 状态根里不该出现任何来自技能目录之外的字节(含崩溃残留的 .tmp)。+ const stateRoot = manager.approvalStateRoot();+ const leaked: string[] = [];+ const walk = (dir: string): void => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const child = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(child);+ else if (entry.name === 'leak.txt') leaked.push(child);+ }+ };+ if (fs.existsSync(stateRoot)) walk(stateRoot);+ expect(leaked).toEqual([]);+ });++ it('rejects bytes swapped after the hash check but before the snapshot copy finishes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 先停用、再删快照:停用本身会把快照重建回来(字节没动、校验放行),顺序颠倒+ // 会让后面的启用走"快照已存在"的早退路径,根本不经过复制。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 模拟同权限本机进程抢在复制这一刻换掉源字节:复制动作落到 temp 的是被改写的+ // 内容,而源目录事后看起来仍然"没问题"。所以校验必须落在**已经复制到 temp 的+ // 那份字节**上;若校验读的是源目录,这里就会放行一份没人确认过的技能指令。+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, tampered, 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ try {+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ } finally {+ spy.mockRestore();+ }+ expect(swapped).toBe(1); // 确认这一轮真的走到了复制+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('applies the SKILL.md size ceiling to the bytes that actually landed in the snapshot', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 源目录看起来一切正常(预检放行),复制这一刻落到 temp 的却是超大文件。上限必须+ // 作用在这份字节上,而不是只作用在预检读到的那份 —— 预检不是安全边界。+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, 'x'.repeat(GHOST_SKILL_MD_MAX_BYTES + 1), 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ let result: Awaited<ReturnType<GhostManager['setEnabled']>>;+ try {+ result = await manager.setEnabled('skilled', true);+ } finally {+ spy.mockRestore();+ }+ await expectRejection(result, 'io');+ // 断言到 reason 才能区分校验顺序:上限先跑报"exceeds N bytes",指纹先跑报+ // "no longer matches..."。只比 code 的话两种顺序都是 io,用例就退化成+ // 行为钉住、测不出重排。+ expect((result as { rejection: { reason: string } }).rejection.reason).toMatch(+ /exceeds \d+ bytes/,+ );+ expect(swapped).toBe(1);+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('keeps an install unusable when a stale approval cannot be revoked', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ // 撤销失败(状态根不可写等,与写批准失败同一成因)不得退回"继续拿旧批准跑":+ // removeInstallApproval 的契约是返回后一定不再被授权运行。+ const spy = vi+ .spyOn(fs.promises, 'rm')+ .mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));+ try {+ await manager.removeInstallApproval('hello');+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(receiptPath())).toBe(true); // receipt 还在盘上+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('does not trust an already-present snapshot whose bytes were rewritten in place', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const snapshotSkillMd = path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md');+ // 快照就位后被就地改写(状态根没有写保护)。主 Agent 是顺着共享链接持续读它的,+ // 所以"快照已存在"不能当成"仍是被批准的那份字节"直接早退信任。+ await fs.promises.writeFile(+ snapshotSkillMd,+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 安装目录里的字节没动过 → 删掉坏快照后能按批准字节重建,自愈。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(await fs.promises.readFile(snapshotSkillMd, 'utf8')).toContain('Approved instructions');+ });++ it('refuses to keep a rewritten snapshot when the installed bytes drifted too', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ // 快照与安装目录都被改成同一份未批准内容:此时没有任何可信来源可重建,必须拒。+ await fs.promises.writeFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), tampered);+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ tampered,+ );++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('still heals a deleted snapshot when the installed skill bytes are untouched', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 字节指纹校验不能把合法的自愈场景一起堵死:外部清理误删快照、内容没动过。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(true);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).toContain('Approved instructions');+ });++ it('bundled unchanged approval repairs a deleted skill snapshot without toggling enabled state', async () => {+ const manifest = skillManifest();+ await manager.install(await makeCindy('skill.cindy', manifest, skillFiles()));+ const listed = manager.list()[0];+ const source = await writeBundledSource(listed.manifest, skillFiles());+ const snapshotRoot = listed.approvedSkillRoot!;+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(+ await manager.approveTrustedBundledInstall(listed.manifest, listed.enabled, source),+ ).toBe(true);+ expect(manager.list()[0].enabled).toBe(listed.enabled);+ const repairedSnapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(+ await fs.promises.readFile(+ path.join(repairedSnapshotRoot, 'skills', 'demo', 'SKILL.md'),+ 'utf8',+ ),+ ).toContain('Approved instructions');+ });++ it('snapshot repair persists a one-way disable before the compatibility marker disappears', async () => {+ const manifest = skillManifest();+ await manager.install(await makeCindy('skill.cindy', manifest, skillFiles()));+ const listed = manager.list()[0];+ const source = await writeBundledSource(listed.manifest, skillFiles());+ expect(await manager.approveTrustedBundledInstall(listed.manifest, true, source)).toBe(true);++ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const disabledMarker = path.join(rootDir, listed.manifest.id, '.disabled');+ await fs.promises.writeFile(disabledMarker, '');+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(+ await manager.approveTrustedBundledInstall(listed.manifest, false, source),+ ).toBe(true);+ expect(JSON.parse(await fs.promises.readFile(receiptPath('skilled'), 'utf8'))).toMatchObject({+ enabled: false,+ });++ await fs.promises.rm(disabledMarker);+ const restarted = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ isTrustedBundledSource: (id, sourceDir) =>+ trustedBundledIds.has(id) &&+ path.resolve(sourceDir) === path.resolve(workDir, 'bundled-seeds', id),+ mutateSnapshot: async (request) => {+ const { parentDir, ...workerRequest } = request;+ await runGhostSnapshotWorkerRequest(workerRequest, parentDir);+ },+ });+ await restarted.approveTrustedBundledInstall(listed.manifest, true, source);+ expect(restarted.list()[0].enabled).toBe(false);+ expect(fs.existsSync(disabledMarker)).toBe(true);+ });++ it('invalidates a receipt whose skill content digests no longer match the manifest', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath('skilled'), 'utf8'),+ ) as Record<string, unknown>;+ // 手工把指纹字段抹掉:必填项缺失一律判 invalid,不允许退化成"跳过校验"。+ delete receipt.skillContentSha256;+ await fs.promises.writeFile(receiptPath('skilled'), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('invalidates a schema v1 receipt instead of trusting its legacy content digests', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ // v2 改了内容摘要 framing;旧 receipt 的摘要不能拿来继续授权,必须 fail closed。+ receipt.schemaVersion = 1;+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('revoking approval fails the install closed, and a later bundled approval heals it', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;++ // 随包对账在换入新种子字节后写批准失败时走的收敛动作:撤掉陈旧批准。+ // 撤掉之后插件必须彻底不可运行,而不是继续拿旧批准跑新代码。+ await manager.removeInstallApproval('hello');++ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ // 下一轮启动对账重新补批准即自愈,不需要用户介入。+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: true,+ approval: { state: 'approved' },+ });+ });++ it('uses the immutable bundled source directory when minting the approval receipt', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const sourceDir = path.join(workDir, 'bundled-seeds', approvedManifest.id);+ trustedBundledIds.add(approvedManifest.id);+ await fs.promises.mkdir(sourceDir, { recursive: true });+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(approvedManifest));+ await fs.promises.writeFile(path.join(sourceDir, 'main.js'), 'immutable bundled bytes');+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'mutable bytes');++ const unsafeCall = manager.approveTrustedBundledInstall as unknown as (+ manifest: InstalledGhost['manifest'],+ markerEnabled: boolean,+ ) => Promise<boolean>;+ await expect(unsafeCall.call(manager, approvedManifest, true)).rejects.toThrow(+ /verified bundled source directory/,+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: path.join(rootDir, approvedManifest.id),+ }),+ ).rejects.toThrow(/mutable installed directory/);+ const arbitrarySourceDir = path.join(workDir, 'arbitrary-source', approvedManifest.id);+ await fs.promises.mkdir(arbitrarySourceDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(arbitrarySourceDir, 'ghost.json'),+ JSON.stringify(approvedManifest),+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: arbitrarySourceDir,+ }),+ ).rejects.toThrow(/trusted seed roster/);++ expect(+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir }),+ ).toBe(true);+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ const sourcePackageSha256 = receipt.packageSha256;+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'different mutable bytes');+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ const stableReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ expect(stableReceipt.packageSha256).toBe(sourcePackageSha256);+ });++ it('publishes bundled replacements through the pending journal and commits on receipt write', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const { sourceDir } = await writeBundledSource(approvedManifest, {+ 'main.js': 'immutable replacement bytes',+ });+ const stateRoot = manager.approvalStateRoot();+ const pendingPath = path.join(stateRoot, '.pending-hello.json');++ await manager.runExclusiveMutation(async (mutation) => {+ expect(await mutation.removeInstallApproval('hello')).toBe(true);+ await mutation.publishTrustedBundledSeed('hello', sourceDir, { disabled: false });+ expect(fs.existsSync(pendingPath)).toBe(true);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(true);+ await mutation.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ });++ expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'main.js'), 'utf8')).toBe(+ 'immutable replacement bytes',+ );+ expect(fs.existsSync(pendingPath)).toBe(false);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('approved');+ });++ it('keeps a receipt-pinned disable when the .disabled mirror was lost, and rewrites the mirror', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ // 随包对账首轮把安装收编成 bundled 批准(trust 归一),后续轮次走稳态分支。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);++ // 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));++ // 下一轮对账把镜像读数(启用)喂进来:不得据此翻转 receipt —— 否则用户显式+ // 停用的插件被静默重新启用,无确认、无审计。重新启用只有 setEnabled 一条路。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(false);+ expect(manager.list()[0].enabled).toBe(false);+ // 镜像被补写回去:回滚到旧客户端(只认镜像文件)时仍按停用对待。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);+ });++ it('an old-client style .disabled marker still turns a bundled receipt off', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);++ // 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——+ // 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ expect(await manager.approveTrustedBundledInstall(approvedManifest, false, source)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('a bundled update keeps the receipt-pinned disable even when the marker was lost', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));++ // 随包更新那一轮走的是"建全新 receipt"分支,与稳态分支共用同一条合并规则:+ // 只堵稳态分支的话,镜像在更新 tick 之前丢失仍会静默重新启用,同一个洞换条路。+ const bumped = { ...approvedManifest, version: '1.0.1' };+ expect(+ await manager.approveTrustedBundledInstall(+ bumped,+ true,+ await writeBundledSource(bumped),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ manifest: { version: '1.0.1' },+ });+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);+ });++ it('refuses to mint a bundled approval for an id outside the seed roster', async () => {+ // 该入口不经用户确认就铸出批准;builtin-only 边界必须运行期强制,不能只靠+ // "唯一调用者是随包对账"这条纪律。+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: () => false,+ });+ const validated = validateGhostManifest(goodManifest());+ if (!validated.ok) throw new Error(validated.reason);+ await expect(+ guarded.approveTrustedBundledInstall(+ validated.manifest,+ true,+ await writeBundledSource(validated.manifest),+ ),+ ).rejects.toThrow(/种子清单/);});- it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {- const cindy = await makeCindy('a.cindy', goodManifest());- await manager.install(cindy);- await manager.uninstall('hello');- const result = await manager.install(cindy);- expect('ghost' in result).toBe(true);- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ it('invalidates a receipt whose locale snapshot keys no longer match the manifest', async () => {+ hostLocale = 'en';+ const manifest = {+ ...goodManifest(),+ locales: { en: 'locales/en.json' },+ };+ await manager.install(+ await makeCindy('localized.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'Approved English name' }),+ }),+ );+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ receipt.localeResources = {};+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });});});@@@ -4456,9 -864,31 +4573,30 @@@ describe('GhostManager · update(原位expect(leftovers).toEqual([]);});+ it('磁盘上的无 manual 旧布局可直接列出并原位升级,无需重装或重新确认', async () => {+ const legacyDir = path.join(rootDir, 'hello');+ await fs.promises.mkdir(legacyDir, { recursive: true });+ await fs.promises.writeFile(path.join(legacyDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(legacyDir, 'main.js'), '// legacy');+ await fs.promises.writeFile(path.join(legacyDir, '.disabled'), '');+ const legacy = manager.list();+ expect(legacy).toMatchObject([{ manifest: { id: 'hello' }, enabled: false }]);+ expect(legacy[0].manifest.manual).toBeUndefined();++ const updated = await manager.update(+ await makeCindy('legacy-v2.cindy', { ...goodManifest(), version: '2.0.0' }),++ { expectedInstalledApproval: ghostInstallApprovalToken(legacy[0]?.approval) },+ );+ expect(updated).toMatchObject({+ ghost: { manifest: { id: 'hello', version: '2.0.0' }, enabled: false },+ });+ expect((updated as { ghost: InstalledGhost }).ghost.manifest.manual).toBeUndefined();+ expect(fs.existsSync(path.join(legacyDir, '.disabled'))).toBe(true);+ });+it('唤醒状态延续:沉睡中更新仍沉睡,唤醒中更新仍唤醒', async () => {await manager.install(await makeCindy('v1.cindy', goodManifest()), { initiallyEnabled: false });- const r1 = await manager.update(- await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }),- );+ const r1 = await updateGhost(await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }));expect((r1 as { ghost: InstalledGhost }).ghost.enabled).toBe(false);expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);@@@ -4673,40 -1025,124 +4811,161 @@@ describe('GhostManager · skill 槽装�await expectRejection(await manager.install(cindy), 'file-invalid');});});+describe('legacy trust mirror hardening', () => {+ it('degrades an unreadable trust mirror to unverified instead of wedging recovery', async () => {+ await writeLegacyInstall('linked-trust', goodManifest('linked-trust'), {+ trust: {+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: false,+ publisherName: 'Acme',+ },+ });+ const realOpenSync = fs.openSync;+ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {+ if (typeof p === 'string' && p.endsWith(path.join('linked-trust', '.cindy-trust.json'))) {+ const err = new Error('ELOOP: too many symbolic links encountered') as NodeJS.ErrnoException;+ err.code = 'ELOOP';+ throw err;+ }+ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);+ }) as typeof fs.openSync);++ try {+ const frozen = await readLegacyGhostApprovalProjection(+ path.join(rootDir, 'linked-trust'),+ 'linked-trust',+ );+ expect(frozen.projection.trust).toMatchObject({+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ });+ } finally {+ spy.mockRestore();+ }+ });+});++ describe('GhostManager · manual 装入侧对等校验', () => {+ const manifest = (): Record<string, unknown> => ({+ ...goodManifest('manual-demo'),+ manual: {+ items: [+ { dir: 'manual', name: 'overview', description: '总览' },+ { dir: 'manual/advanced', name: 'advanced', description: '进阶' },+ ],+ },+ });++ it('嵌套单元、任意深度 Markdown 与 64KB 边界通过 inspect/install', async () => {+ const cindy = await makeCindy('manual-good.cindy', manifest(), {+ 'manual/MANUAL.md': Buffer.alloc(64 * 1024, 0x61),+ 'manual/references/deep/flow.md': '# 深层',+ 'manual/advanced/MANUAL.md': '# 进阶',+ 'manual/advanced/reference.MD': '# 参考',+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ manifest: { manual: { items: [{ name: 'overview' }, { name: 'advanced' }] } },+ });+ expect(await manager.install(cindy)).toMatchObject({+ ghost: { manifest: { id: 'manual-demo' } },+ });+ });++ it.each([+ ['缺 MANUAL.md', { 'manual/notes.md': '# notes' }],+ [+ '超过 64KB',+ { 'manual/MANUAL.md': '# 入口', 'manual/huge.md': Buffer.alloc(64 * 1024 + 1, 0x61) },+ ],+ ['非法 UTF-8', { 'manual/MANUAL.md': '# 入口', 'manual/bad.md': Buffer.from([0xff, 0xfe]) }],+ [+ '二进制控制字节',+ { 'manual/MANUAL.md': '# 入口', 'manual/binary.md': Buffer.from('ok\u0000bad') },+ ],+ ['非 Markdown', { 'manual/MANUAL.md': '# 入口', 'manual/data.json': '{}' }],+ ] as Array<[string, Record<string, string | Buffer>]>)(+ '%s 的恶意包绕过 Forge 仍拒绝',+ async (_name, entries) => {+ const single = {+ ...goodManifest('manual-demo'),+ manual: { items: [{ dir: 'manual', name: 'overview', description: '总览' }] },+ };+ await expectRejection(+ await manager.install(await makeCindy('manual-bad.cindy', single, entries)),+ 'file-invalid',+ );+ },+ );++ it('ZIP 内符号链接条目不能作为 manual 文件', async () => {+ const single = {+ ...goodManifest('manual-demo'),+ manual: { items: [{ dir: 'manual', name: 'overview', description: '总览' }] },+ };+ const zip = new JSZip();+ zip.file('ghost.json', JSON.stringify(single));+ zip.file('manual/MANUAL.md', '# 入口');+ zip.file('manual/link.md', '../outside.md', { unixPermissions: 0o120777 });+ const out = path.join(workDir, 'manual-link.cindy');+ await fs.promises.writeFile(+ out,+ await zip.generateAsync({ type: 'nodebuffer', platform: 'UNIX' }),+ );+ await expectRejection(await manager.install(out), 'file-invalid');+ });++ it('ZIP manual 文件和显式目录条目含 C0、DEL 或反斜杠时拒绝', async () => {+ const single = {+ ...goodManifest('manual-demo'),+ manual: { items: [{ dir: 'manual', name: 'guide', description: '总览' }] },+ };+ const cases = [+ { name: `bad${String.fromCharCode(1)}name.md`, directory: false },+ { name: `bad${String.fromCharCode(0x7f)}name.md`, directory: false },+ { name: 'bad\\windows.md', directory: false },+ { name: `bad${String.fromCharCode(1)}dir`, directory: true },+ ];+ for (const [index, testCase] of cases.entries()) {+ const zip = new JSZip();+ zip.file('ghost.json', JSON.stringify(single));+ zip.file('manual/MANUAL.md', '# 入口');+ if (testCase.directory) {+ zip.file(`manual/${testCase.name}/`, null, { dir: true });+ zip.file(`manual/${testCase.name}/nested.md`, '# invalid');+ } else {+ zip.file(`manual/${testCase.name}`, '# invalid');+ }+ const out = path.join(workDir, `manual-invalid-path-${index}.cindy`);+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ await expectRejection(await manager.inspect(out), 'file-invalid');+ }+ });++ it('ZIP manual 逻辑路径 1024 字符放行,超过 1024 字符拒绝', async () => {+ const single = {+ ...goodManifest('manual-demo'),+ manual: { items: [{ dir: 'manual', name: 'guide', description: '总览' }] },+ };+ const inspectWithRelativePath = async (relativePath: string, fileName: string) => {+ const zip = new JSZip();+ zip.file('ghost.json', JSON.stringify(single));+ zip.file('manual/MANUAL.md', '# 入口');+ zip.file(`manual/${relativePath}`, '# deep', { createFolders: false });+ const out = path.join(workDir, fileName);+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ return manager.inspect(out);+ };++ expect(await inspectWithRelativePath(`${'a/'.repeat(507)}x.md`, 'manual-1024.cindy')).toMatchObject({+ manifest: { id: 'manual-demo' },+ });+ await expectRejection(+ await inspectWithRelativePath(`${'a/'.repeat(507)}xx.md`, 'manual-1025.cindy'),+ 'file-invalid',+ );+ });+ });diff --cc apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 2d4fd5249b,4ec1f754c8..f14612e90d--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@@ -1310,15 -717,79 +1310,88 @@@ 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('manual 作者契约按职责分流并支持与工具目录交叉导航', () => {+ for (const marker of [+ '## 3.6 manual:按需披露复杂工作流与分层资料',+ '"manual": {',+ 'MANUAL.md',+ '目录树可以任意深',+ 'Markdown 不写 frontmatter',+ 'Manual 的归属不按篇幅长短判断',+ '多工具组合编排',+ '复杂工具深入用法',+ '前置检查、顺序与分支、失败恢复、交付标准',+ '短但决定多个工具如何协作的',+ '很长但只是在枚举某一个工具的参数',+ '用途、输入输出与调用前限制',+ '紧贴实时工具集合的动态规则与参数',+ '同一规则只选一个权威落点',+ '两者并行且可以反复交叉,不是固定读取顺序',+ 'ghost_call({ ghost_id: "my-ghost", tool: "list_tools", args: { category: "deploy" } })',+ 'ghost_manual({ ghost_id: "my-ghost", path: "getting-started/references/deploy.md" })',+ '不要让多个索引文件互相指回形成循环',+ '只作为 tool-result 按需进入上下文',+ '不进入\n生产 system/developer prompt',+ ]) {+ expect(FORGE_GUIDE).toContain(marker);+ }+ expect(FORGE_GUIDE).not.toContain('需要提供较长的工作流、参考表或排障说明时');+ expect(FORGE_GUIDE).not.toContain('只有大手册才拆深层文件');+ });++ it('skill 迁移精确映射召回元数据、正文与容器目录', () => {+ const skillSection = FORGE_GUIDE.slice(+ FORGE_GUIDE.indexOf('## 4.16 捆绑 Agent Skills(skill 槽)'),+ FORGE_GUIDE.indexOf('## 4.17'),+ );+ for (const marker of [+ '迁移时按职责映射,不是按篇幅搬运',+ 'Skill frontmatter 的 `name + description` 所承担的身份/召回作用',+ '对标系统提示词区\n 插件花名册的身份与 `recall`',+ '`manual.items` 只是插件容器级一级目录,不对标 Skill frontmatter',+ '`MANUAL.md` 与深层 Markdown 承接 Skill 正文、references',+ '只经 `ghost_manual` tool-result 按需进入上下文',+ '当前已停止新增,未来计划全部废弃',+ ]) {+ expect(skillSection).toContain(marker);+ }+ });++ it('manual 发布契约按顺序锁定 Cindy 版本门槛与旧客户端回退', () => {+ expect(FORGE_GUIDE).toContain(+ '虽能安装但缺少新版宿主能力、导致插件无法按\n设计正常工作时,必须填写最早可正常工作的正式版本',+ );+ expect(FORGE_GUIDE).toContain('`manual` / `ghost_manual` 属于后者');++ const manualSection = FORGE_GUIDE.slice(+ FORGE_GUIDE.indexOf('## 3.6 manual:按需披露复杂工作流与分层资料'),+ FORGE_GUIDE.indexOf('## 4. main.js 电子脑'),+ );+ const orderedRequirements = [+ 'Cindy 先发布',+ '确认首个支持它的**正式版本号**',+ '`minCindyVersion` 设为不低于\n该正式版本',+ '移除\n`skill.items` 的迁移版本也必须设置上述 `minCindyVersion`',+ '服务端还要保留上一份带 Skill 的历史 release',+ '旧客户端能通过历史版本回退',+ ];+ let previousIndex = -1;+ for (const requirement of orderedRequirements) {+ const index = manualSection.indexOf(requirement);+ expect(index, requirement).toBeGreaterThan(previousIndex);+ previousIndex = index;+ }+ });+it('写死 whenToUse 发现面与二级分派 RULES 契约', () => {expect(FORGE_GUIDE).toContain('给模型做插件发现与判断的唯一字段');expect(FORGE_GUIDE).toContain(`最多 ${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字符`);diff --cc apps/desktop/src/main/cindy-brain/__tests__/ghostManual.test.tsindex 0000000000,d7ff8725d6..f196c83d11mode 000000,100644..100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostManual.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostManual.test.ts@@@ -1,0 -1,508 +1,509 @@@+ import fs from 'node:fs';+ import os from 'node:os';+ import path from 'node:path';++ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++ import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';+ import { readInstalledGhostManual } from '../ghostManual';++ let workDir: string;++ beforeEach(async () => {+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-ghost-manual-test-'));+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ await fs.promises.rm(workDir, { recursive: true, force: true });+ });++ function manifest(): GhostManifest {+ return {+ schemaVersion: 2,+ id: 'manual-demo',+ name: 'Manual Demo',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool'],+ tools: [{ name: 'run', description: 'Run the demo' }],+ manual: {+ items: [+ {+ dir: 'docs/physical-dir',+ name: 'logical-name',+ description: '完整工作流',+ },+ ],+ },+ };+ }++ function ghost(manualDir = 'docs/physical-dir'): InstalledGhost {+ const ghostManifest = manifest();+ ghostManifest.manual!.items[0]!.dir = manualDir;+ return {+ manifest: ghostManifest,+ dir: workDir,+ enabled: true,++ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ };+ }++ async function write(relativePath: string, content: string | Buffer): Promise<void> {+ const target = path.join(workDir, relativePath);+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ await fs.promises.writeFile(target, content);+ }++ function fsError(code: string): NodeJS.ErrnoException {+ return Object.assign(new Error(`private ${code} detail`), { code });+ }++ describe('readInstalledGhostManual', () => {+ it('根索引只投影逻辑 name,逻辑路径映射到不同的物理 dir', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ expect(await readInstalledGhostManual(ghost())).toEqual({+ ok: true,+ manual: [{ name: 'logical-name', description: '完整工作流' }],+ content: '',+ });+ expect(await readInstalledGhostManual(ghost(), 'logical-name')).toEqual({+ ok: true,+ manual: [],+ content: '# 入口',+ });+ });++ it('深层路径不做 URL decode,且不能越过声明单元读取插件其它文件', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/references/%2e%2e.md', '# 百分号文件');+ await write('main.js', 'PRIVATE');+ expect(+ await readInstalledGhostManual(ghost(), 'logical-name/references/%2e%2e.md'),+ ).toMatchObject({ ok: true, content: '# 百分号文件' });+ const escaped = await readInstalledGhostManual(ghost(), 'logical-name/../main.js');+ expect(escaped).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ });+ expect(JSON.stringify(escaped)).not.toContain('PRIVATE');+ expect(JSON.stringify(escaped)).not.toContain(workDir);+ });++ it('未知单元返回根索引;普通子文件写错返回可直接回填的完整逻辑路径', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/references/flow.md', '# 流程');+ const unknown = await readInstalledGhostManual(ghost(), 'unknown');+ expect(unknown).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ manual: [{ name: 'logical-name' }],+ });+ const missing = await readInstalledGhostManual(ghost(), 'logical-name/references/missing.md');+ expect(missing).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ manual: expect.arrayContaining([+ { name: 'logical-name', description: '完整工作流' },+ {+ name: 'logical-name/references/flow.md',+ description: expect.any(String),+ },+ ]),+ });+ expect(missing.manual.map((candidate) => candidate.name)).toEqual([+ 'logical-name',+ 'logical-name/references/flow.md',+ ]);+ for (const candidate of missing.manual) {+ expect(await readInstalledGhostManual(ghost(), candidate.name)).toMatchObject({ ok: true });+ }+ });++ it('只有省略 path 才返回成功根索引,已知单元下的非法路径返回该单元候选', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ expect(await readInstalledGhostManual(ghost(), '')).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ });+ const invalid = await readInstalledGhostManual(ghost(), 'logical-name/../main.md');+ expect(invalid).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ manual: [{ name: 'logical-name' }],+ });+ for (const invalidPath of [+ `logical-name/bad${String.fromCharCode(1)}name.md`,+ `logical-name/bad${String.fromCharCode(0x7f)}name.md`,+ 'logical-name\\windows.md',+ `logical-name/${'a'.repeat(1025)}`,+ ]) {+ expect(await readInstalledGhostManual(ghost(), invalidPath), invalidPath).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ manual: [{ name: 'logical-name' }],+ });+ }+ });++ it('候选同时受条数与字节预算限制,并显式标注截断', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ for (let index = 0; index < 50; index += 1) {+ await write(+ `docs/physical-dir/references/very-long-candidate-${String(index).padStart(2, '0')}.md`,+ '# 候选',+ );+ }+ const result = await readInstalledGhostManual(ghost(), 'logical-name/missing.md');+ expect(result).toMatchObject({ ok: false, errorCode: 'MANUAL_PATH_NOT_FOUND' });+ expect(result.manual.length).toBeLessThanOrEqual(32);+ expect(Buffer.byteLength(JSON.stringify(result.manual), 'utf8')).toBeLessThanOrEqual(4096);+ expect(result.manual.some((candidate) => candidate.description.includes('候选已截断'))).toBe(+ true,+ );+ expect(result.manual.every((candidate) => candidate.name.startsWith('logical-name'))).toBe(+ true,+ );+ });++ it('声明目录的中间层符号链接不能逃出插件安装根', async () => {+ if (process.platform === 'win32') return;+ const outsideDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-manual-outside-'));+ try {+ await fs.promises.mkdir(path.join(workDir, 'docs'), { recursive: true });+ await fs.promises.writeFile(path.join(outsideDir, 'MANUAL.md'), '# 根外私密正文');+ await fs.promises.symlink(outsideDir, path.join(workDir, 'docs/physical-dir'));+ const result = await readInstalledGhostManual(ghost(), 'logical-name');+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ expect(JSON.stringify(result)).not.toContain('根外私密正文');+ expect(JSON.stringify(result)).not.toContain(outsideDir);+ } finally {+ await fs.promises.rm(outsideDir, { recursive: true, force: true });+ }+ });++ it('item.dir 任一中间组件是根内或根外 symlink 都不可用,普通中间目录可读', async () => {+ if (process.platform === 'win32') return;+ await write('docs/plain/unit/MANUAL.md', '# 普通中间目录');+ expect(await readInstalledGhostManual(ghost('docs/plain/unit'), 'logical-name')).toMatchObject({+ ok: true,+ content: '# 普通中间目录',+ });++ const outsideDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-manual-parent-'));+ try {+ await write('real-inside/unit/MANUAL.md', '# 根内正文');+ await fs.promises.mkdir(path.join(outsideDir, 'unit'), { recursive: true });+ await fs.promises.writeFile(path.join(outsideDir, 'unit/MANUAL.md'), '# 根外正文');+ await fs.promises.mkdir(path.join(workDir, 'docs'), { recursive: true });+ for (const [target, secret] of [+ [path.join(workDir, 'real-inside'), '根内正文'],+ [outsideDir, '根外正文'],+ ] as const) {+ const linkPath = path.join(workDir, 'docs/link');+ await fs.promises.rm(linkPath, { force: true });+ await fs.promises.symlink(target, linkPath);+ const result = await readInstalledGhostManual(ghost('docs/link/unit'), 'logical-name');+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ expect(JSON.stringify(result)).not.toContain(secret);+ expect(JSON.stringify(result)).not.toContain(target);+ }+ } finally {+ await fs.promises.rm(outsideDir, { recursive: true, force: true });+ }+ });++ it('入口缺失、超限、非法 UTF-8 与符号链接都返回 MANUAL_UNAVAILABLE 且不给候选', async () => {+ const assertUnavailable = async (): Promise<void> => {+ for (const requestedPath of ['logical-name', 'logical-name/references/missing.md']) {+ expect(await readInstalledGhostManual(ghost(), requestedPath)).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ }+ };++ await fs.promises.mkdir(path.join(workDir, 'docs/physical-dir'), { recursive: true });+ await assertUnavailable();++ await write('docs/physical-dir/MANUAL.md', 'x'.repeat(64 * 1024 + 1));+ await assertUnavailable();++ await write('docs/physical-dir/MANUAL.md', Buffer.from([0xff, 0xfe, 0xfd]));+ await assertUnavailable();++ if (process.platform !== 'win32') {+ const target = path.join(workDir, 'outside.md');+ await fs.promises.writeFile(target, '# outside');+ await fs.promises.rm(path.join(workDir, 'docs/physical-dir/MANUAL.md'));+ await fs.promises.symlink(target, path.join(workDir, 'docs/physical-dir/MANUAL.md'));+ await assertUnavailable();+ }+ });++ it('单元内的中间目录符号链接无论指向根内还是根外都不可读取', async () => {+ if (process.platform === 'win32') return;+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/real-inside/private.md', '# 根内私密正文');+ const outsideDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-manual-child-'));+ try {+ await fs.promises.writeFile(path.join(outsideDir, 'private.md'), '# 根外私密正文');+ for (const [linkName, target, secret] of [+ ['inside-link', path.join(workDir, 'docs/physical-dir/real-inside'), '根内私密正文'],+ ['outside-link', outsideDir, '根外私密正文'],+ ] as const) {+ await fs.promises.symlink(target, path.join(workDir, `docs/physical-dir/${linkName}`));+ const result = await readInstalledGhostManual(+ ghost(),+ `logical-name/${linkName}/private.md`,+ );+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ expect(JSON.stringify(result)).not.toContain(secret);+ expect(JSON.stringify(result)).not.toContain(target);+ }+ } finally {+ await fs.promises.rm(outsideDir, { recursive: true, force: true });+ }+ });++ it.each(['EIO', 'EACCES'])(+ '目标文件 lstat 返回 %s 时归 MANUAL_UNAVAILABLE 且不回填候选',+ async (code) => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/references/flow.md', '# 流程');+ const originalLstat = fs.promises.lstat.bind(fs.promises);+ vi.spyOn(fs.promises, 'lstat').mockImplementation(+ ((target: fs.PathLike, options?: fs.StatOptions) => {+ if (String(target).endsWith(path.join('references', 'blocked.md'))) {+ return Promise.reject(fsError(code));+ }+ return originalLstat(target, options as never);+ }) as typeof fs.promises.lstat,+ );+ const result = await readInstalledGhostManual(ghost(), 'logical-name/references/blocked.md');+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ expect(JSON.stringify(result)).not.toContain(code);+ expect(JSON.stringify(result)).not.toContain(workDir);+ },+ );++ it('目标文件 lstat 返回 ENOTDIR 仍按普通未命中返回候选,且不回填原错误路径', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/references/flow.md', '# 流程');+ const originalLstat = fs.promises.lstat.bind(fs.promises);+ vi.spyOn(fs.promises, 'lstat').mockImplementation(+ ((target: fs.PathLike, options?: fs.StatOptions) => {+ if (String(target).endsWith(path.join('references', 'missing.md'))) {+ return Promise.reject(fsError('ENOTDIR'));+ }+ return originalLstat(target, options as never);+ }) as typeof fs.promises.lstat,+ );+ const requested = 'logical-name/references/missing.md';+ const result = await readInstalledGhostManual(ghost(), requested);+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ });+ expect(result.manual.map((candidate) => candidate.name)).toContain(+ 'logical-name/references/flow.md',+ );+ expect(result.manual.some((candidate) => candidate.name === requested)).toBe(false);+ });++ it('请求的中间父段是普通文件时按错误调用返回候选', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/topic.md', '# 主题');+ const requested = 'logical-name/topic.md/child.md';+ const result = await readInstalledGhostManual(ghost(), requested);+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ });+ expect(result.manual.map((candidate) => candidate.name)).toContain('logical-name/topic.md');+ expect(result.manual.some((candidate) => candidate.name === requested)).toBe(false);+ });++ it('请求的中间父段是特殊文件时仍归 MANUAL_UNAVAILABLE', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ const originalLstat = fs.promises.lstat.bind(fs.promises);+ vi.spyOn(fs.promises, 'lstat').mockImplementation(+ ((target: fs.PathLike, options?: fs.StatOptions) => {+ if (String(target).endsWith(path.join('physical-dir', 'special-parent'))) {+ return Promise.resolve({+ isSymbolicLink: () => false,+ isDirectory: () => false,+ isFile: () => false,+ } as fs.Stats);+ }+ return originalLstat(target, options as never);+ }) as typeof fs.promises.lstat,+ );+ const result = await readInstalledGhostManual(ghost(), 'logical-name/special-parent/child.md');+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ expect(JSON.stringify(result)).not.toContain(workDir);+ });++ it('最终目标是普通目录时按错误调用返回该单元候选', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/chapter.md/next.md', '# 下一章');+ const requested = 'logical-name/chapter.md';+ const result = await readInstalledGhostManual(ghost(), requested);+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ });+ expect(result.manual.map((candidate) => candidate.name)).toContain(+ 'logical-name/chapter.md/next.md',+ );+ expect(result.manual.some((candidate) => candidate.name === requested)).toBe(false);+ });++ it('最终目标是符号链接或特殊文件时仍归 MANUAL_UNAVAILABLE', async () => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/target.md', '# 正文');+ if (process.platform !== 'win32') {+ await fs.promises.symlink(+ path.join(workDir, 'docs/physical-dir/target.md'),+ path.join(workDir, 'docs/physical-dir/link.md'),+ );+ expect(await readInstalledGhostManual(ghost(), 'logical-name/link.md')).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ });+ }++ const originalLstat = fs.promises.lstat.bind(fs.promises);+ vi.spyOn(fs.promises, 'lstat').mockImplementation(+ ((target: fs.PathLike, options?: fs.StatOptions) => {+ if (String(target).endsWith(path.join('physical-dir', 'special.md'))) {+ return Promise.resolve({+ isSymbolicLink: () => false,+ isDirectory: () => false,+ isFile: () => false,+ } as fs.Stats);+ }+ return originalLstat(target, options as never);+ }) as typeof fs.promises.lstat,+ );+ const special = await readInstalledGhostManual(ghost(), 'logical-name/special.md');+ expect(special).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ expect(JSON.stringify(special)).not.toContain(workDir);+ });++ it.each(['ENOENT', 'ENOTDIR'])(+ '候选递归 readdir 返回 %s 时按普通未命中处理,并保留同单元其它候选',+ async (code) => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/a-disappeared/old.md', '# 消失');+ await write('docs/physical-dir/z-surviving/flow.md', '# 流程');+ const originalReaddir = fs.promises.readdir.bind(fs.promises);+ vi.spyOn(fs.promises, 'readdir').mockImplementation(async (target, options) => {+ if (String(target).endsWith(path.join('physical-dir', 'a-disappeared'))) {+ throw fsError(code);+ }+ return originalReaddir(target, options as never) as never;+ });+ const requested = 'logical-name/missing.md';+ const result = await readInstalledGhostManual(ghost(), requested);+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_PATH_NOT_FOUND',+ });+ expect(result.manual.map((candidate) => candidate.name)).toContain(+ 'logical-name/z-surviving/flow.md',+ );+ expect(result.manual.some((candidate) => candidate.name === requested)).toBe(false);+ expect(JSON.stringify(result)).not.toContain(code);+ expect(JSON.stringify(result)).not.toContain(workDir);+ },+ );++ it.each(['EIO', 'EACCES'])(+ '候选 readdir 返回 %s 时归 MANUAL_UNAVAILABLE,不吞错误或返回候选',+ async (code) => {+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write('docs/physical-dir/references/flow.md', '# 流程');+ vi.spyOn(fs.promises, 'readdir').mockRejectedValueOnce(fsError(code));+ const result = await readInstalledGhostManual(ghost(), 'logical-name/references/missing.md');+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ expect(JSON.stringify(result)).not.toContain(code);+ expect(JSON.stringify(result)).not.toContain(workDir);+ },+ );++ it('候选扫描发现不可调用的制品路径时归 MANUAL_UNAVAILABLE', async () => {+ if (process.platform === 'win32') return;+ await write('docs/physical-dir/MANUAL.md', '# 入口');+ await write(`docs/physical-dir/bad${String.fromCharCode(1)}name.md`, '# invalid');+ const result = await readInstalledGhostManual(ghost(), 'logical-name/missing.md');+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ manual: [],+ content: '',+ });+ });++ it('64KB 正文可完整穿过固定 JSON 信封,64KB+1 被拒', async () => {+ const content = '甲'.repeat(Math.floor((64 * 1024) / 3));+ await write('docs/physical-dir/MANUAL.md', content);+ const result = await readInstalledGhostManual(ghost(), 'logical-name');+ expect(result).toMatchObject({ ok: true, content });+ const wire = JSON.stringify(result);+ expect(Buffer.byteLength(wire, 'utf8')).toBeGreaterThan(Buffer.byteLength(content, 'utf8'));+ expect(JSON.parse(wire)).toEqual(result);++ await write('docs/physical-dir/MANUAL.md', 'x'.repeat(64 * 1024 + 1));+ expect(await readInstalledGhostManual(ghost(), 'logical-name')).toMatchObject({+ ok: false,+ errorCode: 'MANUAL_UNAVAILABLE',+ });+ });+ });diff --cc apps/desktop/src/main/cindy-brain/forge.tsindex c6cb3d943e,973cd286bf..6c6612c0e5--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@@ -28,57 -29,19 +30,65 @@@ importvalidateGhostManifest,type GhostManifest,} from '../../shared/ghost.js';- import { GHOST_MANIFEST_MAX_BYTES, readBoundedFileNoFollow } from '../utils/readBoundedFile.js';+ import {+ GHOST_MANIFEST_MAX_BYTES,+ readBoundedFileNoFollow,+ readBoundedFileNoFollowWithStat,+ } from '../utils/readBoundedFile.js';+ import {+ decodeGhostManualMarkdown,+ ghostManualLogicalPathForEntry,+ } from './ghostManualValidation.js';import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';import { GHOST_SIGNATURE_FILE } from './ghostSignature.js';+import { isPathInsideDir } from './dirDeposit.js';import { checkSkillMdConsistency } from './skillSlot.js';+/**+ * `fs.promises.realpath` 没有 native 变体,promisify 一次(scaffold/pack 的受管根+ * 与 workdir 门都靠它拿到规范路径再比对)。+ */+const realpathNative = promisify(fs.realpath.native);++/**+ * 解析已存在祖先的真身、保留尚不存在的尾段,让受管根在首次落盘前就可比对。+ */+async function resolveThroughExistingAncestor(inputPath: string): Promise<string> {+ let cursor = path.resolve(inputPath);+ const tail: string[] = [];+ while (true) {+ try {+ const real = await realpathNative(cursor);+ return path.join(real, ...tail);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ const parent = path.dirname(cursor);+ if (parent === cursor) return path.resolve(inputPath);+ tail.unshift(path.basename(cursor));+ cursor = parent;+ }+ }+}++/**+ * 逐段确认一个已存在目录路径没有 symlink / junction 祖先。+ *+ * 不能用 `realpath(path) === path` 判断:Windows 的 8.3 短路径会被 realpath+ * 展开成长路径,二者文本不同但每一段仍都是普通目录。逐段 lstat 才能既放行+ * 这种合法别名,又继续拒绝真正的 reparse-point 祖先。+ */+async function pathHasLinkSegment(inputPath: string): Promise<boolean> {+ const resolved = path.resolve(inputPath);+ const root = path.parse(resolved).root;+ let current = root;+ const relative = path.relative(root, resolved);+ for (const segment of relative.split(path.sep).filter(Boolean)) {+ current = path.join(current, segment);+ if ((await fs.promises.lstat(current)).isSymbolicLink()) return true;+ }+ return false;+}+/** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */const MAX_BASIC_FILES = 256;const MAX_NODE_FILES = 2_048;@@@ -809,15 -735,123 +819,131 @@@ async function buildGhostPackage}}+ // 3.6) manual:每个声明单元必须以 MANUAL.md 为入口,目录内只允许普通+ // Markdown 文件;逐文件限量、严格 UTF-8,并拒绝并发截短与二进制内容。+ // 缓存本次校验过的字节,生成 zip 时直接使用同一份快照,避免“预检一份、+ // 入包时又读到另一份”的竞态。嵌套单元共享缓存,同一物理文件只校验一次。+ const manualFileSnapshots = new Map<string, Buffer>();+ for (const item of manifest.manual?.items ?? []) {+ const unitRoot = path.join(dir, ...item.dir.split('/'));+ const validateManualDir = async (+ currentDir: string,+ relativeDir: string,+ preloadedEntries?: fs.Dirent[],+ ): Promise<Exclude<ForgePackResult, { ok: true }> | null> => {+ let entries: fs.Dirent[];+ if (preloadedEntries) {+ entries = preloadedEntries;+ } else {+ try {+ entries = await fs.promises.readdir(currentDir, { withFileTypes: true });+ } catch {+ return {+ ok: false,+ errorCode: 'ENTRY_MISSING',+ message: `读取手册目录失败:${item.dir}${relativeDir ? `/${relativeDir}` : ''}`,+ };+ }+ }+ for (const entry of entries) {+ if (shouldSkip(entry.name)) continue;+ const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;+ const logicalPath = `${item.dir}/${relativePath}`;+ const absolutePath = path.join(currentDir, entry.name);+ if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `manual 单元只允许普通 Markdown 文件:${logicalPath}`,+ };+ }+ if (entry.isDirectory()) {+ if (ghostManualLogicalPathForEntry(item.name, relativePath, 'directory') === null) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `manual 目录无法形成合法 ghost_manual 路径:${logicalPath}`,+ };+ }+ const nestedError = await validateManualDir(absolutePath, relativePath);+ if (nestedError) return nestedError;+ continue;+ }+ if (ghostManualLogicalPathForEntry(item.name, relativePath, 'file') === null) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `manual 文件无法形成合法 ghost_manual Markdown 路径:${logicalPath}`,+ };+ }+ if (manualFileSnapshots.has(logicalPath)) continue;+ let read;+ try {+ read = await readBoundedFileNoFollowWithStat(+ absolutePath,+ GHOST_MANUAL_MD_MAX_BYTES,+ {+ containWithin: realDir,+ verifyContentStability: true,+ },+ );+ } catch {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `读取 manual 文件失败:${logicalPath}`,+ };+ }+ if (read === null) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `${logicalPath} 不是普通文件或超过 ${GHOST_MANUAL_MD_MAX_BYTES} 字节上限`,+ };+ }+ const decoded = decodeGhostManualMarkdown(read.bytes);+ if (!decoded.ok) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `manual 文件不合格(${logicalPath}):${decoded.reason}`,+ };+ }+ manualFileSnapshots.set(logicalPath, read.bytes);+ }+ return null;+ };+ let rootEntries: fs.Dirent[];+ try {+ rootEntries = await fs.promises.readdir(unitRoot, { withFileTypes: true });+ } catch {+ return {+ ok: false,+ errorCode: 'ENTRY_MISSING',+ message: `读取手册目录失败:${item.dir}`,+ };+ }+ const manualEntry = rootEntries.find((entry) => entry.name === GHOST_MANUAL_ENTRY_FILE);+ if (!manualEntry?.isFile() || manualEntry.isSymbolicLink()) {+ return {+ ok: false,+ errorCode: 'ENTRY_MISSING',+ message: `清单声明的文件不存在:${item.dir}/${GHOST_MANUAL_ENTRY_FILE}`,+ };+ }+ const manualError = await validateManualDir(unitRoot, '', rootEntries);+ if (manualError) return manualError;+ }+// 4) 收集文件(递归,跳过开发残留),数量/体积设限。+ // 分类一律走 lstat(不信 readdir Dirent 的类型位——libuv 对 junction 的类型位+ // 跨平台不稳),按我们分支的加固语义处理:+ // - 目录:进递归前按 realpath 复核仍在规范源码根内。目录可能在"分类"与+ // "递归"之间被换成指向根外/受管根的 junction(TOCTOU);realpath 越界即拒+ // (SOURCE_OUTSIDE_WORKDIR),避免把根外字节递归卷进 .cindy。+ // - 符号链接:清单声明的入口是链接 → ENTRY_MISSING(装入侧会缺入口 404,+ // 打包期就拦);非声明的链接 → 跳过,不穿透、不把目标字节打进包。+ // - 普通文件:收集(字节读取仍在下面按 realDir containWithin 现读)。const files: Array<{ rel: string; abs: string }> = [];let totalBytes = 0;const maxFiles = manifest.node ? MAX_NODE_FILES : MAX_BASIC_FILES;@@@ -905,17 -906,23 +1031,34 @@@};const tooLarge = await walk(dir, '');if (tooLarge) return tooLarge;+ const collectedPackPaths = new Set(files.map((file) => file.rel));+ const omittedRequiredPath = mustExist.find(+ (requiredPath) => !collectedPackPaths.has(requiredPath),+ );+ if (omittedRequiredPath) {+ return {+ ok: false,+ errorCode: 'ENTRY_MISSING',+ message: `清单声明的文件未进入打包内容:${omittedRequiredPath}`,+ };+ }+ if (manifest.manual !== undefined) {+ const isWithinManualUnit = (rel: string): boolean =>+ manifest.manual!.items.some((item) => rel.startsWith(`${item.dir}/`));+ const packedManualPaths = new Set(+ files.filter((file) => isWithinManualUnit(file.rel)).map((file) => file.rel),+ );+ const changedManualPath =+ [...packedManualPaths].find((rel) => !manualFileSnapshots.has(rel)) ??+ [...manualFileSnapshots.keys()].find((rel) => !packedManualPaths.has(rel));+ if (changedManualPath !== undefined) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `manual 目录在打包期间发生变化:${changedManualPath}`,+ };+ }+ }// AI icon overlay changes both the manifest snapshot and the icon bytes. A// source tree carrying a publisher/reviewer signature cannot be modified// here without re-signing, so let the host fall back to the original icondiff --cc apps/desktop/src/main/cindy-brain/index.tsindex 2cd0192d86,e407b7187c..c30675fd2f--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -22,10 -22,8 +22,9 @@@ importGHOST_CARD_HEIGHT_MAX,GHOST_CARD_HEIGHT_MIN,GHOST_INSTALL_MANIFEST_MAX_BYTES,- GHOST_MANIFEST_FILE,GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,GHOST_NOTIFY_MIN_INTERVAL_MS,+ isGhostInstallApprovalToken,diffGhostPermissionItems,ghostAppContextLocale,ghostPermissionBaselineKey,@@@ -33,11 -31,8 +32,10 @@@ghostWebviewEntryPaths,isCindyAccountGhostId,isOfficialGhostId,+ ghostPermissionItems,+ ghostPermissionProjectionFingerprint,isValidGhostId,layoutWithGhostPanel,- validateGhostManifest,type GhostHostNoticeKey,type GhostImageAspectRatio,type GhostManifest,diff --cc apps/desktop/src/main/mcp-integrations/ghost.tsindex 067e938318,0bfe191c9a..9843e5d79b--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@@ -66,14 -66,11 +66,15 @@@ importgetGhostManager,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 { readInstalledGhostManual } from '../cindy-brain/ghostManual.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/ownerNamespaceMigration.tsindex 900953633c,39f66d6688..0ec3a61b8d--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@@ -8,21 -7,16 +8,25 @@@ import path from 'node:path'import { dataOwnerStorageKey, type AppSessionMode } from './appSessionState.js';import { createLogger } from './logger.js';import {+ GHOST_MANIFEST_FILE,isOfficialGhostId,- GHOST_INSTALL_MANIFEST_MAX_BYTES,+ isValidGhostId,- validateGhostManifest,} from '../shared/ghost.js';-import { readInstalledGhostManifest } from './installedGhostManifest.js';++import { parseInstalledGhostManifest } from './installedGhostManifest.js';import {NO_LEGACY_GHOST_RECOVERY,type LegacyGhostRecoveryStatus,} from '../shared/legacyGhostRecovery.js';+import { readLegacyGhostApprovalProjection } from './cindy-brain/GhostManager.js';+import { withGhostInstallLock } from './cindy-brain/ghostInstallLock.js';- import { readBoundedFileNoFollow, readBoundedFileNoFollowSync, GHOST_MANIFEST_MAX_BYTES } from './utils/readBoundedFile.js';++import {++ GHOST_MANIFEST_MAX_BYTES,++ readBoundedFileNoFollow,++ readBoundedFileNoFollowSync,++} from './utils/readBoundedFile.js';const CLAIM_MARKER = '.owner-namespace-claim-v1.json';+const LEGACY_GHOST_RECOVERY_MARKER = '.legacy-ghost-recovery-v1.json';const BUILTIN_PROVISIONING_STATE_FILE = '.builtin-provisioning.json';const LEGACY_PATHS = ['ghost-kv',@@@ -783,75 -641,22 +787,76 @@@ interface LegacyGhostDirid: string;dir: string;command: string | null;+ rootStats: fsSync.Stats;+ dirStats: fsSync.Stats;+ rootRealPath: string;+ dirRealPath: string;}-function filterLegacyGhostsByIdPolicy(- ghosts: LegacyGhostDir[],- rejectReservedIds: boolean,-): LegacyGhostDir[] {- return rejectReservedIds ? ghosts.filter((ghost) => !isOfficialGhostId(ghost.id)) : ghosts;+interface LegacyGhostDiscovery {+ ghosts: LegacyGhostDir[];+ deferredRoots: string[];+ deferredIds: string[];+ invalidIds: string[];+}++type LegacyGhostManifestRead =+ | { kind: 'ready'; command: string | null }+ | { kind: 'deferred' }+ | { kind: 'invalid' };++function sameLegacyDirectoryIdentity(expected: fsSync.Stats, current: fsSync.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 sameLegacyCanonicalPath(left: string, right: string): boolean {+ const fold = (value: string) => process.platform === 'win32' ? value.toLowerCase() : value;+ return fold(path.resolve(left)) === fold(path.resolve(right));}-function readValidLegacyGhostDir(+function isLegacyPathInside(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate);+ return relative.length > 0 && !path.isAbsolute(relative) &&+ relative !== '..' && !relative.startsWith(`..${path.sep}`);+}++function readLegacyGhostManifest(dir: string,expectedId: string,-): Pick<LegacyGhostDir, 'command'> | null {- const parsed = readInstalledGhostManifest(dir, GHOST_INSTALL_MANIFEST_MAX_BYTES);- if (!parsed.ok || parsed.manifest.id !== expectedId) return null;- return { command: parsed.manifest.command ?? null };+): LegacyGhostManifestRead {+ const manifestPath = path.join(dir, GHOST_MANIFEST_FILE);- // containWithin needs the real path so that symlinked/relocated userData- // doesn't reject the manifest as outside the root. If realpathSync itself- // fails the directory is inaccessible and the scan treats it as invalid.++ // Keep recovery's three-state I/O semantics at this boundary. The installed++ // manifest parser only owns the legacy-manual compatibility rule; it must++ // not collapse a transient no-follow/containment failure into an ordinary++ // invalid manifest, because recovery must defer rather than freeze it out.+ let containWithin: string;+ try {+ containWithin = fsSync.realpathSync(dir);- } catch {- return { kind: 'invalid' };++ } catch (error) {++ return isMissing(error) ? { kind: 'invalid' } : { kind: 'deferred' };+ }+ let bytes: Buffer | null;+ try {+ bytes = readBoundedFileNoFollowSync(manifestPath, GHOST_MANIFEST_MAX_BYTES, {+ containWithin,+ });+ } catch (error) {+ return isMissing(error) ? { kind: 'invalid' } : { kind: 'deferred' };+ }- if (!bytes) return { kind: 'invalid' };++ if (bytes === null) return { kind: 'invalid' };+ let raw: unknown;+ try {- raw = JSON.parse(bytes.toString('utf-8'));++ raw = JSON.parse(bytes.toString('utf8')) as unknown;+ } catch {+ return { kind: 'invalid' };+ }- const parsed = validateGhostManifest(raw);++ const parsed = parseInstalledGhostManifest(raw);+ if (!parsed.ok || parsed.manifest.id !== expectedId) return { kind: 'invalid' };+ return { kind: 'ready', command: parsed.manifest.command ?? null };}function pathExistsNoFollowSync(diff --cc apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 9ed17c0d01,0061fe817b..9e092709e2--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@@ -1054,13 -1026,9 +1058,13 @@@ describe('PluginMarketService migratiofs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installed));runtime.ghosts = [{- manifest: { ...installed, name: 'Localized Test Plugin' },+ manifest: { ...normalizedInstalled, name: 'Localized Test Plugin' },dir: installedDir,enabled: true,+ approval: {+ state: 'approved',+ revision: '00000000-0000-4000-8000-000000000001',+ },},];runtime.install.mockResolvedValue({@@@ -1073,17 -1041,17 +1077,20 @@@...recordForTest(item),releaseId: 'release-1',version: '1.0.0',- manifestDigest: ghostManifestDigest(installed),+ manifestDigest: ghostManifestDigest(normalizedInstalled),});- await h.service.install(item.id, reviewedInstallOptions(item));+ await h.service.install(item.id, {+ ...reviewedInstallOptions(item),+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,+ });expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: installed,+ permissionBaselineManifest: expect.objectContaining({ id: installed.id }),});+ expect(runtime.install.mock.calls[0]?.[1]?.permissionBaselineManifest).not.toHaveProperty(+ 'manual',+ );});it('keeps a stale official record out of automatic updates but allows explicit replacement', async () => {diff --cc apps/desktop/src/main/utils/readBoundedFile.tsindex 442b39f32b,430e1c97df..6ddf742db3--- a/apps/desktop/src/main/utils/readBoundedFile.ts+++ b/apps/desktop/src/main/utils/readBoundedFile.ts@@@ -75,23 -77,10 +77,23 @@@ export class BoundedFileReadChangedErro}/** realpath 产物是否落在同为 realpath 产物的根内(含根本身)。 */+function normalizeRealPathForComparison(realPath: string): string {+ if (process.platform !== 'win32') return realPath;+ // Node's sync and async realpath implementations may preserve different+ // casing for a Windows drive letter even though both paths name the same+ // volume. Normalize only that OS-defined case-insensitive component; the+ // opened-handle inode checks below still prove the file's identity.+ return realPath.replace(/^([A-Z]):/, (_, drive: string) => `${drive.toLowerCase()}:`);+}+- function isWithinRoot(realFilePath: string, realRoot: string): boolean {+ export function isRealPathWithinRoot(realFilePath: string, realRoot: string): boolean {- if (realFilePath === realRoot) return true;- const rootWithSep = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;- return realFilePath.startsWith(rootWithSep);+ const comparableFilePath = normalizeRealPathForComparison(realFilePath);+ const comparableRoot = normalizeRealPathForComparison(realRoot);+ if (comparableFilePath === comparableRoot) return true;+ const rootWithSep = comparableRoot.endsWith(path.sep)+ ? comparableRoot+ : `${comparableRoot}${path.sep}`;+ return comparableFilePath.startsWith(rootWithSep);}/**@@@ -175,23 -145,6 +177,23 @@@ async function verifyStillWithinRoot}}+function verifyStillWithinRootSync(+ handleStat: fs.BigIntStats,+ filePath: string,+ realRoot: string,+): boolean {+ try {+ const [pathStat, realFilePath] = [+ fs.statSync(filePath, { bigint: true }),+ fs.realpathSync(filePath),+ ];+ if (!sameInode(pathStat, handleStat)) return false;- return isWithinRoot(realFilePath, realRoot);++ return isRealPathWithinRoot(realFilePath, realRoot);+ } catch {+ return false;+ }+}+/*** 读取一个"必须是普通文件"的文件,拒绝符号链接,限量读取。*@@@ -265,9 -212,9 +267,9 @@@ export async function readBoundedFileNo) {throw new BoundedFileReadChangedError();}- return { bytes, stat: verificationStat };+ return { bytes, stat: verificationStat, expectedSize: Number(stat.size) };}- return { bytes, stat: after };- return { bytes, stat: finalStat, expectedSize: Number(stat.size) };++ return { bytes, stat: after, expectedSize: Number(stat.size) };} finally {await handle.close();}diff --cc packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.tsindex 38ab97f614,5993b648d4..1e25e8224c--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts@@@ -800,4 -814,228 +814,228 @@@ describe.skipIf(!existsSync(PI_BINARY))expect(secondNames).toContain('skill:only-second');expect(secondNames).not.toContain('skill:only-first');});++ it('loads repeated explicit project skills under no-approve and no-skills', async () => {+ const fixture = await createFixture('pi-rpc-explicit-skills-only-');+ const explicitSkills = [+ path.join(fixture.workingDir, '.pi', 'skills', 'project-pi-skill'),+ path.join(fixture.repoRoot, '.agents', 'skills', 'ancestor-agents-skill'),+ ];+ const result = await runGetCommands({+ binaryPath: PI_BINARY,+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ extraArgs: [+ '--no-skills',+ '--no-extensions',+ ...explicitSkills.flatMap((skillPath) => ['--skill', skillPath]),+ ],+ });++ expect(normalizeSkills(result.commands, fixture).map((skill) => skill.name)).toEqual([+ 'skill:ancestor-agents-skill',+ 'skill:project-pi-skill',+ ]);+ });++ it('keeps global discovery while explicit project skills bypass only the project trust gate', async () => {+ const fixture = await createFixture('pi-rpc-explicit-skills-additive-');+ const explicitSkill = path.join(+ fixture.workingDir,+ '.pi',+ 'skills',+ 'project-pi-skill',+ );+ const result = await runGetCommands({+ binaryPath: PI_BINARY,+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ extraArgs: ['--no-extensions', '--skill', explicitSkill],+ });++ expect(normalizeSkills(result.commands, fixture).map((skill) => skill.name)).toEqual([+ 'skill:global-skill',+ 'skill:project-pi-skill',+ ]);+ expect(result.commands).toEqual(expect.arrayContaining([+ expect.objectContaining({+ name: 'skill:project-pi-skill',+ source: 'skill',+ sourceInfo: expect.objectContaining({+ path: path.join(explicitSkill, 'SKILL.md'),+ source: 'local',- scope: 'temporary',++ scope: 'project',+ }),+ }),+ ]));+ });++ it('loads an explicit immutable skill snapshot from a non-auto-scanned configHome directory', async () => {+ const fixture = await createFixture('pi-rpc-config-home-snapshot-');+ const snapshotSkill = path.join(+ fixture.configHome,+ 'project-resources',+ 'skills',+ '0',+ 'snapshot-skill',+ );+ writeSkill(snapshotSkill, 'snapshot-skill');+ const result = await runGetCommands({+ binaryPath: PI_BINARY,+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ extraArgs: ['--no-extensions', '--skill', snapshotSkill],+ });++ expect(result.commands).toEqual(expect.arrayContaining([+ expect.objectContaining({+ name: 'skill:snapshot-skill',+ source: 'skill',+ sourceInfo: expect.objectContaining({+ baseDir: snapshotSkill,+ path: path.join(snapshotSkill, 'SKILL.md'),+ source: 'local',+ scope: 'temporary',+ }),+ }),+ ]));+ expect(result.commands.some((command) => command.name === 'skill:project-pi-skill')).toBe(false);+ });++ it('reports the exact file provenance for an explicit single-file skill', async () => {+ const fixture = await createFixture('pi-rpc-explicit-file-skill-');+ const explicitSkill = path.join(fixture.workingDir, '.pi', 'skills', 'single-file.md');+ writeFileSync(+ explicitSkill,+ '---\nname: single-file\ndescription: fixture single file\n---\nfixture single file\n',+ );+ const result = await runGetCommands({+ binaryPath: PI_BINARY,+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ extraArgs: ['--no-extensions', '--skill', explicitSkill],+ });++ expect(result.commands).toEqual(expect.arrayContaining([+ expect.objectContaining({+ name: 'skill:single-file',+ source: 'skill',+ sourceInfo: expect.objectContaining({+ baseDir: path.dirname(explicitSkill),+ path: explicitSkill,+ source: 'local',- scope: 'temporary',++ scope: 'project',+ }),+ }),+ ]));+ });++ it('reports one deterministic runtime command when explicit approved paths share a skill name', async () => {+ const fixture = await createFixture('pi-rpc-explicit-duplicate-name-');+ const first = path.join(fixture.workingDir, '.pi', 'skills', 'duplicate-first');+ const second = path.join(fixture.repoRoot, '.agents', 'skills', 'duplicate-second');+ writeSkill(first, 'duplicate-name');+ writeSkill(second, 'duplicate-name');++ const result = await runGetCommands({+ binaryPath: PI_BINARY,+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ extraArgs: [+ '--no-extensions',+ '--skill', first,+ '--skill', second,+ ],+ });++ const duplicates = result.commands.filter((command) => command.name === 'skill:duplicate-name');+ expect(duplicates).toHaveLength(1);+ expect(duplicates[0]).toMatchObject({+ source: 'skill',- sourceInfo: { baseDir: first, source: 'local', scope: 'temporary' },++ sourceInfo: { baseDir: first, source: 'local', scope: 'project' },+ });+ });++ it('executes only explicit host extensions and never installs or executes project packages/extensions', async () => {+ const fixture = await createFixture('pi-rpc-resource-hard-gates-');+ const trustedExtensionMarker = path.join(fixture.root, 'trusted-extension-loaded');+ const projectExtensionMarker = path.join(fixture.root, 'project-extension-loaded');+ const packageExtensionMarker = path.join(fixture.root, 'package-extension-loaded');+ const npmMarker = path.join(fixture.root, 'npm-invoked');+ const gitTrace = path.join(fixture.root, 'git-trace.log');+ const trustedExtension = path.join(fixture.configHome, 'trusted-extension.ts');+ const projectExtension = path.join(fixture.workingDir, '.pi', 'extensions', 'project.ts');+ const localPackage = path.join(fixture.root, 'local-package');+ const packageExtension = path.join(localPackage, 'extensions', 'package.ts');+ const npmProbe = path.join(fixture.root, 'npm-probe.mjs');++ mkdirSync(path.dirname(projectExtension), { recursive: true });+ mkdirSync(path.dirname(packageExtension), { recursive: true });+ const markerExtension = (marker: string) => [+ "import { writeFileSync } from 'node:fs';",+ `writeFileSync(${JSON.stringify(marker)}, 'loaded');`,+ 'export default function () {}',+ ].join('\n');+ writeFileSync(trustedExtension, markerExtension(trustedExtensionMarker));+ writeFileSync(projectExtension, markerExtension(projectExtensionMarker));+ writeFileSync(packageExtension, markerExtension(packageExtensionMarker));+ writeFileSync(path.join(localPackage, 'package.json'), JSON.stringify({+ name: 'fixture-local-package',+ version: '1.0.0',+ pi: { extensions: ['./extensions/package.ts'] },+ }));+ writeFileSync(+ npmProbe,+ `import { writeFileSync } from 'node:fs'; writeFileSync(${JSON.stringify(npmMarker)}, 'called'); process.exit(17);\n`,+ );+ writeFileSync(path.join(fixture.workingDir, '.pi', 'settings.json'), JSON.stringify({+ npmCommand: [process.execPath, npmProbe],+ packages: [+ 'npm:fixture-must-not-install',+ 'git:http://127.0.0.1:9/fixture-must-not-clone',+ localPackage,+ ],+ extensions: [projectExtension],+ }));++ const result = await runGetCommands({+ binaryPath: PI_BINARY,+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ offline: false,+ extraEnv: {+ GIT_TRACE: gitTrace,+ GIT_TERMINAL_PROMPT: '0',+ },+ extraArgs: [+ '--no-extensions',+ '--extension', trustedExtension,+ '--skill', path.join(fixture.workingDir, '.pi', 'skills', 'project-pi-skill'),+ ],+ });++ expect(normalizeSkills(result.commands, fixture).map((skill) => skill.name)).toEqual([+ 'skill:global-skill',+ 'skill:project-pi-skill',+ ]);+ expect(existsSync(trustedExtensionMarker)).toBe(true);+ expect(existsSync(projectExtensionMarker)).toBe(false);+ expect(existsSync(packageExtensionMarker)).toBe(false);+ expect(existsSync(npmMarker)).toBe(false);+ expect(existsSync(path.join(fixture.workingDir, '.pi', 'npm'))).toBe(false);+ expect(existsSync(path.join(fixture.workingDir, '.pi', 'git'))).toBe(false);+ expect(existsSync(gitTrace) ? readFileSync(gitTrace, 'utf8') : '').not.toMatch(/\bclone\b/i);+ });});