@cotal-ai/manager 0.166.3 → 0.167.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,664 @@
1
+ import { jetstreamManager } from "@nats-io/jetstream";
2
+ import { Kvm } from "@nats-io/kv";
3
+ import { DEFAULT_SERVER, DEV_OWNER, mintCreds, newIdentity, principalKey, inspectCredHealth, standaloneConnectOpts, serveEndpoint, drainAndClose, createEndpointStreams, contractStoreContext, publishContractArtifact, contractArtifactCanonicalBytes, provisionEndpointGateOpen, endpointRegistrationBarrier, serveIssuanceGateKv, readEndpointGateGeneration, registerServingInstance, mintLifecycleUid, rejectionText, commitSiblingIssuance, credentialIdOf, newArtifactSigner, RotatingSigner, generationAnchor, sessionsBucket, SESSION_GRANT_MAX_TTL_MS, epgateKey, markLedgerRowRevoked, epcredRowKey, } from "@cotal-ai/core";
4
+ import { claimManagerSiblingIdentities } from "@cotal-ai/workspace";
5
+ import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor } from "./endpoint-evict.js";
6
+ import { MANAGER_ENDPOINT, managerClusterArtifacts, managerContractArtifactValues } from "./manager-service-contract.js";
7
+ import { ManagerSessionPlane, openSessionLedgerKv } from "./session/index.js";
8
+ /** Registers and recovers the manager control service and its dedicated session authority. */
9
+ export class ServePlane {
10
+ deps;
11
+ /** Maps credentialId → the nkey that credential was minted for, for the live per-session
12
+ * SERVING credentials. The §13.1 ledger row records the holder principal, and the row is written
13
+ * at stage time (after the mint), so the two steps need this one hop. Entries are dropped at
14
+ * revoke; a session that never staged drops its entry when the manager exits. */
15
+ sessionServingKeys = new Map();
16
+ constructor(deps) {
17
+ this.deps = deps;
18
+ }
19
+ get auth() { return this.deps.auth(); }
20
+ get remoteAuthority() { return this.deps.remoteAuthority(); }
21
+ get space() { return this.deps.space(); }
22
+ get servers() { return this.deps.servers(); }
23
+ get workspaceRoot() { return this.deps.workspaceRoot(); }
24
+ get managerInstanceId() { return this.deps.managerInstanceId(); }
25
+ get managerServeIdentity() { return this.deps.managerServeIdentity(); }
26
+ get leaseStopping() { return this.deps.leaseStopping(); }
27
+ get remoteBundleRenewal() { return this.deps.remoteBundleRenewal(); }
28
+ get maxSessions() { return this.deps.maxSessions(); }
29
+ get serviceServe() { return this.deps.serviceServe(); }
30
+ set serviceServe(value) { this.deps.setServiceServe(value); }
31
+ get sessionLedgerIdentity() { return this.deps.sessionLedgerIdentity(); }
32
+ set sessionLedgerIdentity(value) { this.deps.setSessionLedgerIdentity(value); }
33
+ get sessionLedgerCreds() { return this.deps.sessionLedgerCreds(); }
34
+ set sessionLedgerCreds(value) { this.deps.setSessionLedgerCreds(value); }
35
+ get sessionLedgerConn() { return this.deps.sessionLedgerConn(); }
36
+ set sessionLedgerConn(value) { this.deps.setSessionLedgerConn(value); }
37
+ get sessionPlane() { return this.deps.sessionPlane(); }
38
+ set sessionPlane(value) { this.deps.setSessionPlane(value); }
39
+ get sessionKeyRenewTimer() { return this.deps.sessionKeyRenewTimer(); }
40
+ set sessionKeyRenewTimer(value) { this.deps.setSessionKeyRenewTimer(value); }
41
+ get connectorStatuses() { return this.deps.connectorStatuses(); }
42
+ /** #2073: dial the manager's ONE control-plane connection and serve its typed command surface on
43
+ * it. Shared by the
44
+ * initial registration AND the closed-connection recovery path ({@link onServeConnectionClosed}),
45
+ * so there is one place that dials and serves this endpoint. Attaches {@link
46
+ * onServeConnectionClosed} as the close handler in both cases: a closed serve connection is
47
+ * always a fault this manager acts on, never a bare log line. */
48
+ async dialServeConnection(state, readCreds = () => state.creds, deadline) {
49
+ const opts = {
50
+ // Open mesh: a bare serve connection (no credential exists; the broker enforces nothing).
51
+ ...(state.creds !== undefined ? standaloneConnectOpts({ creds: readCreds, tls: false }) : {}),
52
+ inboxPrefix: `_INBOX_${state.identity.id}`,
53
+ maxReconnectAttempts: -1,
54
+ };
55
+ const nc = await (deadline === undefined ? this.deps.dial(opts) : this.deps.dialRemoteStanding(opts, deadline));
56
+ this.deps.trackTransport(nc);
57
+ let handle;
58
+ try {
59
+ // The typed surface + the derived `describe`. The descriptor stays PUBLIC in static
60
+ // mode: the broker grant (who holds each command's request-publish row) is the
61
+ // load-bearing authority tier, and a static single-operator mesh leaks nothing by listing
62
+ // command names; the trusted per-caller `view(caller)` scoping joins the user-mode
63
+ // registration follow-up (where actorScope is the trusted source). Every ordinary handler
64
+ // runs the SHARED admission chokepoint ({@link serveGated}).
65
+ handle = serveEndpoint(nc, this.space, state.grant, this.deps.managerServiceDefs(), { public: true }, {
66
+ // The FRESH target resolver (§13.3) for the targeted commands (`despawn`/`attach`): the
67
+ // manager's live managed set IS the current-mapping authority for its own agents (the
68
+ // durable slot rows mirror it). Static mode carries no mapping-revision dimension, so
69
+ // the revision is the constant 0 - a caller that pins a revision pins 0.
70
+ resolveTarget: (t) => this.deps.resolveTarget(t),
71
+ ...(this.deps.omitClassCommands() ? { omitClassCommands: this.deps.omitClassCommands() } : {}),
72
+ });
73
+ // A subscribed replacement must be visible to the broker before the old rails retire.
74
+ if (deadline === undefined)
75
+ await nc.flush();
76
+ else
77
+ await this.deps.withTimeout(nc.flush(), this.deps.remoteStandingTimeLeft(deadline), "remote manager standing serve flush exceeded its 10000ms aggregate budget");
78
+ }
79
+ catch (e) {
80
+ await this.deps.discardServeCandidate(nc, handle);
81
+ throw e;
82
+ }
83
+ // Wired only once the connection serves: a candidate this method closes after a
84
+ // refused serve is not a fault to recover, and the caller already sees the refusal.
85
+ nc.closed().then((err) => {
86
+ if (this.serviceServe?.nc === nc)
87
+ void this.onServeConnectionClosed(err ?? undefined, nc);
88
+ });
89
+ return { nc, handle };
90
+ }
91
+ /** #2073: re-mint the SAME `endpoint-serve` identity through the SAME scoped one-shot executor and
92
+ * §13.1 mint fence `renewDaemonCreds`'s serve branch uses - never a second copy of that mint. Used
93
+ * by both the periodic renewal pass and the closed-connection recovery path below, so a
94
+ * superseded instance's re-mint fails the SAME gate CAS in both places and lands in the exit
95
+ * path rather than needing a second epoch check. */
96
+ async remintServeCreds(s) {
97
+ const authRef = this.auth;
98
+ return this.deps.withEndpointServeExecutor(({ authKv }) => mintCreds(authRef, s.identity, "endpoint-serve", {
99
+ serveIssuance: serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId }),
100
+ endpointServe: s.grant,
101
+ }));
102
+ }
103
+ /** #2073: a closed serve connection is a FAULT the manager acts on, not a log line: this is the
104
+ * control plane a report showed staying dead for hours while the process kept its liveness
105
+ * lease and answered nothing (#2073). `stop()` sets `leaseStopping` BEFORE it tears down this
106
+ * connection, so a close landing from OUR OWN graceful teardown returns here at once. Any other
107
+ * close re-dials with the current credential (a transport blip needs nothing new), re-mints
108
+ * through the existing serve branch when the credential itself has expired, and re-serves on the
109
+ * new connection - bounded by {@link STATIC_RECONCILE_RETRY_DELAYS_MS}. Exhausting every attempt
110
+ * releases this process's lease and exits loud (without `withAgents`, so seats stay up, the path
111
+ * `supervise`'s signal handler already uses) so a restart can serve: a manager that holds the
112
+ * lease and answers nothing is the worst of the three states this issue named, and holding the
113
+ * connection open under unbounded reconnects (the transport-drop case) never reaches this method
114
+ * at all - `nc.closed()` does not resolve until the client itself gives up. */
115
+ async onServeConnectionClosed(err, closed) {
116
+ if (this.leaseStopping)
117
+ return;
118
+ const s = this.serviceServe;
119
+ console.error(`! manager service endpoint connection closed: ${err?.message ?? "unknown reason"}`);
120
+ const recovered = await this.deps.boundedReconnect("service endpoint", async () => {
121
+ if (!s)
122
+ return false;
123
+ const deadline = this.remoteAuthority ? performance.now() + this.deps.remoteStandingBudgetMs : undefined;
124
+ // Let an admitted renewal finish owning its candidate before recovery opens another.
125
+ if (deadline === undefined)
126
+ await this.remoteBundleRenewal;
127
+ else
128
+ await this.deps.withTimeout(Promise.resolve(this.remoteBundleRenewal), this.deps.remoteStandingTimeLeft(deadline), "remote manager closed-serve renewal wait exceeded its 10000ms aggregate budget");
129
+ if (this.leaseStopping || this.serviceServe !== s || s.nc !== closed)
130
+ return true;
131
+ if (deadline !== undefined)
132
+ await this.deps.withTimeout(this.deps.renewRemoteBeforeRedial("serve", () => s.creds), this.deps.remoteStandingTimeLeft(deadline), "remote manager closed-serve renewal wait exceeded its 10000ms aggregate budget");
133
+ else if (inspectCredHealth(s.creds ?? "").state !== "healthy" && s.creds !== undefined) {
134
+ s.creds = await this.remintServeCreds(s);
135
+ this.deps.scheduleServeRenewal(s.creds);
136
+ }
137
+ if (this.leaseStopping || this.serviceServe !== s || s.nc !== closed)
138
+ return true;
139
+ const { nc, handle } = await this.dialServeConnection(s, undefined, deadline);
140
+ if (this.leaseStopping || this.serviceServe !== s || s.nc !== closed) {
141
+ try {
142
+ await handle.stop();
143
+ }
144
+ finally {
145
+ await nc.close();
146
+ }
147
+ return true;
148
+ }
149
+ s.nc = nc;
150
+ s.handle = handle;
151
+ console.error(`manager service endpoint re-dialed: ${MANAGER_ENDPOINT}/${this.managerInstanceId} (epoch ${s.grant.epoch})`);
152
+ return true;
153
+ });
154
+ if (this.leaseStopping || recovered)
155
+ return;
156
+ console.error(`! manager service endpoint could not be restored for ${this.space}/${MANAGER_ENDPOINT}/${this.managerInstanceId}: releasing the lease and exiting`);
157
+ await this.deps.stop();
158
+ process.exit(1);
159
+ }
160
+ /** Register the manager as an ordinary v0.4 `service` endpoint and serve its typed
161
+ * command surface on the ep rails - the manager's ONLY control door. On an AUTH mesh
162
+ * the whole credential path is the SAME one an ordinary endpoint traverses (the enforcement
163
+ * test that keeps "ordinary" honest): provision the §13.1 issuance gate, drive the
164
+ * registration BARRIER's gate CAS, then release the serve credential only on the mint FENCE's
165
+ * revision-pinned CAS win - all over the scoped one-shot executor ({@link
166
+ * withEndpointServeExecutor}), never a seed-signed shortcut. Holding the signing seed only
167
+ * AUTHORIZES the reserved single-label name (`manager`, operator name authority, DEV_OWNER).
168
+ * On an OPEN mesh the same gate/registration/serve-grant ceremony runs over bare one-shot
169
+ * connections and NO credential is ever minted: there is no credential system to issue from,
170
+ * so the gate legitimately keeps an empty `epcred` family (the §13.1 fence is issuance-only)
171
+ * and the serve connection is bare - the broker enforces nothing on an open mesh, exactly the
172
+ * old open-mesh ctl trust ("open = single-trusted-host"). */
173
+ async registerManagerService() {
174
+ const auth = this.auth;
175
+ if (this.remoteAuthority) {
176
+ const remote = this.remoteAuthority;
177
+ this.deps.setGoalWriterIdentity(remote.identities.goalWriter);
178
+ this.sessionLedgerIdentity = remote.identities.sessionLedger;
179
+ this.deps.setGoalWriterCreds(remote.goalWriterCreds);
180
+ this.sessionLedgerCreds = remote.sessionLedgerCreds;
181
+ const state = {
182
+ handle: undefined,
183
+ nc: undefined,
184
+ identity: remote.identities.serve,
185
+ grant: remote.serveGrant,
186
+ creds: remote.serveCreds,
187
+ };
188
+ // The shared dialer wires the closed-connection handler, which re-dials through the all-duty family.
189
+ const { nc, handle } = await this.dialServeConnection(state);
190
+ state.handle = handle;
191
+ state.nc = nc;
192
+ this.serviceServe = state;
193
+ console.error(`remote manager service endpoint activated: ${MANAGER_ENDPOINT}/${this.managerInstanceId} (epoch ${state.grant.epoch})`);
194
+ return;
195
+ }
196
+ // The §13.7 contract store is REGISTRATION's dependency, ensured here MODE-NEUTRALLY:
197
+ // it used to ride the static-only lifecycle reconcile, so a USER-mode manager registered
198
+ // against an absent stream and its artifact publish died no-responders (live-repro'd). A
199
+ // provisioner one-shot creates-or-verifies it (config-B immutability incl. the shadowed-legacy
200
+ // refuse) before the executor publishes a single artifact.
201
+ {
202
+ // Open mesh: the bare connection holds the rights (there is no credential system to mint from).
203
+ const provCreds = auth ? await mintCreds(auth, newIdentity(), "provisioner") : undefined;
204
+ const provNc = await this.deps.dial({ ...standaloneConnectOpts({ creds: provCreds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
205
+ try {
206
+ // The manager now WRITES goal facts (EPF) + progress events (EPE), so the §13.12
207
+ // endpoint streams must exist. Nothing provisioned them before spawn-as-action (no endpoint
208
+ // wrote to EPF/EPE), so the manager ensures the full set here over the provisioner (whose
209
+ // STREAM.CREATE now covers them), idempotently - createEndpointStreams is a superset of
210
+ // ensureContractStore + ensureAuthorityStores, fail-loud on drift. Auth + open both run this.
211
+ await createEndpointStreams(await jetstreamManager(provNc), new Kvm(provNc), this.space);
212
+ }
213
+ finally {
214
+ await drainAndClose(provNc);
215
+ }
216
+ }
217
+ const iid = this.managerInstanceId;
218
+ const artifacts = managerClusterArtifacts();
219
+ // In-memory §13.7 content store: the manager is this document's AUTHOR, so registration and
220
+ // serve authorization verify against the exact artifacts it publishes from memory. The DURABLE
221
+ // `epc` contract-store publication (for third-party digest fetches) runs below inside the same
222
+ // executor, BEFORE the registration that advertises the digests.
223
+ const store = new Map([
224
+ [artifacts.rootDigest, artifacts.document],
225
+ [artifacts.closureDigest, artifacts.manifest],
226
+ ]);
227
+ const readClusterArtifact = (digest) => store.get(digest);
228
+ // §13.9 name authority, static mode: `manager` is a core single-label name requiring OPERATOR
229
+ // authority - the manager holds the space signing seed, so it self-authorizes exactly its own
230
+ // name for exactly DEV_OWNER (never a general authority; any other (name, owner) refuses).
231
+ const authority = {
232
+ authorize: (name, owner) => ({ authorized: name === MANAGER_ENDPOINT && owner === DEV_OWNER, revision: 0 }),
233
+ };
234
+ // The STABLE serve identity: the PERSISTED serve nkey, reused across restart so the
235
+ // gate binds the SAME principal (§13.1 serving-principal binding) - provisionEndpointGateOpen
236
+ // stays idempotent and verified eviction has a stable target. Renewals re-mint the same nkey
237
+ // with a fresh bounded exp; a restart re-provisions the same (idempotent) gate + re-registers.
238
+ const serveIdentity = this.managerServeIdentity;
239
+ const servePrincipal = principalKey(DEV_OWNER, serveIdentity.id).key;
240
+ // An open mesh mints no credentials, so it has no family for a fresh pair to grow.
241
+ const siblings = auth ? claimManagerSiblingIdentities(this.workspaceRoot, this.space) : { goalWriter: newIdentity(), sessionLedger: newIdentity() };
242
+ // The STABLE goal-writer identity - a SIBLING credential in the same §13.1 family
243
+ // (not the gate's bound serving principal), so the run block can family-stage it.
244
+ this.deps.setGoalWriterIdentity(siblings.goalWriter);
245
+ // The STABLE session-LEDGER identity - another SIBLING in the SAME §13.1 family, so
246
+ // the takeover barrier revokes a deposed manager's ledger cred alongside its goal-writer. The
247
+ // per-session serving creds join the same family, each with its own fresh identity.
248
+ this.sessionLedgerIdentity = siblings.sessionLedger;
249
+ // One registration operation for this boot. Fresh executors may replace a dead connection, but
250
+ // they must resume THIS freeze rather than minting a new op that discards Phase-2 progress.
251
+ const registrationOpId = mintLifecycleUid();
252
+ const executorExpired = (e) => /closed connection/i.test(rejectionText(e));
253
+ const retryExpiredExecutor = async (label, fn) => {
254
+ for (;;) {
255
+ try {
256
+ return await fn();
257
+ }
258
+ catch (e) {
259
+ if (!executorExpired(e))
260
+ throw e;
261
+ console.error(`manager ${label} executor expired; retrying${label === "registration" ? ` operation ${registrationOpId}` : ""} with fresh scoped authority`);
262
+ }
263
+ }
264
+ };
265
+ const publishAndProvision = async ({ authKv, nc: execNc }) => {
266
+ // §13.7 contract-artifact publication: every schema root + its closure manifest, plus
267
+ // the cluster document + ITS manifest, land in the EPC store BEFORE the registration that
268
+ // advertises their digests - so a caller can always fetch-verify-compile a registered
269
+ // digest (the generic-invoke read path). Create-only + content-addressed: a retry
270
+ // or a same-artifact republish is an idempotent lost-CAS. The registration itself still
271
+ // verifies against the in-memory copies (the manager is the author).
272
+ const storeCtx = await contractStoreContext(execNc, this.space);
273
+ for (const value of [...managerContractArtifactValues(), artifacts.document, artifacts.manifest])
274
+ await publishContractArtifact(storeCtx, contractArtifactCanonicalBytes(value));
275
+ // §13.1 pre-registration: the issuance gate, born open@gen0 bound to the serve
276
+ // principal - provisioned ONCE, on the FIRST registration. On a RESTART the gate
277
+ // already EXISTS (advanced past gen0 by the prior registration), so re-provisioning the gen0
278
+ // row would conflict "foreign content"; the persisted instanceId makes this a TAKEOVER, and
279
+ // registerServiceInstance below freezes + re-registers the EXISTING gate (advancing the epoch
280
+ // after it verify-evicts the superseded family). The serve principal is the SAME persisted one,
281
+ // so the gate's principal binding is unchanged either way.
282
+ if ((await serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid }).observe()) === null)
283
+ await provisionEndpointGateOpen(authKv, { endpoint: MANAGER_ENDPOINT, instanceId: iid, principal: servePrincipal });
284
+ };
285
+ const completeRegistration = async ({ recordsKv, authKv, nc: execNc }) => {
286
+ await publishAndProvision({ recordsKv, authKv, nc: execNc });
287
+ // On an AUTH mesh a RE-registration (restart of the persisted instanceId)
288
+ // must VERIFY-EVICT the superseded serve family BEFORE the epoch advances (§13.1 "old authority
289
+ // dies before new authority is visible"). Inject the SCOPED delivery-admin evictor; the OPEN
290
+ // mesh mints no serve family, so its empty-family restart never consults an evictor, and one
291
+ // an earlier release staged there stays unverified with the reason in the refusal
292
+ // ({@link openMeshUnverifiedEviction}). NO-ORACLE = LOUD: with no reachable delivery daemon the
293
+ // evictor THROWS naming the cure, so PHASE 2 fails closed with the delivery-daemon fix in the
294
+ // error text - a crash-restart never silently skips eviction (no-fallbacks).
295
+ const barrier = endpointRegistrationBarrier(authKv, this.space, {
296
+ endpoint: MANAGER_ENDPOINT, instanceId: iid, opId: registrationOpId,
297
+ evict: auth ? makeManagerEndpointHolderEvictor({ space: this.space, servers: this.servers ?? DEFAULT_SERVER, auth, log: (line) => console.error(line), unreachableWaitMs: DELIVERY_ADMIN_BOOT_WAIT_MS }) : this.deps.openMeshUnverifiedEviction,
298
+ });
299
+ const spec = { endpoint: MANAGER_ENDPOINT, owner: DEV_OWNER, clusterDigests: [artifacts.closureDigest], protocol: { v: 1 } };
300
+ const { grant } = await registerServingInstance(recordsKv, {
301
+ space: this.space, spec, instanceId: iid, registrant: { owner: DEV_OWNER }, authority, barrier, readClusterArtifact,
302
+ // #1393: when a FOREIGN instance holds the endpoint governance slot, let core tell an
303
+ // in-flight registration from one abandoned by a predecessor that died between its
304
+ // slot-take and its spec publish. The read rides THIS executor's existing auth-bucket read
305
+ // grant (no new grant, no new writer); core refuses on anything but a gate provably
306
+ // reopened past the slot's stamp.
307
+ observeHolderGeneration: (holderInstanceId) => readEndpointGateGeneration(authKv, { endpoint: MANAGER_ENDPOINT, instanceId: holderInstanceId }),
308
+ status: { connectors: this.connectorStatuses.map((row) => ({ ...row, binaries: { ...row.binaries } })) },
309
+ });
310
+ const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
311
+ // Open mesh: NO mint - the §13.1 fence is issuance-only and nothing is ever issued, so the
312
+ // gate keeps an empty `epcred` family; the serve connection below stays bare.
313
+ const creds = auth ? await mintCreds(auth, serveIdentity, "endpoint-serve", { serveIssuance: fence, endpointServe: grant }) : undefined;
314
+ // Mint + family-stage the goal-writer credential HERE, over this executor's
315
+ // authKv (the fence is live), so its credId lands in `epcred.<e>.<iid>` and the takeover
316
+ // barrier revokes it. Open mesh: no mint (no credential system; the goal-writer conn is bare).
317
+ const goalWriterCreds = auth ? await this.deps.mintAndStageGoalWriter(authKv) : undefined;
318
+ // Mint + family-stage the session-LEDGER credential HERE too (same executor, same
319
+ // fence, same §13.1 family), so takeover revokes a deposed manager's ledger connection. The
320
+ // per-session SERVING credentials are minted later, one per redemption, into the SAME family.
321
+ // Open mesh: no mint (no credential system; the ledger connection stays bare).
322
+ const sessionLedgerCreds = auth ? await this.mintAndStageSessionLedger(authKv) : undefined;
323
+ return { grant, creds, goalWriterCreds, sessionLedgerCreds };
324
+ };
325
+ let registration;
326
+ if (auth) {
327
+ // Boot heal may consume an arbitrarily large prior family. End that executor window here and
328
+ // mint fresh scoped authority for the new registration, rather than forcing heal + takeover
329
+ // through one fixed-lifetime connection. A closed connection during heal retries the SAME
330
+ // frozen predecessor op via reconcile's durable cursor; a closed connection during
331
+ // registration retries THIS boot's operationId without heal, so Phase-2 progress stays bound.
332
+ // #783/#871: a predecessor that died mid-barrier leaves this gate frozen under a
333
+ // registration op. registerServiceInstance will then refuse SPEC 13.8 forever, even
334
+ // when the freeze-holder is gone. Complete that SAME op (abort-reopen) on independent
335
+ // holder-gone evidence BEFORE this incarnation freezes a new one. Auth only: the
336
+ // CONNZ oracle rides delivery-admin, which an open mesh does not have.
337
+ await retryExpiredExecutor("boot-heal", () => this.deps.withEndpointServeExecutor(async ({ recordsKv, authKv, nc: execNc }) => {
338
+ await publishAndProvision({ recordsKv, authKv, nc: execNc });
339
+ if (auth) {
340
+ await this.deps.healFrozenRegistrationGate(authKv, iid, auth, recordsKv);
341
+ }
342
+ }));
343
+ registration = await retryExpiredExecutor("registration", () => this.deps.withEndpointServeExecutor(completeRegistration));
344
+ }
345
+ else {
346
+ registration = await this.deps.withOpenServeConnection(completeRegistration).catch((e) => { throw this.deps.openMeshFrozenGateRefusal(e, iid); });
347
+ }
348
+ if (!registration)
349
+ throw new Error("manager registration produced no serve authority");
350
+ const { grant, creds, goalWriterCreds, sessionLedgerCreds } = registration;
351
+ this.deps.setGoalWriterCreds(goalWriterCreds);
352
+ this.sessionLedgerCreds = sessionLedgerCreds;
353
+ // The serve connection presents the CURRENT credential on every (re)connect (the state object
354
+ // is captured by the authenticator), so a fence-traversing renewal is adopted by reconnect
355
+ // without re-registration. Reconnects stay unbounded: the serve rails are this instance's
356
+ // registered surface for its whole incarnation.
357
+ const state = { handle: undefined, nc: undefined, identity: serveIdentity, grant, creds };
358
+ const { nc, handle } = await this.dialServeConnection(state);
359
+ state.nc = nc;
360
+ state.handle = handle;
361
+ this.serviceServe = state;
362
+ console.error(`manager service endpoint registered: ${MANAGER_ENDPOINT}/${iid} (epoch ${grant.epoch}, registrationRevision ${grant.registrationRevision})`);
363
+ // #2073: arm the serve credential's own renewal now, from ITS window, instead of leaving it to
364
+ // `credRenewTimer`'s boot-phased TTL/4 tick. Open mesh mints no credential (`creds` is
365
+ // undefined) and has nothing to schedule.
366
+ if (state.creds !== undefined)
367
+ this.deps.scheduleServeRenewal(state.creds);
368
+ }
369
+ /** Mint the standing `session-ledger` credential and STAGE it into this instance's
370
+ * §13.1 revocation family (`epcred.<e>.<iid>`), over the passed executor's `authKv`, following the
371
+ * {@link mintAndStageGoalWriter} pattern under the same open-and-commit fence.
372
+ *
373
+ * This credential carries the DEDICATED sessions-bucket ledger rows and no session rail at all.
374
+ * It therefore takes no epoch pin: §13.6 makes it the durable revocation authority that must
375
+ * outlive the serving endpoint, so scoping it to one serving epoch would defeat its purpose. The
376
+ * epoch lives where it belongs, on the per-session serving credentials, which are minted per
377
+ * redemption into this same family. Because `mintCreds` stamps a random `issuance:` tag on
378
+ * `session-ledger` (`userTags`), re-minting the SAME nkey on renewal or restart signs distinct
379
+ * bytes and stages a distinct ledger row (per-JWT `credentialId` digest) even within one
380
+ * second. */
381
+ async mintAndStageSessionLedger(authKv) {
382
+ const auth = this.auth;
383
+ const identity = this.sessionLedgerIdentity;
384
+ // Registration instanceId (the persisted logical id), not the per-process lifecycleUid:
385
+ // the barrier enumerates `epcred.<e>.<managerInstanceId>`, so the ledger cred joins that family.
386
+ const iid = this.managerInstanceId;
387
+ const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
388
+ const observed = await fence.observe();
389
+ if (observed === null)
390
+ throw new Error(`the issuance gate for ${MANAGER_ENDPOINT}/${iid} vanished; the session-ledger cred cannot join its §13.1 revocation family`);
391
+ const creds = await mintCreds(auth, identity, "session-ledger");
392
+ const exp = inspectCredHealth(creds).exp;
393
+ if (exp === undefined)
394
+ throw new Error(`the session-ledger credential for ${MANAGER_ENDPOINT}/${iid} is unbounded; the §13.1 ledger row requires an expiry`);
395
+ // The §13.1 open-and-commit fence (see {@link mintAndStageGoalWriter}): stage + revision-pinned
396
+ // commit against the gate this mint's grant was scoped from, releasing only on the win.
397
+ await commitSiblingIssuance(fence, observed, {
398
+ credentialId: credentialIdOf(creds),
399
+ credentialKey: identity.id,
400
+ holderPrincipal: principalKey(DEV_OWNER, identity.id).key,
401
+ endpoint: MANAGER_ENDPOINT, lifecycleUid: iid, sourceChain: ["root"], state: "active", exp,
402
+ generation: observed.generation, processEpoch: observed.processEpoch,
403
+ registrationRevision: observed.registrationRevision, nameAuthorityRevision: observed.nameAuthorityRevision,
404
+ });
405
+ return creds;
406
+ }
407
+ /** #2073: dial the session-ledger's ONE standing connection - shared by the initial start and the
408
+ * closed-connection recovery ({@link onSessionLedgerConnectionClosed}), the same shape {@link
409
+ * dialGoalWriter} uses for its rail. The KV/JetStream clients the session plane opened from the
410
+ * connection at start stay bound to it for this incarnation's life; a redial refreshes the
411
+ * standing authenticator connection the credential renewal presents onto (mirroring `sw.creds`),
412
+ * which is what a closed-connection fault on this rail needs restored. */
413
+ async dialSessionLedgerConnection(sw, identity) {
414
+ const nc = await this.deps.dial({
415
+ ...((this.auth || this.remoteAuthority) ? standaloneConnectOpts({ creds: () => sw.creds, tls: false }) : {}),
416
+ inboxPrefix: `_INBOX_${identity.id}`,
417
+ maxReconnectAttempts: -1,
418
+ });
419
+ nc.closed().then((err) => { void this.onSessionLedgerConnectionClosed(err ?? undefined); });
420
+ this.deps.trackTransport(nc);
421
+ sw.nc = nc;
422
+ }
423
+ /** #2073: the session-ledger rail's closed-connection fault, the same bounded shape {@link
424
+ * onGoalWriterConnectionClosed} uses: re-dial with the current credential, re-mint through the
425
+ * existing session-ledger renewal branch when the credential itself has expired, then re-attach.
426
+ * Exhaustion logs and leaves the credential to the next renewal pass; it never exits the process
427
+ * (brief step 4: only the serve rail is the control plane the report lost). */
428
+ async onSessionLedgerConnectionClosed(err) {
429
+ if (this.leaseStopping)
430
+ return;
431
+ console.error(`! manager session-ledger connection closed: ${err?.message ?? "unknown reason"}`);
432
+ const sw = this.sessionLedgerConn;
433
+ const identity = this.sessionLedgerIdentity;
434
+ const recovered = await this.deps.boundedReconnect("session-ledger", async () => {
435
+ if (!sw || !identity)
436
+ return false;
437
+ if (this.remoteAuthority)
438
+ await this.deps.renewRemoteBeforeRedial("session-ledger", () => sw.creds);
439
+ else if (sw.creds !== undefined && inspectCredHealth(sw.creds).state !== "healthy") {
440
+ sw.creds = await this.deps.withEndpointServeExecutor(({ authKv }) => this.mintAndStageSessionLedger(authKv));
441
+ this.sessionLedgerCreds = sw.creds;
442
+ }
443
+ await this.dialSessionLedgerConnection(sw, identity);
444
+ console.error("manager session-ledger re-dialed");
445
+ return true;
446
+ }, inspectCredHealth(sw?.creds ?? "").state === "expired");
447
+ if (this.leaseStopping || recovered)
448
+ return;
449
+ console.error("! manager session-ledger could not be re-dialed; leaving the credential to the next renewal pass");
450
+ }
451
+ /** Stand up the ONE §13.6 session plane on its own standing connection. Mode-dual,
452
+ * mirroring {@link startGoalWriter}: an AUTH mesh presents the scoped `session-ledger` cred
453
+ * already minted + family-staged inside registration's run block ({@link mintAndStageSessionLedger});
454
+ * an OPEN mesh uses a bare connection (no credential system to mint from). The connection presents
455
+ * the CURRENT credential on every (re)connect, so a half-TTL renewal is adopted without reconnecting.
456
+ *
457
+ * The offer SIGNER is a per-incarnation in-memory keypair: the static collapsed path mints AND
458
+ * redeems the offer in one call ({@link ManagerSessionPlane.establishAttach}), so the manager
459
+ * self-signs and self-verifies its own §13.6 grants and the keypair never leaves the process - a
460
+ * holder never verifies the signature (it presents the grant back over the rail; the broker's
461
+ * per-session caller cred is the holder's real fence). The plane's ledger lives in the DEDICATED
462
+ * sessions bucket (createEndpointStreams provisioned it at registration). */
463
+ async startSessionPlane() {
464
+ const identity = (this.auth || this.remoteAuthority) ? this.sessionLedgerIdentity : newIdentity();
465
+ // The mutable holder captured by the authenticator (mirrors the goal-writer): a half-TTL renewal
466
+ // updates `sw.creds` and the next (re)connect presents the refreshed credential.
467
+ const sw = { nc: undefined, creds: (this.auth || this.remoteAuthority) ? this.sessionLedgerCreds : undefined };
468
+ await this.dialSessionLedgerConnection(sw, identity);
469
+ const nc = sw.nc;
470
+ const serveEpoch = this.serviceServe?.grant.epoch;
471
+ if (serveEpoch === undefined)
472
+ throw new Error("the manager session plane needs the serve grant epoch; registerManagerService must run first");
473
+ const ledgerKv = await openSessionLedgerKv(nc, sessionsBucket(this.space));
474
+ // The session signing key ROTATES. It used to be minted once here with a flat 24h window and
475
+ // handed back frozen forever, so a manager that stayed up past 24h lost its session plane
476
+ // permanently: every attach failed closed with "outside its validity window", and the only
477
+ // recovery was restarting the manager, which kills every live session. It happened three times
478
+ // in one day. Failing closed on an expired key is correct (SPEC 13.10); the defect was that
479
+ // nothing ever renewed the key, so the correct refusal became permanent.
480
+ //
481
+ // Renewal is driven from two places on purpose - a timer below, and opportunistically before
482
+ // each signature. A timer alone stops if the loop is starved or the host suspends; an
483
+ // opportunistic check alone never fires on an idle plane that must sign after a long quiet
484
+ // period. Expiry now requires both to fail at once.
485
+ const rotating = new RotatingSigner((seq, now) => {
486
+ const kp = newArtifactSigner();
487
+ const keyId = seq === 0
488
+ ? `mgr-sessions-${identity.id.slice(0, 12)}`
489
+ : `mgr-sessions-${identity.id.slice(0, 12)}-g${seq}`;
490
+ return {
491
+ keyId,
492
+ keyPair: kp,
493
+ anchor: generationAnchor({
494
+ keyId, publicKey: kp.publicKey, owner: MANAGER_ENDPOINT, roles: ["sessions"],
495
+ scope: { sessions: [MANAGER_ENDPOINT] }, now, ttlMs: SESSION_GRANT_MAX_TTL_MS,
496
+ }),
497
+ };
498
+ }, Date.now());
499
+ this.sessionPlane = new ManagerSessionPlane({
500
+ space: this.space,
501
+ // The session's serving identity is the persisted REGISTRATION instanceId, not the
502
+ // per-process lifecycleUid: a restarted manager re-registers the SAME logical instanceId with
503
+ // an ADVANCED epoch, so a client re-attaches by the same instance while the epoch fences the
504
+ // old incarnation's sessions.
505
+ serving: { instanceId: this.managerInstanceId, epoch: serveEpoch },
506
+ // Read through the rotator on EVERY use rather than capturing a key: signing takes the newest
507
+ // generation, and resolution accepts any generation still inside its overlap so an artifact
508
+ // signed a moment before a swap is not orphaned a moment after it.
509
+ signer: {
510
+ get keyId() { rotating.maybeRenew(Date.now()); return rotating.current().keyId; },
511
+ keyPair: { sign: (input) => rotating.current().keyPair.sign(input) },
512
+ },
513
+ resolveAnchor: (id) => rotating.resolve(id),
514
+ ledgerKv, ttlMs: SESSION_GRANT_MAX_TTL_MS,
515
+ servingCredential: this.sessionServingCredentials(),
516
+ ...(this.maxSessions !== undefined ? { maxSessions: this.maxSessions } : {}),
517
+ });
518
+ this.sessionLedgerConn = sw;
519
+ // The belt to the signing path's braces: renew on a timer as well, so a plane that sits idle
520
+ // for longer than a window still holds a live key when work finally arrives. Checked well
521
+ // inside the renewal margin, unref'd so it never holds the process open.
522
+ const renewTimer = setInterval(() => {
523
+ const rotated = rotating.maybeRenew(Date.now());
524
+ if (rotated)
525
+ console.error(`manager session signing key rotated to ${rotated} (previous generations stay verifiable ` +
526
+ `through their overlap; a key is never allowed to expire unattended)`);
527
+ }, 15 * 60 * 1000);
528
+ renewTimer.unref?.();
529
+ this.sessionKeyRenewTimer = renewTimer;
530
+ console.error(`manager session plane standing (endpoint ${MANAGER_ENDPOINT}, epoch ${serveEpoch}, ${(this.auth || this.remoteAuthority) ? "scoped session-ledger cred, §13.1 family-staged" : "open/bare"})`);
531
+ }
532
+ /**
533
+ * The per-session SERVING credential seam (SPEC 13.6): the manager mints, gate-stages,
534
+ * connects and revokes ONE credential per live session, replacing a standing credential that held
535
+ * `eps.manager.*.<epoch>.{in,out}` and so reached every live session's bytes at its epoch.
536
+ *
537
+ * Each session gets its OWN nkey identity, so the §13.1 barrier's evict-by-holderPrincipal reaches
538
+ * it individually, and each is staged into `epcred.manager.<instanceId>` - the SAME family the
539
+ * ledger and goal-writer creds join. That is how manager takeover still kills a deposed manager's
540
+ * sessions: the barrier enumerates the family, revokes every row, and evicts every holder, so the
541
+ * per-session creds die with the incarnation exactly as the standing one did, with the blast
542
+ * radius of a leaked credential cut from "every session at this epoch" to "one dead session".
543
+ *
544
+ * OPEN MESH: no credential system exists to mint from, so the seam mints nothing and opens a bare
545
+ * connection. That is not a degraded auth path - an open mesh has no broker enforcement at all -
546
+ * and it is still per-session: the connection and the ledger row are still one-per-session, so
547
+ * teardown behaves identically in both modes.
548
+ */
549
+ sessionServingCredentials() {
550
+ const iid = this.managerInstanceId;
551
+ const gate = async (fn) => this.deps.withEndpointServeExecutor(({ authKv }) => fn(authKv));
552
+ return {
553
+ mint: async (grant) => {
554
+ // Open mesh: no auth to mint from. The id still names the session so the ledger row and the
555
+ // teardown path are identical in both modes.
556
+ if (this.remoteAuthority) {
557
+ const identity = newIdentity();
558
+ const creds = await this.remoteAuthority.mintSessionServing({
559
+ identity,
560
+ endpoint: grant.endpoint,
561
+ sessionId: grant.sessionId,
562
+ epoch: grant.serving.epoch,
563
+ exp: Math.floor(grant.exp / 1000),
564
+ });
565
+ const id = credentialIdOf(creds);
566
+ this.sessionServingKeys.set(id, identity.id);
567
+ return { id, creds, exp: grant.exp };
568
+ }
569
+ if (!this.auth)
570
+ return { id: `${grant.sessionId}.s`, creds: "", exp: grant.exp };
571
+ const identity = newIdentity();
572
+ const creds = await mintCreds(this.auth, identity, "session-serving", {
573
+ sessionServing: { endpoint: grant.endpoint, sessionId: grant.sessionId, epoch: grant.serving.epoch },
574
+ expiresAt: Math.floor(grant.exp / 1000), // grant.exp is ms; the JWT exp is seconds
575
+ });
576
+ const health = inspectCredHealth(creds);
577
+ if (health.exp === undefined)
578
+ throw new Error(`the session-serving credential for ${grant.sessionId} is unbounded; a per-session credential never outlives its session (SPEC 13.6)`);
579
+ const id = credentialIdOf(creds);
580
+ this.sessionServingKeys.set(id, identity.id);
581
+ return { id, creds, exp: grant.exp };
582
+ },
583
+ observeGate: async (_endpoint, instanceId) => {
584
+ // Open mesh: nothing is minted and nothing is staged, so there is no gate to pin (see
585
+ // ServingGatePin.gate - the stage refuses loudly if this is ever missing on an auth mesh).
586
+ if (!this.auth && !this.remoteAuthority)
587
+ return { key: epgateKey(MANAGER_ENDPOINT, instanceId), revision: 0 };
588
+ return gate(async (authKv) => {
589
+ const observed = await serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId }).observe();
590
+ if (observed === null)
591
+ throw new Error(`the issuance gate for ${MANAGER_ENDPOINT}/${instanceId} vanished; a session credential never stages against a missing gate (SPEC 13.1)`);
592
+ // The WHOLE observation rides the pin: the stage's fence compares every field of it, which
593
+ // is what lets a lost CAS be classified rather than blanket-refused.
594
+ return { key: epgateKey(MANAGER_ENDPOINT, instanceId), revision: observed.revision, gate: observed };
595
+ });
596
+ },
597
+ stage: async (grant, cred, pin) => {
598
+ if (!this.auth && !this.remoteAuthority)
599
+ return; // open mesh: nothing minted, so nothing to make revocable
600
+ const key = this.sessionServingKeys.get(cred.id);
601
+ if (key === undefined)
602
+ throw new Error(`no minted identity for session credential ${cred.id}; the stage cannot record a holder it did not mint (SPEC 13.1)`);
603
+ // THE REDEMPTION'S OWN PIN IS THE FENCE, and it is never re-read into something newer here:
604
+ // `commitSiblingIssuance` CASes on this observation's revision and, on a loss, refuses unless
605
+ // the gate is still identical to it in every field but the revision. A barrier
606
+ // (freeze, or reopen at a successor coordinate) is therefore always a refusal, while another
607
+ // session's identical-bytes commit touch is not - per-session credentials all serialize on
608
+ // this one gate key, so refusing on that would fail live sessions for contention rather than
609
+ // for a barrier. A read is never a fence (SPEC 13.1); the pinned CAS is.
610
+ const observed = pin.gate;
611
+ if (observed === undefined)
612
+ throw new Error(`the redemption of session ${grant.sessionId} carries no gate observation for ${MANAGER_ENDPOINT}/${iid}; a session credential never stages unfenced (SPEC 13.1)`);
613
+ await gate(async (authKv) => {
614
+ const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
615
+ await commitSiblingIssuance(fence, observed, {
616
+ credentialId: cred.id,
617
+ credentialKey: key,
618
+ holderPrincipal: principalKey(DEV_OWNER, key).key,
619
+ endpoint: MANAGER_ENDPOINT, lifecycleUid: iid,
620
+ // The lineage records that this credential exists because a session was redeemed, so a
621
+ // ledger reader can tell a per-session row from a standing one (SPEC 13.6 sourceChain).
622
+ sourceChain: [`session.${grant.sessionId}`], state: "active",
623
+ exp: Math.floor(cred.exp / 1000),
624
+ generation: observed.generation, processEpoch: observed.processEpoch,
625
+ registrationRevision: observed.registrationRevision, nameAuthorityRevision: observed.nameAuthorityRevision,
626
+ });
627
+ });
628
+ },
629
+ open: async (cred) => {
630
+ // FAIL LOUD: there is deliberately no shared connection to fall back to. Serving a session
631
+ // without its own credential is exactly the standing-writer shape this design removes.
632
+ const opts = (this.auth || this.remoteAuthority) ? standaloneConnectOpts({ creds: cred.creds, /* not yet wired to a recorded transport */ tls: false }) : {};
633
+ return this.deps.dial({ ...opts, maxReconnectAttempts: -1 });
634
+ },
635
+ revoke: async (credentialId) => {
636
+ if (!this.auth && !this.remoteAuthority)
637
+ return; // open mesh: nothing was minted
638
+ await gate(async (authKv) => {
639
+ await markLedgerRowRevoked(authKv, epcredRowKey(MANAGER_ENDPOINT, iid, credentialId));
640
+ });
641
+ this.sessionServingKeys.delete(credentialId);
642
+ },
643
+ };
644
+ }
645
+ /** Tear the session plane down (best-effort, both exit paths): end every live bridge with the
646
+ * honest `manager-restart` reason (this incarnation is going away; any successor takes a new epoch
647
+ * and refuses these grants), then drain each session's own connection and retire the ledger
648
+ * connection ({@link retireConnection}). */
649
+ async stopSessionPlane() {
650
+ const plane = this.sessionPlane;
651
+ const sw = this.sessionLedgerConn;
652
+ this.sessionPlane = undefined;
653
+ this.sessionLedgerConn = undefined;
654
+ // `drain` awaits each session's teardown (connection close, terminal row, credential revoke);
655
+ // `endAll` alone would let the process exit with per-session connections still open.
656
+ try {
657
+ await plane?.drain("manager-restart");
658
+ }
659
+ catch { /* best effort */ }
660
+ if (sw)
661
+ await this.deps.retireConnection(sw.nc);
662
+ }
663
+ }
664
+ //# sourceMappingURL=serve-plane.js.map