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。

fix(pi): 锁回收验证挪走内容 + 披露合并改磁盘优先(review P1×2)

Zhang Yunjina5f16fb5ce3e
diff --git a/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.ts b/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.ts
index 590c7dc406..91f23ee1e0 100644
--- a/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.ts
@@ -1,356 +1,398 @@
-import { createHash } from 'node:crypto';
-import { runInNewContext } from 'node:vm';
-import ts from 'typescript';
-import { describe, expect, it } from 'vitest';
-import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
-
-// 把 CindyMcpGateway 从 bridge 源码里切出来,在 VM 中用桩件驱动。断言都走真实入口
-// (register 后的 cindy_mcp_call_tool / cindy_mcp_list_tools),不直接调内部方法:披露门、
-// MCP 请求次数、落盘与重载都在同一条路径上被验证。
-//
-// 本 PR 只治「披露记录整片失效」:判定按 schema 指纹、按会话落盘。门本身保持上游的
-// 严格 fail closed —— 未披露的调用被拦下、不触达 MCP、不记账;模型显式 list_tools 后
-// 才算披露,随后放行。
-const source = CINDY_BRIDGE_EXTENSION_SOURCE;
-// 从工具名常量切到 CindyMcpGateway 类结束:register() 用到的常量与 helper 都在这段里,
-// 因此 register 后的 cindy_mcp_call_tool 走的是与生产同一条代码路径。
-const sliceStart = source.indexOf("const CINDY_MCP_LIST_TOOLS = 'cindy_mcp_list_tools'");
-const classStart = source.indexOf('class CindyMcpGateway {');
-const classEnd = source.indexOf('\n}\n', classStart) + 3;
-if (sliceStart < 0 || classStart < sliceStart || classEnd <= classStart) {
- throw new Error('CindyMcpGateway slice not found in bridge source');
-}
-const GATEWAY_SOURCE = source.slice(sliceStart, classEnd);
-
-type DisclosedFile = { version: number; entries: Record<string, string> };
-type ToolDescriptor = { name: string; description?: string; inputSchema?: unknown };
-
-const TOOL: ToolDescriptor = {
- name: 'send_to_worker',
- description: '向指定 worker 投递消息',
- inputSchema: { type: 'object', properties: { message: { type: 'string' } } },
-};
-const TOOL_CHANGED: ToolDescriptor = { ...TOOL, description: '向指定 worker 投递消息(v2)' };
-
-function fingerprint(tool: ToolDescriptor): string {
- const description = typeof tool.description === 'string' && tool.description.length > 0
- ? tool.description
- : 'MCP tool ' + tool.name + ' from cindy_orca';
- const inputSchema = tool.inputSchema && typeof tool.inputSchema === 'object'
- ? tool.inputSchema
- : { type: 'object', properties: {}, additionalProperties: true };
- return createHash('sha256').update(JSON.stringify([tool.name, description, inputSchema])).digest('hex');
-}
-
-function loadGateway(options: {
- stored?: DisclosedFile | null;
- writeFails?: boolean;
- /** 磁盘上已有内容(用于多实例合并场景),优先于 stored。 */
- onDisk?: DisclosedFile | null;
- /** 预先存在的锁文件持锁 pid;777 = 活进程,999 = 已退出进程。 */
- lockOwner?: number;
- /** process.kill(pid, 0) 抛出的错误码,默认 ESRCH。 */
- killErrorCode?: string;
- /** 模拟回收残留锁时被另一个实例抢先(rename 失败)。 */
- reclaimLostRace?: boolean;
-} = {}) {
- const writes: DisclosedFile[] = [];
- const renames: string[] = [];
- const warnings: string[] = [];
- const requests: unknown[] = [];
- const disk: { value: DisclosedFile | null } = { value: options.onDisk ?? options.stored ?? null };
- const alivePids = new Set<number>([4242, 777]);
- // 锁文件独立于披露文件,由外部(另一实例或崩溃残留)直接写入。
- // 锁文件独立于披露文件,由外部(另一实例或崩溃残留)直接写入;null = 不存在。
- const lockFile: { value: string | null } = { value: null };
- if (options.lockOwner !== undefined) lockFile.value = String(options.lockOwner);
- const externalWrite = (value: DisclosedFile) => { disk.value = value; };
- const reclaimed: string[] = [];
-
- const code = ts.transpileModule(
- `${GATEWAY_SOURCE}\n(globalThis as any).CindyMcpGateway = CindyMcpGateway;`,
- { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
- ).outputText;
-
- const sandbox: Record<string, unknown> = {
- console: { warn: (line: string) => warnings.push(line) },
- process: {
- pid: 4242,
- env: {
- CINDY_PI_PERMISSION_FILE: '/runtime/perm-s1.json',
- CINDY_PI_SESSION_ID: 's1',
- },
- kill: (pid: number, signal: number) => {
- if (alivePids.has(pid)) {
- if (signal !== 0) alivePids.delete(pid);
- return;
- }
- throw Object.assign(new Error('kill failed'), { code: options.killErrorCode ?? 'ESRCH' });
- },
- },
- path: {
- join: (...parts: string[]) => parts.join('/'),
- dirname: (file: string) => file.slice(0, file.lastIndexOf('/')),
- },
- readFileSync: (file: string) => {
- if (file.endsWith('.lock')) {
- if (lockFile.value === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
- return lockFile.value;
- }
- if (disk.value === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
- return JSON.stringify(disk.value);
- },
- writeFileSync: (file: string, body: string) => {
- if (options.writeFails) throw Object.assign(new Error('denied'), { code: 'EACCES' });
- if (file.endsWith('.lock')) {
- lockFile.value = body; // 记录持锁 pid
- return;
- }
- disk.value = JSON.parse(body) as DisclosedFile;
- writes.push(disk.value);
- },
- renameSync: (from: string, to: string) => {
- if (options.reclaimLostRace && from.endsWith('.lock')) {
- // 模拟另一个实例先把残留锁回收并重建了新锁:本实例的 rename 失败。
- throw Object.assign(new Error('lock gone'), { code: 'ENOENT' });
- }
- if (from.endsWith('.lock')) lockFile.value = null;
- renames.push(`${from} -> ${to}`);
- },
- rmSync: (file: string) => {
- if (file.endsWith('.lock') && !file.includes('.stale-')) lockFile.value = null;
- reclaimed.push(file);
- },
- openSync: (file: string, flags: string) => {
- if (flags === 'wx' && lockFile.value !== null) {
- throw Object.assign(new Error('locked'), { code: 'EEXIST' });
- }
- if (flags === 'wx') lockFile.value = '';
- return 7;
- },
- closeSync: () => undefined,
- createHash,
- fetch: async (_url: string, init: { body: string } & Record<string, unknown>) => {
- requests.push(JSON.parse(init.body));
- return new Response(
- JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text: 'delivered' }] } }),
- { status: 200, headers: { 'content-type': 'application/json' } },
- );
- },
- Response: globalThis.Response,
- URL,
- Headers,
- AbortController,
- TextDecoder,
- setTimeout,
- clearTimeout,
- };
- runInNewContext(code, sandbox);
-
- const Gateway = sandbox.CindyMcpGateway as new () => {
- add(server: string, client: unknown, tools: ToolDescriptor[]): void;
- register(pi: unknown, options?: unknown): void;
- resolveCall(input: unknown): unknown;
- };
- const gateway = new Gateway();
-
- // executeResolvedCall 走 tool.client.request;用最小 client 桩替代 HTTP 层,
- // 每次真实调用都会在 requests 里留下一条,正好用来断言“恰好执行一次”。
- const httpClient = {
- request: async (_method: string, params: { name: string; arguments: unknown }) => {
- requests.push(params);
- return { content: [{ type: 'text', text: 'delivered' }] };
- },
- };
- gateway.add('cindy_orca', httpClient, [TOOL]);
-
- const registered: { name: string; execute: (id: string, params: unknown) => Promise<unknown> }[] = [];
- gateway.register({ registerTool: (tool: { name: string; execute: unknown }) => registered.push(tool as never) });
- const callTool = registered.find((t) => t.name === 'cindy_mcp_call_tool');
- const listTools = registered.find((t) => t.name === 'cindy_mcp_list_tools');
- if (!callTool || !listTools) throw new Error('gateway tools not registered');
-
- return {
- gateway,
- httpClient,
- externalWrite,
- reclaimed,
- writes,
- renames,
- warnings,
- requests,
- disk,
- callRaw: (args: Record<string, unknown> = { message: 'hi' }) =>
- callTool.execute('call-1', { server: 'cindy_orca', tool: 'send_to_worker', args }),
- // 默认模拟真实模型的两步:第一次被路标拦下 → 显式 list_tools 查完 schema → 重发。
- // 只有验证拦截语义的用例用 callRaw;其他错误(如 zod 拒参)原样抛出,不在此处吞掉。
- call: async (args: Record<string, unknown> = { message: 'hi' }) => {
- const input = { server: 'cindy_orca', tool: 'send_to_worker', args };
- try {
- return await callTool.execute('call-1', input);
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- if (!message.includes('Inspect this tool before execution')) throw error;
- await listTools.execute('list-1', { server: 'cindy_orca', tool: 'send_to_worker' });
- return callTool.execute('call-2', input);
- }
- },
- list: () => listTools.execute('list-1', { server: 'cindy_orca', tool: 'send_to_worker' }),
- };
-}
-
-describe('MCP gateway schema disclosure', () => {
- it('blocks the first uninspected call without touching MCP, and discloses only after list_tools', async () => {
- const { gateway, callRaw, list, requests, warnings, writes, disk } = loadGateway();
- const resolved = gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }) as { tool: unknown };
- // 事前未披露
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(resolved)).toBe(false);
-
- // 第一次:被拦下,一个 MCP 请求都不该发出去;回执必须指名要查的 server/tool
- const first = await callRaw().then(() => null, (error: Error) => error);
- expect(first?.message).toContain('Inspect this tool before execution');
- expect(first?.message).toContain('"server":"cindy_orca"');
- expect(first?.message).toContain('"tool":"send_to_worker"');
- expect(requests).toHaveLength(0);
- // 门保持 fail closed:被拦的那次不记账、不落盘
- expect(writes).toHaveLength(0);
- expect(disk.value).toBeNull();
-
- // 显式查完 schema 才算披露:此时记账并落盘
- await list();
- expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
- expect(writes).toHaveLength(1);
-
- // 之后重发:放行并执行成功
- const result = await callRaw();
- expect(requests).toHaveLength(1);
- expect(result).toMatchObject({ content: [{ type: 'text', text: 'delivered' }] });
- expect(writes).toHaveLength(1);
- });
-
- it('reuses a persisted disclosure after a reload when the schema is unchanged', async () => {
- const stored: DisclosedFile = {
- version: 1,
- entries: { 'cindy_orca\u0000send_to_worker': fingerprint(TOOL) },
- };
- const { gateway, call, requests, warnings, writes } = loadGateway({ stored });
-
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
- await call();
-
- expect(requests).toHaveLength(1);
- expect(warnings).toHaveLength(0);
- expect(writes).toHaveLength(0);
- });
-
- it('re-arms the gate when the tool schema actually changes', async () => {
- const stored: DisclosedFile = {
- version: 1,
- entries: { 'cindy_orca\u0000send_to_worker': fingerprint(TOOL) },
- };
- const { gateway, httpClient, callRaw, list, requests, warnings, disk } = loadGateway({ stored });
-
- // 同一会话内工具描述变化(MCP 重连后拿到新 schema)→ 指纹失配 → 门重新武装
- gateway.add('cindy_orca', httpClient, [TOOL_CHANGED]);
- const changed = gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }) as { tool: unknown };
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(changed)).toBe(false);
-
- const first = await callRaw().then(() => null, (error: Error) => error);
- expect(first?.message).toContain('"tool":"send_to_worker"');
- expect(requests).toHaveLength(0);
-
- // 重新查一次新 schema 才重新披露
- await list();
- expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL_CHANGED));
- await callRaw();
- expect(requests).toHaveLength(1);
- });
-
- it('merges a record another instance wrote after startup instead of overwriting it', async () => {
- // 关键:另一实例的写入发生在本实例**构造之后**,本实例内存里没有这条记录,
- // 因此只有落盘时的读-合并才能保住它(删掉合并循环这条测试就会红)。
- const { call, disk, renames, externalWrite } = loadGateway();
- const otherKey = 'cindy_other\u0000other_tool';
- const otherFingerprint = fingerprint({ name: 'other_tool', description: '别的工具' });
- externalWrite({ version: 1, entries: { [otherKey]: otherFingerprint } });
-
- await call();
-
- expect(disk.value?.entries[otherKey]).toBe(otherFingerprint);
- expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
- // 原子替换:先写 tmp 再 rename
- expect(renames).toHaveLength(1);
- expect(renames[0]).toContain('.tmp');
- });
-
- it('recovers a lock left behind by a crashed instance and persists', async () => {
- // 持锁 pid 999 已退出 → 锁必须被回收,本进程仍能落盘。
- const { call, disk } = loadGateway({ lockOwner: 999 });
- await call();
- expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
- });
-
- it('skips persisting while another live instance holds the lock, without breaking the gate', async () => {
- const { gateway, call, requests, disk } = loadGateway({ lockOwner: 777 });
- await call();
- expect(requests).toHaveLength(1);
- expect(disk.value).toBeNull();
- // 本进程内存里的披露已生效
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
- });
-
- it('keeps a stale lock when the liveness probe fails for a reason other than ESRCH', async () => {
- // EINVAL 等非 ESRCH 错误不能证明进程已退出 → 不回收,跳过落盘但不挡工具执行。
- const { gateway, call, requests, disk } = loadGateway({ lockOwner: 999, killErrorCode: 'EINVAL' });
- await call();
- expect(requests).toHaveLength(1);
- expect(disk.value).toBeNull();
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
- });
-
- it('skips persisting when another instance reclaimed the stale lock first', async () => {
- // 回收必须与重新加锁互斥:rename 失败说明锁已被别人收走/重建,本实例直接放弃,
- // 不能继续 rmSync(那会删掉对方刚建的锁,两边都进写入路径互相覆盖记录)。
- const { call, requests, disk, reclaimed } = loadGateway({ lockOwner: 999, reclaimLostRace: true });
- await call();
- expect(requests).toHaveLength(1);
- expect(disk.value).toBeNull();
- expect(reclaimed.some((file) => file.endsWith('.lock') && !file.includes('.stale-'))).toBe(false);
- });
-
- it('treats a missing or corrupt disclosure file as undisclosed and still executes', async () => {
- for (const stored of [
- null,
- { version: 1, entries: { 'cindy_orca\u0000send_to_worker': 'not-a-hash' } },
- ] as (DisclosedFile | null)[]) {
- const { gateway, call, requests } = loadGateway({ stored });
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(false);
- await call();
- expect(requests).toHaveLength(1);
- }
- });
-
- it('keeps the in-memory gate working when the disclosure file cannot be written', async () => {
- const { gateway, call, requests, writes } = loadGateway({ writeFails: true });
- await call();
- expect(requests).toHaveLength(1);
- expect(writes).toHaveLength(0);
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
- });
-
- it('records disclosure through cindy_mcp_list_tools too', async () => {
- const { gateway, list, requests, disk } = loadGateway();
- await list();
- expect(requests).toHaveLength(0);
- expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
- expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
- .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
- });
+import { createHash } from 'node:crypto';
+import { runInNewContext } from 'node:vm';
+import ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
+
+// 把 CindyMcpGateway 从 bridge 源码里切出来,在 VM 中用桩件驱动。断言都走真实入口
+// (register 后的 cindy_mcp_call_tool / cindy_mcp_list_tools),不直接调内部方法:披露门、
+// MCP 请求次数、落盘与重载都在同一条路径上被验证。
+//
+// 本 PR 只治「披露记录整片失效」:判定按 schema 指纹、按会话落盘。门本身保持上游的
+// 严格 fail closed —— 未披露的调用被拦下、不触达 MCP、不记账;模型显式 list_tools 后
+// 才算披露,随后放行。
+const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+// 从工具名常量切到 CindyMcpGateway 类结束:register() 用到的常量与 helper 都在这段里,
+// 因此 register 后的 cindy_mcp_call_tool 走的是与生产同一条代码路径。
+const sliceStart = source.indexOf("const CINDY_MCP_LIST_TOOLS = 'cindy_mcp_list_tools'");
+const classStart = source.indexOf('class CindyMcpGateway {');
+const classEnd = source.indexOf('\n}\n', classStart) + 3;
+if (sliceStart < 0 || classStart < sliceStart || classEnd <= classStart) {
+ throw new Error('CindyMcpGateway slice not found in bridge source');
+}
+const GATEWAY_SOURCE = source.slice(sliceStart, classEnd);
+
+type DisclosedFile = { version: number; entries: Record<string, string> };
+type ToolDescriptor = { name: string; description?: string; inputSchema?: unknown };
+
+const TOOL: ToolDescriptor = {
+ name: 'send_to_worker',
+ description: '向指定 worker 投递消息',
+ inputSchema: { type: 'object', properties: { message: { type: 'string' } } },
+};
+const TOOL_CHANGED: ToolDescriptor = { ...TOOL, description: '向指定 worker 投递消息(v2)' };
+
+function fingerprint(tool: ToolDescriptor): string {
+ const description = typeof tool.description === 'string' && tool.description.length > 0
+ ? tool.description
+ : 'MCP tool ' + tool.name + ' from cindy_orca';
+ const inputSchema = tool.inputSchema && typeof tool.inputSchema === 'object'
+ ? tool.inputSchema
+ : { type: 'object', properties: {}, additionalProperties: true };
+ return createHash('sha256').update(JSON.stringify([tool.name, description, inputSchema])).digest('hex');
+}
+
+function loadGateway(options: {
+ stored?: DisclosedFile | null;
+ writeFails?: boolean;
+ /** 磁盘上已有内容(用于多实例合并场景),优先于 stored。 */
+ onDisk?: DisclosedFile | null;
+ /** 预先存在的锁文件持锁 pid;777 = 活进程,999 = 已退出进程。 */
+ lockOwner?: number;
+ /** process.kill(pid, 0) 抛出的错误码,默认 ESRCH。 */
+ killErrorCode?: string;
+ /** 模拟回收残留锁时被另一个实例抢先(rename 失败)。 */
+ reclaimLostRace?: boolean;
+ /** 模拟挪走的残留锁内容其实是另一个实例重建的活锁(pid)。 */
+ reclaimReplacesWith?: number;
+} = {}) {
+ const writes: DisclosedFile[] = [];
+ const renames: string[] = [];
+ const warnings: string[] = [];
+ const requests: unknown[] = [];
+ const disk: { value: DisclosedFile | null } = { value: options.onDisk ?? options.stored ?? null };
+ const alivePids = new Set<number>([4242, 777]);
+ // 锁文件独立于披露文件,由外部(另一实例或崩溃残留)直接写入。
+ // 锁文件独立于披露文件,由外部(另一实例或崩溃残留)直接写入;null = 不存在。
+ const lockFile: { value: string | null } = { value: null };
+ if (options.lockOwner !== undefined) lockFile.value = String(options.lockOwner);
+ // stale 回收槽:rename(lock→stale) 时锁内容搬到这里;内容可为外部预置(模拟
+ // 「旧锁已被另一个实例换成活进程的新锁,但本实例的 rename 仍成功」)。
+ const staleFile: { value: string | null } = { value: options.staleContent ?? null };
+ const externalWrite = (value: DisclosedFile) => { disk.value = value; };
+ const reclaimed: string[] = [];
+
+ const code = ts.transpileModule(
+ `${GATEWAY_SOURCE}\n(globalThis as any).CindyMcpGateway = CindyMcpGateway;`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+
+ const sandbox: Record<string, unknown> = {
+ console: { warn: (line: string) => warnings.push(line) },
+ process: {
+ pid: 4242,
+ env: {
+ CINDY_PI_PERMISSION_FILE: '/runtime/perm-s1.json',
+ CINDY_PI_SESSION_ID: 's1',
+ },
+ kill: (pid: number, signal: number) => {
+ if (alivePids.has(pid)) {
+ if (signal !== 0) alivePids.delete(pid);
+ return;
+ }
+ throw Object.assign(new Error('kill failed'), { code: options.killErrorCode ?? 'ESRCH' });
+ },
+ },
+ path: {
+ join: (...parts: string[]) => parts.join('/'),
+ dirname: (file: string) => file.slice(0, file.lastIndexOf('/')),
+ },
+ readFileSync: (file: string) => {
+ if (file.includes('.stale-')) {
+ if (staleFile.value === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ return staleFile.value;
+ }
+ if (file.endsWith('.lock')) {
+ if (lockFile.value === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ return lockFile.value;
+ }
+ if (disk.value === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ return JSON.stringify(disk.value);
+ },
+ writeFileSync: (file: string, body: string) => {
+ if (options.writeFails) throw Object.assign(new Error('denied'), { code: 'EACCES' });
+ if (file.endsWith('.lock')) {
+ lockFile.value = body; // 记录持锁 pid
+ return;
+ }
+ disk.value = JSON.parse(body) as DisclosedFile;
+ writes.push(disk.value);
+ },
+ renameSync: (from: string, to: string) => {
+ if (options.reclaimLostRace && from.endsWith('.lock')) {
+ // 模拟另一个实例先把残留锁回收并重建了新锁:本实例的 rename 失败。
+ throw Object.assign(new Error('lock gone'), { code: 'ENOENT' });
+ }
+ if (from.endsWith('.lock') && to.includes('.stale-')) {
+ // 回收挪动:锁内容搬进回收槽;外部可同时预置 reclaimReplacesWith,模拟
+ // 「挪走的其实是另一个实例刚重建的活锁」(内容与读到的死 pid 不一致)。
+ staleFile.value = options.reclaimReplacesWith ?? lockFile.value;
+ lockFile.value = null;
+ } else if (from.endsWith('.stale-') && to.endsWith('.lock')) {
+ // 放回:回收槽内容回到锁路径。
+ lockFile.value = staleFile.value;
+ staleFile.value = null;
+ }
+ renames.push(`${from} -> ${to}`);
+ },
+ rmSync: (file: string) => {
+ if (file.includes('.stale-')) staleFile.value = null;
+ else if (file.endsWith('.lock')) lockFile.value = null;
+ reclaimed.push(file);
+ },
+ openSync: (file: string, flags: string) => {
+ if (flags === 'wx' && lockFile.value !== null) {
+ throw Object.assign(new Error('locked'), { code: 'EEXIST' });
+ }
+ if (flags === 'wx') lockFile.value = '';
+ return 7;
+ },
+ closeSync: () => undefined,
+ createHash,
+ fetch: async (_url: string, init: { body: string } & Record<string, unknown>) => {
+ requests.push(JSON.parse(init.body));
+ return new Response(
+ JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text: 'delivered' }] } }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ );
+ },
+ Response: globalThis.Response,
+ URL,
+ Headers,
+ AbortController,
+ TextDecoder,
+ setTimeout,
+ clearTimeout,
+ };
+ runInNewContext(code, sandbox);
+
+ const Gateway = sandbox.CindyMcpGateway as new () => {
+ add(server: string, client: unknown, tools: ToolDescriptor[]): void;
+ register(pi: unknown, options?: unknown): void;
+ resolveCall(input: unknown): unknown;
+ };
+ const gateway = new Gateway();
+
+ // executeResolvedCall 走 tool.client.request;用最小 client 桩替代 HTTP 层,
+ // 每次真实调用都会在 requests 里留下一条,正好用来断言“恰好执行一次”。
+ const httpClient = {
+ request: async (_method: string, params: { name: string; arguments: unknown }) => {
+ requests.push(params);
+ return { content: [{ type: 'text', text: 'delivered' }] };
+ },
+ };
+ gateway.add('cindy_orca', httpClient, [TOOL]);
+
+ const registered: { name: string; execute: (id: string, params: unknown) => Promise<unknown> }[] = [];
+ gateway.register({ registerTool: (tool: { name: string; execute: unknown }) => registered.push(tool as never) });
+ const callTool = registered.find((t) => t.name === 'cindy_mcp_call_tool');
+ const listTools = registered.find((t) => t.name === 'cindy_mcp_list_tools');
+ if (!callTool || !listTools) throw new Error('gateway tools not registered');
+
+ return {
+ gateway,
+ httpClient,
+ externalWrite,
+ reclaimed,
+ writes,
+ renames,
+ warnings,
+ requests,
+ disk,
+ callRaw: (args: Record<string, unknown> = { message: 'hi' }) =>
+ callTool.execute('call-1', { server: 'cindy_orca', tool: 'send_to_worker', args }),
+ // 默认模拟真实模型的两步:第一次被路标拦下 → 显式 list_tools 查完 schema → 重发。
+ // 只有验证拦截语义的用例用 callRaw;其他错误(如 zod 拒参)原样抛出,不在此处吞掉。
+ call: async (args: Record<string, unknown> = { message: 'hi' }) => {
+ const input = { server: 'cindy_orca', tool: 'send_to_worker', args };
+ try {
+ return await callTool.execute('call-1', input);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (!message.includes('Inspect this tool before execution')) throw error;
+ await listTools.execute('list-1', { server: 'cindy_orca', tool: 'send_to_worker' });
+ return callTool.execute('call-2', input);
+ }
+ },
+ list: () => listTools.execute('list-1', { server: 'cindy_orca', tool: 'send_to_worker' }),
+ };
+}
+
+describe('MCP gateway schema disclosure', () => {
+ it('blocks the first uninspected call without touching MCP, and discloses only after list_tools', async () => {
+ const { gateway, callRaw, list, requests, warnings, writes, disk } = loadGateway();
+ const resolved = gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }) as { tool: unknown };
+ // 事前未披露
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(resolved)).toBe(false);
+
+ // 第一次:被拦下,一个 MCP 请求都不该发出去;回执必须指名要查的 server/tool
+ const first = await callRaw().then(() => null, (error: Error) => error);
+ expect(first?.message).toContain('Inspect this tool before execution');
+ expect(first?.message).toContain('"server":"cindy_orca"');
+ expect(first?.message).toContain('"tool":"send_to_worker"');
+ expect(requests).toHaveLength(0);
+ // 门保持 fail closed:被拦的那次不记账、不落盘
+ expect(writes).toHaveLength(0);
+ expect(disk.value).toBeNull();
+
+ // 显式查完 schema 才算披露:此时记账并落盘
+ await list();
+ expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
+ expect(writes).toHaveLength(1);
+
+ // 之后重发:放行并执行成功
+ const result = await callRaw();
+ expect(requests).toHaveLength(1);
+ expect(result).toMatchObject({ content: [{ type: 'text', text: 'delivered' }] });
+ expect(writes).toHaveLength(1);
+ });
+
+ it('reuses a persisted disclosure after a reload when the schema is unchanged', async () => {
+ const stored: DisclosedFile = {
+ version: 1,
+ entries: { 'cindy_orca\u0000send_to_worker': fingerprint(TOOL) },
+ };
+ const { gateway, call, requests, warnings, writes } = loadGateway({ stored });
+
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
+ await call();
+
+ expect(requests).toHaveLength(1);
+ expect(warnings).toHaveLength(0);
+ expect(writes).toHaveLength(0);
+ });
+
+ it('re-arms the gate when the tool schema actually changes', async () => {
+ const stored: DisclosedFile = {
+ version: 1,
+ entries: { 'cindy_orca\u0000send_to_worker': fingerprint(TOOL) },
+ };
+ const { gateway, httpClient, callRaw, list, requests, warnings, disk } = loadGateway({ stored });
+
+ // 同一会话内工具描述变化(MCP 重连后拿到新 schema)→ 指纹失配 → 门重新武装
+ gateway.add('cindy_orca', httpClient, [TOOL_CHANGED]);
+ const changed = gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }) as { tool: unknown };
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(changed)).toBe(false);
+
+ const first = await callRaw().then(() => null, (error: Error) => error);
+ expect(first?.message).toContain('"tool":"send_to_worker"');
+ expect(requests).toHaveLength(0);
+
+ // 重新查一次新 schema 才重新披露
+ await list();
+ expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL_CHANGED));
+ await callRaw();
+ expect(requests).toHaveLength(1);
+ });
+
+ it('merges a record another instance wrote after startup instead of overwriting it', async () => {
+ // 关键:另一实例的写入发生在本实例**构造之后**,本实例内存里没有这条记录,
+ // 因此只有落盘时的读-合并才能保住它(删掉合并循环这条测试就会红)。
+ const { call, disk, renames, externalWrite } = loadGateway();
+ const otherKey = 'cindy_other\u0000other_tool';
+ const otherFingerprint = fingerprint({ name: 'other_tool', description: '别的工具' });
+ externalWrite({ version: 1, entries: { [otherKey]: otherFingerprint } });
+
+ await call();
+
+ expect(disk.value?.entries[otherKey]).toBe(otherFingerprint);
+ expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
+ // 原子替换:先写 tmp 再 rename
+ expect(renames).toHaveLength(1);
+ expect(renames[0]).toContain('.tmp');
+ });
+
+ it('recovers a lock left behind by a crashed instance and persists', async () => {
+ // 持锁 pid 999 已退出 → 锁必须被回收,本进程仍能落盘。
+ const { call, disk } = loadGateway({ lockOwner: 999 });
+ await call();
+ expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
+ });
+
+ it('skips persisting while another live instance holds the lock, without breaking the gate', async () => {
+ const { gateway, call, requests, disk } = loadGateway({ lockOwner: 777 });
+ await call();
+ expect(requests).toHaveLength(1);
+ expect(disk.value).toBeNull();
+ // 本进程内存里的披露已生效
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
+ });
+
+ it('keeps a stale lock when the liveness probe fails for a reason other than ESRCH', async () => {
+ // EINVAL 等非 ESRCH 错误不能证明进程已退出 → 不回收,跳过落盘但不挡工具执行。
+ const { gateway, call, requests, disk } = loadGateway({ lockOwner: 999, killErrorCode: 'EINVAL' });
+ await call();
+ expect(requests).toHaveLength(1);
+ expect(disk.value).toBeNull();
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
+ });
+
+ it('restores the lock and skips persisting when the reclaimed lock was actually a live one', async () => {
+ // 两个实例同时读到死 pid:A 先回收旧锁并重建;B 的 rename 仍会成功,但掣走的是
+ // A 的新锁(内容 777,活进程)。校验内容不一致后必须放回并放弃本次落盘,
+ // 否则 B 会在 A 持锁写披露的同时进入写入路径,后写方覆盖先写方的记录。
+ const { call, requests, disk, renames } = loadGateway({ lockOwner: 999, reclaimReplacesWith: 777 });
+ await call();
+ expect(requests).toHaveLength(1);
+ expect(disk.value).toBeNull();
+ // 放回:回收槽内容回到锁路径(放回 rename + 原写入 rename 都有记录)
+ expect(renames.some((r) => r.includes('.stale-4242 -> /runtime/mcp-disclosure-s1.json.lock'))).toBe(true);
+ });
+
+ it('keeps another instance newer fingerprint when persisting a different tool', async () => {
+ // A 启动时载入 X 的旧指纹;另一实例随后更新 X 并落盘新指纹(外部写入磁盘);
+ // A 之后只为 Y 落盘。磁盘优先 + 只覆盖本次键:X 必须保持新指纹,不能被 A 内存
+ // 里的旧值回退——否则下次启动 A 会把 X 判为未披露。
+ const { gateway, disk, externalWrite } = loadGateway({
+ stored: { version: 1, entries: { 'cindy_orcasend_to_worker': fingerprint(TOOL) } },
+ });
+ const newer = fingerprint(TOOL_CHANGED);
+ externalWrite({ version: 1, entries: { 'cindy_orcasend_to_worker': newer } });
+
+ // A 为另一个工具 Y 显式披露(list_tools 单工具查询的生产路径)。
+ const other = { name: 'list_workers', description: '列出 workers', inputSchema: { type: 'object' } };
+ gateway.add('cindy_orca', { request: async () => ({ content: [] }) }, [other]);
+ await (gateway as unknown as { listResult: (params: unknown) => Promise<unknown> })
+ .listResult({ server: 'cindy_orca', tool: 'list_workers' });
+
+ expect(disk.value?.entries['cindy_orcasend_to_worker']).toBe(newer);
+ expect(disk.value?.entries['cindy_orcalist_workers']).toBe(fingerprint(other));
+ });
+
+
+ it('treats a missing or corrupt disclosure file as undisclosed and still executes', async () => {
+ for (const stored of [
+ null,
+ { version: 1, entries: { 'cindy_orca\u0000send_to_worker': 'not-a-hash' } },
+ ] as (DisclosedFile | null)[]) {
+ const { gateway, call, requests } = loadGateway({ stored });
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(false);
+ await call();
+ expect(requests).toHaveLength(1);
+ }
+ });
+
+ it('keeps the in-memory gate working when the disclosure file cannot be written', async () => {
+ const { gateway, call, requests, writes } = loadGateway({ writeFails: true });
+ await call();
+ expect(requests).toHaveLength(1);
+ expect(writes).toHaveLength(0);
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
+ });
+
+ it('records disclosure through cindy_mcp_list_tools too', async () => {
+ const { gateway, list, requests, disk } = loadGateway();
+ await list();
+ expect(requests).toHaveLength(0);
+ expect(disk.value?.entries['cindy_orca\u0000send_to_worker']).toBe(fingerprint(TOOL));
+ expect((gateway as unknown as { isSchemaDisclosed(c: unknown): boolean })
+ .isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);
+ });
});
\ No newline at end of file
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index 815bab27b2..5064ce4e1a 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -2890,9 +2890,11 @@ function acquireDisclosureLock(lockPath: string): boolean {
if (attempt === 1) return false;
const owner = readLockOwner(lockPath);
if (owner === undefined || owner === process.pid || isProcessAlive(owner)) return false;
- // 回收:把残留锁**原子地挪走**,只有 rename 成功的那个实例才有权回收。否则两个
- // 实例会先各自读到旧 owner,然后都执行 rmSync——A 删掉旧锁并重新加锁后,B 仍然
- // 会把 A 的新锁删掉,两边同时进入写入路径,后一次替换覆盖前一次刚存的披露记录。
+ // 回收:把残留锁**原子地挪走**,再验证挪走的确实是自己刚读到的那个死锁。
+ // 只靠 rename 成功不够:两个实例可能先后读到同一个旧 owner,A 先回收旧锁并重建,
+ // B 随后的 rename 仍会成功——掣走的是 A 的新锁(活锁)。所以挪走后必须校验
+ // stale 内容:不是那个死 pid 就说明掣了别人的锁,立即放回并放弃本次落盘。
+ // 「只有 wx 成功才算拿到锁」的不变量保证 B 全程不会进入写入路径。
const stale = lockPath + '.stale-' + process.pid;
try { rmSync(stale, { force: true }); } catch { /* 上次没清掉的回收槽 */ }
try {
@@ -2900,6 +2902,19 @@ function acquireDisclosureLock(lockPath: string): boolean {
} catch {
return false; // 已被另一个实例回收或重建:不争,跳过本次落盘。
}
+ let stolen: number | undefined;
+ try {
+ const parsed = Number.parseInt(readFileSync(stale, 'utf8').trim(), 10);
+ stolen = Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
+ } catch {
+ stolen = undefined;
+ }
+ if (stolen !== owner) {
+ // 掣走的是别的实例刚建的活锁:放回去(若路径已被占用则丢弃掣走的副本——
+ // 路径上那个新锁才是有效的),本次不落盘。
+ try { renameSync(stale, lockPath); } catch { try { rmSync(stale, { force: true }); } catch { /* 忽略 */ } }
+ return false;
+ }
try { rmSync(stale, { force: true }); } catch { /* 残留回收槽不影响正确性 */ }
}
}
@@ -2989,7 +3004,7 @@ class CindyMcpGateway {
}
}
- private persistDisclosures(): void {
+ private persistDisclosures(changedKey: string): void {
const file = this.disclosureFile();
if (!file) return;
const temp = file + '.' + process.pid + '.tmp';
@@ -2997,7 +3012,11 @@ class CindyMcpGateway {
const lockPath = file + '.lock';
if (!acquireDisclosureLock(lockPath)) return;
try {
- const merged = new Map<string, string>(this.disclosedSchemas);
+ // 以**锁内读到的磁盘记录为基础**,只覆盖本次实际披露的那个键。整份内存记录
+ // 优先会把另一个实例刚保存的新指纹改回本进程启动时载入的旧值:A 载入 X=f1,
+ // B 更新 X 落盘 f2,A 之后只为 Y 落盘时会把 X 回退成 f1——B 那边对 X 的披露
+ // 就被作废了。内存里的旧值不写回;本进程对 X 的认知只影响下次启动载入。
+ const merged: Record<string, string> = {};
try {
const existing = JSON.parse(readFileSync(file, 'utf8')) as {
version?: unknown; entries?: unknown;
@@ -3005,14 +3024,16 @@ class CindyMcpGateway {
if (existing?.version === 1 && existing.entries && typeof existing.entries === 'object') {
for (const [key, fingerprint] of Object.entries(existing.entries as Record<string, unknown>)) {
if (typeof fingerprint === 'string' && /^[a-f0-9]{64}$/.test(fingerprint)) {
- if (!merged.has(key)) merged.set(key, fingerprint);
+ merged[key] = fingerprint;
}
}
}
} catch {
- // 磁盘记录缺失/损坏:按只有本进程记录处理。
+ // 磁盘记录缺失/损坏:按只有本次变更处理。
}
- writeFileSync(temp, JSON.stringify({ version: 1, entries: Object.fromEntries(merged) }), { mode: 0o600 });
+ const current = this.disclosedSchemas.get(changedKey);
+ if (current) merged[changedKey] = current;
+ writeFileSync(temp, JSON.stringify({ version: 1, entries: merged }), { mode: 0o600 });
renameSync(temp, file);
} finally {
try { rmSync(lockPath, { force: true }); } catch { /* 残留锁由下次写入回收 */ }
@@ -3182,7 +3203,7 @@ class CindyMcpGateway {
const fingerprint = this.schemaFingerprint(call.tool);
if (this.disclosedSchemas.get(key) === fingerprint) return false;
this.disclosedSchemas.set(key, fingerprint);
- this.persistDisclosures();
+ this.persistDisclosures(key);
return true;
}