@cotal-ai/manager 0.167.0 → 0.168.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -7,15 +7,20 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSy
7
7
  import { isAbsolute, join, resolve, sep } from "node:path";
8
8
  import { parse as parseYaml } from "yaml";
9
9
  import Headless from "@xterm/headless";
10
- import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, MANAGED_HANDOFF_KIND, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, MANAGER_LEASE_TTL_MS, awaitLeaseExpiry, leaseRemainingMs, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, assertValidChannel, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, DeprovisionError, addDeprovisionAccounting, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, firstFreeName, spawnNameError, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, provisionAgentDurables, registry, resolveAuthProvider, resolveReadAcl, runAgentBearer, runDriverCaller, saveAgentFile, eventChannel, eventChannelPrincipal, digestIdToken, capabilityWithin, grantOverreach, grantParts, isIssuedCaller, issuedSpawnerStanding, withIssuerSession, renderOnceTask, shownSpawner, } from "@cotal-ai/core";
10
+ import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, MANAGED_HANDOFF_KIND, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, assertValidChannel, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, provisionAgentDurables, registry, resolveAuthProvider, resolveReadAcl, runAgentBearer, runDriverCaller, saveAgentFile, eventChannel, eventChannelPrincipal, digestIdToken, capabilityWithin, grantOverreach, grantParts, isIssuedCaller, issuedSpawnerStanding, withIssuerSession, renderOnceTask, shownSpawner, } from "@cotal-ai/core";
11
11
  import { loadLaunchPersonaFile, PersonaSourceError, retainConnectorSeat } from "@cotal-ai/workspace";
12
- import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, probeLiveness, remintDaemonCreds, resolveAgentType, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, SEAT_CAP_UNLIMITED, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
12
+ import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds, resolveAgentType, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, SEAT_CAP_UNLIMITED, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
13
13
  import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
14
14
  import { Retirement } from "./retirement.js";
15
15
  import { ServePlane } from "./serve-plane.js";
16
+ import { NamesCapacity } from "./names-capacity.js";
16
17
  import { AttachEndpoint } from "./attach-endpoint.js";
17
- import { DELIVERY_ADMIN_BOOT_WAIT_MS, isUnansweredDeliveryAdmin, makeManagerEndpointEvictionEvidence, makeManagerEndpointHolderEvictor, untilDeliveryAdminAnswers, withScopedEndpoint } from "./endpoint-evict.js";
18
+ import { DELIVERY_ADMIN_BOOT_WAIT_MS, isUnansweredDeliveryAdmin, makeManagerEndpointHolderEvictor, untilDeliveryAdminAnswers, withScopedEndpoint } from "./endpoint-evict.js";
18
19
  import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
20
+ import { ManagedStaticLifecycle, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
21
+ export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
22
+ import { LeaseKeeper } from "./lease-keeper.js";
23
+ export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
19
24
  import { SessionRecovery } from "./session-recovery.js";
20
25
  import { SeatCustody } from "./seat-custody.js";
21
26
  import { withTimeout } from "./manager-timeout.js";
@@ -33,7 +38,7 @@ import { TranscriptReceiver } from "./transcript-receive.js";
33
38
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
34
39
  import { jetstream, jetstreamManager } from "@nats-io/jetstream";
35
40
  import { Kvm } from "@nats-io/kv";
36
- import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, issuedHorizon, REMOTE_MANAGER_IDENTITY_NAMES } from "@cotal-ai/core";
41
+ import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, REMOTE_MANAGER_IDENTITY_NAMES } from "@cotal-ai/core";
37
42
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
38
43
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
39
44
  // per-session credentials on their own short-lived connections).
@@ -41,17 +46,13 @@ import { ManagerSessionPlane } from "./session/index.js";
41
46
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
42
47
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
43
48
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
44
- import { provisionEndpointGateOpen, serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, requestGoalCancel, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, mintCheckpoint, MAX_SCHEDULE_MS, resumeCheckpoint, readCheckpointSettle, readCheckpointSpec, expireCheckpoint, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, seatCapRefused, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
49
+ import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, requestGoalCancel, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, mintCheckpoint, MAX_SCHEDULE_MS, resumeCheckpoint, readCheckpointSettle, readCheckpointSpec, expireCheckpoint, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, seatCapRefused, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
45
50
  import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
46
51
  import { measureManagerVitals } from "./vitals.js";
47
- import { staticLifecycleTransport, activateStaticLifecycle, runStaticTerminal, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, planStaticSlotResume, ownedBySibling, observeStaticSlot, listStaticSlotObservations, walkStaticSlots, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
48
- import { CHAT_ALIAS_PREFIX, CHAT_EXPIRY_CONCURRENCY, ChatSessionExpiry, chatOpenLists, chatRetireRefusal, drawChatAlias, isChatAlias, readChatOpenInput, readChatRetireInput, sealChatAdmission, } from "./chat-session.js";
52
+ import { staticLifecycleTransport, activateStaticLifecycle, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
53
+ import { CHAT_ALIAS_PREFIX, } from "./chat-session.js";
49
54
  // Capture the loaded package version before an installation can replace its files.
50
55
  const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
51
- /** Minimum slot lifetime for rate-flooring (P4c). A slot freed (by despawn OR natural exit/reap)
52
- * before living this long leaves a cooling stamp that still counts toward the ceiling until it
53
- * expires — so churn (spawn↔despawn or spawn↔fast-exit) can't outrun the concurrency bound. */
54
- const MIN_LIFETIME = 10_000;
55
56
  /** Cadence of the turn-deadline sweep while turns are pending: the poll that turns an elapsed
56
57
  * hold's fire into its expired settle and commits the deadline terminal. Deadlines are
57
58
  * minutes-scale; a few seconds of lateness on the commit is invisible to the run. */
@@ -102,16 +103,6 @@ const OPERATOR_READINESS_MS = 3_000;
102
103
  * `.catch`. Generous over the helper's 5s connect timeout to allow the two consumer-deletes + ACL purge
103
104
  * + drain on a healthy-but-slow broker. */
104
105
  const DEPROVISION_TIMEOUT_MS = 15_000;
105
- /** How long a clean stop keeps trying to release its liveness lease when the broker does not answer
106
- * (#3916). The client redials a lost broker every 2 s, so a connection dropped by an outage of up to
107
- * about 3 s is back inside this budget. A longer outage is left to the row's TTL: the stop's other
108
- * steps also wait on the broker, and the whole stop must still finish inside the 15 s a CLI stop
109
- * waits before it sends SIGKILL. */
110
- const LEASE_RELEASE_BUDGET_MS = 5_000;
111
- /** The pause between lease release attempts that got no answer. An attempt that waits for its own
112
- * deadline already spaces the retries; this only keeps one that fails at once, on a closed
113
- * connection, from spinning. */
114
- const LEASE_RELEASE_RETRY_MS = 250;
115
106
  /** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
116
107
  * connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
117
108
  * each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
@@ -173,13 +164,7 @@ export function credRenewIntervalMs(ttlSeconds) {
173
164
  * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
174
165
  * a reuse. */
175
166
  const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
176
- /** One initial terminal entry plus three re-drives. The short first retry absorbs a one-shot
177
- * broker/eviction blip; the wider later spacing avoids hammering a persistently unavailable
178
- * authority. The finite ~36s window is intentionally not a liveness inference: exhausting it
179
- * leaves the durable alias held and requires a later manager start. */
180
- export const STATIC_RECONCILE_RETRY_DELAYS_MS = [1_000, 5_000, 30_000];
181
167
  const REMOTE_STANDING_BUDGET_MS = 10_000;
182
- const STATIC_RECONCILE_MAX_ATTEMPTS = STATIC_RECONCILE_RETRY_DELAYS_MS.length + 1;
183
168
  /** The owner a retained seat resumes under: its inventory identity's, which is the same value the
184
169
  * adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
185
170
  * it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
@@ -286,25 +271,6 @@ function ownPersona(record) {
286
271
  });
287
272
  return owned;
288
273
  }
289
- /** `start()`'s refusal when this manager instance's lease is held (#3915): by another live process
290
- * on this workspace root, or by a holder on another root. A restart whose predecessor on this root
291
- * is dead, this process's own earlier start included, waits the key out instead (#4092). The
292
- * message is the operator copy; `held` and `sameRoot` are the data, so no caller parses it. A
293
- * lease that could not be read or written is a plain `Error`. */
294
- export class ManagerInstanceLeaseHeld extends Error {
295
- instanceId;
296
- space;
297
- held;
298
- sameRoot;
299
- name = "ManagerInstanceLeaseHeld";
300
- constructor(message, instanceId, space, held, sameRoot) {
301
- super(message);
302
- this.instanceId = instanceId;
303
- this.space = space;
304
- this.held = held;
305
- this.sameRoot = sameRoot;
306
- }
307
- }
308
274
  /** Operator-facing phrasing per cause. Kept beside the union so adding a member without a sentence
309
275
  * is a type error rather than a blank in the log. The stop family's sentences carry the principal
310
276
  * from the cause, so they render through {@link STOP_CAUSE_TEXT} under the same exhaustive-Record
@@ -322,23 +288,6 @@ const FREE_SLOT_CAUSE_TEXT = {
322
288
  "supervise-record-failed": "this manager stopped it: its supervise policy could not be recorded for a manager restart",
323
289
  "inline-snapshot-changed": "this manager retired it instead of restarting it: its inline persona snapshot changed after launch",
324
290
  };
325
- /** The SPEC 13.6 end reason a live attach session gets when this cause frees its seat. The causes
326
- * that free the slot in the same step that saw the seat's own process exit report `process-exit`.
327
- * A failed recovery frees it later, after its own stop, so it reports `target-despawn` with every
328
- * manager stop. */
329
- const FREE_SLOT_ATTACH_END = {
330
- "process-exit": "process-exit",
331
- "pi-crash-loop": "process-exit",
332
- "supervise-crash-loop": "process-exit",
333
- "inline-snapshot-changed": "process-exit",
334
- "pi-recovery-failed": "target-despawn",
335
- "supervise-recovery-failed": "target-despawn",
336
- "session-bind-failed": "target-despawn",
337
- "resume-session-rebind-failed": "target-despawn",
338
- "carried-fork-refused": "target-despawn",
339
- "resume-custody-unrecorded": "target-despawn",
340
- "supervise-record-failed": "target-despawn",
341
- };
342
291
  /** The stop family's sentences — the same job {@link FREE_SLOT_CAUSE_TEXT} does for the string
343
292
  * causes, beside it so both stay the single place a cause becomes a sentence. A requested stop's
344
293
  * sentence embeds the authenticated principal and a recursive reap's embeds the parent that
@@ -594,28 +543,9 @@ export class Manager {
594
543
  preserveStopTimeoutMs;
595
544
  endpointServeExecutorExpiresInSeconds;
596
545
  agents = new Map();
597
- /** Names whose spawn is in flight (reserved synchronously before the provision await) — counted
598
- * toward the ceiling (once per name, see {@link Manager.occupancy}) so two concurrent same-name
599
- * spawns can't both pass the gate (P4a). Each name carries the OWNER its launch was admitted
600
- * for, so the per-owner ceiling ({@link Manager.ownerSeats}) counts a launch from the moment it
601
- * is reserved; a cap read only off `agents` would let a burst of concurrent spawns overshoot it,
602
- * because none of them has a seat yet when the next one checks. */
603
- reserved = new Map();
604
- /** Reserved names whose launch already put its seat in `agents`. The name stays reserved until
605
- * the launch settles, so no other spawn can take it, but the ceiling counts that seat through
606
- * `agents` and, if it frees young, its cooling stamp, never through the reservation (#906). */
607
- reservedLive = new Set();
608
- /** Every numbered name {@link uniqueName} has issued. A suffix carries nothing but arrival order,
609
- * so reissuing a freed one would give a later principal the name an earlier one posted under, and
610
- * a reader of that name could not tell the two apart (#382). Never pruned in-process: one string
611
- * per numbered spawn. */
612
- issuedNumberedNames = new Set();
613
546
  /** Lifecycle UIDs already handed to `Runtime.spawnDelegated`: a lifecycle is handed off at most
614
547
  * once, so a lost create acknowledgement can never become a second create. */
615
548
  delegatedLaunched = new Set();
616
- /** Expiry stamps (`startedAt + MIN_LIFETIME`) for slots that freed while still young — a
617
- * count-only, lazily-pruned recycle floor (P4c). Pruned + summed into the ceiling gate. */
618
- cooling = [];
619
549
  /** This manager process's own incarnation uid (SPEC 13.1; minted once per supervisor process,
620
550
  * never reused across restarts) — the endpoint's presence key AND the `managerInstance` audit
621
551
  * coordinate every static activation records. */
@@ -757,26 +687,6 @@ export class Manager {
757
687
  connectorStatuses = [];
758
688
  /** The boot inventory's warnings, printed once start completes, so a refused start prints none. */
759
689
  bootNotes = [];
760
- /** Static aliases whose startup exact-op terminal is still in flight. Scoped per alias: control
761
- * serves during the sweep, but no caller can reuse or attach an alias the sweep still owns. */
762
- reconcilingAliases = new Set();
763
- /** In-flight static chat-session terminals, by lifecycle UID, so every caller that retires one
764
- * session joins one terminal instead of racing its CAS sequence. */
765
- chatRetirements = new Map();
766
- /** The expiry side of every chat session this process admitted and nothing retired sooner. */
767
- chatExpiry = new ChatSessionExpiry((session) => this.expireStaticChatSession(session), {
768
- retryDelaysMs: STATIC_RECONCILE_RETRY_DELAYS_MS,
769
- concurrency: CHAT_EXPIRY_CONCURRENCY,
770
- log: (line) => console.error(line),
771
- });
772
- /** Current failed/recovered static reconciliation coordinates. This is an operator snapshot, not
773
- * lifecycle authority: every re-drive re-reads broker KV and re-runs planStaticSlotResume. */
774
- staticReconcileItems = new Map();
775
- staticReconcileLastSweep;
776
- staticReconcileLastSweepResources;
777
- staticReconcileSweepsInFlight = 0;
778
- staticReconcileDrainWaiters = [];
779
- staticReconcileStopping = false;
780
690
  /** The complete boot task. stop() joins it after fencing static reconciliation, so a registration
781
691
  * already past an earlier shutdown check cannot finish after stop() returns. */
782
692
  startTask;
@@ -805,6 +715,28 @@ export class Manager {
805
715
  /** True on a USER-AUTH space (the on-disk marker; cross-checked against the registry at start).
806
716
  * Gates the whole spawn path: user mode grants ledger actors + bearer plumbing, never static mints. */
807
717
  userMode = false;
718
+ namesCapacity = new NamesCapacity({
719
+ userMode: () => this.userMode,
720
+ authEnabled: () => this.auth !== undefined,
721
+ maintenanceActive: () => this.maintenanceState === "active",
722
+ roster: () => this.ep.getRoster(),
723
+ agentFor: (name) => this.agents.get(name),
724
+ hasAgent: (name) => this.agents.has(name),
725
+ removeAgent: (name) => { this.agents.delete(name); },
726
+ managedCount: () => this.agents.size,
727
+ predecessor: (name) => this.retirement.predecessor(name),
728
+ hasRetirementHold: (name) => this.retirement.hasHold(name),
729
+ holdRetirement: (name, hold) => this.retirement.hold(name, hold),
730
+ endSessionsForTarget: (...args) => { this.sessionPlane?.endForTarget(...args); },
731
+ logSeatReaped: (...args) => this.logSeatReaped(...args),
732
+ recordContinuityAtStop: (...args) => this.recordContinuityAtStop(...args),
733
+ releasedSeatPending: (...args) => this.releasedSeatPending(...args),
734
+ dropSeatRecord: (...args) => this.dropSeatRecord(...args),
735
+ failSeatTurns: (...args) => this.failSeatTurns(...args),
736
+ teardownTarget: (...args) => this.teardownTarget(...args),
737
+ dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
738
+ trackDeprovision: (...args) => this.trackDeprovision(...args),
739
+ });
808
740
  servePlane = new ServePlane({
809
741
  auth: () => this.auth,
810
742
  remoteAuthority: () => this.remoteAuthority,
@@ -897,19 +829,22 @@ export class Manager {
897
829
  brokerTeardown: (task, message) => withTimeout(task, DEPROVISION_TIMEOUT_MS, message),
898
830
  trackLifecycle: () => { this.lifecycleInFlight++; return () => this.releaseLifecycle(); },
899
831
  });
900
- leaseInfo;
901
- leaseRevision;
902
- leaseTimer;
903
- /** What the last renew tick learned about this instance's key. Only a CHANGE of state is printed
904
- * (see {@link noteLease}), so an outage of hours is one line going in and one line coming out. */
905
- leaseState = "held";
906
- /** A renew is in flight. The tick must not start a second one: both would read the same cached
907
- * revision, so whichever lands second CASes against a sequence the first already moved. */
908
- leaseRenewInFlight = false;
909
- /** The promise a currently in-flight `renewLease()` is running, so `stop()` can await it before
910
- * releasing the key instead of racing it: a renew that lands after the cached revision was read
911
- * for release would otherwise move the row out from under a same-cached-revision CAS delete. */
912
- leaseRenewTask;
832
+ lease = new LeaseKeeper({
833
+ endpoint: () => this.ep,
834
+ instanceId: () => this.managerInstanceId,
835
+ space: () => this.space,
836
+ stopping: () => this.leaseStopping,
837
+ });
838
+ get leaseInfo() { return this.lease.leaseInfo; }
839
+ set leaseInfo(info) { this.lease.leaseInfo = info; }
840
+ get leaseRevision() { return this.lease.leaseRevision; }
841
+ set leaseRevision(revision) { this.lease.leaseRevision = revision; }
842
+ get leaseTimer() { return this.lease.leaseTimer; }
843
+ set leaseTimer(timer) { this.lease.leaseTimer = timer; }
844
+ get leaseRenewTask() { return this.lease.leaseRenewTask; }
845
+ acquireInstanceLease(info) { return this.lease.acquireInstanceLease(info); }
846
+ renewLease() { return this.lease.renewLease(); }
847
+ releaseOwnManagerLease() { return this.lease.releaseOwnManagerLease(); }
913
848
  /** Set at the top of `stop()`. `renewLease` returns at once once this is set, and its `gone` arm
914
849
  * does not re-acquire: a manager that is stopping never puts its own key back. It also closes the
915
850
  * lifecycle fence ({@link beginLifecycle}), so no spawn can launch a seat the stop never sees. */
@@ -1041,6 +976,45 @@ export class Manager {
1041
976
  stopHandle: (agent, graceful, cause) => this.stopHandle(agent, graceful, cause),
1042
977
  trackStoppedHandle: (agent, floor, cause) => this.trackStoppedHandle(agent, floor, cause),
1043
978
  });
979
+ get staticReconcileLastSweepResources() { return this.staticLifecycle.resources(); }
980
+ set staticReconcileLastSweepResources(value) { this.staticLifecycle.setResources(value); }
981
+ staticLifecycle = new ManagedStaticLifecycle({
982
+ space: () => this.space,
983
+ servers: () => this.servers,
984
+ auth: () => this.auth,
985
+ secrets: () => this.secrets,
986
+ workspaceRoot: () => this.workspaceRoot,
987
+ instanceId: () => this.managerInstanceId,
988
+ processUid: () => this.managerLifecycleUid,
989
+ userMode: () => this.userMode,
990
+ eventPayloadsWithheld: () => this.eventPayloadsWithheld,
991
+ evictor: () => this.staticLifecycleEvict,
992
+ retryDelays: () => this.staticReconcileRetryDelaysMs,
993
+ resumeRequired: () => this.resumeRequired,
994
+ records: () => this.goalWriter?.ctx.kv,
995
+ agentFor: (name) => this.agents.get(name),
996
+ retirementFor: (name) => this.retirement.held(name),
997
+ recordStaticRetirement: (a) => this.retirement.recordStaticRetirement(a),
998
+ noteRetiredPrincipal: (principal) => { this.retirement.rememberRetired(principal); },
999
+ foreignEventChannels: (channels, owner, actor) => foreignEventChannels(channels, owner, actor),
1000
+ withIssuer: (fn) => this.withIssuer(fn),
1001
+ deprovisionBroker: (a) => this.deprovisionBroker(a),
1002
+ reapOrphanSeat: (a) => this.reapOrphanSeat(a),
1003
+ withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
1004
+ readerRemedy: (owner, channel) => this.readerRemedy(owner, channel),
1005
+ withProvisioner: (fn) => this.withProvisioner(fn),
1006
+ beginLifecycle: (resumeOperation) => this.beginLifecycle(resumeOperation),
1007
+ maintenanceError: () => this.maintenanceError(),
1008
+ withRetirementSlot: (run) => this.withRetirementSlot(run),
1009
+ managedStaticInstanceReads: (capabilities) => this.managedStaticInstanceReads(capabilities),
1010
+ issuanceSeam: (i, mode, a, exp) => this.issuanceSeam(i, mode, a, exp),
1011
+ refreshSeatRecord: (a) => this.refreshSeatRecord(a),
1012
+ dial: (opts) => this.dial(opts),
1013
+ seatRecordFor: (row) => this.seatRecordFor(row),
1014
+ restartSupervisedSeat: (row, record) => this.restartSupervisedSeat(row, record),
1015
+ adoptSeat: (row, record) => this.adoptSeat(row, record),
1016
+ dropSeatRecord: (a) => this.dropSeatRecord(a),
1017
+ });
1044
1018
  constructor(opts) {
1045
1019
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
1046
1020
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1410,7 +1384,7 @@ export class Manager {
1410
1384
  }
1411
1385
  async runStart() {
1412
1386
  await this.admitExecutionState();
1413
- this.staticReconcileStopping = false;
1387
+ this.staticLifecycle.start();
1414
1388
  await this.inspectConnectorsAtBoot();
1415
1389
  await this.attach.start();
1416
1390
  // In auth mode the manager is just another user in the space's account — it mints
@@ -1670,7 +1644,7 @@ export class Manager {
1670
1644
  // stop() fences before it waits for an accepted startup reconciliation terminal. Once that
1671
1645
  // terminal drains, start() and stop() resume from the same await boundary; start must observe
1672
1646
  // the fence before it can publish a fresh service registration after shutdown.
1673
- if (this.staticReconcileStopping)
1647
+ if (this.staticLifecycle.stopping)
1674
1648
  return;
1675
1649
  // Register the manager as an ordinary v0.4 `service` endpoint (SPEC §13.7/§13.9)
1676
1650
  // and serve its typed command surface on the ep rails - the ONLY control door, in
@@ -1680,7 +1654,7 @@ export class Manager {
1680
1654
  // trust). Fail-loud: a manager that cannot register does not start half-registered.
1681
1655
  console.error("manager startup: binding the service endpoint");
1682
1656
  await this.registerManagerService();
1683
- if (this.staticReconcileStopping)
1657
+ if (this.staticLifecycle.stopping)
1684
1658
  return;
1685
1659
  // Stand up the standing goal-writer connection for spawn-as-action — AFTER
1686
1660
  // registration (it writes this endpoint's goal facts/records), disjoint from the serve cred.
@@ -3041,54 +3015,6 @@ export class Manager {
3041
3015
  if (failures.length)
3042
3016
  throw new Error(`manager preservation shutdown incomplete: ${failures.join("; ")}`);
3043
3017
  }
3044
- /** Create THIS instance's lease key, waiting out a dead predecessor's row first (#4092).
3045
- *
3046
- * A manager SIGKILLed on this host cannot release its key, so a restart inside the key's TTL
3047
- * loses the create. When the row names this workspace root and a pid that is not running here
3048
- * (or is this process's own pid, which a live predecessor cannot hold), the holder is dead and
3049
- * the restart waits for the bucket TTL to remove the row, then creates again. It never writes
3050
- * over the row: a live holder renews it inside the TTL, and the wait then refuses on that write.
3051
- * Any other conflict refuses at once, as before. */
3052
- async acquireInstanceLease(info) {
3053
- const refuse = (held, e) => {
3054
- if (!held)
3055
- return new Error(`could not acquire the manager lease for space "${this.space}": ${rejectionText(e)}`);
3056
- const sameRoot = held.root === info.root;
3057
- return new ManagerInstanceLeaseHeld(`manager instance ${this.managerInstanceId} already serves space "${this.space}" from ${sameRoot ? "this" : "another"} workspace root (${held.runtime}, pid ${held.pid}, root ${held.root}) - stop it first before restarting the same instance`, this.managerInstanceId, this.space, held, sameRoot);
3058
- };
3059
- try {
3060
- return await this.ep.acquireManagerLease(info);
3061
- }
3062
- catch (e) {
3063
- // Our OWN instance id already holds a live key ⇒ refuse. Anything else (e.g. a KV/JS error) is a
3064
- // real failure to surface, not a silent "held" — keep the cause so it isn't misread as a conflict.
3065
- const held = await this.ep.readOwnManagerLease(this.managerInstanceId).catch(() => undefined);
3066
- if (!held || held.info.root !== info.root || (held.info.pid !== process.pid && probeLiveness(held.info.pid) !== "dead"))
3067
- throw refuse(held?.info, e);
3068
- console.error(`• manager instance ${this.managerInstanceId}: its lease is still held by pid ${held.info.pid}, which is not running on this host; ` +
3069
- `waiting ${Math.ceil(leaseRemainingMs(held.created, MANAGER_LEASE_TTL_MS) / 1000)}s for the lease to expire`);
3070
- const waited = await awaitLeaseExpiry({
3071
- read: async () => {
3072
- const row = await this.ep.readOwnManagerLease(this.managerInstanceId);
3073
- return row && { revision: row.revision, created: row.created };
3074
- },
3075
- revision: held.revision,
3076
- created: held.created,
3077
- ttlMs: MANAGER_LEASE_TTL_MS,
3078
- aborted: () => this.leaseStopping,
3079
- });
3080
- if (waited === "rewritten")
3081
- throw new Error(`manager instance ${this.managerInstanceId}: its lease was written again while waiting for pid ${held.info.pid}'s lease to expire, so a live process holds it - stop it first before restarting the same instance`);
3082
- if (waited !== "expired")
3083
- throw refuse(held.info, e);
3084
- try {
3085
- return await this.ep.acquireManagerLease(info);
3086
- }
3087
- catch (again) {
3088
- throw refuse((await this.ep.readOwnManagerLease(this.managerInstanceId).catch(() => undefined))?.info, again);
3089
- }
3090
- }
3091
- }
3092
3018
  /** Every call joins the first stop and settles with it. A call that asks for a different
3093
3019
  * `withAgents` is refused, since the running stop has already applied its own policy. */
3094
3020
  stop(options = {}) {
@@ -3103,15 +3029,8 @@ export class Manager {
3103
3029
  clearTimeout(this.credentialPushRetry);
3104
3030
  this.credentialPushRetry = undefined;
3105
3031
  this.transcripts?.stop();
3106
- this.staticReconcileStopping = true;
3107
- this.chatExpiry.stop();
3032
+ this.staticLifecycle.stop();
3108
3033
  const starting = this.startTask;
3109
- for (const item of this.staticReconcileItems.values()) {
3110
- if (item.timer)
3111
- clearTimeout(item.timer);
3112
- item.timer = undefined;
3113
- item.nextRetryAt = undefined;
3114
- }
3115
3034
  await this.awaitStaticReconcileDrain();
3116
3035
  await starting?.catch(() => { });
3117
3036
  if (this.leaseTimer)
@@ -3207,36 +3126,6 @@ export class Manager {
3207
3126
  if (failures.length)
3208
3127
  throw new Error(`manager shutdown incomplete: ${failures.join("; ")}`);
3209
3128
  }
3210
- /** Release this instance's liveness lease key on a clean stop, at the broker's own revision
3211
- * rather than a cached one that a renew still in flight moments ago may have already moved past.
3212
- * Re-reads the row and releases only what is PROVABLY this process's (absent, or another pid's,
3213
- * is left alone — the same test {@link reconcileLease} uses).
3214
- *
3215
- * A read or delete that gets no answer, as during a reconnect, is tried again until the delete is
3216
- * acknowledged or {@link LEASE_RELEASE_BUDGET_MS} has passed (#3916). Nothing here throws: a stop
3217
- * must complete either way, and a row that could not be released is left for the bucket TTL, with
3218
- * one line of warning so the cost (a same-root restart waiting out the TTL) is not silent. */
3219
- async releaseOwnManagerLease() {
3220
- const deadline = Date.now() + LEASE_RELEASE_BUDGET_MS;
3221
- for (;;) {
3222
- let why;
3223
- try {
3224
- const own = await this.ep.readOwnManagerLease(this.managerInstanceId);
3225
- if (own === undefined || own.info.pid !== process.pid)
3226
- return;
3227
- await this.ep.releaseManagerLease(this.managerInstanceId, own.revision);
3228
- return;
3229
- }
3230
- catch (e) {
3231
- why = rejectionText(e);
3232
- }
3233
- if (Date.now() >= deadline) {
3234
- console.error(`! manager instance ${this.managerInstanceId} could not release its liveness lease (space "${this.space}"): ${why}; a same-root restart inside the bucket TTL will be refused`);
3235
- return;
3236
- }
3237
- await new Promise((r) => setTimeout(r, LEASE_RELEASE_RETRY_MS));
3238
- }
3239
- }
3240
3129
  /**
3241
3130
  * REMOVE THIS INSTANCE'S SERVICE REGISTRATION on a clean stop (§13.5 deregistration).
3242
3131
  *
@@ -3336,128 +3225,6 @@ export class Manager {
3336
3225
  }
3337
3226
  })().catch(() => this.transportDown.add(nc));
3338
3227
  }
3339
- /** Keep this instance's liveness key fresh, and end the process only when another process holds it.
3340
- *
3341
- * A renew that throws is a question, not a verdict: the request may have timed out with the write
3342
- * landed and only its acknowledgement lost, the key may have expired during a stall, or a same-id
3343
- * process may hold it. The verdict comes from RE-READING the key ({@link reconcileLease}), and each
3344
- * answer has one response:
3345
- * - `held`: adopt the broker's revision and carry on.
3346
- * - `gone`: the key expired or was released while this process was still here, so put it back. The
3347
- * create is atomic, so a same-id process that got there first shows up as `taken` next tick.
3348
- * - `taken`: a different process holds this instance's key, so it took this instance over while
3349
- * this one stalled. This process is the superseded one and stops serving by exiting (SPEC 13.1).
3350
- * An open mesh has no barrier that would evict its serve connection, so nothing else stops it.
3351
- * - `unknown`: the broker could not be asked. Keep serving and ask again next tick, for as long as it
3352
- * takes. A manager that cannot reach its broker gains nothing by ending itself, and the seats it
3353
- * holds lose everything (a pty child dies with its parent).
3354
- *
3355
- * This replaces a fail-close that ended the process one tick past the lease TTL with no answer, which
3356
- * on a live mesh turned a ten-second broker or KV outage into a manager outage that lasted until an
3357
- * operator noticed. */
3358
- async renewLease() {
3359
- // A manager that is stopping never puts its own key back: a stop already fenced this loop, and
3360
- // any tick or explicit call landing after that must be a no-op, not a fresh acquire attempt.
3361
- if (this.leaseStopping)
3362
- return;
3363
- // A renew that runs long must not be overlapped by the next tick: both would CAS against the same
3364
- // cached revision, so whichever lands second is refused over a sequence the first legitimately
3365
- // moved, a conflict this instance manufactured itself.
3366
- if (this.leaseRenewInFlight)
3367
- return;
3368
- this.leaseRenewInFlight = true;
3369
- const task = this.renewLeaseAttempt();
3370
- this.leaseRenewTask = task;
3371
- return task;
3372
- }
3373
- /** The renew attempt itself, split out from {@link renewLease} only so `stop()` can hold the
3374
- * promise a renew already in flight is running ({@link leaseRenewTask}) and await it before
3375
- * releasing the key: releasing against a cached revision a live renew has since moved is a CAS
3376
- * the broker correctly refuses, silently, forever. */
3377
- async renewLeaseAttempt() {
3378
- try {
3379
- if (!this.leaseInfo || this.leaseRevision === undefined)
3380
- return;
3381
- try {
3382
- this.leaseRevision = await this.ep.renewManagerLease(this.leaseInfo, this.leaseRevision);
3383
- this.noteLease("held", `renews its liveness lease again (revision ${this.leaseRevision})`);
3384
- return;
3385
- }
3386
- catch (renewError) {
3387
- const why = rejectionText(renewError);
3388
- const verdict = await this.reconcileLease();
3389
- switch (verdict.kind) {
3390
- case "held":
3391
- // The re-read is the broker's truth about the revision: adopt it, whether our write landed
3392
- // with its acknowledgement lost (revision moved) or never landed (revision unchanged).
3393
- this.leaseRevision = verdict.revision;
3394
- this.noteLease("held-unrenewed", `could not renew its liveness lease (${why}) but the key is still its own at revision ${verdict.revision}; serving, retrying`);
3395
- return;
3396
- case "gone": {
3397
- // A stop that began while this renew was already in flight fences it here too: the
3398
- // await above can cross the point where `stop()` set the flag, and a re-acquire past
3399
- // that point would put a stopping process's key straight back.
3400
- if (this.leaseStopping)
3401
- return;
3402
- // The key being gone is a fact before the re-acquire is attempted, so a successful
3403
- // re-acquire is a change of state (gone to held) and prints, every time it happens.
3404
- const before = this.leaseState;
3405
- this.leaseState = "gone";
3406
- try {
3407
- this.leaseRevision = await this.ep.acquireManagerLease(this.leaseInfo);
3408
- this.noteLease("held", `found its liveness lease key gone (renew: ${why}) and re-acquired it at revision ${this.leaseRevision}`);
3409
- }
3410
- catch (e) {
3411
- this.leaseState = before;
3412
- this.noteLease("gone", `found its liveness lease key gone (renew: ${why}) and could not re-acquire it yet (${rejectionText(e)}); serving, retrying`);
3413
- }
3414
- return;
3415
- }
3416
- case "taken":
3417
- // No `stop()` on the way out: its deregistration deletes the instance's current
3418
- // registration, which is the other process's now. That process took over on the premise
3419
- // that this one was gone, so this exit leaves what a crash would, and seats a custodian or
3420
- // multiplexer owns outlive it the same way.
3421
- console.error(`! manager instance ${this.managerInstanceId} finds its liveness lease key held by ${verdict.by}, not by this process (renew: ${why}); that process serves this instance now, so this one stops serving and exits (space "${this.space}")`);
3422
- process.exit(1);
3423
- case "unknown":
3424
- this.noteLease("unknown", `could not renew its liveness lease (${why}) or re-read it (${verdict.why}); serving, retrying until the broker answers`);
3425
- return;
3426
- }
3427
- }
3428
- }
3429
- finally {
3430
- this.leaseRenewInFlight = false;
3431
- }
3432
- }
3433
- /** Print `what` only when the lease state CHANGES. The renew ticks every few seconds, so a long
3434
- * outage would otherwise print the same line thousands of times; an operator needs the line going
3435
- * in and the line coming out, with the instance and the space on both. */
3436
- noteLease(state, what) {
3437
- if (state === this.leaseState)
3438
- return;
3439
- this.leaseState = state;
3440
- console.error(`${state === "held" ? "✓" : "!"} manager instance ${this.managerInstanceId} ${what} (space "${this.space}")`);
3441
- }
3442
- /** What the broker actually says about THIS instance's lease key, right now. `unknown` is a first-class
3443
- * answer and never collapses into `gone`: not being able to look is not the same fact as looking and
3444
- * finding nothing. */
3445
- async reconcileLease() {
3446
- let current;
3447
- try {
3448
- current = await this.ep.readOwnManagerLease(this.managerInstanceId);
3449
- }
3450
- catch (e) {
3451
- return { kind: "unknown", why: rejectionText(e) };
3452
- }
3453
- if (current === undefined)
3454
- return { kind: "gone" };
3455
- // The pid is what distinguishes US from a same-id restart: the logical instance id and the serve
3456
- // identity both PERSIST across restart by design, so neither can tell the two processes apart.
3457
- if (current.info.pid !== process.pid)
3458
- return { kind: "taken", by: `pid ${current.info.pid} (${current.info.runtime}, root ${current.info.root})` };
3459
- return { kind: "held", revision: current.revision };
3460
- }
3461
3228
  async opFinalizeResume(rawArgs) {
3462
3229
  if (this.execution === "none")
3463
3230
  throw new EpEnvelopeError("unimplemented", this.executionRefusal());
@@ -4813,76 +4580,7 @@ export class Manager {
4813
4580
  isOwnPresence(a, p) {
4814
4581
  return p !== undefined && p.card.id === this.managedPrincipal(a) && p.lifecycleUid === a.lifecycleUid;
4815
4582
  }
4816
- /** Drop a live agent's slot. When `floor` is set and the agent died young (lived less than
4817
- * MIN_LIFETIME), push a cooling stamp so the freed slot still counts toward the ceiling until it
4818
- * expires — flooring the RECYCLE, not the call, so both free paths (despawn + exit/reap) are
4819
- * covered (P4c). Floor self + own-child despawn and natural exit; NEVER admin despawn (operator
4820
- * emergency-kill stays unthrottled) and NEVER the reserved-rollback path (no cold-start paid). */
4821
- freeSlot(a, floor, cause, acceptedBeforeFence = false) {
4822
- if (this.agents.get(a.name) !== a)
4823
- return; // already freed (exit raced despawn, etc.)
4824
- // The terminalizing latch also covers exit/reap paths that never rode stopHandle.
4825
- this.logSeatReaped(a, cause);
4826
- a.terminalizing = true;
4827
- this.agents.delete(a.name);
4828
- this.recordContinuityAtStop(a, "stop");
4829
- if (a.restart?.sessionStatePath)
4830
- rmSync(a.restart.sessionStatePath, { force: true });
4831
- // A released seat's record is the next manager's only pointer to it. It stays until the
4832
- // retirement is confirmed. Dropping it here let a refused retirement leave the lifecycle active
4833
- // with nothing left for that manager to adopt.
4834
- if (!this.releasedSeatPending(a))
4835
- this.dropSeatRecord(a);
4836
- if (a.seatHome)
4837
- rmSync(a.seatHome, { recursive: true, force: true });
4838
- // End any live §13.6 attach session bound to THIS incarnation with the reason its cause names.
4839
- // Fires once per agent on every free path (despawn / self-stop / reap / exit) via the `agents`
4840
- // guard above; a no-op when no plane or no live session for the target.
4841
- this.sessionPlane?.endForTarget(a.name, a.lifecycleUid, typeof cause === "string" ? FREE_SLOT_ATTACH_END[cause] : "target-despawn");
4842
- // The turn relay's reap hook: every pending turn addressed to THIS incarnation is stamped
4843
- // with the death, and its deadline terminal carries it as `agentDownAt`. The addressee is gone
4844
- // and no successor may answer for it; the terminal is still the deadline's, not a new reason.
4845
- this.failSeatTurns(a.name, a.lifecycleUid);
4846
- if (floor && Date.now() - a.startedAt < MIN_LIFETIME)
4847
- this.cooling.push(a.startedAt + MIN_LIFETIME);
4848
- // The departed agent's own custody reference rides the teardown: the exit that freed this slot
4849
- // is usually the seat ending, but a stop that could not prove the process gone leaves one the
4850
- // terminal must still address before it frees the alias.
4851
- const target = this.teardownTarget(a);
4852
- // On a USER mesh the name is RESERVED PENDING RETIREMENT — despawn started this
4853
- // lifecycle's FULL teardown (footprint + standing-authority revoke + the auth-side retirement),
4854
- // and the alias frees only when all of it completes (not the retirement alone). The detached
4855
- // deprovision below drives it; a failed revoke or an unreachable rail keeps the name held,
4856
- // re-driven by a retry. Gate on userMode BY
4857
- // CONSTRUCTION (NEW-1): a static-auth mint has no user-mode lifecycle head to retire, so the
4858
- // reservation + rail request simply don't apply there (the incidental nkey-parse used to mask
4859
- // this, but the intent is "user mode only", not "any principal-shaped id").
4860
- if (this.userMode) {
4861
- const p = parsePrincipalKey(a.id);
4862
- if (p)
4863
- this.retirement.hold(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: p.owner, actor: p.actor, target, startedAt: Date.now() });
4864
- }
4865
- else if (this.auth) {
4866
- // A STATIC lifecycle now also holds its name pending its own terminal (the
4867
- // static retirement the detached deprovision below drives) — the alias frees only when the
4868
- // gate+head terminal completes, exactly the user-mode discipline. The wire principal is the
4869
- // incarnation-unique nkey; owner is the dev owner.
4870
- this.retirement.hold(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: DEV_OWNER, actor: a.id, target, startedAt: Date.now() });
4871
- }
4872
- // Auth mode: tear down the departed agent's minted broker footprint + creds file (#159 B2). The
4873
- // process is already gone, so this must never block the slot free or throw into the caller — it runs
4874
- // detached, and a failure is logged loudly (never swallowed), not retried. The `agents` guard above
4875
- // makes this fire exactly once per agent across every free path (despawn / self-stop / reap / exit).
4876
- if (!a.suppressCleanup && (this.maintenanceState === "active" || acceptedBeforeFence)) {
4877
- // An inline seat's snapshot goes with the seat on every mesh. An open mesh runs no teardown
4878
- // below, and a preservation cut suppresses this, so a resumed seat still finds its snapshot.
4879
- // Settled means the file is gone or the seat never had one. A removal that failed is left to
4880
- // the teardown, which retries it and reports what it could not remove.
4881
- if (a.launch.source.kind !== "inline" || this.dropInlineSnapshot(a.name, a.lifecycleUid))
4882
- target.snapshotSettled = true;
4883
- this.trackDeprovision(target);
4884
- }
4885
- }
4583
+ freeSlot(a, floor, cause, acceptedBeforeFence = false) { this.namesCapacity.freeSlot(a, floor, cause, acceptedBeforeFence); }
4886
4584
  /** Remove one lifecycle's inline snapshot by the path its uid derives, never by a recorded one, so a
4887
4585
  * resume inventory cannot point the removal at another file. Returns whether the file is gone. A
4888
4586
  * failure is logged, never thrown, because the callers must still schedule the teardown. */
@@ -5058,58 +4756,9 @@ export class Manager {
5058
4756
  this.freeSlot(a, true, a.stopCause ?? "process-exit");
5059
4757
  this.reapChildrenOf(this.managedPrincipal(a));
5060
4758
  }
5061
- /** Agent names become `.cotal/agents/<name>.md` paths and mesh identities, so they must be bare
5062
- * tokens, never a path — blocks traversal / arbitrary writes from a model-supplied name. In user
5063
- * mode the name is ALSO the actor, which is a narrower alphabet still; {@link spawnNameError}
5064
- * holds both halves so this door and the auto-numbering that feeds it cannot disagree. */
5065
- nameError(name) {
5066
- return spawnNameError(name, { userMode: this.userMode });
5067
- }
5068
- /** The roster's LIVE occupant names (status !== offline) — occupants this manager may NOT manage
5069
- * (a foreground `cotal spawn`, a connector session, ANOTHER manager's agent). Allocating over any
5070
- * of them mints a sibling the broker/auth then refuses to admit, surfacing as the 30s launch-
5071
- * uncertain black hole. */
5072
- liveRosterNames() {
5073
- const live = new Set();
5074
- for (const p of this.ep.getRoster()) {
5075
- if (p.status === "offline")
5076
- continue;
5077
- const predecessor = this.retirement.predecessor(p.card.name);
5078
- if (predecessor !== undefined && predecessor.principal === p.card.id && predecessor.lifecycleUid === p.lifecycleUid)
5079
- continue;
5080
- live.add(p.card.name);
5081
- }
5082
- return live;
5083
- }
5084
- /** THE single name-liveness predicate both the hard-pinned collision refuse and
5085
- * uniqueName's numbering consult, so they can never drift: a name is taken if this manager
5086
- * reserves/manages/retires it OR a roster-live occupant already holds it. Pass a pre-built
5087
- * {@link liveRosterNames} set when checking many names in one allocation. */
5088
- nameInUse(name, live = this.liveRosterNames()) {
5089
- return this.agents.has(name) || this.reserved.has(name) || this.retirement.hasHold(name) || live.has(name);
5090
- }
5091
- /** First free name in the series `base`, `base_2`, `base_3`, … — checked against live slots,
5092
- * in-flight (reserved) slots, names held pending retirement, AND the live mesh roster. The
5093
- * roster check covers occupants this manager does not manage (a foreground `cotal spawn`, a
5094
- * connector session, another manager's agent): allocating their name would mint a sibling the
5095
- * broker/auth then refuses to admit, surfacing as a 30s launch-uncertain black hole instead of
5096
- * the auto-number the join path gives. Presence is ADVISORY (SPEC §6) — this is an availability
5097
- * choice at allocation, never an authority check (the broker still enforces): a stale
5098
- * still-live-looking row only costs a numbered suffix, and a missed freshly-joined occupant is
5099
- * still refused downstream exactly as before. Offline rows do NOT occupy — a properly retired
5100
- * name stays reusable. A row this manager itself confirmed retired (its alias, principal, and
5101
- * lifecycleUid all matching a {@link confirmedRetiredPredecessors} entry) does not occupy
5102
- * either, even while its advisory presence record ages out. A numbered name is never reissued
5103
- * ({@link issuedNumberedNames}), even after its holder retired. The requested base is exempt
5104
- * from that history: it is the persona's own name, which stays reusable even when it once came
5105
- * out of another persona's numbering. */
5106
- uniqueName(base, unavailable = new Set()) {
5107
- const live = this.liveRosterNames();
5108
- // The cap belongs to user mode alone: only there is the numbered name the actor. Static and open
5109
- // mode key the actor on the minted nkey, so a numbered name there has no length to fit.
5110
- const name = firstFreeName(base, (n) => unavailable.has(n) || this.nameInUse(n, live) || (n !== base && this.issuedNumberedNames.has(n)), this.userMode ? { actorBound: true } : undefined);
5111
- return name;
5112
- }
4759
+ nameError(name) { return this.namesCapacity.nameError(name); }
4760
+ nameInUse(name, live) { return this.namesCapacity.nameInUse(name, live); }
4761
+ uniqueName(base, unavailable = new Set()) { return this.namesCapacity.uniqueName(base, unavailable); }
5113
4762
  /** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
5114
4763
  * under that file's own `name:`), as if a peer asked via the control plane. Used to pre-spawn the
5115
4764
  * demo's experts at startup so the manager owns them. */
@@ -6266,7 +5915,7 @@ export class Manager {
6266
5915
  // alone) so a retry re-drives the standing-authority revoke (INT-2) AND the broker cleanup before
6267
5916
  // any hold-clear (C): the alias must not free while the durable teardown or the revoke is still
6268
5917
  // outstanding. All the teardown ops are idempotent, and the rail request is single-flighted.
6269
- if (this.reconcilingAliases.has(identityName))
5918
+ if (this.staticLifecycle.isReconciling(identityName))
6270
5919
  return { ok: false, error: `the name "${identityName}" is still reconciling at manager startup; its prior lifecycle terminal owns this alias until it completes. Retry shortly.` };
6271
5920
  const held = this.retirement.held(identityName);
6272
5921
  if (held !== undefined) {
@@ -6374,7 +6023,7 @@ export class Manager {
6374
6023
  }
6375
6024
  // Another spawn may have reserved the candidate while the disk/broker proof awaited.
6376
6025
  // Recheck in the same synchronous window as the cap and reservation below.
6377
- if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.issuedNumberedNames.has(name))) {
6026
+ if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
6378
6027
  if (!hardPinned)
6379
6028
  continue;
6380
6029
  return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
@@ -6416,8 +6065,8 @@ export class Manager {
6416
6065
  // allocation, where there is no name to give back.
6417
6066
  hooks?.onEffect?.();
6418
6067
  if (!hardPinned && name !== identityName)
6419
- this.issuedNumberedNames.add(name);
6420
- this.reserved.set(name, owner);
6068
+ this.namesCapacity.rememberNumbered(name);
6069
+ this.namesCapacity.reserve(name, owner);
6421
6070
  try {
6422
6071
  // A stable nkey identity assigned at spawn: the public key is the agent's card.id (threaded via
6423
6072
  // COTAL_ID); the seed is retained to mint matching creds later.
@@ -6809,7 +6458,7 @@ export class Manager {
6809
6458
  });
6810
6459
  }
6811
6460
  this.agents.set(name, managed);
6812
- this.reservedLive.add(name);
6461
+ this.namesCapacity.placed(name);
6813
6462
  if (managed.once)
6814
6463
  this.watchOnceExit(managed);
6815
6464
  // The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
@@ -6992,8 +6641,7 @@ export class Manager {
6992
6641
  return { ok: false, error };
6993
6642
  }
6994
6643
  finally {
6995
- this.reserved.delete(name);
6996
- this.reservedLive.delete(name);
6644
+ this.namesCapacity.release(name);
6997
6645
  if (seatHome)
6998
6646
  rmSync(seatHome, { recursive: true, force: true });
6999
6647
  // A failed removal is logged, never thrown, so the grant's teardown below is still scheduled.
@@ -7087,11 +6735,11 @@ export class Manager {
7087
6735
  return { ok: false, agents: [], error: `retained principal "${principal}" is already live and this runtime cannot authoritatively adopt it` };
7088
6736
  orphans.push({ principal, reference: orphan });
7089
6737
  }
7090
- if (this.agents.has(entry.name) || this.reserved.has(entry.name))
6738
+ if (this.agents.has(entry.name) || this.namesCapacity.isReserved(entry.name))
7091
6739
  return { ok: false, agents: [], error: `retained agent "${entry.name}" is already managed or reserved` };
7092
6740
  }
7093
6741
  for (const entry of entries) {
7094
- this.reserved.set(entry.name, resumeOwner(entry));
6742
+ this.namesCapacity.reserve(entry.name, resumeOwner(entry));
7095
6743
  batchReservations.push(entry.name);
7096
6744
  }
7097
6745
  const preflight = [];
@@ -7130,8 +6778,7 @@ export class Manager {
7130
6778
  }
7131
6779
  finally {
7132
6780
  for (const name of batchReservations) {
7133
- this.reserved.delete(name);
7134
- this.reservedLive.delete(name);
6781
+ this.namesCapacity.release(name);
7135
6782
  }
7136
6783
  // Preflight builds every launch before any child starts, so a refused batch, a failed launch,
7137
6784
  // or the agents skipped after it leave built specs no runtime ever received.
@@ -7374,7 +7021,7 @@ export class Manager {
7374
7021
  const nameErr = this.nameError(entry.name);
7375
7022
  if (nameErr)
7376
7023
  return { ok: false, error: nameErr };
7377
- if (this.agents.has(entry.name) || (!batchReserved && this.reserved.has(entry.name)))
7024
+ if (this.agents.has(entry.name) || (!batchReserved && this.namesCapacity.isReserved(entry.name)))
7378
7025
  return { ok: false, error: `retained agent "${entry.name}" is already managed or reserved; same-principal resume never auto-numbers` };
7379
7026
  const occupancy = batchReserved ? undefined : this.occupancy();
7380
7027
  if (occupancy && occupancy.used >= MAX_AGENTS)
@@ -7520,7 +7167,7 @@ export class Manager {
7520
7167
  }
7521
7168
  async launchPreparedResume(entry, prepared, batchReserved, supervised) {
7522
7169
  if (!batchReserved)
7523
- this.reserved.set(entry.name, resumeOwner(entry));
7170
+ this.namesCapacity.reserve(entry.name, resumeOwner(entry));
7524
7171
  try {
7525
7172
  // Recover the STATIC identity's nkey seed from the adopted credential (the
7526
7173
  // creds file embeds it) so the manager stays this incarnation's RENEWAL OWNER across a
@@ -7600,7 +7247,7 @@ export class Manager {
7600
7247
  suppressCleanup: true,
7601
7248
  };
7602
7249
  this.agents.set(entry.name, managed);
7603
- this.reservedLive.add(entry.name);
7250
+ this.namesCapacity.placed(entry.name);
7604
7251
  if (this.resumeAttemptId)
7605
7252
  this.resumedAgentNames.add(entry.name);
7606
7253
  try {
@@ -7641,8 +7288,7 @@ export class Manager {
7641
7288
  }
7642
7289
  finally {
7643
7290
  if (!batchReserved) {
7644
- this.reserved.delete(entry.name);
7645
- this.reservedLive.delete(entry.name);
7291
+ this.namesCapacity.release(entry.name);
7646
7292
  }
7647
7293
  }
7648
7294
  }
@@ -7957,55 +7603,9 @@ export class Manager {
7957
7603
  if (!watched)
7958
7604
  console.error(`! ${a.name}: runtime "${handle.kind}" cannot prove a child exit (AgentHandle.waitForExit is not implemented) - it stays managed after it exits, until it is stopped`);
7959
7605
  }
7960
- /** Prune expired cooling stamps (drop those at/before now) and return the live count — the
7961
- * recycle floor's contribution to the ceiling (P4c). Lazy: pruned only when the gate consults it. */
7962
- coolingCount() {
7963
- const now = Date.now();
7964
- this.cooling = this.cooling.filter((stamp) => stamp > now);
7965
- return this.cooling.length;
7966
- }
7967
- /** What holds the ceiling's slots, one count per seat (#906). A launching seat sits in `reserved`
7968
- * from accept until its launch settles, in `agents` once its process exists, and in `cooling`
7969
- * if it then frees young, so a reservation stops counting once it reaches `agents`. `managed` is
7970
- * what this manager's `ps` lists, `reserved` is the accepted launches that have no process yet,
7971
- * and `launching` is every unsettled launch that still holds a slot through `reserved` or
7972
- * `agents`. A launch whose seat already freed holds no slot but its cooling stamp, so its
7973
- * failure can free nothing. */
7974
- occupancy() {
7975
- const cooling = this.coolingCount();
7976
- let reserved = 0;
7977
- let launching = 0;
7978
- for (const name of this.reserved.keys()) {
7979
- const placed = this.reservedLive.has(name);
7980
- if (!placed)
7981
- reserved++;
7982
- if (!placed || this.agents.has(name))
7983
- launching++;
7984
- }
7985
- const managed = this.agents.size;
7986
- return {
7987
- managed,
7988
- reserved,
7989
- cooling,
7990
- launching,
7991
- used: managed + reserved + cooling,
7992
- nextCoolingMs: cooling ? Math.min(...this.cooling) - Date.now() : undefined,
7993
- };
7994
- }
7995
- occupancyText(o) {
7996
- return `${o.used} of ${MAX_AGENTS} slots: ${o.managed} managed, ${o.reserved} reserved, ${o.cooling} cooling`;
7997
- }
7998
- /** The capacity refusal states the split it enforces and whether waiting can free a slot: a
7999
- * cooling slot frees at a known time, an unsettled launch frees one only if it fails, and a
8000
- * managed seat frees one only when it is stopped. */
8001
- capacityRefusal(o) {
8002
- const remedy = o.nextCoolingMs !== undefined
8003
- ? `waiting frees a cooling slot in ${Math.ceil(o.nextCoolingMs / 1000)}s, or despawn one`
8004
- : o.launching
8005
- ? `waiting frees a slot only if an unsettled launch fails (${o.launching} pending); otherwise despawn one`
8006
- : "waiting frees no slot; despawn one";
8007
- return `at capacity (${this.occupancyText(o)}); ${remedy}`;
8008
- }
7606
+ occupancy() { return this.namesCapacity.occupancy(); }
7607
+ occupancyText(o) { return this.namesCapacity.occupancyText(o); }
7608
+ capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
8009
7609
  /**
8010
7610
  * The owner a launch belongs to, read ONCE so the per-owner ceiling, the agent's addressing
8011
7611
  * triple and the user-mode provisioner cannot charge three different owners for one seat. A
@@ -8037,9 +7637,7 @@ export class Manager {
8037
7637
  for (const a of this.agents.values())
8038
7638
  if (this.seatOwner(a) === owner)
8039
7639
  seats++;
8040
- for (const [name, reservedFor] of this.reserved)
8041
- if (reservedFor === owner && !this.reservedLive.has(name))
8042
- seats++;
7640
+ seats += this.namesCapacity.ownerReservations(owner);
8043
7641
  return seats;
8044
7642
  }
8045
7643
  /**
@@ -8332,10 +7930,10 @@ export class Manager {
8332
7930
  resumeRequired: this.resumeRequired,
8333
7931
  stopping: this.leaseStopping,
8334
7932
  lifecycleInFlight: this.lifecycleInFlight,
8335
- reservedLaunches: this.reserved.size,
7933
+ reservedLaunches: this.namesCapacity.reservedCount,
8336
7934
  retirementsPending: this.retirement.pendingCount,
8337
7935
  deprovisioningInFlight: this.retirement.inFlightCount,
8338
- staticReconciliationInFlight: this.staticReconcileSweepsInFlight,
7936
+ staticReconciliationInFlight: this.staticLifecycle.sweepsInFlight,
8339
7937
  agents: [...this.agents.values()]
8340
7938
  .filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter)
8341
7939
  .map((a) => ({
@@ -8355,23 +7953,8 @@ export class Manager {
8355
7953
  },
8356
7954
  };
8357
7955
  }
8358
- /** Render the current operator snapshot. Recovered rows live until the next sweep starts, then
8359
- * clear, so recovery is visible without becoming stale process-lifetime history. */
8360
7956
  staticReconciliationStatus() {
8361
- const failures = [...this.staticReconcileItems.values()]
8362
- .map(({ owner: _owner, timer: _timer, flight: _flight, retryFlight: _retryFlight, ...item }) => ({ ...item }))
8363
- .sort((a, b) => a.alias.localeCompare(b.alias));
8364
- const state = this.staticReconcileLastSweep?.error !== undefined ? "failed" :
8365
- failures.some((item) => item.disposition === "retrying") ? "retrying" :
8366
- failures.some((item) => item.disposition === "retry-scheduled") ? "retry-wait" :
8367
- failures.some((item) => item.disposition === "refused" || item.disposition === "refused-foreign" || item.disposition === "retry-exhausted") ? "failed" :
8368
- this.staticReconcileSweepsInFlight > 0 ? "running" :
8369
- failures.some((item) => item.disposition === "recovered") ? "recovered" : "idle";
8370
- return {
8371
- state,
8372
- ...(this.staticReconcileLastSweep ? { lastSweep: { ...this.staticReconcileLastSweep } } : {}),
8373
- failures,
8374
- };
7957
+ return this.staticLifecycle.staticReconciliationStatus();
8375
7958
  }
8376
7959
  /** Complete a crashed predecessor's FROZEN registration gate before this incarnation starts a
8377
7960
  * new one (#783 item 3 / #871). The CLI `cotal reconcile-gate` already does this; a successor
@@ -9986,8 +9569,7 @@ export class Manager {
9986
9569
  continue;
9987
9570
  }
9988
9571
  if (adopts) {
9989
- const reconciling = this.staticReconcileSweepsInFlight > 0
9990
- || [...this.staticReconcileItems.values()].some((i) => i.lifecycleUid === uid && i.disposition !== "recovered");
9572
+ const reconciling = this.staticLifecycle.pendingLifecycle(uid);
9991
9573
  if (reconciling)
9992
9574
  continue;
9993
9575
  this.onceInherited.delete(uid);
@@ -10101,844 +9683,32 @@ export class Manager {
10101
9683
  reapOrphanSeat(a) {
10102
9684
  return this.seatCustody.reapOrphanSeat(a);
10103
9685
  }
10104
- /** The static terminal for one departed incarnation: delegates the gate/head CAS
10105
- * sequence to the shared core saga over the executor transport; the footprint teardown (creds
10106
- * file + broker durables/ACL) runs INSIDE the barrier as its cleanup step. On completion the
10107
- * wire principal joins {@link retiredPrincipals} (the retired-principal refusal index) and the name hold
10108
- * clears (ABA-guarded by uid). A lifecycle with no slot row (spawned before the
10109
- * durable registry existed) has nothing to terminalize: its footprint teardown runs directly
10110
- * and the hold clears, the honest upgrade path. `onDeprovision` receives the accounting of the
10111
- * broker teardown this call ran, on success or on a {@link DeprovisionError}. */
10112
- async driveStaticRetirement(a, surfaceFailure = false, onDeprovision) {
10113
- // A renewal that published its flight before the synchronous terminal latch is accepted work.
10114
- // Drain it before the durable terminal enumerates credential ids and before cleanup deletes its
10115
- // material; a failed renewal must not block retirement because it may still have staged an id.
10116
- const acceptedRenewal = a.staticCredentialRenewal;
10117
- if (acceptedRenewal)
10118
- await acceptedRenewal.catch(() => { });
10119
- const opId = managedRetirementOpId(a.lifecycleUid);
10120
- const evict = this.staticLifecycleEvict ?? makeManagerEndpointEvictionEvidence({
10121
- space: this.space,
10122
- servers: this.servers ?? DEFAULT_SERVER,
10123
- auth: this.auth,
10124
- log: (line) => console.error(`static retirement ${a.name}: ${line}`),
10125
- // A daemon credential reload briefly removes its responder while it reconnects.
10126
- unreachableWaitMs: DEPROVISION_TIMEOUT_MS,
10127
- });
10128
- const cleanup = async () => {
10129
- // SPEC 13.15: every issuance bound to this incarnation's ledger family is retired here,
10130
- // inside the barrier and after the ledger rows were revoked (the source is frozen first,
10131
- // then the index is walked). A retirement that lost is surfaced, never skipped: an active
10132
- // attempt row on a retired lifecycle would authorize a run the credential no longer can.
10133
- const retired = await this.withIssuer((i) => i.store.retireSource({ space: this.space, bucket: epAuthBucket(this.space), key: `cred.${a.lifecycleUid}` }));
10134
- if (retired > 0)
10135
- console.error(`static retirement ${a.name}: retired ${retired} issuance(s) bound to uid ${a.lifecycleUid}`);
10136
- const secrets = this.secrets;
10137
- const files = a.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, a.name, a.lifecycleUid);
10138
- // The broker teardown mints its own credential, so a creds file that cannot be removed must not
10139
- // skip it. The failures are thrown together, so the terminal still stops at an incomplete cleanup.
10140
- const failed = [];
10141
- if (files.creds) {
10142
- const creds = files.creds;
10143
- await attemptCleanup(failed, `secret ${creds}`, () => secrets.delete(agentSecretKeyForFile(creds, this.space)));
10144
- await attemptCleanup(failed, `file ${creds}`, () => rmSync(creds, { force: true }));
10145
- }
10146
- // The lifecycle's inline snapshot, when no earlier step settled it. Keyed by the uid, so a boot
10147
- // sweep or a reconcile that knows only the slot row removes it too.
10148
- if (!a.snapshotSettled) {
10149
- const snapshot = inlineSnapshotPath(this.workspaceRoot, a.lifecycleUid);
10150
- await attemptCleanup(failed, `file ${snapshot}`, () => removeInlineSnapshot(this.workspaceRoot, a.lifecycleUid));
10151
- }
10152
- await attemptCleanup(failed, "broker teardown", async () => {
10153
- try {
10154
- const accounting = await this.deprovisionBroker(a);
10155
- onDeprovision?.(accounting);
10156
- }
10157
- catch (e) {
10158
- if (e instanceof DeprovisionError)
10159
- onDeprovision?.(e.accounting);
10160
- throw e;
10161
- }
10162
- });
10163
- if (failed.length)
10164
- throw new Error(`cleanup failed: ${describeCleanupFailures(failed)}`);
10165
- };
10166
- // The process goes before its footprint: reap the orphan seat by reference, then tear down.
10167
- const reapThenCleanup = async () => {
10168
- await this.reapOrphanSeat(a);
10169
- await cleanup();
10170
- };
10171
- try {
10172
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: a.id, lifecycleUid: a.lifecycleUid, alias: a.name }, async (t) => {
10173
- const slot = await readStaticSlot(t, DEV_OWNER, a.name);
10174
- if (slot === undefined || slot.row.lifecycleUid !== a.lifecycleUid) {
10175
- // No durable registration for THIS incarnation: a spawn from before the registry (or a slot already
10176
- // replaced by a successor — then this stale teardown must not touch the registry at all).
10177
- await reapThenCleanup();
10178
- return;
10179
- }
10180
- await runStaticTerminal(t, {
10181
- owner: DEV_OWNER, alias: a.name, actor: a.id, lifecycleUid: a.lifecycleUid, opId,
10182
- managerInstance: this.managerInstanceId, managerProcessUid: this.managerLifecycleUid,
10183
- }, { cleanup: reapThenCleanup, evict, log: (line) => console.error(`static retirement ${a.name}: ${line}`) });
10184
- });
10185
- this.retirement.recordStaticRetirement(a);
10186
- }
10187
- catch (e) {
10188
- const h = this.retirement.held(a.name);
10189
- if (h && h.target.lifecycleUid === a.lifecycleUid)
10190
- h.lastError = `the static retirement did not complete (${rejectionText(e)}); the name stays held - a same-name spawn retries the same terminal (op ${opId})`;
10191
- console.error(`static retirement ${a.name} (${a.id}): ${rejectionText(e)}`);
10192
- if (surfaceFailure)
10193
- throw e;
10194
- }
9686
+ driveStaticRetirement(a, surfaceFailure = false, onDeprovision) {
9687
+ return this.staticLifecycle.driveStaticRetirement(a, surfaceFailure, onDeprovision);
10195
9688
  }
10196
- /** `chat-session-open`: admit one static chat session. The manager draws the `chat_` alias and a
10197
- * fresh nkey identity, then runs the same native steps a static spawn does: the slot intent and
10198
- * the shared activation saga, the provisioner's bind-only DM and DELIVER durables plus the ACL
10199
- * row, and the agent-profile mint. The leaf carries the spawn's three lists under the spawn's
10200
- * rules (`resolveReadAcl`, a default-deny post list, the foreign event-channel refusal) and
10201
- * nothing else: no role (so no TASK queue), no capabilities, no endpoint rows, no issuance. It
10202
- * expires at `ttl` with no renewal, because no managed row exists to renew it.
10203
- *
10204
- * The session is registered with the tracker before the first durable write and scheduled for
10205
- * its expiry before the reply is sent, or after a rollback that did not complete, so this
10206
- * process retires it at the expiry even when the reply is lost or the client never retires.
10207
- *
10208
- * The credential is ledgered before it leaves this process (slot credentialId, then the `cred.`
10209
- * row), so the static terminal marks the row revoked and verify-evicts the session's principal;
10210
- * the broker keeps accepting the leaf until its expiry. The direct ledger write is deliberate:
10211
- * the leaf is not an issuance, so the issuance seam, which writes the same row inside its
10212
- * finalization, never runs for it, and without the row the terminal's eviction set would be
10213
- * empty. The credential leaves only sealed to `sealTo`, bound to the space, this instance and
10214
- * the reply's fields, so a reply printed anywhere carries no usable credential. A failure at
10215
- * any step drives the terminal before the refusal is returned, and the refusal says whether it
10216
- * completed. */
10217
- async openStaticChatSession(raw) {
10218
- if (!this.auth || this.userMode)
10219
- throw new EpEnvelopeError("unimplemented", "chat-session-open admits static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
10220
- const input = readChatOpenInput(raw);
10221
- if ("error" in input)
10222
- throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
10223
- const lists = chatOpenLists(input);
10224
- if ("error" in lists)
10225
- throw new EpEnvelopeError("bad-request", lists.error, undefined, "not-executed");
10226
- const alias = drawChatAlias();
10227
- const identity = newIdentity();
10228
- // The spawn's rule, against the drawn actor: a concrete event channel of any other principal is
10229
- // refused, and a wildcard is an ordinary grant.
10230
- const foreign = foreignEventChannels([...lists.allowSubscribe, ...lists.allowPublish], DEV_OWNER, identity.id);
10231
- if (foreign.length)
10232
- throw new EpEnvelopeError("bad-request", `chat-session-open asks for another agent's event channel: ${foreign.join(", ")}. A session may be granted its OWN event plane and no other, because that plane carries the session's tool inputs and outputs. Grant a reader out of band rather than through a chat session: ${this.readerRemedy(DEV_OWNER, foreign[0])}`, undefined, "not-executed");
10233
- const lifecycleUid = mintLifecycleUid();
10234
- const exp = Math.floor(Date.now() / 1000) + input.ttl;
10235
- const pin = { owner: DEV_OWNER, actor: identity.id, lifecycleUid, alias };
10236
- const session = { alias, actor: identity.id, lifecycleUid, channels: lists.allowSubscribe, expiresAt: exp * 1000 };
10237
- // Registered before the first durable write, so the startup sweep never mistakes this opening's
10238
- // provisioning row for a crashed spawn, and the stop knows it.
10239
- try {
10240
- this.chatExpiry.register(session);
10241
- }
10242
- catch (e) {
10243
- throw new EpEnvelopeError("unavailable", rejectionText(e), undefined, "not-executed");
10244
- }
10245
- try {
10246
- await this.withLifecycleExecutor(pin, (t) => activateStaticLifecycle(t, { owner: DEV_OWNER, alias, actor: identity.id, lifecycleUid, managerInstance: this.managerLifecycleUid, ownerInstanceId: this.managerInstanceId }));
10247
- const creds = await this.withProvisioner((prov) => provisionAgent(prov, this.auth, identity, { subscribe: lists.subscribe, allowSubscribe: lists.allowSubscribe, allowPublish: lists.allowPublish, lifecycleUid, expiresAt: exp }));
10248
- // The same credential id the issuance path derives, so a re-sent identical credential maps to
10249
- // the same row.
10250
- const credentialId = credentialIdOf(creds);
10251
- await this.withLifecycleExecutor(pin, async (t) => {
10252
- await recordSlotCredential(t, DEV_OWNER, alias, lifecycleUid, credentialId);
10253
- await appendStaticCredentialRow(t, { lifecycleUid, credentialId, holderPrincipal: principalKey(DEV_OWNER, identity.id).key, exp });
10254
- const slot = await readStaticSlot(t, DEV_OWNER, alias);
10255
- if (slot === undefined || slot.row.lifecycleUid !== lifecycleUid || slot.row.phase !== "provisioning")
10256
- throw new Error(`the static slot for "${alias}" is ${slot === undefined ? "absent" : `${slot.row.phase} at uid ${slot.row.lifecycleUid}`}, not this opening's provisioning intent`);
10257
- await casStaticSlot(t, { ...slot.row, phase: "active" }, slot.revision);
10258
- });
10259
- const { sealer, sealed } = sealChatAdmission({
10260
- space: this.space, managerInstanceId: this.managerInstanceId, alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealTo: input.sealTo, creds,
10261
- });
10262
- this.chatExpiry.arm(lifecycleUid);
10263
- console.error(`chat session ${alias} admitted as ${identity.id} (uid ${lifecycleUid}), expires ${new Date(exp * 1000).toISOString()}`);
10264
- return { alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealer, sealed };
10265
- }
10266
- catch (e) {
10267
- // A confirmed rollback leaves a known state, a retired slot. An unconfirmed one does not, so
10268
- // the session stays registered and its expiry, or the stop, retries the same terminal.
10269
- let rollback;
10270
- try {
10271
- await this.chatTerminal(session);
10272
- }
10273
- catch (r) {
10274
- rollback = rejectionText(r);
10275
- try {
10276
- this.chatExpiry.arm(lifecycleUid);
10277
- }
10278
- catch (t) {
10279
- rollback += `; ${rejectionText(t)}`;
10280
- }
10281
- }
10282
- throw new EpEnvelopeError(e instanceof EpEnvelopeError ? e.code : "unavailable", `chat-session-open did not complete for ${alias}: ${rejectionText(e)}; ${rollback === undefined ? "its rollback retired the slot" : `its rollback was not confirmed (${rollback}), so the slot stays held until a retire, its expiry here, this manager's stop, or the next start of this manager instance`}`, undefined, rollback === undefined ? "executed" : "unknown");
10283
- }
10284
- }
10285
- /** `chat-session-retire`: end one static chat session through the native static terminal (ledger
10286
- * row marked revoked, verified eviction of its principal's live connections, footprint cleanup,
10287
- * gate and head retirement). It refuses before any effect unless {@link admitChatRetirement}
10288
- * admits the request. A terminal that cannot complete answers `failed` with the reason, never
10289
- * success; the slot stays held. The broker keeps accepting the leaf until its expiry either way. */
10290
- async retireStaticChatSession(raw) {
10291
- if (!this.auth || this.userMode)
10292
- throw new EpEnvelopeError("unimplemented", "chat-session-retire retires static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
10293
- const input = readChatRetireInput(raw);
10294
- if ("error" in input)
10295
- throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
10296
- if (await this.admitChatRetirement(input) === "alreadyRetired")
10297
- return { outcome: "alreadyRetired" };
10298
- try {
10299
- await this.chatTerminal({ ...input, channels: this.chatExpiry.channels(input.lifecycleUid) });
10300
- }
10301
- catch (e) {
10302
- return { outcome: "failed", reason: `retirement pending: ${rejectionText(e)}` };
10303
- }
10304
- return { outcome: "retired" };
9689
+ openStaticChatSession(raw) {
9690
+ return this.staticLifecycle.openStaticChatSession(raw);
10305
9691
  }
10306
- /** The expiry cleanup's retirement of one session this process admitted. It is lifecycle work, so
10307
- * it is admitted like a control call and a stop drains it. A throw is a failure the tracker
10308
- * retries; a slot that is no longer this instance's to retire ends the tracking instead. */
10309
- async expireStaticChatSession(session) {
10310
- const release = this.beginLifecycle();
10311
- if (!release)
10312
- throw new Error(this.maintenanceError());
10313
- try {
10314
- console.error(`chat session ${session.alias} (uid ${session.lifecycleUid}) reached its expiry; retiring it`);
10315
- let admitted;
10316
- try {
10317
- admitted = await this.admitChatRetirement(session);
10318
- }
10319
- catch (e) {
10320
- if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
10321
- console.error(`! chat session ${session.alias} expired, but its slot is not this instance's to retire (${e.message}); expiry tracking ends`);
10322
- return;
10323
- }
10324
- throw e;
10325
- }
10326
- if (admitted === "admitted")
10327
- await this.chatTerminal(session);
10328
- }
10329
- finally {
10330
- release();
10331
- }
9692
+ retireStaticChatSession(raw) {
9693
+ return this.staticLifecycle.retireStaticChatSession(raw);
10332
9694
  }
10333
- /** The ownership admission shared by `chat-session-retire`, the expiry and the stop. It throws a
10334
- * not-executed refusal unless the alias is a chat alias whose slot this logical instance owns
10335
- * at the requested UID and actor. An already retired slot ends its expiry tracking. */
10336
- async admitChatRetirement(s) {
10337
- if (!isChatAlias(s.alias))
10338
- throw new EpEnvelopeError("permission-denied", `"${s.alias}" is not a chat session alias`, undefined, "not-executed");
10339
- if (this.reconcilingAliases.has(s.alias))
10340
- throw new EpEnvelopeError("unavailable", `the chat session "${s.alias}" is still reconciling at manager startup; that terminal owns it`, undefined, "not-executed");
10341
- const recordsKv = this.goalWriter?.ctx.kv;
10342
- if (!recordsKv)
10343
- throw new EpEnvelopeError("unavailable", `the durable static slot store is not ready while retiring "${s.alias}"`, undefined, "not-executed");
10344
- let slot;
10345
- try {
10346
- slot = await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, s.alias);
10347
- }
10348
- catch (e) {
10349
- throw new EpEnvelopeError("unavailable", `the durable slot for "${s.alias}" could not be read: ${rejectionText(e)}`, undefined, "not-executed");
10350
- }
10351
- const refused = chatRetireRefusal(slot?.row, s, this.managerInstanceId);
10352
- if (refused)
10353
- throw new EpEnvelopeError(refused.code, refused.message, undefined, "not-executed");
10354
- if (slot.row.phase !== "retired")
10355
- return "admitted";
10356
- this.chatExpiry.forget(s.lifecycleUid);
10357
- return "alreadyRetired";
10358
- }
10359
- /** One static terminal per chat session UID, however many callers ask: the explicit retire, the
10360
- * expiry cleanup and the open's rollback join it instead of racing its CAS sequence. A completed
10361
- * terminal ends the expiry tracking. `channels` names the membership rows to delete by name;
10362
- * without it the delivery inventory alone finds them. */
10363
- chatTerminal(s) {
10364
- let flight = this.chatRetirements.get(s.lifecycleUid);
10365
- if (!flight) {
10366
- flight = this.withRetirementSlot(() => this.driveStaticRetirement({ id: s.actor, name: s.alias, lifecycleUid: s.lifecycleUid, secretPaths: {}, ...(s.channels ? { launch: { allowSubscribe: s.channels } } : {}) }, true))
10367
- .then(() => this.chatExpiry.forget(s.lifecycleUid))
10368
- .finally(() => this.chatRetirements.delete(s.lifecycleUid));
10369
- this.chatRetirements.set(s.lifecycleUid, flight);
10370
- }
10371
- return flight;
9695
+ retireChatSessionsOnStop() {
9696
+ return this.staticLifecycle.retireChatSessionsOnStop();
10372
9697
  }
10373
- /** Whether `row` is a chat slot this process registered, at its exact alias, actor and UID,
10374
- * under this logical instance and this process's incarnation. */
10375
- holdsLiveChatSlot(row) {
10376
- return row.ownerInstanceId === this.managerInstanceId && row.managerInstance === this.managerLifecycleUid && this.chatExpiry.holdsExact(row);
10377
- }
10378
- /** The stop's retirement of every chat session this process still tracks, through the same
10379
- * ownership admission and terminal as `chat-session-retire`, at most
10380
- * {@link CHAT_EXPIRY_CONCURRENCY} at a time. It runs after the lifecycle fence closed and every
10381
- * admitted operation drained, as the seat teardown does, and mints nothing the terminal does not
10382
- * already mint. Every outcome is logged. It throws, naming each one, when any session was not
10383
- * retired; that session stays held until the next start of this manager instance. */
10384
- async retireChatSessionsOnStop() {
10385
- const queue = this.chatExpiry.remaining();
10386
- const failed = [];
10387
- const retireOne = async (session) => {
10388
- const at = `chat session ${session.alias} (uid ${session.lifecycleUid})`;
10389
- try {
10390
- if (await this.admitChatRetirement(session) === "alreadyRetired") {
10391
- console.error(`${at} was already retired at stop`);
10392
- return;
10393
- }
10394
- await this.chatTerminal(session);
10395
- console.error(`${at} retired at stop`);
10396
- }
10397
- catch (e) {
10398
- if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
10399
- this.chatExpiry.forget(session.lifecycleUid);
10400
- console.error(`! ${at} was not retired at stop: its slot is not this instance's to retire (${e.message})`);
10401
- return;
10402
- }
10403
- failed.push(`${session.alias} (uid ${session.lifecycleUid}): ${rejectionText(e)}`);
10404
- console.error(`! ${at} was not retired at stop (${rejectionText(e)}); it stays held until the next start of this manager instance`);
10405
- }
10406
- };
10407
- await Promise.all(Array.from({ length: Math.min(CHAT_EXPIRY_CONCURRENCY, queue.length) }, async () => {
10408
- for (let next = queue.shift(); next !== undefined; next = queue.shift())
10409
- await retireOne(next);
10410
- }));
10411
- if (failed.length)
10412
- throw new Error(`${failed.length} chat session(s) were not retired and stay held until the next start of this manager instance: ${failed.join("; ")}`);
10413
- }
10414
- /** Name, at a stop that does not retire them, each chat session this process still tracks. */
10415
9698
  reportChatSessionsLeftAtStop(why) {
10416
- for (const session of this.chatExpiry.remaining())
10417
- console.error(`! chat session ${session.alias} (uid ${session.lifecycleUid}) was not retired because ${why}; the next start of this manager instance retires it`);
10418
- }
10419
- /** Push renewal of ONE live managed-static credential: re-mint the SAME nkey
10420
- * identity with the SAME scope (recorded on the managed row at spawn) and a fresh bounded
10421
- * exp, ledger the new credentialId (slot record first, then the row, then the file — a
10422
- * credential is never materialized before its ledger row exists), and re-sign the SAME
10423
- * lifecycle-keyed file the agent endpoint's source seam re-reads. Never advances the epoch;
10424
- * renewal remains the THIRD transition. */
10425
- async renewManagedStaticCred(a) {
10426
- if (!this.auth || !a.seed || !a.secretPaths?.creds)
10427
- throw new Error("renewManagedStaticCred: not a renewable managed-static agent");
10428
- // Admission is synchronous. An accepted renewal publishes its flight before its first caller can
10429
- // terminalize the agent; terminalization rejects later callers and drains this flight before the
10430
- // durable terminal starts, giving renewal-before-terminal and terminal-before-renewal one order.
10431
- if (a.terminalizing)
10432
- throw new Error("renewManagedStaticCred: the lifecycle is terminalizing; no credential is minted after the terminal begins");
10433
- if (a.staticCredentialRenewal)
10434
- return a.staticCredentialRenewal;
10435
- const renewal = this.driveManagedStaticCredRenewal(a).finally(() => {
10436
- if (a.staticCredentialRenewal === renewal)
10437
- a.staticCredentialRenewal = undefined;
10438
- });
10439
- a.staticCredentialRenewal = renewal;
10440
- return renewal;
10441
- }
10442
- async driveManagedStaticCredRenewal(a) {
10443
- // The SAME permission scope the spawn minted (recorded on the managed row): allowSubscribe/
10444
- // allowPublish/role/capabilities are the JWT-shaping inputs; `subscribe` (the active read
10445
- // set) shapes durable membership only and is not a mint input.
10446
- if (!a.issued)
10447
- throw new Error(`renewManagedStaticCred: ${a.name} carries no issuance; a static credential minted before SPEC 13.15 is not renewed under an unbound generation - respawn the agent`);
10448
- // A renewal never outlives the generation's horizon, and none is minted at or past it: the
10449
- // generation then authorizes nothing and its rows are being removed (SPEC 13.15).
10450
- const now = Math.floor(Date.now() / 1000);
10451
- const horizon = issuedHorizon(a.issued.generation);
10452
- if (now >= horizon)
10453
- throw new Error(`renewManagedStaticCred: ${a.name}'s issued generation reached its horizon ${new Date(horizon * 1000).toISOString()} (${STATIC_GENERATION_HORIZON_SEC / 86_400} days after its spawn) and is not renewed - respawn the agent (rotation instead of this cap: Cotal-AI/Cotal#4942)`);
10454
- const exp = Math.min(now + MANAGED_STATIC_TTL_SEC, horizon);
10455
- // A RENEWAL keeps the generation (SPEC 13.15): the same JWT-shaping inputs produce the same
10456
- // ceiling, which `confirm` verifies against the recorded evidence before the ledger append. A
10457
- // changed ceiling is refused there: that is a fresh issuance on a new connection, never a renewal.
10458
- const issued = a.issued;
10459
- const endpoints = lowerPersonaEndpoints(a.launch.endpoints);
10460
- const reads = this.managedStaticInstanceReads(a.launch.capabilities);
10461
- if (reads.length) {
10462
- // Resolve this incarnation's original issuance, not its current spawner or a reconstructed
10463
- // run admission. Old seats and run helpers keep the exact ceiling they were minted with.
10464
- const caller = { owner: DEV_OWNER, actor: a.id, uid: a.lifecycleUid, generation: issued.generation };
10465
- const { evidence } = await withIssuerSession({ servers: this.servers ?? DEFAULT_SERVER, space: this.space, auth: this.auth, tls: false }, (s) => s.store.resolve({ space: this.space, ...caller }, s.sourceIsLive));
10466
- if (!grantOverreach(this.space, caller, evidence.permissions, { endpoints: reads }).length)
10467
- endpoints.push(...reads);
10468
- }
10469
- const creds = await this.withIssuer((i) => mintCreds(this.auth, { id: a.id, seed: a.seed }, "agent", {
10470
- eventPayloads: this.eventPayloadsWithheld ? false : a.launch.eventPayloads,
10471
- allowSubscribe: a.launch.allowSubscribe,
10472
- allowPublish: a.launch.allowPublish,
10473
- role: a.role,
10474
- capabilities: a.launch.capabilities,
10475
- ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
10476
- lifecycleUid: a.lifecycleUid,
10477
- expiresAt: exp,
10478
- issued,
10479
- issuance: this.issuanceSeam(i, "renew", a, exp),
10480
- }));
10481
- const secrets = this.secrets;
10482
- const credsPath = a.secretPaths.creds;
10483
- await secrets.put(agentSecretKeyForFile(credsPath, this.space), creds);
10484
- await materializeSecretToFile(secrets, agentSecretKeyForFile(credsPath, this.space), credsPath);
10485
- // The record pins the credential's digest, so it follows the re-signed file.
10486
- this.refreshSeatRecord(a);
10487
- console.error(`managed cred renewal ${a.name}: re-signed for the same identity (exp +${exp - now}s); the agent endpoint's source re-read adopts it`);
10488
- }
10489
- /** The static-slot reconciliation ("no active orphan"): ensure the authority stores, then sweep
10490
- * every durable slot row and act by the TOTAL resume table — `provisioning`/`terminalizing`
10491
- * re-drive the exact-op terminal; an `active` row survives ONLY when a LIVE managed agent this
10492
- * manager process owns backs it at the same uid (`adopted`), else no managed owner claimed it and
10493
- * its broker authority is contained and terminalized; `retired` rows seed the retired-principal refusal index. Two call sites: the BOOT sweep
10494
- * (`postAdoption=false`, under the lease before control serving) DEFERS active-non-adopted
10495
- * slots while a resume is still pending (adoption runs after it); the POST-ADOPTION sweep
10496
- * (`postAdoption=true`, inside finalizeResume while `resumeRequired` still fences ordinary
10497
- * spawns) terminalizes any active slot the resume did not claim. */
10498
- staticReconcileKey(row) {
10499
- return JSON.stringify([row.owner, row.alias, row.lifecycleUid]);
10500
- }
10501
- /** Read one retry coordinate from the durable slot store. The status snapshot never authorizes a
10502
- * re-drive: every timer comes through this fresh read before the planner and exact terminal. */
10503
- async readStaticReconcileSlot(alias) {
10504
- if (!this.auth)
10505
- return undefined;
10506
- const identity = newIdentity();
10507
- const creds = await mintCreds(this.auth, identity, "provisioner");
10508
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
10509
- try {
10510
- const recordsKv = await new Kvm(nc).open(recordsBucket(this.space));
10511
- return (await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, alias))?.row;
10512
- }
10513
- finally {
10514
- await drainAndClose(nc);
10515
- }
9699
+ return this.staticLifecycle.reportChatSessionsLeftAtStop(why);
10516
9700
  }
10517
- scheduleStaticReconcileRetry(key, item) {
10518
- if (this.staticReconcileStopping || item.timer || item.attempts >= item.maxAttempts)
10519
- return;
10520
- const delay = this.staticReconcileRetryDelaysMs[item.attempts - 1];
10521
- if (delay === undefined)
10522
- return;
10523
- const nextRetryAtMs = Date.now() + delay;
10524
- item.disposition = "retry-scheduled";
10525
- item.nextRetryAt = new Date(nextRetryAtMs).toISOString();
10526
- item.timer = setTimeout(() => {
10527
- item.timer = undefined;
10528
- item.nextRetryAt = undefined;
10529
- const run = async () => {
10530
- // The timer may fire while the failed attempt is still unwinding, especially in compressed
10531
- // smoke schedules. Join that flight before consuming another budget entry; never overlap it.
10532
- if (item.flight)
10533
- await item.flight;
10534
- await this.retryStaticReconcile(key);
10535
- };
10536
- void run().catch((error) => {
10537
- item.lastError = `retry driver failed before the exact terminal: ${rejectionText(error)}`;
10538
- item.disposition = "retry-exhausted";
10539
- item.remedy = "restart this manager for a fresh per-process retry budget";
10540
- console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
10541
- });
10542
- }, delay);
10543
- item.timer.unref?.();
10544
- console.error(`! static reconcile retry-scheduled alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts + 1}/${item.maxAttempts} nextRetryAt=${item.nextRetryAt}`);
10545
- }
10546
- retryStaticReconcile(key) {
10547
- const item = this.staticReconcileItems.get(key);
10548
- if (!item || this.staticReconcileStopping || item.disposition === "recovered")
10549
- return Promise.resolve();
10550
- if (item.retryFlight)
10551
- return item.retryFlight;
10552
- const flight = this.driveStaticReconcileRetry(key, item);
10553
- let wrapped;
10554
- wrapped = flight.finally(() => {
10555
- if (item.retryFlight === wrapped)
10556
- item.retryFlight = undefined;
10557
- });
10558
- item.retryFlight = wrapped;
10559
- return wrapped;
10560
- }
10561
- async driveStaticReconcileRetry(key, item) {
10562
- if (item.flight)
10563
- await item.flight;
10564
- if (this.staticReconcileStopping || item.disposition === "recovered")
10565
- return;
10566
- // A retry trigger consumes one finite budget entry even if the authoritative re-read itself
10567
- // fails. Otherwise a broker outage before the planner could reschedule forever without ever
10568
- // incrementing `attempts`, violating the bounded-retry guarantee.
10569
- item.attempts++;
10570
- item.disposition = "retrying";
10571
- item.remedy = undefined;
10572
- console.error(`static reconcile retrying alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
10573
- let row;
10574
- try {
10575
- row = await this.readStaticReconcileSlot(item.alias);
10576
- }
10577
- catch (error) {
10578
- item.lastError = `durable slot re-read failed: ${rejectionText(error)}`;
10579
- if (item.attempts >= item.maxAttempts) {
10580
- item.disposition = "retry-exhausted";
10581
- item.remedy = "restart this manager for a fresh per-process retry budget";
10582
- console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
10583
- }
10584
- else {
10585
- this.scheduleStaticReconcileRetry(key, item);
10586
- }
10587
- return;
10588
- }
10589
- if (row === undefined || row.owner !== item.owner || row.actor !== item.actor || row.lifecycleUid !== item.lifecycleUid) {
10590
- item.disposition = "refused";
10591
- item.remedy = "inspect the durable slot; reconciliation will not cross incarnations";
10592
- item.lastError = row === undefined
10593
- ? "the durable slot vanished; reconciliation never acts from the in-memory snapshot"
10594
- : `the durable slot moved to actor ${row.actor} uid ${row.lifecycleUid}; reconciliation never crosses incarnations`;
10595
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10596
- return;
10597
- }
10598
- item.phase = row.phase;
10599
- if (row.phase === "retired") {
10600
- item.disposition = "recovered";
10601
- item.recoveredAt = new Date().toISOString();
10602
- item.lastError = undefined;
10603
- console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
10604
- return;
10605
- }
10606
- if (ownedBySibling(row, this.managerInstanceId)) {
10607
- item.disposition = "refused";
10608
- item.remedy = "the owning manager must reconcile or an operator must perform an explicit CAS takeover";
10609
- item.lastError = `the durable slot belongs to manager instance ${row.ownerInstanceId}, not ${this.managerInstanceId}`;
10610
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10611
- return;
10612
- }
10613
- const live = this.agents.get(row.alias);
10614
- const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
10615
- if (planStaticSlotResume(row, adopted) !== "drive-terminal") {
10616
- item.disposition = "refused";
10617
- item.remedy = adopted ? "leave the adopted live lifecycle running" : "inspect the fresh durable slot state";
10618
- item.lastError = adopted
10619
- ? "the durable lifecycle is now backed by an adopted live managed agent"
10620
- : `the fresh durable phase ${row.phase} is not terminal-plannable`;
10621
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10622
- return;
10623
- }
10624
- await this.attemptStaticReconcile(key, item, row, false);
10625
- }
10626
- /** Enter one exact terminal at most once per coordinate. Sweep and timer triggers join the same
10627
- * promise. A settled failed item keeps its original per-process budget; a restart builds a fresh
10628
- * map from the still-authoritative durable row. */
10629
- attemptStaticReconcile(key, item, row, countAttempt = true) {
10630
- if (item.flight)
10631
- return item.flight;
10632
- if (item.timer)
10633
- return Promise.resolve({ succeeded: false });
10634
- // A timer/retry driver increments before its mandatory durable re-read, then calls with
10635
- // countAttempt=false. Let that already-consumed budget entry enter the terminal. Only a fresh
10636
- // sweep entry (countAttempt=true) is refused once the per-process budget is exhausted.
10637
- if (countAttempt && item.attempts >= item.maxAttempts)
10638
- return Promise.resolve({ succeeded: false });
10639
- const flight = (async () => {
10640
- if (countAttempt)
10641
- item.attempts++;
10642
- item.phase = row.phase;
10643
- item.disposition = "retrying";
10644
- item.nextRetryAt = undefined;
10645
- this.reconcilingAliases.add(row.alias);
10646
- console.error(`static reconcile terminal alias=${row.alias} phase=${row.phase} uid=${row.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
10647
- let deprovision;
10648
- try {
10649
- await this.withRetirementSlot(() => this.driveStaticRetirement({ id: row.actor, name: row.alias, lifecycleUid: row.lifecycleUid, runtime: row.runtime }, true, (accounting) => { deprovision = accounting; }));
10650
- if (item.attempts === 1) {
10651
- this.staticReconcileItems.delete(key);
10652
- }
10653
- else {
10654
- item.phase = "retired";
10655
- item.disposition = "recovered";
10656
- item.recoveredAt = new Date().toISOString();
10657
- item.lastError = undefined;
10658
- console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
10659
- }
10660
- return { succeeded: true, deprovision };
10661
- }
10662
- catch (error) {
10663
- item.lastError = rejectionText(error);
10664
- try {
10665
- const fresh = await this.readStaticReconcileSlot(item.alias);
10666
- if (fresh?.lifecycleUid === item.lifecycleUid && fresh.actor === item.actor)
10667
- item.phase = fresh.phase;
10668
- }
10669
- catch { /* the terminal error remains primary; the next retry re-reads authoritatively */ }
10670
- const blocked = lifecycleBlockedFrom(error);
10671
- const ownOp = managedRetirementOpId(item.lifecycleUid);
10672
- const foreign = blocked !== undefined && (blocked.blockedOp !== "retirement" || blocked.opId !== ownOp);
10673
- if (foreign) {
10674
- item.disposition = "refused-foreign";
10675
- item.remedy = blocked?.remedy ?? "resolve the foreign durable operation; it is never force-cleared";
10676
- console.error(`! static reconcile refused-foreign alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10677
- }
10678
- else if (item.attempts >= item.maxAttempts) {
10679
- item.disposition = "retry-exhausted";
10680
- item.remedy = "restart this manager for a fresh per-process retry budget";
10681
- console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
10682
- }
10683
- else {
10684
- // The initial serial sweep must publish its complete failed aggregate before any timer can
10685
- // re-enter a middle row. Mark it now; the sweep arms the timer after its last planned row.
10686
- if (this.staticReconcileSweepsInFlight > 0)
10687
- item.disposition = "retry-scheduled";
10688
- else
10689
- this.scheduleStaticReconcileRetry(key, item);
10690
- }
10691
- return { succeeded: false, deprovision };
10692
- }
10693
- finally {
10694
- this.reconcilingAliases.delete(row.alias);
10695
- }
10696
- })();
10697
- item.flight = flight.finally(() => {
10698
- if (item.flight === wrapped)
10699
- item.flight = undefined;
10700
- });
10701
- const wrapped = item.flight;
10702
- return wrapped;
9701
+ renewManagedStaticCred(a) {
9702
+ return this.staticLifecycle.renewManagedStaticCred(a);
10703
9703
  }
10704
- releaseStaticReconcileSweep() {
10705
- this.staticReconcileSweepsInFlight--;
10706
- if (this.staticReconcileSweepsInFlight !== 0)
10707
- return;
10708
- const waiters = this.staticReconcileDrainWaiters;
10709
- this.staticReconcileDrainWaiters = [];
10710
- for (const wake of waiters)
10711
- wake();
9704
+ readStaticReconcileSlot(alias) {
9705
+ return this.staticLifecycle.readStaticReconcileSlot(alias);
10712
9706
  }
10713
- /** Shutdown accepts no new static reconciliation work, then drains every sweep and exact-terminal
10714
- * flight that crossed the fence before stop(). A sweep can discover several rows before its first
10715
- * await, so the serial loop also consults the fence and never starts a later row after shutdown. */
10716
- async awaitStaticReconcileDrain() {
10717
- while (true) {
10718
- if (this.staticReconcileSweepsInFlight > 0)
10719
- await new Promise((resolve) => this.staticReconcileDrainWaiters.push(resolve));
10720
- const flights = [];
10721
- for (const item of this.staticReconcileItems.values()) {
10722
- if (item.flight)
10723
- flights.push(item.flight);
10724
- if (item.retryFlight)
10725
- flights.push(item.retryFlight);
10726
- }
10727
- if (flights.length === 0 && this.staticReconcileSweepsInFlight === 0)
10728
- return;
10729
- await Promise.allSettled(flights);
10730
- }
9707
+ awaitStaticReconcileDrain() {
9708
+ return this.staticLifecycle.awaitStaticReconcileDrain();
10731
9709
  }
10732
- async reconcileStaticLifecycles(postAdoption = false) {
10733
- if (!this.auth || this.staticReconcileStopping)
10734
- return;
10735
- // Admission is synchronous with the shutdown fence. Once this increments, stop() must drain the
10736
- // whole accepted sweep even if it is still minting its short-lived provisioner credential.
10737
- this.staticReconcileSweepsInFlight++;
10738
- try {
10739
- // Recovered is a transition report, not permanent history. The next sweep clears it before
10740
- // deriving a fresh plan; failed coordinates keep their per-process budget and are joined.
10741
- for (const [key, item] of this.staticReconcileItems) {
10742
- if (item.disposition === "recovered")
10743
- this.staticReconcileItems.delete(key);
10744
- }
10745
- const sweep = {
10746
- kind: postAdoption ? "post-adoption" : "startup",
10747
- startedAt: new Date().toISOString(),
10748
- attempted: 0,
10749
- succeeded: 0,
10750
- failed: 0,
10751
- };
10752
- this.staticReconcileLastSweep = sweep;
10753
- const slotRows = [];
10754
- // A sweep that stops before it plans any alias records why on the sweep itself: otherwise
10755
- // `status` cannot tell it from a sweep that collected and found nothing.
10756
- try {
10757
- const identity = newIdentity();
10758
- const creds = await mintCreds(this.auth, identity, "provisioner");
10759
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
10760
- try {
10761
- const jsm = await jetstreamManager(nc);
10762
- const kvm = new Kvm(nc);
10763
- await ensureAuthorityStores(jsm, kvm, this.space);
10764
- const recordsKv = await kvm.open(recordsBucket(this.space));
10765
- for (const slot of await walkStaticSlots(recordsKv, DEV_OWNER))
10766
- slotRows.push(slot.row);
10767
- }
10768
- finally {
10769
- await drainAndClose(nc);
10770
- }
10771
- }
10772
- catch (error) {
10773
- sweep.completedAt = new Date().toISOString();
10774
- sweep.error = rejectionText(error);
10775
- throw error;
10776
- }
10777
- let retiredSlots = 0;
10778
- let preservedForeign = 0;
10779
- let preservedAdopted = 0;
10780
- let deferredSlots = 0;
10781
- const terminalRows = [];
10782
- const restartRows = [];
10783
- for (const row of slotRows) {
10784
- if (row.phase === "retired") {
10785
- // A retirement is a GLOBAL refusal fact — seed the retired-principal index for EVERY retired incarnation
10786
- // regardless of which instance owned it, so a sibling-retired incarnation's copied credential
10787
- // is refused at this control surface too. Ownership gates only the DESTRUCTIVE sweep below.
10788
- this.retirement.rememberRetired(principalKey(row.owner, row.actor).key);
10789
- retiredSlots++;
10790
- continue;
10791
- }
10792
- // RECONCILE OWNERSHIP (multi-manager-per-space): a manager adjudicates ONLY the non-retired
10793
- // rows THIS logical instance owns. A SIBLING manager's active/provisioning row is LEFT UNTOUCHED —
10794
- // sweep-terminalizing it would destroy the sibling's live agent (the historical all-agents-kill
10795
- // hazard, now cross-instance). A legacy row (no owner recorded) predates multi-manager,
10796
- // so this manager is its legitimate single-manager-past successor and reconciles it. An orphaned
10797
- // sibling row is reclaimed only by an explicit operator CAS takeover, never here.
10798
- if (ownedBySibling(row, this.managerInstanceId)) {
10799
- preservedForeign++;
10800
- continue;
10801
- }
10802
- // A chat session this process is opening or holds is live membership, as an adopted seat
10803
- // is: its own open, expiry or stop runs its terminal, which this sweep must not race. The
10804
- // match is the exact registered alias, actor and UID under this logical instance and this
10805
- // process's incarnation, so a foreign, legacy or unrecorded row, or any UID this process
10806
- // did not register, falls through to the ordinary plan below.
10807
- if (this.holdsLiveChatSlot(row)) {
10808
- preservedAdopted++;
10809
- continue;
10810
- }
10811
- // ADOPTION is genuine membership: a slot backed by a live managed agent THIS process owns
10812
- // at the SAME uid is never an orphan (empty at boot; exactly the adopted set at the
10813
- // post-adoption sweep — the fix for the resume hole).
10814
- const live = this.agents.get(row.alias);
10815
- const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
10816
- if (adopted) {
10817
- preservedAdopted++;
10818
- }
10819
- // Boot sweep with a resume PENDING: an active slot may yet be adopted (the resume path runs
10820
- // AFTER this boot sweep), so DEFER it — the post-adoption sweep terminalizes any the resume
10821
- // did not claim. provisioning/terminalizing NEVER defer (they are crashed operations, never
10822
- // an agent to adopt). At `postAdoption` (or a non-resume boot) nothing defers.
10823
- if (!postAdoption && row.phase === "active" && !adopted && this.resumeRequired) {
10824
- deferredSlots++;
10825
- continue;
10826
- }
10827
- // A boot after this instance's manager ended without stopping its seats: a seat with a record
10828
- // is taken back instead of retired, restarted under its policy when supervised (#4094) and
10829
- // adopted while it still runs otherwise (#4095).
10830
- if (!postAdoption && row.phase === "active" && !adopted) {
10831
- const record = this.seatRecordFor(row);
10832
- if (record) {
10833
- restartRows.push({ row, record });
10834
- continue;
10835
- }
10836
- }
10837
- if (planStaticSlotResume(row, adopted) !== "none")
10838
- terminalRows.push(row);
10839
- }
10840
- try {
10841
- // Mark the complete planned set before the first terminal awaits. A timer owns only its own
10842
- // alias, but the initial serial sweep must close every discovery-to-await gap up front.
10843
- for (const row of terminalRows)
10844
- this.reconcilingAliases.add(row.alias);
10845
- for (const { row } of restartRows)
10846
- this.reconcilingAliases.add(row.alias);
10847
- // Restarts run first; one that cannot restart joins the terminals below.
10848
- for (const { row, record } of restartRows) {
10849
- if (this.staticReconcileStopping)
10850
- break;
10851
- // A supervised seat is restarted; any other seat is adopted while it still runs.
10852
- const refusal = record.supervise ? await this.restartSupervisedSeat(row, record) : await this.adoptSeat(row, record);
10853
- if (refusal === undefined) {
10854
- this.reconcilingAliases.delete(row.alias);
10855
- continue;
10856
- }
10857
- console.error(record.supervise
10858
- ? `! ${row.alias}: the supervised seat its previous manager left was not restarted (${refusal}); retiring the lifecycle`
10859
- : `! ${row.alias}: the seat its previous manager left was not adopted (${refusal}); retiring the lifecycle`);
10860
- this.dropSeatRecord({ name: row.alias, lifecycleUid: row.lifecycleUid });
10861
- terminalRows.push(row);
10862
- }
10863
- const sweepDeprovision = {
10864
- examined: 0,
10865
- deleted: 0,
10866
- absent: 0,
10867
- refused: 0,
10868
- acknowledged: 0,
10869
- disappeared: 0,
10870
- consumers: { examined: 0, deleted: 0, absent: 0, refused: 0, acknowledged: 0, disappeared: 0 },
10871
- acls: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
10872
- members: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
10873
- };
10874
- for (const row of terminalRows) {
10875
- if (this.staticReconcileStopping)
10876
- break;
10877
- sweep.attempted++;
10878
- const key = this.staticReconcileKey(row);
10879
- let item = this.staticReconcileItems.get(key);
10880
- if (!item) {
10881
- item = {
10882
- owner: row.owner,
10883
- alias: row.alias,
10884
- actor: row.actor,
10885
- lifecycleUid: row.lifecycleUid,
10886
- phase: row.phase,
10887
- attempts: 0,
10888
- maxAttempts: STATIC_RECONCILE_MAX_ATTEMPTS,
10889
- disposition: "retrying",
10890
- };
10891
- this.staticReconcileItems.set(key, item);
10892
- }
10893
- const attempt = await this.attemptStaticReconcile(key, item, row);
10894
- if (attempt.deprovision)
10895
- addDeprovisionAccounting(sweepDeprovision, attempt.deprovision);
10896
- if (attempt.succeeded)
10897
- sweep.succeeded++;
10898
- else
10899
- sweep.failed++;
10900
- this.reconcilingAliases.delete(row.alias);
10901
- }
10902
- sweep.completedAt = new Date().toISOString();
10903
- this.staticReconcileLastSweepResources = {
10904
- slots: {
10905
- examined: slotRows.length,
10906
- retired: retiredSlots,
10907
- preservedForeign,
10908
- preservedAdopted,
10909
- deferred: deferredSlots,
10910
- terminalized: sweep.succeeded,
10911
- failed: sweep.failed,
10912
- },
10913
- deprovision: sweepDeprovision,
10914
- };
10915
- for (const row of terminalRows) {
10916
- const key = this.staticReconcileKey(row);
10917
- const item = this.staticReconcileItems.get(key);
10918
- if (item?.disposition === "retry-scheduled" && !item.timer)
10919
- this.scheduleStaticReconcileRetry(key, item);
10920
- }
10921
- const failed = terminalRows.flatMap((row) => {
10922
- const item = this.staticReconcileItems.get(this.staticReconcileKey(row));
10923
- return item && item.disposition !== "recovered" ? [`${item.alias}:${item.phase}:${item.disposition}`] : [];
10924
- });
10925
- if (sweep.failed === 0) {
10926
- console.error(`✓ static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, 0 failed`);
10927
- }
10928
- else {
10929
- console.error(`! static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, ${sweep.failed} failed; failed=${failed.join(",")}`);
10930
- }
10931
- }
10932
- finally {
10933
- for (const row of terminalRows)
10934
- this.reconcilingAliases.delete(row.alias);
10935
- for (const { row } of restartRows)
10936
- this.reconcilingAliases.delete(row.alias);
10937
- }
10938
- }
10939
- finally {
10940
- this.releaseStaticReconcileSweep();
10941
- }
9710
+ reconcileStaticLifecycles(postAdoption = false) {
9711
+ return this.staticLifecycle.reconcileStaticLifecycles(postAdoption);
10942
9712
  }
10943
9713
  /** The membership gate: decide a control caller by its
10944
9714
  * AUTHENTICATED wire principal. A LIVE managed slot passes (unless terminalizing); a RETIRING