@cotal-ai/manager 0.170.0 → 0.171.1

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,757 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { accountFromCreds, credsClaims, credsRenewalDelayMs, divergentSecretStoreNotice, inspectCredHealth, mintCreds, parseDaemonStoreAnswer, parseSecretStoreIdentity, rejectionText, REMOTE_MANAGER_IDENTITY_NAMES, requestSafeReconnect, sameSecretStoreIdentity, serveIssuanceGateKv, STANDING_RENEWABLE_TTL_SEC } from "@cotal-ai/core";
4
+ import { agentSecretKeyForFile, DELIVERY_CREDS_KIND, MEMBERSHIP_RW_CREDS_KIND, remintDaemonCreds, spaceMaterialKey, SYSTEM_CREDS_FILES, writeRenewalRecord } from "@cotal-ai/workspace";
5
+ import { credsAuthenticator, RequestError } from "@nats-io/transport-node";
6
+ import { isUnansweredDeliveryAdmin, untilDeliveryAdminAnswers } from "./endpoint-evict.js";
7
+ import { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
8
+ import { MANAGER_ENDPOINT } from "./manager-service-contract.js";
9
+ import { withTimeout } from "./manager-timeout.js";
10
+ import { Manager } from "./manager.js";
11
+ /** The delivery-admin `reloadCreds` request bound — STRICTLY GREATER than the daemon's internal
12
+ * per-component preflight bound (4s each, run in parallel) so a slow or refused proof returns the
13
+ * daemon's STRUCTURED per-component failure, never a client-side timeout that the catch below would
14
+ * misrecord as "no delivery-admin responder" (a false negative while the daemon is mid-proof). */
15
+ const DELIVERY_ADMIN_RELOAD_TIMEOUT_MS = 15_000;
16
+ /** Pick a `setInterval` period for {@link Manager.renewDaemonCreds} that guarantees at least one
17
+ * tick lands inside every renewal owner's `[renewAt, exp)` window.
18
+ *
19
+ * `inspectCredHealth` marks a credential `near-expiry` at 75% of its iat-to-exp lifetime and
20
+ * `expired` at 100%, so the window width is TTL/4. Ticks TTL/4 apart therefore land at least once
21
+ * inside every window; ticks TTL/2 apart (the old schedule) can miss it entirely for any TTL. That
22
+ * is the cause of Cotal #457, reproduced at both TTL=86400 and TTL=20 (the compressed-ratio probe).
23
+ *
24
+ * Deriving from the caller's TTL keeps the schedule correct for any credential class: the 24h
25
+ * `STANDING_RENEWABLE_TTL_SEC` and the 30-day `ROTATION_RENEWED_TTL_SEC` both get a tick inside
26
+ * their own renewal window without a hardcoded number. Post-boot responsiveness is already
27
+ * covered by the caller invoking `renewDaemonCreds` once synchronously before starting the timer,
28
+ * so no separate floor is needed. The pass is idempotent, since `renewDaemonCreds` no-ops each
29
+ * credential when its state is `healthy`, so a tick that lands before the window costs one health
30
+ * check per owner. A managed seat's credential is judged as of the next tick instead, because the
31
+ * seat re-reads its file only once a minute and nothing pushes the renewal to it: a tick that
32
+ * lands in the window's last minute can come too late for the seat to adopt it. */
33
+ export function credRenewIntervalMs(ttlSeconds) {
34
+ return Math.max(1, Math.floor((ttlSeconds / 4) * 1000));
35
+ }
36
+ export const REMOTE_STANDING_BUDGET_MS = 10_000;
37
+ /** One absolute budget across authority, preflight and adoption waits, or one closed-serve attempt. */
38
+ export function remoteStandingTimeLeft(deadline) {
39
+ const left = deadline - performance.now();
40
+ if (left <= 0)
41
+ throw new Error("remote manager standing operation exceeded its 10000ms aggregate budget");
42
+ return Math.ceil(left);
43
+ }
44
+ export function sameStrings(a, b) {
45
+ return JSON.stringify([...(a ?? [])].sort()) === JSON.stringify([...(b ?? [])].sort());
46
+ }
47
+ /** True only when the delivery-admin rail has no bound responder. A timeout is a hung rail, not absence. */
48
+ function isAbsentDeliveryAdmin(error) {
49
+ return error instanceof RequestError && error.isNoResponders();
50
+ }
51
+ /** The store challenge went UNANSWERED while a delivery daemon exists: the rail timed out, or it had
52
+ * no responder while the lease row names a holder. Both are what a daemon that is starting or
53
+ * re-acquiring its lease looks like, so manager boot waits them out (#871); a renewal pass still
54
+ * refuses on the first one. A reply that does not decode was answered and is never this. */
55
+ class DeliveryAdminUnanswered extends Error {
56
+ }
57
+ /** How long one store challenge waits for the delivery daemon's answer. */
58
+ const STORE_CHALLENGE_TIMEOUT_MS = 5_000;
59
+ /** Renewal of the manager's own standing credentials: the delivery daemon's reload, the remote
60
+ * standing bundle, and the pushes of renewed credentials to the live connections. */
61
+ export class CredentialRenewal {
62
+ deps;
63
+ constructor(deps) {
64
+ this.deps = deps;
65
+ }
66
+ // The Manager members these bodies use, under their Manager names. Each reads or writes through
67
+ // its dep at use.
68
+ get agents() { return this.deps.agents(); }
69
+ get auth() { return this.deps.auth(); }
70
+ get credentialPushRetry() { return this.deps.credentialPushRetry(); }
71
+ set credentialPushRetry(value) { this.deps.setCredentialPushRetry(value); }
72
+ get credentialPushes() { return this.deps.credentialPushes(); }
73
+ get daemonRenewalEligible() { return this.deps.daemonRenewalEligible(); }
74
+ set daemonRenewalEligible(value) { this.deps.setDaemonRenewalEligible(value); }
75
+ get daemonRenewalOwner() { return this.deps.daemonRenewalOwner(); }
76
+ set daemonRenewalOwner(value) { this.deps.setDaemonRenewalOwner(value); }
77
+ get endpointServeRenewalTimer() { return this.deps.endpointServeRenewalTimer(); }
78
+ set endpointServeRenewalTimer(value) { this.deps.setEndpointServeRenewalTimer(value); }
79
+ get ep() { return this.deps.ep(); }
80
+ get finishRemoteBundleAdoption() { return this.deps.finishRemoteBundleAdoption(); }
81
+ set finishRemoteBundleAdoption(value) { this.deps.setFinishRemoteBundleAdoption(value); }
82
+ get goalWriter() { return this.deps.goalWriter(); }
83
+ get goalWriterCreds() { return this.deps.goalWriterCreds(); }
84
+ set goalWriterCreds(value) { this.deps.setGoalWriterCreds(value); }
85
+ get leaseStopping() { return this.deps.leaseStopping(); }
86
+ get managerInstanceId() { return this.deps.managerInstanceId(); }
87
+ get pendingCredentialPushes() { return this.deps.pendingCredentialPushes(); }
88
+ get remoteAuthority() { return this.deps.remoteAuthority(); }
89
+ get remoteBundleAdoption() { return this.deps.remoteBundleAdoption(); }
90
+ set remoteBundleAdoption(value) { this.deps.setRemoteBundleAdoption(value); }
91
+ get remoteBundleRenewal() { return this.deps.remoteBundleRenewal(); }
92
+ set remoteBundleRenewal(value) { this.deps.setRemoteBundleRenewal(value); }
93
+ get remoteExecutorCreds() { return this.deps.remoteExecutorCreds(); }
94
+ set remoteExecutorCreds(value) { this.deps.setRemoteExecutorCreds(value); }
95
+ get remoteRenewalDebt() { return this.deps.remoteRenewalDebt(); }
96
+ set remoteRenewalDebt(value) { this.deps.setRemoteRenewalDebt(value); }
97
+ get remoteSupervisorCreds() { return this.deps.remoteSupervisorCreds(); }
98
+ set remoteSupervisorCreds(value) { this.deps.setRemoteSupervisorCreds(value); }
99
+ get runHosting() { return this.deps.runHosting(); }
100
+ get secretStoreIdentity() { return this.deps.secretStoreIdentity(); }
101
+ set secretStoreIdentity(value) { this.deps.setSecretStoreIdentity(value); }
102
+ get secrets() { return this.deps.secrets(); }
103
+ get serviceServe() { return this.deps.serviceServe(); }
104
+ get sessionLedgerConn() { return this.deps.sessionLedgerConn(); }
105
+ get sessionLedgerCreds() { return this.deps.sessionLedgerCreds(); }
106
+ set sessionLedgerCreds(value) { this.deps.setSessionLedgerCreds(value); }
107
+ get space() { return this.deps.space(); }
108
+ get supervisorCredentialPush() { return this.deps.supervisorCredentialPush(); }
109
+ set supervisorCredentialPush(value) { this.deps.setSupervisorCredentialPush(value); }
110
+ get supervisorCredentialPushPending() { return this.deps.supervisorCredentialPushPending(); }
111
+ set supervisorCredentialPushPending(value) { this.deps.setSupervisorCredentialPushPending(value); }
112
+ get userMode() { return this.deps.userMode(); }
113
+ get workspaceRoot() { return this.deps.workspaceRoot(); }
114
+ beginLifecycle(...args) { return this.deps.beginLifecycle(...args); }
115
+ dialRemoteStanding(...args) { return this.deps.dialRemoteStanding(...args); }
116
+ dialServeConnection(...args) { return this.deps.dialServeConnection(...args); }
117
+ discardServeCandidate(...args) { return this.deps.discardServeCandidate(...args); }
118
+ mintAndStageGoalWriter(...args) { return this.deps.mintAndStageGoalWriter(...args); }
119
+ mintAndStageSessionLedger(...args) { return this.deps.mintAndStageSessionLedger(...args); }
120
+ probeStaticCredential(...args) { return this.deps.probeStaticCredential(...args); }
121
+ renewManagedStaticCred(...args) { return this.deps.renewManagedStaticCred(...args); }
122
+ withEndpointServeExecutor(fn) { return this.deps.withEndpointServeExecutor(fn); }
123
+ /** Proof that this manager remints into the store the delivery daemon reloads from.
124
+ * Fingerprint-only `reloadCreds` is safe only after this. Two named, different stores
125
+ * refuse the pass. A daemon that is not bound yet is not a named store: start and
126
+ * remint still proceed (tests, delayed delivery), writing this manager's store. The
127
+ * challenge runs again before every remint, so a later daemon on a foreign store is
128
+ * refused then rather than certified by an earlier absence. A request timeout is not
129
+ * absence: a hung rail would skip the proof, so it fails closed.
130
+ *
131
+ * ABSENCE IS READ OFF THE LEASE ROW, never off the rail's no-responder shape alone (#1694).
132
+ * The rail is queue-grouped, so "no responder answered" is itself something the rail reports,
133
+ * and a responder that answers in a shape the client turns into that error makes the pass read
134
+ * "absent" while a holder is live on the row — certifying every later remint with no proof at
135
+ * all. So a no-responder outcome is decided by the row: a row that names a holder makes the
136
+ * pass refuse (undetermined — a live daemon went unanswered, which must not read as "no
137
+ * daemon"), and only a row that is absent or holderless settles "absent", the state start()
138
+ * treats as not-yet-bound. An unreadable row (a failed read, or a key that exists but does not
139
+ * parse) is a genuine unknown and refuses fail-closed, like a hung rail. */
140
+ async daemonStoreRelation(timeoutMs) {
141
+ let reply;
142
+ try {
143
+ reply = await this.ep.requestDeliveryAdmin("reloadStoreIdentity", {}, timeoutMs);
144
+ }
145
+ catch (e) {
146
+ const msg = rejectionText(e);
147
+ if (isAbsentDeliveryAdmin(e))
148
+ return this.absentByLeaseRow(isUnansweredDeliveryAdmin(e));
149
+ const failure = `could not challenge the delivery daemon's SecretStore: ${msg}`;
150
+ throw isUnansweredDeliveryAdmin(e) ? new DeliveryAdminUnanswered(failure) : new Error(failure);
151
+ }
152
+ if (!reply.ok)
153
+ throw new Error(reply.error ?? "delivery daemon refused to name the SecretStore it reloads from");
154
+ let answer;
155
+ try {
156
+ answer = parseDaemonStoreAnswer(reply.data);
157
+ }
158
+ catch (e) {
159
+ throw new Error(`delivery daemon named an unreadable SecretStore: ${rejectionText(e)}. Nothing reminted. ` +
160
+ `Check that delivery and manager use the same Cotal version, then restart delivery through its supervisor. ` +
161
+ `For a saved local delivery service: \`cotal down delivery --space ${this.space}\`, ` +
162
+ `then \`cotal up --space ${this.space}\``);
163
+ }
164
+ // The answerer's own claim first, so an honest non-holder is refused by its own admission and
165
+ // the operator-facing reason names that. This is the CHEAP half of the test and NOT the binding
166
+ // one: a responder that does not hold the lease can assert `true` here just as easily.
167
+ if (!answer.holdsDeliveryLease)
168
+ throw new Error("the delivery-admin rail was answered by a responder that does not hold this space's " +
169
+ "delivery lease, so its SecretStore is not the store the daemon reloads from - nothing reminted");
170
+ // THE BINDING TEST, measured by this manager rather than asserted by the answerer. The lease
171
+ // row's holder is read here under this manager's own credential; the answerer must BE that
172
+ // principal. A reply asserting the claim while some other process holds the shard fails here,
173
+ // which is the case a bare store identity could not see. An unreadable row is an unknown and
174
+ // refuses too: this test may never be satisfied by failing to run.
175
+ const holder = await this.ep.deliveryLeaseHolder(Manager.DELIVERY_SHARD);
176
+ if (holder === undefined)
177
+ throw new Error("this manager could not read the delivery lease row, so it cannot verify that the answering " +
178
+ "responder is the process that reloads the standing credentials - nothing reminted");
179
+ if (holder !== answer.responder)
180
+ throw new Error(`the delivery-admin rail was answered by ${answer.responder}, which is not the holder of ` +
181
+ `this space's delivery lease (${holder}), so its SecretStore is not the store the daemon ` +
182
+ `reloads from - nothing reminted`);
183
+ const daemon = answer.identity;
184
+ // The workspace store records its id the first time it is named, so it is named here, where
185
+ // only an auth manager reaches, rather than in a constructor every open-mode manager runs.
186
+ this.secretStoreIdentity ??= parseSecretStoreIdentity(this.secrets.identity);
187
+ if (!sameSecretStoreIdentity(this.secretStoreIdentity, daemon)) {
188
+ console.error(`! ${divergentSecretStoreNotice(this.secretStoreIdentity, daemon)}`);
189
+ return "divergent";
190
+ }
191
+ return "shared";
192
+ }
193
+ /** Settle a no-responder challenge outcome from the lease row, never from the rail's own
194
+ * reporting shape (#1694). The three cases:
195
+ *
196
+ * 1. The row READS but names a holder: a live daemon holds the shard and the rail went
197
+ * unanswered. That is undetermined, not "no daemon" — treating it as absent would let this
198
+ * manager remint with no proof while a reloading daemon runs, which is exactly what the
199
+ * challenge exists to prevent. Refuse.
200
+ * 2. The row is unreadable — a read that fails (a denied or erroring bucket) OR a key that
201
+ * exists but does not parse as a lease record (`readDeliveryLeaseEntry` throws for both):
202
+ * undetermined, and it refuses the same fail-closed way a hung rail does. Never a silent
203
+ * "absent" over a row the manager could not read.
204
+ * 3. The row is absent or holderless (no key, a DEL/PURGE tombstone, or a row that names no
205
+ * holder): today's "absent", the state start() treats as a daemon that is not bound yet.
206
+ *
207
+ * `deliveryLeaseHolder` swallows its read failures into `undefined`, which would fold case 2
208
+ * into case 3 — so this reads the entry directly and lets the read's own failure refuse. */
209
+ async absentByLeaseRow(unanswered) {
210
+ let entry;
211
+ try {
212
+ entry = await this.ep.readDeliveryLeaseEntry(Manager.DELIVERY_SHARD);
213
+ }
214
+ catch (e) {
215
+ throw new Error(`could not read the delivery lease row to settle whether the delivery daemon is absent ` +
216
+ `(${rejectionText(e)}) - absence is undetermined, nothing reminted`);
217
+ }
218
+ const holder = entry?.info.holder;
219
+ if (holder !== undefined && holder !== "") {
220
+ const refusal = `the delivery-admin rail reported no responder while the delivery lease names a holder ` +
221
+ `(${holder}) - absence cannot be read off the rail alone, and nothing reminted`;
222
+ throw unanswered ? new DeliveryAdminUnanswered(refusal) : new Error(refusal);
223
+ }
224
+ return "absent";
225
+ }
226
+ /** Keep this manager's renewal lease alive between credential passes (#1634). The manager bucket
227
+ * expires keys at MANAGER_LEASE_TTL_MS, far below the credential pass's cadence, so the lease
228
+ * needs its own heartbeat like the per-instance liveness lease. A non-owner calls this too: the
229
+ * CAS is how a survivor picks up a dead owner's expired lease with no operator step. Never
230
+ * throws; a failed heartbeat leaves ownership to the next pass rather than ending the process. */
231
+ async keepDaemonRenewalLease() {
232
+ if (!this.auth || !this.daemonRenewalEligible)
233
+ return;
234
+ try {
235
+ const held = await this.ep.holdDaemonRenewalLease(this.managerInstanceId);
236
+ if (this.daemonRenewalOwner && !held)
237
+ console.error(`! daemon credential renewal for space "${this.space}" passed to another manager (this one lost the renewal lease) - it keeps serving its seats`);
238
+ this.daemonRenewalOwner = held;
239
+ }
240
+ catch (e) {
241
+ console.error(`! could not refresh the daemon renewal lease: ${rejectionText(e)} - ownership is re-decided on the next pass`);
242
+ }
243
+ }
244
+ /** Decide whether THIS manager owns the daemon's credential renewal (#1634). Both conditions are
245
+ * required, because each answers a question the other cannot:
246
+ *
247
+ * 1. The daemon must reload from this manager's store (#1447). Reminting into a store the daemon
248
+ * never reads writes bytes nobody adopts, and fingerprint-only `reloadCreds` would then name a
249
+ * generation the daemon cannot see.
250
+ * 2. This manager must hold the per-space renewal lease. Store identity CANNOT pick one owner on
251
+ * its own: `sameSecretStoreIdentity` is pure equality with no holder and no tiebreak, so every
252
+ * manager sharing one store passes it, and two owners reminting on independent timers have no
253
+ * ordering between them - one's write lands between the other's re-sign and its adoption
254
+ * request, which is the #773 refusal the challenge exists to prevent.
255
+ *
256
+ * A manager failing either test serves the space normally and skips only the daemon remint. */
257
+ async claimDaemonRenewalOwnership(waitMs = 0) {
258
+ // EVERY refusal outcome drops a held lease, not only "divergent". The refusal paths THROW
259
+ // (#1694: a non-holder answer, an unbindable answerer, an unreadable or holder-naming row on a
260
+ // no-responder rail), and a thrown refusal caught by renewDaemonCreds would otherwise leave a
261
+ // manager that once owned the renewal still holding the lease behind its own heartbeat — the
262
+ // pass refuses, the log says so, and the space keeps a renewal owner that must not remint.
263
+ // Deciding here, inside the claim, is what keeps the release on the refusal path itself.
264
+ let relation;
265
+ try {
266
+ // Only the read-only challenge is retried, so a wait that ends mid-attempt abandons a read,
267
+ // never the lease work below.
268
+ relation = await untilDeliveryAdminAnswers(waitMs, (requestMs) => this.daemonStoreRelation(requestMs(STORE_CHALLENGE_TIMEOUT_MS)), (reason, delayMs) => console.error(`! delivery-admin rail did not answer the store challenge (${reason}); retrying in ${delayMs / 1000}s`), (e) => e instanceof DeliveryAdminUnanswered);
269
+ }
270
+ catch (e) {
271
+ this.daemonRenewalEligible = false;
272
+ if (this.daemonRenewalOwner)
273
+ await this.ep.releaseDaemonRenewalLease().catch(() => { });
274
+ this.daemonRenewalOwner = false;
275
+ throw e;
276
+ }
277
+ this.daemonRenewalEligible = relation !== "divergent";
278
+ if (relation === "divergent") {
279
+ // Not our daemon's store: drop any lease we hold rather than sit on it, so the manager that
280
+ // CAN remint is not blocked behind us.
281
+ if (this.daemonRenewalOwner)
282
+ await this.ep.releaseDaemonRenewalLease();
283
+ this.daemonRenewalOwner = false;
284
+ return;
285
+ }
286
+ await this.keepDaemonRenewalLease();
287
+ }
288
+ /** #2073: arm the `endpoint-serve` credential's own renewal from its `[renewAt, exp)` window
289
+ * instead of `credRenewTimer`'s boot-phased TTL/4 tick, which can miss that window depending on
290
+ * when the timer happened to start relative to the credential's `iat`. Called after the initial
291
+ * mint (`registerManagerService`) and after every successful re-mint in the serve branch below,
292
+ * so the schedule always tracks the CURRENT credential. `credsRenewalDelayMs` is the same 75%
293
+ * convention the endpoint's delivery renewal and the membership feed use (`@cotal-ai/core`); no
294
+ * second copy of that arithmetic lives here. */
295
+ scheduleServeRenewal(creds) {
296
+ if (this.endpointServeRenewalTimer)
297
+ clearTimeout(this.endpointServeRenewalTimer);
298
+ const delay = Math.max(1_000, credsRenewalDelayMs(creds));
299
+ const renewAt = new Date(Date.now() + delay).toISOString();
300
+ this.endpointServeRenewalTimer = setTimeout(() => { void this.renewDaemonCreds(); }, delay);
301
+ this.endpointServeRenewalTimer.unref?.();
302
+ console.error(`manager endpoint-serve renewal scheduled at ${renewAt}`);
303
+ }
304
+ scheduleCredentialPushRetry() {
305
+ if (this.credentialPushRetry || this.leaseStopping)
306
+ return;
307
+ this.credentialPushRetry = setTimeout(() => {
308
+ this.credentialPushRetry = undefined;
309
+ if (this.leaseStopping)
310
+ return;
311
+ void Promise.all([
312
+ ...[...this.pendingCredentialPushes].map((nc) => this.pushRenewedCreds(nc)),
313
+ ...(this.supervisorCredentialPushPending ? [this.pushSupervisorCreds()] : []),
314
+ ]);
315
+ }, 1_000);
316
+ this.credentialPushRetry.unref();
317
+ }
318
+ /** Retain a busy transport and retry its adopted credential without replaying requests. */
319
+ pushRenewedCreds(nc) {
320
+ const active = this.credentialPushes.get(nc);
321
+ if (active)
322
+ return active;
323
+ const push = this.pushRenewedCredsOnce(nc).finally(() => { this.credentialPushes.delete(nc); });
324
+ this.credentialPushes.set(nc, push);
325
+ return push;
326
+ }
327
+ async pushRenewedCredsOnce(nc) {
328
+ this.pendingCredentialPushes.add(nc);
329
+ try {
330
+ await requestSafeReconnect(nc);
331
+ this.pendingCredentialPushes.delete(nc);
332
+ }
333
+ catch (e) {
334
+ if (nc.isClosed())
335
+ this.pendingCredentialPushes.delete(nc);
336
+ console.error(`! manager credential push deferred: ${rejectionText(e)}`);
337
+ if (!nc.isClosed())
338
+ this.scheduleCredentialPushRetry();
339
+ }
340
+ }
341
+ pushSupervisorCreds() {
342
+ if (this.supervisorCredentialPush)
343
+ return this.supervisorCredentialPush;
344
+ const push = this.pushSupervisorCredsOnce().finally(() => { this.supervisorCredentialPush = undefined; });
345
+ this.supervisorCredentialPush = push;
346
+ return push;
347
+ }
348
+ async pushSupervisorCredsOnce() {
349
+ this.supervisorCredentialPushPending = true;
350
+ try {
351
+ await this.ep.refreshCredsRequestSafe();
352
+ this.supervisorCredentialPushPending = false;
353
+ }
354
+ catch (e) {
355
+ console.error(`! remote manager supervisor credential push deferred: ${rejectionText(e)}`);
356
+ this.scheduleCredentialPushRetry();
357
+ }
358
+ }
359
+ /** #2073: the shared bounded-retry shape for a closed standing connection: wait out each of
360
+ * {@link STATIC_RECONCILE_RETRY_DELAYS_MS}, trying `attempt` after each. Waiting does not repair
361
+ * two closes, so they skip the first delay. One that closes while an all-duty renewal is in flight,
362
+ * as one the broker expires just before adoption, tries when that renewal adopts. One whose
363
+ * credential has `expired` tries at once, because its attempt renews the credential. A stop landing
364
+ * while this loop waits is not a fault this loop reports (the caller re-checks `leaseStopping`). */
365
+ async boundedReconnect(label, attempt, expired = false) {
366
+ let first = this.remoteBundleAdoption ?? (expired ? Promise.resolve() : undefined);
367
+ for (const delayMs of STATIC_RECONCILE_RETRY_DELAYS_MS) {
368
+ await (first ?? new Promise((r) => setTimeout(r, delayMs)));
369
+ first = undefined;
370
+ if (this.leaseStopping)
371
+ return true;
372
+ try {
373
+ if (await attempt())
374
+ return true;
375
+ }
376
+ catch (e) {
377
+ console.error(`! manager ${label} re-dial attempt failed: ${rejectionText(e)}`);
378
+ }
379
+ }
380
+ return false;
381
+ }
382
+ /** One class-2 renewal pass: re-sign `.cotal/delivery.creds` + `.cotal/membership-rw.creds`
383
+ * for their existing nkeys, then request the delivery daemon's EXPLICIT `reloadCreds` adoption on the
384
+ * delivery-admin rail and persist the audit record (`.cotal/renewal.<spaceKey>.json`) that `cotal doctor auth`
385
+ * renders — so "file re-signed" and "daemon adopted" are distinguishable states. A missing daemon
386
+ * (no responder) is recorded honestly: each daemon's own 75% renewal timer remains the adoption backstop.
387
+ * Never throws — renewal failure must be LOUD (log + record), not fatal to the supervisor. */
388
+ async renewDaemonCreds() {
389
+ const release = this.beginLifecycle();
390
+ if (!release)
391
+ return;
392
+ try {
393
+ // #1634: re-decide every pass, so a daemon that moved onto this manager's store becomes
394
+ // ownable, one that moved off retires this manager's ownership, and a crashed owner's expired
395
+ // lease is taken over by a survivor.
396
+ await this.claimDaemonRenewalOwnership();
397
+ // Re-sign through the manager's ONE store — the SAME store the delivery daemon reads
398
+ // (`runDelivery(args, store)`), so a hosted remint writes the store the daemon renews from,
399
+ // never a divergent one. Locally this is the workstation FS store (`.cotal/*.creds`).
400
+ // `this.space` gates cross-space signer swaps; the `preflight` proves broker acceptance before
401
+ // overwriting from ANY signer form (full or stripped). A same-label alternate full bundle is
402
+ // self-bound, not broker-bound, so the manager-hosted path proves every re-sign before it could
403
+ // clobber the last-good with a broker-dead cred; a wrong-account signer's cred is refused here.
404
+ const results = this.daemonRenewalOwner
405
+ ? await remintDaemonCreds(this.workspaceRoot, this.space, this.secrets, {
406
+ preflight: (creds) => this.probeStaticCredential(creds).then((r) => r.ok),
407
+ })
408
+ : [];
409
+ const resigned = results.filter((r) => r.ok);
410
+ let adoption;
411
+ if (resigned.length) {
412
+ // Hand the daemon the EXPECTED generation per component (SHA-256 of the JWT we just
413
+ // re-signed) so its reply proves it adopted THIS generation, not merely re-read some file.
414
+ const expected = {};
415
+ for (const r of resigned) {
416
+ if (r.file === DELIVERY_CREDS_KIND && r.fingerprint)
417
+ expected.delivery = r.fingerprint;
418
+ else if (r.file === MEMBERSHIP_RW_CREDS_KIND && r.fingerprint)
419
+ expected.membership = r.fingerprint;
420
+ }
421
+ try {
422
+ const reply = await this.ep.requestDeliveryAdmin("reloadCreds", { expected }, DELIVERY_ADMIN_RELOAD_TIMEOUT_MS);
423
+ // Keep the per-component aggregate on BOTH outcomes: on a top-level failure `reply.data`
424
+ // still carries which component adopted and which was refused, which `doctor auth` renders.
425
+ adoption = reply.ok
426
+ ? { ok: true, detail: reply.data }
427
+ : { ok: false, error: reply.error, detail: reply.data };
428
+ }
429
+ catch (e) {
430
+ adoption = { ok: false, error: `no delivery-admin responder (${rejectionText(e)}) - the daemon's 75% re-read backstop adopts the re-signed file` };
431
+ }
432
+ }
433
+ for (const r of results.filter((x) => !x.ok && !x.skipped))
434
+ console.error(`! credential renewal: could not re-sign ${r.file}: ${r.error} - the daemon dies loud at this cred's expiry unless it is reminted`);
435
+ if (adoption && !adoption.ok)
436
+ console.error(`! credential renewal: daemon adoption failed: ${adoption.error}`);
437
+ // `writeRenewalRecord` redacts the ephemeral fingerprint at the persistence boundary (covering
438
+ // the `doctor auth --fix` writer too), so the results pass straight through.
439
+ // A non-owner (#1634) re-signed nothing, so it writes no record: an empty one renders in
440
+ // `doctor auth` as a pass that never ran.
441
+ if (this.daemonRenewalOwner)
442
+ writeRenewalRecord(this.workspaceRoot, this.space, { ts: new Date().toISOString(), owner: "manager", results, adoption });
443
+ this.warnOnSystemCredExpiry();
444
+ // The MANAGER is the renewal owner for its managed-static agent creds —
445
+ // supervisor-side PUSH remint for recorded LIVE slots (the child JWT is never proof of
446
+ // incarnation; a copied credential cannot drive this and is stranded at its own row's TTL).
447
+ // Same class-2 mechanics as the daemon creds: re-sign the file for the SAME nkey; the
448
+ // agent endpoint's 75% source re-read adopts it.
449
+ //
450
+ // Each credential is judged as of the NEXT pass, so one whose renewal point falls before it
451
+ // is re-signed now, ahead of the endpoint's re-read. Judged as of now, a credential whose
452
+ // renewal point lands just after a pass waited a whole interval: the endpoint warned every
453
+ // minute that the file still held the old generation, and when the next pass came in the
454
+ // credential's last minute, the endpoint's one-minute retry could miss it and the connection
455
+ // expired.
456
+ const nextPassSec = Math.floor(Date.now() / 1000) + Math.ceil(credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC) / 1000);
457
+ if (!this.userMode) {
458
+ for (const a of [...this.agents.values()]) {
459
+ // The `terminalizing` test here is an OPTIMISATION, NOT THE GUARD. There are awaits below
460
+ // it, so an agent can latch mid-iteration and this filter will have already let it
461
+ // through — what actually refuses is the same test at the top of
462
+ // {@link renewManagedStaticCred}, which every renewal on this path goes through.
463
+ // COUPLING: deleting or weakening that check silently promotes this line from an
464
+ // optimisation into the whole guard, and nothing fails at the moment of the change.
465
+ if (a.userOwner || a.terminalizing || !a.seed || !a.secretPaths?.creds)
466
+ continue;
467
+ try {
468
+ const stored = await this.secrets.get(agentSecretKeyForFile(a.secretPaths.creds, this.space));
469
+ if (stored === undefined)
470
+ continue; // no materialized cred (never minted here) - nothing to renew
471
+ const health = inspectCredHealth(stored, nextPassSec);
472
+ if (health.state === "healthy")
473
+ continue;
474
+ if (health.state === "unbounded" || health.state === "unreadable") {
475
+ console.error(`! managed cred renewal ${a.name}: credential is ${health.state}${health.error ? ` (${health.error})` : ""} - not renewed (a pre-TTL credential stays as minted until respawn)`);
476
+ continue;
477
+ }
478
+ await this.renewManagedStaticCred(a);
479
+ }
480
+ catch (e) {
481
+ console.error(`! managed cred renewal ${a.name}: ${rejectionText(e)} - the agent dies loud at this cred's expiry unless it is reminted`);
482
+ }
483
+ }
484
+ }
485
+ // The manager is the `endpoint-serve` renewal owner for its own
486
+ // service credential: re-mint the same serve identity with a fresh bounded exp through the
487
+ // §13.1 mint fence over a scoped one-shot executor (staging a new ledger row in a later
488
+ // second or idempotently re-staging the active row within the same second, and releasing only
489
+ // on winning the gate CAS; never the standing connection). The serve connection's
490
+ // authenticator presents the refreshed credential on its next (re)connect.
491
+ if (this.serviceServe?.creds && this.auth) {
492
+ const s = this.serviceServe;
493
+ const authRef = this.auth;
494
+ try {
495
+ const health = inspectCredHealth(this.serviceServe.creds);
496
+ if (health.state !== "healthy") {
497
+ s.creds = await this.withEndpointServeExecutor(({ authKv }) => mintCreds(authRef, s.identity, "endpoint-serve", {
498
+ serveIssuance: serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId }),
499
+ endpointServe: s.grant,
500
+ }));
501
+ // #2073: a superseded instance's re-mint fails the gate CAS above and lands in the
502
+ // catch below, not here — this re-mint already re-checks the issuance gate through
503
+ // the SAME executor a fresh registration would use, so there is no second epoch read
504
+ // to add before re-binding after a re-dial.
505
+ await this.pushRenewedCreds(s.nc);
506
+ this.scheduleServeRenewal(s.creds);
507
+ }
508
+ }
509
+ catch (e) {
510
+ console.error(`! endpoint-serve renewal: ${rejectionText(e)} - the manager's service endpoint dies loud at this cred's expiry unless it is re-registered`);
511
+ }
512
+ }
513
+ // The manager is also the goal-writer's renewal owner — re-mint the SAME
514
+ // goal-writer nkey with a fresh bounded exp AND re-stage its new credId into the §13.1 family,
515
+ // through the scoped executor (never the standing seed). Without this the standing goal-writer
516
+ // connection dies at its TTL and spawn-as-action stops accepting until a restart. The
517
+ // connection's authenticator presents the refreshed credential on its next (re)connect.
518
+ if (this.goalWriter && this.goalWriterCreds && this.auth) {
519
+ const gw = this.goalWriter;
520
+ try {
521
+ if (inspectCredHealth(this.goalWriterCreds).state !== "healthy") {
522
+ const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageGoalWriter(authKv));
523
+ this.goalWriterCreds = fresh;
524
+ gw.creds = fresh;
525
+ await this.pushRenewedCreds(gw.nc);
526
+ }
527
+ }
528
+ catch (e) {
529
+ console.error(`! goal-writer renewal: ${rejectionText(e)} - spawn-as-action stops accepting at this cred's expiry unless the manager restarts`);
530
+ }
531
+ }
532
+ // The manager is also the session-ledger's renewal owner — re-mint the SAME nkey
533
+ // with a fresh bounded exp AND re-stage its new credId into the §13.1 family, through the
534
+ // scoped executor. Without this the standing session-ledger connection dies at its TTL and
535
+ // `attach` stops establishing sessions until a restart. The connection's authenticator presents
536
+ // the refreshed credential on its next (re)connect.
537
+ // SPEC 14.6: every hosted drive's per-run `run-driver` credential is the manager's to renew
538
+ // for the same nkey; a run parked in a pause for days must not die at the credential's TTL.
539
+ await this.runHosting?.renew();
540
+ if (this.sessionLedgerConn && this.sessionLedgerCreds && this.auth) {
541
+ const sw = this.sessionLedgerConn;
542
+ try {
543
+ if (inspectCredHealth(this.sessionLedgerCreds).state !== "healthy") {
544
+ const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageSessionLedger(authKv));
545
+ this.sessionLedgerCreds = fresh;
546
+ sw.creds = fresh;
547
+ await this.pushRenewedCreds(sw.nc);
548
+ }
549
+ }
550
+ catch (e) {
551
+ console.error(`! session-ledger renewal: ${rejectionText(e)} - attach stops establishing sessions at this cred's expiry unless the manager restarts`);
552
+ }
553
+ }
554
+ }
555
+ catch (e) {
556
+ console.error(`! credential renewal pass failed: ${rejectionText(e)}`);
557
+ }
558
+ finally {
559
+ release();
560
+ }
561
+ }
562
+ /** Renew the remote registration executor through the typed host protocol. A healthy credential
563
+ * is retained; near-expiry and expired credentials are replaced for the same nkey. */
564
+ async renewRemoteExecutor(force = false) {
565
+ if (!this.remoteAuthority)
566
+ return;
567
+ const current = this.remoteExecutorCreds;
568
+ if (!force && current && inspectCredHealth(current).state === "healthy")
569
+ return;
570
+ try {
571
+ this.remoteExecutorCreds = await this.remoteAuthority.renewExecutor();
572
+ }
573
+ catch (e) {
574
+ console.error(`! remote manager executor renewal: ${rejectionText(e)} - registration maintenance and clean deregistration remain unavailable until renewal succeeds`);
575
+ if (force)
576
+ throw e;
577
+ }
578
+ }
579
+ /** An active signerless manager renews its standing duties together. The issuer stages the closed
580
+ * credential family first; broker preflight proves every JWT and existing caller-held nkey
581
+ * before any mutable holder changes. A failed candidate leaves all current creds intact. */
582
+ async renewRemoteStandingBundle(force = false) {
583
+ if (this.remoteBundleRenewal)
584
+ return this.remoteBundleRenewal;
585
+ if (this.leaseStopping)
586
+ return;
587
+ this.remoteBundleAdoption = new Promise((resolve) => { this.finishRemoteBundleAdoption = resolve; });
588
+ const renewal = this.renewRemoteStandingBundleOnce(force, performance.now() + REMOTE_STANDING_BUDGET_MS);
589
+ this.remoteBundleRenewal = renewal;
590
+ try {
591
+ await renewal;
592
+ }
593
+ finally {
594
+ this.finishRemoteBundleAdoption?.();
595
+ if (this.remoteBundleRenewal === renewal) {
596
+ this.remoteBundleRenewal = undefined;
597
+ this.remoteBundleAdoption = undefined;
598
+ this.finishRemoteBundleAdoption = undefined;
599
+ }
600
+ }
601
+ }
602
+ /** A signerless manager's closed standing connection re-dials through the all-duty family only.
603
+ * A healthy holder re-dials as is. An unhealthy one waits for the closed renewal and adoption,
604
+ * and a refusal fails this attempt with last-good and debt kept. Nothing is minted locally. */
605
+ async renewRemoteBeforeRedial(label, read) {
606
+ if (inspectCredHealth(read() ?? "").state === "healthy")
607
+ return;
608
+ await this.deps.renewRemoteStandingBundle(true);
609
+ if (inspectCredHealth(read() ?? "").state !== "healthy")
610
+ throw new Error(`the ${label} credential is not healthy after all-duty renewal; last-good is kept and nothing is minted locally`);
611
+ }
612
+ async renewRemoteStandingBundleOnce(force, deadline) {
613
+ const remote = this.remoteAuthority;
614
+ if (!remote?.renewStandingBundle || !this.serviceServe)
615
+ return;
616
+ const current = [this.remoteSupervisorCreds, this.remoteExecutorCreds, this.serviceServe.creds,
617
+ this.goalWriterCreds, this.sessionLedgerCreds];
618
+ if (!force && current.every((cred) => cred && inspectCredHealth(cred).state === "healthy")) {
619
+ await Promise.all([
620
+ ...[...this.pendingCredentialPushes].map((nc) => this.pushRenewedCreds(nc)),
621
+ ...(this.supervisorCredentialPushPending ? [this.pushSupervisorCreds()] : []),
622
+ ]);
623
+ return;
624
+ }
625
+ const processEpoch = this.serviceServe.grant.epoch;
626
+ let candidate;
627
+ const serving = this.serviceServe;
628
+ const previous = { nc: serving.nc, handle: serving.handle };
629
+ let replacement;
630
+ let adopted = false;
631
+ try {
632
+ // Only this continuation can adopt. A host operation may still issue after this wait times
633
+ // out, but its late result cannot re-enter preflight or change any Manager holder.
634
+ candidate = await withTimeout(remote.renewStandingBundle(processEpoch), remoteStandingTimeLeft(deadline), "remote manager standing authority exceeded its 10000ms aggregate budget; issuance outcome is unknown");
635
+ if (Object.keys(candidate).sort().join(",") !== [...REMOTE_MANAGER_IDENTITY_NAMES].sort().join(","))
636
+ throw new Error("host returned an incomplete or widened standing credential family");
637
+ for (const name of REMOTE_MANAGER_IDENTITY_NAMES) {
638
+ if (typeof candidate[name] !== "string" || inspectCredHealth(candidate[name]).state === "unreadable")
639
+ throw new Error(`host returned an unreadable ${name} credential`);
640
+ if (!remote.accountPublicKey || accountFromCreds(candidate[name]) !== remote.accountPublicKey)
641
+ throw new Error(`host returned a ${name} credential for another account`);
642
+ if (credsClaims(candidate[name]).sub !== remote.identities[name].id)
643
+ throw new Error(`host returned a ${name} credential for a different nkey than the held identity`);
644
+ const staged = candidate[name];
645
+ const nc = await this.dialRemoteStanding({ authenticator: (nonce) => credsAuthenticator(new TextEncoder().encode(staged))(nonce), maxReconnectAttempts: 0 }, deadline);
646
+ await nc.close();
647
+ }
648
+ remoteStandingTimeLeft(deadline);
649
+ if (this.leaseStopping || this.serviceServe !== serving || serving.nc !== previous.nc || serving.grant.epoch !== processEpoch)
650
+ throw new Error("manager changed its active serve epoch or connection while standing renewal was in flight");
651
+ const stagedServeCreds = candidate.serve;
652
+ replacement = await this.dialServeConnection({ ...serving, creds: stagedServeCreds }, () => adopted ? serving.creds : stagedServeCreds, deadline);
653
+ remoteStandingTimeLeft(deadline);
654
+ if (this.leaseStopping || this.serviceServe !== serving || serving.nc !== previous.nc || serving.grant.epoch !== processEpoch)
655
+ throw new Error("manager changed its active serve epoch or connection while standing renewal was in flight");
656
+ if (REMOTE_MANAGER_IDENTITY_NAMES.some((name) => inspectCredHealth(candidate[name]).state !== "healthy"))
657
+ throw new Error("standing candidate is no longer healthy after broker preflight");
658
+ serving.nc = replacement.nc;
659
+ serving.handle = replacement.handle;
660
+ replacement = undefined;
661
+ this.remoteSupervisorCreds = candidate.supervisor;
662
+ this.remoteExecutorCreds = candidate.executor;
663
+ this.serviceServe.creds = candidate.serve;
664
+ adopted = true;
665
+ this.goalWriterCreds = candidate.goalWriter;
666
+ this.sessionLedgerCreds = candidate.sessionLedger;
667
+ if (this.goalWriter)
668
+ this.goalWriter.creds = candidate.goalWriter;
669
+ if (this.sessionLedgerConn)
670
+ this.sessionLedgerConn.creds = candidate.sessionLedger;
671
+ // Adoption is committed above; a connection that cannot come back yet is a push failure the
672
+ // endpoint's own reconnect loop retries with the adopted credential, not unadopted debt.
673
+ this.remoteRenewalDebt = undefined;
674
+ // Maintenance needed by admitted handlers must not wait for those same handlers to drain.
675
+ this.finishRemoteBundleAdoption?.();
676
+ await withTimeout(Promise.all([
677
+ this.pushSupervisorCreds(),
678
+ (async () => {
679
+ try {
680
+ // A handler or a lost broker PONG can keep stop/flush pending forever. Only the
681
+ // retired transport is expendable: never retry its requests or close the replacement.
682
+ await withTimeout((async () => {
683
+ await previous.handle.stop();
684
+ await previous.nc.flush();
685
+ })(), 5_000, "old serve drain unfinished after 5000ms; closing retired transport, in-flight request outcomes are unknown and must not be retried");
686
+ }
687
+ finally {
688
+ await previous.nc.close();
689
+ }
690
+ })().catch((e) => console.error(`! remote manager retired serve drainage after renewal: ${rejectionText(e)}`)),
691
+ ...(this.goalWriter ? [this.pushRenewedCreds(this.goalWriter.nc)] : []),
692
+ ...(this.sessionLedgerConn ? [this.pushRenewedCreds(this.sessionLedgerConn.nc)] : []),
693
+ ]), remoteStandingTimeLeft(deadline), "remote manager standing reconnect exceeded its 10000ms aggregate budget; adopted transports keep their native reconnect ownership");
694
+ }
695
+ catch (e) {
696
+ if (replacement) {
697
+ await this.discardServeCandidate(replacement.nc, replacement.handle);
698
+ }
699
+ if (adopted) {
700
+ console.error(`! remote manager adopted standing family: ${rejectionText(e)}`);
701
+ return;
702
+ }
703
+ const unadoptedSubjects = candidate && typeof candidate === "object"
704
+ ? Object.values(candidate).flatMap((cred) => { try {
705
+ return typeof cred === "string" && credsClaims(cred).sub ? [credsClaims(cred).sub] : [];
706
+ }
707
+ catch {
708
+ return [];
709
+ } })
710
+ : REMOTE_MANAGER_IDENTITY_NAMES.map((name) => remote.identities[name].id);
711
+ this.remoteRenewalDebt = { at: Date.now(), processEpoch, reason: rejectionText(e), unadoptedSubjects };
712
+ console.error(`! remote manager all-duty renewal: ${this.remoteRenewalDebt.reason} - no unsigned or local replacement is available`);
713
+ if (force)
714
+ throw e;
715
+ }
716
+ }
717
+ /** Warn, on every renewal pass, when a $SYS credential is at or past its renewal point.
718
+ *
719
+ * The manager is the renewal owner for every credential it CAN re-sign, and these two are the ones
720
+ * it cannot: they are `rotation-renewed`, so no resident process re-mints them and they simply die
721
+ * on their 30-day horizon. Before this, a mesh that never ran `doctor auth` got no signal at all,
722
+ * it discovered the expiry as an "Authorization Violation" in the delivery log and a refused
723
+ * membership adoption, weeks after the warning would have been actionable (#338). The pass runs
724
+ * every half-TTL of the 24h class, so this repeats about twice a day for the ~7 days between the
725
+ * renewal point and expiry: loud enough to be seen, bounded enough not to be noise.
726
+ *
727
+ * Diagnostic only, and deliberately non-fatal: renewal is an operator action (`cotal down` then
728
+ * `cotal up --rotate-sys`, which needs a broker restart), so the manager must report it, never
729
+ * attempt it. An absent file is the unprovisioned space, reported by the daemon that needs it. */
730
+ warnOnSystemCredExpiry() {
731
+ for (const file of SYSTEM_CREDS_FILES) {
732
+ let health;
733
+ try {
734
+ // The pair is PER-SPACE, so the location comes from the resolver and never from a
735
+ // path built here (§2 rule 1). Building `.cotal/<kind>` instead would not warn on a wrong
736
+ // file — it would silently warn on NOTHING, for every provisioned root, forever, which is
737
+ // exactly the signal #338 added this for. The resolver may also refuse (§2 rules 3, 4); that
738
+ // refusal is caught with the unreadable case for the reason on the tin — the daemon that
739
+ // NEEDS the pair resolves it through the same function and reports it loudly there, so a
740
+ // diagnostic pass has nothing to add by crashing renewal.
741
+ const path = join(this.workspaceRoot, ".cotal", spaceMaterialKey(file, this.space, { injected: false, root: this.workspaceRoot }));
742
+ if (!existsSync(path))
743
+ continue;
744
+ health = inspectCredHealth(readFileSync(path, "utf8"));
745
+ }
746
+ catch {
747
+ continue; // an unreadable $SYS file is the daemon's loud failure, not a renewal-pass crash
748
+ }
749
+ const when = health.exp ? new Date(health.exp * 1000).toISOString() : "an unknown date";
750
+ if (health.state === "expired")
751
+ console.error(`! $SYS credential ${file} EXPIRED ${when} - the broker denies it, and NOTHING renews it in place (it is rotation-renewed). Live eviction and the membership feed stay down until: \`cotal down\` then \`cotal up --rotate-sys\` (agents, creds and data survive)`);
752
+ else if (health.state === "near-expiry")
753
+ console.error(`! $SYS credential ${file} expires ${when} and nothing renews it in place (it is rotation-renewed) - schedule: \`cotal down\` then \`cotal up --rotate-sys\` (agents, creds and data survive)`);
754
+ }
755
+ }
756
+ }
757
+ //# sourceMappingURL=credential-renewal.js.map