Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 会话级只读 library extraDirs,ChatInput 不计系统槽 (#3745)

Praise11e02c0306f8
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index f205d140c1..267825b8eb 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -721,10 +721,16 @@ describe('sendToSession ordering', () => {
'idleWorker: async ({ callerLeadSessionId, workerId, expectedStatus }) => {',
);
- expect(resumeBranch).toContain('const extraDirs = await readSessionExtraDirsFromDb(target.sessionId);');
+ expect(resumeBranch).toContain(
+ 'const extraDirs = extraDirsForRuntime(await readSessionExtraDirsFromDb(target.sessionId));',
+ );
expect(resumeBranch).toContain('permissionMode: permissionModeOrAsk(row.permissionMode),');
expect(resumeBranch).toContain('...(extraDirs.length > 0 ? { extraDirs } : {}),');
- expectOrder(resumeBranch, 'const extraDirs = await readSessionExtraDirsFromDb(target.sessionId);', 'const opts = buildCreateOptsWithStderr({');
+ expectOrder(
+ resumeBranch,
+ 'const extraDirs = extraDirsForRuntime(await readSessionExtraDirsFromDb(target.sessionId));',
+ 'const opts = buildCreateOptsWithStderr({',
+ );
expectOrder(resumeBranch, '...(extraDirs.length > 0 ? { extraDirs } : {}),', 'await bootstrapSession(opts);');
expect(serviceDepsBlock).toContain('resumeWorkerSession: async (target) => {');
expect(serviceDepsBlock).toContain('await resumeOrcaWorkerSessionIfMissing(target);');
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 9d9f0fc48e..fedfaa24ac 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -218,8 +218,8 @@ describe('session runtime control wiring', () => {
it('serializes local and remote directory validation, runtime apply, persistence, and rollback', () => {
const grantUpdate = handlerBody(
registerSource,
- 'const applyDirectoryGrants =',
- 'ipcMain.handle(MAKER_INVOKE.SET_EXTRA_DIRS',
+ 'export function applyDirectoryGrants(',
+ 'export async function applyLibraryReadonlyExtraDir(',
);
const extraDirs = handlerBody(
registerSource,
@@ -242,6 +242,44 @@ describe('session runtime control wiring', () => {
expect(extraDirs).toContain("applyDirectoryGrants('extraDirs'");
expect(writableDirs).toContain("applyDirectoryGrants('writableDirs'");
expect(writableDirs).toContain('senderId: event.sender.id');
+ expect(registerSource).toContain('setGhostLibraryExtraDirSync(syncLibraryReadonlyExtraDir)');
+ expect(registerSource).toContain('const persistOnly = !sess');
+ expect(registerSource).toContain('await applyLibraryReadonlyExtraDir(sessionId, nextRoot)');
+ expect(registerSource).toContain(
+ 'const extraDirs = extraDirsForRuntime(await readSessionExtraDirsFromDb(target.sessionId))',
+ );
+ const applyLibrary = handlerBody(
+ registerSource,
+ 'export async function applyLibraryReadonlyExtraDir(',
+ 'let libraryExtraDirSyncGeneration',
+ );
+ expect(grantUpdate).toContain('options.replaceLibrarySlot');
+ expect(grantUpdate).toContain('excludeDirectoryGrantConflictsWithSlots');
+ expect(applyLibrary).toContain('fsp.realpath(root)');
+ expect(applyLibrary).toContain('replaceLibrarySlot: true');
+ expect(applyLibrary).toContain('applyDirectoryGrants(');
+ expect(applyLibrary).toContain("'extraDirs'");
+ expect(applyLibrary).toContain('{ remote: false, replaceLibrarySlot: true }');
+ expect(applyLibrary).not.toContain('consumeWritableDirectoryPickerGrants');
+ const syncLibrary = handlerBody(
+ registerSource,
+ 'async function syncLibraryReadonlyExtraDir(',
+ 'let agentInputCoordinatorHolder',
+ );
+ expect(syncLibrary).toContain('listVisibleActiveSessionIds()');
+ expect(syncLibrary).toContain('targets.add(focused)');
+ expect(syncLibrary).toContain('sessionIsRemote(sessionId)');
+ expect(syncLibrary).toContain('!remote && grantRoot && sessionId === focused ? grantRoot : null');
+ expect(syncLibrary).toContain("throw new Error('library extraDirs sync superseded')");
+ expect(syncLibrary).toContain("throw new Error('library extraDirs not granted to focused session')");
+ expect(syncLibrary).toContain('if (!remote && nextRoot && sessionId === focused) throw error');
+ expect(syncLibrary).toContain('libraryExtraDirSyncChain.then(run, run)');
+ expect(syncLibrary).toMatch(
+ /await applyLibraryReadonlyExtraDir\(sessionId, nextRoot\);[\s\S]*if \(generation !== libraryExtraDirSyncGeneration\)/,
+ );
+ expect(extraDirs).toContain('!isLibraryExtraDirSlot(dir)');
+ expect(extraDirs).not.toContain('splitExtraDirSlots(persisted)');
+ expect(extraDirs).not.toContain('[...requested, ...library]');
});
it('guards local user model changes before parsing input while preserving trusted internal paths', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
index c7e1e34e2c..ff98f20029 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
@@ -1336,6 +1336,46 @@ describe('改图代办(edit_image)', () => {
expect(resolveOwnedMedia).toHaveBeenCalledWith('art', HASH_S, 'cloud:owner-a:1');
expect(editImage).not.toHaveBeenCalled();
});
+
+ it('library 正本 blob 相对键可消费;sidecar 禁止当像素', async () => {
+ const HASH = 'a'.repeat(64);
+ const blob = `assets/${HASH.slice(0, 2)}/${HASH}/blob.png`;
+ const resolveOwnedMedia = vi.fn(async (_g: string, key: string) =>
+ key === blob ? `/library/${blob}` : null,
+ );
+ const { slot, editImage } = makeSlot({
+ resolveOwnedMedia,
+ } as Partial<CindySlotDeps>);
+ const ok = await slot.handleModelRequest('art', {
+ ...EDIT_REQ,
+ hashes: [blob],
+ });
+ expect(ok).toMatchObject({ ok: true });
+ expect(resolveOwnedMedia).toHaveBeenCalledWith('art', blob, 'cloud:test-owner:1');
+ expect(editImage).toHaveBeenCalledWith(expect.objectContaining({ imagePaths: [`/library/${blob}`] }));
+
+ const sidecar = makeSlot();
+ const rejected = await sidecar.slot.handleModelRequest('art', {
+ ...EDIT_REQ,
+ hashes: [`assets/${HASH.slice(0, 2)}/${HASH}/preview.webp`],
+ });
+ expect(rejected).toMatchObject({ ok: false });
+ expect((rejected as { message: string }).message).toContain('sidecar');
+ expect(sidecar.editImage).not.toHaveBeenCalled();
+
+ const prefixedResolve = vi.fn();
+ const prefixedSidecar = makeSlot({
+ resolveOwnedMedia: prefixedResolve,
+ } as Partial<CindySlotDeps>);
+ const prefixedRejected = await prefixedSidecar.slot.handleModelRequest('art', {
+ ...EDIT_REQ,
+ hashes: [`library:assets/${HASH.slice(0, 2)}/${HASH}/preview.webp`],
+ });
+ expect(prefixedRejected).toMatchObject({ ok: false });
+ expect((prefixedRejected as { message: string }).message).toContain('sidecar');
+ expect(prefixedSidecar.editImage).not.toHaveBeenCalled();
+ expect(prefixedResolve).not.toHaveBeenCalled();
+ });
});
describe('管子续命挂钩(同步视频代办 hold/release)', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts
index 19fb69334e..be98be1261 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts
@@ -6,7 +6,7 @@
import { describe, expect, it, vi } from 'vitest';
-import { ImageChannelRegistry, decodeImageResponse, type ImageChannel } from '../imageChannelRegistry';
+import { ImageChannelRegistry, decodeImageResponse, assertLibraryEditImageSource, type ImageChannel } from '../imageChannelRegistry';
function channel(ready: boolean, supportsEdit?: boolean): ImageChannel {
return {
@@ -92,3 +92,16 @@ describe('decodeImageResponse', () => {
expect(() => decodeImageResponse({ data: [{}] })).toThrow(/返回为空/);
});
});
+
+describe('assertLibraryEditImageSource', () => {
+ const HASH = 'b'.repeat(64);
+ const blob = `assets/${HASH.slice(0, 2)}/${HASH}/blob.png`;
+
+ it('正本 blob 可消费,sidecar 与错误文件名 fail-visible', () => {
+ expect(() => assertLibraryEditImageSource(blob)).not.toThrow();
+ expect(() => assertLibraryEditImageSource(`/abs/library/${blob}`)).not.toThrow();
+ expect(() => assertLibraryEditImageSource(`assets/${HASH.slice(0, 2)}/${HASH}/preview.webp`)).toThrow(/sidecar/);
+ expect(() => assertLibraryEditImageSource(`assets/${HASH.slice(0, 2)}/${HASH}/meta.json`)).toThrow(/sidecar/);
+ expect(() => assertLibraryEditImageSource(`assets/${HASH.slice(0, 2)}/${HASH}.png`)).toThrow(/正本 blob/);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
index 1de27566f7..bfa8037df4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
@@ -9,7 +9,8 @@ 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 { GhostLibrarySlot, libraryAvailableRef, type GhostLibrarySlotDeps } from '../librarySlot.js';
+import { createHash } from 'node:crypto';
import { LibraryBindingStore } from '../libraryBinding.js';
import { LibraryVault } from '../libraryVault.js';
import { createLibraryDbCore, type SqliteDatabaseConstructor } from '../libraryDbCore.js';
@@ -45,8 +46,10 @@ describe('GhostLibrarySlot', () => {
let scopeKey: string | null = 'local:owner-a:1';
let ghost: InstalledGhost;
let slot: GhostLibrarySlot;
+ let bindingStore: LibraryBindingStore;
let showItemInFolder: ReturnType<typeof vi.fn>;
let showSaveDialog: ReturnType<typeof vi.fn>;
+ let syncAgentReadonlyExtraDir: ReturnType<typeof vi.fn>;
let clock: number;
beforeEach(async () => {
@@ -57,13 +60,14 @@ describe('GhostLibrarySlot', () => {
clock = 0;
await fs.promises.mkdir(candidate, { recursive: true });
ghost = makeGhost(true);
+ bindingStore = new LibraryBindingStore({
+ getFile: () => bindingFile,
+ getManagedRoots: () => [path.join(tmp, 'managed')],
+ getDefaultRoot: (id) => path.join(defaultRootBase, id),
+ });
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),
- }),
+ bindingStore,
getDefaultRoot: (id) => path.join(defaultRootBase, id),
captureOwnerScope: () => scopeKey,
createVault: (d) => new LibraryVault(d),
@@ -78,10 +82,12 @@ describe('GhostLibrarySlot', () => {
betterSqliteModulePath: () => 'better-sqlite3',
showItemInFolder: (...args: unknown[]) => showItemInFolder(...args),
showSaveDialog: (...args: unknown[]) => showSaveDialog(...args),
+ syncAgentReadonlyExtraDir: (...args: unknown[]) => syncAgentReadonlyExtraDir(...args),
now: () => clock,
};
showItemInFolder = vi.fn();
showSaveDialog = vi.fn(async () => ({ canceled: true }));
+ syncAgentReadonlyExtraDir = vi.fn(async () => {});
slot = new GhostLibrarySlot(deps);
});
@@ -440,4 +446,112 @@ describe('GhostLibrarySlot', () => {
expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE' });
expect(fs.existsSync(dest)).toBe(false);
});
+
+ it('open/status 握手含 authorizedReadonly 与 generation/identity,JSON 不含绝对库根', async () => {
+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));
+ const openHs = open as unknown as {
+ authorizedReadonly: boolean;
+ libraryGeneration: number;
+ libraryIdentity: string;
+ };
+ expect(openHs.authorizedReadonly).toBe(true);
+ expect(openHs.libraryGeneration).toBe(0);
+ expect(openHs.libraryIdentity).toBe('default');
+ const dumped = JSON.stringify(open);
+ expect(dumped).not.toContain(defaultRootBase);
+ expect(dumped).not.toMatch(/\/Users\//);
+ expect(dumped).not.toContain(tmp);
+
+ const st = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect((st as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ const probeDump = JSON.stringify({ open, status: st });
+ expect(probeDump).not.toContain(defaultRootBase);
+ expect(probeDump).not.toMatch(/\/Users\/.*\/libraries\//);
+ });
+
+ it('open 把库根交给 extraDirs 同步;dispose 时撤槽', async () => {
+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));
+ expect(syncAgentReadonlyExtraDir).toHaveBeenCalledWith(
+ GHOST_ID,
+ path.join(defaultRootBase, GHOST_ID),
+ );
+ await slot.disposeGhost(GHOST_ID);
+ expect(syncAgentReadonlyExtraDir).toHaveBeenCalledWith(GHOST_ID, null);
+ });
+
+ it('bind generation 变了:握手换身份,extraDirs 同步新根不留旧根', async () => {
+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ const defaultRoot = path.join(defaultRootBase, GHOST_ID);
+ expect(syncAgentReadonlyExtraDir).toHaveBeenCalledWith(GHOST_ID, defaultRoot);
+
+ const bound = await bindingStore.setBinding(GHOST_ID, candidate);
+ expect(bound.ok).toBe(true);
+ await slot.disposeGhost(GHOST_ID);
+ syncAgentReadonlyExtraDir.mockClear();
+
+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));
+ const hs = open as unknown as {
+ authorizedReadonly: boolean;
+ libraryGeneration: number;
+ libraryIdentity: string;
+ };
+ expect(hs.authorizedReadonly).toBe(true);
+ expect(hs.libraryGeneration).toBe(1);
+ expect(hs.libraryIdentity).toBe('g1');
+ const dumped = JSON.stringify(open);
+ expect(dumped).not.toContain(candidate);
+ expect(dumped).not.toContain(defaultRoot);
+ expect(dumped).not.toMatch(/\/Users\/.*\/libraries\//);
+
+ const newRoot = path.join(await fs.promises.realpath(candidate), GHOST_ID);
+ expect(syncAgentReadonlyExtraDir).toHaveBeenCalledWith(GHOST_ID, newRoot);
+ expect(syncAgentReadonlyExtraDir.mock.calls.map((call) => call[1])).not.toContain(defaultRoot);
+ });
+
+ it('extraDirs 同步失败则握手 authorizedReadonly=false,不假装授权', async () => {
+ syncAgentReadonlyExtraDir.mockRejectedValueOnce(new Error('require app-server 0.144.6 or newer'));
+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));
+ expect((open as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ expect(JSON.stringify(open)).not.toContain(defaultRootBase);
+ });
+
+ it('writeCommit ACK 含 64-hex sha256,形状 {ok,op,path,bytes,sha256}', async () => {
+ const body = 'pixel-bytes';
+ const sha = createHash('sha256').update(body).digest('hex');
+ const rel = 'assets/ab/abc123def456abc123def456abc123de/blob.png';
+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ const begin = await slot.handleLibraryRequest(GHOST_ID, {
+ op: 'writeBegin', path: rel, totalBytes: Buffer.byteLength(body), sha256: sha,
+ });
+ if (!begin.ok || begin.op !== 'writeBegin') throw new Error(JSON.stringify(begin));
+ const chunk = await slot.handleLibraryRequest(GHOST_ID, {
+ op: 'writeChunk', streamId: begin.streamId, seq: 1, content: body,
+ });
+ expect(chunk.ok).toBe(true);
+ const commit = await slot.handleLibraryRequest(GHOST_ID, { op: 'writeCommit', streamId: begin.streamId });
+ expect(commit).toEqual({
+ ok: true,
+ op: 'writeCommit',
+ path: rel,
+ bytes: Buffer.byteLength(body),
+ sha256: sha,
+ });
+ expect(commit.ok && 'sha256' in commit && /^[0-9a-f]{64}$/.test(commit.sha256)).toBe(true);
+ expect(fs.existsSync(path.join(tmp, 'libraryConfirmed.ts'))).toBe(false);
+ expect(fs.existsSync(path.join(process.cwd(), 'apps/desktop/src/main/cindy-brain/libraryConfirmed.ts'))).toBe(false);
+ });
+
+ it('available 引用:授权相对键,未授权 cindy-media,SVG 未授权不可读', () => {
+ const hash = 'c'.repeat(64);
+ expect(libraryAvailableRef({ authorized: true, hash, ext: 'png', confirmed: true }))
+ .toBe(`library:assets/${hash.slice(0, 2)}/${hash}/blob.png`);
+ expect(libraryAvailableRef({ authorized: false, hash, ext: 'png', confirmed: true }))
+ .toBe(`cindy-media://blobs/${hash}.png`);
+ expect(libraryAvailableRef({ authorized: false, hash, ext: 'svg', confirmed: true })).toBeNull();
+ expect(libraryAvailableRef({ authorized: true, hash, ext: 'png', confirmed: false })).toBeNull();
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts
index 1e49e1004e..5069a386c5 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryVault.test.ts
@@ -16,6 +16,8 @@ import {
DEFAULT_LIBRARY_LIMITS,
type LibraryVaultDeps,
type LibraryLimits,
+ type LibraryFileIdentity,
+ type LibraryReadHandle,
} from '../libraryVault.js';
const sha256Of = (s: string): string => createHash('sha256').update(s).digest('hex');
@@ -50,22 +52,55 @@ describe('LibraryVault', () => {
let diskFree: number | null = 1024 ** 4; // 1 TiB:默认宽裕
let limitsOverride: Partial<LibraryLimits> = {};
- const makeVault = (): LibraryVault => {
+ const makeVault = (over: Partial<LibraryVaultDeps> = {}): LibraryVault => {
const deps: LibraryVaultDeps = {
rootDir: () => libraryRoot,
ghostId: 'test-ghost',
getDiskFreeBytes: async () => diskFree,
locationKind: 'default',
+ limits: limitsOverride,
+ ...over,
};
return new LibraryVault(deps);
};
+ const identityStub = (
+ size: number,
+ isFile = true,
+ ino = 1,
+ dev = 1,
+ ): LibraryFileIdentity => ({
+ size: BigInt(size),
+ isFile: () => isFile,
+ ino: BigInt(ino),
+ dev: BigInt(dev),
+ });
+
+ const fakeReadHandle = (opts: {
+ statSize: number;
+ isFile?: boolean;
+ data?: Buffer;
+ ino?: number;
+ dev?: number;
+ readSpy?: () => void;
+ }): LibraryReadHandle => {
+ const data = opts.data ?? Buffer.alloc(opts.statSize);
+ return {
+ stat: async () => identityStub(opts.statSize, opts.isFile ?? true, opts.ino ?? 1, opts.dev ?? 1),
+ read: async (buffer, offset, length, position) => {
+ opts.readSpy?.();
+ const bytesRead = data.copy(buffer, offset, position, position + length);
+ return { bytesRead };
+ },
+ close: async () => undefined,
+ };
+ };
+
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 () => {
@@ -448,4 +483,98 @@ describe('LibraryVault', () => {
expect(d.ok).toBe(false);
});
});
+
+ describe('read 路径 O_NOFOLLOW + identity 复核', () => {
+ it('常规 blob 可读(真实 fs,正本 assets/<2>/<hash>/blob.ext)', async () => {
+ const vault = makeVault();
+ await vault.open();
+ const rel = 'assets/ab/abc123def456abc123def456abc123de/blob.png';
+ const body = 'pixel-bytes';
+ const w = await vault.write({ path: rel, content: body });
+ expect(w.ok).toBe(true);
+ const r = await vault.read({ path: rel });
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.content).toBe(body);
+ expect(r.sha256).toBe(sha256Of(body));
+ expect(r.bytes).toBe(Buffer.byteLength(body));
+ }
+ });
+
+ it('打开后目标 identity 变化 → INTERNAL 且不得返回字节', async () => {
+ const vault = makeVault();
+ await vault.open();
+ await vault.write({ path: 'assets/ab/deadbeefdeadbeefdeadbeefdeadbeef/blob.bin', content: 'secret' });
+ let readCalled = false;
+ const vaultSwap = makeVault({
+ lstatForRead: async () => identityStub(6, true, 1, 1),
+ openForRead: async () =>
+ fakeReadHandle({
+ statSize: 6,
+ data: Buffer.from('secret'),
+ ino: 999,
+ readSpy: () => {
+ readCalled = true;
+ },
+ }),
+ });
+ await vaultSwap.open();
+ const r = await vaultSwap.read({ path: 'assets/ab/deadbeefdeadbeefdeadbeefdeadbeef/blob.bin' });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.errorCode).toBe('INTERNAL');
+ expect(r).not.toHaveProperty('content');
+ expect(readCalled).toBe(false);
+ });
+
+ it('ino=0 身份不可用 → fail-closed INTERNAL,不得返回字节', async () => {
+ const vault = makeVault();
+ await vault.open();
+ await vault.write({ path: 'assets/cd/cafecafecafecafecafecafecafecafe/blob.bin', content: 'leak' });
+ let readCalled = false;
+ const vaultZero = makeVault({
+ lstatForRead: async () => identityStub(4, true, 0, 1),
+ openForRead: async () =>
+ fakeReadHandle({
+ statSize: 4,
+ data: Buffer.from('leak'),
+ ino: 0,
+ readSpy: () => {
+ readCalled = true;
+ },
+ }),
+ });
+ await vaultZero.open();
+ const r = await vaultZero.read({ path: 'assets/cd/cafecafecafecafecafecafecafecafe/blob.bin' });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.errorCode).toBe('INTERNAL');
+ expect(r).not.toHaveProperty('content');
+ expect(readCalled).toBe(false);
+ });
+
+ it('openForRead 收到 O_RDONLY|O_NOFOLLOW;失败不得回落无复核 read', async () => {
+ const vault = makeVault();
+ await vault.open();
+ await vault.write({ path: 'assets/ef/efefefefefefefefefefefefefefefef/blob.bin', content: 'payload' });
+ const seenFlags: number[] = [];
+ const vaultFlags = makeVault({
+ lstatForRead: async () => identityStub(7, true, 1, 1),
+ openForRead: async (_abs, flags) => {
+ seenFlags.push(flags);
+ const err = new Error('ELOOP') as NodeJS.ErrnoException;
+ err.code = 'ELOOP';
+ throw err;
+ },
+ });
+ await vaultFlags.open();
+ const r = await vaultFlags.read({ path: 'assets/ef/efefefefefefefefefefefefefefefef/blob.bin' });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.errorCode).toBe('INTERNAL');
+ expect(r).not.toHaveProperty('content');
+ expect(seenFlags).toHaveLength(1);
+ expect(seenFlags[0] & fs.constants.O_RDONLY).toBe(fs.constants.O_RDONLY);
+ if (typeof fs.constants.O_NOFOLLOW === 'number') {
+ expect(seenFlags[0] & fs.constants.O_NOFOLLOW).toBe(fs.constants.O_NOFOLLOW);
+ }
+ });
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.ts
index e6926324b1..932be2626c 100644
--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts
@@ -80,6 +80,8 @@ import {
} from '../../shared/ghost.js';
import type { CindyProxySearchService } from '../mcp-integrations/cindyProxySearch.js';
import { probeImageSize } from './imageProbe.js';
+import { isLibraryBlobRelPath, isLibrarySidecarRelPath } from './librarySlot.js';
+import { assertLibraryEditImageSource } from './imageChannelRegistry.js';
import {
decodeCatalogPin,
type OneshotRoute,
@@ -201,10 +203,11 @@ export interface CindySlotDeps {
*/
videoCapabilities?(model: string, providerId?: string): CindyVideoCapabilities | null;
/**
- * 指纹 → 磁盘路径,且仅当该媒体在此意识名下(出生或画廊,查账本);
+ * 指纹或 library 相对键 → 磁盘路径,且仅当该媒体在此意识名下;
* 不属于它 / 查无此账 / 文件缺失一律 null(不区分,不给探测空间)。
* ownerScopeKey 是任务受理时捕获的稳定作用域;宿主须锁定同一 DB,并在
* 每个查询 await 边界复核,禁止通过动态 defaultDb 跨到新账号。
+ * editImage 消费口:正本只认 assets/<2>/<hash>/blob.<ext>;sidecar 禁止当像素。
*/
resolveOwnedMedia(ghostId: string, hash: string, ownerScopeKey: string): Promise<string | null>;
/**
@@ -947,7 +950,15 @@ export class GhostCindySlot {
return { ok: false, message: `源图过多(上限 ${maxSources} 张)` };
}
for (const h of p.hashes) {
- if (typeof h !== 'string' || !HASH_RE.test(h)) {
+ if (typeof h !== 'string') {
+ return { ok: false, message: '源图指纹格式不合法' };
+ }
+ const blobKey = h.startsWith('library:') ? h.slice('library:'.length) : h;
+ if (isLibrarySidecarRelPath(blobKey) || (blobKey.includes('/') && !isLibraryBlobRelPath(blobKey))) {
+ return { ok: false, message: '源图必须是 library 正本 blob,sidecar 禁止当像素' };
+ }
+ if (isLibraryBlobRelPath(blobKey)) continue;
+ if (!HASH_RE.test(h)) {
return { ok: false, message: '源图指纹格式不合法' };
}
}
@@ -1028,11 +1039,25 @@ export class GhostCindySlot {
// (统一话术不泄露细节)。异步模式也在受理期同步校验,拒绝立即可见。
const imagePaths: string[] = [];
for (const hash of hashes) {
- const abs = await this.deps.resolveOwnedMedia(ghostId, hash, ownerScopeKey);
+ const lookup = hash.startsWith('library:') ? hash.slice('library:'.length) : hash;
+ if (isLibrarySidecarRelPath(lookup)) {
+ return { ok: false, message: '源图必须是 library 正本 blob,sidecar 禁止当像素' };
+ }
+ const abs = await this.deps.resolveOwnedMedia(ghostId, lookup, ownerScopeKey);
assertOwnerScopeCurrent();
if (!abs) {
return { ok: false, message: '源图不在本意识名下(仅能改自己生成或画廊里的媒体)' };
}
+ if (isLibraryBlobRelPath(lookup)) {
+ try {
+ assertLibraryEditImageSource(abs);
+ } catch (err) {
+ return {
+ ok: false,
+ message: err instanceof Error ? err.message : '源图必须是 library 正本 blob,sidecar 禁止当像素',
+ };
+ }
+ }
imagePaths.push(abs);
}
diff --git a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
index 99e566a6fe..208758d744 100644
--- a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
+++ b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
@@ -20,6 +20,21 @@
import type { GhostImageAspectRatio } from '../../shared/ghost.js';
import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
+import { isLibraryBlobRelPath, isLibrarySidecarRelPath } from './librarySlot.js';
+
+/** editImage 源路径只认 library 正本 blob;sidecar / 非 blob 文件名 fail-visible。 */
+export function assertLibraryEditImageSource(relOrAbs: string): void {
+ const rel = relOrAbs.replace(/\\/g, '/');
+ const marker = '/assets/';
+ const idx = rel.lastIndexOf(marker);
+ const candidate = idx >= 0 ? rel.slice(idx + 1) : rel.split('/').slice(-4).join('/');
+ if (isLibrarySidecarRelPath(candidate)) {
+ throw new Error('sidecar meta.json/preview.webp 禁止当像素');
+ }
+ if (!isLibraryBlobRelPath(candidate)) {
+ throw new Error('editImage 只打开 library 正本 blob');
+ }
+}
/** 通道适配层的出参(decodeImageResponse 的入参:字节 base64;声明格式仅作参考)。 */
export interface ImageChannelResult {
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index d701d7a0f2..dbe0ede421 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1001,6 +1001,13 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {
// Library 会话一并作废:关 db worker + 作废 handle——在途写入已在串行链上
// 归属原 owner 完成或随 vault.invalidate 作废,新 owner 解析到全新根。
await getGhostLibrarySlot().disposeAll();
+ if (libraryExtraDirSync) {
+ await libraryExtraDirSync(null).catch((error) => {
+ log.warn('library extraDirs owner-boundary sync failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
await getGhostSetupCoordinator()?.waitForActionsIdle();
}
@@ -2417,6 +2424,12 @@ export function noteGhostSessionFocused(sessionId: string | null): void {
// 负责 Worker → Lead 归一、异步乱序和失败后的重试。
ghostPrimarySessionFocusTracker.note(sessionId);
ghostSessionFocusTracker.note(sessionId);
+ void refreshMivoLibraryExtraDirGrant().catch((error) => {
+ log.warn('library extraDirs focus sync failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
}
const ghostSessionFocusByWebContents = new Map<number, string | null>();
@@ -3151,6 +3164,49 @@ export function setGhostWorkspaceSessionService(service: WorkspaceSessionService
getGhostWorkspaceSlot().setSessionService(service);
}
+const MIVO_LIBRARY_GHOST_IDS = new Set(['xd-mivo', 'cindy-mivo']);
+let libraryExtraDirSync: ((root: string | null) => Promise<void>) | null = null;
+
+/** maker-ipc 注入:把 library 根同步进当前 Mivo 会话 extraDirs。cindy-brain 不反向依赖 register。 */
+export function setGhostLibraryExtraDirSync(
+ sync: ((root: string | null) => Promise<void>) | null,
+): void {
+ libraryExtraDirSync = sync;
+}
+
+export function getFocusedGhostSessionId(): string | null {
+ return ghostSessionFocusTracker.current();
+}
+
+async function refreshMivoLibraryExtraDirGrant(): Promise<void> {
+ if (!libraryExtraDirSync) return;
+ const focused = ghostSessionFocusTracker.current();
+ if (!focused) {
+ await libraryExtraDirSync(null);
+ return;
+ }
+ const ghost = findAvailableGhost('xd-mivo') ?? findAvailableGhost('cindy-mivo');
+ if (!ghost || ghost.enabled === false || ghost.manifest.library !== true) {
+ await libraryExtraDirSync(null);
+ return;
+ }
+ const ghostId = ghost.manifest.id;
+ const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(ghostId);
+ if (resolution.kind === 'custom' && resolution.root === null) {
+ await libraryExtraDirSync(null);
+ return;
+ }
+ const root = resolution.kind === 'custom' && resolution.root !== null
+ ? resolution.root
+ : ownerScopedUserDataPath('libraries', ghostId);
+ await libraryExtraDirSync(root);
+}
+
+function syncMivoLibraryExtraDirFromSlot(ghostId: string, root: string | null): Promise<void> {
+ if (!MIVO_LIBRARY_GHOST_IDS.has(ghostId) || !libraryExtraDirSync) return Promise.resolve();
+ return libraryExtraDirSync(root);
+}
+
let previewSlotSingleton: GhostPreviewSlot | null = null;
/** 插件预览开页通道(main → 全窗口 renderer;右侧栏开 web-browser 标签)。 */
@@ -5142,6 +5198,7 @@ export function getGhostLibrarySlot(): GhostLibrarySlot {
workerScriptPath: defaultLibraryDbWorkerPath,
betterSqliteModulePath: () => resolveBetterSqliteModuleEntry() ?? 'better-sqlite3',
log,
+ syncAgentReadonlyExtraDir: syncMivoLibraryExtraDirFromSlot,
showItemInFolder: (absPath) => {
shell.showItemInFolder(absPath);
},
@@ -5218,6 +5275,7 @@ async function relocateGhostLibraryTo(
allowInsideManagedRoot: opts?.allowInsideManagedRoot,
});
await slot.disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
return set.ok ? { ok: true } : { ok: false, message: set.message };
}
const result = await migrateGhostLibrary({
@@ -5258,6 +5316,7 @@ async function relocateGhostLibraryTo(
allowInsideManagedRoot: opts?.allowInsideManagedRoot,
});
await slot.disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
return result.ok ? { ok: true } : { ok: false, message: result.message };
} finally {
slot.setRelocating(id, false);
@@ -5348,7 +5407,15 @@ export async function deleteGhostLibraryForActiveOwner(ghostId: string): Promise
},
log,
});
- if (result.ok) return { ok: true };
+ if (result.ok) {
+ await refreshMivoLibraryExtraDirGrant().catch((error) => {
+ log.warn('library extraDirs delete sync failed', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ return { ok: true };
+ }
return { ok: false, message: result.message };
}
@@ -6071,6 +6138,7 @@ async function uninstallGhostAndCleanupLocked(
// warn,不把卸载报成失败(与上面清账同纪律)。
try {
await getGhostLibrarySlot().disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
const vault = new LibraryVault({
rootDir: () => ownerScopedUserDataPath('libraries', id),
ghostId: id,
@@ -7559,6 +7627,12 @@ export function registerGhostIpc(): void {
const ghost = findAvailableGhost(id);
if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动
resumeGhostUnreadProjection(id); // 沉睡期间保留的那颗点回来(#1421)
+ await refreshMivoLibraryExtraDirGrant().catch((error) => {
+ log.warn('library extraDirs enable sync failed', {
+ id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
} else {
// 未读停止投影(记录保留):沉睡的意识没法把面板里的内容给你看,留一颗点
// 只是噪声;但用户是"先别烦我"不是"这条我读过了",唤醒要能找回来。
@@ -7568,6 +7642,12 @@ export function registerGhostIpc(): void {
// (要等插件再次上报或重启)。熄灯类操作(runtime/node/订阅)放在前面是既有
// 行为且幂等,唯独这条会留下用户可见的错状态(copilot + codex review)。
suspendGhostUnreadProjection(id);
+ await refreshMivoLibraryExtraDirGrant().catch((error) => {
+ log.warn('library extraDirs disable sync failed', {
+ id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
}
return { ok: true };
} finally {
@@ -7622,6 +7702,7 @@ export function registerGhostIpc(): void {
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); // 作废会话,下一请求用新根
+ await refreshMivoLibraryExtraDirGrant();
return { ok: true as const, warnings: set.warnings };
} finally {
releaseMutation();
@@ -7650,6 +7731,7 @@ export function registerGhostIpc(): void {
if (!res.ok) return res;
await getGhostLibraryBindingStore().removeBinding(id);
await getGhostLibrarySlot().disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
return { ok: true as const };
});
// 漂移恢复(位置失效):解除 binding 回默认(原自定义目录数据原样保留,
@@ -7661,6 +7743,7 @@ export function registerGhostIpc(): void {
try {
await getGhostLibraryBindingStore().removeBinding(id);
await getGhostLibrarySlot().disposeGhost(id);
+ await refreshMivoLibraryExtraDirGrant();
return { ok: true as const };
} finally {
releaseMutation();
diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.ts
index 77130c6e7c..794314cdfe 100644
--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts
@@ -32,6 +32,45 @@ import { LibraryBindingStore, type LibraryLocationResolution } from './libraryBi
import { LibrarySqlService, type LibrarySqlServiceDeps } from './librarySqlService.js';
import type { LibraryDbResult } from './libraryDbCore.js';
+/** 正本相对键:assets/<hash 前 2 位>/<64-hex>/blob.<ext>(不是 <hash>.<ext>)。 */
+const LIBRARY_BLOB_REL_RE = /^assets\/([0-9a-f]{2})\/([0-9a-f]{64})\/blob\.([A-Za-z0-9]+)$/i;
+const LIBRARY_SIDECAR_BASENAME = new Set(['meta.json', 'preview.webp']);
+
+export function libraryBlobRelPath(hash: string, ext: string): string {
+ const cleanExt = ext.replace(/^\./, '');
+ return `assets/${hash.slice(0, 2)}/${hash}/blob.${cleanExt}`;
+}
+
+export function isLibrarySidecarRelPath(relPath: string): boolean {
+ const base = relPath.split('/').pop() ?? '';
+ return LIBRARY_SIDECAR_BASENAME.has(base);
+}
+
+export function isLibraryBlobRelPath(relPath: string): boolean {
+ const m = LIBRARY_BLOB_REL_RE.exec(relPath);
+ if (!m) return false;
+ return m[1] === m[2].slice(0, 2);
+}
+
+/**
+ * 插件回执 available 引用:协议形状不动,只改值。
+ * 已授权 + confirmed → library:assets/<2>/<hash>/blob.<ext>;
+ * 未授权维持 cindy-media://;SVG 未授权无备胎(返回 null);
+ * writing/unconfirmed/unavailable 不放开直读。
+ */
+export function libraryAvailableRef(input: {
+ authorized: boolean;
+ hash: string;
+ ext: string;
+ confirmed: boolean;
+}): string | null {
+ if (!input.confirmed) return null;
+ const ext = input.ext.replace(/^\./, '');
+ if (input.authorized) return `library:${libraryBlobRelPath(input.hash, ext)}`;
+ if (ext.toLowerCase() === 'svg') return null;
+ return `cindy-media://blobs/${input.hash}.${ext}`;
+}
+
/** 单插件的库会话(vault + sql 绑定到同一根与 owner scope)。 */
interface GhostLibrarySession {
vault: LibraryVault;
@@ -41,6 +80,10 @@ interface GhostLibrarySession {
locationKind: 'default' | 'custom';
/** 自定义位置漂移(binding-moved/disk-missing):全部操作 unavailable。 */
drift: 'binding-moved' | 'disk-missing' | null;
+ /** bind/unbind 代次;默认根为 0。不含绝对路径。 */
+ generation: number;
+ /** 库身份短码(default / g<generation>),不含绝对路径。 */
+ identity: string;
}
export interface GhostLibrarySlotDeps {
@@ -68,6 +111,11 @@ export interface GhostLibrarySlotDeps {
showSaveDialog?(opts: { defaultPath: string; ghostName: string }): Promise<{ canceled: boolean; filePath?: string }>;
/** 可注入时钟(单测限速);默认 Date.now。 */
now?(): number;
+ /**
+ * 库根 realpath 变化后同步当前 Mivo 会话 extraDirs。
+ * root 为 null 则撤槽。失败只记日志,不挡 library 主路径。
+ */
+ syncAgentReadonlyExtraDir?(ghostId: string, root: string | null): Promise<void>;
}
const fail = (errorCode: string, message: string): GhostPipeLibraryResult => ({ ok: false, errorCode, message });
@@ -82,6 +130,8 @@ export class GhostLibrarySlot {
private readonly lastSaveAsAttemptAt = new Map<string, number>();
/** 全局另存为对话框在场标记(系统弹窗一次一个,不排队)。 */
private saveAsDialogInFlight = false;
+ /** extraDirs 注入成功才握手 authorizedReadonly,失败走 cindy-media 备胎。 */
+ private extraDirGranted = false;
constructor(private readonly deps: GhostLibrarySlotDeps) {}
@@ -151,6 +201,9 @@ export class GhostLibrarySlot {
if (session.vault.getMeta()?.orphaned) {
await session.vault.clearOrphaned().catch(() => {});
}
+ await this.syncAgentReadonlyExtraDir(ghostId, session.vault.getRootDir());
+ } else {
+ await this.syncAgentReadonlyExtraDir(ghostId, null);
}
}
return session;
@@ -206,7 +259,48 @@ export class GhostLibrarySlot {
betterSqliteModulePath: this.deps.betterSqliteModulePath,
log: this.deps.log,
});
- return { vault, sql, ownerScopeKey: scopeKey, locationKind: resolution.kind, drift };
+ const record = 'record' in resolution ? resolution.record : undefined;
+ const generation = record?.generation ?? 0;
+ const identity = record ? `g${generation}` : 'default';
+ return {
+ vault,
+ sql,
+ ownerScopeKey: scopeKey,
+ locationKind: resolution.kind,
+ drift,
+ generation,
+ identity,
+ };
+ }
+
+ /** open/status 握手:已授权只读布尔 + 库代次/身份。谁问谁得,不回绝对路径。 */
+ private handshakeFields(
+ session: GhostLibrarySession,
+ state: 'ready' | 'readonly' | 'unavailable',
+ ): { authorizedReadonly: boolean; libraryGeneration: number; libraryIdentity: string } {
+ return {
+ authorizedReadonly:
+ this.extraDirGranted && session.drift === null && (state === 'ready' || state === 'readonly'),
+ libraryGeneration: session.generation,
+ libraryIdentity: session.identity,
+ };
+ }
+
+ private async syncAgentReadonlyExtraDir(ghostId: string, root: string | null): Promise<void> {
+ if (!this.deps.syncAgentReadonlyExtraDir) {
+ this.extraDirGranted = root !== null;
+ return;
+ }
+ try {
+ await this.deps.syncAgentReadonlyExtraDir(ghostId, root);
+ this.extraDirGranted = root !== null;
+ } catch (error) {
+ this.extraDirGranted = false;
+ this.deps.log?.warn('library extraDirs sync failed', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
}
private async teardownSession(ghostId: string): Promise<void> {
@@ -215,6 +309,7 @@ export class GhostLibrarySlot {
this.sessions.delete(ghostId);
await session.sql.dispose().catch(() => {});
await session.vault.invalidate().catch(() => {});
+ await this.syncAgentReadonlyExtraDir(ghostId, null);
}
/** 停用/卸载/owner 切换收口:作废全部会话(commit 5 的生命周期接线点)。 */
@@ -298,27 +393,33 @@ export class GhostLibrarySlot {
return fail('LIBRARY_UNAVAILABLE', `Library 不可用(${session.drift});请在 Cindy 设置中重新确认存储位置`);
}
if (session.drift !== null) {
- return {
+ const drifted = {
ok: true as const, op: op as 'open' | 'status', state: 'unavailable' as const,
reason: session.drift, usedBytes: 0, fileCount: 0, location: 'custom' as const,
};
+ return { ...drifted, ...this.handshakeFields(session, 'unavailable') } as GhostPipeLibraryResult;
}
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 };
+ const body = {
+ ok: true as const, op: 'open' as const, state: r.state, reason: r.reason ?? undefined,
+ usedBytes: r.usedBytes, fileCount: r.fileCount, location: session.locationKind,
+ };
+ return { ...body, ...this.handshakeFields(session, r.state) } as GhostPipeLibraryResult;
}
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,
+ const body = {
+ ok: true as const, op: 'status' as const, 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,
};
+ return { ...body, ...this.handshakeFields(session, r.state) } as GhostPipeLibraryResult;
}
case 'read': {
const r = await vault.read({ path: req.path, encoding: req.encoding, offset: req.offset, length: req.length });
diff --git a/apps/desktop/src/main/cindy-brain/libraryVault.ts b/apps/desktop/src/main/cindy-brain/libraryVault.ts
index 52d2c0368d..baf8a5cd0c 100644
--- a/apps/desktop/src/main/cindy-brain/libraryVault.ts
+++ b/apps/desktop/src/main/cindy-brain/libraryVault.ts
@@ -99,6 +99,30 @@ interface UsageLedger {
mutations: number;
}
+/**
+ * 读路径身份(bigint dev/ino/size)。与 fileReadBytes.FileIdentityStat 同口径:
+ * 默认 numeric Stats 在 inode > 2^53 时会把不同文件比成相等。
+ * 打开器保持私有,不作为 Agent 工具导出;本类型仅供单测构造 stub。
+ */
+export interface LibraryFileIdentity {
+ dev: bigint;
+ ino: bigint;
+ size: bigint;
+ isFile(): boolean;
+}
+
+/** 读路径句柄子集(可注入)。生产包一层 fs.promises.FileHandle,不导出打开器。 */
+export interface LibraryReadHandle {
+ stat: () => Promise<LibraryFileIdentity>;
+ read: (
+ buffer: Buffer,
+ offset: number,
+ length: number,
+ position: number,
+ ) => Promise<{ bytesRead: number }>;
+ close: () => Promise<void>;
+}
+
export interface LibraryVaultDeps {
/** Library 根(生产 = 默认根或 binding 解析结果;每次现取,支持切换)。 */
rootDir(): string;
@@ -117,6 +141,15 @@ export interface LibraryVaultDeps {
warn: (msg: string, meta?: Record<string, unknown>) => void;
};
now?(): number;
+ /**
+ * 读路径 lstat({bigint:true}) 注入点,仅单测换链 / ino=0。生产勿设。
+ * 打开器保持私有,不作为 Agent 工具导出。
+ */
+ lstatForRead?(absPath: string): Promise<LibraryFileIdentity | null>;
+ /**
+ * 读路径打开注入点,仅单测。生产缺省走 O_RDONLY|O_NOFOLLOW,失败不得回落裸 open。
+ */
+ openForRead?(absPath: string, flags: number): Promise<LibraryReadHandle>;
}
/** Windows 保留设备名(与 fsSlot/dirDeposit 同口径;目录名撞上同样出事)。 */
@@ -223,6 +256,19 @@ function fsFailure(err: unknown, fallback: LibraryErrorCode, message: string): L
const fail = (errorCode: LibraryErrorCode, message: string): LibraryFailure => ({ ok: false, errorCode, message });
+/**
+ * `dev + ino` 是 policy-checked 路径与已打开 fd 之间的稳定身份。ino=0 表示
+ * 平台/文件系统不报告 inode(部分 Windows / 网络盘)——身份不可用,fail-closed,
+ * 禁止 `0n === 0n` 静默过闸。与 fileReadBytes.isSameFileObject 同口径。
+ */
+function isSameLibraryFileObject(expected: LibraryFileIdentity, actual: LibraryFileIdentity): boolean {
+ return expected.ino !== 0n && expected.dev === actual.dev && expected.ino === actual.ino;
+}
+
+function toLibraryFileIdentity(st: { dev: bigint; ino: bigint; size: bigint; isFile(): boolean }): LibraryFileIdentity {
+ return { dev: st.dev, ino: st.ino, size: st.size, isFile: () => st.isFile() };
+}
+
/** 在途分块流。tmp 文件独占创建,Commit 前 title 停在 staging 区。 */
interface ActiveStream {
streamId: string;
@@ -463,7 +509,7 @@ export class LibraryVault {
return { target, realBase };
}
- /** 目标本身不得是 symlink(不穿透);返回 stat 或 null(不存在)。 */
+ /** 目标本身不得是 symlink(不穿透);返回 stat 或 null(不存在)。写路径继续用 numeric。 */
private async lstatTarget(target: string): Promise<fs.Stats | null> {
try {
return await fs.promises.lstat(target);
@@ -472,6 +518,33 @@ export class LibraryVault {
}
}
+ /**
+ * 读路径 bigint lstat(可注入)。生产走 lstat({bigint:true}),不存在返回 null。
+ * 打开器保持私有,不作为 Agent 工具导出。
+ */
+ private async lstatIdentityForRead(target: string): Promise<LibraryFileIdentity | null> {
+ if (this.deps.lstatForRead) return this.deps.lstatForRead(target);
+ try {
+ return toLibraryFileIdentity(await fs.promises.lstat(target, { bigint: true }));
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * 读路径打开:O_RDONLY|O_NOFOLLOW,失败不得回落 `open(path,'r')`。
+ * 生产包一层 FileHandle;单测可注入。打开器不导出。
+ */
+ private async openReadHandle(target: string, flags: number): Promise<LibraryReadHandle> {
+ if (this.deps.openForRead) return this.deps.openForRead(target, flags);
+ const fh = await fs.promises.open(target, flags);
+ return {
+ stat: async () => toLibraryFileIdentity(await fh.stat({ bigint: true })),
+ read: (buffer, offset, length, position) => fh.read(buffer, offset, length, position),
+ close: () => fh.close(),
+ };
+ }
+
/* ── 原子写核心 ─────────────────────────────────────────────────── */
/**
@@ -609,38 +682,46 @@ export class LibraryVault {
}
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 分段读`);
- }
+ // policy-checked 路径的 bigint 身份;打开后再用同 fd fstat 复核。
+ // O_NOFOLLOW 只护最终分量;祖先换链靠 dev/ino(ino=0 fail-closed)。
+ const expected = await this.lstatIdentityForRead(resolved.target);
+ if (!expected) return fail('NOT_FOUND', `文件不存在:${relPath}`);
+ if (!expected.isFile()) return fail('PATH_INVALID', `不是文件:${relPath}`);
+ const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
+ let handle: LibraryReadHandle | null = null;
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();
+ handle = await this.openReadHandle(resolved.target, flags);
+ const opened = await handle.stat();
+ if (!opened.isFile()) return fail('PATH_INVALID', `不是文件:${relPath}`);
+ if (!isSameLibraryFileObject(expected, opened)) {
+ return fail('INTERNAL', '读取身份校验失败(目标 identity 不一致)');
+ }
+ const size = Number(opened.size);
+ const offset = typeof req.offset === 'number' && Number.isInteger(req.offset) && req.offset >= 0 ? req.offset : 0;
+ if (offset > size) return fail('PATH_INVALID', `offset 超出文件大小(${size})`);
+ let length = 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 分段读`);
}
+ const buf = Buffer.alloc(length);
+ const { bytesRead } = length === 0 ? { bytesRead: 0 } : await handle.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'),
+ };
} catch (err) {
return this.tmpFailure(err, '读取失败(主机 IO 错误)');
+ } finally {
+ if (handle) await handle.close().catch(() => {});
}
}
diff --git a/apps/desktop/src/main/maker-host/session-storage.ts b/apps/desktop/src/main/maker-host/session-storage.ts
index a0fb533cec..63fd2a4299 100644
--- a/apps/desktop/src/main/maker-host/session-storage.ts
+++ b/apps/desktop/src/main/maker-host/session-storage.ts
@@ -10,7 +10,7 @@
* 原子写 source='review',自动化 runner 仍会在创建后 backfill 为 'scheduler'。
*/
-import { and, eq, inArray } from 'drizzle-orm';
+import { and, eq, inArray, ne } from 'drizzle-orm';
import { dbToMakerAgentKind, makerToDbAgentKind } from '../../shared/agentKindConversion.js';
@@ -250,3 +250,17 @@ export async function readSessionWritableDirsFromDb(id: string): Promise<string[
}
return [];
}
+
+/** 当前 owner 可见、未删除的桌面会话(含 plugin 入口)。review 不注入 library 槽。 */
+export async function listVisibleActiveSessionIds(): Promise<string[]> {
+ const db = getDbClient().drizzle;
+ const rows = await db
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(and(
+ inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES),
+ eq(sessions.status, 'active'),
+ ne(sessions.source, 'review'),
+ ));
+ return rows.map((row) => row.id);
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.ts
index e0230111cb..a2dfac882f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.ts
@@ -3,7 +3,17 @@ import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
-import { excludeDirectoryGrantConflicts } from '../extraDirsValidator';
+import {
+ excludeDirectoryGrantConflicts,
+ excludeDirectoryGrantConflictsWithSlots,
+ extraDirsForRuntime,
+ EXTRA_DIRS_MAX,
+ LIBRARY_EXTRA_DIR_SLOT_PREFIX,
+ libraryExtraDirSlot,
+ nextLibraryExtraDirs,
+ splitExtraDirSlots,
+ validateExtraDirs,
+} from '../extraDirsValidator';
const cleanupDirs: string[] = [];
@@ -75,4 +85,81 @@ describe('excludeDirectoryGrantConflicts', () => {
excludeDirectoryGrantConflicts([sharedAlias, sibling], [specs]),
).resolves.toEqual([sibling]);
});
+
+ it('writable 候选与 cindy-library 槽指向同一根时互斥', async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-dir-grants-library-slot-'));
+ cleanupDirs.push(root);
+ const library = path.join(root, 'library');
+ const output = path.join(root, 'output');
+ mkdirSync(library);
+ mkdirSync(output);
+ const slot = libraryExtraDirSlot(library);
+ await expect(excludeDirectoryGrantConflictsWithSlots([library, output], [slot])).resolves.toEqual([
+ output,
+ ]);
+ await expect(excludeDirectoryGrantConflictsWithSlots([slot], [library])).resolves.toEqual([]);
+ });
+});
+
+describe('validateExtraDirs library slot', () => {
+ it('满 10 个用户目录时 library 槽仍通过,over-limit 不误伤槽', async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-extra-dirs-max-'));
+ cleanupDirs.push(root);
+ const workdir = path.join(root, 'workdir');
+ mkdirSync(workdir);
+ const users: string[] = [];
+ for (let i = 0; i < EXTRA_DIRS_MAX; i += 1) {
+ const dir = path.join(root, `user-${i}`);
+ mkdirSync(dir);
+ users.push(dir);
+ }
+ const eleventh = path.join(root, 'user-overflow');
+ mkdirSync(eleventh);
+ const libraryRoot = path.join(root, 'library');
+ mkdirSync(libraryRoot);
+ const librarySlot = `${LIBRARY_EXTRA_DIR_SLOT_PREFIX}${libraryRoot}`;
+
+ const overflow = await validateExtraDirs([...users, eleventh], workdir);
+ expect(overflow.valid).toEqual(users);
+ expect(overflow.rejected).toEqual([{ path: eleventh, reason: 'over-limit' }]);
+
+ const withSlot = await validateExtraDirs([...users, librarySlot], workdir);
+ expect(withSlot.valid).toEqual([...users, librarySlot]);
+ expect(withSlot.rejected).toEqual([]);
+ });
+
+ it('library 槽相对路径不当绝对根,越界键拒绝', async () => {
+ const overflow = await validateExtraDirs(
+ [`${LIBRARY_EXTRA_DIR_SLOT_PREFIX}../escape`, `${LIBRARY_EXTRA_DIR_SLOT_PREFIX}relative/root`],
+ '/tmp/workdir',
+ );
+ expect(overflow.valid).toEqual([]);
+ expect(overflow.rejected.map((entry) => entry.reason)).toEqual(['not-absolute', 'not-absolute']);
+ });
+});
+
+describe('nextLibraryExtraDirs', () => {
+ it('注入 library 槽且不挤掉满额用户目录', () => {
+ const users = Array.from({ length: EXTRA_DIRS_MAX }, (_, i) => `/user/${i}`);
+ const next = nextLibraryExtraDirs(users, '/var/libraries/xd-mivo');
+ expect(splitExtraDirSlots(next).user).toEqual(users);
+ expect(next).toContain(libraryExtraDirSlot('/var/libraries/xd-mivo'));
+ expect(extraDirsForRuntime(next)).toEqual([...users, '/var/libraries/xd-mivo']);
+ });
+
+ it('generation 变更时新根替换旧根,用户目录保留', () => {
+ const current = ['/user/a', libraryExtraDirSlot('/old/libraries/xd-mivo'), '/user/b'];
+ const next = nextLibraryExtraDirs(current, '/new/libraries/xd-mivo');
+ expect(next).toEqual([
+ '/user/a',
+ '/user/b',
+ libraryExtraDirSlot('/new/libraries/xd-mivo'),
+ ]);
+ expect(next).not.toContain(libraryExtraDirSlot('/old/libraries/xd-mivo'));
+ });
+
+ it('root 为 null 时撤槽,用户目录原样', () => {
+ const current = ['/user/a', libraryExtraDirSlot('/var/libraries/xd-mivo')];
+ expect(nextLibraryExtraDirs(current, null)).toEqual(['/user/a']);
+ });
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts
index 50b76dedf5..81ec5868d5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts
@@ -121,4 +121,16 @@ describe('remote directory grant atomic update', () => {
});
expect(state.terminate).toHaveBeenCalledOnce();
});
+
+ it('runtime setExtraDirs 抛错则不持久化,避免假授权', async () => {
+ const state = createState(['/old-read']);
+ state.setExtraDirs.mockRejectedValueOnce(new Error('require app-server 0.144.6 or newer'));
+ await expect(state.update('extraDirs', ['/library-root'])).rejects.toThrow(
+ 'require app-server 0.144.6 or newer',
+ );
+ expect(state.runtime.extraDirs).toEqual(['/old-read']);
+ expect(state.db.extraDirs).toEqual(['/old-read']);
+ expect(state.persist).not.toHaveBeenCalled();
+ expect(state.terminate).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/main/maker-ipc/extraDirsValidator.ts b/apps/desktop/src/main/maker-ipc/extraDirsValidator.ts
index 39b24e23c7..85e1ffc2a9 100644
--- a/apps/desktop/src/main/maker-ipc/extraDirsValidator.ts
+++ b/apps/desktop/src/main/maker-ipc/extraDirsValidator.ts
@@ -26,6 +26,55 @@ const log = createLogger('extra-dirs-validator');
export const EXTRA_DIRS_MAX = 10;
+/** 与 register.ts library 槽前缀对齐:不占用户 EXTRA_DIRS_MAX=10。 */
+export const LIBRARY_EXTRA_DIR_SLOT_PREFIX = 'cindy-library:';
+
+export function isLibraryExtraDirSlot(dir: string): boolean {
+ return dir.startsWith(LIBRARY_EXTRA_DIR_SLOT_PREFIX);
+}
+
+export function libraryExtraDirSlot(root: string): string {
+ return `${LIBRARY_EXTRA_DIR_SLOT_PREFIX}${root}`;
+}
+
+export function libraryRootFromSlot(dir: string): string {
+ return isLibraryExtraDirSlot(dir) ? dir.slice(LIBRARY_EXTRA_DIR_SLOT_PREFIX.length) : dir;
+}
+
+export function splitExtraDirSlots(dirs: readonly string[]): { user: string[]; library: string[] } {
+ const user: string[] = [];
+ const library: string[] = [];
+ for (const dir of dirs) {
+ if (isLibraryExtraDirSlot(dir)) library.push(dir);
+ else user.push(dir);
+ }
+ return { user, library };
+}
+
+/** 运行时 extraDirs 去掉 library 槽前缀,只留真实绝对路径。 */
+export function extraDirsForRuntime(dirs: readonly string[]): string[] {
+ return dirs.map((dir) => libraryRootFromSlot(dir));
+}
+
+/** 保留用户自选目录,library 槽最多一条。root 为 null 则撤槽。 */
+export function nextLibraryExtraDirs(current: readonly string[], root: string | null): string[] {
+ const { user } = splitExtraDirSlots(current);
+ return root ? [...user, libraryExtraDirSlot(root)] : user;
+}
+
+/** extraDirs / writableDirs 冲突检测:把 cindy-library: 槽还原成真实根再比。 */
+export async function excludeDirectoryGrantConflictsWithSlots(
+ candidates: readonly string[],
+ blocked: readonly string[],
+): Promise<string[]> {
+ const runtimeAccepted = await excludeDirectoryGrantConflicts(
+ extraDirsForRuntime(candidates),
+ extraDirsForRuntime(blocked),
+ );
+ const accepted = new Set(runtimeAccepted);
+ return candidates.filter((dir) => accepted.has(libraryRootFromSlot(dir)));
+}
+
export interface ValidateResult {
/** 通过校验, 实际可用的绝对路径列表 (去重后, 顺序保留首次出现) */
valid: string[];
@@ -80,17 +129,20 @@ export async function validateExtraDirs(
continue;
}
- if (!path.isAbsolute(dir)) {
+ const librarySlot = isLibraryExtraDirSlot(dir);
+ const root = librarySlot ? dir.slice(LIBRARY_EXTRA_DIR_SLOT_PREFIX.length) : dir;
+
+ if (!path.isAbsolute(root)) {
rejected.push({ path: dir, reason: 'not-absolute' });
continue;
}
// 完全重复 — 第一次出现已 push 到 valid; 后续直接静默丢
- if (seen.has(dir)) continue;
+ if (seen.has(dir) || seen.has(root)) continue;
let stat;
try {
- stat = await fs.stat(dir);
+ stat = await fs.stat(root);
} catch {
rejected.push({ path: dir, reason: 'not-exist' });
continue;
@@ -101,17 +153,19 @@ export async function validateExtraDirs(
}
// workingDir 子目录 / 自身 — 静默去重 (UI 上不报警, 因为加进来无意义)
- if (wd && isSelfOrSubdir(dir, wd)) {
+ if (wd && isSelfOrSubdir(root, wd)) {
rejected.push({ path: dir, reason: 'redundant-subdir' });
continue;
}
- if (valid.length >= EXTRA_DIRS_MAX) {
+ const userCount = valid.filter((entry) => !isLibraryExtraDirSlot(entry)).length;
+ if (!librarySlot && userCount >= EXTRA_DIRS_MAX) {
rejected.push({ path: dir, reason: 'over-limit' });
continue;
}
seen.add(dir);
+ seen.add(root);
valid.push(dir);
}
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index e803218231..51d42b3761 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -28,7 +28,11 @@ import {
buildMobileClientPromptNote,
shouldPrependMobileClientPromptNote,
} from './mobileClientPromptNote.js';
-import { excludeDirectoryGrantConflicts, validateExtraDirs } from './extraDirsValidator.js';
+import {
+ excludeDirectoryGrantConflicts,
+ extraDirsForRuntime,
+ validateExtraDirs,
+} from './extraDirsValidator.js';
import type { MakerSessionCreateOpts } from './sessionRequest.js';
type CreateOpts = MakerSessionCreateOpts;
@@ -551,7 +555,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
if (opts.extraDirs === undefined) {
try {
const row = await deps.readSessionExtraDirsFromDb(sessionId);
- if (row.length > 0) opts.extraDirs = row;
+ if (row.length > 0) {
+ opts.extraDirs = extraDirsForRuntime(row);
+ }
} catch (err) {
deps.log.warn(`${source}: read extra_dirs from DB failed (non-fatal)`, {
sessionId,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 7b2491c521..09237ab0d2 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -437,6 +437,7 @@ import {
readSessionExtraDirsFromDb,
readSessionWritableDirsFromDb,
readSessionWorkingDirFromDb,
+ listVisibleActiveSessionIds,
} from '../maker-host/session-storage.js';
import {
backgroundTurnPredatesSessionClear,
@@ -628,7 +629,15 @@ import { runAcceptedCallback } from './acceptedCallbackRunner.js';
import { createElectronIpcHandlerRegistry } from './electronIpcRegistry.js';
import { refreshCodexMcpEnvironment } from './codexMcpRefresh.js';
import { broadcastSchedulerChanged } from './schedule.js';
-import { excludeDirectoryGrantConflicts, validateExtraDirs } from './extraDirsValidator.js';
+import {
+ excludeDirectoryGrantConflictsWithSlots,
+ extraDirsForRuntime,
+ isLibraryExtraDirSlot,
+ libraryExtraDirSlot,
+ libraryRootFromSlot,
+ splitExtraDirSlots,
+ validateExtraDirs,
+} from './extraDirsValidator.js';
import {
applyRemoteDirectoryGrantUpdate,
isPersistedDirectoryGrantSubset,
@@ -1065,6 +1074,8 @@ import {
setGhostSessionRevealer,
setGhostErrandRunner,
setGhostWorkspaceSessionService,
+ setGhostLibraryExtraDirSync,
+ getFocusedGhostSessionId,
notifyGhostSessionEvent,
getInstalledGhostName,
} from '../cindy-brain/index.js';
@@ -2857,6 +2868,234 @@ export async function withSendToSessionLock<T>(
}
}
+export interface ApplyDirectoryGrantsOptions {
+ remote: boolean;
+ senderId?: number;
+ /** extraDirs: requested 只含 library 槽(可空=撤槽),用户目录在锁内从 DB 现读。 */
+ replaceLibrarySlot?: boolean;
+}
+
+/**
+ * extraDirs / writableDirs 授权内部入口。IPC 与 library 静默注入共用。
+ * extraDirs 轴不走 picker;writableDirs 仍消费 picker grant。
+ */
+export function applyDirectoryGrants(
+ axis: 'extraDirs' | 'writableDirs',
+ sessionId: string,
+ requestedDirs: string[],
+ options: ApplyDirectoryGrantsOptions,
+): Promise<string[] | void> {
+ return withSendToSessionLock(sessionId, async () => {
+ const [sourceRow] = await getDbClient()
+ .drizzle.select({ source: sessions.source })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (sourceRow?.source === 'review') {
+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Review task settings are fixed to the source task');
+ }
+ const maker = getMaker();
+ const sess = maker.getSession(sessionId);
+ const supported = axis === 'extraDirs'
+ ? sess?.capabilities.extraDirs.supported
+ : sess?.capabilities.writableDirs?.supported;
+ const label = axis === 'extraDirs' ? 'set-extra-dirs' : 'set-writable-dirs';
+ if (sess && !supported) {
+ log.debug(`${label}: agent capability=false, no-op`, {
+ sessionId,
+ agentKind: sess.agentKind,
+ });
+ return;
+ }
+ const persistOnly = !sess;
+ const workDir = persistOnly
+ ? (await readSessionWorkingDirFromDb(sessionId) ?? undefined)
+ : (sess.workDir || undefined);
+ let dirsToApply = requestedDirs;
+ if (axis === 'extraDirs') {
+ const persisted = await readSessionExtraDirsFromDb(sessionId);
+ const { user: dbUser, library: dbLibrary } = splitExtraDirSlots(persisted);
+ if (options.replaceLibrarySlot) {
+ const { library } = splitExtraDirSlots(requestedDirs);
+ dirsToApply = [...dbUser, ...library];
+ } else {
+ const { user } = splitExtraDirSlots(requestedDirs);
+ dirsToApply = [...user, ...dbLibrary];
+ }
+ }
+ const result = await applyRemoteDirectoryGrantUpdate(axis, dirsToApply, {
+ setExtraDirs: persistOnly
+ ? async () => {}
+ : (dirs) => sess.setExtraDirs(extraDirsForRuntime(dirs)),
+ setWritableDirs: persistOnly
+ ? async () => {}
+ : (dirs) => sess.setWritableDirs(dirs),
+ }, {
+ validate: async (requested) => {
+ if (axis !== 'extraDirs') {
+ return validateExtraDirs(requested, workDir);
+ }
+ const { user, library } = splitExtraDirSlots(requested);
+ const userResult = await validateExtraDirs(user, workDir);
+ const libraryValid: string[] = [];
+ const libraryRejected: Array<{ path: string; reason: string }> = [];
+ for (const slot of library) {
+ const root = libraryRootFromSlot(slot);
+ const checked = await validateExtraDirs([root], workDir);
+ if (checked.valid.length === 1) libraryValid.push(libraryExtraDirSlot(checked.valid[0]));
+ else libraryRejected.push(...checked.rejected);
+ }
+ return {
+ valid: [...userResult.valid, ...libraryValid],
+ rejected: [...userResult.rejected, ...libraryRejected],
+ };
+ },
+ readExtraDirs: () => readSessionExtraDirsFromDb(sessionId),
+ readWritableDirs: () => readSessionWritableDirsFromDb(sessionId),
+ excludeConflicts: async (candidates, blocked) => {
+ const accepted = await excludeDirectoryGrantConflictsWithSlots(candidates, blocked);
+ if (axis === 'writableDirs') {
+ const previousDirs = await readSessionWritableDirsFromDb(sessionId);
+ const [route] = await getDbClient()
+ .drizzle.select({ remoteHostId: sessions.remoteHostId })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (options.remote || route?.remoteHostId) {
+ // The picker lives on the controller filesystem, so device-link and SSH may only
+ // retain/revoke roots that were already persisted on the execution side.
+ if (!isPersistedDirectoryGrantSubset(accepted, previousDirs)) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'remote writable directories can only retain or revoke existing grants',
+ );
+ }
+ return accepted;
+ } else {
+ if (options.senderId === undefined) {
+ throwIpcError('PRECONDITION_FAILED', 'Writable directory picker owner unavailable');
+ }
+ try {
+ await consumeWritableDirectoryPickerGrants({
+ scopeId: sessionId,
+ senderId: options.senderId,
+ requestedDirs: accepted,
+ previousDirs,
+ });
+ } catch (error) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ error instanceof Error
+ ? error.message
+ : 'Writable directory authorization failed',
+ );
+ }
+ }
+ }
+ return accepted;
+ },
+ persist: (patch) => persistSessionFields(sessionId, patch),
+ terminate: () => maker.closeSession(sessionId),
+ });
+ log.info(label, {
+ sessionId,
+ requested: requestedDirs.length,
+ kept: result.dirs.length,
+ rejected: result.rejectedCount,
+ });
+ if (options.remote) markRemoteSettingPersistedInsideHandler(result.dirs);
+ return result.dirs;
+ });
+}
+
+/**
+ * Mivo 会话 library ready 时静默写入只读 extraDirs(专用槽,不弹 picker)。
+ * root 为 null 则撤该会话 library 槽,用户自选目录保留。
+ */
+export async function applyLibraryReadonlyExtraDir(
+ sessionId: string,
+ root: string | null,
+): Promise<string[] | void> {
+ let canonical: string | null = null;
+ if (root) {
+ try {
+ canonical = await fsp.realpath(root);
+ } catch {
+ canonical = null;
+ }
+ }
+ return applyDirectoryGrants(
+ 'extraDirs',
+ sessionId,
+ canonical ? [libraryExtraDirSlot(canonical)] : [],
+ { remote: false, replaceLibrarySlot: true },
+ );
+}
+
+async function sessionIsRemote(sessionId: string): Promise<boolean> {
+ const [row] = await getDbClient()
+ .drizzle.select({ remoteHostId: sessions.remoteHostId })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ return Boolean(row?.remoteHostId);
+}
+
+let libraryExtraDirSyncGeneration = 0;
+let libraryExtraDirSyncRoot: string | null = null;
+let libraryExtraDirSyncChain: Promise<void> = Promise.resolve();
+
+async function syncLibraryReadonlyExtraDir(root: string | null): Promise<void> {
+ libraryExtraDirSyncRoot = root;
+ const generation = ++libraryExtraDirSyncGeneration;
+ const run = async () => {
+ if (generation !== libraryExtraDirSyncGeneration) {
+ throw new Error('library extraDirs sync superseded');
+ }
+ const grantRoot = libraryExtraDirSyncRoot;
+ const focused = getFocusedGhostSessionId();
+ if (generation !== libraryExtraDirSyncGeneration) {
+ throw new Error('library extraDirs sync superseded');
+ }
+ const visible = await listVisibleActiveSessionIds();
+ if (generation !== libraryExtraDirSyncGeneration) {
+ throw new Error('library extraDirs sync superseded');
+ }
+ const targets = new Set(visible);
+ if (focused) targets.add(focused);
+ let granted = false;
+ for (const sessionId of targets) {
+ if (generation !== libraryExtraDirSyncGeneration) {
+ throw new Error('library extraDirs sync superseded');
+ }
+ const remote = await sessionIsRemote(sessionId);
+ if (generation !== libraryExtraDirSyncGeneration) {
+ throw new Error('library extraDirs sync superseded');
+ }
+ const nextRoot = !remote && grantRoot && sessionId === focused ? grantRoot : null;
+ try {
+ await applyLibraryReadonlyExtraDir(sessionId, nextRoot);
+ if (nextRoot) granted = true;
+ } catch (error) {
+ log.warn('library extraDirs session sync failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ if (!remote && nextRoot && sessionId === focused) throw error;
+ }
+ if (generation !== libraryExtraDirSyncGeneration) {
+ throw new Error('library extraDirs sync superseded');
+ }
+ }
+ if (grantRoot && !granted) {
+ throw new Error('library extraDirs not granted to focused session');
+ }
+ };
+ const queued = libraryExtraDirSyncChain.then(run, run);
+ libraryExtraDirSyncChain = queued.then(() => undefined, () => undefined);
+ await queued;
+}
+
let agentInputCoordinatorHolder: AgentInputCoordinator | null = null;
let contextOverflowRolloverHolder: ReturnType<typeof createContextOverflowRollover> | null = null;
const overflowSuppressedBroadcasts = new Map<
@@ -7945,7 +8184,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
orcaWorkerId: target.id,
orcaWorkerSessionId: target.sessionId,
};
- const extraDirs = await readSessionExtraDirsFromDb(target.sessionId);
+ const extraDirs = extraDirsForRuntime(await readSessionExtraDirsFromDb(target.sessionId));
const writableDirs = await readSessionWritableDirsFromDb(target.sessionId);
const opts = buildCreateOptsWithStderr({
id: row.id,
@@ -9139,7 +9378,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (co.extraDirs === undefined) {
try {
const extraDirs = await readSessionExtraDirsFromDb(sessionId);
- if (extraDirs.length > 0) co.extraDirs = extraDirs;
+ if (extraDirs.length > 0) co.extraDirs = extraDirsForRuntime(extraDirs);
} catch (err) {
log.warn('agent-switch bootstrap: read extra_dirs from DB failed (non-fatal)', {
sessionId,
@@ -9959,7 +10198,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (createOpts.extraDirs === undefined) {
try {
const row = await readSessionExtraDirsFromDb(targetSessionId);
- if (row.length > 0) createOpts.extraDirs = row;
+ if (row.length > 0) createOpts.extraDirs = extraDirsForRuntime(row);
} catch (err) {
log.warn('sendToSession: read extra_dirs from DB failed (non-fatal)', {
targetSessionId,
@@ -10236,6 +10475,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 同一条 `local-db:sessions:created` 通道让侧边栏刷新;focus 复用 deep link
// 的会话聚焦通道。注入方式与 setGhostAgentTurnRunner 同款倒置,避免
// cindy-brain 反向依赖 maker-ipc / localDb 形成模块环。
+ setGhostLibraryExtraDirSync(syncLibraryReadonlyExtraDir);
setGhostWorkspaceSessionService({
findActiveSessionByWorkdir,
createDraftSession: async (params) => {
@@ -10321,7 +10561,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (createOpts.extraDirs === undefined) {
try {
const extraDirs = await readSessionExtraDirsFromDb(sessionId);
- if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
+ if (extraDirs.length > 0) createOpts.extraDirs = extraDirsForRuntime(extraDirs);
} catch (err) {
log.warn('inter-agent queue: read extra_dirs from DB failed (non-fatal)', {
sessionId,
@@ -12548,7 +12788,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (createOpts.extraDirs === undefined) {
try {
const extraDirs = await readSessionExtraDirsFromDb(sessionId);
- if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
+ if (extraDirs.length > 0) createOpts.extraDirs = extraDirsForRuntime(extraDirs);
} catch (err) {
log.warn('overflow replay: read extra_dirs from DB failed (non-fatal)', {
sessionId,
@@ -12826,7 +13066,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (co.extraDirs === undefined) {
try {
const row = await readSessionExtraDirsFromDb(sessionId);
- if (row.length > 0) co.extraDirs = row;
+ if (row.length > 0) co.extraDirs = extraDirsForRuntime(row);
} catch (err) {
log.warn('context-usage lazy-create: read extra_dirs from DB failed (non-fatal)', {
sessionId,
@@ -17036,7 +17276,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!workDirReady) return null;
await synthesizeOrcaVendorOptionsFromDb(sessionId, createOpts);
const extraDirs = await readSessionExtraDirsFromDb(sessionId).catch(() => []);
- if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
+ if (extraDirs.length > 0) createOpts.extraDirs = extraDirsForRuntime(extraDirs);
const writableDirs = await readSessionWritableDirsFromDb(sessionId).catch(() => []);
if (writableDirs.length > 0) createOpts.writableDirs = writableDirs;
await ensureRemoteReadyForSessionStart({ createOpts });
@@ -17304,86 +17544,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
);
- const applyDirectoryGrants = (
- axis: 'extraDirs' | 'writableDirs',
- sessionId: string,
- requestedDirs: string[],
- options: { remote: boolean; senderId?: number },
- ) =>
- withSendToSessionLock(sessionId, async () => {
- await assertReviewSettingsUnlocked(sessionId);
- const sess = maker.getSession(sessionId);
- const supported =
- axis === 'extraDirs'
- ? sess?.capabilities.extraDirs.supported
- : sess?.capabilities.writableDirs?.supported;
- const label = axis === 'extraDirs' ? 'set-extra-dirs' : 'set-writable-dirs';
- if (!sess || !supported) {
- log.debug(`${label}: ${sess ? 'agent capability=false' : 'session not found'}, no-op`, {
- sessionId,
- ...(sess ? { agentKind: sess.agentKind } : {}),
- });
- return;
- }
- const result = await applyRemoteDirectoryGrantUpdate(axis, requestedDirs, sess, {
- validate: (requested) => validateExtraDirs(requested, sess.workDir || undefined),
- readExtraDirs: () => readSessionExtraDirsFromDb(sessionId),
- readWritableDirs: () => readSessionWritableDirsFromDb(sessionId),
- excludeConflicts: async (candidates, blocked) => {
- const accepted = await excludeDirectoryGrantConflicts(candidates, blocked);
- if (axis === 'writableDirs') {
- const previousDirs = await readSessionWritableDirsFromDb(sessionId);
- const [route] = await getDbClient()
- .drizzle.select({ remoteHostId: sessions.remoteHostId })
- .from(sessions)
- .where(eq(sessions.id, sessionId))
- .limit(1);
- if (options.remote || route?.remoteHostId) {
- // The picker lives on the controller filesystem, so device-link and SSH may only
- // retain/revoke roots that were already persisted on the execution side.
- if (!isPersistedDirectoryGrantSubset(accepted, previousDirs)) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'remote writable directories can only retain or revoke existing grants',
- );
- }
- return accepted;
- } else {
- if (options.senderId === undefined) {
- throwIpcError('PRECONDITION_FAILED', 'Writable directory picker owner unavailable');
- }
- try {
- await consumeWritableDirectoryPickerGrants({
- scopeId: sessionId,
- senderId: options.senderId,
- requestedDirs: accepted,
- previousDirs,
- });
- } catch (error) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- error instanceof Error
- ? error.message
- : 'Writable directory authorization failed',
- );
- }
- }
- }
- return accepted;
- },
- persist: (patch) => persistSessionFields(sessionId, patch),
- terminate: () => maker.closeSession(sessionId),
- });
- log.info(label, {
- sessionId,
- requested: requestedDirs.length,
- kept: result.dirs.length,
- rejected: result.rejectedCount,
- });
- if (options.remote) markRemoteSettingPersistedInsideHandler(result.dirs);
- return result.dirs;
- });
-
// 两类目录授权均在同一 session 锁内完成校验、运行时应用与持久化。
// session 不在 / capability 不支持都 no-op, 不抛错 — 跟 setModel 容错语义一致。
ipcMain.handle(MAKER_INVOKE.SET_EXTRA_DIRS, async (event, sessionId: unknown, dirs: unknown) => {
@@ -17395,7 +17555,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');
if (!Array.isArray(dirs)) throwIpcError('INVALID_PARAMS', 'dirs must be string[]');
- return applyDirectoryGrants('extraDirs', sessionId, dirs as string[], {
+ const requested = (dirs as string[]).filter((dir) => typeof dir === 'string' && !isLibraryExtraDirSlot(dir));
+ return applyDirectoryGrants('extraDirs', sessionId, requested, {
remote: deviceLinkInvoke,
...(!deviceLinkInvoke ? { senderId: event.sender.id } : {}),
});
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index c1fa1fda28..2fe2fe79d4 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -1396,9 +1396,11 @@ describe('远程交互接线不变式', () => {
expect(body).not.toContain('persist:');
const main = mainSrc('maker-ipc/register.ts');
- const transactionStart = main.indexOf('const applyDirectoryGrants = (');
+ const transactionStart = main.indexOf('export function applyDirectoryGrants(');
expect(transactionStart).toBeGreaterThan(-1);
- const transaction = main.slice(transactionStart, transactionStart + 4_000);
+ const transactionEnd = main.indexOf('export async function applyLibraryReadonlyExtraDir(', transactionStart);
+ expect(transactionEnd).toBeGreaterThan(transactionStart);
+ const transaction = main.slice(transactionStart, transactionEnd);
expect(transaction).toContain('withSendToSessionLock(sessionId');
expect(transaction).toContain('persist: (patch) => persistSessionFields(sessionId, patch)');
});
diff --git a/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts b/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts
index adb295620a..c0a695b44d 100644
--- a/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts
+++ b/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts
@@ -2,6 +2,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
__extraDirsPathOverlapForTesting,
+ countUserExtraDirs,
+ extraDirDisplayLabel,
+ LIBRARY_EXTRA_DIR_SLOT_PREFIX,
+ MAX_EXTRA_DIRS,
+ partitionExtraDirs,
pickAndAddExtraDir,
} from '../components/new-chat/extraDirsActions';
@@ -85,4 +90,62 @@ describe('pickAndAddExtraDir', () => {
expect(confirm).not.toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalled();
});
+
+ it('library 槽不占用户 EXTRA_DIRS_MAX,显示为系统项', async () => {
+ const library = `${LIBRARY_EXTRA_DIR_SLOT_PREFIX}/tmp/mivo-library`;
+ const userDirs = Array.from({ length: MAX_EXTRA_DIRS }, (_, i) => `/tmp/user-${i}`);
+ expect(countUserExtraDirs([...userDirs, library])).toBe(MAX_EXTRA_DIRS);
+ expect(partitionExtraDirs([...userDirs, library])).toEqual({
+ system: [library],
+ user: userDirs,
+ });
+ expect(extraDirDisplayLabel(library)).toBe('Mivo 作品库(只读)');
+
+ vi.stubGlobal('window', {
+ electronAPI: {
+ dialog: {
+ showOpenDirectory: vi.fn(async () => ({ success: true, path: '/tmp/another' })),
+ },
+ },
+ });
+ const onChange = vi.fn();
+ await pickAndAddExtraDir({
+ extraDirs: [...userDirs, library],
+ workingDir: '/workspace',
+ onChange,
+ confirm: vi.fn(async () => true),
+ parentDirectoryConfirm: {
+ title: 'title',
+ description: (path) => path,
+ confirmText: 'confirm',
+ cancelText: 'cancel',
+ },
+ });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
+
+describe('composer extraDirs UI 接线 library 槽', () => {
+ it('ChatInput 配额与计数走 countUserExtraDirs,不把 extraDirs.length 当用户名额', async () => {
+ const { readFileSync } = await import('node:fs');
+ const { dirname, join } = await import('node:path');
+ const { fileURLToPath } = await import('node:url');
+ const here = dirname(fileURLToPath(import.meta.url));
+ const source = readFileSync(join(here, '../components/new-chat/ChatInput.tsx'), 'utf8');
+ expect(source).toMatch(/countUserExtraDirs\(currentExtraDirs\) \+ countUserExtraDirs\(currentWritableDirs\)/);
+ expect(source).toMatch(/countUserExtraDirs\(extraDirs \?\? \[\]\) \+ countUserExtraDirs\(writableDirs \?\? \[\]\)/);
+ expect(source).not.toMatch(/currentExtraDirs\.length \+ currentWritableDirs\.length/);
+ expect(source).not.toMatch(/extraDirsCount=\{\(extraDirs \?\? \[\]\)\.length \+ \(writableDirs \?\? \[\]\)\.length\}/);
+ });
+
+ it('AtMentionPanel 把 library 槽显示为系统项且不提供移除按钮', async () => {
+ const { readFileSync } = await import('node:fs');
+ const { dirname, join } = await import('node:path');
+ const { fileURLToPath } = await import('node:url');
+ const here = dirname(fileURLToPath(import.meta.url));
+ const source = readFileSync(join(here, '../components/new-chat/AtMentionPanel.tsx'), 'utf8');
+ expect(source).toContain('extraDirDisplayLabel');
+ expect(source).toContain('isLibraryExtraDirSlot');
+ expect(source).toMatch(/isLibraryExtraDirSlot\(p\) \? null/);
+ });
});
diff --git a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx
index 126cd79505..db9c4e2d11 100644
--- a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx
@@ -51,7 +51,7 @@ import {
type ComposerSuggestionAction,
type ComposerSuggestionEntry,
} from '@/lib/composerSuggestion';
-import { extraDirBasename } from './extraDirsActions';
+import { extraDirBasename, extraDirDisplayLabel, isLibraryExtraDirSlot } from './extraDirsActions';
const TOOLTIP_FALLBACK_H = 120;
const VIEWPORT_PAD = 8;
@@ -556,26 +556,32 @@ export function AtMentionPanel({
size={16}
className="shrink-0 text-[var(--cmd-palette-item-icon)] opacity-60"
/>
- <Tip text={p} mono side="top">
+ <Tip
+ text={isLibraryExtraDirSlot(p) ? extraDirDisplayLabel(p) : p}
+ mono={!isLibraryExtraDirSlot(p)}
+ side="top"
+ >
<span className="min-w-0 flex-1 truncate text-left text-14 text-[var(--cmd-palette-item-text)]">
- {extraDirBasename(p)}
+ {extraDirDisplayLabel(p)}
</span>
</Tip>
- <button
- type="button"
- onMouseDown={(e) => e.preventDefault()}
- onClick={() => referenceDirs.onRemove(p)}
- className={cn(
- 'rounded-full p-1 opacity-0 transition-opacity',
- 'hover:bg-[var(--cmd-palette-item-hover)]',
- 'group-hover:opacity-70 hover:!opacity-100',
- 'focus-visible:opacity-100 focus-visible:outline-none',
- 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- )}
- aria-label={t('extraDirs.remove', { name: extraDirBasename(p) })}
- >
- <X size={12} className="text-[var(--cmd-palette-item-text)]" />
- </button>
+ {isLibraryExtraDirSlot(p) ? null : (
+ <button
+ type="button"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => referenceDirs.onRemove(p)}
+ className={cn(
+ 'rounded-full p-1 opacity-0 transition-opacity',
+ 'hover:bg-[var(--cmd-palette-item-hover)]',
+ 'group-hover:opacity-70 hover:!opacity-100',
+ 'focus-visible:opacity-100 focus-visible:outline-none',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ aria-label={t('extraDirs.remove', { name: extraDirBasename(p) })}
+ >
+ <X size={12} className="text-[var(--cmd-palette-item-text)]" />
+ </button>
+ )}
</div>
))}
</div>
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 50a580c2c0..6606643f90 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -261,7 +261,7 @@ import {
type ComposerSuggestionAction,
type ComposerSuggestionEntry,
} from '@/lib/composerSuggestion';
-import { MAX_EXTRA_DIRS, pickAndAddExtraDir } from './extraDirsActions';
+import { countUserExtraDirs, MAX_EXTRA_DIRS, pickAndAddExtraDir } from './extraDirsActions';
import { applyListBackspace, applyListContinuation } from '@/lib/composerListContinuation';
import type { Effort, PermissionMode } from '@/lib/userPreferences.types';
import { getAppShortcutCombos } from '@/lib/appShortcutStore';
@@ -4362,7 +4362,7 @@ export function ChatInput({
if (onExtraDirsChange) {
const currentExtraDirs = extraDirs ?? [];
const currentWritableDirs = writableDirs ?? [];
- const totalDirs = currentExtraDirs.length + currentWritableDirs.length;
+ const totalDirs = countUserExtraDirs(currentExtraDirs) + countUserExtraDirs(currentWritableDirs);
actions.push({
id: 'add-extra-dir',
label:
@@ -4398,7 +4398,7 @@ export function ChatInput({
) {
const currentExtraDirs = extraDirs ?? [];
const currentWritableDirs = writableDirs ?? [];
- const totalDirs = currentExtraDirs.length + currentWritableDirs.length;
+ const totalDirs = countUserExtraDirs(currentExtraDirs) + countUserExtraDirs(currentWritableDirs);
actions.push({
id: 'add-writable-dir',
label:
@@ -8423,7 +8423,7 @@ export function ChatInput({
)}
{/* 「+」只负责合成打开统一建议面板;内容与输入 @ 完全共用。 */}
<ExtraDirsButton
- extraDirsCount={(extraDirs ?? []).length + (writableDirs ?? []).length}
+ extraDirsCount={countUserExtraDirs(extraDirs ?? []) + countUserExtraDirs(writableDirs ?? [])}
hasReferenceDirs={!settingsLocked && (onExtraDirsChange !== undefined || onWritableDirsChange !== undefined)}
open={syntheticAtOpen}
onOpenChange={handleComposerSuggestionOpenChange}
diff --git a/apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts b/apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts
index 28f890d66d..4bd82f960d 100644
--- a/apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts
+++ b/apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts
@@ -15,6 +15,34 @@ const log = createLogger('ExtraDirsActions');
/** 与 main 端 EXTRA_DIRS_MAX 保持一致;UI 满了 disable 添加入口。 */
export const MAX_EXTRA_DIRS = 10;
+/** 与 main library 槽前缀对齐:系统项不占用户 10 名额。 */
+export const LIBRARY_EXTRA_DIR_SLOT_PREFIX = 'cindy-library:';
+
+export function isLibraryExtraDirSlot(dir: string): boolean {
+ return dir.startsWith(LIBRARY_EXTRA_DIR_SLOT_PREFIX);
+}
+
+export function extraDirDisplayLabel(dir: string): string {
+ return isLibraryExtraDirSlot(dir) ? 'Mivo 作品库(只读)' : extraDirBasename(dir);
+}
+
+export function partitionExtraDirs(dirs: readonly string[]): {
+ system: string[];
+ user: string[];
+} {
+ const system: string[] = [];
+ const user: string[] = [];
+ for (const dir of dirs) {
+ if (isLibraryExtraDirSlot(dir)) system.push(dir);
+ else user.push(dir);
+ }
+ return { system, user };
+}
+
+export function countUserExtraDirs(dirs: readonly string[]): number {
+ return dirs.filter((dir) => !isLibraryExtraDirSlot(dir)).length;
+}
+
function normalizedPathForComparison(raw: string | null | undefined): string | null {
const normalized = normalizeWorkingDirForStorage(raw);
return normalized ? stripTrailingPathSeparators(normalized) : null;
@@ -99,7 +127,7 @@ export async function pickAndAddExtraDir({
confirm,
parentDirectoryConfirm,
}: PickAndAddExtraDirOptions): Promise<void> {
- if (extraDirs.length + otherDirs.length >= MAX_EXTRA_DIRS) return;
+ if (countUserExtraDirs(extraDirs) + countUserExtraDirs(otherDirs) >= MAX_EXTRA_DIRS) return;
let picked: string | null = null;
try {
const r = await window.electronAPI.dialog.showOpenDirectory(
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 1b09a8abd9..0131e0da17 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -8308,6 +8308,9 @@ export type GhostPipeLibraryResult =
softLimitBytes?: number;
softLimitExceeded?: boolean;
location?: 'default' | 'custom';
+ authorizedReadonly?: boolean;
+ libraryGeneration?: number;
+ libraryIdentity?: string;
}
| {
ok: true;
diff --git a/docs/design-previews/library-extradirs-quota/extract-helpers.mjs b/docs/design-previews/library-extradirs-quota/extract-helpers.mjs
new file mode 100644
index 0000000000..a85ef4e9cf
--- /dev/null
+++ b/docs/design-previews/library-extradirs-quota/extract-helpers.mjs
@@ -0,0 +1,666 @@
+// extract-helpers.mjs — extract.mjs 作者的共享工具函数。
+//
+// 诞生背景(2026-07-29 login-all-hifi 事故):每个 demo 的 extract.mjs 手写 repoRoot
+// 定位(`../../..` 数目录层级),demo 从 _tmp/ 迁到 docs/design-previews/ 后路径全断,
+// 一天连修 3 个 bug(repoRoot 深度、provenance 前缀、truth 相对路径)。本库把这些
+// 「每个 demo 都要做且都做错过」的事收敛为一次实现:
+// - findRepoRoot():git 定位仓库根,与目录深度彻底解耦——demo 随便搬家;
+// - makeLeaf():provenance 工厂,source 相对路径 / hash / locatorPattern 一次做对;
+// - importTsModule():esbuild 临时编译 TS 纯函数后 import(门 F oracle 用产品公式本身);
+// - extractThemeVars():主题桥——从产品 themes/colors.ts 的 registerColor 全表提取
+// light/dark 双态色值,每个值都是带 provenance 的 truth 叶子(组件模式 adapter 复刻
+// 主题变量时用它,而不是手抄一份色表——手抄两边同错就是假绿)。
+//
+// 使用方式:init.mjs 会把本文件拷贝进 demo 目录(extract-helpers.mjs),extract.mjs
+// `import { findRepoRoot, makeLeaf } from './extract-helpers.mjs'`——demo 自包含,
+// 随 PR 入产品仓后不依赖 skill 安装位置。
+
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
+import { createRequire, isBuiltin } from 'node:module';
+import { pathToFileURL } from 'node:url';
+
+/**
+ * 定位产品仓库根。优先 `git rev-parse --show-toplevel`(worktree/submodule 都正确),
+ * 降级为向上找 .git。**禁止**用 `../../..` 数目录层级——那是 2026-07-29 三连 bug 的根因。
+ */
+export function findRepoRoot(startDir = process.cwd()) {
+ try {
+ const out = execFileSync('git', ['-C', startDir, 'rev-parse', '--show-toplevel'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+ if (out) return out;
+ } catch {}
+ let cur = resolve(startDir);
+ while (true) {
+ if (existsSync(join(cur, '.git'))) return cur;
+ const next = dirname(cur);
+ if (next === cur) break;
+ cur = next;
+ }
+ throw new Error(`findRepoRoot: 从 ${startDir} 向上找不到 git 仓库根——extract 必须在产品仓内运行,或显式传 startDir`);
+}
+
+export function sha256File(file) {
+ return createHash('sha256').update(readFileSync(file)).digest('hex');
+}
+
+export function readJson(file) {
+ return JSON.parse(readFileSync(file, 'utf8'));
+}
+
+/**
+ * truth 叶子工厂:{ value, provenance: { source, locator, hash[, locatorPattern] } }。
+ * source 自动写成「相对 demo 目录」的路径(truth.mjs 以 cwd=demoDir 跑 extract,
+ * 校验器 validateProvenance 也按 demoDir 解析)——搬家后重跑 extract 即自动修正,
+ * 不再出现「provenance 前缀硬编码旧目录深度」(obs 16371)。
+ *
+ * @param value 提取到的值(界面文案/几何/色值等)
+ * @param sourceFile 源文件绝对路径(或相对 demoDir 的路径)
+ * @param opts.locator 必填:一句话说明该值在源文件中的定位方式(人读)
+ * @param opts.locatorPattern 可选:恰含一个捕获组的正则(writeback 机械写回的锚,regex 模式)
+ * @param opts.keyPath 可选:源文件中该值的完整对象路径(writeback 机械写回的锚,AST 模式;
+ * 从顶层变量名/export default/JSON 根起,如 'loginDesignTokens.hero.size';记进
+ * provenance.locatorKeyPath,由 writeback 用产品仓 typescript 在 AST 上定位)
+ * @param opts.demoDir 默认 process.cwd()(truth.mjs 保证 = demo 目录)
+ */
+export function makeLeaf(value, sourceFile, { locator, locatorPattern, keyPath, demoDir = process.cwd() } = {}) {
+ if (!locator || typeof locator !== 'string') {
+ throw new Error(`makeLeaf(${JSON.stringify(value)}): 必须写 locator——一句话说明该值在源文件里怎么定位`);
+ }
+ const abs = isAbsolute(sourceFile) ? sourceFile : resolve(demoDir, sourceFile);
+ if (!existsSync(abs)) throw new Error(`makeLeaf: 源文件不存在:${abs}`);
+ if (locatorPattern !== undefined) {
+ let groups;
+ try {
+ groups = new RegExp(`${locatorPattern}|`).exec('').length - 1;
+ } catch (err) {
+ throw new Error(`makeLeaf: locatorPattern 不是合法正则:${err.message}`);
+ }
+ if (groups !== 1) throw new Error(`makeLeaf: locatorPattern 必须恰含一个捕获组(当前 ${groups} 个):${locatorPattern}`);
+ }
+ if (keyPath !== undefined) {
+ if (typeof keyPath !== 'string' || !keyPath.trim() || keyPath.split('.').some((s) => !s || /\s/.test(s))) {
+ throw new Error(`makeLeaf: keyPath 必须是「段.段.段」非空路径(段不含空白):${JSON.stringify(keyPath)}`);
+ }
+ }
+ const provenance = { source: relative(demoDir, abs), locator, hash: sha256File(abs) };
+ if (locatorPattern !== undefined) provenance.locatorPattern = locatorPattern;
+ if (keyPath !== undefined) provenance.locatorKeyPath = keyPath;
+ return { value, provenance };
+}
+
+/* ────────────────────────────────────────────────────────────────────────────
+ fixture locator:受限 JSON 路径 + 双侧值绑定
+
+ 审核 P1 #3 的根因:旧实现只 hash 整个 fixture 文件,locator 是自由文本。于是
+ `makeFixtureLeaf('HANDWRITTEN', 'fixtures/providers.json', { locator: 'data[0].displayName' })`
+ 能过全部校验——hash 对得上(文件没改),locator 看起来很像路径(其实没人解析它),
+ value 却是手打的。fixture 从"声明性降级"变成了"手抄数据的免检通道"。
+
+ 修法两条,工厂函数与 validateProvenance 双侧共用本节代码(单一真相源,免得两边漂):
+ ① locator 收紧为可机械解析的 JSON 路径(对象键 / 数组下标 / JSON Pointer),
+ 自由文本一律拒——不可解析的锚等于没有锚;
+ ② 解析 fixture 文件、按 locator 取值,与叶子 value canonical-equal 比对,不符即拒。
+
+ 注意:本文件被 init.mjs 整份拷进 demo 目录(demo 自包含),因此只许 import node
+ 内建模块——canonicalJson 与 fs-utils.canonicalize 语义相同但必须在此独立实现。
+ ──────────────────────────────────────────────────────────────────────────── */
+
+const LOCATOR_KEY_CHARS = /[A-Za-z0-9_$-]/;
+export const FIXTURE_LOCATOR_SYNTAX =
+ '受限 JSON 路径:对象键用 `.` 分隔、数组下标用 `.0` 或 `[0]`(如 data.0.displayName / ' +
+ 'data[0].displayName),或 RFC6901 JSON Pointer(如 /data/0/displayName)';
+
+/**
+ * 解析 fixture locator 为路径段数组。不合法(自由文本、空段、非数字下标等)返回 null。
+ * 段一律是 string;取值时按容器类型决定它是对象键还是数组下标。
+ */
+export function parseFixtureLocator(locator) {
+ if (typeof locator !== 'string' || !locator) return null;
+ if (locator !== locator.trim()) return null;
+ // JSON Pointer(RFC6901):必须以 / 开头,~1 → / 、~0 → ~
+ if (locator.startsWith('/')) {
+ const raw = locator.slice(1).split('/');
+ if (raw.some((s) => s === '')) return null;
+ // 未转义的 ~ 后必须跟 0/1,否则是笔误而不是合法 pointer
+ if (raw.some((s) => /~(?![01])/.test(s))) return null;
+ return raw.map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
+ }
+ const segs = [];
+ let i = 0;
+ while (i < locator.length) {
+ if (locator[i] === '[') {
+ const close = locator.indexOf(']', i);
+ if (close === -1) return null;
+ const idx = locator.slice(i + 1, close);
+ if (!/^\d+$/.test(idx)) return null;
+ segs.push(idx);
+ i = close + 1;
+ } else {
+ let j = i;
+ while (j < locator.length && LOCATOR_KEY_CHARS.test(locator[j])) j += 1;
+ if (j === i) return null;
+ segs.push(locator.slice(i, j));
+ i = j;
+ }
+ if (i >= locator.length) break;
+ if (locator[i] === '.') {
+ i += 1;
+ if (i >= locator.length) return null;
+ } else if (locator[i] !== '[') return null;
+ }
+ return segs.length ? segs : null;
+}
+
+/** 按已解析的路径段在 fixture JSON 上取值。返回 {ok:true,value} 或 {ok:false,reason}。 */
+export function resolveFixtureLocator(root, segs) {
+ let cur = root;
+ const walked = [];
+ for (const seg of segs) {
+ const at = walked.length ? walked.join('.') : '(root)';
+ if (Array.isArray(cur)) {
+ if (!/^\d+$/.test(seg)) return { ok: false, reason: `${at} 是数组,段必须是数字下标(当前 "${seg}")` };
+ const idx = Number(seg);
+ if (idx >= cur.length) return { ok: false, reason: `${at} 数组长 ${cur.length},下标 ${idx} 越界` };
+ cur = cur[idx];
+ } else if (cur !== null && typeof cur === 'object') {
+ if (!Object.hasOwn(cur, seg)) return { ok: false, reason: `${at} 下没有键 "${seg}"` };
+ cur = cur[seg];
+ } else {
+ return { ok: false, reason: `${at} 不是对象/数组(${cur === null ? 'null' : typeof cur}),无法继续取 "${seg}"` };
+ }
+ walked.push(seg);
+ }
+ return { ok: true, value: cur };
+}
+
+/** 键序无关的稳定序列化(值比对用)。与 fs-utils.canonicalize 同语义,见本节顶部注释。 */
+export function canonicalJson(value) {
+ const norm = (v) => {
+ if (Array.isArray(v)) return v.map(norm);
+ if (v !== null && typeof v === 'object' && Object.getPrototypeOf(v) !== null && Object.getPrototypeOf(v) !== Object.prototype) return v;
+ if (v !== null && typeof v === 'object') {
+ const out = Object.create(null); // r12:同 fs-utils.canonicalize,__proto__ 键不许被静默丢弃
+ for (const k of Object.keys(v).sort()) out[k] = norm(v[k]);
+ return out;
+ }
+ return v;
+ };
+ return JSON.stringify(norm(value));
+}
+
+const CAPTURED_FROM_KEYS = ['environment', 'capturedAt', 'endpoint', 'note'];
+
+/**
+ * capturedFrom 必须是结构化声明,不是自由文本。
+ *
+ * 为什么收紧:自由文本没有任何可机械检查的成分,"沙盒响应" 四个字就能过——
+ * 但它既没说是哪个环境、也没说什么时候录的,reviewer 三个月后完全无法判断这份
+ * fixture 还代表不代表真实服务端。structured 之后至少 environment / capturedAt
+ * 两段是必填且可校验的(capturedAt 必须是真日期)。
+ *
+ * 返回 problems 数组(以 'capturedFrom' 开头,调用方自行加 path 前缀)。
+ */
+export function validateCapturedFrom(capturedFrom) {
+ if (capturedFrom === undefined || capturedFrom === null) {
+ return ['capturedFrom 必填(sourceKind=fixture):结构化对象 { environment, capturedAt[, endpoint, note] }'];
+ }
+ if (typeof capturedFrom === 'string') {
+ return [
+ 'capturedFrom 不接受自由文本(旧写法已下线):改成结构化对象 ' +
+ '{ environment: "公司沙盒", capturedAt: "2026-07-30", endpoint: "GET /api/providers" }',
+ ];
+ }
+ if (typeof capturedFrom !== 'object' || Array.isArray(capturedFrom)) {
+ return ['capturedFrom 必须是对象 { environment, capturedAt[, endpoint, note] }'];
+ }
+ const problems = [];
+ for (const key of ['environment', 'capturedAt']) {
+ if (typeof capturedFrom[key] !== 'string' || !capturedFrom[key].trim()) problems.push(`capturedFrom.${key} 必填非空 string`);
+ }
+ const at = typeof capturedFrom.capturedAt === 'string' ? capturedFrom.capturedAt.trim() : '';
+ if (at) {
+ if (!/^\d{4}-\d{2}-\d{2}([T ].*)?$/.test(at)) problems.push(`capturedFrom.capturedAt 必须以 ISO 日期开头(YYYY-MM-DD),当前 "${at}"`);
+ else if (Number.isNaN(Date.parse(at.slice(0, 10)))) problems.push(`capturedFrom.capturedAt 不是真实日期:"${at}"`);
+ }
+ for (const key of ['endpoint', 'note']) {
+ if (capturedFrom[key] !== undefined && (typeof capturedFrom[key] !== 'string' || !capturedFrom[key].trim()))
+ problems.push(`capturedFrom.${key} 必须是非空 string`);
+ }
+ for (const key of Object.keys(capturedFrom)) {
+ if (!CAPTURED_FROM_KEYS.includes(key)) problems.push(`capturedFrom.${key} 不是支持的字段(${CAPTURED_FROM_KEYS.join('/')})`);
+ }
+ return problems;
+}
+
+/**
+ * 校验「叶子 value ≡ fixture 文件里 locator 指向的值」。fixtureAbs 须已确认存在。
+ * 返回 problems 数组(空 = 绑定成立)。
+ */
+export function validateFixtureValueBinding(value, fixtureAbs, locator) {
+ const segs = parseFixtureLocator(locator);
+ if (!segs) return [`locator 必须是可机械解析的${FIXTURE_LOCATOR_SYNTAX};自由文本不接受(当前 ${JSON.stringify(locator)})`];
+ let json;
+ try {
+ json = JSON.parse(readFileSync(fixtureAbs, 'utf8'));
+ } catch (err) {
+ return [`fixture 不是合法 JSON,无法核对 locator 指向的值:${err.message}`];
+ }
+ const hit = resolveFixtureLocator(json, segs);
+ if (!hit.ok) return [`locator "${locator}" 在 fixture 里定位失败:${hit.reason}`];
+ if (canonicalJson(hit.value) !== canonicalJson(value)) {
+ return [
+ `value 与 fixture 不符:locator "${locator}" 指向 ${canonicalJson(hit.value)},` +
+ `叶子写的是 ${canonicalJson(value)}——fixture 叶子的值必须来自 fixture 本身,不能手打`,
+ ];
+ }
+ return [];
+}
+
+/**
+ * 服务端驱动数据的叶子工厂:值来自**录制的服务端响应**(providers 配置、account
+ * memberships 等源码里没有字面量的数据)。产出 provenance.sourceKind='fixture',
+ * 并强制结构化 capturedFrom——诚实声明"这不是源码溯源",而不是假装是。
+ *
+ * 硬约束(与 validateProvenance 同口径同代码,这里提前抛以便 extract 作者立刻看到):
+ * - locator 必须是受限 JSON 路径,且在 fixture 里能定位到与 value canonical-equal 的值;
+ * - capturedFrom 必须是结构化对象 { environment, capturedAt[, endpoint, note] };
+ * - fixtureFile 必须存在,且落在 demo 内 `fixtures/` 下(随 PR 走、reviewer 能打开)。
+ *
+ * 边界(诚实声明):本工具能证明"这个值确实来自这份 fixture",**不能**证明"这个值
+ * 本来可以从源码提取却偷懒用了 fixture"——后者没有机械判据,属人工审查项。
+ *
+ * @param value 从 fixture 里读出的值
+ * @param fixtureFile fixture 文件路径(绝对或相对 demoDir),须为 demo 内 fixtures/<name>.json
+ * @param opts.locator 必填:该值在 fixture 中的 JSON 路径(如 'data.0.displayName')
+ * @param opts.capturedFrom 必填:{ environment, capturedAt[, endpoint, note] }
+ * @param opts.demoDir 默认 process.cwd()
+ */
+export function makeFixtureLeaf(value, fixtureFile, { locator, capturedFrom, demoDir = process.cwd() } = {}) {
+ if (!locator || typeof locator !== 'string') {
+ throw new Error(`makeFixtureLeaf(${JSON.stringify(value)}): 必须写 locator——该值在 fixture 里的 JSON 路径`);
+ }
+ const cfProblems = validateCapturedFrom(capturedFrom);
+ if (cfProblems.length) throw new Error(`makeFixtureLeaf(${JSON.stringify(value)}): ${cfProblems.join(';')}`);
+ const abs = isAbsolute(fixtureFile) ? fixtureFile : resolve(demoDir, fixtureFile);
+ if (!existsSync(abs)) throw new Error(`makeFixtureLeaf: fixture 文件不存在:${abs}`);
+ const rel = relative(demoDir, abs).split('\\').join('/');
+ if (!rel || rel === '..' || rel.startsWith('../')) {
+ throw new Error(`makeFixtureLeaf: fixture 必须放 demo 目录内(当前 ${abs} 在 demo 外,随 PR 走不了)`);
+ }
+ if (!rel.startsWith('fixtures/')) {
+ throw new Error(`makeFixtureLeaf: fixture 必须放 demo 内 fixtures/ 下(当前 ${rel})`);
+ }
+ const bindProblems = validateFixtureValueBinding(value, abs, locator);
+ if (bindProblems.length) throw new Error(`makeFixtureLeaf: ${bindProblems.join(';')}`);
+ const cf = { environment: capturedFrom.environment.trim(), capturedAt: capturedFrom.capturedAt.trim() };
+ if (capturedFrom.endpoint !== undefined) cf.endpoint = capturedFrom.endpoint.trim();
+ if (capturedFrom.note !== undefined) cf.note = capturedFrom.note.trim();
+ return {
+ value,
+ provenance: { source: rel, sourceKind: 'fixture', locator, capturedFrom: cf, hash: sha256File(abs) },
+ };
+}
+
+/** 从正则捕获组提取源文件中的值(常见「读常量」场景的一步到位封装)。 */
+export function extractByPattern(sourceFile, pattern, { locator, demoDir = process.cwd(), transform } = {}) {
+ const abs = isAbsolute(sourceFile) ? sourceFile : resolve(demoDir, sourceFile);
+ const content = readFileSync(abs, 'utf8');
+ const matches = [...content.matchAll(new RegExp(pattern, 'g'))];
+ if (matches.length !== 1) throw new Error(`extractByPattern: ${pattern} 在 ${abs} 命中 ${matches.length} 次(必须恰 1 次)`);
+ if (matches[0].length !== 2) throw new Error(`extractByPattern: ${pattern} 必须恰含一个捕获组`);
+ const raw = matches[0][1];
+ return makeLeaf(transform ? transform(raw) : raw, abs, {
+ locator: locator ?? `正则 ${pattern}`,
+ locatorPattern: pattern,
+ demoDir,
+ });
+}
+
+export function resolveFrom(name, startDirs) {
+ const attempts = [];
+ for (const dir of startDirs.filter(Boolean)) {
+ try {
+ return createRequire(join(resolve(dir), 'package.json')).resolve(name);
+ } catch (err) {
+ attempts.push(`${dir}: ${err.message}`);
+ }
+ }
+ throw new Error(`无法解析模块 ${name}(在产品仓装了吗?)\n${attempts.join('\n')}`);
+}
+
+/**
+ * esbuild 临时编译 TS 模块后 import——门 F 的 oracle 必须是产品布局公式本身,
+ * 不许在 extract 里手抄公式(抄错两边同错 = 假绿)。esbuild 从产品仓 node_modules 解析。
+ */
+export async function importTsModule(tsFile, { repoRoot } = {}) {
+ const abs = resolve(tsFile);
+ if (!existsSync(abs)) throw new Error(`importTsModule: 文件不存在:${abs}`);
+ const root = repoRoot ?? findRepoRoot(dirname(abs));
+ // 候选链不放 process.cwd():cwd 可能是 demo 目录(不可信侧),
+ // 命中 <demo>/node_modules/esbuild 就是任意代码执行(审核 r4 CRITICAL)。
+ const esbuildPath = resolveFrom('esbuild', [process.env.QA_HIFI_MODULE_ROOT, root]);
+ const esbuildMod = await import(pathToFileURL(esbuildPath).href);
+ const esbuild = esbuildMod.default?.build ? esbuildMod.default : esbuildMod;
+ const result = await esbuild.build({
+ entryPoints: [abs],
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ write: false,
+ logLevel: 'silent',
+ plugins: [
+ {
+ // 只允许打进相对导入的纯函数依赖;裸导入(react 等)一律 external——
+ // oracle 应是纯计算模块,拖进 UI 依赖说明选错了提取对象
+ name: 'externalize-bare',
+ setup(build) {
+ build.onResolve({ filter: /^[^./]/ }, (args) => (isBuiltin(args.path) ? undefined : { path: args.path, external: true }));
+ },
+ },
+ ],
+ });
+ const outFile = join(mkdtempSync(join(tmpdir(), 'qa-hifi-ts-')), 'mod.mjs');
+ writeFileSync(outFile, result.outputFiles[0].text);
+ return import(pathToFileURL(outFile).href);
+}
+
+/* ────────────────────────────────────────────────────────────────────────────
+ 主题桥:registerColor 全表 → 带 provenance 的 truth 叶子
+
+ 组件模式(直接渲染产品组件)下 demo 需要一份 CSS 自定义属性表来复刻产品主题。
+ spike 阶段是在 build 脚本里就地正则一把梭;产品化后必须走 truth 叶子——否则
+ 色值进了 demo 却不在 truth.json 里,门 A 的防伪链(provenance + extractor-drift)
+ 管不到它,改了产品色表也没人报警。
+
+ 语义与 themes/theme-service.ts 的 resolveThemeValue 对齐:
+ · light 有值 → 用 light;
+ · dark 有值 → 用 dark;dark 为 null/未写 → 回退 light(历史 :root-only token 的级联)。
+ ──────────────────────────────────────────────────────────────────────────── */
+
+const REGISTER_COLOR_HEAD = /registerColor\(\s*(['"])((?:[^'"\\]|\\.)*?)\1\s*,\s*\{/g;
+
+function escapeRe(s) {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+/** 从 `{` 开始找配平的 `}`,跳过字符串/模板/注释。返回 {body, endIdx} 或 null(未配平)。 */
+function scanBraceBlock(src, openIdx) {
+ let depth = 0;
+ for (let i = openIdx; i < src.length; i++) {
+ const c = src[i];
+ if (c === '/' && src[i + 1] === '/') {
+ i = src.indexOf('\n', i);
+ if (i === -1) break;
+ continue;
+ }
+ if (c === '/' && src[i + 1] === '*') {
+ const end = src.indexOf('*/', i + 2);
+ if (end === -1) break;
+ i = end + 1;
+ continue;
+ }
+ if (c === "'" || c === '"' || c === '`') {
+ for (let j = i + 1; j < src.length; j++) {
+ if (src[j] === '\\') { j++; continue; }
+ if (src[j] === c) { i = j; break; }
+ if (j === src.length - 1) return null;
+ }
+ continue;
+ }
+ if (c === '{') depth++;
+ else if (c === '}') {
+ depth--;
+ if (depth === 0) return { body: src.slice(openIdx + 1, i), endIdx: i };
+ }
+ }
+ return null;
+}
+
+const JS_ESCAPES = { n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v', 0: '\0' };
+
+function unescapeJs(raw) {
+ return raw.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_m, esc) => {
+ if (esc[0] === 'u' || esc[0] === 'x') {
+ const hex = esc[1] === '{' ? esc.slice(2, -1) : esc.slice(1);
+ return String.fromCodePoint(Number.parseInt(hex, 16));
+ }
+ return Object.hasOwn(JS_ESCAPES, esc) ? JS_ESCAPES[esc] : esc;
+ });
+}
+
+/** 从 openIdx 处的引号跳到闭合引号,返回闭合引号之后的下标(未闭合返回 src.length)。 */
+function skipStringLiteral(src, openIdx) {
+ const q = src[openIdx];
+ for (let j = openIdx + 1; j < src.length; j += 1) {
+ if (src[j] === '\\') { j += 1; continue; }
+ if (src[j] === q) return j + 1;
+ }
+ return src.length;
+}
+
+/**
+ * 词法化扫描对象体,列出**顶层**属性的「值起始下标」。
+ *
+ * 审核 P1 #4 的根因:旧实现用裸正则 `(?:^|[,{\s])light\s*:` 在 body 上找键,body 里
+ * 的注释原样保留,于是 `// light: '#stale'` 这行注释会被当成真属性命中,过时色值
+ * 直接进 truth 且 provenance 全绿(hash 对得上,因为文件确实没改)。
+ *
+ * 本函数按字符走:注释整段跳过、字符串/模板整段跳过、只在 depth===0 记录属性,
+ * 因此注释里的伪属性、嵌套对象里的同名属性都不会被误当成 defaults 的顶层属性。
+ * 返回 Map<键名, 值起始下标>(同名键取第一个,与 JS 对象字面量后者覆盖前者不同——
+ * 源码里真出现重复键属于异常,取第一个后值比对/pattern 自检会把问题暴露出来)。
+ */
+function scanTopLevelProps(body) {
+ const props = new Map();
+ let depth = 0;
+ let i = 0;
+ const remember = (name, colonIdx) => {
+ let v = colonIdx + 1;
+ while (v < body.length && /\s/.test(body[v])) v += 1;
+ if (!props.has(name)) props.set(name, v);
+ };
+ const colonAfter = (from) => {
+ let k = from;
+ while (k < body.length && /\s/.test(body[k])) k += 1;
+ return body[k] === ':' ? k : -1;
+ };
+ while (i < body.length) {
+ const c = body[i];
+ if (c === '/' && body[i + 1] === '/') {
+ const nl = body.indexOf('\n', i);
+ i = nl === -1 ? body.length : nl + 1;
+ continue;
+ }
+ if (c === '/' && body[i + 1] === '*') {
+ const end = body.indexOf('*/', i + 2);
+ i = end === -1 ? body.length : end + 2;
+ continue;
+ }
+ if (c === "'" || c === '"' || c === '`') {
+ const after = skipStringLiteral(body, i);
+ // 带引号的键:`'light': '#fff'` —— 字符串后紧跟 ':' 才算键,否则是个值
+ if (depth === 0) {
+ const colon = colonAfter(after);
+ if (colon !== -1) remember(unescapeJs(body.slice(i + 1, after - 1)), colon);
+ }
+ i = after;
+ continue;
+ }
+ if (c === '{' || c === '[' || c === '(') { depth += 1; i += 1; continue; }
+ if (c === '}' || c === ']' || c === ')') { depth -= 1; i += 1; continue; }
+ if (depth === 0 && /[A-Za-z_$]/.test(c)) {
+ let j = i;
+ while (j < body.length && /[A-Za-z0-9_$]/.test(body[j])) j += 1;
+ const colon = colonAfter(j);
+ if (colon !== -1) remember(body.slice(i, j), colon);
+ i = j;
+ continue;
+ }
+ i += 1;
+ }
+ return props;
+}
+
+/**
+ * 读 defaults 对象体里某个**顶层**模式键的值。返回:
+ * { kind: 'string', raw, value, quote, valueIdx } | { kind: 'null' } | { kind: 'absent' }
+ * | { kind: 'unresolvable' }(函数调用 / 变量 / 带插值的模板字面量 —— 静态提取不了)
+ * valueIdx = 值在 body 内的起始下标(调用方加 body 偏移即得源码绝对位置,供 pattern 自检)。
+ */
+function readModeValue(body, key, props = scanTopLevelProps(body)) {
+ if (!props.has(key)) return { kind: 'absent' };
+ let i = props.get(key);
+ const valueIdx = i;
+ const q = body[i];
+ if (q === "'" || q === '"' || q === '`') {
+ let raw = '';
+ for (let j = i + 1; j < body.length; j++) {
+ const c = body[j];
+ if (c === '\\') { raw += c + (body[j + 1] ?? ''); j++; continue; }
+ if (c === q) return { kind: 'string', raw, value: unescapeJs(raw), quote: q, valueIdx };
+ // 模板插值 = 运行期求值,静态提取不了
+ if (q === '`' && c === '$' && body[j + 1] === '{') return { kind: 'unresolvable' };
+ raw += c;
+ }
+ return { kind: 'unresolvable' };
+ }
+ if (/^null\b/.test(body.slice(i))) return { kind: 'null' };
+ return { kind: 'unresolvable' };
+}
+
+/**
+ * 生成「该 token 该模式」的 writeback 定位锚:恰含一个捕获组、在整个 colors.ts 里恰命中
+ * 一次的正则。`(?:(?!registerColor\()[\s\S])*?` 保证不越界到下一个 registerColor 调用。
+ * 生成后自检(命中次数 + 捕获内容 == 源码原文 + 捕获位置 == 词法扫描定位到的真值位置),
+ * 不达标就返回 null —— 宁可退化成「无机械写回通道」(writeback 会明确拒绝并要求 agent
+ * 双改),也不给一个会写错位置的锚。
+ *
+ * 位置自检是 #4 修复的一部分:正则本身不懂注释,`// light:'#x'` 里的伪属性同样会被它
+ * 命中。只要注释里的值恰好与真值同字面量,次数/内容自检就都过得去,锚却指向注释——
+ * writeback 会把改动写进注释里。要求捕获位置与词法位置一致才能彻底排除这种错位。
+ */
+function makeModePattern(src, id, key, expectedRaw, absValueIdx) {
+ const pattern =
+ String.raw`registerColor\(\s*['"]${escapeRe(id)}['"]` +
+ String.raw`(?:(?!registerColor\()[\s\S])*?\b${key}\s*:\s*['"]([^'"]*)['"]`;
+ let hits;
+ try {
+ hits = [...src.matchAll(new RegExp(pattern, 'g'))];
+ } catch {
+ return null;
+ }
+ if (hits.length !== 1 || hits[0][1] !== expectedRaw) return null;
+ // 捕获组紧跟在开引号之后:pattern 尾部固定为 ['"]([^'"]*)['"],故 groupStart = matchEnd - 1 - raw.length
+ const groupStart = hits[0].index + hits[0][0].length - 1 - expectedRaw.length;
+ if (Number.isInteger(absValueIdx) && groupStart !== absValueIdx + 1) return null;
+ return pattern;
+}
+
+/**
+ * 提取 `themes/colors.ts` 的 registerColor 全表为 truth 子树。
+ *
+ * truth.themeVars = extractThemeVars(colorsFile, { demoDir });
+ * // → { 'surface': { light: <leaf>, dark: <leaf> }, 'surface-hsl': {...}, ... }
+ *
+ * 每个叶子是 makeLeaf() 的产物(value = CSS 值字符串,provenance.source = colors.ts,
+ * locator 写明 token 名与模式)。light/dark 各自可机械写回时带 locatorPattern;
+ * dark 回退 light 的叶子不带锚(它在源码里没有对应字面量,给锚只会写错位置)。
+ *
+ * 跳过的 token(light 非字面量、或 dark 是非字面量表达式)不进结果:静态提取拿不到
+ * 真值,硬塞一个猜的值等于往 truth 里注假。跳过项通过 onSkip 回调交出;没给回调时
+ * 打一条 stderr 汇总——不静默。
+ *
+ * @param colorsFile 产品 colors.ts 路径(绝对,或相对 demoDir)
+ * @param opts.prefix 只要 id 以此开头的 token(如 'login-');缺省全量
+ * @param opts.demoDir 默认 process.cwd()(truth.mjs 保证 = demo 目录)
+ * @param opts.onSkip (skipped) => void,skipped = [{ id, mode, reason }]
+ */
+export function extractThemeVars(colorsFile, { prefix, demoDir = process.cwd(), onSkip } = {}) {
+ const abs = isAbsolute(colorsFile) ? colorsFile : resolve(demoDir, colorsFile);
+ if (!existsSync(abs)) throw new Error(`extractThemeVars: 源文件不存在:${abs}`);
+ const src = readFileSync(abs, 'utf8');
+
+ const out = Object.create(null); // r12:key 是产品源码里的 color id,同一形状
+ const skipped = [];
+ let scanned = 0;
+ REGISTER_COLOR_HEAD.lastIndex = 0;
+ for (const head of src.matchAll(REGISTER_COLOR_HEAD)) {
+ scanned++;
+ const id = unescapeJs(head[2]);
+ const openIdx = head.index + head[0].length - 1;
+ const block = scanBraceBlock(src, openIdx);
+ if (!block) {
+ skipped.push({ id, mode: 'both', reason: 'defaults 对象大括号未配平(源码语法异常?)' });
+ continue;
+ }
+ if (prefix && !id.startsWith(prefix)) continue;
+ if (Object.hasOwn(out, id)) {
+ throw new Error(`extractThemeVars: token '${id}' 在 ${abs} 里注册了两次——产品侧 ColorRegistry 会直接抛错,先修源码`);
+ }
+
+ // 词法扫描一次,light/dark 共用——注释里的伪属性在这一步就被排除(审核 P1 #4)
+ const props = scanTopLevelProps(block.body);
+ const bodyOffset = openIdx + 1; // block.body 在 src 中的起始位置
+ const light = readModeValue(block.body, 'light', props);
+ const dark = readModeValue(block.body, 'dark', props);
+ if (light.kind !== 'string') {
+ skipped.push({
+ id,
+ mode: 'light',
+ reason: light.kind === 'null' || light.kind === 'absent'
+ ? 'light 为 null/未写(该 token 在 light 下无值)'
+ : 'light 是非字面量表达式(函数调用/变量/模板插值),静态提取不到真值',
+ });
+ continue;
+ }
+ if (dark.kind === 'unresolvable') {
+ skipped.push({ id, mode: 'dark', reason: 'dark 是非字面量表达式,静态提取不到真值(不敢回退 light,那会写进假值)' });
+ continue;
+ }
+
+ const lightPattern = makeModePattern(src, id, 'light', light.raw, bodyOffset + light.valueIdx);
+ const lightLeaf = makeLeaf(light.value, abs, {
+ locator: `colors.ts registerColor('${id}') 的 defaults.light`,
+ ...(lightPattern ? { locatorPattern: lightPattern } : {}),
+ demoDir,
+ });
+
+ let darkLeaf;
+ if (dark.kind === 'string') {
+ const darkPattern = makeModePattern(src, id, 'dark', dark.raw, bodyOffset + dark.valueIdx);
+ darkLeaf = makeLeaf(dark.value, abs, {
+ locator: `colors.ts registerColor('${id}') 的 defaults.dark`,
+ ...(darkPattern ? { locatorPattern: darkPattern } : {}),
+ demoDir,
+ });
+ } else {
+ // dark: null / 未写 → theme-service.resolveThemeValue 回退 light(旧 :root-only 级联)
+ darkLeaf = makeLeaf(light.value, abs, {
+ locator: `colors.ts registerColor('${id}') 的 defaults.dark 为 null/未写,按 theme-service.resolveThemeValue 回退 light`,
+ demoDir,
+ });
+ }
+
+ out[id] = { light: lightLeaf, dark: darkLeaf };
+ }
+
+ if (scanned === 0) {
+ throw new Error(`extractThemeVars: 在 ${abs} 里一个 registerColor(...) 都没匹配到——源码格式变了,先修本函数的解析再跑`);
+ }
+ if (Object.keys(out).length === 0) {
+ throw new Error(
+ `extractThemeVars: ${abs} 扫到 ${scanned} 个 registerColor,但${prefix ? ` prefix='${prefix}' 过滤后` : ''}一个可用 token 都没有`,
+ );
+ }
+ if (skipped.length) {
+ if (onSkip) onSkip(skipped);
+ else console.warn(`[extractThemeVars] 跳过 ${skipped.length} 个 token:${skipped.map((s) => `${s.id}(${s.mode})`).join(', ')}`);
+ }
+ return out;
+}
diff --git a/docs/design-previews/library-extradirs-quota/extract.mjs b/docs/design-previews/library-extradirs-quota/extract.mjs
new file mode 100644
index 0000000000..217dc46c88
--- /dev/null
+++ b/docs/design-previews/library-extradirs-quota/extract.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+import { readFileSync } from 'node:fs';
+import { findRepoRoot, makeLeaf, extractByPattern, readJson } from './extract-helpers.mjs';
+import { join } from 'node:path';
+
+const repoRoot = findRepoRoot();
+const actions = join(repoRoot, 'apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts');
+const chatInput = join(repoRoot, 'apps/desktop/src/renderer/components/new-chat/ChatInput.tsx');
+const panel = join(repoRoot, 'apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx');
+const validator = join(repoRoot, 'apps/desktop/src/main/maker-ipc/extraDirsValidator.ts');
+const zh = join(repoRoot, 'apps/desktop/src/renderer/i18n/locales/zh-CN/common.json');
+const en = join(repoRoot, 'apps/desktop/src/renderer/i18n/locales/en/common.json');
+
+const zhCopy = readJson(zh).extraDirs;
+const enCopy = readJson(en).extraDirs;
+const chatSrc = readFileSync(chatInput, 'utf8');
+const panelSrc = readFileSync(panel, 'utf8');
+const count = (src, re) => (src.match(re) || []).length;
+
+const truth = {
+ quota: {
+ max: extractByPattern(validator, 'export const EXTRA_DIRS_MAX = (\\d+)', {
+ locator: 'extraDirsValidator EXTRA_DIRS_MAX',
+ }),
+ slotPrefix: extractByPattern(actions, "export const LIBRARY_EXTRA_DIR_SLOT_PREFIX = '([^']+)'", {
+ locator: 'extraDirsActions LIBRARY_EXTRA_DIR_SLOT_PREFIX',
+ }),
+ systemLabel: extractByPattern(actions, "isLibraryExtraDirSlot\\(dir\\) \\? '([^']+)'", {
+ locator: 'extraDirsActions extraDirDisplayLabel 系统项文案',
+ }),
+ },
+ wiring: {
+ chatInputQuotaSites: makeLeaf(
+ count(chatSrc, /countUserExtraDirs\(currentExtraDirs\) \+ countUserExtraDirs\(currentWritableDirs\)/g),
+ chatInput,
+ { locator: 'ChatInput 加目录/可写目录两处配额公式次数' },
+ ),
+ chatInputBadgeSites: makeLeaf(
+ count(chatSrc, /countUserExtraDirs\(extraDirs \?\? \[\]\) \+ countUserExtraDirs\(writableDirs \?\? \[\]\)/g),
+ chatInput,
+ { locator: 'ChatInput ExtraDirsButton extraDirsCount 公式次数' },
+ ),
+ panelLabelSites: makeLeaf(
+ count(panelSrc, /extraDirDisplayLabel\(p\)/g),
+ panel,
+ { locator: 'AtMentionPanel extraDirDisplayLabel(p) 次数' },
+ ),
+ panelNoRemoveSites: makeLeaf(
+ count(panelSrc, /isLibraryExtraDirSlot\(p\) \? null/g),
+ panel,
+ { locator: 'AtMentionPanel library 槽不画移除按钮' },
+ ),
+ },
+ copy: {
+ 'zh-CN': {
+ sectionTitle: makeLeaf(zhCopy.sectionTitle, zh, { locator: 'extraDirs.sectionTitle', keyPath: 'extraDirs.sectionTitle' }),
+ addReadOnly: makeLeaf(zhCopy.addReadOnly, zh, { locator: 'extraDirs.addReadOnly', keyPath: 'extraDirs.addReadOnly' }),
+ atLimit: makeLeaf(zhCopy.atLimit, zh, { locator: 'extraDirs.atLimit', keyPath: 'extraDirs.atLimit' }),
+ tooltipCount: makeLeaf(zhCopy.tooltipCount, zh, { locator: 'extraDirs.tooltipCount', keyPath: 'extraDirs.tooltipCount' }),
+ empty: makeLeaf(zhCopy.empty, zh, { locator: 'extraDirs.empty', keyPath: 'extraDirs.empty' }),
+ },
+ en: {
+ sectionTitle: makeLeaf(enCopy.sectionTitle, en, { locator: 'extraDirs.sectionTitle', keyPath: 'extraDirs.sectionTitle' }),
+ addReadOnly: makeLeaf(enCopy.addReadOnly, en, { locator: 'extraDirs.addReadOnly', keyPath: 'extraDirs.addReadOnly' }),
+ atLimit: makeLeaf(enCopy.atLimit, en, { locator: 'extraDirs.atLimit', keyPath: 'extraDirs.atLimit' }),
+ tooltipCount: makeLeaf(enCopy.tooltipCount, en, { locator: 'extraDirs.tooltipCount', keyPath: 'extraDirs.tooltipCount' }),
+ empty: makeLeaf(enCopy.empty, en, { locator: 'extraDirs.empty', keyPath: 'extraDirs.empty' }),
+ },
+ },
+};
+
+process.stdout.write(JSON.stringify(truth));
diff --git a/docs/design-previews/library-extradirs-quota/index.html b/docs/design-previews/library-extradirs-quota/index.html
new file mode 100644
index 0000000000..247a911081
--- /dev/null
+++ b/docs/design-previews/library-extradirs-quota/index.html
@@ -0,0 +1,431 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>library-extradirs-quota · qa-hifi demo</title>
+<style>
+/* ===== 界面本体样式 =====
+ 规则:任何文案/几何/颜色值只准来自内嵌 truth(门 A/D 会抓手写漂移)。
+ chrome 工具区样式由 qa-chrome 注入,不要在这里覆盖 qa-* 类。 */
+.panel { font-family: ui-sans-serif, system-ui, sans-serif; padding: 20px 24px; max-width: 480px; }
+.quota-title { font-size: 14px; font-weight: 600; margin: 0 0 12px; }
+html.dark .quota-title { color: #ececec; }
+html:not(.dark) .quota-title { color: #1a1a1a; }
+.row { display: flex; align-items: center; gap: 8px; height: 44px; padding: 0 10px; border-radius: 6px; }
+html:not(.dark) .row:hover { background: #f3f3f3; }
+html.dark .row:hover { background: #2a2a2a; }
+.dir-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; }
+html:not(.dark) .dir-label { color: #1a1a1a; }
+html.dark .dir-label { color: #ececec; }
+.remove { border: 0; background: transparent; cursor: pointer; font-size: 12px; opacity: .7; }
+.add-btn { margin-top: 8px; height: 36px; padding: 0 12px; border-radius: 8px; border: 1px solid #ccc; background: transparent; font-size: 13px; cursor: pointer; }
+.add-btn[disabled] { opacity: .45; cursor: not-allowed; }
+.count-badge { margin-left: 8px; font-size: 12px; opacity: .7; }
+.fill-btn { margin-top: 16px; font-size: 12px; opacity: .8; }
+</style>
+</head>
+<body>
+<!-- 真值块:由 `node <skill>/scripts/truth.mjs --demo <dir> --embed` 写入,禁止手抄 -->
+<script id="qa-truth" type="application/json">{"copy":{"en":{"addReadOnly":{"provenance":{"hash":"2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b","locator":"extraDirs.addReadOnly","locatorKeyPath":"extraDirs.addReadOnly","source":"../../../apps/desktop/src/renderer/i18n/locales/en/common.json"},"value":"Add read-only directory…"},"atLimit":{"provenance":{"hash":"2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b","locator":"extraDirs.atLimit","locatorKeyPath":"extraDirs.atLimit","source":"../../../apps/desktop/src/renderer/i18n/locales/en/common.json"},"value":"Limit reached ({{max}})"},"empty":{"provenance":{"hash":"2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b","locator":"extraDirs.empty","locatorKeyPath":"extraDirs.empty","source":"../../../apps/desktop/src/renderer/i18n/locales/en/common.json"},"value":"No reference directories yet"},"sectionTitle":{"provenance":{"hash":"2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b","locator":"extraDirs.sectionTitle","locatorKeyPath":"extraDirs.sectionTitle","source":"../../../apps/desktop/src/renderer/i18n/locales/en/common.json"},"value":"Reference directories (read-only)"},"tooltipCount":{"provenance":{"hash":"2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b","locator":"extraDirs.tooltipCount","locatorKeyPath":"extraDirs.tooltipCount","source":"../../../apps/desktop/src/renderer/i18n/locales/en/common.json"},"value":"{{count}} additional directories"}},"zh-CN":{"addReadOnly":{"provenance":{"hash":"f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364","locator":"extraDirs.addReadOnly","locatorKeyPath":"extraDirs.addReadOnly","source":"../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"},"value":"添加只读目录…"},"atLimit":{"provenance":{"hash":"f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364","locator":"extraDirs.atLimit","locatorKeyPath":"extraDirs.atLimit","source":"../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"},"value":"已达上限 {{max}} 个"},"empty":{"provenance":{"hash":"f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364","locator":"extraDirs.empty","locatorKeyPath":"extraDirs.empty","source":"../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"},"value":"还没有引用目录"},"sectionTitle":{"provenance":{"hash":"f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364","locator":"extraDirs.sectionTitle","locatorKeyPath":"extraDirs.sectionTitle","source":"../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"},"value":"引用目录(只读)"},"tooltipCount":{"provenance":{"hash":"f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364","locator":"extraDirs.tooltipCount","locatorKeyPath":"extraDirs.tooltipCount","source":"../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"},"value":"{{count}} 个附加目录"}}},"quota":{"max":{"provenance":{"hash":"bb3226c65b8c7fab2c3c4a1daf6daba7dc26d5f1464ed24769e8f852a13f4a39","locator":"extraDirsValidator EXTRA_DIRS_MAX","locatorPattern":"export const EXTRA_DIRS_MAX = (\\d+)","source":"../../../apps/desktop/src/main/maker-ipc/extraDirsValidator.ts"},"value":"10"},"slotPrefix":{"provenance":{"hash":"8d491fec6e76e07a6a3f001e572e5af94726a41b2d06b72c0c33aea83297f51c","locator":"extraDirsActions LIBRARY_EXTRA_DIR_SLOT_PREFIX","locatorPattern":"export const LIBRARY_EXTRA_DIR_SLOT_PREFIX = '([^']+)'","source":"../../../apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts"},"value":"cindy-library:"},"systemLabel":{"provenance":{"hash":"8d491fec6e76e07a6a3f001e572e5af94726a41b2d06b72c0c33aea83297f51c","locator":"extraDirsActions extraDirDisplayLabel 系统项文案","locatorPattern":"isLibraryExtraDirSlot\\(dir\\) \\? '([^']+)'","source":"../../../apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts"},"value":"Mivo 作品库(只读)"}},"wiring":{"chatInputBadgeSites":{"provenance":{"hash":"019cfe7d536522b125dfcf3ce774e17520a495a432c47c420a55b7ef3a032e51","locator":"ChatInput ExtraDirsButton extraDirsCount 公式次数","source":"../../../apps/desktop/src/renderer/components/new-chat/ChatInput.tsx"},"value":1},"chatInputQuotaSites":{"provenance":{"hash":"019cfe7d536522b125dfcf3ce774e17520a495a432c47c420a55b7ef3a032e51","locator":"ChatInput 加目录/可写目录两处配额公式次数","source":"../../../apps/desktop/src/renderer/components/new-chat/ChatInput.tsx"},"value":2},"panelLabelSites":{"provenance":{"hash":"8626dd9995da248787a2189a5726b7a955224c50cca2911b9729454c98376067","locator":"AtMentionPanel extraDirDisplayLabel(p) 次数","source":"../../../apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx"},"value":2},"panelNoRemoveSites":{"provenance":{"hash":"8626dd9995da248787a2189a5726b7a955224c50cca2911b9729454c98376067","locator":"AtMentionPanel library 槽不画移除按钮","source":"../../../apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx"},"value":1}}}</script>
+<script>
+// ===== demo 配置(作者唯一要写的部分;字段说明见 qa-chrome 头注释) =====
+window.__qaDemo = {
+ name: 'library-extradirs-quota',
+ pr: null,
+ summary: {
+ what: 'composer 引用目录把 cindy-library: 当系统槽:不占用户 10 名额,显示「Mivo 作品库(只读)」且不可移除。',
+ how: 'ChatInput 配额走 countUserExtraDirs;AtMentionPanel 用 extraDirDisplayLabel,library 槽不画移除按钮。',
+ accept: '未满员可添加;10 个用户目录 + library 槽时加号禁用且计数仍为 10;系统项文案来自源码。',
+ },
+ matrix: {
+ plat: { label: '端', options: [{ v: 'desktop', label: '桌面' }] },
+ region: { label: '区域', options: [{ v: 'cn', label: '中国大陆' }] },
+ os: { label: '系统', options: [{ v: 'mac', label: 'macOS' }] },
+ mode: { label: '主题', options: [{ v: 'light', label: 'Light' }, { v: 'dark', label: 'Dark' }] },
+ lang: { label: '语言', options: [{ v: 'zh-CN', label: '简中' }, { v: 'en', label: 'EN' }] },
+ },
+ defaultPrefs: { plat: 'desktop', region: 'cn', os: 'mac', mode: 'light', lang: 'zh-CN' },
+ initialState: 'mixed',
+ states: {
+ mixed: {},
+ full: {},
+ },
+ tabStates: [],
+ adaptive: null,
+ // adaptive: { min: { w: 960, h: 640 }, initial: { w: 1200, h: 800 }, bandLabel: (w, h) => (w < 1100 ? '压缩档' : '标准档') },
+ scale: () => 1,
+ renderApp(ctx) {
+ const t = ctx.truth;
+ const lang = ctx.prefs.lang === 'en' ? 'en' : 'zh-CN';
+ const copy = t.copy[lang];
+ const max = Number(t.quota.max);
+ const prefix = t.quota.slotPrefix;
+ const systemLabel = t.quota.systemLabel;
+ const userCount = ctx.state === 'full' ? max : 2;
+ const atLimit = userCount >= max;
+ const addLabel = atLimit
+ ? copy.atLimit.replace('{{max}}', String(max))
+ : copy.addReadOnly;
+ const badge = copy.tooltipCount.replace('{{count}}', String(userCount));
+ const users = Array.from({ length: userCount }, (_, i) => 'refs-' + (i + 1));
+ const row = (label, system) => {
+ const el = document.createElement('div');
+ el.className = 'row';
+ el.setAttribute('data-node-id', system ? 'library-slot' : 'user-dir-' + label);
+ const name = document.createElement('span');
+ name.className = 'dir-label';
+ name.textContent = label;
+ el.appendChild(name);
+ if (!system) {
+ const rm = document.createElement('button');
+ rm.type = 'button';
+ rm.className = 'remove';
+ rm.textContent = '×';
+ el.appendChild(rm);
+ }
+ return el;
+ };
+ ctx.frame.innerHTML = '';
+ const panel = document.createElement('div');
+ panel.className = 'panel';
+ panel.setAttribute('data-node-id', 'extra-dirs-panel');
+ const head = document.createElement('div');
+ head.style.display = 'flex';
+ head.style.alignItems = 'baseline';
+ const title = document.createElement('h2');
+ title.className = 'quota-title';
+ title.setAttribute('data-node-id', 'section-title');
+ title.textContent = copy.sectionTitle;
+ const badgeEl = document.createElement('span');
+ badgeEl.className = 'count-badge';
+ badgeEl.textContent = badge;
+ head.appendChild(title);
+ head.appendChild(badgeEl);
+ panel.appendChild(head);
+ panel.appendChild(row(systemLabel, true));
+ users.forEach((name) => panel.appendChild(row(name, false)));
+ const add = document.createElement('button');
+ add.type = 'button';
+ add.className = 'add-btn';
+ add.setAttribute('data-node-id', 'add-extra-dir');
+ add.textContent = addLabel;
+ add.disabled = atLimit;
+ panel.appendChild(add);
+ if (ctx.state !== 'full') {
+ const fill = document.createElement('button');
+ fill.type = 'button';
+ fill.className = 'fill-btn';
+ fill.setAttribute('data-qa-goto', 'full');
+ fill.setAttribute('data-node-id', 'fill-quota');
+ fill.textContent = prefix + 'fill';
+ fill.addEventListener('click', () => ctx.setState('full'));
+ panel.appendChild(fill);
+ }
+ ctx.frame.appendChild(panel);
+ },
+};
+</script>
+<script>
+/* QA_CHROME_BEGIN — 标准 chrome 运行时,由 init.mjs 内联;勿手改。
+ 升级:node <skill>/scripts/init.mjs --dir <demo-dir> --update-chrome */
+/* qa-chrome.js — qa-hifi-demo 标准 chrome 运行时(由 init.mjs 内联进 index.html)。
+ *
+ * 诞生背景:__qa 五个 API + 偏好持久化 + matrix 切换器 + 状态补齐 tab 曾由每个 demo
+ * 重新实现一遍——10 个 demo 写出 10 种偏好切换器(replay.mjs clickPref 要猜 7 种 selector
+ * 就是后果)。本文件是「demo 合约」的唯一标准实现;demo 作者只提供 window.__qaDemo 配置:
+ *
+ * window.__qaDemo = {
+ * name: 'my-demo', // 必填,localStorage key 用
+ * pr: 123, // 可选,PR 号徽标
+ * summary: { what, how, accept }, // 三段说明(各 ≤2 行)
+ * matrix: { // 五维切换器;键固定 plat/region/os/mode/lang
+ * plat: { label: '端', options: [{ v: 'desk', label: '桌面' }, ...] },
+ * region: { label: '区域', options: [...] },
+ * os: { label: '系统', options: [...] },
+ * mode: { label: '主题', options: [...] },
+ * lang: { label: '语言', options: [...] },
+ * },
+ * defaultPrefs: { plat, region, os, mode, lang }, // 必填,全 string
+ * initialState: 'entry', // 必填
+ * states: { entry: {}, scanning: {}, ... }, // 必填:id → {}(可带 onEnter(ctx))
+ * tabStates: [{ id, label, note }], // via:null 状态(注意与 spec.states 对齐)
+ * adaptive: null | { min: {w,h}, initial: {w,h}, bandLabel: (w,h)=>string },
+ * scale: (prefs) => 1, // 设计px→CSS px(默认 1)
+ * renderApp(ctx) { ... }, // 必填:渲染界面本体进 ctx.frame
+ * };
+ *
+ * ctx = { truth, prefs, state, frame, setState(id), chrome }。truth 已解包(叶子裸值)。
+ * 标准 DOM 合约(verify.mjs replay.mjs 的第一优先 selector,别改):
+ * 偏好入口 [data-qa-pref="key:value"]
+ * 状态 tab [data-qa-state-tab]
+ * 状态入口 [data-qa-goto="<state-id>"]
+ * 帧容器 .frame
+ */
+(() => {
+ 'use strict';
+ const cfg = window.__qaDemo;
+ if (!cfg) throw new Error('qa-chrome: 缺 window.__qaDemo 配置(必须在本脚本之前定义)');
+ for (const key of ['name', 'defaultPrefs', 'initialState', 'states', 'renderApp']) {
+ if (!cfg[key]) throw new Error(`qa-chrome: __qaDemo.${key} 必填`);
+ }
+
+ // ---------- truth ----------
+ const truthEl = document.getElementById('qa-truth');
+ if (!truthEl) throw new Error('qa-chrome: 缺 <script id="qa-truth"> 内嵌真值块');
+ const RAW_TRUTH = JSON.parse(truthEl.textContent);
+ const unwrap = (n) => {
+ if (n && typeof n === 'object' && !Array.isArray(n) && 'value' in n && n.provenance) return n.value;
+ if (Array.isArray(n)) return n.map(unwrap);
+ if (n && typeof n === 'object') return Object.fromEntries(Object.entries(n).map(([k, v]) => [k, unwrap(v)]));
+ return n;
+ };
+ const TRUTH = unwrap(RAW_TRUTH);
+
+ // ---------- prefs(五维,localStorage 持久化;流程状态不持久化) ----------
+ const PREF_KEYS = ['plat', 'region', 'os', 'mode', 'lang'];
+ const STORE_KEY = `qa-hifi:${cfg.name}:prefs`;
+ let stored = null;
+ try { stored = JSON.parse(localStorage.getItem(STORE_KEY) || 'null'); } catch {}
+ const prefs = { ...cfg.defaultPrefs };
+ if (stored && typeof stored === 'object') for (const k of PREF_KEYS) if (typeof stored[k] === 'string') prefs[k] = stored[k];
+ const persistPrefs = () => { try { localStorage.setItem(STORE_KEY, JSON.stringify(prefs)); } catch {} };
+
+ // ---------- state ----------
+ let state = cfg.initialState;
+ if (!(state in cfg.states)) throw new Error(`qa-chrome: initialState "${state}" 不在 states 里`);
+
+ // ---------- chrome DOM ----------
+ const css = `
+ :root { --qa-bg:#f4f5f7; --qa-panel:#fff; --qa-ink:#1c1e21; --qa-sub:#6b7280; --qa-line:#e5e7eb; --qa-acc:#2563eb; }
+ body.qa-dark { --qa-bg:#111318; --qa-panel:#1b1e25; --qa-ink:#e8eaed; --qa-sub:#9aa0a6; --qa-line:#2c313a; --qa-acc:#5b8def; }
+ body { margin:0; background:var(--qa-bg); color:var(--qa-ink); font:14px/1.5 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif; }
+ .qa-chrome { padding:12px 16px; border-bottom:1px solid var(--qa-line); background:var(--qa-panel); }
+ .qa-head { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
+ .qa-title { font-size:15px; font-weight:600; }
+ .qa-badge { font-size:12px; padding:1px 8px; border-radius:999px; background:var(--qa-acc); color:#fff; }
+ .qa-summary { margin:6px 0 0; padding:0; list-style:none; color:var(--qa-sub); font-size:12px; }
+ .qa-summary b { color:var(--qa-ink); font-weight:600; }
+ .qa-ctl { display:flex; gap:14px; flex-wrap:wrap; margin-top:10px; align-items:center; }
+ .qa-seg { display:flex; align-items:center; gap:6px; }
+ .qa-seg-label { font-size:12px; color:var(--qa-sub); }
+ .qa-seg-group { display:inline-flex; border:1px solid var(--qa-line); border-radius:8px; overflow:hidden; }
+ .qa-seg-group button { border:0; background:transparent; color:var(--qa-ink); padding:3px 10px; font-size:12px; cursor:pointer; }
+ .qa-seg-group button.on { background:var(--qa-acc); color:#fff; }
+ .qa-tabbtn { margin-left:auto; border:1px solid var(--qa-line); background:transparent; color:var(--qa-ink); border-radius:8px; padding:3px 12px; font-size:12px; cursor:pointer; }
+ .qa-tabbtn.on { background:var(--qa-acc); color:#fff; border-color:var(--qa-acc); }
+ .qa-tabpanel { display:none; margin-top:10px; border:1px dashed var(--qa-line); border-radius:8px; padding:10px; }
+ .qa-tabpanel.on { display:block; }
+ .qa-tabpanel .qa-tab-entry { display:flex; gap:8px; align-items:baseline; padding:4px 0; }
+ .qa-tabpanel .qa-tab-entry button { border:1px solid var(--qa-acc); color:var(--qa-acc); background:transparent; border-radius:6px; padding:2px 10px; font-size:12px; cursor:pointer; }
+ .qa-tabpanel .qa-tab-note { color:var(--qa-sub); font-size:12px; }
+ .qa-stage { display:flex; justify-content:center; padding:28px 16px; }
+ .qa-framewrap { position:relative; }
+ .frame { position:relative; background:var(--qa-panel); border:1px solid var(--qa-line); border-radius:12px; overflow:hidden; box-shadow:0 8px 30px rgba(0,0,0,.08); }
+ .qa-size-badge { position:absolute; left:0; bottom:-22px; font-size:11px; color:var(--qa-sub); }
+ .qa-handle { position:absolute; z-index:9; }
+ .qa-handle-e { right:-6px; top:0; width:12px; height:100%; cursor:ew-resize; }
+ .qa-handle-s { bottom:-6px; left:0; height:12px; width:100%; cursor:ns-resize; }
+ .qa-handle-se { right:-8px; bottom:-8px; width:16px; height:16px; cursor:nwse-resize; }
+ `;
+ const styleEl = document.createElement('style');
+ styleEl.textContent = css;
+ document.head.appendChild(styleEl);
+
+ const chromeEl = document.createElement('div');
+ chromeEl.className = 'qa-chrome';
+ const head = document.createElement('div');
+ head.className = 'qa-head';
+ const title = document.createElement('span');
+ title.className = 'qa-title';
+ title.textContent = cfg.name;
+ head.appendChild(title);
+ if (cfg.pr) {
+ const badge = document.createElement('span');
+ badge.className = 'qa-badge';
+ badge.textContent = `PR #${cfg.pr}`;
+ head.appendChild(badge);
+ }
+ chromeEl.appendChild(head);
+ if (cfg.summary) {
+ const ul = document.createElement('ul');
+ ul.className = 'qa-summary';
+ for (const [k, label] of [['what', '做了什么'], ['how', '怎么做'], ['accept', '怎么验收']]) {
+ if (!cfg.summary[k]) continue;
+ const li = document.createElement('li');
+ const b = document.createElement('b');
+ b.textContent = `${label}:`;
+ li.appendChild(b);
+ li.appendChild(document.createTextNode(cfg.summary[k]));
+ ul.appendChild(li);
+ }
+ chromeEl.appendChild(ul);
+ }
+
+ const ctl = document.createElement('div');
+ ctl.className = 'qa-ctl';
+ const segButtons = {};
+ for (const key of PREF_KEYS) {
+ const dim = cfg.matrix?.[key];
+ if (!dim || !Array.isArray(dim.options) || dim.options.length === 0) continue;
+ const seg = document.createElement('div');
+ seg.className = 'qa-seg';
+ const label = document.createElement('span');
+ label.className = 'qa-seg-label';
+ label.textContent = dim.label ?? key;
+ seg.appendChild(label);
+ const group = document.createElement('div');
+ group.className = 'qa-seg-group';
+ for (const opt of dim.options) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.dataset.qaPref = `${key}:${opt.v}`;
+ btn.textContent = opt.label ?? opt.v;
+ btn.addEventListener('click', () => { prefs[key] = opt.v; persistPrefs(); render(); });
+ group.appendChild(btn);
+ (segButtons[key] ??= []).push({ v: opt.v, btn });
+ }
+ seg.appendChild(group);
+ ctl.appendChild(seg);
+ }
+
+ // 状态补齐 tab(via:null 状态的唯一取证入口;进 tab 必须写理由)
+ const tabStates = Array.isArray(cfg.tabStates) ? cfg.tabStates : [];
+ let tabOpen = false;
+ let tabBtn = null;
+ let tabPanel = null;
+ if (tabStates.length) {
+ tabBtn = document.createElement('button');
+ tabBtn.type = 'button';
+ tabBtn.className = 'qa-tabbtn';
+ tabBtn.dataset.qaStateTab = '';
+ tabBtn.textContent = '状态补齐';
+ tabBtn.addEventListener('click', () => { tabOpen = !tabOpen; render(); });
+ ctl.appendChild(tabBtn);
+
+ tabPanel = document.createElement('div');
+ tabPanel.className = 'qa-tabpanel';
+ for (const ts of tabStates) {
+ if (!(ts.id in cfg.states)) throw new Error(`qa-chrome: tabStates "${ts.id}" 不在 states 里`);
+ const row = document.createElement('div');
+ row.className = 'qa-tab-entry';
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.dataset.qaGoto = ts.id;
+ btn.textContent = ts.label ?? ts.id;
+ btn.addEventListener('click', () => { gotoState(ts.id); });
+ row.appendChild(btn);
+ const note = document.createElement('span');
+ note.className = 'qa-tab-note';
+ note.textContent = ts.note ?? '';
+ row.appendChild(note);
+ tabPanel.appendChild(row);
+ }
+ }
+ chromeEl.appendChild(ctl);
+ if (tabPanel) chromeEl.appendChild(tabPanel);
+ document.body.prepend(chromeEl);
+
+ // ---------- 帧 + 拉伸 ----------
+ const stage = document.createElement('div');
+ stage.className = 'qa-stage';
+ const frameWrap = document.createElement('div');
+ frameWrap.className = 'qa-framewrap';
+ const frame = document.createElement('div');
+ frame.className = 'frame';
+ frameWrap.appendChild(frame);
+ stage.appendChild(frameWrap);
+ document.body.appendChild(stage);
+
+ const ad = cfg.adaptive ?? null;
+ let frameW = ad?.initial?.w ?? ad?.min?.w ?? 960;
+ let frameH = ad?.initial?.h ?? ad?.min?.h ?? 640;
+ let sizeBadge = null;
+
+ // 拖拽手柄与 __qa.resize 走同一代码路径(setFrameSize),内部 clamp 到 adaptive.min
+ function setFrameSize(w, h) {
+ if (ad?.min) { w = Math.max(ad.min.w, w); h = Math.max(ad.min.h, h); }
+ frameW = Math.round(w);
+ frameH = Math.round(h);
+ frame.style.width = `${frameW}px`;
+ frame.style.height = `${frameH}px`;
+ if (sizeBadge) {
+ const band = typeof ad?.bandLabel === 'function' ? ` · ${ad.bandLabel(frameW, frameH)}` : '';
+ sizeBadge.textContent = `${frameW}×${frameH}${band}`;
+ }
+ render();
+ }
+ if (ad) {
+ sizeBadge = document.createElement('div');
+ sizeBadge.className = 'qa-size-badge';
+ frameWrap.appendChild(sizeBadge);
+ for (const [dirCls, dx, dy] of [['e', 1, 0], ['s', 0, 1], ['se', 1, 1]]) {
+ const handle = document.createElement('div');
+ handle.className = `qa-handle qa-handle-${dirCls}`;
+ handle.addEventListener('pointerdown', (e) => {
+ e.preventDefault();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startW = frameW;
+ const startH = frameH;
+ const move = (ev) => setFrameSize(startW + (ev.clientX - startX) * dx, startH + (ev.clientY - startY) * dy);
+ const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ });
+ frameWrap.appendChild(handle);
+ }
+ }
+
+ // ---------- 状态机 ----------
+ function gotoState(id) {
+ if (!(id in cfg.states)) throw new Error(`qa-chrome: unknown state "${id}"`);
+ state = id;
+ const onEnter = cfg.states[id]?.onEnter;
+ render();
+ if (typeof onEnter === 'function') onEnter(ctx());
+ }
+
+ function ctx() {
+ return { truth: TRUTH, rawTruth: RAW_TRUTH, prefs: { ...prefs }, state, frame, setState: gotoState, chrome: chromeEl };
+ }
+
+ // ---------- 渲染 ----------
+ function render() {
+ document.body.classList.toggle('qa-dark', prefs.mode === 'dark');
+ for (const key of Object.keys(segButtons)) {
+ for (const { v, btn } of segButtons[key]) btn.classList.toggle('on', prefs[key] === v);
+ }
+ if (tabBtn) tabBtn.classList.toggle('on', tabOpen);
+ if (tabPanel) tabPanel.classList.toggle('on', tabOpen);
+ cfg.renderApp(ctx());
+ }
+
+ // ---------- __qa API(demo 合约) ----------
+ window.__qa = {
+ current: () => state,
+ goto: (id) => { gotoState(id); },
+ prefs: () => ({ ...prefs }),
+ scale: () => (typeof cfg.scale === 'function' ? Number(cfg.scale({ ...prefs })) : 1),
+ resize: (w, h) => { setFrameSize(Number(w), Number(h)); },
+ metrics: (ids) => {
+ const fr = frame.getBoundingClientRect();
+ const probes = {};
+ for (const id of ids ?? []) {
+ const el = frame.querySelector(`[data-qa-probe="${id}"]`);
+ if (!el) { probes[id] = null; continue; }
+ const r = el.getBoundingClientRect();
+ probes[id] = { x: r.x - fr.x, y: r.y - fr.y, w: r.width, h: r.height };
+ }
+ return { frame: { w: fr.width, h: fr.height }, probes };
+ },
+ };
+
+ // ---------- 启动 ----------
+ setFrameSize(frameW, frameH);
+})();
+
+/* QA_CHROME_END */
+</script>
+</body>
+</html>
diff --git a/docs/design-previews/library-extradirs-quota/report.json b/docs/design-previews/library-extradirs-quota/report.json
new file mode 100644
index 0000000000..4c3eada053
--- /dev/null
+++ b/docs/design-previews/library-extradirs-quota/report.json
@@ -0,0 +1,190 @@
+{
+ "ok": true,
+ "partial": false,
+ "toolVersion": "qa-hifi-demo@2026-07-30-component-mode-r14",
+ "demo": "library-extradirs-quota",
+ "inputHashes": {
+ "spec.json": "7e26e8232399f37adb935965140f27ba32b4c08494a9a5dbb2b23497991036cd",
+ "truth.json": "59802b8927a9b3f40b54ae52d4cf244d92f63079cb982782bf21723ee9fa20fa",
+ "index.html": "1b3a36cb5d0c69bc92ca1eebfb7b88bc8a11b1ed2fa3e26f68e090a81c88567c",
+ "baselines": {
+ "declared": [],
+ "files": []
+ }
+ },
+ "statesResult": {
+ "total": 2,
+ "viaReachable": 2,
+ "tabOnly": 0
+ },
+ "truthStats": {
+ "fixtureLeaves": 0
+ },
+ "artifactRoot": "/var/folders/v9/vclyhlmn7c9cv6jb74z_7lyw0000gn/T/qa-hifi-out-lDPl4t",
+ "coverage": {
+ "cases": [
+ {
+ "id": "desk-zh-light",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "light",
+ "lang": "zh-CN"
+ },
+ "source": "verify.cases"
+ },
+ {
+ "id": "desk-en-dark",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "dark",
+ "lang": "en"
+ },
+ "source": "verify.cases"
+ }
+ ]
+ },
+ "gateA": {
+ "name": "真值一致",
+ "pass": true,
+ "detail": "",
+ "provenance": "required",
+ "extractorDrift": "none",
+ "refsOutsideSnapshot": "none",
+ "observeBinding": "bound",
+ "extractorSha256": "bf7827122b627f7676d838815a5b6ba880722f334d0ae8c2af7527e4839ed428",
+ "requestsOutsideSnapshot": "none",
+ "snapshotDrift": "none",
+ "snapshotManifest": {
+ "added": 0,
+ "removed": 0,
+ "changed": 0
+ },
+ "postRunHashRecheck": "ok"
+ },
+ "gateB": {
+ "name": "状态覆盖",
+ "pass": true,
+ "total": 4,
+ "passed": 4,
+ "failures": [],
+ "cases": [
+ {
+ "id": "desk-zh-light",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "light",
+ "lang": "zh-CN"
+ },
+ "passed": 2,
+ "total": 2,
+ "failures": []
+ },
+ {
+ "id": "desk-en-dark",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "dark",
+ "lang": "en"
+ },
+ "passed": 2,
+ "total": 2,
+ "failures": []
+ }
+ ],
+ "entryRenderProof": "n/a"
+ },
+ "gateC": {
+ "name": "交互鲁棒",
+ "pass": true,
+ "checks": [
+ {
+ "id": "no-clip",
+ "pass": true,
+ "failures": []
+ },
+ {
+ "id": "persistence",
+ "pass": true,
+ "failures": []
+ }
+ ],
+ "cases": [
+ {
+ "id": "desk-zh-light",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "light",
+ "lang": "zh-CN"
+ }
+ },
+ {
+ "id": "desk-en-dark",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "dark",
+ "lang": "en"
+ }
+ }
+ ]
+ },
+ "gateD": {
+ "name": "渲染绑定",
+ "pass": true,
+ "total": 4,
+ "passed": 4,
+ "failures": [],
+ "cases": [
+ {
+ "id": "desk-zh-light",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "light",
+ "lang": "zh-CN"
+ }
+ },
+ {
+ "id": "desk-en-dark",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "dark",
+ "lang": "en"
+ }
+ }
+ ]
+ },
+ "gateF": {
+ "name": "适配还原",
+ "pass": true,
+ "total": 0,
+ "passed": 0,
+ "failures": [],
+ "cases": [],
+ "detail": "spec.adaptive 未配置——窗口拉伸行为未验证"
+ },
+ "gateX": {
+ "name": "自定义门",
+ "pass": true,
+ "total": 0,
+ "passed": 0,
+ "failures": [],
+ "gates": [],
+ "detail": "未声明 customGates"
+ },
+ "generatedAt": "2026-09-01T11:43:08.856Z"
+}
diff --git a/docs/design-previews/library-extradirs-quota/spec.json b/docs/design-previews/library-extradirs-quota/spec.json
new file mode 100644
index 0000000000..3547fa59a6
--- /dev/null
+++ b/docs/design-previews/library-extradirs-quota/spec.json
@@ -0,0 +1,78 @@
+{
+ "meta": {
+ "name": "library-extradirs-quota",
+ "summary": {
+ "what": "composer 引用目录把 cindy-library: 当系统槽:不占用户 10 名额,显示「Mivo 作品库(只读)」且不可移除。",
+ "how": "ChatInput 配额走 countUserExtraDirs;AtMentionPanel 用 extraDirDisplayLabel,library 槽不画移除按钮。",
+ "accept": "未满员可添加;10 个用户目录 + library 槽时加号禁用且计数仍为 10;系统项文案来自源码。"
+ }
+ },
+ "matrix": {
+ "platforms": ["desktop"],
+ "regions": ["cn"],
+ "systems": ["mac"],
+ "themes": ["light", "dark"],
+ "langs": ["zh-CN", "en"]
+ },
+ "states": [
+ {
+ "id": "mixed",
+ "via": [{ "expect": "mixed" }]
+ },
+ {
+ "id": "full",
+ "via": [
+ { "click": "[data-qa-goto=full]" },
+ { "expect": "full" }
+ ]
+ }
+ ],
+ "verify": {
+ "cases": [
+ {
+ "id": "desk-zh-light",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "light",
+ "lang": "zh-CN"
+ }
+ },
+ {
+ "id": "desk-en-dark",
+ "prefs": {
+ "plat": "desktop",
+ "region": "cn",
+ "os": "mac",
+ "mode": "dark",
+ "lang": "en"
+ }
+ }
+ ],
+ "noClip": [".quota-title", ".dir-label", ".add-btn", ".count-badge"],
+ "persistence": {
+ "via": [{ "click": "[data-qa-pref='mode:dark']" }, { "click": "[data-qa-pref='lang:en']" }],
+ "expected": { "plat": "desktop", "region": "cn", "os": "mac", "mode": "dark", "lang": "en" },
+ "storageKey": "qa-hifi:library-extradirs-quota:prefs",
+ "reloads": 1,
+ "initialState": "mixed"
+ }
+ },
+ "bindings": [
+ {
+ "sel": ".quota-title",
+ "prop": "textContent",
+ "truth": "copy.zh-CN.sectionTitle",
+ "kind": "text",
+ "via": [{ "click": "[data-qa-pref='lang:zh-CN']" }]
+ },
+ {
+ "sel": ".quota-title",
+ "prop": "textContent",
+ "truth": "copy.en.sectionTitle",
+ "kind": "text",
+ "via": [{ "click": "[data-qa-pref='lang:en']" }]
+ }
+ ]
+}
diff --git a/docs/design-previews/library-extradirs-quota/truth.json b/docs/design-previews/library-extradirs-quota/truth.json
new file mode 100644
index 0000000000..68fe92fe24
--- /dev/null
+++ b/docs/design-previews/library-extradirs-quota/truth.json
@@ -0,0 +1,161 @@
+{
+ "copy": {
+ "en": {
+ "addReadOnly": {
+ "provenance": {
+ "hash": "2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b",
+ "locator": "extraDirs.addReadOnly",
+ "locatorKeyPath": "extraDirs.addReadOnly",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/en/common.json"
+ },
+ "value": "Add read-only directory…"
+ },
+ "atLimit": {
+ "provenance": {
+ "hash": "2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b",
+ "locator": "extraDirs.atLimit",
+ "locatorKeyPath": "extraDirs.atLimit",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/en/common.json"
+ },
+ "value": "Limit reached ({{max}})"
+ },
+ "empty": {
+ "provenance": {
+ "hash": "2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b",
+ "locator": "extraDirs.empty",
+ "locatorKeyPath": "extraDirs.empty",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/en/common.json"
+ },
+ "value": "No reference directories yet"
+ },
+ "sectionTitle": {
+ "provenance": {
+ "hash": "2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b",
+ "locator": "extraDirs.sectionTitle",
+ "locatorKeyPath": "extraDirs.sectionTitle",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/en/common.json"
+ },
+ "value": "Reference directories (read-only)"
+ },
+ "tooltipCount": {
+ "provenance": {
+ "hash": "2fa12aa8624821eb20f64306f27e407058634a5e90c53af3aa75c86d150c9c1b",
+ "locator": "extraDirs.tooltipCount",
+ "locatorKeyPath": "extraDirs.tooltipCount",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/en/common.json"
+ },
+ "value": "{{count}} additional directories"
+ }
+ },
+ "zh-CN": {
+ "addReadOnly": {
+ "provenance": {
+ "hash": "f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364",
+ "locator": "extraDirs.addReadOnly",
+ "locatorKeyPath": "extraDirs.addReadOnly",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"
+ },
+ "value": "添加只读目录…"
+ },
+ "atLimit": {
+ "provenance": {
+ "hash": "f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364",
+ "locator": "extraDirs.atLimit",
+ "locatorKeyPath": "extraDirs.atLimit",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"
+ },
+ "value": "已达上限 {{max}} 个"
+ },
+ "empty": {
+ "provenance": {
+ "hash": "f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364",
+ "locator": "extraDirs.empty",
+ "locatorKeyPath": "extraDirs.empty",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"
+ },
+ "value": "还没有引用目录"
+ },
+ "sectionTitle": {
+ "provenance": {
+ "hash": "f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364",
+ "locator": "extraDirs.sectionTitle",
+ "locatorKeyPath": "extraDirs.sectionTitle",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"
+ },
+ "value": "引用目录(只读)"
+ },
+ "tooltipCount": {
+ "provenance": {
+ "hash": "f62799baa971ce5f5b2f82a902344eb519040087ce7bcf8b5d153e57a8758364",
+ "locator": "extraDirs.tooltipCount",
+ "locatorKeyPath": "extraDirs.tooltipCount",
+ "source": "../../../apps/desktop/src/renderer/i18n/locales/zh-CN/common.json"
+ },
+ "value": "{{count}} 个附加目录"
+ }
+ }
+ },
+ "quota": {
+ "max": {
+ "provenance": {
+ "hash": "bb3226c65b8c7fab2c3c4a1daf6daba7dc26d5f1464ed24769e8f852a13f4a39",
+ "locator": "extraDirsValidator EXTRA_DIRS_MAX",
+ "locatorPattern": "export const EXTRA_DIRS_MAX = (\\d+)",
+ "source": "../../../apps/desktop/src/main/maker-ipc/extraDirsValidator.ts"
+ },
+ "value": "10"
+ },
+ "slotPrefix": {
+ "provenance": {
+ "hash": "8d491fec6e76e07a6a3f001e572e5af94726a41b2d06b72c0c33aea83297f51c",
+ "locator": "extraDirsActions LIBRARY_EXTRA_DIR_SLOT_PREFIX",
+ "locatorPattern": "export const LIBRARY_EXTRA_DIR_SLOT_PREFIX = '([^']+)'",
+ "source": "../../../apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts"
+ },
+ "value": "cindy-library:"
+ },
+ "systemLabel": {
+ "provenance": {
+ "hash": "8d491fec6e76e07a6a3f001e572e5af94726a41b2d06b72c0c33aea83297f51c",
+ "locator": "extraDirsActions extraDirDisplayLabel 系统项文案",
+ "locatorPattern": "isLibraryExtraDirSlot\\(dir\\) \\? '([^']+)'",
+ "source": "../../../apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts"
+ },
+ "value": "Mivo 作品库(只读)"
+ }
+ },
+ "wiring": {
+ "chatInputBadgeSites": {
+ "provenance": {
+ "hash": "019cfe7d536522b125dfcf3ce774e17520a495a432c47c420a55b7ef3a032e51",
+ "locator": "ChatInput ExtraDirsButton extraDirsCount 公式次数",
+ "source": "../../../apps/desktop/src/renderer/components/new-chat/ChatInput.tsx"
+ },
+ "value": 1
+ },
+ "chatInputQuotaSites": {
+ "provenance": {
+ "hash": "019cfe7d536522b125dfcf3ce774e17520a495a432c47c420a55b7ef3a032e51",
+ "locator": "ChatInput 加目录/可写目录两处配额公式次数",
+ "source": "../../../apps/desktop/src/renderer/components/new-chat/ChatInput.tsx"
+ },
+ "value": 2
+ },
+ "panelLabelSites": {
+ "provenance": {
+ "hash": "8626dd9995da248787a2189a5726b7a955224c50cca2911b9729454c98376067",
+ "locator": "AtMentionPanel extraDirDisplayLabel(p) 次数",
+ "source": "../../../apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx"
+ },
+ "value": 2
+ },
+ "panelNoRemoveSites": {
+ "provenance": {
+ "hash": "8626dd9995da248787a2189a5726b7a955224c50cca2911b9729454c98376067",
+ "locator": "AtMentionPanel library 槽不画移除按钮",
+ "source": "../../../apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx"
+ },
+ "value": 1
+ }
+ }
+}
diff --git a/docs/dev-rules/plugin-library-storage.md b/docs/dev-rules/plugin-library-storage.md
index 63094eac5f..6d4841432a 100644
--- a/docs/dev-rules/plugin-library-storage.md
+++ b/docs/dev-rules/plugin-library-storage.md
@@ -2,8 +2,8 @@
> **状态**:权威开发规则(authoritative)
> **读取时机**:新增或修改 library 能力(持久作品库)、binding / 目录选择、迁移、
-> 回收站删除、SQLite 语句门、面板 `/library/` 投影,或任何触碰
-> `libraries/` / `libraries-binding.json` / `libraries-trash/` 落盘布局的改动之前
+> 回收站删除、SQLite 语句门、面板 `/library/` 投影、会话级只读 extraDirs 注入,
+> 或任何触碰 `libraries/` / `libraries-binding.json` / `libraries-trash/` 落盘布局的改动之前
`library: true` 给插件一个**用户作品级**的持久存储区,与 `fs: true` 私有储物柜
(256MiB/2000 文件配额、卸载即回收)是两个语义:不受配额约束(只受磁盘保留
@@ -76,13 +76,24 @@ backups)对插件不可达——路径语法段首不许点,协议层天然
10. **known limitation(如实告知,不假装覆盖)**:Windows 上 binding 的文件
identity(st_ino)多为 0,「同路径删后重建」检不出(POSIX 可检出);映射
网络盘符检测需要 Win32 API,v1 只拒 UNC 路径。
+11. **Agent 只读 extraDirs(会话级,PR0)**:当前 Mivo 会话且 library 可用时,宿主把
+ library 根 realpath 静默写入该会话只读 extraDirs。只读、不弹 picker / 确认卡、
+ 不改权限档。library 专用槽不占用户 EXTRA_DIRS_MAX=10。回执 / 握手 / probe 禁绝对
+ 路径,相对键 `library:assets/<2>/<hash>/blob.<ext>`。路径不跨 turn 缓存。
+ confirmed 只认宿主 `librarySlot.writeCommit` ACK 的 64-hex sha256。仓内无
+ `libraryConfirmed.ts`(不存在),不得发明该文件。
+12. **切根像素与限额**:正本文件名是 `blob`(路径 `assets/<2>/<hash>/blob.<ext>`),
+ 不是 `<hash>.<ext>`。同目录 sidecar `meta.json` / `preview.webp` 禁止当像素。
+ 16MiB 是 library 分块阈值(更大走 writeBegin),cindy-media 单件 50MiB、配额
+ 1GiB。library 软水位 8GiB + 磁盘保留 1GiB + 5 万文件保险丝。
## Review 清单
-1. 路径/SQL 是否仍只经白名单与相对键?有没有新的绝对路径出口?(saveAs 成功 path 必须是库内相对键,不得把用户另存目标送进沙箱)
+1. 路径/SQL 是否仍只经白名单与相对键?有没有新的绝对路径出口?(saveAs 成功 path 必须是库内相对键,不得把用户另存目标送进沙箱;extraDirs 握手/回执/probe 同禁)
2. 失败路径是否保持「不可用 ≠ 空」「任一步失败原位原样」?
3. 生命周期挂点(uninstall/setEnabled/owner 边界)是否补了对应的 dispose?
4. i18n 五语与中文标点门禁、FORGE_GUIDE §4.10.1 是否同步?
+5. 会话级 extraDirs 是否只读、静默、专用槽不占 EXTRA_DIRS_MAX=10?confirmed 是否只认 writeCommit ACK,有没有发明 `libraryConfirmed.ts`?
最小验证入口:
diff --git a/docs/image-store-agent-readable-library-final.md b/docs/image-store-agent-readable-library-final.md
new file mode 100644
index 0000000000..a556d2adc3
--- /dev/null
+++ b/docs/image-store-agent-readable-library-final.md
@@ -0,0 +1,124 @@
+# Final:让 Mivo library 成为 Agent 能读的媒体库(Cindy 宿主侧决策)
+
+> 状态:PR0 契约正本(与 `docs/dev-rules/plugin-library-storage.md` 不变量 11–12 对齐)。**行号锚点以 main@6e114a35(2026-08-31 与远端同步后)为准。**
+> 输入:Sol 预检清单 + 三份 code-explorer + 源码逐行核对 + kirozeng 在 mivo-canvas-plugin#398 的评论(2026-08-31T14:01:17Z)+ 同步远端后全锚点复核。
+> 范围裁决(owner 2026-08-31):远程/SSH 不考虑;容量/压缩/进度条/30 天清理是后续;路径泄漏规避即可;授权必须自动、不弹卡。
+> kiro 表态(已收):红线 2 对 **library 已 confirmed** 的图放开像素直读;老路 cindy-media 保留备胎;Mivo 文档由他改。
+
+## 0. 一句话结论
+
+图只要进了 library 并且 **confirmed**,当前使用 Mivo 的那条任务里的 Agent(Claude / Codex / Pi 三个都要)就能用普通 Read 直接读像素,不再经过 cindy-media,且用户不需要点任何授权卡。主路径 = 宿主把 library 根静默写入该会话的只读 extraDirs;Claude 额外补一次「续聊式 Query 重建」。拷贝进工作目录不是最终答案。
+
+Kiro 选 A 之后,原先最大的红线冲突(「进画布只读节点、选中才送像素」)已经解开。G2 不翻盘。
+
+## 1. 核心决策(D1–D8)
+
+### D1 主方案 = G2 目录授权直读
+library 根作为会话级只读引用目录(extraDirs / readOnlyRoots)授权给当前任务。Agent 用原生 Read 读像素,节点/坐标仍走 Mivo 插件 MCP。
+- 否决 H2(opaque handle 宿主代读):三个 harness 都要新工具,路径泄漏没严重到值得换整条读图通道。
+- 否决「拷贝进会话工作目录」作为架构:每张图变副本,library 仍是局外人;只允许作 Claude 重建落地前的临时缺口,PR 里写明删除条件。
+- kiro 背书:今天 Agent 已经在用普通 Read 读 cindy-media blob 目录(Mivo `ghost.json:86`)。G2 只是把可读目录从 cindy-media 换成 library,不是新范式。
+
+### D2 三个 Agent 全支持,不挑单一环境
+- Codex:`setExtraDirs` 现成,下一 turn 生效(runtimeWorkspaceRoots 每 turn 现读,Sol VERIFIED)。**必须 app-server ≥ 0.144.6**;低版本 `setExtraDirs` 直接抛错(`codex/index.ts:12445-12449`,启动时 extraDirs 非空也会在 `4518` 炸掉)。PR-V 要闸版本,低版本走 cindy-media 备胎,不得假装授权成功。
+- Pi:`setExtraDirs` → 权限文件热更新,当轮生效;READONLY_BUILTINS(read/grep/find/ls)非凭证路径直接放行不弹卡。「能读」这件事上最顺。
+- Claude:`additionalDirectories` 在 Query 创建时冻结(`claude-code/index.ts:3543` 附近传入 sdkQuery),`setExtraDirs` 只改 closure(`6615`),普通 send() 不重建 → 中途授权对 SDK 无效。必须补 D3。能力表注释仍自称「下一 turn 立即生效, 真正的 hot-reload」(`862`),与冻结注释矛盾——PR-V 顺手改注释,不另开 PR。
+- 只挑一个 agent = 用户换模型后画布图忽明忽暗,否决。
+
+### D3 Claude 冻结的解法 = 续聊式 Query 重建
+授权/撤销 library 根后,若当前 Query 的目录名单与最新 closure 不一致,在下一次 send 前走 rewind 同款「close 旧 q → buildQuery({resumeSessionAt, forkSession:true})」续上同一场对话。禁止用 `fresh:true`(那是另开一场)。
+- 必测:SDK 在 resume 续聊时是否吃新 additionalDirectories;测不过退到从最新 checkpoint fork,仍是续聊。
+- 撤权侧已有:`auto-review-policy.ts:248-255` 把 Read 标 `requireWorkspaceBoundary: true`;区外读在 `shared/auto-review.ts:118-123` 升 `prompt-each-time`(tree 级区外根另有 `prompt` 分支,`127-128`)。**宿主审核门现读**,撤权当轮即在宿主面生效,即使 SDK allowlist 还冻着旧根。保留不动。
+- Pi 普通只读不经这条 adapter(bridge `READONLY_BUILTINS` 直放);Pi 的「能读」靠 extraDirs 进权限文件,不靠 auto-review 升档。
+- 会话恢复 / lazy-create 已从 SQLite extra_dirs 回灌 → 「先授权再开聊」三 harness 天然通,不需重建。
+
+### D4 授权自动化:静默写入,不弹卡,不动权限档
+- 事实核对(main@6e114a35,与远端同步后复核):`applyDirectoryGrants` **存在**,是 `register.ts:16615` 的局部函数(`SET_EXTRA_DIRS` / `SET_WRITABLE_DIRS` 两个 handler 在 `16705`/`16716` 调它),不是导出 API;`consumeWritableDirectoryPickerGrants` **存在**(`writableDirectoryPickerGrant.ts:55`),只服务 **writableDirs** 轴。extraDirs 轴没有确认卡,main 侧校验只有 `validateExtraDirs`:绝对路径 / 存在 / 是目录 / 非工作区子目录 / 上限 10。kiro 说这两个名字「全仓不存在」在同步后的远端 HEAD 上依然不成立,**不采纳**。
+- 所以:Mivo 会话打开且 library 可用时,宿主在 **main 进程内部**调用 `applyDirectoryGrants('extraDirs', …)` 注入 library realpath。合法、不需要新权限面、不弹卡。它今天只被 `SET_EXTRA_DIRS` IPC 包着——PR-V 要把这个局部函数抽成 main 可调的内部入口,供 library-ready / 迁根 / 卸载走,**不要再造一条平行授权通道**。
+- 明确否决「切 bypassPermissions / Full Access」:那是全盘放开,与「只读这一块作品库」量级完全不同。授权后 Ask/Auto 档区内读自动放行,本来就不弹卡,无需 bypass。
+- 边界:只授权给当前使用 Mivo 的会话;不授权可写;不广播到所有会话。
+- UI 呈现:运行时静默,但设置里的「额外目录」列表应把它显示为「Mivo 作品库(只读)」系统项,与用户自选目录区分,且不占用户的 10 个名额(需要专用槽位或豁免计数)。
+- 生命周期:library 迁移 / 插件卸载 / 换绑定必须同步改/撤该会话 extraDirs——extra_dirs 持久在 SQLite,不撤会钉死在旧路径。**迁根成功后旧根会被改名 `<old>.migrated-<ts>`(14 天 grace)**,extraDirs 不同步是立刻 ENOENT,不是「钉死旧路径还能读」。
+
+### D5 路径泄漏 = 规避,不重构
+- 插件 ghost_call 回执只用相对键 / 资源 id / 指纹,禁止出现 `/Users/.../libraries/<ghostId>/`(对齐 plugin-library-storage.md Review 清单第 1 条)。
+- **握手字段同样禁绝对路径**:Mivo `recordLibraryProbe()` 会把 open/status 回执原文落到 `diagnostics/library-probe.json`,插件侧没有脱敏。绝对根只由宿主注入 extraDirs + 宿主提示词给 Agent;插件继续不知道绝对根。
+- 已授权后插件回执的 available 引用改成相对键 `library:assets/<2>/<hash>/blob.<ext>`;未授权维持 `cindy-media://` + `deposit_media`。协议形状不动,只改值。
+- Pi 的 `piExtraDirsPrompt`(`pi/index.ts:1134`)现在把绝对目录逐条写进每个后续 user turn,改成不含绝对路径的能力描述(如「本任务可只读引用插件作品库」)。
+- Read 工具参数里出现真实路径不可避免,owner 已裁决可接受。落库 8KiB 截断维持现状。
+- reveal_path 不得当库根授权用(它是一次性单文件确认卡)。
+- **library 内路径不保证跨 turn 稳定**:Agent 每次从最新回执取相对键,不得缓存。归档接线后 `archive/` rename 会让热区失效。
+
+### D6 「无限扩容」的诚实口径
+本次只保证:摆脱 cindy-media 的 **1GiB 寄存配额** + 解锁 **SVG**(cindy-media 双重拒收 SVG)。cindy-media 单件上限是 **50MiB**(`GHOST_CINDY_DEPOSIT_MAX_BYTES`,2026-07-29 已从更低值上调),不是 16MiB。**16MiB 是 library 单次读写分块阈值**(更大走 writeBegin),两个数不能串。library 自身仍有 8GiB 软水位(仅告警)+ 磁盘保留 1GiB 硬拒 + 50,000 文件保险丝(libraryVault.ts DEFAULT_LIBRARY_LIMITS)。容量归用户,产品只提醒和兜底——进度条 / 压缩 / 30 天清理 / 快满拒写全部后续,不进本次 PR。
+
+### D7 两步变一步的口径
+- 对用户:成立。不再需要「选中 → 送进 cindy-media → Agent 才能看」。
+- 对 Agent 内部:仍是两类工具(插件 MCP 给节点/坐标,Read 给像素),少掉的是 cindy-media 中转那一跳。
+- **只对 confirmed 放开。** 判据只认宿主 `librarySlot.writeCommit` ACK 的 64-hex sha256(`library-write` / `writeCommit` 回执)。仓内无 `libraryConfirmed.ts`(不存在),不得发明该文件。`writing` / `unconfirmed` / `unavailable` 不放开。cindy-media 短指纹(16–128 位)不得升格。
+- 未进 library 的图、以及未 confirmed 的图,Agent 仍读不到——这是设计而非缺陷。
+- SVG:G2 的新增能力。直读原文字节,不再要求 cindy-media 加 `image/svg+xml`。定位必须经别名索引(节点是 `mivo-asset:<uuid>`,不含 hash)。**未授权时 SVG 没有 cindy-media 备胎**,维持读不到。
+
+### D8 范围排除(本次不做)
+远程/SSH extraDirs 透传;容量治理 UI;Mivo 插件侧接线(握手消费 / 回执形态 / 文档改口径由 kiro 在 PR3 字段定稿后做);H2 代读通道;全局(跨会话)library 可读。
+
+## 2. PR 拆分(Cindy 宿主仓,均未开工)
+
+| PR | 内容 | 痛点 | 关键约束 |
+|---|---|---|---|
+| PR0 契约 | 写明「library 根可作会话级只读目录」:只进当前 Mivo 会话、只读、插件沙箱仍零文件、回执/握手禁绝对路径、只认 `blob.*`、路径不跨 turn 缓存、confirmed 才放开 | 现在没有这句话,三个 harness 对着空气接线 | 文档改动,GO |
+| PR1 安全打开器 | libraryVault 读路径补 fileReadBytes.ts 同款 O_NOFOLLOW + bigint dev/ino 同 fd 复核 | 现 read() 无身份复核,直读把这条缝暴露给 Agent | 仅宿主内部用 |
+| PR2A/2B 改图/上传切根 | editImage / upload 消费口从 cindy-media hash 改认 library 正本 `assets/<hash前2>/<hash>/blob.<ext>`(固定文件名 `blob`,不是 `<hash>.<ext>`,也不是已否决的 canvases/ 前缀)。sidecar `meta.json`/`preview.webp` **禁止当像素** | 画布正本在 library,再经媒体库是双份 | 用 Mivo `BAD_RECEIPT` 公式当契约测试,别只对文档 |
+| PR3 插件可见握手 | **只挂 Library open/status 回执**(不选 app-context:它只消费 locale,3s 超时会让授权态未知成常态)。字段:「已授权只读作品库」布尔 + **库代次/身份**(迁根/bind/unbind 后失效本机 ACK)。谁问谁得(open/status 不带会话身份)。不回绝对路径 | Agent 不知道已授权,会继续往 cindy-media 送;换库后插件说 confirmed、当前根没文件 | 字段定稿前 Mivo 三道回执门禁不放宽 |
+| PR-V(本次主 PR) | ①Mivo 会话 + library ready → 宿主经抽出的 `applyDirectoryGrants` 静默注入 library realpath(专用槽位,不占用户 10 名额)②Codex/Pi 走现成 setExtraDirs;Codex 闸 ≥0.144.6 ③Claude 目录代际不一致时续聊重建 ④Pi prompt 去绝对路径 ⑤迁移/卸载/bind-unbind 同步改撤 extraDirs ⑥临时拷贝兜底带删除条件 ⑦修正 CC 自相矛盾注释 | 图在 library 里 Agent 看不见,是整个目标的最后一公里 | fresh:true 禁用于授权;**必须等 PR3 握手字段落地**,否则 Agent/插件行为不确定 |
+
+依赖:**PR0 → PR1 → {PR2A, PR2B} → PR3 → PR-V**。
+PR-V 不再与 PR3 并行。没有握手,授权了 Agent 也不知道该走哪条引用形态。
+
+切根会碰到的合法落点(PR0/PR2 契约必须列全):`assets/<2>/<hash>/blob.<ext>` 正本;同目录 sidecar 禁止当像素;`attachments/<canvasId>.json`;`index/asset-aliases.json`(非内容寻址节点定位正本的唯一途径);`families/`;`exports/`;`assets/_staging/`、`assets/_probe/`;契约预留但今天未接线的 `archive/`、`trash/`;`.cindy-library/` 宿主保留。
+
+## 3. 验收门槛(不过 = 没做成)
+
+1. Codex:app-server ≥ 0.144.6 时,会话中途注入 library 根,下一 turn Read library 内 confirmed 图成功;Ask/Auto 不弹卡;write 被拒。低版本不得假装授权成功,必须回 cindy-media 备胎。
+2. Pi:中途注入当轮 read 成功;后续 prompt 无 `/Users/.../libraries/`;结构化写进 library 根被拦(含 Full Access)。
+3. Claude:开聊即有根 → 首 turn 可读;中途授权 → 重建后下一 turn 可读且仍是同一场对话;fresh:true 路径未被用于授权。
+4. 静默性:全程无授权卡弹出;权限档保持用户原档(Ask/Auto/Full 均可用)。
+5. 迁移后旧根立刻失效(ENOENT)、新根生效;卸载后撤权;`library-bind` / `library-unbind` 后库代次变化,插件本机 ACK 失效。
+6. 插件 MCP 回执与 open/status 握手 grep 不到绝对路径。
+7. 无关会话读同一 library 文件 → 弹卡或拒绝。
+8. 用户已有 10 个自选 extraDirs 时,library 槽位不挤占、不被挤掉。
+9. 未 confirmed / writing / unavailable 的图不走直读;未授权时 cindy-media 老路仍可用;SVG 仅在已授权+confirmed+别名可解析时可读。
+
+## 4. 已识别风险与反转条件
+
+- R1 Claude SDK resume 续聊不吃新 additionalDirectories → 改用 checkpoint fork 续聊;仍不行才允许临时拷贝兜底,且不改回「拷贝为架构」。
+- R2 validateExtraDirs 的 redundant-subdir / 上限 10 与自动注入互踩 → PR-V 内做专用槽位或豁免逻辑,不改用户可见语义。
+- R3 Pi grep/find/ls 区外递归不经 host(已知行为差异)→ library 根本来就要授权成区内,非本次新增风险;记录不修。
+- R4 产品未来要求跨会话全局可读 → 授权面从会话级变全局,另立方案,不在本次范围。
+- R5 迁根后 extraDirs 不同步 → 立刻 ENOENT。PR-V 必须把 relocate 成功当作硬门槛同步改 extraDirs,验收第 5 条覆盖。
+- R6 `library-bind` / `unbind` 不迁移内容 + 插件 ACK 留在 IDB → 「插件说 confirmed、当前根没文件」。靠 PR3 库代次让插件失效 ACK;宿主不同步授权则直读 ENOENT。
+- R7 SVG 无 cindy-media 备胎 → 未授权/降级时 SVG 读不到是预期,不要当回归修。
+
+## 5. kiro #398 反馈收口(本轮裁决)
+
+| kiro 意见 | 裁决 | 理由 |
+|---|---|---|
+| 选 A:confirmed 图放开像素直读,老路保留 | **采纳,G2 不翻盘** | 最大红线冲突已解;未授权/旧宿主必须还能走 cindy-media |
+| 握手挂 Library open/status,不选 app-context | **采纳,改 D4/PR3** | app-context 只消费 locale,3s 超时会让授权态未知成常态 |
+| PR3 必须先于 PR-V | **采纳,改依赖** | 没有握手,Agent 不知道该读哪种引用 |
+| 回执/握手禁绝对路径(含 probe 落盘) | **采纳,写入 D5/PR0** | `recordLibraryProbe` 原文落盘,不能靠插件脱敏 |
+| 相对键 `library:assets/.../blob.<ext>` | **采纳** | 协议形状不动,只改值 |
+| 切根只认 `blob.*`,公式不是 `<hash>.<ext>` | **采纳** | 定稿正文原先已写对;实现别按 cindy-media 类推 |
+| 16MiB 不是 cindy-media 单件上限 | **采纳,改 D6** | 寄存单件 50MiB,配额 1GiB;16MiB 是 library 分块 |
+| Codex 闸 ≥0.144.6 | **采纳,写入 D2/验收** | `setExtraDirs` 低版本抛错 |
+| SVG 直读原文,关 #290 第 3 项 | **采纳进 D7**;关 issue 是 Mivo 侧 | 定位必须走别名;未授权无备胎 |
+| 迁根改名旧根 + bind/unbind 代次 | **采纳,写入 D4/PR3/R5/R6** | 今天只表现为补图失败,G2 会放大成 Agent ENOENT |
+| 路径不跨 turn 缓存 | **采纳,写入 D5/PR0** | 归档接线后会 rename |
+| confirmed 复用 `libraryConfirmed.ts` | **驳回发明文件;采纳 writeCommit ACK** | 仓内无 `libraryConfirmed.ts`(不存在),不得发明。confirmed 只认 `librarySlot.writeCommit` ACK 的 64-hex sha256 |
+| `applyDirectoryGrants` / picker 函数「全仓不存在」 | **驳回**(同步远端后复核仍在) | main@6e114a35:`register.ts:16615`、`writableDirectoryPickerGrant.ts:55` 都在;PR-V 抽局部函数给 main 调,不新写权限面 |
+| D3 引用 `auto-review-policy.ts:248-255` 不存在、档位是 `prompt` | **驳回行号/档位;部分采纳 Pi 差异** | CC 侧该文件 406 行,248-255 恰是 `requireWorkspaceBoundary: true` 那段;区外读升 `prompt-each-time`(shared/auto-review.ts:118-123)。kiro 说的 155 行文件是 **pi/auto-review-policy.ts**(现 164 行)——他对错了文件;Pi 普通读不经 adapter 这条采纳 |
+| CC 冻结行号 3355 / setExtraDirs 6415 / Pi prompt 963 | **驳回** | main@6e114a35 是 3543 / 6615 / 1134。行号会漂,以「锚点语句 + grep」为准;注释自相矛盾那条采纳 |
+
+同步复核补充(main@6e114a35):远端新进的 25 个 commit 无任何 extraDirs/library 组合改动,无人抢跑实现;`feat(permissions): 支持外部可写目录 (#3587)` 只动 writableDirs 轴,与本方案的只读轴不冲突,反而证明 `applyDirectoryGrants` 双轴入口是活跃维护面。
+
+PR0 契约已写入本文件与 plugin-library-storage.md。实现从 PR1 起;Mivo 红线文档由 kiro 改,宿主仓不代改。
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.ts
new file mode 100644
index 0000000000..c8274adb3d
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/__tests__/extraDirs-rebuild.test.ts
@@ -0,0 +1,205 @@
+/**
+ * Claude 中途注入 extraDirs 必须走 rewind 同款 resume+fork 续聊,禁止 fresh:true。
+ */
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentDeps } from '../../base-agent.js';
+import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
+import type { Logger } from '../../../interfaces/logger.js';
+import { sanitizeClaudeProjectKey } from '../claude-projects-fs.js';
+
+const sdkMock = vi.hoisted(() => ({
+ forkSession: vi.fn(),
+ query: vi.fn(),
+}));
+
+vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
+ forkSession: sdkMock.forkSession,
+ query: sdkMock.query,
+}));
+
+vi.mock('../../shared/image-resizer.js', () => ({
+ getDefaultImageResizer: () => ({
+ process: vi.fn(async (p: string) => p),
+ validateBuffer: vi.fn(async () => true),
+ }),
+}));
+
+import { ClaudeCodeAgent } from '../index.js';
+
+const tempDirs: string[] = [];
+const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;
+const originalIdleTimeout = process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS;
+
+function createLogger(): Logger {
+ const logger: Logger = {
+ trace() {},
+ debug() {},
+ info() {},
+ warn() {},
+ error() {},
+ fatal() {},
+ child() {
+ return logger;
+ },
+ };
+ return logger;
+}
+
+function createDeps(): AgentDeps {
+ const auth: AuthAdapter = {
+ async getState() {
+ return { authenticated: true };
+ },
+ async triggerLogin() {
+ return { authenticated: true };
+ },
+ async logout() {},
+ async getAuthEnv() {
+ return {};
+ },
+ };
+ return {
+ auth,
+ runtimeConfig: {},
+ binaryPath: process.execPath,
+ logger: createLogger(),
+ };
+}
+
+function createControlledStream() {
+ const items: unknown[] = [];
+ let waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null =
+ null;
+ let ended = false;
+ const pump = (): void => {
+ if (!waiter) return;
+ if (items.length > 0) {
+ const w = waiter;
+ waiter = null;
+ w.resolve({ done: false, value: items.shift() });
+ return;
+ }
+ if (ended) {
+ const w = waiter;
+ waiter = null;
+ w.resolve({ done: true, value: undefined });
+ }
+ };
+ return {
+ emit(msg: unknown): void {
+ items.push(msg);
+ pump();
+ },
+ end(): void {
+ ended = true;
+ pump();
+ },
+ [Symbol.asyncIterator]() {
+ return {
+ next: () =>
+ new Promise<IteratorResult<unknown>>((resolve, reject) => {
+ waiter = { resolve, reject };
+ pump();
+ }),
+ };
+ },
+ };
+}
+
+function createFakeQuery(stream = createControlledStream()) {
+ let closed = false;
+ return {
+ stream,
+ [Symbol.asyncIterator]: () => stream[Symbol.asyncIterator](),
+ setPermissionMode: vi.fn(async () => {
+ if (closed) throw new Error('ProcessTransport is not ready for writing');
+ }),
+ setModel: vi.fn(async () => {
+ if (closed) throw new Error('ProcessTransport is not ready for writing');
+ }),
+ applyFlagSettings: vi.fn(async () => {
+ if (closed) throw new Error('ProcessTransport is not ready for writing');
+ }),
+ interrupt: vi.fn(async () => {}),
+ send: vi.fn(async () => {}),
+ close: vi.fn(() => {
+ closed = true;
+ }),
+ rewindFiles: vi.fn(async () => ({
+ canRewind: true,
+ filesChanged: [],
+ insertions: 0,
+ deletions: 0,
+ })),
+ };
+}
+
+async function makeTempDir(): Promise<string> {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'maker-core-claude-extradirs-'));
+ tempDirs.push(dir);
+ return dir;
+}
+
+afterEach(async () => {
+ sdkMock.forkSession.mockReset();
+ sdkMock.query.mockReset();
+ if (originalClaudeConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
+ else process.env.CLAUDE_CONFIG_DIR = originalClaudeConfigDir;
+ if (originalIdleTimeout === undefined) delete process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS;
+ else process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS = originalIdleTimeout;
+ await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
+});
+
+describe('Claude extraDirs mid-session rebuild', () => {
+ it('setExtraDirs 后下一次 send 走 resume+fork,不用 fresh:true', async () => {
+ const configDir = await makeTempDir();
+ const workingDir = await makeTempDir();
+ process.env.CLAUDE_CONFIG_DIR = configDir;
+ process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS = '0';
+ const sdkSessionId = 'sdk-live-library';
+ const normalized = await fs.realpath(workingDir);
+ const projectDir = path.join(configDir, 'projects', sanitizeClaudeProjectKey(normalized));
+ await fs.mkdir(projectDir, { recursive: true });
+ await fs.writeFile(path.join(projectDir, `${sdkSessionId}.jsonl`), '{"type":"summary"}\n', 'utf8');
+
+ const firstQuery = createFakeQuery();
+ sdkMock.query.mockReturnValue(firstQuery);
+ const agent = new ClaudeCodeAgent(createDeps());
+ const handle = await agent.startSession({
+ sessionId: 'session-library-extradirs',
+ model: 'claude-opus-4-6',
+ workingDir,
+ resumeSessionId: sdkSessionId,
+ });
+
+ const libraryRoot = '/Users/example/libraries/xd-mivo';
+ await handle.setExtraDirs?.([libraryRoot]);
+
+ const secondQuery = createFakeQuery();
+ sdkMock.query.mockReturnValue(secondQuery);
+ await handle.send({ type: 'user', content: 'read the canvas asset' });
+
+ expect(sdkMock.query).toHaveBeenCalledTimes(2);
+ const rebuildArgs = sdkMock.query.mock.calls[1]?.[0] as {
+ options: Record<string, unknown>;
+ };
+ expect(rebuildArgs.options.forkSession).toBe(true);
+ expect(rebuildArgs.options.resume).toBe(sdkSessionId);
+ expect(rebuildArgs.options.additionalDirectories).toEqual([libraryRoot]);
+ expect(rebuildArgs.options.resumeSessionAt).toBeUndefined();
+ expect(rebuildArgs.options).not.toHaveProperty('fresh');
+ expect(firstQuery.close).toHaveBeenCalled();
+
+ const source = await fs.readFile(new URL('../index.ts', import.meta.url), 'utf8');
+ expect(source).toContain('pendingRewindTo = sdkSessionId');
+ expect(source).toContain('directoryGrantRebuild ? {} : { resumeSessionAt: resumeAt }');
+ expect(source).toContain('extraDirsCopyFallbackEnabled = false');
+
+ await handle.close();
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 8c3807e590..b1a8dfdf96 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -868,8 +868,8 @@ const CAPABILITIES: Capabilities = {
message: 'setMemory 影响下次 startSession; 当前 live session 需 close 重起才生效',
},
},
- // SDK 原生 additionalDirectories 字段, buildQuery turn-by-turn 装配 → 改完下一 turn
- // 立即生效, 真正的 hot-reload 体验。
+ // SDK additionalDirectories 在 Query 创建时冻结。setExtraDirs 只改 closure;
+ // 代际不一致时下一次 send 走 rewind 同款 resume+fork 重建,不用 fresh:true。
extraDirs: { supported: true },
writableDirs: { supported: true },
};
@@ -2488,6 +2488,12 @@ export class ClaudeCodeAgent extends BaseAgent {
let mutableExtraDirs: string[] = Array.isArray(opts.extraDirs) ? [...opts.extraDirs] : [];
let mutableWritableDirs: string[] = Array.isArray(opts.writableDirs) ? [...opts.writableDirs] : [];
let autoReviewDirectoryGeneration = 0;
+ let activeQueryDirectoryGeneration = autoReviewDirectoryGeneration;
+ let extraDirsRebuildAttempted = false;
+ // 拷贝进工作目录只允许作 Claude resume 不吃新 additionalDirectories 时的临时缺口。
+ // 默认关闭;启用条件:extraDirsRebuildAttempted 且下一 Query 代际仍落后。落地后
+ // library extraDirs 重建成功即删副本,不得把拷贝写成架构。
+ const extraDirsCopyFallbackEnabled = false;
let activeQueryHasDirectoryGrants = mutableExtraDirs.length > 0 || mutableWritableDirs.length > 0;
// ── Usage tracker (Stage 2 B') ──────────────────────────────────────────
@@ -3548,6 +3554,8 @@ export class ClaudeCodeAgent extends BaseAgent {
// 计划模式开启时 SDK 跑 plan; 读 mutable 值让 rewind/fork 重建拿到当前档而非创建时快照。
const additionalDirectories = [...new Set([...mutableExtraDirs, ...mutableWritableDirs])];
activeQueryHasDirectoryGrants = additionalDirectories.length > 0;
+ activeQueryDirectoryGeneration = autoReviewDirectoryGeneration;
+ extraDirsRebuildAttempted = false;
const sdkStartPermissionMode = extra?.permissionMode ?? effectiveSdkPermissionMode();
sdkInPlanMode = sdkStartPermissionMode === 'plan';
const query = sdkQuery({
@@ -5467,6 +5475,21 @@ export class ClaudeCodeAgent extends BaseAgent {
while (idleResumeRebuildGate) {
await idleResumeRebuildGate;
}
+ if (
+ activeQueryDirectoryGeneration !== autoReviewDirectoryGeneration
+ && !pendingRewindTo
+ && !activeBridgeRewindResumeAt
+ && sdkSessionId
+ ) {
+ pendingRewindTo = sdkSessionId;
+ extraDirsRebuildAttempted = true;
+ } else if (
+ extraDirsCopyFallbackEnabled
+ && extraDirsRebuildAttempted
+ && activeQueryDirectoryGeneration !== autoReviewDirectoryGeneration
+ ) {
+ log.warn('Claude extraDirs copy fallback is gated off; resume+fork rebuild remains the only path');
+ }
if (sendOpts?.signal?.aborted) {
throw new Error('Claude send cancelled before acceptance');
}
@@ -5608,9 +5631,11 @@ export class ClaudeCodeAgent extends BaseAgent {
if (!resumeAt) {
throw new Error('Claude rewind rebuild missing resume target');
}
+ const directoryGrantRebuild = pendingRewindTo === sdkSessionId;
log.debug('send ▶ pendingRewindTo detected — rebuilding sdkQuery with 三件套', {
- resumeSessionAt: resumeAt,
+ resumeSessionAt: directoryGrantRebuild ? undefined : resumeAt,
resumeSdkSid: sdkSessionId,
+ directoryGrantRebuild,
});
// 关键: 重建 abortController + inputQueue。老的两个在 q.close() 时已经污染
// (controller 进 aborted 状态, queue 的 generator 还在等 waiter), 复用会让
@@ -5639,8 +5664,18 @@ export class ClaudeCodeAgent extends BaseAgent {
// 不能再读包含 arm 态的 effectiveSdkPermissionMode()。否则 rewind 窗口里用户 arm
// 了下一 turn 的 plan,但当前排队行显式 planMode:false 时,新 Query 会先以 plan
// 起跑且 replay 看不到 diff,导致普通 turn 误跑成 plan turn (Codex review 3535801840)。
+ // extraDirs 中途授权复用这条重建,但不把 session id 当 resumeSessionAt。
+ // rewind 已在 commitRewindFiles 关过旧 q;directory grant 这条补 close。
+ if (directoryGrantRebuild) {
+ rewindTransitionQueries.add(q);
+ try {
+ q.close();
+ } catch (e) {
+ log.warn('rewind rebuild: q.close threw', { error: String(e) });
+ }
+ }
q = await buildQuery({
- resumeSessionAt: resumeAt,
+ ...(directoryGrantRebuild ? {} : { resumeSessionAt: resumeAt }),
forkSession: true,
permissionMode: snapSdkPermissionMode,
});
@@ -6643,6 +6678,7 @@ export class ClaudeCodeAgent extends BaseAgent {
log.debug('setExtraDirs', { from: mutableExtraDirs.length, to: newDirs.length });
mutableExtraDirs = [...newDirs];
autoReviewDirectoryGeneration++;
+ extraDirsRebuildAttempted = false;
},
async setWritableDirs(newDirs: string[]) {
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 11ebe7b50f..9d20a02b6b 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -3610,6 +3610,20 @@ describe('CodexAgent reference directories', () => {
extraDirs: ['/shared-old'],
})).rejects.toThrow('require app-server 0.144.6 or newer');
});
+
+ it('rejects mid-session extraDirs when the app-server is too old to apply them', async () => {
+ const agent = new CodexAgent(createDeps());
+ installFakeHost(agent, undefined, { userAgent: 'mock-codex/0.143.0' });
+ const handle = await agent.startSession({
+ sessionId: 'session-extra-dirs-old-server-mid',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await expect(handle.setExtraDirs?.(['/shared-old'])).rejects.toThrow(
+ 'require app-server 0.144.6 or newer',
+ );
+ await handle.close();
+ });
});
describe('CodexAgent.listCustomizations', () => {
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-extra-dirs-prompt.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-extra-dirs-prompt.test.ts
new file mode 100644
index 0000000000..4e40e42c1b
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-extra-dirs-prompt.test.ts
@@ -0,0 +1,24 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '../index.ts'), 'utf8');
+
+describe('piExtraDirsPrompt', () => {
+ it('后续 prompt 只写 basename,不出现 /Users/.../libraries/', () => {
+ const start = source.indexOf('function piExtraDirsPrompt(');
+ const end = source.indexOf('interface FailedPiStartupCleanup');
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ const fn = source.slice(start, end);
+ expect(fn).toContain('extraDirBasename');
+ expect(fn).toContain('This task can read the plugin library');
+ expect(fn).toContain('Do not modify them');
+ expect(fn).not.toContain('${dir}');
+ expect(fn).not.toContain('${readOnlyDirs');
+ expect(fn).not.toMatch(/\/Users\/.*\/libraries\//);
+ expect(fn).not.toContain('libraries/');
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index df74cdd8e1..ffeebdfd65 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -1157,21 +1157,27 @@ async function buildPiPrompt(message: UserMessage, opts?: { remote?: boolean }):
return { text: textParts.join(' ').trim(), images };
}
+function extraDirBasename(dir: string): string {
+ const trimmed = dir.replace(/[\\/]+$/, '');
+ const parts = trimmed.split(/[\\/]/);
+ return parts[parts.length - 1] || 'reference';
+}
+
function piExtraDirsPrompt(readOnlyDirs: readonly string[], writableDirs: readonly string[]): string {
const sections: string[] = [];
if (readOnlyDirs.length > 0) {
+ const labels = [...new Set(readOnlyDirs.map(extraDirBasename))];
sections.push(
'<cindy-extra-reference-directories>',
- 'The following absolute directories are available as read-only references. Do not modify them:',
- ...readOnlyDirs.map((dir) => `- ${dir}`),
+ 'This task can read the plugin library and extra references as read-only. Do not modify them:',
+ ...labels.map((label) => `- ${label}`),
'</cindy-extra-reference-directories>',
);
}
if (writableDirs.length > 0) {
sections.push(
'<cindy-extra-writable-directories>',
- 'The user explicitly allowed reading and writing inside these absolute directories:',
- ...writableDirs.map((dir) => `- ${dir}`),
+ 'The user explicitly allowed additional writable locations for this task. Stay inside those grants; do not write the plugin library root.',
'</cindy-extra-writable-directories>',
);
}