formal-proof-consistency.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // formal-proof 全枚举 ↔ 投影 guard 一致性(13-golden-test-mapping §结构性 8)。
  2. // packages/formal-proof/src/model.ts 的 evaluate 是可执行裁决表(02-projection「规则模块下沉」);
  3. // 本测试机械对账:每个 coherent ProductContext × Candidate 组合的 Decision,
  4. // 必须与投影同源派生(computeAvailability / computeInputRouting)一致。
  5. //
  6. // 对账面(v4 A 区可观测量,10 §4.2.2):
  7. // compact / slashCompact → availability.compact(含 reasonCode ↔ ruleId 映射)
  8. // sendText / setGoal → inputRouting.mode(allow→startNow / enqueue→enqueue / reject→reject)
  9. // 不在对账面的候选:
  10. // forkLatest/forkOld/editLatest/editOld —— 行级动作(RowActions §4.4.1),M3 rows guard 接线时对账;
  11. // system 候选 —— 状态推进由 reducer 事件流黄金测试覆盖(product-projection.test.ts)。
  12. import { describe, expect, it } from "vitest";
  13. import {
  14. evaluate,
  15. userCandidates,
  16. type Candidate,
  17. type ProductContext,
  18. } from "@zcode/formal-proof/model";
  19. import type { SessionEvent } from "@zcode/contracts";
  20. import { SessionEventType } from "@zcode/contracts";
  21. import {
  22. ProductProjection,
  23. computeAvailability,
  24. computeInputRouting,
  25. type AvailabilityContext,
  26. } from "../src/zcode-protocol-v4/index.js";
  27. // ── ProductContext(formal-proof 词表)→ AvailabilityContext(v4 guard 输入面)──
  28. const RUN_PHASES = ["idle", "running", "completed", "compacting", "goalVerifying"] as const;
  29. const QUEUES = ["empty", "text", "goal", "compact", "mixed"] as const;
  30. const COMPACT_MEMORIES = ["never", "compactable", "justCompacted", "notNeeded"] as const;
  31. const GOALS = ["none", "active", "verifying", "verified", "failed"] as const;
  32. const TURNS = ["latest", "old", "none"] as const;
  33. function toAvailabilityContext(context: ProductContext): AvailabilityContext {
  34. return {
  35. phase:
  36. context.runPhase === "running" || context.runPhase === "goalVerifying"
  37. ? "running"
  38. : context.runPhase === "idle"
  39. ? "draft"
  40. : "completedSuccess",
  41. goalStatus:
  42. context.goal === "none"
  43. ? null
  44. : context.goal === "verifying"
  45. ? "verifying"
  46. : context.goal === "verified"
  47. ? "verified"
  48. : context.goal === "failed"
  49. ? "failed"
  50. : "active",
  51. compacting: context.runPhase === "compacting",
  52. goalVerifying: context.runPhase === "goalVerifying",
  53. queueLength: context.queue === "empty" ? 0 : 1,
  54. // formal-proof 无 autoDrain 维度;不变量:completed 下滞留的 queue 只可能是
  55. // autoDrain=false 的 held queue(autoDrain=true 时 assistantComplete 即消费)。
  56. autoDrain: context.queue === "empty",
  57. };
  58. }
  59. // coherent 剪枝:goal=verifying ⇔ runPhase=goalVerifying(其余组合事件流不可达,
  60. // 由 feature-boundary 剪枝规则背书,非本测试对账对象)。
  61. function isCoherent(context: ProductContext): boolean {
  62. return (context.runPhase === "goalVerifying") === (context.goal === "verifying");
  63. }
  64. // 裁决差异表(显式登记,禁止静默跳过):
  65. // justCompactedNoNeed —— v4 裁决:compact 保持可点击,noop 由 compact marker 表达
  66. // (10 §4.4.7 noop 状态;G 组黄金测试已覆盖),availability 不禁用。
  67. const DECISION_OVERRIDES = new Set(["justCompactedNoNeed"]);
  68. // formal-proof ruleId → product-protocol guard reasonCode(09 §词表)。
  69. const REASON_CODE_BY_RULE_ID: Record<string, string> = {
  70. compactingCannotCompact: "compactOperationLock",
  71. idleCannotCompact: "idleCannotCompact",
  72. // 2026-07-05 重裁决:compacting 输入 enqueue(原 compactingCannotSend reject 已废弃)。
  73. compactingAcceptsFutureInput: "compactingAcceptsFutureInput",
  74. goalVerifierAcceptsFutureInput: "goalVerifierAcceptsFutureInput",
  75. heldQueueInputRequiresChoice: "heldQueueInputRequiresChoice",
  76. };
  77. function* coherentContexts(): Generator<ProductContext> {
  78. for (const runPhase of RUN_PHASES) {
  79. for (const queue of QUEUES) {
  80. for (const compactMemory of COMPACT_MEMORIES) {
  81. for (const canCompactAgain of [true, false]) {
  82. for (const goal of GOALS) {
  83. for (const selectedTurn of TURNS) {
  84. for (const forked of [true, false]) {
  85. const context: ProductContext = {
  86. runPhase,
  87. queue,
  88. compactMemory,
  89. canCompactAgain,
  90. goal,
  91. selectedTurn,
  92. forked,
  93. };
  94. if (isCoherent(context)) yield context;
  95. }
  96. }
  97. }
  98. }
  99. }
  100. }
  101. }
  102. }
  103. function candidateById(id: string): Candidate {
  104. const candidate = userCandidates.find((item) => item.id === id);
  105. if (!candidate) throw new Error(`unknown candidate: ${id}`);
  106. return candidate;
  107. }
  108. describe("formal-proof 全枚举 ↔ guard 同源派生一致", () => {
  109. it("compact/slashCompact:Decision ↔ availability.compact 全枚举一致", () => {
  110. let checked = 0;
  111. for (const context of coherentContexts()) {
  112. const availability = computeAvailability(toAvailabilityContext(context));
  113. for (const candidateId of ["compact", "slashCompact"]) {
  114. const decision = evaluate(context, candidateById(candidateId));
  115. if (DECISION_OVERRIDES.has(decision.ruleId)) {
  116. // 裁决差异:见 DECISION_OVERRIDES 注释。
  117. expect(availability.compact.allowed).toBe(true);
  118. checked += 1;
  119. continue;
  120. }
  121. const label = `${JSON.stringify(context)} × ${candidateId} → ${decision.ruleId}`;
  122. if (decision.kind === "allow" || decision.kind === "enqueue") {
  123. // compact enqueue 与立即执行共享同一个可用入口;真正的 route 由命令 admission
  124. // 读取 inputRouting/held queue 决定,availability 只表达是否允许提交该意图。
  125. expect(availability.compact, label).toEqual({ allowed: true });
  126. } else if (decision.kind === "reject") {
  127. const reasonCode = REASON_CODE_BY_RULE_ID[decision.ruleId];
  128. expect(reasonCode, `未登记的 reject ruleId:${label}`).toBeDefined();
  129. expect(availability.compact, label).toEqual({
  130. allowed: false,
  131. reasonCode,
  132. });
  133. } else {
  134. throw new Error(`compact 候选出现未预期裁决种类:${label}`);
  135. }
  136. checked += 1;
  137. }
  138. }
  139. // 全枚举非空防呆:coherent 上下文 × 2 候选应达千级组合。
  140. expect(checked).toBeGreaterThan(3000);
  141. });
  142. it("sendText/setGoal:Decision ↔ inputRouting.mode 全枚举一致", () => {
  143. let checked = 0;
  144. for (const context of coherentContexts()) {
  145. const routing = computeInputRouting(toAvailabilityContext(context), "queue");
  146. for (const candidateId of ["sendText", "setGoal"]) {
  147. const decision = evaluate(context, candidateById(candidateId));
  148. const label = `${JSON.stringify(context)} × ${candidateId} → ${decision.ruleId}`;
  149. if (decision.kind === "allow") {
  150. expect(routing.mode, label).toBe("startNow");
  151. } else if (decision.kind === "enqueue") {
  152. expect(routing.mode, label).toBe("enqueue");
  153. // 维护/验证 work 入队必须带 reasonCode(催化 UI 提示「忙态中,已入队」)。
  154. if (
  155. decision.ruleId === "compactingAcceptsFutureInput" ||
  156. decision.ruleId === "goalVerifierAcceptsFutureInput"
  157. ) {
  158. expect(routing.reasonCode, label).toBe(REASON_CODE_BY_RULE_ID[decision.ruleId]);
  159. }
  160. } else if (decision.kind === "choice") {
  161. // heldQueueInputRequiresChoice(2026-07-05 裁决):held 输入让用户裁决。
  162. expect(routing.mode, label).toBe("choice");
  163. expect(routing.reasonCode, label).toBe(REASON_CODE_BY_RULE_ID[decision.ruleId]);
  164. } else if (decision.kind === "reject") {
  165. expect(routing.mode, label).toBe("reject");
  166. expect(routing.reasonCode, label).toBe(REASON_CODE_BY_RULE_ID[decision.ruleId]);
  167. } else if (decision.kind === "undefined") {
  168. // formal-proof 未定义区:不作为一致性断言对象;登记数量防呆
  169. // (膨胀说明规则被删)。
  170. checked -= 1;
  171. } else {
  172. throw new Error(`send 候选出现未预期裁决种类:${label}`);
  173. }
  174. checked += 1;
  175. }
  176. }
  177. expect(checked).toBeGreaterThan(2000);
  178. });
  179. });
  180. // ── reducer 落地对账:五个 runPhase 原型经真实事件流构造,guard 与裁决表一致 ──
  181. describe("formal-proof 原型 ↔ reducer 事件流投影一致", () => {
  182. let eventSeq = 0;
  183. function makeEvent(type: SessionEvent["type"], payload: unknown, turnId?: string): SessionEvent {
  184. eventSeq += 1;
  185. return {
  186. id: `event-${eventSeq}`,
  187. sessionId: "session-1",
  188. turnId,
  189. type,
  190. timestamp: new Date(1_700_000_000_000 + eventSeq * 1000),
  191. traceId: "trace-1",
  192. sequenceNumber: eventSeq,
  193. payload,
  194. } as SessionEvent;
  195. }
  196. function project(events: SessionEvent[]): ProductProjection {
  197. const projection = new ProductProjection("session-1", "epoch-1");
  198. for (const event of events) projection.applyEvent(event);
  199. return projection;
  200. }
  201. const created = () =>
  202. makeEvent(SessionEventType.SessionCreated, {
  203. mode: "default",
  204. contextWindow: 1000,
  205. });
  206. const turnStarted = () =>
  207. makeEvent(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, "turn-1");
  208. const turnDone = () =>
  209. makeEvent(
  210. SessionEventType.TurnComplete,
  211. {
  212. response: "ok",
  213. tokenCount: 1,
  214. toolCallCount: 0,
  215. duration: 10,
  216. resultType: "success",
  217. },
  218. "turn-1",
  219. );
  220. it("idle(draft):compact 拒绝 idleCannotCompact,输入 startNow", () => {
  221. const snapshot = project([created()]).getSnapshot();
  222. expect(snapshot.availability.compact).toEqual({
  223. allowed: false,
  224. reasonCode: "idleCannotCompact",
  225. });
  226. expect(snapshot.inputRouting.mode).toBe("startNow");
  227. });
  228. it("running:compact 可提交并进入 typed queue,输入 enqueue", () => {
  229. const snapshot = project([created(), turnStarted()]).getSnapshot();
  230. expect(snapshot.availability.compact).toEqual({ allowed: true });
  231. expect(snapshot.inputRouting.mode).toBe("enqueue");
  232. });
  233. it("completed:compact 放行,输入 startNow", () => {
  234. const snapshot = project([created(), turnStarted(), turnDone()]).getSnapshot();
  235. expect(snapshot.availability.compact).toEqual({ allowed: true });
  236. expect(snapshot.inputRouting.mode).toBe("startNow");
  237. });
  238. it("compacting:compact 拒绝 compactOperationLock,输入 enqueue(compactingAcceptsFutureInput);终态解锁", () => {
  239. const projection = project([
  240. created(),
  241. turnStarted(),
  242. turnDone(),
  243. makeEvent(SessionEventType.CompactStarted, {
  244. operationId: "op-1",
  245. messageId: "msg-1",
  246. status: "started",
  247. trigger: "manual",
  248. display: "separator",
  249. }),
  250. ]);
  251. const during = projection.getSnapshot();
  252. expect(during.control.activeWorks).toEqual([expect.objectContaining({ kind: "compact" })]);
  253. expect(during.availability.compact).toEqual({
  254. allowed: false,
  255. reasonCode: "compactOperationLock",
  256. });
  257. expect(during.inputRouting).toEqual({
  258. mode: "enqueue",
  259. reasonCode: "compactingAcceptsFutureInput",
  260. });
  261. projection.applyEvent(
  262. makeEvent(SessionEventType.CompactCompleted, {
  263. operationId: "op-1",
  264. messageId: "msg-1",
  265. status: "completed",
  266. trigger: "manual",
  267. display: "separator",
  268. preCompactTokenCount: 800,
  269. postCompactTokenCount: 300,
  270. }),
  271. );
  272. const after = projection.getSnapshot();
  273. expect(after.control.activeWorks).toEqual([]);
  274. expect(after.availability.compact).toEqual({ allowed: true });
  275. expect(after.inputRouting.mode).toBe("startNow");
  276. });
  277. it("goalVerifying:消息与 compact 都可入队;验证通过后恢复立即执行", () => {
  278. const projection = project([
  279. created(),
  280. turnStarted(),
  281. turnDone(),
  282. makeEvent(SessionEventType.TargetChanged, {
  283. action: "set",
  284. source: "command",
  285. target: {
  286. sessionID: "session-1",
  287. targetID: "target-1",
  288. objective: "修绿测试",
  289. summaryTitle: null,
  290. status: "active",
  291. tokenBudget: null,
  292. tokensUsed: 0,
  293. timeUsedSeconds: 0,
  294. time: { created: 0, updated: 0 },
  295. },
  296. previousTarget: null,
  297. }),
  298. makeEvent(SessionEventType.TargetCompletionVerification, {
  299. targetId: "target-1",
  300. status: "started",
  301. verificationId: "verify-1",
  302. goalIteration: 1,
  303. }),
  304. ]);
  305. expect(projection.getSnapshot().availability.compact).toEqual({ allowed: true });
  306. expect(projection.getSnapshot().inputRouting).toEqual({
  307. mode: "enqueue",
  308. reasonCode: "goalVerifierAcceptsFutureInput",
  309. });
  310. projection.applyEvent(
  311. makeEvent(SessionEventType.TargetCompletionVerification, {
  312. targetId: "target-1",
  313. status: "completed",
  314. verificationId: "verify-1",
  315. goalIteration: 1,
  316. verification: { passed: true, reason: "ok" },
  317. }),
  318. );
  319. expect(projection.getSnapshot().availability.compact).toEqual({
  320. allowed: true,
  321. });
  322. });
  323. it("held(stop + 残留 queue):autoDrain=false,输入 choice(heldQueueInputRequiresChoice)", () => {
  324. const projection = project([
  325. created(),
  326. turnStarted(),
  327. makeEvent(
  328. SessionEventType.TurnSteerQueued,
  329. {
  330. pendingInputId: "pi-1",
  331. input: "顺便加个测试",
  332. inputPreview: "顺便加个测试",
  333. inputSize: 6,
  334. targetTurnId: "turn-1",
  335. queueLength: 1,
  336. },
  337. "turn-1",
  338. ),
  339. makeEvent(
  340. SessionEventType.TurnComplete,
  341. {
  342. response: "",
  343. tokenCount: 0,
  344. toolCallCount: 0,
  345. duration: 100,
  346. resultType: "cancelled",
  347. },
  348. "turn-1",
  349. ),
  350. ]);
  351. const snapshot = projection.getSnapshot();
  352. // stopKeepsQueueAndDisablesAutoDrain:queue 原样保留 + 不自动消费。
  353. expect(snapshot.queue.items).toHaveLength(1);
  354. expect(snapshot.queue.autoDrain).toBe(false);
  355. // heldQueueInputRequiresChoice(2026-07-05 裁决):不静默入队,让用户裁决。
  356. expect(snapshot.inputRouting).toEqual({
  357. mode: "choice",
  358. reasonCode: "heldQueueInputRequiresChoice",
  359. });
  360. // held 消解路径之一:queue 清空后回到 startNow(choice=clearQueueAndSend 的投影面)。
  361. projection.applyEvent(
  362. makeEvent(
  363. SessionEventType.TurnSteerDiscarded,
  364. { pendingInputIds: ["pi-1"], reason: "user_cleared" },
  365. "turn-1",
  366. ),
  367. );
  368. expect(projection.getSnapshot().inputRouting.mode).toBe("startNow");
  369. });
  370. });