@cotal-ai/manager 0.166.3 → 0.167.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -7,38 +7,42 @@ 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, MANAGER_LEASE_TTL_MS, awaitLeaseExpiry, leaseRemainingMs, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, assertValidChannel, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, DeprovisionError, addDeprovisionAccounting, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, firstFreeName, spawnNameError, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, provisionAgentDurables, registry, resolveAuthProvider, resolveReadAcl, runAgentBearer, runDriverCaller, saveAgentFile, eventChannel, eventChannelPrincipal, digestIdToken, capabilityWithin, grantOverreach, grantParts, isIssuedCaller, issuedSpawnerStanding, withIssuerSession, renderOnceTask, shownSpawner, } from "@cotal-ai/core";
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, 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, watchProvedExit, } from "./runtime/index.js";
14
+ import { Retirement } from "./retirement.js";
15
+ import { ServePlane } from "./serve-plane.js";
14
16
  import { AttachEndpoint } from "./attach-endpoint.js";
15
17
  import { DELIVERY_ADMIN_BOOT_WAIT_MS, isUnansweredDeliveryAdmin, makeManagerEndpointEvictionEvidence, makeManagerEndpointHolderEvictor, untilDeliveryAdminAnswers, withScopedEndpoint } from "./endpoint-evict.js";
16
18
  import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
19
+ import { SessionRecovery } from "./session-recovery.js";
20
+ import { SeatCustody } from "./seat-custody.js";
21
+ import { withTimeout } from "./manager-timeout.js";
17
22
  import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
18
- import { inlinePersonaDir, inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment, writeContinuityAssignment } from "./launch.js";
23
+ import { inlinePersonaDir, inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment } from "./launch.js";
19
24
  import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
20
25
  import { controlShutdown } from "./control-shutdown.js";
21
26
  import { RunHosting, servedRequestSubject } from "./run-hosting.js";
22
27
  import { enrolledAcl } from "./remote-authority.js";
23
28
  import { pendingEnrollment } from "./pending-enrollment.js";
24
29
  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";
30
+ import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, supervisePolicy, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
27
31
  import { TranscriptReceiver } from "./transcript-receive.js";
28
32
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
29
33
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
30
34
  import { jetstream, jetstreamManager } from "@nats-io/jetstream";
31
35
  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";
36
+ import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, issuedHorizon, REMOTE_MANAGER_IDENTITY_NAMES } from "@cotal-ai/core";
33
37
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
34
38
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
35
39
  // per-session credentials on their own short-lived connections).
36
- import { ManagerSessionPlane, openSessionLedgerKv } from "./session/index.js";
40
+ import { ManagerSessionPlane } from "./session/index.js";
37
41
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
38
42
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
39
43
  // 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";
44
+ import { provisionEndpointGateOpen, serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, requestGoalCancel, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, mintCheckpoint, MAX_SCHEDULE_MS, resumeCheckpoint, readCheckpointSettle, readCheckpointSpec, expireCheckpoint, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, seatCapRefused, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
45
+ import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
42
46
  import { measureManagerVitals } from "./vitals.js";
43
47
  import { staticLifecycleTransport, activateStaticLifecycle, runStaticTerminal, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, planStaticSlotResume, ownedBySibling, observeStaticSlot, listStaticSlotObservations, walkStaticSlots, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
44
48
  import { CHAT_ALIAS_PREFIX, CHAT_EXPIRY_CONCURRENCY, ChatSessionExpiry, chatOpenLists, chatRetireRefusal, drawChatAlias, isChatAlias, readChatOpenInput, readChatRetireInput, sealChatAdmission, } from "./chat-session.js";
@@ -93,11 +97,6 @@ const LATE_JOIN_POLL_MS = 1_000;
93
97
  * must run without exiting before it is ready: long enough that a harness refusing its arguments
94
98
  * exits first and is reported as failed. */
95
99
  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
100
  /** Upper bound on a detached agent-exit deprovision (#159 B2). A wedged broker must not leave the
102
101
  * fire-and-forget teardown pending forever with no log — past this it rejects into freeSlot's fail-loud
103
102
  * `.catch`. Generous over the helper's 5s connect timeout to allow the two consumer-deletes + ACL purge
@@ -239,15 +238,6 @@ function failedTerminal(error, source) {
239
238
  catch { /* unreadable or not interchangeable */ }
240
239
  return { error: text };
241
240
  }
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
241
  /** One absolute budget across authority, preflight and adoption waits, or one closed-serve attempt. */
252
242
  function remoteStandingTimeLeft(deadline) {
253
243
  const left = deadline - performance.now();
@@ -626,33 +616,6 @@ export class Manager {
626
616
  /** Expiry stamps (`startedAt + MIN_LIFETIME`) for slots that freed while still young — a
627
617
  * count-only, lazily-pruned recycle floor (P4c). Pruned + summed into the ceiling gate. */
628
618
  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
619
  /** This manager process's own incarnation uid (SPEC 13.1; minted once per supervisor process,
657
620
  * never reused across restarts) — the endpoint's presence key AND the `managerInstance` audit
658
621
  * coordinate every static activation records. */
@@ -715,11 +678,6 @@ export class Manager {
715
678
  /** Renews the session signing key long before its window closes. A key that expires unattended
716
679
  * takes the whole session plane down until the manager is restarted, which kills live sessions. */
717
680
  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
681
  /** The STABLE session-LEDGER identity (auth mode) — minted once at registration
724
682
  * alongside the serve + goal-writer identities; a renewal re-mints the SAME nkey with a fresh
725
683
  * bounded exp and re-stages its distinct credId into the §13.1 revocation family. The current
@@ -831,14 +789,6 @@ export class Manager {
831
789
  /** Held as an instance field so broker-owning smokes can compress the schedule without changing
832
790
  * production semantics. It is never a fence expiry: the durable non-retired row stays authoritative. */
833
791
  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
792
  /** Retirements holding one of the {@link RETIREMENT_CONCURRENCY} slots. */
843
793
  retirementsRunning = 0;
844
794
  /** Retirements waiting for a slot, oldest first. */
@@ -855,6 +805,98 @@ export class Manager {
855
805
  /** True on a USER-AUTH space (the on-disk marker; cross-checked against the registry at start).
856
806
  * Gates the whole spawn path: user mode grants ledger actors + bearer plumbing, never static mints. */
857
807
  userMode = false;
808
+ servePlane = new ServePlane({
809
+ auth: () => this.auth,
810
+ remoteAuthority: () => this.remoteAuthority,
811
+ space: () => this.space,
812
+ servers: () => this.servers,
813
+ workspaceRoot: () => this.workspaceRoot,
814
+ managerInstanceId: () => this.managerInstanceId,
815
+ managerServeIdentity: () => this.managerServeIdentity,
816
+ leaseStopping: () => this.leaseStopping,
817
+ remoteBundleRenewal: () => this.remoteBundleRenewal,
818
+ maxSessions: () => this.maxSessions,
819
+ serviceServe: () => this.serviceServe,
820
+ setServiceServe: (value) => { this.serviceServe = value; },
821
+ sessionLedgerIdentity: () => this.sessionLedgerIdentity,
822
+ setSessionLedgerIdentity: (value) => { this.sessionLedgerIdentity = value; },
823
+ sessionLedgerCreds: () => this.sessionLedgerCreds,
824
+ setSessionLedgerCreds: (value) => { this.sessionLedgerCreds = value; },
825
+ sessionLedgerConn: () => this.sessionLedgerConn,
826
+ setSessionLedgerConn: (value) => { this.sessionLedgerConn = value; },
827
+ sessionPlane: () => this.sessionPlane,
828
+ setSessionPlane: (value) => { this.sessionPlane = value; },
829
+ sessionKeyRenewTimer: () => this.sessionKeyRenewTimer,
830
+ setSessionKeyRenewTimer: (value) => { this.sessionKeyRenewTimer = value; },
831
+ connectorStatuses: () => this.connectorStatuses,
832
+ setGoalWriterIdentity: (value) => { this.goalWriterIdentity = value; },
833
+ setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
834
+ remoteStandingBudgetMs: REMOTE_STANDING_BUDGET_MS,
835
+ dial: (...args) => this.dial(...args),
836
+ dialRemoteStanding: (...args) => this.dialRemoteStanding(...args),
837
+ trackTransport: (...args) => this.trackTransport(...args),
838
+ discardServeCandidate: (...args) => this.discardServeCandidate(...args),
839
+ managerServiceDefs: (...args) => this.managerServiceDefs(...args),
840
+ omitClassCommands: (...args) => this.omitClassCommands(...args),
841
+ resolveTarget: (target) => this.resolveServeTarget(target),
842
+ withEndpointServeExecutor: (...args) => this.withEndpointServeExecutor(...args),
843
+ withOpenServeConnection: (...args) => this.withOpenServeConnection(...args),
844
+ boundedReconnect: (...args) => this.boundedReconnect(...args),
845
+ renewRemoteBeforeRedial: (...args) => this.renewRemoteBeforeRedial(...args),
846
+ scheduleServeRenewal: (...args) => this.scheduleServeRenewal(...args),
847
+ stop: (...args) => this.stop(...args),
848
+ healFrozenRegistrationGate: (...args) => this.healFrozenRegistrationGate(...args),
849
+ mintAndStageGoalWriter: (...args) => this.mintAndStageGoalWriter(...args),
850
+ retireConnection: (...args) => this.retireConnection(...args),
851
+ withTimeout,
852
+ remoteStandingTimeLeft,
853
+ openMeshUnverifiedEviction,
854
+ openMeshFrozenGateRefusal,
855
+ });
856
+ resolveServeTarget(t) {
857
+ if (this.remoteAuthority) {
858
+ const key = principalKey(t.owner, t.actor).key;
859
+ for (const a of this.agents.values())
860
+ if (a.id === key)
861
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
862
+ const participant = [...this.participants.values()].find((p) => p.owner === t.owner && p.actor === t.actor && this.currentParticipant(p.owner, p.actor, p.uid) === p);
863
+ return participant ? { lifecycleUid: participant.uid, mappingRevision: 0 } : undefined;
864
+ }
865
+ if (t.owner === DEV_OWNER) {
866
+ for (const a of this.agents.values())
867
+ if (!a.userOwner && a.id === t.actor)
868
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
869
+ return undefined;
870
+ }
871
+ const key = principalKey(t.owner, t.actor).key;
872
+ for (const a of this.agents.values())
873
+ if (a.userOwner && a.id === key)
874
+ return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
875
+ return undefined;
876
+ }
877
+ retirement = new Retirement({
878
+ auth: () => this.auth,
879
+ remoteAuthority: () => this.remoteAuthority,
880
+ userMode: () => this.userMode,
881
+ workspaceRoot: () => this.workspaceRoot,
882
+ space: () => this.space,
883
+ servers: () => this.servers,
884
+ secrets: () => this.secrets,
885
+ serveIdentity: () => this.managerServeIdentity,
886
+ lifecycleUid: () => this.managerLifecycleUid,
887
+ instanceId: () => this.managerInstanceId,
888
+ serveEpoch: () => this.serviceServe?.grant.epoch,
889
+ dial: (opts) => this.dial(opts),
890
+ withRetirementSlot: (run) => this.withRetirementSlot(run),
891
+ driveStaticRetirement: (a) => this.driveStaticRetirement(a),
892
+ awaitHandleExit: (handle) => this.awaitHandleExit(handle),
893
+ shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
894
+ dropSeatRecord: (a) => this.dropSeatRecord(a),
895
+ fenceRetiringAcl: (a) => this.fenceRetiringAcl(a),
896
+ lifecycleMembershipInventory: (a) => this.lifecycleMembershipInventory(a),
897
+ brokerTeardown: (task, message) => withTimeout(task, DEPROVISION_TIMEOUT_MS, message),
898
+ trackLifecycle: () => { this.lifecycleInFlight++; return () => this.releaseLifecycle(); },
899
+ });
858
900
  leaseInfo;
859
901
  leaseRevision;
860
902
  leaseTimer;
@@ -951,6 +993,54 @@ export class Manager {
951
993
  throw e;
952
994
  }
953
995
  }
996
+ seatCustody = new SeatCustody({
997
+ staticAuth: () => !!this.auth && !this.userMode,
998
+ workspaceRoot: () => this.workspaceRoot,
999
+ space: () => this.space,
1000
+ instanceId: () => this.managerInstanceId,
1001
+ endpoint: () => this.ep,
1002
+ secrets: () => this.secrets,
1003
+ eventPayloadsWithheld: () => this.eventPayloadsWithheld,
1004
+ runtimeFor: (kind) => this.runtimeFor(kind),
1005
+ requiredRuntime: () => this.requiredRuntime,
1006
+ withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
1007
+ watchConnectorHolder: (handle, holder) => this.watchConnectorHolder(handle, holder),
1008
+ resumeEntryOf: (agent) => this.resumeEntryOf(agent),
1009
+ inventoryReferenceError: (entry) => this.inventoryReferenceError(entry),
1010
+ registerAgent: (name, agent) => { this.agents.set(name, agent); },
1011
+ agentFor: (name) => this.agents.get(name),
1012
+ watchExit: (agent) => this.watchExit(agent),
1013
+ bindOnceSeat: (agent) => this.bindOnceSeat(agent),
1014
+ renewManagedStaticCred: (agent) => this.renewManagedStaticCred(agent),
1015
+ resumeSupervisedAgent: (entry, supervised) => this.resumePreservedAgent(entry, false, false, undefined, supervised),
1016
+ });
1017
+ sessionRecovery = new SessionRecovery({
1018
+ workspaceRoot: () => this.workspaceRoot,
1019
+ execution: () => this.execution,
1020
+ executionRefusal: () => this.executionRefusal(),
1021
+ instanceId: () => this.managerInstanceId,
1022
+ endpoint: () => this.ep,
1023
+ beginLifecycle: () => this.beginLifecycle(),
1024
+ freeSlot: (agent, floor, cause) => this.freeSlot(agent, floor, cause),
1025
+ reapChildrenOf: (principal) => this.reapChildrenOf(principal),
1026
+ managedPrincipal: (agent) => this.managedPrincipal(agent),
1027
+ inlineSnapshotChange: (agent) => this.inlineSnapshotChange(agent),
1028
+ agentFor: (name) => this.agents.get(name),
1029
+ maintenanceState: () => this.maintenanceState,
1030
+ resolveConnector: (name) => this.resolveConnector(name),
1031
+ runtimeFor: (kind) => this.runtimeFor(kind),
1032
+ reserveCustody: (runtime) => this.reserveCustody(runtime),
1033
+ recordSlotCustody: (agent, reference) => this.recordSlotCustody(agent, reference),
1034
+ spawnCustodied: (runtime, name, spec, cwd, reserved) => this.spawnCustodied(runtime, name, spec, cwd, reserved),
1035
+ awaitReadiness: (agent, timeoutMs, opts) => this.awaitReadiness(agent, timeoutMs, opts),
1036
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
1037
+ recordSlotRuntime: (agent) => this.recordSlotRuntime(agent),
1038
+ refreshSeatRecord: (agent) => this.refreshSeatRecord(agent),
1039
+ watchExit: (agent) => this.watchExit(agent),
1040
+ tail: (session) => this.tail(session),
1041
+ stopHandle: (agent, graceful, cause) => this.stopHandle(agent, graceful, cause),
1042
+ trackStoppedHandle: (agent, floor, cause) => this.trackStoppedHandle(agent, floor, cause),
1043
+ });
954
1044
  constructor(opts) {
955
1045
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
956
1046
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -2328,14 +2418,7 @@ export class Manager {
2328
2418
  for (const wake of waiters)
2329
2419
  wake();
2330
2420
  }
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
- }
2421
+ trackDeprovision(a, context = "") { this.retirement.trackDeprovision(a, context); }
2339
2422
  async awaitLifecycleDrain() {
2340
2423
  if (this.lifecycleInFlight === 0)
2341
2424
  return;
@@ -4777,14 +4860,14 @@ export class Manager {
4777
4860
  if (this.userMode) {
4778
4861
  const p = parsePrincipalKey(a.id);
4779
4862
  if (p)
4780
- this.retiring.set(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: p.owner, actor: p.actor, target, startedAt: Date.now() });
4863
+ this.retirement.hold(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: p.owner, actor: p.actor, target, startedAt: Date.now() });
4781
4864
  }
4782
4865
  else if (this.auth) {
4783
4866
  // A STATIC lifecycle now also holds its name pending its own terminal (the
4784
4867
  // static retirement the detached deprovision below drives) — the alias frees only when the
4785
4868
  // gate+head terminal completes, exactly the user-mode discipline. The wire principal is the
4786
4869
  // 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() });
4870
+ this.retirement.hold(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: DEV_OWNER, actor: a.id, target, startedAt: Date.now() });
4788
4871
  }
4789
4872
  // Auth mode: tear down the departed agent's minted broker footprint + creds file (#159 B2). The
4790
4873
  // process is already gone, so this must never block the slot free or throw into the caller — it runs
@@ -4818,35 +4901,7 @@ export class Manager {
4818
4901
  teardownTarget(a) {
4819
4902
  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
4903
  }
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
- }
4904
+ deprovision(a) { return this.retirement.deprovision(a); }
4850
4905
  /** Run one retirement in a {@link RETIREMENT_CONCURRENCY} slot, oldest first: a seat's deprovision, a
4851
4906
  * chat session's terminal and a static reconcile's terminal all take one. No retirement awaits
4852
4907
  * another, so the bounded pool cannot deadlock. */
@@ -4867,357 +4922,8 @@ export class Manager {
4867
4922
  this.retirementsRunning--;
4868
4923
  }
4869
4924
  }
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
- }
4925
+ confirmRetirement(a) { this.retirement.confirmRetirement(a); }
4926
+ deprovisionBroker(a) { return this.retirement.deprovisionBroker(a); }
5221
4927
  /** Narrow the retiring lifecycle's read-ACL row to no reads ({@link fenceLifecycleAcl}) through a
5222
4928
  * `deprovisioner` credential pinned to it. Returns undefined once fenced, or the reason it was not. */
5223
4929
  async fenceRetiringAcl(a) {
@@ -5259,194 +4965,32 @@ export class Manager {
5259
4965
  this.trackStoppedHandle(child, true, cause, true);
5260
4966
  }
5261
4967
  }
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
4968
  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);
4969
+ return this.sessionRecovery.readManagedSessionState(a);
5285
4970
  }
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
4971
  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
- }
4972
+ return this.sessionRecovery.retainedSessionId(entry, connector);
5304
4973
  }
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
4974
  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 };
4975
+ return this.sessionRecovery.forkProvenance(a);
5332
4976
  }
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;
4977
+ refuseCarriedFork(a, timeoutMs) {
4978
+ return this.sessionRecovery.refuseCarriedFork(a, timeoutMs);
5351
4979
  }
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");
4980
+ refuseLateCarriedFork(a, timeoutMs) {
4981
+ return this.sessionRecovery.refuseLateCarriedFork(a, timeoutMs);
5368
4982
  }
5369
4983
  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;
4984
+ return this.sessionRecovery.readManagedSession(a);
5374
4985
  }
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
4986
  recordContinuity(a, sessionId) {
5378
- if (a.continuity)
5379
- writeContinuityAssignment(this.workspaceRoot, { ...a.continuity, sessionId });
4987
+ return this.sessionRecovery.recordContinuity(a, sessionId);
5380
4988
  }
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
4989
  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
- }
4990
+ return this.sessionRecovery.recordContinuityAtStop(a, boundary);
5392
4991
  }
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})`);
5416
- }
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})`);
4992
+ armSessionRecovery(a) {
4993
+ return this.sessionRecovery.armSessionRecovery(a);
5450
4994
  }
5451
4995
  /** Why an inline seat's snapshot no longer matches its launch, or `undefined` when it does or the
5452
4996
  * seat is not inline. The recorded path and the relaunch's path must both be this lifecycle's
@@ -5475,150 +5019,8 @@ export class Manager {
5475
5019
  }
5476
5020
  return undefined;
5477
5021
  }
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
5022
  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
- })();
5023
+ return this.sessionRecovery.recoverManagedSession(a);
5622
5024
  }
5623
5025
  /** A managed agent's process exited: on its own (crash, /exit, finished), or after a stop this
5624
5026
  * manager started, whose recorded cause then frees the slot. Continuation-capable Pi seats
@@ -5672,7 +5074,7 @@ export class Manager {
5672
5074
  for (const p of this.ep.getRoster()) {
5673
5075
  if (p.status === "offline")
5674
5076
  continue;
5675
- const predecessor = this.confirmedRetiredPredecessors.get(p.card.name);
5077
+ const predecessor = this.retirement.predecessor(p.card.name);
5676
5078
  if (predecessor !== undefined && predecessor.principal === p.card.id && predecessor.lifecycleUid === p.lifecycleUid)
5677
5079
  continue;
5678
5080
  live.add(p.card.name);
@@ -5684,7 +5086,7 @@ export class Manager {
5684
5086
  * reserves/manages/retires it OR a roster-live occupant already holds it. Pass a pre-built
5685
5087
  * {@link liveRosterNames} set when checking many names in one allocation. */
5686
5088
  nameInUse(name, live = this.liveRosterNames()) {
5687
- return this.agents.has(name) || this.reserved.has(name) || this.retiring.has(name) || live.has(name);
5089
+ return this.agents.has(name) || this.reserved.has(name) || this.retirement.hasHold(name) || live.has(name);
5688
5090
  }
5689
5091
  /** First free name in the series `base`, `base_2`, `base_3`, … — checked against live slots,
5690
5092
  * in-flight (reserved) slots, names held pending retirement, AND the live mesh roster. The
@@ -6866,7 +6268,7 @@ export class Manager {
6866
6268
  // outstanding. All the teardown ops are idempotent, and the rail request is single-flighted.
6867
6269
  if (this.reconcilingAliases.has(identityName))
6868
6270
  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);
6271
+ const held = this.retirement.held(identityName);
6870
6272
  if (held !== undefined) {
6871
6273
  hooks?.onEffect?.();
6872
6274
  void this.deprovision(held.target).catch(() => { });
@@ -7607,7 +7009,7 @@ export class Manager {
7607
7009
  // retires it, and its name stays held for retireDelegatedAgent.
7608
7010
  const p = orphan.delegated ? parsePrincipalKey(orphan.id) : null;
7609
7011
  if (p)
7610
- this.retiring.set(orphan.name, { opId: managedRetirementOpId(orphan.lifecycleUid), owner: p.owner, actor: p.actor, target: orphan, startedAt: Date.now() });
7012
+ this.retirement.hold(orphan.name, { opId: managedRetirementOpId(orphan.lifecycleUid), owner: p.owner, actor: p.actor, target: orphan, startedAt: Date.now() });
7611
7013
  this.trackDeprovision(orphan, "(orphaned spawn)");
7612
7014
  }
7613
7015
  }
@@ -7648,7 +7050,7 @@ export class Manager {
7648
7050
  // must not hide the durable teardown state the manager already owns. Refuse and re-drive the
7649
7051
  // exact held lifecycle before consulting generic principal liveness. A confirmed terminal has
7650
7052
  // already removed the hold, so fresh-lifecycle resume still reaches the fail-closed roster gate.
7651
- const held = this.retiring.get(entry.name);
7053
+ const held = this.retirement.held(entry.name);
7652
7054
  if (held) {
7653
7055
  void this.deprovision(held.target).catch(() => { });
7654
7056
  return {
@@ -7669,7 +7071,7 @@ export class Manager {
7669
7071
  if (principals.has(principal))
7670
7072
  return { ok: false, agents: [], error: `resume inventory contains duplicate principal "${principal}"` };
7671
7073
  principals.add(principal);
7672
- const confirmedPredecessor = this.confirmedRetiredPredecessors.get(entry.name);
7074
+ const confirmedPredecessor = this.retirement.predecessor(entry.name);
7673
7075
  const principalIsLive = liveRoster.some((presence) => {
7674
7076
  if (presence.card.id !== principal)
7675
7077
  return false;
@@ -8713,7 +8115,7 @@ export class Manager {
8713
8115
  return { ok: false, error: this.maintenanceError() };
8714
8116
  try {
8715
8117
  const live = this.agents.get(name);
8716
- const held = live ? undefined : this.retiring.get(name);
8118
+ const held = live ? undefined : this.retirement.held(name);
8717
8119
  const principal = live?.delegated ? parsePrincipalKey(live.id) : held?.target.delegated ? held : null;
8718
8120
  const lifecycleUid = live?.lifecycleUid ?? held?.target.lifecycleUid;
8719
8121
  if (!principal || !lifecycleUid)
@@ -8729,7 +8131,7 @@ export class Manager {
8729
8131
  }
8730
8132
  catch (e) {
8731
8133
  const error = `the delegated retirement under intent ${intentId} did not complete (${rejectionText(e)})`;
8732
- const hold = this.retiring.get(name);
8134
+ const hold = this.retirement.held(name);
8733
8135
  if (hold?.target.lifecycleUid === target.lifecycleUid)
8734
8136
  hold.lastError = error;
8735
8137
  return { ok: false, error: `${error}; "${name}" is unchanged` };
@@ -8745,7 +8147,7 @@ export class Manager {
8745
8147
  await this.shredUserSecrets(unshredded, (live ?? held?.target)?.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, target.lifecycleUid));
8746
8148
  if (unshredded.length) {
8747
8149
  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);
8150
+ const hold = this.retirement.held(name);
8749
8151
  if (hold?.target.lifecycleUid === target.lifecycleUid)
8750
8152
  hold.lastError = error;
8751
8153
  return { ok: false, error };
@@ -8931,8 +8333,8 @@ export class Manager {
8931
8333
  stopping: this.leaseStopping,
8932
8334
  lifecycleInFlight: this.lifecycleInFlight,
8933
8335
  reservedLaunches: this.reserved.size,
8934
- retirementsPending: this.retiring.size,
8935
- deprovisioningInFlight: this.deprovisioningFlight.size,
8336
+ retirementsPending: this.retirement.pendingCount,
8337
+ deprovisioningInFlight: this.retirement.inFlightCount,
8936
8338
  staticReconciliationInFlight: this.staticReconcileSweepsInFlight,
8937
8339
  agents: [...this.agents.values()]
8938
8340
  .filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter)
@@ -9017,353 +8419,8 @@ export class Manager {
9017
8419
  }
9018
8420
  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
8421
  }
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
- }
8422
+ dialServeConnection(state, readCreds = () => state.creds, deadline) { return this.servePlane.dialServeConnection(state, readCreds, deadline); }
8423
+ registerManagerService() { return this.servePlane.registerManagerService(); }
9367
8424
  /** Mint the standing `goal-writer` credential and STAGE it into this
9368
8425
  * instance's §13.1 revocation family (`epcred.<e>.<iid>`), over the passed executor's `authKv`
9369
8426
  * (the scoped `endpoint-serve-executor`, which holds the epcred write grant). The GRANT profile
@@ -9496,300 +8553,9 @@ export class Manager {
9496
8553
  this.goalWriter = undefined;
9497
8554
  await this.retireConnection(gw.nc);
9498
8555
  }
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
- }
8556
+ mintAndStageSessionLedger(authKv) { return this.servePlane.mintAndStageSessionLedger(authKv); }
8557
+ startSessionPlane() { return this.servePlane.startSessionPlane(); }
8558
+ stopSessionPlane() { return this.servePlane.stopSessionPlane(); }
9793
8559
  /** The boot reconcile: a fresh incarnation (a manager restart takes a NEW
9794
8560
  * instanceId, so the in-memory acceptance map starts empty) inherits the endpoint's accepted-but-
9795
8561
  * unterminal goals from any predecessor. The local signer enumerates with an ephemeral PROVISIONER.
@@ -11282,87 +10048,17 @@ export class Manager {
11282
10048
  // the goal already terminalized (the readiness outcome won the settle race) - nothing to cancel.
11283
10049
  }
11284
10050
  }
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
- }
10051
+ recordSlotRuntime(a) {
10052
+ return this.seatCustody.recordSlotRuntime(a);
10053
+ }
10054
+ recordSlotCustody(a, runtime) {
10055
+ return this.seatCustody.recordSlotCustody(a, runtime);
11315
10056
  }
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
10057
  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}`);
10058
+ return this.seatCustody.reserveCustody(runtime);
10059
+ }
10060
+ spawnCustodied(runtime, name, spec, cwd, reserved) {
10061
+ return this.seatCustody.spawnCustodied(runtime, name, spec, cwd, reserved);
11366
10062
  }
11367
10063
  /** Keep launch provenance independent of status and runtime wire contracts. */
11368
10064
  watchConnectorHolder(handle, holder) {
@@ -11373,48 +10069,14 @@ export class Manager {
11373
10069
  // identity-less holders, never a release or a failed stop request.
11374
10070
  watchProvedExit(handle, () => holder.ended(), () => true);
11375
10071
  }
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
10072
  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 });
10073
+ return this.seatCustody.recordSeat(a);
11397
10074
  }
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
10075
  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
- }
10076
+ return this.seatCustody.refreshSeatRecord(a);
11409
10077
  }
11410
10078
  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
- }
10079
+ return this.seatCustody.dropSeatRecord(a);
11418
10080
  }
11419
10081
  /** True when a default stop wrote a runtime reference for this exact lifecycle and it is still
11420
10082
  * there. That file is what a later manager adopts, so a slot free must not remove it before the
@@ -11427,185 +10089,17 @@ export class Manager {
11427
10089
  return false;
11428
10090
  }
11429
10091
  }
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
10092
  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;
10093
+ return this.seatCustody.seatRecordFor(row);
11460
10094
  }
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;
10095
+ adoptSeat(row, record) {
10096
+ return this.seatCustody.adoptSeat(row, record);
11542
10097
  }
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}`);
10098
+ restartSupervisedSeat(row, record) {
10099
+ return this.seatCustody.restartSupervisedSeat(row, record);
10100
+ }
10101
+ reapOrphanSeat(a) {
10102
+ return this.seatCustody.reapOrphanSeat(a);
11609
10103
  }
11610
10104
  /** The static terminal for one departed incarnation: delegates the gate/head CAS
11611
10105
  * sequence to the shared core saga over the executor transport; the footprint teardown (creds
@@ -11688,16 +10182,10 @@ export class Manager {
11688
10182
  managerInstance: this.managerInstanceId, managerProcessUid: this.managerLifecycleUid,
11689
10183
  }, { cleanup: reapThenCleanup, evict, log: (line) => console.error(`static retirement ${a.name}: ${line}`) });
11690
10184
  });
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
- }
10185
+ this.retirement.recordStaticRetirement(a);
11698
10186
  }
11699
10187
  catch (e) {
11700
- const h = this.retiring.get(a.name);
10188
+ const h = this.retirement.held(a.name);
11701
10189
  if (h && h.target.lifecycleUid === a.lifecycleUid)
11702
10190
  h.lastError = `the static retirement did not complete (${rejectionText(e)}); the name stays held - a same-name spawn retries the same terminal (op ${opId})`;
11703
10191
  console.error(`static retirement ${a.name} (${a.id}): ${rejectionText(e)}`);
@@ -12297,7 +10785,7 @@ export class Manager {
12297
10785
  // A retirement is a GLOBAL refusal fact — seed the retired-principal index for EVERY retired incarnation
12298
10786
  // regardless of which instance owned it, so a sibling-retired incarnation's copied credential
12299
10787
  // is refused at this control surface too. Ownership gates only the DESTRUCTIVE sweep below.
12300
- this.retiredPrincipals.add(principalKey(row.owner, row.actor).key);
10788
+ this.retirement.rememberRetired(principalKey(row.owner, row.actor).key);
12301
10789
  retiredSlots++;
12302
10790
  continue;
12303
10791
  }
@@ -12465,14 +10953,7 @@ export class Manager {
12465
10953
  ? `the caller's lifecycle ${a.lifecycleUid} is terminalizing; control is refused from the first terminal step`
12466
10954
  : undefined;
12467
10955
  }
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;
10956
+ return this.retirement.membershipRefusal(caller);
12476
10957
  }
12477
10958
  /** Open a short-lived PROVISIONER connection, run the onboarding ops on it, and drain it (closure (ii),
12478
10959
  * residual 2). The DM/DLV consumer-create surface — the irreducible onboarding power — lives only for