@culture.dev/agents 0.0.0-stage → 0.15.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/README.md +59 -2
- package/dist/contract-schemas/agent.json +128 -0
- package/dist/contract-schemas/allowlist.json +25 -0
- package/dist/contract-schemas/api.json +501 -0
- package/dist/contract-schemas/capabilities.json +208 -0
- package/dist/contract-schemas/common.json +123 -0
- package/dist/contract-schemas/control-action.json +279 -0
- package/dist/contract-schemas/error.json +269 -0
- package/dist/contract-schemas/event.json +316 -0
- package/dist/contract-schemas/run.json +336 -0
- package/dist/contract-schemas/session.json +77 -0
- package/dist/contract-schemas/version.json +22 -0
- package/dist/src/contract/api.d.ts +41 -0
- package/dist/src/contract/api.js +35 -0
- package/dist/src/contract/api.js.map +1 -0
- package/dist/src/contract/errors.d.ts +21 -0
- package/dist/src/contract/errors.js +25 -0
- package/dist/src/contract/errors.js.map +1 -0
- package/dist/src/contract/generated/agent.d.ts +31 -0
- package/dist/src/contract/generated/agent.js +3 -0
- package/dist/src/contract/generated/agent.js.map +1 -0
- package/dist/src/contract/generated/allowlist.d.ts +10 -0
- package/dist/src/contract/generated/allowlist.js +3 -0
- package/dist/src/contract/generated/allowlist.js.map +1 -0
- package/dist/src/contract/generated/capabilities.d.ts +46 -0
- package/dist/src/contract/generated/capabilities.js +3 -0
- package/dist/src/contract/generated/capabilities.js.map +1 -0
- package/dist/src/contract/generated/common.d.ts +40 -0
- package/dist/src/contract/generated/common.js +3 -0
- package/dist/src/contract/generated/common.js.map +1 -0
- package/dist/src/contract/generated/control-action.d.ts +73 -0
- package/dist/src/contract/generated/control-action.js +3 -0
- package/dist/src/contract/generated/control-action.js.map +1 -0
- package/dist/src/contract/generated/error.d.ts +25 -0
- package/dist/src/contract/generated/error.js +3 -0
- package/dist/src/contract/generated/error.js.map +1 -0
- package/dist/src/contract/generated/event.d.ts +80 -0
- package/dist/src/contract/generated/event.js +3 -0
- package/dist/src/contract/generated/event.js.map +1 -0
- package/dist/src/contract/generated/index.d.ts +81 -0
- package/dist/src/contract/generated/index.js +3 -0
- package/dist/src/contract/generated/index.js.map +1 -0
- package/dist/src/contract/generated/run.d.ts +63 -0
- package/dist/src/contract/generated/run.js +3 -0
- package/dist/src/contract/generated/run.js.map +1 -0
- package/dist/src/contract/generated/session.d.ts +12 -0
- package/dist/src/contract/generated/session.js +3 -0
- package/dist/src/contract/generated/session.js.map +1 -0
- package/dist/src/contract/generated/version.d.ts +9 -0
- package/dist/src/contract/generated/version.js +3 -0
- package/dist/src/contract/generated/version.js.map +1 -0
- package/dist/src/contract/ids.d.ts +36 -0
- package/dist/src/contract/ids.js +85 -0
- package/dist/src/contract/ids.js.map +1 -0
- package/dist/src/contract/index.d.ts +17 -0
- package/dist/src/contract/index.js +13 -0
- package/dist/src/contract/index.js.map +1 -0
- package/dist/src/contract/run-state.d.ts +13 -0
- package/dist/src/contract/run-state.js +24 -0
- package/dist/src/contract/run-state.js.map +1 -0
- package/dist/src/contract/schemas.d.ts +18 -0
- package/dist/src/contract/schemas.js +37 -0
- package/dist/src/contract/schemas.js.map +1 -0
- package/dist/src/contract/validate.d.ts +17 -0
- package/dist/src/contract/validate.js +68 -0
- package/dist/src/contract/validate.js.map +1 -0
- package/dist/src/daemon/allowlist.d.ts +23 -0
- package/dist/src/daemon/allowlist.js +57 -0
- package/dist/src/daemon/allowlist.js.map +1 -0
- package/dist/src/daemon/daemon.d.ts +31 -0
- package/dist/src/daemon/daemon.js +141 -0
- package/dist/src/daemon/daemon.js.map +1 -0
- package/dist/src/daemon/errors.d.ts +14 -0
- package/dist/src/daemon/errors.js +26 -0
- package/dist/src/daemon/errors.js.map +1 -0
- package/dist/src/daemon/harness-catalog.d.ts +11 -0
- package/dist/src/daemon/harness-catalog.js +21 -0
- package/dist/src/daemon/harness-catalog.js.map +1 -0
- package/dist/src/daemon/http.d.ts +15 -0
- package/dist/src/daemon/http.js +76 -0
- package/dist/src/daemon/http.js.map +1 -0
- package/dist/src/daemon/lock.d.ts +47 -0
- package/dist/src/daemon/lock.js +167 -0
- package/dist/src/daemon/lock.js.map +1 -0
- package/dist/src/daemon/main.d.ts +32 -0
- package/dist/src/daemon/main.js +204 -0
- package/dist/src/daemon/main.js.map +1 -0
- package/dist/src/daemon/paths.d.ts +29 -0
- package/dist/src/daemon/paths.js +26 -0
- package/dist/src/daemon/paths.js.map +1 -0
- package/dist/src/daemon/ports.d.ts +58 -0
- package/dist/src/daemon/ports.js +2 -0
- package/dist/src/daemon/ports.js.map +1 -0
- package/dist/src/daemon/routes.d.ts +15 -0
- package/dist/src/daemon/routes.js +259 -0
- package/dist/src/daemon/routes.js.map +1 -0
- package/dist/src/daemon/sse.d.ts +8 -0
- package/dist/src/daemon/sse.js +56 -0
- package/dist/src/daemon/sse.js.map +1 -0
- package/dist/src/harness/availability.d.ts +9 -0
- package/dist/src/harness/availability.js +52 -0
- package/dist/src/harness/availability.js.map +1 -0
- package/dist/src/harness/claude-code/agent.d.ts +4 -0
- package/dist/src/harness/claude-code/agent.js +33 -0
- package/dist/src/harness/claude-code/agent.js.map +1 -0
- package/dist/src/harness/claude-code/backend.d.ts +48 -0
- package/dist/src/harness/claude-code/backend.js +83 -0
- package/dist/src/harness/claude-code/backend.js.map +1 -0
- package/dist/src/harness/claude-code/capabilities.d.ts +7 -0
- package/dist/src/harness/claude-code/capabilities.js +11 -0
- package/dist/src/harness/claude-code/capabilities.js.map +1 -0
- package/dist/src/harness/claude-code/index.d.ts +15 -0
- package/dist/src/harness/claude-code/index.js +20 -0
- package/dist/src/harness/claude-code/index.js.map +1 -0
- package/dist/src/harness/claude-code/map.d.ts +30 -0
- package/dist/src/harness/claude-code/map.js +108 -0
- package/dist/src/harness/claude-code/map.js.map +1 -0
- package/dist/src/harness/common/capabilities.d.ts +34 -0
- package/dist/src/harness/common/capabilities.js +60 -0
- package/dist/src/harness/common/capabilities.js.map +1 -0
- package/dist/src/harness/common/guard.d.ts +18 -0
- package/dist/src/harness/common/guard.js +31 -0
- package/dist/src/harness/common/guard.js.map +1 -0
- package/dist/src/harness/common/processes.d.ts +21 -0
- package/dist/src/harness/common/processes.js +46 -0
- package/dist/src/harness/common/processes.js.map +1 -0
- package/dist/src/harness/common/queue.d.ts +20 -0
- package/dist/src/harness/common/queue.js +76 -0
- package/dist/src/harness/common/queue.js.map +1 -0
- package/dist/src/harness/common/run-driver.d.ts +88 -0
- package/dist/src/harness/common/run-driver.js +317 -0
- package/dist/src/harness/common/run-driver.js.map +1 -0
- package/dist/src/harness/common/sandbox-workspace.d.ts +72 -0
- package/dist/src/harness/common/sandbox-workspace.js +155 -0
- package/dist/src/harness/common/sandbox-workspace.js.map +1 -0
- package/dist/src/harness/common/text.d.ts +9 -0
- package/dist/src/harness/common/text.js +49 -0
- package/dist/src/harness/common/text.js.map +1 -0
- package/dist/src/harness/common/types.d.ts +111 -0
- package/dist/src/harness/common/types.js +2 -0
- package/dist/src/harness/common/types.js.map +1 -0
- package/dist/src/harness/config.d.ts +43 -0
- package/dist/src/harness/config.js +200 -0
- package/dist/src/harness/config.js.map +1 -0
- package/dist/src/harness/index.d.ts +21 -0
- package/dist/src/harness/index.js +89 -0
- package/dist/src/harness/index.js.map +1 -0
- package/dist/src/harness/opencode/backend.d.ts +37 -0
- package/dist/src/harness/opencode/backend.js +114 -0
- package/dist/src/harness/opencode/backend.js.map +1 -0
- package/dist/src/harness/opencode/capabilities.d.ts +8 -0
- package/dist/src/harness/opencode/capabilities.js +11 -0
- package/dist/src/harness/opencode/capabilities.js.map +1 -0
- package/dist/src/harness/opencode/client.d.ts +70 -0
- package/dist/src/harness/opencode/client.js +189 -0
- package/dist/src/harness/opencode/client.js.map +1 -0
- package/dist/src/harness/opencode/index.d.ts +13 -0
- package/dist/src/harness/opencode/index.js +19 -0
- package/dist/src/harness/opencode/index.js.map +1 -0
- package/dist/src/harness/opencode/lines.d.ts +14 -0
- package/dist/src/harness/opencode/lines.js +99 -0
- package/dist/src/harness/opencode/lines.js.map +1 -0
- package/dist/src/harness/opencode/map.d.ts +13 -0
- package/dist/src/harness/opencode/map.js +84 -0
- package/dist/src/harness/opencode/map.js.map +1 -0
- package/dist/src/harness/opencode/turn.d.ts +23 -0
- package/dist/src/harness/opencode/turn.js +143 -0
- package/dist/src/harness/opencode/turn.js.map +1 -0
- package/dist/src/harness/reclaim.d.ts +13 -0
- package/dist/src/harness/reclaim.js +18 -0
- package/dist/src/harness/reclaim.js.map +1 -0
- package/dist/src/harness/stub/backend.d.ts +11 -0
- package/dist/src/harness/stub/backend.js +125 -0
- package/dist/src/harness/stub/backend.js.map +1 -0
- package/dist/src/harness/stub/index.d.ts +18 -0
- package/dist/src/harness/stub/index.js +21 -0
- package/dist/src/harness/stub/index.js.map +1 -0
- package/dist/src/harness/stub/workspace.d.ts +29 -0
- package/dist/src/harness/stub/workspace.js +92 -0
- package/dist/src/harness/stub/workspace.js.map +1 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +3 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/runs/agents.d.ts +10 -0
- package/dist/src/runs/agents.js +49 -0
- package/dist/src/runs/agents.js.map +1 -0
- package/dist/src/runs/control.d.ts +31 -0
- package/dist/src/runs/control.js +105 -0
- package/dist/src/runs/control.js.map +1 -0
- package/dist/src/runs/index.d.ts +8 -0
- package/dist/src/runs/index.js +7 -0
- package/dist/src/runs/index.js.map +1 -0
- package/dist/src/runs/ports.d.ts +31 -0
- package/dist/src/runs/ports.js +5 -0
- package/dist/src/runs/ports.js.map +1 -0
- package/dist/src/runs/scan.d.ts +38 -0
- package/dist/src/runs/scan.js +149 -0
- package/dist/src/runs/scan.js.map +1 -0
- package/dist/src/runs/service.d.ts +70 -0
- package/dist/src/runs/service.js +239 -0
- package/dist/src/runs/service.js.map +1 -0
- package/dist/src/sandbox/harness-session.d.ts +11 -0
- package/dist/src/sandbox/harness-session.js +170 -0
- package/dist/src/sandbox/harness-session.js.map +1 -0
- package/dist/src/sandbox/host-command.d.ts +19 -0
- package/dist/src/sandbox/host-command.js +41 -0
- package/dist/src/sandbox/host-command.js.map +1 -0
- package/dist/src/sandbox/index.d.ts +11 -0
- package/dist/src/sandbox/index.js +15 -0
- package/dist/src/sandbox/index.js.map +1 -0
- package/dist/src/sandbox/naming.d.ts +49 -0
- package/dist/src/sandbox/naming.js +106 -0
- package/dist/src/sandbox/naming.js.map +1 -0
- package/dist/src/sandbox/openshell-client.d.ts +81 -0
- package/dist/src/sandbox/openshell-client.js +49 -0
- package/dist/src/sandbox/openshell-client.js.map +1 -0
- package/dist/src/sandbox/policy.d.ts +26 -0
- package/dist/src/sandbox/policy.js +100 -0
- package/dist/src/sandbox/policy.js.map +1 -0
- package/dist/src/sandbox/run-sandbox.d.ts +38 -0
- package/dist/src/sandbox/run-sandbox.js +247 -0
- package/dist/src/sandbox/run-sandbox.js.map +1 -0
- package/dist/src/sandbox/run-sandboxes.d.ts +18 -0
- package/dist/src/sandbox/run-sandboxes.js +225 -0
- package/dist/src/sandbox/run-sandboxes.js.map +1 -0
- package/dist/src/sandbox/timeout.d.ts +12 -0
- package/dist/src/sandbox/timeout.js +39 -0
- package/dist/src/sandbox/timeout.js.map +1 -0
- package/dist/src/sandbox/types.d.ts +125 -0
- package/dist/src/sandbox/types.js +15 -0
- package/dist/src/sandbox/types.js.map +1 -0
- package/dist/src/sandbox/worktree.d.ts +72 -0
- package/dist/src/sandbox/worktree.js +157 -0
- package/dist/src/sandbox/worktree.js.map +1 -0
- package/dist/src/store/derive.d.ts +39 -0
- package/dist/src/store/derive.js +68 -0
- package/dist/src/store/derive.js.map +1 -0
- package/dist/src/store/event-log.d.ts +79 -0
- package/dist/src/store/event-log.js +202 -0
- package/dist/src/store/event-log.js.map +1 -0
- package/dist/src/store/files.d.ts +51 -0
- package/dist/src/store/files.js +103 -0
- package/dist/src/store/files.js.map +1 -0
- package/dist/src/store/index.d.ts +15 -0
- package/dist/src/store/index.js +11 -0
- package/dist/src/store/index.js.map +1 -0
- package/dist/src/store/liveness.d.ts +61 -0
- package/dist/src/store/liveness.js +150 -0
- package/dist/src/store/liveness.js.map +1 -0
- package/dist/src/store/run-store.d.ts +67 -0
- package/dist/src/store/run-store.js +211 -0
- package/dist/src/store/run-store.js.map +1 -0
- package/dist/src/util/sequence.d.ts +58 -0
- package/dist/src/util/sequence.js +119 -0
- package/dist/src/util/sequence.js.map +1 -0
- package/dist/src/worker/control.d.ts +60 -0
- package/dist/src/worker/control.js +205 -0
- package/dist/src/worker/control.js.map +1 -0
- package/dist/src/worker/delivery.d.ts +17 -0
- package/dist/src/worker/delivery.js +43 -0
- package/dist/src/worker/delivery.js.map +1 -0
- package/dist/src/worker/driver.d.ts +88 -0
- package/dist/src/worker/driver.js +6 -0
- package/dist/src/worker/driver.js.map +1 -0
- package/dist/src/worker/fake-driver.d.ts +65 -0
- package/dist/src/worker/fake-driver.js +123 -0
- package/dist/src/worker/fake-driver.js.map +1 -0
- package/dist/src/worker/index.d.ts +15 -0
- package/dist/src/worker/index.js +11 -0
- package/dist/src/worker/index.js.map +1 -0
- package/dist/src/worker/main.d.ts +1 -0
- package/dist/src/worker/main.js +57 -0
- package/dist/src/worker/main.js.map +1 -0
- package/dist/src/worker/retained.d.ts +13 -0
- package/dist/src/worker/retained.js +40 -0
- package/dist/src/worker/retained.js.map +1 -0
- package/dist/src/worker/run-loop.d.ts +63 -0
- package/dist/src/worker/run-loop.js +325 -0
- package/dist/src/worker/run-loop.js.map +1 -0
- package/dist/src/worker/spawn.d.ts +68 -0
- package/dist/src/worker/spawn.js +201 -0
- package/dist/src/worker/spawn.js.map +1 -0
- package/image/Dockerfile +81 -0
- package/image/build.sh +62 -0
- package/image/pnpm-shim.sh +25 -0
- package/package.json +54 -4
- package/policy/profiles/culture-agents-claude-subscription.yaml +59 -0
- package/policy/profiles/culture-agents-local-gateway.yaml +49 -0
- package/policy/run-sandbox.policy.json +10 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The append-only event log of one run (`events.jsonl`) and its cursor file.
|
|
3
|
+
*
|
|
4
|
+
* - Only newline-terminated lines count. A final segment without a newline is a torn append
|
|
5
|
+
* (a crash mid-write): readers ignore it and the next writer truncates it before appending,
|
|
6
|
+
* so earlier events are kept and no state is invented.
|
|
7
|
+
* - Every complete line must validate against `event.json`, carry the run's id, continue the
|
|
8
|
+
* cursor (1, 2, 3, ...) and, for `run.state`, make a legal transition from the previous
|
|
9
|
+
* state. A broken line before the end is corruption and is reported, never skipped.
|
|
10
|
+
* - There is exactly one writer at a time: the worker while it lives, the core afterwards.
|
|
11
|
+
*/
|
|
12
|
+
import { closeSync, fstatSync, fsyncSync, ftruncateSync, openSync, readFileSync, readSync, writeSync } from "node:fs";
|
|
13
|
+
import { assertValid, canTransition, isTerminal, validate, } from "../contract/index.js";
|
|
14
|
+
import { FILE_MODE, atomicWrite, runFile } from "./files.js";
|
|
15
|
+
/** The event log breaks a contract rule somewhere other than a torn final line. */
|
|
16
|
+
export class EventLogCorruptError extends Error {
|
|
17
|
+
line;
|
|
18
|
+
constructor(line, detail) {
|
|
19
|
+
super(`event log line ${line}: ${detail}`);
|
|
20
|
+
this.line = line;
|
|
21
|
+
this.name = "EventLogCorruptError";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Check one parsed event against the previous tail; returns the new tail. */
|
|
25
|
+
export function checkNext(runId, tail, value, line) {
|
|
26
|
+
const result = validate("event", value);
|
|
27
|
+
if (!result.ok)
|
|
28
|
+
throw new EventLogCorruptError(line, `does not validate: ${result.issues[0]?.path} ${result.issues[0]?.message}`);
|
|
29
|
+
const event = result.value;
|
|
30
|
+
if (event.run_id !== runId)
|
|
31
|
+
throw new EventLogCorruptError(line, `run_id ${event.run_id} is not ${runId}`);
|
|
32
|
+
if (event.cursor !== tail.cursor + 1)
|
|
33
|
+
throw new EventLogCorruptError(line, `cursor ${event.cursor} after ${tail.cursor}`);
|
|
34
|
+
if (tail.state !== null && isTerminal(tail.state))
|
|
35
|
+
throw new EventLogCorruptError(line, "event after the terminal state");
|
|
36
|
+
let state = tail.state;
|
|
37
|
+
if (event.kind === "run.state") {
|
|
38
|
+
const data = event.data;
|
|
39
|
+
if (data.from !== tail.state || !canTransition(data.from, data.to)) {
|
|
40
|
+
throw new EventLogCorruptError(line, `illegal transition ${String(data.from)} -> ${data.to} after ${String(tail.state)}`);
|
|
41
|
+
}
|
|
42
|
+
state = data.to;
|
|
43
|
+
}
|
|
44
|
+
else if (tail.cursor === 0) {
|
|
45
|
+
throw new EventLogCorruptError(line, "the first event must be run.state null -> queued");
|
|
46
|
+
}
|
|
47
|
+
return { event, tail: { cursor: event.cursor, state } };
|
|
48
|
+
}
|
|
49
|
+
/** Parse log content. Only newline-terminated lines count; a trailing partial line is reported as torn. */
|
|
50
|
+
export function parseLog(runId, content) {
|
|
51
|
+
const buf = typeof content === "string" ? Buffer.from(content, "utf8") : content;
|
|
52
|
+
const end = buf.lastIndexOf(0x0a) + 1;
|
|
53
|
+
const events = [];
|
|
54
|
+
let tail = { cursor: 0, state: null };
|
|
55
|
+
const text = buf.subarray(0, end).toString("utf8");
|
|
56
|
+
const lines = text === "" ? [] : text.slice(0, -1).split("\n");
|
|
57
|
+
lines.forEach((raw, i) => {
|
|
58
|
+
let value;
|
|
59
|
+
try {
|
|
60
|
+
value = JSON.parse(raw);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw new EventLogCorruptError(i + 1, "is not JSON");
|
|
64
|
+
}
|
|
65
|
+
const next = checkNext(runId, tail, value, i + 1);
|
|
66
|
+
events.push(next.event);
|
|
67
|
+
tail = next.tail;
|
|
68
|
+
});
|
|
69
|
+
return { events, tail, completeBytes: end, torn: end < buf.length };
|
|
70
|
+
}
|
|
71
|
+
/** Read and parse a run's whole log (missing file = empty log). */
|
|
72
|
+
export function readLog(dir, runId) {
|
|
73
|
+
let content;
|
|
74
|
+
try {
|
|
75
|
+
content = readFileSync(runFile(dir, "events"));
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
if (err.code === "ENOENT")
|
|
79
|
+
return parseLog(runId, "");
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
82
|
+
return parseLog(runId, content);
|
|
83
|
+
}
|
|
84
|
+
/** Read the cursor file; null when absent or unreadable. */
|
|
85
|
+
export function readCursorFile(dir) {
|
|
86
|
+
try {
|
|
87
|
+
const n = Number(readFileSync(runFile(dir, "cursor"), "utf8").trim());
|
|
88
|
+
return Number.isInteger(n) && n >= 0 ? n : null;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The single writer of a run's log. Opening it validates the existing log and drops a torn
|
|
96
|
+
* final line. Appends are synchronous, so a crash leaves at most one torn line. `durable` appends
|
|
97
|
+
* are fsynced together with the cursor file.
|
|
98
|
+
*
|
|
99
|
+
* A line counts only once every byte of it, newline included, is in the file. An append that fails
|
|
100
|
+
* before that (a short write followed by ENOSPC, for example) leaves at most a partial line with
|
|
101
|
+
* no newline, which readers already ignore as a torn tail; the writer truncates it, at once when
|
|
102
|
+
* it can and otherwise before its next append, so a later line never joins onto it.
|
|
103
|
+
*/
|
|
104
|
+
export class EventLogWriter {
|
|
105
|
+
dir;
|
|
106
|
+
runId;
|
|
107
|
+
clock;
|
|
108
|
+
fd;
|
|
109
|
+
tail;
|
|
110
|
+
/** Bytes of complete lines: where the next line starts. */
|
|
111
|
+
bytes;
|
|
112
|
+
/** True when a failed append may have left bytes past `bytes`. */
|
|
113
|
+
torn = false;
|
|
114
|
+
constructor(dir, runId, clock) {
|
|
115
|
+
this.dir = dir;
|
|
116
|
+
this.runId = runId;
|
|
117
|
+
this.clock = clock;
|
|
118
|
+
this.fd = openSync(runFile(dir, "events"), "a+", FILE_MODE);
|
|
119
|
+
const size = fstatSync(this.fd).size;
|
|
120
|
+
const buf = Buffer.alloc(size);
|
|
121
|
+
if (size > 0)
|
|
122
|
+
readSync(this.fd, buf, 0, size, 0);
|
|
123
|
+
const parsed = parseLog(runId, buf);
|
|
124
|
+
if (parsed.torn) {
|
|
125
|
+
ftruncateSync(this.fd, parsed.completeBytes);
|
|
126
|
+
fsyncSync(this.fd);
|
|
127
|
+
}
|
|
128
|
+
this.tail = parsed.tail;
|
|
129
|
+
this.bytes = parsed.completeBytes;
|
|
130
|
+
}
|
|
131
|
+
static open(dir, runId, clock = Date.now) {
|
|
132
|
+
return new EventLogWriter(dir, runId, clock);
|
|
133
|
+
}
|
|
134
|
+
get cursor() {
|
|
135
|
+
return this.tail.cursor;
|
|
136
|
+
}
|
|
137
|
+
get state() {
|
|
138
|
+
return this.tail.state;
|
|
139
|
+
}
|
|
140
|
+
/** Drop what a failed append left after the last complete line. Throws when it cannot. */
|
|
141
|
+
repair() {
|
|
142
|
+
if (!this.torn)
|
|
143
|
+
return;
|
|
144
|
+
ftruncateSync(this.fd, this.bytes);
|
|
145
|
+
this.torn = false;
|
|
146
|
+
}
|
|
147
|
+
/** Write every byte of `line` (a short write is continued); on failure the partial line is dropped. */
|
|
148
|
+
writeLine(line) {
|
|
149
|
+
let written = 0;
|
|
150
|
+
try {
|
|
151
|
+
while (written < line.length) {
|
|
152
|
+
const n = writeSync(this.fd, line, written, line.length - written);
|
|
153
|
+
if (n <= 0)
|
|
154
|
+
throw new Error("the event log accepted no bytes");
|
|
155
|
+
written += n;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
this.torn = true; // assume bytes landed even when the failing call reported none
|
|
160
|
+
try {
|
|
161
|
+
this.repair();
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// Still torn: readers ignore the partial line, and the next append repairs before it writes.
|
|
165
|
+
}
|
|
166
|
+
throw err;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Append one event at the next cursor; throws (and writes nothing) if it breaks the contract.
|
|
171
|
+
* When the write itself fails, nothing is appended and the cursor does not advance. Once the
|
|
172
|
+
* whole line is in the file the cursor advances, before the fsync: if the fsync or the cursor
|
|
173
|
+
* file then fails, this throws but the event stays in the log and its cursor is never reused.
|
|
174
|
+
*/
|
|
175
|
+
append(input, durable = false) {
|
|
176
|
+
const candidate = {
|
|
177
|
+
run_id: this.runId,
|
|
178
|
+
cursor: this.tail.cursor + 1,
|
|
179
|
+
time: new Date(this.clock()).toISOString(),
|
|
180
|
+
kind: input.kind,
|
|
181
|
+
data: input.data,
|
|
182
|
+
};
|
|
183
|
+
const checked = checkNext(this.runId, this.tail, assertValid("event", candidate), candidate.cursor);
|
|
184
|
+
const line = Buffer.from(`${JSON.stringify(checked.event)}\n`, "utf8");
|
|
185
|
+
this.repair();
|
|
186
|
+
this.writeLine(line);
|
|
187
|
+
this.bytes += line.length;
|
|
188
|
+
this.tail = checked.tail;
|
|
189
|
+
if (durable)
|
|
190
|
+
fsyncSync(this.fd);
|
|
191
|
+
atomicWrite(runFile(this.dir, "cursor"), `${checked.tail.cursor}\n`, durable);
|
|
192
|
+
return checked.event;
|
|
193
|
+
}
|
|
194
|
+
/** Append a `run.state` transition from the current state. */
|
|
195
|
+
transition(to, reason, durable = false) {
|
|
196
|
+
return this.append({ kind: "run.state", data: { from: this.tail.state, to, reason } }, durable || isTerminal(to));
|
|
197
|
+
}
|
|
198
|
+
close() {
|
|
199
|
+
closeSync(this.fd);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
//# sourceMappingURL=event-log.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-log.js","sourceRoot":"","sources":["../../../src/store/event-log.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEtH,OAAO,EACL,WAAW,EACX,aAAa,EACb,U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E,QAAQ,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9E,OAAO,OAAO,CAAC,KAAK,CAAC;IACvB,CAAC;IAED,8DAA8D;IAC9D,UAAU,CAAC,EAAY,EAAE,MAAqB,EAAE,OAAO,GAAG,KAAK;QAC7D,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACpH,CAAC;IAED,KAAK;QACH,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACrB,CAAC;CACF"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export declare const FILE_MODE = 384;
|
|
2
|
+
export declare const DIR_MODE = 448;
|
|
3
|
+
/** File names inside `<stateDir>/runs/<run-id>/`. */
|
|
4
|
+
export declare const RUN_FILES: {
|
|
5
|
+
/** The run record (contract `run.json` shape), a cache; state is derived from the event log. */
|
|
6
|
+
readonly record: "run.json";
|
|
7
|
+
/** Append-only event log: one contract event per line, cursor 1, 2, 3, ... */
|
|
8
|
+
readonly events: "events.jsonl";
|
|
9
|
+
/** The newest cursor in the event log, as a decimal integer. */
|
|
10
|
+
readonly cursor: "cursor";
|
|
11
|
+
/** Worker identity: pid, process start time and boot id (liveness evidence). */
|
|
12
|
+
readonly worker: "worker.json";
|
|
13
|
+
/** Worker heartbeat: the last time the worker proved it was alive (ISO timestamp). */
|
|
14
|
+
readonly heartbeat: "heartbeat";
|
|
15
|
+
/** The worker's control socket (newline-delimited JSON). */
|
|
16
|
+
readonly socket: "control.sock";
|
|
17
|
+
/** The driver selection the worker loads (module specifier and options). */
|
|
18
|
+
readonly driver: "driver.json";
|
|
19
|
+
/** Where a completed run's commits landed: `{ branch, commits }` with full SHAs, oldest first. */
|
|
20
|
+
readonly collected: "collected.json";
|
|
21
|
+
/** A sandbox kept after a completed turn's work could not be brought to the host: `{ sandbox, until }`. */
|
|
22
|
+
readonly retained: "retained.json";
|
|
23
|
+
/** The worker's own stdout/stderr (diagnostics only, never parsed). */
|
|
24
|
+
readonly log: "worker.log";
|
|
25
|
+
};
|
|
26
|
+
export type RunFile = keyof typeof RUN_FILES;
|
|
27
|
+
/**
|
|
28
|
+
* The state directory: `$CULTURE_AGENTS_STATE_DIR`, else `$XDG_STATE_HOME/culture-agents`,
|
|
29
|
+
* else `~/.local/state/culture-agents`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function defaultStateDir(env?: NodeJS.ProcessEnv): string;
|
|
32
|
+
/** `<stateDir>/runs`. */
|
|
33
|
+
export declare function runsDir(stateDir: string): string;
|
|
34
|
+
/** `<stateDir>/runs/<run-id>`; the id is checked so it can never escape the runs directory. */
|
|
35
|
+
export declare function runDir(stateDir: string, runId: string): string;
|
|
36
|
+
/** Path of one run file. */
|
|
37
|
+
export declare function runFile(dir: string, file: RunFile): string;
|
|
38
|
+
/** mkdir -p with owner-only directories. */
|
|
39
|
+
export declare function ensureDir(path: string): void;
|
|
40
|
+
/** fsync a directory so a rename or create inside it is durable. */
|
|
41
|
+
export declare function fsyncDir(path: string): void;
|
|
42
|
+
/**
|
|
43
|
+
* Replace `path` atomically: write a 0600 temp file next to it, optionally fsync it, rename it
|
|
44
|
+
* over the target, and (when `durable`) fsync the directory. A reader sees the old or the new
|
|
45
|
+
* content, never a partial file.
|
|
46
|
+
*/
|
|
47
|
+
export declare function atomicWrite(path: string, content: string, durable?: boolean): void;
|
|
48
|
+
/** Like `atomicWrite` for a JSON value (one line, trailing newline). */
|
|
49
|
+
export declare function atomicWriteJson(path: string, value: unknown, durable?: boolean): void;
|
|
50
|
+
/** The current time as a contract timestamp (UTC, `Z`). */
|
|
51
|
+
export declare function nowIso(clock?: () => number): string;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run-store layout and low-level file helpers. Every run file is owner-only (0600) and every
|
|
3
|
+
* run directory 0700, because harness output may contain secrets (spec: D1 stores them
|
|
4
|
+
* without redaction). Records are replaced atomically (temp file + rename).
|
|
5
|
+
*/
|
|
6
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, writeSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { isRunId } from "../contract/index.js";
|
|
10
|
+
export const FILE_MODE = 0o600;
|
|
11
|
+
export const DIR_MODE = 0o700;
|
|
12
|
+
/** File names inside `<stateDir>/runs/<run-id>/`. */
|
|
13
|
+
export const RUN_FILES = {
|
|
14
|
+
/** The run record (contract `run.json` shape), a cache; state is derived from the event log. */
|
|
15
|
+
record: "run.json",
|
|
16
|
+
/** Append-only event log: one contract event per line, cursor 1, 2, 3, ... */
|
|
17
|
+
events: "events.jsonl",
|
|
18
|
+
/** The newest cursor in the event log, as a decimal integer. */
|
|
19
|
+
cursor: "cursor",
|
|
20
|
+
/** Worker identity: pid, process start time and boot id (liveness evidence). */
|
|
21
|
+
worker: "worker.json",
|
|
22
|
+
/** Worker heartbeat: the last time the worker proved it was alive (ISO timestamp). */
|
|
23
|
+
heartbeat: "heartbeat",
|
|
24
|
+
/** The worker's control socket (newline-delimited JSON). */
|
|
25
|
+
socket: "control.sock",
|
|
26
|
+
/** The driver selection the worker loads (module specifier and options). */
|
|
27
|
+
driver: "driver.json",
|
|
28
|
+
/** Where a completed run's commits landed: `{ branch, commits }` with full SHAs, oldest first. */
|
|
29
|
+
collected: "collected.json",
|
|
30
|
+
/** A sandbox kept after a completed turn's work could not be brought to the host: `{ sandbox, until }`. */
|
|
31
|
+
retained: "retained.json",
|
|
32
|
+
/** The worker's own stdout/stderr (diagnostics only, never parsed). */
|
|
33
|
+
log: "worker.log",
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The state directory: `$CULTURE_AGENTS_STATE_DIR`, else `$XDG_STATE_HOME/culture-agents`,
|
|
37
|
+
* else `~/.local/state/culture-agents`.
|
|
38
|
+
*/
|
|
39
|
+
export function defaultStateDir(env = process.env) {
|
|
40
|
+
const override = env["CULTURE_AGENTS_STATE_DIR"];
|
|
41
|
+
if (override)
|
|
42
|
+
return override;
|
|
43
|
+
const xdg = env["XDG_STATE_HOME"];
|
|
44
|
+
return join(xdg?.startsWith("/") ? xdg : join(homedir(), ".local", "state"), "culture-agents");
|
|
45
|
+
}
|
|
46
|
+
/** `<stateDir>/runs`. */
|
|
47
|
+
export function runsDir(stateDir) {
|
|
48
|
+
return join(stateDir, "runs");
|
|
49
|
+
}
|
|
50
|
+
/** `<stateDir>/runs/<run-id>`; the id is checked so it can never escape the runs directory. */
|
|
51
|
+
export function runDir(stateDir, runId) {
|
|
52
|
+
if (!isRunId(runId))
|
|
53
|
+
throw new RangeError(`invalid run id: ${JSON.stringify(runId)}`);
|
|
54
|
+
return join(runsDir(stateDir), runId);
|
|
55
|
+
}
|
|
56
|
+
/** Path of one run file. */
|
|
57
|
+
export function runFile(dir, file) {
|
|
58
|
+
return join(dir, RUN_FILES[file]);
|
|
59
|
+
}
|
|
60
|
+
/** mkdir -p with owner-only directories. */
|
|
61
|
+
export function ensureDir(path) {
|
|
62
|
+
mkdirSync(path, { recursive: true, mode: DIR_MODE });
|
|
63
|
+
}
|
|
64
|
+
/** fsync a directory so a rename or create inside it is durable. */
|
|
65
|
+
export function fsyncDir(path) {
|
|
66
|
+
const fd = openSync(path, "r");
|
|
67
|
+
try {
|
|
68
|
+
fsyncSync(fd);
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
closeSync(fd);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
let tmpSeq = 0;
|
|
75
|
+
/**
|
|
76
|
+
* Replace `path` atomically: write a 0600 temp file next to it, optionally fsync it, rename it
|
|
77
|
+
* over the target, and (when `durable`) fsync the directory. A reader sees the old or the new
|
|
78
|
+
* content, never a partial file.
|
|
79
|
+
*/
|
|
80
|
+
export function atomicWrite(path, content, durable = false) {
|
|
81
|
+
const tmp = `${path}.tmp-${process.pid}-${++tmpSeq}`;
|
|
82
|
+
const fd = openSync(tmp, "wx", FILE_MODE);
|
|
83
|
+
try {
|
|
84
|
+
writeSync(fd, content);
|
|
85
|
+
if (durable)
|
|
86
|
+
fsyncSync(fd);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
closeSync(fd);
|
|
90
|
+
}
|
|
91
|
+
renameSync(tmp, path);
|
|
92
|
+
if (durable)
|
|
93
|
+
fsyncDir(dirname(path));
|
|
94
|
+
}
|
|
95
|
+
/** Like `atomicWrite` for a JSON value (one line, trailing newline). */
|
|
96
|
+
export function atomicWriteJson(path, value, durable = false) {
|
|
97
|
+
atomicWrite(path, `${JSON.stringify(value)}\n`, durable);
|
|
98
|
+
}
|
|
99
|
+
/** The current time as a contract timestamp (UTC, `Z`). */
|
|
100
|
+
export function nowIso(clock = Date.now) {
|
|
101
|
+
return new Date(clock()).toISOString();
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=files.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"files.js","sourceRoot":"","sources":["../../../src/store/files.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAC3F,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAE/C,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,CAAC;AAC/B,MAAM,CAAC,MAAM,QAAQ,GAAG,KAAK,CAAC;AAE9B,qDAAqD;AACrD,MAAM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AU,eAAe,CAAC,IAAY,EAAE,KAAc,EAAE,OAAO,GAAG,KAAK;IAC3E,WAAW,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC3D,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,MAAM,CAAC,QAAsB,IAAI,CAAC,GAAG;IACnD,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;AACzC,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The run store: on-disk run directories, the append-only event log, worker liveness evidence,
|
|
3
|
+
* and the derivation of every reported state from those files (contract/README.md: run state
|
|
4
|
+
* machine, `unknown`, after a core restart).
|
|
5
|
+
*/
|
|
6
|
+
export { deriveRun, ORPHANED_REASON } from "./derive.js";
|
|
7
|
+
export type { DeriveInput, DerivedRun } from "./derive.js";
|
|
8
|
+
export { EventLogCorruptError, EventLogWriter, checkNext, parseLog, readCursorFile, readLog } from "./event-log.js";
|
|
9
|
+
export type { EventInput, LogTail, ParsedLog } from "./event-log.js";
|
|
10
|
+
export { DIR_MODE, FILE_MODE, RUN_FILES, atomicWrite, atomicWriteJson, defaultStateDir, ensureDir, nowIso, runDir, runFile, runsDir, } from "./files.js";
|
|
11
|
+
export type { RunFile } from "./files.js";
|
|
12
|
+
export { checkLiveness, identityOf, readHeartbeat, readProcStat, readWorkerIdentity, writeHeartbeat, writeWorkerIdentity, LivenessUnknownError, } from "./liveness.js";
|
|
13
|
+
export type { Liveness, LivenessOptions, WorkerIdentity } from "./liveness.js";
|
|
14
|
+
export { createRun, followEvents, listRunIds, listRuns, readEvents, readRecord, settleOrphan, showRun, showRunAt, writeRecord, } from "./run-store.js";
|
|
15
|
+
export type { EventsPage, FollowOptions, ListOptions, ShowOptions, ShownRun } from "./run-store.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The run store: on-disk run directories, the append-only event log, worker liveness evidence,
|
|
3
|
+
* and the derivation of every reported state from those files (contract/README.md: run state
|
|
4
|
+
* machine, `unknown`, after a core restart).
|
|
5
|
+
*/
|
|
6
|
+
export { deriveRun, ORPHANED_REASON } from "./derive.js";
|
|
7
|
+
export { EventLogCorruptError, EventLogWriter, checkNext, parseLog, readCursorFile, readLog } from "./event-log.js";
|
|
8
|
+
export { DIR_MODE, FILE_MODE, RUN_FILES, atomicWrite, atomicWriteJson, defaultStateDir, ensureDir, nowIso, runDir, runFile, runsDir, } from "./files.js";
|
|
9
|
+
export { checkLiveness, identityOf, readHeartbeat, readProcStat, readWorkerIdentity, writeHeartbeat, writeWorkerIdentity, LivenessUnknownError, } from "./liveness.js";
|
|
10
|
+
export { createRun, followEvents, listRunIds, listRuns, readEvents, readRecord, settleOrphan, showRun, showRunAt, writeRecord, } from "./run-store.js";
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/store/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAEpH,OAAO,EACL,QAAQ,EACR,SAAS,EACT,SAAS,EACT,WAAW,EACX,eAAe,EACf,eAAe,EACf,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,OAAO,GACR,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,aAAa,EACb,UAAU,EACV,aAAa,EACb,YAAY,EACZ,kBAAkB,EAClB,cAAc,EACd,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,UAAU,EACV,YAAY,EACZ,OAAO,EACP,SAAS,EACT,WAAW,GACZ,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Contents of `worker.json`. */
|
|
2
|
+
export interface WorkerIdentity {
|
|
3
|
+
pid: number;
|
|
4
|
+
/** `/proc/<pid>/stat` start time (clock ticks after boot), or null without `/proc`. */
|
|
5
|
+
start_time: string | null;
|
|
6
|
+
/** `/proc/sys/kernel/random/boot_id`, or null without `/proc`. */
|
|
7
|
+
boot_id: string | null;
|
|
8
|
+
started_at: string;
|
|
9
|
+
}
|
|
10
|
+
export interface Liveness {
|
|
11
|
+
alive: boolean;
|
|
12
|
+
/** The recorded worker pid, or null when no worker was ever recorded. */
|
|
13
|
+
pid: number | null;
|
|
14
|
+
/** How the verdict was reached, for diagnostics. */
|
|
15
|
+
reason: string;
|
|
16
|
+
/** The worker's last heartbeat, if any. */
|
|
17
|
+
heartbeat_at: string | null;
|
|
18
|
+
}
|
|
19
|
+
interface ProcStat {
|
|
20
|
+
state: string;
|
|
21
|
+
startTime: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The liveness evidence could not be read (for example EMFILE, ENFILE, ENOMEM, EIO, EACCES), so the
|
|
25
|
+
* worker is neither known alive nor known dead. Callers must not settle the run on this read: a
|
|
26
|
+
* request fails, and a follower checks again on its next tick.
|
|
27
|
+
*/
|
|
28
|
+
export declare class LivenessUnknownError extends Error {
|
|
29
|
+
readonly name = "LivenessUnknownError";
|
|
30
|
+
constructor(what: string, cause: unknown);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Parse `/proc/<pid>/stat`; null when the process does not exist or `/proc` is unavailable. A read
|
|
34
|
+
* that fails for any other reason throws `LivenessUnknownError`: it says nothing about the process.
|
|
35
|
+
*/
|
|
36
|
+
export declare function readProcStat(pid: number): ProcStat | null;
|
|
37
|
+
/** The identity of a process (normally the calling worker itself). */
|
|
38
|
+
export declare function identityOf(pid?: number, clock?: () => number): WorkerIdentity;
|
|
39
|
+
/** Write `worker.json` durably (part of the acknowledgement guarantee). */
|
|
40
|
+
export declare function writeWorkerIdentity(dir: string, identity: WorkerIdentity): void;
|
|
41
|
+
/**
|
|
42
|
+
* The recorded worker; null when none was recorded (no `worker.json`) or the file does not hold a
|
|
43
|
+
* worker identity. A file that exists but cannot be read throws `LivenessUnknownError`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function readWorkerIdentity(dir: string): WorkerIdentity | null;
|
|
46
|
+
/** Record a heartbeat (not fsynced: it is evidence for a live process, not for a crash). */
|
|
47
|
+
export declare function writeHeartbeat(dir: string, clock?: () => number): void;
|
|
48
|
+
/** The last heartbeat; null when none was written. An unreadable heartbeat throws `LivenessUnknownError`. */
|
|
49
|
+
export declare function readHeartbeat(dir: string): string | null;
|
|
50
|
+
export interface LivenessOptions {
|
|
51
|
+
/** Fallback only (no `/proc`): a heartbeat older than this means dead. Default 10 s. */
|
|
52
|
+
heartbeatStaleMs?: number;
|
|
53
|
+
clock?: () => number;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Decide whether the run's recorded worker is alive now. `alive: false` is returned only on
|
|
57
|
+
* evidence that the worker is gone; when the evidence cannot be read this throws
|
|
58
|
+
* `LivenessUnknownError` instead, so a transient read failure never reads as a dead worker.
|
|
59
|
+
*/
|
|
60
|
+
export declare function checkLiveness(dir: string, options?: LivenessOptions): Liveness;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker liveness evidence. A worker records its pid together with its process start time
|
|
3
|
+
* (`/proc/<pid>/stat` field 22, clock ticks since boot) and the kernel boot id. A worker is
|
|
4
|
+
* alive only when a process with that pid exists now, is not a zombie, and has the same start
|
|
5
|
+
* time on the same boot. A reused pid has a different start time, so it is never mistaken for
|
|
6
|
+
* the worker. The heartbeat is reported as supporting evidence; it never makes a dead worker
|
|
7
|
+
* alive and never makes a live (but slow or stopped) worker dead (README: a worker that is
|
|
8
|
+
* alive is never reported as `unknown`).
|
|
9
|
+
*
|
|
10
|
+
* Platform: Linux `/proc`. Without `/proc` the identity cannot be checked; the fallback is
|
|
11
|
+
* `kill(pid, 0)` plus a fresh heartbeat, and the result says it is weaker.
|
|
12
|
+
*/
|
|
13
|
+
import { readFileSync } from "node:fs";
|
|
14
|
+
import { atomicWrite, atomicWriteJson, nowIso, runFile } from "./files.js";
|
|
15
|
+
/**
|
|
16
|
+
* The liveness evidence could not be read (for example EMFILE, ENFILE, ENOMEM, EIO, EACCES), so the
|
|
17
|
+
* worker is neither known alive nor known dead. Callers must not settle the run on this read: a
|
|
18
|
+
* request fails, and a follower checks again on its next tick.
|
|
19
|
+
*/
|
|
20
|
+
export class LivenessUnknownError extends Error {
|
|
21
|
+
name = "LivenessUnknownError";
|
|
22
|
+
constructor(what, cause) {
|
|
23
|
+
super(`worker liveness cannot be established: ${what}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Error codes that mean "this file or process does not exist" (a `/proc` entry that vanishes mid-read gives ESRCH). */
|
|
27
|
+
const ABSENT = new Set(["ENOENT", "ESRCH", "ENOTDIR"]);
|
|
28
|
+
/** Read a file; null only when it does not exist. Any other failure is `LivenessUnknownError`. */
|
|
29
|
+
function readIfPresent(path, what) {
|
|
30
|
+
try {
|
|
31
|
+
return readFileSync(path, "utf8");
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
if (ABSENT.has(err.code ?? ""))
|
|
35
|
+
return null;
|
|
36
|
+
throw new LivenessUnknownError(what, err);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Parse `/proc/<pid>/stat`; null when the process does not exist or `/proc` is unavailable. A read
|
|
41
|
+
* that fails for any other reason throws `LivenessUnknownError`: it says nothing about the process.
|
|
42
|
+
*/
|
|
43
|
+
export function readProcStat(pid) {
|
|
44
|
+
const raw = readIfPresent(`/proc/${pid}/stat`, `reading /proc/${pid}/stat`);
|
|
45
|
+
if (raw === null)
|
|
46
|
+
return null;
|
|
47
|
+
// comm (field 2) is parenthesised and may contain spaces or parens: split after the last ')'.
|
|
48
|
+
const rest = raw.slice(raw.lastIndexOf(")") + 2).split(" ");
|
|
49
|
+
// rest[0] is field 3 (state); field 22 (starttime) is rest[19].
|
|
50
|
+
const state = rest[0];
|
|
51
|
+
const startTime = rest[19];
|
|
52
|
+
if (state === undefined || startTime === undefined)
|
|
53
|
+
return null;
|
|
54
|
+
return { state, startTime };
|
|
55
|
+
}
|
|
56
|
+
function readBootId() {
|
|
57
|
+
try {
|
|
58
|
+
return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** The identity of a process (normally the calling worker itself). */
|
|
65
|
+
export function identityOf(pid = process.pid, clock = Date.now) {
|
|
66
|
+
return { pid, start_time: readProcStat(pid)?.startTime ?? null, boot_id: readBootId(), started_at: nowIso(clock) };
|
|
67
|
+
}
|
|
68
|
+
/** Write `worker.json` durably (part of the acknowledgement guarantee). */
|
|
69
|
+
export function writeWorkerIdentity(dir, identity) {
|
|
70
|
+
atomicWriteJson(runFile(dir, "worker"), identity, true);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The recorded worker; null when none was recorded (no `worker.json`) or the file does not hold a
|
|
74
|
+
* worker identity. A file that exists but cannot be read throws `LivenessUnknownError`.
|
|
75
|
+
*/
|
|
76
|
+
export function readWorkerIdentity(dir) {
|
|
77
|
+
const text = readIfPresent(runFile(dir, "worker"), "reading the worker identity");
|
|
78
|
+
if (text === null)
|
|
79
|
+
return null;
|
|
80
|
+
let value;
|
|
81
|
+
try {
|
|
82
|
+
value = JSON.parse(text);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return null; // written atomically, so never a half-written file: this is not a worker record
|
|
86
|
+
}
|
|
87
|
+
if (value === null || typeof value !== "object" || !Number.isInteger(value.pid) || value.pid < 1)
|
|
88
|
+
return null;
|
|
89
|
+
return {
|
|
90
|
+
pid: value.pid,
|
|
91
|
+
start_time: typeof value.start_time === "string" ? value.start_time : null,
|
|
92
|
+
boot_id: typeof value.boot_id === "string" ? value.boot_id : null,
|
|
93
|
+
started_at: typeof value.started_at === "string" ? value.started_at : "",
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/** Record a heartbeat (not fsynced: it is evidence for a live process, not for a crash). */
|
|
97
|
+
export function writeHeartbeat(dir, clock = Date.now) {
|
|
98
|
+
atomicWrite(runFile(dir, "heartbeat"), `${nowIso(clock)}\n`);
|
|
99
|
+
}
|
|
100
|
+
/** The last heartbeat; null when none was written. An unreadable heartbeat throws `LivenessUnknownError`. */
|
|
101
|
+
export function readHeartbeat(dir) {
|
|
102
|
+
const text = readIfPresent(runFile(dir, "heartbeat"), "reading the worker heartbeat")?.trim() ?? "";
|
|
103
|
+
return text === "" ? null : text;
|
|
104
|
+
}
|
|
105
|
+
function pidExists(pid) {
|
|
106
|
+
try {
|
|
107
|
+
process.kill(pid, 0);
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
return err.code === "EPERM";
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Decide whether the run's recorded worker is alive now. `alive: false` is returned only on
|
|
116
|
+
* evidence that the worker is gone; when the evidence cannot be read this throws
|
|
117
|
+
* `LivenessUnknownError` instead, so a transient read failure never reads as a dead worker.
|
|
118
|
+
*/
|
|
119
|
+
export function checkLiveness(dir, options = {}) {
|
|
120
|
+
const identity = readWorkerIdentity(dir);
|
|
121
|
+
const heartbeat_at = readHeartbeat(dir);
|
|
122
|
+
if (identity === null)
|
|
123
|
+
return { alive: false, pid: null, reason: "no worker recorded", heartbeat_at };
|
|
124
|
+
const { pid } = identity;
|
|
125
|
+
const verdict = (alive, reason) => ({ alive, pid, reason, heartbeat_at });
|
|
126
|
+
if (identity.start_time !== null) {
|
|
127
|
+
const stat = readProcStat(pid);
|
|
128
|
+
if (stat === null)
|
|
129
|
+
return verdict(false, "no process with the recorded pid");
|
|
130
|
+
if (stat.state === "Z" || stat.state === "X")
|
|
131
|
+
return verdict(false, "the recorded pid is a dead (zombie) process");
|
|
132
|
+
if (stat.startTime !== identity.start_time)
|
|
133
|
+
return verdict(false, "the recorded pid belongs to a different process (pid reused)");
|
|
134
|
+
const boot = readBootId();
|
|
135
|
+
if (identity.boot_id !== null && boot !== null && boot !== identity.boot_id) {
|
|
136
|
+
return verdict(false, "the host rebooted since the worker started");
|
|
137
|
+
}
|
|
138
|
+
return verdict(true, "pid and process start time match the recorded worker");
|
|
139
|
+
}
|
|
140
|
+
// Weaker fallback without /proc: the pid exists and the heartbeat is fresh.
|
|
141
|
+
if (!pidExists(pid))
|
|
142
|
+
return verdict(false, "no process with the recorded pid");
|
|
143
|
+
const stale = options.heartbeatStaleMs ?? 10_000;
|
|
144
|
+
const now = (options.clock ?? Date.now)();
|
|
145
|
+
const fresh = heartbeat_at !== null && now - Date.parse(heartbeat_at) <= stale;
|
|
146
|
+
return fresh
|
|
147
|
+
? verdict(true, "pid exists and heartbeat is fresh (no /proc identity check)")
|
|
148
|
+
: verdict(false, "pid exists but no fresh heartbeat and no /proc identity check");
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=liveness.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"liveness.js","sourceRoot":"","sources":["../../../src/store/liveness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AA2B3E;;;;GAIG;AACH,MAAM,OAAO,oBA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