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,105 @@
|
|
|
1
|
+
// e2e: batch ③ — SLA overdue flagging (C.4) + per-face concurrency (C.5) + owner digest (C.6).
|
|
2
|
+
// Pure functions + Store wiring + test-board integration; 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 S = await import(new URL("../lib/sla.js", import.meta.url).href);
|
|
9
|
+
const { parseBridgeBlock } = await import(new URL("../lib/verify.js", import.meta.url).href);
|
|
10
|
+
const { Store } = await import(new URL("../lib/store.js", import.meta.url).href);
|
|
11
|
+
const boardCh = await import(new URL("../lib/board.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 now = 1_800_000_000_000;
|
|
20
|
+
|
|
21
|
+
// ---------- S1: parseDueAt / overdueDecision ----------
|
|
22
|
+
ok("S1a epoch ms passthrough", S.parseDueAt(now - 1000) === now - 1000);
|
|
23
|
+
ok("S1b ISO parsed", S.parseDueAt(new Date(now).toISOString()) === now);
|
|
24
|
+
ok("S1c invalid → null", S.parseDueAt("not-a-date") === null && S.parseDueAt(null) === null && S.parseDueAt({}) === null);
|
|
25
|
+
|
|
26
|
+
ok("S2a no dueAt → null", S.overdueDecision({ dueAt: undefined, status: "open", now }) === null);
|
|
27
|
+
ok("S2b terminal states ignored", S.overdueDecision({ dueAt: now - 1000, status: "done", now }) === null && S.overdueDecision({ dueAt: now - 1000, status: "blocked", now }) === null);
|
|
28
|
+
ok("S2c not yet due → null", S.overdueDecision({ dueAt: now + 60000, status: "open", now }) === null);
|
|
29
|
+
{
|
|
30
|
+
const r = S.overdueDecision({ dueAt: now - 3600000, status: "in-progress", now });
|
|
31
|
+
ok("S2d overdue fires with duration", r?.overdueMs === 3600000, JSON.stringify(r));
|
|
32
|
+
}
|
|
33
|
+
ok("S2e notified once → silent", S.overdueDecision({ dueAt: now - 3600000, status: "open", now, notifiedAt: now - 1000 }) === null);
|
|
34
|
+
|
|
35
|
+
// ---------- D1: buildDigest ----------
|
|
36
|
+
ok("D1a all empty → empty", S.buildDigest({}).empty === true && S.buildDigest({ unreadBy: {}, pending: [], overdue: [], retries: [], blockedRecent: [] }).empty === true);
|
|
37
|
+
{
|
|
38
|
+
const d = S.buildDigest({
|
|
39
|
+
unreadBy: { reviewer1: 2, buddy: 1 },
|
|
40
|
+
pending: [{ key: "a1", reason: "命中禁词: 部署" }],
|
|
41
|
+
overdue: ["k9"],
|
|
42
|
+
retries: [{ key: "r1", n: 2 }],
|
|
43
|
+
blockedRecent: ["b1", "b2"],
|
|
44
|
+
running: ["run1"],
|
|
45
|
+
});
|
|
46
|
+
ok("D1b sections rendered", !d.empty && d.text.includes("未读消息 3 条(reviewer1×2、buddy×1)") && d.text.includes("待审批 1 张") && d.text.includes("逾期 1 张") && d.text.includes("自动重派排队 1 张") && d.text.includes("近期失败/阻塞 2 张") && d.text.includes("正在跑 1 张"), d.text.replaceAll("\n", " | ").slice(0, 160));
|
|
47
|
+
}
|
|
48
|
+
{
|
|
49
|
+
const many = S.buildDigest({ overdue: ["a", "b", "c", "d", "e", "f"] });
|
|
50
|
+
ok("D1c >5 truncated with ellipsis", many.text.includes("逾期 6 张:a, b, c, d, e…"), many.text);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ---------- C1: Store.runsFor + face concurrency arithmetic ----------
|
|
54
|
+
{
|
|
55
|
+
const dir = mkdtempSync(join(tmpdir(), "bridge-sla-"));
|
|
56
|
+
const store = new Store(join(dir, "state.json"));
|
|
57
|
+
store.beginRun("t1", { agent: "trae" });
|
|
58
|
+
ok("C1a face gate at 1 run: max1 closed, max2 open", !(store.runsFor("trae") < 1) && (store.runsFor("trae") < 2));
|
|
59
|
+
store.beginRun("t2", { agent: "trae" });
|
|
60
|
+
store.beginRun("t3", { agent: "codex" });
|
|
61
|
+
ok("C1b runsFor counts per face", store.runsFor("trae") === 2 && store.runsFor("codex") === 1 && store.runsFor("pi") === 0);
|
|
62
|
+
ok("C1c face gate at 2 runs: max2 closed too", !(store.runsFor("trae") < 2));
|
|
63
|
+
rmSync(dir, { recursive: true, force: true });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---------- B1: test-board integrated overdue scan (replicates maybeSla's decision flow) ----------
|
|
67
|
+
{
|
|
68
|
+
const dir = mkdtempSync(join(tmpdir(), "bridge-sla-board-"));
|
|
69
|
+
const boardDir = join(dir, "board");
|
|
70
|
+
await boardCh.init(fileURLToPath(new URL("../board", import.meta.url)));
|
|
71
|
+
const cfg = { dir: boardDir, identity: "bridge" };
|
|
72
|
+
const desc = '任务说明\n```bridge\n{ "dueAt": "2020-01-01T00:00:00Z" }\n```\n';
|
|
73
|
+
await boardCh.withBoard(cfg, (b) => b.defineTask("zcode", "sla-e2e-1", { title: "sla e2e", description: desc }));
|
|
74
|
+
const notified = {};
|
|
75
|
+
let flagged;
|
|
76
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
77
|
+
const t = b.getTask("sla-e2e-1");
|
|
78
|
+
const bb = parseBridgeBlock(t.description);
|
|
79
|
+
const dec = S.overdueDecision({ dueAt: bb?.dueAt, status: t.status, now: Date.now(), notifiedAt: notified[t.key] });
|
|
80
|
+
ok("B1a bridge block dueAt extracted, overdue fires", bb?.dueAt === "2020-01-01T00:00:00Z" && !!dec);
|
|
81
|
+
if (dec) {
|
|
82
|
+
notified[t.key] = Date.now();
|
|
83
|
+
boardCh.note(b, "bridge", `[OVERDUE] ${t.key} 已逾期 — 测试`);
|
|
84
|
+
boardCh.message(b, "bridge", t.createdBy ?? "kemu", `[bridge] 任务 ${t.key} 已逾期,请处置。`);
|
|
85
|
+
flagged = t.key;
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
ok("B1b flagged key", flagged === "sla-e2e-1");
|
|
89
|
+
await boardCh.withBoard(cfg, (b) => {
|
|
90
|
+
const evs = b.timeline(100);
|
|
91
|
+
ok("B1c [OVERDUE] note on chain", evs.some((e) => String(e.summary).includes("[OVERDUE] sla-e2e-1")));
|
|
92
|
+
const msgs = b.inbox("zcode", true);
|
|
93
|
+
ok("B1d creator notified", msgs.some((m) => JSON.stringify(m).includes("已逾期")));
|
|
94
|
+
// 第二次扫描:notified 台账拦住,不再重复
|
|
95
|
+
const t = b.getTask("sla-e2e-1");
|
|
96
|
+
const bb = parseBridgeBlock(t.description);
|
|
97
|
+
const again = S.overdueDecision({ dueAt: bb?.dueAt, status: t.status, now: Date.now(), notifiedAt: notified[t.key] });
|
|
98
|
+
ok("B1e second scan silent (once-per-card)", again === null);
|
|
99
|
+
ok("B1f chain intact", b.verifyChain().brokenAtSeq === null);
|
|
100
|
+
});
|
|
101
|
+
rmSync(dir, { recursive: true, force: true });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
console.log(`\n${pass} PASS, ${fail} FAIL`);
|
|
105
|
+
process.exit(fail ? 1 : 0);
|
package/guard.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// guard — invoked by the agent-bridge-guard scheduled task, rep=PT1M (registered
|
|
2
|
+
// cadence measured from guard.log: median gap exactly 1.00 min over 2889 samples).
|
|
3
|
+
// v2 (2026-10-02 incident follow-up): liveness = process existence AND control-port
|
|
4
|
+
// responsiveness; every "dead" verdict needs two consecutive runs (two-strike)
|
|
5
|
+
// before spawning/killing; kill only after command-line confirmation, with a 30min
|
|
6
|
+
// cooldown and a 3/hour cap. Decision logic lives in lib/guard-core.mjs (e2e-tested).
|
|
7
|
+
//
|
|
8
|
+
// Hard rule: this process MUST exit within seconds. run_daemon.bat is an
|
|
9
|
+
// infinite restart loop, so any blocking spawn leaves the guard hung forever and
|
|
10
|
+
// no future guard run restarts the daemon (that exact failure cost 1.5 days of
|
|
11
|
+
// silent downtime on 2026-09-23..25). Hence: async bounded I/O + detached spawn
|
|
12
|
+
// + unref + hard exit. Probe is capped at 3.5s and the command-line identity check at
|
|
13
|
+
// 9s, both under a 15s hard exit.
|
|
14
|
+
import { readFileSync, existsSync, mkdirSync, appendFileSync } from "node:fs";
|
|
15
|
+
import { spawn } from "node:child_process";
|
|
16
|
+
import { join, dirname } from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
import { getProcessInfo, IS_WINDOWS } from "./lib/platform.js";
|
|
19
|
+
import { runGuardCheck } from "./lib/guard-core.mjs";
|
|
20
|
+
|
|
21
|
+
const BASE = dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
const logFile = join(BASE, "logs", "guard.log");
|
|
23
|
+
const log = (m) => {
|
|
24
|
+
try {
|
|
25
|
+
mkdirSync(dirname(logFile), { recursive: true });
|
|
26
|
+
appendFileSync(logFile, `[${new Date().toISOString()}] ${m}\n`);
|
|
27
|
+
} catch { /* guard must never fail on logging */ }
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// Belt-and-braces: whatever happens above, don't linger past 15s. The identity confirm is a
|
|
31
|
+
// PowerShell call and 2026-10-06 measurement says powershell cold-start alone is ~4.0-4.4s, a
|
|
32
|
+
// single-pid Get-CimInstance is 5.7-7.5s — the old 8s exit capped confirm at 3.5s, so confirm
|
|
33
|
+
// returned null every time and the kill branch could never legitimately fire. Budget now:
|
|
34
|
+
// probe 3.5s + confirm 9s = 12.5s worst case, inside a 15s hard exit, inside the 60s task period.
|
|
35
|
+
setTimeout(() => { log("watchdog exit — something blocked"); process.exit(0); }, 15000).unref();
|
|
36
|
+
|
|
37
|
+
let cfg = {};
|
|
38
|
+
try { cfg = JSON.parse(readFileSync(join(BASE, "daemon.config.json"), "utf8")); } catch { /* fall back to defaults */ }
|
|
39
|
+
const port = cfg.http?.port ?? 8790;
|
|
40
|
+
const tokenPath = join(BASE, "control.token");
|
|
41
|
+
const token = existsSync(tokenPath) ? readFileSync(tokenPath, "utf8").trim() : "";
|
|
42
|
+
|
|
43
|
+
// Command-line identity check over the platform primitive (drained + timer-raced
|
|
44
|
+
// on win32 — see lib/platform.js for the conhost-pipe incident history).
|
|
45
|
+
// Returns true/false, or null when inconclusive (caller must stand down — never kill on a guess).
|
|
46
|
+
async function confirmByCommandLine(pid, timeoutMs) {
|
|
47
|
+
const info = await getProcessInfo(pid, timeoutMs);
|
|
48
|
+
if (info.commandLine == null) return null;
|
|
49
|
+
return info.commandLine.includes("daemon.js") && info.commandLine.includes(BASE) ? true : false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const ctx = {
|
|
53
|
+
log,
|
|
54
|
+
now: () => Date.now(),
|
|
55
|
+
readState: () => { try { return JSON.parse(readFileSync(join(BASE, "state.json"), "utf8")); } catch { return null; } },
|
|
56
|
+
stopPresent: () => existsSync(join(BASE, "STOP")),
|
|
57
|
+
processAlive: (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } },
|
|
58
|
+
strikeFile: join(BASE, "logs", "guard-strikes.json"),
|
|
59
|
+
probe: async (statePid) => {
|
|
60
|
+
// 四种判据分开返回,别把「连不上」和「连上不答」混成一个:
|
|
61
|
+
// refused = 内核 RST,端口上没人监听 → 支持杀/重启
|
|
62
|
+
// timeout = 连上了但 3.5s 内没回 → 与「饥饿的健在守护」同形(10-05 实测慢答 36.989433s),不可当死
|
|
63
|
+
try {
|
|
64
|
+
const r = await fetch(`http://127.0.0.1:${port}/ps?token=${encodeURIComponent(token)}`, { signal: AbortSignal.timeout(3500) });
|
|
65
|
+
if (r.status === 200) {
|
|
66
|
+
const body = await r.json();
|
|
67
|
+
return Number(body.pid) === Number(statePid) ? "ok" : "mismatch";
|
|
68
|
+
}
|
|
69
|
+
return "ok"; // 任何 HTTP 应答都说明事件循环在服务
|
|
70
|
+
} catch (e) {
|
|
71
|
+
if ((e?.cause?.code ?? e?.code) === "ECONNREFUSED") return "refused";
|
|
72
|
+
return "timeout";
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
confirmDaemon: (pid) => confirmByCommandLine(pid, 9000),
|
|
76
|
+
kill: (pid) => { try { process.kill(pid, "SIGKILL"); } catch (e) { log(`SIGKILL pid=${pid} failed: ${e.message}`); } },
|
|
77
|
+
spawnLauncher: () => {
|
|
78
|
+
// detached + ignore stdio + unref: the loop outlives the guard and the guard
|
|
79
|
+
// exits immediately. (cmd /c start via execFileSync is what hung before.)
|
|
80
|
+
if (IS_WINDOWS) {
|
|
81
|
+
const child = spawn("cmd.exe", ["/c", join(BASE, "run_daemon.bat")], { detached: true, stdio: "ignore", windowsHide: true });
|
|
82
|
+
child.unref();
|
|
83
|
+
log(`launcher spawned (child pid=${child.pid})`);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
const sh = join(BASE, "scripts", "run-daemon.sh");
|
|
87
|
+
if (!existsSync(sh)) { log("launcher skipped: scripts/run-daemon.sh not present"); return false; }
|
|
88
|
+
const child = spawn("sh", [sh], { detached: true, stdio: "ignore" });
|
|
89
|
+
child.unref();
|
|
90
|
+
log(`launcher spawned (child pid=${child.pid})`);
|
|
91
|
+
return true;
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
runGuardCheck(ctx)
|
|
96
|
+
.catch((e) => log(`guard check failed: ${e.stack || e.message}`))
|
|
97
|
+
.finally(() => process.exit(0));
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// codex adapter — headless `codex exec`.
|
|
2
|
+
// Prompt is fed via stdin (NEVER argv: long Chinese text corrupts through
|
|
3
|
+
// shells on this box). Result is taken from the per-run `-o` file (no races).
|
|
4
|
+
// `-p/--profile` is deliberately unused: 0.147 ProfileV2 silently no-ops
|
|
5
|
+
// against this machine's legacy inline [profiles.*].
|
|
6
|
+
import { readFileSync, existsSync, readdirSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
|
|
10
|
+
export function probeModel(agentCfg) {
|
|
11
|
+
try {
|
|
12
|
+
const toml = readFileSync(agentCfg.modelProbe.file, "utf8");
|
|
13
|
+
const head = toml.split(/^\s*\[/m)[0]; // top-level keys only
|
|
14
|
+
const model = /^\s*model\s*=\s*"([^"]+)"/m.exec(head)?.[1] ?? null;
|
|
15
|
+
const provider = /^\s*model_provider\s*=\s*"([^"]+)"/m.exec(head)?.[1] ?? "openai";
|
|
16
|
+
return { model, provider, source: agentCfg.modelProbe.file };
|
|
17
|
+
} catch {
|
|
18
|
+
return { model: null, provider: null, source: "probe-failed" };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function buildRun({ agentCfg, runDir, promptFile, workdir, fm }) {
|
|
23
|
+
const lastMsg = join(runDir, "last-message.txt");
|
|
24
|
+
const args = [agentCfg.script, "exec",
|
|
25
|
+
"-C", workdir,
|
|
26
|
+
"-s", fm.sandbox || agentCfg.sandbox || "workspace-write",
|
|
27
|
+
"--json",
|
|
28
|
+
"-o", lastMsg,
|
|
29
|
+
...(agentCfg.extraArgs ?? [])];
|
|
30
|
+
if (fm.model) args.push("-m", fm.model);
|
|
31
|
+
if (fm.provider && !fm.model) args.push("-c", `model_provider="${fm.provider}"`);
|
|
32
|
+
args.push("-"); // read prompt from stdin
|
|
33
|
+
return {
|
|
34
|
+
exe: agentCfg.node ?? "node",
|
|
35
|
+
args,
|
|
36
|
+
cwd: workdir,
|
|
37
|
+
stdinFile: promptFile,
|
|
38
|
+
lastMsgFile: lastMsg,
|
|
39
|
+
env: { ...(agentCfg.env ?? {}) },
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 分段续跑(#29):codex 是四面里唯一有原生会话续跑的(`codex exec resume <SESSION_ID> [PROMPT]`,
|
|
45
|
+
* 实测 --help 于 2026-09-29)。接上原 thread ⇒ 模型上下文不必靠检查点文本重建,
|
|
46
|
+
* 本段的 prompt 就是「原题 + 检查点」那段续跑题面(走 stdin,与首段同一条通道)。
|
|
47
|
+
* 注意 resume 子命令没有 -C/-s:工作目录靠 spawn 的 cwd(runner 已按 workdir 起),
|
|
48
|
+
* 沙箱改用配置键 sandbox_mode 传,值与首段同源。
|
|
49
|
+
*/
|
|
50
|
+
export function resumeSpec(o) {
|
|
51
|
+
const threadId = o.resume?.threadId;
|
|
52
|
+
if (!threadId) return null;
|
|
53
|
+
const { agentCfg, runDir, promptFile, workdir, fm } = o;
|
|
54
|
+
const lastMsg = join(runDir, "last-message.txt");
|
|
55
|
+
return {
|
|
56
|
+
exe: agentCfg.node ?? "node",
|
|
57
|
+
args: [agentCfg.script, "exec", "resume", threadId,
|
|
58
|
+
"--json",
|
|
59
|
+
"-o", lastMsg,
|
|
60
|
+
"-c", `sandbox_mode="${fm.sandbox || agentCfg.sandbox || "workspace-write"}"`,
|
|
61
|
+
...(agentCfg.extraArgs ?? []),
|
|
62
|
+
"-"],
|
|
63
|
+
cwd: workdir,
|
|
64
|
+
stdinFile: promptFile,
|
|
65
|
+
lastMsgFile: lastMsg,
|
|
66
|
+
env: { ...(agentCfg.env ?? {}) },
|
|
67
|
+
resumed: true,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Parse one codex --json JSONL line. Returns {milestone?, threadId?, raw}. */
|
|
72
|
+
export function parseEvent(line) {
|
|
73
|
+
let obj;
|
|
74
|
+
try { obj = JSON.parse(line); } catch { return null; }
|
|
75
|
+
const t = obj.type ?? obj.msg?.type ?? null;
|
|
76
|
+
const out = { raw: obj };
|
|
77
|
+
if (t === "thread.started" || obj.thread_id) out.threadId = obj.thread_id ?? obj.id ?? null;
|
|
78
|
+
if (t === "turn.started") out.milestone = "turn-started";
|
|
79
|
+
if (t === "turn.completed") out.milestone = "turn-completed";
|
|
80
|
+
// 错误项不是进展:实测配额墙那轮(temp/segsmoke-*/codex-seg1)有 2 条 item.completed,
|
|
81
|
+
// 两条都是 {"item":{"type":"error"}},items=2 让 #25 的「0 步进展」条件判不出来,
|
|
82
|
+
// 于是明知供应方停了还会一直重试。
|
|
83
|
+
if (t === "item.completed" && obj.item?.type !== "error") out.milestone = "item";
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function readResult(run) {
|
|
88
|
+
try {
|
|
89
|
+
if (existsSync(run.lastMsgFile)) return readFileSync(run.lastMsgFile, "utf8").trim();
|
|
90
|
+
} catch { /* fall through */ }
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 兜底源:codex 自己落盘会话轨迹 sessions/YYYY/MM/DD/rollout-<时间>-<thread_id>.jsonl,
|
|
96
|
+
* 里面每完成一次模型调用就追加一条 event_msg/payload.type="token_count",带累计 total_token_usage。
|
|
97
|
+
* 被 kill 的轮我们那份 codex.jsonl 没有 turn.completed,但这里往往已经写到了最后一步。
|
|
98
|
+
* 口径已对照过:三个两边都有的历史轮,input/cached/output/total 逐字段完全相等(见 out/ 里的说明)。
|
|
99
|
+
*/
|
|
100
|
+
function rolloutUsage(raw, agentCfg) {
|
|
101
|
+
const threadId = (() => {
|
|
102
|
+
for (const line of raw.split("\n")) {
|
|
103
|
+
if (!line.trim().startsWith("{")) continue;
|
|
104
|
+
let ev; try { ev = JSON.parse(line); } catch { continue; }
|
|
105
|
+
const id = ev.thread_id ?? ev.msg?.thread_id;
|
|
106
|
+
if (id) return String(id).toLowerCase();
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
})();
|
|
110
|
+
if (!threadId) return null;
|
|
111
|
+
|
|
112
|
+
const home = agentCfg?.env?.CODEX_HOME || process.env.CODEX_HOME || join(homedir(), ".codex");
|
|
113
|
+
const sess = join(home, "sessions");
|
|
114
|
+
if (!existsSync(sess)) return null;
|
|
115
|
+
|
|
116
|
+
// 文件名里带 thread_id ⇒ 定位是精确匹配;目录只有 年/月/日 三层,走穿也不贵。
|
|
117
|
+
// 只在缺 turn.completed 时才会走到这里,正常轮不碰这块磁盘扫描。
|
|
118
|
+
let file = null;
|
|
119
|
+
const walk = (d, depth) => {
|
|
120
|
+
if (file || depth > 4) return;
|
|
121
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
122
|
+
const p = join(d, e.name);
|
|
123
|
+
if (e.isDirectory()) walk(p, depth + 1);
|
|
124
|
+
else if (e.name.toLowerCase().includes(threadId)) { file = p; return; }
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
walk(sess, 0);
|
|
128
|
+
if (!file) return null;
|
|
129
|
+
|
|
130
|
+
let last = null, counts = 0;
|
|
131
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
132
|
+
if (!line.trim().startsWith("{")) continue;
|
|
133
|
+
let ev; try { ev = JSON.parse(line); } catch { continue; }
|
|
134
|
+
const tt = ev?.payload?.type === "token_count" ? ev.payload.info?.total_token_usage : null;
|
|
135
|
+
if (!tt) continue;
|
|
136
|
+
counts++;
|
|
137
|
+
last = tt; // 累计口径,取最后一条即整轮总量
|
|
138
|
+
}
|
|
139
|
+
if (!last) return { found: file, usage: null, counts };
|
|
140
|
+
return { found: file, counts, usage: last };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 权威用量:优先 codex.jsonl 里 type="turn.completed" 那条的顶层 usage(实测一次 run 恰好一条)。
|
|
145
|
+
* 多条就相加,防未来一轮变多轮时漏记。
|
|
146
|
+
* input_tokens 按 OpenAI Responses 口径已含 cached_input_tokens ⇒ prompt 直接取它,不再加缓存。
|
|
147
|
+
* 没有 turn.completed(跑一半被 kill、连接超时)⇒ 退到 rollout 的 token_count 累计值。
|
|
148
|
+
*/
|
|
149
|
+
export function readUsage({ runDir, agentCfg }) {
|
|
150
|
+
const file = join(runDir, "codex.jsonl");
|
|
151
|
+
if (!existsSync(file)) return null;
|
|
152
|
+
const raw = readFileSync(file, "utf8");
|
|
153
|
+
let acc = null, turns = 0;
|
|
154
|
+
for (const line of raw.split("\n")) {
|
|
155
|
+
if (!line.trim().startsWith("{")) continue;
|
|
156
|
+
let ev;
|
|
157
|
+
try { ev = JSON.parse(line); } catch { continue; }
|
|
158
|
+
const u = ev?.type === "turn.completed" ? ev.usage : null;
|
|
159
|
+
if (!u) continue;
|
|
160
|
+
turns++;
|
|
161
|
+
acc ??= { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 };
|
|
162
|
+
acc.input += u.input_tokens ?? 0;
|
|
163
|
+
acc.cached += u.cached_input_tokens ?? 0;
|
|
164
|
+
acc.cacheWrite += u.cache_write_input_tokens ?? 0;
|
|
165
|
+
acc.output += u.output_tokens ?? 0;
|
|
166
|
+
acc.reasoning += u.reasoning_output_tokens ?? 0;
|
|
167
|
+
}
|
|
168
|
+
if (!acc) {
|
|
169
|
+
// resume 段不能走 rollout 兜底:那条轨迹按 thread 累计,一个 thread 跑了 k 段就含 k 段的量,
|
|
170
|
+
// 当成「本段用量」会把上一段的 token 记到这一段头上。宁可 missing,也不给一个跨段的假数。
|
|
171
|
+
const resumedRun = (() => {
|
|
172
|
+
try { return !!JSON.parse(readFileSync(join(runDir, "meta.json"), "utf8")).resumed; } catch { return false; }
|
|
173
|
+
})();
|
|
174
|
+
const ro = resumedRun ? null : rolloutUsage(raw, agentCfg);
|
|
175
|
+
if (ro?.usage) {
|
|
176
|
+
const u = ro.usage;
|
|
177
|
+
return {
|
|
178
|
+
source: "rollout:token_count",
|
|
179
|
+
// 一条 token_count = 一次模型调用回报 ⇒ 这个数能当步数用
|
|
180
|
+
steps: ro.counts || null, maxSteps: null, overflow: null,
|
|
181
|
+
normalized: {
|
|
182
|
+
prompt: u.input_tokens ?? 0, completion: u.output_tokens ?? 0,
|
|
183
|
+
cached: u.cached_input_tokens ?? 0, cacheWrite: u.cache_write_input_tokens ?? 0,
|
|
184
|
+
reasoning: u.reasoning_output_tokens ?? 0,
|
|
185
|
+
},
|
|
186
|
+
total: u.total_tokens ?? null,
|
|
187
|
+
semantics: "兜底自 codex 会话轨迹的累计值;正在飞的最后一次调用没回报 ⇒ 是下界",
|
|
188
|
+
raw: u,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
// 两份权威产物都查过了:我们那份没 turn.completed,rollout 里一条 token_count 都没有
|
|
192
|
+
// (实测:第一次调用还没回报就被掐的那几次)。token 确实烧了却再也量不到
|
|
193
|
+
// ⇒ 交 normalizeUsage 落成 missing,不许当 0。
|
|
194
|
+
return {
|
|
195
|
+
source: `codex.jsonl+rollout${resumedRun ? "(resume 段:rollout 累计值跨段不可拆,不采用)" : ro ? "(0 条 token_count)" : "(rollout 未找到)"}`,
|
|
196
|
+
steps: null, maxSteps: null, overflow: null,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
source: "codex.jsonl:turn.completed",
|
|
201
|
+
steps: turns || null, maxSteps: null, overflow: null,
|
|
202
|
+
normalized: { prompt: acc.input, completion: acc.output, cached: acc.cached, cacheWrite: acc.cacheWrite, reasoning: acc.reasoning },
|
|
203
|
+
semantics: "input_tokens 含缓存(Responses 口径)",
|
|
204
|
+
raw: acc,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// 余额断供 → 公开待认领任务的转化逻辑。
|
|
2
|
+
//
|
|
3
|
+
// 为什么单独成模块:这段逻辑要能脱离 daemon.js 起真守护来验证(真守护一启动就会
|
|
4
|
+
// 动队列、抢卡)。纯函数 + 注入 board 桩 = 可离线断言。daemon.js 只做接线。
|
|
5
|
+
//
|
|
6
|
+
// 语义:
|
|
7
|
+
// - 只对 category==="billing"(余额/额度耗尽)触发。rate 会自愈、auth 要换 key,都不该转派。
|
|
8
|
+
// - 不自动改派:同一部署的面往往共用一个钱包,改派很可能撞另一个同样空的。转成"公开可认领",
|
|
9
|
+
// 由有额度的人来捡,是当前唯一不会二连撞的形态。
|
|
10
|
+
// - 幂等:同一 key 只转一次(记账 key 由调用方持有,落 state 所以重启不丢)。
|
|
11
|
+
|
|
12
|
+
/** 断供卡面的追加说明(纯函数,便于断言内容)。 */
|
|
13
|
+
export function billingMarker({ key, agent, hit, runDir, stamp }) {
|
|
14
|
+
return [
|
|
15
|
+
"",
|
|
16
|
+
"—— 供应方断供 · 公开待认领 ——",
|
|
17
|
+
`原承接面:${agent}(${hit?.label ?? hit?.category ?? "billing"})`,
|
|
18
|
+
`断供时间:${stamp}`,
|
|
19
|
+
`原日志:${runDir}`,
|
|
20
|
+
`证据:${hit?.file}:「${String(hit?.line ?? "").slice(0, 200)}」`,
|
|
21
|
+
"任何有可用额度的 agent 均可认领本卡;认领前先确认自己的面可用(node bridge-ctl.js ps)。",
|
|
22
|
+
`恢复原面的承接:node bridge-ctl.js supply-clear ${agent} && node bridge-ctl.js requeue ${key} ${agent}`,
|
|
23
|
+
].join("\n");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 广播文案(纯函数)。 */
|
|
27
|
+
export function billingBroadcast({ agent, hit, key, title }) {
|
|
28
|
+
return `供应方断供转公开待认领:**${key}**(原面 ${agent}·${hit?.label ?? "billing"})—— ${title}。有额度的 agent 可从卡面认领;原面恢复后可 supply-clear + requeue 接回。`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** owner 私信文案(纯函数;只在"该面首次断供"时发)。 */
|
|
32
|
+
export function billingOwnerNotice({ agent, hit, key, runDir }) {
|
|
33
|
+
return `${agent} 没钱了(${hit?.label ?? "余额/额度耗尽"}),卡 ${key} 已转成【公开待认领】挂到板上,等有额度的 agent 捡。要充值才能恢复原面。日志: ${runDir}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 执行转化。board 需提供 { setStatus, defineTask, note } 三个写操作:
|
|
38
|
+
* setStatus(key, status) / defineTask(key, {description}) / note(text)
|
|
39
|
+
* 调用方(daemon.js)用小适配器把 board 助手包成这三个形状,模块本身不依赖 board 的内部签名。
|
|
40
|
+
*
|
|
41
|
+
* 返回 { converted, reason }:switch-off / not-billing / already-converted / converted
|
|
42
|
+
*/
|
|
43
|
+
export function convertBillingTask(io, { key, agent, task, hit, runDir, converted, enabled = true }) {
|
|
44
|
+
if (!enabled) return { converted: false, reason: "switch-off" };
|
|
45
|
+
if (hit?.category !== "billing") return { converted: false, reason: "not-billing" };
|
|
46
|
+
if (converted[key]) return { converted: false, reason: "already-converted" };
|
|
47
|
+
|
|
48
|
+
const stamp = new Date().toISOString().slice(0, 16).replace("T", " ");
|
|
49
|
+
const prevDesc = String(task?.description ?? "");
|
|
50
|
+
const title = String(task?.title ?? key);
|
|
51
|
+
|
|
52
|
+
io.setStatus(key, "blocked");
|
|
53
|
+
io.defineTask(key, { description: `${prevDesc}${billingMarker({ key, agent, hit, runDir, stamp })}` });
|
|
54
|
+
io.note(billingBroadcast({ key, agent, hit, title }));
|
|
55
|
+
converted[key] = { at: new Date().toISOString(), agent, category: hit.category, label: hit.label };
|
|
56
|
+
return { converted: true };
|
|
57
|
+
}
|
package/lib/board.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Daemon-side board channel. Uses the SHARED octopus-blackboard Board library
|
|
2
|
+
// directly (same code the CLI/MCP run) — never raw SQL, never text parsing.
|
|
3
|
+
// Every op opens/closes its own handle (like the MCP server does).
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
|
|
6
|
+
let Board = null;
|
|
7
|
+
|
|
8
|
+
export async function init(pkgDir) {
|
|
9
|
+
const mod = await import(pathToFileURL(pkgDir + "/dist/board.js").href);
|
|
10
|
+
Board = mod.Board;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function withBoard(boardCfg, fn, sessionId = null) {
|
|
14
|
+
const b = Board.open({ boardDir: boardCfg.dir, agent: boardCfg.identity, ...(sessionId ? { sessionId } : {}) });
|
|
15
|
+
try {
|
|
16
|
+
return await fn(b);
|
|
17
|
+
} finally {
|
|
18
|
+
try { b.close(); } catch { /* already closed */ }
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// --- thin named helpers (all synchronous over Board) ---
|
|
23
|
+
export const head = (b) => b.head();
|
|
24
|
+
export const since = (b, cursor) => b.since(cursor);
|
|
25
|
+
export const card = (b, key) => b.taskCard(key) ?? null;
|
|
26
|
+
export const claim = (b, actor, key) => b.claim(actor, key);
|
|
27
|
+
export const progress = (b, actor, key, pct) => b.setProgress(actor, key, pct);
|
|
28
|
+
export const done = (b, actor, key) => b.complete(actor, key);
|
|
29
|
+
export const setStatus = (b, actor, key, status) => b.setTaskStatus(actor, key, status);
|
|
30
|
+
// defineTask:创建或更新卡的 title/description 等字段(key 已存在时只更新传入字段)。
|
|
31
|
+
// 2026-10-06 补:billing-convert 要在卡面追加"断供待认领"说明时用;此前 lib/board.js 漏了这个助手。
|
|
32
|
+
export const defineTask = (b, actor, key, opts) => b.defineTask(actor, key, opts);
|
|
33
|
+
export const note = (b, actor, text) => b.note(actor, text);
|
|
34
|
+
export const message = (b, actor, to, body) => b.message(actor, to, body);
|
|
35
|
+
export const heartbeat = (b, sessionId) => b.heartbeat(sessionId);
|
|
36
|
+
export const startSession = (b, label, options) => b.startSession(label, options);
|
|
37
|
+
export const stopSession = (b, sessionId) => b.stopSession(sessionId);
|
|
38
|
+
export const listCards = (b) => b.listTaskCards();
|
|
39
|
+
export const activeSessions = (b, withinMs) => b.activeSessions(withinMs);
|
|
40
|
+
// 验证层一等公民 API(2026-10-07 共享包扩展后可用):verify 落 kind=verify 的
|
|
41
|
+
// 时间线事件(进哈希链,verdict fail-closed 只收 pass/fail)。旧 dist 无此方法时
|
|
42
|
+
// 返回 null/[],调用方(io.verify?. / board.verify?.)判空跳过——不阻塞任务流。
|
|
43
|
+
export const verify = (b, actor, key, verdict, opts) =>
|
|
44
|
+
typeof b.verify === "function" ? b.verify(actor, key, verdict, opts ?? {}) : null;
|
|
45
|
+
export const verificationsFor = (b, key) =>
|
|
46
|
+
typeof b.verificationsFor === "function" ? b.verificationsFor(key) : [];
|
package/lib/caps.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// 能力匹配(2026-10-07 采纳建议③ 第一步):任务书 bridge 块可声明 needs: ["content", ...],
|
|
2
|
+
// 各面在 daemon.config.json 的 agents.<face>.capabilities 声明能力。
|
|
3
|
+
// 语义(向后兼容优先):
|
|
4
|
+
// - 任务未声明 needs → 所有面都合格(现状不变)
|
|
5
|
+
// - 面未声明 capabilities → 视为"万能",任何 needs 都合格(存量配置零改动)
|
|
6
|
+
// - 双边都声明了 → needs 全集 ⊆ capabilities 才合格(大小写不敏感)
|
|
7
|
+
// 匹配失败时由调用方(daemon handle())按 fallbacks 找有能力的可用面改派,
|
|
8
|
+
// 与 asciiOnly 硬门限同一形态;全不可用则 refuse 上板。
|
|
9
|
+
|
|
10
|
+
export function parseNeeds(block) {
|
|
11
|
+
const n = block?.needs;
|
|
12
|
+
if (typeof n === "string" && n.trim()) return [n.trim().toLowerCase()];
|
|
13
|
+
if (Array.isArray(n)) return n.filter((x) => x != null).map((x) => String(x).trim().toLowerCase()).filter(Boolean);
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function faceHasCaps(faceCaps, needs) {
|
|
18
|
+
if (!needs?.length) return true;
|
|
19
|
+
if (!Array.isArray(faceCaps) || faceCaps.length === 0) return true; // 未声明 = 万能
|
|
20
|
+
const have = new Set(faceCaps.map((c) => String(c).trim().toLowerCase()));
|
|
21
|
+
return needs.every((n) => have.has(n));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 按序挑第一个"有能力且可探活"的候选面;isReachable 异步(探活),返回 {face, skipped}。 */
|
|
25
|
+
export async function pickCapableFace({ candidates, needs, agentsCfg, isReachable }) {
|
|
26
|
+
const skipped = [];
|
|
27
|
+
for (const f of candidates) {
|
|
28
|
+
if (!faceHasCaps(agentsCfg?.[f]?.capabilities, needs)) { skipped.push(f); continue; }
|
|
29
|
+
try {
|
|
30
|
+
if (await isReachable(f)) return { face: f, skipped };
|
|
31
|
+
} catch { /* 探活异常视同不可达 */ }
|
|
32
|
+
skipped.push(f);
|
|
33
|
+
}
|
|
34
|
+
return { face: null, skipped };
|
|
35
|
+
}
|