proofdeck 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +23 -0
  3. package/README.md +97 -2
  4. package/README.zh-CN.md +89 -0
  5. package/bin/proofdeck.js +126 -0
  6. package/board/LICENSE +201 -0
  7. package/board/README.md +473 -0
  8. package/board/README.zh-CN.md +424 -0
  9. package/board/dist/_chk.db-shm +0 -0
  10. package/board/dist/_chk.db-wal +0 -0
  11. package/board/dist/adapters.d.ts +40 -0
  12. package/board/dist/adapters.d.ts.map +1 -0
  13. package/board/dist/adapters.js +124 -0
  14. package/board/dist/adapters.js.map +1 -0
  15. package/board/dist/board.d.ts +628 -0
  16. package/board/dist/board.d.ts.map +1 -0
  17. package/board/dist/board.js +2767 -0
  18. package/board/dist/board.js.map +1 -0
  19. package/board/dist/cli.d.ts +3 -0
  20. package/board/dist/cli.d.ts.map +1 -0
  21. package/board/dist/cli.js +1663 -0
  22. package/board/dist/cli.js.map +1 -0
  23. package/board/dist/config.d.ts +57 -0
  24. package/board/dist/config.d.ts.map +1 -0
  25. package/board/dist/config.js +99 -0
  26. package/board/dist/config.js.map +1 -0
  27. package/board/dist/db.d.ts +9 -0
  28. package/board/dist/db.d.ts.map +1 -0
  29. package/board/dist/db.js +506 -0
  30. package/board/dist/db.js.map +1 -0
  31. package/board/dist/git.d.ts +35 -0
  32. package/board/dist/git.d.ts.map +1 -0
  33. package/board/dist/git.js +147 -0
  34. package/board/dist/git.js.map +1 -0
  35. package/board/dist/index.d.ts +18 -0
  36. package/board/dist/index.d.ts.map +1 -0
  37. package/board/dist/index.js +13 -0
  38. package/board/dist/index.js.map +1 -0
  39. package/board/dist/mcp-config.d.ts +26 -0
  40. package/board/dist/mcp-config.d.ts.map +1 -0
  41. package/board/dist/mcp-config.js +88 -0
  42. package/board/dist/mcp-config.js.map +1 -0
  43. package/board/dist/mcp.d.ts +3 -0
  44. package/board/dist/mcp.d.ts.map +1 -0
  45. package/board/dist/mcp.js +949 -0
  46. package/board/dist/mcp.js.map +1 -0
  47. package/board/dist/quickstart.d.ts +75 -0
  48. package/board/dist/quickstart.d.ts.map +1 -0
  49. package/board/dist/quickstart.js +156 -0
  50. package/board/dist/quickstart.js.map +1 -0
  51. package/board/dist/serve.d.ts +10 -0
  52. package/board/dist/serve.d.ts.map +1 -0
  53. package/board/dist/serve.js +445 -0
  54. package/board/dist/serve.js.map +1 -0
  55. package/board/dist/signing.d.ts +18 -0
  56. package/board/dist/signing.d.ts.map +1 -0
  57. package/board/dist/signing.js +26 -0
  58. package/board/dist/signing.js.map +1 -0
  59. package/board/dist/sync.d.ts +49 -0
  60. package/board/dist/sync.d.ts.map +1 -0
  61. package/board/dist/sync.js +158 -0
  62. package/board/dist/sync.js.map +1 -0
  63. package/board/dist/types.d.ts +359 -0
  64. package/board/dist/types.d.ts.map +1 -0
  65. package/board/dist/types.js +20 -0
  66. package/board/dist/types.js.map +1 -0
  67. package/board/docs/adr/0001-shared-worktree-collision.md +102 -0
  68. package/board/docs/adr/0001-shared-worktree-collision.zh-CN.md +90 -0
  69. package/board/docs/attribution.md +123 -0
  70. package/board/docs/attribution.zh-CN.md +104 -0
  71. package/board/docs/development-workflow.md +81 -0
  72. package/board/docs/development-workflow.zh-CN.md +75 -0
  73. package/board/docs/diagrams/banner.png +0 -0
  74. package/board/docs/diagrams/banner.svg +1 -0
  75. package/board/docs/diagrams/before-after.png +0 -0
  76. package/board/docs/diagrams/before-after.svg +1 -0
  77. package/board/docs/diagrams/governance-chain.png +0 -0
  78. package/board/docs/diagrams/governance-chain.svg +1 -0
  79. package/board/docs/diagrams/value-flow.png +0 -0
  80. package/board/docs/diagrams/value-flow.svg +1 -0
  81. package/board/docs/entry-point.md +81 -0
  82. package/board/docs/entry-point.zh-CN.md +65 -0
  83. package/board/docs/kanban.png +0 -0
  84. package/board/docs/octoryn-mark.png +0 -0
  85. package/board/docs/registry-metadata.md +34 -0
  86. package/board/docs/registry-metadata.zh-CN.md +30 -0
  87. package/board/package.json +87 -0
  88. package/config.example.json +71 -0
  89. package/daemon.js +1112 -0
  90. package/docs/assets/demo.gif +0 -0
  91. package/docs/demo-run.mjs +61 -0
  92. package/docs/render-demo.py +94 -0
  93. package/e2e/verify-acceptance.mjs +150 -0
  94. package/e2e/verify-antifraud.mjs +128 -0
  95. package/e2e/verify-caps.mjs +46 -0
  96. package/e2e/verify-checkpoint.mjs +208 -0
  97. package/e2e/verify-firstclass.mjs +110 -0
  98. package/e2e/verify-judge.mjs +52 -0
  99. package/e2e/verify-lease.mjs +95 -0
  100. package/e2e/verify-replay.mjs +92 -0
  101. package/e2e/verify-resilience.mjs +323 -0
  102. package/e2e/verify-review.mjs +86 -0
  103. package/e2e/verify-scheduling.mjs +110 -0
  104. package/e2e/verify-schema-evolution.mjs +107 -0
  105. package/e2e/verify-sla-digest.mjs +105 -0
  106. package/guard.js +97 -0
  107. package/lib/adapters/codex.js +206 -0
  108. package/lib/billing-convert.js +57 -0
  109. package/lib/board.js +46 -0
  110. package/lib/caps.js +35 -0
  111. package/lib/checkpoint.js +130 -0
  112. package/lib/gating.js +218 -0
  113. package/lib/guard-core.mjs +108 -0
  114. package/lib/http.js +161 -0
  115. package/lib/judge.js +89 -0
  116. package/lib/lease.js +93 -0
  117. package/lib/notify.js +56 -0
  118. package/lib/platform.js +120 -0
  119. package/lib/replay.js +68 -0
  120. package/lib/review.js +40 -0
  121. package/lib/runner.js +152 -0
  122. package/lib/schedule.js +59 -0
  123. package/lib/sla.js +42 -0
  124. package/lib/spans.js +36 -0
  125. package/lib/starve.js +43 -0
  126. package/lib/store.js +109 -0
  127. package/lib/supply.js +101 -0
  128. package/lib/usage.js +103 -0
  129. package/lib/verify.js +223 -0
  130. package/lib/watchdog-core.mjs +68 -0
  131. package/lib/watchdog-worker.mjs +75 -0
  132. package/package.json +55 -4
  133. package/scripts/run-daemon.sh +18 -0
  134. package/scripts/run-e2e.mjs +39 -0
@@ -0,0 +1,208 @@
1
+ // #29 分段续跑判据(离线,零 API):题面按段分叉、检查点两种来源、停手判据表、段号进台账。
2
+ // 跑法:node e2e/verify-checkpoint.mjs
3
+ import { mkdtempSync, writeFileSync, mkdirSync, readFileSync, existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { fileURLToPath } from "node:url";
7
+ import { dirname } from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+
10
+ const BASE = join(dirname(fileURLToPath(import.meta.url)), "..");
11
+ const U = (p) => pathToFileURL(p).href; // Windows 下裸 D:/ 走 ESM loader 会报 ERR_UNSUPPORTED_ESM_URL_SCHEME
12
+ const { maxSegments, capture, renderPriming, shouldStopSegmenting, segmentOverrun, CP_NAME, SEGMENT_CAP } =
13
+ await import(U(`${BASE}/lib/checkpoint.js`));
14
+ const { getAdapter } = await import(U(`${BASE}/lib/runner.js`));
15
+ const { normalizeUsage, missingUsage } = await import(U(`${BASE}/lib/usage.js`));
16
+ const { isStarved, maxStarveRun, starveTotal, isStarveLoop, STARVE_LIMIT } = await import(U(`${BASE}/lib/starve.js`));
17
+
18
+ const TS = new Date().toISOString().replace(/[:.]/g, "-");
19
+ const ROOT = join(BASE, "out", `verify-checkpoint-${TS}`);
20
+ mkdirSync(ROOT, { recursive: true });
21
+
22
+ const checks = [];
23
+ const ck = (name, fn) => { try { checks.push([name, fn()]); } catch (e) { checks.push([name, [false, `抛错 ${e.message}`]]); } };
24
+
25
+ // 题面分叉用真函数:从 daemon.js 源码里抠出 buildPrompt 体,注入同样的 trunc 求值。
26
+ // (不复制粘贴一份题面到测试里——那种测试只能证明测试自己没改。)
27
+ const src = readFileSync(join(BASE, "daemon.js"), "utf8");
28
+ const m = /function buildPrompt\(key, task, dispatch, agent[^)]*\)\s*\{\n([\s\S]*?)\n\}/.exec(src);
29
+ if (!m) { console.log("FAIL 取不到 buildPrompt 体,daemon.js 结构变了,这个测试要跟着改"); process.exit(1); }
30
+ const trunc = (s, n) => (s.length > n ? s.slice(0, n) + "\n…[截断]" : s);
31
+ const buildPrompt = new Function("key", "task", "dispatch", "agent", "totalSegments", "trunc", m[1]);
32
+
33
+ // ---- 1) segments 解析 ----
34
+ ck("不写 segments ⇒ 1 段(今天的行为)", () => [maxSegments({}) === 1, `得 ${maxSegments({})}`]);
35
+ ck("segments=1 / 空串 / 垃圾值都按 1 段", () =>
36
+ [maxSegments({ segments: "1" }) === 1 && maxSegments({ segments: "" }) === 1 && maxSegments({ segments: "abc" }) === 1,
37
+ `${maxSegments({ segments: "1" })}/${maxSegments({ segments: "" })}/${maxSegments({ segments: "abc" })}`]);
38
+ ck(`segments=5 夹到封顶 ${SEGMENT_CAP}`, () => [maxSegments({ segments: "5" }) === SEGMENT_CAP, `得 ${maxSegments({ segments: "5" })}`]);
39
+ ck("segments=3 原样", () => [maxSegments({ segments: "3" }) === 3, `得 ${maxSegments({ segments: "3" })}`]);
40
+
41
+ // ---- 2) 题面:单段字节不变,分段才提 CHECKPOINT.md ----
42
+ const one = buildPrompt("task:t1", { number: 1, title: "T" }, { path: "D:/x.md", text: "正文" }, "codex", 1, trunc);
43
+ const two = buildPrompt("task:t1", { number: 1, title: "T" }, { path: "D:/x.md", text: "正文" }, "codex", 2, trunc);
44
+ ck("单段题面不提 CHECKPOINT.md", () => [!one.includes(CP_NAME) && one.includes("3) 最后一条回复"), "题面第 4 条漏进单段"]);
45
+ ck("分段题面才要求写 CHECKPOINT.md", () => [two.includes(CP_NAME) && two.includes("分 2 段"), "分段了却没写检查点要求"]);
46
+ ck("分段只多这一条,前三条一字不差", () => {
47
+ const head = (s) => s.split("\n").filter((l) => /^\d\) /.test(l)).slice(0, 3).join("\n");
48
+ return [head(one) === head(two), "前三条要求被改动了"];
49
+ });
50
+
51
+ // ---- 3) 检查点两种来源 ----
52
+ const work = mkdtempSync(join(tmpdir(), "cpwork-"));
53
+ mkdirSync(join(work, "sub"), { recursive: true });
54
+ writeFileSync(join(work, "answer.md"), "# 答案\n前三题已做", "utf8");
55
+ writeFileSync(join(work, "sub", "run_round3.py"), "print(3)", "utf8");
56
+ const runDir = join(ROOT, "seg1");
57
+ mkdirSync(runDir, { recursive: true });
58
+ writeFileSync(join(runDir, "meta.json"), JSON.stringify({ agent: "trae", segment: 1 }), "utf8");
59
+
60
+ const result1 = { exitCode: 0, killed: false, stalled: false, items: 12, threadId: "thr-abc-123", model: "mimo-v2.6-pro", agentSuccess: false };
61
+ const usage1 = { ...missingUsage("trae", "测试用"), steps: 15, maxSteps: 15, overflow: true };
62
+
63
+ const derived = capture({ agent: "trae", workdir: work, runDir, segment: 1, result: result1, usage: usage1, why: "agent 自报 success=false" });
64
+ ck("无 CHECKPOINT.md ⇒ kind=derived 并点名只含事实", () =>
65
+ [derived.kind === "derived" && derived.text.includes("只含事实、不含模型自述"), `kind=${derived.kind}`]);
66
+ ck("派生检查点带 workdir 实际文件(含子目录)", () =>
67
+ [derived.text.includes("answer.md") && derived.text.includes("sub/run_round3.py") && derived.fileCount === 2,
68
+ `列到 ${derived.fileCount} 个`]);
69
+ ck("派生检查点带上限读数与 thread", () =>
70
+ [derived.text.includes("steps=15/15(达上限)") && derived.text.includes("thr-abc-123") && derived.text.includes("mimo-v2.6-pro"), "漏了用量/thread/model"]);
71
+ ck("检查点落盘在本段 runDir 且带段号", () =>
72
+ [derived.file === join(runDir, "checkpoint-seg1.md") && existsSync(derived.file), derived.file]);
73
+
74
+ writeFileSync(join(work, CP_NAME), "已完成:前三题。现存:answer.md。下一步:做第 4、5 题。", "utf8");
75
+ const agentCp = capture({ agent: "trae", workdir: work, runDir, segment: 1, result: result1, usage: usage1, why: "超时被杀" });
76
+ ck("有 CHECKPOINT.md ⇒ kind=agent 且正文进检查点", () =>
77
+ [agentCp.kind === "agent" && agentCp.text.includes("做第 4、5 题"), `kind=${agentCp.kind}`]);
78
+ ck("agent 自写仍附桥侧事实与文件清单(自述不当唯一依据)", () =>
79
+ [agentCp.text.includes("桥侧事实") && agentCp.text.includes("工作目录实际文件"), "只抄了模型的话"]);
80
+
81
+ // ---- 4) 下一段题面 ----
82
+ const priming = renderPriming({ segment: 2, total: 3, cp: agentCp, why: "agent 自报 success=false", resumed: true });
83
+ ck("续跑题面标出段号/死因/检查点路径", () =>
84
+ [priming.includes("第 2/3 段") && priming.includes("success=false") && priming.includes("checkpoint-seg1.md"), "缺锚点"]);
85
+ ck("续跑题面要求以磁盘为准核对", () => [priming.includes("以磁盘为准"), "没让下一段核对自述"]);
86
+ ck("能续会话与不能续会话的说法不同", () => {
87
+ const fresh = renderPriming({ segment: 2, total: 3, cp: agentCp, why: "rc=1", resumed: false });
88
+ return [priming.includes("接上上一段的会话") && !priming.includes("新会话")
89
+ && fresh.includes("新会话") && !fresh.includes("接上上一段的会话"), "两种说法混了"];
90
+ });
91
+
92
+ // ---- 5) 停手判据表 ----
93
+ const T = (o) => shouldStopSegmenting({ ok: false, segment: 1, total: 3, killedBy: null, stopFilePresent: false, supplyLatched: false, ...o });
94
+ ck("成功 ⇒ 不再起段", () => [String(T({ ok: true })).includes("成功"), `得 ${T({ ok: true })}`]);
95
+ ck("人工掐死 ⇒ 停(人的意图高于段数)", () => [String(T({ killedBy: "manual" })).includes("人工掐死"), "还会续跑"]);
96
+ ck("STOP 在位 ⇒ 停", () => [String(T({ stopFilePresent: true })).includes("STOP"), "还会续跑"]);
97
+ ck("供应方熔断 ⇒ 停(白烧)", () => [String(T({ supplyLatched: true })).includes("熔断"), "还会续跑"]);
98
+ ck("末段仍未收敛 ⇒ 停并说「分段用尽」", () => [String(T({ segment: 3, total: 3 })).includes("分段用尽"), `得 ${T({ segment: 3, total: 3 })}`]);
99
+ ck("普通失败 + 还有段数 ⇒ 可以再起一段", () => [T({ segment: 1, total: 2, why: "rc=1" }) === null, `得 ${T({ segment: 1, total: 2 })}`]);
100
+ ck("饿死成环 ⇒ 停(对一个纯配置缺陷,续跑只再烧一遍预算)", () =>
101
+ [String(T({ starved: true })).includes("饿死"), "还会续跑"]);
102
+ ck("反面对照:starved=false 不该被误当环路,仍可起段", () => [T({ starved: false }) === null, `得 ${T({ starved: false })}`]);
103
+
104
+ // ---- 5c) 调用点硬闸:判据万一再写反,段号这层也得拦住(P0 回归)----
105
+ ck("硬闸:单卡预算 1 段时起第 2 段 ⇒ 拦", () =>
106
+ [segmentOverrun({ segment: 2, total: 1 }) === true && segmentOverrun({ segment: 2, total: 3 }) === false, "拦错或放错"]);
107
+ ck("硬闸:越过全局封顶(预算被写大也拦)", () =>
108
+ [segmentOverrun({ segment: SEGMENT_CAP + 1, total: 99 }) === true, `封顶 ${SEGMENT_CAP} 没拦住`]);
109
+ ck("反面对照:合法末段不许误拦(seg=total 都要放它跑完)", () =>
110
+ [!segmentOverrun({ segment: 3, total: 3 }) && !segmentOverrun({ segment: SEGMENT_CAP, total: SEGMENT_CAP }) && !segmentOverrun({ segment: 1, total: 1 }), "误拦合法段"]);
111
+ ck("P0 回归:seg=2..7 在 total=1 下全部被拦", () =>
112
+ [[2, 3, 4, 5, 6, 7].every((s) => segmentOverrun({ segment: s, total: 1 })), "仍有段能溜过去"]);
113
+
114
+ // ---- 5b) 饿死判据打在真实轨迹上(零 API,读历史 run 目录;期望值先跑探针量出来,不许猜)----
115
+ // OSS 环境没有内部 runs/ 标本 ⇒ 整节显式 SKIP(不许静默算过);有标本的环境(含 trae 适配器)才跑。
116
+ const SPECIMEN = [
117
+ // max_tokens:4096 时代的死循环:14 次调用 6 次饿死、最长连续 4 ⇒ 判死
118
+ { run: "runs/<specimen-4096-loop>", total: 6, best: 4, loop: true },
119
+ // 反面对照:同一预算下 success=true 的轮次,开头连着 2 次截断后自己走通 ⇒ 阈值 3 不误伤
120
+ { run: "runs/<specimen-4096-control>", total: 2, best: 2, loop: false },
121
+ // 抬到 32768 之后:一次都没有
122
+ { run: "runs/<specimen-32768-clean>", total: 0, best: 0, loop: false },
123
+ ];
124
+ const presentSpecimens = SPECIMEN.filter((s) => existsSync(join(BASE, s.run, "trae.traj.json")));
125
+ if (presentSpecimens.length === 0) {
126
+ console.log("SKIP 5b 真实轨迹饿死标本(本环境无内部 runs/ 标本;判据逻辑已由 5/5c 的合成用例覆盖)");
127
+ }
128
+ else {
129
+ const traeAdapter = await import(U(`${BASE}/lib/adapters/trae.js`));
130
+ for (const s of presentSpecimens) {
131
+ ck(`真实轨迹读数 ${s.run}`, () => {
132
+ const f = join(BASE, s.run, "trae.traj.json");
133
+ const li = JSON.parse(readFileSync(f, "utf8")).llm_interactions ?? [];
134
+ const meta = traeAdapter.readMeta({ lastMsgFile: f });
135
+ return [
136
+ starveTotal(li) === s.total && maxStarveRun(li) === s.best && isStarveLoop(li) === s.loop
137
+ && meta.starvedTotal === s.total && meta.starve === s.best,
138
+ `判据 total=${starveTotal(li)} best=${maxStarveRun(li)} loop=${isStarveLoop(li)} / 适配器 ${meta.starvedTotal}/${meta.starve},期望 ${s.total}/${s.best}/${s.loop}`,
139
+ ];
140
+ });
141
+ }
142
+ }
143
+ ck("判据不吃 reasoning_tokens(该面轨迹里它恒为 0,仍要判得出来)", () => {
144
+ const mk = (n) => Array.from({ length: n }, () => ({ response: { finish_reason: "length", content: "", tool_calls: [], usage: { reasoning_tokens: 0 } } }));
145
+ return [isStarveLoop(mk(STARVE_LIMIT)) && !isStarveLoop(mk(STARVE_LIMIT - 1)) && isStarved(mk(1)[0].response),
146
+ `阈值错(limit=${STARVE_LIMIT})`];
147
+ });
148
+ ck("带 tool_calls 的 length 不算饿死(模型确实在动手,只是这一步没写完)", () => {
149
+ const li = [{ response: { finish_reason: "length", content: "", tool_calls: [{ name: "str_replace_based_edit_tool" }] } }];
150
+ return [!isStarved(li[0].response) && maxStarveRun(li) === 0 && !isStarveLoop(li), "把在落笔的调用误判成饿死"];
151
+ });
152
+ ck("content 非空的 length 不算饿死(写出了一半)", () =>
153
+ [!isStarved({ finish_reason: "length", content: "写出了一半的正文", tool_calls: [] }), "误判成饿死"]);
154
+ ck("fr=stop/tool_calls 永不计入饿死", () =>
155
+ [!isStarved({ finish_reason: "stop", content: "", tool_calls: [] }) && !isStarved({ finish_reason: "tool_calls", content: "", tool_calls: [] }), "误判"]);
156
+
157
+ // ---- 6) 谁能真续会话:内置参考适配器 codex 有 resumeSpec;未注册面必须显式报错 ----
158
+ ck("codex 有 resumeSpec", () => [typeof getAdapter("codex").resumeSpec === "function", "没有"]);
159
+ ck("未注册适配器 getAdapter 直接抛错(不静默兜底)", () => {
160
+ try { getAdapter("no-such-face"); return [false, "竟然没抛"]; }
161
+ catch (e) { return [String(e.message).includes("not registered"), e.message]; }
162
+ });
163
+ ck("codex resumeSpec 无 threadId 时返回 null(退回新会话)", () => {
164
+ const codex = getAdapter("codex");
165
+ return [codex.resumeSpec({ agentCfg: {}, runDir, promptFile: "p", workdir: work, fm: {}, resume: { segment: 2 } }) === null, "没有 threadId 也硬构"];
166
+ });
167
+ ck("codex resumeSpec 构出 exec resume <thread> + stdin 题面", () => {
168
+ const spec = getAdapter("codex").resumeSpec({
169
+ agentCfg: { node: "node", script: "cx.js", sandbox: "workspace-write", extraArgs: ["--skip-git-repo-check"] },
170
+ runDir, promptFile: join(runDir, "prompt.md"), workdir: work, fm: {}, resume: { threadId: "T-1", segment: 2 },
171
+ });
172
+ const j = spec.args.join(" ");
173
+ return [spec.resumed === true && j.includes("exec resume T-1") && j.includes('--json')
174
+ && j.includes('-c sandbox_mode="workspace-write"') && spec.args.at(-1) === "-" && spec.cwd === work
175
+ && !j.includes(" -C "), `args=${j}`];
176
+ });
177
+
178
+ // ---- 7) 台账:一行一段,段号必须留痕 ----
179
+ ck("readUsage 拒绝对 resume 段用 rollout 累计兜底", () => {
180
+ const dir = join(ROOT, "codex-resume-seg");
181
+ mkdirSync(dir, { recursive: true });
182
+ writeFileSync(join(dir, "meta.json"), JSON.stringify({ agent: "codex", segment: 2, resumed: true }), "utf8");
183
+ writeFileSync(join(dir, "codex.jsonl"), JSON.stringify({ type: "session.config.loaded" }) + "\n", "utf8");
184
+ const codex = getAdapter("codex");
185
+ const u = codex.readUsage({ runDir: dir, agentCfg: { env: { CODEX_HOME: join(ROOT, "fake-codex-home") } } });
186
+ const e = normalizeUsage("codex", u);
187
+ return [e.missing === true && String(e.reason).includes("跨段不可拆") && e.prompt === null,
188
+ `missing=${e.missing} reason=${e.reason}`];
189
+ });
190
+ ck("段号进台账字段(缺省=1 段,历史行不炸)", () => {
191
+ const line = { ...normalizeUsage("codex", null), segment: 2, segments: 3, resumeFrom: join(ROOT, "seg1") };
192
+ const back = { ...normalizeUsage("codex", null), segment: 1, segments: 1, resumeFrom: null };
193
+ return [line.segment === 2 && line.segments === 3 && back.segment === 1 && back.resumeFrom === null, "段号没并进台账"];
194
+ });
195
+
196
+ // 留档本轮全部产物,出问题能对着看
197
+ for (const [n, c] of Object.entries({ "checkpoint-derived.md": derived.text, "checkpoint-agent.md": agentCp.text, "priming-resumed.md": priming })) {
198
+ writeFileSync(join(ROOT, n), c, "utf8");
199
+ }
200
+
201
+ let bad = 0;
202
+ for (const [name, [ok, why]] of checks) {
203
+ if (!ok) bad++;
204
+ console.log(`${ok ? "PASS" : "FAIL"} ${name}${ok ? "" : ` —— ${why}`}`);
205
+ }
206
+ console.log(`\n留档:${ROOT}`);
207
+ console.log(bad === 0 ? "CHECKPOINT PASS" : `CHECKPOINT FAIL(${bad} 条不过)`);
208
+ process.exit(bad === 0 ? 0 : 1);
@@ -0,0 +1,110 @@
1
+ // e2e: 共享包扩展一等公民(2026-10-07)—— tasks.acceptance 列 + Board.verify/verificationsFor
2
+ // 公开写 API + 桥侧裁决落链。纯 TEST board + temp store,不碰现网。
3
+ import { mkdtempSync, rmSync, readFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { pathToFileURL, fileURLToPath } from "node:url";
7
+
8
+ const boardCh = await import(new URL("../lib/board.js", import.meta.url).href);
9
+ const { Store } = await import(new URL("../lib/store.js", import.meta.url).href);
10
+ const V = await import(new URL("../lib/verify.js", import.meta.url).href);
11
+ const R = await import(new URL("../lib/review.js", import.meta.url).href);
12
+
13
+ let pass = 0, fail = 0;
14
+ const ok = (name, cond, detail = "") => {
15
+ if (cond) { pass++; console.log(`PASS ${name}${detail ? " — " + detail : ""}`); }
16
+ else { fail++; console.log(`FAIL ${name}${detail ? " — " + detail : ""}`); }
17
+ };
18
+
19
+ const dir = mkdtempSync(join(tmpdir(), "bridge-fc-"));
20
+ const storeDir = mkdtempSync(join(tmpdir(), "bridge-fcstore-"));
21
+ const store = new Store(join(storeDir, "state.json"));
22
+ await boardCh.init(fileURLToPath(new URL("../board", import.meta.url)));
23
+ const cfg = { dir: join(dir, "board"), identity: "bridge" };
24
+ const acc1 = { baseDir: join(dir, "fc-base"), mode: "auto", checks: [{ type: "fileExists", path: "out/a.md" }] };
25
+
26
+ try {
27
+ // ---- 1. Board 一等 acceptance 列 ----
28
+ await boardCh.withBoard(cfg, (b) => {
29
+ b.defineTask("zcode", "fc-1", { title: "first-class", acceptance: acc1 });
30
+ const t = b.getTask("fc-1");
31
+ ok("F1a defineTask 收 acceptance 并解析回对象", JSON.stringify(t.acceptance) === JSON.stringify(acc1), JSON.stringify(t.acceptance));
32
+ ok("F1b taskCard 透传", JSON.stringify(b.taskCard("fc-1").task.acceptance) === JSON.stringify(acc1));
33
+ });
34
+ // 列优先:再定义(只给 description 围栏块)不清掉列值 —— COALESCE 语义
35
+ await boardCh.withBoard(cfg, (b) => {
36
+ b.defineTask("zcode", "fc-1", { description: "x\n```bridge\n{\"acceptance\":{\"mode\":\"human\"}}\n```\n" });
37
+ ok("F1c 列值不被裸重定义清除(列优先于围栏块的前提)", b.getTask("fc-1").acceptance?.mode === "auto");
38
+ b.defineTask("zcode", "fc-2", { title: "no acc" });
39
+ ok("F1d 未声明的任务 acceptance=null", b.getTask("fc-2").acceptance === null);
40
+ const t3 = b.defineTask("zcode", "fc-3", { title: "str", acceptance: '{"mode":"cross"}' });
41
+ ok("F1e 字符串 spec 规范化为对象", t3.acceptance?.mode === "cross");
42
+ const t4 = b.defineTask("zcode", "fc-4", { title: "bad", acceptance: "not-json" });
43
+ ok("F1f 垃圾 spec fail-closed 落 null", t4.acceptance === null);
44
+ });
45
+
46
+ // ---- 2. Board.verify 公开写 API ----
47
+ await boardCh.withBoard(cfg, (b) => {
48
+ const ev = b.verify("bridge", "fc-1", "pass", { level: "V1", checks: [{ type: "fileExists", target: "out/a.md", pass: true }] });
49
+ ok("F2a verify 返回事件且 kind=verify", ev?.kind === "verify");
50
+ const vs = b.verificationsFor("fc-1");
51
+ ok("F2b verificationsFor 读回裁决", vs.length === 1 && vs[0].verdict === "pass" && vs[0].level === "V1", JSON.stringify(vs[0] ?? {}));
52
+ let threw = false;
53
+ try { b.verify("bridge", "fc-1", "PROBABLY"); } catch { threw = true; }
54
+ ok("F2c verdict fail-closed(非 pass/fail 抛错)", threw);
55
+ ok("F2d 未知任务 verify 返回 undefined", b.verify("bridge", "nope", "pass") === undefined);
56
+ ok("F2e 未知任务 verificationsFor 返回 []", b.verificationsFor("nope").length === 0);
57
+ ok("F2f 链完整", b.verifyChain().brokenAtSeq === null);
58
+ });
59
+
60
+ // ---- 3. 桥侧裁决落链(真实 Board + io=boardCh 模块)----
61
+ const vPass = { pass: true, checks: [{ type: "fileExists", target: "out/a.md", pass: true, evidence: "ok" }] };
62
+ const vFail = { pass: false, checks: [{ type: "countAtLeast", target: "out/a.md", pass: false, evidence: "missing" }] };
63
+ await boardCh.withBoard(cfg, (b) => {
64
+ V.applyVerifyPass({ b, io: boardCh, ID: "bridge", key: "fc-1", v: vPass });
65
+ const vs = b.verificationsFor("fc-1");
66
+ ok("F3a applyVerifyPass 落 verify 事件", vs.length === 2 && vs[0].verdict === "pass" && vs[0].actor === "bridge", `n=${vs.length}`);
67
+ });
68
+ await boardCh.withBoard(cfg, (b) => {
69
+ b.defineTask("zcode", "fc-5", { title: "fail path", acceptance: acc1 });
70
+ const res = V.applyVerifyFail({ b, io: boardCh, store, ID: "bridge", owner: "reviewer1", key: "fc-5", agent: "trae", task: { createdBy: "reviewer1" }, v: vFail, maxAttempts: 2, baseMs: 1000, maxDelayMs: 2000, holdBase: 1000, holdMax: 4000, now: Date.now() });
71
+ ok("F3b applyVerifyFail 走重试路径", res.outcome === "retry-scheduled", JSON.stringify(res));
72
+ const vs = b.verificationsFor("fc-5");
73
+ ok("F3c FAIL 裁决落链", vs.length === 1 && vs[0].verdict === "fail" && vs[0].level === "V1");
74
+ ok("F3d 链完整(fail 分支后)", b.verifyChain().brokenAtSeq === null);
75
+ });
76
+ // 复核 accept/reject → V2 事件
77
+ await boardCh.withBoard(cfg, (b) => {
78
+ b.defineTask("zcode", "fc-6", { title: "review acc", acceptance: { mode: "cross" } });
79
+ R.queueReview({ b, io: boardCh, store, ID: "bridge", key: "fc-6", agent: "trae", mode: "cross", reviewer: "reviewer1", runDir: "D:/runs/y" });
80
+ const a = R.applyReviewAccept({ b, io: boardCh, store, ID: "bridge", key: "fc-6" });
81
+ ok("F3e review accept ok", a.ok === true);
82
+ ok("F3f V2 PASS 落链", b.verificationsFor("fc-6").some((v) => v.verdict === "pass" && v.level === "V2"));
83
+ });
84
+ await boardCh.withBoard(cfg, (b) => {
85
+ b.defineTask("zcode", "fc-7", { title: "review rej", acceptance: { mode: "human" } });
86
+ R.queueReview({ b, io: boardCh, store, ID: "bridge", key: "fc-7", agent: "trae", mode: "human", reviewer: "reviewer1", runDir: "D:/runs/z" });
87
+ const r = R.applyReviewReject({ b, io: boardCh, store, ID: "bridge", key: "fc-7", reason: "工件不完整" });
88
+ ok("F3g review reject ok", r.ok === true);
89
+ ok("F3h V3 FAIL 落链(带理由)", b.verificationsFor("fc-7").some((v) => v.verdict === "fail" && v.level === "V3" && String(v.summary).includes("工件不完整")));
90
+ ok("F3i 终局链完整", b.verifyChain().brokenAtSeq === null);
91
+ });
92
+
93
+ // ---- 4. MCP 面存在性(handleTool 未导出,做结构断言)----
94
+ const mcpSrc = readFileSync(fileURLToPath(new URL("../board/dist/mcp.js", import.meta.url)), "utf8");
95
+ ok("F4a board_task_define schema 带 acceptance", /name: "board_task_define"[\s\S]*?acceptance: \{/.test(mcpSrc));
96
+ ok("F4b board_verify 工具已注册", mcpSrc.includes('name: "board_verify"') && /case "board_verify":/.test(mcpSrc));
97
+ ok("F4c handler 透传 acceptance", /board_task_define[\s\S]{0,400}acceptance: args\.acceptance \?\? null/.test(mcpSrc));
98
+
99
+ // ---- 5. 类型声明同步 ----
100
+ const dts = readFileSync(fileURLToPath(new URL("../board/dist/board.d.ts", import.meta.url)), "utf8");
101
+ const typesDts = readFileSync(fileURLToPath(new URL("../board/dist/types.d.ts", import.meta.url)), "utf8");
102
+ ok("F5a board.d.ts 声明 verify/verificationsFor", dts.includes("verify(actor:") && dts.includes("verificationsFor(key:"));
103
+ ok("F5b types.d.ts Task 带 acceptance", /interface Task [\s\S]{0,900}acceptance: Record<string, unknown> \| null;/.test(typesDts));
104
+
105
+ console.log(`\n${pass} passed, ${fail} failed`);
106
+ if (fail > 0) process.exit(1);
107
+ } finally {
108
+ try { rmSync(dir, { recursive: true, force: true }); } catch { }
109
+ try { rmSync(storeDir, { recursive: true, force: true }); } catch { }
110
+ }
@@ -0,0 +1,52 @@
1
+ // e2e: V1.5 judge(采纳建议①)—— parseVerdict 容错提取 / prompt 构建 / runJudge
2
+ // 基础设施不可用时 fail-open(verdict=unavailable,不阻塞任务流)。不真跑模型。
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+
8
+ const J = await import(new URL("../lib/judge.js", import.meta.url).href);
9
+
10
+ let pass = 0, fail = 0;
11
+ const ok = (name, cond, detail = "") => {
12
+ if (cond) { pass++; console.log(`PASS ${name}${detail ? " — " + detail : ""}`); }
13
+ else { fail++; console.log(`FAIL ${name}${detail ? " — " + detail : ""}`); }
14
+ };
15
+
16
+ const dir = mkdtempSync(join(tmpdir(), "bridge-judge-"));
17
+
18
+ try {
19
+ // ---- parseVerdict ----
20
+ ok("J1a 严格 JSON", JSON.stringify(J.parseVerdict('{"pass":true,"reason":"ok"}')) === JSON.stringify({ pass: true, reason: "ok" }));
21
+ ok("J1b markdown 围栏包裹", J.parseVerdict('结论如下\n```json\n{"pass":false,"reason":"台账对不上"}\n```\n完')?.pass === false);
22
+ ok("J1c 前后杂讯夹 JSON", J.parseVerdict('评审完成。{"pass": true, "reason": "自洽"} 请查收。')?.pass === true);
23
+ ok("J1d 缺 pass 字段 → null", J.parseVerdict('{"verdict":"pass"}') === null);
24
+ ok("J1e 空串/非串 → null", J.parseVerdict("") === null && J.parseVerdict(null) === null);
25
+ ok("J1f 纯文本无 JSON → null", J.parseVerdict("我觉得可以。") === null);
26
+ ok("J1g pass 非布尔 → null", J.parseVerdict('{"pass":"yes"}') === null);
27
+ ok("J1h reason 缺省为空串", J.parseVerdict('{"pass":true}')?.reason === "");
28
+
29
+ // ---- buildJudgePrompt ----
30
+ {
31
+ const p = J.buildJudgePrompt({ key: "t-1", description: "写 30 首诗", rubric: null, workdir: "D:/w" });
32
+ ok("J2a prompt 含任务书与默认 rubric", p.includes("写 30 首诗") && p.includes("占位符"));
33
+ ok("J2b prompt 要求严格 JSON", p.includes('{"pass"') && p.includes("宁可错报给人工复核"));
34
+ const p2 = J.buildJudgePrompt({ key: "t-1", description: "x", rubric: "只看错别字", workdir: "D:/w" });
35
+ ok("J2c 自定义 rubric 覆盖默认", p2.includes("只看错别字") && !p2.includes("无占位符"));
36
+ }
37
+
38
+ // ---- runJudge 不可用路径(fail-open)----
39
+ {
40
+ const r = await J.runJudge({ judgeAgent: "no-such-face", agentCfg: {}, key: "t-2", description: "x", workdir: "D:/w", runDirBase: dir, log: () => { } });
41
+ ok("J3a 未知面 → unavailable(不炸)", r.verdict === "unavailable" && String(r.reason).includes("spawn"), r.reason);
42
+ }
43
+ {
44
+ const r = await J.runJudge({ judgeAgent: "dsh", agentCfg: { script: "D:/nonexistent/run.mjs", node: "node" }, key: "t-3", description: "x", workdir: "D:/w", runDirBase: dir, log: () => { } });
45
+ ok("J3b 面脚本不存在 → unavailable", r.verdict === "unavailable", r.reason);
46
+ }
47
+
48
+ console.log(`\n${pass} passed, ${fail} failed`);
49
+ if (fail > 0) process.exit(1);
50
+ } finally {
51
+ try { rmSync(dir, { recursive: true, force: true }); } catch { }
52
+ }
@@ -0,0 +1,95 @@
1
+ // 隔离验证:认领租约三态(lib/lease.js)
2
+ // A) 自己身份(bridge)的过期 claim,不在 busyKeys → apply 后被释放 + note 上链
3
+ // B) 自己身份但正在跑(busyKeys 命中)→ 豁免不动
4
+ // C) 他人身份(codex)的过期 claim → 只进报告,绝不代释放
5
+ // 附带:report-only 轮必须零写板(head seq 不变);apply 前后 verifyChain brokenAt=null。
6
+ // 全程第二实例 + 系统临时目录测试板,零 token,不碰真板真 state。
7
+ import { execFileSync } from 'node:child_process';
8
+ import { pathToFileURL, fileURLToPath } from 'node:url';
9
+ import { join } from 'node:path';
10
+ import { tmpdir } from 'node:os';
11
+ import { DatabaseSync } from 'node:sqlite';
12
+
13
+ const SRC = fileURLToPath(new URL('..', import.meta.url));
14
+ const PKG = fileURLToPath(new URL('../board', import.meta.url));
15
+ const RUN = String(Date.now());
16
+ const BOARD = join(tmpdir(), `proofdeck-board-lease-verify-${RUN}`);
17
+ const NODE = process.execPath;
18
+ const CLI = `${PKG}/dist/cli.js`;
19
+ const TTL_MS = 24 * 3600000;
20
+
21
+ const board = (agent, args) => execFileSync(NODE, [CLI, ...args], {
22
+ encoding: 'utf8',
23
+ env: { ...process.env, OCTOBOARD_DIR: BOARD, OCTOBOARD_AGENT: agent },
24
+ });
25
+
26
+ for (const k of ['lease-own-stale', 'lease-own-busy', 'lease-other-stale']) {
27
+ board('qoder', ['task', 'add', k, '--title', `租约验证 ${k}`, '--desc', '租约冒烟卡(测试板,勿在真板执行)']);
28
+ }
29
+ board('bridge', ['claim', 'lease-own-stale']);
30
+ board('bridge', ['claim', 'lease-own-busy']);
31
+ board('bridge', ['progress', 'lease-own-busy', '30']);
32
+ board('codex', ['claim', 'lease-other-stale']);
33
+
34
+ // 把 A、C 的 updated_at/claimed_at 回拨 30 小时(列名从 schema 动态认,别赌命名)
35
+ {
36
+ const db = new DatabaseSync(`${BOARD}/board.db`);
37
+ const cols = db.prepare("SELECT name FROM pragma_table_info('tasks')").all().map((r) => r.name);
38
+ const updCol = cols.find((c) => /update/i.test(c));
39
+ const claimCol = cols.find((c) => /claim/i.test(c) && !/by/i.test(c));
40
+ const old = new Date(Date.now() - 30 * 3600000).toISOString();
41
+ for (const k of ['lease-own-stale', 'lease-other-stale']) {
42
+ db.prepare(`UPDATE tasks SET ${updCol} = ?${claimCol ? `, ${claimCol} = ?` : ''} WHERE key = ?`)
43
+ .run(...(claimCol ? [old, old, k] : [old, k]));
44
+ }
45
+ db.close();
46
+ }
47
+
48
+ const boardLib = await import(pathToFileURL(`${SRC}/lib/lease.js`));
49
+ const boardChannel = await import(pathToFileURL(`${SRC}/lib/board.js`));
50
+ await boardChannel.init(PKG); // daemon 启动同样先 init,Board 库是惰性装载的
51
+ const headOf = async () => {
52
+ const { Board } = await import(pathToFileURL(`${PKG}/dist/board.js`));
53
+ const b = Board.open({ boardDir: BOARD, agent: 'zcode' });
54
+ try { return { seq: b.head().seq, chain: b.verifyChain() }; } finally { b.close(); }
55
+ };
56
+
57
+ const cfgB = { dir: BOARD, identity: 'bridge' };
58
+ const head0 = await headOf();
59
+
60
+ // 轮 1:report-only —— 分类必须正确,且零写板
61
+ const rep = await boardLib.leaseSweep({
62
+ boardCfg: cfgB, identity: 'bridge', ttlMs: TTL_MS, sessionMs: 600000,
63
+ busyKeys: new Set(['lease-own-busy']), apply: false, now: Date.now(),
64
+ });
65
+ const head1 = await headOf();
66
+
67
+ // 轮 2:apply —— 只释放 A;B 豁免;C 原样
68
+ const res = await boardLib.leaseSweep({
69
+ boardCfg: cfgB, identity: 'bridge', ttlMs: TTL_MS, sessionMs: 600000,
70
+ busyKeys: new Set(['lease-own-busy']), apply: true, now: Date.now(),
71
+ });
72
+ const head2 = await headOf();
73
+
74
+ const claimOf = async (k) => {
75
+ const { Board } = await import(pathToFileURL(`${PKG}/dist/board.js`));
76
+ const b = Board.open({ boardDir: BOARD, agent: 'zcode' });
77
+ try { return b.taskCard(k)?.task.claimedBy ?? null; } finally { b.close(); }
78
+ };
79
+
80
+ const checks = [
81
+ ['report-only: own-stale 识别 A', rep.ownStale.some((s) => s.key === 'lease-own-stale')],
82
+ ['report-only: busy 豁免 B(在 aliveOwn,不在 ownStale)', rep.aliveOwn.some((s) => s.key === 'lease-own-busy') && !rep.ownStale.some((s) => s.key === 'lease-own-busy')],
83
+ ['report-only: other-stale 识别 C', rep.otherStale.some((s) => s.key === 'lease-other-stale' && s.holder === 'codex')],
84
+ ['report-only: 零写板(head seq 不变)', head1.seq === head0.seq],
85
+ ['apply: 释放了 A', res.released.includes('lease-own-stale')],
86
+ ['apply: A 的 claim 已清', (await claimOf('lease-own-stale')) === null],
87
+ ['apply: B 原样(仍 bridge 持有)', (await claimOf('lease-own-busy')) === 'bridge'],
88
+ ['apply: C 原样(仍 codex 持有,未被代释放)', (await claimOf('lease-other-stale')) === 'codex'],
89
+ ['apply: 链校验 brokenAt=null', head2.chain.brokenAtSeq === null && head2.chain.ok],
90
+ ['apply: C 出现在 otherStale 报告(本轮与上轮一致)', res.otherStale.some((s) => s.key === 'lease-other-stale')],
91
+ ];
92
+ for (const [name, ok] of checks) console.log(`${ok ? 'PASS' : 'FAIL'} ${name}`);
93
+ console.log(`head: ${head0.seq} -> ${head1.seq} -> ${head2.seq}`);
94
+ console.log(checks.every(([, ok]) => ok) ? 'LEASE VERIFY PASS' : 'LEASE VERIFY FAIL');
95
+ process.exit(checks.every(([, ok]) => ok) ? 0 : 1);
@@ -0,0 +1,92 @@
1
+ // e2e: replay 时间旅行(采纳建议④)—— foldTasks 折叠规则 × 真实 Board 事件流 + diffToNow。
2
+ // 纯 TEST board,不碰现网。
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { pathToFileURL, fileURLToPath } from "node:url";
7
+
8
+ const boardCh = await import(new URL("../lib/board.js", import.meta.url).href);
9
+ const R = await import(new URL("../lib/replay.js", import.meta.url).href);
10
+
11
+ let pass = 0, fail = 0;
12
+ const ok = (name, cond, detail = "") => {
13
+ if (cond) { pass++; console.log(`PASS ${name}${detail ? " — " + detail : ""}`); }
14
+ else { fail++; console.log(`FAIL ${name}${detail ? " — " + detail : ""}`); }
15
+ };
16
+
17
+ const dir = mkdtempSync(join(tmpdir(), "bridge-replay-"));
18
+ await boardCh.init(fileURLToPath(new URL("../board", import.meta.url)));
19
+ const cfg = { dir: join(dir, "board"), identity: "bridge" };
20
+
21
+ // 在已知 seq 点位记录快照锚点
22
+ const marks = {};
23
+ const mark = (name) => {
24
+ return boardCh.withBoard(cfg, (b) => { marks[name] = b.head().seq; });
25
+ };
26
+
27
+ await mark("defined");
28
+ await boardCh.withBoard(cfg, (b) => {
29
+ b.defineTask("zcode", "rp-a", { title: "A" });
30
+ b.defineTask("zcode", "rp-b", { title: "B" });
31
+ b.note("zcode", "中间的 note 不该影响折叠");
32
+ });
33
+ await mark("defined2");
34
+ await boardCh.withBoard(cfg, (b) => { b.claim("trae", "rp-a"); });
35
+ await mark("claimed");
36
+ await boardCh.withBoard(cfg, (b) => { b.setProgress("trae", "rp-a", 40); });
37
+ await mark("progress40");
38
+ await boardCh.withBoard(cfg, (b) => { b.complete("trae", "rp-a"); b.setTaskStatus("zcode", "rp-b", "blocked"); });
39
+ await mark("settled");
40
+ await boardCh.withBoard(cfg, (b) => { b.setTaskStatus("zcode", "rp-a", "open"); }); // 重开:释放持有
41
+ await mark("reopened");
42
+
43
+ try {
44
+ const events = await boardCh.withBoard(cfg, (b) => b.since(0));
45
+
46
+ {
47
+ const f = R.foldTasks(events, marks.defined);
48
+ ok("R1 定义前无任务", f.size === 0);
49
+ }
50
+ {
51
+ const f = R.foldTasks(events, marks.defined2);
52
+ ok("R2 两张卡已出现且 open", f.get("rp-a")?.status === "open" && f.get("rp-b")?.status === "open" && f.size === 2);
53
+ ok("R2b claim 前无持有者", f.get("rp-a")?.claimedBy === null);
54
+ }
55
+ {
56
+ const f = R.foldTasks(events, marks.claimed);
57
+ ok("R3 claim 登记持有(不改状态)", f.get("rp-a")?.claimedBy === "trae" && f.get("rp-a")?.status === "open", JSON.stringify(f.get("rp-a")));
58
+ }
59
+ {
60
+ const f = R.foldTasks(events, marks.progress40);
61
+ ok("R4 progress 40 → in-progress", f.get("rp-a")?.status === "in-progress" && f.get("rp-a")?.progress === 40);
62
+ }
63
+ {
64
+ const f = R.foldTasks(events, marks.settled);
65
+ ok("R5a complete → done 且 progress≥100", f.get("rp-a")?.status === "done" && f.get("rp-a")?.progress >= 100);
66
+ ok("R5b task-status blocked 生效", f.get("rp-b")?.status === "blocked");
67
+ }
68
+ {
69
+ const f = R.foldTasks(events);
70
+ ok("R6a 重开释放持有者", f.get("rp-a")?.status === "open" && f.get("rp-a")?.claimedBy === null && f.get("rp-a")?.progress === 0);
71
+ // 全量折叠应与当前板一致(diff 为空)
72
+ const current = await boardCh.withBoard(cfg, (b) => new Map(b.listTasks().map((t) => [t.key, t])));
73
+ const diffs = R.diffToNow(f, current);
74
+ ok("R6b 全量折叠 vs 现板 无差异", diffs.length === 0, JSON.stringify(diffs));
75
+ }
76
+ {
77
+ // 时间旅行差异:在 claimed 时刻看,rp-a 现在也回到了 open(done→重开)⇒ 无差异;
78
+ // rp-b 则是 open→blocked ⇒ 有差异
79
+ const f = R.foldTasks(events, marks.claimed);
80
+ const current = await boardCh.withBoard(cfg, (b) => new Map(b.listTasks().map((t) => [t.key, t])));
81
+ const diffs = R.diffToNow(f, current);
82
+ const da = diffs.find((d) => d.key === "rp-a");
83
+ const db = diffs.find((d) => d.key === "rp-b");
84
+ ok("R7a rp-a 终态回到 open ⇒ 无差异", da === undefined, JSON.stringify(da));
85
+ ok("R7b 差异点名 rp-b(open→blocked)", db && db.now === "blocked", JSON.stringify(db));
86
+ }
87
+
88
+ console.log(`\n${pass} passed, ${fail} failed`);
89
+ if (fail > 0) process.exit(1);
90
+ } finally {
91
+ try { rmSync(dir, { recursive: true, force: true }); } catch { }
92
+ }