@cotal-ai/manager 0.167.0 → 0.168.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,926 @@
1
+ import { drainAndClose } from "@cotal-ai/core";
2
+ import { rmSync } from "node:fs";
3
+ import { CotalEndpoint, lowerPersonaEndpoints, DEFAULT_SERVER, DEV_OWNER, dialerFor, DeprovisionError, addDeprovisionAccounting, mintCreds, mintLifecycleUid, managedRetirementOpId, newIdentity, principalKey, provisionAgent, grantOverreach, withIssuerSession } from "@cotal-ai/core";
4
+ import { agentLifecycleSecretFilePaths, agentSecretKeyForFile, materializeSecretToFile } from "@cotal-ai/workspace";
5
+ import { makeManagerEndpointEvictionEvidence } from "./endpoint-evict.js";
6
+ import { inlineSnapshotPath, removeInlineSnapshot } from "./launch.js";
7
+ import { rejectionText, attemptCleanup, describeCleanupFailures } from "@cotal-ai/core";
8
+ import {} from "./resume.js";
9
+ import { jetstreamManager } from "@nats-io/jetstream";
10
+ import { Kvm } from "@nats-io/kv";
11
+ import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, issuedHorizon } from "@cotal-ai/core";
12
+ import { EpEnvelopeError, lifecycleBlockedFrom } from "@cotal-ai/core";
13
+ import {} from "./manager-service-contract.js";
14
+ import { staticLifecycleTransport, activateStaticLifecycle, runStaticTerminal, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, planStaticSlotResume, ownedBySibling, walkStaticSlots } from "./static-lifecycle.js";
15
+ import { CHAT_EXPIRY_CONCURRENCY, ChatSessionExpiry, chatOpenLists, chatRetireRefusal, drawChatAlias, isChatAlias, readChatOpenInput, readChatRetireInput, sealChatAdmission } from "./chat-session.js";
16
+ /** One initial terminal entry plus three re-drives. The short first retry absorbs a one-shot
17
+ * broker/eviction blip; the wider later spacing avoids hammering a persistently unavailable
18
+ * authority. The finite ~36s window is intentionally not a liveness inference: exhausting it
19
+ * leaves the durable alias held and requires a later manager start. */
20
+ export const STATIC_RECONCILE_RETRY_DELAYS_MS = [1_000, 5_000, 30_000];
21
+ const STATIC_RECONCILE_MAX_ATTEMPTS = STATIC_RECONCILE_RETRY_DELAYS_MS.length + 1;
22
+ const DEPROVISION_TIMEOUT_MS = 15_000;
23
+ /** Static chat admission, credential renewal, terminal cleanup and resumable reconciliation. */
24
+ export class ManagedStaticLifecycle {
25
+ deps;
26
+ /** Static aliases whose startup exact-op terminal is still in flight. Scoped per alias: control
27
+ * serves during the sweep, but no caller can reuse or attach an alias the sweep still owns. */
28
+ reconcilingAliases = new Set();
29
+ /** In-flight static chat-session terminals, by lifecycle UID, so every caller that retires one
30
+ * session joins one terminal instead of racing its CAS sequence. */
31
+ chatRetirements = new Map();
32
+ /** The expiry side of every chat session this process admitted and nothing retired sooner. */
33
+ chatExpiry = new ChatSessionExpiry((session) => this.expireStaticChatSession(session), {
34
+ retryDelaysMs: STATIC_RECONCILE_RETRY_DELAYS_MS,
35
+ concurrency: CHAT_EXPIRY_CONCURRENCY,
36
+ log: (line) => console.error(line),
37
+ });
38
+ /** Current failed/recovered static reconciliation coordinates. This is an operator snapshot, not
39
+ * lifecycle authority: every re-drive re-reads broker KV and re-runs planStaticSlotResume. */
40
+ staticReconcileItems = new Map();
41
+ staticReconcileLastSweep;
42
+ staticReconcileLastSweepResources;
43
+ staticReconcileSweepsInFlight = 0;
44
+ staticReconcileDrainWaiters = [];
45
+ staticReconcileStopping = false;
46
+ constructor(deps) {
47
+ this.deps = deps;
48
+ }
49
+ start() { this.staticReconcileStopping = false; }
50
+ get stopping() { return this.staticReconcileStopping; }
51
+ isReconciling(alias) { return this.reconcilingAliases.has(alias); }
52
+ get sweepsInFlight() { return this.staticReconcileSweepsInFlight; }
53
+ pendingLifecycle(uid) {
54
+ return this.staticReconcileSweepsInFlight > 0 || [...this.staticReconcileItems.values()].some((item) => item.lifecycleUid === uid && item.disposition !== "recovered");
55
+ }
56
+ resources() { return this.staticReconcileLastSweepResources; }
57
+ setResources(value) { this.staticReconcileLastSweepResources = value; }
58
+ stop() {
59
+ this.staticReconcileStopping = true;
60
+ this.chatExpiry.stop();
61
+ for (const item of this.staticReconcileItems.values()) {
62
+ if (item.timer)
63
+ clearTimeout(item.timer);
64
+ item.timer = undefined;
65
+ item.nextRetryAt = undefined;
66
+ }
67
+ }
68
+ /** The static terminal for one departed incarnation: delegates the gate/head CAS
69
+ * sequence to the shared core saga over the executor transport; the footprint teardown (creds
70
+ * file + broker durables/ACL) runs INSIDE the barrier as its cleanup step. On completion the
71
+ * wire principal joins {@link retiredPrincipals} (the retired-principal refusal index) and the name hold
72
+ * clears (ABA-guarded by uid). A lifecycle with no slot row (spawned before the
73
+ * durable registry existed) has nothing to terminalize: its footprint teardown runs directly
74
+ * and the hold clears, the honest upgrade path. `onDeprovision` receives the accounting of the
75
+ * broker teardown this call ran, on success or on a {@link DeprovisionError}. */
76
+ async driveStaticRetirement(a, surfaceFailure = false, onDeprovision) {
77
+ // A renewal that published its flight before the synchronous terminal latch is accepted work.
78
+ // Drain it before the durable terminal enumerates credential ids and before cleanup deletes its
79
+ // material; a failed renewal must not block retirement because it may still have staged an id.
80
+ const acceptedRenewal = a.staticCredentialRenewal;
81
+ if (acceptedRenewal)
82
+ await acceptedRenewal.catch(() => { });
83
+ const opId = managedRetirementOpId(a.lifecycleUid);
84
+ const evict = this.deps.evictor() ?? makeManagerEndpointEvictionEvidence({
85
+ space: this.deps.space(),
86
+ servers: this.deps.servers() ?? DEFAULT_SERVER,
87
+ auth: this.deps.auth(),
88
+ log: (line) => console.error(`static retirement ${a.name}: ${line}`),
89
+ // A daemon credential reload briefly removes its responder while it reconnects.
90
+ unreachableWaitMs: DEPROVISION_TIMEOUT_MS,
91
+ });
92
+ const cleanup = async () => {
93
+ // SPEC 13.15: every issuance bound to this incarnation's ledger family is retired here,
94
+ // inside the barrier and after the ledger rows were revoked (the source is frozen first,
95
+ // then the index is walked). A retirement that lost is surfaced, never skipped: an active
96
+ // attempt row on a retired lifecycle would authorize a run the credential no longer can.
97
+ const retired = await this.deps.withIssuer((i) => i.store.retireSource({ space: this.deps.space(), bucket: epAuthBucket(this.deps.space()), key: `cred.${a.lifecycleUid}` }));
98
+ if (retired > 0)
99
+ console.error(`static retirement ${a.name}: retired ${retired} issuance(s) bound to uid ${a.lifecycleUid}`);
100
+ const secrets = this.deps.secrets();
101
+ const files = a.secretPaths ?? agentLifecycleSecretFilePaths(this.deps.workspaceRoot(), this.deps.space(), a.name, a.lifecycleUid);
102
+ // The broker teardown mints its own credential, so a creds file that cannot be removed must not
103
+ // skip it. The failures are thrown together, so the terminal still stops at an incomplete cleanup.
104
+ const failed = [];
105
+ if (files.creds) {
106
+ const creds = files.creds;
107
+ await attemptCleanup(failed, `secret ${creds}`, () => secrets.delete(agentSecretKeyForFile(creds, this.deps.space())));
108
+ await attemptCleanup(failed, `file ${creds}`, () => rmSync(creds, { force: true }));
109
+ }
110
+ // The lifecycle's inline snapshot, when no earlier step settled it. Keyed by the uid, so a boot
111
+ // sweep or a reconcile that knows only the slot row removes it too.
112
+ if (!a.snapshotSettled) {
113
+ const snapshot = inlineSnapshotPath(this.deps.workspaceRoot(), a.lifecycleUid);
114
+ await attemptCleanup(failed, `file ${snapshot}`, () => removeInlineSnapshot(this.deps.workspaceRoot(), a.lifecycleUid));
115
+ }
116
+ await attemptCleanup(failed, "broker teardown", async () => {
117
+ try {
118
+ const accounting = await this.deps.deprovisionBroker(a);
119
+ onDeprovision?.(accounting);
120
+ }
121
+ catch (e) {
122
+ if (e instanceof DeprovisionError)
123
+ onDeprovision?.(e.accounting);
124
+ throw e;
125
+ }
126
+ });
127
+ if (failed.length)
128
+ throw new Error(`cleanup failed: ${describeCleanupFailures(failed)}`);
129
+ };
130
+ // The process goes before its footprint: reap the orphan seat by reference, then tear down.
131
+ const reapThenCleanup = async () => {
132
+ await this.deps.reapOrphanSeat(a);
133
+ await cleanup();
134
+ };
135
+ try {
136
+ await this.deps.withLifecycleExecutor({ owner: DEV_OWNER, actor: a.id, lifecycleUid: a.lifecycleUid, alias: a.name }, async (t) => {
137
+ const slot = await readStaticSlot(t, DEV_OWNER, a.name);
138
+ if (slot === undefined || slot.row.lifecycleUid !== a.lifecycleUid) {
139
+ // No durable registration for THIS incarnation: a spawn from before the registry (or a slot already
140
+ // replaced by a successor - then this stale teardown must not touch the registry at all).
141
+ await reapThenCleanup();
142
+ return;
143
+ }
144
+ await runStaticTerminal(t, {
145
+ owner: DEV_OWNER, alias: a.name, actor: a.id, lifecycleUid: a.lifecycleUid, opId,
146
+ managerInstance: this.deps.instanceId(), managerProcessUid: this.deps.processUid(),
147
+ }, { cleanup: reapThenCleanup, evict, log: (line) => console.error(`static retirement ${a.name}: ${line}`) });
148
+ });
149
+ this.deps.recordStaticRetirement(a);
150
+ }
151
+ catch (e) {
152
+ const h = this.deps.retirementFor(a.name);
153
+ if (h && h.target.lifecycleUid === a.lifecycleUid)
154
+ h.lastError = `the static retirement did not complete (${rejectionText(e)}); the name stays held - a same-name spawn retries the same terminal (op ${opId})`;
155
+ console.error(`static retirement ${a.name} (${a.id}): ${rejectionText(e)}`);
156
+ if (surfaceFailure)
157
+ throw e;
158
+ }
159
+ }
160
+ /** `chat-session-open`: admit one static chat session. The manager draws the `chat_` alias and a
161
+ * fresh nkey identity, then runs the same native steps a static spawn does: the slot intent and
162
+ * the shared activation saga, the provisioner's bind-only DM and DELIVER durables plus the ACL
163
+ * row, and the agent-profile mint. The leaf carries the spawn's three lists under the spawn's
164
+ * rules (`resolveReadAcl`, a default-deny post list, the foreign event-channel refusal) and
165
+ * nothing else: no role (so no TASK queue), no capabilities, no endpoint rows, no issuance. It
166
+ * expires at `ttl` with no renewal, because no managed row exists to renew it.
167
+ *
168
+ * The session is registered with the tracker before the first durable write and scheduled for
169
+ * its expiry before the reply is sent, or after a rollback that did not complete, so this
170
+ * process retires it at the expiry even when the reply is lost or the client never retires.
171
+ *
172
+ * The credential is ledgered before it leaves this process (slot credentialId, then the `cred.`
173
+ * row), so the static terminal marks the row revoked and verify-evicts the session's principal;
174
+ * the broker keeps accepting the leaf until its expiry. The direct ledger write is deliberate:
175
+ * the leaf is not an issuance, so the issuance seam, which writes the same row inside its
176
+ * finalization, never runs for it, and without the row the terminal's eviction set would be
177
+ * empty. The credential leaves only sealed to `sealTo`, bound to the space, this instance and
178
+ * the reply's fields, so a reply printed anywhere carries no usable credential. A failure at
179
+ * any step drives the terminal before the refusal is returned, and the refusal says whether it
180
+ * completed. */
181
+ async openStaticChatSession(raw) {
182
+ if (!this.deps.auth() || this.deps.userMode())
183
+ throw new EpEnvelopeError("unimplemented", "chat-session-open admits static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
184
+ const input = readChatOpenInput(raw);
185
+ if ("error" in input)
186
+ throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
187
+ const lists = chatOpenLists(input);
188
+ if ("error" in lists)
189
+ throw new EpEnvelopeError("bad-request", lists.error, undefined, "not-executed");
190
+ const alias = drawChatAlias();
191
+ const identity = newIdentity();
192
+ // The spawn's rule, against the drawn actor: a concrete event channel of any other principal is
193
+ // refused, and a wildcard is an ordinary grant.
194
+ const foreign = this.deps.foreignEventChannels([...lists.allowSubscribe, ...lists.allowPublish], DEV_OWNER, identity.id);
195
+ if (foreign.length)
196
+ throw new EpEnvelopeError("bad-request", `chat-session-open asks for another agent's event channel: ${foreign.join(", ")}. A session may be granted its OWN event plane and no other, because that plane carries the session's tool inputs and outputs. Grant a reader out of band rather than through a chat session: ${this.deps.readerRemedy(DEV_OWNER, foreign[0])}`, undefined, "not-executed");
197
+ const lifecycleUid = mintLifecycleUid();
198
+ const exp = Math.floor(Date.now() / 1000) + input.ttl;
199
+ const pin = { owner: DEV_OWNER, actor: identity.id, lifecycleUid, alias };
200
+ const session = { alias, actor: identity.id, lifecycleUid, channels: lists.allowSubscribe, expiresAt: exp * 1000 };
201
+ // Registered before the first durable write, so the startup sweep never mistakes this opening's
202
+ // provisioning row for a crashed spawn, and the stop knows it.
203
+ try {
204
+ this.chatExpiry.register(session);
205
+ }
206
+ catch (e) {
207
+ throw new EpEnvelopeError("unavailable", rejectionText(e), undefined, "not-executed");
208
+ }
209
+ try {
210
+ await this.deps.withLifecycleExecutor(pin, (t) => activateStaticLifecycle(t, { owner: DEV_OWNER, alias, actor: identity.id, lifecycleUid, managerInstance: this.deps.processUid(), ownerInstanceId: this.deps.instanceId() }));
211
+ const creds = await this.deps.withProvisioner((prov) => provisionAgent(prov, this.deps.auth(), identity, { subscribe: lists.subscribe, allowSubscribe: lists.allowSubscribe, allowPublish: lists.allowPublish, lifecycleUid, expiresAt: exp }));
212
+ // The same credential id the issuance path derives, so a re-sent identical credential maps to
213
+ // the same row.
214
+ const credentialId = credentialIdOf(creds);
215
+ await this.deps.withLifecycleExecutor(pin, async (t) => {
216
+ await recordSlotCredential(t, DEV_OWNER, alias, lifecycleUid, credentialId);
217
+ await appendStaticCredentialRow(t, { lifecycleUid, credentialId, holderPrincipal: principalKey(DEV_OWNER, identity.id).key, exp });
218
+ const slot = await readStaticSlot(t, DEV_OWNER, alias);
219
+ if (slot === undefined || slot.row.lifecycleUid !== lifecycleUid || slot.row.phase !== "provisioning")
220
+ throw new Error(`the static slot for "${alias}" is ${slot === undefined ? "absent" : `${slot.row.phase} at uid ${slot.row.lifecycleUid}`}, not this opening's provisioning intent`);
221
+ await casStaticSlot(t, { ...slot.row, phase: "active" }, slot.revision);
222
+ });
223
+ const { sealer, sealed } = sealChatAdmission({
224
+ space: this.deps.space(), managerInstanceId: this.deps.instanceId(), alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealTo: input.sealTo, creds,
225
+ });
226
+ this.chatExpiry.arm(lifecycleUid);
227
+ console.error(`chat session ${alias} admitted as ${identity.id} (uid ${lifecycleUid}), expires ${new Date(exp * 1000).toISOString()}`);
228
+ return { alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealer, sealed };
229
+ }
230
+ catch (e) {
231
+ // A confirmed rollback leaves a known state, a retired slot. An unconfirmed one does not, so
232
+ // the session stays registered and its expiry, or the stop, retries the same terminal.
233
+ let rollback;
234
+ try {
235
+ await this.chatTerminal(session);
236
+ }
237
+ catch (r) {
238
+ rollback = rejectionText(r);
239
+ try {
240
+ this.chatExpiry.arm(lifecycleUid);
241
+ }
242
+ catch (t) {
243
+ rollback += `; ${rejectionText(t)}`;
244
+ }
245
+ }
246
+ throw new EpEnvelopeError(e instanceof EpEnvelopeError ? e.code : "unavailable", `chat-session-open did not complete for ${alias}: ${rejectionText(e)}; ${rollback === undefined ? "its rollback retired the slot" : `its rollback was not confirmed (${rollback}), so the slot stays held until a retire, its expiry here, this manager's stop, or the next start of this manager instance`}`, undefined, rollback === undefined ? "executed" : "unknown");
247
+ }
248
+ }
249
+ /** `chat-session-retire`: end one static chat session through the native static terminal (ledger
250
+ * row marked revoked, verified eviction of its principal's live connections, footprint cleanup,
251
+ * gate and head retirement). It refuses before any effect unless {@link admitChatRetirement}
252
+ * admits the request. A terminal that cannot complete answers `failed` with the reason, never
253
+ * success; the slot stays held. The broker keeps accepting the leaf until its expiry either way. */
254
+ async retireStaticChatSession(raw) {
255
+ if (!this.deps.auth() || this.deps.userMode())
256
+ throw new EpEnvelopeError("unimplemented", "chat-session-retire retires static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
257
+ const input = readChatRetireInput(raw);
258
+ if ("error" in input)
259
+ throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
260
+ if (await this.admitChatRetirement(input) === "alreadyRetired")
261
+ return { outcome: "alreadyRetired" };
262
+ try {
263
+ await this.chatTerminal({ ...input, channels: this.chatExpiry.channels(input.lifecycleUid) });
264
+ }
265
+ catch (e) {
266
+ return { outcome: "failed", reason: `retirement pending: ${rejectionText(e)}` };
267
+ }
268
+ return { outcome: "retired" };
269
+ }
270
+ /** The expiry cleanup's retirement of one session this process admitted. It is lifecycle work, so
271
+ * it is admitted like a control call and a stop drains it. A throw is a failure the tracker
272
+ * retries; a slot that is no longer this instance's to retire ends the tracking instead. */
273
+ async expireStaticChatSession(session) {
274
+ const release = this.deps.beginLifecycle();
275
+ if (!release)
276
+ throw new Error(this.deps.maintenanceError());
277
+ try {
278
+ console.error(`chat session ${session.alias} (uid ${session.lifecycleUid}) reached its expiry; retiring it`);
279
+ let admitted;
280
+ try {
281
+ admitted = await this.admitChatRetirement(session);
282
+ }
283
+ catch (e) {
284
+ if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
285
+ console.error(`! chat session ${session.alias} expired, but its slot is not this instance's to retire (${e.message}); expiry tracking ends`);
286
+ return;
287
+ }
288
+ throw e;
289
+ }
290
+ if (admitted === "admitted")
291
+ await this.chatTerminal(session);
292
+ }
293
+ finally {
294
+ release();
295
+ }
296
+ }
297
+ /** The ownership admission shared by `chat-session-retire`, the expiry and the stop. It throws a
298
+ * not-executed refusal unless the alias is a chat alias whose slot this logical instance owns
299
+ * at the requested UID and actor. An already retired slot ends its expiry tracking. */
300
+ async admitChatRetirement(s) {
301
+ if (!isChatAlias(s.alias))
302
+ throw new EpEnvelopeError("permission-denied", `"${s.alias}" is not a chat session alias`, undefined, "not-executed");
303
+ if (this.reconcilingAliases.has(s.alias))
304
+ throw new EpEnvelopeError("unavailable", `the chat session "${s.alias}" is still reconciling at manager startup; that terminal owns it`, undefined, "not-executed");
305
+ const recordsKv = this.deps.records();
306
+ if (!recordsKv)
307
+ throw new EpEnvelopeError("unavailable", `the durable static slot store is not ready while retiring "${s.alias}"`, undefined, "not-executed");
308
+ let slot;
309
+ try {
310
+ slot = await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, s.alias);
311
+ }
312
+ catch (e) {
313
+ throw new EpEnvelopeError("unavailable", `the durable slot for "${s.alias}" could not be read: ${rejectionText(e)}`, undefined, "not-executed");
314
+ }
315
+ const refused = chatRetireRefusal(slot?.row, s, this.deps.instanceId());
316
+ if (refused)
317
+ throw new EpEnvelopeError(refused.code, refused.message, undefined, "not-executed");
318
+ if (slot.row.phase !== "retired")
319
+ return "admitted";
320
+ this.chatExpiry.forget(s.lifecycleUid);
321
+ return "alreadyRetired";
322
+ }
323
+ /** One static terminal per chat session UID, however many callers ask: the explicit retire, the
324
+ * expiry cleanup and the open's rollback join it instead of racing its CAS sequence. A completed
325
+ * terminal ends the expiry tracking. `channels` names the membership rows to delete by name;
326
+ * without it the delivery inventory alone finds them. */
327
+ chatTerminal(s) {
328
+ let flight = this.chatRetirements.get(s.lifecycleUid);
329
+ if (!flight) {
330
+ flight = this.deps.withRetirementSlot(() => this.driveStaticRetirement({ id: s.actor, name: s.alias, lifecycleUid: s.lifecycleUid, secretPaths: {}, ...(s.channels ? { launch: { allowSubscribe: s.channels } } : {}) }, true))
331
+ .then(() => this.chatExpiry.forget(s.lifecycleUid))
332
+ .finally(() => this.chatRetirements.delete(s.lifecycleUid));
333
+ this.chatRetirements.set(s.lifecycleUid, flight);
334
+ }
335
+ return flight;
336
+ }
337
+ /** Whether `row` is a chat slot this process registered, at its exact alias, actor and UID,
338
+ * under this logical instance and this process's incarnation. */
339
+ holdsLiveChatSlot(row) {
340
+ return row.ownerInstanceId === this.deps.instanceId() && row.managerInstance === this.deps.processUid() && this.chatExpiry.holdsExact(row);
341
+ }
342
+ /** The stop's retirement of every chat session this process still tracks, through the same
343
+ * ownership admission and terminal as `chat-session-retire`, at most
344
+ * {@link CHAT_EXPIRY_CONCURRENCY} at a time. It runs after the lifecycle fence closed and every
345
+ * admitted operation drained, as the seat teardown does, and mints nothing the terminal does not
346
+ * already mint. Every outcome is logged. It throws, naming each one, when any session was not
347
+ * retired; that session stays held until the next start of this manager instance. */
348
+ async retireChatSessionsOnStop() {
349
+ const queue = this.chatExpiry.remaining();
350
+ const failed = [];
351
+ const retireOne = async (session) => {
352
+ const at = `chat session ${session.alias} (uid ${session.lifecycleUid})`;
353
+ try {
354
+ if (await this.admitChatRetirement(session) === "alreadyRetired") {
355
+ console.error(`${at} was already retired at stop`);
356
+ return;
357
+ }
358
+ await this.chatTerminal(session);
359
+ console.error(`${at} retired at stop`);
360
+ }
361
+ catch (e) {
362
+ if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
363
+ this.chatExpiry.forget(session.lifecycleUid);
364
+ console.error(`! ${at} was not retired at stop: its slot is not this instance's to retire (${e.message})`);
365
+ return;
366
+ }
367
+ failed.push(`${session.alias} (uid ${session.lifecycleUid}): ${rejectionText(e)}`);
368
+ console.error(`! ${at} was not retired at stop (${rejectionText(e)}); it stays held until the next start of this manager instance`);
369
+ }
370
+ };
371
+ await Promise.all(Array.from({ length: Math.min(CHAT_EXPIRY_CONCURRENCY, queue.length) }, async () => {
372
+ for (let next = queue.shift(); next !== undefined; next = queue.shift())
373
+ await retireOne(next);
374
+ }));
375
+ if (failed.length)
376
+ throw new Error(`${failed.length} chat session(s) were not retired and stay held until the next start of this manager instance: ${failed.join("; ")}`);
377
+ }
378
+ /** Name, at a stop that does not retire them, each chat session this process still tracks. */
379
+ reportChatSessionsLeftAtStop(why) {
380
+ for (const session of this.chatExpiry.remaining())
381
+ console.error(`! chat session ${session.alias} (uid ${session.lifecycleUid}) was not retired because ${why}; the next start of this manager instance retires it`);
382
+ }
383
+ /** Push renewal of ONE live managed-static credential: re-mint the SAME nkey
384
+ * identity with the SAME scope (recorded on the managed row at spawn) and a fresh bounded
385
+ * exp, ledger the new credentialId (slot record first, then the row, then the file - a
386
+ * credential is never materialized before its ledger row exists), and re-sign the SAME
387
+ * lifecycle-keyed file the agent endpoint's source seam re-reads. Never advances the epoch;
388
+ * renewal remains the THIRD transition. */
389
+ async renewManagedStaticCred(a) {
390
+ if (!this.deps.auth() || !a.seed || !a.secretPaths?.creds)
391
+ throw new Error("renewManagedStaticCred: not a renewable managed-static agent");
392
+ // Admission is synchronous. An accepted renewal publishes its flight before its first caller can
393
+ // terminalize the agent; terminalization rejects later callers and drains this flight before the
394
+ // durable terminal starts, giving renewal-before-terminal and terminal-before-renewal one order.
395
+ if (a.terminalizing)
396
+ throw new Error("renewManagedStaticCred: the lifecycle is terminalizing; no credential is minted after the terminal begins");
397
+ if (a.staticCredentialRenewal)
398
+ return a.staticCredentialRenewal;
399
+ const renewal = this.driveManagedStaticCredRenewal(a).finally(() => {
400
+ if (a.staticCredentialRenewal === renewal)
401
+ a.staticCredentialRenewal = undefined;
402
+ });
403
+ a.staticCredentialRenewal = renewal;
404
+ return renewal;
405
+ }
406
+ async driveManagedStaticCredRenewal(a) {
407
+ // The SAME permission scope the spawn minted (recorded on the managed row): allowSubscribe/
408
+ // allowPublish/role/capabilities are the JWT-shaping inputs; `subscribe` (the active read
409
+ // set) shapes durable membership only and is not a mint input.
410
+ if (!a.issued)
411
+ throw new Error(`renewManagedStaticCred: ${a.name} carries no issuance; a static credential minted before SPEC 13.15 is not renewed under an unbound generation - respawn the agent`);
412
+ // A renewal never outlives the generation's horizon, and none is minted at or past it: the
413
+ // generation then authorizes nothing and its rows are being removed (SPEC 13.15).
414
+ const now = Math.floor(Date.now() / 1000);
415
+ const horizon = issuedHorizon(a.issued.generation);
416
+ if (now >= horizon)
417
+ throw new Error(`renewManagedStaticCred: ${a.name}'s issued generation reached its horizon ${new Date(horizon * 1000).toISOString()} (${STATIC_GENERATION_HORIZON_SEC / 86_400} days after its spawn) and is not renewed - respawn the agent (rotation instead of this cap: Cotal-AI/Cotal#4942)`);
418
+ const exp = Math.min(now + MANAGED_STATIC_TTL_SEC, horizon);
419
+ // A RENEWAL keeps the generation (SPEC 13.15): the same JWT-shaping inputs produce the same
420
+ // ceiling, which `confirm` verifies against the recorded evidence before the ledger append. A
421
+ // changed ceiling is refused there: that is a fresh issuance on a new connection, never a renewal.
422
+ const issued = a.issued;
423
+ const endpoints = lowerPersonaEndpoints(a.launch.endpoints);
424
+ const reads = this.deps.managedStaticInstanceReads(a.launch.capabilities);
425
+ if (reads.length) {
426
+ // Resolve this incarnation's original issuance, not its current spawner or a reconstructed
427
+ // run admission. Old seats and run helpers keep the exact ceiling they were minted with.
428
+ const caller = { owner: DEV_OWNER, actor: a.id, uid: a.lifecycleUid, generation: issued.generation };
429
+ const { evidence } = await withIssuerSession({ servers: this.deps.servers() ?? DEFAULT_SERVER, space: this.deps.space(), auth: this.deps.auth(), tls: false }, (s) => s.store.resolve({ space: this.deps.space(), ...caller }, s.sourceIsLive));
430
+ if (!grantOverreach(this.deps.space(), caller, evidence.permissions, { endpoints: reads }).length)
431
+ endpoints.push(...reads);
432
+ }
433
+ const creds = await this.deps.withIssuer((i) => mintCreds(this.deps.auth(), { id: a.id, seed: a.seed }, "agent", {
434
+ eventPayloads: this.deps.eventPayloadsWithheld() ? false : a.launch.eventPayloads,
435
+ allowSubscribe: a.launch.allowSubscribe,
436
+ allowPublish: a.launch.allowPublish,
437
+ role: a.role,
438
+ capabilities: a.launch.capabilities,
439
+ ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
440
+ lifecycleUid: a.lifecycleUid,
441
+ expiresAt: exp,
442
+ issued,
443
+ issuance: this.deps.issuanceSeam(i, "renew", a, exp),
444
+ }));
445
+ const secrets = this.deps.secrets();
446
+ const credsPath = a.secretPaths.creds;
447
+ await secrets.put(agentSecretKeyForFile(credsPath, this.deps.space()), creds);
448
+ await materializeSecretToFile(secrets, agentSecretKeyForFile(credsPath, this.deps.space()), credsPath);
449
+ // The record pins the credential's digest, so it follows the re-signed file.
450
+ this.deps.refreshSeatRecord(a);
451
+ console.error(`managed cred renewal ${a.name}: re-signed for the same identity (exp +${exp - now}s); the agent endpoint's source re-read adopts it`);
452
+ }
453
+ /** Render the current operator snapshot. Recovered rows live until the next sweep starts, then
454
+ * clear, so recovery is visible without becoming stale process-lifetime history. */
455
+ staticReconciliationStatus() {
456
+ const failures = [...this.staticReconcileItems.values()]
457
+ .map(({ owner: _owner, timer: _timer, flight: _flight, retryFlight: _retryFlight, ...item }) => ({ ...item }))
458
+ .sort((a, b) => a.alias.localeCompare(b.alias));
459
+ const state = this.staticReconcileLastSweep?.error !== undefined ? "failed" :
460
+ failures.some((item) => item.disposition === "retrying") ? "retrying" :
461
+ failures.some((item) => item.disposition === "retry-scheduled") ? "retry-wait" :
462
+ failures.some((item) => item.disposition === "refused" || item.disposition === "refused-foreign" || item.disposition === "retry-exhausted") ? "failed" :
463
+ this.staticReconcileSweepsInFlight > 0 ? "running" :
464
+ failures.some((item) => item.disposition === "recovered") ? "recovered" : "idle";
465
+ return {
466
+ state,
467
+ ...(this.staticReconcileLastSweep ? { lastSweep: { ...this.staticReconcileLastSweep } } : {}),
468
+ failures,
469
+ };
470
+ }
471
+ /** The static-slot reconciliation ("no active orphan"): ensure the authority stores, then sweep
472
+ * every durable slot row and act by the TOTAL resume table - `provisioning`/`terminalizing`
473
+ * re-drive the exact-op terminal; an `active` row survives ONLY when a LIVE managed agent this
474
+ * manager process owns backs it at the same uid (`adopted`), else no managed owner claimed it and
475
+ * its broker authority is contained and terminalized; `retired` rows seed the retired-principal refusal index. Two call sites: the BOOT sweep
476
+ * (`postAdoption=false`, under the lease before control serving) DEFERS active-non-adopted
477
+ * slots while a resume is still pending (adoption runs after it); the POST-ADOPTION sweep
478
+ * (`postAdoption=true`, inside finalizeResume while `resumeRequired` still fences ordinary
479
+ * spawns) terminalizes any active slot the resume did not claim. */
480
+ staticReconcileKey(row) {
481
+ return JSON.stringify([row.owner, row.alias, row.lifecycleUid]);
482
+ }
483
+ /** Read one retry coordinate from the durable slot store. The status snapshot never authorizes a
484
+ * re-drive: every timer comes through this fresh read before the planner and exact terminal. */
485
+ async readStaticReconcileSlot(alias) {
486
+ if (!this.deps.auth())
487
+ return undefined;
488
+ const identity = newIdentity();
489
+ const creds = await mintCreds(this.deps.auth(), identity, "provisioner");
490
+ const nc = await this.deps.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
491
+ try {
492
+ const recordsKv = await new Kvm(nc).open(recordsBucket(this.deps.space()));
493
+ return (await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, alias))?.row;
494
+ }
495
+ finally {
496
+ await drainAndClose(nc);
497
+ }
498
+ }
499
+ scheduleStaticReconcileRetry(key, item) {
500
+ if (this.staticReconcileStopping || item.timer || item.attempts >= item.maxAttempts)
501
+ return;
502
+ const delay = this.deps.retryDelays()[item.attempts - 1];
503
+ if (delay === undefined)
504
+ return;
505
+ const nextRetryAtMs = Date.now() + delay;
506
+ item.disposition = "retry-scheduled";
507
+ item.nextRetryAt = new Date(nextRetryAtMs).toISOString();
508
+ item.timer = setTimeout(() => {
509
+ item.timer = undefined;
510
+ item.nextRetryAt = undefined;
511
+ const run = async () => {
512
+ // The timer may fire while the failed attempt is still unwinding, especially in compressed
513
+ // smoke schedules. Join that flight before consuming another budget entry; never overlap it.
514
+ if (item.flight)
515
+ await item.flight;
516
+ await this.retryStaticReconcile(key);
517
+ };
518
+ void run().catch((error) => {
519
+ item.lastError = `retry driver failed before the exact terminal: ${rejectionText(error)}`;
520
+ item.disposition = "retry-exhausted";
521
+ item.remedy = "restart this manager for a fresh per-process retry budget";
522
+ console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
523
+ });
524
+ }, delay);
525
+ item.timer.unref?.();
526
+ console.error(`! static reconcile retry-scheduled alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts + 1}/${item.maxAttempts} nextRetryAt=${item.nextRetryAt}`);
527
+ }
528
+ retryStaticReconcile(key) {
529
+ const item = this.staticReconcileItems.get(key);
530
+ if (!item || this.staticReconcileStopping || item.disposition === "recovered")
531
+ return Promise.resolve();
532
+ if (item.retryFlight)
533
+ return item.retryFlight;
534
+ const flight = this.driveStaticReconcileRetry(key, item);
535
+ let wrapped;
536
+ wrapped = flight.finally(() => {
537
+ if (item.retryFlight === wrapped)
538
+ item.retryFlight = undefined;
539
+ });
540
+ item.retryFlight = wrapped;
541
+ return wrapped;
542
+ }
543
+ async driveStaticReconcileRetry(key, item) {
544
+ if (item.flight)
545
+ await item.flight;
546
+ if (this.staticReconcileStopping || item.disposition === "recovered")
547
+ return;
548
+ // A retry trigger consumes one finite budget entry even if the authoritative re-read itself
549
+ // fails. Otherwise a broker outage before the planner could reschedule forever without ever
550
+ // incrementing `attempts`, violating the bounded-retry guarantee.
551
+ item.attempts++;
552
+ item.disposition = "retrying";
553
+ item.remedy = undefined;
554
+ console.error(`static reconcile retrying alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
555
+ let row;
556
+ try {
557
+ row = await this.readStaticReconcileSlot(item.alias);
558
+ }
559
+ catch (error) {
560
+ item.lastError = `durable slot re-read failed: ${rejectionText(error)}`;
561
+ if (item.attempts >= item.maxAttempts) {
562
+ item.disposition = "retry-exhausted";
563
+ item.remedy = "restart this manager for a fresh per-process retry budget";
564
+ console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
565
+ }
566
+ else {
567
+ this.scheduleStaticReconcileRetry(key, item);
568
+ }
569
+ return;
570
+ }
571
+ if (row === undefined || row.owner !== item.owner || row.actor !== item.actor || row.lifecycleUid !== item.lifecycleUid) {
572
+ item.disposition = "refused";
573
+ item.remedy = "inspect the durable slot; reconciliation will not cross incarnations";
574
+ item.lastError = row === undefined
575
+ ? "the durable slot vanished; reconciliation never acts from the in-memory snapshot"
576
+ : `the durable slot moved to actor ${row.actor} uid ${row.lifecycleUid}; reconciliation never crosses incarnations`;
577
+ console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
578
+ return;
579
+ }
580
+ item.phase = row.phase;
581
+ if (row.phase === "retired") {
582
+ item.disposition = "recovered";
583
+ item.recoveredAt = new Date().toISOString();
584
+ item.lastError = undefined;
585
+ console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
586
+ return;
587
+ }
588
+ if (ownedBySibling(row, this.deps.instanceId())) {
589
+ item.disposition = "refused";
590
+ item.remedy = "the owning manager must reconcile or an operator must perform an explicit CAS takeover";
591
+ item.lastError = `the durable slot belongs to manager instance ${row.ownerInstanceId}, not ${this.deps.instanceId()}`;
592
+ console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
593
+ return;
594
+ }
595
+ const live = this.deps.agentFor(row.alias);
596
+ const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
597
+ if (planStaticSlotResume(row, adopted) !== "drive-terminal") {
598
+ item.disposition = "refused";
599
+ item.remedy = adopted ? "leave the adopted live lifecycle running" : "inspect the fresh durable slot state";
600
+ item.lastError = adopted
601
+ ? "the durable lifecycle is now backed by an adopted live managed agent"
602
+ : `the fresh durable phase ${row.phase} is not terminal-plannable`;
603
+ console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
604
+ return;
605
+ }
606
+ await this.attemptStaticReconcile(key, item, row, false);
607
+ }
608
+ /** Enter one exact terminal at most once per coordinate. Sweep and timer triggers join the same
609
+ * promise. A settled failed item keeps its original per-process budget; a restart builds a fresh
610
+ * map from the still-authoritative durable row. */
611
+ attemptStaticReconcile(key, item, row, countAttempt = true) {
612
+ if (item.flight)
613
+ return item.flight;
614
+ if (item.timer)
615
+ return Promise.resolve({ succeeded: false });
616
+ // A timer/retry driver increments before its mandatory durable re-read, then calls with
617
+ // countAttempt=false. Let that already-consumed budget entry enter the terminal. Only a fresh
618
+ // sweep entry (countAttempt=true) is refused once the per-process budget is exhausted.
619
+ if (countAttempt && item.attempts >= item.maxAttempts)
620
+ return Promise.resolve({ succeeded: false });
621
+ const flight = (async () => {
622
+ if (countAttempt)
623
+ item.attempts++;
624
+ item.phase = row.phase;
625
+ item.disposition = "retrying";
626
+ item.nextRetryAt = undefined;
627
+ this.reconcilingAliases.add(row.alias);
628
+ console.error(`static reconcile terminal alias=${row.alias} phase=${row.phase} uid=${row.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
629
+ let deprovision;
630
+ try {
631
+ await this.deps.withRetirementSlot(() => this.driveStaticRetirement({ id: row.actor, name: row.alias, lifecycleUid: row.lifecycleUid, runtime: row.runtime }, true, (accounting) => { deprovision = accounting; }));
632
+ if (item.attempts === 1) {
633
+ this.staticReconcileItems.delete(key);
634
+ }
635
+ else {
636
+ item.phase = "retired";
637
+ item.disposition = "recovered";
638
+ item.recoveredAt = new Date().toISOString();
639
+ item.lastError = undefined;
640
+ console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
641
+ }
642
+ return { succeeded: true, deprovision };
643
+ }
644
+ catch (error) {
645
+ item.lastError = rejectionText(error);
646
+ try {
647
+ const fresh = await this.readStaticReconcileSlot(item.alias);
648
+ if (fresh?.lifecycleUid === item.lifecycleUid && fresh.actor === item.actor)
649
+ item.phase = fresh.phase;
650
+ }
651
+ catch { /* the terminal error remains primary; the next retry re-reads authoritatively */ }
652
+ const blocked = lifecycleBlockedFrom(error);
653
+ const ownOp = managedRetirementOpId(item.lifecycleUid);
654
+ const foreign = blocked !== undefined && (blocked.blockedOp !== "retirement" || blocked.opId !== ownOp);
655
+ if (foreign) {
656
+ item.disposition = "refused-foreign";
657
+ item.remedy = blocked?.remedy ?? "resolve the foreign durable operation; it is never force-cleared";
658
+ console.error(`! static reconcile refused-foreign alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
659
+ }
660
+ else if (item.attempts >= item.maxAttempts) {
661
+ item.disposition = "retry-exhausted";
662
+ item.remedy = "restart this manager for a fresh per-process retry budget";
663
+ console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
664
+ }
665
+ else {
666
+ // The initial serial sweep must publish its complete failed aggregate before any timer can
667
+ // re-enter a middle row. Mark it now; the sweep arms the timer after its last planned row.
668
+ if (this.staticReconcileSweepsInFlight > 0)
669
+ item.disposition = "retry-scheduled";
670
+ else
671
+ this.scheduleStaticReconcileRetry(key, item);
672
+ }
673
+ return { succeeded: false, deprovision };
674
+ }
675
+ finally {
676
+ this.reconcilingAliases.delete(row.alias);
677
+ }
678
+ })();
679
+ item.flight = flight.finally(() => {
680
+ if (item.flight === wrapped)
681
+ item.flight = undefined;
682
+ });
683
+ const wrapped = item.flight;
684
+ return wrapped;
685
+ }
686
+ releaseStaticReconcileSweep() {
687
+ this.staticReconcileSweepsInFlight--;
688
+ if (this.staticReconcileSweepsInFlight !== 0)
689
+ return;
690
+ const waiters = this.staticReconcileDrainWaiters;
691
+ this.staticReconcileDrainWaiters = [];
692
+ for (const wake of waiters)
693
+ wake();
694
+ }
695
+ /** Shutdown accepts no new static reconciliation work, then drains every sweep and exact-terminal
696
+ * flight that crossed the fence before stop(). A sweep can discover several rows before its first
697
+ * await, so the serial loop also consults the fence and never starts a later row after shutdown. */
698
+ async awaitStaticReconcileDrain() {
699
+ while (true) {
700
+ if (this.staticReconcileSweepsInFlight > 0)
701
+ await new Promise((resolve) => this.staticReconcileDrainWaiters.push(resolve));
702
+ const flights = [];
703
+ for (const item of this.staticReconcileItems.values()) {
704
+ if (item.flight)
705
+ flights.push(item.flight);
706
+ if (item.retryFlight)
707
+ flights.push(item.retryFlight);
708
+ }
709
+ if (flights.length === 0 && this.staticReconcileSweepsInFlight === 0)
710
+ return;
711
+ await Promise.allSettled(flights);
712
+ }
713
+ }
714
+ async reconcileStaticLifecycles(postAdoption = false) {
715
+ if (!this.deps.auth() || this.staticReconcileStopping)
716
+ return;
717
+ // Admission is synchronous with the shutdown fence. Once this increments, stop() must drain the
718
+ // whole accepted sweep even if it is still minting its short-lived provisioner credential.
719
+ this.staticReconcileSweepsInFlight++;
720
+ try {
721
+ // Recovered is a transition report, not permanent history. The next sweep clears it before
722
+ // deriving a fresh plan; failed coordinates keep their per-process budget and are joined.
723
+ for (const [key, item] of this.staticReconcileItems) {
724
+ if (item.disposition === "recovered")
725
+ this.staticReconcileItems.delete(key);
726
+ }
727
+ const sweep = {
728
+ kind: postAdoption ? "post-adoption" : "startup",
729
+ startedAt: new Date().toISOString(),
730
+ attempted: 0,
731
+ succeeded: 0,
732
+ failed: 0,
733
+ };
734
+ this.staticReconcileLastSweep = sweep;
735
+ const slotRows = [];
736
+ // A sweep that stops before it plans any alias records why on the sweep itself: otherwise
737
+ // `status` cannot tell it from a sweep that collected and found nothing.
738
+ try {
739
+ const identity = newIdentity();
740
+ const creds = await mintCreds(this.deps.auth(), identity, "provisioner");
741
+ const nc = await this.deps.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
742
+ try {
743
+ const jsm = await jetstreamManager(nc);
744
+ const kvm = new Kvm(nc);
745
+ await ensureAuthorityStores(jsm, kvm, this.deps.space());
746
+ const recordsKv = await kvm.open(recordsBucket(this.deps.space()));
747
+ for (const slot of await walkStaticSlots(recordsKv, DEV_OWNER))
748
+ slotRows.push(slot.row);
749
+ }
750
+ finally {
751
+ await drainAndClose(nc);
752
+ }
753
+ }
754
+ catch (error) {
755
+ sweep.completedAt = new Date().toISOString();
756
+ sweep.error = rejectionText(error);
757
+ throw error;
758
+ }
759
+ let retiredSlots = 0;
760
+ let preservedForeign = 0;
761
+ let preservedAdopted = 0;
762
+ let deferredSlots = 0;
763
+ const terminalRows = [];
764
+ const restartRows = [];
765
+ for (const row of slotRows) {
766
+ if (row.phase === "retired") {
767
+ // A retirement is a GLOBAL refusal fact - seed the retired-principal index for EVERY retired incarnation
768
+ // regardless of which instance owned it, so a sibling-retired incarnation's copied credential
769
+ // is refused at this control surface too. Ownership gates only the DESTRUCTIVE sweep below.
770
+ this.deps.noteRetiredPrincipal(principalKey(row.owner, row.actor).key);
771
+ retiredSlots++;
772
+ continue;
773
+ }
774
+ // RECONCILE OWNERSHIP (multi-manager-per-space): a manager adjudicates ONLY the non-retired
775
+ // rows THIS logical instance owns. A SIBLING manager's active/provisioning row is LEFT UNTOUCHED -
776
+ // sweep-terminalizing it would destroy the sibling's live agent (the historical all-agents-kill
777
+ // hazard, now cross-instance). A legacy row (no owner recorded) predates multi-manager,
778
+ // so this manager is its legitimate single-manager-past successor and reconciles it. An orphaned
779
+ // sibling row is reclaimed only by an explicit operator CAS takeover, never here.
780
+ if (ownedBySibling(row, this.deps.instanceId())) {
781
+ preservedForeign++;
782
+ continue;
783
+ }
784
+ // A chat session this process is opening or holds is live membership, as an adopted seat
785
+ // is: its own open, expiry or stop runs its terminal, which this sweep must not race. The
786
+ // match is the exact registered alias, actor and UID under this logical instance and this
787
+ // process's incarnation, so a foreign, legacy or unrecorded row, or any UID this process
788
+ // did not register, falls through to the ordinary plan below.
789
+ if (this.holdsLiveChatSlot(row)) {
790
+ preservedAdopted++;
791
+ continue;
792
+ }
793
+ // ADOPTION is genuine membership: a slot backed by a live managed agent THIS process owns
794
+ // at the SAME uid is never an orphan (empty at boot; exactly the adopted set at the
795
+ // post-adoption sweep - the fix for the resume hole).
796
+ const live = this.deps.agentFor(row.alias);
797
+ const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
798
+ if (adopted) {
799
+ preservedAdopted++;
800
+ }
801
+ // Boot sweep with a resume PENDING: an active slot may yet be adopted (the resume path runs
802
+ // AFTER this boot sweep), so DEFER it - the post-adoption sweep terminalizes any the resume
803
+ // did not claim. provisioning/terminalizing NEVER defer (they are crashed operations, never
804
+ // an agent to adopt). At `postAdoption` (or a non-resume boot) nothing defers.
805
+ if (!postAdoption && row.phase === "active" && !adopted && this.deps.resumeRequired()) {
806
+ deferredSlots++;
807
+ continue;
808
+ }
809
+ // A boot after this instance's manager ended without stopping its seats: a seat with a record
810
+ // is taken back instead of retired, restarted under its policy when supervised (#4094) and
811
+ // adopted while it still runs otherwise (#4095).
812
+ if (!postAdoption && row.phase === "active" && !adopted) {
813
+ const record = this.deps.seatRecordFor(row);
814
+ if (record) {
815
+ restartRows.push({ row, record });
816
+ continue;
817
+ }
818
+ }
819
+ if (planStaticSlotResume(row, adopted) !== "none")
820
+ terminalRows.push(row);
821
+ }
822
+ try {
823
+ // Mark the complete planned set before the first terminal awaits. A timer owns only its own
824
+ // alias, but the initial serial sweep must close every discovery-to-await gap up front.
825
+ for (const row of terminalRows)
826
+ this.reconcilingAliases.add(row.alias);
827
+ for (const { row } of restartRows)
828
+ this.reconcilingAliases.add(row.alias);
829
+ // Restarts run first; one that cannot restart joins the terminals below.
830
+ for (const { row, record } of restartRows) {
831
+ if (this.staticReconcileStopping)
832
+ break;
833
+ // A supervised seat is restarted; any other seat is adopted while it still runs.
834
+ const refusal = record.supervise ? await this.deps.restartSupervisedSeat(row, record) : await this.deps.adoptSeat(row, record);
835
+ if (refusal === undefined) {
836
+ this.reconcilingAliases.delete(row.alias);
837
+ continue;
838
+ }
839
+ console.error(record.supervise
840
+ ? `! ${row.alias}: the supervised seat its previous manager left was not restarted (${refusal}); retiring the lifecycle`
841
+ : `! ${row.alias}: the seat its previous manager left was not adopted (${refusal}); retiring the lifecycle`);
842
+ this.deps.dropSeatRecord({ name: row.alias, lifecycleUid: row.lifecycleUid });
843
+ terminalRows.push(row);
844
+ }
845
+ const sweepDeprovision = {
846
+ examined: 0,
847
+ deleted: 0,
848
+ absent: 0,
849
+ refused: 0,
850
+ acknowledged: 0,
851
+ disappeared: 0,
852
+ consumers: { examined: 0, deleted: 0, absent: 0, refused: 0, acknowledged: 0, disappeared: 0 },
853
+ acls: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
854
+ members: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
855
+ };
856
+ for (const row of terminalRows) {
857
+ if (this.staticReconcileStopping)
858
+ break;
859
+ sweep.attempted++;
860
+ const key = this.staticReconcileKey(row);
861
+ let item = this.staticReconcileItems.get(key);
862
+ if (!item) {
863
+ item = {
864
+ owner: row.owner,
865
+ alias: row.alias,
866
+ actor: row.actor,
867
+ lifecycleUid: row.lifecycleUid,
868
+ phase: row.phase,
869
+ attempts: 0,
870
+ maxAttempts: STATIC_RECONCILE_MAX_ATTEMPTS,
871
+ disposition: "retrying",
872
+ };
873
+ this.staticReconcileItems.set(key, item);
874
+ }
875
+ const attempt = await this.attemptStaticReconcile(key, item, row);
876
+ if (attempt.deprovision)
877
+ addDeprovisionAccounting(sweepDeprovision, attempt.deprovision);
878
+ if (attempt.succeeded)
879
+ sweep.succeeded++;
880
+ else
881
+ sweep.failed++;
882
+ this.reconcilingAliases.delete(row.alias);
883
+ }
884
+ sweep.completedAt = new Date().toISOString();
885
+ this.staticReconcileLastSweepResources = {
886
+ slots: {
887
+ examined: slotRows.length,
888
+ retired: retiredSlots,
889
+ preservedForeign,
890
+ preservedAdopted,
891
+ deferred: deferredSlots,
892
+ terminalized: sweep.succeeded,
893
+ failed: sweep.failed,
894
+ },
895
+ deprovision: sweepDeprovision,
896
+ };
897
+ for (const row of terminalRows) {
898
+ const key = this.staticReconcileKey(row);
899
+ const item = this.staticReconcileItems.get(key);
900
+ if (item?.disposition === "retry-scheduled" && !item.timer)
901
+ this.scheduleStaticReconcileRetry(key, item);
902
+ }
903
+ const failed = terminalRows.flatMap((row) => {
904
+ const item = this.staticReconcileItems.get(this.staticReconcileKey(row));
905
+ return item && item.disposition !== "recovered" ? [`${item.alias}:${item.phase}:${item.disposition}`] : [];
906
+ });
907
+ if (sweep.failed === 0) {
908
+ console.error(`✓ static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, 0 failed`);
909
+ }
910
+ else {
911
+ console.error(`! static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, ${sweep.failed} failed; failed=${failed.join(",")}`);
912
+ }
913
+ }
914
+ finally {
915
+ for (const row of terminalRows)
916
+ this.reconcilingAliases.delete(row.alias);
917
+ for (const { row } of restartRows)
918
+ this.reconcilingAliases.delete(row.alias);
919
+ }
920
+ }
921
+ finally {
922
+ this.releaseStaticReconcileSweep();
923
+ }
924
+ }
925
+ }
926
+ //# sourceMappingURL=managed-static-lifecycle.js.map