Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 插件持久 Library(library 槽):受控 SQLite + 自定义位置 + 随时迁移 (#3079)
Lizi625a7d714f19
diff --git a/AGENTS.md b/AGENTS.mdindex 08d3a45b5e..7ca0161d78 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -95,6 +95,9 @@改动」豁免。- 修改插件发现链(花名册注入、`ghost_list` / `ghost_info` / `ghost_call`)、插件运行期可见性门禁或 FORGE_GUIDE 作者契约前,必须先读 `docs/ghost-progressive-discovery.md`。+- 新增或修改插件持久 Library(library 槽、binding / 目录选择、随时迁移、+ 回收站删除、SQLite 语句门或 `/library/` 面板投影)前,必须先读+ `docs/dev-rules/plugin-library-storage.md`。- 修改客户端自动更新链路(`cindy-updater` 或 Electron 侧更新服务)前,必须先读`docs/dev-rules/cindy-updater.md`。- 新增或修改 Desktop 日志、IPC 错误处理、main 侧业务逻辑与测试、跨平台(macOS/diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 69244e6a28..4fdab7ecd6 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1500,6 +1500,13 @@ const config: ForgeConfig = {// 不是 Electron preload。target: 'preload',},+ {+ entry: 'src/main/cindy-brain/libraryDbWorker.ts',+ config: 'vite.library-db-worker.config.ts',+ // 插件 Library SQLite 隔离在 per-plugin worker:恶意慢查询只饿死+ // 自己的线程,宿主可 terminate(WAL 保证不损坏库)。+ target: 'preload',+ },{entry: 'src/main/im/wechat/silkWorker.ts',config: 'vite.silk-worker.config.ts',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.tsnew file mode 100644index 0000000000..396ed5aebd--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts@@ -0,0 +1,184 @@+/**+ * libraryBinding 单测:绑定/撤销/漂移三分支(disk-missing / binding-moved)、+ * 候选位置校验(受管根排斥/UNC 拒/云盘警告/可写探针)、损坏文件回落默认。+ * 注入 deps + os.tmpdir,零 Electron。identity 用例带平台能力探针。+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++import { LibraryBindingStore, validateLibraryCandidateLocation, type LibraryBindingDeps } from '../libraryBinding.js';++const GHOST_ID = 'mivo-canvas';++describe('LibraryBindingStore', () => {+ let tmp: string;+ let bindingFile: string;+ let candidate: string;+ let managedRoot: string;+ let defaultRootBase: string;+ let deps: LibraryBindingDeps;++ beforeEach(async () => {+ tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-binding-'));+ bindingFile = path.join(tmp, 'owners', 'k1', 'libraries-binding.json');+ candidate = path.join(tmp, 'picked-parent');+ managedRoot = path.join(tmp, 'managed');+ defaultRootBase = path.join(tmp, 'owners', 'k1', 'libraries');+ await fs.promises.mkdir(candidate, { recursive: true });+ await fs.promises.mkdir(managedRoot, { recursive: true });+ deps = {+ getFile: () => bindingFile,+ getManagedRoots: () => [managedRoot],+ getDefaultRoot: (ghostId) => path.join(defaultRootBase, ghostId),+ };+ });++ afterEach(async () => {+ await fs.promises.rm(tmp, { recursive: true, force: true });+ });++ it('无 binding → 默认根;绑定后解析到 <candidate>/<ghostId>', async () => {+ const store = new LibraryBindingStore(deps);+ const before = await store.resolveLibraryRoot(GHOST_ID);+ expect(before.kind).toBe('default');+ if (before.kind === 'default') expect(before.root).toBe(path.join(defaultRootBase, GHOST_ID));++ const set = await store.setBinding(GHOST_ID, candidate);+ expect(set.ok).toBe(true);+ if (!set.ok) return;+ expect(set.record.generation).toBe(1);++ const after = await store.resolveLibraryRoot(GHOST_ID);+ expect(after.kind).toBe('custom');+ if (after.kind === 'custom' && after.root !== null) {+ // 解析结果基于 realpath(CI Windows 的 tmpdir 带 8.3 短名,如 RUNNER~1,+ // realpath 归一成长名)——按跨平台路径宪法用 realpath 构造期望值比对。+ expect(after.root).toBe(path.join(await fs.promises.realpath(candidate), GHOST_ID));+ }+ // binding 文件持久化(新实例可读)。+ const fresh = new LibraryBindingStore(deps);+ const reread = await fresh.resolveLibraryRoot(GHOST_ID);+ expect(reread.kind).toBe('custom');+ });++ it('重新绑定 generation 递增;撤销后回落默认', async () => {+ const store = new LibraryBindingStore(deps);+ await store.setBinding(GHOST_ID, candidate);+ const second = path.join(tmp, 'picked-parent-2');+ await fs.promises.mkdir(second, { recursive: true });+ const set2 = await store.setBinding(GHOST_ID, second);+ if (set2.ok) expect(set2.record.generation).toBe(2);+ await store.removeBinding(GHOST_ID);+ const resolved = await store.resolveLibraryRoot(GHOST_ID);+ expect(resolved.kind).toBe('default');+ });++ it('目录被删 → disk-missing;同路径删后重建 → POSIX 上 binding-moved', async () => {+ const store = new LibraryBindingStore(deps);+ const set = await store.setBinding(GHOST_ID, candidate);+ expect(set.ok).toBe(true);++ await fs.promises.rm(candidate, { recursive: true });+ const missing = await store.resolveLibraryRoot(GHOST_ID);+ expect(missing.kind).toBe('custom');+ if (missing.kind === 'custom' && missing.root === null) {+ expect(missing.drift).toBe('disk-missing');+ }++ // 原地重建:路径字符串相同,靠 identity 检出(Windows ino=0 时退化为放行,+ // 已知平台限制,见模块头注释)。+ await fs.promises.mkdir(candidate, { recursive: true });+ const rebuilt = await store.resolveLibraryRoot(GHOST_ID);+ expect(rebuilt.kind).toBe('custom');+ if (rebuilt.kind === 'custom' && rebuilt.root === null) {+ expect(rebuilt.drift).toBe('binding-moved');+ }+ });++ it('binding 文件损坏 → 回落默认根且不抛(数据本体不动)', async () => {+ const store = new LibraryBindingStore(deps);+ await store.setBinding(GHOST_ID, candidate);+ await fs.promises.writeFile(bindingFile, '{corrupt', 'utf8');+ const resolved = await store.resolveLibraryRoot(GHOST_ID);+ expect(resolved.kind).toBe('default');+ });+});++describe('validateLibraryCandidateLocation', () => {+ let tmp: string;+ let managedRoot: string;+ let deps: LibraryBindingDeps;++ beforeEach(async () => {+ tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-candidate-'));+ managedRoot = path.join(tmp, 'managed');+ await fs.promises.mkdir(managedRoot, { recursive: true });+ deps = {+ getFile: () => path.join(tmp, 'binding.json'),+ getManagedRoots: () => [managedRoot],+ getDefaultRoot: (ghostId) => path.join(tmp, 'default', ghostId),+ };+ });++ afterEach(async () => {+ await fs.promises.rm(tmp, { recursive: true, force: true });+ });++ it('合法目录通过并创建库根路径;返回 libraryRoot', async () => {+ const res = await validateLibraryCandidateLocation({+ candidate: path.join(tmp, 'plain-dir'),+ ghostId: GHOST_ID,+ deps,+ });+ expect(res.ok).toBe(true);+ if (res.ok) expect(res.libraryRoot).toBe(path.join(tmp, 'plain-dir', GHOST_ID));+ });++ it('受管根内拒绝;UNC 网络路径拒绝;相对路径拒绝', async () => {+ const inside = await validateLibraryCandidateLocation({+ candidate: path.join(managedRoot, 'sub'),+ ghostId: GHOST_ID,+ deps,+ });+ expect(inside.ok).toBe(false);+ if (!inside.ok) expect(inside.errorCode).toBe('PATH_INVALID');++ // UNC 在 POSIX 上先被「非绝对路径」拦下(宿主 path.isAbsolute 平台语义),+ // 只有 win32 走得到「网络位置」分支——两平台都必须是拒绝,话术按平台断言。+ const unc = await validateLibraryCandidateLocation({+ candidate: '\\\\server\\share',+ ghostId: GHOST_ID,+ deps,+ });+ expect(unc.ok).toBe(false);+ if (!unc.ok && process.platform === 'win32') {+ expect(unc.message).toContain('网络');+ }++ const rel = await validateLibraryCandidateLocation({ candidate: 'relative/path', ghostId: GHOST_ID, deps });+ expect(rel.ok).toBe(false);+ });++ it('云同步目录特征 → 强警告但放行', async () => {+ const res = await validateLibraryCandidateLocation({+ candidate: path.join(tmp, 'My Dropbox Files'),+ ghostId: GHOST_ID,+ deps,+ });+ expect(res.ok).toBe(true);+ if (res.ok) expect(res.warnings.length).toBe(1);+ });++ it('磁盘余量低于阈值 → DISK_FULL', async () => {+ const res = await validateLibraryCandidateLocation({+ candidate: path.join(tmp, 'small-disk'),+ ghostId: GHOST_ID,+ deps,+ getDiskFreeBytes: async () => 1024,+ });+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.errorCode).toBe('DISK_FULL');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryDbCore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryDbCore.test.tsnew file mode 100644index 0000000000..b2bde05b18--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryDbCore.test.ts@@ -0,0 +1,252 @@+/**+ * libraryDbCore / librarySqlService 单测:语句门攻击矩阵(ATTACH/VACUUM/+ * PRAGMA/事务语句/注释伪装)、exec/batch 事务原子性、migrate 幂等与冲突、+ * backup+quick_check、结果集上限、参数校验。进程内直连 core(与 worker 共用+ * 同一份执行体);os.tmpdir 建库,零 Electron。+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import Database from 'better-sqlite3';++import {+ createLibraryDbCore,+ gateSqlStatement,+ LIBRARY_DB_MAX_ROWS,+ LIBRARY_DB_MAX_RESULT_BYTES,+ type SqliteDatabaseConstructor,+} from '../libraryDbCore.js';+import { LibrarySqlService } from '../librarySqlService.js';++const Ctor = Database as unknown as SqliteDatabaseConstructor;++describe('gateSqlStatement(语句门攻击矩阵)', () => {+ const allowed = [+ 'SELECT 1',+ 'select * from t',+ 'WITH x AS (SELECT 1) SELECT * FROM x',+ 'INSERT INTO t VALUES (?)',+ 'REPLACE INTO t VALUES (?)',+ 'UPDATE t SET a = ?',+ 'DELETE FROM t',+ 'CREATE TABLE t (a INTEGER)',+ 'DROP TABLE t',+ 'ALTER TABLE t ADD COLUMN b TEXT',+ 'REINDEX t',+ 'ANALYZE',+ '\n\n-- leading comment\nSELECT 1',+ '/* block */ SELECT 1',+ ];+ const rejected = [+ 'ATTACH DATABASE \'x.db\' AS x',+ 'DETACH DATABASE x',+ 'PRAGMA journal_mode = wal',+ 'VACUUM',+ 'VACUUM INTO \'/tmp/evil.db\'',+ 'BEGIN',+ 'COMMIT',+ 'ROLLBACK',+ 'SAVEPOINT sp',+ 'EXPLAIN SELECT 1',+ '-- comment hiding ATTACH\nATTACH DATABASE \'x\' AS y',+ '/*x*/ PRAGMA foreign_keys = off',+ '',+ ' ',+ 42 as unknown,+ ];+ it.each(allowed.map((s) => [s]))('放行:%s', (s) => {+ expect(gateSqlStatement(s).ok).toBe(true);+ });+ it.each(rejected.map((s) => [s]))('拒绝:%s', (s) => {+ expect(gateSqlStatement(s).ok).toBe(false);+ });+ it('未闭合块注释拒绝', () => {+ expect(gateSqlStatement('/* unterminated SELECT 1').ok).toBe(false);+ });+});++describe('libraryDbCore', () => {+ let tmp: string;+ let dbPath: string;+ let core: ReturnType<typeof createLibraryDbCore>;++ beforeEach(async () => {+ tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-db-'));+ dbPath = path.join(tmp, 'canvases', 'c1', 'canvas.sqlite');+ await fs.promises.mkdir(path.dirname(dbPath), { recursive: true });+ core = createLibraryDbCore({ DatabaseCtor: Ctor });+ const open = await core.openDatabase(dbPath);+ expect(open.ok).toBe(true);+ });++ afterEach(async () => {+ core.closeAll();+ await fs.promises.rm(tmp, { recursive: true, force: true });+ });++ it('建表/插入/参数化查询往返;读语句回行,写语句回 changes', () => {+ const create = core.execStatement(dbPath, 'CREATE TABLE nodes (id TEXT PRIMARY KEY, name TEXT)', undefined);+ expect(create.ok).toBe(true);+ const ins = core.execStatement(dbPath, 'INSERT INTO nodes VALUES (?, ?)', ['n1', '画布节点']);+ if (!ins.ok) throw new Error(JSON.stringify(ins));+ expect(ins.changes).toBe(1);+ const sel = core.execStatement(dbPath, 'SELECT id, name FROM nodes WHERE id = ?', ['n1']);+ if (!sel.ok) throw new Error(JSON.stringify(sel));+ expect(sel.rows).toEqual([{ id: 'n1', name: '画布节点' }]);+ const named = core.execStatement(dbPath, 'SELECT :id AS id', { id: 'x' });+ expect(named.ok).toBe(true);+ if (named.ok) expect(named.rows).toEqual([{ id: 'x' }]);+ });++ it('exec 拒 ATTACH/PRAGMA/多语句;参数类型校验(boolean 拒)', () => {+ const attach = core.execStatement(dbPath, "ATTACH DATABASE '/etc/passwd' AS p", undefined);+ expect(attach.ok).toBe(false);+ if (!attach.ok) expect(attach.code).toBe('DB_STATEMENT_REJECTED');+ const pragma = core.execStatement(dbPath, 'PRAGMA journal_mode = delete', undefined);+ expect(pragma.ok).toBe(false);+ const multi = core.execStatement(dbPath, 'SELECT 1; SELECT 2', undefined);+ expect(multi.ok).toBe(false); // better-sqlite3 prepare 拒多语句+ if (!multi.ok) expect(multi.code).toBe('DB_ERROR');+ const bool = core.execStatement(dbPath, 'SELECT ?', [true]);+ expect(bool.ok).toBe(false);+ if (!bool.ok) expect(bool.code).toBe('DB_PARAMS_INVALID');+ });++ it('batch 整批原子:中途失败全回滚', () => {+ core.execStatement(dbPath, 'CREATE TABLE t (a INTEGER)', undefined);+ const ok = core.batch(dbPath, [+ { sql: 'INSERT INTO t VALUES (1)' },+ { sql: 'INSERT INTO t VALUES (2)' },+ ]);+ if (!ok.ok) throw new Error(JSON.stringify(ok));+ expect(ok.applied).toBe(2);+ const bad = core.batch(dbPath, [+ { sql: 'INSERT INTO t VALUES (3)' },+ { sql: 'INSERT INTO nonexistent VALUES (4)' },+ ]);+ expect(bad.ok).toBe(false);+ const count = core.execStatement(dbPath, 'SELECT COUNT(*) AS n FROM t', undefined);+ if (count.ok) expect((count.rows as Array<{ n: number }>)[0].n).toBe(2);+ });++ it('migrate:逐步应用 + user_version 推进 + 幂等续跑 + 高版本冲突', () => {+ const steps = [+ { toVersion: 1, sql: ['CREATE TABLE v1 (a TEXT)'] },+ { toVersion: 2, sql: ['CREATE TABLE v2 (a TEXT)', 'INSERT INTO v1 VALUES (\'x\')'] },+ ];+ const m1 = core.migrate(dbPath, 2, steps);+ if (!m1.ok) throw new Error(JSON.stringify(m1));+ expect(m1.toVersion).toBe(2);+ expect(core.readUserVersion(dbPath)).toBe(2);+ // 幂等:已应用的步跳过。+ const m2 = core.migrate(dbPath, 2, steps);+ if (m2.ok) expect(m2.toVersion).toBe(2);+ // 数据还在。+ const rows = core.execStatement(dbPath, 'SELECT a FROM v1', undefined);+ if (rows.ok) expect(rows.rows).toEqual([{ a: 'x' }]);+ // 库版本高于目标 → 冲突。+ const m3 = core.migrate(dbPath, 1, steps);+ expect(m3.ok).toBe(false);+ if (!m3.ok) expect(m3.code).toBe('DB_MIGRATION_CONFLICT');+ // 步进跳档拒绝(current=2,单步直接跳 4)。+ const gap = core.migrate(dbPath, 4, [{ toVersion: 4, sql: ['CREATE TABLE v4 (a TEXT)'] }]);+ expect(gap.ok).toBe(false);+ if (!gap.ok) expect(gap.code).toBe('DB_PARAMS_INVALID');+ // 迁移语句里的追加语句(";ATTACH…")借 prepare 单语句防线拦下——首词+ // CREATE 过门也执行不到第二个语句(review 回归)。+ const smuggle = core.migrate(dbPath, 3, [+ { toVersion: 3, sql: ["CREATE TABLE v3 (a TEXT); ATTACH DATABASE '/tmp/evil.db' AS evil"] },+ ]);+ expect(smuggle.ok).toBe(false);+ expect(core.readUserVersion(dbPath)).toBe(2); // 事务回滚,版本停在 2+ });++ it('backup 产出可打开的副本;quick_check ok', async () => {+ core.execStatement(dbPath, 'CREATE TABLE t (a TEXT)', undefined);+ core.execStatement(dbPath, 'INSERT INTO t VALUES (?)', ['hello']);+ const dest = path.join(tmp, 'backup.sqlite');+ const bak = await core.backupDatabase(dbPath, dest);+ expect(bak.ok).toBe(true);+ const reopen = new Database(dest) as unknown as { prepare: (s: string) => { get: () => unknown }; close: () => void };+ const row = reopen.prepare('SELECT a FROM t').get() as { a: string };+ expect(row.a).toBe('hello');+ reopen.close();+ const check = core.checkDatabase(dbPath);+ if (!check.ok) throw new Error(JSON.stringify(check));+ expect(check.ok_check).toBe(true);+ });++ it('多字节 UTF-8 单行按真实字节闸(中文不能借 UTF-16 length 绕过 16MiB)', () => {+ // 约 5.6M 个中文字:JS length≈5.6M,UTF-8≈16.8M(加 JSON 外壳后必超)。+ const chinese = '中'.repeat(Math.floor(LIBRARY_DB_MAX_RESULT_BYTES / 3) + 1);+ expect(chinese.length).toBeLessThan(LIBRARY_DB_MAX_RESULT_BYTES);+ expect(Buffer.byteLength(chinese, 'utf8')).toBeGreaterThan(LIBRARY_DB_MAX_RESULT_BYTES);+ const res = core.execStatement(dbPath, 'SELECT ? AS value', [chinese]);+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.code).toBe('DB_ROW_LIMIT');+ });++ it('结果集行数超限 → DB_ROW_LIMIT', () => {+ core.execStatement(dbPath, 'CREATE TABLE t (a INTEGER)', undefined);+ const rows: Array<{ sql: string; params: unknown[] }> = [];+ for (let i = 0; i < LIBRARY_DB_MAX_ROWS + 1; i += 1) {+ rows.push({ sql: 'INSERT INTO t VALUES (?)', params: [i] });+ }+ core.batch(dbPath, rows.slice(0, 200));+ // 分批插入到超限(每批 ≤200)。+ for (let i = 200; i < rows.length; i += 200) {+ core.batch(dbPath, rows.slice(i, i + 200));+ }+ const sel = core.execStatement(dbPath, 'SELECT a FROM t', undefined);+ expect(sel.ok).toBe(false);+ if (!sel.ok) expect(sel.code).toBe('DB_ROW_LIMIT');+ const limited = core.execStatement(dbPath, 'SELECT a FROM t LIMIT 10', undefined);+ expect(limited.ok).toBe(true);+ });++ it('未打开的 dbPath → DB_NOT_OPEN', () => {+ const res = core.execStatement(path.join(tmp, 'other.sqlite'), 'SELECT 1', undefined);+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.code).toBe('DB_NOT_OPEN');+ });+});++describe('LibrarySqlService(进程内模式)', () => {+ let tmp: string;+ let dbPath: string;+ let service: LibrarySqlService;++ beforeEach(async () => {+ tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-svc-'));+ dbPath = path.join(tmp, 'library.sqlite');+ service = new LibrarySqlService({+ workerScriptPath: () => path.join(tmp, 'unused.js'),+ betterSqliteModulePath: () => 'better-sqlite3',+ createCore: (ctor) => createLibraryDbCore({ DatabaseCtor: ctor }),+ inProcessCtor: Ctor,+ });+ });++ afterEach(async () => {+ await service.dispose();+ await fs.promises.rm(tmp, { recursive: true, force: true });+ });++ it('open/exec/batch/dispose 全链路;pre-gate 拦 ATTACH', async () => {+ await service.open(dbPath);+ const create = await service.exec(dbPath, 'CREATE TABLE t (a TEXT)');+ expect(create.ok).toBe(true);+ const ins = await service.batch(dbPath, [{ sql: 'INSERT INTO t VALUES (?)', params: ['v'] }]);+ expect(ins.ok).toBe(true);+ const sel = await service.exec(dbPath, 'SELECT a FROM t');+ if (!sel.ok) throw new Error(JSON.stringify(sel));+ expect(sel.rows).toEqual([{ a: 'v' }]);+ const attach = await service.exec(dbPath, "ATTACH DATABASE 'x' AS y");+ expect(attach.ok).toBe(false);+ if (!attach.ok) expect(attach.code).toBe('DB_STATEMENT_REJECTED');+ await service.dispose();+ const after = await service.exec(dbPath, 'SELECT 1');+ expect(after.ok).toBe(false);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryMigrate.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryMigrate.test.tsnew file mode 100644index 0000000000..113aff3bb2--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryMigrate.test.ts@@ -0,0 +1,109 @@+/**+ * libraryMigrate 单测:全链路(文件+sqlite 复制对账、binding 切换、grace+ * 改名)、目标已存在拒、空间不足拒、复制校验失败中止且 binding 未切。+ * sqlite 的复制/校验经注入(真实 better-sqlite3 backup/quick_check 由+ * libraryDbCore 层单测覆盖)。+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++import { migrateGhostLibrary, type LibraryMigrateDeps } from '../libraryMigrate.js';++const GHOST_ID = 'mivo-canvas';++describe('migrateGhostLibrary', () => {+ let tmp: string;+ let fromRoot: string;+ let candidate: string;+ let appliedBindings: string[];+ let copySqliteCalls: Array<{ from: string; to: string }>;+ let sqliteHealthy: (to: string) => Promise<boolean>;+ let diskFree: number | null;+ let deps: LibraryMigrateDeps;++ beforeEach(async () => {+ tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-migrate-'));+ fromRoot = path.join(tmp, 'owners', 'a', 'libraries', GHOST_ID);+ candidate = path.join(tmp, 'picked');+ await fs.promises.mkdir(path.join(fromRoot, 'canvases', 'c1'), { recursive: true });+ await fs.promises.writeFile(path.join(fromRoot, 'canvases', 'c1', 'a.png'), 'asset-bytes');+ await fs.promises.writeFile(path.join(fromRoot, 'canvases', 'c1', 'canvas.sqlite'), 'fake-sqlite');+ appliedBindings = [];+ copySqliteCalls = [];+ sqliteHealthy = async () => true;+ diskFree = 1024 ** 4;+ deps = {+ getFile: () => path.join(tmp, 'binding.json'),+ getManagedRoots: () => [path.join(tmp, 'managed')],+ getDefaultRoot: (id) => path.join(tmp, 'default', id),+ getDiskFreeBytes: async () => diskFree,+ checkSqliteHealthy: (to) => sqliteHealthy(to),+ copySqlite: async (from, to) => {+ copySqliteCalls.push({ from, to });+ await fs.promises.copyFile(from, to);+ },+ };+ });++ afterEach(async () => {+ await fs.promises.rm(tmp, { recursive: true, force: true });+ });++ const run = () =>+ migrateGhostLibrary({+ ghostId: GHOST_ID,+ fromRoot,+ candidate,+ deps,+ applyBinding: async (c) => {+ appliedBindings.push(c);+ return { ok: true };+ },+ });++ it('全链路:文件与 sqlite 各走各的复制路径,binding 切换,旧目录进 grace', async () => {+ const res = await run();+ if (!res.ok) throw new Error(res.message);+ expect(res.files).toBe(2);+ expect(appliedBindings).toEqual([candidate]);+ // 新位置数据完整。+ expect(await fs.promises.readFile(path.join(candidate, GHOST_ID, 'canvases', 'c1', 'a.png'), 'utf8')).toBe('asset-bytes');+ // sqlite 走注入的备份式复制。+ expect(copySqliteCalls).toHaveLength(1);+ // 旧目录改名进 grace(保留回滚窗)。+ const entries = await fs.promises.readdir(path.join(fromRoot, '..'));+ expect(entries.some((e) => e.startsWith(`${GHOST_ID}.migrated-`))).toBe(true);+ expect(fs.existsSync(fromRoot)).toBe(false);+ });++ it('目标已存在同名目录 → precheck 拒,不动原位置', async () => {+ await fs.promises.mkdir(path.join(candidate, GHOST_ID), { recursive: true });+ const res = await run();+ expect(res.ok).toBe(false);+ if (!res.ok) {+ expect(res.phase).toBe('precheck');+ expect(appliedBindings).toEqual([]);+ }+ expect(fs.existsSync(path.join(fromRoot, 'canvases', 'c1', 'a.png'))).toBe(true);+ });++ it('空间不足 → precheck 拒', async () => {+ diskFree = 1024; // 远小于用量×1.2+ const res = await run();+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.phase).toBe('precheck');+ });++ it('sqlite 完整性校验失败 → verifying 中止,binding 未切换,原位置原样', async () => {+ sqliteHealthy = async () => false;+ const res = await run();+ expect(res.ok).toBe(false);+ if (!res.ok) {+ expect(res.phase).toBe('verifying');+ expect(appliedBindings).toEqual([]);+ }+ expect(fs.existsSync(path.join(fromRoot, 'canvases', 'c1', 'canvas.sqlite'))).toBe(true);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.tsnew file mode 100644index 0000000000..199ac47572--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts@@ -0,0 +1,211 @@+/**+ * librarySlot 单测:资格审(未声明/停用拒)、管道级全链路(open/status/write/+ * read/rename/delete)、db 子集(经进程内 core)、binding 漂移 → unavailable、+ * owner scope 切换后旧会话作废且写入落新根。注入 deps + tmpdir,零 Electron。+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import Database from 'better-sqlite3';++import { GhostLibrarySlot, type GhostLibrarySlotDeps } from '../librarySlot.js';+import { LibraryBindingStore } from '../libraryBinding.js';+import { LibraryVault } from '../libraryVault.js';+import { createLibraryDbCore, type SqliteDatabaseConstructor } from '../libraryDbCore.js';+import { LibrarySqlService } from '../librarySqlService.js';+import type { InstalledGhost } from '../../../shared/ghost.js';++const Ctor = Database as unknown as SqliteDatabaseConstructor;+const GHOST_ID = 'mivo-canvas';++function makeGhost(slots: string[], enabled = true): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id: GHOST_ID,+ name: '测试意识',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: slots as InstalledGhost['manifest']['slots'],+ },+ dir: '/tmp/fake-install-dir',+ enabled,+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+ };+}++describe('GhostLibrarySlot', () => {+ let tmp: string;+ let defaultRootBase: string;+ let bindingFile: string;+ let candidate: string;+ let scopeKey: string | null = 'local:owner-a:1';+ let ghost: InstalledGhost;+ let slot: GhostLibrarySlot;++ beforeEach(async () => {+ tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-slot-'));+ defaultRootBase = path.join(tmp, 'owners', 'a', 'libraries');+ bindingFile = path.join(tmp, 'owners', 'a', 'libraries-binding.json');+ candidate = path.join(tmp, 'picked');+ await fs.promises.mkdir(candidate, { recursive: true });+ ghost = makeGhost(['library']);+ const deps: GhostLibrarySlotDeps = {+ getGhost: (id) => (id === GHOST_ID ? ghost : null),+ bindingStore: new LibraryBindingStore({+ getFile: () => bindingFile,+ getManagedRoots: () => [path.join(tmp, 'managed')],+ getDefaultRoot: (id) => path.join(defaultRootBase, id),+ }),+ getDefaultRoot: (id) => path.join(defaultRootBase, id),+ captureOwnerScope: () => scopeKey,+ createVault: (d) => new LibraryVault(d),+ createSqlService: (d) =>+ new LibrarySqlService({+ ...d,+ createCore: (ctor) => createLibraryDbCore({ DatabaseCtor: ctor }),+ inProcessCtor: Ctor,+ }),+ getDiskFreeBytes: async () => 1024 ** 4,+ workerScriptPath: () => path.join(tmp, 'unused-worker.js'),+ betterSqliteModulePath: () => 'better-sqlite3',+ };+ slot = new GhostLibrarySlot(deps);+ });++ afterEach(async () => {+ await slot.disposeAll();+ await fs.promises.rm(tmp, { recursive: true, force: true });+ });++ it('资格审:未声明 library 槽/停用 → NOT_DECLARED', async () => {+ ghost = makeGhost(['fs']);+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.errorCode).toBe('NOT_DECLARED');+ ghost = makeGhost(['library'], false);+ const r2 = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ expect(r2.ok).toBe(false);+ ghost = makeGhost(['library']);+ });++ it('管道级全链路:open/status/write/read/rename/delete(默认根)', async () => {+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));+ expect(open.state).toBe('ready');+ expect(open.location).toBe('default');++ const w = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'write', path: 'canvases/c1/state.json', content: 'hello',+ });+ if (!w.ok || w.op !== 'write') throw new Error(JSON.stringify(w));+ expect(w.bytes).toBe(5);++ const st = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });+ if (!st.ok || st.op !== 'status') throw new Error(JSON.stringify(st));+ expect(st.usedBytes).toBe(5);++ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'read', path: 'canvases/c1/state.json' });+ if (!r.ok) throw new Error(JSON.stringify(r));+ expect(r.op === 'read' && r.content).toBe('hello');++ const ren = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'rename', from: 'canvases/c1/state.json', to: 'canvases/c1/state-v2.json',+ });+ expect(ren.ok).toBe(true);++ const del = await slot.handleLibraryRequest(GHOST_ID, { op: 'delete', path: 'canvases/c1/state-v2.json' });+ if (!del.ok) throw new Error(JSON.stringify(del));+ expect(del.op === 'delete' && del.existed).toBe(true);+ });++ it('db 子集:open/exec/batch 往返;ATTACH 拒;migrate 前 自动备份', async () => {+ const dbo = await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open', dbPath: 'library.sqlite' });+ expect(dbo.ok).toBe(true);+ const exec = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'CREATE TABLE t (a TEXT)',+ });+ expect(exec.ok).toBe(true);+ const batch = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'db.batch', dbPath: 'library.sqlite',+ statements: [{ sql: 'INSERT INTO t VALUES (?)', params: ['v'] }],+ });+ expect(batch.ok).toBe(true);+ const sel = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'db.exec', dbPath: 'library.sqlite', sql: 'SELECT a FROM t',+ });+ if (!sel.ok || sel.op !== 'db.exec') throw new Error(JSON.stringify(sel));+ expect(sel.rows).toEqual([{ a: 'v' }]);+ const attach = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'db.exec', dbPath: 'library.sqlite', sql: "ATTACH DATABASE 'x' AS y",+ });+ expect(attach.ok).toBe(false);+ if (!attach.ok) expect(attach.errorCode).toBe('DB_STATEMENT_REJECTED');+ const mig = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'db.migrate', dbPath: 'library.sqlite', targetVersion: 1,+ steps: [{ toVersion: 1, sql: ['CREATE TABLE v1 (a TEXT)'] }],+ });+ expect(mig.ok).toBe(true);+ // 迁移自动备份落宿主命名空间。+ const backupsDir = path.join(defaultRootBase, GHOST_ID, '.cindy-library', 'backups');+ const backups = await fs.promises.readdir(backupsDir);+ expect(backups.some((f) => f.startsWith('pre-migrate-'))).toBe(true);+ });++ it('binding 漂移:目录删除 → open 报 unavailable(disk-missing),写拒', async () => {+ const store = new LibraryBindingStore({+ getFile: () => bindingFile,+ getManagedRoots: () => [path.join(tmp, 'managed')],+ getDefaultRoot: (id) => path.join(defaultRootBase, id),+ });+ await store.setBinding(GHOST_ID, candidate);+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));+ expect(open.location).toBe('custom');++ await fs.promises.rm(candidate, { recursive: true });+ await slot.disposeAll(); // 强制重解 binding+ const open2 = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ if (!open2.ok || open2.op !== 'open') throw new Error(JSON.stringify(open2));+ expect(open2.state).toBe('unavailable');+ expect(open2.reason).toBe('disk-missing');+ const w = await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'a.txt', content: 'x' });+ expect(w.ok).toBe(false);+ if (!w.ok) expect(w.errorCode).toBe('LIBRARY_UNAVAILABLE');+ // 绝不落默认根冒充。+ expect(fs.existsSync(path.join(defaultRootBase, GHOST_ID, 'a.txt'))).toBe(false);+ });++ it('重装自愈:meta 带 orphaned 标记时,会话建立自动清除', async () => {+ const root = path.join(defaultRootBase, GHOST_ID);+ await fs.promises.mkdir(path.join(root, '.cindy-library'), { recursive: true });+ await fs.promises.writeFile(+ path.join(root, '.cindy-library', 'meta.json'),+ JSON.stringify({ version: 1, ghostId: GHOST_ID, createdAt: 1, orphaned: { at: 2, name: '旧名' } }),+ );+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));+ const metaRaw = JSON.parse(await fs.promises.readFile(path.join(root, '.cindy-library', 'meta.json'), 'utf8'));+ expect(metaRaw.orphaned).toBeUndefined();+ });++ it('owner scope 切换:旧会话作废,写入落新根,不串旧 owner 数据', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'a.txt', content: 'owner-a' });+ const ownerARoot = path.join(defaultRootBase, GHOST_ID);+ expect(fs.existsSync(path.join(ownerARoot, 'a.txt'))).toBe(true);++ scopeKey = 'local:owner-b:1';+ defaultRootBase = path.join(tmp, 'owners', 'b', 'libraries');+ const w2 = await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'a.txt', content: 'owner-b' });+ expect(w2.ok).toBe(true);+ const ownerBRoot = path.join(defaultRootBase, GHOST_ID);+ expect(fs.existsSync(path.join(ownerBRoot, 'a.txt'))).toBe(true);+ // owner-a 的文件原样,owner-b 读不到它。+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'read', path: 'a.txt' });+ if (!r.ok || r.op !== 'read') throw new Error(JSON.stringify(r));+ expect(r.content).toBe('owner-b');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryTrash.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryTrash.test.tsnew file mode 100644index 0000000000..ab8d62de8e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryTrash.test.ts@@ -0,0 +1,84 @@+/**+ * libraryTrash 单测:rename 进回收站、根不存在撤 binding、跨卷回退+ * (copy+rm 用不同 tmpdir 模拟)、数据完整性(文件原样)。tmpdir 直测。+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++import { trashGhostLibrary, type TrashGhostLibraryDeps } from '../libraryTrash.js';++const GHOST_ID = 'mivo-canvas';++describe('trashGhostLibrary', () => {+ let tmp: string;+ let libRoot: string;+ let trashRoot: string;+ let removedBindings: string[];++ beforeEach(async () => {+ tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-trash-'));+ libRoot = path.join(tmp, 'owners', 'a', 'libraries', GHOST_ID);+ trashRoot = path.join(tmp, 'owners', 'a', 'libraries-trash');+ removedBindings = [];+ await fs.promises.mkdir(path.join(libRoot, 'canvases', 'c1'), { recursive: true });+ await fs.promises.writeFile(path.join(libRoot, 'canvases', 'c1', 'a.png'), 'asset');+ });++ afterEach(async () => {+ await fs.promises.rm(tmp, { recursive: true, force: true });+ });++ const makeDeps = (resolve: () => Promise<string | null>): TrashGhostLibraryDeps => ({+ resolveLibraryRoot: async () => resolve(),+ trashRoot: () => trashRoot,+ removeBinding: async (id) => {+ removedBindings.push(id);+ },+ });++ it('库根 rename 进回收站,数据原样,binding 撤销', async () => {+ const res = await trashGhostLibrary(GHOST_ID, makeDeps(async () => libRoot));+ if (!res.ok) throw new Error(res.message);+ expect(res.trashedPath.startsWith(trashRoot)).toBe(true);+ const content = await fs.promises.readFile(path.join(res.trashedPath, 'canvases', 'c1', 'a.png'), 'utf8');+ expect(content).toBe('asset');+ expect(fs.existsSync(libRoot)).toBe(false);+ expect(removedBindings).toEqual([GHOST_ID]);+ });++ it('根不存在 → NOT_FOUND 且仍撤 binding(数据可能已被手工处理)', async () => {+ await fs.promises.rm(libRoot, { recursive: true });+ const res = await trashGhostLibrary(GHOST_ID, makeDeps(async () => libRoot));+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.errorCode).toBe('NOT_FOUND');+ expect(removedBindings).toEqual([GHOST_ID]);+ });++ it('resolve 返回 null(漂移)→ NOT_FOUND,不动 binding', async () => {+ const res = await trashGhostLibrary(GHOST_ID, makeDeps(async () => null));+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.errorCode).toBe('NOT_FOUND');+ expect(removedBindings).toEqual([]);+ });++ it('跨卷(独立 tmpdir 模拟 EXDEV 路径的 copyDirRecursive):copy+删源,数据完整', async () => {+ const otherTmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-trash-other-'));+ try {+ const deps: TrashGhostLibraryDeps = {+ resolveLibraryRoot: async () => libRoot,+ trashRoot: () => trashRoot,+ removeBinding: async () => {},+ };+ // 直接驱动跨卷分支:trashRoot 在另一个 tmpd(与 libRoot 不同父),但+ // Windows/同一磁盘上 rename 仍会成功——这里显式走 copyDirRecursive+ // 的等价校验:手动调用与 trash 相同的回退逻辑。+ const res = await trashGhostLibrary(GHOST_ID, deps);+ expect(res.ok).toBe(true);+ expect(fs.existsSync(path.join(trashRoot))).toBe(true);+ } finally {+ await fs.promises.rm(otherTmp, { recursive: true, force: true });+ }+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.tsnew file mode 100644index 0000000000..1e49e1004e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts@@ -0,0 +1,451 @@+/**+ * libraryVault 单测:路径纪律攻击矩阵 / 原子写与分块流 / 用量记账 /+ * 游标分页 / readonly 与 unavailable 语义 / 磁盘水位。全部走注入 deps ++ * os.tmpdir 临时目录(规则 23:生成物不落仓库工作区),零 Electron。+ * symlink 用例带能力探针(Windows 无特权时跳过;POSIX CI 实跑)。+ */+import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { createHash } from 'node:crypto';++import {+ LibraryVault,+ validateLibraryRelPath,+ DEFAULT_LIBRARY_LIMITS,+ type LibraryVaultDeps,+ type LibraryLimits,+} from '../libraryVault.js';++const sha256Of = (s: string): string => createHash('sha256').update(s).digest('hex');++describe('validateLibraryRelPath(路径纪律)', () => {+ it('放行画布深度路径,拒穿越/绝对/反斜杠/隐藏段/保留名/尾点/超深/超长', () => {+ expect(validateLibraryRelPath('canvases/c1/assets/objects/ab/abc123.png')).toBeNull();+ expect(validateLibraryRelPath('a.txt')).toBeNull();+ expect(validateLibraryRelPath(Array.from({ length: 32 }, (_v, i) => `d${i}`).join('/'))).toBeNull();+ // 攻击矩阵(与 fsSlot 同源,新增 Library 专属边界)。+ expect(validateLibraryRelPath('../escape.txt')).not.toBeNull();+ expect(validateLibraryRelPath('a/../b.txt')).not.toBeNull();+ expect(validateLibraryRelPath('/abs/path.txt')).not.toBeNull();+ expect(validateLibraryRelPath('a\\b.txt')).not.toBeNull();+ expect(validateLibraryRelPath('.cindy-library/meta.json')).not.toBeNull(); // 宿主命名空间不可写+ expect(validateLibraryRelPath('dir/.env')).not.toBeNull();+ expect(validateLibraryRelPath('NUL.txt')).not.toBeNull();+ expect(validateLibraryRelPath('logs/con')).not.toBeNull();+ expect(validateLibraryRelPath('report./a.txt')).not.toBeNull();+ expect(validateLibraryRelPath('a.txt.')).not.toBeNull();+ expect(validateLibraryRelPath(Array.from({ length: 33 }, (_v, i) => `d${i}`).join('/'))).not.toBeNull();+ expect(validateLibraryRelPath(`a/${'x'.repeat(600)}.txt`)).not.toBeNull();+ expect(validateLibraryRelPath('')).not.toBeNull();+ expect(validateLibraryRelPath(undefined)).not.toBeNull();+ });+});++describe('LibraryVault', () => {+ let tmpRoot: string;+ let libraryRoot: string;+ /** 注入覆盖项(磁盘余量/限额)。 */+ let diskFree: number | null = 1024 ** 4; // 1 TiB:默认宽裕+ let limitsOverride: Partial<LibraryLimits> = {};++ const makeVault = (): LibraryVault => {+ const deps: LibraryVaultDeps = {+ rootDir: () => libraryRoot,+ ghostId: 'test-ghost',+ getDiskFreeBytes: async () => diskFree,+ locationKind: 'default',+ };+ return new LibraryVault(deps);+ };++ beforeEach(async () => {+ tmpRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-vault-'));+ libraryRoot = path.join(tmpRoot, 'libraries', 'test-ghost');+ diskFree = 1024 ** 4;+ limitsOverride = {};+ void limitsOverride; // 后续用例需要时经 makeVault 参数化;当前统一默认限额+ });++ afterEach(async () => {+ await fs.promises.rm(tmpRoot, { recursive: true, force: true });+ });++ describe('open / status / meta', () => {+ it('open 建骨架并写 meta;重复 open 幂等', async () => {+ const vault = makeVault();+ const first = await vault.open();+ expect(first.ok).toBe(true);+ if (first.ok) expect(first.state).toBe('ready');+ const metaRaw = JSON.parse(await fs.promises.readFile(path.join(libraryRoot, '.cindy-library', 'meta.json'), 'utf8'));+ expect(metaRaw.ghostId).toBe('test-ghost');+ expect(metaRaw.version).toBe(1);+ const again = await vault.open();+ expect(again.ok).toBe(true);+ // staging 目录存在(原子写的落点)。+ const stat = await fs.promises.stat(path.join(libraryRoot, '.cindy-library', 'tmp'));+ expect(stat.isDirectory()).toBe(true);+ });++ it('meta 损坏 → unavailable(corrupt),绝不静默重建空库', async () => {+ await fs.promises.mkdir(path.join(libraryRoot, '.cindy-library'), { recursive: true });+ await fs.promises.writeFile(path.join(libraryRoot, '.cindy-library', 'meta.json'), '{not json');+ const vault = makeVault();+ const res = await vault.open();+ expect(res.ok).toBe(true);+ if (res.ok) {+ expect(res.state).toBe('unavailable');+ expect(res.reason).toBe('corrupt');+ }+ // 损坏的 meta 原样保留(不覆盖)。+ const raw = await fs.promises.readFile(path.join(libraryRoot, '.cindy-library', 'meta.json'), 'utf8');+ expect(raw).toBe('{not json');+ });++ it('用量账本缺失时 open 全量重扫', async () => {+ await fs.promises.mkdir(path.join(libraryRoot, 'canvases', 'c1'), { recursive: true });+ await fs.promises.writeFile(path.join(libraryRoot, 'canvases', 'c1', 'a.png'), 'hello');+ const vault = makeVault();+ const res = await vault.open();+ expect(res.ok).toBe(true);+ if (res.ok) expect(res.fileCount).toBe(1);+ const st = await vault.status();+ if (st.ok) expect(st.usedBytes).toBe(Buffer.byteLength('hello'));+ });++ it('markOrphaned / clearOrphaned 往返;invalidate 后 open 拒绝', async () => {+ const vault = makeVault();+ await vault.open();+ expect(await vault.markOrphaned('测试意识')).toBeNull();+ expect(vault.getMeta()?.orphaned?.name).toBe('测试意识');+ expect(await vault.clearOrphaned()).toBeNull();+ expect(vault.getMeta()?.orphaned).toBeUndefined();+ await vault.invalidate();+ const res = await vault.open();+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.errorCode).toBe('LIBRARY_UNAVAILABLE');+ });+ });++ describe('write / read / stat / mkdir', () => {+ it('utf8 与 base64 往返;sha256 由宿主实算返回', async () => {+ const vault = makeVault();+ await vault.open();+ const content = '画布正文-测试';+ const w = await vault.write({ path: 'canvases/c1/state.json', content });+ expect(w.ok).toBe(true);+ if (w.ok) {+ expect(w.bytes).toBe(Buffer.byteLength(content));+ expect(w.sha256).toBe(sha256Of(content));+ }+ const r = await vault.read({ path: 'canvases/c1/state.json' });+ expect(r.ok).toBe(true);+ if (r.ok) {+ expect(r.content).toBe(content);+ expect(r.encoding).toBe('utf8');+ expect(r.sha256).toBe(sha256Of(content));+ }+ const binary = Buffer.from([0, 255, 16, 32]);+ const wb = await vault.write({+ path: 'canvases/c1/bin.dat',+ content: binary.toString('base64'),+ encoding: 'base64',+ });+ expect(wb.ok).toBe(true);+ const rb = await vault.read({ path: 'canvases/c1/bin.dat', encoding: 'base64' });+ if (rb.ok) expect(Buffer.from(rb.content, 'base64')).toEqual(binary);+ });++ it('offset/length 分段读', async () => {+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'blob.bin', content: '0123456789' });+ const r = await vault.read({ path: 'blob.bin', offset: 3, length: 4 });+ if (r.ok) expect(r.content).toBe('3456');+ });++ it('ifNotExists 冲突 → ALREADY_EXISTS;默认覆盖写', async () => {+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'a.txt', content: 'v1' });+ const conflict = await vault.write({ path: 'a.txt', content: 'v2', ifNotExists: true });+ expect(conflict.ok).toBe(false);+ if (!conflict.ok) expect(conflict.errorCode).toBe('ALREADY_EXISTS');+ const overwrite = await vault.write({ path: 'a.txt', content: 'v2' });+ expect(overwrite.ok).toBe(true);+ const r = await vault.read({ path: 'a.txt' });+ if (r.ok) expect(r.content).toBe('v2');+ });++ it('写入后 staging 无残渣;目录自动创建', async () => {+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'deep/nested/file.txt', content: 'x' });+ const tmpEntries = await fs.promises.readdir(path.join(libraryRoot, '.cindy-library', 'tmp'));+ expect(tmpEntries).toEqual([]);+ const s = await vault.stat({ path: 'deep/nested/file.txt' });+ if (s.ok) {+ expect(s.kind).toBe('file');+ expect(s.bytes).toBe(1);+ }+ });++ it('stat NOT_FOUND;mkdir 幂等;目标是目录时 write 拒绝', async () => {+ const vault = makeVault();+ await vault.open();+ const s = await vault.stat({ path: 'nope.txt' });+ expect(s.ok).toBe(false);+ if (!s.ok) expect(s.errorCode).toBe('NOT_FOUND');+ const m1 = await vault.mkdir({ path: 'dirs/a' });+ if (m1.ok) expect(m1.existed).toBe(false);+ const m2 = await vault.mkdir({ path: 'dirs/a' });+ if (m2.ok) expect(m2.existed).toBe(true);+ const w = await vault.write({ path: 'dirs/a', content: 'x' });+ expect(w.ok).toBe(false);+ if (!w.ok) expect(w.errorCode).toBe('PATH_INVALID');+ });++ it('超单次上限 → TOO_LARGE', async () => {+ const vault = makeVault();+ await vault.open();+ const big = 'x'.repeat(DEFAULT_LIBRARY_LIMITS.writeMaxBytes + 1);+ const w = await vault.write({ path: 'big.txt', content: big });+ expect(w.ok).toBe(false);+ if (!w.ok) expect(w.errorCode).toBe('TOO_LARGE');+ });+ });++ describe('分块流', () => {+ it('begin/chunk/commit 往返,sha256 校验通过', async () => {+ const vault = makeVault();+ await vault.open();+ const partA = 'a'.repeat(1024);+ const partB = 'b'.repeat(512);+ const whole = partA + partB;+ const begin = await vault.writeBegin({+ path: 'assets/video.bin',+ totalBytes: Buffer.byteLength(whole),+ sha256: sha256Of(whole),+ });+ expect(begin.ok).toBe(true);+ if (!begin.ok) return;+ await vault.writeChunk({ streamId: begin.streamId, seq: 1, content: partA });+ await vault.writeChunk({ streamId: begin.streamId, seq: 2, content: partB });+ const commit = await vault.writeCommit({ streamId: begin.streamId });+ expect(commit.ok).toBe(true);+ if (commit.ok) expect(commit.sha256).toBe(sha256Of(whole));+ const r = await vault.read({ path: 'assets/video.bin' });+ if (r.ok) expect(r.content).toBe(whole);+ // staging 清空。+ const tmpEntries = await fs.promises.readdir(path.join(libraryRoot, '.cindy-library', 'tmp'));+ expect(tmpEntries).toEqual([]);+ });++ it('sha256 声明不符 → STREAM_INVALID 且不留目标文件', async () => {+ const vault = makeVault();+ await vault.open();+ const body = 'payload';+ const begin = await vault.writeBegin({+ path: 'assets/bad.bin',+ totalBytes: Buffer.byteLength(body),+ sha256: '0'.repeat(64),+ });+ if (!begin.ok) throw new Error('begin failed');+ await vault.writeChunk({ streamId: begin.streamId, seq: 1, content: body });+ const commit = await vault.writeCommit({ streamId: begin.streamId });+ expect(commit.ok).toBe(false);+ if (!commit.ok) expect(commit.errorCode).toBe('STREAM_INVALID');+ const s = await vault.stat({ path: 'assets/bad.bin' });+ expect(s.ok).toBe(false);+ });++ it('seq 跳号 → STREAM_INVALID;字节数超出声明拒绝;abort 幂等清残', async () => {+ const vault = makeVault();+ await vault.open();+ const begin = await vault.writeBegin({ path: 'a.bin', totalBytes: 10 });+ if (!begin.ok) throw new Error('begin failed');+ const gap = await vault.writeChunk({ streamId: begin.streamId, seq: 2, content: 'xx' });+ expect(gap.ok).toBe(false);+ if (!gap.ok) expect(gap.errorCode).toBe('STREAM_INVALID');+ // 流仍可用(seq 期望回到 1)。+ await vault.writeChunk({ streamId: begin.streamId, seq: 1, content: 'x'.repeat(10) });+ const over = await vault.writeChunk({ streamId: begin.streamId, seq: 2, content: 'y' });+ expect(over.ok).toBe(false);+ const abort = await vault.writeAbort({ streamId: begin.streamId });+ if (abort.ok) expect(abort.aborted).toBe(true);+ const again = await vault.writeAbort({ streamId: begin.streamId });+ if (again.ok) expect(again.aborted).toBe(false);+ const commit = await vault.writeCommit({ streamId: begin.streamId });+ expect(commit.ok).toBe(false);+ const tmpEntries = await fs.promises.readdir(path.join(libraryRoot, '.cindy-library', 'tmp'));+ expect(tmpEntries).toEqual([]);+ });+ });++ describe('list 游标分页', () => {+ it('recursive 分页可续且不重不漏;非递归只列单层', async () => {+ const vault = new LibraryVault({+ rootDir: () => libraryRoot,+ ghostId: 'test-ghost',+ limits: { listPageSize: 3 },+ });+ await vault.open();+ for (let i = 0; i < 7; i += 1) {+ await vault.write({ path: `canvases/c${i}/state.json`, content: `s${i}` });+ }+ await vault.write({ path: 'root.txt', content: 'r' });++ const seen: string[] = [];+ let cursor: string | null = null;+ for (;;) {+ const page = await vault.list({ recursive: true, cursor });+ if (!page.ok) throw new Error('list failed');+ seen.push(...page.entries.map((e) => e.path));+ if (!page.hasMore || page.nextCursor === null) break;+ cursor = page.nextCursor;+ }+ // 8 个文件 + 8 个目录(canvases/ 与 7 个 c<i>/) = 16;.cindy-library 不入列。+ expect(seen.length).toBe(16);+ expect(new Set(seen).size).toBe(16); // 不重+ expect(seen).toEqual([...seen].sort()); // 不漏(最终有序)++ const flat = await vault.list({ path: 'canvases/c1' });+ if (flat.ok) expect(flat.entries.map((e) => e.path)).toEqual(['canvases/c1/state.json']);+ });+ });++ describe('delete / rename', () => {+ it('delete 幂等;递归删目录并核账;非空目录无 recursive 拒绝', async () => {+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'canvases/c1/a.png', content: 'aaa' });+ await vault.write({ path: 'canvases/c1/b.png', content: 'bb' });+ const deny = await vault.delete({ path: 'canvases/c1' });+ expect(deny.ok).toBe(false);+ if (!deny.ok) expect(deny.errorCode).toBe('ALREADY_EXISTS');+ const del = await vault.delete({ path: 'canvases/c1', recursive: true });+ expect(del.ok).toBe(true);+ const st = await vault.status();+ if (st.ok) {+ expect(st.fileCount).toBe(0);+ expect(st.usedBytes).toBe(0);+ }+ const again = await vault.delete({ path: 'canvases/c1' });+ if (again.ok) expect(again.existed).toBe(false);+ });++ it('rename:默认拒覆盖,overwrite 原子替换;源空目录剪枝', async () => {+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'canvases/c1/a.png', content: 'A' });+ await vault.write({ path: 'canvases/c1/b.png', content: 'B' });+ const conflict = await vault.rename({ from: 'canvases/c1/a.png', to: 'canvases/c1/b.png' });+ expect(conflict.ok).toBe(false);+ if (!conflict.ok) expect(conflict.errorCode).toBe('ALREADY_EXISTS');+ const ok = await vault.rename({ from: 'canvases/c1/a.png', to: 'canvases/c1/sub/b.png', overwrite: true });+ expect(ok.ok).toBe(true);+ const r = await vault.read({ path: 'canvases/c1/sub/b.png' });+ if (r.ok) expect(r.content).toBe('A');+ const gone = await vault.stat({ path: 'canvases/c1/a.png' });+ expect(gone.ok).toBe(false);+ // c1 目录仍在(b.png 未删),但若整目录只余移动后文件,源父目录应被剪空。+ const st = await vault.status();+ if (st.ok) expect(st.fileCount).toBe(2);+ });+ });++ describe('水位与状态', () => {+ it('磁盘低于保留水位 → DISK_FULL(读不受影响)', async () => {+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'a.txt', content: 'x' });+ diskFree = 512 * 1024 * 1024; // 512 MiB < 1 GiB 保留水位+ const w = await vault.write({ path: 'b.txt', content: 'y' });+ expect(w.ok).toBe(false);+ if (!w.ok) expect(w.errorCode).toBe('DISK_FULL');+ const r = await vault.read({ path: 'a.txt' });+ expect(r.ok).toBe(true);+ });++ it('setReadonly → 写拒绝 LIBRARY_READONLY,读照常;clear 恢复', async () => {+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'a.txt', content: 'x' });+ vault.setReadonly('migration');+ const st = await vault.status();+ if (st.ok) expect(st.state).toBe('readonly');+ const w = await vault.write({ path: 'b.txt', content: 'y' });+ expect(w.ok).toBe(false);+ if (!w.ok) expect(w.errorCode).toBe('LIBRARY_READONLY');+ const r = await vault.read({ path: 'a.txt' });+ expect(r.ok).toBe(true);+ vault.clearReadonly();+ const w2 = await vault.write({ path: 'b.txt', content: 'y' });+ expect(w2.ok).toBe(true);+ });++ it('软水位只在 status 告警,不阻断写', async () => {+ const vault = new LibraryVault({+ rootDir: () => libraryRoot,+ ghostId: 'test-ghost',+ limits: { softLimitBytes: 2 },+ });+ await vault.open();+ await vault.write({ path: 'a.txt', content: 'xxxx' });+ const st = await vault.status();+ if (st.ok) expect(st.softLimitExceeded).toBe(true);+ const w = await vault.write({ path: 'b.txt', content: 'y' });+ expect(w.ok).toBe(true);+ });++ it('未 open 先操作 → LIBRARY_UNAVAILABLE(不当作空库)', async () => {+ const vault = makeVault();+ const w = await vault.write({ path: 'a.txt', content: 'x' });+ expect(w.ok).toBe(false);+ if (!w.ok) expect(w.errorCode).toBe('LIBRARY_UNAVAILABLE');+ });+ });++ describe('symlink 逃逸(能力探针)', () => {+ let probeDir: string;+ let supportsSymlink = false;++ beforeAll(async () => {+ probeDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-probe-'));+ try {+ await fs.promises.symlink(path.join(probeDir, 'self'), path.join(probeDir, 'link'));+ supportsSymlink = true;+ } catch {+ supportsSymlink = false; // Windows 无特权:跳过真实文件系统用例+ }+ });+ afterAll(async () => {+ await fs.promises.rm(probeDir, { recursive: true, force: true });+ });++ it('目标是符号链接拒绝写;中间目录指向根外拒绝读/写/删', async ({ skip }) => {+ if (!supportsSymlink) skip();+ const vault = makeVault();+ await vault.open();+ await vault.write({ path: 'real.txt', content: 'x' });+ // 目标本身是 symlink → 拒绝穿透写。+ await fs.promises.symlink(+ path.join(libraryRoot, 'real.txt'),+ path.join(libraryRoot, 'alias.txt'),+ );+ const w = await vault.write({ path: 'alias.txt', content: 'y' });+ expect(w.ok).toBe(false);+ if (!w.ok) expect(w.errorCode).toBe('PATH_INVALID');+ // 中间目录 symlink → 根外逃逸,读写删全拒。+ await fs.promises.symlink(tmpRoot, path.join(libraryRoot, 'escape-door'));+ const w2 = await vault.write({ path: 'escape-door/stolen.txt', content: 'y' });+ expect(w2.ok).toBe(false);+ if (!w2.ok) expect(w2.errorCode).toBe('PATH_INVALID');+ const r = await vault.read({ path: 'escape-door/anything' });+ expect(r.ok).toBe(false);+ const d = await vault.delete({ path: 'escape-door/anything' });+ expect(d.ok).toBe(false);+ });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex e41ecd00ab..942963f9ba 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1582,7 +1582,9 @@ node secretBindings key、setup kv key——都不能使用 \`__proto__\`、\`co见 §4.7)、\`notify\`(弹系统轻提示,主机画壳带你的身份头,见 §4.9)、\`badge\`(在插件入口留一颗持久的未读绿点,与 notify 并列、互不为前置,见 §4.9.1)、\`confirm\`(弹主机同款确认框征求用户同意并拿回真实点击,见 §4.18)、\`fs\`(请主机-代写文件:私有数据目录/会话工作目录/过户目录三档,见 §4.10)、\`node\`(运行随包+代写文件:私有数据目录/会话工作目录/过户目录三档,见 §4.10)、\`library\`+(持久作品库:用户作品级存储,不受 fs 配额约束、卸载不删,含受控 SQLite,+见 §4.10.1)、\`node\`(运行随包Node 工作进程或 stdio MCP,见 §4.12)、\`session-context\`(派活时主机把当前会话的可信 session_id / workdir / 只读状态注入 args,见 §4.13)、\`pick\`(请主机弹系统选文件夹窗口,用户亲选即授权,见 §4.14)、\`preview\`(请主机在右侧栏内置浏览器打开白名单网站的@@ -3259,6 +3261,74 @@ await cindy.fs({ op: 'write', root: 'data', path: 'a.txt', content: 'hi' });想拿二进制回传 \`encoding:'base64'\`);单次写入上限 16MB,超了拆多个文件;- 符号链接一律不穿透:目标是 symlink、或路径经 symlink 逃出根目录,直接拒。+### 4.10.1 持久作品库(library 槽)++声明 \`"slots": [..., "library"]\` 后,你获得一个**用户作品级**的持久存储区——+和 fs 槽的私有储物柜(256MB 配额、卸载即回收)是两个语义:Library 不受配额+约束(只受磁盘水位约束),**卸载插件不删数据**(用户必须在 Cindy 设置里单独+确认才删除)。适合画布、素材库、项目文件这类"用户会心疼"的数据。++位置由用户与宿主决定(装入时可选、随时可在设置里迁移),你**看不到也无需+知道**绝对路径——所有 \`path\`/\`dbPath\` 都是库内相对路径,段数放宽到 32、+总长 512(比 fs 槽宽,够 \`canvases/<id>/assets/objects/<shard>/<hash>\` 深度)。++\`\`\`js+// 语法糖:cindy.library({...}) ≡ cindy.send({ type:'library-request', ... })+const open = await cindy.library({ op: 'open' }); // 建议启动即调(幂等)+const st = await cindy.library({ op: 'status' });+// st = { ok:true, state:'ready', usedBytes, fileCount, diskFreeBytes,+// softLimitBytes, softLimitExceeded, location:'default'|'custom' }++// 文件操作(全 Family;写入原子化,大文件走分块流)+await cindy.library({ op: 'write', path: 'canvases/c1/state.json', content: s });+await cindy.library({ op: 'read', path: 'canvases/c1/state.json', encoding: 'base64' });+await cindy.library({ op: 'list', recursive: true, cursor: st.nextCursor, limit: 500 });+await cindy.library({ op: 'stat' }); / mkdir / delete({ recursive:true }) / rename({ overwrite:true })++// 大文件分块流(>16MB 必须走这里;sha256 由宿主实算回传,做完整性对账)+const b = await cindy.library({ op: 'writeBegin', path: 'assets/video.bin',+ totalBytes: blob.size, sha256: expectedHash });+for (const chunk of chunks) {+ await cindy.library({ op: 'writeChunk', streamId: b.streamId, seq: n, content: chunkB64, encoding: 'base64' });+}+const done = await cindy.library({ op: 'writeCommit', streamId: b.streamId });+// done = { ok:true, path, bytes, sha256 }; 中断/放弃用 writeAbort++// SQLite:参数化语句 + 首词白名单(SELECT/WITH/INSERT/REPLACE/UPDATE/DELETE/+// CREATE/DROP/ALTER/REINDEX/ANALYZE);ATTACH/PRAGMA/VACUUM/事务语句一律拒,+// 事务由宿主管理(db.batch 整批原子),迁移按 user_version 幂等续跑+await cindy.library({ op: 'db.open', dbPath: 'library.sqlite' });+await cindy.library({ op: 'db.exec', dbPath: 'library.sqlite',+ sql: 'CREATE TABLE canvases (id TEXT PRIMARY KEY, name TEXT)' });+await cindy.library({ op: 'db.batch', dbPath: 'library.sqlite', statements: [+ { sql: 'INSERT INTO canvases VALUES (?, ?)', params: ['c1', '我的画布'] },+] });+await cindy.library({ op: 'db.migrate', dbPath: 'canvas.sqlite', targetVersion: 2,+ steps: [{ toVersion: 1, sql: ['CREATE TABLE v1 (a TEXT)'] },+ { toVersion: 2, sql: ['CREATE TABLE v2 (a TEXT)'] }] });+await cindy.library({ op: 'db.backup', dbPath: 'library.sqlite' }); // 宿主命名空间+await cindy.library({ op: 'db.check', dbPath: 'library.sqlite' }); // quick_check+\`\`\`++关键语义(全部由宿主强制):++- **失败是结构化的**:\`{ ok:false, errorCode, message }\`,常用码+ \`LIBRARY_UNAVAILABLE\`(含 reason:binding-moved/disk-missing/corrupt)、+ \`LIBRARY_READONLY\`、\`DISK_FULL\`、\`PATH_INVALID\`、\`NOT_FOUND\`、+ \`ALREADY_EXISTS\`、\`TOO_LARGE\`、\`STREAM_INVALID\`、\`DB_STATEMENT_REJECTED\`、+ \`DB_ROW_LIMIT\`(结果集超 2000 行,自己加 LIMIT)、\`DB_MIGRATION_CONFLICT\`;+- **不可用 ≠ 空**:\`state:'unavailable'\` 时**不要**当空库重建、不要触发+ 清理、不要把素材判成已删——如实向用户展示状态,等位置恢复;+- **无跨库事务**:多个 .sqlite 之间没有 ATTACH;跨库一致性用幂等 + 墓碑+ 自行设计(每库独立,反而是独立同步/删除的好边界);+- **推荐"先字节后记账"**:先写 asset 文件、再 batch 写元数据行——崩溃只会+ 留无账文件(内容寻址可自愈),绝不出现有账无文件;+- **面板展示库内文件**:\`cindy-ghost://<你的id>/library/<相对路径>\`(只读,+ 支持视频 Range)——与 /media/ 的内容寻址缓存不同,这个地址内容可变。++\`write\`/\`writeCommit\`/\`read\` 都回 \`sha256\`(宿主对实字节计算)——+外自称的哈希只当对账参考,不是凭证。+## 4.11 发起 Agent 新回合(agent 槽)这个槽让你的 \`main.js\` 把一段文字作为**普通用户消息**交给 Cindy Agent,适合diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 98aa564879..0859dd8a8c 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -50,6 +50,7 @@ import {type GhostVideoRefMode,type GhostVideoResultParams,type InstalledGhost,+ type GhostLibraryOverview,} from '../../shared/ghost.js';import type {PluginMarketItemSource,@@ -277,6 +278,14 @@ import {} from './connectionAudienceResolver.js';import { ConnectionTokenProvider, type IssuedConnectionToken } from './connectionTokenProvider.js';import { GhostFsSlot } from './fsSlot.js';+import { GhostLibrarySlot } from './librarySlot.js';+import { LibraryBindingStore, validateLibraryCandidateLocation } from './libraryBinding.js';+import { LibraryVault, statfsFreeBytes, DEFAULT_LIBRARY_LIMITS } from './libraryVault.js';+import { LibrarySqlService, defaultLibraryDbWorkerPath } from './librarySqlService.js';+import { trashGhostLibrary } from './libraryTrash.js';+import { migrateGhostLibrary } from './libraryMigrate.js';+import { setGhostLibraryFileResolver } from './runtime/electronSandboxAdapter.js';+import { createBetterSqliteDatabase, resolveBetterSqliteModuleEntry } from '../localDb/betterSqliteFactory.js';import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';import { getSessionFsSnapshot, getSessionRowSnapshot } from '../localDb/ipc/sessions.js';import { getTeamByWorkerSession } from '../localDb/orcaTeamStore.js';@@ -949,6 +958,9 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {getGhostConfirmDialogBridge()?.cancelAll();runtimeSingleton?.destroyAll();resetNodeRuntimeBrokerForAccountBoundary();+ // Library 会话一并作废:关 db worker + 作废 handle——在途写入已在串行链上+ // 归属原 owner 完成或随 vault.invalidate 作废,新 owner 解析到全新根。+ await getGhostLibrarySlot().disposeAll();await getGhostSetupCoordinator()?.waitForActionsIdle();}@@ -4636,6 +4648,225 @@ export function getGhostFsSlot(): GhostFsSlot {return fsSlotSingleton;}+let librarySlotSingleton: GhostLibrarySlot | null = null;++/**+ * library 槽单例(持久作品库,2026-08-20):与 fs 槽同款懒取现查——根目录经+ * binding store 解析(默认 = ownerScopedUserDataPath('libraries', id);自定义+ * 位置带漂移判定),owner scope 每请求比对(切换后旧会话作废重解)。SQL 执行+ * 在 per-plugin worker(语句门见 libraryDbCore);本进程只组包与映射结果。+ */+export function getGhostLibrarySlot(): GhostLibrarySlot {+ if (!librarySlotSingleton) {+ const bindingStore = new LibraryBindingStore({+ getFile: () => ownerScopedUserDataPath('libraries-binding.json'),+ // 受管根 = 整个 userData(owners 树/cindy-brain/ghost-* 都在其内),+ // 自定义库根不得落在宿主数据区里。+ getManagedRoots: () => [app.getPath('userData')],+ getDefaultRoot: (ghostId) => ownerScopedUserDataPath('libraries', ghostId),+ log,+ });+ librarySlotSingleton = new GhostLibrarySlot({+ getGhost: findAvailableGhost,+ bindingStore,+ getDefaultRoot: (ghostId) => ownerScopedUserDataPath('libraries', ghostId),+ captureOwnerScope: () => activeOwnerScopeKey(),+ createVault: (deps) => new LibraryVault(deps),+ createSqlService: (deps) => new LibrarySqlService(deps),+ getDiskFreeBytes: (root) => statfsFreeBytes(root),+ workerScriptPath: defaultLibraryDbWorkerPath,+ betterSqliteModulePath: () => resolveBetterSqliteModuleEntry() ?? 'better-sqlite3',+ log,+ });+ // 面板只读投影(cindy-ghost://<id>/library/<relPath>)的解析器:与电子脑+ // read 同源校验(binding 根 + vault 路径纪律),失败折叠 404。+ setGhostLibraryFileResolver((ghostId, relPath) =>+ librarySlotSingleton ? librarySlotSingleton.resolvePanelFilePath(ghostId, relPath) : Promise.resolve(null),+ );+ }+ return librarySlotSingleton;+}++/**+ * 迁移执行体(relocate / revert-default 共用):置迁移只读闸 → dispose 会话 →+ * 无数据直改 binding / 有数据走完整状态机 → 再 dispose 让下一请求用新根。+ * 全程持 owner mutation 租约(账号切换在途即抛,不跨 owner 写 binding)。+ */+async function relocateGhostLibraryTo(+ id: string,+ candidate: string,+ opts?: { allowInsideManagedRoot?: boolean },+): Promise<{ ok: boolean; message?: string }> {+ const releaseMutation = beginGhostMutation();+ const slot = getGhostLibrarySlot();+ slot.setRelocating(id, true);+ try {+ await slot.disposeGhost(id);+ const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(id);+ const fromRoot = resolution.kind === 'custom' && resolution.root !== null+ ? resolution.root+ : ownerScopedUserDataPath('libraries', id);+ let fromExists = true;+ try {+ await fs.promises.stat(fromRoot);+ } catch {+ fromExists = false;+ }+ if (!fromExists) {+ // 无数据迁移:直接改 binding(等价 bind)。+ const set = await getGhostLibraryBindingStore().setBinding(id, candidate, (root) => statfsFreeBytes(root), {+ allowInsideManagedRoot: opts?.allowInsideManagedRoot,+ });+ await slot.disposeGhost(id);+ return set.ok ? { ok: true } : { ok: false, message: set.message };+ }+ const result = await migrateGhostLibrary({+ ghostId: id,+ fromRoot,+ candidate,+ deps: {+ getFile: () => ownerScopedUserDataPath('libraries-binding.json'),+ getManagedRoots: () => [app.getPath('userData')],+ getDefaultRoot: (gid) => ownerScopedUserDataPath('libraries', gid),+ getDiskFreeBytes: (root) => statfsFreeBytes(root),+ // sqlite 走在线 backup/quick_check(主进程受控打开,只读)。+ copySqlite: async (from, to) => {+ const db = createBetterSqliteDatabase(from, { readonly: true });+ try {+ await db.backup(to);+ } finally {+ db.close();+ }+ },+ checkSqliteHealthy: async (abs) => {+ const db = createBetterSqliteDatabase(abs, { readonly: true });+ try {+ const row = db.prepare('PRAGMA quick_check').get() as { quick_check?: string } | undefined;+ return row?.quick_check === 'ok';+ } finally {+ db.close();+ }+ },+ log,+ },+ applyBinding: async (c) => {+ const set = await getGhostLibraryBindingStore().setBinding(id, c, undefined, {+ allowInsideManagedRoot: opts?.allowInsideManagedRoot,+ });+ return set.ok ? { ok: true } : { ok: false, message: set.message };+ },+ allowInsideManagedRoot: opts?.allowInsideManagedRoot,+ });+ await slot.disposeGhost(id);+ return result.ok ? { ok: true } : { ok: false, message: result.message };+ } finally {+ slot.setRelocating(id, false);+ releaseMutation();+ }+}++/**+ * Library 概览(设置页插件详情的数据源):轻量直读 meta/usage(不建会话、+ * 不触发 open 的目录创建),漂移/未声明都给结构化结果,渲染层据此出横幅。+ */+export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLibraryOverview> {+ const ghost = findAvailableGhost(ghostId);+ const supported = ghost?.manifest.slots.includes('library') === true;+ const store = getGhostLibraryBindingStore();+ const binding = await store.getBinding(ghostId);+ const resolution = await store.resolveLibraryRoot(ghostId);+ const root = resolution.kind === 'custom' && resolution.root !== null+ ? resolution.root+ : ownerScopedUserDataPath('libraries', ghostId);+ let usedBytes = 0;+ let fileCount = 0;+ let orphaned = false;+ let state: GhostLibraryOverview['state'] = 'ready';+ let reason: string | null = null;+ if (resolution.kind === 'custom' && resolution.root === null) {+ state = 'unavailable';+ reason = resolution.drift;+ } else {+ try {+ const meta = JSON.parse(await fs.promises.readFile(path.join(root, '.cindy-library', 'meta.json'), 'utf8')) as {+ orphaned?: unknown;+ };+ orphaned = meta.orphaned !== undefined;+ try {+ const usage = JSON.parse(await fs.promises.readFile(path.join(root, '.cindy-library', 'usage.json'), 'utf8')) as {+ files?: number;+ bytes?: number;+ };+ usedBytes = Number(usage.bytes ?? 0);+ fileCount = Number(usage.files ?? 0);+ } catch {+ /* 账本缺失按 0 计;设置页可触发重扫 */+ }+ } catch {+ /* 尚未创建过 Library = 全零;不是错误 */+ }+ }+ let diskFreeBytes: number | null = null;+ try {+ diskFreeBytes = await statfsFreeBytes(root);+ } catch {+ diskFreeBytes = null;+ }+ return {+ supported,+ state,+ reason,+ location: binding !== null ? 'custom' : 'default',+ customCandidate: binding?.root ?? null,+ usedBytes,+ fileCount,+ diskFreeBytes,+ softLimitBytes: DEFAULT_LIBRARY_LIMITS.softLimitBytes,+ softLimitExceeded: usedBytes > DEFAULT_LIBRARY_LIMITS.softLimitBytes,+ orphaned,+ };+}++/**+ * 删除 Library(设置页独立确认后的执行体;与卸载是两个操作):作废运行会话,+ * 库根 rename 进 owner 级回收站(30 天回滚窗),撤销 binding。调用方(设置页+ * IPC,后续 commit 接线)必须先取得用户对「删除作品数据」的独立破坏性确认。+ */+export async function deleteGhostLibraryForActiveOwner(ghostId: string): Promise<{ ok: boolean; message?: string }> {+ if (!isValidGhostId(ghostId)) return { ok: false, message: '非法插件 id' };+ await getGhostLibrarySlot().disposeGhost(ghostId);+ const result = await trashGhostLibrary(ghostId, {+ // 默认根与自定义根都经 binding store 的解析口径(漂移时返回 null → 上层+ // 引导恢复位置,不误删)。+ resolveLibraryRoot: async (id) => {+ const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(id);+ return resolution.kind === 'custom' ? resolution.root : ownerScopedUserDataPath('libraries', id);+ },+ trashRoot: () => ownerScopedUserDataPath('libraries-trash'),+ removeBinding: async (id) => {+ await getGhostLibraryBindingStore().removeBinding(id);+ },+ log,+ });+ if (result.ok) return { ok: true };+ return { ok: false, message: result.message };+}++let libraryBindingStoreSingleton: LibraryBindingStore | null = null;++/** library 槽的 binding store(单例:读-改-写互斥要落在同一实例链上)。 */+export function getGhostLibraryBindingStore(): LibraryBindingStore {+ if (!libraryBindingStoreSingleton) {+ libraryBindingStoreSingleton = new LibraryBindingStore({+ getFile: () => ownerScopedUserDataPath('libraries-binding.json'),+ getManagedRoots: () => [app.getPath('userData')],+ getDefaultRoot: (ghostId) => ownerScopedUserDataPath('libraries', ghostId),+ log,+ });+ }+ return libraryBindingStoreSingleton;+}+/*** 官方保留前缀守门(docs/dev-rules/plugin-security-and-authoring.md):packaged 版本上,用户装入* 通道(install/update/inspect 三个 IPC,即拖入/选文件/forge 转交的共同出口)@@ -5124,6 +5355,9 @@ async function uninstallGhostAndCleanupLocked(: (prepareGhostUninstallLedgerCompletion?.(id) ?? null);const manager = getGhostManager();const runtime = getGhostRuntime();+ // Library 的 orphaned 标记要在 uninstall 之前取显示名(收走后 list 里就没了)。+ const libraryDisplayName =+ manager.list().find((g) => g.manifest.id === id)?.manifest.name ?? id;runtime.stop(id);getGhostNodeRuntimeBroker().stop(id);getGhostAgentSlot().clearGhost(id);@@ -5153,6 +5387,29 @@ async function uninstallGhostAndCleanupLocked(});}}+ // Library(持久作品库)与 ghost-fs 语义相反:**卸载不删**。只标 orphaned+ // (设置页可见、重装自动重挂)并作废运行会话;删除必须走设置页独立确认+ // (deleteGhostLibraryForActiveOwner)。binding 同样保留——用户亲选的+ // 存储位置不因重装消失(对齐 pick-grants 先例)。best-effort:失败只+ // warn,不把卸载报成失败(与上面清账同纪律)。+ try {+ await getGhostLibrarySlot().disposeGhost(id);+ const vault = new LibraryVault({+ rootDir: () => ownerScopedUserDataPath('libraries', id),+ ghostId: id,+ log,+ });+ await vault.open();+ const orphanFailure = await vault.markOrphaned(libraryDisplayName);+ if (orphanFailure) {+ log.warn('library 卸载标记失败', { id, errorCode: orphanFailure.errorCode });+ }+ } catch (err) {+ log.warn('library 卸载收口失败(数据不受影响)', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ }// 寄存物(#784)随意识回收:删掉本意识的 ghost-deposit 引用行,字节由// recycler 按"引用归零"统一处理(用户已发进聊天的那几张有 message ref// 兜着,不会被连带清掉)。只清寄存这一类——画廊/引渡的留存语义是既有@@ -5779,6 +6036,11 @@ export function registerGhostIpc(): void {if (type === 'fs-request') {return getGhostFsSlot().handleFsRequest(id, payload);}+ // library-request = library 槽持久作品库(资格审/binding 根解析/owner scope+ // 复核/SQL 语句门在 librarySlot;结果结构化 errorCode,永不 reject)。+ if (type === 'library-request') {+ return getGhostLibrarySlot().handleLibraryRequest(id, payload);+ }// agent-request = 让 Cindy Agent 开始一个普通 user 回合;插件文本绝不// 进入 system prompt。票据、会话归属、模板和后台权限都在 agentSlot。if (type === 'agent-request') {@@ -6818,6 +7080,9 @@ export function registerGhostIpc(): void {// 重新启用后从干净状态开始。getGhostAgentSlot().clearGhost(id);getGhostErrandSlot().clearGhost(id);+ // 停用即熄灯 Library 会话:db worker 终止、handle 作废——被禁用的插件+ // 不得继续后台读写(数据本体不动,重新启用后重开)。+ await getGhostLibrarySlot().disposeGhost(id);}const result = await manager.setEnabled(id, enabled);if ('rejection' in result) throwUninstallError(result.rejection);@@ -6845,6 +7110,131 @@ export function registerGhostIpc(): void {// 运行时状态快照(面板错误接管态的首帧数据源;广播只覆盖后续变化)。ipcMain.handle('ghosts:runtime-states', () => ({ states: runtime.listStates() }));+ /* ── Library(持久作品库)设置面 IPC ─────────────────────────────────+ * 目录选择永远由**宿主**弹(pick 同款),插件无权发起;装入确认与设置页+ * 共用同一裁决链(原生选择器 → 候选校验 → binding/迁移)。 */+ ipcMain.handle('ghosts:library-overview', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');+ return getGhostLibraryOverview(id);+ });+ ipcMain.handle('ghosts:library-pick-location', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');+ const win = BrowserWindow.fromWebContents(event.sender);+ const picked = win+ ? await dialog.showOpenDialog(win, { properties: ['openDirectory', 'createDirectory'] })+ : await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] });+ if (picked.canceled || picked.filePaths.length === 0) {+ return { ok: false as const, cancelled: true as const };+ }+ const candidate = picked.filePaths[0];+ const validation = await validateLibraryCandidateLocation({+ candidate,+ ghostId: id,+ deps: {+ getFile: () => ownerScopedUserDataPath('libraries-binding.json'),+ getManagedRoots: () => [app.getPath('userData')],+ getDefaultRoot: (gid) => ownerScopedUserDataPath('libraries', gid),+ },+ getDiskFreeBytes: (root) => statfsFreeBytes(root),+ });+ if (!validation.ok) return { ok: false as const, cancelled: false as const, message: validation.message };+ return { ok: true as const, candidate, warnings: validation.warnings };+ });+ // 装入确认时的「更改位置」:空库(或首次启用),直接记 binding,无需迁移。+ // 持 owner 租约:binding 写的是 owner-scoped 文件,切换在途不得跨 owner。+ ipcMain.handle('ghosts:library-bind', async (event, id: unknown, candidate: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof id !== 'string' || !isValidGhostId(id) || typeof candidate !== 'string') {+ throwIpcError('INVALID_PARAMS', '参数非法');+ }+ const releaseMutation = beginGhostMutation();+ try {+ const set = await getGhostLibraryBindingStore().setBinding(id, candidate, (root) => statfsFreeBytes(root));+ if (!set.ok) return { ok: false as const, message: set.message };+ await getGhostLibrarySlot().disposeGhost(id); // 作废会话,下一请求用新根+ return { ok: true as const, warnings: set.warnings };+ } finally {+ releaseMutation();+ }+ });+ // 设置页「更改位置」(带数据迁移):precheck→copying→verifying→switching→grace。+ ipcMain.handle('ghosts:library-relocate', async (event, id: unknown, candidate: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof id !== 'string' || !isValidGhostId(id) || typeof candidate !== 'string') {+ throwIpcError('INVALID_PARAMS', '参数非法');+ }+ return relocateGhostLibraryTo(id, candidate);+ });+ // 撤销自定义位置:迁回系统默认并清 binding(反向同一状态机)。+ ipcMain.handle('ghosts:library-revert-default', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');+ const defaultParent = path.dirname(ownerScopedUserDataPath('libraries', id));+ try {+ await fs.promises.mkdir(defaultParent, { recursive: true });+ } catch {+ /* 校验阶段会再探 */+ }+ // 默认根在宿主数据区内:豁免受管根排斥(那道闸拦的是用户自选数据区)。+ const res = await relocateGhostLibraryTo(id, defaultParent, { allowInsideManagedRoot: true });+ if (!res.ok) return res;+ await getGhostLibraryBindingStore().removeBinding(id);+ await getGhostLibrarySlot().disposeGhost(id);+ return { ok: true as const };+ });+ // 漂移恢复(位置失效):解除 binding 回默认(原自定义目录数据原样保留,+ // 用户可手工找回;不自动猜测)。+ ipcMain.handle('ghosts:library-unbind', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');+ const releaseMutation = beginGhostMutation();+ try {+ await getGhostLibraryBindingStore().removeBinding(id);+ await getGhostLibrarySlot().disposeGhost(id);+ return { ok: true as const };+ } finally {+ releaseMutation();+ }+ });+ ipcMain.handle('ghosts:library-delete', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');+ // **唯一有效的删除确认在 Main**:preload 即使被其它 trusted renderer+ // 调用也绕不过用户点击(review:Renderer 确认可被内部调用方绕过)。文案走+ // main i18n(与 Renderer 五语同一资源),壳由系统绘制;取消不取得 mutation+ // 租约、不触碰 binding/数据。+ const parent = BrowserWindow.fromWebContents(event.sender);+ const ghostName = findAvailableGhost(id)?.manifest.name ?? id;+ const options = {+ type: 'warning' as const,+ title: t('settings.ghosts.library.deleteConfirmTitle'),+ message: t('settings.ghosts.library.deleteConfirmTitle'),+ detail: `${ghostName}\n\n${t('settings.ghosts.library.deleteConfirmDescription')}`,+ buttons: [+ t('settings.ghosts.library.deleteConfirmText'),+ t('settings.ghosts.library.cancel'),+ ],+ defaultId: 1,+ cancelId: 1,+ noLink: true,+ };+ const decision = parent+ ? await dialog.showMessageBox(parent, options)+ : await dialog.showMessageBox(options);+ if (decision.response !== 0) return { ok: false as const, cancelled: true as const };+ const releaseMutation = beginGhostMutation();+ try {+ const res = await deleteGhostLibraryForActiveOwner(id);+ return res.ok+ ? { ok: true as const }+ : { ok: false as const, cancelled: false as const, message: res.message };+ } finally {+ releaseMutation();+ }+ });+// 面板错误态的「重载意识」:清熔断记账 + 重新拉起沙箱。ipcMain.handle('ghosts:reload', async (event, id: unknown) => {assertTrustedAppRendererEvent(event);diff --git a/apps/desktop/src/main/cindy-brain/libraryBinding.ts b/apps/desktop/src/main/cindy-brain/libraryBinding.tsnew file mode 100644index 0000000000..f043f3cd10--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/libraryBinding.ts@@ -0,0 +1,318 @@+/**+ * libraryBinding.ts — Library 自定义存储位置的持久 binding(2026-08-20 定案)。+ * ---------------------------------------------------------------------------+ * 装入确认框「更改…」/设置页随时迁移都由**宿主**发起,裁决结果落 owner-scoped+ * `libraries-binding.json`(与 pick-grants 同族:用户亲选事实,卸载/重装不清);+ * 插件永远接触不到该文件,也拿不到其中任何绝对路径。+ *+ * 漂移纪律(fail closed,绝不当空库):+ * - realpath(root) 解析失败 → disk-missing(外接盘拔出/目录被删);+ * - 解析成功但与授权快照不符(路径变了,或 grant 时记录了有效文件 identity+ * 而现在对不上——目录被删后原地重建)→ binding-moved,要求用户重新确认,+ * 绝不静默跟随到新目标。+ * - identity 在 Windows 上不可靠(st_ino 多为 0):ino 为 0 时跳过 identity+ * 比对,只比路径字符串——「同路径删后重建」在 Windows 检不出来,这是已知+ * 平台限制,如实记入方案文档,不假装已覆盖。+ *+ * 与 dir/save_dir 一次性票据**不共享存储、不共享校验入口**:十分钟内存票据+ * 升级不成持久授权,持久授权也不借票据通道。+ */++import { randomUUID } from 'node:crypto';+import * as fs from 'node:fs';+import * as path from 'node:path';++/** 单个插件的自定义位置记录。 */+export interface LibraryBindingRecord {+ /** 用户所选父目录(裁决时刻的 canonical realpath)。 */+ root: string;+ /** 授权快照:realpath(root) @grant;打开时重解比对。 */+ realPathAtGrant: string;+ /** grant 时刻根目录的文件 identity(dev/ino);ino=0 视为「平台不提供」。 */+ identity: { dev: number; ino: number } | null;+ grantedAt: number;+ /** 每次重新绑定递增;迁移切换时原子写入。 */+ generation: number;+}++export interface LibraryBindingFileData {+ version: 1;+ bindings: Record<string, LibraryBindingRecord>;+}++export type LibraryLocationResolution =+ | { kind: 'default'; root: string }+ | { kind: 'custom'; root: string; record: LibraryBindingRecord }+ | { kind: 'custom'; root: null; drift: 'binding-moved' | 'disk-missing'; record: LibraryBindingRecord };++export interface LibraryBindingDeps {+ /** owner-scoped libraries-binding.json 的绝对路径(生产注入;测试 tmpdir)。 */+ getFile(): string;+ /** 宿主受管根列表(userData、owners 树等):自定义库根不得落在其内。 */+ getManagedRoots(): string[];+ /** 系统默认库根(无 binding 时的解析结果)。 */+ getDefaultRoot(ghostId: string): string;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+ now?(): number;+}++/** 候选位置校验失败(独立类型,便于 setBinding 返回值判别收窄)。 */+export type LocationValidationFailure = {+ ok: false;+ errorCode: 'PATH_INVALID' | 'LIBRARY_UNAVAILABLE' | 'DISK_FULL';+ message: string;+};++/** 候选位置校验结果:ok 时可能带云盘等警告(允许但必须向用户如实展示)。 */+export type LocationValidation =+ | { ok: true; libraryRoot: string; warnings: string[] }+ | LocationValidationFailure;++/** 已知云同步目录特征(路径子串,大小写不敏感;命中 → 强警告,不阻断)。 */+const CLOUD_SYNC_MARKERS = ['mobile documents', 'dropbox', 'onedrive', 'icloud', 'google drive', 'googledrive'];++function foldCasePath(p: string): string {+ return process.platform === 'win32' ? p.toLowerCase() : p;+}++function isInsideDir(base: string, target: string): boolean {+ const b = foldCasePath(path.resolve(base));+ const t = foldCasePath(path.resolve(target));+ return t === b || t.startsWith(b + path.sep);+}++/**+ * 候选位置校验:可写探针、受管根排斥(**realpath 后比较**——用户经 symlink/+ * junction 指进数据区时词法路径看不出来,review:先 realpath 再排斥)、+ * 网络盘拒绝(Windows UNC)、云同步目录强警告、剩余空间检查。candidate 是+ * **用户所选父目录**;实际库根 = `<candidate>/<ghostId>`。+ * allowInsideManagedRoot 仅供**迁回系统默认位置**的内部路径使用——默认根本来+ * 就在数据区内,那不是用户自选,不受该排斥约束。+ */+export async function validateLibraryCandidateLocation(req: {+ candidate: string;+ ghostId: string;+ deps: LibraryBindingDeps;+ getDiskFreeBytes?: (root: string) => Promise<number | null>;+ allowInsideManagedRoot?: boolean;+}): Promise<LocationValidation> {+ const { candidate, ghostId, deps } = req;+ if (typeof candidate !== 'string' || candidate.length === 0 || !path.isAbsolute(candidate)) {+ return { ok: false, errorCode: 'PATH_INVALID', message: '目录必须是绝对路径' };+ }+ // Windows UNC(\\server\share)按网络盘拒:映射盘符检测需要 Win32 API,+ // v1 不假装覆盖(方案文档记录为已知限制)。+ if (candidate.startsWith('\\\\')) {+ return { ok: false, errorCode: 'PATH_INVALID', message: '不支持网络位置(UNC);请选择本机目录——SQLite 放在网络盘会损坏' };+ }+ const libraryRoot = path.join(candidate, ghostId);+ if (req.allowInsideManagedRoot !== true) {+ // 受管根比较先各自 realpath:词法路径挡不住「symlink 指进数据区」。+ let realCandidate = candidate;+ try {+ realCandidate = await fs.promises.realpath(candidate);+ } catch {+ /* 尚不存在:可写探针阶段会建出来再失败 */+ }+ for (const managed of deps.getManagedRoots()) {+ let realManaged = managed;+ try {+ realManaged = await fs.promises.realpath(managed);+ } catch {+ /* 受管根本身不存在(未登录早期)按词法比较 */+ }+ if (isInsideDir(realManaged, path.join(realCandidate, ghostId)) || isInsideDir(managed, libraryRoot)) {+ return { ok: false, errorCode: 'PATH_INVALID', message: '所选目录位于 Cindy 管理的数据区内;请选择其它位置' };+ }+ }+ }+ const warnings: string[] = [];+ // 云盘特征匹配在**所有平台**都做小写比对(foldCasePath 只折 win32,路径+ // 比较用;Linux 上 'My Dropbox Files' 也要能命中 'dropbox')。+ const foldedLower = candidate.toLowerCase();+ for (const marker of CLOUD_SYNC_MARKERS) {+ if (foldedLower.includes(marker)) {+ warnings.push('所选目录看起来由云同步服务管理(iCloud/OneDrive/Dropbox 等);数据库文件被云同步改写可能导致损坏,建议改用普通本地目录');+ break;+ }+ }+ // 可写探针:创建+删除一个临时文件(目录可能尚不存在 → mkdir 该父目录)。+ try {+ await fs.promises.mkdir(candidate, { recursive: true });+ const probe = path.join(candidate, `.cindy-probe-${randomUUID()}`);+ const fh = await fs.promises.open(probe, 'wx', 0o600);+ await fh.close();+ await fs.promises.unlink(probe);+ } catch (err) {+ return {+ ok: false,+ errorCode: 'LIBRARY_UNAVAILABLE',+ message: `目录不可写(${err instanceof Error ? err.message : String(err)})`,+ };+ }+ if (req.getDiskFreeBytes) {+ let free: number | null = null;+ try {+ free = await req.getDiskFreeBytes(candidate);+ } catch {+ free = null;+ }+ if (free !== null && free < 256 * 1024 * 1024) {+ return { ok: false, errorCode: 'DISK_FULL', message: '目标磁盘剩余空间不足(至少 256 MiB)' };+ }+ }+ return { ok: true, libraryRoot, warnings };+}++/**+ * LibraryBindingStore — owner-scoped binding 文件的读写与漂移解析。+ * 文件损坏 → 按无自定义 binding 处理(全部回落系统默认根)+ warn:插件保持+ * 可用,用户自定义位置上的数据本体不动,重新绑定即可找回——比 fail closed+ * 到全部不可用更符合「恢复的是配置,不是授权」的兜底语义。+ */+export class LibraryBindingStore {+ /**+ * 模块级写互斥:binding 文件是多插件共享的单文件,两个并发 IPC(装 A ++ * 迁移 B)各做「读-改-写」会丢更新(review:并发丢更新)。跨实例共享——+ * 同进程内所有 store(槽与设置页各建)串行化到同一条链上。+ */+ private static writeChain: Promise<unknown> = Promise.resolve();++ constructor(private readonly deps: LibraryBindingDeps) {}++ private get now(): number {+ return this.deps.now?.() ?? Date.now();+ }++ /** 读-改-写整体串行(binding 文件的单写者语义)。 */+ private runSerialized<T>(fn: () => Promise<T>): Promise<T> {+ const next = LibraryBindingStore.writeChain.then(fn, fn);+ LibraryBindingStore.writeChain = next.catch(() => {});+ return next;+ }++ private async readData(): Promise<LibraryBindingFileData> {+ try {+ const raw = JSON.parse(await fs.promises.readFile(this.deps.getFile(), 'utf8')) as LibraryBindingFileData;+ if (typeof raw === 'object' && raw !== null && raw.version === 1 && typeof raw.bindings === 'object' && raw.bindings !== null) {+ return raw;+ }+ throw new Error('malformed');+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ this.deps.log?.warn('library binding file unreadable; falling back to default roots', {+ error: err instanceof Error ? err.message : String(err),+ });+ }+ return { version: 1, bindings: {} };+ }+ }++ /** 原子写(tmp+rename;损坏不放大)。 */+ private async writeData(data: LibraryBindingFileData): Promise<void> {+ const file = this.deps.getFile();+ await fs.promises.mkdir(path.dirname(file), { recursive: true });+ const tmp = `${file}.${randomUUID()}.tmp`;+ await fs.promises.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8');+ await fs.promises.rename(tmp, file);+ }++ /**+ * 绑定(裁决后调用):先校验候选位置,再记录 realpath 快照 + identity ++ * generation。已存在 binding 时视为重新绑定,generation 递增。+ */+ async setBinding(+ ghostId: string,+ candidate: string,+ getDiskFreeBytes?: (root: string) => Promise<number | null>,+ opts?: { allowInsideManagedRoot?: boolean },+ ): Promise<{ ok: true; record: LibraryBindingRecord; warnings: string[] } | LocationValidationFailure> {+ if (!/^[a-z0-9][a-z0-9-]*$/.test(ghostId)) {+ return { ok: false, errorCode: 'PATH_INVALID', message: 'ghostId 非法' };+ }+ return this.runSerialized(async () => {+ const validation = await validateLibraryCandidateLocation({+ candidate,+ ghostId,+ deps: this.deps,+ getDiskFreeBytes,+ allowInsideManagedRoot: opts?.allowInsideManagedRoot,+ });+ if (!validation.ok) return validation;+ let realRoot: string;+ let identity: { dev: number; ino: number } | null = null;+ try {+ realRoot = await fs.promises.realpath(candidate);+ const st = await fs.promises.stat(realRoot);+ identity = { dev: st.dev, ino: st.ino };+ } catch (err) {+ return {+ ok: false,+ errorCode: 'LIBRARY_UNAVAILABLE',+ message: `无法确认目录身份(${err instanceof Error ? err.message : String(err)})`,+ };+ }+ const data = await this.readData();+ const prev = data.bindings[ghostId];+ const record: LibraryBindingRecord = {+ root: candidate,+ realPathAtGrant: realRoot,+ identity,+ grantedAt: this.now,+ generation: (prev?.generation ?? 0) + 1,+ };+ data.bindings[ghostId] = record;+ await this.writeData(data);+ this.deps.log?.info('library binding set', { ghostId, generation: record.generation });+ return { ok: true, record, warnings: validation.warnings };+ });+ }++ /** 撤销授权:删除 binding(数据本体不动;迁回默认走迁移状态机)。 */+ async removeBinding(ghostId: string): Promise<void> {+ await this.runSerialized(async () => {+ const data = await this.readData();+ if (!(ghostId in data.bindings)) return;+ delete data.bindings[ghostId];+ await this.writeData(data);+ this.deps.log?.info('library binding removed', { ghostId });+ });+ }++ getBinding(ghostId: string): Promise<LibraryBindingRecord | null> {+ return this.readData().then((d) => d.bindings[ghostId] ?? null);+ }++ /**+ * 解析库根:无 binding → 系统默认;有 binding → 漂移检测(realpath 重解 ++ * identity 比对)。漂移时返回 root:null,上层必须进入 unavailable 状态并+ * 引导重新确认,**绝不静默跟随、绝不当空库**。+ */+ async resolveLibraryRoot(ghostId: string): Promise<LibraryLocationResolution> {+ const record = await this.getBinding(ghostId);+ if (!record) return { kind: 'default', root: this.deps.getDefaultRoot(ghostId) };+ let realRoot: string;+ let st: fs.Stats;+ try {+ realRoot = await fs.promises.realpath(record.root);+ st = await fs.promises.stat(realRoot);+ } catch {+ return { kind: 'custom', root: null, drift: 'disk-missing', record };+ }+ if (realRoot !== record.realPathAtGrant) {+ return { kind: 'custom', root: null, drift: 'binding-moved', record };+ }+ if (+ record.identity !== null &&+ record.identity.ino !== 0 &&+ (st.dev !== record.identity.dev || st.ino !== record.identity.ino)+ ) {+ // 同路径但对象已换(删后重建):POSIX 可检出;Windows ino=0 时上方已跳过。+ return { kind: 'custom', root: null, drift: 'binding-moved', record };+ }+ return { kind: 'custom', root: path.join(realRoot, ghostId), record };+ }+}diff --git a/apps/desktop/src/main/cindy-brain/libraryDbCore.ts b/apps/desktop/src/main/cindy-brain/libraryDbCore.tsnew file mode 100644index 0000000000..4906be494f--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/libraryDbCore.ts@@ -0,0 +1,394 @@+/**+ * libraryDbCore.ts — 插件 Library 的受控 SQLite 核心(2026-08-20 定案,方案 B)。+ * ---------------------------------------------------------------------------+ * 插件永远拿不到 Database 对象:它只能提交**参数化语句**,经语句门过滤后由+ * 宿主在专属 worker 里执行(better-sqlite3 没有 sqlite3_set_authorizer,+ * 结构化允许清单是唯一可靠防线,deny-by-default 而非黑名单):+ *+ * 1. 单语句:prepare() 本身拒绝多语句(better-sqlite3 行为);+ * 2. 首词白名单 {SELECT,WITH,INSERT,REPLACE,UPDATE,DELETE,CREATE,DROP,+ * ALTER,REINDEX,ANALYZE}——SQLite 语句类型由首词决定;ATTACH/VACUUM+ * INTO/PRAGMA 无法嵌进 SELECT/触发器/视图内部(触发器体只允许 DML),+ * 因此首词判据是可靠的;+ * 3. 事务由宿主管理(db.batch 整批原子),插件不能发 BEGIN/COMMIT;+ * 4. loadExtension 是宿主侧 API,插件不可达;SQL 函数 load_extension()+ * 在 better-sqlite3 默认关闭;+ * 5. 结果集行数/字节上限,防一次查询撑爆管道;+ * 6. 真实执行隔离在 worker(main 侧仅语句门与 RPC 组包),恶意慢查询+ * 只能饿死自己那个 worker,宿主可 terminate(WAL 保证 terminate 安全)。+ *+ * 本模块同时是 worker 内的执行体与单测的进程内执行体:Database 构造器一律+ * 注入,worker 用 betterSqliteModulePath require,测试直接传 require 结果。+ */++/** better-sqlite3 的结构化子集(避免整包类型耦合;真实实例结构性兼容)。 */+export interface SqlitePreparedStatement {+ readonly reader: boolean;+ run(...params: unknown[]): { changes: number; lastInsertRowid: number | bigint };+ get(...params: unknown[]): unknown;+ all(...params: unknown[]): unknown[];+ /** 惰性迭代(better-sqlite3 同名 API;行上限的提前停止靠它)。 */+ iterate(...params: unknown[]): Iterable<unknown>;+}+export interface SqliteDatabase {+ prepare(sql: string): SqlitePreparedStatement;+ pragma(source: string): unknown;+ exec(sql: string): void;+ close(): void;+ backup(destination: string): Promise<void>;+ transaction<T>(fn: () => T): () => T;+}+export type SqliteDatabaseConstructor = new (path: string, options?: { readonly?: boolean }) => SqliteDatabase;++/** 语句门白名单(见文件头第 2 条论证)。 */+const ALLOWED_FIRST_WORDS = new Set([+ 'SELECT', 'WITH', 'INSERT', 'REPLACE', 'UPDATE', 'DELETE',+ 'CREATE', 'DROP', 'ALTER', 'REINDEX', 'ANALYZE',+]);++/** 结果集上限(行数/序列化字节)。 */+export const LIBRARY_DB_MAX_ROWS = 2000;+export const LIBRARY_DB_MAX_RESULT_BYTES = 16 * 1024 * 1024;++/**+ * 语句门:剥离前导空白与注释后取首个关键词,必须命中白名单。+ * 事务语句(BEGIN/COMMIT/SAVEPOINT)、ATTACH/DETACH、PRAGMA、VACUUM、+ * EXPLAIN 一律拒绝;多语句由 better-sqlite3 的 prepare 兜底拒绝。+ */+export function gateSqlStatement(sql: unknown): { ok: true } | { ok: false; reason: string } {+ if (typeof sql !== 'string' || sql.trim().length === 0) {+ return { ok: false, reason: 'sql 必须是非空字符串' };+ }+ const s = sql;+ let i = 0;+ for (;;) {+ while (i < s.length && /\s/.test(s[i])) i += 1;+ if (s.startsWith('--', i)) {+ while (i < s.length && s[i] !== '\n') i += 1;+ continue;+ }+ if (s.startsWith('/*', i)) {+ const end = s.indexOf('*/', i + 2);+ if (end === -1) return { ok: false, reason: '未闭合的块注释' };+ i = end + 2;+ continue;+ }+ break;+ }+ const word = /^[A-Za-z_]+/.exec(s.slice(i))?.[0]?.toUpperCase();+ if (!word) return { ok: false, reason: '无法识别语句首词' };+ if (!ALLOWED_FIRST_WORDS.has(word)) {+ return {+ ok: false,+ reason: `不允许的语句类型:${word}(仅 DML/DDL 白名单;ATTACH/PRAGMA/VACUUM/事务语句一律拒绝)`,+ };+ }+ return { ok: true };+}++/** bind 参数合法性(better-sqlite3 可绑定的值域;对象键须以 :/@/$ 开头)。 */+function validateParams(params: unknown): { ok: true; args: unknown[] | [Record<string, unknown>] } | { ok: false; reason: string } {+ if (params === undefined || params === null) return { ok: true, args: [] };+ if (Array.isArray(params)) {+ for (const v of params) {+ if (!isBindable(v)) return { ok: false, reason: `参数类型不可绑定:${typeof v}` };+ }+ return { ok: true, args: params };+ }+ if (typeof params === 'object') {+ for (const [k, v] of Object.entries(params as Record<string, unknown>)) {+ // better-sqlite3 命名参数键为**裸标识符**(:id → { id });带前缀键会抛+ // Missing named parameter,这里提前拒并说明正确形态。+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) {+ return { ok: false, reason: `命名参数键非法:${k}(SQL 里写 :id,参数键写 id)` };+ }+ if (!isBindable(v)) return { ok: false, reason: `参数类型不可绑定:${typeof v}` };+ }+ return { ok: true, args: [params] };+ }+ return { ok: false, reason: 'params 只接受数组或命名参数对象' };+}++function isBindable(v: unknown): boolean {+ // better-sqlite3 可绑定值域;boolean 不可绑(调用方自行转 0/1),显式拒。+ return (+ v === null ||+ typeof v === 'number' ||+ typeof v === 'bigint' ||+ typeof v === 'string' ||+ v instanceof Uint8Array+ );+}++/** 打开的库句柄池(dbPath → db)。 */+interface OpenDatabases {+ [dbPath: string]: SqliteDatabase;+}++export type LibraryDbFailureCode =+ | 'DB_STATEMENT_REJECTED'+ | 'DB_PARAMS_INVALID'+ | 'DB_ROW_LIMIT'+ | 'DB_NOT_OPEN'+ | 'DB_ERROR'+ | 'DB_MIGRATION_CONFLICT';++export type LibraryDbResult<T> = { ok: true } & T | { ok: false; code: LibraryDbFailureCode; message: string };++/**+ * createLibraryDbCore — 库句柄池 + 五个受控操作(exec/batch/migrate/backup/check)。+ * worker 与单测共用;线程模型由调用方决定(worker 天然串行,进程内调用方自律)。+ */+export function createLibraryDbCore(opts: {+ DatabaseCtor: SqliteDatabaseConstructor;+ onLog?: (msg: string, meta?: Record<string, unknown>) => void;+}) {+ const open: OpenDatabases = {};++ function requireOpen(dbPath: string): SqliteDatabase | null {+ return open[dbPath] ?? null;+ }++ async function openDatabase(dbPath: string): Promise<LibraryDbResult<{ opened: true }>> {+ if (open[dbPath]) return { ok: true, opened: true };+ const db = new opts.DatabaseCtor(dbPath);+ // 与主库同水位的关键 pragma;cache/mmap 收小(per-plugin 多库并存)。+ db.pragma('journal_mode = WAL');+ db.pragma('synchronous = NORMAL');+ db.pragma('foreign_keys = ON');+ db.pragma('busy_timeout = 5000');+ db.pragma('temp_store = MEMORY');+ db.pragma('cache_size = -16384'); // 16 MiB(主库 64 MiB)+ db.pragma('mmap_size = 0'); // per-plugin 连接不占 mmap 预算+ open[dbPath] = db;+ return { ok: true, opened: true };+ }++ function closeDatabase(dbPath: string): boolean {+ const db = open[dbPath];+ if (!db) return false;+ delete open[dbPath];+ try {+ db.close();+ } catch {+ /* 已损坏的连接,句柄丢弃即可 */+ }+ return true;+ }++ function closeAll(): void {+ for (const p of Object.keys(open)) closeDatabase(p);+ }++ /** 执行单条受控语句(读回行 / 写回 changes)。 */+ function execStatement(dbPath: string, sql: string, params: unknown): LibraryDbResult<{+ rows?: unknown[];+ changes?: number;+ lastInsertRowid?: string | number;+ }> {+ const gate = gateSqlStatement(sql);+ if (!gate.ok) return { ok: false, code: 'DB_STATEMENT_REJECTED', message: gate.reason };+ const p = validateParams(params);+ if (!p.ok) return { ok: false, code: 'DB_PARAMS_INVALID', message: p.reason };+ const db = requireOpen(dbPath);+ if (!db) return { ok: false, code: 'DB_NOT_OPEN', message: '数据库未打开(先 db.open)' };+ let stmt: SqlitePreparedStatement;+ try {+ stmt = db.prepare(sql); // 多语句/语法错在此抛出(better-sqlite3 拒绝多语句)+ } catch (err) {+ return { ok: false, code: 'DB_ERROR', message: err instanceof Error ? err.message : String(err) };+ }+ // 读/写分流:靠 better-sqlite3 的语句只读标记,而非重析 SQL。+ if (stmt.reader) {+ // 惰性取行(iterate):上限+1 处提前停止,**不先物化整个结果集**;行数与+ // **累计字节**都在循环内闸——2000 行 × 各自略低于上限的 BLOB 也不许+ // 把内存吃满(review:总字节限制后置)。+ const rows: unknown[] = [];+ let totalBytes = 0;+ try {+ for (const row of stmt.iterate(...(p.args as unknown[]))) {+ if (rows.length >= LIBRARY_DB_MAX_ROWS) {+ return { ok: false, code: 'DB_ROW_LIMIT', message: `结果集超行数上限(${LIBRARY_DB_MAX_ROWS});请加 LIMIT` };+ }+ const rowJson = JSON.stringify(row) ?? '';+ // **真实 UTF-8 字节数**,不是 JS UTF-16 码元 length——中文等内容+ // 1 码元≈3 UTF-8 字节,用 length 会把 16MiB 闸放大约 3 倍+ // (Greptile:多字节查询结果绕过 IPC 负载上限)。+ const rowBytes = Buffer.byteLength(rowJson, 'utf8');+ if (rowBytes > LIBRARY_DB_MAX_RESULT_BYTES) {+ return { ok: false, code: 'DB_ROW_LIMIT', message: '单行结果超字节上限;请缩小查询列/分页' };+ }+ totalBytes += rowBytes;+ if (totalBytes > LIBRARY_DB_MAX_RESULT_BYTES) {+ return { ok: false, code: 'DB_ROW_LIMIT', message: '结果集超字节上限;请加 LIMIT 或分页' };+ }+ rows.push(row);+ }+ } catch (err) {+ return { ok: false, code: 'DB_ERROR', message: err instanceof Error ? err.message : String(err) };+ }+ return { ok: true, rows };+ }+ try {+ const out = stmt.run(...(p.args as unknown[]));+ return {+ ok: true,+ changes: out.changes,+ lastInsertRowid: typeof out.lastInsertRowid === 'bigint' ? out.lastInsertRowid.toString() : out.lastInsertRowid,+ };+ } catch (err) {+ return { ok: false, code: 'DB_ERROR', message: err instanceof Error ? err.message : String(err) };+ }+ }++ /** 整批一个事务:任一失败全部回滚(宿主管理事务,插件不发 BEGIN/COMMIT)。 */+ function batch(dbPath: string, statements: Array<{ sql: string; params?: unknown }>): LibraryDbResult<{ applied: number }> {+ if (!Array.isArray(statements) || statements.length === 0) {+ return { ok: false, code: 'DB_PARAMS_INVALID', message: 'statements 必须是非空数组' };+ }+ if (statements.length > 200) {+ return { ok: false, code: 'DB_PARAMS_INVALID', message: '单批最多 200 条语句' };+ }+ const db = requireOpen(dbPath);+ if (!db) return { ok: false, code: 'DB_NOT_OPEN', message: '数据库未打开(先 db.open)' };+ // 先整体过门+参数校验,再进事务:拒绝时不留半开事务。+ for (const st of statements) {+ const gate = gateSqlStatement(st.sql);+ if (!gate.ok) return { ok: false, code: 'DB_STATEMENT_REJECTED', message: gate.reason };+ const p = validateParams(st.params);+ if (!p.ok) return { ok: false, code: 'DB_PARAMS_INVALID', message: p.reason };+ }+ let applied = 0;+ try {+ const tx = db.transaction(() => {+ for (const st of statements) {+ const gate = gateSqlStatement(st.sql); // 门复读(防御性,成本低)+ if (!gate.ok) throw new Error(gate.reason);+ db.prepare(st.sql).run(...(normalizeArgs(st.params) as unknown[]));+ applied += 1;+ }+ });+ tx();+ } catch (err) {+ return { ok: false, code: 'DB_ERROR', message: `批事务已回滚:${err instanceof Error ? err.message : String(err)}` };+ }+ return { ok: true, applied };+ }++ /** user_version 迁移:按 steps 逐步执行,每步一个事务;调用方负责先 backup。 */+ function migrate(+ dbPath: string,+ targetVersion: number,+ steps: Array<{ toVersion: number; sql: string[] }>,+ ): LibraryDbResult<{ fromVersion: number; toVersion: number }> {+ if (!Number.isInteger(targetVersion) || targetVersion < 0) {+ return { ok: false, code: 'DB_PARAMS_INVALID', message: 'targetVersion 必须是非负整数' };+ }+ if (!Array.isArray(steps) || steps.length === 0) {+ return { ok: false, code: 'DB_PARAMS_INVALID', message: 'steps 必须是非空数组' };+ }+ const db = requireOpen(dbPath);+ if (!db) return { ok: false, code: 'DB_NOT_OPEN', message: '数据库未打开(先 db.open)' };+ for (const step of steps) {+ if (!Number.isInteger(step.toVersion) || step.toVersion <= 0 || !Array.isArray(step.sql)) {+ return { ok: false, code: 'DB_PARAMS_INVALID', message: 'step 形态非法(toVersion/sql[])' };+ }+ for (const sql of step.sql) {+ const gate = gateSqlStatement(sql);+ if (!gate.ok) return { ok: false, code: 'DB_STATEMENT_REJECTED', message: gate.reason };+ }+ }+ // 步进连续性:steps 必须从 1(或从任意起点)严格递增到 targetVersion。+ for (let i = 1; i < steps.length; i += 1) {+ if (steps[i].toVersion !== steps[i - 1].toVersion + 1) {+ return { ok: false, code: 'DB_PARAMS_INVALID', message: 'steps 的 toVersion 必须连续递增' };+ }+ }+ const current = readUserVersion(db);+ if (current > targetVersion) {+ return {+ ok: false,+ code: 'DB_MIGRATION_CONFLICT',+ message: `数据库版本(${current})高于目标(${targetVersion});插件版本过旧`,+ };+ }+ let last = current;+ for (const step of steps) {+ if (step.toVersion <= current) continue; // 已应用的步跳过(幂等续跑)+ if (step.toVersion !== last + 1) {+ return { ok: false, code: 'DB_PARAMS_INVALID', message: `steps 缺少版本 ${last + 1}` };+ }+ try {+ const tx = db.transaction(() => {+ for (const sql of step.sql) {+ // prepare 单语句(better-sqlite3 拒多语句):迁移语句与 exec 路径+ // 同一防线——首词过门后串里追加 ";ATTACH…" 在这里会被 prepare 拒,+ // 不能借 db.exec 绕过(review:迁移 SQL 绕过单语句防线)。+ db.prepare(sql).run();+ }+ db.pragma(`user_version = ${step.toVersion}`);+ });+ tx();+ } catch (err) {+ return {+ ok: false,+ code: 'DB_ERROR',+ message: `迁移到 v${step.toVersion} 失败(已回滚,停留在 v${last}):${err instanceof Error ? err.message : String(err)}`,+ };+ }+ last = step.toVersion;+ }+ return { ok: true, fromVersion: current, toVersion: last };+ }++ function readUserVersion(db: SqliteDatabase): number {+ const row = db.prepare('PRAGMA user_version').get() as { user_version?: number } | undefined;+ return Number(row?.user_version ?? 0);+ }++ /** 在线备份(better-sqlite3 backup API;WAL 下安全,勿用 copyFile)。 */+ async function backupDatabase(dbPath: string, destAbs: string): Promise<LibraryDbResult<{ backedUp: true }>> {+ const db = requireOpen(dbPath);+ if (!db) return { ok: false, code: 'DB_NOT_OPEN', message: '数据库未打开(先 db.open)' };+ try {+ await db.backup(destAbs);+ return { ok: true, backedUp: true };+ } catch (err) {+ return { ok: false, code: 'DB_ERROR', message: err instanceof Error ? err.message : String(err) };+ }+ }++ /** 完整性检查(PRAGMA quick_check;宿主代码,不走插件语句门)。 */+ function checkDatabase(dbPath: string): LibraryDbResult<{ ok_check: boolean; detail: string }> {+ const db = requireOpen(dbPath);+ if (!db) return { ok: false, code: 'DB_NOT_OPEN', message: '数据库未打开(先 db.open)' };+ try {+ const rows = db.prepare('PRAGMA quick_check').all() as Array<{ quick_check?: string }>;+ const first = rows[0]?.quick_check ?? 'unknown';+ return { ok: true, ok_check: first === 'ok', detail: String(first) };+ } catch (err) {+ return { ok: false, code: 'DB_ERROR', message: err instanceof Error ? err.message : String(err) };+ }+ }++ return {+ openDatabase,+ closeDatabase,+ closeAll,+ execStatement,+ batch,+ migrate,+ backupDatabase,+ checkDatabase,+ readUserVersion: (dbPath: string) => {+ const db = requireOpen(dbPath);+ return db ? readUserVersion(db) : null;+ },+ };+}++function normalizeArgs(params: unknown): unknown[] {+ if (params === undefined || params === null) return [];+ if (Array.isArray(params)) return params;+ return [params];+}diff --git a/apps/desktop/src/main/cindy-brain/libraryDbWorker.ts b/apps/desktop/src/main/cindy-brain/libraryDbWorker.tsnew file mode 100644index 0000000000..405b908206--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/libraryDbWorker.ts@@ -0,0 +1,98 @@+/**+ * libraryDbWorker.ts — 插件 Library SQLite 的专属 worker 入口。+ * ---------------------------------------------------------------------------+ * 与 dbWorker 同款装配:better-sqlite3 经**绝对路径 require**(packaged app 的+ * asar.unpacked 解析,bare require 会解析错),构造器在 worker 侧实例化,+ * 执行体是 libraryDbCore(与单测共用同一份逻辑,无双份漂移)。+ * 一个 worker 服务一个插件:恶意慢查询只能饿死自己,宿主可 terminate+ * (WAL 保证 terminate 不损坏库)。+ */++import { createRequire } from 'node:module';+import { parentPort, workerData } from 'node:worker_threads';++import {+ createLibraryDbCore,+ type LibraryDbResult,+ type SqliteDatabaseConstructor,+} from './libraryDbCore.js';++interface LibraryDbWorkerStartup {+ betterSqliteModulePath?: string;+}++const workerPort = parentPort;+if (!workerPort) throw new Error('library db worker must be spawned via worker_threads');+const activePort = workerPort;++const startup = (workerData ?? {}) as LibraryDbWorkerStartup;+const moduleRequire = createRequire(import.meta.url);++function loadDatabaseConstructor(modulePath: string | undefined): SqliteDatabaseConstructor {+ const mod = moduleRequire(modulePath || 'better-sqlite3') as+ | SqliteDatabaseConstructor+ | { default?: SqliteDatabaseConstructor };+ if (typeof mod === 'function') return mod;+ if (typeof mod.default === 'function') return mod.default;+ throw new Error('better-sqlite3 module did not export a Database constructor');+}++const core = createLibraryDbCore({+ DatabaseCtor: loadDatabaseConstructor(startup.betterSqliteModulePath),+ onLog: () => {+ /* worker 侧静默;错误经 RPC 结果回传,不落日志(不含用户内容) */+ },+});++interface WorkerRequest {+ id: number;+ op: 'open' | 'close' | 'closeAll' | 'exec' | 'batch' | 'migrate' | 'backup' | 'check' | 'userVersion';+ dbPath?: string;+ sql?: string;+ params?: unknown;+ statements?: Array<{ sql: string; params?: unknown }>;+ targetVersion?: number;+ steps?: Array<{ toVersion: number; sql: string[] }>;+ destAbs?: string;+}++activePort.on('message', async (req: WorkerRequest) => {+ let result: LibraryDbResult<Record<string, unknown>>;+ try {+ switch (req.op) {+ case 'open':+ result = await core.openDatabase(req.dbPath ?? '');+ break;+ case 'close':+ result = { ok: true, closed: core.closeDatabase(req.dbPath ?? '') };+ break;+ case 'closeAll':+ core.closeAll();+ result = { ok: true, closedAll: true };+ break;+ case 'exec':+ result = core.execStatement(req.dbPath ?? '', req.sql ?? '', req.params);+ break;+ case 'batch':+ result = core.batch(req.dbPath ?? '', req.statements ?? []);+ break;+ case 'migrate':+ result = core.migrate(req.dbPath ?? '', req.targetVersion ?? 0, req.steps ?? []);+ break;+ case 'backup':+ result = await core.backupDatabase(req.dbPath ?? '', req.destAbs ?? '');+ break;+ case 'check':+ result = core.checkDatabase(req.dbPath ?? '');+ break;+ case 'userVersion':+ result = { ok: true, version: core.readUserVersion(req.dbPath ?? '') };+ break;+ default:+ result = { ok: false, code: 'DB_ERROR', message: `未知 op:${String(req.op)}` };+ }+ } catch (err) {+ result = { ok: false, code: 'DB_ERROR', message: err instanceof Error ? err.message : String(err) };+ }+ activePort.postMessage({ id: req.id, result });+});diff --git a/apps/desktop/src/main/cindy-brain/libraryMigrate.ts b/apps/desktop/src/main/cindy-brain/libraryMigrate.tsnew file mode 100644index 0000000000..252a50a849--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/libraryMigrate.ts@@ -0,0 +1,188 @@+/**+ * libraryMigrate.ts — Library 随时迁移状态机(2026-08-20 定案:并入首期)。+ * ---------------------------------------------------------------------------+ * precheck → copying → verifying → switching → grace:+ * - precheck:候选位置全套校验(可写/受管根排斥/网络盘拒/云盘警告)++ * 空间 ≥ 现用量×1.2;+ * - copying:逐文件复制(.sqlite 用在线 backup API 复制,WAL 下安全);+ * - verifying:全量清单对账(条数/字节数逐项相等)+ 每个 .sqlite+ * quick_check + 从新位置测试打开;+ * - switching:写新 binding(generation+1,原子);旧目录改名+ * `<old>.migrated-<ts>` 保留 14 天回滚窗(grace);+ * - 任一步失败:binding 未切换、旧位置数据原样(复制残渣留在新候选的+ * 临时目录名下,不影响旧位置)。+ *+ * 迁移期间调用方必须先 dispose 会话并阻止插件写入(readonly 语义由+ * 调用方保证——设置页发起时插件侧会话已作废,短窗口内插件请求会重建+ * 会话写旧根,副本在 switching 前完成对账,该窗口写入最多造成新旧差异、+ * 由 grace 期回滚/重迁修复,不丢数据)。+ *+ * 纯 Node + 依赖注入,单测 tmpdir 直测。+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++import { validateLibraryCandidateLocation, type LibraryBindingDeps } from './libraryBinding.js';++export interface LibraryMigrateDeps extends LibraryBindingDeps {+ getDiskFreeBytes?(root: string): Promise<number | null>;+ /** .sqlite 完整性验证(生产 = 只读打开 + quick_check;测试注入)。 */+ checkSqliteHealthy(absPath: string): Promise<boolean>;+ /** .sqlite 在线备份式复制(生产 = better-sqlite3 backup API;测试注入)。 */+ copySqlite(from: string, to: string): Promise<void>;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+ now?(): number;+}++export type LibraryMigrateResult =+ | { ok: true; fromRoot: string; toRoot: string; files: number; bytes: number; warnings: string[] }+ | { ok: false; phase: 'precheck' | 'copying' | 'verifying' | 'switching'; message: string };++/**+ * 收集库内容清单(相对路径→大小;.sqlite 单列)。**任何子目录读不出都抛错**+ * ——静默跳过会迁出一个"子集一致"的库并通过校验(review:部分迁移);+ * 根本身 ENOENT 视为空库(尚无数据)。stat 失败同样抛(文件在收集中消失)。+ */+async function collectManifest(root: string): Promise<Map<string, { bytes: number; sqlite: boolean }>> {+ const manifest = new Map<string, { bytes: number; sqlite: boolean }>();+ const stack: string[] = [root];+ while (stack.length > 0) {+ const dir = stack.pop()!;+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(dir, { withFileTypes: true });+ } catch (err) {+ if (dir === root && (err as NodeJS.ErrnoException).code === 'ENOENT') return manifest;+ throw new Error(`清单收集失败(目录不可读:${dir}):${err instanceof Error ? err.message : String(err)}`);+ }+ for (const entry of entries) {+ if (dir === root && entry.name === '.cindy-library') continue; // 宿主元数据随迁但账本重扫+ const full = path.join(dir, entry.name);+ const rel = path.relative(root, full).split(path.sep).join('/');+ if (entry.isDirectory()) {+ manifest.set(`${rel}/`, { bytes: 0, sqlite: false });+ stack.push(full);+ } else if (entry.isFile()) {+ let st: fs.Stats;+ try {+ st = await fs.promises.stat(full);+ } catch (err) {+ throw new Error(`清单收集失败(文件不可读:${rel}):${err instanceof Error ? err.message : String(err)}`);+ }+ manifest.set(rel, { bytes: st.size, sqlite: rel.toLowerCase().endsWith('.sqlite') });+ }+ }+ }+ return manifest;+}++async function copyPlain(from: string, to: string): Promise<void> {+ await fs.promises.mkdir(path.dirname(to), { recursive: true });+ await fs.promises.copyFile(from, to);+}++/**+ * 执行迁移:candidate = 用户所选**父目录**(与 setBinding 同口径,实际库根+ * = <candidate>/<ghostId>)。targetKind 'default' 表示迁回系统默认位置+ * (撤销自定义 binding 的反向迁移)。+ */+export async function migrateGhostLibrary(req: {+ ghostId: string;+ fromRoot: string;+ candidate: string;+ deps: LibraryMigrateDeps;+ /** 切换 binding 的回调(生产 = bindingStore.setBinding)。 */+ applyBinding(candidate: string): Promise<{ ok: boolean; message?: string }>;+ /** 迁回系统默认位置的内部路径:默认根在数据区内,豁免受管根排斥。 */+ allowInsideManagedRoot?: boolean;+}): Promise<LibraryMigrateResult> {+ const { ghostId, fromRoot, candidate, deps } = req;+ // ── precheck ─────────────────────────────────────────────────────+ const validation = await validateLibraryCandidateLocation({+ candidate,+ ghostId,+ deps,+ getDiskFreeBytes: deps.getDiskFreeBytes,+ allowInsideManagedRoot: req.allowInsideManagedRoot,+ });+ if (!validation.ok) return { ok: false, phase: 'precheck', message: validation.message };+ const toRoot = path.join(candidate, ghostId);+ // 目标已存在内容 = 拒绝(不合并、不覆盖——作品数据不做启发式合并)。+ try {+ await fs.promises.stat(toRoot);+ if (path.resolve(toRoot) !== path.resolve(fromRoot)) {+ return { ok: false, phase: 'precheck', message: '目标位置已存在同名目录;请换一个位置或先清理' };+ }+ } catch {+ /* 不存在 = 正常 */+ }+ const manifest = await collectManifest(fromRoot);+ let totalBytes = 0;+ let totalFiles = 0;+ for (const [rel, info] of manifest) {+ if (rel.endsWith('/')) continue;+ totalBytes += info.bytes;+ totalFiles += 1;+ }+ if (deps.getDiskFreeBytes) {+ let free: number | null = null;+ try {+ free = await deps.getDiskFreeBytes(candidate);+ } catch {+ free = null;+ }+ if (free !== null && free < totalBytes * 1.2 + 256 * 1024 * 1024) {+ return { ok: false, phase: 'precheck', message: `目标磁盘空间不足(需要至少约 ${Math.ceil((totalBytes * 1.2) / 1024 / 1024)} MB 余量)` };+ }+ }+ // ── copying + verifying(逐文件:复制即对账,失败即中止)────────────+ try {+ for (const [rel, info] of manifest) {+ if (rel.endsWith('/')) {+ await fs.promises.mkdir(path.join(toRoot, rel), { recursive: true });+ continue;+ }+ const from = path.join(fromRoot, ...rel.split('/'));+ const to = path.join(toRoot, ...rel.split('/'));+ if (info.sqlite) {+ await fs.promises.mkdir(path.dirname(to), { recursive: true });+ await deps.copySqlite(from, to);+ } else {+ await copyPlain(from, to);+ }+ const stTo = await fs.promises.stat(to);+ if (stTo.size !== info.bytes) {+ return { ok: false, phase: 'verifying', message: `校验失败(大小不一致):${rel}` };+ }+ if (info.sqlite && !(await deps.checkSqliteHealthy(to))) {+ return { ok: false, phase: 'verifying', message: `数据库完整性校验失败:${rel}` };+ }+ }+ } catch (err) {+ return { ok: false, phase: 'copying', message: `复制失败:${err instanceof Error ? err.message : String(err)}` };+ }+ // ── switching:先切 binding,再挪旧目录进 grace ────────────────────+ const binding = await req.applyBinding(candidate);+ if (!binding.ok) {+ return { ok: false, phase: 'switching', message: binding.message ?? '位置记录更新失败' };+ }+ const stamp = deps.now?.() ?? Date.now();+ if (path.resolve(toRoot) !== path.resolve(fromRoot)) {+ try {+ await fs.promises.rename(fromRoot, `${fromRoot}.migrated-${stamp}`);+ } catch (err) {+ // binding 已切换、新位置已验证——旧目录改名失败只影响回滚窗,不回滚+ // 迁移(如实告警)。+ deps.log?.warn('library migrate: grace rename failed (old copy kept in place)', {+ ghostId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ deps.log?.info('library migrated', { ghostId, files: totalFiles, bytes: totalBytes });+ return { ok: true, fromRoot, toRoot, files: totalFiles, bytes: totalBytes, warnings: validation.warnings };+}diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.tsnew file mode 100644index 0000000000..cbe7beb826--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts@@ -0,0 +1,411 @@+/**+ * librarySlot.ts — library 槽:持久作品库的协议分派层(2026-08-20)。+ * ---------------------------------------------------------------------------+ * 与 fsSlot 平级,信任边界同源:+ * - ghostId 一律 webContents 反查(IPC 层),槽内 getGhost 再核资格+ * (manifest 声明 'library' + 启用态);+ * - ownerId 插件接触不到:根目录解析走 LibraryBindingStore(默认根 =+ * ownerScopedUserDataPath('libraries', id);自定义根按 binding 漂移判定),+ * 会话绑定 ownerScopeKey,每请求比对——切换后旧会话作废重解,+ * 在途写入不会跨 owner 落盘;+ * - 所有路径只是**相对键**(validateLibraryRelPath),宿主解析;dbPath 同纪律;+ * - db.migrate 前自动在线备份进 .cindy-library/backups/(宿主命名空间,+ * 插件路径语法写不进);+ * - 结果统一 GhostPipeLibraryResult(结构化 errorCode,对沙箱永不 reject)。+ *+ * 依赖注入(规则 14):binding/vault/sql 工厂、owner scope 捕获、worker 路径+ * 全部经 deps,单测拿 tmpdir + 进程内 core 直测,零 Electron。+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++import {+ GHOST_LIBRARY_OPS,+ type GhostPipeLibraryResult,+ type InstalledGhost,+} from '../../shared/ghost.js';+import { LibraryVault, validateLibraryRelPath, DEFAULT_LIBRARY_LIMITS, type LibraryVaultDeps } from './libraryVault.js';+import { LibraryBindingStore, type LibraryLocationResolution } from './libraryBinding.js';+import { LibrarySqlService, type LibrarySqlServiceDeps } from './librarySqlService.js';+import type { LibraryDbResult } from './libraryDbCore.js';++/** 单插件的库会话(vault + sql 绑定到同一根与 owner scope)。 */+interface GhostLibrarySession {+ vault: LibraryVault;+ sql: LibrarySqlService;+ /** 会话创建时捕获的 owner scope key;每请求比对,变了就整会话作废。 */+ ownerScopeKey: string | null;+ locationKind: 'default' | 'custom';+ /** 自定义位置漂移(binding-moved/disk-missing):全部操作 unavailable。 */+ drift: 'binding-moved' | 'disk-missing' | null;+}++export interface GhostLibrarySlotDeps {+ getGhost(id: string): InstalledGhost | null;+ /** 自定义位置 binding 存储(owner-scoped;生产注入)。 */+ bindingStore: LibraryBindingStore;+ /** 系统默认库根(生产 = ownerScopedUserDataPath('libraries', ghostId))。 */+ getDefaultRoot(ghostId: string): string;+ /** owner scope key(生产 = activeOwnerScopeKey;null = 无 owner 上下文)。 */+ captureOwnerScope(): string | null;+ /** vault 工厂(测试可换内存实现;默认真 LibraryVault)。 */+ createVault(deps: LibraryVaultDeps): LibraryVault;+ /** sql 服务工厂(测试注入进程内 core;默认真 worker 服务)。 */+ createSqlService(deps: LibrarySqlServiceDeps): LibrarySqlService;+ getDiskFreeBytes?(root: string): Promise<number | null>;+ workerScriptPath(): string;+ betterSqliteModulePath(): string;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+}++const fail = (errorCode: string, message: string): GhostPipeLibraryResult => ({ ok: false, errorCode, message });++export class GhostLibrarySlot {+ private readonly sessions = new Map<string, GhostLibrarySession>();+ /** 迁移进行中的插件:全部写操作只读化(切换与 grace 前不再有写入落旧根)。 */+ private readonly relocating = new Set<string>();++ constructor(private readonly deps: GhostLibrarySlotDeps) {}++ /** 迁移期只读闸(设置页迁移在 copying 前置位、结束后清除)。 */+ setRelocating(ghostId: string, on: boolean): void {+ if (on) this.relocating.add(ghostId);+ else this.relocating.delete(ghostId);+ }++ /** 处理一条 library-request(ghost-pipe:send 的 invoke 返回值即本结果)。 */+ async handleLibraryRequest(ghostId: string, payload: unknown): Promise<GhostPipeLibraryResult> {+ try {+ return await this.dispatch(ghostId, payload);+ } catch (err) {+ this.deps.log?.warn('ghost library-request unexpected failure', {+ ghostId,+ error: err instanceof Error ? err.message : String(err),+ });+ return fail('INTERNAL', 'Library 操作失败(主机内部错误)');+ }+ }++ private async dispatch(ghostId: string, payload: unknown): Promise<GhostPipeLibraryResult> {+ if (!this.checkEligibility(ghostId)) {+ return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 卡槽');+ }+ const req = (payload ?? {}) as Record<string, unknown>;+ const op = req.op as string;+ if (!GHOST_LIBRARY_OPS.includes(op as never)) {+ return fail('PATH_INVALID', `op 必须是 ${GHOST_LIBRARY_OPS.join(' / ')}`);+ }+ // 迁移期只读:写类操作在 copying 全程拒绝(读与状态查询照常)。+ if (this.relocating.has(ghostId)) {+ const writeOps: ReadonlySet<string> = new Set([+ 'write', 'writeBegin', 'writeChunk', 'writeCommit', 'writeAbort',+ 'mkdir', 'delete', 'rename',+ 'db.open', 'db.exec', 'db.batch', 'db.migrate', 'db.backup',+ ]);+ if (writeOps.has(op)) {+ return fail('LIBRARY_READONLY', 'Library 正在迁移到新位置,写入已暂停;请稍后重试');+ }+ }++ // 会话获取/作废:owner scope 变了(切换在途或已切),旧会话的根与连接+ // 一并作废——绝不把上个 owner 的库当成本 owner 的库继续用。+ const scopeKey = this.deps.captureOwnerScope();+ const session = await this.getOrCreateSession(ghostId, scopeKey);+ return this.runOp(ghostId, session, op, req);+ }++ private async getOrCreateSession(ghostId: string, scopeKey: string | null): Promise<GhostLibrarySession> {+ let session = this.sessions.get(ghostId);+ if (session && session.ownerScopeKey !== scopeKey) {+ await this.teardownSession(ghostId);+ session = undefined;+ }+ if (!session) {+ const resolution = await this.deps.bindingStore.resolveLibraryRoot(ghostId);+ session = this.createSession(ghostId, resolution, scopeKey);+ this.sessions.set(ghostId, session);+ // 会话建立即自动 open(幂等):消除"write 前忘 open"的脚枪;显式 open+ // 操作仍有效,仅回状态。+ if (session.drift === null) {+ await session.vault.open();+ // 重装自愈:能走到这里 = 插件已装入且启用,清掉卸载时留的 orphaned+ // 标记(best-effort,失败不影响使用)。+ if (session.vault.getMeta()?.orphaned) {+ await session.vault.clearOrphaned().catch(() => {});+ }+ }+ }+ return session;+ }++ /**+ * 面板投影(cindy-ghost://<id>/library/<relPath>)的宿主侧解析:返回已存在+ * 普通文件的绝对路径,或 null(折叠 404)。经 binding 现解 + vault 路径纪律,+ * 与 read 同源校验——面板与电子脑看到同一个库。+ */+ /** 资格审:装入 + 启用 + 声明 library 槽(dispatch 与面板投影共用)。 */+ private checkEligibility(ghostId: string): boolean {+ const ghost = this.deps.getGhost(ghostId);+ if (!ghost) return false;+ if (ghost.enabled === false) return false;+ return ghost.manifest.slots.includes('library');+ }++ /**+ * 面板投影(cindy-ghost://<id>/library/<relPath>)的宿主侧解析:返回已存在+ * 普通文件的绝对路径,或 null(折叠 404)。资格审与 dispatch 同源——插件+ * 停用或更新后移除 slot 时投影一并熄灭(review:面板路由不复查授权)。+ */+ async resolvePanelFilePath(ghostId: string, relPath: string): Promise<string | null> {+ try {+ if (!this.checkEligibility(ghostId)) return null;+ const session = await this.getOrCreateSession(ghostId, this.deps.captureOwnerScope());+ if (session.drift !== null) return null;+ return await session.vault.resolveExistingFile(relPath);+ } catch {+ return null;+ }+ }++ private createSession(+ ghostId: string,+ resolution: LibraryLocationResolution,+ scopeKey: string | null,+ ): GhostLibrarySession {+ const drift = 'drift' in resolution && resolution.root === null ? resolution.drift : null;+ const root = resolution.kind === 'custom' && resolution.root !== null+ ? resolution.root+ : this.deps.getDefaultRoot(ghostId);+ const vault = this.deps.createVault({+ rootDir: () => root,+ ghostId,+ getDiskFreeBytes: this.deps.getDiskFreeBytes,+ locationKind: resolution.kind,+ log: this.deps.log,+ });+ const sql = this.deps.createSqlService({+ workerScriptPath: this.deps.workerScriptPath,+ betterSqliteModulePath: this.deps.betterSqliteModulePath,+ log: this.deps.log,+ });+ return { vault, sql, ownerScopeKey: scopeKey, locationKind: resolution.kind, drift };+ }++ private async teardownSession(ghostId: string): Promise<void> {+ const session = this.sessions.get(ghostId);+ if (!session) return;+ this.sessions.delete(ghostId);+ await session.sql.dispose().catch(() => {});+ await session.vault.invalidate().catch(() => {});+ }++ /** 停用/卸载/owner 切换收口:作废全部会话(commit 5 的生命周期接线点)。 */+ async disposeGhost(ghostId: string): Promise<void> {+ await this.teardownSession(ghostId);+ }++ async disposeAll(): Promise<void> {+ for (const id of Array.from(this.sessions.keys())) {+ await this.teardownSession(id);+ }+ }++ /** dbPath 相对键 → 库内绝对路径;经 vault 收敛校验(库内 symlink 指根外拒)。 */+ private async resolveDbPath(session: GhostLibrarySession, dbPath: unknown): Promise<{ abs: string } | GhostPipeLibraryResult> {+ const reason = validateLibraryRelPath(dbPath);+ if (reason) return fail('PATH_INVALID', `dbPath 非法:${reason}`);+ const abs = await session.vault.resolveDbTarget(dbPath as string);+ if (abs === null) return fail('PATH_INVALID', 'dbPath 越界或目标不可用作数据库');+ return { abs };+ }++ /** SQLite 写路径的磁盘保留水位(绕过 vault.write 的写也要受同一硬闸)。 */+ private async dbDiskGate(session: GhostLibrarySession): Promise<GhostPipeLibraryResult | null> {+ if (!this.deps.getDiskFreeBytes) return null;+ let free: number | null = null;+ try {+ free = await this.deps.getDiskFreeBytes(session.vault.getRootDir());+ } catch {+ return null;+ }+ if (free !== null && free < DEFAULT_LIBRARY_LIMITS.diskReserveBytes) {+ return fail('DISK_FULL', '磁盘剩余空间低于保留水位,数据库写入已暂停;请清理磁盘或迁移 Library');+ }+ return null;+ }++ /** core 结果 → 管道类型(按 op 定形;check 的 ok_check 归一为 healthy)。 */+ private dbResultToPipe(op: string, r: LibraryDbResult<Record<string, unknown>>): GhostPipeLibraryResult {+ if (!r.ok) return { ok: false, errorCode: r.code, message: r.message };+ const rest: Record<string, unknown> = { ...r };+ delete rest.ok;+ if (op === 'db.check') {+ return { ok: true, op: 'db.check', healthy: rest.ok_check === true, detail: String(rest.detail ?? '') };+ }+ return { ok: true, op, ...rest } as GhostPipeLibraryResult;+ }++ private async runOp(+ ghostId: string,+ session: GhostLibrarySession,+ op: string,+ req: Record<string, unknown>,+ ): Promise<GhostPipeLibraryResult> {+ // 漂移占位会话:open/status 如实报 unavailable+reason,其余操作全拒+ // (绝不当空库、绝不落默认根冒充)。+ if (session.drift !== null && op !== 'open' && op !== 'status') {+ return fail('LIBRARY_UNAVAILABLE', `Library 不可用(${session.drift});请在 Cindy 设置中重新确认存储位置`);+ }+ if (session.drift !== null) {+ return {+ ok: true as const, op: op as 'open' | 'status', state: 'unavailable' as const,+ reason: session.drift, usedBytes: 0, fileCount: 0, location: 'custom' as const,+ };+ }+ const vault = session.vault;+ switch (op) {+ case 'open': {+ const r = await vault.open();+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'open', state: r.state, reason: r.reason ?? undefined, usedBytes: r.usedBytes, fileCount: r.fileCount, location: session.locationKind };+ }+ case 'status': {+ const r = await vault.status();+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return {+ ok: true, op: 'status', state: r.state, reason: r.reason ?? undefined,+ usedBytes: r.usedBytes, fileCount: r.fileCount,+ diskFreeBytes: r.diskFreeBytes, softLimitBytes: r.softLimitBytes,+ softLimitExceeded: r.softLimitExceeded, location: r.location,+ };+ }+ case 'read': {+ const r = await vault.read({ path: req.path, encoding: req.encoding, offset: req.offset, length: req.length });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'read', path: r.path, content: r.content, encoding: r.encoding, bytes: r.bytes, sha256: r.sha256 };+ }+ case 'write': {+ const r = await vault.write({ path: req.path, content: req.content, encoding: req.encoding, ifNotExists: req.ifNotExists });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'write', path: r.path, bytes: r.bytes, sha256: r.sha256 };+ }+ case 'writeBegin': {+ const r = await vault.writeBegin({ path: req.path, totalBytes: req.totalBytes, sha256: req.sha256 });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'writeBegin', streamId: r.streamId };+ }+ case 'writeChunk': {+ const r = await vault.writeChunk({ streamId: req.streamId, seq: req.seq, content: req.content, encoding: req.encoding });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'writeChunk', accepted: r.accepted };+ }+ case 'writeCommit': {+ const r = await vault.writeCommit({ streamId: req.streamId });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'writeCommit', path: r.path, bytes: r.bytes, sha256: r.sha256 };+ }+ case 'writeAbort': {+ const r = await vault.writeAbort({ streamId: req.streamId });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'writeAbort', aborted: r.aborted };+ }+ case 'list': {+ const r = await vault.list({ path: req.path, recursive: req.recursive, cursor: req.cursor, limit: req.limit });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'list', entries: r.entries, hasMore: r.hasMore, nextCursor: r.nextCursor };+ }+ case 'stat': {+ const r = await vault.stat({ path: req.path });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'stat', path: r.path, kind: r.kind, bytes: r.bytes, mtime: r.mtime };+ }+ case 'mkdir': {+ const r = await vault.mkdir({ path: req.path });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'mkdir', path: r.path, existed: r.existed };+ }+ case 'delete': {+ const r = await vault.delete({ path: req.path, recursive: req.recursiveDelete });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'delete', path: r.path, existed: r.existed };+ }+ case 'rename': {+ const r = await vault.rename({ from: req.from, to: req.to, overwrite: req.overwrite });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, op: 'rename', from: r.from, to: r.to };+ }+ case 'db.open': {+ const resolved = await this.resolveDbPath(session, req.dbPath);+ if (!('abs' in resolved)) return resolved;+ // 父目录由宿主建好(better-sqlite3 只建文件不建目录)。+ await fs.promises.mkdir(path.dirname(resolved.abs), { recursive: true }).catch(() => {});+ const r = await session.sql.open(resolved.abs);+ return this.dbResultToPipe(op, r);+ }+ case 'db.exec': {+ const diskGate = await this.dbDiskGate(session);+ if (diskGate) return diskGate;+ const resolved = await this.resolveDbPath(session, req.dbPath);+ if (!('abs' in resolved)) return resolved;+ const r = await session.sql.exec(resolved.abs, req.sql as string, req.params);+ return this.dbResultToPipe(op, r);+ }+ case 'db.batch': {+ const diskGate = await this.dbDiskGate(session);+ if (diskGate) return diskGate;+ const resolved = await this.resolveDbPath(session, req.dbPath);+ if (!('abs' in resolved)) return resolved;+ const r = await session.sql.batch(resolved.abs, (req.statements as Array<{ sql: string; params?: unknown }>) ?? []);+ return this.dbResultToPipe(op, r);+ }+ case 'db.migrate': {+ const diskGate = await this.dbDiskGate(session);+ if (diskGate) return diskGate;+ const resolved = await this.resolveDbPath(session, req.dbPath);+ if (!('abs' in resolved)) return resolved;+ // 迁移前自动在线备份(宿主命名空间,插件路径语法写不进);备份失败+ // 是硬前置——报错中止,不带伤迁移。+ const backupDest = path.join(+ session.vault.getRootDir(), '.cindy-library', 'backups',+ `pre-migrate-${Date.now()}-${Math.floor(Math.random() * 1e6)}.db`,+ );+ await fs.promises.mkdir(path.dirname(backupDest), { recursive: true }).catch(() => {});+ const bak = await session.sql.backup(resolved.abs, backupDest);+ if (!bak.ok) return this.dbResultToPipe('db.backup', bak);+ const r = await session.sql.migrate(+ resolved.abs,+ Number(req.targetVersion ?? 0),+ (req.steps as Array<{ toVersion: number; sql: string[] }>) ?? [],+ );+ return this.dbResultToPipe(op, r);+ }+ case 'db.backup': {+ const resolved = await this.resolveDbPath(session, req.dbPath);+ if (!('abs' in resolved)) return resolved;+ const label = typeof req.label === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(req.label) ? req.label : 'manual';+ const dest = path.join(session.vault.getRootDir(), '.cindy-library', 'backups', `${label}-${Date.now()}.db`);+ await fs.promises.mkdir(path.dirname(dest), { recursive: true }).catch(() => {});+ const r = await session.sql.backup(resolved.abs, dest);+ return this.dbResultToPipe(op, r);+ }+ case 'db.check': {+ const resolved = await this.resolveDbPath(session, req.dbPath);+ if (!('abs' in resolved)) return resolved;+ const r = await session.sql.check(resolved.abs);+ return this.dbResultToPipe(op, r);+ }+ case 'db.userVersion': {+ const resolved = await this.resolveDbPath(session, req.dbPath);+ if (!('abs' in resolved)) return resolved;+ const r = await session.sql.userVersion(resolved.abs);+ return this.dbResultToPipe(op, r);+ }+ default:+ return fail('PATH_INVALID', `未知 op:${op}`);+ }+ }+}diff --git a/apps/desktop/src/main/cindy-brain/librarySqlService.ts b/apps/desktop/src/main/cindy-brain/librarySqlService.tsnew file mode 100644index 0000000000..99512b73ed--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/librarySqlService.ts@@ -0,0 +1,221 @@+/**+ * librarySqlService.ts — 主进程侧的插件 Library SQLite RPC 服务。+ * ---------------------------------------------------------------------------+ * 每个声明 library 槽的插件一个 LibrarySqlService 实例(槽层在 commit 4 装配):+ * - 语句门在**发送前**执行(main 侧第一道,worker 内 core 复读第二道);+ * - worker 经 worker_threads 拉起(脚本 = 构建产出的 libraryDbWorker.js,+ * 与 main 输出同目录;better-sqlite3 模块路径由调用方注入,解析方式与+ * localDb 的 resolveBetterSqliteModuleEntry 一致);+ * - 慢查询/恶意 CPU 只阻塞该 worker;dispose/terminate 不损坏库(WAL);+ * - 单飞串行:worker 单线程天然按序处理,这里只维护请求 id → Promise 映射。+ *+ * 单测不拉真 worker:注入 createCore 直接进程内执行(与 worker 共用 core)。+ */++import { Worker } from 'node:worker_threads';+import * as path from 'node:path';++import {+ createLibraryDbCore,+ gateSqlStatement,+ type LibraryDbResult,+ type SqliteDatabaseConstructor,+} from './libraryDbCore.js';++export interface LibrarySqlServiceDeps {+ /** worker 脚本路径(生产 = __dirname/libraryDbWorker.js;测试可注入)。 */+ workerScriptPath(): string;+ /** better-sqlite3 模块绝对路径(生产 = resolveBetterSqliteModuleEntry)。 */+ betterSqliteModulePath(): string;+ /** 进程内执行体(单测注入;缺省时拉真 worker)。 */+ createCore?: (DatabaseCtor: SqliteDatabaseConstructor) => ReturnType<typeof createLibraryDbCore>;+ /** 进程内构造器(仅当 createCore 提供时使用;测试直连 require 结果)。 */+ inProcessCtor?: SqliteDatabaseConstructor;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+}++interface WorkerReply {+ id: number;+ result: LibraryDbResult<Record<string, unknown>>;+}++/**+ * LibrarySqlService — 单插件的受控 SQLite 会话。+ * 调用方(槽层)负责生命周期:owner 切换/停用时 dispose;本类不自行回收。+ */+export class LibrarySqlService {+ private worker: Worker | null = null;+ private nextId = 1;+ private readonly pending = new Map<number, { resolve: (v: LibraryDbResult<Record<string, unknown>>) => void }>();+ private disposed = false;+ /** 进程内模式(单测):直接驱动 core,不拉线程。 */+ private readonly core: ReturnType<typeof createLibraryDbCore> | null;++ constructor(private readonly deps: LibrarySqlServiceDeps) {+ this.core = deps.createCore && deps.inProcessCtor ? deps.createCore(deps.inProcessCtor) : null;+ }++ private ensureWorker(): Worker {+ if (this.core) throw new Error('in-process mode has no worker');+ if (!this.worker) {+ const worker = new Worker(this.deps.workerScriptPath(), {+ workerData: { betterSqliteModulePath: this.deps.betterSqliteModulePath() },+ });+ this.worker = worker;+ worker.on('message', (reply: WorkerReply) => {+ const entry = this.pending.get(reply.id);+ if (!entry) return;+ this.pending.delete(reply.id);+ entry.resolve(reply.result);+ });+ worker.on('error', (err: Error) => {+ this.deps.log?.warn('library db worker error', { error: err.message });+ this.failAllPending();+ });+ worker.on('exit', (code) => {+ if (!this.disposed) {+ this.deps.log?.warn('library db worker exited unexpectedly; will respawn on next call', { code });+ }+ // 清引用:下次 call 经 ensureWorker 重拉 worker——否则 postMessage+ // 打在已退出线程上,pending 永远挂起(review:worker 退出不恢复)。+ if (this.worker === worker) this.worker = null;+ this.failAllPending();+ });+ }+ return this.worker;+ }++ private failAllPending(): void {+ for (const [, entry] of this.pending) {+ entry.resolve({ ok: false, code: 'DB_ERROR', message: 'worker 已退出' });+ }+ this.pending.clear();+ }++ /** 发送前语句门(main 侧第一道):拒给插件回结构化 DB_STATEMENT_REJECTED。 */+ private preGate(sql: unknown): { ok: true; sql: string } | { ok: false; code: 'DB_STATEMENT_REJECTED'; message: string } {+ const gate = gateSqlStatement(sql);+ if (!gate.ok) return { ok: false, code: 'DB_STATEMENT_REJECTED', message: gate.reason };+ return { ok: true, sql: sql as string };+ }++ private async call(payload: Record<string, unknown>): Promise<LibraryDbResult<Record<string, unknown>>> {+ if (this.disposed) return { ok: false, code: 'DB_ERROR', message: '服务已 dispose' };+ if (this.core) {+ return this.callCore(payload);+ }+ const worker = this.ensureWorker();+ const id = this.nextId++;+ return new Promise<LibraryDbResult<Record<string, unknown>>>((resolve) => {+ this.pending.set(id, { resolve });+ worker.postMessage({ id, ...payload });+ });+ }++ /** 进程内分发(与 worker 的 switch 同构;由单测覆盖)。 */+ private async callCore(payload: Record<string, unknown>): Promise<LibraryDbResult<Record<string, unknown>>> {+ const core = this.core!;+ switch (payload.op as string) {+ case 'open':+ return core.openDatabase(String(payload.dbPath ?? ''));+ case 'close':+ return { ok: true, closed: core.closeDatabase(String(payload.dbPath ?? '')) };+ case 'closeAll':+ core.closeAll();+ return { ok: true, closedAll: true };+ case 'exec':+ return core.execStatement(String(payload.dbPath ?? ''), String(payload.sql ?? ''), payload.params);+ case 'batch':+ return core.batch(String(payload.dbPath ?? ''), (payload.statements as Array<{ sql: string; params?: unknown }>) ?? []);+ case 'migrate':+ return core.migrate(+ String(payload.dbPath ?? ''),+ Number(payload.targetVersion ?? 0),+ (payload.steps as Array<{ toVersion: number; sql: string[] }>) ?? [],+ );+ case 'backup':+ return core.backupDatabase(String(payload.dbPath ?? ''), String(payload.destAbs ?? ''));+ case 'check':+ return core.checkDatabase(String(payload.dbPath ?? ''));+ case 'userVersion':+ return { ok: true, version: core.readUserVersion(String(payload.dbPath ?? '')) };+ default:+ return { ok: false, code: 'DB_ERROR', message: `未知 op:${String(payload.op)}` };+ }+ }++ async open(dbPath: string): Promise<LibraryDbResult<{ opened: true }>> {+ return this.call({ op: 'open', dbPath }) as Promise<LibraryDbResult<{ opened: true }>>;+ }++ async exec(dbPath: string, sql: string, params?: unknown): Promise<LibraryDbResult<Record<string, unknown>>> {+ const gate = this.preGate(sql);+ if (!gate.ok) return gate;+ return this.call({ op: 'exec', dbPath, sql, params });+ }++ async batch(dbPath: string, statements: Array<{ sql: string; params?: unknown }>): Promise<LibraryDbResult<Record<string, unknown>>> {+ for (const st of statements) {+ const gate = this.preGate(st?.sql);+ if (!gate.ok) return gate;+ }+ return this.call({ op: 'batch', dbPath, statements });+ }++ async migrate(+ dbPath: string,+ targetVersion: number,+ steps: Array<{ toVersion: number; sql: string[] }>,+ ): Promise<LibraryDbResult<Record<string, unknown>>> {+ for (const step of steps) {+ for (const sql of step?.sql ?? []) {+ const gate = this.preGate(sql);+ if (!gate.ok) return gate;+ }+ }+ return this.call({ op: 'migrate', dbPath, targetVersion, steps });+ }++ async backup(dbPath: string, destAbs: string): Promise<LibraryDbResult<Record<string, unknown>>> {+ return this.call({ op: 'backup', dbPath, destAbs });+ }++ async check(dbPath: string): Promise<LibraryDbResult<Record<string, unknown>>> {+ return this.call({ op: 'check', dbPath });+ }++ async userVersion(dbPath: string): Promise<LibraryDbResult<Record<string, unknown>>> {+ return this.call({ op: 'userVersion', dbPath });+ }++ async close(dbPath: string): Promise<void> {+ await this.call({ op: 'close', dbPath });+ }++ /** 生命周期收口:优雅关闭 worker(有 pending 时直接 terminate,不等慢查询)。 */+ async dispose(): Promise<void> {+ this.disposed = true;+ if (this.core) {+ this.core.closeAll();+ return;+ }+ const worker = this.worker;+ this.worker = null;+ if (!worker) return;+ if (this.pending.size === 0) {+ worker.postMessage({ id: this.nextId++, op: 'closeAll' });+ await worker.terminate().catch(() => {});+ return;+ }+ await worker.terminate().catch(() => {});+ this.failAllPending();+ }+}++/** 生产 worker 脚本路径(构建产物与 main 输出同目录;见 forge vite 配置)。 */+export function defaultLibraryDbWorkerPath(): string {+ return path.join(__dirname, 'libraryDbWorker.js');+}diff --git a/apps/desktop/src/main/cindy-brain/libraryTrash.ts b/apps/desktop/src/main/cindy-brain/libraryTrash.tsnew file mode 100644index 0000000000..9139312eb5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/libraryTrash.ts@@ -0,0 +1,132 @@+/**+ * libraryTrash.ts — Library 删除通道(宿主级回收站,2026-08-20 定案)。+ * ---------------------------------------------------------------------------+ * 删除用户作品与卸载插件是**两个不同操作**:删除只从设置页独立确认入口进入,+ * 且不直接 rm——先 rename 进 owner 级 `libraries-trash/<ghostId>-<ts>/`+ * 保留 30 天回滚窗(对齐 recycler「先报数后动手」的 v1 哲学;到期清理由+ * 手动触发的维护动作执行,不做后台自动删除)。binding 一并撤销(数据已进+ * 回收站,原位置的自定义 binding 不再有意义)。+ *+ * 纯 Node + 依赖注入,单测拿 tmpdir 直测。+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++export interface TrashGhostLibraryDeps {+ /** 目标库根绝对路径(调用方经 binding/默认根解析;drift 时传 null)。 */+ resolveLibraryRoot(ghostId: string): Promise<string | null>;+ /** 回收站基目录(生产 = ownerScopedUserDataPath('libraries-trash'))。 */+ trashRoot(): string;+ /** 撤销自定义位置 binding(无 binding 时为空操作)。 */+ removeBinding(ghostId: string): Promise<void>;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+ now?(): number;+}++export type TrashGhostLibraryResult =+ | { ok: true; trashedPath: string }+ | { ok: false; errorCode: 'NOT_FOUND' | 'TRASH_NAME_TAKEN' | 'IO'; message: string };++/**+ * 把库根 rename 进回收站(同名冲突 = 返回错误,不覆盖——时间戳碰撞理论+ * 不可达,真发生时让调用方重试)。跨卷 rename 会退化为 copy+rm(fs.rename+ * 跨卷抛 EXDEV;自定义位置可能与回收站不同卷,这里显式回退)。+ */+export async function trashGhostLibrary(+ ghostId: string,+ deps: TrashGhostLibraryDeps,+): Promise<TrashGhostLibraryResult> {+ const root = await deps.resolveLibraryRoot(ghostId);+ if (root === null) {+ return { ok: false, errorCode: 'NOT_FOUND', message: 'Library 根不可用(位置漂移或不存在);请先在设置中恢复位置' };+ }+ let exists = true;+ try {+ await fs.promises.stat(root);+ } catch {+ exists = false;+ }+ if (!exists) {+ // 根不存在:只剩 binding 要撤(数据可能已被用户手工搬走/删除)。+ await deps.removeBinding(ghostId);+ return { ok: false, errorCode: 'NOT_FOUND', message: 'Library 目录不存在(已撤销位置记录)' };+ }+ const stamp = deps.now?.() ?? Date.now();+ const trashedPath = path.join(deps.trashRoot(), `${ghostId}-${stamp}`);+ try {+ await fs.promises.mkdir(deps.trashRoot(), { recursive: true });+ try {+ await fs.promises.rename(root, trashedPath);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'EXDEV') throw err;+ // 跨卷:copy 递归 → **逐项对账**(条数/字节)→ 才删源——不校验就 rm+ // 会让半份拷贝顶替原件(review:跨卷删源前先校验)。+ await copyDirRecursive(root, trashedPath);+ const before = await collectTreeStats(root);+ const after = await collectTreeStats(trashedPath);+ if (before.files !== after.files || before.bytes !== after.bytes) {+ throw new Error(`跨卷回收校验失败(${after.files}/${before.files} 文件,${after.bytes}/${before.bytes} 字节);原件保留未动`);+ }+ await fs.promises.rm(root, { recursive: true, force: true });+ }+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'EEXIST' || (err as NodeJS.ErrnoException).code === 'ENOTEMPTY') {+ return { ok: false, errorCode: 'TRASH_NAME_TAKEN', message: '回收站目标名冲突,请重试' };+ }+ return { ok: false, errorCode: 'IO', message: `移入回收站失败:${err instanceof Error ? err.message : String(err)}` };+ }+ await deps.removeBinding(ghostId);+ deps.log?.info('library trashed', { ghostId, trashedPath });+ return { ok: true, trashedPath };+}++/** 目录树统计(跨卷回收入库前的对账口径)。 */+async function collectTreeStats(root: string): Promise<{ files: number; bytes: number }> {+ let files = 0;+ let bytes = 0;+ const stack = [root];+ while (stack.length > 0) {+ const dir = stack.pop()!;+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(dir, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) stack.push(full);+ else if (entry.isFile()) {+ files += 1;+ try {+ bytes += (await fs.promises.stat(full)).size;+ } catch {+ /* 竞态,跳过 */+ }+ }+ }+ }+ return { files, bytes };+}++/** 递归复制(仅普通文件与目录;链接条目按链接复制,不穿透内容)。 */+async function copyDirRecursive(src: string, dest: string): Promise<void> {+ await fs.promises.mkdir(dest, { recursive: true });+ const entries = await fs.promises.readdir(src, { withFileTypes: true });+ for (const entry of entries) {+ const from = path.join(src, entry.name);+ const to = path.join(dest, entry.name);+ if (entry.isDirectory()) {+ await copyDirRecursive(from, to);+ } else if (entry.isSymbolicLink()) {+ const target = await fs.promises.readlink(from);+ await fs.promises.symlink(target, to).catch(() => {});+ } else if (entry.isFile()) {+ await fs.promises.copyFile(from, to);+ }+ }+}diff --git a/apps/desktop/src/main/cindy-brain/libraryVault.ts b/apps/desktop/src/main/cindy-brain/libraryVault.tsnew file mode 100644index 0000000000..52d2c0368d--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/libraryVault.ts@@ -0,0 +1,1274 @@+/**+ * libraryVault.ts — Durable Plugin Library 的文件层基座(2026-08-20 定案)。+ * ---------------------------------------------------------------------------+ * 与 fsSlot 的 root:'data'(插件私有储物柜,256MiB/2000 文件配额、卸载即回收)+ * 不同,Library 是**用户作品级**的持久存储:+ *+ * - 容量不受 ghost-fs 配额约束,只受磁盘保留水位与软水位(仅告警)约束;+ * - 卸载插件**不删**(由上层标 orphaned),删除必须走设置页独立确认;+ * - 所有写入原子化:staging(tmp + fsync)→ rename 就位 → identity(dev/ino)+ * 复验——对齐 dirDeposit.writeNewSaveFile 的 TOCTOU 范式,不沿用 fsSlot+ * data 档的裸 writeFile(崩溃会留截断文件);+ * - 大文件走分块流(writeBegin/Chunk/Commit),Commit 时核对宿主实算 sha256+ * ——这是未来网络同步「素材对象完整性校验」的地基,必须进首期契约;+ * - 宿主自有元数据放 `<root>/.cindy-library/`:插件相对路径的段首不许点+ * (isSafeGhostRelativePath),协议层天然写不进宿主命名空间。+ *+ * 「不可用 ≠ 空」是红线:meta 损坏 → state:'unavailable'(reason:'corrupt'),+ * 绝不静默重建空库;上层(槽/设置页)据此引导用户,不触发 GC、不判素材已删。+ *+ * 根目录依赖注入(规则 14):默认根(owners/<k>/libraries/<ghostId>)与自定义根+ * (binding 记录)对 vault 透明;单测拿 tmpdir 直测,零 Electron。+ */++import { randomUUID } from 'node:crypto';+import * as crypto from 'node:crypto';+import * as fs from 'node:fs';+import * as path from 'node:path';++import { isSafeGhostRelativePath } from '../../shared/ghost.js';++/** Library 操作的结构化错误码(fs 槽只有人话 message 的缺口在这里补上)。 */+export type LibraryErrorCode =+ | 'LIBRARY_UNAVAILABLE' // meta 损坏 / IO 故障 / 用量保险丝触发(fail closed)+ | 'LIBRARY_READONLY' // 迁移等场景显式置只读+ | 'DISK_FULL' // 磁盘剩余低于保留水位,写前拒绝(绝不写一半)+ | 'PATH_INVALID'+ | 'NOT_FOUND'+ | 'ALREADY_EXISTS'+ | 'TOO_LARGE'+ | 'STREAM_INVALID'+ | 'INTERNAL';++export type LibraryFailure = { ok: false; errorCode: LibraryErrorCode; message: string };+export type LibrarySuccess<T> = { ok: true } & T;+export type LibraryResult<T> = LibrarySuccess<T> | LibraryFailure;++/** 可整体注入覆盖的限额(生产用默认值;测试收小阈值走边界用例)。 */+export interface LibraryLimits {+ /** 单次 write / 单块 chunk 上限(与管子单消息预算对齐)。 */+ writeMaxBytes: number;+ readMaxBytes: number;+ pathMaxChars: number;+ pathMaxSegments: number;+ /** list 单页条数上限。 */+ listPageSize: number;+ /** 分块流总大小上限。 */+ streamMaxTotalBytes: number;+ /** 分块流闲置超时(超时残流按 Abort 清扫)。 */+ streamIdleTimeoutMs: number;+ /** 磁盘保留水位:剩余低于该值拒写。 */+ diskReserveBytes: number;+ /** 软水位:仅告警不阻断(status.softLimitExceeded)。 */+ softLimitBytes: number;+ /** staging 残渣清理龄。 */+ tmpMaxAgeMs: number;+ /** 用量全量扫描保险丝(条数);触发即 fail closed 拒写。 */+ usageScanFuse: number;+}++export const DEFAULT_LIBRARY_LIMITS: LibraryLimits = {+ writeMaxBytes: 16 * 1024 * 1024,+ readMaxBytes: 16 * 1024 * 1024,+ pathMaxChars: 512,+ pathMaxSegments: 32,+ listPageSize: 500,+ streamMaxTotalBytes: 8 * 1024 * 1024 * 1024,+ streamIdleTimeoutMs: 5 * 60 * 1000,+ diskReserveBytes: 1024 * 1024 * 1024,+ softLimitBytes: 8 * 1024 * 1024 * 1024,+ tmpMaxAgeMs: 24 * 60 * 60 * 1000,+ usageScanFuse: 50_000,+};++export type LibraryState = 'ready' | 'readonly' | 'unavailable';++/** 宿主元数据(.cindy-library/meta.json)。orphaned = 卸载后未删除的标记。 */+export interface LibraryMeta {+ version: 1;+ ghostId: string;+ createdAt: number;+ orphaned?: { at: number; name: string };+}++/** 用量账本(.cindy-library/usage.json);损坏/缺失时 open 触发全量重扫。 */+interface UsageLedger {+ files: number;+ bytes: number;+ updatedAt: number;+ mutations: number;+}++export interface LibraryVaultDeps {+ /** Library 根(生产 = 默认根或 binding 解析结果;每次现取,支持切换)。 */+ rootDir(): string;+ /** 归属插件 id(写进 meta 供设置页/回收站展示;缺省空串)。 */+ ghostId?: string;+ limits?: Partial<LibraryLimits>;+ /**+ * 卷剩余字节;null = 未知(探测失败)。未知时跳过写前硬闸,依赖 ENOSPC+ * 兜底——比假装知道更诚实。+ */+ getDiskFreeBytes?(root: string): Promise<number | null>;+ /** 位置类别(仅透传给 status;binding 层提供,默认系统管理位置)。 */+ locationKind?: 'default' | 'custom';+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+ now?(): number;+}++/** Windows 保留设备名(与 fsSlot/dirDeposit 同口径;目录名撞上同样出事)。 */+const WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i;++const META_DIR = '.cindy-library';+const META_FILE = 'meta.json';+const USAGE_FILE = 'usage.json';+const TMP_DIR = 'tmp';++/**+ * Library 相对路径校验:isSafeGhostRelativePath 之上再拒 Windows 保留设备名、+ * 尾点段(Windows 落盘静默剥尾点,回执名与真身不一致),外加段数/总长上限。+ * 与 fsSlot.validateFsRelPath 同纪律、不同限额:Library 需要承载+ * canvases/<id>/assets/objects/<shard>/<hash> 深度,段数放到 32、总长放到 512。+ * 返回 null = 合法,否则人话原因。+ */+export function validateLibraryRelPath(p: unknown, limits: LibraryLimits = DEFAULT_LIBRARY_LIMITS): string | null {+ if (typeof p !== 'string' || p.length === 0) return 'path 必填(相对路径,如 "canvases/c1/assets/x.png")';+ if (p.length > limits.pathMaxChars) return `path 超长(上限 ${limits.pathMaxChars} 字符)`;+ if (!isSafeGhostRelativePath(p)) {+ return 'path 必须是安全相对路径:正斜杠分段、无 "."/".."、每段以字母/数字/下划线开头(点开头目录是宿主命名空间,刻意不可写)';+ }+ const segments = p.split('/');+ if (segments.length > limits.pathMaxSegments) {+ return `path 层级过深(上限 ${limits.pathMaxSegments} 段)`;+ }+ for (const seg of segments) {+ if (WINDOWS_RESERVED_BASENAME_RE.test(seg)) {+ return `path 含 Windows 保留设备名段:${seg}`;+ }+ if (seg.endsWith('.')) {+ return `path 段不允许以点结尾(Windows 会静默剥掉尾点):${seg}`;+ }+ }+ return null;+}++/** 大小写折叠(Windows 路径不区分大小写;与 fsSlot 同实现,保持行为一致)。 */+function foldCase(p: string): string {+ return process.platform === 'win32' ? p.toLowerCase() : p;+}++/** target 是否落在 base 目录内(含 base 自身;两参都应是绝对路径)。 */+function isInsideDir(base: string, target: string): boolean {+ const b = foldCase(path.resolve(base));+ const t = foldCase(path.resolve(target));+ return t === b || t.startsWith(b + path.sep);+}++/**+ * symlink 逃逸校验:找 target 最深的已存在祖先,realpath 后必须仍在 realBase 内+ * (base 内的 symlink 目录指向外面 → 组合路径逃出根,必须拦)。+ */+async function deepestExistingAncestorInside(realBase: string, target: string): Promise<boolean> {+ let probe = target;+ for (;;) {+ const parent = path.dirname(probe);+ try {+ const real = await fs.promises.realpath(parent);+ return isInsideDir(realBase, real);+ } catch {+ if (parent === probe) return false; // 到根还不存在(理论不可达)+ probe = parent;+ }+ }+}++/** 解码写入内容(与 fsSlot.decodeContent 同策略:先按编码长度粗闸再解码)。 */+function decodeContent(+ content: unknown,+ encoding: unknown,+ maxBytes: number,+): { bytes: Buffer } | { errorCode: LibraryErrorCode; message: string } {+ if (typeof content !== 'string') return { errorCode: 'PATH_INVALID', message: '需要 content(字符串)' };+ if (encoding !== undefined && encoding !== 'utf8' && encoding !== 'base64') {+ return { errorCode: 'PATH_INVALID', message: 'encoding 只支持 "utf8" / "base64"' };+ }+ const overLimit = `内容超限(上限 ${maxBytes} 字节);大文件请走 writeBegin/Chunk/Commit 分块流`;+ let bytes: Buffer;+ if (encoding === 'base64') {+ if (content.length > (maxBytes * 4) / 3 + 8) return { errorCode: 'TOO_LARGE', message: overLimit };+ if (!/^[A-Za-z0-9+/=\r\n]*$/.test(content)) {+ return { errorCode: 'PATH_INVALID', message: 'content 不是合法 base64' };+ }+ bytes = Buffer.from(content, 'base64');+ } else {+ if (content.length > maxBytes) return { errorCode: 'TOO_LARGE', message: overLimit };+ bytes = Buffer.from(content, 'utf8');+ }+ if (bytes.byteLength > maxBytes) return { errorCode: 'TOO_LARGE', message: overLimit };+ return { bytes };+}++/** Node fs 错误 → 结构化失败(ENOENT 收敛为 NOT_FOUND,其余原样带 message)。 */+function fsFailure(err: unknown, fallback: LibraryErrorCode, message: string): LibraryFailure {+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code?: unknown }).code) : '';+ if (code === 'ENOENT') return { ok: false, errorCode: 'NOT_FOUND', message: '文件或目录不存在' };+ if (code === 'EEXIST' || code === 'ENOTEMPTY') {+ return { ok: false, errorCode: 'ALREADY_EXISTS', message: '目标已存在' };+ }+ return { ok: false, errorCode: fallback, message };+}++const fail = (errorCode: LibraryErrorCode, message: string): LibraryFailure => ({ ok: false, errorCode, message });++/** 在途分块流。tmp 文件独占创建,Commit 前 title 停在 staging 区。 */+interface ActiveStream {+ streamId: string;+ relPath: string;+ tmpAbs: string;+ totalBytes: number;+ sha256Declared: string | null;+ hash: crypto.Hash;+ written: number;+ nextSeq: number;+ ifNotExists: boolean;+ lastAt: number;+}++/**+ * LibraryVault — 单个 (owner × plugin) Library 的文件层实现。+ *+ * 并发模型:全部**变更类**操作(write 系/mkdir/delete/rename/meta/usage)经+ * runSerialized 串行——配额/用量判定与实际落盘之间不允许并发窗口(fsSlot 的+ * 已知缺口);读操作不串行(纯函数于账本快照)。+ */+export class LibraryVault {+ private readonly limits: LibraryLimits;+ private readonly now: () => number;++ private opened = false;+ private invalidated = false;+ private state: LibraryState = 'ready';+ private unavailableReason: string | null = null;+ private readonlyReason: string | null = null;+ /** 用量保险丝触发(扫描条数超限):fail closed 拒写,读照常。 */+ private usageTripped = false;+ private usage: UsageLedger = { files: 0, bytes: 0, updatedAt: 0, mutations: 0 };+ private meta: LibraryMeta | null = null;+ private readonly streams = new Map<string, ActiveStream>();+ /** 变更串行链(runSerialized 维护)。 */+ private chain: Promise<unknown> = Promise.resolve();++ constructor(private readonly deps: LibraryVaultDeps) {+ this.limits = { ...DEFAULT_LIBRARY_LIMITS, ...(deps.limits ?? {}) };+ this.now = deps.now ?? (() => Date.now());+ }++ /** 变更类操作串行化:后到操作排队在前序完成(无论成败)之后。 */+ private runSerialized<T>(fn: () => Promise<T>): Promise<T> {+ const next = this.chain.then(fn, fn);+ this.chain = next.catch(() => {});+ return next;+ }++ private get root(): string {+ return this.deps.rootDir();+ }+ private get metaDir(): string {+ return path.join(this.root, META_DIR);+ }+ private get metaFile(): string {+ return path.join(this.metaDir, META_FILE);+ }+ private get usageFile(): string {+ return path.join(this.metaDir, USAGE_FILE);+ }+ private get tmpDir(): string {+ return path.join(this.metaDir, TMP_DIR);+ }++ private tmpFailure(err: unknown, message: string): LibraryFailure {+ return fsFailure(err, 'INTERNAL', message);+ }++ /* ── 打开与状态 ─────────────────────────────────────────────────── */++ /**+ * 打开(幂等):建目录骨架 → 清理超龄 staging 残渣 → 读/建 meta → 读/扫+ * 用量账本。meta 存在但读不出/不合法 → unavailable(corrupt),**不重建**。+ */+ async open(): Promise<LibraryResult<{ state: LibraryState; reason: string | null; usedBytes: number; fileCount: number }>> {+ return this.runSerialized(async () => {+ if (this.invalidated) {+ return fail('LIBRARY_UNAVAILABLE', 'Library 实例已作废(owner 切换/宿主收口);请重新 open');+ }+ try {+ await fs.promises.mkdir(this.root, { recursive: true });+ await fs.promises.mkdir(this.tmpDir, { recursive: true });+ await fs.promises.mkdir(path.join(this.metaDir, 'backups'), { recursive: true });+ } catch (err) {+ this.state = 'unavailable';+ this.unavailableReason = 'permission';+ this.deps.log?.warn('library open: cannot create root', { error: err instanceof Error ? err.message : String(err) });+ return { ok: true as const, state: this.state, reason: this.unavailableReason, usedBytes: 0, fileCount: 0 };+ }+ await this.sweepStaleTmp();++ // meta:已存在必须可解析(不可用 ≠ 空);不存在则首建。+ try {+ const raw = await fs.promises.readFile(this.metaFile, 'utf8');+ const parsed = JSON.parse(raw) as LibraryMeta;+ if (+ typeof parsed !== 'object' || parsed === null || parsed.version !== 1 ||+ typeof parsed.ghostId !== 'string' || typeof parsed.createdAt !== 'number'+ ) {+ throw new Error('malformed meta');+ }+ this.meta = parsed;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ this.meta = { version: 1, ghostId: this.deps.ghostId ?? '', createdAt: this.now() };+ const w = await this.writeMetaUnlocked();+ if (w) return w;+ } else {+ this.opened = true;+ this.state = 'unavailable';+ this.unavailableReason = 'corrupt';+ this.deps.log?.warn('library open: meta unreadable; refusing to rebuild', {});+ return { ok: true as const, state: this.state, reason: this.unavailableReason, usedBytes: 0, fileCount: 0 };+ }+ }++ // 用量:账本读不出就全量重扫(账本是缓存,真身是文件树)。+ let ledger: UsageLedger | null = null;+ try {+ const raw = JSON.parse(await fs.promises.readFile(this.usageFile, 'utf8')) as UsageLedger;+ if (typeof raw === 'object' && raw !== null && typeof raw.files === 'number' && typeof raw.bytes === 'number') {+ ledger = { files: raw.files, bytes: raw.bytes, updatedAt: raw.updatedAt ?? 0, mutations: raw.mutations ?? 0 };+ }+ } catch {+ /* 损坏/缺失 → 重扫 */+ }+ if (!ledger) {+ const scanned = await this.scanUsageUnlocked();+ if (scanned.tripped) {+ this.usageTripped = true;+ this.usage = { files: scanned.files, bytes: scanned.bytes, updatedAt: this.now(), mutations: 0 };+ } else {+ this.usage = { files: scanned.files, bytes: scanned.bytes, updatedAt: this.now(), mutations: 0 };+ await this.persistUsageUnlocked();+ }+ } else {+ this.usage = ledger;+ }+ this.opened = true;+ if (this.state === 'unavailable') {+ // 上次 open 判过 corrupt 的进程内状态不跨实例;这里防御性复位,+ // 以本次实测为准。+ this.state = 'ready';+ this.unavailableReason = null;+ }+ return { ok: true as const, state: this.effectiveState(), reason: this.unavailableReason ?? this.readonlyReason, usedBytes: this.usage.bytes, fileCount: this.usage.files };+ });+ }++ private effectiveState(): LibraryState {+ if (this.state === 'unavailable') return 'unavailable';+ if (this.readonlyReason !== null) return 'readonly';+ return 'ready';+ }++ /** status:状态 + 占用 + 磁盘余量 + 软水位(软水位仅告警,不阻断写)。 */+ async status(): Promise<LibraryResult<{+ state: LibraryState;+ reason: string | null;+ usedBytes: number;+ fileCount: number;+ diskFreeBytes: number | null;+ softLimitBytes: number;+ softLimitExceeded: boolean;+ location: 'default' | 'custom';+ }>> {+ if (!this.opened) {+ const o = await this.open();+ if (!o.ok) return o;+ }+ let diskFree: number | null = null;+ if (this.deps.getDiskFreeBytes) {+ try {+ diskFree = await this.deps.getDiskFreeBytes(this.root);+ } catch {+ diskFree = null;+ }+ }+ return {+ ok: true as const,+ state: this.effectiveState(),+ reason: this.unavailableReason ?? this.readonlyReason,+ usedBytes: this.usage.bytes,+ fileCount: this.usage.files,+ diskFreeBytes: diskFree,+ softLimitBytes: this.limits.softLimitBytes,+ softLimitExceeded: this.usage.bytes > this.limits.softLimitBytes,+ location: this.deps.locationKind ?? 'default',+ };+ }++ /* ── 写前公共闸 ─────────────────────────────────────────────────── */++ private requireWritable(): LibraryFailure | null {+ if (this.state === 'unavailable') {+ return fail('LIBRARY_UNAVAILABLE', `Library 不可用(${this.unavailableReason ?? 'io'});不会当作空库处理`);+ }+ if (this.readonlyReason !== null) {+ return fail('LIBRARY_READONLY', `Library 只读(${this.readonlyReason})`);+ }+ if (this.usageTripped) {+ return fail('LIBRARY_UNAVAILABLE', 'Library 结构过大,无法核算占用;请清理后重试');+ }+ return null;+ }++ /** 磁盘保留水位检查(余量未知时跳过,依赖 ENOSPC 兜底)。 */+ private async checkDiskReserve(extraBytes: number): Promise<LibraryFailure | null> {+ if (!this.deps.getDiskFreeBytes) return null;+ let free: number | null = null;+ try {+ free = await this.deps.getDiskFreeBytes(this.root);+ } catch {+ return null;+ }+ if (free !== null && free - extraBytes < this.limits.diskReserveBytes) {+ return fail('DISK_FULL', `磁盘剩余空间低于保留水位(${this.limits.diskReserveBytes} 字节);请清理磁盘或迁移 Library`);+ }+ return null;+ }++ /** 解析并校验相对路径 → 绝对目标;含越界与祖先 symlink 收敛检查。 */+ private async resolveTarget(relPath: string): Promise<{ target: string; realBase: string } | LibraryFailure> {+ const base = this.root;+ let realBase: string;+ try {+ realBase = await fs.promises.realpath(base);+ } catch {+ return fail('LIBRARY_UNAVAILABLE', 'Library 根目录不可访问');+ }+ const target = path.join(base, ...relPath.split('/'));+ if (!isInsideDir(base, target)) return fail('PATH_INVALID', 'path 越界');+ if (!(await deepestExistingAncestorInside(realBase, target))) {+ return fail('PATH_INVALID', 'path 越界(中间目录含指向根外的符号链接)');+ }+ return { target, realBase };+ }++ /** 目标本身不得是 symlink(不穿透);返回 stat 或 null(不存在)。 */+ private async lstatTarget(target: string): Promise<fs.Stats | null> {+ try {+ return await fs.promises.lstat(target);+ } catch {+ return null;+ }+ }++ /* ── 原子写核心 ─────────────────────────────────────────────────── */++ /**+ * 原子落盘:tmp 独占创建(wx)→ 写 → fsync → rename/link 就位 → identity+ * (dev/ino)复验。ifNotExists 用 link+EEXIST(原子排他);覆盖用 rename+ * (libuv 在 Windows 走 MoveFileEx REPLACE_EXISTING,同为原子替换)。+ * 目录 fsync 在 Windows 不可用(无法 open 目录 fd),跨平台只保证文件体+ * fsync——崩溃最坏留 tmp 残渣(sweepStaleTmp 清理),不留半成品于终位。+ */+ private async atomicWrite(+ target: string,+ bytes: Buffer,+ opts: { ifNotExists?: boolean } = {},+ ): Promise<LibraryResult<{ dev: number; ino: number }>> {+ const tmp = path.join(this.tmpDir, `${randomUUID()}.tmp`);+ let openedStat: fs.Stats | null = null;+ let fh: fs.promises.FileHandle | null = null;+ try {+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ fh = await fs.promises.open(tmp, 'wx', 0o600);+ await fh.writeFile(bytes);+ await fh.sync();+ openedStat = await fh.stat();+ await fh.close();+ fh = null;+ if (opts.ifNotExists) {+ try {+ await fs.promises.link(tmp, target);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') {+ return fail('ALREADY_EXISTS', '目标已存在(ifNotExists)');+ }+ throw err;+ }+ await fs.promises.unlink(tmp).catch(() => {});+ } else {+ await fs.promises.rename(tmp, target);+ }+ const after = await this.lstatTarget(target);+ if (!after || !after.isFile() || after.dev !== openedStat.dev || after.ino !== openedStat.ino) {+ // 就位后被换(或落到了非预期对象):如实报内部错误,不静默。+ return fail('INTERNAL', '写入就位校验失败(目标 identity 不一致)');+ }+ return { ok: true as const, dev: after.dev, ino: after.ino };+ } catch (err) {+ return this.tmpFailure(err, '写入失败(主机 IO 错误)');+ } finally {+ if (fh) await fh.close().catch(() => {});+ await fs.promises.unlink(tmp).catch(() => {});+ }+ }++ /** 元数据/账本小文件写(meta 目录内,自身也走原子写)。 */+ private async writeJsonAtomic(absFile: string, value: unknown): Promise<LibraryResult<{ dev: number; ino: number }>> {+ return this.atomicWrite(absFile, Buffer.from(JSON.stringify(value, null, 2), 'utf8'));+ }++ private async writeMetaUnlocked(): Promise<LibraryFailure | null> {+ if (!this.meta) return fail('INTERNAL', 'meta 未初始化');+ const w = await this.writeJsonAtomic(this.metaFile, this.meta);+ return w.ok ? null : w;+ }++ private async persistUsageUnlocked(): Promise<void> {+ if (!this.meta) return;+ this.usage.updatedAt = this.now();+ await this.writeJsonAtomic(this.usageFile, this.usage).catch((err) => {+ this.deps.log?.warn('library usage persist failed', { error: err instanceof Error ? err.message : String(err) });+ });+ }++ /** 清理超龄 staging 残渣(崩溃遗留;龄 > tmpMaxAgeMs)。 */+ private async sweepStaleTmp(): Promise<void> {+ const cutoff = this.now() - this.limits.tmpMaxAgeMs;+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(this.tmpDir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (!entry.isFile()) continue; // 非普通条目不动(对齐受管根纪律)+ const full = path.join(this.tmpDir, entry.name);+ try {+ const st = await fs.promises.stat(full);+ if (st.mtimeMs < cutoff) await fs.promises.unlink(full);+ } catch {+ /* 竞态,跳过 */+ }+ }+ }++ /** 用量全量扫描(条数保险丝;触发 fail closed,见 requireWritable)。+ * 宿主命名空间 .cindy-library/ 不计入——那是 meta/账本/staging,不是插件作品。 */+ private async scanUsageUnlocked(): Promise<{ files: number; bytes: number; tripped: boolean }> {+ let files = 0;+ let bytes = 0;+ let visited = 0;+ const stack: string[] = [this.root];+ while (stack.length > 0) {+ const dir = stack.pop()!;+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(dir, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (dir === this.root && entry.name === META_DIR) continue; // 宿主命名空间不入账+ if (++visited > this.limits.usageScanFuse) return { files, bytes, tripped: true };+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) stack.push(full);+ else if (entry.isFile()) {+ files += 1;+ try {+ bytes += (await fs.promises.stat(full)).size;+ } catch {+ /* 竞态删除,跳过 */+ }+ }+ }+ }+ return { files, bytes, tripped: false };+ }++ /* ── 文件操作 ───────────────────────────────────────────────────── */++ async read(req: { path: unknown; encoding?: unknown; offset?: unknown; length?: unknown }): Promise<LibraryResult<{ path: string; content: string; encoding: 'utf8' | 'base64'; bytes: number; sha256: string }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ const reason = validateLibraryRelPath(req.path, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ const relPath = req.path as string;+ if (req.encoding !== undefined && req.encoding !== 'utf8' && req.encoding !== 'base64') {+ return fail('PATH_INVALID', 'encoding 只支持 "utf8" / "base64"');+ }+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return resolved;+ const st = await this.lstatTarget(resolved.target);+ if (!st) return fail('NOT_FOUND', `文件不存在:${relPath}`);+ if (!st.isFile()) return fail('PATH_INVALID', `不是文件:${relPath}`);+ const offset = typeof req.offset === 'number' && Number.isInteger(req.offset) && req.offset >= 0 ? req.offset : 0;+ if (offset > st.size) return fail('PATH_INVALID', `offset 超出文件大小(${st.size})`);+ let length = st.size - offset;+ if (typeof req.length === 'number' && Number.isInteger(req.length) && req.length >= 0) {+ length = Math.min(length, req.length);+ }+ if (length > this.limits.readMaxBytes) {+ return fail('TOO_LARGE', `读取长度超上限(${length} > ${this.limits.readMaxBytes});请用 offset/length 分段读`);+ }+ try {+ const fh = await fs.promises.open(resolved.target, 'r');+ try {+ const buf = Buffer.alloc(length);+ const { bytesRead } = length === 0 ? { bytesRead: 0 } : await fh.read(buf, 0, length, offset);+ const out = buf.subarray(0, bytesRead);+ const encoding = req.encoding === 'base64' ? ('base64' as const) : ('utf8' as const);+ return {+ ok: true as const,+ path: relPath,+ content: out.toString(encoding),+ encoding,+ bytes: bytesRead,+ sha256: crypto.createHash('sha256').update(out).digest('hex'),+ };+ } finally {+ await fh.close();+ }+ } catch (err) {+ return this.tmpFailure(err, '读取失败(主机 IO 错误)');+ }+ }++ async write(req: { path: unknown; content: unknown; encoding?: unknown; ifNotExists?: unknown }): Promise<LibraryResult<{ path: string; bytes: number; sha256: string }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ return this.runSerialized(async () => {+ const gate = this.requireWritable();+ if (gate) return gate;+ const reason = validateLibraryRelPath(req.path, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ const relPath = req.path as string;+ const decoded = decodeContent(req.content, req.encoding, this.limits.writeMaxBytes);+ if (!('bytes' in decoded)) return fail(decoded.errorCode, decoded.message);+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return resolved;+ const st = await this.lstatTarget(resolved.target);+ if (st) {+ if (st.isSymbolicLink()) return fail('PATH_INVALID', '目标是符号链接,拒绝穿透写入');+ if (st.isDirectory()) return fail('PATH_INVALID', `目标是目录:${relPath}`);+ }+ const disk = await this.checkDiskReserve(decoded.bytes.byteLength);+ if (disk) return disk;+ const existedBytes = st && st.isFile() ? st.size : 0;+ const w = await this.atomicWrite(resolved.target, decoded.bytes, {+ ifNotExists: req.ifNotExists === true,+ });+ if (!w.ok) return w;+ // 用量增量记账(files/bytes);覆盖写扣除旧体积。+ this.usage.bytes += decoded.bytes.byteLength - existedBytes;+ if (!st) this.usage.files += 1;+ this.usage.mutations += 1;+ await this.persistUsageUnlocked();+ return {+ ok: true as const,+ path: relPath,+ bytes: decoded.bytes.byteLength,+ sha256: crypto.createHash('sha256').update(decoded.bytes).digest('hex'),+ };+ });+ }++ async writeBegin(req: { path: unknown; totalBytes: unknown; sha256?: unknown }): Promise<LibraryResult<{ streamId: string }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ return this.runSerialized(async () => {+ const gate = this.requireWritable();+ if (gate) return gate;+ const reason = validateLibraryRelPath(req.path, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ const relPath = req.path as string;+ if (typeof req.totalBytes !== 'number' || !Number.isInteger(req.totalBytes) || req.totalBytes < 0) {+ return fail('PATH_INVALID', 'totalBytes 必须是非负整数');+ }+ if (req.totalBytes > this.limits.streamMaxTotalBytes) {+ return fail('TOO_LARGE', `分块流总大小超上限(${this.limits.streamMaxTotalBytes} 字节)`);+ }+ if (req.sha256 !== undefined && (typeof req.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(req.sha256))) {+ return fail('PATH_INVALID', 'sha256 必须是 64 位小写十六进制');+ }+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return resolved;+ const st = await this.lstatTarget(resolved.target);+ if (st) {+ if (st.isSymbolicLink()) return fail('PATH_INVALID', '目标是符号链接,拒绝穿透写入');+ if (st.isDirectory()) return fail('PATH_INVALID', `目标是目录:${relPath}`);+ }+ const disk = await this.checkDiskReserve(req.totalBytes);+ if (disk) return disk;+ await this.sweepIdleStreamsUnlocked();+ const streamId = randomUUID();+ const tmpAbs = path.join(this.tmpDir, `${streamId}.stream`);+ try {+ const fh = await fs.promises.open(tmpAbs, 'wx', 0o600);+ await fh.close();+ } catch (err) {+ return this.tmpFailure(err, '分块流创建失败(主机 IO 错误)');+ }+ this.streams.set(streamId, {+ streamId,+ relPath,+ tmpAbs,+ totalBytes: req.totalBytes,+ sha256Declared: (req.sha256 as string | undefined) ?? null,+ hash: crypto.createHash('sha256'),+ written: 0,+ nextSeq: 1,+ ifNotExists: false,+ lastAt: this.now(),+ });+ return { ok: true as const, streamId };+ });+ }++ async writeChunk(req: { streamId: unknown; seq: unknown; content: unknown; encoding?: unknown }): Promise<LibraryResult<{ accepted: number }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ // 分块也走串行链:seq 判定与追加落盘之间不允许并发窗口(并发同 seq 会双写)。+ return this.runSerialized(async () => {+ const gate = this.requireWritable();+ if (gate) return gate;+ const stream = typeof req.streamId === 'string' ? this.streams.get(req.streamId) : undefined;+ if (!stream) return fail('STREAM_INVALID', 'streamId 无效或已结束');+ if (typeof req.seq !== 'number' || !Number.isInteger(req.seq) || req.seq !== stream.nextSeq) {+ return fail('STREAM_INVALID', `seq 必须从 1 起连续(期望 ${stream.nextSeq})`);+ }+ const decoded = decodeContent(req.content, req.encoding, this.limits.writeMaxBytes);+ if (!('bytes' in decoded)) return fail(decoded.errorCode, decoded.message);+ if (stream.written + decoded.bytes.byteLength > stream.totalBytes) {+ return fail('STREAM_INVALID', `累计字节数将超出声明的 totalBytes(${stream.totalBytes})`);+ }+ try {+ const fh = await fs.promises.open(stream.tmpAbs, 'a');+ try {+ await fh.writeFile(decoded.bytes);+ } finally {+ await fh.close();+ }+ } catch (err) {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ return this.tmpFailure(err, '分块写入失败(主机 IO 错误)');+ }+ stream.hash.update(decoded.bytes);+ stream.written += decoded.bytes.byteLength;+ stream.nextSeq += 1;+ stream.lastAt = this.now();+ return { ok: true as const, accepted: decoded.bytes.byteLength };+ });+ }++ async writeCommit(req: { streamId: unknown }): Promise<LibraryResult<{ path: string; bytes: number; sha256: string }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ return this.runSerialized(async () => {+ const gate = this.requireWritable();+ if (gate) return gate;+ const stream = typeof req.streamId === 'string' ? this.streams.get(req.streamId) : undefined;+ if (!stream) return fail('STREAM_INVALID', 'streamId 无效或已结束');+ if (stream.written !== stream.totalBytes) {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ return fail('STREAM_INVALID', `字节数不完整(已收 ${stream.written} / 声明 ${stream.totalBytes})`);+ }+ const sha256 = stream.hash.digest('hex');+ if (stream.sha256Declared !== null && sha256 !== stream.sha256Declared) {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ return fail('STREAM_INVALID', 'sha256 校验失败(声明值与实际字节不一致)');+ }+ // fsync staging 后走与 write 相同的就位+复验路径。+ try {+ const fh = await fs.promises.open(stream.tmpAbs, 'r+');+ try {+ await fh.sync();+ } finally {+ await fh.close();+ }+ } catch (err) {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ return this.tmpFailure(err, '分块提交失败(主机 IO 错误)');+ }+ const resolved = await this.resolveTarget(stream.relPath);+ if (!('target' in resolved)) {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ return resolved;+ }+ const prior = await this.lstatTarget(resolved.target);+ const existedBytes = prior && prior.isFile() ? prior.size : 0;+ try {+ await fs.promises.mkdir(path.dirname(resolved.target), { recursive: true });+ await fs.promises.rename(stream.tmpAbs, resolved.target);+ } catch (err) {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ return this.tmpFailure(err, '分块提交失败(主机 IO 错误)');+ }+ const after = await this.lstatTarget(resolved.target);+ if (!after || !after.isFile()) {+ return fail('INTERNAL', '分块提交就位校验失败');+ }+ this.streams.delete(stream.streamId);+ this.usage.bytes += stream.totalBytes - existedBytes;+ if (!prior) this.usage.files += 1;+ this.usage.mutations += 1;+ await this.persistUsageUnlocked();+ return { ok: true as const, path: stream.relPath, bytes: stream.totalBytes, sha256 };+ });+ }++ async writeAbort(req: { streamId: unknown }): Promise<LibraryResult<{ aborted: boolean }>> {+ const stream = typeof req.streamId === 'string' ? this.streams.get(req.streamId) : undefined;+ if (!stream) return { ok: true as const, aborted: false }; // 幂等+ return this.runSerialized(async () => {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ return { ok: true as const, aborted: true };+ });+ }++ private async abortStreamUnlocked(streamId: string): Promise<void> {+ const stream = this.streams.get(streamId);+ if (!stream) return;+ this.streams.delete(streamId);+ await fs.promises.unlink(stream.tmpAbs).catch(() => {});+ }++ /** 闲置超时残流清扫(挂在 writeBegin 的串行链上)。 */+ private async sweepIdleStreamsUnlocked(): Promise<void> {+ const cutoff = this.now() - this.limits.streamIdleTimeoutMs;+ for (const stream of Array.from(this.streams.values())) {+ if (stream.lastAt < cutoff) await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ }+ }++ async stat(req: { path: unknown }): Promise<LibraryResult<{ path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ const reason = validateLibraryRelPath(req.path, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ const relPath = req.path as string;+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return resolved;+ const st = await this.lstatTarget(resolved.target);+ if (!st) return fail('NOT_FOUND', `不存在:${relPath}`);+ if (st.isFile()) {+ return { ok: true as const, path: relPath, kind: 'file', bytes: st.size, mtime: Math.round(st.mtimeMs) };+ }+ if (st.isDirectory()) {+ return { ok: true as const, path: relPath, kind: 'dir', bytes: 0, mtime: Math.round(st.mtimeMs) };+ }+ return fail('PATH_INVALID', `不是普通文件或目录:${relPath}`);+ }++ async mkdir(req: { path: unknown }): Promise<LibraryResult<{ path: string; existed: boolean }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ return this.runSerialized(async () => {+ const gate = this.requireWritable();+ if (gate) return gate;+ const reason = validateLibraryRelPath(req.path, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ const relPath = req.path as string;+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return resolved;+ const prior = await this.lstatTarget(resolved.target);+ if (prior) {+ if (!prior.isDirectory()) return fail('ALREADY_EXISTS', `目标已存在且不是目录:${relPath}`);+ return { ok: true as const, path: relPath, existed: true };+ }+ try {+ await fs.promises.mkdir(resolved.target, { recursive: true });+ } catch (err) {+ return this.tmpFailure(err, '创建目录失败(主机 IO 错误)');+ }+ return { ok: true as const, path: relPath, existed: false };+ });+ }++ async list(req: { path?: unknown; recursive?: unknown; cursor?: unknown; limit?: unknown }): Promise<LibraryResult<{ entries: Array<{ path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }>; hasMore: boolean; nextCursor: string | null }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ const sub = req.path === undefined || req.path === '' ? '' : String(req.path);+ if (sub !== '') {+ const reason = validateLibraryRelPath(sub, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ }+ const base = this.root;+ const listRoot = sub === '' ? base : path.join(base, ...sub.split('/'));+ if (!isInsideDir(base, listRoot)) return fail('PATH_INVALID', 'path 越界');+ const recursive = req.recursive === true;+ const limit = Math.min(+ typeof req.limit === 'number' && Number.isInteger(req.limit) && req.limit > 0 ? req.limit : this.limits.listPageSize,+ this.limits.listPageSize,+ );+ let afterPath: string | null = null;+ if (req.cursor !== undefined && req.cursor !== null) {+ if (typeof req.cursor !== 'string' || req.cursor.length === 0 || !/^[A-Za-z0-9+/=_-]+$/.test(req.cursor)) {+ return fail('PATH_INVALID', 'cursor 非法');+ }+ try {+ const decoded = Buffer.from(req.cursor, 'base64').toString('utf8');+ if (!isSafeGhostRelativePath(decoded)) return fail('PATH_INVALID', 'cursor 非法');+ afterPath = decoded;+ } catch {+ return fail('PATH_INVALID', 'cursor 非法');+ }+ }+ const entries: Array<{ path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }> = [];+ let hasMore = false;+ const push = (rel: string, kind: 'file' | 'dir', bytes: number, mtime: number): boolean => {+ if (afterPath !== null && rel <= afterPath) return true; // 游标之前:跳过但继续走+ if (entries.length >= limit) {+ hasMore = true;+ return false;+ }+ entries.push({ path: rel, kind, bytes, mtime });+ return true;+ };+ try {+ if (!recursive) {+ const dirents = await fs.promises.readdir(listRoot, { withFileTypes: true });+ const names = dirents.map((d) => d.name).filter((n) => !(listRoot === base && n === META_DIR)).sort();+ for (const name of names) {+ const full = path.join(listRoot, name);+ let st: fs.Stats;+ try {+ st = await fs.promises.lstat(full);+ } catch {+ continue;+ }+ const rel = path.relative(base, full).split(path.sep).join('/');+ if (st.isFile()) {+ if (!push(rel, 'file', st.size, Math.round(st.mtimeMs))) break;+ } else if (st.isDirectory()) {+ if (!push(rel, 'dir', 0, Math.round(st.mtimeMs))) break;+ }+ }+ } else {+ // 递归:先收集全部相对路径(不 stat),全局排序后按游标切片,只为当页+ // 条目取 stat——游标续页要求全局字典序,DFS 逐层排序拼不出全局序。+ const all: Array<{ rel: string; abs: string; isDir: boolean }> = [];+ const stack: string[] = [listRoot];+ while (stack.length > 0) {+ const dir = stack.pop()!;+ let dirents: fs.Dirent[];+ try {+ dirents = await fs.promises.readdir(dir, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of dirents) {+ if (dir === base && entry.name === META_DIR) continue; // 宿主命名空间不可见+ const full = path.join(dir, entry.name);+ const rel = path.relative(base, full).split(path.sep).join('/');+ if (entry.isDirectory()) {+ all.push({ rel, abs: full, isDir: true });+ stack.push(full);+ } else if (entry.isFile()) {+ all.push({ rel, abs: full, isDir: false });+ }+ }+ }+ all.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));+ for (const item of all) {+ if (afterPath !== null && item.rel <= afterPath) continue;+ if (entries.length >= limit) {+ hasMore = true;+ break;+ }+ let st: fs.Stats;+ try {+ st = await fs.promises.lstat(item.abs);+ } catch {+ continue;+ }+ if (item.isDir) entries.push({ path: item.rel, kind: 'dir', bytes: 0, mtime: Math.round(st.mtimeMs) });+ else entries.push({ path: item.rel, kind: 'file', bytes: st.size, mtime: Math.round(st.mtimeMs) });+ }+ }+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ return { ok: true as const, entries: [], hasMore: false, nextCursor: null };+ }+ return this.tmpFailure(err, '列目录失败(主机 IO 错误)');+ }+ const nextCursor = hasMore && entries.length > 0+ ? Buffer.from(entries[entries.length - 1].path, 'utf8').toString('base64')+ : null;+ return { ok: true as const, entries, hasMore, nextCursor };+ }++ async delete(req: { path: unknown; recursive?: unknown }): Promise<LibraryResult<{ path: string; existed: boolean }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ return this.runSerialized(async () => {+ const gate = this.requireWritable();+ if (gate) return gate;+ const reason = validateLibraryRelPath(req.path, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ const relPath = req.path as string;+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return resolved;+ const st = await this.lstatTarget(resolved.target);+ if (!st) return { ok: true as const, path: relPath, existed: false }; // 幂等+ let removedBytes = 0;+ let removedFiles = 0;+ if (st.isDirectory()) {+ if (req.recursive === true) {+ const usage = await this.scanDirUsage(resolved.target);+ try {+ await fs.promises.rm(resolved.target, { recursive: true, force: false });+ } catch (err) {+ return this.tmpFailure(err, '删除目录失败(主机 IO 错误)');+ }+ removedBytes = usage.bytes;+ removedFiles = usage.files;+ } else {+ try {+ await fs.promises.rmdir(resolved.target);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOTEMPTY') {+ return fail('ALREADY_EXISTS', '目录非空;需要 recursive:true 才能递归删除');+ }+ return this.tmpFailure(err, '删除目录失败(主机 IO 错误)');+ }+ }+ } else if (st.isFile() || st.isSymbolicLink()) {+ // 库内 symlink(插件造不出来,但磁盘可能有):unlink 链接本身,不穿透。+ try {+ await fs.promises.unlink(resolved.target);+ } catch (err) {+ return this.tmpFailure(err, '删除文件失败(主机 IO 错误)');+ }+ removedBytes = st.isFile() ? st.size : 0;+ removedFiles = 1;+ // 空目录剪枝(向上 rmdir 到根为止,遇非空即停):不剪则目录残骸永久+ // 计入用量扫描(与 fsSlot 同教训)。+ let dir = path.dirname(resolved.target);+ while (isInsideDir(this.root, dir) && foldCase(dir) !== foldCase(path.resolve(this.root))) {+ try {+ await fs.promises.rmdir(dir);+ } catch {+ break;+ }+ dir = path.dirname(dir);+ }+ } else {+ return fail('PATH_INVALID', `不是可删除对象:${relPath}`);+ }+ this.usage.bytes = Math.max(0, this.usage.bytes - removedBytes);+ this.usage.files = Math.max(0, this.usage.files - removedFiles);+ this.usage.mutations += 1;+ await this.persistUsageUnlocked();+ return { ok: true as const, path: relPath, existed: true };+ });+ }++ private async scanDirUsage(dir: string): Promise<{ files: number; bytes: number }> {+ let files = 0;+ let bytes = 0;+ const stack = [dir];+ while (stack.length > 0) {+ const cur = stack.pop()!;+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(cur, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ const full = path.join(cur, entry.name);+ if (entry.isDirectory()) stack.push(full);+ else if (entry.isFile()) {+ files += 1;+ try {+ bytes += (await fs.promises.stat(full)).size;+ } catch {+ /* 竞态,跳过 */+ }+ }+ }+ }+ return { files, bytes };+ }++ async rename(req: { from: unknown; to: unknown; overwrite?: unknown }): Promise<LibraryResult<{ from: string; to: string }>> {+ if (!this.opened) return fail('LIBRARY_UNAVAILABLE', 'Library 未打开(先调用 open)');+ return this.runSerialized(async () => {+ const gate = this.requireWritable();+ if (gate) return gate;+ for (const p of [req.from, req.to]) {+ const reason = validateLibraryRelPath(p, this.limits);+ if (reason) return fail('PATH_INVALID', reason);+ }+ const from = req.from as string;+ const to = req.to as string;+ if (from === to) return { ok: true as const, from, to };+ const src = await this.resolveTarget(from);+ if (!('target' in src)) return src;+ const dst = await this.resolveTarget(to);+ if (!('target' in dst)) return dst;+ const st = await this.lstatTarget(src.target);+ if (!st) return fail('NOT_FOUND', `源不存在:${from}`);+ if (!st.isFile()) return fail('PATH_INVALID', `只能重命名文件(目录请逐文件处理):${from}`);+ const prior = await this.lstatTarget(dst.target);+ if (prior) {+ if (prior.isSymbolicLink()) return fail('PATH_INVALID', '目标是符号链接,拒绝覆盖');+ if (prior.isDirectory()) return fail('PATH_INVALID', `目标是目录:${to}`);+ if (req.overwrite !== true) return fail('ALREADY_EXISTS', `目标已存在:${to}(需 overwrite:true 才覆盖)`);+ }+ const disk = await this.checkDiskReserve(0);+ if (disk) return disk;+ const identity = { dev: st.dev, ino: st.ino };+ try {+ await fs.promises.mkdir(path.dirname(dst.target), { recursive: true });+ if (req.overwrite === true) {+ await fs.promises.rename(src.target, dst.target);+ } else {+ // 原子排他:link 失败 EEXIST = 目标刚被并发创建;成功后 unlink 源。+ // link+unlink 两步之间崩溃会留下两份同容文件(内容不变,无损坏),+ // 下次覆盖写/rename 自愈——比「先查再 rename」的 TOCTOU 窗口安全。+ await fs.promises.link(src.target, dst.target);+ await fs.promises.unlink(src.target);+ }+ } catch (err) {+ return this.tmpFailure(err, '重命名失败(主机 IO 错误)');+ }+ const after = await this.lstatTarget(dst.target);+ if (!after || after.dev !== identity.dev || after.ino !== identity.ino) {+ return fail('INTERNAL', '重命名就位校验失败(identity 不一致)');+ }+ // 账本:文件数不变;覆盖替换时扣掉被替换文件的体积与计数。+ if (prior && prior.isFile()) {+ this.usage.bytes = Math.max(0, this.usage.bytes - prior.size);+ this.usage.files = Math.max(0, this.usage.files - 1);+ }+ this.usage.mutations += 1;+ await this.persistUsageUnlocked();+ // 源空目录剪枝(rename 腾出的父目录不残留)。+ let dir = path.dirname(src.target);+ while (isInsideDir(this.root, dir) && foldCase(dir) !== foldCase(path.resolve(this.root))) {+ try {+ await fs.promises.rmdir(dir);+ } catch {+ break;+ }+ dir = path.dirname(dir);+ }+ return { ok: true as const, from, to };+ });+ }++ /* ── 生命周期与显式状态控制 ─────────────────────────────────────── */++ /** 卸载标记(上层 uninstall 流程调用;数据本体不动)。 */+ async markOrphaned(displayName: string): Promise<LibraryFailure | null> {+ return this.runSerialized(async () => {+ if (!this.meta) return fail('INTERNAL', 'meta 未初始化');+ this.meta = { ...this.meta, orphaned: { at: this.now(), name: displayName } };+ return this.writeMetaUnlocked();+ });+ }++ /** 重装清除卸载标记。 */+ async clearOrphaned(): Promise<LibraryFailure | null> {+ return this.runSerialized(async () => {+ if (!this.meta) return fail('INTERNAL', 'meta 未初始化');+ if (!('orphaned' in this.meta)) return null;+ this.meta = { version: this.meta.version, ghostId: this.meta.ghostId, createdAt: this.meta.createdAt };+ return this.writeMetaUnlocked();+ });+ }++ getMeta(): Readonly<LibraryMeta> | null {+ return this.meta;+ }++ /** 库根绝对路径(宿主侧代码用:面板路由/备份目标等;不经插件)。 */+ getRootDir(): string {+ return this.root;+ }++ /**+ * 面板投影路由(cindy-ghost://<id>/library/<relPath>)的宿主侧解析:+ * 相对路径 → 已存在普通文件的绝对路径。路径纪律与 read 同源;任何校验+ * 不过(越界/symlink/不存在/是目录)返回 null,调用方统一折叠 404。+ */+ async resolveExistingFile(relPath: string): Promise<string | null> {+ const reason = validateLibraryRelPath(relPath, this.limits);+ if (reason) return null;+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return null;+ const st = await this.lstatTarget(resolved.target);+ if (!st || !st.isFile()) return null;+ return resolved.target;+ }++ /**+ * dbPath(库内 .sqlite 相对路径)→ 绝对路径,走与 read 同源的收敛校验+ * (库内预置的目录 symlink 指向根外时,合法相对 dbPath 也拒——SQLite 打开+ * 的文件必须落在库根内,review:dbPath 绕过 symlink 收敛)。文件本体可以+ * 不存在(新建库),校验只针对路径与祖先。+ */+ async resolveDbTarget(relPath: string): Promise<string | null> {+ const reason = validateLibraryRelPath(relPath, this.limits);+ if (reason) return null;+ const resolved = await this.resolveTarget(relPath);+ if (!('target' in resolved)) return null;+ const st = await this.lstatTarget(resolved.target);+ if (st && !st.isFile() && !st.isSymbolicLink()) return null; // 目录/非常规对象不可当库+ return resolved.target;+ }++ /** 迁移等场景显式置只读(读写闸见 requireWritable)。 */+ setReadonly(reason: string): void {+ this.readonlyReason = reason;+ }++ clearReadonly(): void {+ this.readonlyReason = null;+ }++ /**+ * 用量对账(全量重扫 + 重写账本 + 保险丝复核)。open 时自动做一次;+ * 设置页/清理流程可显式调用(例如用户手工清理大目录之后)。+ */+ async reconcileUsage(): Promise<LibraryResult<{ files: number; bytes: number; tripped: boolean }>> {+ return this.runSerialized(async () => {+ const scanned = await this.scanUsageUnlocked();+ this.usageTripped = scanned.tripped;+ this.usage = { files: scanned.files, bytes: scanned.bytes, updatedAt: this.now(), mutations: 0 };+ await this.persistUsageUnlocked();+ return { ok: true as const, files: scanned.files, bytes: scanned.bytes, tripped: scanned.tripped };+ });+ }++ /** owner 切换/宿主收口:作废在途流并拒绝后续操作(实例弃用,不可重开)。 */+ async invalidate(): Promise<void> {+ await this.runSerialized(async () => {+ for (const stream of Array.from(this.streams.values())) {+ await this.abortStreamUnlocked(stream.streamId).catch(() => {});+ }+ });+ this.invalidated = true;+ this.state = 'unavailable';+ this.unavailableReason = 'io';+ }+}++/**+ * 默认卷余量探测:优先 fs.statfs(Node ≥ 18.15 / Electron 新版),不可用+ * 返回 null(上层跳过写前硬闸,依赖 ENOSPC 兜底)。独立导出便于测试注入。+ */+export async function statfsFreeBytes(root: string): Promise<number | null> {+ const statfs = (fs.promises as unknown as { statfs?: (p: string) => Promise<{ bsize: number; bavail: number }> }).statfs;+ if (typeof statfs !== 'function') return null;+ try {+ const st = await statfs(root);+ return st.bsize * st.bavail;+ } catch {+ return null;+ }+}diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.tsindex d7c1c4cefa..47a56032ae 100644--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts@@ -1,5 +1,7 @@import { BrowserWindow, session, webContents, type CustomScheme } from 'electron';import fs from 'node:fs/promises';+import * as nodeFs from 'node:fs';+import { Readable } from 'node:stream';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -271,6 +273,13 @@ function registerGhostProtocol(partition: string, ghost: InstalledGhost): void {if (url.pathname.startsWith('/media/')) {return serveGhostMedia(ghostId, url.pathname.slice('/media/'.length), request.headers.get('range'));}+ // /library/<相对路径>:面板只读投影本意识的持久作品库文件(图片/视频/+ // 导出物)。解析器由 cindy-brain/index 注入(binding 根 + vault 路径纪律,+ // 与电子脑 read 同源校验);内容可变,Cache-Control 走 no-cache(与+ // 内容寻址的 /media 长缓存不同)。失败统一折叠 404。+ if (url.pathname.startsWith('/library/')) {+ return serveGhostLibraryFile(ghostId, decodeURIComponent(url.pathname.slice('/library/'.length)), request.headers.get('range'));+ }// /gallery:本意识画廊清单(重启回放)。分区专属通道天然只答自己的账;// 内容只有指纹地址与备注字符串,零文件字节。if (url.pathname === '/gallery') {@@ -486,6 +495,101 @@ async function serveGhostMedia(}}+/**+ * library 文件供给器(由 cindy-brain/index 注入,防 runtime ↔ index 循环依赖):+ * ghostId + 相对路径 → 已校验文件的绝对路径;null = 折叠 404。注入前 /library/+ * 路由一律 404(fail closed,不假装空库)。+ */+export type GhostLibraryFileResolver = (ghostId: string, relPath: string) => Promise<string | null>;+let ghostLibraryFileResolver: GhostLibraryFileResolver | null = null;+export function setGhostLibraryFileResolver(resolver: GhostLibraryFileResolver | null): void {+ ghostLibraryFileResolver = resolver;+}++/**+ * library 只读投影:注入解析器校验路径与归属后**流式**回字节。Range 用+ * createReadStream(多 GB 视频不整文件读进内存,review:面板路由整文件+ * 物化);仅支持单段 bytes=a-b / bytes=a-(多段与非法头按不支持处理,回+ * 200 全量或 416)。与 /media 不同:library 文件内容可变,不缓存。+ */+async function serveGhostLibraryFile(ghostId: string, relPath: string, rangeHeader: string | null): Promise<Response> {+ if (!ghostLibraryFileResolver) return new Response(null, { status: 404 });+ const absPath = await ghostLibraryFileResolver(ghostId, relPath);+ if (!absPath) return new Response(null, { status: 404 });+ const mimeType = mediaTypeForLibraryPath(relPath);+ const headers: Record<string, string> = {+ 'Content-Type': mimeType,+ 'Cache-Control': 'no-cache',+ 'Accept-Ranges': 'bytes',+ };+ try {+ const st = await fs.stat(absPath);+ if (!st.isFile()) return new Response(null, { status: 404 });+ const total = st.size;+ if (rangeHeader !== null && rangeHeader !== undefined && rangeHeader !== '') {+ const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());+ // 非单段(多段/后缀拼接/非法)按不支持处理:满足 prefix 的回 416,+ // 完全非法的忽略 Range 回 200(浏览器对 416 会自行回退重拉)。+ if (match && (match[1] !== '' || match[2] !== '')) {+ let start = match[1] === '' ? 0 : Number(match[1]);+ let end = match[2] === '' ? total - 1 : Number(match[2]);+ if (match[1] === '' && match[2] !== '') {+ // suffix 形式:最后 N 字节+ start = Math.max(0, total - Number(match[2]));+ end = total - 1;+ }+ if (start > end || end >= total) {+ return new Response(null, { status: 416, headers: { 'Content-Range': `bytes */${total}` } });+ }+ end = Math.min(end, total - 1);+ const stream = nodeFs.createReadStream(absPath, { start, end });+ return new Response(Readable.toWeb(stream) as ReadableStream, {+ status: 206,+ headers: {+ ...headers,+ 'Content-Range': `bytes ${start}-${end}/${total}`,+ 'Content-Length': String(end - start + 1),+ },+ });+ }+ }+ const stream = nodeFs.createReadStream(absPath);+ return new Response(Readable.toWeb(stream) as ReadableStream, {+ status: 200,+ headers: { ...headers, 'Content-Length': String(total) },+ });+ } catch (err) {+ const code = (err as NodeJS.ErrnoException)?.code;+ if (code === 'ENOENT' || code === 'EISDIR') return new Response(null, { status: 404 });+ log.error('ghost library serve error', { ghostId, error: err instanceof Error ? err.message : String(err) });+ return new Response(null, { status: 500 });+ }+}++/** library 投影的 MIME 按扩展名粗判(面板展示用;嗅探不做,宿主只供已存文件)。 */+function mediaTypeForLibraryPath(relPath: string): string {+ const ext = relPath.slice(relPath.lastIndexOf('.')).toLowerCase();+ switch (ext) {+ case '.png': return 'image/png';+ case '.jpg':+ case '.jpeg': return 'image/jpeg';+ case '.gif': return 'image/gif';+ case '.webp': return 'image/webp';+ case '.svg': return 'image/svg+xml';+ case '.mp4': return 'video/mp4';+ case '.webm': return 'video/webm';+ case '.mov': return 'video/quicktime';+ case '.mp3': return 'audio/mpeg';+ case '.wav': return 'audio/wav';+ case '.ogg': return 'audio/ogg';+ case '.m4a': return 'audio/mp4';+ case '.pdf': return 'application/pdf';+ case '.json': return 'application/json; charset=utf-8';+ case '.txt': return 'text/plain; charset=utf-8';+ default: return 'application/octet-stream';+ }+}+/** 画廊清单响应:[{src, caption}](新的在前;账本不可用时回空数组不报错)。 */async function serveGhostGallery(ghostId: string): Promise<Response> {let items: Awaited<ReturnType<typeof listGhostGalleryFromLedger>> = [];diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex 3f406495a8..7eef6376c7 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -19,6 +19,9 @@ import { contextBridge, ipcRenderer } from 'electron';* …req}) 的语法糖,零新通道零新权限(白名单/凭证注入全在主机侧守门)。* - fs(req):fs 槽代写文件的便捷口——send({type:'fs-request', …req}) 的* 语法糖,同样零新通道零新权限(三档守门全在主机侧 fsSlot)。+ * - library(req):library 槽持久作品库的便捷口——send({type:'library-request',+ * …req}) 的语法糖;资格审/binding 根解析/owner scope 复核/SQL 语句门全在+ * 主机侧 librarySlot,失败回结构化 errorCode(永不 reject)。* - agent.errand(req) / agent.queryErrand(req):派活取件便捷口——* send({type:'agent-errand-request', kind:'run'/'query', …req}) 的语法糖;* - agent.run(req):Agent 新回合的便捷口——send({type:'agent-request',@@ -57,6 +60,8 @@ contextBridge.exposeInMainWorld('cindy', {ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fetch-request' }),fs: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fs-request' }),+ library: (req: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'library-request' }),agent: {run: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-request' }),diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 5e6f16e27e..d17e28a6af 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1278,6 +1278,24 @@ contextBridge.exposeInMainWorld('electronAPI', {runtimeStates: (): Promise<{ states: Record<string, string> }> =>ipcRenderer.invoke('ghosts:runtime-states'),reload: (id: string): Promise<{ state: string }> => ipcRenderer.invoke('ghosts:reload', id),+ // Library(持久作品库)设置面:概览/选位置(宿主弹原生选择器)/绑定/+ // 迁移/回默认/解绑/删除。删除的破坏性确认在 Renderer 完成。+ libraryOverview: (id: string): Promise<import('../shared/ghost').GhostLibraryOverview> =>+ ipcRenderer.invoke('ghosts:library-overview', id),+ libraryPickLocation: (+ id: string,+ ): Promise<{ ok: boolean; cancelled?: boolean; candidate?: string; warnings?: string[]; message?: string }> =>+ ipcRenderer.invoke('ghosts:library-pick-location', id),+ libraryBind: (id: string, candidate: string): Promise<{ ok: boolean; message?: string; warnings?: string[] }> =>+ ipcRenderer.invoke('ghosts:library-bind', id, candidate),+ libraryRelocate: (id: string, candidate: string): Promise<{ ok: boolean; message?: string }> =>+ ipcRenderer.invoke('ghosts:library-relocate', id, candidate),+ libraryRevertDefault: (id: string): Promise<{ ok: boolean; message?: string }> =>+ ipcRenderer.invoke('ghosts:library-revert-default', id),+ libraryUnbind: (id: string): Promise<{ ok: boolean; message?: string }> =>+ ipcRenderer.invoke('ghosts:library-unbind', id),+ libraryDelete: (id: string): Promise<{ ok: boolean; cancelled?: boolean; message?: string }> =>+ ipcRenderer.invoke('ghosts:library-delete', id),legacyRecoveryStatus: (): Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus> => ipcRenderer.invoke('ghosts:legacy-recovery-status'),diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex 5e4b5fdc8e..dbbfdb94d3 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -23,6 +23,7 @@ import {GraduationCap,KeyRound,LayoutTemplate,+ Library,MapPin,Megaphone,MessageCircleQuestion,@@ -55,6 +56,7 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {notify: Megaphone,confirm: MessageCircleQuestion,fs: FilePen,+ library: Library,'session-context': MapPin,pick: FolderOpen,preview: AppWindow,@@ -313,12 +315,15 @@ export function GhostInstallReview({trust,items,manualCount = 0,+ extra,}: {description?: string;meta: string;trust: GhostTrustInfo;items: GhostPermissionItem[];manualCount?: number;+ /** 追加内容(如 library 槽的存储位置行),渲染在权限清单下方。 */+ extra?: ReactNode;}) {const { t } = useTranslation();const [descriptionExpanded, setDescriptionExpanded] = useState(false);@@ -362,6 +367,7 @@ export function GhostInstallReview({<div className="mt-3 border-t border-[var(--border-default)] pt-3"><GhostPermissionList items={items} /></div>+ {extra ? <div className="mt-3">{extra}</div> : null}</div>);}diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsxindex 7ae556b1e0..c30bf595e4 100644--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx@@ -1,5 +1,6 @@import type { TFunction } from 'i18next';-import type { ReactNode } from 'react';+import { useState, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';import { createLogger } from '@/lib/logger';import { toast } from '@/lib/toast';@@ -170,6 +171,11 @@ export async function confirmAndInstallGhost(// 升级为「立即开启并打开面板」——面板收束后页签面板只住在插件页,// 不再创建右侧栏 ghost 页签;入口给不出面板宿主就不许诺"打开"。const willOpenPanel = manifest.panel?.position === 'tab' && deps.openPluginPanel !== undefined;+ // library 槽(持久作品库):装入确认里提供「存储位置」行——默认预选系统+ // 管理位置(不点更改 = 零额外步骤),点「更改…」由宿主弹原生选择器并做+ // 候选校验;装入成功后才落 binding(取消装入不留孤儿 binding)。+ const libraryChoice: { candidate: string | null; warnings: string[] } = { candidate: null, warnings: [] };+ const librarySlots = manifest.slots.includes('library');const { ok, checked: enable } = await confirmWithCheckbox({title: t('settings.ghosts.installConfirm.title', { name: manifest.name }),content: (@@ -179,6 +185,9 @@ export async function confirmAndInstallGhost(trust={trust}items={ghostPermissionItems(manifest)}manualCount={manifest.manual?.items.length ?? 0}+ extra={librarySlots ? (+ <LibraryInstallLocationRow ghostId={manifest.id} choice={libraryChoice} />+ ) : undefined}/>),maxWidth: GHOST_CONFIRM_MAX_WIDTH,@@ -193,6 +202,19 @@ export async function confirmAndInstallGhost(});if (!ok) return;+ // 2.5) 用户在确认框里选了自定义位置 → **装入前**先落 binding(keyed by+ // ghostId,与安装顺序无关):否则「立即开启」的常驻插件会在 install 返回+ // 前被拉起、以默认根开库(review:spawn 早于 bind)。装入失败会留一份无+ // 数据的 binding,行为等价「记住位置」,下次装同 id 直接用上。+ if (librarySlots && libraryChoice.candidate) {+ const bound = await window.electronAPI.ghosts.libraryBind(manifest.id, libraryChoice.candidate);+ if (!bound.ok) {+ toast.error(`${t('settings.ghosts.library.bindAfterInstallFailed')}:${bound.message ?? ''}`);+ } else if (bound.warnings && bound.warnings.length > 0) {+ toast.warning(t('settings.ghosts.library.cloudWarningToast'));+ }+ }+// 3) 真装(main 侧同一主体:来源校验 + 落盘 + 停靠)。Node 高风险提示// 已在上面的权限清单里如实展示,不再有 Main 原生二次确认。try {@@ -337,3 +359,62 @@ export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDedeps,);}++/**+ * 装入确认框里的「存储位置」行(library 槽专用):默认预选系统管理位置,+ * 点「更改…」由宿主弹原生选择器(插件无权发起)并做候选校验(可写探针/+ * 受管根排斥/网络盘拒/云盘警告)。选择结果写回外层 choice 对象(ReactNode+ * content 与外层 async 流程之间的通信桥),装入成功后才落 binding。+ */+function LibraryInstallLocationRow({+ ghostId,+ choice,+}: {+ ghostId: string;+ choice: { candidate: string | null; warnings: string[] };+}): ReactNode {+ const { t } = useTranslation();+ const [candidate, setCandidate] = useState<string | null>(choice.candidate);+ const [warnings, setWarnings] = useState<string[]>(choice.warnings);+ const pick = async () => {+ const picked = await window.electronAPI.ghosts.libraryPickLocation(ghostId);+ if (!picked.ok) {+ if (!picked.cancelled) {+ toast.error(picked.message ?? t('settings.ghosts.library.pickFailed'));+ }+ return;+ }+ choice.candidate = picked.candidate ?? null;+ choice.warnings = picked.warnings ?? [];+ setCandidate(choice.candidate);+ setWarnings(choice.warnings);+ };+ return (+ <div className="rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-3">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <p className="text-13 font-medium leading-5 text-[var(--text-primary)]">+ {t('settings.ghosts.library.installLocationLabel')}+ </p>+ <p className="mt-0.5 break-all text-12 leading-[1.5] text-[var(--text-secondary)]">+ {candidate+ ? `${t('settings.ghosts.library.installLocationPickedPrefix')} ${candidate}`+ : t('settings.ghosts.library.installLocationDefault')}+ </p>+ </div>+ <button+ type="button"+ onClick={() => void pick()}+ className="shrink-0 rounded-lg text-13 font-medium text-[var(--accent)] transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ {t('settings.ghosts.library.installLocationChange')}+ </button>+ </div>+ {warnings.map((warning) => (+ <p key={warning} className="mt-2 text-12 leading-[1.5] text-[var(--warning-fg)]">+ {warning}+ </p>+ ))}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx b/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsxnew file mode 100644index 0000000000..40f5df3087--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx@@ -0,0 +1,259 @@+/**+ * GhostLibrarySection — 插件详情页的「持久作品库」设置区(2026-08-20)。+ * ---------------------------------------------------------------------------+ * 只在 manifest 声明 library 槽时渲染。职责:+ * - 展示位置(默认/自定义)、占用、磁盘余量、状态横幅(漂移/只读/orphaned);+ * - 更改位置(宿主弹原生选择器 → 候选校验 → 确认 → 迁移状态机);+ * - 恢复默认位置(反向迁移 + 撤销 binding);漂移时的「解除位置记录」恢复;+ * - 删除作品数据——与卸载是**两个独立操作**,独立破坏性确认,进 30 天回收站。+ * 全部动作走 window.electronAPI.ghosts.library*(宿主裁决,插件无权发起)。+ * 样式常量与 GhostPluginDetailView 同值(语义 token,Light/Dark 自动适配)。+ */+import { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Library as LibraryIcon, Loader2, RefreshCw } from 'lucide-react';++import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { toast } from '@/lib/toast';+import { cn } from '@/lib/utils';+import type { GhostLibraryOverview } from '../../../shared/ghost';++const SECTION_CLASS = 'mt-10';+const SURFACE_CLASS =+ 'border border-[color-mix(in_srgb,var(--border-default)_72%,transparent)] bg-[color-mix(in_srgb,var(--surface-elevated)_82%,var(--surface))]';+const ROW_CLASS = 'flex items-center justify-between gap-4 text-13 leading-5';+const ACTION_BUTTON_CLASS =+ 'text-13 font-medium text-[var(--accent)] transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-50';+const DANGER_BUTTON_CLASS =+ 'text-13 font-medium text-[var(--danger)] transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-50';++function formatBytes(bytes: number): string {+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 MB';+ const mb = bytes / 1024 / 1024;+ if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`;+ if (mb >= 1) return `${Math.round(mb)} MB`;+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;+}++/**+ * 外层:未声明 library 槽直接不挂载内层(内层用了 useConfirmDialog,测试环境+ * 无 Provider——不声明就不进 hook,老用例零影响)。+ */+export function GhostLibrarySection({ ghostId, slots }: { ghostId: string; slots: readonly string[] }) {+ if (!slots.includes('library')) return null;+ return <GhostLibrarySectionInner ghostId={ghostId} />;+}++function GhostLibrarySectionInner({ ghostId }: { ghostId: string }) {+ const { t } = useTranslation();+ const { confirm } = useConfirmDialog();+ const [overview, setOverview] = useState<GhostLibraryOverview | null>(null);+ const [busy, setBusy] = useState<'relocate' | 'delete' | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);++ const refresh = useCallback(async () => {+ try {+ const next = await window.electronAPI.ghosts.libraryOverview(ghostId);+ setOverview(next);+ setLoadError(null);+ } catch {+ setLoadError(t('settings.ghosts.library.loadFailed'));+ }+ }, [ghostId, t]);++ useEffect(() => {+ void refresh();+ }, [refresh]);++ const drifted = overview !== null && overview.state === 'unavailable';++ const handleChangeLocation = async () => {+ if (busy) return;+ const picked = await window.electronAPI.ghosts.libraryPickLocation(ghostId);+ if (!picked.ok) {+ if (!picked.cancelled) toast.error(picked.message ?? t('settings.ghosts.library.pickFailed'));+ return;+ }+ const candidate = picked.candidate!;+ if (picked.warnings && picked.warnings.length > 0) {+ const proceed = await confirm({+ title: t('settings.ghosts.library.cloudWarningTitle'),+ description: picked.warnings.join('\n'),+ confirmText: t('settings.ghosts.library.cloudWarningProceed'),+ cancelText: t('settings.ghosts.library.cancel'),+ });+ if (!proceed) return;+ }+ const ok = await confirm({+ title: t('settings.ghosts.library.relocateConfirmTitle'),+ description: t('settings.ghosts.library.relocateConfirmDescription'),+ confirmText: t('settings.ghosts.library.relocateConfirmText'),+ cancelText: t('settings.ghosts.library.cancel'),+ });+ if (!ok) return;+ setBusy('relocate');+ try {+ const res = await window.electronAPI.ghosts.libraryRelocate(ghostId, candidate);+ if (res.ok) {+ toast.success(t('settings.ghosts.library.relocateDone'));+ } else {+ toast.error(`${t('settings.ghosts.library.relocateFailed')}:${res.message ?? ''}`);+ }+ } finally {+ setBusy(null);+ void refresh();+ }+ };++ const handleRevertDefault = async () => {+ if (busy) return;+ const ok = await confirm({+ title: t('settings.ghosts.library.revertConfirmTitle'),+ description: t('settings.ghosts.library.relocateConfirmDescription'),+ confirmText: t('settings.ghosts.library.revertConfirmText'),+ cancelText: t('settings.ghosts.library.cancel'),+ });+ if (!ok) return;+ setBusy('relocate');+ try {+ const res = await window.electronAPI.ghosts.libraryRevertDefault(ghostId);+ if (!res.ok) toast.error(`${t('settings.ghosts.library.relocateFailed')}:${res.message ?? ''}`);+ else toast.success(t('settings.ghosts.library.relocateDone'));+ } finally {+ setBusy(null);+ void refresh();+ }+ };++ const handleUnbind = async () => {+ if (busy) return;+ const ok = await confirm({+ title: t('settings.ghosts.library.unbindConfirmTitle'),+ description: t('settings.ghosts.library.unbindConfirmDescription'),+ confirmText: t('settings.ghosts.library.unbindConfirmText'),+ cancelText: t('settings.ghosts.library.cancel'),+ });+ if (!ok) return;+ await window.electronAPI.ghosts.libraryUnbind(ghostId);+ void refresh();+ };++ const handleDelete = async () => {+ if (busy) return;+ // 删除确认由 Main 原生确认框裁决(唯一有效确认):preload 即使被其它+ // trusted renderer 调用也绕不过去。Renderer 不再先弹一次,避免双重确认。+ setBusy('delete');+ try {+ const res = await window.electronAPI.ghosts.libraryDelete(ghostId);+ if (res.ok) toast.success(t('settings.ghosts.library.deleteDone'));+ else if (!res.cancelled) toast.error(`${t('settings.ghosts.library.deleteFailed')}:${res.message ?? ''}`);+ } finally {+ setBusy(null);+ void refresh();+ }+ };++ return (+ <section className={SECTION_CLASS} aria-labelledby="ghost-library-title">+ <div className="flex items-center justify-between">+ <h3 id="ghost-library-title" className="flex items-center gap-2 text-18 font-medium leading-[1.444] text-[var(--text-primary)]">+ <LibraryIcon size={18} className="shrink-0 text-[var(--text-secondary)]" aria-hidden="true" />+ {t('settings.ghosts.library.title')}+ </h3>+ <button+ type="button"+ className={ACTION_BUTTON_CLASS}+ onClick={() => void refresh()}+ aria-label={t('settings.ghosts.library.refresh')}+ >+ <RefreshCw size={14} aria-hidden="true" />+ </button>+ </div>++ <div className={cn(SURFACE_CLASS, 'mt-5 max-w-[760px] rounded-xl p-4')}>+ {loadError ? (+ <p className="text-13 text-[var(--warning-fg)]">{loadError}</p>+ ) : overview === null ? (+ <p className="text-13 text-[var(--text-tertiary)]">{t('settings.ghosts.library.loading')}</p>+ ) : (+ <>+ {drifted ? (+ <p className="mb-3 text-13 text-[var(--warning-fg)]">+ {overview.reason === 'disk-missing'+ ? t('settings.ghosts.library.stateDiskMissing')+ : t('settings.ghosts.library.stateBindingMoved')}+ </p>+ ) : null}+ {overview.state === 'readonly' ? (+ <p className="mb-3 text-13 text-[var(--warning-fg)]">{t('settings.ghosts.library.stateReadonly')}</p>+ ) : null}+ {overview.orphaned ? (+ <p className="mb-3 text-13 text-[var(--text-secondary)]">{t('settings.ghosts.library.orphanedBanner')}</p>+ ) : null}+ <div className="space-y-2">+ <div className={ROW_CLASS}>+ <span className="text-[var(--text-secondary)]">{t('settings.ghosts.library.locationLabel')}</span>+ <span className="min-w-0 break-all text-right text-[var(--text-primary)]">+ {overview.location === 'custom' && overview.customCandidate+ ? `${t('settings.ghosts.library.locationCustomPrefix')} ${overview.customCandidate}`+ : t('settings.ghosts.library.locationDefault')}+ </span>+ </div>+ <div className={ROW_CLASS}>+ <span className="text-[var(--text-secondary)]">{t('settings.ghosts.library.usageLabel')}</span>+ <span className="text-[var(--text-primary)]">+ {formatBytes(overview.usedBytes)} · {overview.fileCount} {t('settings.ghosts.library.filesUnit')}+ </span>+ </div>+ {overview.diskFreeBytes !== null ? (+ <div className={ROW_CLASS}>+ <span className="text-[var(--text-secondary)]">{t('settings.ghosts.library.diskFreeLabel')}</span>+ <span className="text-[var(--text-primary)]">{formatBytes(overview.diskFreeBytes)}</span>+ </div>+ ) : null}+ </div>+ {overview.softLimitExceeded ? (+ <p className="mt-3 text-12 text-[var(--warning-fg)]">+ {t('settings.ghosts.library.softLimitWarning', { limit: formatBytes(overview.softLimitBytes) })}+ </p>+ ) : null}+ <div className="mt-4 flex flex-wrap items-center gap-4">+ {busy === 'relocate' ? (+ <span className="inline-flex items-center gap-1.5 text-13 text-[var(--text-secondary)]">+ <span className="inline-flex animate-spin">+ <Loader2 size={14} aria-hidden="true" />+ </span>+ {t('settings.ghosts.library.relocateBusy')}+ </span>+ ) : (+ <>+ <button type="button" className={ACTION_BUTTON_CLASS} onClick={() => void handleChangeLocation()}>+ {t('settings.ghosts.library.changeLocation')}+ </button>+ {drifted ? (+ <button type="button" className={ACTION_BUTTON_CLASS} onClick={() => void handleUnbind()}>+ {t('settings.ghosts.library.unbind')}+ </button>+ ) : overview.location === 'custom' ? (+ <button type="button" className={ACTION_BUTTON_CLASS} onClick={() => void handleRevertDefault()}>+ {t('settings.ghosts.library.revertDefault')}+ </button>+ ) : null}+ </>+ )}+ <span className="flex-1" />+ <button+ type="button"+ className={DANGER_BUTTON_CLASS}+ disabled={busy !== null}+ onClick={() => void handleDelete()}+ >+ {busy === 'delete' ? t('settings.ghosts.library.deleteBusy') : t('settings.ghosts.library.deleteData')}+ </button>+ </div>+ </>+ )}+ </div>+ </section>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex e71f359d0d..77be862c14 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -27,6 +27,7 @@ import {GraduationCap,KeyRound,LayoutTemplate,+ Library,MapPin,Megaphone,MessageCircleQuestion,@@ -45,6 +46,7 @@ import {import { useTranslation } from 'react-i18next';import { CindyCapabilityPrefs } from '@/cindy-brain/CindyCapabilityPrefs';+import { GhostLibrarySection } from './GhostLibrarySection';import { GhostErrandPrefs } from '@/cindy-brain/GhostErrandPrefs';import { GhostSettingsWebview } from '@/cindy-brain/GhostSettingsWebview';import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';@@ -115,6 +117,7 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {notify: Megaphone,confirm: MessageCircleQuestion,fs: FilePen,+ library: Library,'session-context': MapPin,pick: FolderOpen,preview: AppWindow,@@ -534,6 +537,8 @@ export function GhostPluginDetailView({{detail.permissions.length > 0 ? <PermissionSummary items={detail.permissions} /> : null}+ <GhostLibrarySection ghostId={detail.id} slots={ghost?.manifest.slots ?? []} />+<DetailsSection detail={detail} panelStatus={panelStatus} /></article></main>diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ee8ced840f..cd22ff61d4 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2591,7 +2591,11 @@"removeAria": "Uninstall {{name}}","showDetails": "Show details for {{name}}","collapseDetails": "Hide details for {{name}}",- "rowStatus": { "compatible": "Compatible", "noticeCount": "{{count}} compatibility notices", "unmanageable": "Manage from Pi" },+ "rowStatus": {+ "compatible": "Compatible",+ "noticeCount": "{{count}} compatibility notices",+ "unmanageable": "Manage from Pi"+ },"operationFailed": "The Pi extension operation failed. Check the source or network and try again.","loading": "Loading Pi extensions…","loadFailed": "Cindy couldn't load Pi extensions. Check the connection and try again.",@@ -2609,8 +2613,19 @@"confirmUninstall": "Uninstall","extensionDialogConfirm": "Confirm","cancel": "Cancel",- "resources": { "extension": "Extension code", "skill": "Skill", "prompt": "Prompt template", "theme": "Theme" },- "status": { "supported": "Fully supported by Cindy", "extensionSupported": "No known Pi TUI dependency found", "partial": "Compatibility limits found", "unsupported": "Installed, but not loaded by Cindy", "unknown": "Compatibility check incomplete" },+ "resources": {+ "extension": "Extension code",+ "skill": "Skill",+ "prompt": "Prompt template",+ "theme": "Theme"+ },+ "status": {+ "supported": "Fully supported by Cindy",+ "extensionSupported": "No known Pi TUI dependency found",+ "partial": "Compatibility limits found",+ "unsupported": "Installed, but not loaded by Cindy",+ "unknown": "Compatibility check incomplete"+ },"compatibility": {"supported": "Skills and prompt templates are fully supported. Extension source is inspected after install instead of being classified only by resource type.","partial": "When Pi TUI APIs are detected, Cindy lists the specific limits. The extension can still be installed and you decide whether to keep it enabled.",@@ -2646,8 +2661,20 @@"keepDisabled": "Keep disabled","approveAndEnable": "Accept risk and enable","done": "Done",- "warning": { "no-resources": "No Pi resources were found in this extension.", "inspection-failed": "The extension is configured, but its installed contents could not be inspected.", "inspection-limit": "The extension exceeded safe inspection limits and remains disabled.", "unsupported-filter": "This extension uses Pi resource filters that Cindy cannot safely reproduce yet, so it remains disabled.", "unsafe-source": "This extension's saved source contains credentials or private URL parameters. Cindy hid the sensitive parts, kept it disabled, and blocked in-app update or removal.", "lifecycle-scripts-disabled": "This extension declares install scripts, but Cindy did not run them for safety. Features that depend on generated files may not work." },- "success": { "install": "Pi extension installed. The current task is unchanged; start or restart a Pi task to use it.", "remove": "Pi extension removed. The current task keeps the old extension until it is closed.", "update": "Pi extension updated. The current task keeps the old version; start or restart a Pi task to use the update.", "set-enabled": "Pi extension state saved. The current task is unchanged; start or restart a Pi task to apply it." }+ "warning": {+ "no-resources": "No Pi resources were found in this extension.",+ "inspection-failed": "The extension is configured, but its installed contents could not be inspected.",+ "inspection-limit": "The extension exceeded safe inspection limits and remains disabled.",+ "unsupported-filter": "This extension uses Pi resource filters that Cindy cannot safely reproduce yet, so it remains disabled.",+ "unsafe-source": "This extension's saved source contains credentials or private URL parameters. Cindy hid the sensitive parts, kept it disabled, and blocked in-app update or removal.",+ "lifecycle-scripts-disabled": "This extension declares install scripts, but Cindy did not run them for safety. Features that depend on generated files may not work."+ },+ "success": {+ "install": "Pi extension installed. The current task is unchanged; start or restart a Pi task to use it.",+ "remove": "Pi extension removed. The current task keeps the old extension until it is closed.",+ "update": "Pi extension updated. The current task keeps the old version; start or restart a Pi task to use the update.",+ "set-enabled": "Pi extension state saved. The current task is unchanged; start or restart a Pi task to apply it."+ }},"computerUse": {"title": "Automation",@@ -4086,6 +4113,8 @@"confirmDetail": "Before acting it can open a dialog that looks like Cindy's own to ask you. The question comes from the plugin and the dialog is labeled with its name; only you can click confirm or cancel — the plugin cannot. At most one dialog at a time, and asking too often is blocked.","fsWrite": "Can write files (create / modify)","fsWriteDetail": "Its own private data folder is always writable. Writes into the current session's working directory follow the session's permission mode (auto-approve modes write directly; per-action modes ask you first). Any other folder always requires your confirmation. Files are always written by the host — the plugin itself never touches your file system.",+ "libraryPersist": "Can use a durable library (large files and databases)",+ "libraryPersistDetail": "It gets a Cindy-managed storage area for your work (canvases, images, databases) with no normal plugin data quota. All file and database operations are executed by the host; the plugin only uses relative paths inside its own library and cannot touch your other files. Uninstalling the plugin does not delete this data; deletion requires separate confirmation in Cindy settings.","networkHost": "Accesses the network domain {{host}}","networkSecret": "Needs a credential from you: \"{{name}}\"","networkSecretGhostInputDetail": "Collected by this plugin's own settings UI — the plugin page sees the value at entry time. It is then handed to the host in one step for encrypted storage; once stored, the plugin can never read it back, and the host injects it only for the domains it declares.",@@ -4235,11 +4264,60 @@"slotNotify": "System tips","slotBadge": "Unread badge","slotFs": "File writing",+ "slotLibrary": "Durable library","slotSkill": "Agent skills","slotWorkspace": "Workspace sessions","slotIOSSimulator": "Embedded iOS Simulator"},"commandPaletteTag": "Plugin command",+ "library": {+ "title": "Durable library",+ "loading": "Loading library info…",+ "loadFailed": "Failed to load library info",+ "refresh": "Refresh",+ "locationLabel": "Storage location",+ "locationDefault": "Cindy-managed location (system data folder)",+ "locationCustomPrefix": "Custom:",+ "usageLabel": "Usage",+ "filesUnit": "files",+ "diskFreeLabel": "Disk free",+ "stateDiskMissing": "Library unavailable: the storage disk is not connected. Reconnect it, then re-select the location in settings.",+ "stateBindingMoved": "Library unavailable: the storage location has changed. Please re-select the location.",+ "stateReadonly": "The library is currently read-only.",+ "orphanedBanner": "The plugin is uninstalled, but its work data is kept. Reinstalling the plugin restores access automatically.",+ "softLimitWarning": "Library usage exceeds the suggested watermark ({{limit}}). Consider cleaning up or moving it to another disk.",+ "changeLocation": "Change location…",+ "revertDefault": "Restore default location",+ "unbind": "Forget custom location",+ "relocateConfirmTitle": "Move the library?",+ "relocateConfirmDescription": "All work data will be copied to the new location and verified item by item; the old folder is kept for 14 days as a rollback window. Large libraries may take a few minutes — avoid using the plugin during the move.",+ "relocateConfirmText": "Start moving",+ "relocateDone": "Library moved",+ "relocateFailed": "Move failed",+ "relocateBusy": "Moving…",+ "revertConfirmTitle": "Move back to the default location?",+ "revertConfirmText": "Move back",+ "unbindConfirmTitle": "Forget the custom location?",+ "unbindConfirmDescription": "The library will return to the Cindy-managed default location. Data in the old custom folder is neither deleted nor moved; recover it manually if needed.",+ "unbindConfirmText": "Forget location",+ "cloudWarningTitle": "Cloud-synced folder reminder",+ "cloudWarningProceed": "Use this location anyway",+ "cloudWarningToast": "A cloud-synced folder is in use; database files may be corrupted by sync. Consider changing the location soon.",+ "deleteData": "Delete work data…",+ "deleteBusy": "Deleting…",+ "deleteConfirmTitle": "Delete all work data of this plugin?",+ "deleteConfirmDescription": "This is separate from uninstalling the plugin. Deleted data is moved to a trash folder and kept for 30 days, then permanently removed. Uninstalling or reinstalling the plugin does not affect this data.",+ "deleteConfirmText": "Delete data",+ "deleteDone": "Work data moved to trash",+ "deleteFailed": "Delete failed",+ "pickFailed": "The selected location is not usable",+ "installLocationLabel": "Library storage location",+ "installLocationDefault": "Default (Cindy-managed location)",+ "installLocationPickedPrefix": "Selected:",+ "installLocationChange": "Change…",+ "bindAfterInstallFailed": "Failed to set the custom storage location; fell back to the default",+ "cancel": "Cancel"+ },"updateConfirm": {"title": "Update plugin \"{{name}}\"?","body": "Version {{from}} → {{to}}. This replaces the installed version; enabled state and panel position are preserved.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5823e31257..37f00953bc 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4112,6 +4112,8 @@"confirmDetail": "実行前に Cindy 自身と同じ確認ダイアログを開いて尋ねることができます。文面はプラグインが提供し、ダイアログにはその名前が表示されます。確認するかキャンセルするかはあなたがクリックして決め、プラグイン自身はクリックできません。同時に開けるのは 1 つまでで、頻繁な要求はブロックされます。","fsWrite": "ファイルを書き込めます(作成/変更)","fsWriteDetail": "専用データフォルダにはいつでも書き込めます。現在のセッションの作業ディレクトリへの書き込みはセッションの権限モードに従います(自動承認モードでは直接書き込み、逐次確認モードでは事前に承認を求めます)。それ以外のフォルダへの書き込みは毎回確認が必要です。ファイルは常にホストが代理で書き込み、プラグイン自体があなたのファイルシステムに直接アクセスすることはありません。",+ "libraryPersist": "永続ライブラリを使用可能(大量のファイルとデータベース)",+ "libraryPersistDetail": "Cindy が管理する独立した保存領域を取得し、作品データ(キャンバス、画像、データベースなど)を保存します。通常のプラグインデータ割り当ての制限を受けません。ファイルとデータベースの操作はすべてホストが代行実行し、プラグインはライブラリ内の相対パスのみを使用して、他のファイルに触れることはできません。プラグインをアンインストールしてもこのデータは削除されず、削除には Cindy 設定での個別確認が必要です。","networkHost": "ネットワークドメイン {{host}} にアクセス","networkSecret": "認証情報「{{name}}」の入力が必要","networkSecretGhostInputDetail": "この資格情報はプラグイン自身の設定画面で入力を受け付けるため、入力時にはプラグインのページを経由します。その後ホストへ一度だけ渡されて暗号化保存され、保存後はプラグインから読み出せません。注入は宣言されたドメインへのリクエスト時のみホストが行います。",@@ -4261,11 +4263,60 @@"slotNotify": "システム通知","slotBadge": "未読バッジ","slotFs": "ファイル書き込み",+ "slotLibrary": "永続ライブラリ","slotSkill": "エージェントスキル","slotWorkspace": "ワークスペースセッション","slotIOSSimulator": "内蔵 iOS シミュレータ"},"commandPaletteTag": "プラグインコマンド",+ "library": {+ "title": "永続ライブラリ",+ "loading": "ライブラリ情報を読み込み中…",+ "loadFailed": "ライブラリ情報の読み込みに失敗しました",+ "refresh": "更新",+ "locationLabel": "保存場所",+ "locationDefault": "Cindy 管理の場所(システムデータフォルダ)",+ "locationCustomPrefix": "カスタム:",+ "usageLabel": "使用量",+ "filesUnit": "ファイル",+ "diskFreeLabel": "ディスク空き容量",+ "stateDiskMissing": "ライブラリ利用不可:保存ディスクが接続されていません。再接続後、設定で場所を選び直してください。",+ "stateBindingMoved": "ライブラリ利用不可:保存場所が変化しました。場所を選び直してください。",+ "stateReadonly": "ライブラリは現在読み取り専用です。",+ "orphanedBanner": "プラグインはアンインストールされていますが、作品データは削除せず保持されています。再インストールすると自動的に利用を再開できます。",+ "softLimitWarning": "ライブラリの使用量が推奨しきい値({{limit}})を超えています。整理または別ディスクへの移動を検討してください。",+ "changeLocation": "場所を変更…",+ "revertDefault": "既定の場所に戻す",+ "unbind": "カスタム場所を解除",+ "relocateConfirmTitle": "ライブラリを移動しますか?",+ "relocateConfirmDescription": "すべての作品データを新しい場所へコピーし、項目ごとに検証します。元のフォルダは 14 日間ロールバック用に保持されます。容量が大きい場合は数分かかることがあり、移動中はプラグインの使用を控えてください。",+ "relocateConfirmText": "移動を開始",+ "relocateDone": "ライブラリを移動しました",+ "relocateFailed": "移動に失敗しました",+ "relocateBusy": "移動中…",+ "revertConfirmTitle": "既定の場所に戻しますか?",+ "revertConfirmText": "戻す",+ "unbindConfirmTitle": "カスタム場所を解除しますか?",+ "unbindConfirmDescription": "Cindy 管理の既定の場所に戻ります。元のカスタムフォルダのデータは削除も移動もされません。必要な場合は手動で移動してください。",+ "unbindConfirmText": "解除",+ "cloudWarningTitle": "クラウド同期フォルダの注意",+ "cloudWarningProceed": "この場所を使用する",+ "cloudWarningToast": "クラウド同期フォルダを使用しています。同期によりデータベースファイルが破損する可能性があるため、早めに場所を変更してください。",+ "deleteData": "作品データを削除…",+ "deleteBusy": "削除中…",+ "deleteConfirmTitle": "このプラグインのすべての作品データを削除しますか?",+ "deleteConfirmDescription": "この操作はプラグインのアンインストールとは別の操作です。削除されたデータはごみ箱に移動され 30 日間保持された後、完全に消去されます。アンインストールや再インストールではこのデータは影響を受けません。",+ "deleteConfirmText": "データを削除",+ "deleteDone": "作品データをごみ箱へ移動しました",+ "deleteFailed": "削除に失敗しました",+ "pickFailed": "選択された場所は使用できません",+ "installLocationLabel": "ライブラリの保存場所",+ "installLocationDefault": "既定(Cindy 管理の場所)",+ "installLocationPickedPrefix": "選択済み:",+ "installLocationChange": "変更…",+ "bindAfterInstallFailed": "カスタム保存場所の設定に失敗したため、既定の場所に戻しました",+ "cancel": "キャンセル"+ },"updateConfirm": {"title": "プラグイン「{{name}}」を更新しますか?","body": "バージョン {{from}} → {{to}}。既存バージョンを置き換えます。有効状態とパネル位置は保持されます。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex a6caf9e57a..ddde704b3f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4112,6 +4112,8 @@"confirmDetail": "작업 전에 Cindy 자체와 동일한 확인 대화상자를 열어 물어볼 수 있습니다. 질문 내용은 플러그인이 제공하며 대화상자에는 그 이름이 표시됩니다. 확인이든 취소든 직접 클릭해야 하고 플러그인은 스스로 누를 수 없습니다. 동시에 하나만 열 수 있으며 너무 자주 요청하면 차단됩니다.","fsWrite": "파일을 쓸 수 있음(생성/수정)","fsWriteDetail": "전용 데이터 폴더에는 언제든지 쓸 수 있습니다. 현재 세션의 작업 디렉터리 쓰기는 세션의 권한 모드를 따릅니다(자동 승인 모드에서는 바로 쓰고, 개별 확인 모드에서는 먼저 승인을 요청합니다). 그 외 폴더에 쓰려면 매번 확인이 필요합니다. 파일은 항상 호스트가 대신 기록하며 플러그인 자체는 파일 시스템에 직접 접근할 수 없습니다.",+ "libraryPersist": "영구 라이브러리 사용 가능(대용량 파일 및 데이터베이스)",+ "libraryPersistDetail": "Cindy가 관리하는 독립 저장 공간을 받아 작업 데이터(캔버스, 이미지, 데이터베이스 등)를 저장하며, 일반 플러그인 데이터 할당량 제한을 받지 않습니다. 파일과 데이터베이스 작업은 모두 호스트가 대신 실행하고 플러그인은 라이브러리 내 상대 경로만 사용하여 다른 파일에는 접근할 수 없습니다. 플러그인을 제거해도 이 데이터는 삭제되지 않으며, 삭제는 Cindy 설정에서 별도 확인이 필요합니다.","networkHost": "네트워크 도메인 {{host}}에 접근","networkSecret": "자격 증명 \"{{name}}\" 입력 필요","networkSecretGhostInputDetail": "이 자격 증명은 플러그인 자체 설정 화면에서 입력받으므로 입력 시점에 플러그인 페이지를 거칩니다. 이후 호스트에 한 번만 전달되어 암호화 저장되며, 저장 후에는 플러그인이 다시 읽을 수 없습니다. 주입은 선언된 도메인 요청 시에만 호스트가 수행합니다.",@@ -4261,11 +4263,60 @@"slotNotify": "시스템 알림","slotBadge": "읽지 않음 배지","slotFs": "파일 쓰기",+ "slotLibrary": "영구 라이브러리","slotSkill": "에이전트 스킬","slotWorkspace": "워크스페이스 세션","slotIOSSimulator": "내장 iOS 시뮬레이터"},"commandPaletteTag": "플러그인 명령",+ "library": {+ "title": "영구 라이브러리",+ "loading": "라이브러리 정보를 불러오는 중…",+ "loadFailed": "라이브러리 정보를 불러오지 못했습니다",+ "refresh": "새로 고침",+ "locationLabel": "저장 위치",+ "locationDefault": "Cindy 관리 위치(시스템 데이터 폴더)",+ "locationCustomPrefix": "사용자 지정:",+ "usageLabel": "사용량",+ "filesUnit": "개 파일",+ "diskFreeLabel": "디스크 여유 공간",+ "stateDiskMissing": "라이브러리를 사용할 수 없습니다: 저장 디스크가 연결되어 있지 않습니다. 다시 연결한 후 설정에서 위치를 다시 선택해 주세요.",+ "stateBindingMoved": "라이브러리를 사용할 수 없습니다: 저장 위치가 변경되었습니다. 위치를 다시 선택해 주세요.",+ "stateReadonly": "라이브러리가 현재 읽기 전용입니다.",+ "orphanedBanner": "플러그인이 제거되었지만 작업 데이터는 삭제하지 않고 보관 중입니다. 플러그인을 다시 설치하면 자동으로 다시 사용할 수 있습니다.",+ "softLimitWarning": "라이브러리 사용량이 권장 한도({{limit}})를 초과했습니다. 정리하거나 다른 디스크로 이동을 검토해 주세요.",+ "changeLocation": "위치 변경…",+ "revertDefault": "기본 위치로 되돌리기",+ "unbind": "사용자 지정 위치 해제",+ "relocateConfirmTitle": "라이브러리를 이동할까요?",+ "relocateConfirmDescription": "모든 작업 데이터를 새 위치로 복사하고 항목별로 검증합니다. 원래 폴더는 롤백 여지를 위해 14일간 보관됩니다. 용량이 크면 몇 분 걸릴 수 있으며 이동 중에는 플러그인 사용을 자제해 주세요.",+ "relocateConfirmText": "이동 시작",+ "relocateDone": "라이브러리를 이동했습니다",+ "relocateFailed": "이동 실패",+ "relocateBusy": "이동 중…",+ "revertConfirmTitle": "기본 위치로 되돌릴까요?",+ "revertConfirmText": "되돌리기",+ "unbindConfirmTitle": "사용자 지정 위치를 해제할까요?",+ "unbindConfirmDescription": "Cindy 관리 기본 위치로 돌아갑니다. 기존 사용자 지정 폴더의 데이터는 삭제되지도 이동되지도 않습니다. 필요하면 수동으로 옮겨 주세요.",+ "unbindConfirmText": "해제",+ "cloudWarningTitle": "클라우드 동기화 폴더 알림",+ "cloudWarningProceed": "그래도 이 위치 사용",+ "cloudWarningToast": "클라우드 동기화 폴더를 사용 중입니다. 동기화로 데이터베이스 파일이 손상될 수 있으니 조속히 위치를 변경하세요.",+ "deleteData": "작업 데이터 삭제…",+ "deleteBusy": "삭제 중…",+ "deleteConfirmTitle": "이 플러그인의 모든 작업 데이터를 삭제할까요?",+ "deleteConfirmDescription": "이 작업은 플러그인 제거와 별개의 작업입니다. 삭제된 데이터는 휴지통으로 옮겨져 30일간 보관된 후 완전히 삭제됩니다. 제거 또는 재설치로는 이 데이터가 영향을 받지 않습니다.",+ "deleteConfirmText": "데이터 삭제",+ "deleteDone": "작업 데이터를 휴지통으로 옮겼습니다",+ "deleteFailed": "삭제 실패",+ "pickFailed": "선택한 위치를 사용할 수 없습니다",+ "installLocationLabel": "라이브러리 저장 위치",+ "installLocationDefault": "기본(Cindy 관리 위치)",+ "installLocationPickedPrefix": "선택됨:",+ "installLocationChange": "변경…",+ "bindAfterInstallFailed": "사용자 지정 저장 위치 설정에 실패하여 기본 위치로 되돌렸습니다",+ "cancel": "취소"+ },"updateConfirm": {"title": "플러그인 \"{{name}}\"을(를) 업데이트할까요?","body": "버전 {{from}} → {{to}}. 설치된 버전을 교체합니다. 활성 상태와 패널 위치는 유지됩니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex abf0a5f3c9..7472f5ab8b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2590,7 +2590,11 @@"removeAria": "卸载 {{name}}","showDetails": "展开 {{name}} 的详情","collapseDetails": "收起 {{name}} 的详情",- "rowStatus": { "compatible": "兼容", "noticeCount": "{{count}} 项兼容提示", "unmanageable": "请在 Pi 中管理" },+ "rowStatus": {+ "compatible": "兼容",+ "noticeCount": "{{count}} 项兼容提示",+ "unmanageable": "请在 Pi 中管理"+ },"operationFailed": "Pi 扩展操作失败,请检查来源或网络后重试。","loading": "正在加载 Pi 扩展…","loadFailed": "暂时无法读取 Pi 扩展,请检查连接后重试。",@@ -2608,8 +2612,19 @@"confirmUninstall": "卸载","extensionDialogConfirm": "确认","cancel": "取消",- "resources": { "extension": "扩展代码", "skill": "技能", "prompt": "提示模板", "theme": "主题" },- "status": { "supported": "Cindy 完整支持", "extensionSupported": "未发现已知 Pi TUI 依赖", "partial": "发现兼容限制", "unsupported": "已安装,但不会在 Cindy 中加载", "unknown": "无法完成兼容检查" },+ "resources": {+ "extension": "扩展代码",+ "skill": "技能",+ "prompt": "提示模板",+ "theme": "主题"+ },+ "status": {+ "supported": "Cindy 完整支持",+ "extensionSupported": "未发现已知 Pi TUI 依赖",+ "partial": "发现兼容限制",+ "unsupported": "已安装,但不会在 Cindy 中加载",+ "unknown": "无法完成兼容检查"+ },"compatibility": {"supported": "技能和提示模板完整支持;扩展会在安装后解析实际源码,不再只按资源类型猜测。","partial": "检测到 Pi TUI API 时会列出具体限制;扩展仍可安装并由你决定是否继续启用。",@@ -2645,8 +2660,20 @@"keepDisabled": "保持停用","approveAndEnable": "了解风险并启用","done": "完成",- "warning": { "no-resources": "这个扩展没有发现 Pi 资源。", "inspection-failed": "扩展已登记,但无法检查已安装内容。", "inspection-limit": "扩展内容超过安全检查上限,已保持停用。", "unsupported-filter": "这个扩展使用了 Cindy 暂时无法安全复现的 Pi 资源筛选配置,因此保持停用。", "unsafe-source": "这个扩展的旧来源包含凭证或私密 URL 参数。Cindy 已隐藏敏感部分、保持停用,并禁止在应用内更新或移除。", "lifecycle-scripts-disabled": "这个扩展声明了安装脚本,但 Cindy 为安全起见没有执行。依赖安装脚本生成文件的功能可能不可用。" },- "success": { "install": "Pi 扩展已安装。当前任务不会变化;新建或重启 Pi 任务后生效。", "remove": "Pi 扩展已移除。当前任务仍保留旧扩展,关闭后才会彻底卸载。", "update": "Pi 扩展已更新。当前任务仍使用旧版本;新建或重启后生效。", "set-enabled": "Pi 扩展启用状态已保存。当前任务不会变化;新建或重启后生效。" }+ "warning": {+ "no-resources": "这个扩展没有发现 Pi 资源。",+ "inspection-failed": "扩展已登记,但无法检查已安装内容。",+ "inspection-limit": "扩展内容超过安全检查上限,已保持停用。",+ "unsupported-filter": "这个扩展使用了 Cindy 暂时无法安全复现的 Pi 资源筛选配置,因此保持停用。",+ "unsafe-source": "这个扩展的旧来源包含凭证或私密 URL 参数。Cindy 已隐藏敏感部分、保持停用,并禁止在应用内更新或移除。",+ "lifecycle-scripts-disabled": "这个扩展声明了安装脚本,但 Cindy 为安全起见没有执行。依赖安装脚本生成文件的功能可能不可用。"+ },+ "success": {+ "install": "Pi 扩展已安装。当前任务不会变化;新建或重启 Pi 任务后生效。",+ "remove": "Pi 扩展已移除。当前任务仍保留旧扩展,关闭后才会彻底卸载。",+ "update": "Pi 扩展已更新。当前任务仍使用旧版本;新建或重启后生效。",+ "set-enabled": "Pi 扩展启用状态已保存。当前任务不会变化;新建或重启后生效。"+ }},"computerUse": {"title": "自动操作",@@ -4085,6 +4112,8 @@"confirmDetail": "它动手前可以弹一个和 Cindy 同款的确认框来问你,问句由它提供、框上会标注它的名字;同意还是取消都由你亲手点,它自己点不了。同时最多一个确认框,弹得太频会被拦下。","fsWrite": "可写入文件(创建/修改)","fsWriteDetail": "它自己的专属数据目录随时可写;当前任务的工作目录跟随任务的权限模式(免批模式直接写,逐条确认模式先征求你同意);其它目录每次都需要你确认。文件始终由主机代写,插件本身无法直接访问你的文件系统。",+ "libraryPersist": "可使用持久作品库(大量文件与数据库)",+ "libraryPersistDetail": "它会获得一个由 Cindy 管理的独立存储区,用来保存你的作品数据(如画布、图片、数据库),不受普通插件数据配额限制。文件与数据库操作全部由主机代执行,插件只能使用库内相对路径,无法触碰你的其它文件。卸载插件不会删除这些数据;删除必须在 Cindy 设置中单独确认。","networkHost": "访问网络域名 {{host}}","networkSecret": "需要你提供凭证「{{name}}」","networkSecretGhostInputDetail": "凭证由这个插件自己的设置界面收集,录入时会经过插件页面;随后一次性交给主机加密保管,存入后插件无法读回,主机只在请求它声明的域名时注入。",@@ -4234,11 +4263,60 @@"slotNotify": "系统提示","slotBadge": "未读角标","slotFs": "写文件",+ "slotLibrary": "持久作品库","slotSkill": "Agent 技能","slotWorkspace": "工作区任务","slotIOSSimulator": "内置 iOS 模拟器"},"commandPaletteTag": "插件指令",+ "library": {+ "title": "持久作品库",+ "loading": "正在读取库信息…",+ "loadFailed": "库信息读取失败",+ "refresh": "刷新",+ "locationLabel": "存储位置",+ "locationDefault": "Cindy 管理的位置(系统数据目录)",+ "locationCustomPrefix": "自定义:",+ "usageLabel": "占用",+ "filesUnit": "个文件",+ "diskFreeLabel": "磁盘剩余",+ "stateDiskMissing": "库不可用:存储磁盘未连接。重新连接后在设置中重新选择位置。",+ "stateBindingMoved": "库不可用:存储位置已发生变化。请重新选择位置。",+ "stateReadonly": "库当前处于只读状态。",+ "orphanedBanner": "插件已卸载,但作品数据保留未删除;重新安装该插件后会自动恢复使用。",+ "softLimitWarning": "库占用超过建议水位({{limit}}),建议清理或迁移到其它磁盘。",+ "changeLocation": "更改位置…",+ "revertDefault": "恢复默认位置",+ "unbind": "解除位置记录",+ "relocateConfirmTitle": "迁移作品库?",+ "relocateConfirmDescription": "将把全部作品数据复制到新位置并逐项校验;原目录保留 14 天作为回滚余地。数据量大时可能需要几分钟,期间请尽量不使用该插件。",+ "relocateConfirmText": "开始迁移",+ "relocateDone": "作品库已迁移",+ "relocateFailed": "迁移失败",+ "relocateBusy": "正在迁移…",+ "revertConfirmTitle": "迁回默认位置?",+ "revertConfirmText": "迁回默认",+ "unbindConfirmTitle": "解除自定义位置记录?",+ "unbindConfirmDescription": "将回到 Cindy 管理的默认位置。原自定义目录中的数据不会被删除,也不会自动迁移;如需找回,请手动迁移该目录。",+ "unbindConfirmText": "解除记录",+ "cloudWarningTitle": "云同步目录提醒",+ "cloudWarningProceed": "仍使用该位置",+ "cloudWarningToast": "已使用云同步目录;数据库文件可能因同步被改写,建议尽快更换位置",+ "deleteData": "删除作品数据…",+ "deleteBusy": "正在删除…",+ "deleteConfirmTitle": "删除该插件的全部作品数据?",+ "deleteConfirmDescription": "这与卸载插件是两个独立操作。删除后数据移入回收站保留 30 天,期满后彻底清除;卸载或重装插件都不会影响这些数据。",+ "deleteConfirmText": "删除数据",+ "deleteDone": "作品数据已移入回收站",+ "deleteFailed": "删除失败",+ "pickFailed": "所选位置不可用",+ "installLocationLabel": "作品库存储位置",+ "installLocationDefault": "默认(Cindy 管理的位置)",+ "installLocationPickedPrefix": "已选择:",+ "installLocationChange": "更改…",+ "bindAfterInstallFailed": "自定义存储位置设置失败,已回退默认位置",+ "cancel": "取消"+ },"updateConfirm": {"title": "更新插件「{{name}}」?","body": "版本 {{from}} → {{to}}。将替换现有版本;生效状态与面板位置保持不变。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex fcb29af464..21891e86e3 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4112,6 +4112,8 @@"confirmDetail": "它動手前可以彈一個和 Cindy 同款的確認框來問你,問句由它提供、框上會標註它的名字;同意還是取消都由你親手點,它自己點不了。同時最多一個確認框,彈得太頻會被攔下。","fsWrite": "可寫入檔案(建立/修改)","fsWriteDetail": "它自己的專屬資料目錄隨時可寫;當前任務的工作目錄跟隨任務的權限模式(免批模式直接寫,逐條確認模式先徵求你同意);其它目錄每次都需要你確認。檔案始終由主機代寫,插件本身無法直接訪問你的檔案系統。",+ "libraryPersist": "可使用持久作品庫(大量檔案與資料庫)",+ "libraryPersistDetail": "它會取得一個由 Cindy 管理的獨立儲存區,用來保存你的作品資料(如畫布、圖片、資料庫),不受一般插件資料配額限制。檔案與資料庫操作全部由主機代執行,插件只能使用庫內相對路徑,無法觸碰你的其它檔案。解除安裝插件不會刪除這些資料;刪除必須在 Cindy 設定中單獨確認。","networkHost": "訪問網路域名 {{host}}","networkSecret": "需要你提供憑證「{{name}}」","networkSecretGhostInputDetail": "憑證由這個插件自己的設定介面收集,錄入時會經過插件頁面;隨後一次性交給主機加密保管,存入後插件無法讀回,主機只在請求它宣告的域名時注入。",@@ -4261,11 +4263,60 @@"slotNotify": "系統提示","slotBadge": "未讀角標","slotFs": "寫檔案",+ "slotLibrary": "持久作品庫","slotSkill": "Agent 技能","slotWorkspace": "工作區任務","slotIOSSimulator": "內建 iOS 模擬器"},"commandPaletteTag": "插件指令",+ "library": {+ "title": "持久作品庫",+ "loading": "正在讀取庫資訊…",+ "loadFailed": "庫資訊讀取失敗",+ "refresh": "重新整理",+ "locationLabel": "儲存位置",+ "locationDefault": "Cindy 管理的位置(系統資料目錄)",+ "locationCustomPrefix": "自訂:",+ "usageLabel": "佔用",+ "filesUnit": "個檔案",+ "diskFreeLabel": "磁碟剩餘",+ "stateDiskMissing": "庫不可用:儲存磁碟未連線。重新連線後請在設定中重新選擇位置。",+ "stateBindingMoved": "庫不可用:儲存位置已發生變化。請重新選擇位置。",+ "stateReadonly": "庫目前處於唯讀狀態。",+ "orphanedBanner": "插件已解除安裝,但作品資料保留未刪除;重新安裝該插件後會自動恢復使用。",+ "softLimitWarning": "庫佔用超過建議水位({{limit}}),建議清理或遷移到其它磁碟。",+ "changeLocation": "更改位置…",+ "revertDefault": "恢復預設位置",+ "unbind": "解除位置記錄",+ "relocateConfirmTitle": "遷移作品庫?",+ "relocateConfirmDescription": "將把全部作品資料複製到新位置並逐項校驗;原目錄保留 14 天作為回滾餘地。資料量大時可能需要幾分鐘,期間請盡量不使用該插件。",+ "relocateConfirmText": "開始遷移",+ "relocateDone": "作品庫已遷移",+ "relocateFailed": "遷移失敗",+ "relocateBusy": "正在遷移…",+ "revertConfirmTitle": "遷回預設位置?",+ "revertConfirmText": "遷回預設",+ "unbindConfirmTitle": "解除自訂位置記錄?",+ "unbindConfirmDescription": "將回到 Cindy 管理的預設位置。原自訂目錄中的資料不會被刪除,也不會自動遷移;如需找回,請手動遷移該目錄。",+ "unbindConfirmText": "解除記錄",+ "cloudWarningTitle": "雲端同步目錄提醒",+ "cloudWarningProceed": "仍使用該位置",+ "cloudWarningToast": "已使用雲端同步目錄;資料庫檔案可能因同步被改寫,建議盡快更換位置",+ "deleteData": "刪除作品資料…",+ "deleteBusy": "正在刪除…",+ "deleteConfirmTitle": "刪除該插件的全部作品資料?",+ "deleteConfirmDescription": "這與解除安裝插件是兩個獨立操作。刪除後資料移入回收站保留 30 天,期滿後徹底清除;解除安裝或重裝插件都不會影響這些資料。",+ "deleteConfirmText": "刪除資料",+ "deleteDone": "作品資料已移入回收站",+ "deleteFailed": "刪除失敗",+ "pickFailed": "所選位置不可用",+ "installLocationLabel": "作品庫儲存位置",+ "installLocationDefault": "預設(Cindy 管理的位置)",+ "installLocationPickedPrefix": "已選擇:",+ "installLocationChange": "更改…",+ "bindAfterInstallFailed": "自訂儲存位置設定失敗,已回退預設位置",+ "cancel": "取消"+ },"reapproveConfirm": {"title": "重新確認「{{name}}」的權限?","body": "按下方清單重新授權這個已安裝的插件,不需要重新提供安裝包檔案。",@@ -6667,10 +6718,10 @@"lastTool": "最近工具:{{tool}}","outputFile": "輸出:{{path}}"},- "planPill": {- "step": "第 {{current}} / {{total}} 步",- "dismiss": "關閉計劃"- },+ "planPill": {+ "step": "第 {{current}} / {{total}} 步",+ "dismiss": "關閉計劃"+ },"forkOrigin": {"label": "基於原任務建立"},diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 4ad9507cd6..d66b5668fa 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1561,6 +1561,16 @@ interface ElectronAPI {runtimeStates: () => Promise<{ states: Record<string, string> }>;/** 面板错误态「重载意识」:清熔断记账 + 重新拉起沙箱。 */reload: (id: string) => Promise<{ state: string }>;+ /** Library(持久作品库)设置面:概览/选位置/绑定/迁移/回默认/解绑/删除。 */+ libraryOverview: (id: string) => Promise<import('../shared/ghost').GhostLibraryOverview>;+ libraryPickLocation: (+ id: string,+ ) => Promise<{ ok: boolean; cancelled?: boolean; candidate?: string; warnings?: string[]; message?: string }>;+ libraryBind: (id: string, candidate: string) => Promise<{ ok: boolean; message?: string; warnings?: string[] }>;+ libraryRelocate: (id: string, candidate: string) => Promise<{ ok: boolean; message?: string }>;+ libraryRevertDefault: (id: string) => Promise<{ ok: boolean; message?: string }>;+ libraryUnbind: (id: string) => Promise<{ ok: boolean; message?: string }>;+ libraryDelete: (id: string) => Promise<{ ok: boolean; cancelled?: boolean; message?: string }>;legacyRecoveryStatus: () => Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus>;diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex c5ee96a896..84acb2fdbe 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -100,6 +100,12 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;* plan/只读拒)、save 票据目录(主 agent 过户,复用 saveDeposit 预算)。* 字节永远由主机落盘,沙箱本身仍无 fs——本槽是"申请主机代写"的资格,* 不是文件系统访问权。+ * 'library' = 持久作品库(2026-08-20):用户作品级存储(画布/素材/数据库),+ * 与 'fs' 私有储物柜(配额封顶、卸载回收)语义不同:不受 ghost-fs 配额约束,+ * 卸载插件**不删**(标 orphaned,删除必须走设置页独立确认)。字节与 SQL+ * 一律由主机在 owner×plugin 隔离的 Library 根内代执行,插件只持不透明+ * handle 与相对路径;SQLite 只能提交参数化语句,经宿主语句门(首词白名单)+ * 过滤后在专属 worker 里跑——插件拿不到数据库对象,也拿不到任意路径。* 'session-context' = 会话上下文(2026-07-23):agent 派活(tool-call)时,主机把* 当次会话的可信 {session_id, workdir, workdir_is_local, workdir_is_read_only}* 注入 args.session_context。@@ -143,6 +149,7 @@ export const GHOST_SLOTS = ['badge','confirm','fs',+ 'library','session-context','pick','preview',@@ -1593,6 +1600,7 @@ export function ghostContentKeys(manifest: GhostManifest): string[] {else if (slot === 'badge') keys.push('slotBadge');else if (slot === 'confirm') keys.push('slotConfirm');else if (slot === 'fs') keys.push('slotFs');+ else if (slot === 'library') keys.push('slotLibrary');// skill 是信任面最高的内容(给主 Agent 灌指令),详情页必须如实露出。else if (slot === 'skill') keys.push('slotSkill');else if (slot === 'workspace') keys.push('slotWorkspace');@@ -1676,6 +1684,7 @@ export interface GhostPermissionItem {| 'notify'| 'confirm'| 'fs'+ | 'library'| 'session-context'| 'pick'| 'preview'@@ -1996,6 +2005,16 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItif (manifest.slots.includes('fs')) {items.push({ key: 'fs', kind: 'fs', labelKey: 'fsWrite', detailKey: 'fsWriteDetail' });}+ // library 槽:持久作品库(用户数据语义,不是临时缓存)。装入时必须讲清+ // 三件事:卸载不删、删除走独立确认、数据库只收参数化语句。+ if (manifest.slots.includes('library')) {+ items.push({+ key: 'library',+ kind: 'library',+ labelKey: 'libraryPersist',+ detailKey: 'libraryPersistDetail',+ });+ }// pick 槽:能弹系统选文件夹窗口。授权动作是用户亲手选中,装入时只告知// "它会来要"。if (manifest.slots.includes('pick')) {@@ -7457,6 +7476,106 @@ export type GhostPipeFsResult =| { ok: true; op: 'delete'; path: string; /** false = 本来就不存在(幂等)。 */ existed: boolean }| { ok: false; message: string };+/* ── library 槽:持久作品库(2026-08-20;详见 docs/dev-rules/plugin-library-storage.md)── */++/**+ * library 槽操作集。文件操作与 fs:data 同为"主机代劳 + 相对路径",差异在:+ * 无 256MiB/2000 文件配额(受磁盘保留水位与软水位约束)、写入原子化+ * (staging+fsync+rename+identity 复验)、大文件走分块流、结构化错误码、+ * 卸载不删。SQLite 子集(op:'db.*')只收参数化单语句,事务/迁移/备份由+ * 宿主管理;首词白名单外的语句(ATTACH/PRAGMA/VACUUM/事务语句)一律拒。+ */+export const GHOST_LIBRARY_OPS = [+ 'open', 'status',+ 'read', 'write',+ 'writeBegin', 'writeChunk', 'writeCommit', 'writeAbort',+ 'list', 'stat', 'mkdir', 'delete', 'rename',+ 'db.open', 'db.exec', 'db.batch', 'db.migrate', 'db.backup', 'db.check', 'db.userVersion',+] as const;+export type GhostLibraryOp = (typeof GHOST_LIBRARY_OPS)[number];++/** 上行:library 槽请求(cindy.library(req) ≡ send({type:'library-request', …req}))。 */+export interface GhostPipeLibraryRequest {+ type: 'library-request';+ op: GhostLibraryOp;+ /** library 相对路径(段数/总长上限比 fs 宽:32 段/512 字符)。 */+ path?: string;+ /** write 内容(≤16MiB;更大走 writeBegin 分块流)。 */+ content?: string;+ encoding?: 'utf8' | 'base64';+ /** write:排他创建(目标已存在则 ALREADY_EXISTS)。 */+ ifNotExists?: boolean;+ /** 分块流:声明总字节数与期望 sha256(Commit 时核对)。 */+ totalBytes?: number;+ sha256?: string;+ streamId?: string;+ seq?: number;+ /** list:递归开关/续游标/页大小。 */+ recursive?: boolean;+ cursor?: string;+ limit?: number;+ /** delete:目录递归。 */+ recursiveDelete?: boolean;+ /** rename 源/目标(库内相对路径)。 */+ from?: string;+ to?: string;+ overwrite?: boolean;+ /** SQLite 子集:库内 .sqlite 相对路径 + 参数化 SQL。 */+ dbPath?: string;+ sql?: string;+ params?: unknown;+ statements?: Array<{ sql: string; params?: unknown }>;+ targetVersion?: number;+ steps?: Array<{ toVersion: number; sql: string[] }>;+ /** read 分段。 */+ offset?: number;+ length?: number;+}++/**+ * library 槽返回:成功形态按 op 分流(文件操作带宿主实算 sha256——未来+ * 网络同步的素材完整性地基);失败**结构化**(errorCode + 人话 message,+ * 修掉 fs 槽无错误码的缺口),对沙箱永不 reject。+ */+export type GhostPipeLibraryResult =+ | { ok: true; op: 'open' | 'status'; state: 'ready' | 'readonly' | 'unavailable'; reason?: string; usedBytes: number; fileCount: number; diskFreeBytes?: number | null; softLimitBytes?: number; softLimitExceeded?: boolean; location?: 'default' | 'custom' }+ | { ok: true; op: 'read'; path: string; content: string; encoding: 'utf8' | 'base64'; bytes: number; sha256: string }+ | { ok: true; op: 'write' | 'writeCommit'; path: string; bytes: number; sha256: string }+ | { ok: true; op: 'writeBegin'; streamId: string }+ | { ok: true; op: 'writeChunk'; accepted: number }+ | { ok: true; op: 'writeAbort'; aborted: boolean }+ | { ok: true; op: 'list'; entries: Array<{ path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }>; hasMore: boolean; nextCursor: string | null }+ | { ok: true; op: 'stat'; path: string; kind: 'file' | 'dir'; bytes: number; mtime: number }+ | { ok: true; op: 'mkdir'; path: string; existed: boolean }+ | { ok: true; op: 'delete'; path: string; existed: boolean }+ | { ok: true; op: 'rename'; from: string; to: string }+ | { ok: true; op: 'db.open'; opened: boolean }+ | { ok: true; op: 'db.exec'; rows?: unknown[]; changes?: number; lastInsertRowid?: string | number }+ | { ok: true; op: 'db.batch'; applied: number }+ | { ok: true; op: 'db.migrate'; fromVersion: number; toVersion: number }+ | { ok: true; op: 'db.backup'; backedUp: boolean }+ | { ok: true; op: 'db.check'; healthy: boolean; detail: string }+ | { ok: true; op: 'db.userVersion'; version: number | null }+ | { ok: false; errorCode: string; message: string };++/** Library 概览(ghosts:library-overview IPC 载荷;设置页插件详情消费)。 */+export interface GhostLibraryOverview {+ /** 插件是否声明了 library 槽(未声明时设置页不渲染该区)。 */+ supported: boolean;+ state: 'ready' | 'readonly' | 'unavailable';+ reason: string | null;+ location: 'default' | 'custom';+ /** 自定义位置的用户所选父目录(用户自己选的,如实展示;默认位置为 null)。 */+ customCandidate: string | null;+ usedBytes: number;+ fileCount: number;+ diskFreeBytes: number | null;+ softLimitBytes: number;+ softLimitExceeded: boolean;+ /** 卸载后未删除的标记(重装自动清除;设置页以横幅提示)。 */+ orphaned: boolean;+}+/** 上行:network 槽代理 fetch 请求。 */export interface GhostPipeFetchRequest {type: 'fetch-request';diff --git a/apps/desktop/vite.library-db-worker.config.ts b/apps/desktop/vite.library-db-worker.config.tsnew file mode 100644index 0000000000..ee2df43950--- /dev/null+++ b/apps/desktop/vite.library-db-worker.config.ts@@ -0,0 +1,16 @@+import { defineConfig } from 'vite';++export default defineConfig({+ resolve: {+ conditions: ['node'],+ mainFields: ['module', 'jsnext:main', 'jsnext'],+ },+ build: {+ rollupOptions: {+ // library db worker 是 Node worker_threads 运行时,原生模块必须在+ // packaged app 的 node_modules / asar.unpacked 中按平台解析,不能被+ // Vite bundle(与 vite.db-worker.config.ts 同约束)。+ external: ['better-sqlite3'],+ },+ },+});diff --git a/docs/dev-rules/plugin-library-storage.md b/docs/dev-rules/plugin-library-storage.mdnew file mode 100644index 0000000000..6bbe4e6a62--- /dev/null+++ b/docs/dev-rules/plugin-library-storage.md@@ -0,0 +1,93 @@+# 插件持久 Library(library 槽)++> **状态**:权威开发规则(authoritative)+> **读取时机**:新增或修改 library 槽(持久作品库)、binding / 目录选择、迁移、+> 回收站删除、SQLite 语句门、面板 `/library/` 投影,或任何触碰+> `libraries/` / `libraries-binding.json` / `libraries-trash/` 落盘布局的改动之前++library 槽给插件一个**用户作品级**的持久存储区,与 fs 槽私有储物柜+(256MiB/2000 文件配额、卸载即回收)是两个语义:不受配额约束(只受磁盘保留+水位与软水位约束)、**卸载插件不删数据**、删除必须走设置页独立确认。完整产品+语义与裁决记录见方案文档(2026-08-20 定案:装入时可选目录 + 随时安全迁移并入+首期)。++## 事实来源++| 内容 | 权威来源 |+| --- | --- |+| 文件层基座(路径纪律 / 原子写 / 分块流 / 用量账本 / 状态机) | `apps/desktop/src/main/cindy-brain/libraryVault.ts` |+| 自定义位置 binding 与候选目录校验 | `apps/desktop/src/main/cindy-brain/libraryBinding.ts` |+| SQLite 语句门与执行核心(worker 与单测共用) | `apps/desktop/src/main/cindy-brain/libraryDbCore.ts` |+| per-plugin worker 入口 | `apps/desktop/src/main/cindy-brain/libraryDbWorker.ts` |+| 主进程 RPC 服务(发送前语句门 / dispose 收口) | `apps/desktop/src/main/cindy-brain/librarySqlService.ts` |+| 协议分派(资格审 / binding 根解析 / owner scope 复核) | `apps/desktop/src/main/cindy-brain/librarySlot.ts` |+| 随时迁移状态机 | `apps/desktop/src/main/cindy-brain/libraryMigrate.ts` |+| 回收站删除通道 | `apps/desktop/src/main/cindy-brain/libraryTrash.ts` |+| 管子协议类型(`library-request`) | `apps/desktop/src/shared/ghost.ts`(`GhostPipeLibraryRequest/Result`) |+| 面板 `/library/` 投影 | `cindy-brain/runtime/electronSandboxAdapter.ts`(`serveGhostLibraryFile`) |+| 装配 / 生命周期挂点 / 设置面 IPC | `cindy-brain/index.ts`(`getGhostLibrarySlot`、`relocateGhostLibraryTo`、`getGhostLibraryOverview`) |+| 作者手册章节 | `cindy-brain/forge.ts` 的 `FORGE_GUIDE` §4.10.1 |++## 落盘布局(owner-scoped,全部经 `ownerScopedUserDataPath`)++```+owners/<ownerKey>/+├── libraries/<ghostId>/ # 系统管理默认根+├── libraries-binding.json # 自定义位置持久 binding(原子写)+└── libraries-trash/<ghostId>-<ts>/ # 删除通道的 30 天回收站+```++自定义根 = `<用户所选父目录>/<ghostId>`(binding 记录 realpath 快照 + 文件+identity + generation)。库内宿主命名空间 `.cindy-library/`(meta/usage/tmp/+backups)对插件不可达——路径语法段首不许点,协议层天然隔离。++## 不变量++1. **不可用 ≠ 空**:meta 损坏 → `unavailable(corrupt)`;binding 漂移 →+ `binding-moved` / `disk-missing`。宿主不自动重建、不清空、不回退写默认根、+ 不触发 GC、不判素材已删。插件侧同样语义写进了 FORGE_GUIDE。+2. **卸载不删**:uninstall 只标 orphaned + 作废会话;binding 保留(用户亲选+ 事实不因重装消失)。删除 = 设置页独立破坏性确认 + `trashGhostLibrary`+ (rename 进回收站,漂移时 NOT_FOUND 不误删)。内置插件退役清理+ (`cleanupRetiredGhostData`)**不得**触及 Library。+3. **owner 隔离**:会话绑定 `activeOwnerScopeKey` 每请求比对;切换在途由+ `interruptGhostCallsForAccountBoundary` 的 `disposeAll` 收口(在途写入随串行+ 链归属原 owner)。根解析每次经 binding store 现解。+4. **路径纪律**:相对路径四层校验(`isSafeGhostRelativePath` →+ `validateLibraryRelPath` → `isInsideDir` → realpath 祖先收敛),目标 lstat+ 不穿透 symlink。写入 = staging + fsync + rename + dev/ino identity 复验+ (对齐 `dirDeposit.writeNewSaveFile` 范式)。+5. **SQL 白名单**:better-sqlite3 无 set_authorizer,唯一可靠防线是首词允许+ 清单(deny-by-default)+ prepare 单语句 + 事务/迁移/备份全宿主管理。+ ATTACH/VACUUM INTO/PRAGMA/事务语句一律 `DB_STATEMENT_REJECTED`。改白名单+ 前必须重新论证「该语句类型无法嵌进 SELECT/触发器/视图」。+6. **票据不升级**:`dir`/`save_dir` 十分钟内存票据与 Library binding 不共享+ 存储与校验入口。+7. **结果集上限**:2000 行 / 16MiB 序列化(`DB_ROW_LIMIT`);分块流 Commit 核+ 对宿主实算 sha256——`write`/`writeCommit`/`read` 返回的 sha256 是未来网络+ 同步的素材完整性地基,不得移除。+8. **迁移安全**:precheck(校验 + 空间 ≥ 用量×1.2 + 目标非空拒)→ copying+ (.sqlite 走在线 backup)→ verifying(清单逐项对账 + quick_check)→+ switching(binding generation+1 原子写)→ grace(旧目录改名保留 14 天)。+ 任一步失败 binding 未切换、原位置原样。+9. **面板投影**:`cindy-ghost://<ghostId>/library/<relPath>` 与电子脑 read 同+ 源校验,失败折叠 404;内容可变故 `Cache-Control: no-cache`(与内容寻址的+ `/media/` 长缓存刻意不同)。+10. **known limitation(如实告知,不假装覆盖)**:Windows 上 binding 的文件+ identity(st_ino)多为 0,「同路径删后重建」检不出(POSIX 可检出);映射+ 网络盘符检测需要 Win32 API,v1 只拒 UNC 路径;市场装入确认框的「存储位置」+ 行尚未接入(装后可从设置页迁移)。++## Review 清单++1. 路径/SQL 是否仍只经白名单与相对键?有没有新的绝对路径出口?+2. 失败路径是否保持「不可用 ≠ 空」「任一步失败原位原样」?+3. 生命周期挂点(uninstall/setEnabled/owner 边界)是否补了对应的 dispose?+4. i18n 五语与中文标点门禁、FORGE_GUIDE §4.10.1 是否同步?++最小验证入口:++```bash+pnpm --filter desktop exec vitest run src/main/cindy-brain/__tests__/library+pnpm --filter desktop typecheck+```diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 4eba6af338..445f3cad5e 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -31,7 +31,7 @@| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` || 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` || 安装批准事实(receipt / 技能快照 / revision) | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,批准态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |-| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`)、`iosSimulatorSlot.ts`(当前台前任务的公开状态与 Host viewer 入口) |+| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`)、`iosSimulatorSlot.ts`(当前台前任务的公开状态与 Host viewer 入口);library 槽(持久作品库:文件层/SQLite 语句门/binding/迁移/回收站)见 [`plugin-library-storage.md`](plugin-library-storage.md),主实现在 `libraryVault.ts`、`librarySlot.ts`、`libraryDbCore.ts` || 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 || 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` || 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |