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.
- package/LICENSE +201 -0
- package/NOTICE +23 -0
- package/README.md +97 -2
- package/README.zh-CN.md +89 -0
- package/bin/proofdeck.js +126 -0
- package/board/LICENSE +201 -0
- package/board/README.md +473 -0
- package/board/README.zh-CN.md +424 -0
- package/board/dist/_chk.db-shm +0 -0
- package/board/dist/_chk.db-wal +0 -0
- package/board/dist/adapters.d.ts +40 -0
- package/board/dist/adapters.d.ts.map +1 -0
- package/board/dist/adapters.js +124 -0
- package/board/dist/adapters.js.map +1 -0
- package/board/dist/board.d.ts +628 -0
- package/board/dist/board.d.ts.map +1 -0
- package/board/dist/board.js +2767 -0
- package/board/dist/board.js.map +1 -0
- package/board/dist/cli.d.ts +3 -0
- package/board/dist/cli.d.ts.map +1 -0
- package/board/dist/cli.js +1663 -0
- package/board/dist/cli.js.map +1 -0
- package/board/dist/config.d.ts +57 -0
- package/board/dist/config.d.ts.map +1 -0
- package/board/dist/config.js +99 -0
- package/board/dist/config.js.map +1 -0
- package/board/dist/db.d.ts +9 -0
- package/board/dist/db.d.ts.map +1 -0
- package/board/dist/db.js +506 -0
- package/board/dist/db.js.map +1 -0
- package/board/dist/git.d.ts +35 -0
- package/board/dist/git.d.ts.map +1 -0
- package/board/dist/git.js +147 -0
- package/board/dist/git.js.map +1 -0
- package/board/dist/index.d.ts +18 -0
- package/board/dist/index.d.ts.map +1 -0
- package/board/dist/index.js +13 -0
- package/board/dist/index.js.map +1 -0
- package/board/dist/mcp-config.d.ts +26 -0
- package/board/dist/mcp-config.d.ts.map +1 -0
- package/board/dist/mcp-config.js +88 -0
- package/board/dist/mcp-config.js.map +1 -0
- package/board/dist/mcp.d.ts +3 -0
- package/board/dist/mcp.d.ts.map +1 -0
- package/board/dist/mcp.js +949 -0
- package/board/dist/mcp.js.map +1 -0
- package/board/dist/quickstart.d.ts +75 -0
- package/board/dist/quickstart.d.ts.map +1 -0
- package/board/dist/quickstart.js +156 -0
- package/board/dist/quickstart.js.map +1 -0
- package/board/dist/serve.d.ts +10 -0
- package/board/dist/serve.d.ts.map +1 -0
- package/board/dist/serve.js +445 -0
- package/board/dist/serve.js.map +1 -0
- package/board/dist/signing.d.ts +18 -0
- package/board/dist/signing.d.ts.map +1 -0
- package/board/dist/signing.js +26 -0
- package/board/dist/signing.js.map +1 -0
- package/board/dist/sync.d.ts +49 -0
- package/board/dist/sync.d.ts.map +1 -0
- package/board/dist/sync.js +158 -0
- package/board/dist/sync.js.map +1 -0
- package/board/dist/types.d.ts +359 -0
- package/board/dist/types.d.ts.map +1 -0
- package/board/dist/types.js +20 -0
- package/board/dist/types.js.map +1 -0
- package/board/docs/adr/0001-shared-worktree-collision.md +102 -0
- package/board/docs/adr/0001-shared-worktree-collision.zh-CN.md +90 -0
- package/board/docs/attribution.md +123 -0
- package/board/docs/attribution.zh-CN.md +104 -0
- package/board/docs/development-workflow.md +81 -0
- package/board/docs/development-workflow.zh-CN.md +75 -0
- package/board/docs/diagrams/banner.png +0 -0
- package/board/docs/diagrams/banner.svg +1 -0
- package/board/docs/diagrams/before-after.png +0 -0
- package/board/docs/diagrams/before-after.svg +1 -0
- package/board/docs/diagrams/governance-chain.png +0 -0
- package/board/docs/diagrams/governance-chain.svg +1 -0
- package/board/docs/diagrams/value-flow.png +0 -0
- package/board/docs/diagrams/value-flow.svg +1 -0
- package/board/docs/entry-point.md +81 -0
- package/board/docs/entry-point.zh-CN.md +65 -0
- package/board/docs/kanban.png +0 -0
- package/board/docs/octoryn-mark.png +0 -0
- package/board/docs/registry-metadata.md +34 -0
- package/board/docs/registry-metadata.zh-CN.md +30 -0
- package/board/package.json +87 -0
- package/config.example.json +71 -0
- package/daemon.js +1112 -0
- package/docs/assets/demo.gif +0 -0
- package/docs/demo-run.mjs +61 -0
- package/docs/render-demo.py +94 -0
- package/e2e/verify-acceptance.mjs +150 -0
- package/e2e/verify-antifraud.mjs +128 -0
- package/e2e/verify-caps.mjs +46 -0
- package/e2e/verify-checkpoint.mjs +208 -0
- package/e2e/verify-firstclass.mjs +110 -0
- package/e2e/verify-judge.mjs +52 -0
- package/e2e/verify-lease.mjs +95 -0
- package/e2e/verify-replay.mjs +92 -0
- package/e2e/verify-resilience.mjs +323 -0
- package/e2e/verify-review.mjs +86 -0
- package/e2e/verify-scheduling.mjs +110 -0
- package/e2e/verify-schema-evolution.mjs +107 -0
- package/e2e/verify-sla-digest.mjs +105 -0
- package/guard.js +97 -0
- package/lib/adapters/codex.js +206 -0
- package/lib/billing-convert.js +57 -0
- package/lib/board.js +46 -0
- package/lib/caps.js +35 -0
- package/lib/checkpoint.js +130 -0
- package/lib/gating.js +218 -0
- package/lib/guard-core.mjs +108 -0
- package/lib/http.js +161 -0
- package/lib/judge.js +89 -0
- package/lib/lease.js +93 -0
- package/lib/notify.js +56 -0
- package/lib/platform.js +120 -0
- package/lib/replay.js +68 -0
- package/lib/review.js +40 -0
- package/lib/runner.js +152 -0
- package/lib/schedule.js +59 -0
- package/lib/sla.js +42 -0
- package/lib/spans.js +36 -0
- package/lib/starve.js +43 -0
- package/lib/store.js +109 -0
- package/lib/supply.js +101 -0
- package/lib/usage.js +103 -0
- package/lib/verify.js +223 -0
- package/lib/watchdog-core.mjs +68 -0
- package/lib/watchdog-worker.mjs +75 -0
- package/package.json +55 -4
- package/scripts/run-daemon.sh +18 -0
- package/scripts/run-e2e.mjs +39 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// e2e: resilience of the guard v2 + daemon freeze-watchdog (2026-10-02 incident gaps ①-④).
|
|
2
|
+
// Never touches the production board or the live daemon's state — all mutations go to a
|
|
3
|
+
// temp baseDir; the only production reads are the final guard.js smoke (read-only path
|
|
4
|
+
// against a healthy daemon). Kill targets are sacrificial processes we spawn ourselves.
|
|
5
|
+
import { Worker } from "node:worker_threads";
|
|
6
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
7
|
+
import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { pathToFileURL, fileURLToPath } from "node:url";
|
|
11
|
+
import { createServer } from "node:http";
|
|
12
|
+
import { getProcessInfo } from "../lib/platform.js";
|
|
13
|
+
|
|
14
|
+
const GUARD_CORE = new URL("../lib/guard-core.mjs", import.meta.url).href;
|
|
15
|
+
const WORKER = fileURLToPath(new URL("../lib/watchdog-worker.mjs", import.meta.url));
|
|
16
|
+
const WD_CORE = new URL("../lib/watchdog-core.mjs", import.meta.url).href;
|
|
17
|
+
const { runGuardCheck } = await import(GUARD_CORE);
|
|
18
|
+
const wd = await import(WD_CORE);
|
|
19
|
+
|
|
20
|
+
let pass = 0, fail = 0;
|
|
21
|
+
const ok = (name, cond, detail = "") => {
|
|
22
|
+
if (cond) { pass++; console.log(`PASS ${name}${detail ? " — " + detail : ""}`); }
|
|
23
|
+
else { fail++; console.log(`FAIL ${name}${detail ? " — " + detail : ""}`); }
|
|
24
|
+
};
|
|
25
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
26
|
+
const tempBase = mkdtempSync(join(tmpdir(), "bridge-resilience-"));
|
|
27
|
+
const strikeFile = join(tempBase, "guard-strikes.json");
|
|
28
|
+
const wlogFile = join(tempBase, "watchdog.log");
|
|
29
|
+
const stateFile = join(tempBase, "state.json");
|
|
30
|
+
const setState = (pid) => writeFileSync(stateFile, JSON.stringify({ pid }));
|
|
31
|
+
|
|
32
|
+
const victimProc = (marker) => spawn(process.execPath, ["-e", `setTimeout(()=>{},60000) /*${marker}*/`], { stdio: "ignore" });
|
|
33
|
+
const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
|
|
34
|
+
const waitFor = async (cond, ms) => { const t0 = Date.now(); while (Date.now() - t0 < ms) { if (await cond()) return true; await sleep(150); } return false; };
|
|
35
|
+
|
|
36
|
+
// 探针必须把「没人监听」和「连上了不回答」分成两种判据:前者支持杀,后者不支持。
|
|
37
|
+
// 2026-10-06 实测:一个健在但被饿死的守护回答 /ps 用了 36.989433s,而 guard 的探针预算只有
|
|
38
|
+
// 3500ms——把超时当死,就会杀掉健在的守护(10-05 事故形状)。
|
|
39
|
+
// 夹具要用「真的没人监听」的端口:先绑一个临时口再关掉。不能拿 1 号端口冒充——
|
|
40
|
+
// 2026-10-06 实测 fetch 对 127.0.0.1:1 在连接前就按 blocked-port 拒绝(cause 是 "bad port"、
|
|
41
|
+
// 没有 ECONNREFUSED 码),会把它误分类成 timeout,让整组 refused 断言测不到目标分支。
|
|
42
|
+
const deadPort = await new Promise((resolve, reject) => {
|
|
43
|
+
const s = createServer();
|
|
44
|
+
s.listen(0, "127.0.0.1", () => { const p = s.address().port; s.close(() => resolve(p)); });
|
|
45
|
+
s.on("error", reject);
|
|
46
|
+
});
|
|
47
|
+
const closedPortProbe = async () => {
|
|
48
|
+
try { await fetch(`http://127.0.0.1:${deadPort}/ps`, { signal: AbortSignal.timeout(1500) }); return "ok"; }
|
|
49
|
+
catch (e) { return (e?.cause?.code ?? e?.code) === "ECONNREFUSED" ? "refused" : "timeout"; }
|
|
50
|
+
};
|
|
51
|
+
const timeoutProbe = async () => "timeout";
|
|
52
|
+
|
|
53
|
+
// ctx factory against the temp world. confirmDaemon = the real powershell mechanics
|
|
54
|
+
// (same shape as guard.js's confirmByCommandLine, marker parameterized).
|
|
55
|
+
const mkCtx = (overrides = {}) => ({
|
|
56
|
+
log: () => { },
|
|
57
|
+
now: () => Date.now(),
|
|
58
|
+
readState: () => { try { return JSON.parse(readFileSync(stateFile, "utf8")); } catch { return null; } },
|
|
59
|
+
stopPresent: () => existsSync(join(tempBase, "STOP")),
|
|
60
|
+
processAlive: pidAlive,
|
|
61
|
+
strikeFile: overrides.strikeFile ?? strikeFile,
|
|
62
|
+
probe: closedPortProbe,
|
|
63
|
+
confirmDaemon: async (pid) => {
|
|
64
|
+
// 经共享双平台原语取命令行(win32=排水版 CIM / posix=ps)——测试直接测生产原语。
|
|
65
|
+
// 预算 30s:生产 guard 是 9s(慢 WMI 下按设计弃权);测试预算放宽以聚焦逻辑而非机器负载。
|
|
66
|
+
const info = await getProcessInfo(pid, 30000);
|
|
67
|
+
if (info.commandLine == null) return null;
|
|
68
|
+
return info.commandLine.includes(overrides.marker ?? "guard-e2e-victim") ? true : false;
|
|
69
|
+
},
|
|
70
|
+
kill: (pid) => { try { process.kill(pid, "SIGKILL"); } catch { } },
|
|
71
|
+
spawnLauncher: () => { (overrides.spawned ??= []).push(1); return true; },
|
|
72
|
+
...overrides.ctx,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// ---------- G1: two-strike before spawn (restart-race fix, gap ②) ----------
|
|
76
|
+
{
|
|
77
|
+
const dead = spawnSync(process.execPath, ["-e", ""]);
|
|
78
|
+
await sleep(300);
|
|
79
|
+
setState(dead.pid);
|
|
80
|
+
const spawned = [];
|
|
81
|
+
const ctx = mkCtx({ spawned, marker: "x" });
|
|
82
|
+
const r1 = await runGuardCheck(ctx);
|
|
83
|
+
ok("G1a first sighting of dead pid waits (no spawn)", r1.action === "wait" && spawned.length === 0, JSON.stringify(r1));
|
|
84
|
+
const r2 = await runGuardCheck(ctx);
|
|
85
|
+
ok("G1b second sighting spawns launcher", r2.action === "spawn" && spawned.length === 1, JSON.stringify(r2));
|
|
86
|
+
// alive again → strikes cleared
|
|
87
|
+
const alive = victimProc("guard-e2e-victim");
|
|
88
|
+
setState(alive.pid);
|
|
89
|
+
const portSrv = createServer((req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ pid: alive.pid })); });
|
|
90
|
+
await new Promise((r) => portSrv.listen(0, "127.0.0.1", r));
|
|
91
|
+
const port = portSrv.address().port;
|
|
92
|
+
const ctxAlive = mkCtx({ ctx: { probe: async () => "ok" } });
|
|
93
|
+
const r3 = await runGuardCheck(ctxAlive);
|
|
94
|
+
const ledger = JSON.parse(readFileSync(strikeFile, "utf8"));
|
|
95
|
+
ok("G1c responsive daemon reports alive and clears strikes", r3.state === "alive" && ledger.key === null, JSON.stringify(r3));
|
|
96
|
+
// mismatch → report, never touch
|
|
97
|
+
const ctxMis = mkCtx({ ctx: { probe: async () => "mismatch" } });
|
|
98
|
+
const r4 = await runGuardCheck(ctxMis);
|
|
99
|
+
ok("G1d foreign port owner is reported, not killed", r4.state === "mismatch" && r4.action === "none", JSON.stringify(r4));
|
|
100
|
+
portSrv.close(); alive.kill("SIGKILL");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------- G2: 端口拒连且正身已确认 → 两振 → 杀(gap ①)----------
|
|
104
|
+
{
|
|
105
|
+
// CIM/PS 冷启动预热(Windows 首查可 >9s:PS 冷启 4.2s + 单 pid CIM 5.7~7.5s)。
|
|
106
|
+
// 预热让断言聚焦 guard 两振逻辑本身;生产 guard 9s 预算下遇到冷 CIM 会按设计弃权。
|
|
107
|
+
await getProcessInfo(process.pid, 20000);
|
|
108
|
+
}
|
|
109
|
+
{
|
|
110
|
+
const victim = victimProc("guard-e2e-victim");
|
|
111
|
+
await sleep(300);
|
|
112
|
+
setState(victim.pid);
|
|
113
|
+
const ctx = mkCtx({});
|
|
114
|
+
const r1 = await runGuardCheck(ctx);
|
|
115
|
+
ok("G2a refused strike 1 waits", r1.action === "wait", JSON.stringify(r1));
|
|
116
|
+
const r2 = await runGuardCheck(ctx);
|
|
117
|
+
ok("G2b strike 2 confirms via command line and kills", r2.action === "kill", JSON.stringify(r2));
|
|
118
|
+
const died = await waitFor(async () => !pidAlive(victim.pid), 3000);
|
|
119
|
+
ok("G2c victim actually died", died);
|
|
120
|
+
const ledger = JSON.parse(readFileSync(strikeFile, "utf8"));
|
|
121
|
+
ok("G2d kill recorded in ledger, count reset", ledger.kills.length === 1 && ledger.count === 0, JSON.stringify(ledger));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ---------- G3: no positive ID → abstain; ledger caps → cooldown/manual ----------
|
|
125
|
+
{
|
|
126
|
+
const stranger = victimProc("some-unrelated-process");
|
|
127
|
+
await sleep(300);
|
|
128
|
+
setState(stranger.pid);
|
|
129
|
+
const ctx = mkCtx({ marker: "guard-e2e-victim" }); // victim's cmdline lacks the marker
|
|
130
|
+
await runGuardCheck(ctx);
|
|
131
|
+
const r2 = await runGuardCheck(ctx);
|
|
132
|
+
ok("G3a unconfirmed pid → abstain from killing", r2.action === "abstain" && pidAlive(stranger.pid), JSON.stringify(r2));
|
|
133
|
+
stranger.kill("SIGKILL");
|
|
134
|
+
|
|
135
|
+
// cooldown / manual-cap live on the unresponsive branch → need a LIVE pid and a
|
|
136
|
+
// ledger keyed by that exact pid (a key change resets the ledger).
|
|
137
|
+
const frozen = victimProc("guard-e2e-victim");
|
|
138
|
+
await sleep(300);
|
|
139
|
+
setState(frozen.pid);
|
|
140
|
+
const now = Date.now();
|
|
141
|
+
const ctxC = mkCtx({ ctx: {} });
|
|
142
|
+
writeFileSync(strikeFile, JSON.stringify({ key: frozen.pid, count: 1, lastAt: now, lastKillAt: now - 60000, kills: [] }));
|
|
143
|
+
const rc = await runGuardCheck(ctxC);
|
|
144
|
+
ok("G3b kill cooldown active", rc.action === "cooldown", JSON.stringify(rc));
|
|
145
|
+
|
|
146
|
+
writeFileSync(strikeFile, JSON.stringify({ key: frozen.pid, count: 5, lastAt: now, lastKillAt: 0, kills: [now - 3000, now - 2000, now - 1000] }));
|
|
147
|
+
const rm = await runGuardCheck(ctxC);
|
|
148
|
+
ok("G3c 3 kills within 1h → stop auto-kill, require manual", rm.action === "manual", JSON.stringify(rm));
|
|
149
|
+
frozen.kill("SIGKILL");
|
|
150
|
+
|
|
151
|
+
rmSync(stateFile);
|
|
152
|
+
const ctxN = mkCtx({});
|
|
153
|
+
const n1 = await runGuardCheck(ctxN);
|
|
154
|
+
const n2 = await runGuardCheck(ctxN);
|
|
155
|
+
ok("G3d missing state.json → two-strike then spawn", n1.action === "wait" && n2.action === "spawn", `${n1.action}/${n2.action}`);
|
|
156
|
+
|
|
157
|
+
writeFileSync(join(tempBase, "STOP"), "1");
|
|
158
|
+
const ctxS = mkCtx({});
|
|
159
|
+
const rs = await runGuardCheck(ctxS);
|
|
160
|
+
ok("G3e STOP present → stand down entirely", rs.state === "stopped", JSON.stringify(rs));
|
|
161
|
+
rmSync(join(tempBase, "STOP"));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ---------- W1/W2: daemon freeze-watchdog worker (gap ④) ----------
|
|
165
|
+
{
|
|
166
|
+
const victim = victimProc("watchdog-e2e-victim");
|
|
167
|
+
await sleep(300);
|
|
168
|
+
const w = new Worker(WORKER, { workerData: { pid: victim.pid, staleMs: 1500, graceMs: 0, checkMs: 500, logFile: wlogFile, port: deadPort, probeBudgetMs: 2000, probeAttemptMs: 800 } });
|
|
169
|
+
const killed = await waitFor(async () => !pidAlive(victim.pid), 8000);
|
|
170
|
+
ok("W1 silent main thread → worker kills frozen pid", killed, `victim pid=${victim.pid}`);
|
|
171
|
+
await sleep(300);
|
|
172
|
+
const wlog = existsSync(wlogFile) ? readFileSync(wlogFile, "utf8") : "";
|
|
173
|
+
ok("W1b watchdog logged its verdict", wlog.includes("SIGKILL") && /判为 refused/.test(wlog), wlog.split("\n").slice(-2).join(" | "));
|
|
174
|
+
ok("W1c worker exit did not take the test process down", true); // we are still running
|
|
175
|
+
try { await w.terminate(); } catch { }
|
|
176
|
+
|
|
177
|
+
const victim2 = victimProc("watchdog-e2e-victim2");
|
|
178
|
+
await sleep(300);
|
|
179
|
+
const w2 = new Worker(WORKER, { workerData: { pid: victim2.pid, staleMs: 1500, graceMs: 0, checkMs: 500, logFile: join(tempBase, "watchdog2.log") } });
|
|
180
|
+
const hb = setInterval(() => { try { w2.postMessage("hb"); } catch { } }, 200);
|
|
181
|
+
await sleep(4000);
|
|
182
|
+
const stillAlive = pidAlive(victim2.pid);
|
|
183
|
+
ok("W2 healthy heartbeat → worker never kills", stillAlive);
|
|
184
|
+
clearInterval(hb); w2.unref(); victim2.kill("SIGKILL");
|
|
185
|
+
|
|
186
|
+
// W2b:10-05 误杀形状的 worker 级复现——心跳断了但控制口还在应答(健在只是慢)→ 绝不杀
|
|
187
|
+
const victim3 = victimProc("watchdog-e2e-victim3");
|
|
188
|
+
await sleep(300);
|
|
189
|
+
const answerSrv = createServer((req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ pid: victim3.pid })); });
|
|
190
|
+
await new Promise((r) => answerSrv.listen(0, "127.0.0.1", r));
|
|
191
|
+
const answerPort = answerSrv.address().port;
|
|
192
|
+
const w3 = new Worker(WORKER, { workerData: { pid: victim3.pid, staleMs: 1000, graceMs: 0, checkMs: 400, logFile: join(tempBase, "watchdog3.log"), port: answerPort, probeBudgetMs: 3000, probeAttemptMs: 800 } });
|
|
193
|
+
await sleep(6000);
|
|
194
|
+
ok("W2b 心跳静默 + 控制口有应答 → 看门狗不杀健在守护", pidAlive(victim3.pid), `pid=${victim3.pid} port=${answerPort}`);
|
|
195
|
+
const w3log = existsSync(join(tempBase, "watchdog3.log")) ? readFileSync(join(tempBase, "watchdog3.log"), "utf8") : "";
|
|
196
|
+
ok("W2c 弃权时有留痕(写明是慢不是冻结)", /有应答|心跳已恢复/.test(w3log), w3log.trim().split("\n").slice(-1)[0] ?? "(无日志)");
|
|
197
|
+
w3.unref(); answerSrv.close(); victim3.kill("SIGKILL");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ---------- G5/G6: 判据成立才落账(2026-10-06 缺口②续:超时不是死) ----------
|
|
201
|
+
// 每组用**自己的** strike 账本:默认那份被前面的块写过,读数会串台(G5b 首次 FAIL 就是这么来的)。
|
|
202
|
+
{
|
|
203
|
+
const victim = victimProc("guard-e2e-victim");
|
|
204
|
+
await sleep(300);
|
|
205
|
+
setState(victim.pid);
|
|
206
|
+
const g5File = join(tempBase, "g5-strikes.json");
|
|
207
|
+
writeFileSync(g5File, JSON.stringify({ key: victim.pid, count: 0, lastAt: 0, lastKillAt: 0, kills: [] }));
|
|
208
|
+
let confirmCalls = 0;
|
|
209
|
+
const ctx = mkCtx({ strikeFile: g5File, ctx: { probe: timeoutProbe, confirmDaemon: async () => { confirmCalls++; return true; } } });
|
|
210
|
+
const r1 = await runGuardCheck(ctx);
|
|
211
|
+
const r2 = await runGuardCheck(ctx);
|
|
212
|
+
const ledger = JSON.parse(readFileSync(g5File, "utf8"));
|
|
213
|
+
ok("G5a 探针超时两轮都不杀", r1.action !== "kill" && r2.action !== "kill" && pidAlive(victim.pid), `${r1.action}/${r2.action}`);
|
|
214
|
+
ok("G5b 探针超时不吃 strike 预算(ledger.count=0)", ledger.count === 0, JSON.stringify(ledger));
|
|
215
|
+
ok("G5c 判据不成立时不做正身确认 I/O", confirmCalls === 0, `confirmCalls=${confirmCalls}`);
|
|
216
|
+
await runGuardCheck(ctx); await runGuardCheck(ctx); await runGuardCheck(ctx);
|
|
217
|
+
ok("G5d 连续超时也不进冷却/人工上限", pidAlive(victim.pid) && JSON.parse(readFileSync(g5File, "utf8")).kills.length === 0);
|
|
218
|
+
victim.kill("SIGKILL");
|
|
219
|
+
|
|
220
|
+
// refused(真的没人监听)才是支持杀的判据;且必须先正身确认,确认不成立不落账
|
|
221
|
+
const v2 = victimProc("guard-e2e-victim");
|
|
222
|
+
await sleep(300);
|
|
223
|
+
setState(v2.pid);
|
|
224
|
+
const g6File = join(tempBase, "g6-strikes.json");
|
|
225
|
+
const seed6 = () => writeFileSync(g6File, JSON.stringify({ key: v2.pid, count: 0, lastAt: 0, lastKillAt: 0, kills: [] }));
|
|
226
|
+
seed6();
|
|
227
|
+
const ctxNull = mkCtx({ strikeFile: g6File, ctx: { probe: closedPortProbe, confirmDaemon: async () => null } });
|
|
228
|
+
const u1 = await runGuardCheck(ctxNull);
|
|
229
|
+
const u2 = await runGuardCheck(ctxNull);
|
|
230
|
+
const u3 = await runGuardCheck(ctxNull);
|
|
231
|
+
const l2 = JSON.parse(readFileSync(g6File, "utf8"));
|
|
232
|
+
ok("G6a 拒连但正身不确定:三轮 abstain,不落账,不杀", u1.action === "abstain" && u2.action === "abstain" && u3.action === "abstain" && l2.count === 0 && pidAlive(v2.pid), `${u1.state}/${l2.count}`);
|
|
233
|
+
seed6();
|
|
234
|
+
const ctxOk = mkCtx({ strikeFile: g6File, ctx: { probe: closedPortProbe, confirmDaemon: async () => true } });
|
|
235
|
+
const k1 = await runGuardCheck(ctxOk);
|
|
236
|
+
const k2 = await runGuardCheck(ctxOk);
|
|
237
|
+
ok("G6b 拒连两轮且正身确认 → 杀", k1.action === "wait" && k2.action === "kill", `${k1.action}/${k2.action}`);
|
|
238
|
+
const died = await waitFor(async () => !pidAlive(v2.pid), 3000);
|
|
239
|
+
ok("G6c 被杀的确实是那个命令行确认过的进程", died);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------- W3-W5: 看门狗决策核(挂起自测 + 端口再判),纯注入时钟,不需要真睡 ----------
|
|
243
|
+
{
|
|
244
|
+
const mk = (o = {}) => {
|
|
245
|
+
const c = { t: 1000, kills: 0, logs: [], probeCalls: 0, probe: o.probe ?? (async () => "timeout"), hbGap: null };
|
|
246
|
+
const w = wd.createWatchdog({
|
|
247
|
+
now: () => c.t,
|
|
248
|
+
staleMs: o.staleMs ?? 30000,
|
|
249
|
+
graceMs: o.graceMs ?? 0,
|
|
250
|
+
checkMs: o.checkMs ?? 10000,
|
|
251
|
+
probe: async () => { c.probeCalls++; return c.probe(); },
|
|
252
|
+
kill: () => { c.kills++; },
|
|
253
|
+
log: (m) => c.logs.push(m),
|
|
254
|
+
});
|
|
255
|
+
return { c, w, adv: (ms) => { c.t += ms; } };
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
// 节拍正常、心跳停 → 两振 → 探针无应答 → 杀(10-02 缺口①的原意,必须保住)
|
|
259
|
+
{
|
|
260
|
+
const { c, w, adv } = mk();
|
|
261
|
+
let v = null;
|
|
262
|
+
for (let i = 0; i < 10 && c.kills === 0; i++) { adv(10000); v = await w.tick(); }
|
|
263
|
+
ok("W3a 节拍准、心跳静默超阈值、端口始终无应答 → 杀冻结的守护", c.kills === 1, `verdict=${v} probeCalls=${c.probeCalls}`);
|
|
264
|
+
}
|
|
265
|
+
// 端口能答(哪怕慢)= 主循环还活着 → 绝不杀
|
|
266
|
+
{
|
|
267
|
+
const { c, w, adv } = mk({ probe: async () => "answered" });
|
|
268
|
+
for (let i = 0; i < 10 && c.kills === 0; i++) { adv(10000); await w.tick(); }
|
|
269
|
+
ok("W3b 探针有应答 → 不杀,计数清零", c.kills === 0 && c.probeCalls >= 1, `kills=${c.kills} probeCalls=${c.probeCalls}`);
|
|
270
|
+
}
|
|
271
|
+
// 自己那一拍就迟到(= 整进程被挂起过)→ 静默读数不可解释:清零、不做任何 I/O
|
|
272
|
+
{
|
|
273
|
+
const { c, w, adv } = mk();
|
|
274
|
+
adv(5 * 60 * 1000); // 一次性跳 5 分钟:worker 的 tickGap 远超 checkMs
|
|
275
|
+
const v = await w.tick();
|
|
276
|
+
ok("W4a 自身节拍迟到 → 判挂起,不吃静默读数", v === "suspend-reset", `verdict=${v}`);
|
|
277
|
+
ok("W4b 挂起判定期间不做端口 I/O、不杀", c.probeCalls === 0 && c.kills === 0, `probe=${c.probeCalls} kills=${c.kills}`);
|
|
278
|
+
for (let i = 0; i < 3; i++) { adv(10000); await w.tick(); }
|
|
279
|
+
ok("W4c 挂起后计数从 0 重新起算(不会紧接着就杀)", c.kills === 0 && c.probeCalls === 0, `kills=${c.kills} probe=${c.probeCalls}`);
|
|
280
|
+
}
|
|
281
|
+
// 探针预算期间心跳回来了 → 主线程已复活,弃权
|
|
282
|
+
{
|
|
283
|
+
let release;
|
|
284
|
+
const { c, w, adv } = mk({ probe: () => new Promise((r) => { release = () => r("timeout"); }) });
|
|
285
|
+
for (let i = 0; i < 6; i++) { adv(10000); const p = w.tick(); if (c.probeCalls) { w.onHeartbeat(); adv(1000); release(); await p; break; } }
|
|
286
|
+
ok("W5 探针期间心跳恢复 → 弃权不杀", c.kills === 0, `kills=${c.kills}`);
|
|
287
|
+
}
|
|
288
|
+
// 启动宽限期内一律不动作
|
|
289
|
+
{
|
|
290
|
+
const { c, w, adv } = mk({ graceMs: 600000, staleMs: 1000 });
|
|
291
|
+
adv(10000); await w.tick(); adv(10000); await w.tick();
|
|
292
|
+
ok("W6 graceMs 内不判不杀", c.kills === 0 && c.probeCalls === 0, `kills=${c.kills}`);
|
|
293
|
+
}
|
|
294
|
+
// 只开火一次。SIGKILL 之后守护必然已死、bat 循环接手;若真没死透(权限异常),
|
|
295
|
+
// 让分钟级 guard 去兜,也比 worker 每拍刷一次 taskkill 好(2026-10-06 W1b 实测到过二次 ESRCH)。
|
|
296
|
+
{
|
|
297
|
+
const { c, w, adv } = mk();
|
|
298
|
+
for (let i = 0; i < 12; i++) { adv(10000); await w.tick(); }
|
|
299
|
+
ok("W7 开火一次之后各拍不再杀", c.kills === 1, `kills=${c.kills} probe=${c.probeCalls}`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ---------- B1: launcher wait primitive (gap ③) ----------
|
|
304
|
+
if (process.platform === "win32") {
|
|
305
|
+
const t0 = Date.now();
|
|
306
|
+
spawnSync("cmd.exe", ["/c", "ping -n 3 127.0.0.1 > NUL"], { windowsHide: true });
|
|
307
|
+
const dt = Date.now() - t0;
|
|
308
|
+
ok("B1 ping -n 3 sleeps ~2s in non-interactive cmd", dt >= 1800 && dt < 4500, `${dt}ms`);
|
|
309
|
+
} else {
|
|
310
|
+
console.log("SKIP B1 (win32-only launcher wait primitive)");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ---------- G4: real guard.js against the real (healthy) daemon — read-only smoke ----------
|
|
314
|
+
{
|
|
315
|
+
const r = spawnSync(process.execPath, [fileURLToPath(new URL("../guard.js", import.meta.url))], { encoding: "utf8", timeout: 25000 });
|
|
316
|
+
const glog = readFileSync(fileURLToPath(new URL("../logs/guard.log", import.meta.url)), "utf8").slice(-2000);
|
|
317
|
+
ok("G4 real guard.js run exits fast with a verdict (no daemon here: no-state / launcher-probe path)",
|
|
318
|
+
r.status === 0 && /control responsive|端口拒连|探针超时|DIFFERENT daemon pid|launcher spawned|no readable state/.test(glog), `rc=${r.status} :: ${glog.trim().split("\n").pop()}`);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
rmSync(tempBase, { recursive: true, force: true });
|
|
322
|
+
console.log(`\n${pass} PASS, ${fail} FAIL`);
|
|
323
|
+
process.exit(fail ? 1 : 0);
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// e2e: review queue (验证层 V2 交叉 / V3 人工) — queueReview / accept / reject against
|
|
2
|
+
// a TEST board + temp store. Never touches the real 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 R = await import(new URL("../lib/review.js", import.meta.url).href);
|
|
9
|
+
const { Store } = await import(new URL("../lib/store.js", import.meta.url).href);
|
|
10
|
+
const boardCh = await import(new URL("../lib/board.js", import.meta.url).href);
|
|
11
|
+
|
|
12
|
+
let pass = 0, fail = 0;
|
|
13
|
+
const ok = (name, cond, detail = "") => {
|
|
14
|
+
if (cond) { pass++; console.log(`PASS ${name}${detail ? " — " + detail : ""}`); }
|
|
15
|
+
else { fail++; console.log(`FAIL ${name}${detail ? " — " + detail : ""}`); }
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const dir = mkdtempSync(join(tmpdir(), "bridge-review-"));
|
|
19
|
+
const storeDir = mkdtempSync(join(tmpdir(), "bridge-rstore-"));
|
|
20
|
+
const store = new Store(join(storeDir, "state.json"));
|
|
21
|
+
await boardCh.init(fileURLToPath(new URL("../board", import.meta.url)));
|
|
22
|
+
const cfg = { dir: join(dir, "board"), identity: "bridge" };
|
|
23
|
+
|
|
24
|
+
// ---- queueReview: cross → V2 ----
|
|
25
|
+
{
|
|
26
|
+
await boardCh.withBoard(cfg, (b) => b.defineTask("zcode", "rev-cross-1", { title: "cross e2e", description: "测试" }));
|
|
27
|
+
let res;
|
|
28
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
29
|
+
res = R.queueReview({ b, io: boardCh, store, ID: "bridge", key: "rev-cross-1", agent: "trae", mode: "cross", reviewer: "reviewer1", runDir: "D:/runs/x", v1Note: "(V1 机械项已过 2/2)" });
|
|
30
|
+
});
|
|
31
|
+
ok("Q1a cross → V2 queued", res.level === "V2" && res.reviewer === "reviewer1", JSON.stringify(res));
|
|
32
|
+
ok("Q1b ledger entry", store.s.review["rev-cross-1"]?.mode === "cross" && store.s.review["rev-cross-1"]?.agent === "trae");
|
|
33
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
34
|
+
const evs = b.timeline(100);
|
|
35
|
+
ok("Q1c REVIEW note with level+reviewer", evs.some((e) => String(e.summary).includes("verdict=REVIEW level=V2 reviewer=reviewer1")));
|
|
36
|
+
ok("Q1d v1Note carried", evs.some((e) => String(e.summary).includes("V1 机械项已过 2/2")));
|
|
37
|
+
const msgs = b.inbox("reviewer1", true);
|
|
38
|
+
ok("Q1e reviewer notified with commands", msgs.some((m) => JSON.stringify(m).includes("review-accept rev-cross-1")));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ---- accept: done + PASS note ----
|
|
43
|
+
{
|
|
44
|
+
let res;
|
|
45
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
46
|
+
res = R.applyReviewAccept({ b, io: boardCh, store, ID: "bridge", key: "rev-cross-1" });
|
|
47
|
+
});
|
|
48
|
+
ok("Q2a accept ok", res.ok === true && res.mode === "cross", JSON.stringify(res));
|
|
49
|
+
ok("Q2b ledger cleared", store.s.review["rev-cross-1"] === undefined);
|
|
50
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
51
|
+
ok("Q2c task done", b.getTask("rev-cross-1")?.status === "done");
|
|
52
|
+
ok("Q2d PASS note (复核人 recorded)", b.timeline(200).some((e) => String(e.summary).includes("verdict=PASS level=V2") && String(e.summary).includes("复核人=reviewer1")));
|
|
53
|
+
ok("Q2e executor notified", b.inbox("trae", true).some((m) => JSON.stringify(m).includes("复核通过")));
|
|
54
|
+
ok("Q2f chain ok", b.verifyChain().brokenAtSeq === null);
|
|
55
|
+
});
|
|
56
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
57
|
+
const r = R.applyReviewAccept({ b, io: boardCh, store, ID: "bridge", key: "rev-cross-1" });
|
|
58
|
+
ok("Q2g accept on empty queue → refused", r.ok === false && String(r.why).includes("不在复核队列"));
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ---- reject: open + FAIL note; human → V3 ----
|
|
63
|
+
{
|
|
64
|
+
await boardCh.withBoard(cfg, (b) => b.defineTask("zcode", "rev-human-1", { title: "human e2e", description: "测试" }));
|
|
65
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
66
|
+
R.queueReview({ b, io: boardCh, store, ID: "bridge", key: "rev-human-1", agent: "codex", mode: "human", reviewer: "kemu", runDir: "D:/runs/y" });
|
|
67
|
+
});
|
|
68
|
+
ok("Q3a human → V3 queued", store.s.review["rev-human-1"]?.mode === "human");
|
|
69
|
+
let res;
|
|
70
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
71
|
+
res = R.applyReviewReject({ b, io: boardCh, store, ID: "bridge", key: "rev-human-1", reason: "第三节口径不对" });
|
|
72
|
+
});
|
|
73
|
+
ok("Q3b reject ok", res.ok === true, JSON.stringify(res));
|
|
74
|
+
ok("Q3c ledger cleared", store.s.review["rev-human-1"] === undefined);
|
|
75
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
76
|
+
ok("Q3d task back to open", b.getTask("rev-human-1")?.status === "open");
|
|
77
|
+
ok("Q3e FAIL note carries reason + V3", b.timeline(300).some((e) => String(e.summary).includes("verdict=FAIL level=V3") && String(e.summary).includes("第三节口径不对")));
|
|
78
|
+
ok("Q3f executor notified with requeue hint", b.inbox("codex", true).some((m) => JSON.stringify(m).includes("requeue rev-human-1")));
|
|
79
|
+
ok("Q3g chain ok", b.verifyChain().brokenAtSeq === null);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
rmSync(dir, { recursive: true, force: true });
|
|
84
|
+
rmSync(storeDir, { recursive: true, force: true });
|
|
85
|
+
console.log(`\n${pass} PASS, ${fail} FAIL`);
|
|
86
|
+
process.exit(fail ? 1 : 0);
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// e2e: scheduling layer (调度层 C.2 priority+aging / C.3 auto-retry) — pure core +
|
|
2
|
+
// Store wiring on a temp state file. Never touches the real board or daemon state.
|
|
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 { normPriority, effectiveRank, bestLaneIndex, retryDecision } = await import(new URL("../lib/schedule.js", import.meta.url).href);
|
|
9
|
+
const { Store } = await import(new URL("../lib/store.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
|
+
// ---------- P1: priority normalization ----------
|
|
18
|
+
ok("P1a null/unknown → P2", normPriority(null) === "P2" && normPriority("P9") === "P2" && normPriority(undefined) === "P2");
|
|
19
|
+
ok("P1b case-insensitive valid", normPriority("p0") === "P0" && normPriority("P3") === "P3");
|
|
20
|
+
|
|
21
|
+
// ---------- P2: aging math ----------
|
|
22
|
+
const H = 3600000;
|
|
23
|
+
ok("P2a fresh P3 stays 3", effectiveRank("P3", 0, H) === 3);
|
|
24
|
+
ok("P2b P3 lifts one rank per aging period", effectiveRank("P3", H, H) === 2 && effectiveRank("P3", 2 * H, H) === 1);
|
|
25
|
+
ok("P2c clamps at P0", effectiveRank("P3", 10 * H, H) === 0 && effectiveRank("P0", 10 * H, H) === 0);
|
|
26
|
+
ok("P2d negative wait never lifts", effectiveRank("P2", -5000, H) === 2);
|
|
27
|
+
|
|
28
|
+
// ---------- P3: bestLaneIndex ordering ----------
|
|
29
|
+
const now = 1_000_000_000_000;
|
|
30
|
+
const aging = H;
|
|
31
|
+
ok("P3a empty lane → -1", bestLaneIndex({ lane: [], laneAt: {}, now, agingMs: aging }) === -1);
|
|
32
|
+
{
|
|
33
|
+
const lane = ["a", "b"];
|
|
34
|
+
const laneAt = { a: { at: now, priority: "P2" }, b: { at: now, priority: "P0" } };
|
|
35
|
+
ok("P3b P0 beats P2 regardless of order", bestLaneIndex({ lane, laneAt, now, agingMs: aging }) === 1);
|
|
36
|
+
}
|
|
37
|
+
{
|
|
38
|
+
const lane = ["a", "b"];
|
|
39
|
+
const laneAt = { a: { at: now - 1000, priority: "P2" }, b: { at: now, priority: "P2" } };
|
|
40
|
+
ok("P3c same rank → FIFO (older first)", bestLaneIndex({ lane, laneAt, now, agingMs: aging }) === 0);
|
|
41
|
+
}
|
|
42
|
+
{
|
|
43
|
+
const lane = ["old", "p0"];
|
|
44
|
+
const laneAt = { old: { at: now - 2.5 * H, priority: "P3" }, p0: { at: now, priority: "P0" } };
|
|
45
|
+
ok("P3d aged P3 (rank1) still loses to fresh P0", bestLaneIndex({ lane, laneAt, now, agingMs: aging }) === 1);
|
|
46
|
+
}
|
|
47
|
+
{
|
|
48
|
+
const lane = ["old", "fresh"];
|
|
49
|
+
const laneAt = { old: { at: now - 2.5 * H, priority: "P3" }, fresh: { at: now, priority: "P1" } };
|
|
50
|
+
ok("P3e aged P3 (rank1, older) beats fresh P1 (rank1) — anti-starvation", bestLaneIndex({ lane, laneAt, now, agingMs: aging }) === 0);
|
|
51
|
+
}
|
|
52
|
+
{
|
|
53
|
+
const lane = ["x", "y"];
|
|
54
|
+
ok("P3f missing laneAt treated as now (no aging)", bestLaneIndex({ lane, laneAt: {}, now, agingMs: aging }) === 0);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ---------- R1: retryDecision matrix ----------
|
|
58
|
+
const base = { why: "自报 success=false", result: { exitCode: 1 }, attempts: 0, maxAttempts: 2, baseMs: 30 * 60000, maxDelayMs: 4 * 3600000 };
|
|
59
|
+
ok("R1a transient failure retries with base delay", retryDecision(base).retry === true && retryDecision(base).delayMs === 30 * 60000 && retryDecision(base).attempt === 1);
|
|
60
|
+
ok("R1b backoff doubles per attempt", retryDecision({ ...base, attempts: 1 }).delayMs === 60 * 60000);
|
|
61
|
+
ok("R1c cap stops retrying", retryDecision({ ...base, attempts: 2 }).retry === false);
|
|
62
|
+
ok("R1d delay clamps at maxDelayMs", retryDecision({ ...base, attempts: 1, baseMs: 2 * H, maxDelayMs: 3 * H }).delayMs === 3 * H);
|
|
63
|
+
ok("R1e supply latch → no retry", retryDecision({ ...base, latch: { streak: 2 } }).retry === false);
|
|
64
|
+
ok("R1f manual kill → no retry", retryDecision({ ...base, killedBy: "manual" }).retry === false);
|
|
65
|
+
ok("R1g spawn error → no retry", retryDecision({ ...base, result: { spawnError: "ENOENT" } }).retry === false);
|
|
66
|
+
ok("R1h timeout kill → retry", retryDecision({ ...base, result: { killed: true, exitCode: null } }).retry === true);
|
|
67
|
+
ok("R1i stall kill → retry", retryDecision({ ...base, result: { stalled: true, exitCode: 1 } }).retry === true);
|
|
68
|
+
|
|
69
|
+
// ---------- S1: Store wiring on temp state ----------
|
|
70
|
+
{
|
|
71
|
+
const dir = mkdtempSync(join(tmpdir(), "bridge-sched-"));
|
|
72
|
+
const store = new Store(join(dir, "state.json"));
|
|
73
|
+
const t0 = now;
|
|
74
|
+
store.queue("t1", "trae", { priority: "P1" });
|
|
75
|
+
store.queue("t2", "trae", { priority: "P0" });
|
|
76
|
+
store.queue("t3", "trae", { priority: null }); // legacy → P2
|
|
77
|
+
ok("S1a queue records laneAt meta", store.s.laneAt.t1?.priority === "P1" && Number.isFinite(store.s.laneAt.t1?.at));
|
|
78
|
+
const pick1 = store.pickBest("trae", (k) => store.s.laneAt[k]?.priority, t0, aging, bestLaneIndex);
|
|
79
|
+
ok("S1b pickBest pops highest priority first", pick1 === "t2" && !store.s.lanes.trae.includes("t2"));
|
|
80
|
+
ok("S1c laneAt cleaned on pop", store.s.laneAt.t2 === undefined);
|
|
81
|
+
const pick2 = store.pickBest("trae", (k) => store.s.laneAt[k]?.priority, t0, aging, bestLaneIndex);
|
|
82
|
+
ok("S1d then P1 before P2", pick2 === "t1");
|
|
83
|
+
const pick3 = store.pickBest("trae", (k) => store.s.laneAt[k]?.priority, t0, aging, bestLaneIndex);
|
|
84
|
+
ok("S1e legacy P2 last; empty lane → null", pick3 === "t3" && store.pickBest("trae", (k) => null, t0, aging, bestLaneIndex) === null);
|
|
85
|
+
|
|
86
|
+
// retry lifecycle through the real requeue path (finished key must be clearable)
|
|
87
|
+
store.queue("r1", "codex", {});
|
|
88
|
+
ok("S1f-pre dispatch pops the card before beginRun", store.shiftLane("codex") === "r1");
|
|
89
|
+
store.endRun("r1", "failed rc=1", "codex"); // simulate settle bookkeeping (no run was open: endRun tolerates)
|
|
90
|
+
ok("S1f finished key blocks a plain re-queue", store.queue("r1", "codex") === false);
|
|
91
|
+
const rq = store.requeue("r1", "codex", { priority: "P0" });
|
|
92
|
+
ok("S1g requeue clears finished and re-lanes with meta", rq.ok === true && store.s.laneAt.r1?.priority === "P0", JSON.stringify(rq));
|
|
93
|
+
|
|
94
|
+
// busy-requeue semantics used by maybeRetry: run active → refused, entry kept by caller
|
|
95
|
+
store.queue("r2", "trae", {});
|
|
96
|
+
store.beginRun("r2", { agent: "trae" });
|
|
97
|
+
const busy = store.requeue("r2", "trae");
|
|
98
|
+
ok("S1h running key refused with 正在运行", busy.ok === false && String(busy.why).includes("正在运行"));
|
|
99
|
+
|
|
100
|
+
// legacy state (no laneAt/retries keys) must not crash
|
|
101
|
+
const legacy = new Store(join(dir, "legacy.json"));
|
|
102
|
+
legacy.state = { cursor: 1, pid: 1, lanes: { trae: ["k1"] } }; // simulate pre-laneAt state
|
|
103
|
+
const lk = legacy.pickBest("trae", () => null, t0, aging, bestLaneIndex);
|
|
104
|
+
ok("S1i legacy state without laneAt works", lk === "k1" && (legacy.s.laneAt?.k1 === undefined || true));
|
|
105
|
+
|
|
106
|
+
rmSync(dir, { recursive: true, force: true });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
console.log(`\n${pass} PASS, ${fail} FAIL`);
|
|
110
|
+
process.exit(fail ? 1 : 0);
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// 机械验证:事件 schema 版本化规则四判据(docs/design/2026-10-02-设计-事件schema版本化规则.md §3)
|
|
2
|
+
// A) 未来格式事件(新 kind + payload.v:2 + 未知键)按 computeHash 公式续链写入 → 链完好、读者透传
|
|
3
|
+
// B) tasks 表 ADD COLUMN 后 Board API 照常工作、链完好(加法安全)
|
|
4
|
+
// C) CLI 在含未知 kind 的板上照常工作(多版本读者并存)
|
|
5
|
+
// D) 改旧行一个字符 → brokenAtSeq 精确命中(R1 不可改写是机器强制的)
|
|
6
|
+
// 全程系统临时目录测试板,真板零接触。D 放最后,做了链就故意断了。
|
|
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 { createHash, randomUUID } from 'node:crypto';
|
|
12
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
13
|
+
|
|
14
|
+
const PKG = fileURLToPath(new URL('../board', import.meta.url));
|
|
15
|
+
const RUN = String(Date.now());
|
|
16
|
+
const BOARD = join(tmpdir(), `proofdeck-board-schema-verify-${RUN}`);
|
|
17
|
+
const NODE = process.execPath;
|
|
18
|
+
const CLI = `${PKG}/dist/cli.js`;
|
|
19
|
+
|
|
20
|
+
const board = (agent, args) => execFileSync(NODE, [CLI, ...args], {
|
|
21
|
+
encoding: 'utf8', env: { ...process.env, OCTOBOARD_DIR: BOARD, OCTOBOARD_AGENT: agent },
|
|
22
|
+
});
|
|
23
|
+
board('zcode', ['task', 'add', 'schema-evo-probe', '--title', 'schema 演进探针', '--desc', '测试板专用']);
|
|
24
|
+
board('zcode', ['claim', 'schema-evo-probe']);
|
|
25
|
+
|
|
26
|
+
// —— 用包自己的 Board.computeHash(未来写入方的唯一正解;顺带验证文档公式复刻与其一致)——
|
|
27
|
+
const { Board } = await import(pathToFileURL(`${PKG}/dist/board.js`));
|
|
28
|
+
const sha = (e) => Board.computeHash(e);
|
|
29
|
+
|
|
30
|
+
const openB = async () => Board.open({ boardDir: BOARD, agent: 'zcode' });
|
|
31
|
+
|
|
32
|
+
const head0 = await openB().then((b) => { try { return b.head(); } finally { b.close(); } });
|
|
33
|
+
|
|
34
|
+
// A) 注入未来格式事件:按写入方完整协议(行 + hash + meta head 锚更新)续链。
|
|
35
|
+
// meta 的 head_seq/head_hash 是写协议的一部分——append() 每写一行就推进它,
|
|
36
|
+
// verifyChain 尾部拿它做尾截断检查;裸插行不推进锚 = 故意制造"尾锚不符"。
|
|
37
|
+
{
|
|
38
|
+
const db = new DatabaseSync(`${BOARD}/board.db`);
|
|
39
|
+
const e = {
|
|
40
|
+
seq: head0.seq + 1,
|
|
41
|
+
at: new Date().toISOString(),
|
|
42
|
+
actor: 'zcode', sessionId: null, kind: 'test_kind_v2',
|
|
43
|
+
refTable: null, refId: null,
|
|
44
|
+
summary: '[schema-evo] 未来格式事件:payload.v=2 + 读者不认识的键',
|
|
45
|
+
payload: { v: 2, owner: '未来 risks.owner 的占位', due: '2026-10-09', unknownTomorrow: { nested: true } },
|
|
46
|
+
prevHash: head0.hash,
|
|
47
|
+
};
|
|
48
|
+
db.prepare(`INSERT INTO timeline (id, seq, at, actor, session_id, kind, ref_table, ref_id, summary, payload, prev_hash, hash)
|
|
49
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
50
|
+
.run(randomUUID(), e.seq, e.at, e.actor, e.sessionId, e.kind, e.refTable, e.refId, e.summary, JSON.stringify(e.payload), e.prevHash, sha(e));
|
|
51
|
+
db.prepare("UPDATE meta SET value = ? WHERE key = 'head_seq'").run(String(e.seq));
|
|
52
|
+
db.prepare("UPDATE meta SET value = ? WHERE key = 'head_hash'").run(sha(e));
|
|
53
|
+
db.close();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// 判据读取
|
|
57
|
+
const chainOf = async () => (await openB().then((b) => { try { return b.verifyChain(); } finally { b.close(); } }));
|
|
58
|
+
const sinceEvent = async (afterSeq) => (await openB().then((b) => {
|
|
59
|
+
try { return b.since(afterSeq).find((e) => e.kind === 'test_kind_v2') ?? null; } finally { b.close(); }
|
|
60
|
+
}));
|
|
61
|
+
|
|
62
|
+
const chainA = await chainOf();
|
|
63
|
+
const ev = await sinceEvent(head0.seq);
|
|
64
|
+
|
|
65
|
+
// B) 加列后 Board API 照常
|
|
66
|
+
{
|
|
67
|
+
const db = new DatabaseSync(`${BOARD}/board.db`);
|
|
68
|
+
db.exec("ALTER TABLE tasks ADD COLUMN zcode_test_owner TEXT");
|
|
69
|
+
db.close();
|
|
70
|
+
}
|
|
71
|
+
{
|
|
72
|
+
const b = await openB();
|
|
73
|
+
try { b.setProgress('zcode', 'schema-evo-probe', 50); b.taskCard('schema-evo-probe'); } finally { b.close(); }
|
|
74
|
+
}
|
|
75
|
+
const chainB = await chainOf();
|
|
76
|
+
|
|
77
|
+
// C) CLI 照常(timeline 输出含未知 kind,status 正常退出)
|
|
78
|
+
const cliTimeline = board('zcode', ['timeline']);
|
|
79
|
+
const cliStatus = board('zcode', ['status']);
|
|
80
|
+
|
|
81
|
+
// D) 最后做:改写防线两连测
|
|
82
|
+
// D1: DB 触发器直接拒绝 UPDATE(共享包 schema 自带的 append-only 守卫——第一道防线)
|
|
83
|
+
// D2: 测试板上卸掉触发器再改一个字符 → 链校验精确指出断点(哈希链=第二道防线)
|
|
84
|
+
{
|
|
85
|
+
const db = new DatabaseSync(`${BOARD}/board.db`);
|
|
86
|
+
let rejected = false;
|
|
87
|
+
try { db.prepare("UPDATE timeline SET summary = summary || 'x' WHERE seq = 1").run(); }
|
|
88
|
+
catch (e) { rejected = /append-only/.test(e.message); }
|
|
89
|
+
db.exec("DROP TRIGGER timeline_no_update; DROP TRIGGER timeline_no_delete;");
|
|
90
|
+
db.prepare("UPDATE timeline SET summary = summary || 'x' WHERE seq = 1").run();
|
|
91
|
+
db.close();
|
|
92
|
+
globalThis.__d1 = rejected;
|
|
93
|
+
}
|
|
94
|
+
const chainD = await chainOf();
|
|
95
|
+
|
|
96
|
+
const checks = [
|
|
97
|
+
['A: 未来格式续链 → verifyChain ok', chainA.ok && chainA.brokenAtSeq === null && chainA.length === head0.seq + 1],
|
|
98
|
+
['A: since() 透传 payload.v=2 与未知键', ev?.payload?.v === 2 && ev?.payload?.unknownTomorrow?.nested === true],
|
|
99
|
+
['B: ADD COLUMN 后 Board API 写读正常、链完好', chainB.ok && chainB.brokenAtSeq === null],
|
|
100
|
+
['C: CLI timeline 照常渲染未知 kind 事件(按 summary)', cliTimeline.includes('未来格式事件')],
|
|
101
|
+
['C: CLI status 正常', cliStatus.includes('schema-evo-probe')],
|
|
102
|
+
['D1: DB 触发器拒绝 UPDATE(append-only 第一道防线)', globalThis.__d1 === true],
|
|
103
|
+
['D2: 绕过触发器改一行 → brokenAtSeq 精确命中 seq=1(链=第二道防线)', chainD.brokenAtSeq === 1],
|
|
104
|
+
];
|
|
105
|
+
for (const [name, ok] of checks) console.log(`${ok ? 'PASS' : 'FAIL'} ${name}`);
|
|
106
|
+
console.log(checks.every(([, ok]) => ok) ? 'SCHEMA-EVO VERIFY PASS' : 'SCHEMA-EVO VERIFY FAIL');
|
|
107
|
+
process.exit(checks.every(([, ok]) => ok) ? 0 : 1);
|