@cotal-ai/manager 0.55.0 → 0.56.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.
package/dist/manager.js CHANGED
@@ -4,7 +4,7 @@ import { hostname } from "node:os";
4
4
  import { credsAuthenticator } from "@nats-io/transport-node";
5
5
  import { existsSync, lstatSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs";
6
6
  import { isAbsolute, join, dirname, resolve } from "node:path";
7
- import { CotalEndpoint, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, divergentSecretStoreNotice, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, deprovisionAgent, firstFreeName, spawnNameError, idFromCreds, inspectCredHealth, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, mintCreds, mintGeneration, mintAcceptedToken, openIssuedStore, acceptedBucket, issuedBucket, mintLifecycleUid, managedRetirementOpId, mkSecretDir, newIdentity, actionContext, parsePrincipalKey, parseShareSelection, principalKey, probeConnect, provisionAgent, provisionAgentDurables, registry, resolveAuthProvider, saveAgentFile, subjectMatches, AUTH_ENDPOINT, EP_CMD_RETIRE_LIFECYCLE, epRequestSubject, epCallerReplyFilter, parseEpSubject, controlServiceSubject, eventChannelPrincipal, } from "@cotal-ai/core";
7
+ import { CotalEndpoint, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, divergentSecretStoreNotice, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, deprovisionAgent, firstFreeName, spawnNameError, idFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, mintCreds, mintGeneration, mintAcceptedToken, openIssuedStore, acceptedBucket, issuedBucket, mintLifecycleUid, managedRetirementOpId, mkSecretDir, newIdentity, actionContext, parsePrincipalKey, parseShareSelection, principalKey, probeConnect, provisionAgent, provisionAgentDurables, registry, resolveAuthProvider, saveAgentFile, subjectMatches, AUTH_ENDPOINT, EP_CMD_RETIRE_LIFECYCLE, epRequestSubject, epCallerReplyFilter, parseEpSubject, controlServiceSubject, eventChannelPrincipal, } from "@cotal-ai/core";
8
8
  import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, connectorInstallHint, DEFAULT_CONNECTOR, defaultAgentType, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds, resolveOnPath, createManagerInstanceIdentity, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
9
9
  import { createRuntime, isCustodialRuntime, requireRuntimeAdopt, requireRuntimeReap, RuntimeReapUnproven, } from "./runtime/index.js";
10
10
  import { AttachEndpoint } from "./attach-endpoint.js";
@@ -109,7 +109,7 @@ const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
109
109
  * broker/eviction blip; the wider later spacing avoids hammering a persistently unavailable
110
110
  * authority. The finite ~36s window is intentionally not a liveness inference: exhausting it
111
111
  * leaves the durable alias held and requires a later manager start. */
112
- const STATIC_RECONCILE_RETRY_DELAYS_MS = [1_000, 5_000, 30_000];
112
+ export const STATIC_RECONCILE_RETRY_DELAYS_MS = [1_000, 5_000, 30_000];
113
113
  const STATIC_RECONCILE_MAX_ATTEMPTS = STATIC_RECONCILE_RETRY_DELAYS_MS.length + 1;
114
114
  /** The STABLE retirement opId for one lifecycle (#29 piece 3): deterministic from the uid, so a
115
115
  * despawn retry, a same-name-spawn nudge, and the auth service's boot resume all drive the SAME
@@ -514,6 +514,11 @@ export class Manager {
514
514
  leaseStopping = false;
515
515
  /** The class-2 renewal owner's half-TTL schedule (D5 slice 5); armed only on auth meshes. */
516
516
  credRenewTimer;
517
+ /** #2073: the `endpoint-serve` credential's OWN renewal, armed from its `[renewAt, exp)` window
518
+ * (`credsRenewalDelayMs`) rather than left to `credRenewTimer`'s boot-phased TTL/4 tick, which can
519
+ * miss the window by ordering. Re-armed at registration and after every successful re-mint;
520
+ * cleared in `stop()` beside `credRenewTimer`. */
521
+ endpointServeRenewalTimer;
517
522
  /** #1634: does THIS manager own the delivery daemon's credential renewal? True only while the
518
523
  * daemon reloads from this manager's store AND this manager holds the per-space renewal lease.
519
524
  * Starts false: a manager that has not proved both must not remint. */
@@ -639,17 +644,42 @@ export class Manager {
639
644
  * write it to. The operator reading the refusal is on the manager's mesh, never on the record's. A
640
645
  * boolean parameter is how that happened, so the mode is read from `this` and a third door cannot
641
646
  * pass the wrong one.
647
+ *
648
+ * The selector below reads the three-valued mesh mode (`open | static | user`), not a boolean
649
+ * derived from it (#567). `this.userMode` is `false` for BOTH static and open, so a boolean
650
+ * selector collapses those two and an open mesh was handed the static route (`cotal mint
651
+ * --provision`), which `mint` refuses outright on an open mesh. A boolean also has no third
652
+ * state to invert, so a mutation grid over `return this.userMode ? … : …` proves the one arm it
653
+ * has is load-bearing but is structurally blind to a missing arm: there is no mutant that turns
654
+ * "two arms" into "three arms". Switching on `meshMode` gives a fourth mesh mode nowhere to fall
655
+ * silently, since `switch` has no default arm to catch it.
642
656
  */
657
+ get meshMode() {
658
+ if (this.userMode)
659
+ return "user";
660
+ if (this.auth !== undefined)
661
+ return "static";
662
+ return "open";
663
+ }
643
664
  readerRemedy(owner, channel) {
644
- return this.userMode
645
- ? `\`cotal actor grant <reader> --owner ${owner} --scope '' --allow-subscribe '${channel}' ` +
646
- `--allow-publish ''\`, with every field spelled out: \`actor grant\` is an upsert of the ` +
647
- `WHOLE row and an omitted flag means the WIDE default (\`>\` read, \`>\` post, \`spawn,role:default\` ` +
648
- `scope), not "leave it alone".`
649
- : `\`cotal mint <reader> --profile agent --allow-subscribe ${channel} --provision\`, where there ` +
650
- `is no actor ledger for \`actor grant\` to write to. The AGENT profile, not the observer ` +
651
- `one: \`mint\` reads --allow-subscribe only for that profile, so an observer mint is ` +
652
- `refused outright and writes no creds file.`;
665
+ switch (this.meshMode) {
666
+ case "user":
667
+ return (`\`cotal actor grant <reader> --owner ${owner} --scope '' --allow-subscribe '${channel}' ` +
668
+ `--allow-publish ''\`, with every field spelled out: \`actor grant\` is an upsert of the ` +
669
+ `WHOLE row and an omitted flag means the WIDE default (\`>\` read, \`>\` post, \`spawn,role:default\` ` +
670
+ `scope), not "leave it alone".`);
671
+ case "static":
672
+ return (`\`cotal mint <reader> --profile agent --allow-subscribe ${channel} --provision\`, where there ` +
673
+ `is no actor ledger for \`actor grant\` to write to. The AGENT profile, not the observer ` +
674
+ `one: \`mint\` reads --allow-subscribe only for that profile, so an observer mint is ` +
675
+ `refused outright and writes no creds file.`);
676
+ case "open":
677
+ return (`there is nothing to grant on an open mesh: it has no credentials and no ACLs, so any peer ` +
678
+ `may read \`${channel}\` by connecting bare and listing that channel (\`cotal join\` or an ` +
679
+ `endpoint whose channels include it); this refusal stands because the own-channel rule ` +
680
+ `applies to every mesh, and a spawn is not the place to hand out a read on another agent's ` +
681
+ `tool inputs and outputs.`);
682
+ }
653
683
  }
654
684
  start() {
655
685
  if (this.startTask)
@@ -1055,6 +1085,50 @@ export class Manager {
1055
1085
  }
1056
1086
  await this.keepDaemonRenewalLease();
1057
1087
  }
1088
+ /** #2073: arm the `endpoint-serve` credential's own renewal from its `[renewAt, exp)` window
1089
+ * instead of `credRenewTimer`'s boot-phased TTL/4 tick, which can miss that window depending on
1090
+ * when the timer happened to start relative to the credential's `iat`. Called after the initial
1091
+ * mint (`registerManagerService`) and after every successful re-mint in the serve branch below,
1092
+ * so the schedule always tracks the CURRENT credential. `credsRenewalDelayMs` is the same 75%
1093
+ * convention the endpoint's delivery renewal and the membership feed use (`@cotal-ai/core`); no
1094
+ * second copy of that arithmetic lives here. */
1095
+ scheduleServeRenewal(creds) {
1096
+ if (this.endpointServeRenewalTimer)
1097
+ clearTimeout(this.endpointServeRenewalTimer);
1098
+ const delay = Math.max(1_000, credsRenewalDelayMs(creds));
1099
+ const renewAt = new Date(Date.now() + delay).toISOString();
1100
+ this.endpointServeRenewalTimer = setTimeout(() => { void this.renewDaemonCreds(); }, delay);
1101
+ this.endpointServeRenewalTimer.unref?.();
1102
+ console.error(`manager endpoint-serve renewal scheduled at ${renewAt}`);
1103
+ }
1104
+ /** #2073: push a freshly re-minted credential onto its LIVE connection instead of waiting for a
1105
+ * reconnect the expiry itself would force two dials too late. `nc.reconnect()` re-evaluates the
1106
+ * authenticator, which reads the mutable `creds` holder on every attempt, so the new CONNECT
1107
+ * presents the fresh credential without re-registration. In-flight requests on the connection
1108
+ * fail once, on the reconnect. Best-effort, matching `CotalEndpoint.swapConnectionOntoFreshCreds`:
1109
+ * a connection that is already closed (e.g. mid re-dial after a fault) cannot reconnect, and that
1110
+ * failure is not this call's to report. */
1111
+ async pushRenewedCreds(nc) {
1112
+ await nc.reconnect().catch(() => { });
1113
+ }
1114
+ /** #2073: the shared bounded-retry shape for a closed standing connection: wait out each of
1115
+ * {@link STATIC_RECONCILE_RETRY_DELAYS_MS}, trying `attempt` after each. A stop landing while
1116
+ * this loop waits is not a fault this loop reports (the caller re-checks `leaseStopping`). */
1117
+ async boundedReconnect(label, attempt) {
1118
+ for (const delayMs of STATIC_RECONCILE_RETRY_DELAYS_MS) {
1119
+ await new Promise((r) => setTimeout(r, delayMs));
1120
+ if (this.leaseStopping)
1121
+ return true;
1122
+ try {
1123
+ if (await attempt())
1124
+ return true;
1125
+ }
1126
+ catch (e) {
1127
+ console.error(`! manager ${label} re-dial attempt failed: ${e.message}`);
1128
+ }
1129
+ }
1130
+ return false;
1131
+ }
1058
1132
  /** One class-2 renewal pass (D5 slice 5): re-sign `.cotal/delivery.creds` + `.cotal/membership-rw.creds`
1059
1133
  * for their existing nkeys, then request the delivery daemon's EXPLICIT `reloadCreds` adoption on the
1060
1134
  * delivery-admin rail and persist the audit record (`.cotal/renewal.<spaceKey>.json`) that `cotal doctor auth`
@@ -1165,6 +1239,12 @@ export class Manager {
1165
1239
  serveIssuance: serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId }),
1166
1240
  endpointServe: s.grant,
1167
1241
  }));
1242
+ // #2073: a superseded instance's re-mint fails the gate CAS above and lands in the
1243
+ // catch below, not here — this re-mint already re-checks the issuance gate through
1244
+ // the SAME executor a fresh registration would use, so there is no second epoch read
1245
+ // to add before re-binding after a re-dial.
1246
+ await this.pushRenewedCreds(s.nc);
1247
+ this.scheduleServeRenewal(s.creds);
1168
1248
  }
1169
1249
  }
1170
1250
  catch (e) {
@@ -1183,6 +1263,7 @@ export class Manager {
1183
1263
  const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageGoalWriter(authKv));
1184
1264
  this.goalWriterCreds = fresh;
1185
1265
  gw.creds = fresh;
1266
+ await this.pushRenewedCreds(gw.nc);
1186
1267
  }
1187
1268
  }
1188
1269
  catch (e) {
@@ -1204,6 +1285,7 @@ export class Manager {
1204
1285
  const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageSessionLedger(authKv));
1205
1286
  this.sessionLedgerCreds = fresh;
1206
1287
  sw.creds = fresh;
1288
+ await this.pushRenewedCreds(sw.nc);
1207
1289
  }
1208
1290
  }
1209
1291
  catch (e) {
@@ -1739,6 +1821,8 @@ export class Manager {
1739
1821
  clearInterval(this.leaseTimer);
1740
1822
  if (this.credRenewTimer)
1741
1823
  clearInterval(this.credRenewTimer);
1824
+ if (this.endpointServeRenewalTimer)
1825
+ clearTimeout(this.endpointServeRenewalTimer);
1742
1826
  if (this.daemonRenewalLeaseTimer)
1743
1827
  clearInterval(this.daemonRenewalLeaseTimer);
1744
1828
  if (this.sessionKeyRenewTimer)
@@ -3540,9 +3624,14 @@ export class Manager {
3540
3624
  * uncertain black hole. */
3541
3625
  liveRosterNames() {
3542
3626
  const live = new Set();
3543
- for (const p of this.ep.getRoster())
3544
- if (p.status !== "offline")
3545
- live.add(p.card.name);
3627
+ for (const p of this.ep.getRoster()) {
3628
+ if (p.status === "offline")
3629
+ continue;
3630
+ const predecessor = this.confirmedRetiredPredecessors.get(p.card.name);
3631
+ if (predecessor !== undefined && predecessor.principal === p.card.id && predecessor.lifecycleUid === p.lifecycleUid)
3632
+ continue;
3633
+ live.add(p.card.name);
3634
+ }
3546
3635
  return live;
3547
3636
  }
3548
3637
  /** THE single name-liveness predicate both the hard-pinned collision refuse (M6, P2 item 2) and
@@ -3561,7 +3650,9 @@ export class Manager {
3561
3650
  * choice at allocation, never an authority check (the broker still enforces): a stale
3562
3651
  * still-live-looking row only costs a numbered suffix, and a missed freshly-joined occupant is
3563
3652
  * still refused downstream exactly as before. Offline rows do NOT occupy — a properly retired
3564
- * name stays reusable. */
3653
+ * name stays reusable. A row this manager itself confirmed retired (its alias, principal, and
3654
+ * lifecycleUid all matching a {@link confirmedRetiredPredecessors} entry) does not occupy
3655
+ * either, even while its advisory presence record ages out. */
3565
3656
  uniqueName(base) {
3566
3657
  const live = this.liveRosterNames();
3567
3658
  return firstFreeName(base, (n) => this.nameInUse(n, live));
@@ -3682,33 +3773,40 @@ export class Manager {
3682
3773
  route,
3683
3774
  }, caller, hooks);
3684
3775
  }
3685
- /** Resolve a placed spawn directory on this manager's host. The manager serves any existing
3686
- * absolute directory it can resolve. It creates nothing and never substitutes the workspace root. */
3687
- resolveSpawnCwd(value) {
3688
- const asked = typeof value === "string" ? value : String(value ?? "");
3689
- const refuse = (reason) => {
3690
- throw new EpEnvelopeError("failed-precondition", `cwd does not resolve on this host: ${JSON.stringify(asked)} (${reason})`);
3691
- };
3692
- if (!isAbsolute(asked))
3693
- refuse("expected an absolute path");
3694
- let cwd = asked;
3776
+ /** The realpath + directory checks a placed spawn directory must pass on this manager's host,
3777
+ * shared by the served `resolve-cwd` command and the `spawn` admission check (#385 item 2): one
3778
+ * function, so the two doors never drift. Creates nothing and never substitutes the workspace root. */
3779
+ checkSpawnCwd(resolved) {
3780
+ let cwd = resolved;
3695
3781
  try {
3696
- cwd = realpathSync(asked);
3782
+ cwd = realpathSync(resolved);
3697
3783
  }
3698
3784
  catch (error) {
3699
- refuse(`path cannot be resolved: ${error.message}`);
3785
+ return { refusal: `path cannot be resolved: ${error.message}` };
3700
3786
  }
3701
3787
  try {
3702
3788
  if (!statSync(cwd).isDirectory())
3703
- refuse("path is not a directory");
3789
+ return { refusal: "path is not a directory" };
3704
3790
  }
3705
3791
  catch (error) {
3706
- if (error instanceof EpEnvelopeError)
3707
- throw error;
3708
- refuse(error.message);
3792
+ return { refusal: error.message };
3709
3793
  }
3710
3794
  return { cwd, host: hostname() };
3711
3795
  }
3796
+ /** Resolve a placed spawn directory on this manager's host. The manager serves any existing
3797
+ * absolute directory it can resolve. It creates nothing and never substitutes the workspace root. */
3798
+ resolveSpawnCwd(value) {
3799
+ const asked = typeof value === "string" ? value : String(value ?? "");
3800
+ const refuse = (reason) => {
3801
+ throw new EpEnvelopeError("failed-precondition", `cwd does not resolve on this host: ${JSON.stringify(asked)} (${reason})`);
3802
+ };
3803
+ if (!isAbsolute(asked))
3804
+ refuse("expected an absolute path");
3805
+ const result = this.checkSpawnCwd(asked);
3806
+ if ("refusal" in result)
3807
+ return refuse(result.refusal);
3808
+ return result;
3809
+ }
3712
3810
  /** Resolve a connector by agent type. Library composition (installedExtensions off) → a registry
3713
3811
  * hit, exactly as before (the composition root imported what it wants). The published binary gates
3714
3812
  * on MANIFEST membership FIRST — so a live `cotal ext remove` is honored even though the registry
@@ -4060,6 +4158,20 @@ export class Manager {
4060
4158
  if (this.userMode)
4061
4159
  return { ok: false, error: "supervise is a restart policy this host cannot enforce: a user-mode seat has no static slot to keep the incarnation owned across a process death" };
4062
4160
  }
4161
+ // A placed spawn's cwd is checked on this host BEFORE anything is minted or reserved: an absolute
4162
+ // path this manager cannot realpath, or one that is not a directory, is refused here with the
4163
+ // asked path, the reason and this host, so a misplaced spawn in a multi-manager space is
4164
+ // diagnosable at the moment it happens (#385 item 2) instead of failing inside the pty launch.
4165
+ // The resolved realpath is threaded to the launch cwd below (`resolvedCwd`) so it is computed once.
4166
+ let resolvedCwd;
4167
+ if (typeof opts.cwd === "string" && opts.cwd !== "") {
4168
+ const asked = opts.cwd;
4169
+ const target = resolve(this.workspaceRoot, asked);
4170
+ const checked = this.checkSpawnCwd(target);
4171
+ if ("refusal" in checked)
4172
+ return { ok: false, error: `spawn: cwd does not resolve on this host (${hostname()}): ${JSON.stringify(asked)} (${checked.refusal}); the seat was not launched` };
4173
+ resolvedCwd = checked.cwd;
4174
+ }
4063
4175
  // Resolve the launch profile: IDENTITY (free-form `name:`) + role + read/post ACL + capabilities
4064
4176
  // + model/variant. Either from a fully-resolved manifest launch object (`opts.resolved`, whose `config`
4065
4177
  // is a materialized transient persona — the file is NOT the access authority), or from the
@@ -4411,7 +4523,9 @@ export class Manager {
4411
4523
  // Per-agent cwd overrides the manager's shared workspace root, so agents can be rooted at
4412
4524
  // arbitrary folders/repos. A relative path resolves against the workspace root; omitted → the
4413
4525
  // agent shares the workspace root (the prior, unchanged behavior).
4414
- const cwd = opts.cwd ? resolve(this.workspaceRoot, opts.cwd) : this.workspaceRoot;
4526
+ // The realpath the admission check above already resolved (#385 item 2) — never re-resolved here,
4527
+ // so the admission refusal and the launch cwd can never disagree on the same request.
4528
+ const cwd = resolvedCwd ?? this.workspaceRoot;
4415
4529
  const configSha256 = this.fileDigest(configPath);
4416
4530
  const manifestPath = opts.launchRef
4417
4531
  ? join(this.workspaceRoot, ".cotal", "run", `${opts.launchRef.runId}.json`)
@@ -5571,6 +5685,104 @@ export class Manager {
5571
5685
  }
5572
5686
  console.error(`✓ boot self-heal: ${MANAGER_ENDPOINT}/${instanceId} registration gate reopened at generation ${report.reopenedAtGeneration} (processEpoch ${report.after.processEpoch}, registrationRevision ${report.after.registrationRevision}; freeze-holder gone, sweepComplete=true). Continuing the normal takeover.`);
5573
5687
  }
5688
+ /** #2073: dial the manager's ONE control-plane connection and serve its typed command surface on
5689
+ * it, exactly the shape `registerManagerService` used inline before this lane. Shared by the
5690
+ * initial registration AND the closed-connection recovery path ({@link onServeConnectionClosed}),
5691
+ * so there is one place that dials and serves this endpoint. Attaches {@link
5692
+ * onServeConnectionClosed} as the close handler in both cases: a closed serve connection is
5693
+ * always a fault this manager acts on, never a bare log line. */
5694
+ async dialServeConnection(state) {
5695
+ const enc = new TextEncoder();
5696
+ const nc = await this.dial({
5697
+ // Open mesh: a bare serve connection (no credential exists; the broker enforces nothing).
5698
+ ...(state.creds !== undefined ? { authenticator: (nonce) => credsAuthenticator(enc.encode(state.creds))(nonce) } : {}),
5699
+ inboxPrefix: `_INBOX_${state.identity.id}`,
5700
+ maxReconnectAttempts: -1,
5701
+ });
5702
+ nc.closed().then((err) => { void this.onServeConnectionClosed(err ?? undefined); });
5703
+ let handle;
5704
+ try {
5705
+ // The 1b typed surface + the derived `describe`. The descriptor stays PUBLIC in static
5706
+ // mode: the broker grant (who holds each command's request-publish row) is the
5707
+ // load-bearing authority tier, and a static single-operator mesh leaks nothing by listing
5708
+ // command names; the trusted per-caller `view(caller)` scoping joins the user-mode
5709
+ // registration follow-up (where actorScope is the trusted source). Every ordinary handler
5710
+ // runs the SHARED admission chokepoint ({@link serveGated}).
5711
+ handle = serveEndpoint(nc, this.space, state.grant, this.managerServiceDefs(), { public: true }, {
5712
+ // The FRESH target resolver (§13.3) for the targeted commands (`despawn`/`attach`): the
5713
+ // manager's live managed set IS the current-mapping authority for its own agents (the
5714
+ // durable slot rows mirror it). Static mode carries no mapping-revision dimension, so
5715
+ // the revision is the constant 0 — a caller that pins a revision pins 0.
5716
+ resolveTarget: (t) => {
5717
+ if (t.owner === DEV_OWNER) {
5718
+ for (const a of this.agents.values())
5719
+ if (!a.userOwner && a.id === t.actor)
5720
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
5721
+ return undefined;
5722
+ }
5723
+ const key = principalKey(t.owner, t.actor).key;
5724
+ for (const a of this.agents.values())
5725
+ if (a.userOwner && a.id === key)
5726
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
5727
+ return undefined;
5728
+ },
5729
+ ...(this.omitClassCommands() ? { omitClassCommands: this.omitClassCommands() } : {}),
5730
+ });
5731
+ }
5732
+ catch (e) {
5733
+ await nc.drain().catch(() => nc.close());
5734
+ throw e;
5735
+ }
5736
+ return { nc, handle };
5737
+ }
5738
+ /** #2073: re-mint the SAME `endpoint-serve` identity through the SAME scoped one-shot executor and
5739
+ * §13.1 mint fence `renewDaemonCreds`'s serve branch uses — never a second copy of that mint. Used
5740
+ * by both the periodic renewal pass and the closed-connection recovery path below, so a
5741
+ * superseded instance's re-mint fails the SAME gate CAS in both places and lands in the exit
5742
+ * path rather than needing a second epoch check. */
5743
+ async remintServeCreds(s) {
5744
+ const authRef = this.auth;
5745
+ return this.withEndpointServeExecutor(({ authKv }) => mintCreds(authRef, s.identity, "endpoint-serve", {
5746
+ serveIssuance: serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId }),
5747
+ endpointServe: s.grant,
5748
+ }));
5749
+ }
5750
+ /** #2073: a closed serve connection is a FAULT the manager acts on, not a log line: this is the
5751
+ * control plane a report showed staying dead for hours while the process kept its liveness
5752
+ * lease and answered nothing (#2073). `stop()` sets `leaseStopping` BEFORE it tears down this
5753
+ * connection, so a close landing from OUR OWN graceful teardown returns here at once. Any other
5754
+ * close re-dials with the current credential (a transport blip needs nothing new), re-mints
5755
+ * through the existing serve branch when the credential itself has expired, and re-serves on the
5756
+ * new connection — bounded by {@link STATIC_RECONCILE_RETRY_DELAYS_MS}. Exhausting every attempt
5757
+ * releases this process's lease and exits loud (without `withAgents`, so seats stay up, the path
5758
+ * `supervise`'s signal handler already uses) so a restart can serve: a manager that holds the
5759
+ * lease and answers nothing is the worst of the three states this issue named, and holding the
5760
+ * connection open under unbounded reconnects (the transport-drop case) never reaches this method
5761
+ * at all — `nc.closed()` does not resolve until the client itself gives up. */
5762
+ async onServeConnectionClosed(err) {
5763
+ if (this.leaseStopping)
5764
+ return;
5765
+ const s = this.serviceServe;
5766
+ console.error(`! manager service endpoint connection closed: ${err?.message ?? "unknown reason"}`);
5767
+ const recovered = await this.boundedReconnect("service endpoint", async () => {
5768
+ if (!s)
5769
+ return false;
5770
+ if (inspectCredHealth(s.creds ?? "").state !== "healthy" && s.creds !== undefined) {
5771
+ s.creds = await this.remintServeCreds(s);
5772
+ this.scheduleServeRenewal(s.creds);
5773
+ }
5774
+ const { nc, handle } = await this.dialServeConnection(s);
5775
+ s.nc = nc;
5776
+ s.handle = handle;
5777
+ console.error(`manager service endpoint re-dialed: ${MANAGER_ENDPOINT}/${this.managerInstanceId} (epoch ${s.grant.epoch})`);
5778
+ return true;
5779
+ });
5780
+ if (this.leaseStopping || recovered)
5781
+ return;
5782
+ console.error(`! manager service endpoint could not be restored for ${this.space}/${MANAGER_ENDPOINT}/${this.managerInstanceId}: releasing the lease and exiting`);
5783
+ await this.stop();
5784
+ process.exit(1);
5785
+ }
5574
5786
  /** P2 item 1: register the manager as an ordinary v0.4 `service` endpoint and serve its typed
5575
5787
  * command surface on the ep rails - since 1d the manager's ONLY control door. On an AUTH mesh
5576
5788
  * the whole credential path is the SAME one an ordinary endpoint traverses (the enforcement
@@ -5820,50 +6032,16 @@ export class Manager {
5820
6032
  // without re-registration. Reconnects stay unbounded: the serve rails are this instance's
5821
6033
  // registered surface for its whole incarnation.
5822
6034
  const state = { handle: undefined, nc: undefined, identity: serveIdentity, grant, creds };
5823
- const enc = new TextEncoder();
5824
- const nc = await this.dial({
5825
- // Open mesh: a bare serve connection (no credential exists; the broker enforces nothing).
5826
- ...(creds !== undefined ? { authenticator: (nonce) => credsAuthenticator(enc.encode(state.creds))(nonce) } : {}),
5827
- inboxPrefix: `_INBOX_${serveIdentity.id}`,
5828
- maxReconnectAttempts: -1,
5829
- });
5830
- nc.closed().then((err) => { if (err)
5831
- console.error(`! manager service endpoint connection closed: ${err.message}`); });
5832
- try {
5833
- // The 1b typed surface + the derived `describe`. The descriptor stays PUBLIC in static
5834
- // mode: the broker grant (who holds each command's request-publish row) is the
5835
- // load-bearing authority tier, and a static single-operator mesh leaks nothing by listing
5836
- // command names; the trusted per-caller `view(caller)` scoping joins the user-mode
5837
- // registration follow-up (where actorScope is the trusted source). Every ordinary handler
5838
- // runs the SHARED admission chokepoint ({@link serveGated}).
5839
- state.handle = serveEndpoint(nc, this.space, grant, this.managerServiceDefs(), { public: true }, {
5840
- // The FRESH target resolver (§13.3) for the targeted commands (`despawn`/`attach`): the
5841
- // manager's live managed set IS the current-mapping authority for its own agents (the
5842
- // durable slot rows mirror it). Static mode carries no mapping-revision dimension, so
5843
- // the revision is the constant 0 — a caller that pins a revision pins 0.
5844
- resolveTarget: (t) => {
5845
- if (t.owner === DEV_OWNER) {
5846
- for (const a of this.agents.values())
5847
- if (!a.userOwner && a.id === t.actor)
5848
- return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
5849
- return undefined;
5850
- }
5851
- const key = principalKey(t.owner, t.actor).key;
5852
- for (const a of this.agents.values())
5853
- if (a.userOwner && a.id === key)
5854
- return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
5855
- return undefined;
5856
- },
5857
- ...(this.omitClassCommands() ? { omitClassCommands: this.omitClassCommands() } : {}),
5858
- });
5859
- }
5860
- catch (e) {
5861
- await nc.drain().catch(() => nc.close());
5862
- throw e;
5863
- }
6035
+ const { nc, handle } = await this.dialServeConnection(state);
5864
6036
  state.nc = nc;
6037
+ state.handle = handle;
5865
6038
  this.serviceServe = state;
5866
6039
  console.error(`manager service endpoint registered: ${MANAGER_ENDPOINT}/${iid} (epoch ${grant.epoch}, registrationRevision ${grant.registrationRevision})`);
6040
+ // #2073: arm the serve credential's own renewal now, from ITS window, instead of leaving it to
6041
+ // `credRenewTimer`'s boot-phased TTL/4 tick. Open mesh mints no credential (`creds` is
6042
+ // undefined) and has nothing to schedule.
6043
+ if (state.creds !== undefined)
6044
+ this.scheduleServeRenewal(state.creds);
5867
6045
  }
5868
6046
  /** P2 item 2 must-5 (b): mint the standing `goal-writer` credential and STAGE it into this
5869
6047
  * instance's §13.1 revocation family (`epcred.<e>.<iid>`), over the passed executor's `authKv`
@@ -5911,19 +6089,18 @@ export class Manager {
5911
6089
  * renewal is adopted without reconnecting the whole endpoint); the ActionContext bonds its
5912
6090
  * KV + JS + JSM to this one connection and space (SPEC 13.4), so a composition mixup cannot splice
5913
6091
  * goal state across brokers. */
5914
- async startGoalWriter() {
5915
- const identity = (this.auth || this.remoteAuthority) ? this.goalWriterIdentity : newIdentity();
6092
+ /** #2073: dial the goal-writer's ONE standing connection and rebuild everything derived from it
6093
+ * (the fence-resolving action context, the issuance-gate reader) — shared by the initial start
6094
+ * and the closed-connection recovery ({@link onGoalWriterConnectionClosed}), so a redial never
6095
+ * leaves the context bound to a dead socket. */
6096
+ async dialGoalWriter(gw) {
5916
6097
  const enc = new TextEncoder();
5917
- // The mutable holder captured by the authenticator (mirrors the serve connection): a half-TTL
5918
- // renewal updates `gw.creds` and the next (re)connect presents the refreshed credential.
5919
- const gw = { nc: undefined, ctx: undefined, creds: (this.auth || this.remoteAuthority) ? this.goalWriterCreds : undefined, identity };
5920
6098
  const nc = await this.dial({
5921
6099
  ...((this.auth || this.remoteAuthority) ? { authenticator: (nonce) => credsAuthenticator(enc.encode(gw.creds))(nonce) } : {}),
5922
- inboxPrefix: `_INBOX_${identity.id}`,
6100
+ inboxPrefix: `_INBOX_${gw.identity.id}`,
5923
6101
  maxReconnectAttempts: -1,
5924
6102
  });
5925
- nc.closed().then((err) => { if (err)
5926
- console.error(`! manager goal-writer connection closed: ${err.message}`); });
6103
+ nc.closed().then((err) => { void this.onGoalWriterConnectionClosed(err ?? undefined); });
5927
6104
  gw.nc = nc;
5928
6105
  // The (i) fence resolver (SPEC 13.6 P2 item 3): resolve an executing instance's CURRENT gate
5929
6106
  // epoch. This manager reconciles only ITS OWN goals (security pin 4), so it resolves its own
@@ -5949,6 +6126,40 @@ export class Manager {
5949
6126
  // rather than closing it. An AUTH mesh gets durable closure from the §13.1 barrier (revoke +
5950
6127
  // cluster-verified eviction BEFORE the epoch advance); an open mesh gets none.
5951
6128
  gw.gate = serveIssuanceGateKv(await new Kvm(nc).open(epAuthBucket(this.space)), this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId });
6129
+ }
6130
+ /** #2073: the goal-writer rail's closed-connection fault, the same bounded shape the serve rail
6131
+ * uses ({@link onServeConnectionClosed}) through the same {@link boundedReconnect} helper:
6132
+ * re-dial with the current credential (a transport blip needs nothing new), re-mint through the
6133
+ * existing goal-writer renewal branch when the credential itself has expired, then re-attach.
6134
+ * Unlike the serve rail this never exits the process on exhaustion (brief step 4: only the serve
6135
+ * rail is the control plane the report lost) — it logs and leaves the credential to the next
6136
+ * scheduled renewal pass. */
6137
+ async onGoalWriterConnectionClosed(err) {
6138
+ if (this.leaseStopping)
6139
+ return;
6140
+ console.error(`! manager goal-writer connection closed: ${err?.message ?? "unknown reason"}`);
6141
+ const gw = this.goalWriter;
6142
+ const recovered = await this.boundedReconnect("goal-writer", async () => {
6143
+ if (!gw)
6144
+ return false;
6145
+ if (gw.creds !== undefined && inspectCredHealth(gw.creds).state !== "healthy") {
6146
+ gw.creds = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageGoalWriter(authKv));
6147
+ this.goalWriterCreds = gw.creds;
6148
+ }
6149
+ await this.dialGoalWriter(gw);
6150
+ console.error("manager goal-writer re-dialed");
6151
+ return true;
6152
+ });
6153
+ if (this.leaseStopping || recovered)
6154
+ return;
6155
+ console.error("! manager goal-writer could not be re-dialed; leaving the credential to the next renewal pass");
6156
+ }
6157
+ async startGoalWriter() {
6158
+ const identity = (this.auth || this.remoteAuthority) ? this.goalWriterIdentity : newIdentity();
6159
+ // The mutable holder captured by the authenticator (mirrors the serve connection): a half-TTL
6160
+ // renewal updates `gw.creds` and the next (re)connect presents the refreshed credential.
6161
+ const gw = { nc: undefined, ctx: undefined, creds: (this.auth || this.remoteAuthority) ? this.goalWriterCreds : undefined, identity };
6162
+ await this.dialGoalWriter(gw);
5952
6163
  this.goalWriter = gw;
5953
6164
  console.error(`manager goal-writer standing (endpoint ${MANAGER_ENDPOINT}, ${(this.auth || this.remoteAuthority) ? "scoped cred, §13.1 family-staged" : "open/bare"})`);
5954
6165
  }
@@ -6016,20 +6227,55 @@ export class Manager {
6016
6227
  * holder never verifies the signature (it presents the grant back over the rail; the broker's
6017
6228
  * per-session caller cred is the holder's real fence). The plane's ledger lives in the DEDICATED
6018
6229
  * sessions bucket (createEndpointStreams provisioned it at registration). */
6019
- async startSessionPlane() {
6020
- const identity = (this.auth || this.remoteAuthority) ? this.sessionLedgerIdentity : newIdentity();
6230
+ /** #2073: dial the session-ledger's ONE standing connection — shared by the initial start and the
6231
+ * closed-connection recovery ({@link onSessionLedgerConnectionClosed}), the same shape {@link
6232
+ * dialGoalWriter} uses for its rail. The KV/JetStream clients the session plane opened from the
6233
+ * connection at start stay bound to it for this incarnation's life; a redial refreshes the
6234
+ * standing authenticator connection the credential renewal presents onto (mirroring `sw.creds`),
6235
+ * which is what a closed-connection fault on this rail needs restored. */
6236
+ async dialSessionLedgerConnection(sw, identity) {
6021
6237
  const enc = new TextEncoder();
6022
- // The mutable holder captured by the authenticator (mirrors the goal-writer): a half-TTL renewal
6023
- // updates `sw.creds` and the next (re)connect presents the refreshed credential.
6024
- const sw = { nc: undefined, creds: (this.auth || this.remoteAuthority) ? this.sessionLedgerCreds : undefined };
6025
6238
  const nc = await this.dial({
6026
6239
  ...((this.auth || this.remoteAuthority) ? { authenticator: (nonce) => credsAuthenticator(enc.encode(sw.creds))(nonce) } : {}),
6027
6240
  inboxPrefix: `_INBOX_${identity.id}`,
6028
6241
  maxReconnectAttempts: -1,
6029
6242
  });
6030
- nc.closed().then((err) => { if (err)
6031
- console.error(`! manager session-ledger connection closed: ${err.message}`); });
6243
+ nc.closed().then((err) => { void this.onSessionLedgerConnectionClosed(err ?? undefined); });
6032
6244
  sw.nc = nc;
6245
+ }
6246
+ /** #2073: the session-ledger rail's closed-connection fault, the same bounded shape {@link
6247
+ * onGoalWriterConnectionClosed} uses: re-dial with the current credential, re-mint through the
6248
+ * existing session-ledger renewal branch when the credential itself has expired, then re-attach.
6249
+ * Exhaustion logs and leaves the credential to the next renewal pass; it never exits the process
6250
+ * (brief step 4: only the serve rail is the control plane the report lost). */
6251
+ async onSessionLedgerConnectionClosed(err) {
6252
+ if (this.leaseStopping)
6253
+ return;
6254
+ console.error(`! manager session-ledger connection closed: ${err?.message ?? "unknown reason"}`);
6255
+ const sw = this.sessionLedgerConn;
6256
+ const identity = this.sessionLedgerIdentity;
6257
+ const recovered = await this.boundedReconnect("session-ledger", async () => {
6258
+ if (!sw || !identity)
6259
+ return false;
6260
+ if (sw.creds !== undefined && inspectCredHealth(sw.creds).state !== "healthy") {
6261
+ sw.creds = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageSessionLedger(authKv));
6262
+ this.sessionLedgerCreds = sw.creds;
6263
+ }
6264
+ await this.dialSessionLedgerConnection(sw, identity);
6265
+ console.error("manager session-ledger re-dialed");
6266
+ return true;
6267
+ });
6268
+ if (this.leaseStopping || recovered)
6269
+ return;
6270
+ console.error("! manager session-ledger could not be re-dialed; leaving the credential to the next renewal pass");
6271
+ }
6272
+ async startSessionPlane() {
6273
+ const identity = (this.auth || this.remoteAuthority) ? this.sessionLedgerIdentity : newIdentity();
6274
+ // The mutable holder captured by the authenticator (mirrors the goal-writer): a half-TTL renewal
6275
+ // updates `sw.creds` and the next (re)connect presents the refreshed credential.
6276
+ const sw = { nc: undefined, creds: (this.auth || this.remoteAuthority) ? this.sessionLedgerCreds : undefined };
6277
+ await this.dialSessionLedgerConnection(sw, identity);
6278
+ const nc = sw.nc;
6033
6279
  const serveEpoch = this.serviceServe?.grant.epoch;
6034
6280
  if (serveEpoch === undefined)
6035
6281
  throw new Error("the manager session plane needs the serve grant epoch; registerManagerService must run first");
@@ -7262,10 +7508,13 @@ export class Manager {
7262
7508
  managerInstance: this.managerInstanceId, managerProcessUid: this.managerLifecycleUid,
7263
7509
  }, { cleanup: reapThenCleanup, evict, log: (line) => console.error(`static retirement ${a.name}: ${line}`) });
7264
7510
  });
7265
- this.retiredPrincipals.add(principalKey(DEV_OWNER, a.id).key);
7511
+ const principal = principalKey(DEV_OWNER, a.id).key;
7512
+ this.retiredPrincipals.add(principal);
7266
7513
  const cur = this.retiring.get(a.name);
7267
- if (cur && cur.lifecycleUid === a.lifecycleUid)
7514
+ if (cur && cur.lifecycleUid === a.lifecycleUid) {
7268
7515
  this.retiring.delete(a.name); // ABA-guarded hold clear
7516
+ this.confirmedRetiredPredecessors.set(a.name, { principal, lifecycleUid: a.lifecycleUid });
7517
+ }
7269
7518
  }
7270
7519
  catch (e) {
7271
7520
  const h = this.retiring.get(a.name);