@cotal-ai/manager 0.168.0 → 0.169.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1068 @@
1
+ import { jetstream } from "@nats-io/jetstream";
2
+ import { EpEnvelopeError, rejectionText, digestIdToken, submissionFingerprint, goalRefOf, bindGoal, createGoal, recordGoalIndex, clearGoalIndex, readGoalResult, readGoalStatus, readGoalSpec, commitGoalResult, requestGoalCancel, goalAlreadyTerminal, transitionGoal, settleGoalUncertain, GOAL_TERMINAL_STATES, MAX_SCHEDULE_MS, mintCheckpoint, resumeCheckpoint, readCheckpointSettle, readCheckpointSpec, expireCheckpoint, } from "@cotal-ai/core";
3
+ import { MANAGER_ENDPOINT } from "./manager-service-contract.js";
4
+ /** Cadence of the turn-deadline sweep while turns are pending: the poll that turns an elapsed
5
+ * hold's fire into its expired settle and commits the deadline terminal. Deadlines are
6
+ * minutes-scale; a few seconds of lateness on the commit is invisible to the run. */
7
+ const TURN_SWEEP_MS = 5_000;
8
+ /** How long a settled turn's answer is kept so a RETRIED yield hears it instead of `not-found`.
9
+ * The window a lost reply is retried in is seconds; five minutes is generous for that and short
10
+ * enough that the map drains between bursts rather than growing for the process lifetime. */
11
+ export const TURN_ANSWER_RETENTION_MS = 5 * 60_000;
12
+ /** The cancel reason of an inherited once task whose spawn has no succeeded terminal. */
13
+ const NEVER_SERVED = "never served: the manager restarted before the spawn's readiness verdict";
14
+ /** Said by every settle of an inherited once task whose seat this manager does not hold. */
15
+ const UNHELD_SEAT = "the manager does not hold the seat; it may still be running";
16
+ function parseTurnNote(raw) {
17
+ let o;
18
+ try {
19
+ o = JSON.parse(raw);
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ if (o === null || typeof o !== "object")
25
+ return undefined;
26
+ const n = o;
27
+ if (n.once !== undefined && n.once !== true)
28
+ return undefined;
29
+ if (typeof n.payload !== "string" || typeof n.holdEpoch !== "number")
30
+ return undefined;
31
+ if (typeof n.deadlineAt !== "number" && !(n.once === true && n.deadlineAt === undefined))
32
+ return undefined;
33
+ if (n.holdToken !== undefined && typeof n.holdToken !== "string")
34
+ return undefined;
35
+ if (n.handoffFrom !== undefined && typeof n.handoffFrom !== "string")
36
+ return undefined;
37
+ if (n.retire !== undefined && (n.once !== true || typeof n.retire !== "string"))
38
+ return undefined;
39
+ if (n.spawn !== undefined && (n.once !== true || typeof n.spawn !== "string"))
40
+ return undefined;
41
+ return {
42
+ payload: n.payload, holdEpoch: n.holdEpoch,
43
+ ...(typeof n.deadlineAt === "number" ? { deadlineAt: n.deadlineAt } : {}),
44
+ ...(typeof n.holdToken === "string" ? { holdToken: n.holdToken } : {}),
45
+ ...(typeof n.handoffFrom === "string" ? { handoffFrom: n.handoffFrom } : {}),
46
+ ...(n.once === true ? { once: true } : {}),
47
+ ...(typeof n.retire === "string" ? { retire: n.retire } : {}),
48
+ ...(typeof n.spawn === "string" ? { spawn: n.spawn } : {}),
49
+ };
50
+ }
51
+ function retireOf(d) {
52
+ return d.retire === undefined ? undefined : { connector: d.retire, name: d.seat.name, uid: d.seat.uid };
53
+ }
54
+ /** The relay record of a `once` task. The prompt is only ever the string value of `context`, so a
55
+ * prompt shaped like a run payload stays text and cannot add an `ask` or a `checkpoint`; the
56
+ * `once` block is the manager's, rendered by the seat beside the prompt. */
57
+ export function onceTurnNote(o) {
58
+ const payload = JSON.stringify({ context: o.prompt, once: { spawner: o.spawner, ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}) } });
59
+ const note = JSON.stringify({
60
+ payload, holdEpoch: o.holdEpoch,
61
+ ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}),
62
+ ...(o.holdToken !== undefined ? { holdToken: o.holdToken } : {}),
63
+ once: true,
64
+ ...(o.retire !== undefined ? { retire: o.retire } : {}),
65
+ spawn: o.spawn,
66
+ });
67
+ return { payload, note };
68
+ }
69
+ /** A turn hold's token, DERIVED from the relay key, so two callers' turns under one goal id never
70
+ * share a hold. */
71
+ export function turnHoldToken(key) {
72
+ return digestIdToken(`${key}:turn-deadline`);
73
+ }
74
+ /** A goal's caller-scoped relay key. */
75
+ export function goalKey(ref) {
76
+ return `${ref.caller.owner}.${ref.caller.actor}.${ref.caller.uid}.${ref.goalId}`;
77
+ }
78
+ /** A caught value as a lifecycle envelope, or undefined when it is not one. A thrown Proxy can throw
79
+ * from `instanceof` itself, so the test runs inside the guard. */
80
+ export function caughtEnvelope(e) {
81
+ try {
82
+ return e instanceof EpEnvelopeError ? e : undefined;
83
+ }
84
+ catch {
85
+ return undefined;
86
+ }
87
+ }
88
+ /** Pending relays, retry answers, deadline sweeps and once-task debts for this manager. */
89
+ export class TurnRelay {
90
+ deps;
91
+ /**
92
+ * The turn relay's same-incarnation idempotency map ({@link goalAcceptances}'s twin), by
93
+ * {@link goalKey}: a same-goal retry serves the identical acceptance; cross-incarnation retries
94
+ * rebuild from the goal-index entry (its acceptance floor + note).
95
+ *
96
+ * One entry per turn this incarnation accepted: the acceptance a duplicate submission is served
97
+ * from, and - once the turn settles - the answer a RETRIED yield is served from.
98
+ *
99
+ * A yield's reply can be lost, and the retry used to find the pending turn already deleted and
100
+ * hear `not-found`, which a seat reads as "drop it": failure reported for work that committed.
101
+ * The settled answer lives here for a bounded window instead, and the sweep drops it after,
102
+ * which is also what keeps this map from being one entry per turn for the process lifetime.
103
+ *
104
+ * `ref` is the goal coordinates the durable terminal is published under. A late yield that
105
+ * arrives after pendingTurns is gone and before `settled` is remembered (or after a concurrent
106
+ * sweep dropped the settled field) still has to name that terminal, never `not-found`. The
107
+ * index entry is not that answer: it is cleared at commit, and the yield path never consults it.
108
+ *
109
+ * `leftoverSince` is when the pending latch dropped. An unsettled leftover ages off that stamp,
110
+ * never off `acceptance.deadlineAt`: a turn that expired after a long outage would otherwise be
111
+ * pruned on the first sweep tick, taking the GoalRef with it, and a late yield in the retry
112
+ * window would hear `not-found` again.
113
+ */
114
+ turnAcceptances = new Map();
115
+ /** Every relayed turn awaiting its seat's yield, by {@link goalKey}. The seat's `turn-pending` pull
116
+ * scans it; the deadline sweep drives expiry; a seat reap stamps its entries `seatDiedAt`, which
117
+ * the deadline terminal carries as `agentDownAt` so the run reads that death as L4002.
118
+ * Rebuilt at boot from goal-index entries carrying a turn note. */
119
+ pendingTurns = new Map();
120
+ /** The deadline sweep behind {@link pendingTurns}: takes the hold's fire into an expired
121
+ * settle and commits the deadline terminal. Unref'd; idle when no turn is pending. */
122
+ turnSweepTimer;
123
+ /** Once tasks whose ending is owed, by {@link goalKey}: the task can no longer run (its seat's
124
+ * exit is proved, or it was never served), so it is cancelled if it has no terminal and its index
125
+ * entry is dropped. A settle that fails stays here and the turn sweep retries it. */
126
+ onceSettles = new Map();
127
+ /** Once tasks a predecessor accepted, by seat uid, until this incarnation binds the seat or
128
+ * proves it gone. `readinessMs` bounds how long a seat no reconcile here can account for is
129
+ * waited for. */
130
+ onceInherited = new Map();
131
+ /** Inherited once seats this manager does not hold whose task has a terminal, by lifecycle uid.
132
+ * Every pull from one is answered `stop`, and its notice repeats until a pull has carried it. */
133
+ onceStops = new Map();
134
+ /** When the goal reconcile finished: the start of an inherited once task's wait for its seat. */
135
+ goalReconcileDoneAt = 0;
136
+ constructor(deps) {
137
+ this.deps = deps;
138
+ }
139
+ get goalWriter() { return this.deps.goalWriter(); }
140
+ get serviceServe() { return this.deps.serviceServe(); }
141
+ get goalReconcileDone() { return this.deps.goalReconcileDone(); }
142
+ markReconciled(at) { this.goalReconcileDoneAt = at; }
143
+ hasAcceptance(key) { return this.turnAcceptances.has(key); }
144
+ pendingForSeat(c) {
145
+ return [...this.pendingTurns.values()].find((p) => p.seat.owner === c.owner && p.seat.actor === c.actor && p.seat.uid === c.uid);
146
+ }
147
+ pendingSeats() {
148
+ return [...new Map([...this.pendingTurns.values()].map((p) => [`${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`, p.seat])).values()];
149
+ }
150
+ // ---- the turn relay (§8 durable actions) ------------------------------------------------------
151
+ //
152
+ // A seat is NOT an endpoint: a run's `turn(agent, payload)` rides the manager, which accepts it
153
+ // as a goal (the spawn-as-action pattern minus the launch closure), parks the payload durably on
154
+ // the goal-index entry's note, and lets the seat PULL it (`turn-pending`) and answer it
155
+ // (`turn-yield`) under its own `manager.self` reach. The deadline is a goal-bound HOLD minted at
156
+ // accept: the delivery daemon's timer writer pumps its schedule, the fire settles it `expired`,
157
+ // and THIS manager commits the deny (`hold-expired` is the predicate core verifies). Three
158
+ // endings, one each: yield -> succeeded (the TurnResult rides the terminal's data), deadline ->
159
+ // failed `turn-deadline`, and a seat death before that is stamped by the reap hook so the same
160
+ // terminal carries `agentDownAt` (the run reads it as L4002). The adoption sweep stamps nothing.
161
+ /** Accept one `turn` goal against a live managed seat. Mirrors {@link serveSpawnGoal}'s accept
162
+ * path (idempotent retry map, index-CAS-before-bind, create-only bindGoal) but runs it INLINE:
163
+ * there is no launch to hand off, so the accept either completes durably or unwinds its own
164
+ * bound goal with a `failed` terminal before refusing. */
165
+ async serveTurnGoal(ctx, target) {
166
+ const gw = this.goalWriter;
167
+ if (!gw)
168
+ throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; turn-as-action cannot accept (SPEC 13.6)");
169
+ const serve = this.serviceServe;
170
+ if (!serve)
171
+ throw new EpEnvelopeError("unavailable", "the manager service endpoint is not serving; a turn's deadline hold is armed over its connection (SPEC 13.9)");
172
+ if (!this.goalReconcileDone)
173
+ throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; retry shortly (SPEC 13.6)");
174
+ const t = ctx.request.target; // targeted command: the serve boundary enforced presence + currency
175
+ const name = target.name;
176
+ const goalId = ctx.request.id;
177
+ const { fingerprint } = submissionFingerprint(ctx.request, ctx.subject);
178
+ const ref = goalRefOf(ctx.subject, goalId);
179
+ const key = goalKey(ref);
180
+ const executor = { lifecycleUid: this.deps.managerInstanceId(), epoch: this.serviceServe?.grant.epoch ?? 0 };
181
+ const acceptedAt = Date.now();
182
+ const prior = this.turnAcceptances.get(key)?.acceptance;
183
+ if (prior !== undefined) {
184
+ if (prior.fingerprint !== fingerprint)
185
+ throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted under a different submission; one goalId never carries two specs (SPEC 13.6)`);
186
+ return prior;
187
+ }
188
+ // Refused here, before anything durable, so the caller's goal id stays free for another seat.
189
+ this.assertSeatTurnFree(name, t, goalId);
190
+ if (target.kind === "managed" && target.agent.once)
191
+ throw new EpEnvelopeError("failed-precondition", `seat "${name}" is a once seat; it takes only the task it was spawned with`, undefined, "not-executed");
192
+ const raw = (ctx.request.args ?? {});
193
+ const payload = String(raw.payload);
194
+ const deadlineAt = raw.deadlineAt === undefined ? acceptedAt + Number(raw.deadlineMs) : Number(raw.deadlineAt);
195
+ if (deadlineAt <= acceptedAt)
196
+ throw new EpEnvelopeError("deadline-exceeded", `goal "${goalId}" names a deadline already past (${new Date(deadlineAt).toISOString()}); a turn with no time left to serve it is never accepted (SPEC 13.6)`);
197
+ const deadlineMs = deadlineAt - acceptedAt;
198
+ const handoffFrom = raw.handoffFrom === undefined ? undefined : String(raw.handoffFrom);
199
+ const holdToken = turnHoldToken(key);
200
+ const note = JSON.stringify({ payload, deadlineAt, holdEpoch: executor.epoch, holdToken, ...(handoffFrom !== undefined ? { handoffFrom } : {}) });
201
+ // A goal that already ENDED is never accepted again, whatever the retry carries: the bind is
202
+ // create-only and outlives an unwind (the failed terminal, the cleared index), so a retry of an
203
+ // unwound accept would otherwise re-record an index entry over a tombstone and, before that
204
+ // check existed, be served an acceptance rebuilt from it — a live deadline on a turn no seat
205
+ // would ever be shown. The terminal is the durable answer, and it is read before anything is
206
+ // written.
207
+ const ended = await readGoalResult(gw.ctx, ref);
208
+ if (ended !== undefined)
209
+ throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" already ended ${ended.state}; a bound goal is never accepted again (SPEC 13.6)`);
210
+ // Index-CAS-before-bind, exactly as spawn: the entry (floor + note) is the durable relay
211
+ // record a successor rebuilds from, so it must exist before the acceptance is servable.
212
+ const idx = await recordGoalIndex(gw.ctx, ref, executor.lifecycleUid, { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, readinessDeadlineMs: deadlineMs }, note);
213
+ if (!idx.recorded && idx.existing.iid !== executor.lifecycleUid)
214
+ throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted by instance "${idx.existing.iid}"; that instance owns its relay and this attempt provisions nothing (SPEC 13.6)`);
215
+ const b = await bindGoal(gw.ctx, ref, fingerprint);
216
+ if (!b.bound) {
217
+ if (b.existing.fingerprint !== fingerprint)
218
+ throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already bound to a different submission; one goalId never carries two specs (SPEC 13.6)`);
219
+ // Same submission, bound, not ended, and not in the acceptance map. Every relay this
220
+ // incarnation holds is in that map (the accept path and the boot sweep both write it), so
221
+ // this is a goal nobody is relaying: an earlier attempt bound it and could not finish its
222
+ // unwind, or a predecessor's relay was left unadopted. Nothing here can rebuild a relay a
223
+ // seat will be shown, so the caller is refused rather than served an acceptance no pending
224
+ // entry backs; the index entry this attempt recorded is withdrawn with it.
225
+ if (idx.recorded)
226
+ await clearGoalIndex(gw.ctx, ref);
227
+ throw new EpEnvelopeError("unavailable", `goal "${goalId}" is bound but no relay of it is pending on this instance; retry (SPEC 13.6)`);
228
+ }
229
+ try {
230
+ await createGoal(gw.ctx, ref, {
231
+ fingerprint,
232
+ command: ctx.subject.command,
233
+ caller: { id: `${ctx.subject.caller.owner}.${ctx.subject.caller.actor}`, lifecycleUid: ctx.subject.caller.uid },
234
+ acceptedEpoch: executor.epoch,
235
+ requestId: goalId,
236
+ sourceSeq: 0,
237
+ acceptedAt,
238
+ readinessDeadlineMs: deadlineMs,
239
+ // The §13.6 target pin: the seat INCARNATION this payload is addressed to. A successor
240
+ // under the same name is a different addressee; its uid differs and the pin holds that.
241
+ target: { owner: t.owner, actor: t.actor, lifecycleUid: t.lifecycleUid, mappingRevision: 0 },
242
+ });
243
+ // The deadline, as a goal-bound hold on the plane: its EXPIRED settle is the one predicate
244
+ // `commitGoalResult` accepts for the deny. The record rides the goal-writer's KV; the
245
+ // `.schedule` request rides the SERVE connection, because the timer row is the serving
246
+ // instance's own (`ept.<e>.<iid>.<epoch>.*.schedule`, SPEC 13.9) and the goal-writer holds
247
+ // none. Measured on an auth mesh: minted over the goal-writer, the schedule publish was
248
+ // broker-denied and every accept unwound.
249
+ await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.deps.space, {
250
+ ref: { endpoint: ref.endpoint, token: holdToken },
251
+ instanceId: this.deps.managerInstanceId(),
252
+ epoch: executor.epoch,
253
+ goal: { caller: { owner: ctx.subject.caller.owner, actor: ctx.subject.caller.actor, uid: ctx.subject.caller.uid }, goalId },
254
+ holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.deps.managerInstanceId() },
255
+ deadline: deadlineAt,
256
+ now: acceptedAt,
257
+ });
258
+ // Again after the awaits, with no await before the maps are written: another caller's
259
+ // accept of this id to this seat may have finished meanwhile, and this unwinds the loser.
260
+ this.assertSeatTurnFree(name, t, goalId);
261
+ }
262
+ catch (e) {
263
+ // The accept is inline (no launch closure to fail later), so a post-bind throw unwinds HERE:
264
+ // commit the failed terminal this attempt owns, clear the index, and refuse the accept — an
265
+ // accepted-but-unanswered goal must never be left for the boot sweep to find (H1's rule).
266
+ const msg = rejectionText(e);
267
+ try {
268
+ await this.deps.assertGoalWriterEpochCurrent(executor.epoch);
269
+ // The goal is TARGET-PINNED, so its completion proves the seat's currency exactly as the
270
+ // yield's does (managed-seat epochs are 0 within an incarnation; the resolver answers from
271
+ // the live agents map). Committed without it, core refused the terminal and the unwind
272
+ // left a bound goal with no ending for every retry to find.
273
+ await commitGoalResult(gw.ctx, {
274
+ ref, now: Date.now(), cause: "complete", state: "failed", data: { error: msg },
275
+ committer: { instanceId: this.deps.managerInstanceId(), epoch: executor.epoch },
276
+ executor: { lifecycleUid: t.lifecycleUid, epoch: 0 },
277
+ resolveCurrentEpoch: (current) => this.deps.turnExecutorEpoch(name, t.owner, t.actor, current.lifecycleUid),
278
+ });
279
+ await clearGoalIndex(gw.ctx, ref);
280
+ }
281
+ catch (e2) {
282
+ console.error(`! turn accept unwind for ${goalId}: ${rejectionText(e2)}`);
283
+ }
284
+ throw caughtEnvelope(e) ?? new EpEnvelopeError("internal", `turn accept for ${goalId} failed: ${msg}`);
285
+ }
286
+ const pending = {
287
+ ref, goalId,
288
+ seat: { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid },
289
+ payload, acceptedAt, deadlineAt,
290
+ holdToken, holdEpoch: executor.epoch,
291
+ ...(handoffFrom !== undefined ? { handoffFrom } : {}),
292
+ };
293
+ this.pendingTurns.set(key, pending);
294
+ this.ensureTurnSweep();
295
+ this.deps.noticeSeatTurns(pending.seat);
296
+ const acceptance = { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, goalId, fingerprint, deadlineAt, executor };
297
+ this.turnAcceptances.set(key, { acceptance, ref });
298
+ this.deps.emitGoalProgress(ref, executor.epoch, { phase: "relayed" });
299
+ return acceptance;
300
+ }
301
+ /** The seat's pull: every pending turn addressed to the CALLER's incarnation, oldest first.
302
+ * The uid is part of the address - a successor seat never receives a predecessor's turn. */
303
+ turnPendingFor(c) {
304
+ // AN EMPTY LIST IS AN ANSWER, so it must not be given before the index is rebuilt. Between
305
+ // registration and `reconcileGoalIndex`, `pendingTurns` holds nothing a predecessor accepted,
306
+ // and a seat that pulls in that window is told authoritatively that it has no turn. The seat
307
+ // treats a refusal as "keep what you hold" and an empty list as "you hold nothing", so the
308
+ // window has to refuse, the same way `serveTurnGoal` does.
309
+ if (!this.goalReconcileDone)
310
+ throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; the pending-turn index is not rebuilt yet, retry (SPEC 13.6)");
311
+ // A once seat this manager does not hold, whose task has ended, is told to end itself. Nothing
312
+ // else rides that answer, and the settled task is never served again.
313
+ const stop = this.onceStops.get(c.uid);
314
+ if (stop !== undefined && stop.owner === c.owner && stop.actor === c.actor) {
315
+ stop.told = true;
316
+ return { turns: [], notices: true, stop: true };
317
+ }
318
+ // Two turns on one seat are serialized at the dispatch (cotal-lang 6.5): only the oldest
319
+ // unsettled one is served, and the next surfaces once it yields or its deadline denies, so a
320
+ // seat is never shown two turns at once.
321
+ // An ELAPSED turn is not servable: its hold is expirable and its run has already thrown from
322
+ // its own pause, so handing it to the seat buys work whose yield is refused. It also cannot be
323
+ // allowed to stay the head, or one expired turn dams every later turn for that seat. A once
324
+ // task is not served before its spawn's readiness verdict, and one with no deadline never
325
+ // elapses.
326
+ const now = Date.now();
327
+ const head = [...this.pendingTurns.values()]
328
+ .filter((p) => p.seat.owner === c.owner && p.seat.actor === c.actor && p.seat.uid === c.uid)
329
+ .filter((p) => (p.deadlineAt === undefined || now < p.deadlineAt) && p.once?.deliverable !== false)
330
+ .sort((x, y) => x.acceptedAt - y.acceptedAt)
331
+ .slice(0, 1);
332
+ for (const p of head)
333
+ p.pulledAt ??= now;
334
+ const turns = head.map((p) => ({ goalId: p.goalId, payload: p.payload, acceptedAt: p.acceptedAt, ...(p.deadlineAt !== undefined ? { deadlineAt: p.deadlineAt } : {}), ...(p.once ? { once: true } : {}) }));
335
+ return { turns, notices: true };
336
+ }
337
+ /** A seat names a turn by goal id alone when it yields, so one incarnation holding two callers'
338
+ * turns under one id could not say which of the two it answered. */
339
+ assertSeatTurnFree(name, t, goalId) {
340
+ if (this.seatTurnKey({ owner: t.owner, actor: t.actor, uid: t.lifecycleUid }, goalId) !== undefined)
341
+ throw new EpEnvelopeError("failed-precondition", `seat "${name}" already holds another caller's turn "${goalId}"; a seat yields by goal id, so it is never handed two turns under one (SPEC 13.6)`);
342
+ }
343
+ /** The relay key of the turn addressed to seat incarnation `c` under `goalId`, pending or kept
344
+ * for a retried yield. The accept path never hands one incarnation two turns under one goal
345
+ * id, so at most one matches. */
346
+ seatTurnKey(c, goalId) {
347
+ for (const [key, { acceptance: a }] of this.turnAcceptances)
348
+ if (a.goalId === goalId && a.owner === c.owner && a.actor === c.actor && a.uid === c.uid)
349
+ return key;
350
+ return undefined;
351
+ }
352
+ /** The seat's yield: claim the hold (one-use; expiry fails closed), then commit the goal
353
+ * `succeeded` carrying the TurnResult. A yield AFTER the deadline drives the deadline terminal
354
+ * instead and refuses - the expiry outcome stands, never a late success over it. */
355
+ async serveTurnYield(c, raw) {
356
+ if (this.deps.execution === "none")
357
+ throw new EpEnvelopeError("unimplemented", this.deps.executionRefusal);
358
+ // Same boot window as the pull, and checked first because it is the earlier boot phase: before
359
+ // the index is rebuilt a predecessor's accepted turn is not in `pendingTurns`, and `not-found`
360
+ // would tell the seat to drop work it is holding.
361
+ if (!this.goalReconcileDone)
362
+ throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; this yield's turn may not be indexed yet, retry (SPEC 13.6)");
363
+ const gw = this.goalWriter;
364
+ if (!gw)
365
+ throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
366
+ const goalId = String(raw.goalId);
367
+ const status = String(raw.status);
368
+ const to = raw.to === undefined ? undefined : String(raw.to);
369
+ const yieldNote = raw.note === undefined ? undefined : String(raw.note);
370
+ if (status === "handoff" && (to === undefined || to.length === 0))
371
+ throw new EpEnvelopeError("failed-precondition", `a handoff yield names its addressee ("to"); a handoff to nobody relays nothing`);
372
+ const key = this.seatTurnKey(c, goalId);
373
+ if (key === undefined)
374
+ throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
375
+ const p = this.pendingTurns.get(key);
376
+ if (!p)
377
+ return this.settledTurnAnswer(key, goalId);
378
+ await this.claimTurnHold(p);
379
+ const epoch = this.serviceServe?.grant.epoch ?? 0;
380
+ await this.deps.assertGoalWriterEpochCurrent(epoch);
381
+ const at = Date.now();
382
+ const data = { status, ...(to !== undefined ? { to } : {}), ...(yieldNote !== undefined ? { note: yieldNote } : {}), ...(p.handoffFrom !== undefined ? { handoffFrom: p.handoffFrom } : {}), at };
383
+ // The goal is TARGET-PINNED, so this completion proves the EXECUTOR's (the seat's) fresh
384
+ // currency, not the manager's: managed-seat epochs are 0 within an incarnation (the same
385
+ // convention resolveTarget serves), and the resolver answers from the live agents map — a
386
+ // seat that died between its yield call and this commit refuses `expired` here.
387
+ const { fact } = await commitGoalResult(gw.ctx, {
388
+ ref: p.ref, now: at, cause: "complete", state: "succeeded", data,
389
+ committer: { instanceId: this.deps.managerInstanceId(), epoch },
390
+ executor: { lifecycleUid: p.seat.uid, epoch: 0 },
391
+ resolveCurrentEpoch: (target) => this.deps.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
392
+ });
393
+ this.deps.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
394
+ // A once task's index entry is its seat's debt, dropped at the seat's proved exit.
395
+ if (!p.once)
396
+ await clearGoalIndex(gw.ctx, p.ref);
397
+ this.pendingTurns.delete(key);
398
+ this.deps.noticeSeatTurns(p.seat);
399
+ this.markTurnLatchDropped(key, at);
400
+ this.rememberSettledTurn(key, fact.state, at);
401
+ if (p.once)
402
+ this.deps.endOnceSeat(p, `yielded ${status}`);
403
+ this.maybeStopTurnSweep();
404
+ return { goalId, state: fact.state };
405
+ }
406
+ /** A seat's answer for a turn no longer pending. A REPLY THAT WAS LOST IS NOT AN ANSWER THAT
407
+ * FAILED: the commit deleted the pending turn, so a retry found nothing and heard `not-found`,
408
+ * which a seat reads as "drop it", reporting failure for work the run already has. The answer
409
+ * the first reply carried is served again instead, to the addressee it was addressed to and
410
+ * nobody else. */
411
+ async settledTurnAnswer(key, goalId) {
412
+ const settled = this.turnAcceptances.get(key);
413
+ if (settled !== undefined) {
414
+ if (settled.settled !== undefined)
415
+ return { goalId, state: settled.settled.state };
416
+ // The in-memory answer is not yet remembered (pending deleted before the terminal CAS,
417
+ // or a concurrent sweep dropped `settled` while the commit was still in flight). The
418
+ // durable terminal is the one the run already has; name it, never `not-found`.
419
+ if (settled.ref !== undefined && this.goalWriter) {
420
+ const ended = await readGoalResult(this.goalWriter.ctx, settled.ref);
421
+ if (ended !== undefined) {
422
+ this.rememberSettledTurn(key, ended.state, ended.ts);
423
+ return { goalId, state: ended.state };
424
+ }
425
+ }
426
+ }
427
+ throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
428
+ }
429
+ /** Claim a pending turn's deadline hold before the seat's answer commits: one use, and a hold
430
+ * that already expired drives the deadline terminal instead and refuses the answer. A once task
431
+ * with no deadline has no hold. */
432
+ async claimTurnHold(p) {
433
+ if (p.holdToken === undefined)
434
+ return;
435
+ const gw = this.goalWriter;
436
+ const cpRef = { endpoint: p.ref.endpoint, token: p.holdToken };
437
+ try {
438
+ await resumeCheckpoint(gw.ctx.kv, gw.ctx.js, gw.ctx.jsm, this.deps.space, { ref: cpRef, presenter: { id: MANAGER_ENDPOINT, lifecycleUid: this.deps.managerInstanceId() }, now: Date.now() });
439
+ }
440
+ catch (e) {
441
+ const settle = await readCheckpointSettle(gw.ctx.jsm, this.deps.space, cpRef).catch(() => undefined);
442
+ if (settle?.settle === "expired") {
443
+ await this.commitTurnDeadline(p);
444
+ throw new EpEnvelopeError("failed-precondition", `turn "${p.goalId}" elapsed its deadline before the seat answered; the deadline terminal stands (SPEC 13.6)`);
445
+ }
446
+ // Already resumed BY THIS MANAGER (the hold is holder-bound): a prior attempt claimed it
447
+ // and then failed to commit. Fall through and commit; the claim is ours to finish.
448
+ if (settle?.settle !== "resumed")
449
+ throw e;
450
+ }
451
+ }
452
+ /** A once seat's report that its task's handoff to its harness was not confirmed. The seat sealed
453
+ * the task before it reported, so nothing hands it over again; the task fails
454
+ * `delivery-unconfirmed` and the seat is stopped. The commit proves the seat's live currency, as
455
+ * a yield's does: a seat already gone commits nothing here, and its exit cancels the task. Only
456
+ * the addressed seat may report, only for its once task; a repeat after the terminal is answered
457
+ * with it. */
458
+ async serveTurnUnconfirmed(c, raw) {
459
+ if (this.deps.execution === "none")
460
+ throw new EpEnvelopeError("unimplemented", this.deps.executionRefusal);
461
+ if (!this.goalReconcileDone)
462
+ throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; this report's turn may not be indexed yet, retry (SPEC 13.6)");
463
+ const gw = this.goalWriter;
464
+ if (!gw)
465
+ throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
466
+ const goalId = String(raw.goalId);
467
+ const key = this.seatTurnKey(c, goalId);
468
+ if (key === undefined)
469
+ throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
470
+ const p = this.pendingTurns.get(key);
471
+ if (!p)
472
+ return this.settledTurnAnswer(key, goalId);
473
+ if (!p.once)
474
+ throw new EpEnvelopeError("failed-precondition", `turn "${goalId}" is a run's turn; turn-unconfirmed reports only a once task, and a run's turn is offered again`);
475
+ await this.claimTurnHold(p);
476
+ const epoch = this.serviceServe?.grant.epoch ?? 0;
477
+ await this.deps.assertGoalWriterEpochCurrent(epoch);
478
+ const at = Date.now();
479
+ const { fact } = await commitGoalResult(gw.ctx, {
480
+ ref: p.ref, now: at, cause: "complete", state: "failed", data: { reason: "delivery-unconfirmed", at },
481
+ committer: { instanceId: this.deps.managerInstanceId(), epoch },
482
+ executor: { lifecycleUid: p.seat.uid, epoch: 0 },
483
+ resolveCurrentEpoch: (target) => this.deps.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
484
+ });
485
+ this.deps.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
486
+ this.pendingTurns.delete(key);
487
+ this.deps.noticeSeatTurns(p.seat);
488
+ this.markTurnLatchDropped(key, at);
489
+ this.rememberSettledTurn(key, fact.state, at);
490
+ this.deps.endOnceSeat(p, "delivery-unconfirmed");
491
+ this.maybeStopTurnSweep();
492
+ return { goalId, state: fact.state };
493
+ }
494
+ /** The caller withdraws a turn it submitted (the reserved `cancel`, SPEC 13.6 item 4), so the
495
+ * seat is not shown it again and a late yield is answered from the cancelled terminal. Only a
496
+ * relay this incarnation holds is moved to `cancelling`, because only its holder can commit the
497
+ * terminal; an ended goal is refused with its cached outcome, which keeps a repeated cancel
498
+ * idempotent. The pending entry is the latch the yield and the deadline sweep race on, taken
499
+ * before the first await so a concurrent cancel finds nothing to take. A failed cancel puts it
500
+ * back so the relay still ends at its deadline, unless something ended the relay while it was
501
+ * held: a yield that read the entry first, or this commit with only its reply lost. An entry
502
+ * whose outcome cannot be read back stays out and converges through the goal index at the
503
+ * next boot, as a failed deadline commit does. */
504
+ async serveTurnCancel(ctx) {
505
+ if (this.deps.execution === "none")
506
+ throw new EpEnvelopeError("unimplemented", this.deps.executionRefusal);
507
+ if (!this.goalReconcileDone)
508
+ throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; the pending-turn index is not rebuilt yet, retry (SPEC 13.6)");
509
+ const gw = this.goalWriter;
510
+ if (!gw)
511
+ throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
512
+ const raw = (ctx.request.args ?? {});
513
+ const goalId = String(raw.goalId);
514
+ const ref = goalRefOf(ctx.subject, goalId);
515
+ const key = goalKey(ref);
516
+ const p = this.pendingTurns.get(key);
517
+ if (p === undefined) {
518
+ const ended = await readGoalResult(gw.ctx, ref);
519
+ if (ended !== undefined)
520
+ throw goalAlreadyTerminal(goalId, ended);
521
+ throw new EpEnvelopeError("failed-precondition", `no turn "${goalId}" of this caller is pending on this manager; cancel withdraws a relayed turn (SPEC 13.6)`);
522
+ }
523
+ this.pendingTurns.delete(key);
524
+ const epoch = this.serviceServe?.grant.epoch ?? 0;
525
+ let fact;
526
+ try {
527
+ await requestGoalCancel(gw.ctx, { request: ctx.subject, goalId, mode: (raw.mode ?? "graceful") });
528
+ await this.deps.assertGoalWriterEpochCurrent(epoch);
529
+ ({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "caller" }, committer: { instanceId: this.deps.managerInstanceId(), epoch } }));
530
+ }
531
+ catch (e) {
532
+ // The remembered answer is read after the durable one, with no await before the put back:
533
+ // a yield that has dropped the entry remembered its answer, and one still committing drops
534
+ // the entry it finds. An ended relay is stamped so its acceptance still ages off.
535
+ if ((await readGoalResult(gw.ctx, ref)) !== undefined)
536
+ this.markTurnLatchDropped(key);
537
+ else if (this.turnAcceptances.get(key)?.settled === undefined)
538
+ this.pendingTurns.set(key, p);
539
+ throw e;
540
+ }
541
+ this.deps.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
542
+ this.deps.noticeSeatTurns(p.seat);
543
+ this.markTurnLatchDropped(key);
544
+ this.rememberSettledTurn(key, fact.state, Date.now());
545
+ if (p.once)
546
+ this.deps.endOnceSeat(p, "cancelled");
547
+ else
548
+ await clearGoalIndex(gw.ctx, ref);
549
+ this.maybeStopTurnSweep();
550
+ return { goalId, state: fact.state };
551
+ }
552
+ /** Commit the deadline terminal for one pending turn whose hold settled EXPIRED: the deny's
553
+ * predicate is that recorded settle, verified by core against the spec's goal binding. The map
554
+ * delete is the idempotency latch (yield-loss and sweep race here); a commit failure after it
555
+ * converges through the goal index at the next boot, the same narrow leg spawn leaves open. */
556
+ async commitTurnDeadline(p) {
557
+ const gw = this.goalWriter;
558
+ if (!gw)
559
+ return;
560
+ const key = goalKey(p.ref);
561
+ if (!this.pendingTurns.delete(key))
562
+ return;
563
+ this.deps.noticeSeatTurns(p.seat);
564
+ this.markTurnLatchDropped(key);
565
+ const epoch = this.serviceServe?.grant.epoch ?? 0;
566
+ try {
567
+ await this.deps.assertGoalWriterEpochCurrent(epoch);
568
+ const { fact } = await commitGoalResult(gw.ctx, { ref: p.ref, now: Date.now(), cause: "deny", denial: { kind: "hold-expired", token: p.holdToken }, data: { reason: "turn-deadline", ...(p.seatDiedAt !== undefined ? { agentDownAt: p.seatDiedAt } : {}), ...(p.handoffFrom !== undefined ? { handoffFrom: p.handoffFrom } : {}), ...(this.onceSeatUnheld(p) ? { seat: UNHELD_SEAT } : {}) }, committer: { instanceId: this.deps.managerInstanceId(), epoch } });
569
+ this.deps.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
570
+ // Remember BEFORE the index clear: a late yield that arrives after the pending latch
571
+ // (the delete at the top of this function) and after this CAS has to name this terminal.
572
+ // Clearing first, then remembering, left a window where maybeStopTurnSweep saw no pending
573
+ // turn and no settled answer, wiped the acceptance, and rememberSettledTurn no-op'd.
574
+ this.rememberSettledTurn(key, fact.state, Date.now());
575
+ if (p.once)
576
+ this.deps.endOnceSeat(p, "turn-deadline");
577
+ else
578
+ await clearGoalIndex(gw.ctx, p.ref);
579
+ }
580
+ catch (e) {
581
+ console.error(`! turn deadline terminal for ${p.goalId}: ${rejectionText(e)}`);
582
+ // A once seat stops at its deadline whether or not the terminal landed, and the task stays
583
+ // pending so the turn sweep writes the terminal again while this manager runs.
584
+ if (p.once) {
585
+ this.pendingTurns.set(key, p);
586
+ this.deps.endOnceSeat(p, "turn-deadline");
587
+ this.ensureTurnSweep();
588
+ }
589
+ }
590
+ this.maybeStopTurnSweep();
591
+ }
592
+ /** The reap hook: a pending turn addressed to the reaped INCARNATION is MARKED dead, never
593
+ * settled early - no honest terminal exists for it (a completion must prove the executor's
594
+ * live currency, and the hold is only expirable once due), so the entry rides to its deadline
595
+ * and the deny then records both facts. The addressee's own client observes the death from
596
+ * presence long before that, which is the run's L4002. */
597
+ failSeatTurns(name, uid) {
598
+ for (const p of this.pendingTurns.values()) {
599
+ if (p.seat.name !== name || p.seat.uid !== uid || p.seatDiedAt !== undefined)
600
+ continue;
601
+ p.seatDiedAt = Date.now();
602
+ console.error(`turn ${p.goalId}: addressed seat ${name}/${uid} died before yielding; the deadline terminal will record it`);
603
+ }
604
+ }
605
+ /** Settle one DUE hold as its owner: the manager minted it, so once the deadline has passed it
606
+ * expires the pause itself ({@link expireCheckpoint}, the guard-hold precedent) rather than
607
+ * waiting on the broker's fire - which it holds no grant to read, and which a hold minted under
608
+ * a predecessor's epoch would carry on a subject this incarnation never subscribes. Idempotent
609
+ * by the plane: a yield that claimed the hold first is observed as `resumed` and left to its
610
+ * own commit, and an already-expired hold returns its recorded settle. */
611
+ async expireTurnHold(p) {
612
+ const gw = this.goalWriter;
613
+ if (!gw)
614
+ return undefined;
615
+ return expireCheckpoint(gw.ctx.kv, gw.ctx.js, gw.ctx.jsm, this.deps.space, { ref: { endpoint: p.ref.endpoint, token: p.holdToken }, now: Date.now() });
616
+ }
617
+ ensureTurnSweep() {
618
+ if (this.turnSweepTimer !== undefined)
619
+ return;
620
+ const t = setInterval(() => { void this.sweepTurnDeadlines().catch((e) => console.error(`! turn deadline sweep: ${rejectionText(e)}`)); }, TURN_SWEEP_MS);
621
+ t.unref?.();
622
+ this.turnSweepTimer = t;
623
+ }
624
+ /** The answer a retried yield is served, held for {@link TURN_ANSWER_RETENTION_MS}. Only for a
625
+ * turn this incarnation accepted: an entry it has no acceptance for is one it cannot vouch for. */
626
+ rememberSettledTurn(key, state, at) {
627
+ const entry = this.turnAcceptances.get(key);
628
+ if (entry === undefined)
629
+ return;
630
+ entry.settled = { state, at };
631
+ }
632
+ /** Stamp when the pending latch dropped, so an unsettled leftover ages off that instant rather
633
+ * than the original deadline. Idempotent: the first drop is the one the retry window starts at. */
634
+ markTurnLatchDropped(key, at = Date.now()) {
635
+ const entry = this.turnAcceptances.get(key);
636
+ if (entry === undefined || entry.leftoverSince !== undefined)
637
+ return;
638
+ entry.leftoverSince = at;
639
+ }
640
+ /** Stop the sweep only when it has nothing left to do. It drives elapsed turns to their deadline
641
+ * terminals AND drops settled answers once their retry window has passed, so a stop while the
642
+ * second is still owed would leave one entry per turn for the process lifetime. */
643
+ maybeStopTurnSweep() {
644
+ if (this.pendingTurns.size > 0 || this.onceSettles.size > 0 || this.onceInherited.size > 0 || [...this.onceStops.values()].some((s) => !s.told))
645
+ return;
646
+ // An acceptance with no `settled` yet is the in-flight deadline commit: pending was the
647
+ // latch and is already gone, the terminal CAS has not returned, and a concurrent sweep
648
+ // tick used to clear the map here, so rememberSettledTurn no-op'd and a late yield heard
649
+ // `not-found` for a deny the run already has. Prune is the only deleter; stop only when
650
+ // it has left nothing.
651
+ if (this.turnAcceptances.size > 0)
652
+ return;
653
+ this.stopTurnSweep();
654
+ }
655
+ stopTurnSweep() {
656
+ if (this.turnSweepTimer === undefined)
657
+ return;
658
+ clearInterval(this.turnSweepTimer);
659
+ this.turnSweepTimer = undefined;
660
+ }
661
+ /** Drive every elapsed pending turn to its deadline terminal. Only entries at/past their own
662
+ * `deadlineAt` are read at all; a `resumed` settle is a yield mid-commit and is left alone. */
663
+ async sweepTurnDeadlines() {
664
+ const now = Date.now();
665
+ // A settled answer is kept only as long as a lost reply could still be retried under it.
666
+ // An UNSETTLED acceptance whose pending latch is already gone is the in-flight (or failed)
667
+ // deadline commit: keep it for the same window so a late yield can still read the durable
668
+ // terminal, then drop it so a commit that never remembered cannot pin the sweep forever.
669
+ for (const [key, e] of [...this.turnAcceptances.entries()]) {
670
+ if (this.pendingTurns.has(key))
671
+ continue;
672
+ // Unsettled leftovers age off the latch-drop stamp, never `deadlineAt`.
673
+ const at = e.settled?.at ?? e.leftoverSince;
674
+ if (at !== undefined && now - at >= TURN_ANSWER_RETENTION_MS)
675
+ this.turnAcceptances.delete(key);
676
+ }
677
+ // The prune above is the one event after which the sweep may have nothing left to do, and
678
+ // the settle-time callers cannot see it: they run when an answer has just been remembered.
679
+ this.maybeStopTurnSweep();
680
+ // A notice is at-most-once, so a seat offline when it went out has not pulled its head turn.
681
+ // Repeat the notice until it does; a seat that pulled is not told again for that turn.
682
+ const heads = new Map();
683
+ for (const p of this.pendingTurns.values()) {
684
+ if ((p.deadlineAt !== undefined && now >= p.deadlineAt) || p.once?.deliverable === false)
685
+ continue;
686
+ const k = `${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`;
687
+ const h = heads.get(k);
688
+ if (h === undefined || p.acceptedAt < h.acceptedAt)
689
+ heads.set(k, p);
690
+ }
691
+ for (const p of heads.values())
692
+ if (p.pulledAt === undefined)
693
+ this.deps.noticeSeatTurns(p.seat);
694
+ for (const stop of this.onceStops.values())
695
+ if (!stop.told)
696
+ this.deps.noticeSeatTurns(stop);
697
+ for (const owed of [...this.onceSettles.values()])
698
+ if (!owed.flight)
699
+ void this.settleOnceTurn(owed.ref, owed.reason);
700
+ if (this.onceInherited.size > 0)
701
+ await this.settleInheritedOnce().catch((e) => console.error(`! inherited once tasks: ${rejectionText(e)}`));
702
+ for (const p of [...this.pendingTurns.values()]) {
703
+ if (p.deadlineAt === undefined || now < p.deadlineAt)
704
+ continue;
705
+ try {
706
+ const settle = await this.expireTurnHold(p);
707
+ if (settle?.settle === "expired")
708
+ await this.commitTurnDeadline(p);
709
+ }
710
+ catch (e) {
711
+ console.error(`! turn deadline sweep for ${p.goalId}: ${rejectionText(e)}`);
712
+ }
713
+ }
714
+ }
715
+ /** Adopt one inherited TURN goal at boot (the reconcile sweep's turn branch): a non-terminal
716
+ * entry carrying a parseable note rebuilds its pending relay - never an `uncertain` settle,
717
+ * because the deadline hold IS this goal's bounded ending and it survived the restart. No
718
+ * liveness verdict is made here (the agents map is empty during reconcile, so absence means
719
+ * "not yet re-registered", never "dead"); a garbled note or a floor that does not name the
720
+ * seat's owner is logged and left, the dead-pointer honesty rule. */
721
+ async adoptTurnGoal(entry) {
722
+ const gw = this.goalWriter;
723
+ if (!gw)
724
+ return;
725
+ const status = await readGoalStatus(gw.ctx, entry.ref);
726
+ if (status === undefined)
727
+ return; // index points at no goal record: a dead pointer, left for honesty
728
+ const parsed = entry.note !== undefined ? parseTurnNote(entry.note) : undefined;
729
+ const ownOnce = parsed?.once === true && entry.iid === this.deps.managerInstanceId() && entry.allocated?.owner !== undefined;
730
+ if (GOAL_TERMINAL_STATES.includes(status.value.state)) {
731
+ // A once task's entry is its seat's debt until that seat's exit is proved, so it outlives
732
+ // the terminal: the stop the predecessor owed may never have landed.
733
+ if (ownOnce)
734
+ await this.inheritOnce(entry.ref, entry.allocated, parsed);
735
+ else
736
+ await clearGoalIndex(gw.ctx, entry.ref);
737
+ return;
738
+ }
739
+ if (entry.iid !== this.deps.managerInstanceId()) {
740
+ console.error(`turn reconcile ${entry.ref.goalId}: accepted by instance "${entry.iid}", not this incarnation "${this.deps.managerInstanceId()}"; left for its owner (never a cross-instance settle)`);
741
+ return;
742
+ }
743
+ if (entry.allocated?.owner === undefined || parsed === undefined) {
744
+ console.error(`turn reconcile ${entry.ref.goalId}: the relay record is garbled (no floor naming the seat's owner, or an unparseable note); left unsettled`);
745
+ return;
746
+ }
747
+ const spec = await readGoalSpec(gw.ctx, entry.ref);
748
+ if (spec === undefined) {
749
+ // NOW IS NOT WHEN THIS WAS ACCEPTED. `acceptedAt` is what orders a seat's queue, and a turn
750
+ // stamped with the boot instant sorts BEHIND every turn accepted since — a predecessor's
751
+ // oldest turn served last, which is the one thing the ordering exists to prevent. A goal
752
+ // with an index entry and no spec is a relay record that is not readable, and this is the
753
+ // same verdict the garbled-note branch above reaches: left unsettled, said out loud.
754
+ console.error(`turn reconcile ${entry.ref.goalId}: the goal spec is unreadable, so its acceptance time is unknown; left unsettled rather than re-stamped with the boot instant`);
755
+ return;
756
+ }
757
+ const p = {
758
+ ref: entry.ref, goalId: entry.ref.goalId,
759
+ seat: { name: entry.allocated.name, owner: entry.allocated.owner, actor: entry.allocated.actor, uid: entry.allocated.uid },
760
+ payload: parsed.payload,
761
+ acceptedAt: spec.value.acceptedAt,
762
+ holdEpoch: parsed.holdEpoch,
763
+ ...(parsed.deadlineAt !== undefined ? { deadlineAt: parsed.deadlineAt, holdToken: parsed.holdToken ?? turnHoldToken(entry.ref.goalId) } : {}),
764
+ ...(parsed.handoffFrom !== undefined ? { handoffFrom: parsed.handoffFrom } : {}),
765
+ // An inherited once task is served again only once its seat is bound to this incarnation.
766
+ ...(parsed.once ? { once: { deliverable: false } } : {}),
767
+ };
768
+ // The hold is the relay's bounded ending, minted AFTER the index entry and the goal record,
769
+ // so a crash between them leaves a goal with no hold: nothing could ever settle it, and the
770
+ // sweep would report the same missing pause every tick. Left unsettled, said once.
771
+ if (p.holdToken !== undefined && (await readCheckpointSpec(gw.ctx.kv, { endpoint: p.ref.endpoint, token: p.holdToken })) === undefined) {
772
+ // A once task's hold is minted before its seat launches, so without one no seat ever ran it:
773
+ // the task is cancelled and its entry dropped, with nothing launched to prove gone.
774
+ if (parsed.once) {
775
+ await this.settleOnceTurn(p.ref, "launch-failed");
776
+ return;
777
+ }
778
+ console.error(`turn reconcile ${p.goalId}: its deadline hold was never minted (the accept crashed before it); left unsettled`);
779
+ return;
780
+ }
781
+ // A once task whose spawn has no succeeded terminal was never served, whatever seat exists:
782
+ // it is cancelled, its row is not rebuilt so a later pull finds nothing, and its seat is
783
+ // settled as an inherited debt.
784
+ if (parsed.once && !(await this.onceServed(entry.ref, parsed))) {
785
+ await this.commitOnceCancel(entry.ref, NEVER_SERVED);
786
+ await this.inheritOnce(entry.ref, entry.allocated, parsed);
787
+ return;
788
+ }
789
+ const key = goalKey(p.ref);
790
+ this.pendingTurns.set(key, p);
791
+ // THE ACCEPTANCE TOO, or the adopted turn's answer is never remembered: `rememberSettledTurn`
792
+ // writes only against an acceptance this incarnation holds, and adoption rebuilt the pending
793
+ // relay without one, so a yield whose reply was lost after a restart still heard `not-found`
794
+ // on the very path adoption exists for. The acceptance is rebuilt from the same records the
795
+ // relay was: the spec holds the fingerprint, the index holds the seat, the note the deadline.
796
+ this.turnAcceptances.set(key, {
797
+ acceptance: {
798
+ name: p.seat.name, owner: p.seat.owner, actor: p.seat.actor, uid: p.seat.uid, goalId: p.goalId,
799
+ fingerprint: spec.value.fingerprint, deadlineAt: p.deadlineAt,
800
+ executor: { lifecycleUid: this.deps.managerInstanceId(), epoch: p.holdEpoch },
801
+ },
802
+ ref: p.ref,
803
+ });
804
+ // NO LIVENESS VERDICT AT BOOT. The agents map is empty here: seats are re-registered later,
805
+ // by the resume path, so `not in the map` at this moment means "not yet re-registered", never
806
+ // "dead". Stamping death from it marked EVERY adopted turn as a dead seat, and its deadline
807
+ // terminal then carried `agentDownAt`, so the run raised L4002 for a seat that was alive the
808
+ // whole time where the reference says L4003. The reap hook is the only honest writer of that
809
+ // fact: it fires when a managed seat actually dies.
810
+ console.error(`turn reconcile ${p.goalId}: pending relay to ${p.seat.name}/${p.seat.uid} adopted (deadline ${p.deadlineAt ?? "none"})`);
811
+ if (parsed.once)
812
+ await this.inheritOnce(entry.ref, entry.allocated, parsed);
813
+ this.ensureTurnSweep();
814
+ }
815
+ // ---- once (a spawn whose prompt is its one relayed task) ----------------------------------------
816
+ //
817
+ // A once spawn's prompt is not a kickoff: the manager accepts it as one turn addressed to the
818
+ // allocated incarnation, under the spawner's own caller triple and a goal id derived from the
819
+ // spawn's, so the spawner reads the task's outcome with `goal-result`. The seat is served it from
820
+ // the spawn's readiness verdict on. The task's terminal (yield, deadline) stops the seat, and the
821
+ // seat's proved exit cancels a task that has none. Until that exit, the task's index entry is the
822
+ // seat's debt: a successor finds it there.
823
+ /** Accept a once spawn's task, inline in the spawn's accept seam: nothing has launched yet, so a
824
+ * refusal here fails the spawn and leaves no seat. Mirrors {@link serveTurnGoal}'s accept, with
825
+ * the goal ref and the seat given rather than read off a request. A task with no deadline mints
826
+ * no hold; its goal still records the spawn's readiness budget, which a successor needs to settle
827
+ * it. */
828
+ async acceptOnceTurn(o) {
829
+ const gw = this.goalWriter;
830
+ if (!gw)
831
+ throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; a once task cannot be accepted (SPEC 13.6)");
832
+ const serve = this.serviceServe;
833
+ if (o.deadlineMs !== undefined && !serve)
834
+ throw new EpEnvelopeError("unavailable", "the manager service endpoint is not serving; a once task's deadline hold is armed over its connection (SPEC 13.9)");
835
+ const ref = { endpoint: o.spawnRef.endpoint, caller: { ...o.spawnRef.caller }, goalId: digestIdToken(`${o.spawnRef.goalId}:once`) };
836
+ const key = goalKey(ref);
837
+ const deadlineAt = o.deadlineMs === undefined ? undefined : o.acceptedAt + o.deadlineMs;
838
+ if (deadlineAt !== undefined && deadlineAt > MAX_SCHEDULE_MS)
839
+ throw new EpEnvelopeError("failed-precondition", `once: the deadline ends after the deadline scheduler's last instant (the end of year 9999)`);
840
+ const holdToken = deadlineAt === undefined ? undefined : turnHoldToken(key);
841
+ const { payload, note } = onceTurnNote({ prompt: o.prompt, spawner: o.spawner, holdEpoch: o.executor.epoch, ...(deadlineAt !== undefined ? { deadlineAt, holdToken } : {}), ...(o.retire !== undefined ? { retire: o.retire } : {}), spawn: o.spawnRef.goalId });
842
+ const { seat } = o;
843
+ const idx = await recordGoalIndex(gw.ctx, ref, o.executor.lifecycleUid, { name: seat.name, owner: seat.owner, actor: seat.actor, uid: seat.uid, readinessDeadlineMs: o.readinessDeadlineMs }, note);
844
+ if (!idx.recorded)
845
+ throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already recorded; a spawn accepts its task once (SPEC 13.6)`);
846
+ const b = await bindGoal(gw.ctx, ref, o.fingerprint);
847
+ if (!b.bound) {
848
+ await clearGoalIndex(gw.ctx, ref);
849
+ throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already bound; a spawn accepts its task once (SPEC 13.6)`);
850
+ }
851
+ try {
852
+ await createGoal(gw.ctx, ref, {
853
+ fingerprint: o.fingerprint,
854
+ command: o.command,
855
+ caller: { id: `${ref.caller.owner}.${ref.caller.actor}`, lifecycleUid: ref.caller.uid },
856
+ acceptedEpoch: o.executor.epoch,
857
+ requestId: ref.goalId,
858
+ sourceSeq: 0,
859
+ acceptedAt: o.acceptedAt,
860
+ readinessDeadlineMs: o.readinessDeadlineMs,
861
+ target: { owner: seat.owner, actor: seat.actor, lifecycleUid: seat.uid, mappingRevision: 0 },
862
+ });
863
+ if (deadlineAt !== undefined)
864
+ await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.deps.space, {
865
+ ref: { endpoint: ref.endpoint, token: holdToken },
866
+ instanceId: this.deps.managerInstanceId(),
867
+ epoch: o.executor.epoch,
868
+ goal: { caller: { ...ref.caller }, goalId: ref.goalId },
869
+ holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.deps.managerInstanceId() },
870
+ deadline: deadlineAt,
871
+ now: o.acceptedAt,
872
+ });
873
+ }
874
+ catch (e) {
875
+ // Nothing launched and nothing was served, so the task is withdrawn with `cancel`.
876
+ try {
877
+ await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
878
+ await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason: "accept-failed" }, committer: { instanceId: this.deps.managerInstanceId(), epoch: o.executor.epoch } });
879
+ await clearGoalIndex(gw.ctx, ref);
880
+ }
881
+ catch (e2) {
882
+ console.error(`! once task accept unwind for ${ref.goalId}: ${rejectionText(e2)}`);
883
+ }
884
+ throw e;
885
+ }
886
+ this.pendingTurns.set(key, {
887
+ ref, goalId: ref.goalId, seat: { ...seat }, payload, acceptedAt: o.acceptedAt, holdEpoch: o.executor.epoch,
888
+ ...(deadlineAt !== undefined ? { deadlineAt, holdToken } : {}),
889
+ once: { deliverable: false },
890
+ });
891
+ this.turnAcceptances.set(key, {
892
+ acceptance: { name: seat.name, owner: seat.owner, actor: seat.actor, uid: seat.uid, goalId: ref.goalId, fingerprint: o.fingerprint, ...(deadlineAt !== undefined ? { deadlineAt } : {}), executor: o.executor },
893
+ ref,
894
+ });
895
+ this.ensureTurnSweep();
896
+ this.deps.emitGoalProgress(ref, o.executor.epoch, { phase: "relayed" });
897
+ return { ref, ...(deadlineAt !== undefined ? { deadlineAt } : {}) };
898
+ }
899
+ /** Serve a once task from now on: its spawn's succeeded terminal is written. */
900
+ openOnceDelivery(ref) {
901
+ const p = this.pendingTurns.get(goalKey(ref));
902
+ if (p?.once === undefined || p.once.deliverable)
903
+ return;
904
+ p.once.deliverable = true;
905
+ this.deps.noticeSeatTurns(p.seat);
906
+ }
907
+ /** End a once task that can no longer run: once its connector, when it has a `retire` hook, proves
908
+ * the seat's launched processes gone, cancel the task with `reason` if it has no terminal yet,
909
+ * then drop its index entry. One flight per task; a failure keeps it in {@link onceSettles} and
910
+ * the turn sweep retries it. */
911
+ settleOnceTurn(ref, reason, retire) {
912
+ const key = goalKey(ref);
913
+ const owed = this.onceSettles.get(key) ?? { ref, reason, ...(retire !== undefined ? { retire } : {}) };
914
+ if (owed.flight)
915
+ return owed.flight;
916
+ this.onceSettles.set(key, owed);
917
+ const flight = this.runOnceSettle(key, owed).finally(() => { owed.flight = undefined; });
918
+ owed.flight = flight;
919
+ return flight;
920
+ }
921
+ async runOnceSettle(key, owed) {
922
+ const gw = this.goalWriter;
923
+ if (!gw)
924
+ return;
925
+ // The pending entry is the latch the yield and the deadline race on; a task settled here is
926
+ // served to no one again.
927
+ const p = this.pendingTurns.get(key);
928
+ // A task past its deadline owes the deadline terminal, which the turn sweep writes again until
929
+ // it lands; the settle waits for it rather than record a cancel in its place.
930
+ const denyOwed = p?.deadlineAt !== undefined && p.deadlineAt <= Date.now();
931
+ if (p && !denyOwed) {
932
+ this.pendingTurns.delete(key);
933
+ this.markTurnLatchDropped(key);
934
+ this.deps.noticeSeatTurns(p.seat);
935
+ }
936
+ try {
937
+ if (denyOwed)
938
+ throw new Error("its deadline terminal is not written yet");
939
+ // A seat whose exit is proved may have left processes of its own running the task: the task
940
+ // is not recorded as ended, nor its debt cleared, before they are proved gone.
941
+ const retired = owed.retire === undefined ? undefined : await this.deps.retireOnceSeat(owed.retire);
942
+ await this.commitOnceCancel(owed.ref, owed.reason);
943
+ await clearGoalIndex(gw.ctx, owed.ref);
944
+ this.onceSettles.delete(key);
945
+ this.deps.forgetOnceWatch(key);
946
+ await retired?.discard().catch((e) => console.error(`! once task ${owed.ref.goalId}: its retirement receipt was not discarded (${rejectionText(e)})`));
947
+ }
948
+ catch (e) {
949
+ console.error(`! once task ${owed.ref.goalId} (${owed.reason}): ${rejectionText(e)}; retried by the turn sweep`);
950
+ this.ensureTurnSweep();
951
+ }
952
+ this.maybeStopTurnSweep();
953
+ }
954
+ /** Cancel a once task with `reason` unless it already has a terminal. */
955
+ async commitOnceCancel(ref, reason) {
956
+ const gw = this.goalWriter;
957
+ if ((await readGoalResult(gw.ctx, ref)) !== undefined)
958
+ return;
959
+ const epoch = this.serviceServe?.grant.epoch ?? 0;
960
+ await this.deps.assertGoalWriterEpochCurrent(epoch);
961
+ if ((await readGoalStatus(gw.ctx, ref))?.value.state !== "cancelling")
962
+ await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
963
+ const { fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason }, committer: { instanceId: this.deps.managerInstanceId(), epoch } });
964
+ this.deps.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
965
+ this.rememberSettledTurn(goalKey(ref), fact.state, Date.now());
966
+ }
967
+ /** Record a once task a predecessor accepted, and bind its seat if this incarnation already
968
+ * adopted it. The static adoption and the goal reconcile run in either order, so each side
969
+ * binds what the other has already found. */
970
+ async inheritOnce(ref, allocated, note) {
971
+ this.onceInherited.set(allocated.uid, {
972
+ ref, seat: { name: allocated.name, owner: allocated.owner, actor: allocated.actor, uid: allocated.uid },
973
+ ...(note.deadlineAt !== undefined ? { deadlineAt: note.deadlineAt } : {}),
974
+ readinessMs: allocated.readinessDeadlineMs ?? this.deps.readinessTimeoutMs(),
975
+ ...(note.retire !== undefined ? { retire: note.retire } : {}),
976
+ });
977
+ const a = this.deps.findManagedByTarget({ owner: allocated.owner, actor: allocated.actor, lifecycleUid: allocated.uid });
978
+ if (a !== undefined)
979
+ await this.bindOnceSeat(a);
980
+ this.ensureTurnSweep();
981
+ }
982
+ /** An inherited once task whose seat this manager cannot hold: it adopts no seats (an open or
983
+ * user-mode mesh) and the seat is not bound here. */
984
+ onceSeatUnheld(p) {
985
+ return p.once !== undefined && this.onceInherited.has(p.seat.uid) && !(this.deps.adoptsSeats());
986
+ }
987
+ /** Whether a once task was served: its spawn's succeeded terminal is written. */
988
+ async onceServed(ref, note) {
989
+ if (note.spawn === undefined)
990
+ return false;
991
+ const spawn = await readGoalResult(this.goalWriter.ctx, { endpoint: ref.endpoint, caller: ref.caller, goalId: note.spawn });
992
+ return spawn?.state === "succeeded";
993
+ }
994
+ /** Make an adopted seat a once seat again: its exit settles its task, and the task is served to
995
+ * it. A task that ended before the restart owes the stop the predecessor may not have made. */
996
+ async bindOnceSeat(a) {
997
+ const inherited = this.onceInherited.get(a.lifecycleUid);
998
+ if (inherited === undefined || a.once !== undefined)
999
+ return;
1000
+ this.onceInherited.delete(a.lifecycleUid);
1001
+ a.once = { ref: inherited.ref, ...(inherited.retire !== undefined ? { retire: inherited.retire } : {}) };
1002
+ this.deps.watchOnceExit(a);
1003
+ const p = this.pendingTurns.get(goalKey(inherited.ref));
1004
+ if (p?.once) {
1005
+ p.once.deliverable = true;
1006
+ this.deps.noticeSeatTurns(p.seat);
1007
+ return;
1008
+ }
1009
+ const ended = this.goalWriter ? await readGoalResult(this.goalWriter.ctx, inherited.ref) : undefined;
1010
+ if (ended !== undefined)
1011
+ this.deps.stopOnceSeat(a, "turn-ended");
1012
+ }
1013
+ /** Inherited once tasks whose seat is not bound here. On a static mesh the boot reconcile adopts
1014
+ * every seat it can and reaps the rest by their custody reference, so once it has finished with
1015
+ * a seat's slot, an unbound seat is proved gone. A manager that adopts no seats cannot reach the
1016
+ * old seat or prove its exit: it does not serve the task to it, a task with a deadline ends at
1017
+ * that deadline, and one without is settled `uncertain` after one readiness window. Its debt is
1018
+ * never cleared here, since nothing proves that seat gone. */
1019
+ async settleInheritedOnce() {
1020
+ const gw = this.goalWriter;
1021
+ if (!gw || !this.goalReconcileDone)
1022
+ return;
1023
+ const adopts = this.deps.adoptsSeats();
1024
+ for (const [uid, d] of [...this.onceInherited]) {
1025
+ const live = this.deps.findManagedByTarget({ owner: d.seat.owner, actor: d.seat.actor, lifecycleUid: uid });
1026
+ if (live !== undefined) {
1027
+ await this.bindOnceSeat(live);
1028
+ continue;
1029
+ }
1030
+ if (adopts) {
1031
+ const reconciling = this.deps.onceSeatReconciling(uid);
1032
+ if (reconciling)
1033
+ continue;
1034
+ this.onceInherited.delete(uid);
1035
+ void this.settleOnceTurn(d.ref, "seat-exited", retireOf(d));
1036
+ continue;
1037
+ }
1038
+ if ((await readGoalResult(gw.ctx, d.ref)) !== undefined) {
1039
+ this.onceInherited.delete(uid);
1040
+ this.keepUnprovedOnceDebt(d);
1041
+ continue;
1042
+ }
1043
+ if (d.deadlineAt !== undefined || Date.now() - this.goalReconcileDoneAt < d.readinessMs)
1044
+ continue;
1045
+ this.onceInherited.delete(uid);
1046
+ const key = goalKey(d.ref);
1047
+ this.pendingTurns.delete(key);
1048
+ this.markTurnLatchDropped(key);
1049
+ try {
1050
+ await settleGoalUncertain(gw.ctx, { ref: d.ref, now: Date.now(), committer: { instanceId: this.deps.managerInstanceId(), epoch: this.serviceServe?.grant.epoch ?? 0 }, reason: `the manager restarted and could not reach the seat; ${UNHELD_SEAT}, and the task may have run in part or in full` });
1051
+ this.keepUnprovedOnceDebt(d);
1052
+ }
1053
+ catch (e) {
1054
+ console.error(`! inherited once task ${d.ref.goalId}: ${rejectionText(e)}`);
1055
+ }
1056
+ }
1057
+ }
1058
+ /** An inherited task's seat this manager cannot reach: its terminal stands, and its index entry,
1059
+ * the seat's debt, stays recorded, because nothing here can prove that seat gone. The seat is
1060
+ * told to end itself on its next pull, and its notice repeats until a pull carries that. */
1061
+ keepUnprovedOnceDebt(d) {
1062
+ console.error(`! once task ${d.ref.goalId}: this manager cannot reach seat ${d.seat.name}/${d.seat.uid} to prove it gone; its debt stays in the goal index, and the seat is told to end itself`);
1063
+ this.onceStops.set(d.seat.uid, { ...d.seat });
1064
+ this.deps.noticeSeatTurns(d.seat);
1065
+ this.ensureTurnSweep();
1066
+ }
1067
+ }
1068
+ //# sourceMappingURL=turn-relay.js.map