@tangle-network/agent-runtime 10.0.2 → 10.0.3
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/CHANGELOG.md +4 -0
- package/dist/{activation-D0Sp7wMc.d.ts → activation-DbSxPRUW.d.ts} +2 -2
- package/dist/{activation-B0DHGRtB.js → activation-kitznAHo.js} +2 -2
- package/dist/{activation-B0DHGRtB.js.map → activation-kitznAHo.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{continuation-CZaeHEzQ.js → continuation-BDeKJgV3.js} +3 -3
- package/dist/{continuation-CZaeHEzQ.js.map → continuation-BDeKJgV3.js.map} +1 -1
- package/dist/{delegate-Co5iUyS0.js → delegate-D8yX_2K7.js} +2 -2
- package/dist/{delegate-Co5iUyS0.js.map → delegate-D8yX_2K7.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-B1Qx2JUz.js → driver-control-acknowledgers-BTSr3Znq.js} +7 -5
- package/dist/{driver-control-acknowledgers-B1Qx2JUz.js.map → driver-control-acknowledgers-BTSr3Znq.js.map} +1 -1
- package/dist/durable-file-DUcTDWJD.js +498 -0
- package/dist/durable-file-DUcTDWJD.js.map +1 -0
- package/dist/durable-file-XqOyDf7q.js +1 -0
- package/dist/durable-writer-thread.d.ts +1 -0
- package/dist/durable-writer-thread.js +86 -0
- package/dist/durable-writer-thread.js.map +1 -0
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +15 -128
- package/dist/durable.js.map +1 -1
- package/dist/{graph-uc4eT1wR.js → graph-4ep9laIH.js} +7 -7
- package/dist/{graph-uc4eT1wR.js.map → graph-4ep9laIH.js.map} +1 -1
- package/dist/{graph-registry-DxhlgHdA.js → graph-registry-B-EGvJ-3.js} +1 -1
- package/dist/{graph-registry-j9t9J0KT.js → graph-registry-BxEBeihr.js} +4 -4
- package/dist/{graph-registry-j9t9J0KT.js.map → graph-registry-BxEBeihr.js.map} +1 -1
- package/dist/{improve-BM0HlzMi.js → improve-CJf87tBs.js} +7 -7
- package/dist/{improve-BM0HlzMi.js.map → improve-CJf87tBs.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +9 -9
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +4 -4
- package/dist/{jsonl-file-BhuxeejY.js → jsonl-file-CVAWegN-.js} +53 -11
- package/dist/jsonl-file-CVAWegN-.js.map +1 -0
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +17 -15
- package/dist/{loop-runner-npLkvCU5.d.ts → loop-runner-CayC8e9K.d.ts} +2 -2
- package/dist/{loop-runner-CRC-RE4D.js → loop-runner-Ckj-Zz3-.js} +2 -2
- package/dist/{loop-runner-CRC-RE4D.js.map → loop-runner-Ckj-Zz3-.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-CJrMGyZW.js → provision-supervisor-NjROV7AQ.js} +6 -6
- package/dist/{provision-supervisor-CJrMGyZW.js.map → provision-supervisor-NjROV7AQ.js.map} +1 -1
- package/dist/result-blob-store-BR-BVZrg.js +76 -0
- package/dist/result-blob-store-BR-BVZrg.js.map +1 -0
- package/dist/{run-cancellation-CBP3Bmad.js → run-cancellation-C9V1lYhq.js} +5 -209
- package/dist/run-cancellation-C9V1lYhq.js.map +1 -0
- package/dist/run-lock-Y3u9kwM0.js +193 -0
- package/dist/run-lock-Y3u9kwM0.js.map +1 -0
- package/dist/run-reopen-CHYTHk7x.js +134 -0
- package/dist/run-reopen-CHYTHk7x.js.map +1 -0
- package/dist/run-state-DgKo8_tO.js +180 -0
- package/dist/run-state-DgKo8_tO.js.map +1 -0
- package/dist/{runtime-BqSaWTEY.js → runtime-CdthBQUs.js} +21 -19
- package/dist/{runtime-BqSaWTEY.js.map → runtime-CdthBQUs.js.map} +1 -1
- package/dist/{search-executor-C9TN-KgI.js → search-executor-Bb0WuI_Z.js} +3 -3
- package/dist/{search-executor-C9TN-KgI.js.map → search-executor-Bb0WuI_Z.js.map} +1 -1
- package/dist/{server-CcMa8Lt9.js → server-BCtyL7jH.js} +3 -3
- package/dist/{server-CcMa8Lt9.js.map → server-BCtyL7jH.js.map} +1 -1
- package/dist/{settle-record-BtjYZabI.js → settle-record-Beh-sXBW.js} +5 -4
- package/dist/settle-record-Beh-sXBW.js.map +1 -0
- package/dist/{structural-rollout-2oRJjwyM.js → structural-rollout-BRfSDPkv.js} +4 -4
- package/dist/{structural-rollout-2oRJjwyM.js.map → structural-rollout-BRfSDPkv.js.map} +1 -1
- package/dist/{supervise-BrgtzJf3.js → supervise-DTUYxnoJ.js} +9 -8
- package/dist/{supervise-BrgtzJf3.js.map → supervise-DTUYxnoJ.js.map} +1 -1
- package/dist/supervise-identity-eMF-h1uP.js +210 -0
- package/dist/supervise-identity-eMF-h1uP.js.map +1 -0
- package/dist/{supervision-discovery-DLMm3UOr.js → supervision-discovery-CAUsSDno.js} +3 -3
- package/dist/{supervision-discovery-DLMm3UOr.js.map → supervision-discovery-CAUsSDno.js.map} +1 -1
- package/dist/{supervisor-ACffs_W4.js → supervisor-BtRRFbgF.js} +13 -176
- package/dist/supervisor-BtRRFbgF.js.map +1 -0
- package/dist/{supervisor-accounting-BlJqoP3k.js → supervisor-accounting-Cuehs4te.js} +59 -112
- package/dist/supervisor-accounting-Cuehs4te.js.map +1 -0
- package/dist/supervisor-root-contract-CmFKzPps.js +165 -0
- package/dist/supervisor-root-contract-CmFKzPps.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{top-web-PYyzBMsK.js → top-web-D-wuEVdM.js} +7 -6
- package/dist/{top-web-PYyzBMsK.js.map → top-web-D-wuEVdM.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-DX1OGeHE.d.ts → types-PBoTtcbX.d.ts} +2 -2
- package/package.json +1 -1
- package/dist/durable-file-CksURHlH.js +0 -1
- package/dist/durable-file-DstVeHcj.js +0 -228
- package/dist/durable-file-DstVeHcj.js.map +0 -1
- package/dist/jsonl-file-BhuxeejY.js.map +0 -1
- package/dist/run-cancellation-CBP3Bmad.js.map +0 -1
- package/dist/run-state-BnhCVbTY.js +0 -357
- package/dist/run-state-BnhCVbTY.js.map +0 -1
- package/dist/settle-record-BtjYZabI.js.map +0 -1
- package/dist/supervisor-ACffs_W4.js.map +0 -1
- package/dist/supervisor-accounting-BlJqoP3k.js.map +0 -1
|
@@ -1,357 +0,0 @@
|
|
|
1
|
-
import { r as readRunCancelRequest } from "./run-cancellation-CBP3Bmad.js";
|
|
2
|
-
import { c as readRunParking } from "./supervisor-ACffs_W4.js";
|
|
3
|
-
import { a as writeAtomicDurableFile, c as mutateRunClaim, l as runGenerationPath, r as publishExclusiveDurableFile, u as runWithWriteClaim } from "./durable-file-DstVeHcj.js";
|
|
4
|
-
import { a as readCommittedJsonLines, t as isNoEntError } from "./jsonl-file-BhuxeejY.js";
|
|
5
|
-
import { a as readFailureRecord, o as readSettleRecord } from "./settle-record-BtjYZabI.js";
|
|
6
|
-
import { K as spawnJournalRecordEvents } from "./supervisor-accounting-BlJqoP3k.js";
|
|
7
|
-
import { isRecord } from "@tangle-network/agent-core";
|
|
8
|
-
import { createHash } from "node:crypto";
|
|
9
|
-
import { setTimeout } from "node:timers/promises";
|
|
10
|
-
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
|
|
11
|
-
import { join, resolve } from "node:path";
|
|
12
|
-
import { open, stat } from "node:fs/promises";
|
|
13
|
-
import { lockHolderVerdict, lockIdentity, parseLockHolderRecord, readLockHolderIdentity } from "@tangle-network/agent-eval/lock-holder";
|
|
14
|
-
// src/durable/run-lock.ts
|
|
15
|
-
/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */
|
|
16
|
-
const RUN_DIRECTORY_LOCK_FILE = "supervise.lock";
|
|
17
|
-
/** The directory is held by a live process. `holder` is what that process recorded. */
|
|
18
|
-
var RunDirectoryLockedError = class extends Error {
|
|
19
|
-
path;
|
|
20
|
-
holder;
|
|
21
|
-
constructor(path, holder) {
|
|
22
|
-
super(`supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`);
|
|
23
|
-
this.name = "RunDirectoryLockedError";
|
|
24
|
-
this.path = path;
|
|
25
|
-
this.holder = holder;
|
|
26
|
-
}
|
|
27
|
-
};
|
|
28
|
-
/**
|
|
29
|
-
* Take `runDir/supervise.lock`, or refuse.
|
|
30
|
-
*
|
|
31
|
-
* The file is published with its full content or not at all, so a contender never reads a
|
|
32
|
-
* half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now
|
|
33
|
-
* belongs to a process with a different start token, or the host rebooted) is stale and is removed
|
|
34
|
-
* under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file
|
|
35
|
-
* names no holder and is reclaimed. A file with unreadable content is left in place and refused:
|
|
36
|
-
* reclaiming it could evict a live holder written by something other than this module.
|
|
37
|
-
*/
|
|
38
|
-
async function acquireRunDirectoryLock(runDir, runId, now = Date.now) {
|
|
39
|
-
const dir = resolve(runDir);
|
|
40
|
-
const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE);
|
|
41
|
-
mkdirSync(dir, { recursive: true });
|
|
42
|
-
const { pid, ...identity } = readLockHolderIdentity(process.pid);
|
|
43
|
-
const owner = {
|
|
44
|
-
pid,
|
|
45
|
-
startedAt: new Date(now()).toISOString(),
|
|
46
|
-
runId,
|
|
47
|
-
...identity
|
|
48
|
-
};
|
|
49
|
-
return mutateRunClaim(path, () => {
|
|
50
|
-
const existing = readLockFile(path);
|
|
51
|
-
if (existing.state === "holder" && !holderIsDead(existing)) throw new RunDirectoryLockedError(path, existing.holder);
|
|
52
|
-
let previousGeneration = 0;
|
|
53
|
-
try {
|
|
54
|
-
previousGeneration = Number(readFileSync(runGenerationPath(dir), "utf8"));
|
|
55
|
-
if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) throw new Error("invalid run directory generation counter");
|
|
56
|
-
} catch (error) {
|
|
57
|
-
if (!isNoEntError(error)) throw error;
|
|
58
|
-
}
|
|
59
|
-
const generation = Math.max(previousGeneration, existing.state === "holder" ? existing.holder.generation ?? 0 : 0) + 1;
|
|
60
|
-
if (!Number.isSafeInteger(generation)) throw new Error("run directory generation exhausted");
|
|
61
|
-
writeAtomicDurableFile(runGenerationPath(dir), `${generation}\n`);
|
|
62
|
-
if (existing.state !== "missing") removeIfPresent(path);
|
|
63
|
-
const written = {};
|
|
64
|
-
const published = publishExclusiveDurableFile(path, (file) => {
|
|
65
|
-
written.holder = Object.freeze({
|
|
66
|
-
...owner,
|
|
67
|
-
generation,
|
|
68
|
-
lock: lockIdentity(file)
|
|
69
|
-
});
|
|
70
|
-
return `${JSON.stringify(written.holder)}\n`;
|
|
71
|
-
});
|
|
72
|
-
const holder = written.holder;
|
|
73
|
-
if (!published || holder === void 0) throw new Error(`supervisePursuit: could not take ${path}`);
|
|
74
|
-
let released = false;
|
|
75
|
-
return Object.freeze({
|
|
76
|
-
...holder,
|
|
77
|
-
generation,
|
|
78
|
-
path,
|
|
79
|
-
run: (operation) => {
|
|
80
|
-
if (holder.lock === void 0) throw new Error("run lock has no inode identity");
|
|
81
|
-
return runWithWriteClaim({
|
|
82
|
-
path,
|
|
83
|
-
generation,
|
|
84
|
-
lock: holder.lock
|
|
85
|
-
}, operation);
|
|
86
|
-
},
|
|
87
|
-
release: async () => {
|
|
88
|
-
if (released) return;
|
|
89
|
-
await releaseHolder(path, holder);
|
|
90
|
-
released = true;
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
/** Read the holder a lock file names, or `undefined` when no lock file names one. */
|
|
96
|
-
async function readRunDirectoryLock(runDir) {
|
|
97
|
-
const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE));
|
|
98
|
-
return existing.state === "holder" ? existing.holder : void 0;
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Whether a run directory is still held by the live process that took its lock.
|
|
102
|
-
*
|
|
103
|
-
* The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a
|
|
104
|
-
* caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks
|
|
105
|
-
* the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a
|
|
106
|
-
* live holder from an unrelated process that later took the same pid, which is the failure this
|
|
107
|
-
* lock's start token exists to prevent.
|
|
108
|
-
*
|
|
109
|
-
* The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,
|
|
110
|
-
* so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take
|
|
111
|
-
* the directory in between. Reporting and listing are what this is for. A caller that intends to
|
|
112
|
-
* TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the
|
|
113
|
-
* guard and refuses atomically.
|
|
114
|
-
*/
|
|
115
|
-
async function runDirectoryHolderIsLive(runDir) {
|
|
116
|
-
const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE));
|
|
117
|
-
if (existing.state !== "holder") return { live: false };
|
|
118
|
-
const verdict = lockHolderVerdict(existing.record, existing.current);
|
|
119
|
-
return {
|
|
120
|
-
live: verdict.liveness !== "dead",
|
|
121
|
-
holder: existing.holder,
|
|
122
|
-
...verdict.liveness === "unknown" ? { unknown: true } : {}
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
function readLockFile(path) {
|
|
126
|
-
let text;
|
|
127
|
-
let current;
|
|
128
|
-
try {
|
|
129
|
-
const file = openSync(path, "r");
|
|
130
|
-
try {
|
|
131
|
-
current = lockIdentity(fstatSync(file, { bigint: true }));
|
|
132
|
-
text = readFileSync(file, "utf8");
|
|
133
|
-
} finally {
|
|
134
|
-
closeSync(file);
|
|
135
|
-
}
|
|
136
|
-
} catch (error) {
|
|
137
|
-
if (isNoEntError(error)) return { state: "missing" };
|
|
138
|
-
throw error;
|
|
139
|
-
}
|
|
140
|
-
if (text.trim().length === 0) return { state: "empty" };
|
|
141
|
-
let parsed;
|
|
142
|
-
try {
|
|
143
|
-
parsed = JSON.parse(text);
|
|
144
|
-
} catch (cause) {
|
|
145
|
-
throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, { cause });
|
|
146
|
-
}
|
|
147
|
-
const record = parsed;
|
|
148
|
-
if (typeof record !== "object" || record === null || typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0 || typeof record.startedAt !== "string" || typeof record.runId !== "string" || record.processStart !== void 0 && typeof record.processStart !== "string" || record.generation !== void 0 && (!Number.isSafeInteger(record.generation) || record.generation < 1)) throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`);
|
|
149
|
-
const { pid, startedAt, runId, processStart } = record;
|
|
150
|
-
const verdictRecord = parseLockHolderRecord(parsed);
|
|
151
|
-
const { pid: _pid, ...identity } = verdictRecord ?? { pid };
|
|
152
|
-
return {
|
|
153
|
-
state: "holder",
|
|
154
|
-
holder: Object.freeze({
|
|
155
|
-
pid,
|
|
156
|
-
startedAt,
|
|
157
|
-
runId,
|
|
158
|
-
...record.generation === void 0 ? {} : { generation: record.generation },
|
|
159
|
-
...processStart === void 0 ? {} : { processStart },
|
|
160
|
-
...identity
|
|
161
|
-
}),
|
|
162
|
-
record: verdictRecord,
|
|
163
|
-
current
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */
|
|
167
|
-
function holderIsDead(existing) {
|
|
168
|
-
return lockHolderVerdict(existing.record, existing.current).liveness === "dead";
|
|
169
|
-
}
|
|
170
|
-
/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */
|
|
171
|
-
async function releaseHolder(path, holder) {
|
|
172
|
-
const deadline = performance.now() + 1e3;
|
|
173
|
-
while (existsSync(`${path}.guard`) && performance.now() < deadline) await setTimeout(10);
|
|
174
|
-
mutateRunClaim(path, () => {
|
|
175
|
-
const existing = readLockFile(path);
|
|
176
|
-
if (existing.state !== "holder") return;
|
|
177
|
-
if (existing.holder.pid !== holder.pid || existing.holder.startedAt !== holder.startedAt || existing.holder.runId !== holder.runId || existing.holder.processStart !== holder.processStart || existing.holder.generation !== holder.generation || existing.holder.lock?.dev !== holder.lock?.dev || existing.holder.lock?.ino !== holder.lock?.ino || existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs) return;
|
|
178
|
-
removeIfPresent(path);
|
|
179
|
-
});
|
|
180
|
-
}
|
|
181
|
-
function removeIfPresent(path) {
|
|
182
|
-
try {
|
|
183
|
-
unlinkSync(path);
|
|
184
|
-
} catch (error) {
|
|
185
|
-
if (!isNoEntError(error)) throw error;
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
// src/durable/spawn-journal/read.ts
|
|
189
|
-
/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.
|
|
190
|
-
* Missing journals return an empty page. Malformed committed records fail by default; incomplete final
|
|
191
|
-
* writes remain unread for the next call. Cursors detect replacement, truncation and edits at
|
|
192
|
-
* their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.
|
|
193
|
-
*/
|
|
194
|
-
async function readSpawnJournal(runDir, options = {}) {
|
|
195
|
-
const { after, tailBytes } = options;
|
|
196
|
-
if (tailBytes !== void 0 && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) throw new RangeError("readSpawnJournal: tailBytes must be a positive safe integer");
|
|
197
|
-
const path = join(runDir, "spawn-journal.jsonl");
|
|
198
|
-
let handle;
|
|
199
|
-
try {
|
|
200
|
-
handle = await open(path, "r");
|
|
201
|
-
} catch (error) {
|
|
202
|
-
if (isNoEntError(error)) return {
|
|
203
|
-
records: [],
|
|
204
|
-
reset: after !== void 0,
|
|
205
|
-
truncated: false,
|
|
206
|
-
remainingBytes: 0
|
|
207
|
-
};
|
|
208
|
-
throw error;
|
|
209
|
-
}
|
|
210
|
-
try {
|
|
211
|
-
const snapshot = await handle.stat({ bigint: true });
|
|
212
|
-
if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`);
|
|
213
|
-
const size = Number(snapshot.size);
|
|
214
|
-
const file = identity(snapshot);
|
|
215
|
-
const resumed = after !== void 0 && after.file === file && Number.isSafeInteger(after.offset) && after.offset >= 0 && after.offset <= size && after.boundary === await boundary(handle, after.offset);
|
|
216
|
-
let offset = resumed ? after.offset : 0;
|
|
217
|
-
const records = [];
|
|
218
|
-
const read = async (start, end, firstOnly = false) => {
|
|
219
|
-
offset = start;
|
|
220
|
-
for await (const record of readCommittedJsonLines(path, {
|
|
221
|
-
handle,
|
|
222
|
-
start,
|
|
223
|
-
end,
|
|
224
|
-
strictUtf8: true,
|
|
225
|
-
invalid: options.invalid,
|
|
226
|
-
onCommit: (committed) => {
|
|
227
|
-
offset = committed;
|
|
228
|
-
}
|
|
229
|
-
})) {
|
|
230
|
-
if (!isRecord(record) || typeof record.root !== "string" || record.kind === "begin" && typeof record.at !== "string") {
|
|
231
|
-
if (options.invalid === "skip") continue;
|
|
232
|
-
throw new Error(`${path}: spawn journal record has no root or begin timestamp`);
|
|
233
|
-
}
|
|
234
|
-
if (record.kind === "begin") records.push({
|
|
235
|
-
kind: "begin",
|
|
236
|
-
root: record.root,
|
|
237
|
-
at: record.at
|
|
238
|
-
});
|
|
239
|
-
else {
|
|
240
|
-
const events = spawnJournalRecordEvents(record, options.invalid);
|
|
241
|
-
if (events.some((event) => !isRecord(event) || typeof event.kind !== "string" || typeof event.id !== "string")) {
|
|
242
|
-
if (options.invalid === "skip") continue;
|
|
243
|
-
throw new Error(`${path}: spawn journal record has no event identity`);
|
|
244
|
-
}
|
|
245
|
-
for (const event of events) records.push({
|
|
246
|
-
kind: "event",
|
|
247
|
-
root: record.root,
|
|
248
|
-
event
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
if (firstOnly) break;
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
let truncated = false;
|
|
255
|
-
if (!resumed && tailBytes !== void 0 && size > tailBytes) {
|
|
256
|
-
await read(0, size, true);
|
|
257
|
-
const openingEnd = offset;
|
|
258
|
-
const tailStart = await lineBoundary(handle, size - tailBytes, size, -1);
|
|
259
|
-
truncated = tailStart > openingEnd;
|
|
260
|
-
await read(Math.max(openingEnd, tailStart), size);
|
|
261
|
-
if (offset === tailStart && tailStart > openingEnd) {
|
|
262
|
-
const previous = await lineBoundary(handle, tailStart - 1, size, -1);
|
|
263
|
-
truncated = previous > openingEnd;
|
|
264
|
-
await read(Math.max(openingEnd, previous), tailStart);
|
|
265
|
-
}
|
|
266
|
-
} else {
|
|
267
|
-
const end = resumed && tailBytes !== void 0 && size - offset > tailBytes ? await lineBoundary(handle, offset + tailBytes, size, 1) : size;
|
|
268
|
-
await read(offset, end);
|
|
269
|
-
}
|
|
270
|
-
if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size) throw new Error(`${path}: journal changed while reading its committed prefix`);
|
|
271
|
-
return {
|
|
272
|
-
records,
|
|
273
|
-
cursor: {
|
|
274
|
-
file,
|
|
275
|
-
offset,
|
|
276
|
-
boundary: await boundary(handle, offset)
|
|
277
|
-
},
|
|
278
|
-
reset: after !== void 0 && !resumed,
|
|
279
|
-
truncated,
|
|
280
|
-
remainingBytes: size - offset
|
|
281
|
-
};
|
|
282
|
-
} finally {
|
|
283
|
-
await handle.close();
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
function identity(info) {
|
|
287
|
-
return `${info.dev}:${info.ino}:${info.birthtimeNs}`;
|
|
288
|
-
}
|
|
289
|
-
async function bytes(handle, start, length) {
|
|
290
|
-
const buffer = Buffer.alloc(length);
|
|
291
|
-
const { bytesRead } = await handle.read(buffer, 0, length, start);
|
|
292
|
-
if (bytesRead !== length) throw new Error("spawn journal changed while reading its boundary");
|
|
293
|
-
return buffer;
|
|
294
|
-
}
|
|
295
|
-
async function boundary(handle, offset) {
|
|
296
|
-
const length = Math.min(offset, 128);
|
|
297
|
-
return createHash("sha256").update(await bytes(handle, 0, length)).update(await bytes(handle, offset - length, length)).digest("hex");
|
|
298
|
-
}
|
|
299
|
-
/** Include the record crossing a tail window or incremental page boundary. */
|
|
300
|
-
async function lineBoundary(handle, position, size, direction) {
|
|
301
|
-
while (position > 0 && position < size) {
|
|
302
|
-
const start = direction === -1 ? Math.max(0, position - 65536) : position;
|
|
303
|
-
const end = direction === -1 ? position : Math.min(size, position + 65536);
|
|
304
|
-
const part = await bytes(handle, start, end - start);
|
|
305
|
-
const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10);
|
|
306
|
-
if (newline !== -1) return start + newline + 1;
|
|
307
|
-
position = direction === -1 ? start : end;
|
|
308
|
-
}
|
|
309
|
-
return position;
|
|
310
|
-
}
|
|
311
|
-
// src/durable/run-state.ts
|
|
312
|
-
/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;
|
|
313
|
-
* a request remains cancelling until settlement. An unheld run with evidence is down.
|
|
314
|
-
* No Runtime evidence (including a missing or empty directory) returns undefined. Reads are
|
|
315
|
-
* advisory snapshots across independently published files, not a transaction or a resume gate.
|
|
316
|
-
*/
|
|
317
|
-
async function readRunState(runDir) {
|
|
318
|
-
const [settle, failure, parking, holder, journal] = await Promise.all([
|
|
319
|
-
readSettleRecord(runDir),
|
|
320
|
-
readFailureRecord(runDir),
|
|
321
|
-
readRunParking(runDir),
|
|
322
|
-
runDirectoryHolderIsLive(runDir),
|
|
323
|
-
readSpawnJournal(runDir, { tailBytes: 65536 })
|
|
324
|
-
]);
|
|
325
|
-
const cancelRequest = readRunCancelRequest(runDir);
|
|
326
|
-
if (!settle && !failure && !parking && !holder.holder && !cancelRequest && journal.records.length === 0) return;
|
|
327
|
-
const holderLive = holder.unknown ? void 0 : holder.live;
|
|
328
|
-
const phase = settle ? "settled" : cancelRequest ? "cancelling" : parking ? "parked" : holderLive === true ? "running" : holderLive === false ? "down" : void 0;
|
|
329
|
-
const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root);
|
|
330
|
-
const failureCode = (settle?.kind === "no-winner" && settle.reason === "driver-failed" ? settle.error?.failure?.code : void 0) ?? root?.failure?.code;
|
|
331
|
-
let latest;
|
|
332
|
-
const observe = (at) => {
|
|
333
|
-
const timestamp = at === void 0 ? void 0 : new Date(at).getTime();
|
|
334
|
-
if (timestamp !== void 0 && Number.isFinite(timestamp)) latest = latest === void 0 ? timestamp : Math.max(latest, timestamp);
|
|
335
|
-
};
|
|
336
|
-
observe(failure?.at);
|
|
337
|
-
observe(parking?.since);
|
|
338
|
-
observe(cancelRequest?.at);
|
|
339
|
-
observe(holder.holder?.startedAt);
|
|
340
|
-
for (const record of journal.records) observe(record.kind === "begin" ? record.at : record.event.at);
|
|
341
|
-
for (const node of settle?.tree.nodes ?? []) {
|
|
342
|
-
observe(node.spawnedAt);
|
|
343
|
-
observe(node.settledAt);
|
|
344
|
-
}
|
|
345
|
-
const lastActivityAt = latest === void 0 ? void 0 : new Date(latest).toISOString();
|
|
346
|
-
return {
|
|
347
|
-
...phase === void 0 ? {} : { phase },
|
|
348
|
-
...failureCode === void 0 ? {} : { failureCode },
|
|
349
|
-
...settle === void 0 ? {} : { settle },
|
|
350
|
-
...cancelRequest === void 0 ? {} : { cancelRequest },
|
|
351
|
-
...holderLive === void 0 ? {} : { holderLive },
|
|
352
|
-
...lastActivityAt === void 0 ? {} : { lastActivityAt }
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
export { acquireRunDirectoryLock as a, RunDirectoryLockedError as i, readSpawnJournal as n, readRunDirectoryLock as o, RUN_DIRECTORY_LOCK_FILE as r, runDirectoryHolderIsLive as s, readRunState as t };
|
|
356
|
-
|
|
357
|
-
//# sourceMappingURL=run-state-BnhCVbTY.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-state-BnhCVbTY.js","names":["delay"],"sources":["../src/durable/run-lock.ts","../src/durable/spawn-journal/read.ts","../src/durable/run-state.ts"],"sourcesContent":["import {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n unlinkSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport {\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { isNoEntError } from './jsonl-file'\nimport { mutateRunClaim, runGenerationPath, runWithWriteClaim } from './run-fence'\n\n/*\n * Exclusive ownership of one durable run directory for the life of one `supervisePursuit` call.\n *\n * Measured motive (discovery-lab recursive smoke r1): the recovery protocol is\n * `SIGKILL` the runner while a child is live, then resume on the same directory. PID 1527 was\n * killed at 06:20:27Z and PID 2058 resumed at 06:24:59Z. Nothing refused a second process while\n * the first was still alive; two processes on one directory both append to `spawn-journal.jsonl`\n * and `observer.jsonl`, and the recorded assignment keys and settlements stop being one sequence.\n * The operator relied on timing. This lock makes the second process refuse and name the holder.\n *\n * The holder is identified by its pid and the OS's start token for that pid. r1 ran in a\n * container whose pids are small (1527, 2058) and restart from 1, so a pid alone names the wrong\n * process after enough spawns: a lock left by a killed run would then match an unrelated live\n * process and hold the directory until an operator removed the file. Whether a holder is dead is\n * agent-eval's one dead-owner rule (`@tangle-network/agent-eval/lock-holder`): the record carries\n * the start token, host, boot id, pid namespace and the lock file's own inode identity, and a\n * holder is reclaimed only when those prove it gone or its pid reused. A record that cannot prove\n * that, such as one written before these fields existed, is refused and is removed by hand.\n *\n * The lock is operational state, not evidence: replay, projection, and the settle record ignore\n * it. A holder whose process is gone is reclaimed through Eval's crash-recoverable mutation lock.\n */\n\n/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */\nexport const RUN_DIRECTORY_LOCK_FILE = 'supervise.lock'\n\n/** What the lock file records about its holder. */\nexport interface RunDirectoryLockHolder {\n readonly pid: number\n /** Monotonic acquisition generation; absent on legacy lock records. */\n readonly generation?: number\n /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /** The OS's start token for `pid` when the host reports one. A holder without one is never proved dead. */\n readonly processStart?: string\n /** Hostname of the holder. Records written before it existed are never proved dead. */\n readonly host?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n /** Inode identity of the lock file this record was written into. */\n readonly lock?: LockIdentity\n}\n\n/** A held lock. `release()` removes the file; it is safe to call more than once. */\nexport interface RunDirectoryLock extends RunDirectoryLockHolder {\n readonly generation: number\n readonly path: string\n /** Bind durable writes to this acquisition, including work queued before release. */\n run<T>(operation: () => T): T\n release(): Promise<void>\n}\n\n/** The directory is held by a live process. `holder` is what that process recorded. */\nexport class RunDirectoryLockedError extends Error {\n readonly path: string\n readonly holder: RunDirectoryLockHolder\n\n constructor(path: string, holder: RunDirectoryLockHolder) {\n super(\n `supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`,\n )\n this.name = 'RunDirectoryLockedError'\n this.path = path\n this.holder = holder\n }\n}\n\n/**\n * Take `runDir/supervise.lock`, or refuse.\n *\n * The file is published with its full content or not at all, so a contender never reads a\n * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now\n * belongs to a process with a different start token, or the host rebooted) is stale and is removed\n * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file\n * names no holder and is reclaimed. A file with unreadable content is left in place and refused:\n * reclaiming it could evict a live holder written by something other than this module.\n */\nexport async function acquireRunDirectoryLock(\n runDir: string,\n runId: string,\n now: () => number = Date.now,\n): Promise<RunDirectoryLock> {\n const dir = resolve(runDir)\n const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n const { pid, ...identity } = readLockHolderIdentity(process.pid)\n const owner = { pid, startedAt: new Date(now()).toISOString(), runId, ...identity }\n return mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state === 'holder' && !holderIsDead(existing)) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n let previousGeneration = 0\n try {\n previousGeneration = Number(readFileSync(runGenerationPath(dir), 'utf8'))\n if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) {\n throw new Error('invalid run directory generation counter')\n }\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n const generation =\n Math.max(\n previousGeneration,\n existing.state === 'holder' ? (existing.holder.generation ?? 0) : 0,\n ) + 1\n if (!Number.isSafeInteger(generation)) throw new Error('run directory generation exhausted')\n writeAtomicDurableFile(runGenerationPath(dir), `${generation}\\n`)\n if (existing.state !== 'missing') removeIfPresent(path)\n const written: { holder?: RunDirectoryLockHolder } = {}\n // The lock file is a hard link of the temporary file, so the temporary file's inode identity\n // is the lock's, and a later verdict can prove this record was written for this very lock.\n const published = publishExclusiveDurableFile(path, (file) => {\n written.holder = Object.freeze({ ...owner, generation, lock: lockIdentity(file) })\n return `${JSON.stringify(written.holder)}\\n`\n })\n const holder = written.holder\n if (!published || holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n let released = false\n return Object.freeze({\n ...holder,\n generation,\n path,\n run: <T>(operation: () => T): T => {\n if (holder.lock === undefined) throw new Error('run lock has no inode identity')\n return runWithWriteClaim({ path, generation, lock: holder.lock }, operation)\n },\n release: async () => {\n if (released) return\n await releaseHolder(path, holder)\n released = true\n },\n })\n })\n}\n\n/** Read the holder a lock file names, or `undefined` when no lock file names one. */\nexport async function readRunDirectoryLock(\n runDir: string,\n): Promise<RunDirectoryLockHolder | undefined> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n return existing.state === 'holder' ? existing.holder : undefined\n}\n\n/** What {@link runDirectoryHolderIsLive} proved about a run directory's recorded holder. */\nexport interface RunDirectoryHolderLiveness {\n /** False only when the holder that took the lock is proved dead; a holder that cannot be proved dead reads as live. */\n readonly live: boolean\n /** The holder could not be verified on this host. `live` stays conservative for exclusion. */\n readonly unknown?: true\n /** The holder the lock file names. Absent when no lock file names one, which reads as not live. */\n readonly holder?: RunDirectoryLockHolder\n}\n\n/**\n * Whether a run directory is still held by the live process that took its lock.\n *\n * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a\n * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks\n * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a\n * live holder from an unrelated process that later took the same pid, which is the failure this\n * lock's start token exists to prevent.\n *\n * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,\n * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take\n * the directory in between. Reporting and listing are what this is for. A caller that intends to\n * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the\n * guard and refuses atomically.\n */\nexport async function runDirectoryHolderIsLive(\n runDir: string,\n): Promise<RunDirectoryHolderLiveness> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n if (existing.state !== 'holder') return { live: false }\n const verdict = lockHolderVerdict(existing.record, existing.current)\n return {\n live: verdict.liveness !== 'dead',\n holder: existing.holder,\n ...(verdict.liveness === 'unknown' ? { unknown: true as const } : {}),\n }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | {\n readonly state: 'holder'\n readonly holder: RunDirectoryLockHolder\n /** The holder as agent-eval's rule reads it; absent when the record names no host. */\n readonly record: LockHolderRecord | undefined\n /** Inode identity of the file the holder was read from. */\n readonly current: LockIdentity\n }\n\nfunction readLockFile(path: string): LockFileState {\n let text: string\n let current: LockIdentity\n try {\n const file = openSync(path, 'r')\n try {\n current = lockIdentity(fstatSync(file, { bigint: true }))\n text = readFileSync(file, 'utf8')\n } finally {\n closeSync(file)\n }\n } catch (error) {\n if (isNoEntError(error)) return { state: 'missing' }\n throw error\n }\n // This module publishes the file with its full content or not at all, so an empty file was\n // not left by a live holder.\n if (text.trim().length === 0) return { state: 'empty' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, {\n cause,\n })\n }\n const record = parsed as Partial<RunDirectoryLockHolder> | null\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid <= 0 ||\n typeof record.startedAt !== 'string' ||\n typeof record.runId !== 'string' ||\n (record.processStart !== undefined && typeof record.processStart !== 'string') ||\n (record.generation !== undefined &&\n (!Number.isSafeInteger(record.generation) || record.generation < 1))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`)\n }\n const { pid, startedAt, runId, processStart } = record\n // A missing or malformed identity field is dropped, which leaves the holder never provably dead.\n const verdictRecord = parseLockHolderRecord(parsed)\n const { pid: _pid, ...identity } = verdictRecord ?? { pid }\n return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(record.generation === undefined ? {} : { generation: record.generation }),\n ...(processStart === undefined ? {} : { processStart }),\n ...identity,\n }),\n record: verdictRecord,\n current,\n }\n}\n\n/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */\nfunction holderIsDead(existing: Extract<LockFileState, { state: 'holder' }>): boolean {\n return lockHolderVerdict(existing.record, existing.current).liveness === 'dead'\n}\n\n/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */\nasync function releaseHolder(path: string, holder: RunDirectoryLockHolder): Promise<void> {\n const deadline = performance.now() + 1_000\n while (existsSync(`${path}.guard`) && performance.now() < deadline) await delay(10)\n mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state !== 'holder') return\n if (\n existing.holder.pid !== holder.pid ||\n existing.holder.startedAt !== holder.startedAt ||\n existing.holder.runId !== holder.runId ||\n existing.holder.processStart !== holder.processStart ||\n existing.holder.generation !== holder.generation ||\n existing.holder.lock?.dev !== holder.lock?.dev ||\n existing.holder.lock?.ino !== holder.lock?.ino ||\n existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs\n )\n return\n removeIfPresent(path)\n })\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n","import { createHash } from 'node:crypto'\nimport type { BigIntStats } from 'node:fs'\nimport { type FileHandle, open, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\nimport { isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/** Serializable checkpoint of a committed byte boundary, bound to one file and its bytes. */\nexport interface SpawnJournalCursor {\n readonly file: string\n readonly offset: number\n readonly boundary: string\n}\n\n/** Physical groups expand to event records; the owning tree is preserved for every event. */\nexport type SpawnJournalReadRecord =\n | { readonly kind: 'begin'; readonly root: NodeId; readonly at: string }\n | { readonly kind: 'event'; readonly root: NodeId; readonly event: SpawnEvent }\n\nexport interface SpawnJournalReadOptions {\n /** Read-only projections may skip malformed physical rows; execution readers stay strict. */\n readonly invalid?: 'throw' | 'skip'\n readonly after?: SpawnJournalCursor\n /** Initial opening-and-tail window, or an incremental page's byte budget. A crossing record\n * is read whole, so one large record can exceed this budget. Omit for complete history. */\n readonly tailBytes?: number\n}\n\nexport interface SpawnJournalReadResult {\n readonly records: ReadonlyArray<SpawnJournalReadRecord>\n /** Absent only when the journal does not exist. Treat as opaque and persist unchanged. */\n readonly cursor?: SpawnJournalCursor\n /** The supplied cursor no longer matches; this page starts over. */\n readonly reset: boolean\n /** An initial opening-and-tail window omitted records between its two windows. */\n readonly truncated: boolean\n /** Bytes after the committed cursor in this snapshot, including an incomplete final write. */\n readonly remainingBytes: number\n}\n\n/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.\n * Missing journals return an empty page. Malformed committed records fail by default; incomplete final\n * writes remain unread for the next call. Cursors detect replacement, truncation and edits at\n * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.\n */\nexport async function readSpawnJournal(\n runDir: string,\n options: SpawnJournalReadOptions = {},\n): Promise<SpawnJournalReadResult> {\n const { after, tailBytes } = options\n if (tailBytes !== undefined && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) {\n throw new RangeError('readSpawnJournal: tailBytes must be a positive safe integer')\n }\n const path = join(runDir, 'spawn-journal.jsonl')\n let handle: FileHandle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (isNoEntError(error)) {\n return { records: [], reset: after !== undefined, truncated: false, remainingBytes: 0 }\n }\n throw error\n }\n try {\n const snapshot = await handle.stat({ bigint: true })\n if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`)\n const size = Number(snapshot.size)\n const file = identity(snapshot)\n const resumed =\n after !== undefined &&\n after.file === file &&\n Number.isSafeInteger(after.offset) &&\n after.offset >= 0 &&\n after.offset <= size &&\n after.boundary === (await boundary(handle, after.offset))\n let offset = resumed ? after.offset : 0\n const records: SpawnJournalReadRecord[] = []\n const read = async (start: number, end: number, firstOnly = false): Promise<void> => {\n offset = start\n for await (const record of readCommittedJsonLines<unknown>(path, {\n handle,\n start,\n end,\n strictUtf8: true,\n invalid: options.invalid,\n onCommit: (committed) => {\n offset = committed\n },\n })) {\n if (\n !isRecord(record) ||\n typeof record.root !== 'string' ||\n (record.kind === 'begin' && typeof record.at !== 'string')\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no root or begin timestamp`)\n }\n if (record.kind === 'begin') {\n records.push({ kind: 'begin', root: record.root, at: record.at as string })\n } else {\n const events = spawnJournalRecordEvents(record, options.invalid)\n if (\n events.some(\n (event) =>\n !isRecord(event) || typeof event.kind !== 'string' || typeof event.id !== 'string',\n )\n ) {\n if (options.invalid === 'skip') continue\n throw new Error(`${path}: spawn journal record has no event identity`)\n }\n for (const event of events) records.push({ kind: 'event', root: record.root, event })\n }\n if (firstOnly) break\n }\n }\n let truncated = false\n if (!resumed && tailBytes !== undefined && size > tailBytes) {\n await read(0, size, true)\n const openingEnd = offset\n const tailStart = await lineBoundary(handle, size - tailBytes, size, -1)\n truncated = tailStart > openingEnd\n await read(Math.max(openingEnd, tailStart), size)\n // A long torn tail must not hide the latest committed activity before it.\n if (offset === tailStart && tailStart > openingEnd) {\n const previous = await lineBoundary(handle, tailStart - 1, size, -1)\n truncated = previous > openingEnd\n await read(Math.max(openingEnd, previous), tailStart)\n }\n } else {\n const end =\n resumed && tailBytes !== undefined && size - offset > tailBytes\n ? await lineBoundary(handle, offset + tailBytes, size, 1)\n : size\n await read(offset, end)\n }\n if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size)\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n return {\n records,\n cursor: { file, offset, boundary: await boundary(handle, offset) },\n reset: after !== undefined && !resumed,\n truncated,\n remainingBytes: size - offset,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction identity(info: BigIntStats): string {\n return `${info.dev}:${info.ino}:${info.birthtimeNs}`\n}\n\nasync function bytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {\n const buffer = Buffer.alloc(length)\n const { bytesRead } = await handle.read(buffer, 0, length, start)\n if (bytesRead !== length) throw new Error('spawn journal changed while reading its boundary')\n return buffer\n}\n\nasync function boundary(handle: FileHandle, offset: number): Promise<string> {\n const length = Math.min(offset, 128)\n return createHash('sha256')\n .update(await bytes(handle, 0, length))\n .update(await bytes(handle, offset - length, length))\n .digest('hex')\n}\n\n/** Include the record crossing a tail window or incremental page boundary. */\nasync function lineBoundary(\n handle: FileHandle,\n position: number,\n size: number,\n direction: -1 | 1,\n): Promise<number> {\n while (position > 0 && position < size) {\n const start = direction === -1 ? Math.max(0, position - 65_536) : position\n const end = direction === -1 ? position : Math.min(size, position + 65_536)\n const part = await bytes(handle, start, end - start)\n const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10)\n if (newline !== -1) return start + newline + 1\n position = direction === -1 ? start : end\n }\n return position\n}\n","import type { RuntimeFailureCause } from '../runtime/failure-cause'\nimport { type RunCancelRequest, readRunCancelRequest } from '../runtime/supervise/run-cancellation'\nimport { readRunParking } from '../runtime/supervise/run-parking'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { runDirectoryHolderIsLive } from './run-lock'\nimport { readFailureRecord, readSettleRecord } from './settle-record'\nimport { readSpawnJournal } from './spawn-journal/read'\n\n/** Runtime evidence only. Product-specific launch, checks and trace completeness belong to callers. */\nexport interface RunState {\n /** Absent when a recorded holder cannot be verified on this host. */\n readonly phase?: 'running' | 'parked' | 'cancelling' | 'settled' | 'down'\n /** A persisted typed root failure; legacy failure messages do not establish a code. */\n readonly failureCode?: RuntimeFailureCause['code']\n readonly settle?: SupervisedResult<unknown>\n readonly cancelRequest?: RunCancelRequest\n /** Absent when holder liveness is unknown. This is advisory, never ownership authorization. */\n readonly holderLive?: boolean\n /** Latest explicit Runtime timestamp observed, as ISO UTC; never a filesystem mtime. */\n readonly lastActivityAt?: string\n}\n\n/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;\n * a request remains cancelling until settlement. An unheld run with evidence is down.\n * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are\n * advisory snapshots across independently published files, not a transaction or a resume gate.\n */\nexport async function readRunState(runDir: string): Promise<RunState | undefined> {\n const [settle, failure, parking, holder, journal] = await Promise.all([\n readSettleRecord(runDir),\n readFailureRecord(runDir),\n readRunParking(runDir),\n runDirectoryHolderIsLive(runDir),\n readSpawnJournal(runDir, { tailBytes: 65_536 }),\n ])\n const cancelRequest = readRunCancelRequest(runDir)\n if (\n !settle &&\n !failure &&\n !parking &&\n !holder.holder &&\n !cancelRequest &&\n journal.records.length === 0\n ) {\n return undefined\n }\n const holderLive = holder.unknown ? undefined : holder.live\n const phase = settle\n ? 'settled'\n : cancelRequest\n ? 'cancelling'\n : parking\n ? 'parked'\n : holderLive === true\n ? 'running'\n : holderLive === false\n ? 'down'\n : undefined\n const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root)\n const failureCode =\n (settle?.kind === 'no-winner' && settle.reason === 'driver-failed'\n ? settle.error?.failure?.code\n : undefined) ?? root?.failure?.code\n let latest: number | undefined\n const observe = (at: string | number | undefined): void => {\n const timestamp = at === undefined ? undefined : new Date(at).getTime()\n if (timestamp !== undefined && Number.isFinite(timestamp)) {\n latest = latest === undefined ? timestamp : Math.max(latest, timestamp)\n }\n }\n observe(failure?.at)\n observe(parking?.since)\n observe(cancelRequest?.at)\n observe(holder.holder?.startedAt)\n for (const record of journal.records)\n observe(record.kind === 'begin' ? record.at : record.event.at)\n for (const node of settle?.tree.nodes ?? []) {\n observe(node.spawnedAt)\n observe(node.settledAt)\n }\n const lastActivityAt = latest === undefined ? undefined : new Date(latest).toISOString()\n return {\n ...(phase === undefined ? {} : { phase }),\n ...(failureCode === undefined ? {} : { failureCode }),\n ...(settle === undefined ? {} : { settle }),\n ...(cancelRequest === undefined ? {} : { cancelRequest }),\n ...(holderLive === undefined ? {} : { holderLive }),\n ...(lastActivityAt === undefined ? {} : { lastActivityAt }),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkDA,MAAa,0BAA0B;;AA8BvC,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CAEA,YAAY,MAAc,QAAgC;EACxD,MACE,qBAAqB,KAAK,kBAAkB,OAAO,IAAI,SAAS,OAAO,MAAM,WAAW,OAAO,UAAU,gDAC3G;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;AAYA,eAAsB,wBACpB,QACA,OACA,MAAoB,KAAK,KACE;CAC3B,MAAM,MAAM,QAAQ,MAAM;CAC1B,MAAM,OAAO,QAAQ,KAAK,uBAAuB;CACjD,UAAU,KAAK,EA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;CACA,QAAQ,SAAS,EAAE;CACnB,QAAQ,SAAS,KAAK;CACtB,QAAQ,eAAe,EAAE;CACzB,QAAQ,OAAO,QAAQ,SAAS;CAChC,KAAK,MAAM,UAAU,QAAQ,SAC3B,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAK,OAAO,MAAM,EAAE;CAC/D,KAAK,MAAM,QAAQ,QAAQ,KAAK,SAAS,CAAC,GAAG;EAC3C,QAAQ,KAAK,SAAS;EACtB,QAAQ,KAAK,SAAS;CACxB;CACA,MAAM,iBAAiB,WAAW,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY;CACvF,OAAO;EACL,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;EACvC,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;EACzC,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;EACvD,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;CAC3D;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"settle-record-BtjYZabI.js","names":[],"sources":["../src/durable/settle-record.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport {\n type AgentProfile,\n canonicalCandidateDigest,\n canonicalCandidateJson,\n} from '@tangle-network/agent-interface'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { terminalAccounting } from '../runtime/supervise/supervisor-accounting'\nimport type { RootStreamReceipt, SupervisedResult } from '../runtime/supervise/types'\nimport { isNoEntError } from './jsonl-file'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\n/** Terminal evidence has one result per segment. Reopen archives that result byte for byte;\n * a failed attempt may resume because failure.json records only the latest throw.\n * Serialization, exclusive publication and validation stay with the record operations below.\n */\n\n/** The settle record: the returned `SupervisedResult` as canonical JSON, written once. */\nexport const SETTLE_RECORD_FILE = 'result.json'\n/** The failure record: the most recent throw, replaced by a later throw. */\nexport const FAILURE_RECORD_FILE = 'failure.json'\n\n/** What `failure.json` records about the most recent throw. */\nexport interface DurableFailureRecord {\n readonly runId: string\n readonly pursuitId: string\n /** ISO instant the throw was recorded. */\n readonly at: string\n readonly error: { readonly name: string; readonly message: string }\n /** The root's retained provider stream at the time of the throw, when the directory holds one:\n * a root that died mid-turn keeps what it had streamed, and this names it. */\n readonly rootStream?: RootStreamReceipt\n}\n\n/** The directory already holds a settle record, so the run it records must not be re-entered. */\nexport class SettledRunDirectoryError extends Error {\n readonly path: string\n /** The root of the recorded run, which is its `runId`. */\n readonly recordedRunId: string\n\n constructor(path: string, recordedRunId: string, requestedRunId: string) {\n super(\n recordedRunId === requestedRunId\n ? `supervisePursuit: ${path} records that run '${recordedRunId}' already settled; a settled run is not re-entered unless the call passes reopen: { operator, reason, operationId }`\n : `supervisePursuit: ${path} records that run '${recordedRunId}' already settled in this directory; a directory holds one settle record, so run '${requestedRunId}' needs its own runDir`,\n )\n this.name = 'SettledRunDirectoryError'\n this.path = path\n this.recordedRunId = recordedRunId\n }\n}\n\n/** A result member whose JSON form would misstate it. */\nclass UnrecordableSettleValueError extends TypeError {\n readonly path: string\n\n constructor(path: string, kind: string) {\n super(\n `supervisePursuit: result${path} is a ${kind}, which JSON cannot record faithfully; a settle record holds plain data only`,\n )\n this.name = 'UnrecordableSettleValueError'\n this.path = path\n }\n}\n\nconst PLAIN_PROTOTYPES = new Set<unknown>([Object.prototype, Array.prototype, null])\n\n/**\n * The JSON value of a result, or a throw naming the first member JSON would misstate. An\n * `undefined` member and a function are dropped, exactly as any JSON consumer drops them; a Map,\n * a Set, a Date, a typed array, or a class instance would be rewritten to `{}` or a string and\n * so is refused.\n */\nfunction jsonValue(result: unknown): unknown {\n const seen: unknown[] = []\n const visit = (value: unknown, path: string): void => {\n if (value === null || typeof value !== 'object') return\n if (value instanceof Map) throw new UnrecordableSettleValueError(path, 'Map')\n if (value instanceof Set) throw new UnrecordableSettleValueError(path, 'Set')\n if (value instanceof Date) throw new UnrecordableSettleValueError(path, 'Date')\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n throw new UnrecordableSettleValueError(path, 'binary buffer')\n }\n if (!PLAIN_PROTOTYPES.has(Object.getPrototypeOf(value))) {\n throw new UnrecordableSettleValueError(path, 'class instance')\n }\n if (seen.includes(value)) throw new UnrecordableSettleValueError(path, 'cycle')\n seen.push(value)\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) visit(item, `${path}[${index}]`)\n } else {\n for (const [key, item] of Object.entries(value)) visit(item, `${path}.${key}`)\n }\n seen.pop()\n }\n visit(result, '')\n return JSON.parse(JSON.stringify(result))\n}\n\n/**\n * The exact bytes `result.json` holds for a result: its JSON value serialized as RFC 8785\n * canonical JSON. Throws `UnrecordableSettleValueError` before any byte is written when the\n * result carries a value JSON would misstate.\n */\nexport function settleRecordJson(result: unknown): string {\n return canonicalCandidateJson(jsonValue(result))\n}\n\n/** The digest the settle record's bytes hash to: the candidate digest of the result's JSON value. */\nexport function settleRecordDigest(result: unknown): string {\n return canonicalCandidateDigest(jsonValue(result))\n}\n\n/** Publish `result.json` in the run directory once. Throws when a record is already there. */\nexport async function writeSettleRecord(runDir: string, result: unknown): Promise<string> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n if (!publishExclusiveDurableFile(path, settleRecordJson(result))) {\n throw new Error(`supervisePursuit: ${path} already exists; a settle record is written once`)\n }\n return path\n}\n\n/** Replace `failure.json` in the run directory with the most recent throw. */\nexport async function writeFailureRecord(\n runDir: string,\n record: DurableFailureRecord,\n): Promise<string> {\n const path = resolve(runDir, FAILURE_RECORD_FILE)\n writeAtomicDurableFile(path, `${JSON.stringify(record, null, 2)}\\n`)\n return path\n}\n\n/**\n * Read the settle record a run directory holds, or `undefined` when it holds none. A file that\n * is present but is not a settle record is corruption and fails loud. `usage` annotates legacy\n * results by replay without changing their sealed fields; recorded usage always wins.\n */\nexport async function readSettleRecord(\n runDir: string,\n options: { readonly usage?: boolean; readonly requestedProfile?: AgentProfile } = {},\n): Promise<SupervisedResult<unknown> | undefined> {\n const recorded = await readTerminalFile(runDir, SETTLE_RECORD_FILE, parseSettleRecord)\n if (!recorded || !options.usage || recorded.usage) return recorded\n const { usage } = await terminalAccounting(\n new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl')),\n recorded.tree.root,\n recorded.spentTotal.ms,\n options.requestedProfile,\n )\n return { ...recorded, usage }\n}\n\nasync function readTerminalFile<T>(\n runDir: string,\n file: string,\n parse: (text: string, path: string) => T,\n): Promise<T | undefined> {\n const path = resolve(runDir, file)\n try {\n return parse(await readFile(path, 'utf8'), path)\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n}\n\nfunction parseTerminalJson(text: string, path: string): unknown {\n try {\n return JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not valid JSON`, { cause })\n }\n}\n\n/** Parse settle-record bytes already read, so a caller hashes and parses the same bytes. */\nexport function parseSettleRecord(text: string, path: string): SupervisedResult<unknown> {\n const parsed = parseTerminalJson(text, path)\n const record = parsed as { kind?: unknown; tree?: { root?: unknown } }\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.kind !== 'string' ||\n typeof record.tree !== 'object' ||\n record.tree === null ||\n typeof record.tree.root !== 'string'\n ) {\n throw new Error(`supervisePursuit: ${path} is not a settle record (no kind or tree.root)`)\n }\n return parsed as SupervisedResult<unknown>\n}\n\n/** Read the most recent failure record, or `undefined` when the directory holds none. */\nexport async function readFailureRecord(runDir: string): Promise<DurableFailureRecord | undefined> {\n return readTerminalFile(runDir, FAILURE_RECORD_FILE, (text, path) => {\n const parsed = parseTerminalJson(text, path)\n const record = parsed as Partial<DurableFailureRecord>\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.runId !== 'string' ||\n typeof record.pursuitId !== 'string' ||\n typeof record.at !== 'string' ||\n typeof record.error?.name !== 'string' ||\n typeof record.error.message !== 'string' ||\n (record.rootStream !== undefined &&\n (typeof record.rootStream.ref !== 'string' || typeof record.rootStream.events !== 'number'))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a failure record`)\n }\n return parsed as DurableFailureRecord\n })\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,MAAa,qBAAqB;;AAElC,MAAa,sBAAsB;;AAenC,IAAa,2BAAb,cAA8C,MAAM;CAClD;;CAEA;CAEA,YAAY,MAAc,eAAuB,gBAAwB;EACvE,MACE,kBAAkB,iBACd,qBAAqB,KAAK,qBAAqB,cAAc,uHAC7D,qBAAqB,KAAK,qBAAqB,cAAc,oFAAoF,eAAe,uBACtK;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,gBAAgB;CACvB;AACF;;AAGA,IAAM,+BAAN,cAA2C,UAAU;CACnD;CAEA,YAAY,MAAc,MAAc;EACtC,MACE,2BAA2B,KAAK,QAAQ,KAAK,6EAC/C;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,MAAM,mCAAmB,IAAI,IAAa;CAAC,OAAO;CAAW,MAAM;CAAW;AAAI,CAAC;;;;;;;AAQnF,SAAS,UAAU,QAA0B;CAC3C,MAAM,OAAkB,CAAC;CACzB,MAAM,SAAS,OAAgB,SAAuB;EACpD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EACjD,IAAI,iBAAiB,KAAK,MAAM,IAAI,6BAA6B,MAAM,KAAK;EAC5E,IAAI,iBAAiB,KAAK,MAAM,IAAI,6BAA6B,MAAM,KAAK;EAC5E,IAAI,iBAAiB,MAAM,MAAM,IAAI,6BAA6B,MAAM,MAAM;EAC9E,IAAI,YAAY,OAAO,KAAK,KAAK,iBAAiB,aAChD,MAAM,IAAI,6BAA6B,MAAM,eAAe;E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