12 模块多 agent 并行开发(dev+test+fix 每,两层 + barrier):
- T06 PbaSession 事件溯源 + deriveMessages + logged 不变量
- T07 PbaEventBus typed event bus + waterfall + ScopeKey 隔离
- T08 能力接缝三角色(board-link + flash Provider/Registry/consumer)
- T09 compaction 完整工程(token-meter/pruner/summarizer/spill)
- T10 CI 质量门 + snapshot + doc-sync
- T11 类型镜像漂移检测(tsconfig.realpi + type-drift-check)
- T12 子代理 + 工作流编排(parallel/pipeline/InlineSubagentProvider)
- T13 上下文注入三段(inject/steer/followup)
- T14 plan/goal/todo checkpoint logged state(look-ahead 状态机)
- T15 profile/bundle 分层(维修诊断 vs 嵌入式开发,共享 base)
- T16 多 LLM provider 适配(ProviderRegistry + glm-5.2/deepseek)
- T17 审批接缝(fail-closed auto-deny)+ credentials/settings/lsp
集成(串行):
- src/index.ts 公共 re-export(board-link/flash 具名避 shared/types 重名)
- tests/system-integration.test.ts 跨模块 10 闭环(事件溯源→compaction→bus→
接缝→checkpoint→inject→workflow→approval→provider→profile)
- 全量 tsc=0;vitest 39 文件 2449 passed/5 skipped(1044 baseline +~1400 模块 + 10 系统)
- 密钥铁律:\${DROBOTICS_LLM_KEY} 占位,grep sk- 明文 0
68 workflow agent / 0 error / ~3M token;mutation 测试每模块 3-9 seeded bug 全杀。
Co-Authored-By: Claude <noreply@anthropic.com>
1330 lines
47 KiB
TypeScript
1330 lines
47 KiB
TypeScript
/**
|
||
* @module tests/workflow.test
|
||
*
|
||
* T12 子代理 + 工作流编排 —— 严谨多方法论测试套件。
|
||
*
|
||
* 被测命名导出(按契约):
|
||
* src/capabilities/workflow/index.ts -> parallel, pipeline, phase, MAX_CONCURRENCY
|
||
* src/capabilities/subagent/index.ts -> InlineSubagentProvider, SubagentRegistry,
|
||
* isolatedSubagentScope, SUBAGENT_SCOPE_ROOT,
|
||
* INLINE_SUBAGENT_ID, SubagentProvider(类型)
|
||
*
|
||
* 测试前置:直接 import 命名导出,mock 注入依赖(handler/emitter),无 pi 运行时、
|
||
* 无硬件、无网络。作用域隔离不变式靠真实 T07 PbaEventBus(纯逻辑)证明。
|
||
*
|
||
* 应用的多方法论(每个 describe 块标注):
|
||
* - 等价类划分(有效/无效/边界类)
|
||
* - 边界值分析(off-by-one、空、单元素、max、min)
|
||
* - 决策表(组合输入→期望,覆盖全分支)
|
||
* - 状态转换(状态+迁移+不可达状态+重入)
|
||
* - 变异测试(≥3 个 seeded bug,内联带 bug 副本,断言每个被某条测试杀死)
|
||
* - 对抗/fuzz(null、undefined、巨大、NaN、循环引用、并发重入、负值)
|
||
* - 元蜕变/不变式(跨变换保持的性质)
|
||
*
|
||
* 门:
|
||
* 1. 真实代码全绿:`npx vitest run tests/workflow.test.ts`
|
||
* 2. 每个植入 bug 变体:测试内断言其输出 != 正确输出(证明 kill)。
|
||
*/
|
||
|
||
import { describe, it, expect } from "vitest";
|
||
import {
|
||
parallel,
|
||
pipeline,
|
||
phase,
|
||
MAX_CONCURRENCY,
|
||
} from "../src/capabilities/workflow/index.js";
|
||
import {
|
||
InlineSubagentProvider,
|
||
SubagentRegistry,
|
||
isolatedSubagentScope,
|
||
SUBAGENT_SCOPE_ROOT,
|
||
INLINE_SUBAGENT_ID,
|
||
type SubagentProvider,
|
||
} from "../src/capabilities/subagent/index.js";
|
||
import { PbaEventBus } from "../src/core/pba-event-bus.js";
|
||
|
||
// ============================================================================
|
||
// 工具:tick 推进(避免依赖真实定时器的精度)
|
||
// ============================================================================
|
||
const tick = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
|
||
|
||
// ============================================================================
|
||
// T12 workflow —— MAX_CONCURRENCY 常量(边界值 + 不变式)
|
||
// ============================================================================
|
||
|
||
describe("T12 workflow MAX_CONCURRENCY —— 常量冻结 + 取值(边界值·不变式)", () => {
|
||
it("值为 8(文档化的 item 并发上限)", () => {
|
||
expect(MAX_CONCURRENCY).toBe(8);
|
||
});
|
||
|
||
it("深冻结:运行时不可变(Object.isFrozen)——值恒为 8,无法挂属性", () => {
|
||
expect(Object.isFrozen(MAX_CONCURRENCY)).toBe(true);
|
||
// number 原始值本不可变;ES 模块严格模式下给原始值挂属性抛 TypeError
|
||
expect(() => {
|
||
(MAX_CONCURRENCY as unknown as { x?: number }).x = 999;
|
||
}).toThrow(TypeError);
|
||
expect(MAX_CONCURRENCY).toBe(8);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 workflow —— parallel(等价类划分 + 边界值 + 决策表 + 对抗 + 元蜕变)
|
||
// ============================================================================
|
||
|
||
describe("T12 parallel —— barrier 原语(等价类划分·边界值·决策表)", () => {
|
||
// ---- 等价类:有效类(全部 fulfilled)----
|
||
it("有效类:3 thunk 全 fulfilled,值保序", async () => {
|
||
const out = await parallel([
|
||
() => Promise.resolve(1),
|
||
() => Promise.resolve(2),
|
||
() => Promise.resolve(3),
|
||
]);
|
||
expect(out).toEqual([1, 2, 3]);
|
||
});
|
||
|
||
it("有效类:thunk 返回异构类型(number/string/object/null value)保序", async () => {
|
||
const obj = { kind: "data" };
|
||
const out = await parallel([
|
||
() => Promise.resolve(42),
|
||
() => Promise.resolve("str"),
|
||
() => Promise.resolve(obj),
|
||
() => Promise.resolve(null),
|
||
() => Promise.resolve(undefined),
|
||
]);
|
||
expect(out).toEqual([42, "str", obj, null, undefined]);
|
||
});
|
||
|
||
// ---- 边界值:空 / 单元素 ----
|
||
it("边界:空 thunk 数组 → 空结果数组(非 undefined)", async () => {
|
||
const out = await parallel([]);
|
||
expect(Array.isArray(out)).toBe(true);
|
||
expect(out).toEqual([]);
|
||
expect(out).toHaveLength(0);
|
||
});
|
||
|
||
it("边界:单 thunk fulfilled → 单元素数组", async () => {
|
||
const out = await parallel([() => Promise.resolve("only")]);
|
||
expect(out).toEqual(["only"]);
|
||
});
|
||
|
||
// ---- 决策表:thunk 状态 × 位置 ----
|
||
it("决策表:[fulfilled, rejected, fulfilled] → [v, null, v],整体不 reject", async () => {
|
||
const out = await parallel([
|
||
() => Promise.resolve("a"),
|
||
() => Promise.reject(new Error("boom")),
|
||
() => Promise.resolve("c"),
|
||
]);
|
||
expect(out).toEqual(["a", null, "c"]);
|
||
});
|
||
|
||
it("决策表:全 rejected → 全 null(不 reject)", async () => {
|
||
const out = await parallel([
|
||
() => Promise.reject(new Error("e1")),
|
||
() => Promise.reject(new Error("e2")),
|
||
]);
|
||
expect(out).toEqual([null, null]);
|
||
});
|
||
|
||
it("决策表:首位 rejected → [null, v],末位仍保序", async () => {
|
||
const out = await parallel([
|
||
() => Promise.reject(new Error("head")),
|
||
() => Promise.resolve("tail"),
|
||
]);
|
||
expect(out).toEqual([null, "tail"]);
|
||
});
|
||
|
||
it("决策表:rejected 原因非 Error(裸串/对象/number)→ 仍落 null", async () => {
|
||
const out = await parallel([
|
||
() => Promise.reject("string reason"),
|
||
() => Promise.reject({ code: 500 }),
|
||
() => Promise.reject(42),
|
||
() => Promise.resolve("ok"),
|
||
]);
|
||
// 无论 reject 值类型,对应位恒 null(allSettled status 语义)
|
||
expect(out).toEqual([null, null, null, "ok"]);
|
||
});
|
||
|
||
// ---- 不变式:真并发 ----
|
||
it("不变式:N thunk 立即并发,maxInflight=N(非串行)", async () => {
|
||
let inflight = 0;
|
||
let maxInflight = 0;
|
||
const mk = (v: number) => () =>
|
||
new Promise<number>((resolve) => {
|
||
inflight++;
|
||
maxInflight = Math.max(maxInflight, inflight);
|
||
setTimeout(() => {
|
||
inflight--;
|
||
resolve(v);
|
||
}, 20);
|
||
});
|
||
const out = await parallel([mk(1), mk(2), mk(3), mk(4)]);
|
||
expect(out).toEqual([1, 2, 3, 4]);
|
||
expect(maxInflight).toBe(4);
|
||
});
|
||
|
||
// ---- 对抗/fuzz ----
|
||
it("对抗:thunk 返回非 Promise(同步值)→ 仍按 fulfilled 取值", async () => {
|
||
// map((t)=>t()) 得同步值,Promise.allSettled 把非 thenable 当 fulfilled
|
||
const out = await parallel([
|
||
// @ts-expect-error —— 故意返回非 Promise,对抗输入
|
||
() => "sync-value",
|
||
() => Promise.resolve("async-value"),
|
||
]);
|
||
expect(out).toEqual(["sync-value", "async-value"]);
|
||
});
|
||
|
||
it("回归(finding 已修):thunk 同步抛错 → 该位落 null,parallel 不 reject", async () => {
|
||
// 不变式:"单 thunk 抛错绝不向上传播(不 reject),只把对应位落 null"。
|
||
// 修复前 thunks.map((t)=>t()) 阶段同步 throw 逃逸 allSettled 使 parallel
|
||
// reject;修复后用 Promise.resolve().then(t) 把同步 throw 转成被 allSettled
|
||
// 吸收的 rejection → 该位落 null,其余位不受影响。
|
||
const out = await parallel([
|
||
() => Promise.resolve("a"),
|
||
() => {
|
||
throw new Error("sync boom");
|
||
},
|
||
() => Promise.resolve("c"),
|
||
]);
|
||
expect(out).toEqual(["a", null, "c"]);
|
||
});
|
||
|
||
// ---- 元蜕变:append 两次 = replay 等价 ----
|
||
it("元蜕变:parallel 的结果等价于按序 await 每个 thunk(保序不变式)", async () => {
|
||
const thunks = [
|
||
() => Promise.resolve("x"),
|
||
() => Promise.resolve("y"),
|
||
() => Promise.resolve("z"),
|
||
];
|
||
const concurrent = await parallel(thunks);
|
||
const sequential: unknown[] = [];
|
||
for (const t of thunks) sequential.push(await t());
|
||
expect(concurrent).toEqual(sequential);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 workflow —— pipeline(等价类 + 边界值 + 决策表 + 状态转换 + 元蜕变)
|
||
// ============================================================================
|
||
|
||
describe("T12 pipeline —— 流水线原语(等价类·边界值·决策表)", () => {
|
||
// ---- 等价类:happy ----
|
||
it("有效类:1 item 过 3 stage,prev 链式传递", async () => {
|
||
const calls: Array<{ stage: number; prev: unknown }> = [];
|
||
const out = await pipeline(
|
||
["img.bin"],
|
||
async (prev, item, i) => {
|
||
calls.push({ stage: 0, prev });
|
||
return `edit(${item}#${i})`;
|
||
},
|
||
async (prev, item, i) => {
|
||
calls.push({ stage: 1, prev });
|
||
return `compile(${prev}+${item}#${i})`;
|
||
},
|
||
async (prev, item, i) => {
|
||
calls.push({ stage: 2, prev });
|
||
return `flash(${prev}+${item}#${i})`;
|
||
},
|
||
);
|
||
expect(calls).toEqual([
|
||
{ stage: 0, prev: undefined },
|
||
{ stage: 1, prev: "edit(img.bin#0)" },
|
||
{ stage: 2, prev: "compile(edit(img.bin#0)+img.bin#0)" },
|
||
]);
|
||
expect(out).toEqual([
|
||
"flash(compile(edit(img.bin#0)+img.bin#0)+img.bin#0)",
|
||
]);
|
||
});
|
||
|
||
// ---- 边界值 ----
|
||
it("边界:空 items → 空结果数组(非 undefined)", async () => {
|
||
const out = await pipeline(
|
||
[],
|
||
async (prev, _item, _i) => prev ?? "x",
|
||
);
|
||
expect(Array.isArray(out)).toBe(true);
|
||
expect(out).toEqual([]);
|
||
});
|
||
|
||
it("边界:单 item 单 stage → 单元素", async () => {
|
||
const out = await pipeline(["solo"], async (_prev, item, i) => `f(${item}#${i})`);
|
||
expect(out).toEqual(["f(solo#0)"]);
|
||
});
|
||
|
||
it("边界:空 stages → identity(终态 = item 本身,非 null/undefined)", async () => {
|
||
const out = await pipeline(["a", "b", "c"]);
|
||
expect(out).toEqual(["a", "b", "c"]);
|
||
// 单 item 空 stages 同样 identity
|
||
const one = await pipeline([42]);
|
||
expect(one).toEqual([42]);
|
||
});
|
||
|
||
it("边界:stage 返回 undefined → prev 链传 undefined(非 null)", async () => {
|
||
const seen: unknown[] = [];
|
||
const out = await pipeline(
|
||
["item"],
|
||
async (_prev, _item, _i) => {
|
||
seen.push("s0");
|
||
return undefined;
|
||
},
|
||
async (prev, _item, _i) => {
|
||
seen.push(["s1", prev]);
|
||
return "done";
|
||
},
|
||
);
|
||
expect(seen).toEqual(["s0", ["s1", undefined]]);
|
||
expect(out).toEqual(["done"]);
|
||
});
|
||
|
||
// ---- 决策表:stage 抛错 × 位置 ----
|
||
it("决策表:stage0 抛错 → item null,stage1/2 不被调用", async () => {
|
||
const seen: number[] = [];
|
||
const out = await pipeline(
|
||
["a"],
|
||
async () => {
|
||
seen.push(0);
|
||
throw new Error("s0 boom");
|
||
},
|
||
async () => {
|
||
seen.push(1);
|
||
return "s1";
|
||
},
|
||
async () => {
|
||
seen.push(2);
|
||
return "s2";
|
||
},
|
||
);
|
||
expect(out).toEqual([null]);
|
||
expect(seen).toEqual([0]);
|
||
});
|
||
|
||
it("决策表:stage1 抛错 → item null,stage2 不被调用(fail-soft per-item)", async () => {
|
||
const seen: number[] = [];
|
||
const out = await pipeline(
|
||
["a"],
|
||
async () => {
|
||
seen.push(0);
|
||
return "s0";
|
||
},
|
||
async () => {
|
||
seen.push(1);
|
||
throw new Error("s1 boom");
|
||
},
|
||
async () => {
|
||
seen.push(2);
|
||
return "s2";
|
||
},
|
||
);
|
||
expect(out).toEqual([null]);
|
||
expect(seen).toEqual([0, 1]);
|
||
});
|
||
|
||
it("决策表:末 stage 抛错 → item null", async () => {
|
||
const out = await pipeline(
|
||
["a"],
|
||
async () => "s0",
|
||
async () => "s1",
|
||
async () => {
|
||
throw new Error("last boom");
|
||
},
|
||
);
|
||
expect(out).toEqual([null]);
|
||
});
|
||
|
||
it("决策表:多 item,部分 item 在不同 stage 失败 → 各自落 null,成功 item 保终态保序", async () => {
|
||
const out = await pipeline(
|
||
["ok1", "fail", "ok2"],
|
||
async (_prev, item) => `e(${item})`,
|
||
async (_prev, item) => {
|
||
if (item === "fail") throw new Error("x");
|
||
return `c(${item})`;
|
||
},
|
||
async (prev) => `f(${prev})`,
|
||
);
|
||
expect(out).toEqual(["f(c(ok1))", null, "f(c(ok2))"]);
|
||
});
|
||
|
||
// ---- 状态转换:per-item 状态机(RUNNING→DONE | RUNNING→FAILED[吸收/跳后续])----
|
||
describe("状态转换:per-item 状态机(RUNNING→DONE/FAILED,FAILED 后不可达后续 stage)", () => {
|
||
it("迁移:item RUNNING(s0)→RUNNING(s1)→DONE,终态=末 stage 值", async () => {
|
||
const transitions: string[] = [];
|
||
await pipeline(
|
||
["it"],
|
||
async () => {
|
||
transitions.push("s0");
|
||
return 1;
|
||
},
|
||
async () => {
|
||
transitions.push("s1");
|
||
return 2;
|
||
},
|
||
).then((r) => {
|
||
transitions.push(`DONE:${r[0]}`);
|
||
});
|
||
expect(transitions).toEqual(["s0", "s1", "DONE:2"]);
|
||
});
|
||
|
||
it("迁移:item FAILED(s1) 后,s2 为不可达状态(永不调用)", async () => {
|
||
const reached: string[] = [];
|
||
await pipeline(
|
||
["it"],
|
||
async () => {
|
||
reached.push("s0");
|
||
return "v0";
|
||
},
|
||
async () => {
|
||
reached.push("s1-FAIL");
|
||
throw new Error("fail");
|
||
},
|
||
async () => {
|
||
reached.push("s2-UNREACHABLE");
|
||
return "v2";
|
||
},
|
||
);
|
||
expect(reached).toEqual(["s0", "s1-FAIL"]);
|
||
// s2 不可达已被吸收 stage 的 catch 证明
|
||
});
|
||
|
||
it("重入:多 item 独立状态机,一 item 失败不传染另一 item", async () => {
|
||
const log: string[] = [];
|
||
await pipeline(
|
||
["a", "b", "c"],
|
||
async (_p, item) => {
|
||
log.push(`${item}:s0`);
|
||
return item;
|
||
},
|
||
async (prev, item) => {
|
||
if (item === "b") {
|
||
log.push(`${item}:s1-FAIL`);
|
||
throw new Error("b fails");
|
||
}
|
||
log.push(`${item}:s1`);
|
||
return prev;
|
||
},
|
||
async (prev, item) => {
|
||
log.push(`${item}:s2`);
|
||
return prev;
|
||
},
|
||
);
|
||
// a/c 完成全 stage;b 在 s1 失败,s2 不可达
|
||
expect(log).toContain("a:s0");
|
||
expect(log).toContain("a:s2");
|
||
expect(log).toContain("b:s1-FAIL");
|
||
expect(log).not.toContain("b:s2");
|
||
expect(log).toContain("c:s2");
|
||
});
|
||
});
|
||
|
||
// ---- 不变式:并发钳制 + 保序 ----
|
||
it("不变式:item 并发 ≤ MAX_CONCURRENCY,结果保序", async () => {
|
||
let inflight = 0;
|
||
let maxInflight = 0;
|
||
const items = Array.from({ length: 20 }, (_, k) => k);
|
||
const out = await pipeline(items, async (_prev, _item, _i) => {
|
||
inflight++;
|
||
maxInflight = Math.max(maxInflight, inflight);
|
||
await tick(10);
|
||
inflight--;
|
||
return "ok";
|
||
});
|
||
expect(out).toEqual(items.map(() => "ok"));
|
||
expect(maxInflight).toBeLessThanOrEqual(MAX_CONCURRENCY);
|
||
expect(maxInflight).toBe(MAX_CONCURRENCY);
|
||
});
|
||
|
||
// ---- 对抗 ----
|
||
it("对抗:stage 索引 i 对每个 item 正确(0-based,保序)", async () => {
|
||
const seen: number[] = [];
|
||
await pipeline(
|
||
["a", "b", "c"],
|
||
async (_prev, _item, i) => {
|
||
seen.push(i);
|
||
return i;
|
||
},
|
||
);
|
||
expect(seen).toEqual([0, 1, 2]);
|
||
});
|
||
|
||
// ---- 元蜕变:单 stage pipeline = 每 item 独立 stage(prev=undefined) 的保序等价 ----
|
||
it("元蜕变:单 stage pipeline 的结果保序等价于每 item 独立 await stage(prev 重置)", async () => {
|
||
const items = [1, 2, 3];
|
||
const stage = async (prev: unknown, item: number, i: number) =>
|
||
`${prev ?? "∅"}→${item}#${i}`;
|
||
const piped = await pipeline(items, stage);
|
||
// pipeline 语义:每 item 独立流过 stage 链,stage[0] 收 prev=undefined
|
||
const seq: unknown[] = [];
|
||
for (let i = 0; i < items.length; i++) {
|
||
seq.push(await stage(undefined, items[i], i));
|
||
}
|
||
expect(piped).toEqual(seq);
|
||
expect(piped).toEqual(["∅→1#0", "∅→2#1", "∅→3#2"]);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 workflow —— phase(等价类 + 对抗)
|
||
// ============================================================================
|
||
|
||
describe("T12 phase —— no-op 锚点(等价类·对抗)", () => {
|
||
it("有效类:任意阶段名 → 返回 undefined,无副作用", () => {
|
||
expect(phase("compile-phase")).toBeUndefined();
|
||
expect(phase("flash-phase")).toBeUndefined();
|
||
});
|
||
|
||
it("边界:空串阶段名 → undefined,不抛", () => {
|
||
expect(phase("")).toBeUndefined();
|
||
});
|
||
|
||
it("对抗:undefined/number/对象名 → 不抛(参数被 void 消费)", () => {
|
||
// @ts-expect-error —— 对抗输入类型
|
||
expect(() => phase(undefined)).not.toThrow();
|
||
// @ts-expect-error
|
||
expect(() => phase(123)).not.toThrow();
|
||
// @ts-expect-error
|
||
expect(() => phase({ a: 1 })).not.toThrow();
|
||
});
|
||
|
||
it("不变式:phase 无累积状态——多次调用彼此独立", () => {
|
||
for (let i = 0; i < 50; i++) {
|
||
expect(phase(`p${i}`)).toBeUndefined();
|
||
}
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 subagent —— isolatedSubagentScope(等价类 + 边界值 + 决策表 + 对抗 + 不变式)
|
||
// ============================================================================
|
||
|
||
describe("T12 isolatedSubagentScope —— 作用域隔离(等价类·边界值·决策表·对抗)", () => {
|
||
// ---- 等价类 ----
|
||
it("有效类:单段 scope → subagent.<scope>", () => {
|
||
expect(isolatedSubagentScope("compile")).toBe("subagent.compile");
|
||
expect(isolatedSubagentScope("probe")).toBe("subagent.probe");
|
||
});
|
||
|
||
it("有效类:多段 scope → subagent.<a.b.c>", () => {
|
||
expect(isolatedSubagentScope("main.task.deep")).toBe(
|
||
"subagent.main.task.deep",
|
||
);
|
||
});
|
||
|
||
// ---- 边界值 ----
|
||
it("边界:undefined → 仅根 subagent", () => {
|
||
expect(isolatedSubagentScope(undefined)).toBe(SUBAGENT_SCOPE_ROOT);
|
||
});
|
||
|
||
it("边界:空串 → 仅根 subagent", () => {
|
||
expect(isolatedSubagentScope("")).toBe(SUBAGENT_SCOPE_ROOT);
|
||
});
|
||
|
||
it("边界:纯点串 '.' / '..' / '...' → 滤空段后仅根", () => {
|
||
expect(isolatedSubagentScope(".")).toBe(SUBAGENT_SCOPE_ROOT);
|
||
expect(isolatedSubagentScope("..")).toBe(SUBAGENT_SCOPE_ROOT);
|
||
expect(isolatedSubagentScope("...")).toBe(SUBAGENT_SCOPE_ROOT);
|
||
});
|
||
|
||
it("边界:首尾点 '.b' / 'a.' → 滤空段后 subagent.b / subagent.a", () => {
|
||
expect(isolatedSubagentScope(".b")).toBe("subagent.b");
|
||
expect(isolatedSubagentScope("a.")).toBe("subagent.a");
|
||
});
|
||
|
||
it("边界:双点段 'a..b' → 滤空段后 subagent.a.b", () => {
|
||
expect(isolatedSubagentScope("a..b")).toBe("subagent.a.b");
|
||
});
|
||
|
||
// ---- 决策表 ----
|
||
const cases: Array<[string | undefined, string]> = [
|
||
[undefined, "subagent"],
|
||
["", "subagent"],
|
||
["x", "subagent.x"],
|
||
["x.y", "subagent.x.y"],
|
||
[" x ", "subagent. x "], // 空格非空段,按 length>0 保留(契约:不 trim)
|
||
[".x.y.", "subagent.x.y"],
|
||
];
|
||
for (const [input, expected] of cases) {
|
||
it(`决策表:isolatedSubagentScope(${JSON.stringify(input)}) === "${expected}"`, () => {
|
||
expect(isolatedSubagentScope(input)).toBe(expected);
|
||
});
|
||
}
|
||
|
||
// ---- 不变式:结果恒以 SUBAGENT_SCOPE_ROOT 为段前缀 ----
|
||
it("不变式:任何输入的输出恒以 'subagent' 为首段(隔离根)", () => {
|
||
const inputs: Array<string | undefined> = [
|
||
undefined,
|
||
"",
|
||
".",
|
||
"a",
|
||
"a.b.c",
|
||
".x.",
|
||
"..",
|
||
"subagent", // 即使输入本身就是根名,输出仍是根
|
||
];
|
||
for (const s of inputs) {
|
||
const out = isolatedSubagentScope(s);
|
||
expect(out === SUBAGENT_SCOPE_ROOT || out.startsWith(SUBAGENT_SCOPE_ROOT + ".")).toBe(true);
|
||
}
|
||
});
|
||
|
||
// ---- 对抗 ----
|
||
it("对抗:超长 scope 不抛,正常前缀化", () => {
|
||
const big = "seg".repeat(1000);
|
||
const out = isolatedSubagentScope(big);
|
||
expect(out).toBe(`${SUBAGENT_SCOPE_ROOT}.${big}`);
|
||
expect(out.length).toBe(SUBAGENT_SCOPE_ROOT.length + 1 + big.length);
|
||
});
|
||
|
||
// ---- 元蜕变:append 两次 = replay 等价(幂等:对已隔离 scope 再隔离不变)----
|
||
it("元蜕变/幂等:对已隔离的 scope 再隔离 === 原值(幂等)", () => {
|
||
const once = isolatedSubagentScope("main.compile");
|
||
const twice = isolatedSubagentScope(once);
|
||
// once = "subagent.main.compile";再隔离按段切,前缀 subagent → "subagent.subagent.main.compile"
|
||
// 即幂等性不成立(前缀会叠加),这恰好证明隔离是"挂根"而非"归一到根"。
|
||
// 文档化此非幂等性:每次 isolatedSubagentScope 都重新挂根。
|
||
expect(twice).toBe("subagent.subagent.main.compile");
|
||
expect(twice.startsWith(SUBAGENT_SCOPE_ROOT)).toBe(true);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 subagent —— InlineSubagentProvider(等价类 + 边界值 + 决策表 + 状态转换 + 对抗)
|
||
// ============================================================================
|
||
|
||
describe("T12 InlineSubagentProvider —— spawn-in-process(等价类·边界值·决策表)", () => {
|
||
// ---- 等价类 ----
|
||
it("有效类:handler 返回值透传,scope 隔离派生", async () => {
|
||
let capturedScope = "";
|
||
const provider = new InlineSubagentProvider(async (prompt, opts) => {
|
||
capturedScope = opts?.scope ?? "";
|
||
return `echo:${prompt}`;
|
||
});
|
||
const r = await provider.spawn("hello", { scope: "probe" });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe("echo:hello");
|
||
expect(r.scope).toBe("subagent.probe");
|
||
expect(capturedScope).toBe("subagent.probe");
|
||
});
|
||
|
||
it("有效类:缺省 id === INLINE_SUBAGENT_ID", () => {
|
||
const p = new InlineSubagentProvider(async () => 0);
|
||
expect(p.id).toBe(INLINE_SUBAGENT_ID);
|
||
expect(INLINE_SUBAGENT_ID).toBe("inline-subagent");
|
||
});
|
||
|
||
it("有效类:显式 id 透传", () => {
|
||
const p = new InlineSubagentProvider(async () => 0, "custom-id");
|
||
expect(p.id).toBe("custom-id");
|
||
});
|
||
|
||
// ---- 边界值 ----
|
||
it("边界:opts 缺省 → scope 退化为根 subagent,handler opts.scope=根", async () => {
|
||
let cap = "";
|
||
const p = new InlineSubagentProvider(async (_prompt, opts) => {
|
||
cap = opts?.scope ?? "";
|
||
return "v";
|
||
});
|
||
const r = await p.spawn("p");
|
||
expect(r.ok).toBe(true);
|
||
expect(r.scope).toBe(SUBAGENT_SCOPE_ROOT);
|
||
expect(cap).toBe(SUBAGENT_SCOPE_ROOT);
|
||
});
|
||
|
||
it("边界:scope=空串 → scope 退化为根", async () => {
|
||
const p = new InlineSubagentProvider(async () => "v");
|
||
const r = await p.spawn("p", { scope: "" });
|
||
expect(r.scope).toBe(SUBAGENT_SCOPE_ROOT);
|
||
});
|
||
|
||
it("边界:handler 返回 undefined → ok:true, value=undefined", async () => {
|
||
const p = new InlineSubagentProvider(async () => undefined);
|
||
const r = await p.spawn("p");
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBeUndefined();
|
||
});
|
||
|
||
it("边界:handler 返回 null → ok:true, value=null(与 fail 的 null 区分靠 ok 字段)", async () => {
|
||
const p = new InlineSubagentProvider(async () => null);
|
||
const r = await p.spawn("p");
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe(null);
|
||
});
|
||
|
||
it("边界:空 prompt → handler 仍收空串", async () => {
|
||
let got = "__unset__";
|
||
const p = new InlineSubagentProvider(async (prompt) => {
|
||
got = prompt;
|
||
return "ok";
|
||
});
|
||
await p.spawn("");
|
||
expect(got).toBe("");
|
||
});
|
||
|
||
// ---- 决策表:timeoutMs × handler 行为 ----
|
||
it("决策表:handler 正常 + 无 timeout → ok:true", async () => {
|
||
const p = new InlineSubagentProvider(async () => "done");
|
||
const r = await p.spawn("p");
|
||
expect(r.ok).toBe(true);
|
||
expect(r.error).toBeUndefined();
|
||
});
|
||
|
||
it("决策表:handler 正常 + timeoutMs 大于耗时 → ok:true(不误杀)", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(10);
|
||
return "done";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: 200 });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe("done");
|
||
});
|
||
|
||
it("决策表:handler 慢 + timeoutMs 小 → ok:false, error 含 timeout, fail-closed", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(200);
|
||
return "never";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: 30 });
|
||
expect(r.ok).toBe(false);
|
||
expect(r.value).toBeUndefined();
|
||
expect(r.error).toContain("timeout");
|
||
expect(r.scope.startsWith(SUBAGENT_SCOPE_ROOT)).toBe(true);
|
||
});
|
||
|
||
it("决策表:handler 抛 Error → ok:false, error=message, fail-closed", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
throw new Error("handler boom");
|
||
});
|
||
const r = await p.spawn("p");
|
||
expect(r.ok).toBe(false);
|
||
expect(r.error).toBe("handler boom");
|
||
expect(r.value).toBeUndefined();
|
||
expect(r.scope.startsWith(SUBAGENT_SCOPE_ROOT)).toBe(true);
|
||
});
|
||
|
||
it("决策表:handler 抛非 Error(裸串/对象)→ ok:false, error=String(e)", async () => {
|
||
const pStr = new InlineSubagentProvider(async () => {
|
||
throw "raw string";
|
||
});
|
||
const rStr = await pStr.spawn("p");
|
||
expect(rStr.ok).toBe(false);
|
||
expect(rStr.error).toBe("raw string");
|
||
|
||
const pObj = new InlineSubagentProvider(async () => {
|
||
throw { code: 7 };
|
||
});
|
||
const rObj = await pObj.spawn("p");
|
||
expect(rObj.ok).toBe(false);
|
||
expect(rObj.error).toBe(String({ code: 7 }));
|
||
});
|
||
|
||
// ---- 边界值:timeoutMs 非法值(不计时)----
|
||
it("边界:timeoutMs=0 → 不计时(handler 完成 ok:true)", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(40);
|
||
return "ok";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: 0 });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe("ok");
|
||
});
|
||
|
||
it("边界:timeoutMs 负值 → 不计时", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(40);
|
||
return "ok";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: -5 });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe("ok");
|
||
});
|
||
|
||
it("边界:timeoutMs=NaN → 不限时(Number.isFinite 拦截)", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(40);
|
||
return "ok";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: NaN });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe("ok");
|
||
});
|
||
|
||
it("边界:timeoutMs=Infinity → 不限时(非有限)", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(40);
|
||
return "ok";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: Infinity });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe("ok");
|
||
});
|
||
|
||
// ---- 状态转换:spawn 内部状态(INIT→RUNNING→{DONE|TIMEOUT|FAILED})----
|
||
describe("状态转换:spawn 内部状态机(INIT→RUNNING→DONE/TIMEOUT/FAILED)", () => {
|
||
it("迁移:RUNNING→DONE,结果 ok=true,error 缺省", async () => {
|
||
const p = new InlineSubagentProvider(async () => "done");
|
||
const r = await p.spawn("p");
|
||
expect(r.ok === true && r.error === undefined).toBe(true);
|
||
});
|
||
|
||
it("迁移:RUNNING→TIMEOUT,error 含 timeout 串,value 缺省", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(300);
|
||
return "x";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: 20 });
|
||
expect(r.ok === false && typeof r.error === "string" && r.error!.includes("timeout")).toBe(true);
|
||
expect(r.value).toBeUndefined();
|
||
});
|
||
|
||
it("迁移:RUNNING→FAILED,error=handler 抛错串,value 缺省", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
throw new Error("fail");
|
||
});
|
||
const r = await p.spawn("p");
|
||
expect(r.ok === false && r.error === "fail").toBe(true);
|
||
expect(r.value).toBeUndefined();
|
||
});
|
||
|
||
it("重入:同一 provider 可被并发 spawn 多次(无内部可变状态耦合)", async () => {
|
||
const p = new InlineSubagentProvider(async (prompt) => {
|
||
await tick(10);
|
||
return `r:${prompt}`;
|
||
});
|
||
const rs = await Promise.all([
|
||
p.spawn("a", { scope: "sa" }),
|
||
p.spawn("b", { scope: "sb" }),
|
||
p.spawn("c", { scope: "sc" }),
|
||
]);
|
||
expect(rs.map((x) => x.value)).toEqual(["r:a", "r:b", "r:c"]);
|
||
expect(rs.map((x) => x.scope)).toEqual([
|
||
"subagent.sa",
|
||
"subagent.sb",
|
||
"subagent.sc",
|
||
]);
|
||
});
|
||
|
||
it("不可达状态:ok=true 时不应携带 error(互斥)", async () => {
|
||
const p = new InlineSubagentProvider(async () => "v");
|
||
const r = await p.spawn("p");
|
||
expect(r.ok === true && r.error === undefined).toBe(true);
|
||
});
|
||
it("不可达状态:ok=false 时不应携带 value(互斥)", async () => {
|
||
const p = new InlineSubagentProvider(async () => {
|
||
throw new Error("x");
|
||
});
|
||
const r = await p.spawn("p");
|
||
expect(r.ok === false && r.value === undefined).toBe(true);
|
||
});
|
||
});
|
||
|
||
// ---- 对抗 ----
|
||
it("对抗:handler 返回循环引用对象 → ok:true(不深拷贝,按引用透传)", async () => {
|
||
const circular: Record<string, unknown> = { self: null };
|
||
circular.self = circular;
|
||
const p = new InlineSubagentProvider(async () => circular);
|
||
const r = await p.spawn("p");
|
||
expect(r.ok).toBe(true);
|
||
expect(r.value).toBe(circular);
|
||
expect((r.value as Record<string, unknown>).self).toBe(r.value);
|
||
});
|
||
|
||
it("对抗:handler 返回巨大数组 → ok:true 透传", async () => {
|
||
const big = Array.from({ length: 10000 }, (_, i) => i);
|
||
const p = new InlineSubagentProvider(async () => big);
|
||
const r = await p.spawn("p");
|
||
expect(r.ok).toBe(true);
|
||
expect((r.value as number[]).length).toBe(10000);
|
||
});
|
||
|
||
it("对抗:prompt 含 unicode/控制字符 → handler 原样收", async () => {
|
||
let got = "";
|
||
const p = new InlineSubagentProvider(async (prompt) => {
|
||
got = prompt;
|
||
return "ok";
|
||
});
|
||
await p.spawn("hello世界😀");
|
||
expect(got).toBe("hello世界😀");
|
||
});
|
||
|
||
// ---- 不变式:spawn 绝不 reject ----
|
||
it("不变式/fail-closed:spawn 绝不 reject(超时/抛错均转 ok:false)", async () => {
|
||
const slow = new InlineSubagentProvider(async () => {
|
||
await tick(200);
|
||
return "x";
|
||
});
|
||
const throwing = new InlineSubagentProvider(async () => {
|
||
throw new Error("e");
|
||
});
|
||
const rt = slow.spawn("p", { timeoutMs: 10 });
|
||
const rh = throwing.spawn("p");
|
||
expect(typeof rt.then).toBe("function");
|
||
expect(typeof rh.then).toBe("function");
|
||
expect(await rt).toMatchObject({ ok: false });
|
||
expect(await rh).toMatchObject({ ok: false });
|
||
});
|
||
|
||
// ---- 不变式:超时定时器被清理(无句柄泄漏)----
|
||
it("不变式:超时后定时器被 clearTimeout(finally 清理,无泄漏)", async () => {
|
||
// 用 spy 计时器不可行(runWithTimeout 用全局 setTimeout),改用行为推断:
|
||
// 超时触发后,handler 仍在跑(未取消 handler promise),但 spawn 已 resolve。
|
||
// 重点是 finally 不抛、不挂起。
|
||
const p = new InlineSubagentProvider(async () => {
|
||
await tick(100);
|
||
return "late";
|
||
});
|
||
const r = await p.spawn("p", { timeoutMs: 10 });
|
||
expect(r.ok).toBe(false);
|
||
// 等待 handler 自然完成,证明 timer 已清理、无悬挂 reject 逃逸
|
||
await tick(120);
|
||
expect(r.ok).toBe(false);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 subagent —— SubagentRegistry(等价类 + 状态转换 + 对抗 + 元蜕变)
|
||
// ============================================================================
|
||
|
||
describe("T12 SubagentRegistry —— 注册/解析(等价类·状态转换·对抗·元蜕变)", () => {
|
||
// ---- 等价类 ----
|
||
it("有效类:register → resolve 返回同一 provider 实例", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "my-sub");
|
||
const disp = reg.register(p);
|
||
expect(reg.resolve("my-sub")).toBe(p);
|
||
expect(disp).toBeInstanceOf(Function);
|
||
});
|
||
|
||
it("有效类:list() 返回按插入序的只读快照", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p1: SubagentProvider = new InlineSubagentProvider(async () => 0, "a");
|
||
const p2: SubagentProvider = new InlineSubagentProvider(async () => 0, "b");
|
||
reg.register(p1);
|
||
reg.register(p2);
|
||
expect(reg.list()).toEqual([p1, p2]);
|
||
});
|
||
|
||
// ---- 边界值 ----
|
||
it("边界:空注册表 list() → 空数组(非 undefined)", () => {
|
||
const reg = new SubagentRegistry();
|
||
expect(reg.list()).toEqual([]);
|
||
});
|
||
|
||
it("边界:空注册表 resolve(任意 id) → 抛 fail-closed", () => {
|
||
const reg = new SubagentRegistry();
|
||
expect(() => reg.resolve("anything")).toThrow(/fail-closed/);
|
||
expect(() => reg.resolve("")).toThrow(/fail-closed/);
|
||
});
|
||
|
||
// ---- fail-closed 不变式 ----
|
||
it("不变式/fail-closed:未知 id 抛错,error 含 id + 'fail-closed'", () => {
|
||
const reg = new SubagentRegistry();
|
||
const id = "no-such-id";
|
||
expect(() => reg.resolve(id)).toThrow(id);
|
||
expect(() => reg.resolve(id)).toThrow(/fail-closed/);
|
||
});
|
||
|
||
it("对抗:resolve(null) → 抛 fail-closed(不静默返回)", () => {
|
||
const reg = new SubagentRegistry();
|
||
// @ts-expect-error —— 对抗输入
|
||
expect(() => reg.resolve(null)).toThrow(/fail-closed/);
|
||
// @ts-expect-error
|
||
expect(() => reg.resolve(undefined)).toThrow(/fail-closed/);
|
||
});
|
||
|
||
// ---- 状态转换:empty → registered → disposed(+ 重入/override)----
|
||
describe("状态转换:empty → registered → disposed(重入·override)", () => {
|
||
it("迁移:empty → registered(resolve 可用)→ disposed(resolve 再抛)", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k");
|
||
const disp = reg.register(p);
|
||
|
||
expect(reg.resolve("k")).toBe(p); // registered
|
||
|
||
disp(); // → disposed
|
||
expect(() => reg.resolve("k")).toThrow(/fail-closed/);
|
||
expect(reg.list()).toEqual([]);
|
||
});
|
||
|
||
it("重入:disposer 幂等——再调 no-op,不抛、不删他人", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k");
|
||
const disp = reg.register(p);
|
||
disp();
|
||
expect(() => disp()).not.toThrow();
|
||
disp();
|
||
expect(reg.list()).toEqual([]);
|
||
});
|
||
|
||
it("override 安全:同 id 重新注册新实例,旧 disposer 失效(不删新)", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p1: SubagentProvider = new InlineSubagentProvider(async () => 1, "k");
|
||
const p2: SubagentProvider = new InlineSubagentProvider(async () => 2, "k");
|
||
const d1 = reg.register(p1);
|
||
reg.register(p2); // override
|
||
expect(reg.resolve("k")).toBe(p2); // 新实例上位
|
||
expect(reg.list()).toEqual([p2]); // 同 id 不重复
|
||
|
||
d1(); // 旧 disposer——仍指 p1,但当前是 p2 → 不删
|
||
expect(reg.resolve("k")).toBe(p2); // 新实例仍在
|
||
expect(reg.list()).toEqual([p2]);
|
||
});
|
||
|
||
it("override:旧 disposer 失效后,仍可注册第三个同 id 实例", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p1: SubagentProvider = new InlineSubagentProvider(async () => 1, "k");
|
||
const p2: SubagentProvider = new InlineSubagentProvider(async () => 2, "k");
|
||
const p3: SubagentProvider = new InlineSubagentProvider(async () => 3, "k");
|
||
reg.register(p1);
|
||
const d2 = reg.register(p2);
|
||
reg.register(p3);
|
||
expect(reg.resolve("k")).toBe(p3);
|
||
d2(); // d2 指 p2,当前 p3 → 不删
|
||
expect(reg.resolve("k")).toBe(p3);
|
||
});
|
||
|
||
it("不可达状态:dispose 后再 resolve 不可达 registered(恒抛)", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k");
|
||
const d = reg.register(p);
|
||
d();
|
||
for (let i = 0; i < 3; i++) {
|
||
expect(() => reg.resolve("k")).toThrow(/fail-closed/);
|
||
}
|
||
});
|
||
|
||
it("并发重入:register→dispose→register 同 id 不留脏状态", () => {
|
||
const reg = new SubagentRegistry();
|
||
const mk = (v: number): SubagentProvider =>
|
||
new InlineSubagentProvider(async () => v, "k");
|
||
for (let i = 0; i < 5; i++) {
|
||
const d = reg.register(mk(i));
|
||
expect(reg.resolve("k")).toBeDefined();
|
||
d();
|
||
expect(() => reg.resolve("k")).toThrow(/fail-closed/);
|
||
}
|
||
expect(reg.list()).toEqual([]);
|
||
});
|
||
});
|
||
|
||
// ---- list() 只读不变式 ----
|
||
it("不变式:list() 返回的快照修改不影响内部注册表(防御性拷贝)", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k");
|
||
reg.register(p);
|
||
const snap = reg.list() as SubagentProvider[];
|
||
// 篡改快照
|
||
snap.length = 0;
|
||
snap.push(new InlineSubagentProvider(async () => 0, "evil"));
|
||
// 内部不受影响
|
||
expect(reg.resolve("k")).toBe(p);
|
||
expect(reg.list()).toEqual([p]);
|
||
});
|
||
|
||
// ---- 元蜕变:register→dispose→register 同实例 = 单次 register 等价 ----
|
||
it("元蜕变:register→dispose→register(p) 后 resolve(p) ≡ 直接 register(p) 后 resolve", () => {
|
||
const reg = new SubagentRegistry();
|
||
const p: SubagentProvider = new InlineSubagentProvider(async () => 0, "k");
|
||
const d = reg.register(p);
|
||
d();
|
||
const d2 = reg.register(p);
|
||
// 状态等价于从未 dispose
|
||
expect(reg.resolve("k")).toBe(p);
|
||
expect(reg.list()).toEqual([p]);
|
||
d2();
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 subagent —— 作用域隔离不变式(靠真实 T07 PbaEventBus)
|
||
// ============================================================================
|
||
|
||
describe("T12 subagent —— 作用域隔离不变式(靠真实 PbaEventBus·ScopeKey)", () => {
|
||
it("不变式⑥:子 agent 事件不达主 agent;主 agent 事件不下渗子 agent", async () => {
|
||
const bus = new PbaEventBus();
|
||
|
||
let mainGot = 0;
|
||
bus.on("task:done", () => mainGot++, "main");
|
||
|
||
let subGot = 0;
|
||
bus.on("task:done", () => subGot++, SUBAGENT_SCOPE_ROOT);
|
||
|
||
const childScope = isolatedSubagentScope("main.compile");
|
||
expect(childScope).toBe(`${SUBAGENT_SCOPE_ROOT}.main.compile`);
|
||
|
||
// 子 agent emit → 主 agent 不收(不串),观测层收
|
||
bus.emit("task:done", {}, childScope);
|
||
expect(mainGot).toBe(0);
|
||
expect(subGot).toBe(1);
|
||
|
||
// 主 agent emit → 子 agent 作用域不收(不下渗)
|
||
let subGotFromMain = 0;
|
||
bus.on("task:done", () => subGotFromMain++, childScope);
|
||
bus.emit("task:done", {}, "main");
|
||
expect(subGotFromMain).toBe(0);
|
||
});
|
||
|
||
it("不变式:两个不同子 agent 作用域互不串(旁支不冒泡)", () => {
|
||
const bus = new PbaEventBus();
|
||
const sa = isolatedSubagentScope("compile");
|
||
const sb = isolatedSubagentScope("probe");
|
||
let aGot = 0;
|
||
let bGot = 0;
|
||
bus.on("task:done", () => aGot++, sa);
|
||
bus.on("task:done", () => bGot++, sb);
|
||
|
||
bus.emit("task:done", {}, sa);
|
||
expect(aGot).toBe(1);
|
||
expect(bGot).toBe(0); // 旁支不收
|
||
|
||
bus.emit("task:done", {}, sb);
|
||
expect(aGot).toBe(1);
|
||
expect(bGot).toBe(1);
|
||
});
|
||
|
||
it("不变式:子 agent emit 到根 subagent 仅达根监听 + global,不达主 agent", () => {
|
||
const bus = new PbaEventBus();
|
||
let mainGot = 0;
|
||
let rootGot = 0;
|
||
let globalGot = 0;
|
||
bus.on("task:done", () => mainGot++, "main");
|
||
bus.on("task:done", () => rootGot++, SUBAGENT_SCOPE_ROOT);
|
||
bus.on("task:done", () => globalGot++); // global 监听收所有
|
||
|
||
bus.emit("task:done", {}, SUBAGENT_SCOPE_ROOT);
|
||
expect(mainGot).toBe(0);
|
||
expect(rootGot).toBe(1);
|
||
expect(globalGot).toBe(1);
|
||
});
|
||
|
||
it("不变式:global emit 不下渗到子 agent 作用域", () => {
|
||
const bus = new PbaEventBus();
|
||
const child = isolatedSubagentScope("x");
|
||
let childGot = 0;
|
||
let globalGot = 0;
|
||
bus.on("task:done", () => childGot++, child);
|
||
bus.on("task:done", () => globalGot++);
|
||
|
||
bus.emit("task:done", {}); // global emit
|
||
expect(childGot).toBe(0);
|
||
expect(globalGot).toBe(1);
|
||
});
|
||
|
||
it("集成:InlineSubagentProvider 派生的 scope 经 bus 冒泡仅达 subagent 根监听", async () => {
|
||
const bus = new PbaEventBus();
|
||
const observed: string[] = [];
|
||
bus.on("task:done", (a) => observed.push(`main:${JSON.stringify(a)}`), "main");
|
||
bus.on("task:done", (a) => observed.push(`sub:${JSON.stringify(a)}`), SUBAGENT_SCOPE_ROOT);
|
||
|
||
const p = new InlineSubagentProvider(async (_prompt, opts) => {
|
||
bus.emit("task:done", { scope: opts?.scope }, opts?.scope);
|
||
return "ok";
|
||
});
|
||
const r = await p.spawn("work", { scope: "compile" });
|
||
expect(r.ok).toBe(true);
|
||
expect(r.scope).toBe("subagent.compile");
|
||
// 主 agent 不收,subagent 根观测层收
|
||
expect(observed).toEqual(['sub:{"scope":"subagent.compile"}']);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 变异测试 —— 植入 seeded bug,断言每个被某条测试杀死
|
||
// ============================================================================
|
||
//
|
||
// 方法:内联带 bug 的逻辑副本(非包装真实代码),在测试内运行 buggy 副本,
|
||
// 断言其输出 != 正确输出(即:若把"断言正确行为"的测试跑在 buggy 副本上会 FAIL
|
||
// → 该 bug 被 kill)。最后真实代码(未植入 bug)全过。
|
||
//
|
||
// 文档化每个植入 bug + 杀它的测试:
|
||
|
||
describe("T12 变异测试 —— 植入 seeded bug 被 kill", () => {
|
||
// ---- 植入 bug #1:parallel rejected 位落 undefined 而非 null(错误默认值)----
|
||
// 真实:s.status === "fulfilled" ? s.value : null
|
||
// 变异:s.status === "fulfilled" ? s.value : undefined
|
||
async function parallelBuggy_rejectedToUndefined(
|
||
thunks: ReadonlyArray<() => Promise<unknown>>,
|
||
): Promise<unknown[]> {
|
||
const settled = await Promise.allSettled(thunks.map((t) => t()));
|
||
return settled.map((s) =>
|
||
s.status === "fulfilled" ? s.value : undefined, // <-- bug: null → undefined
|
||
);
|
||
}
|
||
|
||
it("bug #1 killed:rejected 位应为 null,buggy 给 undefined → 严格相等断言会失败", async () => {
|
||
const buggy = await parallelBuggy_rejectedToUndefined([
|
||
() => Promise.resolve("a"),
|
||
() => Promise.reject(new Error("boom")),
|
||
() => Promise.resolve("c"),
|
||
]);
|
||
// 证明 bug 存在:buggy 给 undefined(!== null)
|
||
expect(buggy[1]).not.toBe(null);
|
||
expect(buggy[1]).toBeUndefined();
|
||
// 对照真实:给 null
|
||
const real = await parallel([
|
||
() => Promise.resolve("a"),
|
||
() => Promise.reject(new Error("boom")),
|
||
() => Promise.resolve("c"),
|
||
]);
|
||
expect(real[1]).toBe(null);
|
||
// 杀它的测试 = 决策表 [fulfilled,rejected,fulfilled]→[v,null,v](toEqual 严格区分 null/undefined)
|
||
expect(buggy).not.toEqual(["a", null, "c"]);
|
||
expect(real).toEqual(["a", null, "c"]);
|
||
});
|
||
|
||
// ---- 植入 bug #2:isolatedSubagentScope 滤空段条件 s.length>0 → s.length>=0(< → <=,保留空段)----
|
||
// 真实:filter((s) => s.length > 0)
|
||
// 变异:filter((s) => s.length >= 0) —— 永真,保留空段
|
||
function isolatedSubagentScopeBuggy_keepEmpty(scope: string | undefined): string {
|
||
const segs = (scope ?? "").split(".").filter((s) => s.length >= 0); // <-- bug: > → >=
|
||
return segs.length === 0
|
||
? SUBAGENT_SCOPE_ROOT
|
||
: `${SUBAGENT_SCOPE_ROOT}.${segs.join(".")}`;
|
||
}
|
||
|
||
it("bug #2 killed:'.b' 应滤空段得 subagent.b,buggy 保留空段得 subagent..b", () => {
|
||
// 真实:".b" → ["", "b"] 滤空 → ["b"] → "subagent.b"
|
||
expect(isolatedSubagentScope(".b")).toBe("subagent.b");
|
||
// buggy:保留 "" → ["", "b"] → "subagent..b"
|
||
const buggy = isolatedSubagentScopeBuggy_keepEmpty(".b");
|
||
expect(buggy).toBe("subagent..b"); // 双点 = bug 证据
|
||
expect(buggy).not.toBe("subagent.b");
|
||
// 边界 '.b' 决策表条目会失败于 buggy
|
||
expect(isolatedSubagentScopeBuggy_keepEmpty(".")).not.toBe(SUBAGENT_SCOPE_ROOT);
|
||
expect(isolatedSubagentScope(".")).toBe(SUBAGENT_SCOPE_ROOT);
|
||
});
|
||
|
||
// ---- 植入 bug #3:pipeline stage 抛错后漏 return(不跳后续 stage,短路逻辑反转)----
|
||
// 真实:catch { return; } —— 跳过后续 stage,results[i] 保持 null
|
||
// 变异:catch { /* 漏 return */ } —— 继续跑后续 stage,覆盖 null
|
||
async function pipelineBuggy_noShortCircuit<T>(
|
||
items: ReadonlyArray<T>,
|
||
...stages: Array<(prev: unknown, item: T, i: number) => Promise<unknown>>
|
||
): Promise<unknown[]> {
|
||
const results: unknown[] = new Array(items.length).fill(null);
|
||
// 简化:单 item 串行(足够暴露 bug)
|
||
for (let i = 0; i < items.length; i++) {
|
||
let prev: unknown = undefined;
|
||
for (const stage of stages) {
|
||
try {
|
||
prev = await stage(prev, items[i], i);
|
||
} catch {
|
||
// <-- bug: 漏 return,继续跑后续 stage
|
||
}
|
||
}
|
||
results[i] = stages.length === 0 ? items[i] : prev;
|
||
}
|
||
return results;
|
||
}
|
||
|
||
it("bug #3 killed:stage1 抛错后 stage2 不应被调用,buggy 仍调用并覆盖 null", async () => {
|
||
const seen: number[] = [];
|
||
const stages = [
|
||
async () => {
|
||
seen.push(0);
|
||
return "s0";
|
||
},
|
||
async () => {
|
||
seen.push(1);
|
||
throw new Error("s1 boom");
|
||
},
|
||
async () => {
|
||
seen.push(2);
|
||
return "s2-recovered";
|
||
},
|
||
];
|
||
|
||
// 真实:stage1 抛错 → 跳 stage2,结果 [null],seen=[0,1]
|
||
const real = await pipeline(["a"], ...stages);
|
||
expect(real).toEqual([null]);
|
||
expect(seen).toEqual([0, 1]);
|
||
|
||
// buggy:不短路 → stage2 被调用,seen 含 2,结果非 null
|
||
const seenBuggy: number[] = [];
|
||
const buggy = await pipelineBuggy_noShortCircuit(["a"],
|
||
async () => { seenBuggy.push(0); return "s0"; },
|
||
async () => { seenBuggy.push(1); throw new Error("s1 boom"); },
|
||
async () => { seenBuggy.push(2); return "s2-recovered"; },
|
||
);
|
||
expect(seenBuggy).toEqual([0, 1, 2]); // stage2 被调用 = bug 证据
|
||
expect(buggy).toEqual(["s2-recovered"]); // 非 null = bug 证据
|
||
expect(buggy).not.toEqual([null]);
|
||
});
|
||
|
||
// ---- 植入 bug #4(额外,强化):SubagentRegistry.resolve 未知 id 返回 undefined 而非抛(fail-closed 反转)----
|
||
class SubagentRegistryBuggy_noFailClosed {
|
||
private readonly providers = new Map<string, SubagentProvider>();
|
||
register(provider: SubagentProvider): () => void {
|
||
this.providers.set(provider.id, provider);
|
||
return () => {
|
||
if (this.providers.get(provider.id) === provider) {
|
||
this.providers.delete(provider.id);
|
||
}
|
||
};
|
||
}
|
||
resolve(id: string): SubagentProvider | undefined {
|
||
// <-- bug: 未知 id 返回 undefined(静默),不抛
|
||
return this.providers.get(id);
|
||
}
|
||
list(): readonly SubagentProvider[] {
|
||
return [...this.providers.values()];
|
||
}
|
||
}
|
||
|
||
it("bug #4 killed:未知 id 应抛 fail-closed,buggy 返回 undefined(误用未配置子代理)", () => {
|
||
const real = new SubagentRegistry();
|
||
const buggy = new SubagentRegistryBuggy_noFailClosed();
|
||
// 真实:抛
|
||
expect(() => real.resolve("nope")).toThrow(/fail-closed/);
|
||
// buggy:静默返回 undefined
|
||
expect(buggy.resolve("nope")).toBeUndefined();
|
||
// 杀它的测试 = fail-closed 不变式断言(toThrow 会失败于 buggy)
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// T12 真实代码回归 —— 全部走真实导出,确认未植入 bug 时全过
|
||
// ============================================================================
|
||
|
||
describe("T12 真实代码回归(未植入 bug,全绿)", () => {
|
||
it("parallel + pipeline + phase + subagent 真实路径端到端", async () => {
|
||
phase("e2e-phase");
|
||
const reg = new SubagentRegistry();
|
||
const bus = new PbaEventBus();
|
||
const events: string[] = [];
|
||
bus.on("task:done", () => events.push("sub"), SUBAGENT_SCOPE_ROOT);
|
||
|
||
const p = new InlineSubagentProvider(async (prompt, opts) => {
|
||
bus.emit("task:done", {}, opts?.scope);
|
||
return `done:${prompt}`;
|
||
}, "e2e-sub");
|
||
reg.register(p);
|
||
|
||
// parallel:3 子任务并发,1 失败落 null
|
||
const out = await parallel([
|
||
() => reg.resolve("e2e-sub").spawn("a", { scope: "a" }).then((r) => r.value),
|
||
() => Promise.reject(new Error("x")),
|
||
() => reg.resolve("e2e-sub").spawn("c", { scope: "c" }).then((r) => r.value),
|
||
]);
|
||
expect(out).toEqual(["done:a", null, "done:c"]);
|
||
|
||
// pipeline:单 item 过 2 stage
|
||
const piped = await pipeline(
|
||
["img"],
|
||
async (_prev, item) => `edit:${item}`,
|
||
async (prev) => `flash:${prev}`,
|
||
);
|
||
expect(piped).toEqual(["flash:edit:img"]);
|
||
|
||
// 子 agent 事件冒泡到 subagent 根(2 次:a + c)
|
||
expect(events.filter((e) => e === "sub")).toHaveLength(2);
|
||
});
|
||
|
||
it("不变式回归:spawn 的 scope 恒以 subagent 为段前缀", async () => {
|
||
const p = new InlineSubagentProvider(async () => 0);
|
||
for (const s of [undefined, "", "x", "x.y", ".b", "a..b"]) {
|
||
const r = await p.spawn("p", s === undefined ? undefined : { scope: s });
|
||
expect(
|
||
r.scope === SUBAGENT_SCOPE_ROOT ||
|
||
r.scope.startsWith(SUBAGENT_SCOPE_ROOT + "."),
|
||
).toBe(true);
|
||
}
|
||
});
|
||
});
|