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。

test: stabilize test scheduling and consolidate validation cases

DavidShenfc522e55e395
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2a3d1ac33a..bda83d213f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -206,7 +206,9 @@ jobs:
run: pnpm install:ripgrep
- name: Run client and package unit tests
- run: pnpm test:unit
+ # test:runner runs once in verify-checks. Running the root test:unit
+ # script here would repeat all runner self-tests for every shard.
+ run: pnpm exec node scripts/test-workspaces.mjs --tier unit
# localDb suites are outside the unit tier; exercise these DB boundaries on both OSes.
- name: Run companion database regressions
diff --git a/package.json b/package.json
index e05660e060..52773a640e 100644
--- a/package.json
+++ b/package.json
@@ -126,6 +126,7 @@
"test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
"test:unit:related": "node scripts/test-workspaces.mjs --tier unit --related",
+ "test:integration": "pnpm test:runner && node scripts/test-workspaces.mjs --tier integration",
"test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all",
"test:git-integration": "pnpm test:runner && node scripts/test-workspaces.mjs --tier git-integration",
"test:db": "pnpm test:runner && node scripts/test-workspaces.mjs --tier db",
diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
index eb06a2f60d..0decd814bc 100644
--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
@@ -2359,33 +2359,37 @@ describe('TelegramIM', () => {
const events: IMMessageEvent[] = [];
im.onMessage((e) => events.push(e));
await connect();
- api.pushUpdates([
- groupMessage({ text: '改个文件', fromId: 111, messageId: 99, mentionBot: true }),
- ]);
- await vi.waitFor(() => expect(events).toHaveLength(1));
- await vi.waitFor(() => {
- expect(
- api.calls.some((c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200'),
- ).toBe(true);
- });
+ vi.useFakeTimers();
+ try {
+ api.pushUpdates([
+ groupMessage({ text: '改个文件', fromId: 111, messageId: 99, mentionBot: true }),
+ ]);
+ await vi.waitFor(() => expect(events).toHaveLength(1));
+ await vi.waitFor(() => {
+ expect(
+ api.calls.some((c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200'),
+ ).toBe(true);
+ });
// 卡片投的是宿主私聊 —— callSend 只会停它自己那条 chat 的 typing loop,
// 群里那条必须由转发分支显式停掉, 否则每 4.5s 继续打一次 sendChatAction。
- await im.sendInteractiveCard(
- events[0].senderId,
- { title: '需要授权', body: '改 src/app.ts?', buttons: [{ id: 'allow', label: '允许' }] },
- { deliverToOwnerDm: true, ownerDmNote: '群聊里的任务需要你授权。' },
- );
- const groupTypingAfterCard = api.calls.filter(
- (c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200',
- ).length;
- // **必须跨过一个 TYPING_REFRESH_MS(4.5s)**: loop 每 4.5s 才刷一次, 只等 100ms 的话
- // 循环还没来得及打下一枪, 断言对「有没有真的停掉」没有判别力(反向验证时会假通过)。
- await new Promise((r) => setTimeout(r, 4_700));
- expect(
- api.calls.filter((c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200')
- .length,
- ).toBe(groupTypingAfterCard);
+ await im.sendInteractiveCard(
+ events[0].senderId,
+ { title: '需要授权', body: '改 src/app.ts?', buttons: [{ id: 'allow', label: '允许' }] },
+ { deliverToOwnerDm: true, ownerDmNote: '群聊里的任务需要你授权。' },
+ );
+ const groupTypingAfterCard = api.calls.filter(
+ (c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200',
+ ).length;
+ // 跨过一个 TYPING_REFRESH_MS(4.5s),验证循环确实已停止。
+ await vi.advanceTimersByTimeAsync(4_700);
+ expect(
+ api.calls.filter((c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200')
+ .length,
+ ).toBe(groupTypingAfterCard);
+ } finally {
+ vi.useRealTimers();
+ }
});
// 交互卡的 callback token 只活在进程内存里(codec 的 callbackRefs), 重启或被淘汰后
diff --git a/packages/maker-pi-manager/src/__tests__/pi-manager-integration.test.ts b/packages/maker-pi-manager/src/__tests__/pi-manager.integration.test.ts
similarity index 99%
rename from packages/maker-pi-manager/src/__tests__/pi-manager-integration.test.ts
rename to packages/maker-pi-manager/src/__tests__/pi-manager.integration.test.ts
index 7167b18116..7c74737c12 100644
--- a/packages/maker-pi-manager/src/__tests__/pi-manager-integration.test.ts
+++ b/packages/maker-pi-manager/src/__tests__/pi-manager.integration.test.ts
@@ -35,7 +35,7 @@ import * as net from "node:net";
import * as path from "node:path";
import * as os from "node:os";
import * as fs from "node:fs";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ManagerServer } from "../server.js";
import { PiSessionRegistry } from "../session-registry.js";
@@ -1042,13 +1042,10 @@ describe.skipIf(process.platform === "win32")(
(idleRegistry as any).recycleIdle();
// Wait for the async kill chain (SIGTERM → waitForExit → teardown)
- await new Promise((r) => setTimeout(r, 2000));
-
- // The child (`sleep 0.1`) should have exited quickly, so kill should
- // succeed and teardown should fire
- // Verify session was recycled
- expect(closedSessions).toContain("idle-s1");
- expect(idleRegistry.list()).toHaveLength(0);
+ await vi.waitFor(() => {
+ expect(closedSessions).toContain("idle-s1");
+ expect(idleRegistry.list()).toHaveLength(0);
+ }, { timeout: 5_000, interval: 20 });
// Clean up
idleRegistry.close();
diff --git a/packages/maker-pi-manager/src/__tests__/protocol.test.ts b/packages/maker-pi-manager/src/__tests__/protocol.test.ts
index 121115f6f1..e9c24debe3 100644
--- a/packages/maker-pi-manager/src/__tests__/protocol.test.ts
+++ b/packages/maker-pi-manager/src/__tests__/protocol.test.ts
@@ -58,220 +58,64 @@ describe('NOTIFICATIONS', () => {
// isRpcMessage — 主守卫
// ---------------------------------------------------------------------------
describe('isRpcMessage', () => {
- // ---- 合法通过 ----
- describe('valid messages', () => {
- it('accepts a valid request', () => {
- expect(isRpcMessage({ type: 'request', id: 1, method: 'test' })).toBe(true);
- });
-
- it('accepts a request with id = 0', () => {
- expect(isRpcMessage({ type: 'request', id: 0, method: 't' })).toBe(true);
- });
-
- it('accepts a valid response with result', () => {
- expect(
- isRpcMessage({ type: 'response', id: 1, result: 'ok' }),
- ).toBe(true);
- });
-
- it('accepts a valid response with error', () => {
- expect(
- isRpcMessage({
- type: 'response',
- id: 42,
- error: { code: 'INTERNAL', message: 'boom' },
- }),
- ).toBe(true);
- });
-
- it('accepts a response without result/error (ack pattern)', () => {
- expect(isRpcMessage({ type: 'response', id: 99 })).toBe(true);
- });
-
- it('accepts a valid notification', () => {
- expect(isRpcMessage({ type: 'notification', method: 'session/closed' })).toBe(
- true,
- );
- });
-
- it('accepts a notification with params', () => {
- expect(
- isRpcMessage({
- type: 'notification',
- method: 'session/closed',
- params: { sessionId: 'abc' },
- }),
- ).toBe(true);
- });
- });
-
- // ---- NaN id 拒绝 ----
- describe('NaN id', () => {
- it('rejects request with NaN id', () => {
- expect(
- isRpcMessage({ type: 'request', id: NaN, method: 'test' }),
- ).toBe(false);
- });
-
- it('rejects response with NaN id', () => {
- expect(isRpcMessage({ type: 'response', id: NaN })).toBe(false);
- });
- });
-
- // ---- Infinity id 拒绝 ----
- describe('Infinity id', () => {
- it('rejects request with Infinity id', () => {
- expect(
- isRpcMessage({ type: 'request', id: Infinity, method: 'test' }),
- ).toBe(false);
- });
-
- it('rejects request with -Infinity id', () => {
- expect(
- isRpcMessage({ type: 'request', id: -Infinity, method: 'test' }),
- ).toBe(false);
- });
-
- it('rejects response with Infinity id', () => {
- expect(isRpcMessage({ type: 'response', id: Infinity })).toBe(false);
- });
- });
-
- // ---- 负数 id 允许(server→client 反向请求需要负数 id 命名空间) ----
- describe('negative id (accepted for bidirectional use)', () => {
- it('accepts request with id = -1 (used by server→client reverse request)', () => {
- expect(
- isRpcMessage({ type: 'request', id: -1, method: 'test' }),
- ).toBe(true);
- });
-
- it('accepts request with id = Number.MIN_SAFE_INTEGER', () => {
- expect(
- isRpcMessage({
- type: 'request',
- id: Number.MIN_SAFE_INTEGER,
- method: 'test',
- }),
- ).toBe(true);
- });
-
- it('accepts response with id = -1 (client responds to server reverse request)', () => {
- expect(isRpcMessage({ type: 'response', id: -1 })).toBe(true);
- });
-
- it('accepts response with decrementing negative id = -10', () => {
- expect(isRpcMessage({ type: 'response', id: -10 })).toBe(true);
- });
- });
-
- // ---- float id 拒绝 ----
- describe('float id', () => {
- it('rejects request with float id', () => {
- expect(
- isRpcMessage({ type: 'request', id: 1.5, method: 'test' }),
- ).toBe(false);
- });
-
- it('rejects request with id = 0.1', () => {
- expect(
- isRpcMessage({ type: 'request', id: 0.1, method: 'test' }),
- ).toBe(false);
- });
-
- it('rejects response with float id', () => {
- expect(isRpcMessage({ type: 'response', id: 1.5 })).toBe(false);
- });
- });
-
- // ---- 缺 id ----
- describe('missing id', () => {
- it('rejects request without id', () => {
- expect(
- isRpcMessage({ type: 'request', method: 'test' }),
- ).toBe(false);
- });
-
- it('rejects response without id', () => {
- expect(isRpcMessage({ type: 'response' })).toBe(false);
- });
- });
-
- // ---- 缺 method ----
- describe('missing method', () => {
- it('rejects request without method', () => {
- expect(isRpcMessage({ type: 'request', id: 1 })).toBe(false);
- });
-
- it('rejects notification without method', () => {
- expect(
- isRpcMessage({ type: 'notification', params: {} }),
- ).toBe(false);
- });
- });
-
- // ---- 未知 type ----
- describe('unknown type', () => {
- it('rejects unknown type string', () => {
- expect(isRpcMessage({ type: 'event', id: 1 })).toBe(false);
- });
-
- it('rejects empty type', () => {
- expect(isRpcMessage({ type: '', id: 1 })).toBe(false);
- });
- });
-
- // ---- 非 object ----
- describe('non-object values', () => {
- it('rejects null', () => {
- expect(isRpcMessage(null)).toBe(false);
- });
-
- it('rejects undefined', () => {
- expect(isRpcMessage(undefined)).toBe(false);
- });
-
- it('rejects string', () => {
- expect(isRpcMessage('not an object')).toBe(false);
- });
-
- it('rejects number', () => {
- expect(isRpcMessage(42)).toBe(false);
- });
-
- it('rejects boolean', () => {
- expect(isRpcMessage(true)).toBe(false);
- });
-
- it('rejects array', () => {
- expect(isRpcMessage([1, 2, 3])).toBe(false);
- });
-
- it('rejects function', () => {
- expect(isRpcMessage(() => {})).toBe(false);
- });
- });
-
- // ---- 边缘 ----
- describe('edge cases', () => {
- it('rejects request with null method', () => {
- expect(
- isRpcMessage({ type: 'request', id: 1, method: null }),
- ).toBe(false);
- });
-
- it('rejects request with id as string', () => {
- expect(
- isRpcMessage({ type: 'request', id: '42', method: 'test' }),
- ).toBe(false);
- });
-
- it('rejects object without type', () => {
- expect(isRpcMessage({ id: 1, method: 'test' })).toBe(false);
- });
-
- it('accepts request with params = undefined (implicit)', () => {
- expect(isRpcMessage({ type: 'request', id: 1, method: 'test' })).toBe(true);
- });
+ // Each row remains an independently reported case, including omitted fields.
+ it.each<[string, unknown]>([
+ ['accepts a valid request', { type: 'request', id: 1, method: 'test' }],
+ ['accepts a request with id = 0', { type: 'request', id: 0, method: 't' }],
+ ['accepts a valid response with result', { type: 'response', id: 1, result: 'ok' }],
+ ['accepts a valid response with error', {
+ type: 'response', id: 42, error: { code: 'INTERNAL', message: 'boom' },
+ }],
+ ['accepts a response without result/error (ack pattern)', { type: 'response', id: 99 }],
+ ['accepts a valid notification', { type: 'notification', method: 'session/closed' }],
+ ['accepts a notification with params', {
+ type: 'notification', method: 'session/closed', params: { sessionId: 'abc' },
+ }],
+ // Negative IDs belong to the server-to-client reverse request namespace.
+ ['accepts request with id = -1 (used by server→client reverse request)', {
+ type: 'request', id: -1, method: 'test',
+ }],
+ ['accepts request with id = Number.MIN_SAFE_INTEGER', {
+ type: 'request', id: Number.MIN_SAFE_INTEGER, method: 'test',
+ }],
+ ['accepts response with id = -1 (client responds to server reverse request)', {
+ type: 'response', id: -1,
+ }],
+ ['accepts response with decrementing negative id = -10', { type: 'response', id: -10 }],
+ ['accepts request with params = undefined (implicit)', {
+ type: 'request', id: 1, method: 'test',
+ }],
+ ])('%s', (_name, input) => {
+ expect(isRpcMessage(input)).toBe(true);
+ });
+
+ it.each<[string, unknown]>([
+ ['rejects request with NaN id', { type: 'request', id: NaN, method: 'test' }],
+ ['rejects response with NaN id', { type: 'response', id: NaN }],
+ ['rejects request with Infinity id', { type: 'request', id: Infinity, method: 'test' }],
+ ['rejects request with -Infinity id', { type: 'request', id: -Infinity, method: 'test' }],
+ ['rejects response with Infinity id', { type: 'response', id: Infinity }],
+ ['rejects request with float id', { type: 'request', id: 1.5, method: 'test' }],
+ ['rejects request with id = 0.1', { type: 'request', id: 0.1, method: 'test' }],
+ ['rejects response with float id', { type: 'response', id: 1.5 }],
+ ['rejects request without id', { type: 'request', method: 'test' }],
+ ['rejects response without id', { type: 'response' }],
+ ['rejects request without method', { type: 'request', id: 1 }],
+ ['rejects notification without method', { type: 'notification', params: {} }],
+ ['rejects unknown type string', { type: 'event', id: 1 }],
+ ['rejects empty type', { type: '', id: 1 }],
+ ['rejects null', null],
+ ['rejects undefined', undefined],
+ ['rejects string', 'not an object'],
+ ['rejects number', 42],
+ ['rejects boolean', true],
+ ['rejects array', [1, 2, 3]],
+ ['rejects function', () => {}],
+ ['rejects request with null method', { type: 'request', id: 1, method: null }],
+ ['rejects request with id as string', { type: 'request', id: '42', method: 'test' }],
+ ['rejects object without type', { id: 1, method: 'test' }],
+ ])('%s', (_name, input) => {
+ expect(isRpcMessage(input)).toBe(false);
});
});
diff --git a/packages/maker-pi-manager/src/__tests__/server.test.ts b/packages/maker-pi-manager/src/__tests__/server.test.ts
index b162c1a6ae..1f7e393042 100644
--- a/packages/maker-pi-manager/src/__tests__/server.test.ts
+++ b/packages/maker-pi-manager/src/__tests__/server.test.ts
@@ -203,6 +203,24 @@ describe('ManagerServer', () => {
await server.stop();
});
+ /** One isolated client per validation case; cleanup also covers failed handshakes. */
+ async function requestFromClient(
+ method: string,
+ params: unknown = {},
+ { id = 2, hello = true }: { id?: number; hello?: boolean } = {},
+ ): Promise<any> {
+ const socket = await connectRaw(socketPath);
+ try {
+ if (hello) await doHello(socket);
+ const response = readNextFrame(socket);
+ writeRequest(socket, id, method, params);
+ return await response;
+ } finally {
+ socket.destroy();
+ socketFrameBuffers.delete(socket);
+ }
+ }
+
// -----------------------------------------------------------------------
// 1. hello handshake
// -----------------------------------------------------------------------
@@ -222,35 +240,31 @@ describe('ManagerServer', () => {
socket.destroy();
});
- it('rejects mismatched protocolVersion with INVALID_PROTOCOL_VERSION', async () => {
- const socket = await connectRaw(socketPath);
- writeRequest(socket, 1, 'protocol/hello', { protocolVersion: 999 });
- const resp = await readNextFrame(socket);
+ it.each([
+ {
+ name: 'rejects mismatched protocolVersion with INVALID_PROTOCOL_VERSION',
+ id: 1,
+ params: { protocolVersion: 999 },
+ error: { code: 'INVALID_PROTOCOL_VERSION', message: expect.stringContaining('999') },
+ },
+ {
+ name: 'rejects missing protocolVersion with INVALID_PARAMS',
+ id: 2,
+ params: {},
+ error: { code: 'INVALID_PARAMS', message: expect.stringContaining('protocolVersion') },
+ },
+ {
+ name: 'rejects non-number protocolVersion with INVALID_PARAMS',
+ id: 3,
+ params: { protocolVersion: 'v1' },
+ error: { code: 'INVALID_PARAMS' },
+ },
+ ].map(({ name, ...input }) => [name, input] as const))('%s', async (_name, { id, params, error }) => {
+ const resp = await requestFromClient('protocol/hello', params, { id, hello: false });
expect(resp.type).toBe('response');
- expect(resp.id).toBe(1);
+ expect(resp.id).toBe(id);
expect(resp.error).toBeDefined();
- expect(resp.error.code).toBe('INVALID_PROTOCOL_VERSION');
- expect(resp.error.message).toContain('999');
- socket.destroy();
- });
-
- it('rejects missing protocolVersion with INVALID_PARAMS', async () => {
- const socket = await connectRaw(socketPath);
- writeRequest(socket, 2, 'protocol/hello', {});
- const resp = await readNextFrame(socket);
- expect(resp.error).toBeDefined();
- expect(resp.error.code).toBe('INVALID_PARAMS');
- expect(resp.error.message).toContain('protocolVersion');
- socket.destroy();
- });
-
- it('rejects non-number protocolVersion with INVALID_PARAMS', async () => {
- const socket = await connectRaw(socketPath);
- writeRequest(socket, 3, 'protocol/hello', { protocolVersion: 'v1' });
- const resp = await readNextFrame(socket);
- expect(resp.error).toBeDefined();
- expect(resp.error.code).toBe('INVALID_PARAMS');
- socket.destroy();
+ expect(resp.error).toMatchObject(error);
});
it('allows client to proceed with requests after successful hello', async () => {
@@ -301,22 +315,22 @@ describe('ManagerServer', () => {
// 2. NOT_INITIALIZED guard
// -----------------------------------------------------------------------
describe('NOT_INITIALIZED guard', () => {
- it('rejects pi/list before hello with NOT_INITIALIZED', async () => {
- const socket = await connectRaw(socketPath);
- writeRequest(socket, 1, 'pi/list', {});
- const resp = await readNextFrame(socket);
+ it.each([
+ {
+ name: 'rejects pi/list before hello with NOT_INITIALIZED',
+ method: 'pi/list',
+ params: {},
+ },
+ {
+ name: 'rejects any non-hello method before initialization',
+ method: 'pi/ensure',
+ params: { sessionId: 'x' },
+ },
+ ].map(({ name, ...input }) => [name, input] as const))('%s', async (_name, { method, params }) => {
+ const resp = await requestFromClient(method, params, { id: 1, hello: false });
expect(resp.error).toBeDefined();
expect(resp.error.code).toBe('NOT_INITIALIZED');
expect(resp.error.message).toContain('protocol/hello');
- socket.destroy();
- });
-
- it('rejects any non-hello method before initialization', async () => {
- const socket = await connectRaw(socketPath);
- writeRequest(socket, 1, 'pi/ensure', { sessionId: 'x' });
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('NOT_INITIALIZED');
- socket.destroy();
});
it('allows hello before initialization (no NOT_INITIALIZED for hello itself)', async () => {
@@ -331,24 +345,22 @@ describe('ManagerServer', () => {
// 3. UNKNOWN_METHOD
// -----------------------------------------------------------------------
describe('UNKNOWN_METHOD', () => {
- it('returns UNKNOWN_METHOD for unregistered method after hello', async () => {
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 2, 'totally/made-up', {});
- const resp = await readNextFrame(socket);
+ it.each([
+ {
+ name: 'returns UNKNOWN_METHOD for unregistered method after hello',
+ id: 2,
+ method: 'totally/made-up',
+ },
+ {
+ name: 'returns UNKNOWN_METHOD even for plausible-but-unregistered methods',
+ id: 3,
+ method: 'protocol/version',
+ },
+ ].map(({ name, ...input }) => [name, input] as const))('%s', async (_name, { id, method }) => {
+ const resp = await requestFromClient(method, {}, { id });
expect(resp.error).toBeDefined();
expect(resp.error.code).toBe('UNKNOWN_METHOD');
- expect(resp.error.message).toContain('totally/made-up');
- socket.destroy();
- });
-
- it('returns UNKNOWN_METHOD even for plausible-but-unregistered methods', async () => {
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 3, 'protocol/version', {});
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('UNKNOWN_METHOD');
- socket.destroy();
+ expect(resp.error.message).toContain(method);
});
});
@@ -411,87 +423,52 @@ describe('ManagerServer', () => {
// 5. error code mapping
// -----------------------------------------------------------------------
describe('error code mapping', () => {
- it('passes through known error codes from handler throws', async () => {
- server.setHandler('test/known-error', async () => {
- throw makeServerError('INVALID_PARAMS', 'bad params', { field: 'x' });
+ it.each([
+ {
+ name: 'passes through known error codes from handler throws',
+ method: 'test/known-error',
+ createError: () => makeServerError('INVALID_PARAMS', 'bad params', { field: 'x' }),
+ expectedError: { code: 'INVALID_PARAMS', message: 'bad params', data: { field: 'x' } },
+ },
+ {
+ name: 'maps unknown error codes to INTERNAL',
+ method: 'test/unknown-code',
+ createError: () => Object.assign(new Error('something went wrong'), { code: 'WEIRD_CUSTOM_CODE' }),
+ expectedError: { code: 'INTERNAL', message: 'something went wrong' },
+ },
+ {
+ name: 'maps throws without code property to INTERNAL',
+ method: 'test/no-code',
+ createError: () => new Error('plain error'),
+ expectedError: { code: 'INTERNAL', message: 'plain error' },
+ },
+ {
+ name: 'maps non-Error throws to INTERNAL with fallback message',
+ method: 'test/throw-string',
+ createError: () => 'just a string',
+ expectedError: { code: 'INTERNAL', message: 'internal error' },
+ },
+ {
+ name: 'maps null-throws to INTERNAL with fallback message',
+ method: 'test/throw-null',
+ createError: () => null,
+ expectedError: { code: 'INTERNAL', message: 'internal error' },
+ },
+ {
+ name: 'maps SESSION_NOT_FOUND from handler',
+ method: 'test/session-not-found',
+ createError: () => makeServerError('SESSION_NOT_FOUND', 'no such session', { sessionId: 'abc' }),
+ expectedError: { code: 'SESSION_NOT_FOUND', data: { sessionId: 'abc' } },
+ },
+ ].map(({ name, ...input }) => [name, input] as const))('%s', async (_name, { method, createError, expectedError }) => {
+ server.setHandler(method, async () => {
+ throw createError();
});
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 2, 'test/known-error', {});
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('INVALID_PARAMS');
- expect(resp.error.message).toBe('bad params');
- expect(resp.error.data).toEqual({ field: 'x' });
- socket.destroy();
- });
-
- it('maps unknown error codes to INTERNAL', async () => {
- server.setHandler('test/unknown-code', async () => {
- const err = new Error('something went wrong') as Error & { code: string };
- err.code = 'WEIRD_CUSTOM_CODE';
- throw err;
- });
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 2, 'test/unknown-code', {});
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('INTERNAL');
- expect(resp.error.message).toBe('something went wrong');
- socket.destroy();
- });
-
- it('maps throws without code property to INTERNAL', async () => {
- server.setHandler('test/no-code', async () => {
- throw new Error('plain error');
- });
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 2, 'test/no-code', {});
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('INTERNAL');
- expect(resp.error.message).toBe('plain error');
- socket.destroy();
- });
-
- it('maps non-Error throws to INTERNAL with fallback message', async () => {
- server.setHandler('test/throw-string', async () => {
- throw 'just a string';
- });
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 2, 'test/throw-string', {});
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('INTERNAL');
- expect(resp.error.message).toBe('internal error');
- socket.destroy();
- });
-
- it('maps null-throws to INTERNAL with fallback message', async () => {
- server.setHandler('test/throw-null', async () => {
- throw null;
- });
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 2, 'test/throw-null', {});
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('INTERNAL');
- expect(resp.error.message).toBe('internal error');
- socket.destroy();
- });
-
- it('maps SESSION_NOT_FOUND from handler', async () => {
- server.setHandler('test/session-not-found', async () => {
- throw makeServerError('SESSION_NOT_FOUND', 'no such session', {
- sessionId: 'abc',
- });
- });
- const socket = await connectRaw(socketPath);
- await doHello(socket);
- writeRequest(socket, 2, 'test/session-not-found', {});
- const resp = await readNextFrame(socket);
- expect(resp.error.code).toBe('SESSION_NOT_FOUND');
- expect(resp.error.data).toEqual({ sessionId: 'abc' });
- socket.destroy();
+ const resp = await requestFromClient(method);
+ expect(resp.error).toMatchObject(expectedError);
+ if ('data' in expectedError) {
+ expect(resp.error.data).toEqual(expectedError.data);
+ }
});
});
diff --git a/packages/maker-pi-manager/src/__tests__/session-registry.test.ts b/packages/maker-pi-manager/src/__tests__/session-registry.test.ts
index b60881c3e1..d1c8a7e19d 100644
--- a/packages/maker-pi-manager/src/__tests__/session-registry.test.ts
+++ b/packages/maker-pi-manager/src/__tests__/session-registry.test.ts
@@ -156,6 +156,11 @@ async function createRegistry(
onSessionClosed,
...overrides,
});
+ // Register cleanup at creation so assertions cannot skip releasing this fixture.
+ cleanupFns.push(() => {
+ registry.close();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ });
return { registry, tmpDir, sockDir, envDir, onSessionClosed };
}
@@ -185,8 +190,7 @@ afterEach(() => {
describe('ensure', () => {
// 1a. 新建 spawn
it('should spawn a new session (isReattach=false)', async () => {
- const { registry, tmpDir, onSessionClosed } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry, onSessionClosed } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -215,8 +219,7 @@ describe('ensure', () => {
// 1b. 已存在 + 同 envHash + restart=false → isReattach=true(不杀)
it('should reattach when same envHash and restart=false', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child1 = makeChild();
mockSpawn.mockReturnValueOnce(child1);
@@ -236,8 +239,7 @@ describe('ensure', () => {
// 1c. 不同 envHash + restart=true → SIGTERM 旧 + 新 spawn
it('should kill old and spawn new when different envHash and restart=true', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child1 = makeChild();
mockSpawn.mockReturnValueOnce(child1);
@@ -259,8 +261,7 @@ describe('ensure', () => {
// 1d. 不同 envHash + restart=false → 纯 attach(不杀旧)
it('should pure attach when different envHash and restart=false', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
mockSpawn.mockReturnValueOnce(makeChild());
mockCreateServer.mockReturnValueOnce(makeServer());
@@ -275,8 +276,7 @@ describe('ensure', () => {
// 1e. In-flight spawn dedup:并发 ensure 同一 id 只 spawn 一次
it('should deduplicate concurrent ensure for same sessionId', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
// Delay spawn resolution so both ensures hit pendingSpawns
let resolveSpawn: (child: any) => void;
@@ -304,8 +304,7 @@ describe('ensure', () => {
// 1f: 已存在 + 同 envHash + restart=true → 不杀(同 hash)
it('should reattach when same envHash even with restart=true', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
mockSpawn.mockReturnValueOnce(makeChild());
mockCreateServer.mockReturnValueOnce(makeServer());
@@ -322,8 +321,7 @@ describe('ensure', () => {
describe('kill', () => {
// 2a. 正常 kill:SIGTERM → 进程退出
it('should kill an active session (SIGTERM → exit)', async () => {
- const { registry, tmpDir, onSessionClosed } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry, onSessionClosed } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -346,8 +344,7 @@ describe('kill', () => {
it('should throw SESSION_KILL_SURVIVED when process survives SIGKILL', async () => {
vi.useFakeTimers();
try {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeSurviveChild();
mockSpawn.mockReturnValueOnce(child);
@@ -379,8 +376,7 @@ describe('kill', () => {
// 2c. 双 kill 幂等
it('should be idempotent on double kill', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -398,8 +394,7 @@ describe('kill', () => {
// 2d. kill in-flight spawn
it('should kill an in-flight spawn (wait for spawn then kill)', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
// Make spawn slow: server.listen delayed
let resolveListen: () => void;
@@ -438,16 +433,14 @@ describe('kill', () => {
// 2e. SESSION_NOT_FOUND
it('should throw SESSION_NOT_FOUND for unknown session', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
await expect(registry.kill('no-such-session')).rejects.toMatchObject({ code: 'SESSION_NOT_FOUND' });
});
// 2f: kill in-flight spawn where spawn fails → kill succeeds (幂等)
it('should treat kill as success when in-flight spawn fails', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
// Make spawn fail immediately
mockSpawn.mockImplementationOnce(() => { throw new Error('spawn ENOENT'); });
@@ -464,8 +457,7 @@ describe('kill', () => {
describe('list / shutdownAll / teardown identity', () => {
// 3a. list 返回正确
it('should list all sessions with correct fields', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
mockSpawn.mockReturnValueOnce(makeChild({ pid: 100 }));
mockCreateServer.mockReturnValueOnce(makeServer());
@@ -492,8 +484,7 @@ describe('list / shutdownAll / teardown identity', () => {
// 3b. shutdownAll 排空 pending + 双轮扫描
it('should drain pending spawns and kill all sessions during shutdownAll', async () => {
- const { registry, tmpDir, onSessionClosed } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry, onSessionClosed } = await createRegistry();
// First spawn: normal
const child1 = makeChild();
@@ -532,7 +523,6 @@ describe('list / shutdownAll / teardown identity', () => {
it('awaits close-handler teardown cleanup during shutdownAll', async () => {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -553,7 +543,6 @@ describe('list / shutdownAll / teardown identity', () => {
it('collects natural-exit teardown while shutdownAll drains pending spawns', async () => {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const live = makeChild();
mockSpawn.mockReturnValueOnce(live);
@@ -586,7 +575,6 @@ describe('list / shutdownAll / teardown identity', () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
try {
const { registry, tmpDir, onSessionClosed } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
// survivor:杀不死(D-state)
const survivor = makeSurviveChild();
@@ -621,8 +609,7 @@ describe('list / shutdownAll / teardown identity', () => {
// 3c. stale entry teardown 不删新会话(身份校验)
it('should not remove a newer session with same id during stale teardown', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child1 = makeChild();
mockSpawn.mockReturnValueOnce(child1);
@@ -659,10 +646,9 @@ describe('list / shutdownAll / teardown identity', () => {
// ── 4. 空闲回收 ──────────────────────────────────────────
describe('idle recycling', () => {
it('should recycle session that exceeds idle timeout', async () => {
- const { registry, tmpDir, onSessionClosed } = await createRegistry({
+ const { registry, onSessionClosed } = await createRegistry({
idleTimeoutMs: 1, // very short timeout
});
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -686,10 +672,9 @@ describe('idle recycling', () => {
});
it('should not recycle session within idle boundary', async () => {
- const { registry, tmpDir, onSessionClosed } = await createRegistry({
+ const { registry, onSessionClosed } = await createRegistry({
idleTimeoutMs: 60_000, // 60 seconds
});
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -708,10 +693,9 @@ describe('idle recycling', () => {
});
it('should not recycle session with attached socket', async () => {
- const { registry, tmpDir } = await createRegistry({
+ const { registry } = await createRegistry({
idleTimeoutMs: 1,
});
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -736,8 +720,7 @@ describe('idle recycling', () => {
});
it('should guard against connected client in killChild (TOCTOU)', async () => {
- const { registry, tmpDir } = await createRegistry({ idleTimeoutMs: 1 });
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry({ idleTimeoutMs: 1 });
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -763,8 +746,7 @@ describe('idle recycling', () => {
});
it('explicit kill ignores attached socket — must terminate the process (round 40-w3 CRITICAL)', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -789,7 +771,6 @@ describe('idle recycling', () => {
describe('env-file', () => {
it('should write env-file with KEY=val format', async () => {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
mockSpawn.mockReturnValueOnce(makeChild());
mockCreateServer.mockReturnValueOnce(makeServer());
@@ -804,7 +785,6 @@ describe('env-file', () => {
it('should create env-file with restrictive permissions', async () => {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
mockSpawn.mockReturnValueOnce(makeChild());
mockCreateServer.mockReturnValueOnce(makeServer());
@@ -824,7 +804,6 @@ describe('env-file', () => {
it('should clean up env-file and child on spawn failure', async () => {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -851,8 +830,7 @@ describe('env-file', () => {
// 轮 40-w4-t5 MEDIUM-5:env-file 写入自身失败(原子写 tmp 失败)时 —— ensure
// reject、无 env-file 残留、不 spawn child、不 listen socket。
it('should reject cleanly when env-file write fails (no residue, no spawn)', async () => {
- const { registry, tmpDir, envDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry, envDir } = await createRegistry();
// 诱发 atomic write 的 writeFile(envTmp) 抛错:mockFsWriteFile 对 .tmp-
// 路径抛 ENOSPC(其余路径透传真实实现)。
@@ -881,8 +859,7 @@ describe('env-file', () => {
process.env.HTTP_PROXY = 'http://proxy.example:8080';
process.env.MY_CUSTOM_VAR = 'should-not-leak';
try {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -911,7 +888,6 @@ describe('env-file', () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
try {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const child = makeSurviveChild();
mockSpawn.mockReturnValueOnce(child);
@@ -946,8 +922,7 @@ describe('env-file', () => {
});
it('5d. should clean stale socket file before listen', async () => {
- const { registry, tmpDir, sockDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry, sockDir } = await createRegistry();
// 轮 21-W4 HIGH:socket 文件名是 sha256(sessionId) 截断 —— stale 文件必须
// 用 ensure 实际生成的 sockPath(registry 的 list 可查)才验证到清理逻辑。
@@ -977,8 +952,7 @@ describe('env-file', () => {
// ── 6. shuttingDown ──────────────────────────────────────
describe('shuttingDown', () => {
it('should reject ensure with INTERNAL after beginShutdown', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
registry.beginShutdown();
@@ -996,8 +970,7 @@ describe('shuttingDown', () => {
});
it('should reject ensure during shutdownAll', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
mockSpawn.mockReturnValueOnce(makeChild());
mockCreateServer.mockReturnValueOnce(makeServer());
@@ -1016,7 +989,6 @@ describe('shuttingDown', () => {
it('should reject new spawn during shutdown (guard in spawnSession before spawn)', async () => {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
// 守卫在 spawnSession 的 env-file 写后、spawn 前 —— 直接置 shuttingDown
// 再 ensure 即可触发(自审轮 6 L-3 把守卫提前后的语义)。
@@ -1037,7 +1009,6 @@ describe('shuttingDown', () => {
it('awaits env-file removal when shutdown races after the credential file is written', async () => {
const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
const envFile = path.join(tmpDir, 'envs', 'env-race-shutdown');
const origRename = fsPromises.rename.bind(fsPromises);
@@ -1059,37 +1030,38 @@ describe('shuttingDown', () => {
// ── 7. sessionId / env 校验 ──────────────────────────────
describe('sessionId / env validation', () => {
- it('should reject sessionId with path traversal (/)', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('../escape', 'cmd', { K: 'v' }, 'h1', false),
- ).rejects.toThrow(/unsafe sessionId/);
- });
-
- it('should reject sessionId with backslash (path traversal)', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('..\\escape', 'cmd', { K: 'v' }, 'h1', false),
- ).rejects.toThrow(/unsafe sessionId/);
- });
-
- it('should reject sessionId with spaces', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('has space', 'cmd', { K: 'v' }, 'h1', false),
- ).rejects.toThrow(/unsafe sessionId/);
+ let fixture: Awaited<ReturnType<typeof createRegistry>>;
+
+ beforeEach(async () => {
+ fixture = await createRegistry();
+ });
+
+ it.each<[string, {
+ sessionId?: string;
+ cmd?: string;
+ env?: Record<string, string>;
+ error: RegExp;
+ }]>([
+ ['should reject sessionId with path traversal (/)', { sessionId: '../escape', error: /unsafe sessionId/ }],
+ ['should reject sessionId with backslash (path traversal)', { sessionId: '..\\escape', error: /unsafe sessionId/ }],
+ ['should reject sessionId with spaces', { sessionId: 'has space', error: /unsafe sessionId/ }],
+ ['should reject env key with leading digit', { env: { '1BAD': 'val' }, error: /unsafe env entry/ }],
+ ['should reject env key with special characters', { env: { 'KEY-INJECT=evil': 'val' }, error: /unsafe env entry/ }],
+ ['should reject env value with newline injection', { env: { KEY: 'val\nINJECT=evil' }, error: /unsafe env entry/ }],
+ ['should reject env value with carriage return', { env: { KEY: 'val\rINJECT=evil' }, error: /unsafe env entry/ }],
+ ['should reject env value with NUL byte (spawn would throw synchronously)', { env: { KEY: 'val\0INJECT' }, error: /unsafe env entry/ }],
+ ['should reject cmd with NUL byte', { cmd: 'echo a\0rm -rf /', error: /unsafe cmd/ }],
+ ])('%s', async (_name, { sessionId = 'test', cmd = 'cmd', env = { K: 'v' }, error }) => {
+ const { registry, envDir } = fixture;
+ await expect(registry.ensure(sessionId, cmd, env, 'h1', false)).rejects.toThrow(error);
+ // NUL inputs must fail before spawn could throw and leave a credential file.
+ // Keep that regression assertion for every invalid input.
+ expect(fs.readdirSync(envDir)).toHaveLength(0);
+ expect(mockSpawn).not.toHaveBeenCalled();
});
it('should accept sessionId with alphanumeric, dash, underscore', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
+ const { registry } = fixture;
mockSpawn.mockReturnValueOnce(makeChild());
mockCreateServer.mockReturnValueOnce(makeServer());
@@ -1102,68 +1074,6 @@ describe('sessionId / env validation', () => {
);
expect(result.sessionId).toBe('my-session_42');
});
-
- it('should reject env key with leading digit', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('test', 'cmd', { '1BAD': 'val' }, 'h1', false),
- ).rejects.toThrow(/unsafe env entry/);
- });
-
- it('should reject env key with special characters', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('test', 'cmd', { 'KEY-INJECT=evil': 'val' }, 'h1', false),
- ).rejects.toThrow(/unsafe env entry/);
- });
-
- it('should reject env value with newline injection', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('test', 'cmd', { KEY: 'val\nINJECT=evil' }, 'h1', false),
- ).rejects.toThrow(/unsafe env entry/);
- });
-
- it('should reject env value with carriage return', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('test', 'cmd', { KEY: 'val\rINJECT=evil' }, 'h1', false),
- ).rejects.toThrow(/unsafe env entry/);
- });
-
- // 轮 40-w5 MEDIUM:env value 含 NUL → Node spawn 同步抛 ERR_INVALID_ARG_VALUE,
- // 发生在 env-file 写入之后会残留凭证文件。ensure 必须在写入前拒绝。
- it('should reject env value with NUL byte (spawn would throw synchronously)', async () => {
- const { registry, tmpDir, envDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('test', 'cmd', { KEY: 'val\0INJECT' }, 'h1', false),
- ).rejects.toThrow(/unsafe env entry/);
- // fail-fast: 任何 env-file 都不得写入
- expect(fs.readdirSync(envDir)).toHaveLength(0);
- expect(mockSpawn).not.toHaveBeenCalled();
- });
-
- // 轮 40-w5 MEDIUM:cmd 含 NUL 同理会同步抛 ERR_INVALID_ARG_VALUE。
- it('should reject cmd with NUL byte', async () => {
- const { registry, tmpDir, envDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
-
- await expect(
- registry.ensure('test', 'echo a\0rm -rf /', { K: 'v' }, 'h1', false),
- ).rejects.toThrow(/unsafe cmd/);
- expect(fs.readdirSync(envDir)).toHaveLength(0);
- expect(mockSpawn).not.toHaveBeenCalled();
- });
});
// ── 8. child stdout / stderr forwarding ─────────────────
@@ -1172,8 +1082,7 @@ describe('sessionId / env validation', () => {
// The forwarding logic itself is independent of how the socket was connected.
describe('child stdout / stderr forwarding', () => {
it('8a. should forward stdout to attached socket', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -1193,8 +1102,7 @@ describe('child stdout / stderr forwarding', () => {
});
it('8b. should discard stdout when no client attached', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -1210,8 +1118,7 @@ describe('child stdout / stderr forwarding', () => {
});
it('8c. detached control frame (extension_ui_request) → fail-closed kill (round 42 P1)', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
child.kill = vi.fn((_signal?: string) => { child.exitCode = 0; return true; });
@@ -1229,8 +1136,7 @@ describe('child stdout / stderr forwarding', () => {
});
it('8f. resumes paused stdout when conn closes before drain (round 16 HIGH — backpressure hang fix)', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -1255,8 +1161,7 @@ describe('child stdout / stderr forwarding', () => {
});
it('8c. should forward client data to child stdin', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -1280,8 +1185,7 @@ describe('child stdout / stderr forwarding', () => {
});
it('8d. should clear attachedSocket on connection close', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -1302,8 +1206,7 @@ describe('child stdout / stderr forwarding', () => {
});
it('8e. should emit pi stderr to logger', async () => {
- const { registry, tmpDir } = await createRegistry();
- cleanupFns.push(() => { registry.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry();
const child = makeChild();
mockSpawn.mockReturnValueOnce(child);
@@ -1320,16 +1223,14 @@ describe('child stdout / stderr forwarding', () => {
// ── 9. close() ───────────────────────────────────────────
describe('close', () => {
it('should clear the idle timer on close', async () => {
- const { registry, tmpDir } = await createRegistry({ idleTimeoutMs: 60_000 });
- cleanupFns.push(() => { fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry({ idleTimeoutMs: 60_000 });
// close() should not throw
expect(() => registry.close()).not.toThrow();
});
it('should be safe to close without idle timer (idleTimeoutMs=0)', async () => {
- const { registry, tmpDir } = await createRegistry({ idleTimeoutMs: 0 });
- cleanupFns.push(() => { fs.rmSync(tmpDir, { recursive: true, force: true }); });
+ const { registry } = await createRegistry({ idleTimeoutMs: 0 });
expect(() => registry.close()).not.toThrow();
});
diff --git a/scripts/__tests__/dev-docs-contract.test.mjs b/scripts/__tests__/dev-docs-contract.test.mjs
index 4b3099c443..e2f2e0f498 100644
--- a/scripts/__tests__/dev-docs-contract.test.mjs
+++ b/scripts/__tests__/dev-docs-contract.test.mjs
@@ -292,8 +292,8 @@ test("client CI keeps the complete two-shard unit gate on Windows", () => {
assert.match(shards, /^ fail-fast: false$/m);
assert.match(shards, /^ shard: \[1, 2\]$/m);
assert.match(shards, /^ XDT_UNIT_TEST_SHARD: \$\{\{ matrix\.shard \}\}\/2$/m);
- assert.match(shards, /^ run: pnpm test:unit$/m);
- assert.doesNotMatch(shards, /pnpm test:unit\s+--/);
+ assert.match(shards, /^ run: pnpm exec node scripts\/test-workspaces\.mjs --tier unit$/m);
+ assert.doesNotMatch(shards, /pnpm test:unit(?:\s|$)/);
const gate = workflowJob(workflow, "windows-unit");
assert.ok(gate, "client CI must preserve the stable Windows unit check");
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index 81438d83a1..edfd0a4dcc 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -205,6 +205,10 @@ test("unit workspace concurrency reserves the full worker budget for heavy works
...unitTestShardArgs(),
]);
assert.equal(makerCore.tiers.unit.execution, undefined);
+ assert.deepEqual(makerCore.tiers.unit.exclude, [
+ "**/*.integration.test.ts",
+ "**/*.e2e.test.ts",
+ ]);
assert.deepEqual(makerCore.tiers.unit.command, {
type: "packageBin",
bin: "vitest",
@@ -212,6 +216,34 @@ test("unit workspace concurrency reserves the full worker budget for heavy works
});
});
+test("real agent integration tests are explicit tiers outside unit", () => {
+ const makerCore = manifest.workspaces.find(
+ (workspace) => workspace.cwd === "packages/maker-core",
+ );
+ const piManager = manifest.workspaces.find(
+ (workspace) => workspace.cwd === "packages/maker-pi-manager",
+ );
+ const desktop = manifest.workspaces.find(
+ (workspace) => workspace.cwd === "apps/desktop",
+ );
+ assert.equal(makerCore.tiers.integration.status, "manual");
+ assert.equal(makerCore.tiers.integration.execution, "exclusive");
+ assert.equal(makerCore.tiers.integration.coverage, "allowlist");
+ assert.deepEqual(makerCore.tiers.integration.include, [
+ "src/agents/codex/*.integration.test.ts",
+ "src/agents/pi/__tests__/*.integration.test.ts",
+ ]);
+ assert.deepEqual(piManager.tiers.unit.exclude, [
+ "src/__tests__/pi-manager.integration.test.ts",
+ ]);
+ assert.deepEqual(piManager.tiers.integration.include, [
+ "src/__tests__/pi-manager.integration.test.ts",
+ ]);
+ assert.deepEqual(desktop.tiers.e2e.include, [
+ "src/main/maker-host/__tests__/*.e2e.test.ts",
+ ]);
+});
+
test("unit tier pins an explicit vitest pool, forks only by documented exception", () => {
// The default forks pool recycles one child process per test file, which on
// 2026-07-30 sustained ~21 LaunchServices check-ins/second and took down
@@ -420,12 +452,14 @@ test("single-level include pattern matches orca workflow test file", () => {
);
});
-test("desktop unit excludes migration, direct db-tier, and source-contract guard tests while keeping normal unit tests", () => {
+test("desktop unit excludes integration, migration, direct db-tier, and source-contract guard tests while keeping normal unit tests", () => {
const workspace = { cwd: "apps/desktop", status: "required" };
const tier = {
status: "required",
exclude: [
"**/*.git-integration.test.ts",
+ "**/*.integration.test.ts",
+ "**/*.e2e.test.ts",
"src/main/localDb/**",
"src/main/__tests__/*Migration.test.ts",
"src/main/__tests__/schemaDriftRepair.test.ts",
@@ -963,7 +997,7 @@ test("unit CI shard arguments cover valid halves and reject malformed input", ()
});
test("test gate lock covers heavy local tiers but skips guard, CI, and explicit bypass", () => {
- for (const tier of ["unit", "db", "git-integration"]) {
+ for (const tier of ["unit", "db", "git-integration", "integration", "e2e"]) {
assert.equal(shouldUseTestGateLock({ tier, env: {} }), true);
}
assert.equal(shouldUseTestGateLock({ all: true, env: {} }), true);
diff --git a/scripts/test-gate-lock.mjs b/scripts/test-gate-lock.mjs
index 72a9a745d3..c9d8843106 100644
--- a/scripts/test-gate-lock.mjs
+++ b/scripts/test-gate-lock.mjs
@@ -11,7 +11,7 @@ const LOCK_PROTOCOL = "cindy-test-workspaces-lock-v1";
const PROBE_TIMEOUT_MS = 1_000;
const RETRY_DELAY_MS = 500;
const WAIT_REPORT_INTERVAL_MS = 60_000;
-const HEAVY_TEST_TIERS = new Set(["unit", "db", "git-integration"]);
+const HEAVY_TEST_TIERS = new Set(["unit", "db", "git-integration", "integration", "e2e"]);
const BIND_DENIED_ERROR_CODES = new Set(["EACCES", "EPERM"]);
export const TEST_GATE_LOCK_TIMEOUT_EXIT_CODE = 75;
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index e4fe360e6d..bd45d26fd4 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -78,6 +78,16 @@ const desktopDbExclude = [
const desktopGitIntegrationInclude = [
'src/main/**/*.git-integration.test.ts',
];
+const makerCoreIntegrationInclude = [
+ 'src/agents/codex/*.integration.test.ts',
+ 'src/agents/pi/__tests__/*.integration.test.ts',
+];
+const makerPiManagerIntegrationInclude = [
+ 'src/__tests__/pi-manager.integration.test.ts',
+];
+const desktopE2eInclude = [
+ 'src/main/maker-host/__tests__/*.e2e.test.ts',
+];
export function desktopUnitWorkerCount(
availableParallelism = os.availableParallelism(),
@@ -96,7 +106,7 @@ const noCollectableWorkspace = (name, cwd, reason = noCollectableTestsReason) =>
tiers: {},
});
-const requiredUnitWorkspace = (name, cwd, { workers = 1, execution, pool } = {}) => ({
+const requiredUnitWorkspace = (name, cwd, { workers = 1, execution, pool, exclude } = {}) => ({
name,
cwd,
status: 'required',
@@ -105,6 +115,7 @@ const requiredUnitWorkspace = (name, cwd, { workers = 1, execution, pool } = {})
status: 'required',
...(execution ? { execution } : {}),
command: unitVitestCommand(workers, pool),
+ ...(exclude?.length ? { exclude } : {}),
},
},
});
@@ -140,6 +151,8 @@ export default {
),
exclude: [
'**/*.git-integration.test.ts',
+ '**/*.integration.test.ts',
+ '**/*.e2e.test.ts',
'src/main/localDb/**',
'src/main/__tests__/*Migration.test.ts',
'src/main/__tests__/schemaDriftRepair.test.ts',
@@ -161,6 +174,14 @@ export default {
command: vitestBin('run', `--maxWorkers=${desktopUnitWorkerCount()}`),
include: desktopGitIntegrationInclude,
},
+ e2e: {
+ status: 'manual',
+ reason: 'Desktop E2E tests spawn the real Codex binary and are explicit because they are platform and binary dependent.',
+ execution: 'exclusive',
+ coverage: 'allowlist',
+ command: vitestBin('run', '--pool=forks', '--maxWorkers=1'),
+ include: desktopE2eInclude,
+ },
db: {
status: 'manual',
reason: 'Desktop DB tests remain an explicit DB tier because they bootstrap runtime assets and cover localDb behavior outside fast unit.',
@@ -228,11 +249,49 @@ export default {
// Stays on forks: palette-scanner's tests stub HOME and the scanner resolves
// it through os.homedir(), which a worker thread cannot see (see
// UNIT_POOL_DEFAULT above).
- requiredUnitWorkspace('@cindy/maker-core', 'packages/maker-core', { pool: 'forks' }),
+ {
+ name: '@cindy/maker-core',
+ cwd: 'packages/maker-core',
+ status: 'required',
+ tiers: {
+ unit: {
+ status: 'required',
+ command: unitVitestCommand(1, 'forks'),
+ exclude: ['**/*.integration.test.ts', '**/*.e2e.test.ts'],
+ },
+ integration: {
+ status: 'manual',
+ reason: 'Pi/Codex integration tests spawn real agent binaries and local protocol servers.',
+ execution: 'exclusive',
+ coverage: 'allowlist',
+ command: vitestBin('run', '--pool=forks', '--maxWorkers=1'),
+ include: makerCoreIntegrationInclude,
+ },
+ },
+ },
requiredUnitWorkspace('@cindy/maker-remote-ssh', 'packages/maker-remote-ssh'),
// 轮 42:新包 maker-pi-manager(TS 单例 pi daemon)已随 SSH remote 交付;
// 漏登记会让 test-workspaces 的 manifest 覆盖校验失败(全量门禁拒跑)。
- requiredUnitWorkspace('@cindy/maker-pi-manager', 'packages/maker-pi-manager'),
+ {
+ name: '@cindy/maker-pi-manager',
+ cwd: 'packages/maker-pi-manager',
+ status: 'required',
+ tiers: {
+ unit: {
+ status: 'required',
+ command: unitVitestCommand(),
+ exclude: ['src/__tests__/pi-manager.integration.test.ts'],
+ },
+ integration: {
+ status: 'manual',
+ reason: 'Pi manager integration tests spawn real processes and sockets.',
+ execution: 'exclusive',
+ coverage: 'allowlist',
+ command: vitestBin('run', '--pool=forks', '--maxWorkers=1'),
+ include: makerPiManagerIntegrationInclude,
+ },
+ },
+ },
requiredUnitWorkspace('@cindy/maker-scheduler', 'packages/maker-scheduler'),
requiredUnitWorkspace('@cindy/maker-shared', 'packages/maker-shared'),
requiredUnitWorkspace('@cindy/model-providers', 'packages/model-providers'),