@cotal-ai/manager 0.166.3 → 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.
Files changed (42) hide show
  1. package/dist/attach-endpoint.d.ts.map +1 -1
  2. package/dist/attach-endpoint.js +2 -0
  3. package/dist/attach-endpoint.js.map +1 -1
  4. package/dist/console/app.js +12 -1
  5. package/dist/console/session-bundle.js +2 -0
  6. package/dist/lease-keeper.d.ts +98 -0
  7. package/dist/lease-keeper.d.ts.map +1 -0
  8. package/dist/lease-keeper.js +257 -0
  9. package/dist/lease-keeper.js.map +1 -0
  10. package/dist/managed-static-lifecycle.d.ts +247 -0
  11. package/dist/managed-static-lifecycle.d.ts.map +1 -0
  12. package/dist/managed-static-lifecycle.js +926 -0
  13. package/dist/managed-static-lifecycle.js.map +1 -0
  14. package/dist/manager-timeout.d.ts +5 -0
  15. package/dist/manager-timeout.d.ts.map +1 -0
  16. package/dist/manager-timeout.js +11 -0
  17. package/dist/manager-timeout.js.map +1 -0
  18. package/dist/manager.d.ts +201 -508
  19. package/dist/manager.d.ts.map +1 -1
  20. package/dist/manager.js +337 -3086
  21. package/dist/manager.js.map +1 -1
  22. package/dist/names-capacity.d.ts +125 -0
  23. package/dist/names-capacity.d.ts.map +1 -0
  24. package/dist/names-capacity.js +236 -0
  25. package/dist/names-capacity.js.map +1 -0
  26. package/dist/retirement.d.ts +221 -0
  27. package/dist/retirement.d.ts.map +1 -0
  28. package/dist/retirement.js +480 -0
  29. package/dist/retirement.js.map +1 -0
  30. package/dist/seat-custody.d.ts +100 -0
  31. package/dist/seat-custody.d.ts.map +1 -0
  32. package/dist/seat-custody.js +320 -0
  33. package/dist/seat-custody.js.map +1 -0
  34. package/dist/serve-plane.d.ts +228 -0
  35. package/dist/serve-plane.d.ts.map +1 -0
  36. package/dist/serve-plane.js +664 -0
  37. package/dist/serve-plane.js.map +1 -0
  38. package/dist/session-recovery.d.ts +115 -0
  39. package/dist/session-recovery.d.ts.map +1 -0
  40. package/dist/session-recovery.js +350 -0
  41. package/dist/session-recovery.js.map +1 -0
  42. package/package.json +12 -12
package/dist/manager.js CHANGED
@@ -7,47 +7,52 @@ 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, deprovisionAgent, 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, AUTH_ENDPOINT, EP_CMD_RETIRE_LIFECYCLE, eventChannel, eventChannelPrincipal, resolveService, invokeCommand, 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, claimManagerSiblingIdentities, 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";
13
- import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, RuntimeReapUnproven, watchProvedExit, } from "./runtime/index.js";
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
+ import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
14
+ import { Retirement } from "./retirement.js";
15
+ import { ServePlane } from "./serve-plane.js";
16
+ import { NamesCapacity } from "./names-capacity.js";
14
17
  import { AttachEndpoint } from "./attach-endpoint.js";
15
- 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";
16
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";
24
+ import { SessionRecovery } from "./session-recovery.js";
25
+ import { SeatCustody } from "./seat-custody.js";
26
+ import { withTimeout } from "./manager-timeout.js";
17
27
  import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
18
- import { inlinePersonaDir, inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment, writeContinuityAssignment } from "./launch.js";
28
+ import { inlinePersonaDir, inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment } from "./launch.js";
19
29
  import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
20
30
  import { controlShutdown } from "./control-shutdown.js";
21
31
  import { RunHosting, servedRequestSubject } from "./run-hosting.js";
22
32
  import { enrolledAcl } from "./remote-authority.js";
23
33
  import { pendingEnrollment } from "./pending-enrollment.js";
24
34
  import { rejectionText, attemptCleanup, describeCleanupFailures } from "@cotal-ai/core";
25
- import { controlSession } from "./control-session.js";
26
- import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, removeReleasedSeatReference, removeSeatRecord, supervisePolicy, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
35
+ import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, supervisePolicy, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
27
36
  import { TranscriptReceiver } from "./transcript-receive.js";
28
37
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
29
38
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
30
39
  import { jetstream, jetstreamManager } from "@nats-io/jetstream";
31
40
  import { Kvm } from "@nats-io/kv";
32
- import { recordsBucket, epAuthBucket, ensureAuthorityStores, createEndpointStreams, contractStoreContext, publishContractArtifact, contractArtifactCanonicalBytes, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, issuedHorizon, newArtifactSigner, RotatingSigner, generationAnchor, sessionsBucket, SESSION_GRANT_MAX_TTL_MS, 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";
33
42
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
34
43
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
35
44
  // per-session credentials on their own short-lived connections).
36
- import { ManagerSessionPlane, openSessionLedgerKv } from "./session/index.js";
45
+ import { ManagerSessionPlane } from "./session/index.js";
37
46
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
38
47
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
39
48
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
40
- import { provisionEndpointGateOpen, endpointRegistrationBarrier, serveIssuanceGateKv, commitSiblingIssuance, markLedgerRowRevoked, epcredRowKey, epgateKey, parseEndpointGate, readEndpointGateGeneration, registerServingInstance, deregisterServiceInstance, serveEndpoint, 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";
41
- import { MANAGER_ENDPOINT, managerClusterArtifacts, managerCommandDefs, managerContractArtifactValues } from "./manager-service-contract.js";
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";
50
+ import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
42
51
  import { measureManagerVitals } from "./vitals.js";
43
- import { staticLifecycleTransport, activateStaticLifecycle, runStaticTerminal, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, planStaticSlotResume, ownedBySibling, observeStaticSlot, listStaticSlotObservations, walkStaticSlots, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
44
- 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";
45
54
  // Capture the loaded package version before an installation can replace its files.
46
55
  const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
47
- /** Minimum slot lifetime for rate-flooring (P4c). A slot freed (by despawn OR natural exit/reap)
48
- * before living this long leaves a cooling stamp that still counts toward the ceiling until it
49
- * expires — so churn (spawn↔despawn or spawn↔fast-exit) can't outrun the concurrency bound. */
50
- const MIN_LIFETIME = 10_000;
51
56
  /** Cadence of the turn-deadline sweep while turns are pending: the poll that turns an elapsed
52
57
  * hold's fire into its expired settle and commits the deadline terminal. Deadlines are
53
58
  * minutes-scale; a few seconds of lateness on the commit is invisible to the run. */
@@ -93,26 +98,11 @@ const LATE_JOIN_POLL_MS = 1_000;
93
98
  * must run without exiting before it is ready: long enough that a harness refusing its arguments
94
99
  * exits first and is reported as failed. */
95
100
  const OPERATOR_READINESS_MS = 3_000;
96
- /** Managed same-session crash recovery follows the Codex host precedent: three restarts are allowed
97
- * inside a rolling two-minute window; the fourth crash is a loop and retires the seat loud. */
98
- const SESSION_RESTART_LIMIT = 3;
99
- const SESSION_RESTART_WINDOW_MS = 120_000;
100
- const RESTART_WORK_EXIT_MS = 10_000;
101
101
  /** Upper bound on a detached agent-exit deprovision (#159 B2). A wedged broker must not leave the
102
102
  * fire-and-forget teardown pending forever with no log — past this it rejects into freeSlot's fail-loud
103
103
  * `.catch`. Generous over the helper's 5s connect timeout to allow the two consumer-deletes + ACL purge
104
104
  * + drain on a healthy-but-slow broker. */
105
105
  const DEPROVISION_TIMEOUT_MS = 15_000;
106
- /** How long a clean stop keeps trying to release its liveness lease when the broker does not answer
107
- * (#3916). The client redials a lost broker every 2 s, so a connection dropped by an outage of up to
108
- * about 3 s is back inside this budget. A longer outage is left to the row's TTL: the stop's other
109
- * steps also wait on the broker, and the whole stop must still finish inside the 15 s a CLI stop
110
- * waits before it sends SIGKILL. */
111
- const LEASE_RELEASE_BUDGET_MS = 5_000;
112
- /** The pause between lease release attempts that got no answer. An attempt that waits for its own
113
- * deadline already spaces the retries; this only keeps one that fails at once, on a closed
114
- * connection, from spinning. */
115
- const LEASE_RELEASE_RETRY_MS = 250;
116
106
  /** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
117
107
  * connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
118
108
  * each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
@@ -174,13 +164,7 @@ export function credRenewIntervalMs(ttlSeconds) {
174
164
  * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
175
165
  * a reuse. */
176
166
  const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
177
- /** One initial terminal entry plus three re-drives. The short first retry absorbs a one-shot
178
- * broker/eviction blip; the wider later spacing avoids hammering a persistently unavailable
179
- * authority. The finite ~36s window is intentionally not a liveness inference: exhausting it
180
- * leaves the durable alias held and requires a later manager start. */
181
- export const STATIC_RECONCILE_RETRY_DELAYS_MS = [1_000, 5_000, 30_000];
182
167
  const REMOTE_STANDING_BUDGET_MS = 10_000;
183
- const STATIC_RECONCILE_MAX_ATTEMPTS = STATIC_RECONCILE_RETRY_DELAYS_MS.length + 1;
184
168
  /** The owner a retained seat resumes under: its inventory identity's, which is the same value the
185
169
  * adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
186
170
  * it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
@@ -239,15 +223,6 @@ function failedTerminal(error, source) {
239
223
  catch { /* unreadable or not interchangeable */ }
240
224
  return { error: text };
241
225
  }
242
- /** Reject `p` with `Error(msg)` if it hasn't settled within `ms`; clears the timer when `p` settles so it
243
- * never keeps the loop alive. Used to bound the detached deprovision so its fail-loud log is guaranteed. */
244
- function withTimeout(p, ms, msg) {
245
- let timer;
246
- const timeout = new Promise((_, reject) => {
247
- timer = setTimeout(() => reject(new Error(msg)), ms);
248
- });
249
- return Promise.race([p.finally(() => clearTimeout(timer)), timeout]);
250
- }
251
226
  /** One absolute budget across authority, preflight and adoption waits, or one closed-serve attempt. */
252
227
  function remoteStandingTimeLeft(deadline) {
253
228
  const left = deadline - performance.now();
@@ -296,25 +271,6 @@ function ownPersona(record) {
296
271
  });
297
272
  return owned;
298
273
  }
299
- /** `start()`'s refusal when this manager instance's lease is held (#3915): by another live process
300
- * on this workspace root, or by a holder on another root. A restart whose predecessor on this root
301
- * is dead, this process's own earlier start included, waits the key out instead (#4092). The
302
- * message is the operator copy; `held` and `sameRoot` are the data, so no caller parses it. A
303
- * lease that could not be read or written is a plain `Error`. */
304
- export class ManagerInstanceLeaseHeld extends Error {
305
- instanceId;
306
- space;
307
- held;
308
- sameRoot;
309
- name = "ManagerInstanceLeaseHeld";
310
- constructor(message, instanceId, space, held, sameRoot) {
311
- super(message);
312
- this.instanceId = instanceId;
313
- this.space = space;
314
- this.held = held;
315
- this.sameRoot = sameRoot;
316
- }
317
- }
318
274
  /** Operator-facing phrasing per cause. Kept beside the union so adding a member without a sentence
319
275
  * is a type error rather than a blank in the log. The stop family's sentences carry the principal
320
276
  * from the cause, so they render through {@link STOP_CAUSE_TEXT} under the same exhaustive-Record
@@ -332,23 +288,6 @@ const FREE_SLOT_CAUSE_TEXT = {
332
288
  "supervise-record-failed": "this manager stopped it: its supervise policy could not be recorded for a manager restart",
333
289
  "inline-snapshot-changed": "this manager retired it instead of restarting it: its inline persona snapshot changed after launch",
334
290
  };
335
- /** The SPEC 13.6 end reason a live attach session gets when this cause frees its seat. The causes
336
- * that free the slot in the same step that saw the seat's own process exit report `process-exit`.
337
- * A failed recovery frees it later, after its own stop, so it reports `target-despawn` with every
338
- * manager stop. */
339
- const FREE_SLOT_ATTACH_END = {
340
- "process-exit": "process-exit",
341
- "pi-crash-loop": "process-exit",
342
- "supervise-crash-loop": "process-exit",
343
- "inline-snapshot-changed": "process-exit",
344
- "pi-recovery-failed": "target-despawn",
345
- "supervise-recovery-failed": "target-despawn",
346
- "session-bind-failed": "target-despawn",
347
- "resume-session-rebind-failed": "target-despawn",
348
- "carried-fork-refused": "target-despawn",
349
- "resume-custody-unrecorded": "target-despawn",
350
- "supervise-record-failed": "target-despawn",
351
- };
352
291
  /** The stop family's sentences — the same job {@link FREE_SLOT_CAUSE_TEXT} does for the string
353
292
  * causes, beside it so both stay the single place a cause becomes a sentence. A requested stop's
354
293
  * sentence embeds the authenticated principal and a recursive reap's embeds the parent that
@@ -604,55 +543,9 @@ export class Manager {
604
543
  preserveStopTimeoutMs;
605
544
  endpointServeExecutorExpiresInSeconds;
606
545
  agents = new Map();
607
- /** Names whose spawn is in flight (reserved synchronously before the provision await) — counted
608
- * toward the ceiling (once per name, see {@link Manager.occupancy}) so two concurrent same-name
609
- * spawns can't both pass the gate (P4a). Each name carries the OWNER its launch was admitted
610
- * for, so the per-owner ceiling ({@link Manager.ownerSeats}) counts a launch from the moment it
611
- * is reserved; a cap read only off `agents` would let a burst of concurrent spawns overshoot it,
612
- * because none of them has a seat yet when the next one checks. */
613
- reserved = new Map();
614
- /** Reserved names whose launch already put its seat in `agents`. The name stays reserved until
615
- * the launch settles, so no other spawn can take it, but the ceiling counts that seat through
616
- * `agents` and, if it frees young, its cooling stamp, never through the reservation (#906). */
617
- reservedLive = new Set();
618
- /** Every numbered name {@link uniqueName} has issued. A suffix carries nothing but arrival order,
619
- * so reissuing a freed one would give a later principal the name an earlier one posted under, and
620
- * a reader of that name could not tell the two apart (#382). Never pruned in-process: one string
621
- * per numbered spawn. */
622
- issuedNumberedNames = new Set();
623
546
  /** Lifecycle UIDs already handed to `Runtime.spawnDelegated`: a lifecycle is handed off at most
624
547
  * once, so a lost create acknowledgement can never become a second create. */
625
548
  delegatedLaunched = new Set();
626
- /** Expiry stamps (`startedAt + MIN_LIFETIME`) for slots that freed while still young — a
627
- * count-only, lazily-pruned recycle floor (P4c). Pruned + summed into the ceiling gate. */
628
- cooling = [];
629
- /** Names RESERVED PENDING RETIREMENT: a despawned agent's name stays held until
630
- * the auth plane confirms its lifecycle's retirement TERMINAL over the auth-admin rail — the
631
- * alias-reuse gate that closes the same-name despawn→respawn race at its root. An UNCERTAIN
632
- * outcome (rail down, timeout) keeps the hold with the last attempt's copy; a same-name spawn
633
- * refuses legibly AND re-fires the request. In-memory: across a manager restart the durable
634
- * truth is the auth-side lifecycle head itself (an unretired head refuses issuance — the
635
- * named residual this belt narrows, not replaces). */
636
- retiring = new Map();
637
- /** Exact predecessor incarnations whose full hosted retirement reached a terminal answer. Presence
638
- * is advisory and can retain that old lifecycle briefly after its process exits. Resume may ignore
639
- * only this exact (alias, principal, lifecycleUid) row when adopting a different lifecycle; every
640
- * unknown, current, or differently identified live row still refuses. A later retirement of the
641
- * same alias replaces its prior predecessor coordinate. */
642
- confirmedRetiredPredecessors = new Map();
643
- /** SINGLE-FLIGHT guard for {@link requestRetirement} (audit #1): one in-flight rail round-trip per
644
- * (name, lifecycleUid). The detached `deprovision` call and every same-name-spawn nudge for THAT
645
- * lifecycle JOIN the same promise instead of stacking independent requests that dual-enter the
646
- * barrier; a fresh trigger after it settles re-drives. Keyed by (name, uid) — NOT name alone — so a
647
- * same-name SUCCESSOR (which can spawn after the hold clears but before this flight's `nc.close`
648
- * yield settles) never joins the predecessor's rail request and skips its own retirement. */
649
- retiringFlight = new Map();
650
- /** Wire principals of RETIRED static incarnations: populated at every completed
651
- * static terminal and from the boot sweep's retired slot rows, so a copied credential of a
652
- * retired incarnation is refused at the control surface even across a manager restart. The
653
- * durable truth is the slot row + principal-keyed head; this set is the in-memory index of it
654
- * (one string per retired incarnation — bounded by lifecycle count, never pruned in-process). */
655
- retiredPrincipals = new Set();
656
549
  /** This manager process's own incarnation uid (SPEC 13.1; minted once per supervisor process,
657
550
  * never reused across restarts) — the endpoint's presence key AND the `managerInstance` audit
658
551
  * coordinate every static activation records. */
@@ -715,11 +608,6 @@ export class Manager {
715
608
  /** Renews the session signing key long before its window closes. A key that expires unattended
716
609
  * takes the whole session plane down until the manager is restarted, which kills live sessions. */
717
610
  sessionKeyRenewTimer;
718
- /** Maps credentialId → the nkey that credential was minted for, for the live per-session
719
- * SERVING credentials. The §13.1 ledger row records the holder principal, and the row is written
720
- * at stage time (after the mint), so the two steps need this one hop. Entries are dropped at
721
- * revoke; a session that never staged drops its entry when the manager exits. */
722
- sessionServingKeys = new Map();
723
611
  /** The STABLE session-LEDGER identity (auth mode) — minted once at registration
724
612
  * alongside the serve + goal-writer identities; a renewal re-mints the SAME nkey with a fresh
725
613
  * bounded exp and re-stages its distinct credId into the §13.1 revocation family. The current
@@ -799,26 +687,6 @@ export class Manager {
799
687
  connectorStatuses = [];
800
688
  /** The boot inventory's warnings, printed once start completes, so a refused start prints none. */
801
689
  bootNotes = [];
802
- /** Static aliases whose startup exact-op terminal is still in flight. Scoped per alias: control
803
- * serves during the sweep, but no caller can reuse or attach an alias the sweep still owns. */
804
- reconcilingAliases = new Set();
805
- /** In-flight static chat-session terminals, by lifecycle UID, so every caller that retires one
806
- * session joins one terminal instead of racing its CAS sequence. */
807
- chatRetirements = new Map();
808
- /** The expiry side of every chat session this process admitted and nothing retired sooner. */
809
- chatExpiry = new ChatSessionExpiry((session) => this.expireStaticChatSession(session), {
810
- retryDelaysMs: STATIC_RECONCILE_RETRY_DELAYS_MS,
811
- concurrency: CHAT_EXPIRY_CONCURRENCY,
812
- log: (line) => console.error(line),
813
- });
814
- /** Current failed/recovered static reconciliation coordinates. This is an operator snapshot, not
815
- * lifecycle authority: every re-drive re-reads broker KV and re-runs planStaticSlotResume. */
816
- staticReconcileItems = new Map();
817
- staticReconcileLastSweep;
818
- staticReconcileLastSweepResources;
819
- staticReconcileSweepsInFlight = 0;
820
- staticReconcileDrainWaiters = [];
821
- staticReconcileStopping = false;
822
690
  /** The complete boot task. stop() joins it after fencing static reconciliation, so a registration
823
691
  * already past an earlier shutdown check cannot finish after stop() returns. */
824
692
  startTask;
@@ -831,14 +699,6 @@ export class Manager {
831
699
  /** Held as an instance field so broker-owning smokes can compress the schedule without changing
832
700
  * production semantics. It is never a fence expiry: the durable non-retired row stays authoritative. */
833
701
  staticReconcileRetryDelaysMs = STATIC_RECONCILE_RETRY_DELAYS_MS;
834
- /** SINGLE-FLIGHT guard for {@link deprovision} (INT-2/C): one in-flight teardown per
835
- * (name, lifecycleUid). The detached freeSlot teardown and every same-name-spawn nudge that
836
- * re-drives it JOIN one promise instead of launching a SECOND, concurrent teardown. Without it,
837
- * two teardowns race the NAME-KEYED ledger revoke: once the first frees the alias and a successor
838
- * mints its own row, the second's delayed revoke (which carries no lifecycle coordinate) would
839
- * delete the SUCCESSOR's standing authority. Keyed by (name, uid) so a later same-name lifecycle
840
- * gets its own flight; a fresh trigger after settle re-drives only if the hold still stands. */
841
- deprovisioningFlight = new Map();
842
702
  /** Retirements holding one of the {@link RETIREMENT_CONCURRENCY} slots. */
843
703
  retirementsRunning = 0;
844
704
  /** Retirements waiting for a slot, oldest first. */
@@ -855,19 +715,136 @@ export class Manager {
855
715
  /** True on a USER-AUTH space (the on-disk marker; cross-checked against the registry at start).
856
716
  * Gates the whole spawn path: user mode grants ledger actors + bearer plumbing, never static mints. */
857
717
  userMode = false;
858
- leaseInfo;
859
- leaseRevision;
860
- leaseTimer;
861
- /** What the last renew tick learned about this instance's key. Only a CHANGE of state is printed
862
- * (see {@link noteLease}), so an outage of hours is one line going in and one line coming out. */
863
- leaseState = "held";
864
- /** A renew is in flight. The tick must not start a second one: both would read the same cached
865
- * revision, so whichever lands second CASes against a sequence the first already moved. */
866
- leaseRenewInFlight = false;
867
- /** The promise a currently in-flight `renewLease()` is running, so `stop()` can await it before
868
- * releasing the key instead of racing it: a renew that lands after the cached revision was read
869
- * for release would otherwise move the row out from under a same-cached-revision CAS delete. */
870
- leaseRenewTask;
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
+ });
740
+ servePlane = new ServePlane({
741
+ auth: () => this.auth,
742
+ remoteAuthority: () => this.remoteAuthority,
743
+ space: () => this.space,
744
+ servers: () => this.servers,
745
+ workspaceRoot: () => this.workspaceRoot,
746
+ managerInstanceId: () => this.managerInstanceId,
747
+ managerServeIdentity: () => this.managerServeIdentity,
748
+ leaseStopping: () => this.leaseStopping,
749
+ remoteBundleRenewal: () => this.remoteBundleRenewal,
750
+ maxSessions: () => this.maxSessions,
751
+ serviceServe: () => this.serviceServe,
752
+ setServiceServe: (value) => { this.serviceServe = value; },
753
+ sessionLedgerIdentity: () => this.sessionLedgerIdentity,
754
+ setSessionLedgerIdentity: (value) => { this.sessionLedgerIdentity = value; },
755
+ sessionLedgerCreds: () => this.sessionLedgerCreds,
756
+ setSessionLedgerCreds: (value) => { this.sessionLedgerCreds = value; },
757
+ sessionLedgerConn: () => this.sessionLedgerConn,
758
+ setSessionLedgerConn: (value) => { this.sessionLedgerConn = value; },
759
+ sessionPlane: () => this.sessionPlane,
760
+ setSessionPlane: (value) => { this.sessionPlane = value; },
761
+ sessionKeyRenewTimer: () => this.sessionKeyRenewTimer,
762
+ setSessionKeyRenewTimer: (value) => { this.sessionKeyRenewTimer = value; },
763
+ connectorStatuses: () => this.connectorStatuses,
764
+ setGoalWriterIdentity: (value) => { this.goalWriterIdentity = value; },
765
+ setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
766
+ remoteStandingBudgetMs: REMOTE_STANDING_BUDGET_MS,
767
+ dial: (...args) => this.dial(...args),
768
+ dialRemoteStanding: (...args) => this.dialRemoteStanding(...args),
769
+ trackTransport: (...args) => this.trackTransport(...args),
770
+ discardServeCandidate: (...args) => this.discardServeCandidate(...args),
771
+ managerServiceDefs: (...args) => this.managerServiceDefs(...args),
772
+ omitClassCommands: (...args) => this.omitClassCommands(...args),
773
+ resolveTarget: (target) => this.resolveServeTarget(target),
774
+ withEndpointServeExecutor: (...args) => this.withEndpointServeExecutor(...args),
775
+ withOpenServeConnection: (...args) => this.withOpenServeConnection(...args),
776
+ boundedReconnect: (...args) => this.boundedReconnect(...args),
777
+ renewRemoteBeforeRedial: (...args) => this.renewRemoteBeforeRedial(...args),
778
+ scheduleServeRenewal: (...args) => this.scheduleServeRenewal(...args),
779
+ stop: (...args) => this.stop(...args),
780
+ healFrozenRegistrationGate: (...args) => this.healFrozenRegistrationGate(...args),
781
+ mintAndStageGoalWriter: (...args) => this.mintAndStageGoalWriter(...args),
782
+ retireConnection: (...args) => this.retireConnection(...args),
783
+ withTimeout,
784
+ remoteStandingTimeLeft,
785
+ openMeshUnverifiedEviction,
786
+ openMeshFrozenGateRefusal,
787
+ });
788
+ resolveServeTarget(t) {
789
+ if (this.remoteAuthority) {
790
+ const key = principalKey(t.owner, t.actor).key;
791
+ for (const a of this.agents.values())
792
+ if (a.id === key)
793
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
794
+ const participant = [...this.participants.values()].find((p) => p.owner === t.owner && p.actor === t.actor && this.currentParticipant(p.owner, p.actor, p.uid) === p);
795
+ return participant ? { lifecycleUid: participant.uid, mappingRevision: 0 } : undefined;
796
+ }
797
+ if (t.owner === DEV_OWNER) {
798
+ for (const a of this.agents.values())
799
+ if (!a.userOwner && a.id === t.actor)
800
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
801
+ return undefined;
802
+ }
803
+ const key = principalKey(t.owner, t.actor).key;
804
+ for (const a of this.agents.values())
805
+ if (a.userOwner && a.id === key)
806
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
807
+ return undefined;
808
+ }
809
+ retirement = new Retirement({
810
+ auth: () => this.auth,
811
+ remoteAuthority: () => this.remoteAuthority,
812
+ userMode: () => this.userMode,
813
+ workspaceRoot: () => this.workspaceRoot,
814
+ space: () => this.space,
815
+ servers: () => this.servers,
816
+ secrets: () => this.secrets,
817
+ serveIdentity: () => this.managerServeIdentity,
818
+ lifecycleUid: () => this.managerLifecycleUid,
819
+ instanceId: () => this.managerInstanceId,
820
+ serveEpoch: () => this.serviceServe?.grant.epoch,
821
+ dial: (opts) => this.dial(opts),
822
+ withRetirementSlot: (run) => this.withRetirementSlot(run),
823
+ driveStaticRetirement: (a) => this.driveStaticRetirement(a),
824
+ awaitHandleExit: (handle) => this.awaitHandleExit(handle),
825
+ shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
826
+ dropSeatRecord: (a) => this.dropSeatRecord(a),
827
+ fenceRetiringAcl: (a) => this.fenceRetiringAcl(a),
828
+ lifecycleMembershipInventory: (a) => this.lifecycleMembershipInventory(a),
829
+ brokerTeardown: (task, message) => withTimeout(task, DEPROVISION_TIMEOUT_MS, message),
830
+ trackLifecycle: () => { this.lifecycleInFlight++; return () => this.releaseLifecycle(); },
831
+ });
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(); }
871
848
  /** Set at the top of `stop()`. `renewLease` returns at once once this is set, and its `gone` arm
872
849
  * does not re-acquire: a manager that is stopping never puts its own key back. It also closes the
873
850
  * lifecycle fence ({@link beginLifecycle}), so no spawn can launch a seat the stop never sees. */
@@ -951,6 +928,93 @@ export class Manager {
951
928
  throw e;
952
929
  }
953
930
  }
931
+ seatCustody = new SeatCustody({
932
+ staticAuth: () => !!this.auth && !this.userMode,
933
+ workspaceRoot: () => this.workspaceRoot,
934
+ space: () => this.space,
935
+ instanceId: () => this.managerInstanceId,
936
+ endpoint: () => this.ep,
937
+ secrets: () => this.secrets,
938
+ eventPayloadsWithheld: () => this.eventPayloadsWithheld,
939
+ runtimeFor: (kind) => this.runtimeFor(kind),
940
+ requiredRuntime: () => this.requiredRuntime,
941
+ withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
942
+ watchConnectorHolder: (handle, holder) => this.watchConnectorHolder(handle, holder),
943
+ resumeEntryOf: (agent) => this.resumeEntryOf(agent),
944
+ inventoryReferenceError: (entry) => this.inventoryReferenceError(entry),
945
+ registerAgent: (name, agent) => { this.agents.set(name, agent); },
946
+ agentFor: (name) => this.agents.get(name),
947
+ watchExit: (agent) => this.watchExit(agent),
948
+ bindOnceSeat: (agent) => this.bindOnceSeat(agent),
949
+ renewManagedStaticCred: (agent) => this.renewManagedStaticCred(agent),
950
+ resumeSupervisedAgent: (entry, supervised) => this.resumePreservedAgent(entry, false, false, undefined, supervised),
951
+ });
952
+ sessionRecovery = new SessionRecovery({
953
+ workspaceRoot: () => this.workspaceRoot,
954
+ execution: () => this.execution,
955
+ executionRefusal: () => this.executionRefusal(),
956
+ instanceId: () => this.managerInstanceId,
957
+ endpoint: () => this.ep,
958
+ beginLifecycle: () => this.beginLifecycle(),
959
+ freeSlot: (agent, floor, cause) => this.freeSlot(agent, floor, cause),
960
+ reapChildrenOf: (principal) => this.reapChildrenOf(principal),
961
+ managedPrincipal: (agent) => this.managedPrincipal(agent),
962
+ inlineSnapshotChange: (agent) => this.inlineSnapshotChange(agent),
963
+ agentFor: (name) => this.agents.get(name),
964
+ maintenanceState: () => this.maintenanceState,
965
+ resolveConnector: (name) => this.resolveConnector(name),
966
+ runtimeFor: (kind) => this.runtimeFor(kind),
967
+ reserveCustody: (runtime) => this.reserveCustody(runtime),
968
+ recordSlotCustody: (agent, reference) => this.recordSlotCustody(agent, reference),
969
+ spawnCustodied: (runtime, name, spec, cwd, reserved) => this.spawnCustodied(runtime, name, spec, cwd, reserved),
970
+ awaitReadiness: (agent, timeoutMs, opts) => this.awaitReadiness(agent, timeoutMs, opts),
971
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
972
+ recordSlotRuntime: (agent) => this.recordSlotRuntime(agent),
973
+ refreshSeatRecord: (agent) => this.refreshSeatRecord(agent),
974
+ watchExit: (agent) => this.watchExit(agent),
975
+ tail: (session) => this.tail(session),
976
+ stopHandle: (agent, graceful, cause) => this.stopHandle(agent, graceful, cause),
977
+ trackStoppedHandle: (agent, floor, cause) => this.trackStoppedHandle(agent, floor, cause),
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
+ });
954
1018
  constructor(opts) {
955
1019
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
956
1020
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1320,7 +1384,7 @@ export class Manager {
1320
1384
  }
1321
1385
  async runStart() {
1322
1386
  await this.admitExecutionState();
1323
- this.staticReconcileStopping = false;
1387
+ this.staticLifecycle.start();
1324
1388
  await this.inspectConnectorsAtBoot();
1325
1389
  await this.attach.start();
1326
1390
  // In auth mode the manager is just another user in the space's account — it mints
@@ -1580,7 +1644,7 @@ export class Manager {
1580
1644
  // stop() fences before it waits for an accepted startup reconciliation terminal. Once that
1581
1645
  // terminal drains, start() and stop() resume from the same await boundary; start must observe
1582
1646
  // the fence before it can publish a fresh service registration after shutdown.
1583
- if (this.staticReconcileStopping)
1647
+ if (this.staticLifecycle.stopping)
1584
1648
  return;
1585
1649
  // Register the manager as an ordinary v0.4 `service` endpoint (SPEC §13.7/§13.9)
1586
1650
  // and serve its typed command surface on the ep rails - the ONLY control door, in
@@ -1590,7 +1654,7 @@ export class Manager {
1590
1654
  // trust). Fail-loud: a manager that cannot register does not start half-registered.
1591
1655
  console.error("manager startup: binding the service endpoint");
1592
1656
  await this.registerManagerService();
1593
- if (this.staticReconcileStopping)
1657
+ if (this.staticLifecycle.stopping)
1594
1658
  return;
1595
1659
  // Stand up the standing goal-writer connection for spawn-as-action — AFTER
1596
1660
  // registration (it writes this endpoint's goal facts/records), disjoint from the serve cred.
@@ -2328,14 +2392,7 @@ export class Manager {
2328
2392
  for (const wake of waiters)
2329
2393
  wake();
2330
2394
  }
2331
- /** A cleanup spawned by accepted active-mode work is part of that work for maintenance draining,
2332
- * even where the ordinary control reply remains fire-and-forget. */
2333
- trackDeprovision(a, context = "") {
2334
- this.lifecycleInFlight++;
2335
- void this.deprovision(a)
2336
- .catch((e) => console.error(`deprovision${context ? ` ${context}` : ""} ${a.name} (${a.id}): ${rejectionText(e)}`))
2337
- .finally(() => this.releaseLifecycle());
2338
- }
2395
+ trackDeprovision(a, context = "") { this.retirement.trackDeprovision(a, context); }
2339
2396
  async awaitLifecycleDrain() {
2340
2397
  if (this.lifecycleInFlight === 0)
2341
2398
  return;
@@ -2958,54 +3015,6 @@ export class Manager {
2958
3015
  if (failures.length)
2959
3016
  throw new Error(`manager preservation shutdown incomplete: ${failures.join("; ")}`);
2960
3017
  }
2961
- /** Create THIS instance's lease key, waiting out a dead predecessor's row first (#4092).
2962
- *
2963
- * A manager SIGKILLed on this host cannot release its key, so a restart inside the key's TTL
2964
- * loses the create. When the row names this workspace root and a pid that is not running here
2965
- * (or is this process's own pid, which a live predecessor cannot hold), the holder is dead and
2966
- * the restart waits for the bucket TTL to remove the row, then creates again. It never writes
2967
- * over the row: a live holder renews it inside the TTL, and the wait then refuses on that write.
2968
- * Any other conflict refuses at once, as before. */
2969
- async acquireInstanceLease(info) {
2970
- const refuse = (held, e) => {
2971
- if (!held)
2972
- return new Error(`could not acquire the manager lease for space "${this.space}": ${rejectionText(e)}`);
2973
- const sameRoot = held.root === info.root;
2974
- 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);
2975
- };
2976
- try {
2977
- return await this.ep.acquireManagerLease(info);
2978
- }
2979
- catch (e) {
2980
- // Our OWN instance id already holds a live key ⇒ refuse. Anything else (e.g. a KV/JS error) is a
2981
- // real failure to surface, not a silent "held" — keep the cause so it isn't misread as a conflict.
2982
- const held = await this.ep.readOwnManagerLease(this.managerInstanceId).catch(() => undefined);
2983
- if (!held || held.info.root !== info.root || (held.info.pid !== process.pid && probeLiveness(held.info.pid) !== "dead"))
2984
- throw refuse(held?.info, e);
2985
- console.error(`• manager instance ${this.managerInstanceId}: its lease is still held by pid ${held.info.pid}, which is not running on this host; ` +
2986
- `waiting ${Math.ceil(leaseRemainingMs(held.created, MANAGER_LEASE_TTL_MS) / 1000)}s for the lease to expire`);
2987
- const waited = await awaitLeaseExpiry({
2988
- read: async () => {
2989
- const row = await this.ep.readOwnManagerLease(this.managerInstanceId);
2990
- return row && { revision: row.revision, created: row.created };
2991
- },
2992
- revision: held.revision,
2993
- created: held.created,
2994
- ttlMs: MANAGER_LEASE_TTL_MS,
2995
- aborted: () => this.leaseStopping,
2996
- });
2997
- if (waited === "rewritten")
2998
- 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`);
2999
- if (waited !== "expired")
3000
- throw refuse(held.info, e);
3001
- try {
3002
- return await this.ep.acquireManagerLease(info);
3003
- }
3004
- catch (again) {
3005
- throw refuse((await this.ep.readOwnManagerLease(this.managerInstanceId).catch(() => undefined))?.info, again);
3006
- }
3007
- }
3008
- }
3009
3018
  /** Every call joins the first stop and settles with it. A call that asks for a different
3010
3019
  * `withAgents` is refused, since the running stop has already applied its own policy. */
3011
3020
  stop(options = {}) {
@@ -3020,15 +3029,8 @@ export class Manager {
3020
3029
  clearTimeout(this.credentialPushRetry);
3021
3030
  this.credentialPushRetry = undefined;
3022
3031
  this.transcripts?.stop();
3023
- this.staticReconcileStopping = true;
3024
- this.chatExpiry.stop();
3032
+ this.staticLifecycle.stop();
3025
3033
  const starting = this.startTask;
3026
- for (const item of this.staticReconcileItems.values()) {
3027
- if (item.timer)
3028
- clearTimeout(item.timer);
3029
- item.timer = undefined;
3030
- item.nextRetryAt = undefined;
3031
- }
3032
3034
  await this.awaitStaticReconcileDrain();
3033
3035
  await starting?.catch(() => { });
3034
3036
  if (this.leaseTimer)
@@ -3124,36 +3126,6 @@ export class Manager {
3124
3126
  if (failures.length)
3125
3127
  throw new Error(`manager shutdown incomplete: ${failures.join("; ")}`);
3126
3128
  }
3127
- /** Release this instance's liveness lease key on a clean stop, at the broker's own revision
3128
- * rather than a cached one that a renew still in flight moments ago may have already moved past.
3129
- * Re-reads the row and releases only what is PROVABLY this process's (absent, or another pid's,
3130
- * is left alone — the same test {@link reconcileLease} uses).
3131
- *
3132
- * A read or delete that gets no answer, as during a reconnect, is tried again until the delete is
3133
- * acknowledged or {@link LEASE_RELEASE_BUDGET_MS} has passed (#3916). Nothing here throws: a stop
3134
- * must complete either way, and a row that could not be released is left for the bucket TTL, with
3135
- * one line of warning so the cost (a same-root restart waiting out the TTL) is not silent. */
3136
- async releaseOwnManagerLease() {
3137
- const deadline = Date.now() + LEASE_RELEASE_BUDGET_MS;
3138
- for (;;) {
3139
- let why;
3140
- try {
3141
- const own = await this.ep.readOwnManagerLease(this.managerInstanceId);
3142
- if (own === undefined || own.info.pid !== process.pid)
3143
- return;
3144
- await this.ep.releaseManagerLease(this.managerInstanceId, own.revision);
3145
- return;
3146
- }
3147
- catch (e) {
3148
- why = rejectionText(e);
3149
- }
3150
- if (Date.now() >= deadline) {
3151
- 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`);
3152
- return;
3153
- }
3154
- await new Promise((r) => setTimeout(r, LEASE_RELEASE_RETRY_MS));
3155
- }
3156
- }
3157
3129
  /**
3158
3130
  * REMOVE THIS INSTANCE'S SERVICE REGISTRATION on a clean stop (§13.5 deregistration).
3159
3131
  *
@@ -3253,128 +3225,6 @@ export class Manager {
3253
3225
  }
3254
3226
  })().catch(() => this.transportDown.add(nc));
3255
3227
  }
3256
- /** Keep this instance's liveness key fresh, and end the process only when another process holds it.
3257
- *
3258
- * A renew that throws is a question, not a verdict: the request may have timed out with the write
3259
- * landed and only its acknowledgement lost, the key may have expired during a stall, or a same-id
3260
- * process may hold it. The verdict comes from RE-READING the key ({@link reconcileLease}), and each
3261
- * answer has one response:
3262
- * - `held`: adopt the broker's revision and carry on.
3263
- * - `gone`: the key expired or was released while this process was still here, so put it back. The
3264
- * create is atomic, so a same-id process that got there first shows up as `taken` next tick.
3265
- * - `taken`: a different process holds this instance's key, so it took this instance over while
3266
- * this one stalled. This process is the superseded one and stops serving by exiting (SPEC 13.1).
3267
- * An open mesh has no barrier that would evict its serve connection, so nothing else stops it.
3268
- * - `unknown`: the broker could not be asked. Keep serving and ask again next tick, for as long as it
3269
- * takes. A manager that cannot reach its broker gains nothing by ending itself, and the seats it
3270
- * holds lose everything (a pty child dies with its parent).
3271
- *
3272
- * This replaces a fail-close that ended the process one tick past the lease TTL with no answer, which
3273
- * on a live mesh turned a ten-second broker or KV outage into a manager outage that lasted until an
3274
- * operator noticed. */
3275
- async renewLease() {
3276
- // A manager that is stopping never puts its own key back: a stop already fenced this loop, and
3277
- // any tick or explicit call landing after that must be a no-op, not a fresh acquire attempt.
3278
- if (this.leaseStopping)
3279
- return;
3280
- // A renew that runs long must not be overlapped by the next tick: both would CAS against the same
3281
- // cached revision, so whichever lands second is refused over a sequence the first legitimately
3282
- // moved, a conflict this instance manufactured itself.
3283
- if (this.leaseRenewInFlight)
3284
- return;
3285
- this.leaseRenewInFlight = true;
3286
- const task = this.renewLeaseAttempt();
3287
- this.leaseRenewTask = task;
3288
- return task;
3289
- }
3290
- /** The renew attempt itself, split out from {@link renewLease} only so `stop()` can hold the
3291
- * promise a renew already in flight is running ({@link leaseRenewTask}) and await it before
3292
- * releasing the key: releasing against a cached revision a live renew has since moved is a CAS
3293
- * the broker correctly refuses, silently, forever. */
3294
- async renewLeaseAttempt() {
3295
- try {
3296
- if (!this.leaseInfo || this.leaseRevision === undefined)
3297
- return;
3298
- try {
3299
- this.leaseRevision = await this.ep.renewManagerLease(this.leaseInfo, this.leaseRevision);
3300
- this.noteLease("held", `renews its liveness lease again (revision ${this.leaseRevision})`);
3301
- return;
3302
- }
3303
- catch (renewError) {
3304
- const why = rejectionText(renewError);
3305
- const verdict = await this.reconcileLease();
3306
- switch (verdict.kind) {
3307
- case "held":
3308
- // The re-read is the broker's truth about the revision: adopt it, whether our write landed
3309
- // with its acknowledgement lost (revision moved) or never landed (revision unchanged).
3310
- this.leaseRevision = verdict.revision;
3311
- this.noteLease("held-unrenewed", `could not renew its liveness lease (${why}) but the key is still its own at revision ${verdict.revision}; serving, retrying`);
3312
- return;
3313
- case "gone": {
3314
- // A stop that began while this renew was already in flight fences it here too: the
3315
- // await above can cross the point where `stop()` set the flag, and a re-acquire past
3316
- // that point would put a stopping process's key straight back.
3317
- if (this.leaseStopping)
3318
- return;
3319
- // The key being gone is a fact before the re-acquire is attempted, so a successful
3320
- // re-acquire is a change of state (gone to held) and prints, every time it happens.
3321
- const before = this.leaseState;
3322
- this.leaseState = "gone";
3323
- try {
3324
- this.leaseRevision = await this.ep.acquireManagerLease(this.leaseInfo);
3325
- this.noteLease("held", `found its liveness lease key gone (renew: ${why}) and re-acquired it at revision ${this.leaseRevision}`);
3326
- }
3327
- catch (e) {
3328
- this.leaseState = before;
3329
- this.noteLease("gone", `found its liveness lease key gone (renew: ${why}) and could not re-acquire it yet (${rejectionText(e)}); serving, retrying`);
3330
- }
3331
- return;
3332
- }
3333
- case "taken":
3334
- // No `stop()` on the way out: its deregistration deletes the instance's current
3335
- // registration, which is the other process's now. That process took over on the premise
3336
- // that this one was gone, so this exit leaves what a crash would, and seats a custodian or
3337
- // multiplexer owns outlive it the same way.
3338
- 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}")`);
3339
- process.exit(1);
3340
- case "unknown":
3341
- this.noteLease("unknown", `could not renew its liveness lease (${why}) or re-read it (${verdict.why}); serving, retrying until the broker answers`);
3342
- return;
3343
- }
3344
- }
3345
- }
3346
- finally {
3347
- this.leaseRenewInFlight = false;
3348
- }
3349
- }
3350
- /** Print `what` only when the lease state CHANGES. The renew ticks every few seconds, so a long
3351
- * outage would otherwise print the same line thousands of times; an operator needs the line going
3352
- * in and the line coming out, with the instance and the space on both. */
3353
- noteLease(state, what) {
3354
- if (state === this.leaseState)
3355
- return;
3356
- this.leaseState = state;
3357
- console.error(`${state === "held" ? "✓" : "!"} manager instance ${this.managerInstanceId} ${what} (space "${this.space}")`);
3358
- }
3359
- /** What the broker actually says about THIS instance's lease key, right now. `unknown` is a first-class
3360
- * answer and never collapses into `gone`: not being able to look is not the same fact as looking and
3361
- * finding nothing. */
3362
- async reconcileLease() {
3363
- let current;
3364
- try {
3365
- current = await this.ep.readOwnManagerLease(this.managerInstanceId);
3366
- }
3367
- catch (e) {
3368
- return { kind: "unknown", why: rejectionText(e) };
3369
- }
3370
- if (current === undefined)
3371
- return { kind: "gone" };
3372
- // The pid is what distinguishes US from a same-id restart: the logical instance id and the serve
3373
- // identity both PERSIST across restart by design, so neither can tell the two processes apart.
3374
- if (current.info.pid !== process.pid)
3375
- return { kind: "taken", by: `pid ${current.info.pid} (${current.info.runtime}, root ${current.info.root})` };
3376
- return { kind: "held", revision: current.revision };
3377
- }
3378
3228
  async opFinalizeResume(rawArgs) {
3379
3229
  if (this.execution === "none")
3380
3230
  throw new EpEnvelopeError("unimplemented", this.executionRefusal());
@@ -4730,76 +4580,7 @@ export class Manager {
4730
4580
  isOwnPresence(a, p) {
4731
4581
  return p !== undefined && p.card.id === this.managedPrincipal(a) && p.lifecycleUid === a.lifecycleUid;
4732
4582
  }
4733
- /** Drop a live agent's slot. When `floor` is set and the agent died young (lived less than
4734
- * MIN_LIFETIME), push a cooling stamp so the freed slot still counts toward the ceiling until it
4735
- * expires — flooring the RECYCLE, not the call, so both free paths (despawn + exit/reap) are
4736
- * covered (P4c). Floor self + own-child despawn and natural exit; NEVER admin despawn (operator
4737
- * emergency-kill stays unthrottled) and NEVER the reserved-rollback path (no cold-start paid). */
4738
- freeSlot(a, floor, cause, acceptedBeforeFence = false) {
4739
- if (this.agents.get(a.name) !== a)
4740
- return; // already freed (exit raced despawn, etc.)
4741
- // The terminalizing latch also covers exit/reap paths that never rode stopHandle.
4742
- this.logSeatReaped(a, cause);
4743
- a.terminalizing = true;
4744
- this.agents.delete(a.name);
4745
- this.recordContinuityAtStop(a, "stop");
4746
- if (a.restart?.sessionStatePath)
4747
- rmSync(a.restart.sessionStatePath, { force: true });
4748
- // A released seat's record is the next manager's only pointer to it. It stays until the
4749
- // retirement is confirmed. Dropping it here let a refused retirement leave the lifecycle active
4750
- // with nothing left for that manager to adopt.
4751
- if (!this.releasedSeatPending(a))
4752
- this.dropSeatRecord(a);
4753
- if (a.seatHome)
4754
- rmSync(a.seatHome, { recursive: true, force: true });
4755
- // End any live §13.6 attach session bound to THIS incarnation with the reason its cause names.
4756
- // Fires once per agent on every free path (despawn / self-stop / reap / exit) via the `agents`
4757
- // guard above; a no-op when no plane or no live session for the target.
4758
- this.sessionPlane?.endForTarget(a.name, a.lifecycleUid, typeof cause === "string" ? FREE_SLOT_ATTACH_END[cause] : "target-despawn");
4759
- // The turn relay's reap hook: every pending turn addressed to THIS incarnation is stamped
4760
- // with the death, and its deadline terminal carries it as `agentDownAt`. The addressee is gone
4761
- // and no successor may answer for it; the terminal is still the deadline's, not a new reason.
4762
- this.failSeatTurns(a.name, a.lifecycleUid);
4763
- if (floor && Date.now() - a.startedAt < MIN_LIFETIME)
4764
- this.cooling.push(a.startedAt + MIN_LIFETIME);
4765
- // The departed agent's own custody reference rides the teardown: the exit that freed this slot
4766
- // is usually the seat ending, but a stop that could not prove the process gone leaves one the
4767
- // terminal must still address before it frees the alias.
4768
- const target = this.teardownTarget(a);
4769
- // On a USER mesh the name is RESERVED PENDING RETIREMENT — despawn started this
4770
- // lifecycle's FULL teardown (footprint + standing-authority revoke + the auth-side retirement),
4771
- // and the alias frees only when all of it completes (not the retirement alone). The detached
4772
- // deprovision below drives it; a failed revoke or an unreachable rail keeps the name held,
4773
- // re-driven by a retry. Gate on userMode BY
4774
- // CONSTRUCTION (NEW-1): a static-auth mint has no user-mode lifecycle head to retire, so the
4775
- // reservation + rail request simply don't apply there (the incidental nkey-parse used to mask
4776
- // this, but the intent is "user mode only", not "any principal-shaped id").
4777
- if (this.userMode) {
4778
- const p = parsePrincipalKey(a.id);
4779
- if (p)
4780
- this.retiring.set(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: p.owner, actor: p.actor, target, startedAt: Date.now() });
4781
- }
4782
- else if (this.auth) {
4783
- // A STATIC lifecycle now also holds its name pending its own terminal (the
4784
- // static retirement the detached deprovision below drives) — the alias frees only when the
4785
- // gate+head terminal completes, exactly the user-mode discipline. The wire principal is the
4786
- // incarnation-unique nkey; owner is the dev owner.
4787
- this.retiring.set(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: DEV_OWNER, actor: a.id, target, startedAt: Date.now() });
4788
- }
4789
- // Auth mode: tear down the departed agent's minted broker footprint + creds file (#159 B2). The
4790
- // process is already gone, so this must never block the slot free or throw into the caller — it runs
4791
- // detached, and a failure is logged loudly (never swallowed), not retried. The `agents` guard above
4792
- // makes this fire exactly once per agent across every free path (despawn / self-stop / reap / exit).
4793
- if (!a.suppressCleanup && (this.maintenanceState === "active" || acceptedBeforeFence)) {
4794
- // An inline seat's snapshot goes with the seat on every mesh. An open mesh runs no teardown
4795
- // below, and a preservation cut suppresses this, so a resumed seat still finds its snapshot.
4796
- // Settled means the file is gone or the seat never had one. A removal that failed is left to
4797
- // the teardown, which retries it and reports what it could not remove.
4798
- if (a.launch.source.kind !== "inline" || this.dropInlineSnapshot(a.name, a.lifecycleUid))
4799
- target.snapshotSettled = true;
4800
- this.trackDeprovision(target);
4801
- }
4802
- }
4583
+ freeSlot(a, floor, cause, acceptedBeforeFence = false) { this.namesCapacity.freeSlot(a, floor, cause, acceptedBeforeFence); }
4803
4584
  /** Remove one lifecycle's inline snapshot by the path its uid derives, never by a recorded one, so a
4804
4585
  * resume inventory cannot point the removal at another file. Returns whether the file is gone. A
4805
4586
  * failure is logged, never thrown, because the callers must still schedule the teardown. */
@@ -4818,35 +4599,7 @@ export class Manager {
4818
4599
  teardownTarget(a) {
4819
4600
  return { id: a.id, name: a.name, lifecycleUid: a.lifecycleUid, userOwner: a.userOwner, delegated: a.delegated, secretPaths: a.secretPaths, runtime: a.handle?.reference, ...(a.handedOff ? { delegatedHandle: a.handle } : {}), launch: { allowSubscribe: a.launch.allowSubscribe }, staticCredentialRenewal: a.staticCredentialRenewal };
4820
4601
  }
4821
- /** Tear down a departed agent's minted footprint (#159 B2, auth mode): its local-principal durables
4822
- * (`dm_local-<id>`, `dlv_local-<id>`), its read-ACL row, and its creds file — everything the spawn's
4823
- * `provisionAgent` + creds-write left behind. Mints an EPHEMERAL, TARGET-PINNED `deprovisioner` cred
4824
- * (mirrors the ephemeral `provisioner`/`purger`): it can delete only THIS agent's local-principal footprint,
4825
- * never a peer's and never the role-shared `svc_<role>` (which its siblings still bind). Open mesh →
4826
- * no-op (nothing was minted). Idempotent at the broker (missing consumer / ACL row = no-op) and on
4827
- * disk (`force` tolerates an absent creds file, e.g. a ledgered deploy that wrote none).
4828
- *
4829
- * Removing the creds file is footprint REDUCTION, not revocation: a JWT copied off disk before exit
4830
- * keeps its inline publish/live-sub/control grants until key rotation or JWT expiry — cred revocation
4831
- * is the separate per-user-auth work, not this. Tearing down the durables + ACL row still shrinks the
4832
- * delivery surface a stale copy could use. */
4833
- async deprovision(a) {
4834
- if (!this.auth && !this.remoteAuthority)
4835
- return; // open mesh mints no creds/durables — nothing to tear down
4836
- // SINGLE-FLIGHT per (name, lifecycleUid) (INT-2/C): join an in-flight teardown for this exact
4837
- // lifecycle rather than launching a second concurrent one whose delayed name-keyed revoke could
4838
- // outlive the hold-clear and delete a successor's row. A fresh trigger after settle re-drives.
4839
- const key = JSON.stringify([a.name, a.lifecycleUid]); // ASCII-safe, delimiter-collision-free
4840
- const inflight = this.deprovisioningFlight.get(key);
4841
- if (inflight)
4842
- return inflight;
4843
- const flight = this.withRetirementSlot(() => this.driveDeprovision(a)).finally(() => {
4844
- if (this.deprovisioningFlight.get(key) === flight)
4845
- this.deprovisioningFlight.delete(key);
4846
- });
4847
- this.deprovisioningFlight.set(key, flight);
4848
- return flight;
4849
- }
4602
+ deprovision(a) { return this.retirement.deprovision(a); }
4850
4603
  /** Run one retirement in a {@link RETIREMENT_CONCURRENCY} slot, oldest first: a seat's deprovision, a
4851
4604
  * chat session's terminal and a static reconcile's terminal all take one. No retirement awaits
4852
4605
  * another, so the bounded pool cannot deadlock. */
@@ -4867,357 +4620,8 @@ export class Manager {
4867
4620
  this.retirementsRunning--;
4868
4621
  }
4869
4622
  }
4870
- /** The actual footprint teardown (wrapped by {@link deprovision}'s single-flight). */
4871
- async driveDeprovision(a) {
4872
- if (this.remoteAuthority) {
4873
- if (a.delegated) {
4874
- // The agent is its user's: only that user's retirement intent retires it, so the name stays
4875
- // held until retireDelegatedAgent confirms the host retired this UID.
4876
- const held = this.retiring.get(a.name);
4877
- if (held?.target.lifecycleUid === a.lifecycleUid)
4878
- held.lastError = `"${a.name}" was launched under a delegated user intent and retires only through its user's retirement intent`;
4879
- return;
4880
- }
4881
- // A hosted composition owns grant revocation and resumable footprint release. It calls this
4882
- // prerequisite before the terminal rail. The callback must preserve this UID and its pending
4883
- // state until the host decides terminal retirement, never map deprovisioning to suspension.
4884
- const target = parsePrincipalKey(a.id);
4885
- if (!target)
4886
- throw new Error(`hosted retirement cannot derive the managed principal ${a.id}`);
4887
- await this.remoteAuthority.prepareAgentRetirement({
4888
- target: { owner: target.owner, actor: target.actor, lifecycleUid: a.lifecycleUid },
4889
- opId: managedRetirementOpId(a.lifecycleUid),
4890
- });
4891
- // A delegated seat's fenced close runs only now, after the grant is revoked so its child can
4892
- // obtain no fresh bearer, and before the barrier, which must never run ahead of a create that
4893
- // could still land. A close that cannot prove that yet throws here and keeps the alias held.
4894
- if (a.delegatedHandle) {
4895
- a.delegatedHandle.stop({ graceful: true });
4896
- await this.awaitHandleExit(a.delegatedHandle);
4897
- }
4898
- // THE LOCAL FAMILY IS THIS PARTICIPANT'S, not the host's (#3055). The hosted enrollment wrote
4899
- // it here, so the host's release cannot remove it, and returning after the terminal request
4900
- // left every hosted seat's actor token, sentinel and health file on disk. It goes once the
4901
- // grant is released and the child is gone, by the same rule as the local arm below: every
4902
- // removal is attempted, and a failure keeps the name held instead of reaching the terminal.
4903
- const unshredded = [];
4904
- await this.shredUserSecrets(unshredded, a.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, a.name, a.lifecycleUid));
4905
- if (unshredded.length)
4906
- throw new Error(`could not shred "${a.name}": ${describeCleanupFailures(unshredded)}`);
4907
- await this.requestRetirement(a);
4908
- return;
4909
- }
4910
- if (!this.auth)
4911
- return; // guaranteed by deprovision; re-checked for the deprovisionBroker narrowing
4912
- if (!this.userMode && !a.userOwner) {
4913
- // A STATIC lifecycle retires through the terminal barrier — freeze → head
4914
- // retiring → B1 ledger revoke → footprint cleanup (creds file + broker durables/ACL, INSIDE
4915
- // the barrier) → gate retired → head retired → alias free. The eviction step is the process
4916
- // kill the stop path already performed (static's best-effort eviction).
4917
- return this.driveStaticRetirement(a);
4918
- }
4919
- // Drop the local creds file FIRST + unconditionally — it is a usable identity on disk, useless for a
4920
- // departed agent, so it must not survive even if the broker teardown below fails or times out. The
4921
- // teardown mints its OWN deprovisioner cred (not this file), so removing it early is independent.
4922
- // Migrated kinds: the store delete is the authoritative removal; the rmSync clears the FS
4923
- // materialization (a byte-identical no-op under the local composition, real once the manager
4924
- // `secretStore` is a non-FS store).
4925
- //
4926
- // LIFECYCLE-OWNED (SPEC 13.1, the manager-local half): the family deleted here is the RECORDED
4927
- // one (spawn/adoption), else the lifecycle-keyed derivation for THIS uid — never a name-only
4928
- // derivation, so a stale/replayed teardown addresses only names a same-alias successor never
4929
- // uses. It deliberately CANNOT remove a name-keyed family it holds no record of (an operator's
4930
- // standing `cotal mint` cred, a seeded workstation cred, a pre-split leftover): deleting an
4931
- // unowned same-name file is the exact successor-clobber this ownership discipline removes.
4932
- const secrets = this.secrets;
4933
- const files = a.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, a.name, a.lifecycleUid);
4934
- // Every removal is attempted, and a failed one is thrown only after the broker teardown below,
4935
- // so a file fault cannot strand the agent's durables and ACL row on the broker.
4936
- const unshredded = [];
4937
- if (files.creds) {
4938
- const creds = files.creds;
4939
- await attemptCleanup(unshredded, `secret ${creds}`, () => secrets.delete(agentSecretKeyForFile(creds, this.space)));
4940
- await attemptCleanup(unshredded, `file ${creds}`, () => rmSync(creds, { force: true }));
4941
- }
4942
- if (a.userOwner) {
4943
- // USER MODE: this teardown IS revocation, not just footprint reduction — the ledger row is
4944
- // the agent's standing mint authority, so delete it (next exchange refused, next connect
4945
- // denied) and shred the secret/sentinel/health files. A copied actor token dies here; a
4946
- // still-LIVE connection ends at its bearer-bound JWT expiry (≤ the agent TTL).
4947
- await this.shredUserSecrets(unshredded, files);
4948
- // The ledger row IS the agent's STANDING mint authority (a different store from the auth-plane
4949
- // cred ledger the rail retirement covers): while it lives, a copied actor token can still mint a
4950
- // fresh connect credential. So a FAILED revoke must NOT be swallowed into a clean terminal (INT-2):
4951
- // mark the standing authority live on the hold so the retirement can never free the name (a freed
4952
- // name says "this lifecycle is fully gone" - false while the mint authority stands), and carry a
4953
- // legible operator copy. A retry re-drives this whole teardown (the same-name-spawn nudge routes
4954
- // through deprovision, not the rail alone), so the revoke is re-attempted, not stranded.
4955
- const holdRevoke = this.retiring.get(a.name);
4956
- if (holdRevoke && holdRevoke.target.lifecycleUid === a.lifecycleUid)
4957
- holdRevoke.standingAuthorityLive = true;
4958
- try {
4959
- await resolveAuthProvider().revokeAgent({
4960
- dir: userAuthStateDir(this.workspaceRoot, this.space),
4961
- owner: a.userOwner,
4962
- actor: a.name,
4963
- });
4964
- const done = this.retiring.get(a.name);
4965
- if (done && done.target.lifecycleUid === a.lifecycleUid)
4966
- done.standingAuthorityLive = false;
4967
- }
4968
- catch (e) {
4969
- const h = this.retiring.get(a.name);
4970
- if (h && h.target.lifecycleUid === a.lifecycleUid)
4971
- h.lastError = `the agent's standing mint authority could not be revoked (${rejectionText(e)}); the name stays held so a copied actor token cannot mint fresh credentials. NEXT: a same-name spawn re-drives the full teardown (including the revoke), or recover the auth state.`;
4972
- console.error(`revoke agent grant ${a.name}: ${rejectionText(e)}`);
4973
- }
4974
- }
4975
- const shredFailure = unshredded.length ? `could not shred "${a.name}": ${describeCleanupFailures(unshredded)}` : undefined;
4976
- try {
4977
- const res = await this.deprovisionBroker(a);
4978
- const h = this.retiring.get(a.name);
4979
- if (h && h.target.lifecycleUid === a.lifecycleUid)
4980
- h.lastResources = res;
4981
- }
4982
- catch (e) {
4983
- const h = this.retiring.get(a.name);
4984
- if (h && h.target.lifecycleUid === a.lifecycleUid) {
4985
- h.lastError = rejectionText(e);
4986
- if (e instanceof DeprovisionError)
4987
- h.lastResources = e.accounting;
4988
- }
4989
- if (shredFailure)
4990
- throw new Error(`${rejectionText(e)}; ${shredFailure}`, { cause: e });
4991
- throw e;
4992
- }
4993
- if (shredFailure)
4994
- throw new Error(shredFailure);
4995
- // After the footprint teardown, ask the AUTH plane to RETIRE the lifecycle over
4996
- // the auth endpoint rail. The rail re-checks the SERVE-ISSUANCE GATE at serve time (not the
4997
- // space-manager lease - that check was replaced in 02794b2f) and refuses unless the registration
4998
- // this request names belongs to our own principal; the terminal (or an already-retired answer)
4999
- // clears the name reservation. Failures keep the hold with
5000
- // their operator copy — legible, retryable, never a silent half-state.
5001
- await this.requestRetirement(a);
5002
- }
5003
- /** Request the auth-side retirement of a departed agent's lifecycle: an ephemeral
5004
- * `retirement-requester` credential (request + reply only), the generic `retireLifecycle` op,
5005
- * a STABLE opId (derived from the lifecycleUid, so every retry re-drives the SAME operation),
5006
- * and the four-outcome handling in operator vocabulary. */
5007
- async requestRetirement(a) {
5008
- if (!this.userMode)
5009
- return; // NEW-1: lifecycle retirement is a user-mesh concept; a static mint has no head to retire
5010
- // SINGLE-FLIGHT per (name, lifecycleUid) (audit #1): the detached deprovision call and every
5011
- // same-name-spawn nudge for THIS lifecycle share ONE in-flight retirement, so concurrent triggers
5012
- // never stack independent rail requests that dual-enter runAgentRetirementBarrier. Keyed by
5013
- // (name, uid), NOT name alone: driveRetirement clears the hold on rail ok but then yields at
5014
- // `nc.close()` with the flight still stored, so the alias can free and a SUCCESSOR (new uid) spawn.
5015
- // A name-only key would let that successor's own teardown JOIN the predecessor's still-pending
5016
- // flight and never send its OWN retirement — leaving the successor's lifecycle unretired. The uid in
5017
- // the key gives the successor a disjoint flight (mirrors {@link deprovisioningFlight}). A fresh
5018
- // trigger after settle re-drives (a still-present hold => retirement not yet confirmed).
5019
- const key = JSON.stringify([a.name, a.lifecycleUid]);
5020
- const inflight = this.retiringFlight.get(key);
5021
- if (inflight)
5022
- return inflight;
5023
- const flight = this.driveRetirement(a).finally(() => {
5024
- if (this.retiringFlight.get(key) === flight)
5025
- this.retiringFlight.delete(key);
5026
- });
5027
- this.retiringFlight.set(key, flight);
5028
- return flight;
5029
- }
5030
- /** The rail round-trip for one retirement (wrapped by {@link requestRetirement}'s single-flight). */
5031
- async driveRetirement(a) {
5032
- if (!this.auth && !this.remoteAuthority)
5033
- return;
5034
- const held = this.retiring.get(a.name);
5035
- const target = parsePrincipalKey(a.id);
5036
- if (!target) {
5037
- if (held)
5038
- held.lastError = "the target principal could not be derived; the retirement was not requested";
5039
- return;
5040
- }
5041
- // The SERVE identity, not the endpoint identity, is who this request speaks as (#549). The field
5042
- // is declared `!:`, which asserts to the type system what the ordering happens to provide, so it
5043
- // is read here as what it actually is. On today's ordering this guard cannot fire: `start()`
5044
- // assigns the identity before it connects anything, and a retirement needs an agent that only a
5045
- // started manager can hold. It is kept as a fail-closed assertion rather than a live face,
5046
- // because the alternative is carrying `undefined` into the caller triple and surfacing the
5047
- // result as "the rail could not be reached", which would name the wrong cause.
5048
- const serveIdentity = this.managerServeIdentity;
5049
- if (!serveIdentity?.id) {
5050
- if (held)
5051
- held.lastError = `the retirement was NOT requested: this manager has no serve identity yet, so it cannot speak as the registered serving instance. The despawn stopped "${a.name}" and the name stays held. NEXT: let the manager finish registering, then re-attempt the same-name spawn to re-drive the teardown.`;
5052
- return;
5053
- }
5054
- const reportFailure = (why, unconfirmed = false) => {
5055
- // An orphan rollback owns no name hold. Re-read after the rail awaits so a successor's
5056
- // hold never receives the predecessor's error or supplies its despawn/retry claims.
5057
- const current = this.retiring.get(a.name);
5058
- const held = current?.target.lifecycleUid === a.lifecycleUid ? current : undefined;
5059
- const copy = !unconfirmed ? why : held
5060
- ? `the despawn stopped "${a.name}", but the retirement's completion could NOT be confirmed (${why}). The name stays held - not failed, not done - and a same-name spawn re-drives the same teardown; the auth service also finishes any started retirement on its next boot. NEXT: if the auth rail stays unreachable, recover the stack (\`cotal supervise\`), then re-attempt the same-name spawn.`
5061
- : `the retirement's completion could NOT be confirmed (${why}). No hold reserves the name for this lifecycle.`;
5062
- if (held)
5063
- held.lastError = copy;
5064
- const prefix = held ? `despawn ${a.name}` : `retire ${a.name}: lifecycle ${a.lifecycleUid}`;
5065
- console.error(`${prefix}: ${copy}`);
5066
- };
5067
- try {
5068
- // The caller triple and the TARGET are both grant-pinned now (#350): the `handle` target
5069
- // rides the subject, so this ephemeral credential can ask to retire exactly this
5070
- // incarnation and nothing else.
5071
- //
5072
- // THE TRIPLE IS THE SERVE PRINCIPAL, and it has to be (#549). The auth rail authorizes this
5073
- // request by comparing the caller's `<owner>.<actor>` against the serve issuance gate's bound
5074
- // principal, and that gate is opened with `principalKey(DEV_OWNER, serveIdentity.id)` (see the
5075
- // registration block). Deriving the caller from `ep.ref().id` instead put the manager's
5076
- // ENDPOINT identity nkey on the wire, which is a different, equally real identity of the same
5077
- // manager, so the comparison was unsatisfiable and EVERY user-mesh retirement was refused as a
5078
- // full no-op. Measured before the fix: 8 refusals in one suite run across 5 agents, with the
5079
- // epoch and the instance id both matching and only the principal disagreeing.
5080
- //
5081
- // Both halves come from the gate's own sources rather than from `ep.ref()`: `DEV_OWNER` is
5082
- // hard-coded at the gate site, so taking the owner from `ep.ref().id` would re-open the same
5083
- // mismatch in the owner half the moment a manager ran under a user-shaped identity. This is
5084
- // also the more honest attribution: the authority being exercised is "I am the registered
5085
- // serving instance", which is exactly what the gate records.
5086
- const caller = this.remoteAuthority
5087
- ? { owner: this.remoteAuthority.owner, actor: this.remoteAuthority.actors.serve, uid: this.managerLifecycleUid }
5088
- : { owner: DEV_OWNER, actor: serveIdentity.id, uid: this.managerLifecycleUid };
5089
- const requestIdentity = newIdentity();
5090
- const retirementTarget = { owner: target.owner, actor: target.actor, lifecycleUid: a.lifecycleUid };
5091
- const opId = managedRetirementOpId(a.lifecycleUid);
5092
- const serveEpoch = this.serviceServe?.grant.epoch ?? 0;
5093
- const creds = this.remoteAuthority
5094
- ? await this.remoteAuthority.mintRetirementRequester({ identity: requestIdentity, target: retirementTarget, opId, serveEpoch })
5095
- : await mintCreds(this.auth, requestIdentity, "retirement-requester", {
5096
- retirementRequester: { ...caller, target: retirementTarget },
5097
- });
5098
- // The requester grant subscribes `_INBOX_<id>.>` only (provision.ts): the endpoint path's
5099
- // JetStream API requests (the contract-store read inside resolveService) must reply under it, not under the client default `_INBOX.`.
5100
- const nc = await this.dial({ authenticator: credsAuthenticator(new TextEncoder().encode(creds)), inboxPrefix: `_INBOX_${requestIdentity.id}`, maxReconnectAttempts: 0 });
5101
- try {
5102
- // The service resolves FRESH on every attempt (never cached on `this`): a plane restart
5103
- // mid-despawn then lands on the new epoch through an ordinary resolve, rather than a
5104
- // caller pinned to a now-superseded incarnation.
5105
- const service = await resolveService(nc, this.space, AUTH_ENDPOINT, caller, { deadlineMs: 10_000, commands: [EP_CMD_RETIRE_LIFECYCLE] });
5106
- // The TARGET rides the invoke's own target (authz mode `exact`, arity 3) — broker-enforced,
5107
- // and pinned by the grant minted above, so it is not a body claim the caller can vary.
5108
- const attributed = await invokeCommand(nc, this.space, service, EP_CMD_RETIRE_LIFECYCLE, {
5109
- opId,
5110
- serveEndpoint: MANAGER_ENDPOINT, serveInstanceId: this.managerInstanceId, serveEpoch,
5111
- }, {
5112
- target: { mode: "exact", owner: target.owner, actor: target.actor, lifecycleUid: a.lifecycleUid },
5113
- deadlineMs: 20_000,
5114
- });
5115
- const r = attributed.reply;
5116
- if (r.ok) {
5117
- this.confirmRetirement(a);
5118
- }
5119
- else if (r.error?.code === "expired") {
5120
- // A stale-epoch refusal cannot confirm retirement. The retry copy follows the
5121
- // current lifecycle's hold, which an orphan rollback does not create.
5122
- reportFailure(r.error.message, true);
5123
- }
5124
- else {
5125
- // The rail's refusal is already the operator copy (lease-loss/stale/foreign-op faces,
5126
- // full-no-op statements included) - surface it INTACT, never flattened.
5127
- const message = r.error?.message ?? "the auth service refused the retirement without a reason";
5128
- reportFailure(message);
5129
- }
5130
- }
5131
- finally {
5132
- await nc.close().catch(() => { });
5133
- }
5134
- }
5135
- catch (e) {
5136
- reportFailure(rejectionText(e), true);
5137
- }
5138
- }
5139
- /** Apply one terminal retirement answer. The predecessor coordinate is recorded only when the
5140
- * answer clears this exact lifecycle's hold, never for an ABA-late answer or an incomplete hosted
5141
- * teardown whose standing authority still lives. */
5142
- confirmRetirement(a) {
5143
- // CAS the hold clear (audit #1 ABA): free the alias ONLY if the current hold is still THIS
5144
- // lifecycle's. A late reply for a retired predecessor must never clear a successor's newer hold.
5145
- const cur = this.retiring.get(a.name);
5146
- // The record names this incarnation only, so a confirmed retirement removes it and a successor's
5147
- // record stays. A mint authority that is still live keeps the record: the seat is gone, and the
5148
- // next manager has to be able to re-drive the revoke.
5149
- if (!(cur?.target.lifecycleUid === a.lifecycleUid && cur.standingAuthorityLive))
5150
- this.dropSeatRecord(a);
5151
- if (cur && cur.target.lifecycleUid === a.lifecycleUid) {
5152
- if (cur.standingAuthorityLive) {
5153
- // INT-2: the auth-plane lifecycle retired, but the manager-side STANDING mint authority is
5154
- // not yet revoked. A copied token could still mint, so neither free the alias nor classify
5155
- // its presence as a completed predecessor.
5156
- console.error(`despawn ${a.name}: the auth-plane lifecycle retired, but the standing mint authority is not yet revoked; the name stays held. ${cur.lastError ?? ""}`);
5157
- }
5158
- else {
5159
- this.confirmedRetiredPredecessors.set(a.name, { principal: a.id, lifecycleUid: a.lifecycleUid });
5160
- this.retiring.delete(a.name);
5161
- console.error(`despawn ${a.name}: the agent's retirement completed; the name is free for reuse`);
5162
- }
5163
- }
5164
- else if (cur) {
5165
- console.error(`despawn ${a.name}: retirement confirmed for a prior lifecycle of "${a.name}"; the current hold is left intact`);
5166
- }
5167
- else {
5168
- // No hold stands, as after an orphaned spawn's rollback: that lifecycle was never despawned and
5169
- // has no successor, so this line names neither.
5170
- console.error(`retire ${a.name}: lifecycle ${a.lifecycleUid} retired; the name had no hold to clear`);
5171
- }
5172
- }
5173
- /** The teardown's ASYNC BROKER PHASE: mint the ephemeral target-pinned deprovisioner cred and
5174
- * delete the agent's broker footprint (dm_/dlv_ durables + read-ACL row). Split from
5175
- * {@link deprovision} because it runs LAST in the ordered teardown chain — after the creds/secret
5176
- * shred and the awaited ledger revoke, which precede it in that same single-flighted chain (the
5177
- * revoke is awaited and can be deliberately slow, so it is not merely a synchronous prefix). The name
5178
- * is NOT freed while any teardown phase is still in flight — the hold clears only after the
5179
- * standing-authority revoke AND the lifecycle retirement both confirm (see {@link driveRetirement}) —
5180
- * but the deletes here are still lifecycle-uid-pinned so even a replayed/stale teardown can never
5181
- * reach a same-name successor's footprint (its names embed a different uid). Each call reports its
5182
- * own accounting: the return value, or the {@link DeprovisionError} it throws once the deletes ran. */
5183
- async deprovisionBroker(a) {
5184
- // LIFECYCLE-PINNED (SPEC 13.1): both the credential's exact-name grants and the delete names
5185
- // carry a.lifecycleUid, so a stale/replayed teardown for this retired incarnation is broker-denied
5186
- // against a same-name successor's footprint (its names embed a different uid).
5187
- // Durable membership rows are lifecycle-keyed per concrete channel. Start with the launch's
5188
- // concrete read channels, then include wildcard-covered and unnamed channels from the inventory.
5189
- const memberChannels = new Set((a.launch?.allowSubscribe ?? []).filter(isConcreteChannel));
5190
- // Fence the lifecycle before its inventory is read: its read-ACL row narrowed to no reads, which
5191
- // every durable join re-reads around the row it writes, so a join the inventory does not see
5192
- // removes its own row. A fence that cannot be written makes the inventory incomplete.
5193
- const unfenced = await this.fenceRetiringAcl(a);
5194
- // Complete the set from the delivery daemon's lifecycle-exact inventory, which covers rows on
5195
- // wildcard-granted channels and teardowns that carry no launch spec. An inventory that cannot be
5196
- // read leaves those rows RETAINED and says so; it never widens the delete beyond exact keys.
5197
- const listed = await this.lifecycleMembershipInventory(a);
5198
- const inventory = unfenced === undefined ? listed : { ...listed, complete: false, reason: `the ACL fence was not written (${unfenced})${listed.complete ? "" : `; ${listed.reason}`}` };
5199
- for (const ch of inventory.channels)
5200
- memberChannels.add(ch);
5201
- if (!inventory.complete)
5202
- console.error(`deprovision ${a.name} (${a.id}): membership inventory incomplete (${inventory.reason}); rows on channels outside its launch policy stay RETAINED for uid ${a.lifecycleUid}`);
5203
- const creds = await mintCreds(this.auth, newIdentity(), "deprovisioner", {
5204
- deprovisionTarget: { principal: a.id, lifecycleUid: a.lifecycleUid, memberChannels: [...memberChannels] },
5205
- });
5206
- // Bound the detached broker teardown so a wedged broker can't leave the deprovision promise pending
5207
- // forever with no log — the timeout rejects into freeSlot's fail-loud `.catch` (paired with the
5208
- // helper's own fail-fast connect). The durables/ACL row still fall to space teardown as a backstop.
5209
- const accounting = await withTimeout(deprovisionAgent({
5210
- servers: this.servers ?? DEFAULT_SERVER,
5211
- space: this.space,
5212
- targetId: a.id,
5213
- lifecycleUid: a.lifecycleUid,
5214
- memberChannels: [...memberChannels],
5215
- creds,
5216
- }), DEPROVISION_TIMEOUT_MS, `deprovision ${a.name} (${a.id}): broker teardown timed out`);
5217
- if (!inventory.complete)
5218
- throw new DeprovisionError(`membership inventory incomplete (${inventory.reason}); rows on channels outside its launch policy stay RETAINED for uid ${a.lifecycleUid}`, accounting);
5219
- return accounting;
5220
- }
4623
+ confirmRetirement(a) { this.retirement.confirmRetirement(a); }
4624
+ deprovisionBroker(a) { return this.retirement.deprovisionBroker(a); }
5221
4625
  /** Narrow the retiring lifecycle's read-ACL row to no reads ({@link fenceLifecycleAcl}) through a
5222
4626
  * `deprovisioner` credential pinned to it. Returns undefined once fenced, or the reason it was not. */
5223
4627
  async fenceRetiringAcl(a) {
@@ -5259,194 +4663,32 @@ export class Manager {
5259
4663
  this.trackStoppedHandle(child, true, cause, true);
5260
4664
  }
5261
4665
  }
5262
- readSessionStatePath(path) {
5263
- let parsed;
5264
- try {
5265
- parsed = JSON.parse(readFileSync(path, "utf8"));
5266
- }
5267
- catch (error) {
5268
- throw new Error(`cannot read connector session state ${path}: ${rejectionText(error)}`);
5269
- }
5270
- const state = parsed;
5271
- if (state.version === 1 && typeof state.sessionId === "string" && state.sessionId.trim() && state.sessionId.length <= 4096 &&
5272
- (state.status === "running" || state.status === "quit"))
5273
- return { sessionId: state.sessionId, status: state.status };
5274
- if (state.version === 2 && state.status === "prompt" && typeof state.connector === "string" && /^[a-z0-9-]{1,64}$/.test(state.connector) &&
5275
- typeof state.prompt === "string" && state.prompt.trim() && state.prompt.length <= 1024 &&
5276
- typeof state.cwd === "string" && state.cwd.trim() && state.cwd.length <= 4096)
5277
- return { connector: state.connector, status: "prompt", prompt: state.prompt, cwd: state.cwd };
5278
- throw new Error(`connector session state ${path} is malformed`);
5279
- }
5280
4666
  readManagedSessionState(a) {
5281
- const path = a.restart?.sessionStatePath;
5282
- if (!path)
5283
- throw new Error("connector supplied no session state path");
5284
- return this.readSessionStatePath(path);
4667
+ return this.sessionRecovery.readManagedSessionState(a);
5285
4668
  }
5286
- /** Upgrade bridge: inventories written before sessionId existed can still resume exactly after
5287
- * the old Pi seat has loaded the new extension once and written its lifecycle-keyed state file. */
5288
4669
  retainedSessionId(entry, connector) {
5289
- if (entry.launch.sessionId)
5290
- return entry.launch.sessionId;
5291
- if (!connector.supportsSessionContinuation)
5292
- return undefined;
5293
- const path = join(this.workspaceRoot, ".cotal", "pi-sessions", `${entry.name}-${entry.identity.lifecycleUid}.json`);
5294
- try {
5295
- const state = this.readSessionStatePath(path);
5296
- if (state.status === "prompt")
5297
- throw new Error(`${state.connector} is waiting at prompt ${JSON.stringify(state.prompt)} for directory ${JSON.stringify(state.cwd)}`);
5298
- return state.sessionId;
5299
- }
5300
- catch (error) {
5301
- throw new Error(`retained ${connector.name} agent ${entry.name} has no sessionId in its older inventory and no usable upgrade state at ${path} ` +
5302
- `(${rejectionText(error)}). Reload the live Pi seat before the preservation cut; refusing to resume fresh and lose its context.`);
5303
- }
4670
+ return this.sessionRecovery.retainedSessionId(entry, connector);
5304
4671
  }
5305
- /** A resumed seat's fork provenance (#1500). The seat forks after it launches, so this reads the
5306
- * record its connector named once the seat has written it, and keeps it on the launch so the
5307
- * resume document carries it across a manager restart. Until the seat has written it, or when the
5308
- * record cannot be read or does not name this seat's source, it is absent: `ps` then shows the
5309
- * source id alone rather than failing the listing for every other seat. */
5310
4672
  forkProvenance(a) {
5311
- // A carried seat's provenance is set only by refuseCarriedFork, once its record names the claim.
5312
- if (a.launch.resumed || a.launch.carried)
5313
- return a.launch.resumed;
5314
- a.launch.resumed = this.readForkRecord(a);
5315
- return a.launch.resumed;
5316
- }
5317
- readForkRecord(a) {
5318
- if (!a.launch.resumeRecordPath || !a.launch.forkSource)
5319
- return undefined;
5320
- let record;
5321
- try {
5322
- record = JSON.parse(readFileSync(a.launch.resumeRecordPath, "utf8"));
5323
- }
5324
- catch {
5325
- return undefined;
5326
- }
5327
- const r = (typeof record === "object" && record !== null ? record : {});
5328
- if (r.source !== a.launch.forkSource || typeof r.transcriptSha256 !== "string" || !/^[a-f0-9]{64}$/.test(r.transcriptSha256) ||
5329
- !(r.title === undefined || r.title === null || (typeof r.title === "string" && r.title.length <= 1024)))
5330
- return undefined;
5331
- return { source: r.source, ...(typeof r.title === "string" && r.title ? { title: r.title } : {}), transcriptSha256: r.transcriptSha256 };
4673
+ return this.sessionRecovery.forkProvenance(a);
5332
4674
  }
5333
- /** Design section 9: a carried seat must fork the bytes the operator carried. Wait for its fork
5334
- * record and hold it to the claim; on a match it becomes the seat's provenance, otherwise the
5335
- * refusal is returned. A seat that writes no record cannot be shown to have forked the claim. */
5336
- async refuseCarriedFork(a, timeoutMs) {
5337
- const claim = a.launch.carried;
5338
- const deadline = Date.now() + timeoutMs;
5339
- let record;
5340
- while (!(record = this.readForkRecord(a))) {
5341
- if (a.terminalizing || a.handle.status() === "exited")
5342
- return `${a.name} stopped before it wrote a fork record`;
5343
- if (Date.now() >= deadline)
5344
- return `${a.name} wrote no fork record within ${timeoutMs} ms, so it cannot be shown to have forked the carried transcript`;
5345
- await new Promise((resolve) => setTimeout(resolve, 100));
5346
- }
5347
- if (record.transcriptSha256 !== claim.transcriptSha256)
5348
- return `${a.name} forked a transcript with sha256:${record.transcriptSha256}, not the carried sha256:${claim.transcriptSha256}`;
5349
- a.launch.resumed = { ...record, host: claim.host, transferredAt: claim.transferredAt };
5350
- return undefined;
4675
+ refuseCarriedFork(a, timeoutMs) {
4676
+ return this.sessionRecovery.refuseCarriedFork(a, timeoutMs);
5351
4677
  }
5352
- /** A carried seat whose launch was uncertain is held to the claim once it joins, as a started one
5353
- * is; the wait ends when the seat stops or exits, which its exit watcher reaps. */
5354
- async refuseLateCarriedFork(a, timeoutMs) {
5355
- for (;;) {
5356
- const late = await this.awaitReadiness(a, timeoutMs, { reapOnExit: false });
5357
- if (late.ok)
5358
- break;
5359
- if (!late.uncertain || a.terminalizing)
5360
- return;
5361
- }
5362
- const refused = await this.refuseCarriedFork(a, timeoutMs);
5363
- if (refused === undefined || a.terminalizing || a.handle.status() === "exited")
5364
- return;
5365
- console.error(`! ${refused}; stopping it`);
5366
- this.stopHandle(a, false, "carried-fork-refused");
5367
- this.trackStoppedHandle(a, true, "carried-fork-refused");
4678
+ refuseLateCarriedFork(a, timeoutMs) {
4679
+ return this.sessionRecovery.refuseLateCarriedFork(a, timeoutMs);
5368
4680
  }
5369
4681
  readManagedSession(a) {
5370
- const state = this.readManagedSessionState(a);
5371
- if (state.status === "prompt")
5372
- throw new Error(`${state.connector} is waiting at prompt ${JSON.stringify(state.prompt)} for directory ${JSON.stringify(state.cwd)}`);
5373
- return state.sessionId;
4682
+ return this.sessionRecovery.readManagedSession(a);
5374
4683
  }
5375
- /** Re-record an exact seat's assignment at a proven session, so crash recovery, a preserved resume
5376
- * and the next manifest launch never pick different sessions. */
5377
4684
  recordContinuity(a, sessionId) {
5378
- if (a.continuity)
5379
- writeContinuityAssignment(this.workspaceRoot, { ...a.continuity, sessionId });
4685
+ return this.sessionRecovery.recordContinuity(a, sessionId);
5380
4686
  }
5381
- /** At a stop boundary the connector's session record is the last proof of the session an exact
5382
- * seat ran, including one it switched to itself. A failed write is logged; the stop goes on. */
5383
4687
  recordContinuityAtStop(a, boundary) {
5384
- if (!a.continuity || !a.restart?.armed)
5385
- return;
5386
- try {
5387
- this.recordContinuity(a, this.readManagedSession(a));
5388
- }
5389
- catch (error) {
5390
- console.error(`! ${a.name}: continuity: exact assignment not updated at ${boundary}: ${rejectionText(error)}`);
5391
- }
5392
- }
5393
- async awaitManagedSessionState(a) {
5394
- const deadline = Date.now() + 15_000;
5395
- let last = "session state not written yet";
5396
- let prompt;
5397
- const promptFailure = () => prompt
5398
- ? `${prompt.connector} is waiting at prompt ${JSON.stringify(prompt.prompt)} for directory ${JSON.stringify(prompt.cwd)}`
5399
- : undefined;
5400
- while (Date.now() < deadline) {
5401
- try {
5402
- const state = this.readManagedSessionState(a);
5403
- if (state.status === "prompt")
5404
- prompt = state;
5405
- else
5406
- return state;
5407
- }
5408
- catch (error) {
5409
- last = rejectionText(error);
5410
- }
5411
- if (a.handle.status() === "exited")
5412
- throw new Error(promptFailure() ?? "process exited before writing session state");
5413
- await new Promise((resolve) => setTimeout(resolve, 100));
5414
- }
5415
- throw new Error(promptFailure() ?? `connector did not write session state (${last})`);
4688
+ return this.sessionRecovery.recordContinuityAtStop(a, boundary);
5416
4689
  }
5417
- /** Bind a continuation-capable connector only after its process is ready. The file proves the
5418
- * latest in-process session (including Pi /resume); the authenticated socket proves this process
5419
- * owns that session now. Presence may lead session_start by milliseconds, so both proofs are
5420
- * awaited within a bounded readiness window rather than read once. */
5421
- async armSessionRecovery(a) {
5422
- if (!a.restart || !a.control)
5423
- return;
5424
- const state = await this.awaitManagedSessionState(a);
5425
- if (state.status !== "running")
5426
- throw new Error("connector reported a deliberate quit before readiness completed");
5427
- await this.awaitRecoveredSession(a, state.sessionId);
5428
- a.restart.armed = true;
5429
- }
5430
- async awaitRecoveredSession(a, expected, handle = a.handle, control = a.control) {
5431
- const deadline = Date.now() + 15_000;
5432
- let last = "control endpoint not ready";
5433
- while (Date.now() < deadline) {
5434
- if (handle.status() === "exited")
5435
- throw new Error("replacement process exited before reporting its session");
5436
- if (control) {
5437
- try {
5438
- const reported = await controlSession(control);
5439
- if (reported !== expected)
5440
- throw new Error(`replacement reported session ${reported}, expected ${expected}`);
5441
- return;
5442
- }
5443
- catch (error) {
5444
- last = rejectionText(error);
5445
- }
5446
- }
5447
- await new Promise((resolve) => setTimeout(resolve, 100));
5448
- }
5449
- throw new Error(`replacement did not prove session ${expected} (${last})`);
4690
+ armSessionRecovery(a) {
4691
+ return this.sessionRecovery.armSessionRecovery(a);
5450
4692
  }
5451
4693
  /** Why an inline seat's snapshot no longer matches its launch, or `undefined` when it does or the
5452
4694
  * seat is not inline. The recorded path and the relaunch's path must both be this lifecycle's
@@ -5475,150 +4717,8 @@ export class Manager {
5475
4717
  }
5476
4718
  return undefined;
5477
4719
  }
5478
- /** Restart one managed process in place. Identity, lifecycle, credentials, durables, children,
5479
- * and the manager row remain owned; only the process handle/control endpoint change. Budget
5480
- * comes from `restart.policy` when spawn carried `supervise`; otherwise the Pi session-recovery
5481
- * constants. Spending the budget falls through to normal retirement. */
5482
4720
  recoverManagedSession(a) {
5483
- if (this.execution === "none")
5484
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
5485
- const restart = a.restart;
5486
- if (!restart || !restart.armed || restart.recovering || a.terminalizing)
5487
- return;
5488
- const release = this.beginLifecycle();
5489
- if (!release)
5490
- return; // preservation owns the cut once the lifecycle fence closes
5491
- const now = Date.now();
5492
- const limit = restart.policy?.restarts ?? SESSION_RESTART_LIMIT;
5493
- const windowMs = restart.policy?.windowMs ?? SESSION_RESTART_WINDOW_MS;
5494
- const supervised = restart.policy !== undefined;
5495
- restart.crashes = restart.crashes.filter((at) => now - at < windowMs);
5496
- restart.crashes.push(now);
5497
- if (restart.crashes.length > limit) {
5498
- console.error(`! ${a.name}: ${supervised ? "supervised" : "Pi"} crash loop (${restart.crashes.length} crashes in ${windowMs / 1000}s) - retiring the managed seat`);
5499
- restart.armed = false;
5500
- this.freeSlot(a, true, supervised ? "supervise-crash-loop" : "pi-crash-loop");
5501
- this.reapChildrenOf(this.managedPrincipal(a));
5502
- release();
5503
- return;
5504
- }
5505
- // An inline seat relaunches from its snapshot, so one that changed after launch, or a recorded
5506
- // path that names another file, would start a session its spawn never accepted. Every in-place
5507
- // restart passes here; the resume cut and a successor's restart make the same two checks in
5508
- // inventoryReferenceError.
5509
- const changed = this.inlineSnapshotChange(a);
5510
- if (changed) {
5511
- console.error(`! ${a.name}: ${changed} - retiring the managed seat instead of restarting it`);
5512
- restart.armed = false;
5513
- this.freeSlot(a, true, "inline-snapshot-changed");
5514
- this.reapChildrenOf(this.managedPrincipal(a));
5515
- release();
5516
- return;
5517
- }
5518
- restart.recovering = true;
5519
- void (async () => {
5520
- let replacement;
5521
- try {
5522
- // A dead PTY leader may have left tool processes in other sessions. Never build or launch
5523
- // a replacement until the runtime proves the whole prior execution closed.
5524
- if (!a.handle.waitForWorkExit)
5525
- throw new Error(`runtime "${a.handle.kind}" cannot prove prior local work ended; automatic restart refused`);
5526
- await withTimeout(a.handle.waitForWorkExit(), RESTART_WORK_EXIT_MS, `prior local work was not proved ended within ${RESTART_WORK_EXIT_MS}ms; automatic restart refused`);
5527
- if (this.agents.get(a.name) !== a || a.terminalizing || this.maintenanceState !== "active")
5528
- return;
5529
- const connector = await this.resolveConnector(a.agent);
5530
- if (this.agents.get(a.name) !== a || a.terminalizing || this.maintenanceState !== "active")
5531
- return;
5532
- const continueSession = connector.supportsSessionContinuation ? this.readManagedSession(a) : undefined;
5533
- const opts = continueSession !== undefined
5534
- ? { ...restart.opts, resume: undefined, reopenSession: undefined, prompt: undefined, continueSession }
5535
- : { ...restart.opts, resume: undefined, reopenSession: undefined, prompt: undefined };
5536
- const spec = connector.buildLaunch(opts);
5537
- spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
5538
- const wanted = this.managedPrincipal(a);
5539
- const joinedAfter = this.ep.getRoster()
5540
- .filter((p) => p.card.id === wanted && p.lifecycleUid === a.lifecycleUid)
5541
- .reduce((max, p) => Math.max(max, p.ts), 0) + 1;
5542
- // Same ordering as the spawn path: the replacement seat's reference is recorded on the
5543
- // still-active slot before its processes exist, so a crash here never strands it.
5544
- const runtime = this.runtimeFor(a.launch.runtime);
5545
- const custody = this.reserveCustody(runtime);
5546
- if (custody)
5547
- await this.recordSlotCustody(a, custody);
5548
- if (this.agents.get(a.name) !== a || a.terminalizing || this.maintenanceState !== "active") {
5549
- discardLaunchArtifacts(spec.artifacts); // No spawn was attempted, so no child can use them.
5550
- return;
5551
- }
5552
- const handle = await this.spawnCustodied(runtime, a.name, spec, a.launch.cwd, custody);
5553
- replacement = handle;
5554
- restart.sessionStatePath = spec.sessionStatePath ?? restart.sessionStatePath;
5555
- if (continueSession !== undefined) {
5556
- await this.awaitRecoveredSession(a, continueSession, handle, spec.control);
5557
- this.recordContinuity(a, continueSession);
5558
- }
5559
- else {
5560
- const previousHandle = a.handle;
5561
- const previousControl = a.control;
5562
- a.handle = handle;
5563
- a.control = spec.control;
5564
- try {
5565
- const readiness = await this.awaitReadiness(a, connector.readinessTimeoutMs ?? this.readinessTimeoutMs, {
5566
- reapOnExit: false,
5567
- joinedAfter,
5568
- });
5569
- if (!readiness.ok)
5570
- throw new Error(readiness.detail);
5571
- }
5572
- catch (error) {
5573
- a.handle = previousHandle;
5574
- a.control = previousControl;
5575
- throw error;
5576
- }
5577
- }
5578
- if (this.agents.get(a.name) !== a || a.terminalizing) {
5579
- try {
5580
- handle.stop({ graceful: false });
5581
- }
5582
- catch { /* terminal path owns cleanup */ }
5583
- return;
5584
- }
5585
- a.handle = handle;
5586
- a.control = spec.control;
5587
- await this.recordSlotRuntime(a);
5588
- replacement = undefined;
5589
- restart.opts = opts;
5590
- restart.recovering = false;
5591
- this.refreshSeatRecord(a);
5592
- if (continueSession !== undefined)
5593
- console.error(`! ${a.name}: recovered Pi session ${continueSession} after crash (${restart.crashes.length}/${limit})`);
5594
- else
5595
- console.error(`! ${a.name}: restarted under the same lifecycle after crash (${restart.crashes.length}/${limit})`);
5596
- this.watchExit(a);
5597
- }
5598
- catch (error) {
5599
- restart.recovering = false;
5600
- restart.armed = false;
5601
- let tail = "";
5602
- try {
5603
- tail = await this.tail((replacement ?? a.handle).attach());
5604
- }
5605
- catch (error) {
5606
- console.error(`! ${a.name}: last output unavailable: ${rejectionText(error)}`);
5607
- }
5608
- console.error(`! ${a.name}: ${supervised ? "supervised restart" : "Pi session recovery"} failed: ${rejectionText(error)}${tail ? ` - last output: ${tail}` : ""} - retiring the managed seat`);
5609
- // The replacement may be alive but unable to prove readiness. Stop it BEFORE
5610
- // retiring credentials/durables; otherwise an untracked process survives under torn auth.
5611
- try {
5612
- replacement?.stop({ graceful: false });
5613
- }
5614
- catch { /* terminal cleanup continues */ }
5615
- this.freeSlot(a, true, supervised ? "supervise-recovery-failed" : "pi-recovery-failed");
5616
- this.reapChildrenOf(this.managedPrincipal(a));
5617
- }
5618
- finally {
5619
- release();
5620
- }
5621
- })();
4721
+ return this.sessionRecovery.recoverManagedSession(a);
5622
4722
  }
5623
4723
  /** A managed agent's process exited: on its own (crash, /exit, finished), or after a stop this
5624
4724
  * manager started, whose recorded cause then frees the slot. Continuation-capable Pi seats
@@ -5656,58 +4756,9 @@ export class Manager {
5656
4756
  this.freeSlot(a, true, a.stopCause ?? "process-exit");
5657
4757
  this.reapChildrenOf(this.managedPrincipal(a));
5658
4758
  }
5659
- /** Agent names become `.cotal/agents/<name>.md` paths and mesh identities, so they must be bare
5660
- * tokens, never a path — blocks traversal / arbitrary writes from a model-supplied name. In user
5661
- * mode the name is ALSO the actor, which is a narrower alphabet still; {@link spawnNameError}
5662
- * holds both halves so this door and the auto-numbering that feeds it cannot disagree. */
5663
- nameError(name) {
5664
- return spawnNameError(name, { userMode: this.userMode });
5665
- }
5666
- /** The roster's LIVE occupant names (status !== offline) — occupants this manager may NOT manage
5667
- * (a foreground `cotal spawn`, a connector session, ANOTHER manager's agent). Allocating over any
5668
- * of them mints a sibling the broker/auth then refuses to admit, surfacing as the 30s launch-
5669
- * uncertain black hole. */
5670
- liveRosterNames() {
5671
- const live = new Set();
5672
- for (const p of this.ep.getRoster()) {
5673
- if (p.status === "offline")
5674
- continue;
5675
- const predecessor = this.confirmedRetiredPredecessors.get(p.card.name);
5676
- if (predecessor !== undefined && predecessor.principal === p.card.id && predecessor.lifecycleUid === p.lifecycleUid)
5677
- continue;
5678
- live.add(p.card.name);
5679
- }
5680
- return live;
5681
- }
5682
- /** THE single name-liveness predicate both the hard-pinned collision refuse and
5683
- * uniqueName's numbering consult, so they can never drift: a name is taken if this manager
5684
- * reserves/manages/retires it OR a roster-live occupant already holds it. Pass a pre-built
5685
- * {@link liveRosterNames} set when checking many names in one allocation. */
5686
- nameInUse(name, live = this.liveRosterNames()) {
5687
- return this.agents.has(name) || this.reserved.has(name) || this.retiring.has(name) || live.has(name);
5688
- }
5689
- /** First free name in the series `base`, `base_2`, `base_3`, … — checked against live slots,
5690
- * in-flight (reserved) slots, names held pending retirement, AND the live mesh roster. The
5691
- * roster check covers occupants this manager does not manage (a foreground `cotal spawn`, a
5692
- * connector session, another manager's agent): allocating their name would mint a sibling the
5693
- * broker/auth then refuses to admit, surfacing as a 30s launch-uncertain black hole instead of
5694
- * the auto-number the join path gives. Presence is ADVISORY (SPEC §6) — this is an availability
5695
- * choice at allocation, never an authority check (the broker still enforces): a stale
5696
- * still-live-looking row only costs a numbered suffix, and a missed freshly-joined occupant is
5697
- * still refused downstream exactly as before. Offline rows do NOT occupy — a properly retired
5698
- * name stays reusable. A row this manager itself confirmed retired (its alias, principal, and
5699
- * lifecycleUid all matching a {@link confirmedRetiredPredecessors} entry) does not occupy
5700
- * either, even while its advisory presence record ages out. A numbered name is never reissued
5701
- * ({@link issuedNumberedNames}), even after its holder retired. The requested base is exempt
5702
- * from that history: it is the persona's own name, which stays reusable even when it once came
5703
- * out of another persona's numbering. */
5704
- uniqueName(base, unavailable = new Set()) {
5705
- const live = this.liveRosterNames();
5706
- // The cap belongs to user mode alone: only there is the numbered name the actor. Static and open
5707
- // mode key the actor on the minted nkey, so a numbered name there has no length to fit.
5708
- const name = firstFreeName(base, (n) => unavailable.has(n) || this.nameInUse(n, live) || (n !== base && this.issuedNumberedNames.has(n)), this.userMode ? { actorBound: true } : undefined);
5709
- return name;
5710
- }
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); }
5711
4762
  /** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
5712
4763
  * under that file's own `name:`), as if a peer asked via the control plane. Used to pre-spawn the
5713
4764
  * demo's experts at startup so the manager owns them. */
@@ -6864,9 +5915,9 @@ export class Manager {
6864
5915
  // alone) so a retry re-drives the standing-authority revoke (INT-2) AND the broker cleanup before
6865
5916
  // any hold-clear (C): the alias must not free while the durable teardown or the revoke is still
6866
5917
  // outstanding. All the teardown ops are idempotent, and the rail request is single-flighted.
6867
- if (this.reconcilingAliases.has(identityName))
5918
+ if (this.staticLifecycle.isReconciling(identityName))
6868
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.` };
6869
- const held = this.retiring.get(identityName);
5920
+ const held = this.retirement.held(identityName);
6870
5921
  if (held !== undefined) {
6871
5922
  hooks?.onEffect?.();
6872
5923
  void this.deprovision(held.target).catch(() => { });
@@ -6972,7 +6023,7 @@ export class Manager {
6972
6023
  }
6973
6024
  // Another spawn may have reserved the candidate while the disk/broker proof awaited.
6974
6025
  // Recheck in the same synchronous window as the cap and reservation below.
6975
- if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.issuedNumberedNames.has(name))) {
6026
+ if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
6976
6027
  if (!hardPinned)
6977
6028
  continue;
6978
6029
  return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
@@ -7014,8 +6065,8 @@ export class Manager {
7014
6065
  // allocation, where there is no name to give back.
7015
6066
  hooks?.onEffect?.();
7016
6067
  if (!hardPinned && name !== identityName)
7017
- this.issuedNumberedNames.add(name);
7018
- this.reserved.set(name, owner);
6068
+ this.namesCapacity.rememberNumbered(name);
6069
+ this.namesCapacity.reserve(name, owner);
7019
6070
  try {
7020
6071
  // A stable nkey identity assigned at spawn: the public key is the agent's card.id (threaded via
7021
6072
  // COTAL_ID); the seed is retained to mint matching creds later.
@@ -7407,7 +6458,7 @@ export class Manager {
7407
6458
  });
7408
6459
  }
7409
6460
  this.agents.set(name, managed);
7410
- this.reservedLive.add(name);
6461
+ this.namesCapacity.placed(name);
7411
6462
  if (managed.once)
7412
6463
  this.watchOnceExit(managed);
7413
6464
  // The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
@@ -7590,8 +6641,7 @@ export class Manager {
7590
6641
  return { ok: false, error };
7591
6642
  }
7592
6643
  finally {
7593
- this.reserved.delete(name);
7594
- this.reservedLive.delete(name);
6644
+ this.namesCapacity.release(name);
7595
6645
  if (seatHome)
7596
6646
  rmSync(seatHome, { recursive: true, force: true });
7597
6647
  // A failed removal is logged, never thrown, so the grant's teardown below is still scheduled.
@@ -7607,7 +6657,7 @@ export class Manager {
7607
6657
  // retires it, and its name stays held for retireDelegatedAgent.
7608
6658
  const p = orphan.delegated ? parsePrincipalKey(orphan.id) : null;
7609
6659
  if (p)
7610
- this.retiring.set(orphan.name, { opId: managedRetirementOpId(orphan.lifecycleUid), owner: p.owner, actor: p.actor, target: orphan, startedAt: Date.now() });
6660
+ this.retirement.hold(orphan.name, { opId: managedRetirementOpId(orphan.lifecycleUid), owner: p.owner, actor: p.actor, target: orphan, startedAt: Date.now() });
7611
6661
  this.trackDeprovision(orphan, "(orphaned spawn)");
7612
6662
  }
7613
6663
  }
@@ -7648,7 +6698,7 @@ export class Manager {
7648
6698
  // must not hide the durable teardown state the manager already owns. Refuse and re-drive the
7649
6699
  // exact held lifecycle before consulting generic principal liveness. A confirmed terminal has
7650
6700
  // already removed the hold, so fresh-lifecycle resume still reaches the fail-closed roster gate.
7651
- const held = this.retiring.get(entry.name);
6701
+ const held = this.retirement.held(entry.name);
7652
6702
  if (held) {
7653
6703
  void this.deprovision(held.target).catch(() => { });
7654
6704
  return {
@@ -7669,7 +6719,7 @@ export class Manager {
7669
6719
  if (principals.has(principal))
7670
6720
  return { ok: false, agents: [], error: `resume inventory contains duplicate principal "${principal}"` };
7671
6721
  principals.add(principal);
7672
- const confirmedPredecessor = this.confirmedRetiredPredecessors.get(entry.name);
6722
+ const confirmedPredecessor = this.retirement.predecessor(entry.name);
7673
6723
  const principalIsLive = liveRoster.some((presence) => {
7674
6724
  if (presence.card.id !== principal)
7675
6725
  return false;
@@ -7685,11 +6735,11 @@ export class Manager {
7685
6735
  return { ok: false, agents: [], error: `retained principal "${principal}" is already live and this runtime cannot authoritatively adopt it` };
7686
6736
  orphans.push({ principal, reference: orphan });
7687
6737
  }
7688
- if (this.agents.has(entry.name) || this.reserved.has(entry.name))
6738
+ if (this.agents.has(entry.name) || this.namesCapacity.isReserved(entry.name))
7689
6739
  return { ok: false, agents: [], error: `retained agent "${entry.name}" is already managed or reserved` };
7690
6740
  }
7691
6741
  for (const entry of entries) {
7692
- this.reserved.set(entry.name, resumeOwner(entry));
6742
+ this.namesCapacity.reserve(entry.name, resumeOwner(entry));
7693
6743
  batchReservations.push(entry.name);
7694
6744
  }
7695
6745
  const preflight = [];
@@ -7728,8 +6778,7 @@ export class Manager {
7728
6778
  }
7729
6779
  finally {
7730
6780
  for (const name of batchReservations) {
7731
- this.reserved.delete(name);
7732
- this.reservedLive.delete(name);
6781
+ this.namesCapacity.release(name);
7733
6782
  }
7734
6783
  // Preflight builds every launch before any child starts, so a refused batch, a failed launch,
7735
6784
  // or the agents skipped after it leave built specs no runtime ever received.
@@ -7972,7 +7021,7 @@ export class Manager {
7972
7021
  const nameErr = this.nameError(entry.name);
7973
7022
  if (nameErr)
7974
7023
  return { ok: false, error: nameErr };
7975
- 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)))
7976
7025
  return { ok: false, error: `retained agent "${entry.name}" is already managed or reserved; same-principal resume never auto-numbers` };
7977
7026
  const occupancy = batchReserved ? undefined : this.occupancy();
7978
7027
  if (occupancy && occupancy.used >= MAX_AGENTS)
@@ -8118,7 +7167,7 @@ export class Manager {
8118
7167
  }
8119
7168
  async launchPreparedResume(entry, prepared, batchReserved, supervised) {
8120
7169
  if (!batchReserved)
8121
- this.reserved.set(entry.name, resumeOwner(entry));
7170
+ this.namesCapacity.reserve(entry.name, resumeOwner(entry));
8122
7171
  try {
8123
7172
  // Recover the STATIC identity's nkey seed from the adopted credential (the
8124
7173
  // creds file embeds it) so the manager stays this incarnation's RENEWAL OWNER across a
@@ -8198,7 +7247,7 @@ export class Manager {
8198
7247
  suppressCleanup: true,
8199
7248
  };
8200
7249
  this.agents.set(entry.name, managed);
8201
- this.reservedLive.add(entry.name);
7250
+ this.namesCapacity.placed(entry.name);
8202
7251
  if (this.resumeAttemptId)
8203
7252
  this.resumedAgentNames.add(entry.name);
8204
7253
  try {
@@ -8239,8 +7288,7 @@ export class Manager {
8239
7288
  }
8240
7289
  finally {
8241
7290
  if (!batchReserved) {
8242
- this.reserved.delete(entry.name);
8243
- this.reservedLive.delete(entry.name);
7291
+ this.namesCapacity.release(entry.name);
8244
7292
  }
8245
7293
  }
8246
7294
  }
@@ -8555,55 +7603,9 @@ export class Manager {
8555
7603
  if (!watched)
8556
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`);
8557
7605
  }
8558
- /** Prune expired cooling stamps (drop those at/before now) and return the live count — the
8559
- * recycle floor's contribution to the ceiling (P4c). Lazy: pruned only when the gate consults it. */
8560
- coolingCount() {
8561
- const now = Date.now();
8562
- this.cooling = this.cooling.filter((stamp) => stamp > now);
8563
- return this.cooling.length;
8564
- }
8565
- /** What holds the ceiling's slots, one count per seat (#906). A launching seat sits in `reserved`
8566
- * from accept until its launch settles, in `agents` once its process exists, and in `cooling`
8567
- * if it then frees young, so a reservation stops counting once it reaches `agents`. `managed` is
8568
- * what this manager's `ps` lists, `reserved` is the accepted launches that have no process yet,
8569
- * and `launching` is every unsettled launch that still holds a slot through `reserved` or
8570
- * `agents`. A launch whose seat already freed holds no slot but its cooling stamp, so its
8571
- * failure can free nothing. */
8572
- occupancy() {
8573
- const cooling = this.coolingCount();
8574
- let reserved = 0;
8575
- let launching = 0;
8576
- for (const name of this.reserved.keys()) {
8577
- const placed = this.reservedLive.has(name);
8578
- if (!placed)
8579
- reserved++;
8580
- if (!placed || this.agents.has(name))
8581
- launching++;
8582
- }
8583
- const managed = this.agents.size;
8584
- return {
8585
- managed,
8586
- reserved,
8587
- cooling,
8588
- launching,
8589
- used: managed + reserved + cooling,
8590
- nextCoolingMs: cooling ? Math.min(...this.cooling) - Date.now() : undefined,
8591
- };
8592
- }
8593
- occupancyText(o) {
8594
- return `${o.used} of ${MAX_AGENTS} slots: ${o.managed} managed, ${o.reserved} reserved, ${o.cooling} cooling`;
8595
- }
8596
- /** The capacity refusal states the split it enforces and whether waiting can free a slot: a
8597
- * cooling slot frees at a known time, an unsettled launch frees one only if it fails, and a
8598
- * managed seat frees one only when it is stopped. */
8599
- capacityRefusal(o) {
8600
- const remedy = o.nextCoolingMs !== undefined
8601
- ? `waiting frees a cooling slot in ${Math.ceil(o.nextCoolingMs / 1000)}s, or despawn one`
8602
- : o.launching
8603
- ? `waiting frees a slot only if an unsettled launch fails (${o.launching} pending); otherwise despawn one`
8604
- : "waiting frees no slot; despawn one";
8605
- return `at capacity (${this.occupancyText(o)}); ${remedy}`;
8606
- }
7606
+ occupancy() { return this.namesCapacity.occupancy(); }
7607
+ occupancyText(o) { return this.namesCapacity.occupancyText(o); }
7608
+ capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
8607
7609
  /**
8608
7610
  * The owner a launch belongs to, read ONCE so the per-owner ceiling, the agent's addressing
8609
7611
  * triple and the user-mode provisioner cannot charge three different owners for one seat. A
@@ -8635,9 +7637,7 @@ export class Manager {
8635
7637
  for (const a of this.agents.values())
8636
7638
  if (this.seatOwner(a) === owner)
8637
7639
  seats++;
8638
- for (const [name, reservedFor] of this.reserved)
8639
- if (reservedFor === owner && !this.reservedLive.has(name))
8640
- seats++;
7640
+ seats += this.namesCapacity.ownerReservations(owner);
8641
7641
  return seats;
8642
7642
  }
8643
7643
  /**
@@ -8713,7 +7713,7 @@ export class Manager {
8713
7713
  return { ok: false, error: this.maintenanceError() };
8714
7714
  try {
8715
7715
  const live = this.agents.get(name);
8716
- const held = live ? undefined : this.retiring.get(name);
7716
+ const held = live ? undefined : this.retirement.held(name);
8717
7717
  const principal = live?.delegated ? parsePrincipalKey(live.id) : held?.target.delegated ? held : null;
8718
7718
  const lifecycleUid = live?.lifecycleUid ?? held?.target.lifecycleUid;
8719
7719
  if (!principal || !lifecycleUid)
@@ -8729,7 +7729,7 @@ export class Manager {
8729
7729
  }
8730
7730
  catch (e) {
8731
7731
  const error = `the delegated retirement under intent ${intentId} did not complete (${rejectionText(e)})`;
8732
- const hold = this.retiring.get(name);
7732
+ const hold = this.retirement.held(name);
8733
7733
  if (hold?.target.lifecycleUid === target.lifecycleUid)
8734
7734
  hold.lastError = error;
8735
7735
  return { ok: false, error: `${error}; "${name}" is unchanged` };
@@ -8745,7 +7745,7 @@ export class Manager {
8745
7745
  await this.shredUserSecrets(unshredded, (live ?? held?.target)?.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, target.lifecycleUid));
8746
7746
  if (unshredded.length) {
8747
7747
  const error = `the host retired "${name}" at ${target.lifecycleUid}, but cleanup failed: ${describeCleanupFailures(unshredded)}; the name stays held until a retried retirement intent removes it`;
8748
- const hold = this.retiring.get(name);
7748
+ const hold = this.retirement.held(name);
8749
7749
  if (hold?.target.lifecycleUid === target.lifecycleUid)
8750
7750
  hold.lastError = error;
8751
7751
  return { ok: false, error };
@@ -8930,10 +7930,10 @@ export class Manager {
8930
7930
  resumeRequired: this.resumeRequired,
8931
7931
  stopping: this.leaseStopping,
8932
7932
  lifecycleInFlight: this.lifecycleInFlight,
8933
- reservedLaunches: this.reserved.size,
8934
- retirementsPending: this.retiring.size,
8935
- deprovisioningInFlight: this.deprovisioningFlight.size,
8936
- staticReconciliationInFlight: this.staticReconcileSweepsInFlight,
7933
+ reservedLaunches: this.namesCapacity.reservedCount,
7934
+ retirementsPending: this.retirement.pendingCount,
7935
+ deprovisioningInFlight: this.retirement.inFlightCount,
7936
+ staticReconciliationInFlight: this.staticLifecycle.sweepsInFlight,
8937
7937
  agents: [...this.agents.values()]
8938
7938
  .filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter)
8939
7939
  .map((a) => ({
@@ -8953,23 +7953,8 @@ export class Manager {
8953
7953
  },
8954
7954
  };
8955
7955
  }
8956
- /** Render the current operator snapshot. Recovered rows live until the next sweep starts, then
8957
- * clear, so recovery is visible without becoming stale process-lifetime history. */
8958
7956
  staticReconciliationStatus() {
8959
- const failures = [...this.staticReconcileItems.values()]
8960
- .map(({ owner: _owner, timer: _timer, flight: _flight, retryFlight: _retryFlight, ...item }) => ({ ...item }))
8961
- .sort((a, b) => a.alias.localeCompare(b.alias));
8962
- const state = this.staticReconcileLastSweep?.error !== undefined ? "failed" :
8963
- failures.some((item) => item.disposition === "retrying") ? "retrying" :
8964
- failures.some((item) => item.disposition === "retry-scheduled") ? "retry-wait" :
8965
- failures.some((item) => item.disposition === "refused" || item.disposition === "refused-foreign" || item.disposition === "retry-exhausted") ? "failed" :
8966
- this.staticReconcileSweepsInFlight > 0 ? "running" :
8967
- failures.some((item) => item.disposition === "recovered") ? "recovered" : "idle";
8968
- return {
8969
- state,
8970
- ...(this.staticReconcileLastSweep ? { lastSweep: { ...this.staticReconcileLastSweep } } : {}),
8971
- failures,
8972
- };
7957
+ return this.staticLifecycle.staticReconciliationStatus();
8973
7958
  }
8974
7959
  /** Complete a crashed predecessor's FROZEN registration gate before this incarnation starts a
8975
7960
  * new one (#783 item 3 / #871). The CLI `cotal reconcile-gate` already does this; a successor
@@ -9017,353 +8002,8 @@ export class Manager {
9017
8002
  }
9018
8003
  console.error(`✓ boot self-heal: ${MANAGER_ENDPOINT}/${instanceId} registration gate reopened at generation ${report.reopenedAtGeneration} (processEpoch ${report.after.processEpoch}, registrationRevision ${report.after.registrationRevision}; freeze-holder gone, sweepComplete=true). Continuing the normal takeover.`);
9019
8004
  }
9020
- /** #2073: dial the manager's ONE control-plane connection and serve its typed command surface on
9021
- * it, exactly the shape `registerManagerService` used inline before this lane. Shared by the
9022
- * initial registration AND the closed-connection recovery path ({@link onServeConnectionClosed}),
9023
- * so there is one place that dials and serves this endpoint. Attaches {@link
9024
- * onServeConnectionClosed} as the close handler in both cases: a closed serve connection is
9025
- * always a fault this manager acts on, never a bare log line. */
9026
- async dialServeConnection(state, readCreds = () => state.creds, deadline) {
9027
- const opts = {
9028
- // Open mesh: a bare serve connection (no credential exists; the broker enforces nothing).
9029
- ...(state.creds !== undefined ? standaloneConnectOpts({ creds: readCreds, tls: false }) : {}),
9030
- inboxPrefix: `_INBOX_${state.identity.id}`,
9031
- maxReconnectAttempts: -1,
9032
- };
9033
- const nc = await (deadline === undefined ? this.dial(opts) : this.dialRemoteStanding(opts, deadline));
9034
- this.trackTransport(nc);
9035
- let handle;
9036
- try {
9037
- // The typed surface + the derived `describe`. The descriptor stays PUBLIC in static
9038
- // mode: the broker grant (who holds each command's request-publish row) is the
9039
- // load-bearing authority tier, and a static single-operator mesh leaks nothing by listing
9040
- // command names; the trusted per-caller `view(caller)` scoping joins the user-mode
9041
- // registration follow-up (where actorScope is the trusted source). Every ordinary handler
9042
- // runs the SHARED admission chokepoint ({@link serveGated}).
9043
- handle = serveEndpoint(nc, this.space, state.grant, this.managerServiceDefs(), { public: true }, {
9044
- // The FRESH target resolver (§13.3) for the targeted commands (`despawn`/`attach`): the
9045
- // manager's live managed set IS the current-mapping authority for its own agents (the
9046
- // durable slot rows mirror it). Static mode carries no mapping-revision dimension, so
9047
- // the revision is the constant 0 — a caller that pins a revision pins 0.
9048
- resolveTarget: (t) => {
9049
- if (this.remoteAuthority) {
9050
- const key = principalKey(t.owner, t.actor).key;
9051
- for (const a of this.agents.values())
9052
- if (a.id === key)
9053
- return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
9054
- const participant = [...this.participants.values()].find((p) => p.owner === t.owner && p.actor === t.actor && this.currentParticipant(p.owner, p.actor, p.uid) === p);
9055
- return participant ? { lifecycleUid: participant.uid, mappingRevision: 0 } : undefined;
9056
- }
9057
- if (t.owner === DEV_OWNER) {
9058
- for (const a of this.agents.values())
9059
- if (!a.userOwner && a.id === t.actor)
9060
- return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
9061
- return undefined;
9062
- }
9063
- const key = principalKey(t.owner, t.actor).key;
9064
- for (const a of this.agents.values())
9065
- if (a.userOwner && a.id === key)
9066
- return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
9067
- return undefined;
9068
- },
9069
- ...(this.omitClassCommands() ? { omitClassCommands: this.omitClassCommands() } : {}),
9070
- });
9071
- // A subscribed replacement must be visible to the broker before the old rails retire.
9072
- if (deadline === undefined)
9073
- await nc.flush();
9074
- else
9075
- await withTimeout(nc.flush(), remoteStandingTimeLeft(deadline), "remote manager standing serve flush exceeded its 10000ms aggregate budget");
9076
- }
9077
- catch (e) {
9078
- await this.discardServeCandidate(nc, handle);
9079
- throw e;
9080
- }
9081
- // Wired only once the connection serves: a candidate this method closes after a
9082
- // refused serve is not a fault to recover, and the caller already sees the refusal.
9083
- nc.closed().then((err) => {
9084
- if (this.serviceServe?.nc === nc)
9085
- void this.onServeConnectionClosed(err ?? undefined, nc);
9086
- });
9087
- return { nc, handle };
9088
- }
9089
- /** #2073: re-mint the SAME `endpoint-serve` identity through the SAME scoped one-shot executor and
9090
- * §13.1 mint fence `renewDaemonCreds`'s serve branch uses — never a second copy of that mint. Used
9091
- * by both the periodic renewal pass and the closed-connection recovery path below, so a
9092
- * superseded instance's re-mint fails the SAME gate CAS in both places and lands in the exit
9093
- * path rather than needing a second epoch check. */
9094
- async remintServeCreds(s) {
9095
- const authRef = this.auth;
9096
- return this.withEndpointServeExecutor(({ authKv }) => mintCreds(authRef, s.identity, "endpoint-serve", {
9097
- serveIssuance: serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId }),
9098
- endpointServe: s.grant,
9099
- }));
9100
- }
9101
- /** #2073: a closed serve connection is a FAULT the manager acts on, not a log line: this is the
9102
- * control plane a report showed staying dead for hours while the process kept its liveness
9103
- * lease and answered nothing (#2073). `stop()` sets `leaseStopping` BEFORE it tears down this
9104
- * connection, so a close landing from OUR OWN graceful teardown returns here at once. Any other
9105
- * close re-dials with the current credential (a transport blip needs nothing new), re-mints
9106
- * through the existing serve branch when the credential itself has expired, and re-serves on the
9107
- * new connection — bounded by {@link STATIC_RECONCILE_RETRY_DELAYS_MS}. Exhausting every attempt
9108
- * releases this process's lease and exits loud (without `withAgents`, so seats stay up, the path
9109
- * `supervise`'s signal handler already uses) so a restart can serve: a manager that holds the
9110
- * lease and answers nothing is the worst of the three states this issue named, and holding the
9111
- * connection open under unbounded reconnects (the transport-drop case) never reaches this method
9112
- * at all — `nc.closed()` does not resolve until the client itself gives up. */
9113
- async onServeConnectionClosed(err, closed) {
9114
- if (this.leaseStopping)
9115
- return;
9116
- const s = this.serviceServe;
9117
- console.error(`! manager service endpoint connection closed: ${err?.message ?? "unknown reason"}`);
9118
- const recovered = await this.boundedReconnect("service endpoint", async () => {
9119
- if (!s)
9120
- return false;
9121
- const deadline = this.remoteAuthority ? performance.now() + REMOTE_STANDING_BUDGET_MS : undefined;
9122
- // Let an admitted renewal finish owning its candidate before recovery opens another.
9123
- if (deadline === undefined)
9124
- await this.remoteBundleRenewal;
9125
- else
9126
- await withTimeout(Promise.resolve(this.remoteBundleRenewal), remoteStandingTimeLeft(deadline), "remote manager closed-serve renewal wait exceeded its 10000ms aggregate budget");
9127
- if (this.leaseStopping || this.serviceServe !== s || s.nc !== closed)
9128
- return true;
9129
- if (deadline !== undefined)
9130
- await withTimeout(this.renewRemoteBeforeRedial("serve", () => s.creds), remoteStandingTimeLeft(deadline), "remote manager closed-serve renewal wait exceeded its 10000ms aggregate budget");
9131
- else if (inspectCredHealth(s.creds ?? "").state !== "healthy" && s.creds !== undefined) {
9132
- s.creds = await this.remintServeCreds(s);
9133
- this.scheduleServeRenewal(s.creds);
9134
- }
9135
- if (this.leaseStopping || this.serviceServe !== s || s.nc !== closed)
9136
- return true;
9137
- const { nc, handle } = await this.dialServeConnection(s, undefined, deadline);
9138
- if (this.leaseStopping || this.serviceServe !== s || s.nc !== closed) {
9139
- try {
9140
- await handle.stop();
9141
- }
9142
- finally {
9143
- await nc.close();
9144
- }
9145
- return true;
9146
- }
9147
- s.nc = nc;
9148
- s.handle = handle;
9149
- console.error(`manager service endpoint re-dialed: ${MANAGER_ENDPOINT}/${this.managerInstanceId} (epoch ${s.grant.epoch})`);
9150
- return true;
9151
- });
9152
- if (this.leaseStopping || recovered)
9153
- return;
9154
- console.error(`! manager service endpoint could not be restored for ${this.space}/${MANAGER_ENDPOINT}/${this.managerInstanceId}: releasing the lease and exiting`);
9155
- await this.stop();
9156
- process.exit(1);
9157
- }
9158
- /** Register the manager as an ordinary v0.4 `service` endpoint and serve its typed
9159
- * command surface on the ep rails - the manager's ONLY control door. On an AUTH mesh
9160
- * the whole credential path is the SAME one an ordinary endpoint traverses (the enforcement
9161
- * test that keeps "ordinary" honest): provision the §13.1 issuance gate, drive the
9162
- * registration BARRIER's gate CAS, then release the serve credential only on the mint FENCE's
9163
- * revision-pinned CAS win — all over the scoped one-shot executor ({@link
9164
- * withEndpointServeExecutor}), never a seed-signed shortcut. Holding the signing seed only
9165
- * AUTHORIZES the reserved single-label name (`manager`, operator name authority, DEV_OWNER).
9166
- * On an OPEN mesh the same gate/registration/serve-grant ceremony runs over bare one-shot
9167
- * connections and NO credential is ever minted: there is no credential system to issue from,
9168
- * so the gate legitimately keeps an empty `epcred` family (the §13.1 fence is issuance-only)
9169
- * and the serve connection is bare — the broker enforces nothing on an open mesh, exactly the
9170
- * old open-mesh ctl trust ("open = single-trusted-host"). */
9171
- async registerManagerService() {
9172
- const auth = this.auth;
9173
- if (this.remoteAuthority) {
9174
- const remote = this.remoteAuthority;
9175
- this.goalWriterIdentity = remote.identities.goalWriter;
9176
- this.sessionLedgerIdentity = remote.identities.sessionLedger;
9177
- this.goalWriterCreds = remote.goalWriterCreds;
9178
- this.sessionLedgerCreds = remote.sessionLedgerCreds;
9179
- const state = {
9180
- handle: undefined,
9181
- nc: undefined,
9182
- identity: remote.identities.serve,
9183
- grant: remote.serveGrant,
9184
- creds: remote.serveCreds,
9185
- };
9186
- // The shared dialer wires the closed-connection handler, which re-dials through the all-duty family.
9187
- const { nc, handle } = await this.dialServeConnection(state);
9188
- state.handle = handle;
9189
- state.nc = nc;
9190
- this.serviceServe = state;
9191
- console.error(`remote manager service endpoint activated: ${MANAGER_ENDPOINT}/${this.managerInstanceId} (epoch ${state.grant.epoch})`);
9192
- return;
9193
- }
9194
- // The §13.7 contract store is REGISTRATION's dependency, ensured here MODE-NEUTRALLY:
9195
- // it used to ride the static-only lifecycle reconcile, so a USER-mode manager registered
9196
- // against an absent stream and its artifact publish died no-responders (live-repro'd). A
9197
- // provisioner one-shot creates-or-verifies it (config-B immutability incl. the shadowed-legacy
9198
- // refuse) before the executor publishes a single artifact.
9199
- {
9200
- // Open mesh: the bare connection holds the rights (there is no credential system to mint from).
9201
- const provCreds = auth ? await mintCreds(auth, newIdentity(), "provisioner") : undefined;
9202
- const provNc = await this.dial({ ...standaloneConnectOpts({ creds: provCreds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
9203
- try {
9204
- // The manager now WRITES goal facts (EPF) + progress events (EPE), so the §13.12
9205
- // endpoint streams must exist. Nothing provisioned them before spawn-as-action (no endpoint
9206
- // wrote to EPF/EPE), so the manager ensures the full set here over the provisioner (whose
9207
- // STREAM.CREATE now covers them), idempotently - createEndpointStreams is a superset of
9208
- // ensureContractStore + ensureAuthorityStores, fail-loud on drift. Auth + open both run this.
9209
- await createEndpointStreams(await jetstreamManager(provNc), new Kvm(provNc), this.space);
9210
- }
9211
- finally {
9212
- await drainAndClose(provNc);
9213
- }
9214
- }
9215
- const iid = this.managerInstanceId;
9216
- const artifacts = managerClusterArtifacts();
9217
- // In-memory §13.7 content store: the manager is this document's AUTHOR, so registration and
9218
- // serve authorization verify against the exact artifacts it publishes from memory. The DURABLE
9219
- // `epc` contract-store publication (for third-party digest fetches) runs below inside the same
9220
- // executor, BEFORE the registration that advertises the digests.
9221
- const store = new Map([
9222
- [artifacts.rootDigest, artifacts.document],
9223
- [artifacts.closureDigest, artifacts.manifest],
9224
- ]);
9225
- const readClusterArtifact = (digest) => store.get(digest);
9226
- // §13.9 name authority, static mode: `manager` is a core single-label name requiring OPERATOR
9227
- // authority — the manager holds the space signing seed, so it self-authorizes exactly its own
9228
- // name for exactly DEV_OWNER (never a general authority; any other (name, owner) refuses).
9229
- const authority = {
9230
- authorize: (name, owner) => ({ authorized: name === MANAGER_ENDPOINT && owner === DEV_OWNER, revision: 0 }),
9231
- };
9232
- // The STABLE serve identity: the PERSISTED serve nkey, reused across restart so the
9233
- // gate binds the SAME principal (§13.1 serving-principal binding) - provisionEndpointGateOpen
9234
- // stays idempotent and verified eviction has a stable target. Renewals re-mint the same nkey
9235
- // with a fresh bounded exp; a restart re-provisions the same (idempotent) gate + re-registers.
9236
- const serveIdentity = this.managerServeIdentity;
9237
- const servePrincipal = principalKey(DEV_OWNER, serveIdentity.id).key;
9238
- // An open mesh mints no credentials, so it has no family for a fresh pair to grow.
9239
- const siblings = auth ? claimManagerSiblingIdentities(this.workspaceRoot, this.space) : { goalWriter: newIdentity(), sessionLedger: newIdentity() };
9240
- // The STABLE goal-writer identity — a SIBLING credential in the same §13.1 family
9241
- // (not the gate's bound serving principal), so the run block can family-stage it.
9242
- this.goalWriterIdentity = siblings.goalWriter;
9243
- // The STABLE session-LEDGER identity — another SIBLING in the SAME §13.1 family, so
9244
- // the takeover barrier revokes a deposed manager's ledger cred alongside its goal-writer. The
9245
- // per-session serving creds join the same family, each with its own fresh identity.
9246
- this.sessionLedgerIdentity = siblings.sessionLedger;
9247
- // One registration operation for this boot. Fresh executors may replace a dead connection, but
9248
- // they must resume THIS freeze rather than minting a new op that discards Phase-2 progress.
9249
- const registrationOpId = mintLifecycleUid();
9250
- const executorExpired = (e) => /closed connection/i.test(rejectionText(e));
9251
- const retryExpiredExecutor = async (label, fn) => {
9252
- for (;;) {
9253
- try {
9254
- return await fn();
9255
- }
9256
- catch (e) {
9257
- if (!executorExpired(e))
9258
- throw e;
9259
- console.error(`manager ${label} executor expired; retrying${label === "registration" ? ` operation ${registrationOpId}` : ""} with fresh scoped authority`);
9260
- }
9261
- }
9262
- };
9263
- const publishAndProvision = async ({ authKv, nc: execNc }) => {
9264
- // §13.7 contract-artifact publication: every schema root + its closure manifest, plus
9265
- // the cluster document + ITS manifest, land in the EPC store BEFORE the registration that
9266
- // advertises their digests — so a caller can always fetch-verify-compile a registered
9267
- // digest (the generic-invoke read path). Create-only + content-addressed: a retry
9268
- // or a same-artifact republish is an idempotent lost-CAS. The registration itself still
9269
- // verifies against the in-memory copies (the manager is the author).
9270
- const storeCtx = await contractStoreContext(execNc, this.space);
9271
- for (const value of [...managerContractArtifactValues(), artifacts.document, artifacts.manifest])
9272
- await publishContractArtifact(storeCtx, contractArtifactCanonicalBytes(value));
9273
- // §13.1 pre-registration: the issuance gate, born open@gen0 bound to the serve
9274
- // principal — provisioned ONCE, on the FIRST registration. On a RESTART the gate
9275
- // already EXISTS (advanced past gen0 by the prior registration), so re-provisioning the gen0
9276
- // row would conflict "foreign content"; the persisted instanceId makes this a TAKEOVER, and
9277
- // registerServiceInstance below freezes + re-registers the EXISTING gate (advancing the epoch
9278
- // after it verify-evicts the superseded family). The serve principal is the SAME persisted one,
9279
- // so the gate's principal binding is unchanged either way.
9280
- if ((await serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid }).observe()) === null)
9281
- await provisionEndpointGateOpen(authKv, { endpoint: MANAGER_ENDPOINT, instanceId: iid, principal: servePrincipal });
9282
- };
9283
- const completeRegistration = async ({ recordsKv, authKv, nc: execNc }) => {
9284
- await publishAndProvision({ recordsKv, authKv, nc: execNc });
9285
- // On an AUTH mesh a RE-registration (restart of the persisted instanceId)
9286
- // must VERIFY-EVICT the superseded serve family BEFORE the epoch advances (§13.1 "old authority
9287
- // dies before new authority is visible"). Inject the SCOPED delivery-admin evictor; the OPEN
9288
- // mesh mints no serve family, so its empty-family restart never consults an evictor, and one
9289
- // an earlier release staged there stays unverified with the reason in the refusal
9290
- // ({@link openMeshUnverifiedEviction}). NO-ORACLE = LOUD: with no reachable delivery daemon the
9291
- // evictor THROWS naming the cure, so PHASE 2 fails closed with the delivery-daemon fix in the
9292
- // error text — a crash-restart never silently skips eviction (no-fallbacks).
9293
- const barrier = endpointRegistrationBarrier(authKv, this.space, {
9294
- endpoint: MANAGER_ENDPOINT, instanceId: iid, opId: registrationOpId,
9295
- evict: auth ? makeManagerEndpointHolderEvictor({ space: this.space, servers: this.servers ?? DEFAULT_SERVER, auth, log: (line) => console.error(line), unreachableWaitMs: DELIVERY_ADMIN_BOOT_WAIT_MS }) : openMeshUnverifiedEviction,
9296
- });
9297
- const spec = { endpoint: MANAGER_ENDPOINT, owner: DEV_OWNER, clusterDigests: [artifacts.closureDigest], protocol: { v: 1 } };
9298
- const { grant } = await registerServingInstance(recordsKv, {
9299
- space: this.space, spec, instanceId: iid, registrant: { owner: DEV_OWNER }, authority, barrier, readClusterArtifact,
9300
- // #1393: when a FOREIGN instance holds the endpoint governance slot, let core tell an
9301
- // in-flight registration from one abandoned by a predecessor that died between its
9302
- // slot-take and its spec publish. The read rides THIS executor's existing auth-bucket read
9303
- // grant (no new grant, no new writer); core refuses on anything but a gate provably
9304
- // reopened past the slot's stamp.
9305
- observeHolderGeneration: (holderInstanceId) => readEndpointGateGeneration(authKv, { endpoint: MANAGER_ENDPOINT, instanceId: holderInstanceId }),
9306
- status: { connectors: this.connectorStatuses.map((row) => ({ ...row, binaries: { ...row.binaries } })) },
9307
- });
9308
- const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
9309
- // Open mesh: NO mint - the §13.1 fence is issuance-only and nothing is ever issued, so the
9310
- // gate keeps an empty `epcred` family; the serve connection below stays bare.
9311
- const creds = auth ? await mintCreds(auth, serveIdentity, "endpoint-serve", { serveIssuance: fence, endpointServe: grant }) : undefined;
9312
- // Mint + family-stage the goal-writer credential HERE, over this executor's
9313
- // authKv (the fence is live), so its credId lands in `epcred.<e>.<iid>` and the takeover
9314
- // barrier revokes it. Open mesh: no mint (no credential system; the goal-writer conn is bare).
9315
- const goalWriterCreds = auth ? await this.mintAndStageGoalWriter(authKv) : undefined;
9316
- // Mint + family-stage the session-LEDGER credential HERE too (same executor, same
9317
- // fence, same §13.1 family), so takeover revokes a deposed manager's ledger connection. The
9318
- // per-session SERVING credentials are minted later, one per redemption, into the SAME family.
9319
- // Open mesh: no mint (no credential system; the ledger connection stays bare).
9320
- const sessionLedgerCreds = auth ? await this.mintAndStageSessionLedger(authKv) : undefined;
9321
- return { grant, creds, goalWriterCreds, sessionLedgerCreds };
9322
- };
9323
- let registration;
9324
- if (auth) {
9325
- // Boot heal may consume an arbitrarily large prior family. End that executor window here and
9326
- // mint fresh scoped authority for the new registration, rather than forcing heal + takeover
9327
- // through one fixed-lifetime connection. A closed connection during heal retries the SAME
9328
- // frozen predecessor op via reconcile's durable cursor; a closed connection during
9329
- // registration retries THIS boot's operationId without heal, so Phase-2 progress stays bound.
9330
- // #783/#871: a predecessor that died mid-barrier leaves this gate frozen under a
9331
- // registration op. registerServiceInstance will then refuse SPEC 13.8 forever, even
9332
- // when the freeze-holder is gone. Complete that SAME op (abort-reopen) on independent
9333
- // holder-gone evidence BEFORE this incarnation freezes a new one. Auth only: the
9334
- // CONNZ oracle rides delivery-admin, which an open mesh does not have.
9335
- await retryExpiredExecutor("boot-heal", () => this.withEndpointServeExecutor(async ({ recordsKv, authKv, nc: execNc }) => {
9336
- await publishAndProvision({ recordsKv, authKv, nc: execNc });
9337
- if (auth) {
9338
- await this.healFrozenRegistrationGate(authKv, iid, auth, recordsKv);
9339
- }
9340
- }));
9341
- registration = await retryExpiredExecutor("registration", () => this.withEndpointServeExecutor(completeRegistration));
9342
- }
9343
- else {
9344
- registration = await this.withOpenServeConnection(completeRegistration).catch((e) => { throw openMeshFrozenGateRefusal(e, iid); });
9345
- }
9346
- if (!registration)
9347
- throw new Error("manager registration produced no serve authority");
9348
- const { grant, creds, goalWriterCreds, sessionLedgerCreds } = registration;
9349
- this.goalWriterCreds = goalWriterCreds;
9350
- this.sessionLedgerCreds = sessionLedgerCreds;
9351
- // The serve connection presents the CURRENT credential on every (re)connect (the state object
9352
- // is captured by the authenticator), so a fence-traversing renewal is adopted by reconnect
9353
- // without re-registration. Reconnects stay unbounded: the serve rails are this instance's
9354
- // registered surface for its whole incarnation.
9355
- const state = { handle: undefined, nc: undefined, identity: serveIdentity, grant, creds };
9356
- const { nc, handle } = await this.dialServeConnection(state);
9357
- state.nc = nc;
9358
- state.handle = handle;
9359
- this.serviceServe = state;
9360
- console.error(`manager service endpoint registered: ${MANAGER_ENDPOINT}/${iid} (epoch ${grant.epoch}, registrationRevision ${grant.registrationRevision})`);
9361
- // #2073: arm the serve credential's own renewal now, from ITS window, instead of leaving it to
9362
- // `credRenewTimer`'s boot-phased TTL/4 tick. Open mesh mints no credential (`creds` is
9363
- // undefined) and has nothing to schedule.
9364
- if (state.creds !== undefined)
9365
- this.scheduleServeRenewal(state.creds);
9366
- }
8005
+ dialServeConnection(state, readCreds = () => state.creds, deadline) { return this.servePlane.dialServeConnection(state, readCreds, deadline); }
8006
+ registerManagerService() { return this.servePlane.registerManagerService(); }
9367
8007
  /** Mint the standing `goal-writer` credential and STAGE it into this
9368
8008
  * instance's §13.1 revocation family (`epcred.<e>.<iid>`), over the passed executor's `authKv`
9369
8009
  * (the scoped `endpoint-serve-executor`, which holds the epcred write grant). The GRANT profile
@@ -9496,300 +8136,9 @@ export class Manager {
9496
8136
  this.goalWriter = undefined;
9497
8137
  await this.retireConnection(gw.nc);
9498
8138
  }
9499
- /** Mint the standing `session-ledger` credential and STAGE it into this instance's
9500
- * §13.1 revocation family (`epcred.<e>.<iid>`), over the passed executor's `authKv`, following the
9501
- * {@link mintAndStageGoalWriter} pattern under the same open-and-commit fence.
9502
- *
9503
- * This credential carries the DEDICATED sessions-bucket ledger rows and no session rail at all.
9504
- * It therefore takes no epoch pin: §13.6 makes it the durable revocation authority that must
9505
- * outlive the serving endpoint, so scoping it to one serving epoch would defeat its purpose. The
9506
- * epoch lives where it belongs, on the per-session serving credentials, which are minted per
9507
- * redemption into this same family. Because `mintCreds` stamps a random `issuance:` tag on
9508
- * `session-ledger` (`userTags`), re-minting the SAME nkey on renewal or restart signs distinct
9509
- * bytes and stages a distinct ledger row (per-JWT `credentialId` digest) even within one
9510
- * second. */
9511
- async mintAndStageSessionLedger(authKv) {
9512
- const auth = this.auth;
9513
- const identity = this.sessionLedgerIdentity;
9514
- // Registration instanceId (the persisted logical id), not the per-process lifecycleUid:
9515
- // the barrier enumerates `epcred.<e>.<managerInstanceId>`, so the ledger cred joins that family.
9516
- const iid = this.managerInstanceId;
9517
- const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
9518
- const observed = await fence.observe();
9519
- if (observed === null)
9520
- throw new Error(`the issuance gate for ${MANAGER_ENDPOINT}/${iid} vanished; the session-ledger cred cannot join its §13.1 revocation family`);
9521
- const creds = await mintCreds(auth, identity, "session-ledger");
9522
- const exp = inspectCredHealth(creds).exp;
9523
- if (exp === undefined)
9524
- throw new Error(`the session-ledger credential for ${MANAGER_ENDPOINT}/${iid} is unbounded; the §13.1 ledger row requires an expiry`);
9525
- // The §13.1 open-and-commit fence (see {@link mintAndStageGoalWriter}): stage + revision-pinned
9526
- // commit against the gate this mint's grant was scoped from, releasing only on the win.
9527
- await commitSiblingIssuance(fence, observed, {
9528
- credentialId: credentialIdOf(creds),
9529
- credentialKey: identity.id,
9530
- holderPrincipal: principalKey(DEV_OWNER, identity.id).key,
9531
- endpoint: MANAGER_ENDPOINT, lifecycleUid: iid, sourceChain: ["root"], state: "active", exp,
9532
- generation: observed.generation, processEpoch: observed.processEpoch,
9533
- registrationRevision: observed.registrationRevision, nameAuthorityRevision: observed.nameAuthorityRevision,
9534
- });
9535
- return creds;
9536
- }
9537
- /** #2073: dial the session-ledger's ONE standing connection — shared by the initial start and the
9538
- * closed-connection recovery ({@link onSessionLedgerConnectionClosed}), the same shape {@link
9539
- * dialGoalWriter} uses for its rail. The KV/JetStream clients the session plane opened from the
9540
- * connection at start stay bound to it for this incarnation's life; a redial refreshes the
9541
- * standing authenticator connection the credential renewal presents onto (mirroring `sw.creds`),
9542
- * which is what a closed-connection fault on this rail needs restored. */
9543
- async dialSessionLedgerConnection(sw, identity) {
9544
- const nc = await this.dial({
9545
- ...((this.auth || this.remoteAuthority) ? standaloneConnectOpts({ creds: () => sw.creds, tls: false }) : {}),
9546
- inboxPrefix: `_INBOX_${identity.id}`,
9547
- maxReconnectAttempts: -1,
9548
- });
9549
- nc.closed().then((err) => { void this.onSessionLedgerConnectionClosed(err ?? undefined); });
9550
- this.trackTransport(nc);
9551
- sw.nc = nc;
9552
- }
9553
- /** #2073: the session-ledger rail's closed-connection fault, the same bounded shape {@link
9554
- * onGoalWriterConnectionClosed} uses: re-dial with the current credential, re-mint through the
9555
- * existing session-ledger renewal branch when the credential itself has expired, then re-attach.
9556
- * Exhaustion logs and leaves the credential to the next renewal pass; it never exits the process
9557
- * (brief step 4: only the serve rail is the control plane the report lost). */
9558
- async onSessionLedgerConnectionClosed(err) {
9559
- if (this.leaseStopping)
9560
- return;
9561
- console.error(`! manager session-ledger connection closed: ${err?.message ?? "unknown reason"}`);
9562
- const sw = this.sessionLedgerConn;
9563
- const identity = this.sessionLedgerIdentity;
9564
- const recovered = await this.boundedReconnect("session-ledger", async () => {
9565
- if (!sw || !identity)
9566
- return false;
9567
- if (this.remoteAuthority)
9568
- await this.renewRemoteBeforeRedial("session-ledger", () => sw.creds);
9569
- else if (sw.creds !== undefined && inspectCredHealth(sw.creds).state !== "healthy") {
9570
- sw.creds = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageSessionLedger(authKv));
9571
- this.sessionLedgerCreds = sw.creds;
9572
- }
9573
- await this.dialSessionLedgerConnection(sw, identity);
9574
- console.error("manager session-ledger re-dialed");
9575
- return true;
9576
- }, inspectCredHealth(sw?.creds ?? "").state === "expired");
9577
- if (this.leaseStopping || recovered)
9578
- return;
9579
- console.error("! manager session-ledger could not be re-dialed; leaving the credential to the next renewal pass");
9580
- }
9581
- /** Stand up the ONE §13.6 session plane on its own standing connection. Mode-dual,
9582
- * mirroring {@link startGoalWriter}: an AUTH mesh presents the scoped `session-ledger` cred
9583
- * already minted + family-staged inside registration's run block ({@link mintAndStageSessionLedger});
9584
- * an OPEN mesh uses a bare connection (no credential system to mint from). The connection presents
9585
- * the CURRENT credential on every (re)connect, so a half-TTL renewal is adopted without reconnecting.
9586
- *
9587
- * The offer SIGNER is a per-incarnation in-memory keypair: the static collapsed path mints AND
9588
- * redeems the offer in one call ({@link ManagerSessionPlane.establishAttach}), so the manager
9589
- * self-signs and self-verifies its own §13.6 grants and the keypair never leaves the process — a
9590
- * holder never verifies the signature (it presents the grant back over the rail; the broker's
9591
- * per-session caller cred is the holder's real fence). The plane's ledger lives in the DEDICATED
9592
- * sessions bucket (createEndpointStreams provisioned it at registration). */
9593
- async startSessionPlane() {
9594
- const identity = (this.auth || this.remoteAuthority) ? this.sessionLedgerIdentity : newIdentity();
9595
- // The mutable holder captured by the authenticator (mirrors the goal-writer): a half-TTL renewal
9596
- // updates `sw.creds` and the next (re)connect presents the refreshed credential.
9597
- const sw = { nc: undefined, creds: (this.auth || this.remoteAuthority) ? this.sessionLedgerCreds : undefined };
9598
- await this.dialSessionLedgerConnection(sw, identity);
9599
- const nc = sw.nc;
9600
- const serveEpoch = this.serviceServe?.grant.epoch;
9601
- if (serveEpoch === undefined)
9602
- throw new Error("the manager session plane needs the serve grant epoch; registerManagerService must run first");
9603
- const ledgerKv = await openSessionLedgerKv(nc, sessionsBucket(this.space));
9604
- // The session signing key ROTATES. It used to be minted once here with a flat 24h window and
9605
- // handed back frozen forever, so a manager that stayed up past 24h lost its session plane
9606
- // permanently: every attach failed closed with "outside its validity window", and the only
9607
- // recovery was restarting the manager, which kills every live session. It happened three times
9608
- // in one day. Failing closed on an expired key is correct (SPEC 13.10); the defect was that
9609
- // nothing ever renewed the key, so the correct refusal became permanent.
9610
- //
9611
- // Renewal is driven from two places on purpose - a timer below, and opportunistically before
9612
- // each signature. A timer alone stops if the loop is starved or the host suspends; an
9613
- // opportunistic check alone never fires on an idle plane that must sign after a long quiet
9614
- // period. Expiry now requires both to fail at once.
9615
- const rotating = new RotatingSigner((seq, now) => {
9616
- const kp = newArtifactSigner();
9617
- const keyId = seq === 0
9618
- ? `mgr-sessions-${identity.id.slice(0, 12)}`
9619
- : `mgr-sessions-${identity.id.slice(0, 12)}-g${seq}`;
9620
- return {
9621
- keyId,
9622
- keyPair: kp,
9623
- anchor: generationAnchor({
9624
- keyId, publicKey: kp.publicKey, owner: MANAGER_ENDPOINT, roles: ["sessions"],
9625
- scope: { sessions: [MANAGER_ENDPOINT] }, now, ttlMs: SESSION_GRANT_MAX_TTL_MS,
9626
- }),
9627
- };
9628
- }, Date.now());
9629
- this.sessionPlane = new ManagerSessionPlane({
9630
- space: this.space,
9631
- // The session's serving identity is the persisted REGISTRATION instanceId, not the
9632
- // per-process lifecycleUid: a restarted manager re-registers the SAME logical instanceId with
9633
- // an ADVANCED epoch, so a client re-attaches by the same instance while the epoch fences the
9634
- // old incarnation's sessions.
9635
- serving: { instanceId: this.managerInstanceId, epoch: serveEpoch },
9636
- // Read through the rotator on EVERY use rather than capturing a key: signing takes the newest
9637
- // generation, and resolution accepts any generation still inside its overlap so an artifact
9638
- // signed a moment before a swap is not orphaned a moment after it.
9639
- signer: {
9640
- get keyId() { rotating.maybeRenew(Date.now()); return rotating.current().keyId; },
9641
- keyPair: { sign: (input) => rotating.current().keyPair.sign(input) },
9642
- },
9643
- resolveAnchor: (id) => rotating.resolve(id),
9644
- ledgerKv, ttlMs: SESSION_GRANT_MAX_TTL_MS,
9645
- servingCredential: this.sessionServingCredentials(),
9646
- ...(this.maxSessions !== undefined ? { maxSessions: this.maxSessions } : {}),
9647
- });
9648
- this.sessionLedgerConn = sw;
9649
- // The belt to the signing path's braces: renew on a timer as well, so a plane that sits idle
9650
- // for longer than a window still holds a live key when work finally arrives. Checked well
9651
- // inside the renewal margin, unref'd so it never holds the process open.
9652
- const renewTimer = setInterval(() => {
9653
- const rotated = rotating.maybeRenew(Date.now());
9654
- if (rotated)
9655
- console.error(`manager session signing key rotated to ${rotated} (previous generations stay verifiable ` +
9656
- `through their overlap; a key is never allowed to expire unattended)`);
9657
- }, 15 * 60 * 1000);
9658
- renewTimer.unref?.();
9659
- this.sessionKeyRenewTimer = renewTimer;
9660
- console.error(`manager session plane standing (endpoint ${MANAGER_ENDPOINT}, epoch ${serveEpoch}, ${(this.auth || this.remoteAuthority) ? "scoped session-ledger cred, §13.1 family-staged" : "open/bare"})`);
9661
- }
9662
- /**
9663
- * The per-session SERVING credential seam (SPEC 13.6): the manager mints, gate-stages,
9664
- * connects and revokes ONE credential per live session, replacing a standing credential that held
9665
- * `eps.manager.*.<epoch>.{in,out}` and so reached every live session's bytes at its epoch.
9666
- *
9667
- * Each session gets its OWN nkey identity, so the §13.1 barrier's evict-by-holderPrincipal reaches
9668
- * it individually, and each is staged into `epcred.manager.<instanceId>` — the SAME family the
9669
- * ledger and goal-writer creds join. That is how manager takeover still kills a deposed manager's
9670
- * sessions: the barrier enumerates the family, revokes every row, and evicts every holder, so the
9671
- * per-session creds die with the incarnation exactly as the standing one did, with the blast
9672
- * radius of a leaked credential cut from "every session at this epoch" to "one dead session".
9673
- *
9674
- * OPEN MESH: no credential system exists to mint from, so the seam mints nothing and opens a bare
9675
- * connection. That is not a degraded auth path — an open mesh has no broker enforcement at all —
9676
- * and it is still per-session: the connection and the ledger row are still one-per-session, so
9677
- * teardown behaves identically in both modes.
9678
- */
9679
- sessionServingCredentials() {
9680
- const iid = this.managerInstanceId;
9681
- const gate = async (fn) => this.withEndpointServeExecutor(({ authKv }) => fn(authKv));
9682
- return {
9683
- mint: async (grant) => {
9684
- // Open mesh: no auth to mint from. The id still names the session so the ledger row and the
9685
- // teardown path are identical in both modes.
9686
- if (this.remoteAuthority) {
9687
- const identity = newIdentity();
9688
- const creds = await this.remoteAuthority.mintSessionServing({
9689
- identity,
9690
- endpoint: grant.endpoint,
9691
- sessionId: grant.sessionId,
9692
- epoch: grant.serving.epoch,
9693
- exp: Math.floor(grant.exp / 1000),
9694
- });
9695
- const id = credentialIdOf(creds);
9696
- this.sessionServingKeys.set(id, identity.id);
9697
- return { id, creds, exp: grant.exp };
9698
- }
9699
- if (!this.auth)
9700
- return { id: `${grant.sessionId}.s`, creds: "", exp: grant.exp };
9701
- const identity = newIdentity();
9702
- const creds = await mintCreds(this.auth, identity, "session-serving", {
9703
- sessionServing: { endpoint: grant.endpoint, sessionId: grant.sessionId, epoch: grant.serving.epoch },
9704
- expiresAt: Math.floor(grant.exp / 1000), // grant.exp is ms; the JWT exp is seconds
9705
- });
9706
- const health = inspectCredHealth(creds);
9707
- if (health.exp === undefined)
9708
- throw new Error(`the session-serving credential for ${grant.sessionId} is unbounded; a per-session credential never outlives its session (SPEC 13.6)`);
9709
- const id = credentialIdOf(creds);
9710
- this.sessionServingKeys.set(id, identity.id);
9711
- return { id, creds, exp: grant.exp };
9712
- },
9713
- observeGate: async (_endpoint, instanceId) => {
9714
- // Open mesh: nothing is minted and nothing is staged, so there is no gate to pin (see
9715
- // ServingGatePin.gate — the stage refuses loudly if this is ever missing on an auth mesh).
9716
- if (!this.auth && !this.remoteAuthority)
9717
- return { key: epgateKey(MANAGER_ENDPOINT, instanceId), revision: 0 };
9718
- return gate(async (authKv) => {
9719
- const observed = await serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId }).observe();
9720
- if (observed === null)
9721
- throw new Error(`the issuance gate for ${MANAGER_ENDPOINT}/${instanceId} vanished; a session credential never stages against a missing gate (SPEC 13.1)`);
9722
- // The WHOLE observation rides the pin: the stage's fence compares every field of it, which
9723
- // is what lets a lost CAS be classified rather than blanket-refused.
9724
- return { key: epgateKey(MANAGER_ENDPOINT, instanceId), revision: observed.revision, gate: observed };
9725
- });
9726
- },
9727
- stage: async (grant, cred, pin) => {
9728
- if (!this.auth && !this.remoteAuthority)
9729
- return; // open mesh: nothing minted, so nothing to make revocable
9730
- const key = this.sessionServingKeys.get(cred.id);
9731
- if (key === undefined)
9732
- throw new Error(`no minted identity for session credential ${cred.id}; the stage cannot record a holder it did not mint (SPEC 13.1)`);
9733
- // THE REDEMPTION'S OWN PIN IS THE FENCE, and it is never re-read into something newer here:
9734
- // `commitSiblingIssuance` CASes on this observation's revision and, on a loss, refuses unless
9735
- // the gate is still identical to it in every field but the revision. A barrier
9736
- // (freeze, or reopen at a successor coordinate) is therefore always a refusal, while another
9737
- // session's identical-bytes commit touch is not — per-session credentials all serialize on
9738
- // this one gate key, so refusing on that would fail live sessions for contention rather than
9739
- // for a barrier. A read is never a fence (SPEC 13.1); the pinned CAS is.
9740
- const observed = pin.gate;
9741
- if (observed === undefined)
9742
- throw new Error(`the redemption of session ${grant.sessionId} carries no gate observation for ${MANAGER_ENDPOINT}/${iid}; a session credential never stages unfenced (SPEC 13.1)`);
9743
- await gate(async (authKv) => {
9744
- const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
9745
- await commitSiblingIssuance(fence, observed, {
9746
- credentialId: cred.id,
9747
- credentialKey: key,
9748
- holderPrincipal: principalKey(DEV_OWNER, key).key,
9749
- endpoint: MANAGER_ENDPOINT, lifecycleUid: iid,
9750
- // The lineage records that this credential exists because a session was redeemed, so a
9751
- // ledger reader can tell a per-session row from a standing one (SPEC 13.6 sourceChain).
9752
- sourceChain: [`session.${grant.sessionId}`], state: "active",
9753
- exp: Math.floor(cred.exp / 1000),
9754
- generation: observed.generation, processEpoch: observed.processEpoch,
9755
- registrationRevision: observed.registrationRevision, nameAuthorityRevision: observed.nameAuthorityRevision,
9756
- });
9757
- });
9758
- },
9759
- open: async (cred) => {
9760
- // FAIL LOUD: there is deliberately no shared connection to fall back to. Serving a session
9761
- // without its own credential is exactly the standing-writer shape this design removes.
9762
- const opts = (this.auth || this.remoteAuthority) ? standaloneConnectOpts({ creds: cred.creds, /* not yet wired to a recorded transport */ tls: false }) : {};
9763
- return this.dial({ ...opts, maxReconnectAttempts: -1 });
9764
- },
9765
- revoke: async (credentialId) => {
9766
- if (!this.auth && !this.remoteAuthority)
9767
- return; // open mesh: nothing was minted
9768
- await gate(async (authKv) => {
9769
- await markLedgerRowRevoked(authKv, epcredRowKey(MANAGER_ENDPOINT, iid, credentialId));
9770
- });
9771
- this.sessionServingKeys.delete(credentialId);
9772
- },
9773
- };
9774
- }
9775
- /** Tear the session plane down (best-effort, both exit paths): end every live bridge with the
9776
- * honest `manager-restart` reason (this incarnation is going away; any successor takes a new epoch
9777
- * and refuses these grants), then drain each session's own connection and retire the ledger
9778
- * connection ({@link retireConnection}). */
9779
- async stopSessionPlane() {
9780
- const plane = this.sessionPlane;
9781
- const sw = this.sessionLedgerConn;
9782
- this.sessionPlane = undefined;
9783
- this.sessionLedgerConn = undefined;
9784
- // `drain` awaits each session's teardown (connection close, terminal row, credential revoke);
9785
- // `endAll` alone would let the process exit with per-session connections still open.
9786
- try {
9787
- await plane?.drain("manager-restart");
9788
- }
9789
- catch { /* best effort */ }
9790
- if (sw)
9791
- await this.retireConnection(sw.nc);
9792
- }
8139
+ mintAndStageSessionLedger(authKv) { return this.servePlane.mintAndStageSessionLedger(authKv); }
8140
+ startSessionPlane() { return this.servePlane.startSessionPlane(); }
8141
+ stopSessionPlane() { return this.servePlane.stopSessionPlane(); }
9793
8142
  /** The boot reconcile: a fresh incarnation (a manager restart takes a NEW
9794
8143
  * instanceId, so the in-memory acceptance map starts empty) inherits the endpoint's accepted-but-
9795
8144
  * unterminal goals from any predecessor. The local signer enumerates with an ephemeral PROVISIONER.
@@ -11220,8 +9569,7 @@ export class Manager {
11220
9569
  continue;
11221
9570
  }
11222
9571
  if (adopts) {
11223
- const reconciling = this.staticReconcileSweepsInFlight > 0
11224
- || [...this.staticReconcileItems.values()].some((i) => i.lifecycleUid === uid && i.disposition !== "recovered");
9572
+ const reconciling = this.staticLifecycle.pendingLifecycle(uid);
11225
9573
  if (reconciling)
11226
9574
  continue;
11227
9575
  this.onceInherited.delete(uid);
@@ -11282,87 +9630,17 @@ export class Manager {
11282
9630
  // the goal already terminalized (the readiness outcome won the settle race) - nothing to cancel.
11283
9631
  }
11284
9632
  }
11285
- /** Re-record the custody reference of a managed agent's CURRENT handle on its active slot: a
11286
- * same-lifecycle restart or a resume binds a new custody under the old uid, and the successor's
11287
- * reap must address the live one. Static auth only; a runtime without durable custody records
11288
- * nothing (there is nothing to reap by reference). */
11289
- async recordSlotRuntime(a) {
11290
- if (a.handle.reference === undefined)
11291
- return;
11292
- await this.recordSlotCustody(a, a.handle.reference);
11293
- }
11294
- /** Record one custody reference on an agent's ACTIVE slot. Split from {@link recordSlotRuntime}
11295
- * so a restart or a resume can record the reference it RESERVED before spawning, while no
11296
- * handle exists yet. Static auth only; a runtime without durable custody reserves nothing.
11297
- * Throws when the slot does not take the reference: a slot left on the previous one reaps that
11298
- * seat, already gone, so a successor would retire the lifecycle over the new one. */
11299
- async recordSlotCustody(a, runtime) {
11300
- if (!this.auth || this.userMode)
11301
- return;
11302
- try {
11303
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: a.id, lifecycleUid: a.lifecycleUid, alias: a.name }, async (t) => {
11304
- const slot = await readStaticSlot(t, DEV_OWNER, a.name);
11305
- if (slot === undefined || slot.row.lifecycleUid !== a.lifecycleUid || slot.row.phase !== "active")
11306
- throw new Error(`the slot is ${slot === undefined ? "absent" : `${slot.row.phase} at uid ${slot.row.lifecycleUid}`}`);
11307
- if (slot.row.runtime?.kind === runtime.kind && slot.row.runtime.id === runtime.id)
11308
- return;
11309
- await casStaticSlot(t, { ...slot.row, runtime }, slot.revision);
11310
- });
11311
- }
11312
- catch (e) {
11313
- throw new Error(`could not record the custody reference ${runtime.kind}:${runtime.id} on the static slot of "${a.name}": ${rejectionText(e)}`);
11314
- }
9633
+ recordSlotRuntime(a) {
9634
+ return this.seatCustody.recordSlotRuntime(a);
9635
+ }
9636
+ recordSlotCustody(a, runtime) {
9637
+ return this.seatCustody.recordSlotCustody(a, runtime);
11315
9638
  }
11316
- /** Mint the custody reference for a seat this manager is about to spawn, BEFORE the processes
11317
- * exist. Absent for a runtime with no durable custody (there is nothing a successor could reap
11318
- * by reference), which is the only case that still spawns unreserved. */
11319
9639
  reserveCustody(runtime) {
11320
- return isCustodialRuntime(runtime) ? runtime.reserve() : undefined;
11321
- }
11322
- /** Spawn under a reserved reference and prove the runtime honoured it. A runtime that minted its
11323
- * own id instead would leave every durable record addressing a seat that does not exist, so the
11324
- * mismatch tears the new seat down and throws rather than returning an unaddressable handle. */
11325
- async spawnCustodied(runtime, name, spec, cwd, reserved) {
11326
- const holder = retainConnectorSeat(this.managerInstanceId, name);
11327
- const handle = runtime.spawn(name, spec, cwd, reserved);
11328
- this.watchConnectorHolder(handle, holder);
11329
- if (reserved === undefined)
11330
- return handle;
11331
- const got = handle.reference;
11332
- if (got?.kind === reserved.kind && got.id === reserved.id)
11333
- return handle;
11334
- // A live seat now exists under a reference no durable row names, and the rollback will reap the
11335
- // RESERVED one, which addresses nothing. `handle.stop` cannot close this: it is fire-and-forget
11336
- // over the seat socket and swallows its own errors, so it proves nothing about the process. Reap
11337
- // the reference the runtime ACTUALLY used — that path verifies identity and proves the exit —
11338
- // and carry what the proof said into the throw, so a mismatch never reports a disposal it did
11339
- // not make.
11340
- let disposal;
11341
- if (got === undefined) {
11342
- try {
11343
- handle.stop({ graceful: false });
11344
- }
11345
- catch { /* reported below */ }
11346
- disposal = "the handle carries no reference, so nothing could reap it by identity and only a best-effort stop was issued";
11347
- }
11348
- else {
11349
- try {
11350
- const evidence = await requireRuntimeReap(runtime, got);
11351
- disposal = `the spawned seat was reaped (${evidence.detail})`;
11352
- }
11353
- catch (e) {
11354
- // Two unrelated failures used to share one sentence here, and the difference is the part the
11355
- // reader has to act on. A runtime that cannot reap at all left nothing behind to find. An
11356
- // UNPROVEN reap may have left a live seat under a reference no durable row names, which is
11357
- // the one case where somebody has to go looking, so it says so and names what to look for.
11358
- disposal =
11359
- e instanceof RuntimeReapUnproven
11360
- ? `the spawned seat was NOT proved gone and may still be running as ${e.reference.kind}:${e.reference.id} (${e.message})`
11361
- : `the spawned seat could NOT be reaped: ${rejectionText(e)}`;
11362
- }
11363
- }
11364
- throw new Error(`runtime "${runtime.kind}" reserved custody ${reserved.kind}:${reserved.id} for "${name}" but spawned ` +
11365
- `${got ? `${got.kind}:${got.id}` : "a handle with no reference"}; the recorded reference would address no seat, so ${disposal}`);
9640
+ return this.seatCustody.reserveCustody(runtime);
9641
+ }
9642
+ spawnCustodied(runtime, name, spec, cwd, reserved) {
9643
+ return this.seatCustody.spawnCustodied(runtime, name, spec, cwd, reserved);
11366
9644
  }
11367
9645
  /** Keep launch provenance independent of status and runtime wire contracts. */
11368
9646
  watchConnectorHolder(handle, holder) {
@@ -11373,48 +9651,14 @@ export class Manager {
11373
9651
  // identity-less holders, never a release or a failed stop request.
11374
9652
  watchProvedExit(handle, () => holder.ended(), () => true);
11375
9653
  }
11376
- /** Persist what a successor needs to take this seat back if this process ends without stopping
11377
- * it: a supervised seat, which a successor restarts (#4094), and a seat on a runtime that can adopt
11378
- * it by reference, which a successor adopts while it still runs (#4095). Static meshes only: a
11379
- * successor finds the seat through its active slot row, and only a static mesh keeps one. Throws
11380
- * when a supervised seat's entry could not be resumed, because a policy this host cannot keep
11381
- * across a manager restart is one it cannot enforce. */
11382
9654
  recordSeat(a) {
11383
- if (!this.auth || this.userMode)
11384
- return;
11385
- const policy = a.restart?.policy;
11386
- const runtime = this.runtimeFor(a.handle.kind);
11387
- const adoptable = a.handle.reference !== undefined && typeof runtime.adopt === "function";
11388
- if (!policy && !adoptable)
11389
- return;
11390
- const agent = this.resumeEntryOf(a);
11391
- if (policy) {
11392
- const unresumable = this.inventoryReferenceError(agent);
11393
- if (unresumable)
11394
- throw new Error(`a successor manager could not restart it: ${unresumable}`);
11395
- }
11396
- writeSeatRecord(this.workspaceRoot, { version: "cotal-seat-record/v1", instanceId: this.managerInstanceId, ...(policy ? { supervise: policy } : {}), crashes: a.restart?.crashes ?? [], agent });
9655
+ return this.seatCustody.recordSeat(a);
11397
9656
  }
11398
- /** Bring a running seat's record up to date after its credential or restart count changed. A
11399
- * record that cannot be rewritten is removed, so a successor retires the seat rather than taking
11400
- * it back from a stale one. */
11401
9657
  refreshSeatRecord(a) {
11402
- try {
11403
- this.recordSeat(a);
11404
- }
11405
- catch (error) {
11406
- console.error(`! ${a.name}: its seat record could not be updated (${rejectionText(error)}); a manager restart now retires it`);
11407
- this.dropSeatRecord(a);
11408
- }
9658
+ return this.seatCustody.refreshSeatRecord(a);
11409
9659
  }
11410
9660
  dropSeatRecord(a) {
11411
- try {
11412
- removeSeatRecord(this.workspaceRoot, this.space, a.name, a.lifecycleUid);
11413
- removeReleasedSeatReference(this.workspaceRoot, this.space, a.name, a.lifecycleUid);
11414
- }
11415
- catch (error) {
11416
- console.error(`! ${a.name}: its seat record could not be removed: ${rejectionText(error)}`);
11417
- }
9661
+ return this.seatCustody.dropSeatRecord(a);
11418
9662
  }
11419
9663
  /** True when a default stop wrote a runtime reference for this exact lifecycle and it is still
11420
9664
  * there. That file is what a later manager adopts, so a slot free must not remove it before the
@@ -11427,1030 +9671,44 @@ export class Manager {
11427
9671
  return false;
11428
9672
  }
11429
9673
  }
11430
- /** The seat record behind one active slot this instance owns, when it describes that exact
11431
- * incarnation on this runtime. Anything else is left to the ordinary terminal. */
11432
9674
  seatRecordFor(row) {
11433
- let record;
11434
- try {
11435
- record = readSeatRecord(this.workspaceRoot, this.space, row.alias);
11436
- }
11437
- catch (error) {
11438
- console.error(`! ${row.alias}: ${rejectionText(error)}; the lifecycle is retired, not restarted`);
11439
- return undefined;
11440
- }
11441
- if (record === undefined)
11442
- return undefined;
11443
- const identity = record.agent.identity;
11444
- if (identity.mode !== "static" || identity.id !== row.actor || identity.lifecycleUid !== row.lifecycleUid)
11445
- return undefined;
11446
- if (record.instanceId !== this.managerInstanceId || record.agent.space !== this.space)
11447
- return undefined;
11448
- let runtimeMatches = record.agent.launch.runtime === row.runtime?.kind;
11449
- if (row.runtime === undefined) {
11450
- // Non-custodial backends such as pty record no slot reference. A custodial backend still
11451
- // requires one, and an unavailable backend must refuse rather than select a replacement.
11452
- const runtime = this.runtimeFor(record.agent.launch.runtime);
11453
- runtimeMatches = runtime.kind === record.agent.launch.runtime && !isCustodialRuntime(runtime);
11454
- }
11455
- if (!runtimeMatches) {
11456
- console.error(`! ${row.alias}: its seat ran on runtime "${record.agent.launch.runtime}" and its slot names "${row.runtime?.kind ?? "none"}"; the lifecycle is retired, not restarted`);
11457
- return undefined;
11458
- }
11459
- return record;
9675
+ return this.seatCustody.seatRecordFor(row);
11460
9676
  }
11461
- /** Take back a seat that outlived its manager (#4095): the runtime reattaches to the exact seat
11462
- * the slot names, and this manager holds it under the record's identity and launch, with no
11463
- * relaunch. Returns why it could not, and the caller then retires the lifecycle, which reaps the
11464
- * seat by the same reference. */
11465
- async adoptSeat(row, record) {
11466
- const entry = record.agent;
11467
- if (entry.identity.mode !== "static")
11468
- return "its record is not a static identity";
11469
- if (row.runtime === undefined)
11470
- return "its slot names no seat";
11471
- const runtime = this.runtimeFor(row.runtime.kind);
11472
- if (typeof runtime.adopt !== "function")
11473
- return `runtime "${runtime.kind}" cannot adopt a seat`;
11474
- // The credential is the manager's own lifecycle-keyed file, and its seed renews it.
11475
- const credsPath = resolve(entry.identity.credential.path);
11476
- if (credsPath !== resolve(agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, entry.name, entry.identity.lifecycleUid).creds))
11477
- return `its credential reference ${credsPath} is not this lifecycle's manager-owned path`;
11478
- const stored = await this.secrets.get(agentSecretKeyForFile(credsPath, this.space));
11479
- if (stored === undefined)
11480
- return "its credential is not in the secret store";
11481
- let seed;
11482
- try {
11483
- const identity = identityFromCreds(stored);
11484
- if (identity.id !== entry.identity.id)
11485
- return `its credential is identity ${identity.id}, not ${entry.identity.id}`;
11486
- seed = identity.seed;
11487
- }
11488
- catch (error) {
11489
- return `its credential is unreadable: ${rejectionText(error)}`;
11490
- }
11491
- let adopted;
11492
- try {
11493
- adopted = runtime.adopt(row.runtime);
11494
- }
11495
- catch (error) {
11496
- return `the seat ${row.runtime.kind}:${row.runtime.id} could not be adopted: ${rejectionText(error)}`;
11497
- }
11498
- const managed = {
11499
- name: entry.name,
11500
- role: entry.role,
11501
- agent: entry.launch.connector,
11502
- id: entry.identity.id,
11503
- seed,
11504
- ...(entry.identity.issued ? { issued: entry.identity.issued } : {}),
11505
- lifecycleUid: entry.identity.lifecycleUid,
11506
- secretPaths: { creds: entry.identity.credential.path },
11507
- spawner: entry.spawner,
11508
- authorityParent: entry.authorityParent,
11509
- startedAt: Date.parse(entry.startedAt),
11510
- // The runtime names an adopted handle by what it holds; the record names the seat.
11511
- handle: { ...adopted, name: entry.name },
11512
- launch: {
11513
- runtime: entry.launch.runtime,
11514
- source: entry.launch.source,
11515
- cwd: entry.launch.cwd,
11516
- model: entry.launch.model,
11517
- variant: entry.launch.variant,
11518
- subscribe: entry.launch.subscribe,
11519
- allowSubscribe: entry.launch.allowSubscribe,
11520
- allowPublish: entry.launch.allowPublish,
11521
- capabilities: entry.launch.capabilities,
11522
- ...(entry.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(entry.launch.endpoints) } : {}),
11523
- events: entry.launch.events,
11524
- eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
11525
- shareTools: entry.launch.shareTools,
11526
- forkSource: entry.launch.forkSource,
11527
- ...(entry.launch.resumed ? { resumed: entry.launch.resumed } : {}),
11528
- sessionId: entry.launch.sessionId,
11529
- unresolvedLaunchOptionKeys: entry.launch.unresolvedLaunchOptionKeys,
11530
- },
11531
- };
11532
- this.agents.set(entry.name, managed);
11533
- this.watchExit(managed);
11534
- console.error(`! ${entry.name}: adopted the seat its previous manager left (${row.runtime.kind}:${row.runtime.id})`);
11535
- await this.bindOnceSeat(managed);
11536
- // A credential that came close to its expiry while no manager ran is renewed now, not at the
11537
- // next pass.
11538
- const health = inspectCredHealth(stored).state;
11539
- if (health === "near-expiry" || health === "expired")
11540
- await this.renewManagedStaticCred(managed).catch((error) => console.error(`! managed cred renewal ${entry.name}: ${rejectionText(error)} - the agent dies loud at this cred's expiry unless it is reminted`));
11541
- return undefined;
9677
+ adoptSeat(row, record) {
9678
+ return this.seatCustody.adoptSeat(row, record);
11542
9679
  }
11543
- /** Restart a supervised seat whose manager ended without stopping it (#4094), as one restart of
11544
- * its own policy. It goes through the resume launch, so the seat comes back under the same name,
11545
- * lifecycle uid, credential, persona and cwd, and a pending turn addressed to it is served to it.
11546
- * Returns why it could not, and the caller then retires the lifecycle. */
11547
- async restartSupervisedSeat(row, record) {
11548
- const policy = record.supervise;
11549
- if (policy === undefined)
11550
- return "its spawn carried no restart policy";
11551
- const now = Date.now();
11552
- const crashes = [...record.crashes.filter((at) => now - at < policy.windowMs), now];
11553
- if (crashes.length > policy.restarts)
11554
- return `its supervise restart budget is spent (${crashes.length} deaths in ${policy.windowMs / 1000}s, ${policy.restarts} allowed)`;
11555
- // Ordinary reap proves only the runtime's seat process/window gone. A durable work-closure
11556
- // proof must also cover detached tools. No reference means unknown, not an empty execution.
11557
- if (row.runtime === undefined)
11558
- return "prior local work has no durable custody reference; automatic restart refused";
11559
- const runtime = this.runtimeFor(row.runtime.kind);
11560
- if (!runtime.reapWork)
11561
- return `runtime "${runtime.kind}" cannot prove prior local work ended after a manager crash; automatic restart refused`;
11562
- try {
11563
- await withTimeout(runtime.reapWork(row.runtime), RESTART_WORK_EXIT_MS, `prior local work was not proved ended within ${RESTART_WORK_EXIT_MS}ms`);
11564
- }
11565
- catch (error) {
11566
- return `prior local work could not be closed; automatic restart refused: ${rejectionText(error)}`;
11567
- }
11568
- await this.ep.waitForPresenceSnapshot();
11569
- // Readiness counts only a heartbeat newer than any the dead seat left, as an in-place restart does.
11570
- const principal = principalKey(DEV_OWNER, row.actor).key;
11571
- const joinedAfter = this.ep.getRoster()
11572
- .filter((p) => p.card.id === principal && p.lifecycleUid === row.lifecycleUid)
11573
- .reduce((max, p) => Math.max(max, p.ts), 0) + 1;
11574
- const reply = await this.resumePreservedAgent(record.agent, false, false, undefined, { policy, crashes, joinedAfter });
11575
- const live = this.agents.get(row.alias);
11576
- if (reply.ok) {
11577
- console.error(`! ${row.alias}: restarted under the same lifecycle after its manager stopped (${crashes.length}/${policy.restarts})`);
11578
- return undefined;
11579
- }
11580
- // An uncertain readiness keeps the seat managed and watched, as any launch does.
11581
- if (live?.lifecycleUid === row.lifecycleUid) {
11582
- console.error(`! ${row.alias}: restarted after its manager stopped, but readiness is uncertain: ${reply.error}`);
11583
- return undefined;
11584
- }
11585
- return `its restart failed: ${reply.error}`;
11586
- }
11587
- /** The terminal's process step: an orphan (no live handle in THIS process) is reaped by the custody
11588
- * reference the slot recorded, before its footprint goes. A successor must never retire a
11589
- * lifecycle and free its alias while the predecessor's seat process is still running outside
11590
- * every manager. The runtime verifies the process identity against its own record and proves the
11591
- * exit; a runtime that cannot reap refuses by name and the lifecycle stays terminalizing. A row
11592
- * with no recorded reference has nothing this manager can address. */
11593
- async reapOrphanSeat(a) {
11594
- if (a.runtime === undefined) {
11595
- // No reference reached this terminal. Under a custodying runtime that is either a row written
11596
- // before the reservation existed, or a caller that dropped the reference on the way here.
11597
- // Do not name the slot row: the row may well hold a reference this caller never read, and
11598
- // a diagnostic that guesses which is which sends the reader the wrong way.
11599
- if (isCustodialRuntime(this.requiredRuntime))
11600
- console.error(`static retirement ${a.name}: no custody reference reached this terminal, though runtime "${this.requiredRuntime.kind}" custodies its seats; any seat it launched is not addressable from here`);
11601
- return;
11602
- }
11603
- // An unproven reap throws from here rather than printing, so it propagates into
11604
- // driveStaticRetirement's catch, which records the failure and HOLDS the name. That is the whole
11605
- // point of refusing: the alias must not be freed while a seat nobody proved gone may still run.
11606
- const runtime = this.runtimeFor(a.runtime.kind);
11607
- const evidence = await requireRuntimeReap(runtime, a.runtime);
11608
- console.error(`static retirement ${a.name}: orphan seat process ${evidence.detail}`);
11609
- }
11610
- /** The static terminal for one departed incarnation: delegates the gate/head CAS
11611
- * sequence to the shared core saga over the executor transport; the footprint teardown (creds
11612
- * file + broker durables/ACL) runs INSIDE the barrier as its cleanup step. On completion the
11613
- * wire principal joins {@link retiredPrincipals} (the retired-principal refusal index) and the name hold
11614
- * clears (ABA-guarded by uid). A lifecycle with no slot row (spawned before the
11615
- * durable registry existed) has nothing to terminalize: its footprint teardown runs directly
11616
- * and the hold clears, the honest upgrade path. `onDeprovision` receives the accounting of the
11617
- * broker teardown this call ran, on success or on a {@link DeprovisionError}. */
11618
- async driveStaticRetirement(a, surfaceFailure = false, onDeprovision) {
11619
- // A renewal that published its flight before the synchronous terminal latch is accepted work.
11620
- // Drain it before the durable terminal enumerates credential ids and before cleanup deletes its
11621
- // material; a failed renewal must not block retirement because it may still have staged an id.
11622
- const acceptedRenewal = a.staticCredentialRenewal;
11623
- if (acceptedRenewal)
11624
- await acceptedRenewal.catch(() => { });
11625
- const opId = managedRetirementOpId(a.lifecycleUid);
11626
- const evict = this.staticLifecycleEvict ?? makeManagerEndpointEvictionEvidence({
11627
- space: this.space,
11628
- servers: this.servers ?? DEFAULT_SERVER,
11629
- auth: this.auth,
11630
- log: (line) => console.error(`static retirement ${a.name}: ${line}`),
11631
- // A daemon credential reload briefly removes its responder while it reconnects.
11632
- unreachableWaitMs: DEPROVISION_TIMEOUT_MS,
11633
- });
11634
- const cleanup = async () => {
11635
- // SPEC 13.15: every issuance bound to this incarnation's ledger family is retired here,
11636
- // inside the barrier and after the ledger rows were revoked (the source is frozen first,
11637
- // then the index is walked). A retirement that lost is surfaced, never skipped: an active
11638
- // attempt row on a retired lifecycle would authorize a run the credential no longer can.
11639
- const retired = await this.withIssuer((i) => i.store.retireSource({ space: this.space, bucket: epAuthBucket(this.space), key: `cred.${a.lifecycleUid}` }));
11640
- if (retired > 0)
11641
- console.error(`static retirement ${a.name}: retired ${retired} issuance(s) bound to uid ${a.lifecycleUid}`);
11642
- const secrets = this.secrets;
11643
- const files = a.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, a.name, a.lifecycleUid);
11644
- // The broker teardown mints its own credential, so a creds file that cannot be removed must not
11645
- // skip it. The failures are thrown together, so the terminal still stops at an incomplete cleanup.
11646
- const failed = [];
11647
- if (files.creds) {
11648
- const creds = files.creds;
11649
- await attemptCleanup(failed, `secret ${creds}`, () => secrets.delete(agentSecretKeyForFile(creds, this.space)));
11650
- await attemptCleanup(failed, `file ${creds}`, () => rmSync(creds, { force: true }));
11651
- }
11652
- // The lifecycle's inline snapshot, when no earlier step settled it. Keyed by the uid, so a boot
11653
- // sweep or a reconcile that knows only the slot row removes it too.
11654
- if (!a.snapshotSettled) {
11655
- const snapshot = inlineSnapshotPath(this.workspaceRoot, a.lifecycleUid);
11656
- await attemptCleanup(failed, `file ${snapshot}`, () => removeInlineSnapshot(this.workspaceRoot, a.lifecycleUid));
11657
- }
11658
- await attemptCleanup(failed, "broker teardown", async () => {
11659
- try {
11660
- const accounting = await this.deprovisionBroker(a);
11661
- onDeprovision?.(accounting);
11662
- }
11663
- catch (e) {
11664
- if (e instanceof DeprovisionError)
11665
- onDeprovision?.(e.accounting);
11666
- throw e;
11667
- }
11668
- });
11669
- if (failed.length)
11670
- throw new Error(`cleanup failed: ${describeCleanupFailures(failed)}`);
11671
- };
11672
- // The process goes before its footprint: reap the orphan seat by reference, then tear down.
11673
- const reapThenCleanup = async () => {
11674
- await this.reapOrphanSeat(a);
11675
- await cleanup();
11676
- };
11677
- try {
11678
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: a.id, lifecycleUid: a.lifecycleUid, alias: a.name }, async (t) => {
11679
- const slot = await readStaticSlot(t, DEV_OWNER, a.name);
11680
- if (slot === undefined || slot.row.lifecycleUid !== a.lifecycleUid) {
11681
- // No durable registration for THIS incarnation: a spawn from before the registry (or a slot already
11682
- // replaced by a successor — then this stale teardown must not touch the registry at all).
11683
- await reapThenCleanup();
11684
- return;
11685
- }
11686
- await runStaticTerminal(t, {
11687
- owner: DEV_OWNER, alias: a.name, actor: a.id, lifecycleUid: a.lifecycleUid, opId,
11688
- managerInstance: this.managerInstanceId, managerProcessUid: this.managerLifecycleUid,
11689
- }, { cleanup: reapThenCleanup, evict, log: (line) => console.error(`static retirement ${a.name}: ${line}`) });
11690
- });
11691
- const principal = principalKey(DEV_OWNER, a.id).key;
11692
- this.retiredPrincipals.add(principal);
11693
- const cur = this.retiring.get(a.name);
11694
- if (cur && cur.target.lifecycleUid === a.lifecycleUid) {
11695
- this.retiring.delete(a.name); // ABA-guarded hold clear
11696
- this.confirmedRetiredPredecessors.set(a.name, { principal, lifecycleUid: a.lifecycleUid });
11697
- }
11698
- }
11699
- catch (e) {
11700
- const h = this.retiring.get(a.name);
11701
- if (h && h.target.lifecycleUid === a.lifecycleUid)
11702
- h.lastError = `the static retirement did not complete (${rejectionText(e)}); the name stays held - a same-name spawn retries the same terminal (op ${opId})`;
11703
- console.error(`static retirement ${a.name} (${a.id}): ${rejectionText(e)}`);
11704
- if (surfaceFailure)
11705
- throw e;
11706
- }
9680
+ restartSupervisedSeat(row, record) {
9681
+ return this.seatCustody.restartSupervisedSeat(row, record);
11707
9682
  }
11708
- /** `chat-session-open`: admit one static chat session. The manager draws the `chat_` alias and a
11709
- * fresh nkey identity, then runs the same native steps a static spawn does: the slot intent and
11710
- * the shared activation saga, the provisioner's bind-only DM and DELIVER durables plus the ACL
11711
- * row, and the agent-profile mint. The leaf carries the spawn's three lists under the spawn's
11712
- * rules (`resolveReadAcl`, a default-deny post list, the foreign event-channel refusal) and
11713
- * nothing else: no role (so no TASK queue), no capabilities, no endpoint rows, no issuance. It
11714
- * expires at `ttl` with no renewal, because no managed row exists to renew it.
11715
- *
11716
- * The session is registered with the tracker before the first durable write and scheduled for
11717
- * its expiry before the reply is sent, or after a rollback that did not complete, so this
11718
- * process retires it at the expiry even when the reply is lost or the client never retires.
11719
- *
11720
- * The credential is ledgered before it leaves this process (slot credentialId, then the `cred.`
11721
- * row), so the static terminal marks the row revoked and verify-evicts the session's principal;
11722
- * the broker keeps accepting the leaf until its expiry. The direct ledger write is deliberate:
11723
- * the leaf is not an issuance, so the issuance seam, which writes the same row inside its
11724
- * finalization, never runs for it, and without the row the terminal's eviction set would be
11725
- * empty. The credential leaves only sealed to `sealTo`, bound to the space, this instance and
11726
- * the reply's fields, so a reply printed anywhere carries no usable credential. A failure at
11727
- * any step drives the terminal before the refusal is returned, and the refusal says whether it
11728
- * completed. */
11729
- async openStaticChatSession(raw) {
11730
- if (!this.auth || this.userMode)
11731
- throw new EpEnvelopeError("unimplemented", "chat-session-open admits static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
11732
- const input = readChatOpenInput(raw);
11733
- if ("error" in input)
11734
- throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
11735
- const lists = chatOpenLists(input);
11736
- if ("error" in lists)
11737
- throw new EpEnvelopeError("bad-request", lists.error, undefined, "not-executed");
11738
- const alias = drawChatAlias();
11739
- const identity = newIdentity();
11740
- // The spawn's rule, against the drawn actor: a concrete event channel of any other principal is
11741
- // refused, and a wildcard is an ordinary grant.
11742
- const foreign = foreignEventChannels([...lists.allowSubscribe, ...lists.allowPublish], DEV_OWNER, identity.id);
11743
- if (foreign.length)
11744
- 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");
11745
- const lifecycleUid = mintLifecycleUid();
11746
- const exp = Math.floor(Date.now() / 1000) + input.ttl;
11747
- const pin = { owner: DEV_OWNER, actor: identity.id, lifecycleUid, alias };
11748
- const session = { alias, actor: identity.id, lifecycleUid, channels: lists.allowSubscribe, expiresAt: exp * 1000 };
11749
- // Registered before the first durable write, so the startup sweep never mistakes this opening's
11750
- // provisioning row for a crashed spawn, and the stop knows it.
11751
- try {
11752
- this.chatExpiry.register(session);
11753
- }
11754
- catch (e) {
11755
- throw new EpEnvelopeError("unavailable", rejectionText(e), undefined, "not-executed");
11756
- }
11757
- try {
11758
- await this.withLifecycleExecutor(pin, (t) => activateStaticLifecycle(t, { owner: DEV_OWNER, alias, actor: identity.id, lifecycleUid, managerInstance: this.managerLifecycleUid, ownerInstanceId: this.managerInstanceId }));
11759
- const creds = await this.withProvisioner((prov) => provisionAgent(prov, this.auth, identity, { subscribe: lists.subscribe, allowSubscribe: lists.allowSubscribe, allowPublish: lists.allowPublish, lifecycleUid, expiresAt: exp }));
11760
- // The same credential id the issuance path derives, so a re-sent identical credential maps to
11761
- // the same row.
11762
- const credentialId = credentialIdOf(creds);
11763
- await this.withLifecycleExecutor(pin, async (t) => {
11764
- await recordSlotCredential(t, DEV_OWNER, alias, lifecycleUid, credentialId);
11765
- await appendStaticCredentialRow(t, { lifecycleUid, credentialId, holderPrincipal: principalKey(DEV_OWNER, identity.id).key, exp });
11766
- const slot = await readStaticSlot(t, DEV_OWNER, alias);
11767
- if (slot === undefined || slot.row.lifecycleUid !== lifecycleUid || slot.row.phase !== "provisioning")
11768
- 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`);
11769
- await casStaticSlot(t, { ...slot.row, phase: "active" }, slot.revision);
11770
- });
11771
- const { sealer, sealed } = sealChatAdmission({
11772
- space: this.space, managerInstanceId: this.managerInstanceId, alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealTo: input.sealTo, creds,
11773
- });
11774
- this.chatExpiry.arm(lifecycleUid);
11775
- console.error(`chat session ${alias} admitted as ${identity.id} (uid ${lifecycleUid}), expires ${new Date(exp * 1000).toISOString()}`);
11776
- return { alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealer, sealed };
11777
- }
11778
- catch (e) {
11779
- // A confirmed rollback leaves a known state, a retired slot. An unconfirmed one does not, so
11780
- // the session stays registered and its expiry, or the stop, retries the same terminal.
11781
- let rollback;
11782
- try {
11783
- await this.chatTerminal(session);
11784
- }
11785
- catch (r) {
11786
- rollback = rejectionText(r);
11787
- try {
11788
- this.chatExpiry.arm(lifecycleUid);
11789
- }
11790
- catch (t) {
11791
- rollback += `; ${rejectionText(t)}`;
11792
- }
11793
- }
11794
- 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");
11795
- }
11796
- }
11797
- /** `chat-session-retire`: end one static chat session through the native static terminal (ledger
11798
- * row marked revoked, verified eviction of its principal's live connections, footprint cleanup,
11799
- * gate and head retirement). It refuses before any effect unless {@link admitChatRetirement}
11800
- * admits the request. A terminal that cannot complete answers `failed` with the reason, never
11801
- * success; the slot stays held. The broker keeps accepting the leaf until its expiry either way. */
11802
- async retireStaticChatSession(raw) {
11803
- if (!this.auth || this.userMode)
11804
- throw new EpEnvelopeError("unimplemented", "chat-session-retire retires static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
11805
- const input = readChatRetireInput(raw);
11806
- if ("error" in input)
11807
- throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
11808
- if (await this.admitChatRetirement(input) === "alreadyRetired")
11809
- return { outcome: "alreadyRetired" };
11810
- try {
11811
- await this.chatTerminal({ ...input, channels: this.chatExpiry.channels(input.lifecycleUid) });
11812
- }
11813
- catch (e) {
11814
- return { outcome: "failed", reason: `retirement pending: ${rejectionText(e)}` };
11815
- }
11816
- return { outcome: "retired" };
9683
+ reapOrphanSeat(a) {
9684
+ return this.seatCustody.reapOrphanSeat(a);
11817
9685
  }
11818
- /** The expiry cleanup's retirement of one session this process admitted. It is lifecycle work, so
11819
- * it is admitted like a control call and a stop drains it. A throw is a failure the tracker
11820
- * retries; a slot that is no longer this instance's to retire ends the tracking instead. */
11821
- async expireStaticChatSession(session) {
11822
- const release = this.beginLifecycle();
11823
- if (!release)
11824
- throw new Error(this.maintenanceError());
11825
- try {
11826
- console.error(`chat session ${session.alias} (uid ${session.lifecycleUid}) reached its expiry; retiring it`);
11827
- let admitted;
11828
- try {
11829
- admitted = await this.admitChatRetirement(session);
11830
- }
11831
- catch (e) {
11832
- if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
11833
- console.error(`! chat session ${session.alias} expired, but its slot is not this instance's to retire (${e.message}); expiry tracking ends`);
11834
- return;
11835
- }
11836
- throw e;
11837
- }
11838
- if (admitted === "admitted")
11839
- await this.chatTerminal(session);
11840
- }
11841
- finally {
11842
- release();
11843
- }
9686
+ driveStaticRetirement(a, surfaceFailure = false, onDeprovision) {
9687
+ return this.staticLifecycle.driveStaticRetirement(a, surfaceFailure, onDeprovision);
11844
9688
  }
11845
- /** The ownership admission shared by `chat-session-retire`, the expiry and the stop. It throws a
11846
- * not-executed refusal unless the alias is a chat alias whose slot this logical instance owns
11847
- * at the requested UID and actor. An already retired slot ends its expiry tracking. */
11848
- async admitChatRetirement(s) {
11849
- if (!isChatAlias(s.alias))
11850
- throw new EpEnvelopeError("permission-denied", `"${s.alias}" is not a chat session alias`, undefined, "not-executed");
11851
- if (this.reconcilingAliases.has(s.alias))
11852
- throw new EpEnvelopeError("unavailable", `the chat session "${s.alias}" is still reconciling at manager startup; that terminal owns it`, undefined, "not-executed");
11853
- const recordsKv = this.goalWriter?.ctx.kv;
11854
- if (!recordsKv)
11855
- throw new EpEnvelopeError("unavailable", `the durable static slot store is not ready while retiring "${s.alias}"`, undefined, "not-executed");
11856
- let slot;
11857
- try {
11858
- slot = await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, s.alias);
11859
- }
11860
- catch (e) {
11861
- throw new EpEnvelopeError("unavailable", `the durable slot for "${s.alias}" could not be read: ${rejectionText(e)}`, undefined, "not-executed");
11862
- }
11863
- const refused = chatRetireRefusal(slot?.row, s, this.managerInstanceId);
11864
- if (refused)
11865
- throw new EpEnvelopeError(refused.code, refused.message, undefined, "not-executed");
11866
- if (slot.row.phase !== "retired")
11867
- return "admitted";
11868
- this.chatExpiry.forget(s.lifecycleUid);
11869
- return "alreadyRetired";
11870
- }
11871
- /** One static terminal per chat session UID, however many callers ask: the explicit retire, the
11872
- * expiry cleanup and the open's rollback join it instead of racing its CAS sequence. A completed
11873
- * terminal ends the expiry tracking. `channels` names the membership rows to delete by name;
11874
- * without it the delivery inventory alone finds them. */
11875
- chatTerminal(s) {
11876
- let flight = this.chatRetirements.get(s.lifecycleUid);
11877
- if (!flight) {
11878
- flight = this.withRetirementSlot(() => this.driveStaticRetirement({ id: s.actor, name: s.alias, lifecycleUid: s.lifecycleUid, secretPaths: {}, ...(s.channels ? { launch: { allowSubscribe: s.channels } } : {}) }, true))
11879
- .then(() => this.chatExpiry.forget(s.lifecycleUid))
11880
- .finally(() => this.chatRetirements.delete(s.lifecycleUid));
11881
- this.chatRetirements.set(s.lifecycleUid, flight);
11882
- }
11883
- return flight;
9689
+ openStaticChatSession(raw) {
9690
+ return this.staticLifecycle.openStaticChatSession(raw);
11884
9691
  }
11885
- /** Whether `row` is a chat slot this process registered, at its exact alias, actor and UID,
11886
- * under this logical instance and this process's incarnation. */
11887
- holdsLiveChatSlot(row) {
11888
- return row.ownerInstanceId === this.managerInstanceId && row.managerInstance === this.managerLifecycleUid && this.chatExpiry.holdsExact(row);
11889
- }
11890
- /** The stop's retirement of every chat session this process still tracks, through the same
11891
- * ownership admission and terminal as `chat-session-retire`, at most
11892
- * {@link CHAT_EXPIRY_CONCURRENCY} at a time. It runs after the lifecycle fence closed and every
11893
- * admitted operation drained, as the seat teardown does, and mints nothing the terminal does not
11894
- * already mint. Every outcome is logged. It throws, naming each one, when any session was not
11895
- * retired; that session stays held until the next start of this manager instance. */
11896
- async retireChatSessionsOnStop() {
11897
- const queue = this.chatExpiry.remaining();
11898
- const failed = [];
11899
- const retireOne = async (session) => {
11900
- const at = `chat session ${session.alias} (uid ${session.lifecycleUid})`;
11901
- try {
11902
- if (await this.admitChatRetirement(session) === "alreadyRetired") {
11903
- console.error(`${at} was already retired at stop`);
11904
- return;
11905
- }
11906
- await this.chatTerminal(session);
11907
- console.error(`${at} retired at stop`);
11908
- }
11909
- catch (e) {
11910
- if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
11911
- this.chatExpiry.forget(session.lifecycleUid);
11912
- console.error(`! ${at} was not retired at stop: its slot is not this instance's to retire (${e.message})`);
11913
- return;
11914
- }
11915
- failed.push(`${session.alias} (uid ${session.lifecycleUid}): ${rejectionText(e)}`);
11916
- console.error(`! ${at} was not retired at stop (${rejectionText(e)}); it stays held until the next start of this manager instance`);
11917
- }
11918
- };
11919
- await Promise.all(Array.from({ length: Math.min(CHAT_EXPIRY_CONCURRENCY, queue.length) }, async () => {
11920
- for (let next = queue.shift(); next !== undefined; next = queue.shift())
11921
- await retireOne(next);
11922
- }));
11923
- if (failed.length)
11924
- throw new Error(`${failed.length} chat session(s) were not retired and stay held until the next start of this manager instance: ${failed.join("; ")}`);
9692
+ retireStaticChatSession(raw) {
9693
+ return this.staticLifecycle.retireStaticChatSession(raw);
11925
9694
  }
11926
- /** Name, at a stop that does not retire them, each chat session this process still tracks. */
11927
- reportChatSessionsLeftAtStop(why) {
11928
- for (const session of this.chatExpiry.remaining())
11929
- console.error(`! chat session ${session.alias} (uid ${session.lifecycleUid}) was not retired because ${why}; the next start of this manager instance retires it`);
11930
- }
11931
- /** Push renewal of ONE live managed-static credential: re-mint the SAME nkey
11932
- * identity with the SAME scope (recorded on the managed row at spawn) and a fresh bounded
11933
- * exp, ledger the new credentialId (slot record first, then the row, then the file — a
11934
- * credential is never materialized before its ledger row exists), and re-sign the SAME
11935
- * lifecycle-keyed file the agent endpoint's source seam re-reads. Never advances the epoch;
11936
- * renewal remains the THIRD transition. */
11937
- async renewManagedStaticCred(a) {
11938
- if (!this.auth || !a.seed || !a.secretPaths?.creds)
11939
- throw new Error("renewManagedStaticCred: not a renewable managed-static agent");
11940
- // Admission is synchronous. An accepted renewal publishes its flight before its first caller can
11941
- // terminalize the agent; terminalization rejects later callers and drains this flight before the
11942
- // durable terminal starts, giving renewal-before-terminal and terminal-before-renewal one order.
11943
- if (a.terminalizing)
11944
- throw new Error("renewManagedStaticCred: the lifecycle is terminalizing; no credential is minted after the terminal begins");
11945
- if (a.staticCredentialRenewal)
11946
- return a.staticCredentialRenewal;
11947
- const renewal = this.driveManagedStaticCredRenewal(a).finally(() => {
11948
- if (a.staticCredentialRenewal === renewal)
11949
- a.staticCredentialRenewal = undefined;
11950
- });
11951
- a.staticCredentialRenewal = renewal;
11952
- return renewal;
11953
- }
11954
- async driveManagedStaticCredRenewal(a) {
11955
- // The SAME permission scope the spawn minted (recorded on the managed row): allowSubscribe/
11956
- // allowPublish/role/capabilities are the JWT-shaping inputs; `subscribe` (the active read
11957
- // set) shapes durable membership only and is not a mint input.
11958
- if (!a.issued)
11959
- 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`);
11960
- // A renewal never outlives the generation's horizon, and none is minted at or past it: the
11961
- // generation then authorizes nothing and its rows are being removed (SPEC 13.15).
11962
- const now = Math.floor(Date.now() / 1000);
11963
- const horizon = issuedHorizon(a.issued.generation);
11964
- if (now >= horizon)
11965
- 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)`);
11966
- const exp = Math.min(now + MANAGED_STATIC_TTL_SEC, horizon);
11967
- // A RENEWAL keeps the generation (SPEC 13.15): the same JWT-shaping inputs produce the same
11968
- // ceiling, which `confirm` verifies against the recorded evidence before the ledger append. A
11969
- // changed ceiling is refused there: that is a fresh issuance on a new connection, never a renewal.
11970
- const issued = a.issued;
11971
- const endpoints = lowerPersonaEndpoints(a.launch.endpoints);
11972
- const reads = this.managedStaticInstanceReads(a.launch.capabilities);
11973
- if (reads.length) {
11974
- // Resolve this incarnation's original issuance, not its current spawner or a reconstructed
11975
- // run admission. Old seats and run helpers keep the exact ceiling they were minted with.
11976
- const caller = { owner: DEV_OWNER, actor: a.id, uid: a.lifecycleUid, generation: issued.generation };
11977
- 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));
11978
- if (!grantOverreach(this.space, caller, evidence.permissions, { endpoints: reads }).length)
11979
- endpoints.push(...reads);
11980
- }
11981
- const creds = await this.withIssuer((i) => mintCreds(this.auth, { id: a.id, seed: a.seed }, "agent", {
11982
- eventPayloads: this.eventPayloadsWithheld ? false : a.launch.eventPayloads,
11983
- allowSubscribe: a.launch.allowSubscribe,
11984
- allowPublish: a.launch.allowPublish,
11985
- role: a.role,
11986
- capabilities: a.launch.capabilities,
11987
- ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
11988
- lifecycleUid: a.lifecycleUid,
11989
- expiresAt: exp,
11990
- issued,
11991
- issuance: this.issuanceSeam(i, "renew", a, exp),
11992
- }));
11993
- const secrets = this.secrets;
11994
- const credsPath = a.secretPaths.creds;
11995
- await secrets.put(agentSecretKeyForFile(credsPath, this.space), creds);
11996
- await materializeSecretToFile(secrets, agentSecretKeyForFile(credsPath, this.space), credsPath);
11997
- // The record pins the credential's digest, so it follows the re-signed file.
11998
- this.refreshSeatRecord(a);
11999
- 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`);
12000
- }
12001
- /** The static-slot reconciliation ("no active orphan"): ensure the authority stores, then sweep
12002
- * every durable slot row and act by the TOTAL resume table — `provisioning`/`terminalizing`
12003
- * re-drive the exact-op terminal; an `active` row survives ONLY when a LIVE managed agent this
12004
- * manager process owns backs it at the same uid (`adopted`), else no managed owner claimed it and
12005
- * its broker authority is contained and terminalized; `retired` rows seed the retired-principal refusal index. Two call sites: the BOOT sweep
12006
- * (`postAdoption=false`, under the lease before control serving) DEFERS active-non-adopted
12007
- * slots while a resume is still pending (adoption runs after it); the POST-ADOPTION sweep
12008
- * (`postAdoption=true`, inside finalizeResume while `resumeRequired` still fences ordinary
12009
- * spawns) terminalizes any active slot the resume did not claim. */
12010
- staticReconcileKey(row) {
12011
- return JSON.stringify([row.owner, row.alias, row.lifecycleUid]);
12012
- }
12013
- /** Read one retry coordinate from the durable slot store. The status snapshot never authorizes a
12014
- * re-drive: every timer comes through this fresh read before the planner and exact terminal. */
12015
- async readStaticReconcileSlot(alias) {
12016
- if (!this.auth)
12017
- return undefined;
12018
- const identity = newIdentity();
12019
- const creds = await mintCreds(this.auth, identity, "provisioner");
12020
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
12021
- try {
12022
- const recordsKv = await new Kvm(nc).open(recordsBucket(this.space));
12023
- return (await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, alias))?.row;
12024
- }
12025
- finally {
12026
- await drainAndClose(nc);
12027
- }
9695
+ retireChatSessionsOnStop() {
9696
+ return this.staticLifecycle.retireChatSessionsOnStop();
12028
9697
  }
12029
- scheduleStaticReconcileRetry(key, item) {
12030
- if (this.staticReconcileStopping || item.timer || item.attempts >= item.maxAttempts)
12031
- return;
12032
- const delay = this.staticReconcileRetryDelaysMs[item.attempts - 1];
12033
- if (delay === undefined)
12034
- return;
12035
- const nextRetryAtMs = Date.now() + delay;
12036
- item.disposition = "retry-scheduled";
12037
- item.nextRetryAt = new Date(nextRetryAtMs).toISOString();
12038
- item.timer = setTimeout(() => {
12039
- item.timer = undefined;
12040
- item.nextRetryAt = undefined;
12041
- const run = async () => {
12042
- // The timer may fire while the failed attempt is still unwinding, especially in compressed
12043
- // smoke schedules. Join that flight before consuming another budget entry; never overlap it.
12044
- if (item.flight)
12045
- await item.flight;
12046
- await this.retryStaticReconcile(key);
12047
- };
12048
- void run().catch((error) => {
12049
- item.lastError = `retry driver failed before the exact terminal: ${rejectionText(error)}`;
12050
- item.disposition = "retry-exhausted";
12051
- item.remedy = "restart this manager for a fresh per-process retry budget";
12052
- 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`);
12053
- });
12054
- }, delay);
12055
- item.timer.unref?.();
12056
- console.error(`! static reconcile retry-scheduled alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts + 1}/${item.maxAttempts} nextRetryAt=${item.nextRetryAt}`);
12057
- }
12058
- retryStaticReconcile(key) {
12059
- const item = this.staticReconcileItems.get(key);
12060
- if (!item || this.staticReconcileStopping || item.disposition === "recovered")
12061
- return Promise.resolve();
12062
- if (item.retryFlight)
12063
- return item.retryFlight;
12064
- const flight = this.driveStaticReconcileRetry(key, item);
12065
- let wrapped;
12066
- wrapped = flight.finally(() => {
12067
- if (item.retryFlight === wrapped)
12068
- item.retryFlight = undefined;
12069
- });
12070
- item.retryFlight = wrapped;
12071
- return wrapped;
9698
+ reportChatSessionsLeftAtStop(why) {
9699
+ return this.staticLifecycle.reportChatSessionsLeftAtStop(why);
12072
9700
  }
12073
- async driveStaticReconcileRetry(key, item) {
12074
- if (item.flight)
12075
- await item.flight;
12076
- if (this.staticReconcileStopping || item.disposition === "recovered")
12077
- return;
12078
- // A retry trigger consumes one finite budget entry even if the authoritative re-read itself
12079
- // fails. Otherwise a broker outage before the planner could reschedule forever without ever
12080
- // incrementing `attempts`, violating the bounded-retry guarantee.
12081
- item.attempts++;
12082
- item.disposition = "retrying";
12083
- item.remedy = undefined;
12084
- console.error(`static reconcile retrying alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
12085
- let row;
12086
- try {
12087
- row = await this.readStaticReconcileSlot(item.alias);
12088
- }
12089
- catch (error) {
12090
- item.lastError = `durable slot re-read failed: ${rejectionText(error)}`;
12091
- if (item.attempts >= item.maxAttempts) {
12092
- item.disposition = "retry-exhausted";
12093
- item.remedy = "restart this manager for a fresh per-process retry budget";
12094
- 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`);
12095
- }
12096
- else {
12097
- this.scheduleStaticReconcileRetry(key, item);
12098
- }
12099
- return;
12100
- }
12101
- if (row === undefined || row.owner !== item.owner || row.actor !== item.actor || row.lifecycleUid !== item.lifecycleUid) {
12102
- item.disposition = "refused";
12103
- item.remedy = "inspect the durable slot; reconciliation will not cross incarnations";
12104
- item.lastError = row === undefined
12105
- ? "the durable slot vanished; reconciliation never acts from the in-memory snapshot"
12106
- : `the durable slot moved to actor ${row.actor} uid ${row.lifecycleUid}; reconciliation never crosses incarnations`;
12107
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
12108
- return;
12109
- }
12110
- item.phase = row.phase;
12111
- if (row.phase === "retired") {
12112
- item.disposition = "recovered";
12113
- item.recoveredAt = new Date().toISOString();
12114
- item.lastError = undefined;
12115
- console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
12116
- return;
12117
- }
12118
- if (ownedBySibling(row, this.managerInstanceId)) {
12119
- item.disposition = "refused";
12120
- item.remedy = "the owning manager must reconcile or an operator must perform an explicit CAS takeover";
12121
- item.lastError = `the durable slot belongs to manager instance ${row.ownerInstanceId}, not ${this.managerInstanceId}`;
12122
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
12123
- return;
12124
- }
12125
- const live = this.agents.get(row.alias);
12126
- const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
12127
- if (planStaticSlotResume(row, adopted) !== "drive-terminal") {
12128
- item.disposition = "refused";
12129
- item.remedy = adopted ? "leave the adopted live lifecycle running" : "inspect the fresh durable slot state";
12130
- item.lastError = adopted
12131
- ? "the durable lifecycle is now backed by an adopted live managed agent"
12132
- : `the fresh durable phase ${row.phase} is not terminal-plannable`;
12133
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
12134
- return;
12135
- }
12136
- await this.attemptStaticReconcile(key, item, row, false);
12137
- }
12138
- /** Enter one exact terminal at most once per coordinate. Sweep and timer triggers join the same
12139
- * promise. A settled failed item keeps its original per-process budget; a restart builds a fresh
12140
- * map from the still-authoritative durable row. */
12141
- attemptStaticReconcile(key, item, row, countAttempt = true) {
12142
- if (item.flight)
12143
- return item.flight;
12144
- if (item.timer)
12145
- return Promise.resolve({ succeeded: false });
12146
- // A timer/retry driver increments before its mandatory durable re-read, then calls with
12147
- // countAttempt=false. Let that already-consumed budget entry enter the terminal. Only a fresh
12148
- // sweep entry (countAttempt=true) is refused once the per-process budget is exhausted.
12149
- if (countAttempt && item.attempts >= item.maxAttempts)
12150
- return Promise.resolve({ succeeded: false });
12151
- const flight = (async () => {
12152
- if (countAttempt)
12153
- item.attempts++;
12154
- item.phase = row.phase;
12155
- item.disposition = "retrying";
12156
- item.nextRetryAt = undefined;
12157
- this.reconcilingAliases.add(row.alias);
12158
- console.error(`static reconcile terminal alias=${row.alias} phase=${row.phase} uid=${row.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
12159
- let deprovision;
12160
- try {
12161
- await this.withRetirementSlot(() => this.driveStaticRetirement({ id: row.actor, name: row.alias, lifecycleUid: row.lifecycleUid, runtime: row.runtime }, true, (accounting) => { deprovision = accounting; }));
12162
- if (item.attempts === 1) {
12163
- this.staticReconcileItems.delete(key);
12164
- }
12165
- else {
12166
- item.phase = "retired";
12167
- item.disposition = "recovered";
12168
- item.recoveredAt = new Date().toISOString();
12169
- item.lastError = undefined;
12170
- console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
12171
- }
12172
- return { succeeded: true, deprovision };
12173
- }
12174
- catch (error) {
12175
- item.lastError = rejectionText(error);
12176
- try {
12177
- const fresh = await this.readStaticReconcileSlot(item.alias);
12178
- if (fresh?.lifecycleUid === item.lifecycleUid && fresh.actor === item.actor)
12179
- item.phase = fresh.phase;
12180
- }
12181
- catch { /* the terminal error remains primary; the next retry re-reads authoritatively */ }
12182
- const blocked = lifecycleBlockedFrom(error);
12183
- const ownOp = managedRetirementOpId(item.lifecycleUid);
12184
- const foreign = blocked !== undefined && (blocked.blockedOp !== "retirement" || blocked.opId !== ownOp);
12185
- if (foreign) {
12186
- item.disposition = "refused-foreign";
12187
- item.remedy = blocked?.remedy ?? "resolve the foreign durable operation; it is never force-cleared";
12188
- console.error(`! static reconcile refused-foreign alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
12189
- }
12190
- else if (item.attempts >= item.maxAttempts) {
12191
- item.disposition = "retry-exhausted";
12192
- item.remedy = "restart this manager for a fresh per-process retry budget";
12193
- 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`);
12194
- }
12195
- else {
12196
- // The initial serial sweep must publish its complete failed aggregate before any timer can
12197
- // re-enter a middle row. Mark it now; the sweep arms the timer after its last planned row.
12198
- if (this.staticReconcileSweepsInFlight > 0)
12199
- item.disposition = "retry-scheduled";
12200
- else
12201
- this.scheduleStaticReconcileRetry(key, item);
12202
- }
12203
- return { succeeded: false, deprovision };
12204
- }
12205
- finally {
12206
- this.reconcilingAliases.delete(row.alias);
12207
- }
12208
- })();
12209
- item.flight = flight.finally(() => {
12210
- if (item.flight === wrapped)
12211
- item.flight = undefined;
12212
- });
12213
- const wrapped = item.flight;
12214
- return wrapped;
9701
+ renewManagedStaticCred(a) {
9702
+ return this.staticLifecycle.renewManagedStaticCred(a);
12215
9703
  }
12216
- releaseStaticReconcileSweep() {
12217
- this.staticReconcileSweepsInFlight--;
12218
- if (this.staticReconcileSweepsInFlight !== 0)
12219
- return;
12220
- const waiters = this.staticReconcileDrainWaiters;
12221
- this.staticReconcileDrainWaiters = [];
12222
- for (const wake of waiters)
12223
- wake();
9704
+ readStaticReconcileSlot(alias) {
9705
+ return this.staticLifecycle.readStaticReconcileSlot(alias);
12224
9706
  }
12225
- /** Shutdown accepts no new static reconciliation work, then drains every sweep and exact-terminal
12226
- * flight that crossed the fence before stop(). A sweep can discover several rows before its first
12227
- * await, so the serial loop also consults the fence and never starts a later row after shutdown. */
12228
- async awaitStaticReconcileDrain() {
12229
- while (true) {
12230
- if (this.staticReconcileSweepsInFlight > 0)
12231
- await new Promise((resolve) => this.staticReconcileDrainWaiters.push(resolve));
12232
- const flights = [];
12233
- for (const item of this.staticReconcileItems.values()) {
12234
- if (item.flight)
12235
- flights.push(item.flight);
12236
- if (item.retryFlight)
12237
- flights.push(item.retryFlight);
12238
- }
12239
- if (flights.length === 0 && this.staticReconcileSweepsInFlight === 0)
12240
- return;
12241
- await Promise.allSettled(flights);
12242
- }
9707
+ awaitStaticReconcileDrain() {
9708
+ return this.staticLifecycle.awaitStaticReconcileDrain();
12243
9709
  }
12244
- async reconcileStaticLifecycles(postAdoption = false) {
12245
- if (!this.auth || this.staticReconcileStopping)
12246
- return;
12247
- // Admission is synchronous with the shutdown fence. Once this increments, stop() must drain the
12248
- // whole accepted sweep even if it is still minting its short-lived provisioner credential.
12249
- this.staticReconcileSweepsInFlight++;
12250
- try {
12251
- // Recovered is a transition report, not permanent history. The next sweep clears it before
12252
- // deriving a fresh plan; failed coordinates keep their per-process budget and are joined.
12253
- for (const [key, item] of this.staticReconcileItems) {
12254
- if (item.disposition === "recovered")
12255
- this.staticReconcileItems.delete(key);
12256
- }
12257
- const sweep = {
12258
- kind: postAdoption ? "post-adoption" : "startup",
12259
- startedAt: new Date().toISOString(),
12260
- attempted: 0,
12261
- succeeded: 0,
12262
- failed: 0,
12263
- };
12264
- this.staticReconcileLastSweep = sweep;
12265
- const slotRows = [];
12266
- // A sweep that stops before it plans any alias records why on the sweep itself: otherwise
12267
- // `status` cannot tell it from a sweep that collected and found nothing.
12268
- try {
12269
- const identity = newIdentity();
12270
- const creds = await mintCreds(this.auth, identity, "provisioner");
12271
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
12272
- try {
12273
- const jsm = await jetstreamManager(nc);
12274
- const kvm = new Kvm(nc);
12275
- await ensureAuthorityStores(jsm, kvm, this.space);
12276
- const recordsKv = await kvm.open(recordsBucket(this.space));
12277
- for (const slot of await walkStaticSlots(recordsKv, DEV_OWNER))
12278
- slotRows.push(slot.row);
12279
- }
12280
- finally {
12281
- await drainAndClose(nc);
12282
- }
12283
- }
12284
- catch (error) {
12285
- sweep.completedAt = new Date().toISOString();
12286
- sweep.error = rejectionText(error);
12287
- throw error;
12288
- }
12289
- let retiredSlots = 0;
12290
- let preservedForeign = 0;
12291
- let preservedAdopted = 0;
12292
- let deferredSlots = 0;
12293
- const terminalRows = [];
12294
- const restartRows = [];
12295
- for (const row of slotRows) {
12296
- if (row.phase === "retired") {
12297
- // A retirement is a GLOBAL refusal fact — seed the retired-principal index for EVERY retired incarnation
12298
- // regardless of which instance owned it, so a sibling-retired incarnation's copied credential
12299
- // is refused at this control surface too. Ownership gates only the DESTRUCTIVE sweep below.
12300
- this.retiredPrincipals.add(principalKey(row.owner, row.actor).key);
12301
- retiredSlots++;
12302
- continue;
12303
- }
12304
- // RECONCILE OWNERSHIP (multi-manager-per-space): a manager adjudicates ONLY the non-retired
12305
- // rows THIS logical instance owns. A SIBLING manager's active/provisioning row is LEFT UNTOUCHED —
12306
- // sweep-terminalizing it would destroy the sibling's live agent (the historical all-agents-kill
12307
- // hazard, now cross-instance). A legacy row (no owner recorded) predates multi-manager,
12308
- // so this manager is its legitimate single-manager-past successor and reconciles it. An orphaned
12309
- // sibling row is reclaimed only by an explicit operator CAS takeover, never here.
12310
- if (ownedBySibling(row, this.managerInstanceId)) {
12311
- preservedForeign++;
12312
- continue;
12313
- }
12314
- // A chat session this process is opening or holds is live membership, as an adopted seat
12315
- // is: its own open, expiry or stop runs its terminal, which this sweep must not race. The
12316
- // match is the exact registered alias, actor and UID under this logical instance and this
12317
- // process's incarnation, so a foreign, legacy or unrecorded row, or any UID this process
12318
- // did not register, falls through to the ordinary plan below.
12319
- if (this.holdsLiveChatSlot(row)) {
12320
- preservedAdopted++;
12321
- continue;
12322
- }
12323
- // ADOPTION is genuine membership: a slot backed by a live managed agent THIS process owns
12324
- // at the SAME uid is never an orphan (empty at boot; exactly the adopted set at the
12325
- // post-adoption sweep — the fix for the resume hole).
12326
- const live = this.agents.get(row.alias);
12327
- const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
12328
- if (adopted) {
12329
- preservedAdopted++;
12330
- }
12331
- // Boot sweep with a resume PENDING: an active slot may yet be adopted (the resume path runs
12332
- // AFTER this boot sweep), so DEFER it — the post-adoption sweep terminalizes any the resume
12333
- // did not claim. provisioning/terminalizing NEVER defer (they are crashed operations, never
12334
- // an agent to adopt). At `postAdoption` (or a non-resume boot) nothing defers.
12335
- if (!postAdoption && row.phase === "active" && !adopted && this.resumeRequired) {
12336
- deferredSlots++;
12337
- continue;
12338
- }
12339
- // A boot after this instance's manager ended without stopping its seats: a seat with a record
12340
- // is taken back instead of retired, restarted under its policy when supervised (#4094) and
12341
- // adopted while it still runs otherwise (#4095).
12342
- if (!postAdoption && row.phase === "active" && !adopted) {
12343
- const record = this.seatRecordFor(row);
12344
- if (record) {
12345
- restartRows.push({ row, record });
12346
- continue;
12347
- }
12348
- }
12349
- if (planStaticSlotResume(row, adopted) !== "none")
12350
- terminalRows.push(row);
12351
- }
12352
- try {
12353
- // Mark the complete planned set before the first terminal awaits. A timer owns only its own
12354
- // alias, but the initial serial sweep must close every discovery-to-await gap up front.
12355
- for (const row of terminalRows)
12356
- this.reconcilingAliases.add(row.alias);
12357
- for (const { row } of restartRows)
12358
- this.reconcilingAliases.add(row.alias);
12359
- // Restarts run first; one that cannot restart joins the terminals below.
12360
- for (const { row, record } of restartRows) {
12361
- if (this.staticReconcileStopping)
12362
- break;
12363
- // A supervised seat is restarted; any other seat is adopted while it still runs.
12364
- const refusal = record.supervise ? await this.restartSupervisedSeat(row, record) : await this.adoptSeat(row, record);
12365
- if (refusal === undefined) {
12366
- this.reconcilingAliases.delete(row.alias);
12367
- continue;
12368
- }
12369
- console.error(record.supervise
12370
- ? `! ${row.alias}: the supervised seat its previous manager left was not restarted (${refusal}); retiring the lifecycle`
12371
- : `! ${row.alias}: the seat its previous manager left was not adopted (${refusal}); retiring the lifecycle`);
12372
- this.dropSeatRecord({ name: row.alias, lifecycleUid: row.lifecycleUid });
12373
- terminalRows.push(row);
12374
- }
12375
- const sweepDeprovision = {
12376
- examined: 0,
12377
- deleted: 0,
12378
- absent: 0,
12379
- refused: 0,
12380
- acknowledged: 0,
12381
- disappeared: 0,
12382
- consumers: { examined: 0, deleted: 0, absent: 0, refused: 0, acknowledged: 0, disappeared: 0 },
12383
- acls: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
12384
- members: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
12385
- };
12386
- for (const row of terminalRows) {
12387
- if (this.staticReconcileStopping)
12388
- break;
12389
- sweep.attempted++;
12390
- const key = this.staticReconcileKey(row);
12391
- let item = this.staticReconcileItems.get(key);
12392
- if (!item) {
12393
- item = {
12394
- owner: row.owner,
12395
- alias: row.alias,
12396
- actor: row.actor,
12397
- lifecycleUid: row.lifecycleUid,
12398
- phase: row.phase,
12399
- attempts: 0,
12400
- maxAttempts: STATIC_RECONCILE_MAX_ATTEMPTS,
12401
- disposition: "retrying",
12402
- };
12403
- this.staticReconcileItems.set(key, item);
12404
- }
12405
- const attempt = await this.attemptStaticReconcile(key, item, row);
12406
- if (attempt.deprovision)
12407
- addDeprovisionAccounting(sweepDeprovision, attempt.deprovision);
12408
- if (attempt.succeeded)
12409
- sweep.succeeded++;
12410
- else
12411
- sweep.failed++;
12412
- this.reconcilingAliases.delete(row.alias);
12413
- }
12414
- sweep.completedAt = new Date().toISOString();
12415
- this.staticReconcileLastSweepResources = {
12416
- slots: {
12417
- examined: slotRows.length,
12418
- retired: retiredSlots,
12419
- preservedForeign,
12420
- preservedAdopted,
12421
- deferred: deferredSlots,
12422
- terminalized: sweep.succeeded,
12423
- failed: sweep.failed,
12424
- },
12425
- deprovision: sweepDeprovision,
12426
- };
12427
- for (const row of terminalRows) {
12428
- const key = this.staticReconcileKey(row);
12429
- const item = this.staticReconcileItems.get(key);
12430
- if (item?.disposition === "retry-scheduled" && !item.timer)
12431
- this.scheduleStaticReconcileRetry(key, item);
12432
- }
12433
- const failed = terminalRows.flatMap((row) => {
12434
- const item = this.staticReconcileItems.get(this.staticReconcileKey(row));
12435
- return item && item.disposition !== "recovered" ? [`${item.alias}:${item.phase}:${item.disposition}`] : [];
12436
- });
12437
- if (sweep.failed === 0) {
12438
- console.error(`✓ static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, 0 failed`);
12439
- }
12440
- else {
12441
- console.error(`! static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, ${sweep.failed} failed; failed=${failed.join(",")}`);
12442
- }
12443
- }
12444
- finally {
12445
- for (const row of terminalRows)
12446
- this.reconcilingAliases.delete(row.alias);
12447
- for (const { row } of restartRows)
12448
- this.reconcilingAliases.delete(row.alias);
12449
- }
12450
- }
12451
- finally {
12452
- this.releaseStaticReconcileSweep();
12453
- }
9710
+ reconcileStaticLifecycles(postAdoption = false) {
9711
+ return this.staticLifecycle.reconcileStaticLifecycles(postAdoption);
12454
9712
  }
12455
9713
  /** The membership gate: decide a control caller by its
12456
9714
  * AUTHENTICATED wire principal. A LIVE managed slot passes (unless terminalizing); a RETIRING
@@ -12465,14 +9723,7 @@ export class Manager {
12465
9723
  ? `the caller's lifecycle ${a.lifecycleUid} is terminalizing; control is refused from the first terminal step`
12466
9724
  : undefined;
12467
9725
  }
12468
- for (const [name, hold] of this.retiring) {
12469
- const held = hold.target.userOwner ? hold.target.id : principalKey(DEV_OWNER, hold.target.id).key;
12470
- if (held === caller)
12471
- return `the caller's lifecycle ${hold.target.lifecycleUid} (name "${name}") is retiring; a retiring incarnation's credential holds no control authority`;
12472
- }
12473
- if (this.retiredPrincipals.has(caller))
12474
- return "the caller's lifecycle is retired; a retired incarnation's credential holds no control authority";
12475
- return undefined;
9726
+ return this.retirement.membershipRefusal(caller);
12476
9727
  }
12477
9728
  /** Open a short-lived PROVISIONER connection, run the onboarding ops on it, and drain it (closure (ii),
12478
9729
  * residual 2). The DM/DLV consumer-create surface — the irreducible onboarding power — lives only for