@tangle-network/agent-runtime 10.0.2 → 10.0.4
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 +8 -0
- package/dist/{activation-B0DHGRtB.js → activation-38MolXIP.js} +2 -2
- package/dist/{activation-B0DHGRtB.js.map → activation-38MolXIP.js.map} +1 -1
- package/dist/{activation-D0Sp7wMc.d.ts → activation-Ckx0yHjT.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{continuation-CZaeHEzQ.js → continuation-CL4B1Y4M.js} +3 -3
- package/dist/{continuation-CZaeHEzQ.js.map → continuation-CL4B1Y4M.js.map} +1 -1
- package/dist/{delegate-Co5iUyS0.js → delegate-dhNeiaH_.js} +2 -2
- package/dist/{delegate-Co5iUyS0.js.map → delegate-dhNeiaH_.js.map} +1 -1
- package/dist/{driver-control-acknowledgers-B1Qx2JUz.js → driver-control-acknowledgers-C6GaGBf_.js} +98 -55
- package/dist/{driver-control-acknowledgers-B1Qx2JUz.js.map → driver-control-acknowledgers-C6GaGBf_.js.map} +1 -1
- package/dist/durable-file-DJ3JsA4B.js +1 -0
- package/dist/durable-file-lXnojyij.js +509 -0
- package/dist/durable-file-lXnojyij.js.map +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-CwLg3LGC.js} +7 -7
- package/dist/{graph-uc4eT1wR.js.map → graph-CwLg3LGC.js.map} +1 -1
- package/dist/{graph-registry-DxhlgHdA.js → graph-registry-Bs6mGKou.js} +1 -1
- package/dist/{graph-registry-j9t9J0KT.js → graph-registry-DtGd03zk.js} +4 -4
- package/dist/{graph-registry-j9t9J0KT.js.map → graph-registry-DtGd03zk.js.map} +1 -1
- package/dist/{improve-BM0HlzMi.js → improve-C_LKfgH9.js} +7 -7
- package/dist/{improve-BM0HlzMi.js.map → improve-C_LKfgH9.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-DyzefaZ6.js} +53 -11
- package/dist/jsonl-file-DyzefaZ6.js.map +1 -0
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +18 -16
- package/dist/{loop-runner-CRC-RE4D.js → loop-runner-BS3ru-yj.js} +2 -2
- package/dist/{loop-runner-CRC-RE4D.js.map → loop-runner-BS3ru-yj.js.map} +1 -1
- package/dist/{loop-runner-npLkvCU5.d.ts → loop-runner-LWqWf8FD.d.ts} +2 -2
- 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-D8N0l2DM.js} +6 -6
- package/dist/{provision-supervisor-CJrMGyZW.js.map → provision-supervisor-D8N0l2DM.js.map} +1 -1
- package/dist/result-blob-store-DfTcyQ05.js +76 -0
- package/dist/result-blob-store-DfTcyQ05.js.map +1 -0
- package/dist/{run-cancellation-CBP3Bmad.js → run-cancellation-D3qc9wAD.js} +5 -209
- package/dist/run-cancellation-D3qc9wAD.js.map +1 -0
- package/dist/run-lock-D1xnb9ve.js +193 -0
- package/dist/run-lock-D1xnb9ve.js.map +1 -0
- package/dist/run-reopen-DVM5AEKV.js +134 -0
- package/dist/run-reopen-DVM5AEKV.js.map +1 -0
- package/dist/run-state-tgQ-S9Ln.js +180 -0
- package/dist/run-state-tgQ-S9Ln.js.map +1 -0
- package/dist/{runtime-BqSaWTEY.js → runtime-BTECV05R.js} +21 -19
- package/dist/{runtime-BqSaWTEY.js.map → runtime-BTECV05R.js.map} +1 -1
- package/dist/{search-executor-C9TN-KgI.js → search-executor-Uco2_KTB.js} +3 -3
- package/dist/{search-executor-C9TN-KgI.js.map → search-executor-Uco2_KTB.js.map} +1 -1
- package/dist/{server-CcMa8Lt9.js → server-BMp24-xn.js} +3 -3
- package/dist/{server-CcMa8Lt9.js.map → server-BMp24-xn.js.map} +1 -1
- package/dist/{settle-record-BtjYZabI.js → settle-record-au3w7bQG.js} +5 -4
- package/dist/settle-record-au3w7bQG.js.map +1 -0
- package/dist/{structural-rollout-2oRJjwyM.js → structural-rollout-D8wufVJI.js} +4 -4
- package/dist/{structural-rollout-2oRJjwyM.js.map → structural-rollout-D8wufVJI.js.map} +1 -1
- package/dist/{supervise-BrgtzJf3.js → supervise-DtVdvZpr.js} +9 -8
- package/dist/{supervise-BrgtzJf3.js.map → supervise-DtVdvZpr.js.map} +1 -1
- package/dist/supervise-identity-S5XwgaF3.js +210 -0
- package/dist/supervise-identity-S5XwgaF3.js.map +1 -0
- package/dist/{supervision-discovery-DLMm3UOr.js → supervision-discovery-Cqu4NxPV.js} +3 -3
- package/dist/{supervision-discovery-DLMm3UOr.js.map → supervision-discovery-Cqu4NxPV.js.map} +1 -1
- package/dist/{supervisor-ACffs_W4.js → supervisor-CHgCAMjm.js} +13 -176
- package/dist/supervisor-CHgCAMjm.js.map +1 -0
- package/dist/{supervisor-accounting-BlJqoP3k.js → supervisor-accounting-CZ7i4cd5.js} +171 -153
- package/dist/supervisor-accounting-CZ7i4cd5.js.map +1 -0
- package/dist/supervisor-root-contract-D70KTGXF.js +165 -0
- package/dist/supervisor-root-contract-D70KTGXF.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-COrMqTRC.js} +7 -6
- package/dist/{top-web-PYyzBMsK.js.map → top-web-COrMqTRC.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-9xsn2GGY.d.ts} +10 -3
- 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,211 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { a as readCommittedJsonLines, c as appendCommittedJsonLine } from "./jsonl-file-BhuxeejY.js";
|
|
4
|
-
import { n as detachedSnapshot } from "./snapshot-BKI_w3JD.js";
|
|
5
|
-
import { a as writeAtomicDurableFile, n as assertNoSymlinkDescendant, o as captureRunWriteContext } from "./durable-file-DstVeHcj.js";
|
|
6
|
-
import { agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
7
|
-
import { randomUUID } from "node:crypto";
|
|
1
|
+
import { d as writeAtomicDurableFile, o as assertNoSymlinkDescendant } from "./durable-file-lXnojyij.js";
|
|
2
|
+
import { D as workerCancellationsDir, p as appendWorkerControlEvent } from "./supervisor-accounting-CZ7i4cd5.js";
|
|
8
3
|
import { existsSync, mkdirSync, readFileSync, watch } from "node:fs";
|
|
9
|
-
import { join
|
|
10
|
-
// src/runtime/supervise/coordination-log.ts
|
|
11
|
-
/**
|
|
12
|
-
* Durable side-log for coordination evidence the spawn journal does not own: questions, analyst
|
|
13
|
-
* findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and
|
|
14
|
-
* delivery outcomes. A durable run
|
|
15
|
-
* (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted
|
|
16
|
-
* coordinator retains the exact evidence produced by prior processes.
|
|
17
|
-
*
|
|
18
|
-
* Answer down-events also fold status on load: a question answered before the crash reloads as
|
|
19
|
-
* `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their
|
|
20
|
-
* ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery
|
|
21
|
-
* window; that outcome remains unknown and no prior instruction is auto-delivered.
|
|
22
|
-
*
|
|
23
|
-
* JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file
|
|
24
|
-
* exactly as they share one spawn-journal file.
|
|
25
|
-
*
|
|
26
|
-
* @experimental
|
|
27
|
-
*/
|
|
28
|
-
/** Persist prior context plus exact continuation authorization, attempt, and result evidence.
|
|
29
|
-
* Settlements have their own journal. */
|
|
30
|
-
function persisted(event) {
|
|
31
|
-
return event.type !== "settled";
|
|
32
|
-
}
|
|
33
|
-
/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */
|
|
34
|
-
var FileCoordinationLog = class {
|
|
35
|
-
path;
|
|
36
|
-
writeContext = captureRunWriteContext();
|
|
37
|
-
appendTail = Promise.resolve();
|
|
38
|
-
constructor(path) {
|
|
39
|
-
this.path = path;
|
|
40
|
-
}
|
|
41
|
-
async append(runId, record, ownerId) {
|
|
42
|
-
if (!persisted(record.event)) return;
|
|
43
|
-
const append = this.appendTail.then(() => this.writeContext(() => this.appendRecord(runId, record, ownerId)));
|
|
44
|
-
this.appendTail = append.catch(() => void 0);
|
|
45
|
-
return append;
|
|
46
|
-
}
|
|
47
|
-
async appendRecord(runId, busRecord, ownerId) {
|
|
48
|
-
const fs = await import("node:fs/promises");
|
|
49
|
-
const { dirname } = await import("node:path");
|
|
50
|
-
await fs.mkdir(dirname(this.path), { recursive: true });
|
|
51
|
-
const record = {
|
|
52
|
-
runId,
|
|
53
|
-
...ownerId !== void 0 ? { ownerId } : {},
|
|
54
|
-
...busRecord
|
|
55
|
-
};
|
|
56
|
-
await appendCommittedJsonLine(this.path, record);
|
|
57
|
-
}
|
|
58
|
-
async load(runId, ownerId) {
|
|
59
|
-
return foldCoordinationRecords(readCommittedJsonLines(this.path, { allowMissing: true }), runId, ownerId);
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
/** @internal Shared replay semantics for file and SQL coordination evidence. */
|
|
63
|
-
async function foldCoordinationRecords(source, runId, ownerId) {
|
|
64
|
-
const byId = /* @__PURE__ */ new Map();
|
|
65
|
-
const findings = [];
|
|
66
|
-
const escalations = [];
|
|
67
|
-
const analystDefinitions = [];
|
|
68
|
-
const continuations = [];
|
|
69
|
-
const deliveryEvidence = [];
|
|
70
|
-
const mail = [];
|
|
71
|
-
const records = [];
|
|
72
|
-
let legacySeq = 0;
|
|
73
|
-
for await (const stored of source) {
|
|
74
|
-
if (stored.runId !== runId) continue;
|
|
75
|
-
if (ownerId !== void 0 && stored.ownerId !== ownerId) continue;
|
|
76
|
-
const record = "seq" in stored ? {
|
|
77
|
-
seq: stored.seq,
|
|
78
|
-
at: stored.at,
|
|
79
|
-
priority: stored.priority,
|
|
80
|
-
event: stored.event
|
|
81
|
-
} : {
|
|
82
|
-
seq: legacySeq++,
|
|
83
|
-
at: Date.parse(stored.at),
|
|
84
|
-
priority: 0,
|
|
85
|
-
event: stored.event
|
|
86
|
-
};
|
|
87
|
-
records.push(record);
|
|
88
|
-
const ev = record.event;
|
|
89
|
-
if (ev.type === "delivery-attempt" || ev.type === "steer" || ev.type === "answer") deliveryEvidence.push(ev);
|
|
90
|
-
if (ev.type === "question") byId.set(ev.question.id, ev.question);
|
|
91
|
-
else if (ev.type === "finding") findings.push(ev.finding);
|
|
92
|
-
else if (ev.type === "answer") {
|
|
93
|
-
const prior = byId.get(ev.questionId);
|
|
94
|
-
if (prior && ev.down.delivered) byId.set(ev.questionId, {
|
|
95
|
-
...prior,
|
|
96
|
-
status: "answered",
|
|
97
|
-
decision: {
|
|
98
|
-
kind: "answer",
|
|
99
|
-
answer: ev.down.instruction,
|
|
100
|
-
by: "prior-run"
|
|
101
|
-
}
|
|
102
|
-
});
|
|
103
|
-
} else if (ev.type === "instruction") continuations.push(ev.instruction);
|
|
104
|
-
else if (ev.type === "mail") mail.push(ev.mail);
|
|
105
|
-
else if (ev.type === "escalation") escalations.push(ev.escalation);
|
|
106
|
-
else if (ev.type === "analyst-defined") analystDefinitions.push(ev.analyst);
|
|
107
|
-
}
|
|
108
|
-
return {
|
|
109
|
-
...ownerId !== void 0 ? { ownerId } : {},
|
|
110
|
-
questions: [...byId.values()],
|
|
111
|
-
findings,
|
|
112
|
-
escalations,
|
|
113
|
-
analystDefinitions,
|
|
114
|
-
continuations,
|
|
115
|
-
deliveryEvidence,
|
|
116
|
-
mail,
|
|
117
|
-
records
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
// src/runtime/supervise/supervise-identity.ts
|
|
121
|
-
function externalExecutionId(kind, identity) {
|
|
122
|
-
return `${kind}-${canonicalCandidateDigest({
|
|
123
|
-
kind,
|
|
124
|
-
identity
|
|
125
|
-
}).slice(7)}`;
|
|
126
|
-
}
|
|
127
|
-
function freezeDetached(value) {
|
|
128
|
-
return detachedSnapshot(value, "supervise");
|
|
129
|
-
}
|
|
130
|
-
function freezeDetachedProfile(value) {
|
|
131
|
-
return freezeDetached(agentProfileSchema.parse(value));
|
|
132
|
-
}
|
|
133
|
-
function canonicalExecution(profile, task, rawExecution, context) {
|
|
134
|
-
const execution = rawExecution === void 0 ? void 0 : freezeDetached(rawExecution);
|
|
135
|
-
if (execution !== void 0) {
|
|
136
|
-
if (typeof execution !== "object" || execution === null || Array.isArray(execution)) throw new ValidationError(`${context}: execution must be an object`);
|
|
137
|
-
const unknown = Object.keys(execution).filter((key) => key !== "candidateDigest" && key !== "correlation");
|
|
138
|
-
if (unknown.length > 0) throw new ValidationError(`${context}: unknown execution fields: ${unknown.join(", ")}`);
|
|
139
|
-
}
|
|
140
|
-
const identity = deriveNodeExecutionIdentity({
|
|
141
|
-
profile,
|
|
142
|
-
execution
|
|
143
|
-
}, task);
|
|
144
|
-
if (!identity?.profileDigest || !identity.taskDigest) throw new ValidationError(`${context}: profile and task must be finite, acyclic canonical JSON for durable identity`);
|
|
145
|
-
const ref = identity.candidateDigest || identity.correlation ? Object.freeze({
|
|
146
|
-
...identity.candidateDigest ? { candidateDigest: identity.candidateDigest } : {},
|
|
147
|
-
...identity.correlation ? { correlation: identity.correlation } : {}
|
|
148
|
-
}) : void 0;
|
|
149
|
-
return {
|
|
150
|
-
identity,
|
|
151
|
-
...ref ? { ref } : {}
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
function rootCoordinationOwner(identity) {
|
|
155
|
-
return canonicalCandidateDigest({
|
|
156
|
-
kind: "supervisor-root",
|
|
157
|
-
identity
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
function childCoordinationOwner(parentOwnerId, identity, context, depth) {
|
|
161
|
-
return canonicalCandidateDigest({
|
|
162
|
-
kind: "supervisor-child",
|
|
163
|
-
parentOwnerId,
|
|
164
|
-
identity,
|
|
165
|
-
assignment: {
|
|
166
|
-
id: context.assignmentId,
|
|
167
|
-
label: context.label,
|
|
168
|
-
key: context.key ?? null,
|
|
169
|
-
depth
|
|
170
|
-
}
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
function supervisionRunNamespace(runDir, runId) {
|
|
174
|
-
return canonicalCandidateDigest(runDir === void 0 ? {
|
|
175
|
-
kind: "supervise-ephemeral-run",
|
|
176
|
-
runId,
|
|
177
|
-
nonce: randomUUID()
|
|
178
|
-
} : {
|
|
179
|
-
kind: "supervise-durable-run",
|
|
180
|
-
runId,
|
|
181
|
-
runDir: resolve(runDir)
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
function workerAssignmentNamespace(runNamespace, parentOwnerId, assignmentId) {
|
|
185
|
-
return canonicalCandidateDigest({
|
|
186
|
-
kind: "supervise-worker-assignment",
|
|
187
|
-
runNamespace,
|
|
188
|
-
parentOwnerId,
|
|
189
|
-
assignmentId
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
/** Hash only durable coordination meaning. Bus sequence/timestamp are delivery metadata and a
|
|
193
|
-
* resumed projection's marker describes the reader, not the original settlement. */
|
|
194
|
-
function coordinationEventId(context, event) {
|
|
195
|
-
const durableEvent = event.type === "settled" && event.worker.resumed === true ? (() => {
|
|
196
|
-
const { resumed: _resumed, ...worker } = event.worker;
|
|
197
|
-
return {
|
|
198
|
-
type: "settled",
|
|
199
|
-
worker
|
|
200
|
-
};
|
|
201
|
-
})() : event;
|
|
202
|
-
return canonicalCandidateDigest({
|
|
203
|
-
kind: "supervise-coordination-event",
|
|
204
|
-
runNamespace: context.runNamespace,
|
|
205
|
-
ownerId: context.ownerId,
|
|
206
|
-
event: detachedSnapshot(durableEvent, "supervise coordination event identity")
|
|
207
|
-
});
|
|
208
|
-
}
|
|
4
|
+
import { join } from "node:path";
|
|
209
5
|
// src/runtime/supervise/run-cancellation.ts
|
|
210
6
|
/** Apply a durable request through the run's existing abort controller. */
|
|
211
7
|
function applyRunCancellation(dir, abortRun, now, path = "turn-boundary") {
|
|
@@ -428,6 +224,6 @@ function assertRunCancellationMatchesCandidate(existing, candidate) {
|
|
|
428
224
|
function isRunCancelRequest(value) {
|
|
429
225
|
return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.at === "string" && typeof value.source === "string" && (value.deadlineMs === void 0 || Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0) && (value.reason === void 0 || typeof value.reason === "string") && (value.operator === void 0 || typeof value.operator === "string");
|
|
430
226
|
}
|
|
431
|
-
export {
|
|
227
|
+
export { runCancelRequestFile as a, writeRunCancellation as c, readRunCancellation as i, cancelRun as n, runCancellationFile as o, readRunCancelRequest as r, watchRunCancellation as s, applyRunCancellation as t };
|
|
432
228
|
|
|
433
|
-
//# sourceMappingURL=run-cancellation-
|
|
229
|
+
//# sourceMappingURL=run-cancellation-D3qc9wAD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-cancellation-D3qc9wAD.js","names":[],"sources":["../src/runtime/supervise/run-cancellation.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, watch } from 'node:fs'\nimport { join } from 'node:path'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport { assertNoSymlinkDescendant, writeAtomicDurableFile } from './durable-file'\nimport { appendWorkerControlEvent, workerCancellationsDir } from './run-layout'\n\n/** Apply a durable request through the run's existing abort controller. */\nexport function applyRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: 'observer' | 'turn-boundary' | 'fallback' = 'turn-boundary',\n): RunCancellation | undefined {\n const request = readRunCancelRequest(dir)\n if (request === undefined) return undefined\n const prior = readRunCancellation(dir, request.operationId)\n // A request acknowledged only as `cancel_requested` is still owed by this run: the process\n // that issued the abort died before the run settled. Abort again; the record stands.\n if (prior?.effect === 'cancel_requested') {\n abortRun(request.reason ?? 'run cancel requested', request)\n }\n if (prior !== undefined) return prior\n abortRun(request.reason ?? 'run cancel requested', request)\n const observedAt = now()\n const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at))\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n path,\n appliedAfterMs,\n ...(request.deadlineMs === undefined\n ? {}\n : { deadlineExceeded: appliedAfterMs > request.deadlineMs }),\n requestedAt: request.at,\n observedAt,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n writeRunCancellation(dir, record)\n return record\n}\n\n/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */\nexport function watchRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n createWatch: typeof watch = watch,\n) {\n mkdirSync(workerCancellationsDir(dir), { recursive: true })\n let active = true\n let failure: unknown\n // One observer aborts its run once: a request this process already applied, or one a dead\n // process acknowledged, is not re-issued on every poll.\n let aborted = false\n const abortOnce = (reason: string, request?: RunCancelRequest): void => {\n if (aborted) return\n aborted = true\n abortRun(reason, request)\n }\n const check = (path: 'observer' | 'fallback' = 'observer'): void => {\n if (failure !== undefined) throw failure\n if (active) applyRunCancellation(dir, abortOnce, () => new Date().toISOString(), path)\n }\n const fail = (error: unknown): void => {\n if (!active) return\n failure = error\n abortRun(`durable run cancellation observer failed: ${String(error)}`)\n }\n // The watcher is an optimization over the poll loop below (instant pickup instead of ≤100 ms).\n // Creating it can fail for reasons that say NOTHING about this run: the host's inotify budget is\n // exhausted (EMFILE — a shared box with many agents held ~110 of the 128 default user instances\n // when this was measured), or the kernel caps watches (ENOSPC). Degrading to poll-only keeps\n // every durable behavior; failing the run would make a neighboring process's resource use kill\n // runs that never touched the limit. Any other creation error still fails loudly.\n let watcher: ReturnType<typeof watch> | undefined\n try {\n watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {\n if (!active || (filename !== null && filename !== 'run.request.json')) return\n try {\n check()\n } catch (error) {\n fail(error)\n }\n })\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EMFILE' && code !== 'ENOSPC') throw error\n }\n watcher?.on('error', fail)\n // Filesystem notifications are advisory. Scan the same durable inbox when one is dropped —\n // and carry the whole observer alone whenever the watcher above could not be created.\n const fallback = setInterval(() => {\n try {\n check('fallback')\n } catch (error) {\n fail(error)\n }\n }, 100)\n fallback.unref()\n return {\n check,\n close(): void {\n active = false\n watcher?.close()\n clearInterval(fallback)\n },\n }\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Requested observation target, measured by the acknowledgement's deadlineExceeded field.\n * The observer always cascades eagerly. This does not guarantee scheduler latency or cleanup. */\n readonly deadlineMs?: number\n /** Who stops the run. `cancelRun` requires it on every new request; it is optional here only\n * so a request written before that rule still reads. The settle record carries it. */\n readonly operator?: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal cancelled state with confirmed teardown.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n /** Runtime path that issued the cascade. */\n readonly path?: 'observer' | 'turn-boundary' | 'fallback'\n /** Runtime clock elapsed between request timestamp and cascade application. */\n readonly appliedAfterMs?: number\n /** Whether application exceeded the requested deadlineMs; absent when no target was requested. */\n readonly deadlineExceeded?: boolean\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The caller's operator identity, carried verbatim from the request. */\n readonly operator?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n}\n\n/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */\nexport function runCancelRequestFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.request.json')\n}\n\n/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */\nexport function runCancellationFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.json')\n}\n\n/** Read the run-scoped cancel request, or `undefined` when none was written. */\nexport function readRunCancelRequest(eventDir: string): RunCancelRequest | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RunCancelRequest>\n if (!isRunCancelRequest(parsed)) {\n throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`)\n }\n return parsed\n}\n\n/**\n * Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has\n * not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the\n * same run — fail loud rather than answer for it.\n */\nexport function readRunCancellation(\n eventDir: string,\n operationId: string,\n): RunCancellation | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not ` +\n `'${operationId}' — one run carries one run-scoped cancel operation`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write the run-scoped acknowledgement. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\n *\n * @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}\n * or {@link cancelRun}.\n */\nexport function writeRunCancellation(eventDir: string, record: RunCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n writeAtomicDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A retry that changes the source, reason, deadline, or operator\n * fails closed. A request the runtime has not answered yet returns `effect: 'unknown'` (never a\n * success); call again with the same `operationId` — or {@link readRunCancellation} — to read the\n * acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n * Reopening a settled run (`supervisePursuit`'s `reopen`) moves that operation aside.\n *\n * A NEW request must name its `operator`, so every stop says who made it. A replay of a request\n * or acknowledgement written before that rule is answered as it was.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n options: {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n readonly operator?: string\n } = {},\n): RunCancellation {\n if (\n options.deadlineMs !== undefined &&\n (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)\n ) {\n throw new Error('cancelRun: deadlineMs must be a finite nonnegative number')\n }\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const candidate = {\n operationId: opId,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending !== undefined) assertSameRunCancelRequest(pending, candidate)\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelRun: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertRunCancellationMatchesCandidate(acknowledged, candidate)\n return acknowledged\n }\n // A new request names who stops the run. A replay of a request written before this rule keeps\n // its absent operator: it was admitted above against the file it replays.\n if (pending === undefined && (options.operator === undefined || options.operator.trim() === '')) {\n throw new Error('cancelRun: operator is required; name who stops the run')\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n }\n if (pending === undefined) {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n writeAtomicDurableFile(file, `${JSON.stringify(request, null, 2)}\\n`, { mode: 0o600 })\n appendWorkerControlEvent(eventDir, 'run', {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n ...(options.operator === undefined ? {} : { operator: options.operator }),\n })\n }\n return {\n operationId: opId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype RunCancelRequestCandidate = Omit<RunCancelRequest, 'at'>\n\nfunction assertSameRunCancelRequest(\n existing: RunCancelRequest,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.deadlineMs !== candidate.deadlineMs) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n if (existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction assertRunCancellationMatchesCandidate(\n existing: RunCancellation,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n // An acknowledgement written before acknowledgements carried the operator (0.251.0) names none\n // even when its admitted request does. The request comparator has already held the candidate\n // to that request, so a legacy record matches any candidate operator; a record that names one\n // must name the same one.\n if (existing.operator !== undefined && existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\n )\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.deadlineMs === undefined ||\n (Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0)) &&\n (value.reason === undefined || typeof value.reason === 'string') &&\n (value.operator === undefined || typeof value.operator === 'string')\n )\n}\n"],"mappings":";;;;;;AAOA,SAAgB,qBACd,KACA,UACA,KACA,OAAkD,iBACrB;CAC7B,MAAM,UAAU,qBAAqB,GAAG;CACxC,IAAI,YAAY,KAAA,GAAW,OAAO,KAAA;CAClC,MAAM,QAAQ,oBAAoB,KAAK,Q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AM,gBAAgB,YAC7B,MAAM,YAAY,SAAS,KAC3B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,aACvB,MAAM,eAAe,KAAA,KACnB,OAAO,SAAS,MAAM,UAAU,KAAK,MAAM,cAAc,OAC3D,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW,cACtD,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa;AAE/D"}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { C as mutateRunClaim, T as runWithWriteClaim, d as writeAtomicDurableFile, g as registerDurableErrorClass, s as publishExclusiveDurableFile, w as runGenerationPath, y as runFencedAlways } from "./durable-file-lXnojyij.js";
|
|
2
|
+
import { t as isNoEntError } from "./jsonl-file-DyzefaZ6.js";
|
|
3
|
+
import { setTimeout } from "node:timers/promises";
|
|
4
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { lockHolderVerdict, lockIdentity, parseLockHolderRecord, readLockHolderIdentity } from "@tangle-network/agent-eval/lock-holder";
|
|
7
|
+
// src/durable/run-lock.ts
|
|
8
|
+
/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */
|
|
9
|
+
const RUN_DIRECTORY_LOCK_FILE = "supervise.lock";
|
|
10
|
+
/** The directory is held by a live process. `holder` is what that process recorded. */
|
|
11
|
+
var RunDirectoryLockedError = class extends Error {
|
|
12
|
+
path;
|
|
13
|
+
holder;
|
|
14
|
+
constructor(path, holder) {
|
|
15
|
+
super(`supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`);
|
|
16
|
+
this.name = "RunDirectoryLockedError";
|
|
17
|
+
this.path = path;
|
|
18
|
+
this.holder = holder;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
registerDurableErrorClass("RunDirectoryLockedError", RunDirectoryLockedError);
|
|
22
|
+
/**
|
|
23
|
+
* Take `runDir/supervise.lock`, or refuse.
|
|
24
|
+
*
|
|
25
|
+
* The file is published with its full content or not at all, so a contender never reads a
|
|
26
|
+
* half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now
|
|
27
|
+
* belongs to a process with a different start token, or the host rebooted) is stale and is removed
|
|
28
|
+
* under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file
|
|
29
|
+
* names no holder and is reclaimed. A file with unreadable content is left in place and refused:
|
|
30
|
+
* reclaiming it could evict a live holder written by something other than this module.
|
|
31
|
+
*/
|
|
32
|
+
async function acquireRunDirectoryLock(runDir, runId, now = Date.now) {
|
|
33
|
+
const dir = resolve(runDir);
|
|
34
|
+
const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE);
|
|
35
|
+
mkdirSync(dir, { recursive: true });
|
|
36
|
+
const { pid, ...identity } = readLockHolderIdentity(process.pid);
|
|
37
|
+
const owner = {
|
|
38
|
+
pid,
|
|
39
|
+
startedAt: new Date(now()).toISOString(),
|
|
40
|
+
runId,
|
|
41
|
+
...identity
|
|
42
|
+
};
|
|
43
|
+
const holder = await runFencedAlways("acquireRunLock", acquireRunLockFenced, dir, path, owner);
|
|
44
|
+
const generation = holder.generation;
|
|
45
|
+
if (generation === void 0) throw new Error(`supervisePursuit: ${path} was taken without a generation`);
|
|
46
|
+
let released = false;
|
|
47
|
+
return Object.freeze({
|
|
48
|
+
...holder,
|
|
49
|
+
generation,
|
|
50
|
+
path,
|
|
51
|
+
run: (operation) => {
|
|
52
|
+
if (holder.lock === void 0) throw new Error("run lock has no inode identity");
|
|
53
|
+
return runWithWriteClaim({
|
|
54
|
+
path,
|
|
55
|
+
generation,
|
|
56
|
+
lock: holder.lock
|
|
57
|
+
}, operation);
|
|
58
|
+
},
|
|
59
|
+
release: async () => {
|
|
60
|
+
if (released) return;
|
|
61
|
+
await releaseHolder(path, holder);
|
|
62
|
+
released = true;
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Take the run directory under its mutation lock and return the holder record it wrote. @internal */
|
|
67
|
+
function acquireRunLockFenced(dir, path, owner) {
|
|
68
|
+
return mutateRunClaim(path, () => {
|
|
69
|
+
const existing = readLockFile(path);
|
|
70
|
+
if (existing.state === "holder" && !holderIsDead(existing)) throw new RunDirectoryLockedError(path, existing.holder);
|
|
71
|
+
let previousGeneration = 0;
|
|
72
|
+
try {
|
|
73
|
+
previousGeneration = Number(readFileSync(runGenerationPath(dir), "utf8"));
|
|
74
|
+
if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) throw new Error("invalid run directory generation counter");
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (!isNoEntError(error)) throw error;
|
|
77
|
+
}
|
|
78
|
+
const generation = Math.max(previousGeneration, existing.state === "holder" ? existing.holder.generation ?? 0 : 0) + 1;
|
|
79
|
+
if (!Number.isSafeInteger(generation)) throw new Error("run directory generation exhausted");
|
|
80
|
+
writeAtomicDurableFile(runGenerationPath(dir), `${generation}\n`);
|
|
81
|
+
if (existing.state !== "missing") removeIfPresent(path);
|
|
82
|
+
const written = {};
|
|
83
|
+
if (!publishExclusiveDurableFile(path, (file) => {
|
|
84
|
+
written.holder = Object.freeze({
|
|
85
|
+
...owner,
|
|
86
|
+
generation,
|
|
87
|
+
lock: lockIdentity(file)
|
|
88
|
+
});
|
|
89
|
+
return `${JSON.stringify(written.holder)}\n`;
|
|
90
|
+
}) || written.holder === void 0) throw new Error(`supervisePursuit: could not take ${path}`);
|
|
91
|
+
return written.holder;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/** Read the holder a lock file names, or `undefined` when no lock file names one. */
|
|
95
|
+
async function readRunDirectoryLock(runDir) {
|
|
96
|
+
const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE));
|
|
97
|
+
return existing.state === "holder" ? existing.holder : void 0;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Whether a run directory is still held by the live process that took its lock.
|
|
101
|
+
*
|
|
102
|
+
* The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a
|
|
103
|
+
* caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks
|
|
104
|
+
* the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a
|
|
105
|
+
* live holder from an unrelated process that later took the same pid, which is the failure this
|
|
106
|
+
* lock's start token exists to prevent.
|
|
107
|
+
*
|
|
108
|
+
* The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,
|
|
109
|
+
* so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take
|
|
110
|
+
* the directory in between. Reporting and listing are what this is for. A caller that intends to
|
|
111
|
+
* TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the
|
|
112
|
+
* guard and refuses atomically.
|
|
113
|
+
*/
|
|
114
|
+
async function runDirectoryHolderIsLive(runDir) {
|
|
115
|
+
const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE));
|
|
116
|
+
if (existing.state !== "holder") return { live: false };
|
|
117
|
+
const verdict = lockHolderVerdict(existing.record, existing.current);
|
|
118
|
+
return {
|
|
119
|
+
live: verdict.liveness !== "dead",
|
|
120
|
+
holder: existing.holder,
|
|
121
|
+
...verdict.liveness === "unknown" ? { unknown: true } : {}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function readLockFile(path) {
|
|
125
|
+
let text;
|
|
126
|
+
let current;
|
|
127
|
+
try {
|
|
128
|
+
const file = openSync(path, "r");
|
|
129
|
+
try {
|
|
130
|
+
current = lockIdentity(fstatSync(file, { bigint: true }));
|
|
131
|
+
text = readFileSync(file, "utf8");
|
|
132
|
+
} finally {
|
|
133
|
+
closeSync(file);
|
|
134
|
+
}
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (isNoEntError(error)) return { state: "missing" };
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
if (text.trim().length === 0) return { state: "empty" };
|
|
140
|
+
let parsed;
|
|
141
|
+
try {
|
|
142
|
+
parsed = JSON.parse(text);
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, { cause });
|
|
145
|
+
}
|
|
146
|
+
const record = parsed;
|
|
147
|
+
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`);
|
|
148
|
+
const { pid, startedAt, runId, processStart } = record;
|
|
149
|
+
const verdictRecord = parseLockHolderRecord(parsed);
|
|
150
|
+
const { pid: _pid, ...identity } = verdictRecord ?? { pid };
|
|
151
|
+
return {
|
|
152
|
+
state: "holder",
|
|
153
|
+
holder: Object.freeze({
|
|
154
|
+
pid,
|
|
155
|
+
startedAt,
|
|
156
|
+
runId,
|
|
157
|
+
...record.generation === void 0 ? {} : { generation: record.generation },
|
|
158
|
+
...processStart === void 0 ? {} : { processStart },
|
|
159
|
+
...identity
|
|
160
|
+
}),
|
|
161
|
+
record: verdictRecord,
|
|
162
|
+
current
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */
|
|
166
|
+
function holderIsDead(existing) {
|
|
167
|
+
return lockHolderVerdict(existing.record, existing.current).liveness === "dead";
|
|
168
|
+
}
|
|
169
|
+
/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */
|
|
170
|
+
async function releaseHolder(path, holder) {
|
|
171
|
+
const deadline = performance.now() + 1e3;
|
|
172
|
+
while (existsSync(`${path}.guard`) && performance.now() < deadline) await setTimeout(10);
|
|
173
|
+
await runFencedAlways("releaseRunLock", releaseRunLockFenced, path, holder);
|
|
174
|
+
}
|
|
175
|
+
/** Remove the lock under its mutation lock while it still names `holder`. @internal */
|
|
176
|
+
function releaseRunLockFenced(path, holder) {
|
|
177
|
+
mutateRunClaim(path, () => {
|
|
178
|
+
const existing = readLockFile(path);
|
|
179
|
+
if (existing.state !== "holder") return;
|
|
180
|
+
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;
|
|
181
|
+
removeIfPresent(path);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
function removeIfPresent(path) {
|
|
185
|
+
try {
|
|
186
|
+
unlinkSync(path);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (!isNoEntError(error)) throw error;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
export { readRunDirectoryLock as a, acquireRunLockFenced as i, RunDirectoryLockedError as n, releaseRunLockFenced as o, acquireRunDirectoryLock as r, runDirectoryHolderIsLive as s, RUN_DIRECTORY_LOCK_FILE as t };
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=run-lock-D1xnb9ve.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-lock-D1xnb9ve.js","names":["delay"],"sources":["../src/durable/run-lock.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 { registerDurableErrorClass, runFencedAlways } from './durable-writer'\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\nregisterDurableErrorClass('RunDirectoryLockedError', RunDirectoryLockedError)\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 // The whole critical section, generation decision and holder record included, runs on the\n // durable writer: the one thread that takes this directory's mutation lock in this process.\n const holder = await runFencedAlways('acquireRunLock', acquireRunLockFenced, dir, path, owner)\n const generation = holder.generation\n if (generation === undefined)\n throw new Error(`supervisePursuit: ${path} was taken without a generation`)\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/** Take the run directory under its mutation lock and return the holder record it wrote. @internal */\nexport function acquireRunLockFenced(\n dir: string,\n path: string,\n owner: Omit<RunDirectoryLockHolder, 'generation' | 'lock'>,\n): RunDirectoryLockHolder {\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 if (!published || written.holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n return written.holder\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 await runFencedAlways('releaseRunLock', releaseRunLockFenced, path, holder)\n}\n\n/** Remove the lock under its mutation lock while it still names `holder`. @internal */\nexport function releaseRunLockFenced(path: string, holder: RunDirectoryLockHolder): void {\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"],"mappings":";;;;;;;;AAmDA,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;AAEA,0BAA0B,2BAA2B,uBAAuB;;;;;;;;;;;AAY5E,eAAsB,wBACpB,QACA,OACA,MAAoB,KAAK,KACE;CAC3B,MAAM,MAAM,QAAQ,MAAM;CAC1B,MAAM,OAAO,QAAQ,KAAK,uBAAuB;CACjD,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;CAClC,MAAM,EAAE,KAAK,GAAG,aAAa,uBAAuB,QAAQ,GAAG;CAC/D,MAAM,QAAQ;EAAE;EAAK,WAAW,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,YAAY;EAAG;EAAO,GAAG;CAAS;CAGlF,MAAM,SAAS,MAAM,gBAAgB,kBAAkB,sBAAsB,KAAK,MAAM,KAAK;CAC7F,MAAM,aAAa,OAAO;CAC1B,IAAI,eAAe,KAAA,GACjB,MAAM,IAAI,MAAM,qBAAqB,KAAK,gCAAgC;CAC5E,IAAI,WAAW;CACf,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA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S,OAAO,MAAM,gBAAgB,OAAO,MAAM,aAEnD;EACF,gBAAgB,IAAI;CACtB,CAAC;AACH;AAEA,SAAS,gBAAgB,MAAoB;CAC3C,IAAI;EACF,WAAW,IAAI;CACjB,SAAS,OAAO;EACd,IAAI,CAAC,aAAa,KAAK,GAAG,MAAM;CAClC;AACF"}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { S as fenceRunWrite, s as publishExclusiveDurableFile, u as syncDurableDirectory, v as runFenced } from "./durable-file-lXnojyij.js";
|
|
2
|
+
import { a as runCancelRequestFile, o as runCancellationFile } from "./run-cancellation-D3qc9wAD.js";
|
|
3
|
+
import { D as workerCancellationsDir, Y as FileSpawnJournal } from "./supervisor-accounting-CZ7i4cd5.js";
|
|
4
|
+
import { nt as assertValidBudget } from "./failure-cause-DoCCGLDH.js";
|
|
5
|
+
import { n as assertResumeLimits } from "./supervisor-root-contract-D70KTGXF.js";
|
|
6
|
+
import { n as SETTLE_RECORD_FILE, s as settleRecordDigest } from "./settle-record-au3w7bQG.js";
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync } from "node:fs";
|
|
8
|
+
import { join, resolve } from "node:path";
|
|
9
|
+
import { readFile } from "node:fs/promises";
|
|
10
|
+
// src/durable/run-reopen.ts
|
|
11
|
+
/** The directory that holds a run's archived settle records. */
|
|
12
|
+
const SETTLE_ARCHIVE_DIR = "settles";
|
|
13
|
+
/** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */
|
|
14
|
+
function assertRunReopen(reopen, opts) {
|
|
15
|
+
if (reopen.operator.trim().length === 0) throw new TypeError("supervisePursuit: reopen.operator must be non-empty");
|
|
16
|
+
if (reopen.reason.trim().length === 0) throw new TypeError("supervisePursuit: reopen.reason must be non-empty");
|
|
17
|
+
if (reopen.operationId.trim().length === 0) throw new TypeError("supervisePursuit: reopen.operationId must be non-empty");
|
|
18
|
+
if (reopen.budget !== void 0) assertValidBudget(reopen.budget, "reopen.budget");
|
|
19
|
+
if (opts.fork !== void 0 || opts.versions !== void 0) throw new TypeError("supervisePursuit: reopen continues this run under its own id; fork and versions start new runs");
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the
|
|
23
|
+
* directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a
|
|
24
|
+
* segment that has since settled again.
|
|
25
|
+
*/
|
|
26
|
+
async function reopenSettledRun(input) {
|
|
27
|
+
const { runDir, runId, reopen, observer, pursuitId, now } = input;
|
|
28
|
+
const operationId = reopen.operationId.trim();
|
|
29
|
+
const settlePath = resolve(runDir, SETTLE_RECORD_FILE);
|
|
30
|
+
const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, "spawn-journal.jsonl"));
|
|
31
|
+
const events = await journal.loadTree(runId) ?? [];
|
|
32
|
+
const reopened = events.filter((event) => event.kind === "reopened" && event.id === runId);
|
|
33
|
+
const mine = reopened.find((event) => event.operationId === operationId);
|
|
34
|
+
const settled = await readBytes(settlePath);
|
|
35
|
+
if (settled === void 0) {
|
|
36
|
+
if (mine !== void 0) return;
|
|
37
|
+
throw new Error(`supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`);
|
|
38
|
+
}
|
|
39
|
+
assertResumeLimits(events, {
|
|
40
|
+
runId,
|
|
41
|
+
budget: reopen.budget ?? input.limits.budget,
|
|
42
|
+
...input.limits.reservationPolicy === void 0 ? {} : { reservationPolicy: input.limits.reservationPolicy }
|
|
43
|
+
}, mine === void 0 ? reopen.budget : void 0);
|
|
44
|
+
const result = JSON.parse(settled);
|
|
45
|
+
const digest = settleRecordDigest(result);
|
|
46
|
+
if (mine !== void 0 && mine.prior.digest !== digest) throw new Error(`supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`);
|
|
47
|
+
const archivedAs = mine?.prior.archivedAs ?? await archiveName(runDir, settled);
|
|
48
|
+
const archivePath = resolve(runDir, archivedAs);
|
|
49
|
+
if (!publishExclusiveDurableFile(archivePath, settled) && await readBytes(archivePath) !== settled) throw new Error(`supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`);
|
|
50
|
+
const at = new Date(now()).toISOString();
|
|
51
|
+
if (mine === void 0) await journal.appendEvent(runId, {
|
|
52
|
+
kind: "reopened",
|
|
53
|
+
id: runId,
|
|
54
|
+
operator: reopen.operator,
|
|
55
|
+
reason: reopen.reason,
|
|
56
|
+
operationId,
|
|
57
|
+
prior: {
|
|
58
|
+
kind: String(result.kind),
|
|
59
|
+
...typeof result.reason === "string" ? { reason: result.reason } : {},
|
|
60
|
+
digest,
|
|
61
|
+
archivedAs
|
|
62
|
+
},
|
|
63
|
+
...reopen.budget === void 0 ? {} : { budget: reopen.budget },
|
|
64
|
+
seq: reopened.length,
|
|
65
|
+
at
|
|
66
|
+
});
|
|
67
|
+
const eventId = `${runId}:pursuit:reopened:${operationId}`;
|
|
68
|
+
if (!(await observer.read()).some((record) => record.event?.id === eventId)) await observer.appendEvent({
|
|
69
|
+
id: eventId,
|
|
70
|
+
pursuitId,
|
|
71
|
+
runId,
|
|
72
|
+
target: "agent.run",
|
|
73
|
+
phase: "event",
|
|
74
|
+
timestamp: now(),
|
|
75
|
+
payload: { reopened: {
|
|
76
|
+
operator: reopen.operator,
|
|
77
|
+
reason: reopen.reason,
|
|
78
|
+
archivedAs
|
|
79
|
+
} }
|
|
80
|
+
});
|
|
81
|
+
runFenced("reopenSettle", reopenSettleFenced, runDir, operationId, settlePath);
|
|
82
|
+
}
|
|
83
|
+
/** Set the settled run's cancellation aside and remove its settle record, under the fence. @internal */
|
|
84
|
+
function reopenSettleFenced(runDir, operationId, settlePath) {
|
|
85
|
+
fenceRunWrite(() => {
|
|
86
|
+
setCancellationAside(runDir, operationId);
|
|
87
|
+
unlinkSync(settlePath);
|
|
88
|
+
syncDurableDirectory(runDir);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that
|
|
92
|
+
* crashed after archiving and before its journal row). */
|
|
93
|
+
async function archiveName(runDir, settled) {
|
|
94
|
+
const dir = resolve(runDir, SETTLE_ARCHIVE_DIR);
|
|
95
|
+
runFenced("makeRunDirectory", makeRunDirectoryFenced, dir);
|
|
96
|
+
const numbers = readdirSync(dir).map((name) => /^(\d+)\.json$/u.exec(name)?.[1]).filter((n) => n !== void 0).map(Number).sort((a, b) => a - b);
|
|
97
|
+
for (const n of numbers) if (await readBytes(join(dir, `${n}.json`)) === settled) return `${SETTLE_ARCHIVE_DIR}/${n}.json`;
|
|
98
|
+
return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`;
|
|
99
|
+
}
|
|
100
|
+
/** Move the settled run's cancel request and acknowledgement aside under the reopen's and the
|
|
101
|
+
* request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent
|
|
102
|
+
* file is skipped. A reopen's operation id names one segment, so a later segment cancelled under
|
|
103
|
+
* the same cancel operation id lands beside this one instead of over it. */
|
|
104
|
+
function setCancellationAside(runDir, reopenOperationId) {
|
|
105
|
+
const requestFile = runCancelRequestFile(runDir);
|
|
106
|
+
const ackFile = runCancellationFile(runDir);
|
|
107
|
+
if (!existsSync(requestFile) && !existsSync(ackFile)) return;
|
|
108
|
+
const source = existsSync(requestFile) ? requestFile : ackFile;
|
|
109
|
+
const { operationId } = JSON.parse(readFileSync(source, "utf8"));
|
|
110
|
+
const reopenedDir = join(workerCancellationsDir(runDir), "reopened");
|
|
111
|
+
const aside = join(reopenedDir, encodeURIComponent(reopenOperationId), encodeURIComponent(operationId));
|
|
112
|
+
mkdirSync(aside, { recursive: true });
|
|
113
|
+
if (existsSync(ackFile)) renameSync(ackFile, join(aside, "run.json"));
|
|
114
|
+
if (existsSync(requestFile)) renameSync(requestFile, join(aside, "run.request.json"));
|
|
115
|
+
syncDurableDirectory(aside);
|
|
116
|
+
syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)));
|
|
117
|
+
syncDurableDirectory(reopenedDir);
|
|
118
|
+
syncDurableDirectory(workerCancellationsDir(runDir));
|
|
119
|
+
}
|
|
120
|
+
async function readBytes(path) {
|
|
121
|
+
try {
|
|
122
|
+
return await readFile(path, "utf8");
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error.code === "ENOENT") return void 0;
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Create a directory inside the run under the fence. @internal */
|
|
129
|
+
function makeRunDirectoryFenced(dir) {
|
|
130
|
+
fenceRunWrite(() => mkdirSync(dir, { recursive: true }));
|
|
131
|
+
}
|
|
132
|
+
export { reopenSettledRun as i, makeRunDirectoryFenced as n, reopenSettleFenced as r, assertRunReopen as t };
|
|
133
|
+
|
|
134
|
+
//# sourceMappingURL=run-reopen-DVM5AEKV.js.map
|