formal-proof-consistency.test.ts 15 KB

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