Skip to content

armgit / cindy

Public Imported from GitHub
0

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

Merge remote-tracking branch 'origin/main' into redo/plugin-approval-receipt-migration

Yuewei-LLbf994ccb8311
diff --cc apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
index 3a7b179530,0000000000..4d9c5ea5dc
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
@@@ -1,386 -1,0 +1,437 @@@
+/**
+ * ghostContentTree.test.ts —— 插件内容目录判据(唯一实现)的单测。
+ *
+ * 这个模块存在的理由就是"同一判据别再散落多处",所以判据本身的回归点集中钉在
+ * 这里:类型判定一律 lstat、路径逐段解析、点开头与非普通条目的策略组合。
+ * 规则 23:全部路径在 os.tmpdir 下,收尾清理。
+ */
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { Readable } from 'node:stream';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ classifyGhostDirEntry,
+ classifyGhostDirEntrySync,
+ collectGhostContentFiles,
+ hashGhostContentBuffers,
+ hashGhostContentFiles,
+ resolveGhostContentPath,
+ resolveGhostContentPathSync,
+} from '../ghostContentTree';
+
+let workDir: string;
+
+beforeEach(async () => {
+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-content-tree-'));
+});
+
+afterEach(async () => {
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+});
+
+/** 建目录链接;该环境无权限时返回 false 让用例跳过(判定逻辑与其他平台同源)。 */
+async function tryLinkDir(target: string, linkPath: string): Promise<boolean> {
+ try {
+ await fs.promises.symlink(target, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** 建文件链接;Windows 无权限时返回 false。 */
+async function tryLinkFile(target: string, linkPath: string): Promise<boolean> {
+ try {
+ await fs.promises.symlink(target, linkPath, 'file');
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+describe('classifyGhostDirEntry', () => {
+ it('separates regular files, real directories and links', async () => {
+ const file = path.join(workDir, 'a.txt');
+ const dir = path.join(workDir, 'sub');
+ const link = path.join(workDir, 'linked');
+ await fs.promises.writeFile(file, 'bytes');
+ await fs.promises.mkdir(dir);
+
+ expect(await classifyGhostDirEntry(file)).toBe('file');
+ expect(await classifyGhostDirEntry(dir)).toBe('directory');
+ expect(classifyGhostDirEntrySync(file)).toBe('file');
+ expect(classifyGhostDirEntrySync(dir)).toBe('directory');
+
+ if (!(await tryLinkDir(dir, link))) return;
+ // 关键:链接指向真目录,但判据看 lstat,所以是 link 而不是 directory。
+ expect(await classifyGhostDirEntry(link)).toBe('link');
+ expect(classifyGhostDirEntrySync(link)).toBe('link');
+ });
+});
+
+describe('resolveGhostContentPath', () => {
+ it('rejects a link in an intermediate segment instead of silently reading outside', async () => {
+ // 回归点:只 lstat 最终段是不够的 —— 中间段被换成链接时 OS 会静默穿透,对最终段
+ // lstat 报的是"真目录、非链接",于是字节从插件目录之外取。
+ const base = path.join(workDir, 'plugin');
+ const outside = path.join(workDir, 'outside');
+ await fs.promises.mkdir(path.join(base, 'skills', 'demo'), { recursive: true });
+ await fs.promises.mkdir(path.join(outside, 'demo'), { recursive: true });
+
+ await expect(
+ resolveGhostContentPath(base, 'skills/demo', { expect: 'directory', label: 'x' }),
+ ).resolves.toBe(path.join(base, 'skills', 'demo'));
+
+ await fs.promises.rm(path.join(base, 'skills'), { recursive: true, force: true });
+ if (!(await tryLinkDir(outside, path.join(base, 'skills')))) return;
+
+ await expect(
+ resolveGhostContentPath(base, 'skills/demo', { expect: 'directory', label: 'x' }),
+ ).rejects.toThrow(/path segment is a link/);
+ expect(() =>
+ resolveGhostContentPathSync(base, 'skills/demo', { expect: 'directory', label: 'x' }),
+ ).toThrow(/path segment is a link/);
+ });
+
+ it('enforces the expected kind of the final segment', async () => {
+ await fs.promises.mkdir(path.join(workDir, 'assets'), { recursive: true });
+ await fs.promises.writeFile(path.join(workDir, 'assets', 'icon.png'), 'png');
+
+ await expect(
+ resolveGhostContentPath(workDir, 'assets/icon.png', { expect: 'file', label: 'icon' }),
+ ).resolves.toBe(path.join(workDir, 'assets', 'icon.png'));
+ await expect(
+ resolveGhostContentPath(workDir, 'assets', { expect: 'file', label: 'icon' }),
+ ).rejects.toThrow(/not a regular file/);
+ await expect(
+ resolveGhostContentPath(workDir, 'assets/icon.png', {
+ expect: 'directory',
+ label: 'icon',
+ }),
+ ).rejects.toThrow(/not a directory/);
+ });
+});
+
+describe('collectGhostContentFiles', () => {
+ it('includes dot entries for skill content and rejects links there', async () => {
+ const dir = path.join(workDir, 'skill');
+ await fs.promises.mkdir(path.join(dir, 'refs'), { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'SKILL.md'), 'md');
+ await fs.promises.writeFile(path.join(dir, '.helper'), 'dot bytes');
+ await fs.promises.writeFile(path.join(dir, 'refs', 'a.md'), 'a');
+
+ const tree = await collectGhostContentFiles(dir, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'approved skill',
+ });
+ // 技能目录里的点开头文件同样算内容:技能指令可以引用它。
+ expect(tree.files).toEqual(['.helper', 'SKILL.md', 'refs/a.md']);
+ expect(tree.hasNonRegularEntry).toBe(false);
+
+ if (!(await tryLinkDir(path.join(workDir, 'skill'), path.join(dir, 'loop')))) return;
+ await expect(
+ collectGhostContentFiles(dir, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'approved skill',
+ }),
+ ).rejects.toThrow(/rejects link entry/);
+ });
+
+ it('keeps dot entries out of the content hash but still type-checks them', async () => {
+ // 回归点:上一版对点开头条目直接 continue,于是名为 `.x` 的链接既不进指纹、
+ // 也不翻状态位 —— 安装目录被塞进链接却判成"与种子逐字节相同"。
+ const dir = path.join(workDir, 'installed');
+ await fs.promises.mkdir(dir, { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// brain');
+ await fs.promises.writeFile(path.join(dir, '.disabled'), '');
+
+ const before = await collectGhostContentFiles(dir, {
+ dotEntries: 'skip',
+ nonRegular: 'flag',
+ label: 'seed',
+ });
+ expect(before.files).toEqual(['main.js']);
+ expect(before.hasNonRegularEntry).toBe(false);
+
+ if (!(await tryLinkDir(workDir, path.join(dir, '.sneaky')))) return;
+ const after = await collectGhostContentFiles(dir, {
+ dotEntries: 'skip',
+ nonRegular: 'flag',
+ label: 'seed',
+ });
+ expect(after.files).toEqual(['main.js']);
+ expect(after.hasNonRegularEntry).toBe(true);
+ // 内容哈希不受影响(链接没有内容),判定靠独立的类型状态位。
+ expect(await hashGhostContentFiles(dir, after.files)).toBe(
+ await hashGhostContentFiles(dir, before.files),
+ );
+ });
+});
+
+describe('hashGhostContentFiles', () => {
+ it('hashes path + bytes so identical trees match and any byte change does not', async () => {
+ const a = path.join(workDir, 'a');
+ const b = path.join(workDir, 'b');
+ for (const dir of [a, b]) {
+ await fs.promises.mkdir(path.join(dir, 'nested'), { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// brain');
+ await fs.promises.writeFile(path.join(dir, 'nested', 'x.txt'), 'x');
+ }
+ const options = { dotEntries: 'skip', nonRegular: 'throw', label: 't' } as const;
+ const treeA = await collectGhostContentFiles(a, options);
+ const treeB = await collectGhostContentFiles(b, options);
+ expect(await hashGhostContentFiles(a, treeA.files)).toBe(
+ await hashGhostContentFiles(b, treeB.files),
+ );
+
+ await fs.promises.writeFile(path.join(b, 'nested', 'x.txt'), 'y');
+ expect(await hashGhostContentFiles(a, treeA.files)).not.toBe(
+ await hashGhostContentFiles(b, treeB.files),
+ );
+ });
+
+ it('uses unambiguous framing when file bytes contain NUL separators', async () => {
+ const oneFile = path.join(workDir, 'one-file');
+ const twoFiles = path.join(workDir, 'two-files');
+ await fs.promises.mkdir(oneFile);
+ await fs.promises.mkdir(twoFiles);
+ await fs.promises.writeFile(path.join(oneFile, 'a'), Buffer.from('x\0b\0y'));
+ await fs.promises.writeFile(path.join(twoFiles, 'a'), 'x');
+ await fs.promises.writeFile(path.join(twoFiles, 'b'), 'y');
+
+ const options = { dotEntries: 'include', nonRegular: 'throw', label: 't' } as const;
+ const oneTree = await collectGhostContentFiles(oneFile, options);
+ const twoTree = await collectGhostContentFiles(twoFiles, options);
+
+ expect(oneTree.files).toEqual(['a']);
+ expect(twoTree.files).toEqual(['a', 'b']);
+ expect(await hashGhostContentFiles(oneFile, oneTree.files)).not.toBe(
+ await hashGhostContentFiles(twoFiles, twoTree.files),
+ );
+ });
+
+ it('rejects an intermediate directory replaced by an outside link after collection', async () => {
+ const root = path.join(workDir, 'plugin');
+ const outside = path.join(workDir, 'outside');
+ await fs.promises.mkdir(path.join(root, 'nested'), { recursive: true });
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'nested', 'x.txt'), 'inside');
+ await fs.promises.writeFile(path.join(outside, 'x.txt'), 'outside');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(path.join(root, 'nested'), { recursive: true, force: true });
+ if (!(await tryLinkDir(outside, path.join(root, 'nested')))) return;
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow(
+ /escaped its root|changed into a link/,
+ );
+ });
+
+ it('rejects an intermediate directory replaced by a link within the content root', async () => {
+ const root = path.join(workDir, 'plugin');
+ const alternate = path.join(root, 'alternate');
+ await fs.promises.mkdir(path.join(root, 'nested'), { recursive: true });
+ await fs.promises.mkdir(alternate, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'nested', 'x.txt'), 'inside');
+ await fs.promises.writeFile(path.join(alternate, 'x.txt'), 'alternate');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(path.join(root, 'nested'), { recursive: true, force: true });
+ if (!(await tryLinkDir(alternate, path.join(root, 'nested')))) return;
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow(
+ /ancestor changed into a link/,
+ );
+ });
+
+ it('rejects a leaf file replaced by a link after collection', async () => {
+ const root = path.join(workDir, 'plugin');
+ const outside = path.join(workDir, 'outside.txt');
+ await fs.promises.mkdir(root, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'main.js'), 'inside');
+ await fs.promises.writeFile(outside, 'outside');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(path.join(root, 'main.js'));
+ if (!(await tryLinkFile(outside, path.join(root, 'main.js')))) return;
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow();
+ });
+
+ it('rejects a same-inode leaf file rewritten while its bytes are being hashed', async () => {
+ const root = path.join(workDir, 'plugin');
+ const file = path.join(root, 'main.js');
+ const originalBytes = Buffer.from('old-prefix|old-suffix');
+ const replacementBytes = Buffer.from('new-prefix|new-suffix');
+ expect(replacementBytes.byteLength).toBe(originalBytes.byteLength);
+ await fs.promises.mkdir(root, { recursive: true });
+ await fs.promises.writeFile(file, originalBytes);
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ const splitAt = 'old-prefix|'.length;
+ const realOpen = fs.promises.open;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ const handle = await realOpen(...args);
+ if (path.resolve(String(args[0])) !== path.resolve(file)) return handle;
+ return new Proxy(handle, {
+ get(target, key) {
+ if (key === 'createReadStream') {
+ return () => Readable.from((async function*() {
+ const first = Buffer.alloc(splitAt);
+ const firstRead = await handle.read(first, 0, first.byteLength, 0);
+ yield first.subarray(0, firstRead.bytesRead);
+
+ await fs.promises.writeFile(file, replacementBytes);
+ const changedAt = new Date(Date.now() + 5_000);
+ await fs.promises.utimes(file, changedAt, changedAt);
+
+ const rest = Buffer.alloc(replacementBytes.byteLength - splitAt);
+ const restRead = await handle.read(rest, 0, rest.byteLength, splitAt);
+ yield rest.subarray(0, restRead.bytesRead);
+ })());
+ }
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }) as typeof fs.promises.open);
+ try {
+ await expect(
+ hashGhostContentFiles(root, tree.files, tree.rootIdentity),
+ ).rejects.toThrow(/entry changed while reading/);
+ } finally {
+ openSpy.mockRestore();
+ }
+ });
+
++ it('rejects a leaf file renamed away and replaced while its opened bytes are being hashed', async () => {
++ const root = path.join(workDir, 'plugin');
++ const file = path.join(root, 'main.js');
++ const detachedFile = path.join(root, 'detached.js');
++ const originalBytes = Buffer.from('approved bytes');
++ await fs.promises.mkdir(root, { recursive: true });
++ await fs.promises.writeFile(file, originalBytes);
++ const tree = await collectGhostContentFiles(root, {
++ dotEntries: 'include',
++ nonRegular: 'throw',
++ label: 'test',
++ });
++
++ const realOpen = fs.promises.open;
++ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
++ ...args: Parameters<typeof fs.promises.open>
++ ) => {
++ const handle = await realOpen(...args);
++ if (path.resolve(String(args[0])) !== path.resolve(file)) return handle;
++ let pinnedHandleStat: fs.BigIntStats | undefined;
++ return new Proxy(handle, {
++ get(target, key) {
++ if (key === 'stat') {
++ return async () => {
++ pinnedHandleStat ??= await handle.stat({ bigint: true });
++ return pinnedHandleStat;
++ };
++ }
++ if (key === 'createReadStream') {
++ return () => Readable.from((async function*() {
++ const bytes = Buffer.alloc(originalBytes.byteLength);
++ const read = await handle.read(bytes, 0, bytes.byteLength, 0);
++ await fs.promises.rename(file, detachedFile);
++ await fs.promises.writeFile(file, 'replacement bytes');
++ yield bytes.subarray(0, read.bytesRead);
++ })());
++ }
++ const value = Reflect.get(target, key);
++ return typeof value === 'function' ? value.bind(target) : value;
++ },
++ });
++ }) as typeof fs.promises.open);
++ try {
++ await expect(
++ hashGhostContentFiles(root, tree.files, tree.rootIdentity),
++ ).rejects.toThrow(/entry path changed while reading/);
++ } finally {
++ openSpy.mockRestore();
++ }
++ });
++
+ it('rejects the content root being replaced between collection and hashing', async () => {
+ const root = path.join(workDir, 'plugin');
+ await fs.promises.mkdir(root, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'main.js'), 'inside');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(root, { recursive: true, force: true });
+ await fs.promises.mkdir(root);
+ await fs.promises.writeFile(path.join(root, 'main.js'), 'replacement');
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow(
+ /root changed/,
+ );
+ });
+});
+
+describe('hashGhostContentBuffers', () => {
+ it('与 hashGhostContentFiles 对同一棵文件树逐字节等价(装入基线与快照对账共用判据)', async () => {
+ const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-buf-hash-'));
+ try {
+ await fs.promises.mkdir(path.join(root, 'nested'), { recursive: true });
+ const tree: Record<string, string> = {
+ 'SKILL.md': '---\nname: x\n---\nbody',
+ '.hidden': 'dot files count',
+ 'nested/helper.txt': 'helper',
+ };
+ for (const [rel, content] of Object.entries(tree)) {
+ await fs.promises.writeFile(path.join(root, ...rel.split('/')), content);
+ }
+ const collected = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+ const fromDisk = await hashGhostContentFiles(root, collected.files, collected.rootIdentity);
+ const fromMemory = hashGhostContentBuffers(
+ Object.entries(tree).map(([p2, c]) => ({ path: p2, bytes: Buffer.from(c) })),
+ );
+ expect(fromMemory).toBe(fromDisk);
+ // 内容差一个字节即不同。
+ const drifted = hashGhostContentBuffers(
+ Object.entries({ ...tree, 'SKILL.md': tree['SKILL.md'] + '!' }).map(([p2, c]) => ({
+ path: p2,
+ bytes: Buffer.from(c),
+ })),
+ );
+ expect(drifted).not.toBe(fromDisk);
+ } finally {
+ await fs.promises.rm(root, { recursive: true, force: true });
+ }
+ });
+});
diff --cc apps/desktop/src/main/cindy-brain/ghostContentTree.ts
index a10c07f1c2,0000000000..4d22a6590e
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
@@@ -1,397 -1,0 +1,405 @@@
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+/**
+ * ghostContentTree —— 「插件内容目录怎么读」的**唯一判据**。
+ *
+ * 为什么存在这个模块:插件链路上有六处各自 readdir + 判类型的实现(技能指纹、
+ * 技能快照拷贝、安装目录漂移指纹、随包种子指纹、种子复制、Forge 打包收集),
+ * 还有五处各自 `path.join(dir, ...rel.split('/'))` 之后再判一次类型。它们本该
+ * 是同一条判据,却分别用 Dirent 类型位 / `lstat` / `stat` / realpath 钳制写过,
+ * 于是每一轮审查都能在其中一处找到没覆盖的角落 —— 补一处、下一轮换另一处。
+ *
+ * 所以类型判定与相对路径解析在本模块各只有一份实现,差异只允许以**显式策略
+ * 参数**表达(点开头条目算不算内容、非普通条目是拒还是只记状态位)。新增读插件
+ * 内容的代码一律从这里取判据,不要再就地 readdir + isDirectory()。
+ */
+
+/**
+ * 目录条目类型。`link` 与 `other` 都属于"非普通条目",单独区分只为错误信息
+ * 能说清是链接还是别的(FIFO / 设备节点等)。
+ */
+export type GhostDirEntryKind = 'file' | 'directory' | 'link' | 'other';
+
+/**
+ * 类型判据的唯一实现:一律看 `lstat`,**不信 Dirent 的类型位**。
+ *
+ * Dirent 的类型位来自 readdir 的批量结果,当前 libuv 把 reparse point(软链与
+ * Windows junction)都报成 link,但那是实现细节、Node 公开契约没保证;判据自己
+ * 拿 lstat 说话,哪天类型位把 junction 报成 directory 也不会跟进去。
+ */
+function kindOfStat(stat: fs.Stats): GhostDirEntryKind {
+ if (stat.isSymbolicLink()) return 'link';
+ if (stat.isDirectory()) return 'directory';
+ if (stat.isFile()) return 'file';
+ return 'other';
+}
+
+export async function classifyGhostDirEntry(absPath: string): Promise<GhostDirEntryKind> {
+ return kindOfStat(await fs.promises.lstat(absPath));
+}
+
+export function classifyGhostDirEntrySync(absPath: string): GhostDirEntryKind {
+ return kindOfStat(fs.lstatSync(absPath));
+}
+
+/** 普通条目 = 真目录或普通文件;其余(链接等)一律非普通。 */
+export function isRegularGhostDirEntry(kind: GhostDirEntryKind): boolean {
+ return kind === 'file' || kind === 'directory';
+}
+
+export interface ResolveGhostContentPathOptions {
+ /** 最终段期望的类型。 */
+ expect: 'directory' | 'file';
+ /** 错误信息前缀(如 `approved skill` / `bundled locale`)。 */
+ label: string;
+}
+
+/**
+ * 解析清单声明的相对路径,**逐段**确认每一段都是真目录 / 最终段是期望类型。
+ *
+ * 只 lstat 最终段是不够的:中间段被换成软链 / Windows junction 时 OS 会静默穿透
+ * —— 对最终段 lstat 报的是"真目录、非链接"(已实测),于是字节从插件目录之外取。
+ * 首次批准那条路径尤其致命:技能指纹是现算的,外部内容会被钉成"批准字节"再复制
+ * 成快照,而 `checkSkillMdConsistency` 只校验 frontmatter 的 name/description,
+ * 这两个值在 manifest 里公开可抄,拦不住。
+ *
+ * `baseDir` 自身不在这里校验(它由调用方给出:安装根下的 `<id>` 若被换成链接,
+ * `GhostManager.list()` 的 `entry.isDirectory()` 已经把它整条跳过;状态根下的
+ * temp / 快照目录是宿主自己创建的)。相对路径的结构安全由清单校验保证
+ * (`isSafeGhostRelativePath` / skill dir 正则:无盘符、无反斜杠、无 `.`/`..` 段)。
+ */
+export async function resolveGhostContentPath(
+ baseDir: string,
+ relPath: string,
+ options: ResolveGhostContentPathOptions,
+): Promise<string> {
+ const segments = relPath.split('/').filter((segment) => segment.length > 0);
+ let current = baseDir;
+ for (const [index, segment] of segments.entries()) {
+ current = path.join(current, segment);
+ assertSegment(
+ await classifyGhostDirEntry(current),
+ index === segments.length - 1 ? options.expect : 'directory',
+ relPath,
+ options.label,
+ );
+ }
+ return current;
+}
+
+export function resolveGhostContentPathSync(
+ baseDir: string,
+ relPath: string,
+ options: ResolveGhostContentPathOptions,
+): string {
+ const segments = relPath.split('/').filter((segment) => segment.length > 0);
+ let current = baseDir;
+ for (const [index, segment] of segments.entries()) {
+ current = path.join(current, segment);
+ assertSegment(
+ classifyGhostDirEntrySync(current),
+ index === segments.length - 1 ? options.expect : 'directory',
+ relPath,
+ options.label,
+ );
+ }
+ return current;
+}
+
+function assertSegment(
+ kind: GhostDirEntryKind,
+ expect: 'directory' | 'file',
+ relPath: string,
+ label: string,
+): void {
+ if (kind === 'link') {
+ throw new Error(`${label} path segment is a link: ${relPath}`);
+ }
+ if (kind !== expect) {
+ throw new Error(
+ `${label} path segment is not a ${expect === 'directory' ? 'directory' : 'regular file'}: ${relPath}`,
+ );
+ }
+}
+
+export interface CollectGhostContentOptions {
+ /**
+ * 点开头条目:`include` = 算内容(技能目录 —— 技能指令可以引用目录里的任意
+ * 文件,漏掉一类就是漏掉一条改写通道);`skip` = 不算内容(安装目录 / 随包种子
+ * —— `.disabled`、`.cindy-trust.json` 是用户与宿主状态,不是插件内容)。
+ *
+ * `skip` 下点开头条目仍然**要过类型判定**:名为 `.x` 的链接不进内容指纹,但
+ * 会按 `nonRegular` 策略处理。点开头**目录**整条跳过(不递归、不进指纹):清单
+ * 声明的相对路径首字符必须是 `[a-zA-Z0-9_]`,任何声明都不可能指向点开头目录里
+ * 的文件,所以它们既不会被当代码加载、也不会被当技能读取。
+ */
+ dotEntries: 'include' | 'skip';
+ /**
+ * 非普通条目(链接 / FIFO 等):`throw` = 立即拒(授权判据路径);`flag` = 只翻
+ * `hasNonRegularEntry`,不进内容指纹(对账判据路径 —— 需要"判不一致"而不是抛错,
+ * 才能走重新播种把目录换回随包字节)。
+ *
+ * `flag` 下**不能拿 sentinel 喂进哈希**:任何 sentinel 都能被"同路径下内容恰好
+ * 等于该 sentinel 的普通文件"撞上(已实测:内容为 `non-regular` 的普通文件与同名
+ * junction 的摘要完全相等),于是被塞进链接的目录仍会被判成逐字节相同。所以类型
+ * 状态是独立字段,不掺进字节流。
+ */
+ nonRegular: 'throw' | 'flag';
+ /** 错误信息前缀。 */
+ label: string;
+}
+
+export interface GhostContentTree {
+ /** 普通文件的相对路径(正斜杠归一化保证双平台一致),已排序。 */
+ files: string[];
+ /** 是否遇到过非普通条目(仅 `nonRegular: 'flag'` 时可能为 true)。 */
+ hasNonRegularEntry: boolean;
+ /** 收集开始时钉住的规范根身份,供后续流式哈希拒绝 collect→hash 间的根替换。 */
+ rootIdentity: GhostContentRootIdentity;
+}
+
+export interface GhostContentRootIdentity {
+ realPath: string;
+ dev: bigint;
+ ino: bigint;
+}
+
+interface GhostContentAncestorIdentity {
+ relativePath: string;
+ dev: bigint;
+ ino: bigint;
+}
+
+function sameFileIdentity(
+ a: Pick<fs.BigIntStats, 'dev' | 'ino'>,
+ b: Pick<fs.BigIntStats, 'dev' | 'ino'>,
+): boolean {
+ if (a.dev === 0n || a.ino === 0n || b.dev === 0n || b.ino === 0n) return false;
+ return a.dev === b.dev && a.ino === b.ino;
+}
+
+function sameStableFileState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {
+ return after.isFile() &&
+ sameFileIdentity(before, after) &&
+ before.size === after.size &&
+ before.mtimeNs === after.mtimeNs &&
+ before.ctimeNs === after.ctimeNs;
+}
+
+async function captureGhostContentRootIdentity(rootDir: string): Promise<GhostContentRootIdentity> {
+ const realPath = await fs.promises.realpath(rootDir);
+ const [pathStat, realStat] = await Promise.all([
+ fs.promises.stat(rootDir, { bigint: true }),
+ fs.promises.stat(realPath, { bigint: true }),
+ ]);
+ if (!pathStat.isDirectory() || !realStat.isDirectory() || !sameFileIdentity(pathStat, realStat)) {
+ throw new Error(`ghost content root is not a stable directory: ${rootDir}`);
+ }
+ return { realPath, dev: realStat.dev, ino: realStat.ino };
+}
+
+async function assertGhostContentRootIdentity(
+ rootDir: string,
+ expected: GhostContentRootIdentity,
+): Promise<void> {
+ const current = await captureGhostContentRootIdentity(rootDir);
+ if (
+ current.realPath !== expected.realPath ||
+ current.dev !== expected.dev ||
+ current.ino !== expected.ino
+ ) {
+ throw new Error(`ghost content root changed while reading: ${rootDir}`);
+ }
+}
+
+async function captureGhostContentAncestorIdentities(
+ rootRealPath: string,
+ relativePath: string,
+): Promise<GhostContentAncestorIdentity[]> {
+ const identities: GhostContentAncestorIdentity[] = [];
+ const segments = relativePath.split('/').slice(0, -1);
+ let absolutePath = rootRealPath;
+ let currentRelativePath = '';
+ for (const segment of segments) {
+ absolutePath = path.join(absolutePath, segment);
+ currentRelativePath = currentRelativePath ? `${currentRelativePath}/${segment}` : segment;
+ const stat = await fs.promises.lstat(absolutePath, { bigint: true });
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
+ throw new Error(`ghost content ancestor changed into a link: ${currentRelativePath}`);
+ }
+ identities.push({ relativePath: currentRelativePath, dev: stat.dev, ino: stat.ino });
+ }
+ return identities;
+}
+
+function assertGhostContentAncestorIdentities(
+ expected: readonly GhostContentAncestorIdentity[],
+ current: readonly GhostContentAncestorIdentity[],
+): void {
+ if (
+ current.length !== expected.length ||
+ current.some(
+ (identity, index) =>
+ identity.relativePath !== expected[index]?.relativePath ||
+ identity.dev !== expected[index]?.dev ||
+ identity.ino !== expected[index]?.ino,
+ )
+ ) {
+ throw new Error('ghost content ancestor changed while reading');
+ }
+}
+
+/** 递归收集目录里的普通文件相对路径;类型判定与策略见 `CollectGhostContentOptions`。 */
+export async function collectGhostContentFiles(
+ rootDir: string,
+ options: CollectGhostContentOptions,
+): Promise<GhostContentTree> {
+ const rootIdentity = await captureGhostContentRootIdentity(rootDir);
+ const files: string[] = [];
+ let hasNonRegularEntry = false;
+
+ const collect = async (relativeDir: string): Promise<void> => {
+ const absoluteDir = path.join(rootIdentity.realPath, ...relativeDir.split('/').filter(Boolean));
+ for (const entry of await fs.promises.readdir(absoluteDir, { withFileTypes: true })) {
+ const isDotEntry = entry.name.startsWith('.');
+ const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
+ const kind = await classifyGhostDirEntry(path.join(absoluteDir, entry.name));
+ if (!isRegularGhostDirEntry(kind)) {
+ // 类型判定排在点开头过滤**之前**:名为 `.x` 的链接同样是一条改写通道,
+ // 不能因为"点开头不算内容"就连它是不是链接都不看。
+ if (options.nonRegular === 'throw') {
+ throw new Error(
+ `${options.label} rejects ${kind === 'link' ? 'link' : 'non-regular'} entry: ${relativePath}`,
+ );
+ }
+ hasNonRegularEntry = true;
+ continue;
+ }
+ if (isDotEntry && options.dotEntries === 'skip') continue;
+ if (kind === 'directory') {
+ await collect(relativePath);
+ } else {
+ files.push(relativePath);
+ }
+ }
+ };
+
+ await collect('');
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
+ files.sort();
+ return { files, hasNonRegularEntry, rootIdentity };
+}
+
+/**
+ * 内容指纹:版本前缀 + 长度前缀路径 + 每文件 SHA-256。
+ *
+ * 不使用 `path \0 bytes \0` 这类分隔符编码:文件内容可以合法包含 NUL,于是
+ * `{ a: "x\0b\0y" }` 与 `{ a: "x", b: "y" }` 会在进入 SHA-256 前形成完全
+ * 相同的字节流。路径使用 UTF-8 字节长度前缀,文件内容先流式收成固定 32 字节摘要,
+ * 因此文件边界无歧义。
+ *
+ * 文件仍然流式读取,不整份进内存 —— 插件目录里除 SKILL.md 之外的文件没有尺寸
+ * 上限,整份 readFile 会让一个塞进来的超大文件把 Host 撑爆。
+ */
+/**
+ * `hashGhostContentFiles` 的内存版:对"路径 + 字节"的内存投影算同一 framing 的
+ * 指纹(逐字节等价,有回归钉住)。用途:装入/更新时从 **.cindy 包本体**(不可变的
+ * JSZip 投影)算批准基线,而不是从已公开的可变安装目录首读 —— 后者在 publish 与
+ * 首次 hash 之间被换过的字节会自洽地成为批准事实(权威判据被污染源初始化)。
+ */
+export function hashGhostContentBuffers(files: readonly { path: string; bytes: Buffer }[]): string {
+ const hash = crypto.createHash('sha256');
+ hash.update('cindy-ghost-content-v2\0');
+ const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+ for (const file of sorted) {
+ const pathBytes = Buffer.from(file.path, 'utf8');
+ const pathLength = Buffer.allocUnsafe(8);
+ pathLength.writeBigUInt64BE(BigInt(pathBytes.byteLength));
+ hash.update(pathLength);
+ hash.update(pathBytes);
+ hash.update(crypto.createHash('sha256').update(file.bytes).digest());
+ }
+ return hash.digest('hex');
+}
+
+export async function hashGhostContentFiles(
+ rootDir: string,
+ files: readonly string[],
+ collectedRootIdentity?: GhostContentRootIdentity,
+): Promise<string> {
+ const rootIdentity = collectedRootIdentity ?? (await captureGhostContentRootIdentity(rootDir));
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
+ const hash = crypto.createHash('sha256');
+ hash.update('cindy-ghost-content-v2\0');
+ for (const relativePath of files) {
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
+ const pathBytes = Buffer.from(relativePath, 'utf8');
+ const pathLength = Buffer.allocUnsafe(8);
+ pathLength.writeBigUInt64BE(BigInt(pathBytes.byteLength));
+ hash.update(pathLength);
+ hash.update(pathBytes);
+
+ const fileHash = crypto.createHash('sha256');
+ const filePath = path.join(rootIdentity.realPath, ...relativePath.split('/'));
+ const ancestorIdentities = await captureGhostContentAncestorIdentities(
+ rootIdentity.realPath,
+ relativePath,
+ );
+ const noFollow = fs.constants.O_NOFOLLOW ?? null;
+ const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | (noFollow ?? 0));
+ try {
+ const handleStat = await handle.stat({ bigint: true });
+ if (!handleStat.isFile()) {
+ throw new Error(`ghost content entry is not a regular file: ${relativePath}`);
+ }
+ assertGhostContentAncestorIdentities(
+ ancestorIdentities,
+ await captureGhostContentAncestorIdentities(rootIdentity.realPath, relativePath),
+ );
+ if (noFollow === null) {
+ const linkStat = await fs.promises.lstat(filePath, { bigint: true });
+ if (linkStat.isSymbolicLink() || !sameFileIdentity(linkStat, handleStat)) {
+ throw new Error(`ghost content entry changed into a link: ${relativePath}`);
+ }
+ }
+ const [pathStat, realFilePath] = await Promise.all([
+ fs.promises.stat(filePath, { bigint: true }),
+ fs.promises.realpath(filePath),
+ ]);
+ const relativeRealPath = path.relative(rootIdentity.realPath, realFilePath);
+ const outsideRoot =
+ relativeRealPath === '..' ||
+ relativeRealPath.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(relativeRealPath);
+ if (!sameFileIdentity(pathStat, handleStat) || outsideRoot) {
+ throw new Error(`ghost content entry escaped its root: ${relativePath}`);
+ }
+
+ const stream = handle.createReadStream({ autoClose: false });
+ for await (const chunk of stream) fileHash.update(chunk as Buffer);
+ const afterReadStat = await handle.stat({ bigint: true });
+ if (!sameStableFileState(handleStat, afterReadStat)) {
+ throw new Error(`ghost content entry changed while reading: ${relativePath}`);
+ }
++ const afterReadPathStat = await fs.promises.lstat(filePath, { bigint: true });
++ if (
++ afterReadPathStat.isSymbolicLink() ||
++ !afterReadPathStat.isFile() ||
++ !sameFileIdentity(afterReadPathStat, afterReadStat)
++ ) {
++ throw new Error(`ghost content entry path changed while reading: ${relativePath}`);
++ }
+ assertGhostContentAncestorIdentities(
+ ancestorIdentities,
+ await captureGhostContentAncestorIdentities(rootIdentity.realPath, relativePath),
+ );
+ } finally {
+ await handle.close();
+ }
+ hash.update(fileHash.digest());
+ }
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
+ return hash.digest('hex');
+}