import * as plugins from './plugins.js'; import { ControllerCodexCreationStore, type ICodexCreationScope, type IBeginCodexCreationInput } from './classes.codexcreationstore.js'; import type { ICodexCreationRuntime, IControllerCodexCreationDocument } from './classes.codexcreationmodels.js'; import { codexSessionProviderGeneration } from './classes.sessionidentityintegration.js'; import { controllerRuntimeIdKey, type TControllerSessionId, } from '../ts_interfaces/index.js'; import { assertControllerRuntimeId } from './classes.validation.js'; import type { IControllerSessionIdentity, IControllerSessionRuntimeBinding, } from './interfaces.identity.js'; import { ControllerSessionIdentityModel, ControllerSessionLocatorModel, ControllerSessionRuntimeBindingModel, controllerSessionIdentityDocumentId, controllerSessionLocatorDocumentId, type IControllerSessionDeletionRecord, type IControllerSessionIdentityDocument, type IControllerSessionLocatorDocument, type IControllerSessionPendingBinding, type IControllerSessionRuntimeBindingDocument, type TControllerSessionLocatorState, } from './classes.sessionidentitymodels.js'; import { ControllerSessionParentRelationshipModel, controllerSessionParentRelationshipDocumentId, type IControllerSessionParentRelationshipDocument, } from './classes.sessionrelationshipmodels.js'; import { ControllerManagedSessionModel, ControllerSessionCreationObligationModel, assertControllerFlexCleanupCohort, assertControllerFlexSessionGeneration, assertControllerFlexSessionGenerationId, cloneControllerFlexCleanupCohort, controllerFlexCleanupCohortsEqual, controllerFlexCleanupCohortLimit, controllerManagedSessionDocumentId, controllerSessionCreationObligationDocumentId, type IControllerFlexCleanupEntry, type IControllerManagedSessionDeletion, type IControllerManagedSessionDocument, type IControllerSessionCreationObligationDocument, type TControllerManagedSessionAdmissionSource, type TControllerManagedSessionState, type TControllerSessionCreationObligationState, } from './classes.managedsessionmodels.js'; const maximumReconciliationAttempts = 24; const base64UrlPattern = /^[A-Za-z0-9_-]+$/; // Mature OpenCode projects can contain thousands of child sessions. Keep the // complete snapshot bounded while preserving 2:1 headroom for replacements. export const controllerSessionIdentitySnapshotEntryLimit = 65_536; export const controllerSessionIdentityScopedLocatorLimit = 131_072; const controllerSessionIdentityLocatorPageEntryLimit = 1_024; export const controllerManagedSessionRecoveryEntryLimit = 65_536; export const controllerManagedSessionRecoveryPageEntryLimit = 1_024; const snapshotLocatorStates: TControllerSessionLocatorState[] = [ 'initializing', 'binding', 'attached', 'detaching', 'deleting', 'completing', ]; type TControllerSessionHarnessId = TControllerSessionId['harnessId']; type TStoredIdentity = NonNullable>>; type TStoredBinding = NonNullable>>; type TStoredLocator = NonNullable>>; type TStoredParentRelationship = NonNullable>>; type TStoredManagedSession = NonNullable>>; type TStoredSessionCreationObligation = NonNullable>>; export type TControllerSessionIdentityErrorCode = | 'invalid_input' | 'not_found' | 'concurrent_change' | 'provider_generation_mismatch' | 'deleting' | 'tombstoned' | 'limit_exceeded' | 'corrupt_state' | 'closed'; export class ControllerSessionIdentityError extends Error { constructor( public readonly code: TControllerSessionIdentityErrorCode, messageArg: string, optionsArg?: ErrorOptions, ) { super(messageArg, optionsArg); this.name = 'ControllerSessionIdentityError'; } } export interface IObserveControllerSessionIdentityInput { projectIdentityId: string; runtimeId: TControllerSessionId; supervisorGeneration: string; providerSessionGeneration?: string; sessionGenerationId?: string; sessionGenerationSequence?: number; observedAt?: Date; signal?: AbortSignal; } export interface IControllerSessionIdentityObservation { identity: IControllerSessionIdentity; binding: IControllerSessionRuntimeBinding; } export interface IAdmitControllerManagedSessionInput extends IObserveControllerSessionIdentityInput { admissionSource: TControllerManagedSessionAdmissionSource; codexOrigin?: IControllerCodexOrigin; } export interface IRequireControllerManagedSessionInput { projectIdentityId: string; runtimeId: TControllerSessionId; supervisorGeneration: string; /** When present, the provider generation must match exactly. */ providerSessionGeneration?: string; } export interface IResolveRetiredManagedSessionIdentityInput { projectIdentityId: string; runtimeId: TControllerSessionId; sessionIdentityId: string; signal?: AbortSignal; } export interface IControllerSessionManagedObservation extends IControllerSessionIdentityObservation { managedAt: number; admissionSource: TControllerManagedSessionAdmissionSource; } export interface IBeginControllerManagedSessionDeletionInput { projectIdentityId: string; runtimeId: TControllerSessionId; supervisorGeneration: string; providerSessionGeneration?: string; flexCleanupCohort?: readonly unknown[]; operationId: string; startedAt: Date; } export interface IMarkControllerManagedSessionDeletionDispatchedInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; dispatchStartedAt: Date; } export interface ICancelControllerManagedSessionDeletionInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; cancelledAt: Date; } export interface ICompleteControllerManagedSessionDeletionInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; retiredAt: Date; } export interface IListControllerManagedSessionDeletionObligationsInput { projectIdentityId: string; harnessId?: TControllerSessionHarnessId; signal?: AbortSignal; } export interface IRetireControllerProjectManagedSessionsInput { projectIdentityId: string; retiredAt: Date; signal?: AbortSignal; } export interface IControllerManagedSessionDeletionObligation { id: string; issuerId: string; projectIdentityId: string; runtimeId: TControllerSessionId; sessionIdentityId: string; managedAt: number; admissionSource: TControllerManagedSessionAdmissionSource; operationId: string; expectedBindingId: string; supervisorGeneration: string; providerSessionGeneration: string; flexCleanupCohort?: IControllerFlexCleanupEntry[]; startedAt: number; dispatchStartedAt?: number; } export interface IBeginControllerManagedSessionCreationInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; requestedAt: Date; expectedFlexSessionGenerationId?: string; } export interface IMarkControllerManagedSessionCreationDispatchedInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; dispatchStartedAt: Date; } export interface ICompleteControllerManagedSessionCreationAdmissionInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; supervisorGeneration: string; providerSessionGeneration: string; sessionGenerationId?: string; sessionGenerationSequence?: number; terminalAt: Date; signal?: AbortSignal; } export interface IRetireControllerManagedSessionCreationInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; terminalAt: Date; } export interface IListControllerSessionCreationObligationsInput { projectIdentityId: string; harnessId?: TControllerSessionHarnessId; signal?: AbortSignal; } export interface IGetControllerSessionCreationObligationInput { projectIdentityId: string; runtimeId: TControllerSessionId; } export interface IControllerSessionCreationObligation { id: string; issuerId: string; projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; state: TControllerSessionCreationObligationState; requestedAt: number; dispatchStartedAt?: number; expectedFlexSessionGenerationId?: string; providerSessionGeneration?: string; sessionIdentityId?: string; terminalAt?: number; } export interface IControllerSessionSnapshotEntry { nativeId: string; providerSessionGeneration: string; sessionGenerationId?: string; sessionGenerationSequence?: number; parentNativeId?: string; } export type TControllerFlexHostSessionAuthority = | 'active' | 'pending_creation_load' | 'deleting_cleanup' | 'project_removal_cleanup' | 'definitively_unmanaged' | 'uncertain'; export interface IResolveControllerFlexHostSessionAuthorityInput { projectIdentityId: string; runtimeId: TControllerSessionId & { harnessId: 'flex' }; providerSessionGeneration: string; signal?: AbortSignal; } export type TControllerPendingFlexProjectManagementLoadAuthority = | Extract | 'definitively_unmanaged'; export interface IResolveControllerPendingFlexProjectManagementLoadAuthorityInput { projectIdentityId: string; runtimeId: TControllerSessionId & { harnessId: 'flex' }; expectedFlexSessionGenerationId: string; signal?: AbortSignal; } export type TControllerFlexProjectManagementRegistrationLoadAuthority = | 'active_load' | 'pending_creation_empty_load' | 'historical_unmanaged_empty_load'; export interface IResolveControllerFlexProjectManagementRegistrationLoadAuthorityInput { projectIdentityId: string; runtimeId: TControllerSessionId & { harnessId: 'flex' }; providerSessionGeneration: string; expectedFlexSessionGenerationId: string; signal?: AbortSignal; } export type TControllerSessionLayoutAuthority = 'managed' | 'definitively_unmanaged'; export interface IResolveControllerSessionLayoutAuthorityInput { projectIdentityId: string; runtimeId: TControllerSessionId; signal?: AbortSignal; } export interface IListControllerFlexManagedCleanupRootsInput { projectIdentityId: string; signal?: AbortSignal; } export interface IReconcileControllerSessionSnapshotInput { projectIdentityId: string; harnessId: TControllerSessionHarnessId; supervisorGeneration: string; sourceAdmissionFenced: true; snapshotComplete: true; managedMembershipsOnly?: true; sessions: readonly IControllerSessionSnapshotEntry[]; observedAt?: Date; signal?: AbortSignal; } export interface IControllerSessionSnapshotObservation { runtimeId: TControllerSessionId; identity: IControllerSessionIdentity; binding: IControllerSessionRuntimeBinding; managed: boolean; } export interface IControllerSessionPendingDeletion { runtimeId: TControllerSessionId; operationId: string; expectedBindingId: string; state: 'deleting' | 'completing'; startedAt: number; } export interface IReconciledControllerSessionSnapshot { status: 'reconciled'; observations: IControllerSessionSnapshotObservation[]; detachedBindings: IControllerSessionRuntimeBinding[]; } export interface IBlockedControllerSessionSnapshot { status: 'blocked_by_deletion'; observations: []; detachedBindings: []; pendingDeletions: IControllerSessionPendingDeletion[]; } export type TControllerSessionSnapshotResult = | IReconciledControllerSessionSnapshot | IBlockedControllerSessionSnapshot; export interface IDetachControllerSessionIdentityInput { projectIdentityId: string; runtimeId: TControllerSessionId; expectedBindingId: string; detachedAt?: Date; } export interface IBeginControllerSessionDeletionInput { projectIdentityId: string; runtimeId: TControllerSessionId; expectedBindingId: string; operationId: string; startedAt?: Date; } export interface ICancelControllerSessionDeletionInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; cancelledAt?: Date; } export interface ICompleteControllerSessionDeletionInput { projectIdentityId: string; runtimeId: TControllerSessionId; operationId: string; completedAt?: Date; } interface IResolvedLocatorInput { projectIdentityId: string; runtimeId: TControllerSessionId; locatorId: string; scopeKey: string; } interface IResolvedSnapshotScope { projectIdentityId: string; harnessId: TControllerSessionHarnessId; scopeKey: string; } interface IInsertedLocator { stored: TStoredLocator; adoptedCompetingWinner: boolean; } interface ISettledLocator { stored: TStoredLocator; competingGeneration: boolean; } interface IResolvedSnapshotSession { runtimeId: TControllerSessionId; providerSessionGeneration: string; parentNativeId?: string; } type TManagedSessionLookupResult = | { status: 'managed'; observation: IControllerSessionManagedObservation; } | { status: 'not_found' | 'supervisor_generation_mismatch' | 'provider_generation_mismatch'; }; const randomId = (bytesArg: number): string => plugins.crypto .randomBytes(bytesArg) .toString('base64url'); const isPlainObject = (valueArg: unknown): valueArg is Record => ( typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg) && ( Object.getPrototypeOf(valueArg) === Object.prototype || Object.getPrototypeOf(valueArg) === null ) ); const hasExactKeys = ( valueArg: Record, requiredKeysArg: readonly string[], optionalKeysArg: readonly string[] = [], ): boolean => { const keys = Object.keys(valueArg); return requiredKeysArg.every((key) => Object.hasOwn(valueArg, key)) && keys.every((key) => requiredKeysArg.includes(key) || optionalKeysArg.includes(key)); }; const isBase64UrlBytes = (valueArg: unknown, byteLengthArg: number): valueArg is string => ( typeof valueArg === 'string' && base64UrlPattern.test(valueArg) && Buffer.from(valueArg, 'base64url').byteLength === byteLengthArg && Buffer.from(valueArg, 'base64url').toString('base64url') === valueArg ); const requireDate = (valueArg: Date | undefined, labelArg: string): Date => { const value = valueArg === undefined ? new Date() : new Date(valueArg); if (!Number.isFinite(value.getTime()) || value.getTime() < 0) { throw new ControllerSessionIdentityError('invalid_input', `${labelArg} must be a valid date.`); } return value; }; const requireRuntimeId = (valueArg: TControllerSessionId): TControllerSessionId => { try { return assertControllerRuntimeId( valueArg, 'Session runtime ID', ['opencode', 'flex', 'codex'], ) as TControllerSessionId; } catch (errorArg) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session runtime ID is invalid.', { cause: errorArg }, ); } }; const requireProviderGeneration = (valueArg: unknown): string | undefined => { if (valueArg === undefined) return undefined; if ( typeof valueArg !== 'string' || valueArg.length === 0 || Buffer.byteLength(valueArg, 'utf8') > 512 || /[\u0000-\u001f\u007f]/u.test(valueArg) ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Provider session generation is invalid.', ); } return valueArg; }; interface IManagedSessionGenerationFacts { codexOrigin?: IControllerCodexOrigin; providerSessionGeneration: string; sessionGenerationId?: string; sessionGenerationSequence?: number; } const requireManagedSessionGenerationFacts = ( runtimeIdArg: TControllerSessionId, providerSessionGenerationArg: unknown, sessionGenerationIdArg: unknown, sessionGenerationSequenceArg: unknown, ): IManagedSessionGenerationFacts => { const providerSessionGeneration = requireProviderGeneration(providerSessionGenerationArg); if (providerSessionGeneration === undefined) { throw new ControllerSessionIdentityError( 'invalid_input', 'Managed session admission requires a provider generation.', ); } if (runtimeIdArg.harnessId === 'flex') { try { assertControllerFlexSessionGeneration( sessionGenerationIdArg, sessionGenerationSequenceArg, providerSessionGeneration, ); } catch (errorArg) { throw new ControllerSessionIdentityError( 'invalid_input', 'Managed Flex session admission requires exact canonical generation facts.', { cause: errorArg }, ); } return { providerSessionGeneration, sessionGenerationId: sessionGenerationIdArg as string, sessionGenerationSequence: sessionGenerationSequenceArg as number, }; } if (sessionGenerationIdArg !== undefined || sessionGenerationSequenceArg !== undefined) { throw new ControllerSessionIdentityError( 'invalid_input', 'Managed OpenCode session admission cannot carry Flex generation facts.', ); } return { providerSessionGeneration }; }; const runtimeIdsEqual = ( leftArg: TControllerSessionId, rightArg: TControllerSessionId, ): boolean => leftArg.harnessId === rightArg.harnessId && leftArg.nativeId === rightArg.nativeId; const compareCodeUnits = (leftArg: string, rightArg: string): number => ( leftArg < rightArg ? -1 : leftArg > rightArg ? 1 : 0 ); const compareRuntimeIds = ( leftArg: TControllerSessionId, rightArg: TControllerSessionId, ): number => compareCodeUnits(leftArg.harnessId, rightArg.harnessId) || compareCodeUnits(leftArg.nativeId, rightArg.nativeId); const compareDocumentIds = (leftArg: string, rightArg: string): number => ( leftArg < rightArg ? -1 : leftArg > rightArg ? 1 : 0 ); const datesEqual = (leftArg: Date, rightArg: Date): boolean => ( leftArg.getTime() === rightArg.getTime() ); const providerGenerationsEqual = ( leftArg: string | undefined, rightArg: string | undefined, ): boolean => leftArg === rightArg; const managedDeletionFactsEqual = ( leftArg: IControllerManagedSessionDeletion, rightArg: IControllerManagedSessionDeletion, ): boolean => leftArg.operationId === rightArg.operationId && leftArg.expectedBindingId === rightArg.expectedBindingId && leftArg.supervisorGeneration === rightArg.supervisorGeneration && providerGenerationsEqual( leftArg.providerSessionGeneration, rightArg.providerSessionGeneration, ) && (leftArg.flexCleanupCohort === undefined ? rightArg.flexCleanupCohort === undefined : rightArg.flexCleanupCohort !== undefined && controllerFlexCleanupCohortsEqual( leftArg.flexCleanupCohort, rightArg.flexCleanupCohort, )) && datesEqual(leftArg.startedAt, rightArg.startedAt) && ( leftArg.dispatchStartedAt === undefined ? rightArg.dispatchStartedAt === undefined : rightArg.dispatchStartedAt !== undefined && datesEqual(leftArg.dispatchStartedAt, rightArg.dispatchStartedAt) ); export const buildControllerFlexCleanupCohort = ( sessionsArg: readonly IControllerSessionSnapshotEntry[], targetRootsArg: readonly IControllerFlexCleanupEntry[], ): IControllerFlexCleanupEntry[] => { if (!Array.isArray(sessionsArg) || sessionsArg.length > controllerFlexCleanupCohortLimit) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The complete Flex cleanup snapshot exceeds its entry limit.', ); } if (!Array.isArray(targetRootsArg) || targetRootsArg.length > controllerFlexCleanupCohortLimit) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The Flex cleanup target-root set exceeds its entry limit.', ); } const sessionsById = new Map(); for (const entry of sessionsArg) { if (!isPlainObject(entry) || !hasExactKeys( entry, [ 'nativeId', 'sessionGenerationId', 'sessionGenerationSequence', 'providerSessionGeneration', ], ['parentNativeId'], ) || typeof entry.nativeId !== 'string' || typeof entry.sessionGenerationId !== 'string' || typeof entry.sessionGenerationSequence !== 'number' || typeof entry.providerSessionGeneration !== 'string' || ( entry.parentNativeId !== undefined && typeof entry.parentNativeId !== 'string' )) { throw new ControllerSessionIdentityError( 'invalid_input', 'Flex cleanup snapshot entries must use the exact canonical shape.', ); } const nativeId = requireRuntimeId({ harnessId: 'flex', nativeId: entry.nativeId }).nativeId; const providerSessionGeneration = requireProviderGeneration(entry.providerSessionGeneration); if (providerSessionGeneration === undefined) { throw new ControllerSessionIdentityError( 'invalid_input', 'Flex cleanup snapshot entries require a provider generation.', ); } try { assertControllerFlexSessionGeneration( entry.sessionGenerationId, entry.sessionGenerationSequence, providerSessionGeneration, ); } catch (errorArg) { throw new ControllerSessionIdentityError( 'invalid_input', 'Flex cleanup snapshot entries require canonical raw generation facts.', { cause: errorArg }, ); } if (sessionsById.has(nativeId)) { throw new ControllerSessionIdentityError( 'invalid_input', 'The complete Flex cleanup snapshot contains a duplicate session ID.', ); } const parentNativeId = entry.parentNativeId === undefined ? undefined : requireRuntimeId({ harnessId: 'flex', nativeId: entry.parentNativeId }).nativeId; sessionsById.set(nativeId, { nativeId, sessionGenerationId: entry.sessionGenerationId, sessionGenerationSequence: entry.sessionGenerationSequence, providerSessionGeneration, ...(parentNativeId === undefined ? {} : { parentNativeId }), }); } for (const entry of sessionsById.values()) { if (entry.parentNativeId !== undefined && !sessionsById.has(entry.parentNativeId)) { throw new ControllerSessionIdentityError( 'invalid_input', 'The complete Flex cleanup snapshot contains a missing parent.', ); } } const rootsById = new Map(); const visiting = new Set(); const resolveRoot = (sessionIdArg: string): string => { const known = rootsById.get(sessionIdArg); if (known !== undefined) return known; if (visiting.has(sessionIdArg)) { throw new ControllerSessionIdentityError( 'invalid_input', 'The complete Flex cleanup snapshot contains a parent cycle.', ); } visiting.add(sessionIdArg); const entry = sessionsById.get(sessionIdArg)!; const root = entry.parentNativeId === undefined ? sessionIdArg : resolveRoot(entry.parentNativeId); visiting.delete(sessionIdArg); rootsById.set(sessionIdArg, root); return root; }; for (const sessionId of sessionsById.keys()) resolveRoot(sessionId); const targetRootIds = new Set(); try { assertControllerFlexCleanupCohort(targetRootsArg); } catch (errorArg) { throw new ControllerSessionIdentityError( 'invalid_input', 'Flex cleanup target roots must use the exact canonical shape.', { cause: errorArg }, ); } for (const target of targetRootsArg) { if (!target.cleanupRoot) { throw new ControllerSessionIdentityError( 'invalid_input', 'Flex cleanup targets must be marked as roots.', ); } const sessionId = requireRuntimeId({ harnessId: 'flex', nativeId: target.sessionId }).nativeId; const providerSessionGeneration = requireProviderGeneration(target.providerSessionGeneration); const entry = sessionsById.get(sessionId); if ( providerSessionGeneration === undefined || !entry || entry.parentNativeId !== undefined || entry.sessionGenerationId !== target.sessionGenerationId || entry.sessionGenerationSequence !== target.sessionGenerationSequence || entry.providerSessionGeneration !== providerSessionGeneration || targetRootIds.has(sessionId) ) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'A Flex cleanup target is not an exact current snapshot root.', ); } targetRootIds.add(sessionId); } const cohort = [...sessionsById.values()] .filter((entry) => targetRootIds.has(rootsById.get(entry.nativeId)!)) .map((entry) => ({ sessionId: entry.nativeId, sessionGenerationId: entry.sessionGenerationId!, sessionGenerationSequence: entry.sessionGenerationSequence!, providerSessionGeneration: entry.providerSessionGeneration, cleanupRoot: targetRootIds.has(entry.nativeId), })) .sort((left, right) => compareCodeUnits(left.sessionId, right.sessionId)); assertControllerFlexCleanupCohort(cohort); return cohort; }; const isAmbiguousWrite = (errorArg: unknown): boolean => ( errorArg instanceof plugins.smartdata.SmartdataExactPersistenceError && errorArg.code === 'ambiguous_write' ); const assertSnapshotParentGraph = (sessionsArg: readonly IResolvedSnapshotSession[]): void => { const parentByChild = new Map(); for (const session of sessionsArg) { if (session.parentNativeId === undefined) continue; const childNativeId = session.runtimeId.nativeId; if (session.parentNativeId === childNativeId) { throw new ControllerSessionIdentityError( 'invalid_input', 'A session snapshot cannot declare itself as its parent.', ); } parentByChild.set(childNativeId, session.parentNativeId); } const visited = new Set(); const visiting = new Set(); const visit = (nativeIdArg: string): void => { if (visited.has(nativeIdArg)) return; if (visiting.has(nativeIdArg)) { throw new ControllerSessionIdentityError( 'invalid_input', 'The session snapshot parent graph contains a cycle.', ); } visiting.add(nativeIdArg); const parentNativeId = parentByChild.get(nativeIdArg); if (parentNativeId !== undefined && parentByChild.has(parentNativeId)) { visit(parentNativeId); } visiting.delete(nativeIdArg); visited.add(nativeIdArg); }; for (const nativeId of parentByChild.keys()) visit(nativeId); }; const publicIdentity = ( documentArg: IControllerSessionIdentityDocument, ): IControllerSessionIdentity => ({ issuerId: documentArg.issuerId, sessionIdentityId: documentArg.sessionIdentityId, projectIdentityId: documentArg.projectIdentityId, createdAt: documentArg.createdAt.getTime(), ...(documentArg.retiredAt === undefined ? {} : { retiredAt: documentArg.retiredAt.getTime() }), }); const publicBinding = ( documentArg: IControllerSessionRuntimeBindingDocument, ): IControllerSessionRuntimeBinding => ({ bindingId: documentArg.bindingId, issuerId: documentArg.issuerId, sessionIdentityId: documentArg.sessionIdentityId, projectIdentityId: documentArg.projectIdentityId, runtimeId: { ...documentArg.runtimeId }, supervisorGeneration: documentArg.supervisorGeneration, ...(documentArg.providerSessionGeneration === undefined ? {} : { providerSessionGeneration: documentArg.providerSessionGeneration }), attachedAt: documentArg.attachedAt.getTime(), ...(documentArg.detachedAt === undefined ? {} : { detachedAt: documentArg.detachedAt.getTime() }), }); const publicManagedObservation = ( observationArg: IControllerSessionIdentityObservation, membershipArg: IControllerManagedSessionDocument, ): IControllerSessionManagedObservation => ({ ...observationArg, managedAt: membershipArg.managedAt.getTime(), admissionSource: membershipArg.admissionSource, }); const publicManagedDeletionObligation = ( membershipArg: IControllerManagedSessionDocument, deletionArg: IControllerManagedSessionDeletion, ): IControllerManagedSessionDeletionObligation => ({ id: membershipArg.id, issuerId: membershipArg.issuerId, projectIdentityId: membershipArg.projectIdentityId, runtimeId: { ...membershipArg.runtimeId }, sessionIdentityId: membershipArg.sessionIdentityId, managedAt: membershipArg.managedAt.getTime(), admissionSource: membershipArg.admissionSource, operationId: deletionArg.operationId, expectedBindingId: deletionArg.expectedBindingId, supervisorGeneration: deletionArg.supervisorGeneration, providerSessionGeneration: deletionArg.providerSessionGeneration, ...(deletionArg.flexCleanupCohort === undefined ? {} : { flexCleanupCohort: cloneControllerFlexCleanupCohort(deletionArg.flexCleanupCohort) }), startedAt: deletionArg.startedAt.getTime(), ...(deletionArg.dispatchStartedAt === undefined ? {} : { dispatchStartedAt: deletionArg.dispatchStartedAt.getTime() }), }); const publicCreationObligation = ( obligationArg: IControllerSessionCreationObligationDocument, ): IControllerSessionCreationObligation => ({ id: obligationArg.id, issuerId: obligationArg.issuerId, projectIdentityId: obligationArg.projectIdentityId, runtimeId: { ...obligationArg.runtimeId }, operationId: obligationArg.operationId, state: obligationArg.state, requestedAt: obligationArg.requestedAt.getTime(), ...(obligationArg.dispatchStartedAt === undefined ? {} : { dispatchStartedAt: obligationArg.dispatchStartedAt.getTime() }), ...(obligationArg.expectedFlexSessionGenerationId === undefined ? {} : { expectedFlexSessionGenerationId: obligationArg.expectedFlexSessionGenerationId }), ...(obligationArg.providerSessionGeneration === undefined ? {} : { providerSessionGeneration: obligationArg.providerSessionGeneration }), ...(obligationArg.sessionIdentityId === undefined ? {} : { sessionIdentityId: obligationArg.sessionIdentityId }), ...(obligationArg.terminalAt === undefined ? {} : { terminalAt: obligationArg.terminalAt.getTime() }), }); export class ControllerSessionIdentityService { private closeStarted = false; private readonly activeOperations = new Set>(); private readonly scopeMutationTails = new Map>(); private readonly codexCreations: ControllerCodexCreationStore; constructor(private readonly issuerId: string) { if (!isBase64UrlBytes(issuerId, 32)) { throw new Error('Controller session identity service issuer is invalid.'); } this.codexCreations = new ControllerCodexCreationStore(issuerId); } public beginCodexCreation(inputArg: IBeginCodexCreationInput): Promise { return this.runOperation(() => this.codexCreations.begin(inputArg)); } public listCodexMemberships(projectIdArg: string, signalArg?: AbortSignal): Promise { this.resolveLocatorInput(projectIdArg, { harnessId: 'codex', nativeId: 'membership-read' }); return this.runOperation(async () => (await this.readManagedSessionStatePages(projectIdArg, 'codex', ['active', 'deleting'], signalArg)) .map(entry => structuredClone(ControllerManagedSessionModel.exact.toPersisted(entry)))); } public async codexOrigin(projectIdArg: string, nativeIdArg: string, signalArg?: AbortSignal): Promise { const input = this.resolveLocatorInput(projectIdArg, { harnessId: 'codex', nativeId: nativeIdArg }); return this.runScopedOperation(input.scopeKey, async () => { const records = await ControllerManagedSessionModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: projectIdArg, harnessId: 'codex', runtimeId: input.runtimeId, state: { $in: ['active', 'deleting'] }, }, limit: 2, signal: signalArg }); if (records.length !== 1) throw new Error('Codex conversation has no unique managed origin.'); const membership = ControllerManagedSessionModel.exact.toPersisted(records[0]!); if (!membership.codexOrigin) throw new Error('Codex conversation origin migration is incomplete.'); return structuredClone(membership.codexOrigin); }); } /** Rebind a provider-observed Codex thread without enrolling any unowned thread. */ public observeManagedCodexSession(inputArg: IObserveControllerSessionIdentityInput): Promise { if (inputArg.runtimeId.harnessId !== 'codex' || !isBase64UrlBytes(inputArg.supervisorGeneration, 32)) { return Promise.reject(new Error('Invalid managed Codex observation.')); } const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); const generation = requireProviderGeneration(inputArg.providerSessionGeneration); const observedAt = requireDate(inputArg.observedAt, 'Codex observation time'); return this.runScopedOperation(input.scopeKey, async () => { inputArg.signal?.throwIfAborted(); let stored = await this.readLocator(input.locatorId, inputArg.signal); if (!stored) return undefined; stored = (await this.settleCoordinator(stored)).stored; const locator = ControllerSessionLocatorModel.exact.toPersisted(stored); this.assertLocatorScope(locator, input); this.assertProviderGeneration(locator, generation); if (locator.state === 'tombstoned') return undefined; const membership = await this.requireManagedMembershipForLocator(input, locator); if (membership.body.state === 'retired') return undefined; if (membership.body.state !== 'active' || locator.state === 'deleting' || locator.state === 'completing') { throw new ControllerSessionIdentityError('deleting', 'Codex session deletion is pending.'); } await this.observeSessionInScope(input, inputArg.supervisorGeneration, generation, observedAt, false, inputArg.signal); return this.managedObservationFromLookupResult(await this.resolveManagedSessionInScope(input, inputArg.supervisorGeneration, generation)); }); } public getCodexCreation(scopeArg: ICodexCreationScope): Promise { return this.runOperation(() => this.codexCreations.get(scopeArg)); } public listCodexCreations(projectIdArg: string, signalArg?: AbortSignal): Promise { return this.runOperation(() => this.codexCreations.listOutstanding(projectIdArg, signalArg)); } public dispatchCodexCreation(scopeArg: ICodexCreationScope, runtimeArg: ICodexCreationRuntime): Promise { return this.runOperation(() => this.codexCreations.dispatch(scopeArg, runtimeArg)); } public bindCodexCreation(scopeArg: ICodexCreationScope, generationArg: string, nativeIdArg: string, createdAtArg: number): Promise { return this.runOperation(() => this.codexCreations.bind(scopeArg, generationArg, nativeIdArg, createdAtArg)); } public async admitCodexCreation(scopeArg: ICodexCreationScope, supervisorGenerationArg: string): Promise { if (!isBase64UrlBytes(supervisorGenerationArg, 32)) throw new Error('Invalid Codex supervisor generation.'); const creation = await this.getCodexCreation(scopeArg); if (!['bound', 'admitted'].includes(creation.state) || creation.nativeId === undefined || creation.providerCreatedAt === undefined) { throw new Error('Codex creation has no bound provider identity.'); } const input = this.resolveLocatorInput(scopeArg.projectIdentityId, { harnessId: 'codex', nativeId: creation.nativeId }); const providerSessionGeneration = codexSessionProviderGeneration(creation.nativeId, creation.providerCreatedAt); return this.runScopedOperation(input.scopeKey, async () => { const observedAt = new Date(); const observation = await this.observeSessionInScope(input, supervisorGenerationArg, providerSessionGeneration, observedAt, false); const managed = await this.admitManagedMembershipInScope(input, observation, { providerSessionGeneration, ...(creation.codexOrigin ? { codexOrigin: creation.codexOrigin } : {}) }, 'controller-created', observedAt); await this.codexCreations.admit(scopeArg, managed.identity.sessionIdentityId); return managed; }); } public findUnmaterializedCodexCreation(projectIdArg: string, nativeIdArg: string): Promise { return this.runOperation(() => this.codexCreations.findUnmaterialized(projectIdArg, nativeIdArg)); } public finalizeCodexCreationMetadata(scopeArg: ICodexCreationScope): Promise { return this.runOperation(() => this.codexCreations.finalizeMetadata(scopeArg)); } public prepareCodexTurn(projectIdArg: string, nativeIdArg: string): Promise { return this.runOperation(async () => { const creation = await this.codexCreations.findUnmaterialized(projectIdArg, nativeIdArg); if (creation) await this.codexCreations.recordTurnDispatch(creation); }); } public cancelUndispatchedCodexTurn(projectIdArg: string, nativeIdArg: string): Promise { return this.runOperation(async () => { const creation = await this.codexCreations.findUnmaterialized(projectIdArg, nativeIdArg); if (creation) await this.codexCreations.cancelUndispatchedTurn(creation); }); } public markCodexMaterialized(projectIdArg: string, nativeIdArg: string): Promise { return this.runOperation(async () => { const creation = await this.codexCreations.findUnmaterialized(projectIdArg, nativeIdArg); if (creation) await this.codexCreations.materialize(creation); }); } public async completeCodexCreationDeletion(projectIdArg: string, nativeIdArg: string): Promise { const creation = await this.runOperation(() => this.codexCreations.findUnmaterialized(projectIdArg, nativeIdArg)); if (!creation) return; if (!creation.sessionIdentityId || !await this.resolveRetiredManagedSessionIdentity({ projectIdentityId: projectIdArg, runtimeId: { harnessId: 'codex', nativeId: nativeIdArg }, sessionIdentityId: creation.sessionIdentityId, })) throw new Error('Codex creation deletion has no exact retired managed identity.'); await this.runOperation(() => this.codexCreations.completeDeletion(creation)); } /** Retires only a never-submitted creation whose exact dispatch runtime is conclusively gone. */ public retireCodexCreation( scopeArg: ICodexCreationScope, assertRuntimeTerminatedArg: (runtimeArg: ICodexCreationRuntime) => Promise, ): Promise { return this.runOperation(async () => { const creation = await this.codexCreations.get(scopeArg); if (creation.state === 'retired') return; if (creation.state === 'materialized' || creation.turnDispatchedAt !== undefined) { throw new Error('Codex creation may contain an executed turn; empty-session retirement is forbidden.'); } if (creation.runtime) await assertRuntimeTerminatedArg(creation.runtime); if (creation.nativeId !== undefined && creation.providerCreatedAt !== undefined) { const input = this.resolveLocatorInput(scopeArg.projectIdentityId, { harnessId: 'codex', nativeId: creation.nativeId }); const expectedGeneration = codexSessionProviderGeneration(creation.nativeId, creation.providerCreatedAt); await this.runScopeMutation(input.scopeKey, async () => { let storedLocator = await this.readLocator(input.locatorId); if (!storedLocator) return; storedLocator = (await this.settleCoordinator(storedLocator)).stored; const locator = ControllerSessionLocatorModel.exact.toPersisted(storedLocator); this.assertLocatorScope(locator, input); if (locator.providerSessionGeneration !== expectedGeneration || (creation.sessionIdentityId !== undefined && locator.sessionIdentityId !== creation.sessionIdentityId)) { throw new Error('The absent Codex creation no longer matches its managed identity.'); } const storedMembership = await this.readManagedSession(input.projectIdentityId, 'codex', locator.sessionIdentityId); const membership = storedMembership && ControllerManagedSessionModel.exact.toPersisted(storedMembership); if (membership && (membership.providerSessionGeneration !== expectedGeneration || membership.state === 'deleting')) { throw new Error('Codex creation retirement conflicts with managed session state.'); } const bindingId = locator.activeBindingId ?? locator.detachedBinding?.bindingId ?? locator.deletion?.finalBindingId; if (!bindingId) throw new Error('The absent Codex creation has no recoverable binding.'); const binding = ControllerSessionRuntimeBindingModel.exact.toPersisted(await this.requireBindingForLocator(locator, bindingId)); if (binding.supervisorGeneration !== creation.runtime?.generation) { throw new Error('The Codex creation was rebound to a runtime whose termination has not been proven.'); } const now = new Date(); await this.beginSessionDeletionInScope(input, bindingId, creation.operationId, now); await this.completeSessionDeletionInScope(input, creation.operationId, now); const completedLocator = ControllerSessionLocatorModel.exact.toPersisted(await this.requireLocator(input.locatorId)); const retiredAt = completedLocator.deletion?.completedAt; if (!retiredAt) throw new Error('Codex creation retirement has no canonical completion time.'); if (storedMembership && membership?.state === 'active') { await this.transitionManagedSessionDocument(storedMembership, (model) => { model.state = 'retired'; model.retiredAt = retiredAt; }, (body) => body.state === 'retired' && body.providerSessionGeneration === expectedGeneration, 'Codex empty-session retirement changed concurrently.'); } }); } await this.codexCreations.retireUnmaterialized(scopeArg, creation.runtime?.generation); }); } private runOperation(operationArg: () => Promise): Promise { if (this.closeStarted) { return Promise.reject(new ControllerSessionIdentityError( 'closed', 'Controller session identity service is closed.', )); } let tracked!: Promise; tracked = Promise.resolve().then(operationArg).finally(() => { this.activeOperations.delete(tracked); }); this.activeOperations.add(tracked); return tracked; } private runScopeMutation( scopeKeyArg: string, operationArg: () => Promise, ): Promise { const previous = this.scopeMutationTails.get(scopeKeyArg) ?? Promise.resolve(); const result = previous.then(operationArg); const tail = result.then(() => undefined, () => undefined); this.scopeMutationTails.set(scopeKeyArg, tail); void tail.then(() => { if (this.scopeMutationTails.get(scopeKeyArg) === tail) { this.scopeMutationTails.delete(scopeKeyArg); } }); return result; } private runScopedOperation( scopeKeyArg: string, operationArg: () => Promise, ): Promise { return this.runOperation(() => this.runScopeMutation(scopeKeyArg, operationArg)); } private runProjectHarnessScopesOperation( projectIdentityIdArg: string, harnessIdArg: TControllerSessionHarnessId | undefined, operationArg: () => Promise, ): Promise { const scopes = (harnessIdArg === undefined ? ['opencode', 'flex', 'codex'] as const : [harnessIdArg] ).map((harnessId) => this.resolveSnapshotScope(projectIdentityIdArg, harnessId)); return this.runOperation(() => { const runAt = (indexArg: number): Promise => ( indexArg >= scopes.length ? operationArg() : this.runScopeMutation(scopes[indexArg].scopeKey, () => runAt(indexArg + 1)) ); return runAt(0); }); } public async close(): Promise { this.closeStarted = true; await Promise.allSettled([...this.activeOperations]); } private resolveSnapshotScope( projectIdentityIdArg: string, harnessIdArg: TControllerSessionHarnessId, ): IResolvedSnapshotScope { if (!isBase64UrlBytes(projectIdentityIdArg, 16)) { throw new ControllerSessionIdentityError('invalid_input', 'Project identity is invalid.'); } if (harnessIdArg !== 'opencode' && harnessIdArg !== 'flex' && harnessIdArg !== 'codex') { throw new ControllerSessionIdentityError('invalid_input', 'Session harness is invalid.'); } return { projectIdentityId: projectIdentityIdArg, harnessId: harnessIdArg, scopeKey: JSON.stringify([this.issuerId, projectIdentityIdArg, harnessIdArg]), }; } private resolveLocatorInput( projectIdentityIdArg: string, runtimeIdArg: TControllerSessionId, ): IResolvedLocatorInput { if (!isBase64UrlBytes(projectIdentityIdArg, 16)) { throw new ControllerSessionIdentityError('invalid_input', 'Project identity is invalid.'); } const runtimeId = requireRuntimeId(runtimeIdArg); const scope = this.resolveSnapshotScope(projectIdentityIdArg, runtimeId.harnessId); return { projectIdentityId: scope.projectIdentityId, runtimeId, locatorId: controllerSessionLocatorDocumentId( this.issuerId, projectIdentityIdArg, runtimeId, ), scopeKey: scope.scopeKey, }; } private async readLocator( locatorIdArg: string, signalArg?: AbortSignal, ): Promise { return (await ControllerSessionLocatorModel.exact.findStoredOne( { id: locatorIdArg }, { signal: signalArg }, )) ?? undefined; } private async requireLocator(locatorIdArg: string): Promise { const stored = await this.readLocator(locatorIdArg); if (!stored) { throw new ControllerSessionIdentityError('not_found', 'Session identity locator was not found.'); } return stored; } private assertLocatorScope( locatorArg: IControllerSessionLocatorDocument, inputArg: IResolvedLocatorInput, ): void { if ( locatorArg.issuerId !== this.issuerId || locatorArg.projectIdentityId !== inputArg.projectIdentityId || !runtimeIdsEqual(locatorArg.runtimeId, inputArg.runtimeId) || locatorArg.id !== inputArg.locatorId ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session identity locator does not match its lookup scope.', ); } } private async readManagedSession( projectIdentityIdArg: string, harnessIdArg: TControllerSessionHarnessId, sessionIdentityIdArg: string, signalArg?: AbortSignal, ): Promise { return (await ControllerManagedSessionModel.exact.findStoredOne({ id: controllerManagedSessionDocumentId( this.issuerId, projectIdentityIdArg, harnessIdArg, sessionIdentityIdArg, ), }, { signal: signalArg })) ?? undefined; } private assertManagedSessionScope( membershipArg: IControllerManagedSessionDocument, projectIdentityIdArg: string, runtimeIdArg: TControllerSessionId, sessionIdentityIdArg: string, ): void { if ( membershipArg.issuerId !== this.issuerId || membershipArg.projectIdentityId !== projectIdentityIdArg || membershipArg.harnessId !== runtimeIdArg.harnessId || !runtimeIdsEqual(membershipArg.runtimeId, runtimeIdArg) || membershipArg.sessionIdentityId !== sessionIdentityIdArg || membershipArg.id !== controllerManagedSessionDocumentId( this.issuerId, projectIdentityIdArg, runtimeIdArg.harnessId, sessionIdentityIdArg, ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Managed session membership does not match its lookup scope.', ); } } private async snapshotMembershipIsActive( scopeArg: IResolvedSnapshotScope, runtimeIdArg: TControllerSessionId, sessionIdentityIdArg: string, signalArg?: AbortSignal, ): Promise { const stored = await this.readManagedSession( scopeArg.projectIdentityId, scopeArg.harnessId, sessionIdentityIdArg, signalArg, ); if (!stored) return false; const membership = ControllerManagedSessionModel.exact.toPersisted(stored); this.assertManagedSessionScope( membership, scopeArg.projectIdentityId, runtimeIdArg, sessionIdentityIdArg, ); return membership.state === 'active'; } private async transitionManagedSessionDocument( currentArg: TStoredManagedSession, changeArg: (modelArg: ControllerManagedSessionModel) => void, postconditionArg: (documentArg: IControllerManagedSessionDocument) => boolean, concurrentMessageArg: string, acceptConcurrentPostconditionArg = false, ): Promise { const current = ControllerManagedSessionModel.exact.toPersisted(currentArg); const updateId = randomId(32); try { const result = await ControllerManagedSessionModel.exact.transition({ current: currentArg, change: (model) => { changeArg(model); model.updateId = updateId; }, }); if (result.status === 'transitioned') { const body = ControllerManagedSessionModel.exact.toPersisted(result.document); if (body.updateId !== updateId || !postconditionArg(body)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Managed session transition committed an invalid postcondition.', ); } return result.document; } if (acceptConcurrentPostconditionArg) { const reconciled = await ControllerManagedSessionModel.exact.findStoredOne({ id: current.id, }); if (reconciled) { const body = ControllerManagedSessionModel.exact.toPersisted(reconciled); if (postconditionArg(body)) return reconciled; } } throw new ControllerSessionIdentityError('concurrent_change', concurrentMessageArg); } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; const reconciled = await ControllerManagedSessionModel.exact.findStoredOne({ id: current.id }); if (reconciled) { const body = ControllerManagedSessionModel.exact.toPersisted(reconciled); if (body.updateId === updateId && postconditionArg(body)) return reconciled; } throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session transition has an ambiguous outcome.', { cause: errorArg }, ); } } private async readSessionCreationObligation( projectIdentityIdArg: string, runtimeIdArg: TControllerSessionId, signalArg?: AbortSignal, ): Promise { return (await ControllerSessionCreationObligationModel.exact.findStoredOne({ id: controllerSessionCreationObligationDocumentId( this.issuerId, projectIdentityIdArg, runtimeIdArg, ), }, { signal: signalArg })) ?? undefined; } private assertSessionCreationObligationScope( obligationArg: IControllerSessionCreationObligationDocument, projectIdentityIdArg: string, runtimeIdArg: TControllerSessionId, ): void { if ( obligationArg.issuerId !== this.issuerId || obligationArg.projectIdentityId !== projectIdentityIdArg || !runtimeIdsEqual(obligationArg.runtimeId, runtimeIdArg) || obligationArg.id !== controllerSessionCreationObligationDocumentId( this.issuerId, projectIdentityIdArg, runtimeIdArg, ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session creation obligation does not match its lookup scope.', ); } } private async transitionSessionCreationObligationDocument( currentArg: TStoredSessionCreationObligation, changeArg: (modelArg: ControllerSessionCreationObligationModel) => void, postconditionArg: (documentArg: IControllerSessionCreationObligationDocument) => boolean, concurrentMessageArg: string, ): Promise { const current = ControllerSessionCreationObligationModel.exact.toPersisted(currentArg); const updateId = randomId(32); try { const result = await ControllerSessionCreationObligationModel.exact.transition({ current: currentArg, change: (model) => { changeArg(model); model.updateId = updateId; }, }); if (result.status === 'transitioned') { const body = ControllerSessionCreationObligationModel.exact.toPersisted(result.document); if (body.updateId !== updateId || !postconditionArg(body)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session creation obligation transition committed an invalid postcondition.', ); } return result.document; } const reconciled = await ControllerSessionCreationObligationModel.exact.findStoredOne({ id: current.id, }); if (reconciled) { const body = ControllerSessionCreationObligationModel.exact.toPersisted(reconciled); if (postconditionArg(body)) return reconciled; } throw new ControllerSessionIdentityError('concurrent_change', concurrentMessageArg); } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; const reconciled = await ControllerSessionCreationObligationModel.exact.findStoredOne({ id: current.id, }); if (reconciled) { const body = ControllerSessionCreationObligationModel.exact.toPersisted(reconciled); if (body.updateId === updateId && postconditionArg(body)) return reconciled; } throw new ControllerSessionIdentityError( 'concurrent_change', 'Session creation obligation transition has an ambiguous outcome.', { cause: errorArg }, ); } } private async readManagedSessionStatePages( projectIdentityIdArg: string, harnessIdArg: TControllerSessionHarnessId | undefined, statesArg: readonly TControllerManagedSessionState[], signalArg?: AbortSignal, ): Promise { const stored: TStoredManagedSession[] = []; const harnessIds: readonly TControllerSessionHarnessId[] = harnessIdArg === undefined ? ['opencode', 'flex', 'codex'] : [harnessIdArg]; for (const harnessId of harnessIds) { for (const state of statesArg) { let lastId: string | undefined; while (true) { signalArg?.throwIfAborted(); const pageLimit = Math.min( controllerManagedSessionRecoveryPageEntryLimit, controllerManagedSessionRecoveryEntryLimit + 1 - stored.length, ); const page = await ControllerManagedSessionModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: projectIdentityIdArg, harnessId, state, ...(lastId === undefined ? {} : { id: { $gt: lastId } }), }, sort: { id: 1 }, limit: pageLimit, signal: signalArg, }); signalArg?.throwIfAborted(); if (stored.length + page.length > controllerManagedSessionRecoveryEntryLimit) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The managed session recovery entry limit was exceeded.', ); } if (page.length > pageLimit) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A managed session recovery page exceeds its requested limit.', ); } if (page.length === 0) break; for (const entry of page) { const body = ControllerManagedSessionModel.exact.toPersisted(entry); if (lastId !== undefined && body.id <= lastId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Managed session recovery pagination did not advance.', ); } this.assertManagedSessionScope( body, projectIdentityIdArg, body.runtimeId, body.sessionIdentityId, ); if (body.harnessId !== harnessId || body.state !== state) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A managed session escaped its recovery scan scope.', ); } stored.push(entry); lastId = body.id; } if (page.length < pageLimit) break; } } } stored.sort((leftArg, rightArg) => compareDocumentIds(leftArg.id, rightArg.id)); return stored; } private async readSessionCreationObligationStatePages( projectIdentityIdArg: string, harnessIdArg: TControllerSessionHarnessId | undefined, statesArg: readonly TControllerSessionCreationObligationState[], signalArg?: AbortSignal, ): Promise { const stored: TStoredSessionCreationObligation[] = []; const harnessIds: readonly TControllerSessionHarnessId[] = harnessIdArg === undefined ? ['opencode', 'flex', 'codex'] : [harnessIdArg]; for (const harnessId of harnessIds) { for (const state of statesArg) { let lastId: string | undefined; while (true) { signalArg?.throwIfAborted(); const pageLimit = Math.min( controllerManagedSessionRecoveryPageEntryLimit, controllerManagedSessionRecoveryEntryLimit + 1 - stored.length, ); const page = await ControllerSessionCreationObligationModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: projectIdentityIdArg, 'runtimeId.harnessId': harnessId, state, ...(lastId === undefined ? {} : { id: { $gt: lastId } }), }, sort: { id: 1 }, limit: pageLimit, signal: signalArg, }); signalArg?.throwIfAborted(); if (stored.length + page.length > controllerManagedSessionRecoveryEntryLimit) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The session creation obligation recovery entry limit was exceeded.', ); } if (page.length > pageLimit) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A session creation obligation recovery page exceeds its requested limit.', ); } if (page.length === 0) break; for (const entry of page) { const body = ControllerSessionCreationObligationModel.exact.toPersisted(entry); if (lastId !== undefined && body.id <= lastId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session creation obligation recovery pagination did not advance.', ); } this.assertSessionCreationObligationScope( body, projectIdentityIdArg, body.runtimeId, ); if (body.runtimeId.harnessId !== harnessId || body.state !== state) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A session creation obligation escaped its recovery scan scope.', ); } stored.push(entry); lastId = body.id; } if (page.length < pageLimit) break; } } } stored.sort((leftArg, rightArg) => compareDocumentIds(leftArg.id, rightArg.id)); return stored; } private async readSnapshotLocators( scopeArg: IResolvedSnapshotScope, signalArg?: AbortSignal, ): Promise { const stored: TStoredLocator[] = []; let lastLocatorId: string | undefined; while (true) { signalArg?.throwIfAborted(); const pageLimit = Math.min( controllerSessionIdentityLocatorPageEntryLimit, controllerSessionIdentityScopedLocatorLimit + 1 - stored.length, ); const page = await ControllerSessionLocatorModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: scopeArg.projectIdentityId, 'runtimeId.harnessId': scopeArg.harnessId, state: { $in: snapshotLocatorStates }, ...(lastLocatorId === undefined ? {} : { id: { $gt: lastLocatorId } }), }, sort: { id: 1 }, limit: pageLimit, signal: signalArg, }); signalArg?.throwIfAborted(); if (stored.length + page.length > controllerSessionIdentityScopedLocatorLimit) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The scoped session identity locator limit was exceeded.', ); } if (page.length > pageLimit) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The session identity locator page exceeds its requested limit.', ); } if (page.length === 0) break; for (const locator of page) { const body = ControllerSessionLocatorModel.exact.toPersisted(locator); if (lastLocatorId !== undefined && body.id <= lastLocatorId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session identity locator pagination did not advance.', ); } const input = this.resolveLocatorInput(body.projectIdentityId, body.runtimeId); this.assertLocatorScope(body, input); if (body.runtimeId.harnessId !== scopeArg.harnessId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A session identity locator escaped its snapshot scope.', ); } stored.push(locator); lastLocatorId = body.id; } if (page.length < pageLimit) break; } return stored; } private async hasSnapshotLocatorCapacity( scopeArg: IResolvedSnapshotScope, signalArg?: AbortSignal, ): Promise { let count = 0; let lastLocatorId: string | undefined; while (count < controllerSessionIdentityScopedLocatorLimit) { signalArg?.throwIfAborted(); const pageLimit = Math.min( controllerSessionIdentityLocatorPageEntryLimit, controllerSessionIdentityScopedLocatorLimit - count, ); const page = await ControllerSessionLocatorModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: scopeArg.projectIdentityId, 'runtimeId.harnessId': scopeArg.harnessId, state: { $in: snapshotLocatorStates }, ...(lastLocatorId === undefined ? {} : { id: { $gt: lastLocatorId } }), }, sort: { id: 1 }, limit: pageLimit, signal: signalArg, }); signalArg?.throwIfAborted(); if (page.length > pageLimit) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A session identity capacity page exceeds its requested limit.', ); } if (page.length === 0) return true; for (const locator of page) { const body = ControllerSessionLocatorModel.exact.toPersisted(locator); if (lastLocatorId !== undefined && body.id <= lastLocatorId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session identity capacity pagination did not advance.', ); } const input = this.resolveLocatorInput(body.projectIdentityId, body.runtimeId); this.assertLocatorScope(body, input); if (body.runtimeId.harnessId !== scopeArg.harnessId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A session identity locator escaped its capacity scope.', ); } lastLocatorId = body.id; } count += page.length; if (count >= controllerSessionIdentityScopedLocatorLimit) return false; if (page.length < pageLimit) return true; } return false; } private async readSnapshotLocatorsByIds( scopeArg: IResolvedSnapshotScope, locatorIdsArg: readonly string[], signalArg?: AbortSignal, ): Promise { const stored: TStoredLocator[] = []; for ( let offset = 0; offset < locatorIdsArg.length; offset += controllerSessionIdentityLocatorPageEntryLimit ) { signalArg?.throwIfAborted(); const locatorIds = locatorIdsArg.slice( offset, offset + controllerSessionIdentityLocatorPageEntryLimit, ); const locatorIdSet = new Set(locatorIds); const page = await ControllerSessionLocatorModel.exact.findStored({ filter: { id: { $in: locatorIds } }, sort: { id: 1 }, limit: locatorIds.length, signal: signalArg, }); signalArg?.throwIfAborted(); if (page.length > locatorIds.length) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A targeted session identity locator page exceeds its requested limit.', ); } for (const locator of page) { const body = ControllerSessionLocatorModel.exact.toPersisted(locator); const input = this.resolveLocatorInput(scopeArg.projectIdentityId, body.runtimeId); this.assertLocatorScope(body, input); if ( body.runtimeId.harnessId !== scopeArg.harnessId || !locatorIdSet.has(body.id) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A targeted session identity locator escaped its snapshot scope.', ); } stored.push(locator); } } stored.sort((leftArg, rightArg) => compareDocumentIds(leftArg.id, rightArg.id)); return stored; } private pendingDeletionFromLocator( locatorArg: IControllerSessionLocatorDocument, ): IControllerSessionPendingDeletion | undefined { if ( (locatorArg.state !== 'deleting' && locatorArg.state !== 'completing') || !locatorArg.deletion ) return undefined; return { runtimeId: { ...locatorArg.runtimeId }, operationId: locatorArg.deletion.operationId, expectedBindingId: locatorArg.deletion.finalBindingId, state: locatorArg.state, startedAt: locatorArg.deletion.startedAt.getTime(), }; } private async transitionLocator( currentArg: TStoredLocator, changeArg: (documentArg: IControllerSessionLocatorDocument) => void, ): Promise { try { const result = await ControllerSessionLocatorModel.exact.transition({ current: currentArg, change: changeArg, }); if (result.status === 'transitioned') return result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; } return this.requireLocator( ControllerSessionLocatorModel.exact.toPersisted(currentArg).id, ); } private identityFromLocator( locatorArg: IControllerSessionLocatorDocument, ): IControllerSessionIdentityDocument { return { id: controllerSessionIdentityDocumentId( locatorArg.issuerId, locatorArg.sessionIdentityId, ), issuerId: locatorArg.issuerId, sessionIdentityId: locatorArg.sessionIdentityId, projectIdentityId: locatorArg.projectIdentityId, createdAt: new Date(locatorArg.identityCreatedAt), }; } private bindingFromPending( locatorArg: IControllerSessionLocatorDocument, pendingArg: IControllerSessionPendingBinding, ): IControllerSessionRuntimeBindingDocument { return { id: pendingArg.bindingId, bindingId: pendingArg.bindingId, issuerId: locatorArg.issuerId, sessionIdentityId: locatorArg.sessionIdentityId, projectIdentityId: locatorArg.projectIdentityId, runtimeId: { ...locatorArg.runtimeId }, supervisorGeneration: pendingArg.supervisorGeneration, ...(locatorArg.providerSessionGeneration === undefined ? {} : { providerSessionGeneration: locatorArg.providerSessionGeneration }), attachedAt: new Date(pendingArg.attachedAt), }; } private identityDocumentsEqual( leftArg: IControllerSessionIdentityDocument, rightArg: IControllerSessionIdentityDocument, ): boolean { return Buffer.from(ControllerSessionIdentityModel.exact.canonicalBytes(leftArg)).equals( ControllerSessionIdentityModel.exact.canonicalBytes(rightArg), ); } private bindingDocumentsEqual( leftArg: IControllerSessionRuntimeBindingDocument, rightArg: IControllerSessionRuntimeBindingDocument, ): boolean { return Buffer.from( ControllerSessionRuntimeBindingModel.exact.canonicalBytes(leftArg), ).equals(ControllerSessionRuntimeBindingModel.exact.canonicalBytes(rightArg)); } private async ensureIdentity( candidateArg: IControllerSessionIdentityDocument, ): Promise { let stored: TStoredIdentity | undefined; try { const result = await ControllerSessionIdentityModel.exact.insert(candidateArg); stored = result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; stored = (await ControllerSessionIdentityModel.exact.findStoredOne({ id: candidateArg.id })) ?? undefined; } if (!stored) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session identity insertion has an ambiguous outcome.', ); } const body = ControllerSessionIdentityModel.exact.toPersisted(stored); if (!this.identityDocumentsEqual(body, candidateArg)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session identity conflicts with its locator candidate.', ); } return stored; } private async ensureBinding( candidateArg: IControllerSessionRuntimeBindingDocument, ): Promise { let stored: TStoredBinding | undefined; try { const result = await ControllerSessionRuntimeBindingModel.exact.insert(candidateArg); stored = result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; stored = (await ControllerSessionRuntimeBindingModel.exact.findStoredOne({ id: candidateArg.id, })) ?? undefined; } if (!stored) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session runtime binding insertion has an ambiguous outcome.', ); } const body = ControllerSessionRuntimeBindingModel.exact.toPersisted(stored); if (!this.bindingDocumentsEqual(body, candidateArg)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session runtime binding conflicts with its locator candidate.', ); } return stored; } private async requireIdentityForLocator( locatorArg: IControllerSessionLocatorDocument, signalArg?: AbortSignal, ): Promise { const stored = await ControllerSessionIdentityModel.exact.findStoredOne({ id: controllerSessionIdentityDocumentId( locatorArg.issuerId, locatorArg.sessionIdentityId, ), }, { signal: signalArg }); if (!stored) { throw new ControllerSessionIdentityError('corrupt_state', 'Session identity record is missing.'); } const body = ControllerSessionIdentityModel.exact.toPersisted(stored); if ( body.issuerId !== locatorArg.issuerId || body.sessionIdentityId !== locatorArg.sessionIdentityId || body.projectIdentityId !== locatorArg.projectIdentityId || !datesEqual(body.createdAt, locatorArg.identityCreatedAt) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session identity record does not match its locator.', ); } return stored; } private async readParentRelationship( scopeArg: IResolvedSnapshotScope, childSessionIdentityIdArg: string, ): Promise { return (await ControllerSessionParentRelationshipModel.exact.findStoredOne({ id: controllerSessionParentRelationshipDocumentId( this.issuerId, scopeArg.projectIdentityId, scopeArg.harnessId, childSessionIdentityIdArg, ), })) ?? undefined; } private assertParentRelationshipScope( relationshipArg: IControllerSessionParentRelationshipDocument, scopeArg: IResolvedSnapshotScope, childSessionIdentityIdArg: string, ): void { if ( relationshipArg.issuerId !== this.issuerId || relationshipArg.projectIdentityId !== scopeArg.projectIdentityId || relationshipArg.harnessId !== scopeArg.harnessId || relationshipArg.childSessionIdentityId !== childSessionIdentityIdArg || relationshipArg.id !== controllerSessionParentRelationshipDocumentId( this.issuerId, scopeArg.projectIdentityId, scopeArg.harnessId, childSessionIdentityIdArg, ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session parent relationship does not match its lookup scope.', ); } } private parentRelationshipDocumentsMatch( leftArg: IControllerSessionParentRelationshipDocument, rightArg: IControllerSessionParentRelationshipDocument, ): boolean { return leftArg.id === rightArg.id && leftArg.issuerId === rightArg.issuerId && leftArg.projectIdentityId === rightArg.projectIdentityId && leftArg.harnessId === rightArg.harnessId && leftArg.parentSessionIdentityId === rightArg.parentSessionIdentityId && leftArg.childSessionIdentityId === rightArg.childSessionIdentityId; } private async assertNoParentRelationshipCycle( scopeArg: IResolvedSnapshotScope, parentSessionIdentityIdArg: string, childSessionIdentityIdArg: string, ): Promise { let ancestorSessionIdentityId = parentSessionIdentityIdArg; const visited = new Set(); for ( let depth = 0; depth <= controllerSessionIdentityScopedLocatorLimit; depth += 1 ) { if (ancestorSessionIdentityId === childSessionIdentityIdArg) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The provider parent relationship would create a cycle.', ); } if (visited.has(ancestorSessionIdentityId)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The stored session parent relationship graph contains a cycle.', ); } visited.add(ancestorSessionIdentityId); const stored = await this.readParentRelationship(scopeArg, ancestorSessionIdentityId); if (!stored) return; const body = ControllerSessionParentRelationshipModel.exact.toPersisted(stored); this.assertParentRelationshipScope(body, scopeArg, ancestorSessionIdentityId); ancestorSessionIdentityId = body.parentSessionIdentityId; } throw new ControllerSessionIdentityError( 'limit_exceeded', 'The session parent relationship ancestry exceeds its scope limit.', ); } private async insertParentRelationship( candidateArg: IControllerSessionParentRelationshipDocument, scopeArg: IResolvedSnapshotScope, ): Promise { let stored: TStoredParentRelationship | undefined; try { const result = await ControllerSessionParentRelationshipModel.exact.insert(candidateArg); stored = result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; stored = await this.readParentRelationship( scopeArg, candidateArg.childSessionIdentityId, ); } if (!stored) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session parent relationship insertion has an ambiguous outcome.', ); } const body = ControllerSessionParentRelationshipModel.exact.toPersisted(stored); this.assertParentRelationshipScope(body, scopeArg, candidateArg.childSessionIdentityId); if (!this.parentRelationshipDocumentsMatch(body, candidateArg)) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The session already has a different immutable parent relationship.', ); } } private async reconcileSnapshotParentRelationship( scopeArg: IResolvedSnapshotScope, sessionArg: IResolvedSnapshotSession, observationArg: IControllerSessionSnapshotObservation, observedAtArg: Date, ): Promise { const childSessionIdentityId = observationArg.identity.sessionIdentityId; const existingStored = await this.readParentRelationship( scopeArg, childSessionIdentityId, ); const existing = existingStored === undefined ? undefined : ControllerSessionParentRelationshipModel.exact.toPersisted(existingStored); if (existing) { this.assertParentRelationshipScope(existing, scopeArg, childSessionIdentityId); } if (sessionArg.parentNativeId === undefined) { if (existing) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The provider removed an immutable session parent relationship.', ); } return; } const parentInput = this.resolveLocatorInput(scopeArg.projectIdentityId, { harnessId: scopeArg.harnessId, nativeId: sessionArg.parentNativeId, }); let parentLocator = await this.readLocator(parentInput.locatorId); if (!parentLocator) { if (existing) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The provider replaced an immutable session parent with an unresolved parent.', ); } return; } parentLocator = (await this.settleCoordinator(parentLocator)).stored; const parentLocatorBody = ControllerSessionLocatorModel.exact.toPersisted(parentLocator); this.assertLocatorScope(parentLocatorBody, parentInput); if (parentLocatorBody.state === 'deleting' || parentLocatorBody.state === 'completing') { throw new ControllerSessionIdentityError( 'concurrent_change', 'A session parent entered deletion during relationship reconciliation.', ); } const parentIdentityStored = await this.requireIdentityForLocator(parentLocatorBody); const parentIdentity = ControllerSessionIdentityModel.exact.toPersisted(parentIdentityStored); const childInput = this.resolveLocatorInput(scopeArg.projectIdentityId, sessionArg.runtimeId); let childLocator = await this.requireLocator(childInput.locatorId); childLocator = (await this.settleCoordinator(childLocator)).stored; const childLocatorBody = ControllerSessionLocatorModel.exact.toPersisted(childLocator); this.assertLocatorScope(childLocatorBody, childInput); const childIdentityStored = await this.requireIdentityForLocator(childLocatorBody); const childIdentity = ControllerSessionIdentityModel.exact.toPersisted(childIdentityStored); if ( childIdentity.sessionIdentityId !== childSessionIdentityId || childIdentity.sessionIdentityId !== observationArg.identity.sessionIdentityId || parentIdentity.sessionIdentityId === childIdentity.sessionIdentityId ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session parent relationship identities are inconsistent.', ); } if (existing) { if (existing.parentSessionIdentityId !== parentIdentity.sessionIdentityId) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The provider replaced an immutable session parent relationship.', ); } return; } if ( observedAtArg.getTime() < parentIdentity.createdAt.getTime() || observedAtArg.getTime() < childIdentity.createdAt.getTime() ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session parent relationship observation precedes its identities.', ); } await this.assertNoParentRelationshipCycle( scopeArg, parentIdentity.sessionIdentityId, childIdentity.sessionIdentityId, ); await this.insertParentRelationship({ id: controllerSessionParentRelationshipDocumentId( this.issuerId, scopeArg.projectIdentityId, scopeArg.harnessId, childIdentity.sessionIdentityId, ), issuerId: this.issuerId, projectIdentityId: scopeArg.projectIdentityId, harnessId: scopeArg.harnessId, parentSessionIdentityId: parentIdentity.sessionIdentityId, childSessionIdentityId: childIdentity.sessionIdentityId, createdAt: new Date(observedAtArg), }, scopeArg); } private async requireBindingForLocator( locatorArg: IControllerSessionLocatorDocument, bindingIdArg: string, signalArg?: AbortSignal, ): Promise { const stored = await ControllerSessionRuntimeBindingModel.exact.findStoredOne({ id: bindingIdArg, }, { signal: signalArg }); if (!stored) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session runtime binding record is missing.', ); } const body = ControllerSessionRuntimeBindingModel.exact.toPersisted(stored); if ( body.bindingId !== bindingIdArg || body.issuerId !== locatorArg.issuerId || body.sessionIdentityId !== locatorArg.sessionIdentityId || body.projectIdentityId !== locatorArg.projectIdentityId || !runtimeIdsEqual(body.runtimeId, locatorArg.runtimeId) || !providerGenerationsEqual( body.providerSessionGeneration, locatorArg.providerSessionGeneration, ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session runtime binding record does not match its locator.', ); } return stored; } private async detachBinding( locatorArg: IControllerSessionLocatorDocument, referenceArg: { bindingId: string; detachedAt: Date }, ): Promise { const stored = await this.requireBindingForLocator(locatorArg, referenceArg.bindingId); const body = ControllerSessionRuntimeBindingModel.exact.toPersisted(stored); if (body.detachedAt !== undefined) { if (!datesEqual(body.detachedAt, referenceArg.detachedAt)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session runtime binding was detached at a different time.', ); } return stored; } let transitioned: TStoredBinding | undefined; try { const result = await ControllerSessionRuntimeBindingModel.exact.transition({ current: stored, change: (model) => { model.detachedAt = new Date(referenceArg.detachedAt); }, }); if (result.status === 'transitioned') transitioned = result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; } const reconciled = transitioned ?? await this.requireBindingForLocator( locatorArg, referenceArg.bindingId, ); const reconciledBody = ControllerSessionRuntimeBindingModel.exact.toPersisted(reconciled); if ( reconciledBody.detachedAt === undefined || !datesEqual(reconciledBody.detachedAt, referenceArg.detachedAt) ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session runtime binding detachment changed concurrently.', ); } return reconciled; } private async retireIdentity( locatorArg: IControllerSessionLocatorDocument, retiredAtArg: Date, ): Promise { const stored = await this.requireIdentityForLocator(locatorArg); const body = ControllerSessionIdentityModel.exact.toPersisted(stored); if (body.retiredAt !== undefined) { if (!datesEqual(body.retiredAt, retiredAtArg)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session identity was retired at a different time.', ); } return stored; } let transitioned: TStoredIdentity | undefined; try { const result = await ControllerSessionIdentityModel.exact.transition({ current: stored, change: (model) => { model.retiredAt = new Date(retiredAtArg); }, }); if (result.status === 'transitioned') transitioned = result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; } const reconciled = transitioned ?? await this.requireIdentityForLocator(locatorArg); const reconciledBody = ControllerSessionIdentityModel.exact.toPersisted(reconciled); if ( reconciledBody.retiredAt === undefined || !datesEqual(reconciledBody.retiredAt, retiredAtArg) ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session identity retirement changed concurrently.', ); } return reconciled; } private async insertLocatorCandidate( candidateArg: IControllerSessionLocatorDocument, ): Promise { try { const result = await ControllerSessionLocatorModel.exact.insert(candidateArg); return { stored: result.document, adoptedCompetingWinner: result.status === 'conflict', }; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; const reconciled = await this.requireLocator(candidateArg.id); const body = ControllerSessionLocatorModel.exact.toPersisted(reconciled); return { stored: reconciled, adoptedCompetingWinner: body.sessionIdentityId !== candidateArg.sessionIdentityId, }; } } private async finishBindingCleanup(currentArg: TStoredLocator): Promise { const body = ControllerSessionLocatorModel.exact.toPersisted(currentArg); if (body.state !== 'attached' || !body.bindingCleanup) return currentArg; await this.detachBinding(body, body.bindingCleanup); const cleanup = body.bindingCleanup; return this.transitionLocator(currentArg, (model) => { if ( model.state === 'attached' && model.bindingCleanup?.bindingId === cleanup.bindingId && datesEqual(model.bindingCleanup.detachedAt, cleanup.detachedAt) ) { delete model.bindingCleanup; model.updatedAt = new Date(cleanup.detachedAt); } }); } private async finishDetaching(currentArg: TStoredLocator): Promise { const body = ControllerSessionLocatorModel.exact.toPersisted(currentArg); if (body.state !== 'detaching' || !body.bindingCleanup || !body.activeBindingId) { return currentArg; } const detached = body.bindingCleanup; await this.detachBinding(body, detached); return this.transitionLocator(currentArg, (model) => { if ( model.state === 'detaching' && model.activeBindingId === detached.bindingId && model.bindingCleanup?.bindingId === detached.bindingId && datesEqual(model.bindingCleanup.detachedAt, detached.detachedAt) ) { model.state = 'detached'; model.detachedBinding = { ...detached }; delete model.activeBindingId; delete model.bindingCleanup; model.updatedAt = new Date(detached.detachedAt); } }); } private async finishBinding(currentArg: TStoredLocator): Promise { const body = ControllerSessionLocatorModel.exact.toPersisted(currentArg); if (body.state !== 'binding' || !body.pendingBinding) return currentArg; await this.ensureIdentity(this.identityFromLocator(body)); await this.ensureBinding(this.bindingFromPending(body, body.pendingBinding)); const pending = body.pendingBinding; return this.transitionLocator(currentArg, (model) => { if ( model.state === 'binding' && model.pendingBinding?.bindingId === pending.bindingId ) { model.state = 'attached'; model.activeBindingId = pending.bindingId; delete model.pendingBinding; delete model.detachedBinding; model.updatedAt = new Date(pending.attachedAt); } }); } private async finishInitializing(currentArg: TStoredLocator): Promise { const body = ControllerSessionLocatorModel.exact.toPersisted(currentArg); if (body.state !== 'initializing' || !body.pendingBinding) return currentArg; await this.ensureIdentity(this.identityFromLocator(body)); await this.ensureBinding(this.bindingFromPending(body, body.pendingBinding)); const pending = body.pendingBinding; return this.transitionLocator(currentArg, (model) => { if ( model.state === 'initializing' && model.pendingBinding?.bindingId === pending.bindingId ) { model.state = 'attached'; model.activeBindingId = pending.bindingId; delete model.pendingBinding; model.updatedAt = new Date(pending.attachedAt); } }); } private finalDetachedAt(deletionArg: IControllerSessionDeletionRecord): Date { if (deletionArg.priorState === 'detached') return new Date(deletionArg.priorDetachedAt!); if (!deletionArg.completedAt) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Completing session deletion has no completion time.', ); } return new Date(deletionArg.completedAt); } private async finishCompletion(currentArg: TStoredLocator): Promise { const body = ControllerSessionLocatorModel.exact.toPersisted(currentArg); if (body.state !== 'completing' || !body.deletion?.completedAt) return currentArg; const detachedAt = this.finalDetachedAt(body.deletion); await this.detachBinding(body, { bindingId: body.deletion.finalBindingId, detachedAt, }); await this.retireIdentity(body, body.deletion.completedAt); const operationId = body.deletion.operationId; return this.transitionLocator(currentArg, (model) => { if ( model.state === 'completing' && model.deletion?.operationId === operationId ) { model.state = 'tombstoned'; delete model.activeBindingId; delete model.detachedBinding; model.updatedAt = new Date(model.deletion.completedAt!); } }); } private async settleCoordinator( currentArg: TStoredLocator, requestedSupervisorGenerationArg?: string, ): Promise { let current = currentArg; let competingGeneration = false; for (let attempt = 0; attempt < maximumReconciliationAttempts; attempt += 1) { const body = ControllerSessionLocatorModel.exact.toPersisted(current); if ( (body.state === 'initializing' || body.state === 'binding') && requestedSupervisorGenerationArg !== undefined && body.pendingBinding?.supervisorGeneration !== requestedSupervisorGenerationArg ) competingGeneration = true; if (body.state === 'initializing') { current = await this.finishInitializing(current); continue; } if (body.state === 'binding') { current = await this.finishBinding(current); continue; } if (body.state === 'attached' && body.bindingCleanup) { current = await this.finishBindingCleanup(current); continue; } if (body.state === 'detaching') { current = await this.finishDetaching(current); continue; } if (body.state === 'completing') { current = await this.finishCompletion(current); continue; } return { stored: current, competingGeneration }; } throw new ControllerSessionIdentityError( 'concurrent_change', 'Session identity coordinator did not converge.', ); } private assertProviderGeneration( locatorArg: IControllerSessionLocatorDocument, providerSessionGenerationArg: string | undefined, ): void { if (!providerGenerationsEqual( locatorArg.providerSessionGeneration, providerSessionGenerationArg, )) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'The provider session generation does not match the retained locator.', ); } } private async observationFromAttached( locatorArg: IControllerSessionLocatorDocument, signalArg?: AbortSignal, ): Promise { if (locatorArg.state !== 'attached' || !locatorArg.activeBindingId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session locator is not attached.', ); } const identity = await this.requireIdentityForLocator(locatorArg, signalArg); const binding = await this.requireBindingForLocator( locatorArg, locatorArg.activeBindingId, signalArg, ); const identityBody = ControllerSessionIdentityModel.exact.toPersisted(identity); const bindingBody = ControllerSessionRuntimeBindingModel.exact.toPersisted(binding); if (identityBody.retiredAt !== undefined || bindingBody.detachedAt !== undefined) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Attached session identity records are retired or detached.', ); } return { identity: publicIdentity(identityBody), binding: publicBinding(bindingBody), }; } private async replaceStableFlexLocatorGeneration( currentArg: TStoredLocator, inputArg: IResolvedLocatorInput, sessionIdentityIdArg: string, pendingBindingArg: IControllerSessionPendingBinding, providerSessionGenerationArg: string, observedAtArg: Date, ): Promise { let current = currentArg; let body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, inputArg); if ( inputArg.runtimeId.harnessId !== 'flex' || providerGenerationsEqual(body.providerSessionGeneration, providerSessionGenerationArg) ) return current; if (observedAtArg.getTime() < body.updatedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Reused Flex session generation precedes the retained locator state.', ); } if (body.state === 'attached' && body.activeBindingId) { await this.detachSessionInScope( inputArg, body.activeBindingId, observedAtArg, ); current = await this.requireLocator(inputArg.locatorId); body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, inputArg); } if (body.state === 'tombstoned') { await this.verifyTombstoneSideRecords(body); } else if (body.state === 'detached') { const identity = await this.requireIdentityForLocator(body); const identityBody = ControllerSessionIdentityModel.exact.toPersisted(identity); if (identityBody.retiredAt === undefined) { await this.retireIdentity(body, observedAtArg); } else if (identityBody.retiredAt.getTime() > observedAtArg.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Reused Flex session generation precedes the retained identity retirement.', ); } } else { throw new ControllerSessionIdentityError( body.state === 'deleting' || body.state === 'completing' ? 'deleting' : 'concurrent_change', 'The retained Flex session generation is not stable enough to replace.', ); } current = await this.requireLocator(inputArg.locatorId); body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, inputArg); if (providerGenerationsEqual(body.providerSessionGeneration, providerSessionGenerationArg)) { return current; } if ( body.state !== 'detached' && body.state !== 'tombstoned' || observedAtArg.getTime() < body.updatedAt.getTime() ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The retained Flex session generation changed during replacement.', ); } const priorSessionIdentityId = body.sessionIdentityId; const priorProviderSessionGeneration = body.providerSessionGeneration; return this.transitionLocator(current, (model) => { if ( (model.state === 'detached' || model.state === 'tombstoned') && model.sessionIdentityId === priorSessionIdentityId && model.providerSessionGeneration === priorProviderSessionGeneration ) { model.sessionIdentityId = sessionIdentityIdArg; model.providerSessionGeneration = providerSessionGenerationArg; model.identityCreatedAt = new Date(observedAtArg); model.state = 'initializing'; model.updatedAt = new Date(observedAtArg); model.pendingBinding = { ...pendingBindingArg }; delete model.activeBindingId; delete model.bindingCleanup; delete model.detachedBinding; delete model.deletion; } }); } private async observeSessionInScope( input: IResolvedLocatorInput, supervisorGeneration: string, providerSessionGeneration: string | undefined, observedAt: Date, allowFlexProviderGenerationReuseArg = false, signalArg?: AbortSignal, ): Promise { const identityCandidateId = randomId(32); const bindingCandidate: IControllerSessionPendingBinding = { bindingId: randomId(32), supervisorGeneration, attachedAt: observedAt, }; let adoptedCompetingFirstWinner = false; let replacementAttempted = false; for (let attempt = 0; attempt < maximumReconciliationAttempts; attempt += 1) { signalArg?.throwIfAborted(); let current = await this.readLocator(input.locatorId, signalArg); if (!current) { const hasCapacity = await this.hasSnapshotLocatorCapacity({ projectIdentityId: input.projectIdentityId, harnessId: input.runtimeId.harnessId, scopeKey: input.scopeKey, }, signalArg); if (!hasCapacity) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The scoped session identity locator limit was exceeded.', ); } const candidate: IControllerSessionLocatorDocument = { id: input.locatorId, issuerId: this.issuerId, sessionIdentityId: identityCandidateId, projectIdentityId: input.projectIdentityId, runtimeId: { ...input.runtimeId }, ...(providerSessionGeneration === undefined ? {} : { providerSessionGeneration }), identityCreatedAt: new Date(observedAt), state: 'initializing', updatedAt: new Date(observedAt), pendingBinding: { ...bindingCandidate }, }; const inserted = await this.insertLocatorCandidate(candidate); current = inserted.stored; adoptedCompetingFirstWinner ||= inserted.adoptedCompetingWinner; } let body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, input); const settled = await this.settleCoordinator(current, supervisorGeneration); current = settled.stored; body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, input); if (!providerGenerationsEqual(body.providerSessionGeneration, providerSessionGeneration)) { if ( allowFlexProviderGenerationReuseArg && input.runtimeId.harnessId === 'flex' && providerSessionGeneration !== undefined && !adoptedCompetingFirstWinner && !replacementAttempted ) { replacementAttempted = true; current = await this.replaceStableFlexLocatorGeneration( current, input, identityCandidateId, bindingCandidate, providerSessionGeneration, observedAt, ); continue; } this.assertProviderGeneration(body, providerSessionGeneration); } if (settled.competingGeneration) { throw new ControllerSessionIdentityError( 'concurrent_change', 'A competing supervisor generation won session binding.', ); } if (body.state === 'deleting' || body.state === 'completing') { throw new ControllerSessionIdentityError('deleting', 'The session is being deleted.'); } if (body.state === 'tombstoned') { throw new ControllerSessionIdentityError( 'tombstoned', 'The session runtime locator is permanently tombstoned.', ); } if (body.state === 'attached' && body.activeBindingId) { const active = await this.requireBindingForLocator(body, body.activeBindingId); const activeBody = ControllerSessionRuntimeBindingModel.exact.toPersisted(active); if (activeBody.detachedAt !== undefined) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The active session binding is already detached.', ); } if (activeBody.supervisorGeneration === supervisorGeneration) { return this.observationFromAttached(body); } if (adoptedCompetingFirstWinner || replacementAttempted) { throw new ControllerSessionIdentityError( 'concurrent_change', 'A competing supervisor generation is already attached.', ); } if ( observedAt.getTime() < activeBody.attachedAt.getTime() || observedAt.getTime() < body.updatedAt.getTime() ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session observation precedes the active binding state.', ); } replacementAttempted = true; const cleanup = { bindingId: body.activeBindingId, detachedAt: new Date(observedAt), }; current = await this.transitionLocator(current, (model) => { if ( model.state === 'attached' && model.activeBindingId === cleanup.bindingId && !model.bindingCleanup ) { model.state = 'binding'; model.pendingBinding = { ...bindingCandidate }; model.bindingCleanup = cleanup; model.updatedAt = new Date(observedAt); } }); continue; } if (body.state === 'detached' && body.detachedBinding) { if (adoptedCompetingFirstWinner || replacementAttempted) { throw new ControllerSessionIdentityError( 'concurrent_change', 'A competing session binding transition won.', ); } const detachedBinding = await this.requireBindingForLocator( body, body.detachedBinding.bindingId, ); const detachedBindingBody = ControllerSessionRuntimeBindingModel.exact.toPersisted( detachedBinding, ); if ( detachedBindingBody.detachedAt === undefined || !datesEqual(detachedBindingBody.detachedAt, body.detachedBinding.detachedAt) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Detached locator does not match its historical binding.', ); } if ( observedAt.getTime() < body.detachedBinding.detachedAt.getTime() || observedAt.getTime() < body.updatedAt.getTime() ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session observation precedes its detachment state.', ); } replacementAttempted = true; const lastBindingId = body.detachedBinding.bindingId; current = await this.transitionLocator(current, (model) => { if ( model.state === 'detached' && model.detachedBinding?.bindingId === lastBindingId ) { model.state = 'binding'; model.pendingBinding = { ...bindingCandidate }; model.updatedAt = new Date(observedAt); } }); continue; } } throw new ControllerSessionIdentityError( 'concurrent_change', 'Session identity observation did not converge.', ); } private async admitManagedMembershipInScope( inputArg: IResolvedLocatorInput, observationArg: IControllerSessionIdentityObservation, generationFactsArg: IManagedSessionGenerationFacts, admissionSourceArg: TControllerManagedSessionAdmissionSource, managedAtArg: Date, ): Promise { const candidate: IControllerManagedSessionDocument = { id: controllerManagedSessionDocumentId( this.issuerId, inputArg.projectIdentityId, inputArg.runtimeId.harnessId, observationArg.identity.sessionIdentityId, ), issuerId: this.issuerId, projectIdentityId: inputArg.projectIdentityId, harnessId: inputArg.runtimeId.harnessId, runtimeId: { ...inputArg.runtimeId }, sessionIdentityId: observationArg.identity.sessionIdentityId, providerSessionGeneration: generationFactsArg.providerSessionGeneration, ...(generationFactsArg.codexOrigin ? { codexOrigin: structuredClone(generationFactsArg.codexOrigin) } : {}), ...(generationFactsArg.sessionGenerationId === undefined ? {} : { sessionGenerationId: generationFactsArg.sessionGenerationId }), ...(generationFactsArg.sessionGenerationSequence === undefined ? {} : { sessionGenerationSequence: generationFactsArg.sessionGenerationSequence }), state: 'active', managedAt: new Date(managedAtArg), admissionSource: admissionSourceArg, updateId: randomId(32), }; let stored: TStoredManagedSession | undefined; try { const result = await ControllerManagedSessionModel.exact.insert(candidate); stored = result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; stored = await this.readManagedSession( inputArg.projectIdentityId, inputArg.runtimeId.harnessId, observationArg.identity.sessionIdentityId, ); } if (!stored) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session admission has an ambiguous outcome.', ); } const membership = ControllerManagedSessionModel.exact.toPersisted(stored); this.assertManagedSessionScope( membership, inputArg.projectIdentityId, inputArg.runtimeId, observationArg.identity.sessionIdentityId, ); if ( membership.providerSessionGeneration !== generationFactsArg.providerSessionGeneration || !codexOriginsEqual(membership.codexOrigin, generationFactsArg.codexOrigin) || membership.sessionGenerationId !== generationFactsArg.sessionGenerationId || membership.sessionGenerationSequence !== generationFactsArg.sessionGenerationSequence ) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'Managed session membership belongs to another provider generation.', ); } if (membership.state === 'deleting') { throw new ControllerSessionIdentityError('deleting', 'The managed session is being deleted.'); } if (membership.state === 'retired') { throw new ControllerSessionIdentityError( 'tombstoned', 'The managed session membership is retired.', ); } return publicManagedObservation(observationArg, membership); } private resolveManagedLookupInput( inputArg: IRequireControllerManagedSessionInput, ): { input: IResolvedLocatorInput; supervisorGeneration: string; providerSessionGeneration: string | undefined; } { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.supervisorGeneration, 32)) { throw new ControllerSessionIdentityError( 'invalid_input', 'Supervisor generation is invalid.', ); } return { input, supervisorGeneration: inputArg.supervisorGeneration, providerSessionGeneration: requireProviderGeneration(inputArg.providerSessionGeneration), }; } private async resolveManagedSessionInScope( inputArg: IResolvedLocatorInput, supervisorGenerationArg: string, providerSessionGenerationArg: string | undefined, ): Promise { let current = await this.readLocator(inputArg.locatorId); if (!current) return { status: 'not_found' }; current = (await this.settleCoordinator(current)).stored; const locator = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(locator, inputArg); if (locator.state === 'deleting' || locator.state === 'completing') { throw new ControllerSessionIdentityError('deleting', 'The session is being deleted.'); } if (locator.state === 'tombstoned') { throw new ControllerSessionIdentityError( 'tombstoned', 'The session runtime locator is permanently tombstoned.', ); } if (locator.state !== 'attached' || !locator.activeBindingId) { return { status: 'not_found' }; } const observation = await this.observationFromAttached(locator); if (observation.binding.supervisorGeneration !== supervisorGenerationArg) { return { status: 'supervisor_generation_mismatch' }; } if ( providerSessionGenerationArg !== undefined && observation.binding.providerSessionGeneration !== providerSessionGenerationArg ) { return { status: 'provider_generation_mismatch' }; } const storedMembership = await this.readManagedSession( inputArg.projectIdentityId, inputArg.runtimeId.harnessId, observation.identity.sessionIdentityId, ); if (!storedMembership) return { status: 'not_found' }; const membership = ControllerManagedSessionModel.exact.toPersisted(storedMembership); this.assertManagedSessionScope( membership, inputArg.projectIdentityId, inputArg.runtimeId, observation.identity.sessionIdentityId, ); if (membership.providerSessionGeneration !== observation.binding.providerSessionGeneration) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Managed session membership generation differs from its immutable binding.', ); } if (membership.state === 'deleting') { throw new ControllerSessionIdentityError('deleting', 'The managed session is being deleted.'); } if (membership.state === 'retired') { throw new ControllerSessionIdentityError( 'tombstoned', 'The managed session membership is retired.', ); } return { status: 'managed', observation: publicManagedObservation(observation, membership), }; } private managedObservationFromLookupResult( resultArg: TManagedSessionLookupResult, ): IControllerSessionManagedObservation { if (resultArg.status === 'managed') return resultArg.observation; if (resultArg.status === 'provider_generation_mismatch') { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'The provider session generation does not match the active managed session.', ); } if (resultArg.status === 'supervisor_generation_mismatch') { throw new ControllerSessionIdentityError( 'concurrent_change', 'The supervisor generation is no longer current for the managed session.', ); } throw new ControllerSessionIdentityError('not_found', 'Managed session was not found.'); } private async requireManagedMembershipForLocator( inputArg: IResolvedLocatorInput, locatorArg: IControllerSessionLocatorDocument, ): Promise<{ stored: TStoredManagedSession; body: IControllerManagedSessionDocument; }> { this.assertLocatorScope(locatorArg, inputArg); const stored = await this.readManagedSession( inputArg.projectIdentityId, inputArg.runtimeId.harnessId, locatorArg.sessionIdentityId, ); if (!stored) { throw new ControllerSessionIdentityError('not_found', 'Managed session was not found.'); } const body = ControllerManagedSessionModel.exact.toPersisted(stored); this.assertManagedSessionScope( body, inputArg.projectIdentityId, inputArg.runtimeId, locatorArg.sessionIdentityId, ); return { stored, body }; } private async requireIdentityPendingManagedDeletion( inputArg: IResolvedLocatorInput, deletionArg: IControllerManagedSessionDeletion, ): Promise { const stored = await this.requireLocator(inputArg.locatorId); const locator = ControllerSessionLocatorModel.exact.toPersisted(stored); this.assertLocatorScope(locator, inputArg); if ( locator.state !== 'deleting' || locator.deletion?.operationId !== deletionArg.operationId || locator.deletion.finalBindingId !== deletionArg.expectedBindingId || locator.deletion.priorState !== 'attached' || !datesEqual(locator.deletion.startedAt, deletionArg.startedAt) ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The identity deletion does not match the managed deletion obligation.', ); } const binding = await this.requireBindingForLocator(locator, deletionArg.expectedBindingId); const bindingBody = ControllerSessionRuntimeBindingModel.exact.toPersisted(binding); if ( bindingBody.detachedAt !== undefined || bindingBody.supervisorGeneration !== deletionArg.supervisorGeneration || !providerGenerationsEqual( bindingBody.providerSessionGeneration, deletionArg.providerSessionGeneration, ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The managed deletion obligation does not match its identity binding.', ); } return locator; } private async requireAttachedIdentityForManagedDeletion( inputArg: IResolvedLocatorInput, deletionArg: IControllerManagedSessionDeletion, ): Promise { const stored = await this.requireLocator(inputArg.locatorId); const locator = ControllerSessionLocatorModel.exact.toPersisted(stored); this.assertLocatorScope(locator, inputArg); if ( locator.state !== 'attached' || locator.activeBindingId !== deletionArg.expectedBindingId || locator.deletion !== undefined ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The identity deletion did not restore the expected active binding.', ); } const observation = await this.observationFromAttached(locator); if ( observation.binding.supervisorGeneration !== deletionArg.supervisorGeneration || !providerGenerationsEqual( observation.binding.providerSessionGeneration, deletionArg.providerSessionGeneration, ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The restored identity binding does not match the managed deletion obligation.', ); } return observation; } private async settleIdentityCancellationForManagedDeletion( inputArg: IResolvedLocatorInput, deletionArg: IControllerManagedSessionDeletion, cancelledAtArg: Date, ): Promise { const stored = await this.requireLocator(inputArg.locatorId); const locator = ControllerSessionLocatorModel.exact.toPersisted(stored); this.assertLocatorScope(locator, inputArg); if ( locator.state === 'deleting' && locator.deletion?.operationId === deletionArg.operationId && locator.deletion.finalBindingId === deletionArg.expectedBindingId ) { await this.cancelSessionDeletionInScope( inputArg, deletionArg.operationId, cancelledAtArg, ); } else if ( locator.state !== 'attached' || locator.activeBindingId !== deletionArg.expectedBindingId || locator.deletion !== undefined ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The identity deletion cannot be cancelled for this managed obligation.', ); } return this.requireAttachedIdentityForManagedDeletion(inputArg, deletionArg); } public observeSession( inputArg: IObserveControllerSessionIdentityInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); const supervisorGeneration = inputArg.supervisorGeneration; if (!isBase64UrlBytes(supervisorGeneration, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Supervisor generation is invalid.', )); } const providerSessionGeneration = requireProviderGeneration( inputArg.providerSessionGeneration, ); const observedAt = requireDate(inputArg.observedAt, 'Session observation time'); return this.runScopedOperation( input.scopeKey, () => this.observeSessionInScope( input, supervisorGeneration, providerSessionGeneration, observedAt, false, inputArg.signal, ), ); } public admitManagedSession( inputArg: IAdmitControllerManagedSessionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.supervisorGeneration, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Supervisor generation is invalid.', )); } if ( inputArg.admissionSource !== 'controller-created' && inputArg.admissionSource !== 'explicit-enrollment' && inputArg.admissionSource !== 'project-folder-discovery' && inputArg.admissionSource !== 'legacy-state-migration' ) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session admission source is invalid.', )); } const generationFacts = requireManagedSessionGenerationFacts( input.runtimeId, inputArg.providerSessionGeneration, inputArg.sessionGenerationId, inputArg.sessionGenerationSequence, ); const managedAt = requireDate(inputArg.observedAt, 'Managed session admission time'); if (inputArg.codexOrigin !== undefined) { assertCodexOrigin(inputArg.codexOrigin); const origin = structuredClone(inputArg.codexOrigin); const qualified = codexQualifiedIdentity(input.runtimeId.nativeId); if (input.runtimeId.harnessId !== 'codex' || (qualified ? qualified.profileId !== origin.profileId || qualified.rawThreadId !== origin.rawThreadId : input.runtimeId.nativeId !== origin.rawThreadId)) throw new Error('Codex enrollment origin does not match the observed conversation.'); generationFacts.codexOrigin = origin; } return this.runScopedOperation(input.scopeKey, async () => { const observation = await this.observeSessionInScope( input, inputArg.supervisorGeneration, generationFacts.providerSessionGeneration, managedAt, false, inputArg.signal, ); return this.admitManagedMembershipInScope( input, observation, generationFacts, inputArg.admissionSource, managedAt, ); }); } public requireManagedSession( inputArg: IRequireControllerManagedSessionInput, ): Promise { const resolved = this.resolveManagedLookupInput(inputArg); return this.runScopedOperation(resolved.input.scopeKey, async () => { const result = await this.resolveManagedSessionInScope( resolved.input, resolved.supervisorGeneration, resolved.providerSessionGeneration, ); return this.managedObservationFromLookupResult(result); }); } public resolveManagedSession( inputArg: IRequireControllerManagedSessionInput, ): Promise { const resolved = this.resolveManagedLookupInput(inputArg); return this.runScopedOperation(resolved.input.scopeKey, async () => { const result = await this.resolveManagedSessionInScope( resolved.input, resolved.supervisorGeneration, resolved.providerSessionGeneration, ); return result.status === 'managed' ? result.observation : undefined; }); } private async resolveSessionLayoutAuthorityInScope( inputArg: IResolvedLocatorInput, signalArg?: AbortSignal, ): Promise { signalArg?.throwIfAborted(); const storedLocator = await this.readLocator(inputArg.locatorId, signalArg); signalArg?.throwIfAborted(); if (!storedLocator) return 'definitively_unmanaged'; const locator = ControllerSessionLocatorModel.exact.toPersisted(storedLocator); this.assertLocatorScope(locator, inputArg); if (locator.state === 'deleting' || locator.state === 'completing') { throw new ControllerSessionIdentityError( 'deleting', 'Session layout authority is pending deletion.', ); } if ( locator.state === 'initializing' || locator.state === 'binding' || locator.state === 'detaching' ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session layout authority is changing.', ); } const storedIdentity = await this.requireIdentityForLocator(locator, signalArg); const identity = ControllerSessionIdentityModel.exact.toPersisted(storedIdentity); if (locator.state === 'attached') { const storedBinding = await this.requireBindingForLocator( locator, locator.activeBindingId!, signalArg, ); const binding = ControllerSessionRuntimeBindingModel.exact.toPersisted(storedBinding); if (identity.retiredAt !== undefined || binding.detachedAt !== undefined) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Attached session layout authority has retired side records.', ); } } else if (locator.state === 'detached') { const storedBinding = await this.requireBindingForLocator( locator, locator.detachedBinding!.bindingId, signalArg, ); const binding = ControllerSessionRuntimeBindingModel.exact.toPersisted(storedBinding); if ( identity.retiredAt !== undefined || binding.detachedAt === undefined || !datesEqual(binding.detachedAt, locator.detachedBinding!.detachedAt) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Detached session layout authority has inconsistent side records.', ); } } else if (identity.retiredAt === undefined) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Tombstoned session layout authority retains an active identity.', ); } const storedMembership = await this.readManagedSession( inputArg.projectIdentityId, inputArg.runtimeId.harnessId, locator.sessionIdentityId, signalArg, ); signalArg?.throwIfAborted(); if (!storedMembership) return 'definitively_unmanaged'; const membership = ControllerManagedSessionModel.exact.toPersisted(storedMembership); this.assertManagedSessionScope( membership, inputArg.projectIdentityId, inputArg.runtimeId, locator.sessionIdentityId, ); if (membership.state === 'deleting') { throw new ControllerSessionIdentityError( 'deleting', 'Session layout membership is pending deletion.', ); } if (!providerGenerationsEqual( membership.providerSessionGeneration, locator.providerSessionGeneration, )) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session layout membership does not match the current provider generation.', ); } if (locator.state === 'tombstoned') { if (membership.state === 'retired') return 'definitively_unmanaged'; throw new ControllerSessionIdentityError( 'corrupt_state', 'A tombstoned session retains active layout membership.', ); } if (membership.state !== 'active') { throw new ControllerSessionIdentityError( 'corrupt_state', 'A stable session retains retired layout membership.', ); } return 'managed'; } public resolveSessionLayoutAuthority( inputArg: IResolveControllerSessionLayoutAuthorityInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); return this.runScopedOperation( input.scopeKey, () => this.resolveSessionLayoutAuthorityInScope(input, inputArg.signal), ); } /** DB-only terminal proof for one exact managed attachment identity. */ public resolveRetiredManagedSessionIdentity( inputArg: IResolveRetiredManagedSessionIdentityInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.sessionIdentityId, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session identity is invalid.', )); } const sessionIdentityId = inputArg.sessionIdentityId; return this.runScopedOperation(input.scopeKey, async () => { inputArg.signal?.throwIfAborted(); const storedMembership = await this.readManagedSession( input.projectIdentityId, input.runtimeId.harnessId, sessionIdentityId, inputArg.signal, ); if (!storedMembership) return false; const membership = ControllerManagedSessionModel.exact.toPersisted(storedMembership); this.assertManagedSessionScope( membership, input.projectIdentityId, input.runtimeId, sessionIdentityId, ); if (membership.state !== 'retired') return false; if (membership.deletion !== undefined || membership.retiredAt === undefined) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Retired managed session membership is not terminal.', ); } inputArg.signal?.throwIfAborted(); const storedIdentity = await ControllerSessionIdentityModel.exact.findStoredOne({ id: controllerSessionIdentityDocumentId(this.issuerId, sessionIdentityId), }, { signal: inputArg.signal }); if (!storedIdentity) return false; const identity = ControllerSessionIdentityModel.exact.toPersisted(storedIdentity); if ( identity.id !== controllerSessionIdentityDocumentId(this.issuerId, sessionIdentityId) || identity.issuerId !== this.issuerId || identity.projectIdentityId !== input.projectIdentityId || identity.sessionIdentityId !== sessionIdentityId ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Retired session identity does not match its managed membership scope.', ); } if (identity.retiredAt === undefined) return false; if ( identity.createdAt.getTime() > membership.managedAt.getTime() || !datesEqual(identity.retiredAt, membership.retiredAt) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Retired managed session identity times are inconsistent.', ); } inputArg.signal?.throwIfAborted(); const storedLocator = await ControllerSessionLocatorModel.exact.findStoredOne({ id: input.locatorId, }, { signal: inputArg.signal }); if (!storedLocator) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Retired managed session locator is missing.', ); } const locator = ControllerSessionLocatorModel.exact.toPersisted(storedLocator); this.assertLocatorScope(locator, input); if (locator.sessionIdentityId !== sessionIdentityId) { if ( locator.identityCreatedAt.getTime() < membership.retiredAt.getTime() || locator.providerSessionGeneration === membership.providerSessionGeneration ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Replacement session locator is inconsistent with the retired identity.', ); } return true; } if (locator.state !== 'tombstoned' || locator.deletion?.completedAt === undefined) { return false; } if ( !datesEqual(locator.identityCreatedAt, identity.createdAt) || locator.providerSessionGeneration !== membership.providerSessionGeneration || !datesEqual(locator.deletion.completedAt, membership.retiredAt) || !datesEqual(locator.updatedAt, membership.retiredAt) || locator.deletion.startedAt.getTime() < membership.managedAt.getTime() ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Retired managed session tombstone is inconsistent with canonical retirement.', ); } inputArg.signal?.throwIfAborted(); const storedBinding = await ControllerSessionRuntimeBindingModel.exact.findStoredOne({ id: locator.deletion.finalBindingId, }, { signal: inputArg.signal }); if (!storedBinding) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Retired managed session tombstone binding is missing.', ); } const binding = ControllerSessionRuntimeBindingModel.exact.toPersisted(storedBinding); if ( binding.id !== locator.deletion.finalBindingId || binding.bindingId !== locator.deletion.finalBindingId || binding.issuerId !== this.issuerId || binding.projectIdentityId !== input.projectIdentityId || binding.sessionIdentityId !== sessionIdentityId || !runtimeIdsEqual(binding.runtimeId, input.runtimeId) || binding.providerSessionGeneration !== membership.providerSessionGeneration || binding.attachedAt.getTime() > locator.deletion.startedAt.getTime() || binding.detachedAt === undefined || !datesEqual(binding.detachedAt, this.finalDetachedAt(locator.deletion)) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Retired managed session tombstone binding is inconsistent.', ); } return true; }).catch((errorArg) => { if ( errorArg instanceof plugins.smartdata.SmartdataExactPersistenceError && ( errorArg.code === 'invalid_document' || errorArg.code === 'noncanonical_document' || errorArg.code === 'reserved_field' ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The retired managed session proof contains a corrupt persisted document.', { cause: errorArg }, ); } throw errorArg; }); } private async hasDispatchedFlexCleanupAuthority( projectIdentityIdArg: string, entryArg: Pick, signalArg?: AbortSignal, ): Promise { const stored = await ControllerManagedSessionModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: projectIdentityIdArg, harnessId: 'flex', state: 'deleting', }, sort: { id: 1 }, limit: controllerFlexCleanupCohortLimit + 1, signal: signalArg, }); if (stored.length > controllerFlexCleanupCohortLimit) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The deleting Flex managed-session obligation limit was exceeded.', ); } let matched = false; for (const document of stored) { const body = ControllerManagedSessionModel.exact.toPersisted(document); this.assertManagedSessionScope( body, projectIdentityIdArg, body.runtimeId, body.sessionIdentityId, ); const deletion = body.deletion; if ( !deletion || deletion.dispatchStartedAt === undefined || deletion.flexCleanupCohort === undefined ) continue; if (!deletion.flexCleanupCohort.some((candidate) => ( candidate.sessionId === entryArg.sessionId && candidate.providerSessionGeneration === entryArg.providerSessionGeneration ))) continue; if (matched) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Multiple managed deletions claim the same Flex cleanup generation.', ); } matched = true; } return matched; } /** DB-only callback authority lookup; it never calls a provider or controller runtime. */ public resolveFlexHostSessionAuthority( inputArg: IResolveControllerFlexHostSessionAuthorityInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (input.runtimeId.harnessId !== 'flex') { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex host authority requires a Flex runtime ID.', )); } const providerSessionGeneration = requireProviderGeneration( inputArg.providerSessionGeneration, ); if (providerSessionGeneration === undefined) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex host authority requires an exact provider generation.', )); } return this.runScopedOperation(input.scopeKey, async () => { inputArg.signal?.throwIfAborted(); if (await this.hasDispatchedFlexCleanupAuthority(input.projectIdentityId, { sessionId: input.runtimeId.nativeId, providerSessionGeneration, }, inputArg.signal)) return 'deleting_cleanup'; const stored = await this.readLocator(input.locatorId); if (!stored) return 'definitively_unmanaged'; const locator = ControllerSessionLocatorModel.exact.toPersisted(stored); this.assertLocatorScope(locator, input); if ( locator.state === 'initializing' || locator.state === 'binding' || locator.state === 'detaching' || locator.state === 'deleting' || locator.state === 'completing' || locator.bindingCleanup !== undefined || locator.pendingBinding !== undefined ) return 'uncertain'; if ( locator.state !== 'attached' || !locator.activeBindingId || locator.providerSessionGeneration !== providerSessionGeneration ) return 'definitively_unmanaged'; const observation = await this.observationFromAttached(locator); if (observation.binding.providerSessionGeneration !== providerSessionGeneration) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The attached Flex binding generation differs from its locator.', ); } const storedMembership = await this.readManagedSession( input.projectIdentityId, 'flex', observation.identity.sessionIdentityId, inputArg.signal, ); if (!storedMembership) return 'definitively_unmanaged'; const membership = ControllerManagedSessionModel.exact.toPersisted(storedMembership); this.assertManagedSessionScope( membership, input.projectIdentityId, input.runtimeId, observation.identity.sessionIdentityId, ); if (membership.providerSessionGeneration !== providerSessionGeneration) { return 'definitively_unmanaged'; } if (membership.state === 'active') return 'active'; if (membership.state === 'retired') return 'definitively_unmanaged'; return 'uncertain'; }); } public beginManagedSessionDeletion( inputArg: IBeginControllerManagedSessionDeletionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.supervisorGeneration, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Supervisor generation is invalid.', )); } const providerSessionGeneration = requireProviderGeneration( inputArg.providerSessionGeneration, ); if (providerSessionGeneration === undefined) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion requires an exact provider generation.', )); } let flexCleanupCohort: IControllerFlexCleanupEntry[] | undefined; if (input.runtimeId.harnessId === 'flex') { if (inputArg.flexCleanupCohort === undefined) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex managed deletion requires an exact cleanup cohort.', )); } try { flexCleanupCohort = cloneControllerFlexCleanupCohort(inputArg.flexCleanupCohort); } catch (errorArg) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex managed deletion cleanup cohort is invalid.', { cause: errorArg }, )); } if (flexCleanupCohort.length === 0) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex managed deletion cleanup cohort cannot be empty.', )); } const cleanupRoots = flexCleanupCohort.filter((entry) => entry.cleanupRoot); if ( cleanupRoots.length !== 1 || cleanupRoots[0].sessionId !== input.runtimeId.nativeId || cleanupRoots[0].providerSessionGeneration !== providerSessionGeneration ) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex managed deletion requires one exact cleanup root.', )); } } else if (inputArg.flexCleanupCohort !== undefined) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'OpenCode managed deletion cannot carry a Flex cleanup cohort.', )); } if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion operation ID is invalid.', )); } const startedAt = requireDate(inputArg.startedAt, 'Managed session deletion start time'); return this.runScopedOperation(input.scopeKey, async () => { let locatorStored = await this.requireLocator(input.locatorId); locatorStored = (await this.settleCoordinator(locatorStored)).stored; const locator = ControllerSessionLocatorModel.exact.toPersisted(locatorStored); const membership = await this.requireManagedMembershipForLocator(input, locator); let membershipStored = membership.stored; let membershipBody = membership.body; if (membershipBody.providerSessionGeneration !== providerSessionGeneration) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'Managed session deletion belongs to another admitted provider generation.', ); } if (input.runtimeId.harnessId === 'flex') { const cleanupRoot = flexCleanupCohort!.find((entry) => entry.cleanupRoot)!; if ( cleanupRoot.sessionGenerationId !== membershipBody.sessionGenerationId || cleanupRoot.sessionGenerationSequence !== membershipBody.sessionGenerationSequence ) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'Flex managed deletion root does not match the admitted raw generation.', ); } } let deletion: IControllerManagedSessionDeletion; if (membershipBody.state === 'active') { if (locator.state !== 'attached' || !locator.activeBindingId) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The active managed session identity is no longer attached.', ); } const observation = await this.observationFromAttached(locator); if (observation.binding.supervisorGeneration !== inputArg.supervisorGeneration) { throw new ControllerSessionIdentityError( 'concurrent_change', 'The supervisor generation is no longer current for managed deletion.', ); } if (!providerGenerationsEqual( observation.binding.providerSessionGeneration, providerSessionGeneration, )) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'The provider generation is no longer current for managed deletion.', ); } if (startedAt.getTime() < membershipBody.managedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion precedes admission.', ); } deletion = { operationId: inputArg.operationId, expectedBindingId: observation.binding.bindingId, supervisorGeneration: inputArg.supervisorGeneration, providerSessionGeneration, ...(flexCleanupCohort === undefined ? {} : { flexCleanupCohort: cloneControllerFlexCleanupCohort(flexCleanupCohort) }), startedAt: new Date(startedAt), }; membershipStored = await this.transitionManagedSessionDocument( membershipStored, (model) => { model.state = 'deleting'; model.deletion = structuredClone(deletion); }, (document) => document.state === 'deleting' && document.deletion !== undefined && managedDeletionFactsEqual(document.deletion, deletion), 'Managed session deletion admission changed concurrently.', true, ); membershipBody = ControllerManagedSessionModel.exact.toPersisted(membershipStored); } else if (membershipBody.state === 'deleting' && membershipBody.deletion) { deletion = membershipBody.deletion; const expectedFacts: IControllerManagedSessionDeletion = { ...deletion, operationId: inputArg.operationId, supervisorGeneration: inputArg.supervisorGeneration, providerSessionGeneration, ...(flexCleanupCohort === undefined ? { flexCleanupCohort: undefined } : { flexCleanupCohort: cloneControllerFlexCleanupCohort(flexCleanupCohort) }), startedAt: new Date(startedAt), }; if (!managedDeletionFactsEqual(deletion, expectedFacts)) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Another managed session deletion operation is already active.', ); } } else { throw new ControllerSessionIdentityError( membershipBody.state === 'retired' ? 'tombstoned' : 'concurrent_change', 'The managed session cannot begin deletion.', ); } await this.beginSessionDeletionInScope( input, deletion.expectedBindingId, deletion.operationId, deletion.startedAt, ); await this.requireIdentityPendingManagedDeletion(input, deletion); return publicManagedDeletionObligation(membershipBody, deletion); }); } public markManagedSessionDeletionDispatched( inputArg: IMarkControllerManagedSessionDeletionDispatchedInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion operation ID is invalid.', )); } const dispatchStartedAt = requireDate( inputArg.dispatchStartedAt, 'Managed session deletion dispatch time', ); return this.runScopedOperation(input.scopeKey, async () => { const locatorStored = await this.requireLocator(input.locatorId); const locator = ControllerSessionLocatorModel.exact.toPersisted(locatorStored); const membership = await this.requireManagedMembershipForLocator(input, locator); if ( membership.body.state !== 'deleting' || !membership.body.deletion || membership.body.deletion.operationId !== inputArg.operationId ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session deletion dispatch does not match the active obligation.', ); } const deletion = membership.body.deletion; if (dispatchStartedAt.getTime() < deletion.startedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion dispatch precedes admission.', ); } await this.requireIdentityPendingManagedDeletion(input, deletion); if (deletion.dispatchStartedAt !== undefined) { if (!datesEqual(deletion.dispatchStartedAt, dispatchStartedAt)) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session deletion was dispatched at a different time.', ); } return publicManagedDeletionObligation(membership.body, deletion); } const markedDeletion: IControllerManagedSessionDeletion = { ...deletion, dispatchStartedAt: new Date(dispatchStartedAt), }; const transitioned = await this.transitionManagedSessionDocument( membership.stored, (model) => { model.deletion = structuredClone(markedDeletion); }, (document) => document.state === 'deleting' && document.deletion !== undefined && managedDeletionFactsEqual(document.deletion, markedDeletion), 'Managed session deletion dispatch changed concurrently.', true, ); const body = ControllerManagedSessionModel.exact.toPersisted(transitioned); return publicManagedDeletionObligation(body, body.deletion!); }); } public cancelManagedSessionDeletion( inputArg: ICancelControllerManagedSessionDeletionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion operation ID is invalid.', )); } const cancelledAt = requireDate( inputArg.cancelledAt, 'Managed session deletion cancellation time', ); return this.runScopedOperation(input.scopeKey, async () => { const locatorStored = await this.requireLocator(input.locatorId); const locator = ControllerSessionLocatorModel.exact.toPersisted(locatorStored); const membership = await this.requireManagedMembershipForLocator(input, locator); if ( membership.body.state !== 'deleting' || !membership.body.deletion || membership.body.deletion.operationId !== inputArg.operationId ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session deletion cancellation does not match the active obligation.', ); } const deletion = membership.body.deletion; if (deletion.dispatchStartedAt !== undefined) { throw new ControllerSessionIdentityError( 'concurrent_change', 'A dispatched managed session deletion cannot be cancelled.', ); } if (cancelledAt.getTime() < deletion.startedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion cancellation precedes admission.', ); } const observation = await this.settleIdentityCancellationForManagedDeletion( input, deletion, cancelledAt, ); const transitioned = await this.transitionManagedSessionDocument( membership.stored, (model) => { model.state = 'active'; delete model.deletion; }, (document) => document.state === 'active' && document.deletion === undefined && document.retiredAt === undefined, 'Managed session deletion cancellation changed concurrently.', ); const body = ControllerManagedSessionModel.exact.toPersisted(transitioned); return publicManagedObservation(observation, body); }); } public completeManagedSessionDeletion( inputArg: ICompleteControllerManagedSessionDeletionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session deletion operation ID is invalid.', )); } const requestedRetiredAt = requireDate(inputArg.retiredAt, 'Managed session retirement time'); return this.runScopedOperation(input.scopeKey, async () => { const locatorStored = await this.requireLocator(input.locatorId); const locator = ControllerSessionLocatorModel.exact.toPersisted(locatorStored); const membership = await this.requireManagedMembershipForLocator(input, locator); if ( (locator.state !== 'deleting' && locator.state !== 'completing' && locator.state !== 'tombstoned') || locator.deletion?.operationId !== inputArg.operationId ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Identity deletion does not match managed completion.', ); } let dispatchStartedAt: Date | undefined; if (membership.body.state === 'deleting' && membership.body.deletion) { const deletion = membership.body.deletion; if ( deletion.operationId !== inputArg.operationId || deletion.expectedBindingId !== locator.deletion.finalBindingId || deletion.dispatchStartedAt === undefined ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session deletion is not dispatch-complete.', ); } dispatchStartedAt = deletion.dispatchStartedAt; if ( locator.deletion.completedAt === undefined && ( requestedRetiredAt.getTime() < deletion.dispatchStartedAt.getTime() || requestedRetiredAt.getTime() < membership.body.managedAt.getTime() ) ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Managed session retirement precedes deletion dispatch.', ); } } else if ( membership.body.state !== 'retired' || membership.body.retiredAt === undefined ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session deletion can no longer be completed.', ); } await this.completeSessionDeletionInScope( input, inputArg.operationId, locator.deletion.completedAt ?? requestedRetiredAt, ); const completedLocator = ControllerSessionLocatorModel.exact.toPersisted( await this.requireLocator(input.locatorId), ); this.assertLocatorScope(completedLocator, input); const canonicalRetiredAt = completedLocator.deletion?.completedAt; if ( completedLocator.state !== 'tombstoned' || completedLocator.deletion?.operationId !== inputArg.operationId || canonicalRetiredAt === undefined ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Completed identity deletion did not retain its canonical completion time.', ); } if ( canonicalRetiredAt.getTime() < membership.body.managedAt.getTime() || ( dispatchStartedAt !== undefined && canonicalRetiredAt.getTime() < dispatchStartedAt.getTime() ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Canonical identity deletion completion precedes managed deletion authority.', ); } if (membership.body.state === 'deleting') { await this.transitionManagedSessionDocument( membership.stored, (model) => { model.state = 'retired'; delete model.deletion; model.retiredAt = new Date(canonicalRetiredAt); }, (document) => document.state === 'retired' && document.deletion === undefined && document.retiredAt !== undefined && datesEqual(document.retiredAt, canonicalRetiredAt), 'Managed session retirement changed concurrently.', ); } else if (!datesEqual(membership.body.retiredAt!, canonicalRetiredAt)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Managed session retirement differs from canonical identity completion.', ); } }); } public listManagedSessionDeletionObligations( inputArg: IListControllerManagedSessionDeletionObligationsInput, ): Promise { return this.runProjectHarnessScopesOperation( inputArg.projectIdentityId, inputArg.harnessId, async () => { const stored = await this.readManagedSessionStatePages( inputArg.projectIdentityId, inputArg.harnessId, ['deleting'], inputArg.signal, ); return stored.map((entry) => { const body = ControllerManagedSessionModel.exact.toPersisted(entry); if (!body.deletion) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Deleting managed session has no deletion obligation.', ); } return publicManagedDeletionObligation(body, body.deletion); }); }, ); } public listFlexManagedCleanupRoots( inputArg: IListControllerFlexManagedCleanupRootsInput, ): Promise { return this.runProjectHarnessScopesOperation( inputArg.projectIdentityId, 'flex', async () => { const stored = await this.readManagedSessionStatePages( inputArg.projectIdentityId, 'flex', ['active', 'deleting'], inputArg.signal, ); const resolvedRoots: IControllerFlexCleanupEntry[] = []; for (const entry of stored) { const body = ControllerManagedSessionModel.exact.toPersisted(entry); if ( body.sessionGenerationId === undefined || body.sessionGenerationSequence === undefined ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A managed Flex root has no retained raw generation.', ); } const root: IControllerFlexCleanupEntry = { sessionId: body.runtimeId.nativeId, sessionGenerationId: body.sessionGenerationId, sessionGenerationSequence: body.sessionGenerationSequence, providerSessionGeneration: body.providerSessionGeneration, cleanupRoot: true, }; if (body.state === 'deleting') { resolvedRoots.push(root); continue; } const locatorInput = this.resolveLocatorInput( inputArg.projectIdentityId, body.runtimeId, ); const storedLocator = await this.readLocator(locatorInput.locatorId); if (!storedLocator) continue; const locator = ControllerSessionLocatorModel.exact.toPersisted(storedLocator); this.assertLocatorScope(locator, locatorInput); if ( locator.state !== 'attached' || !locator.activeBindingId || locator.sessionIdentityId !== body.sessionIdentityId || locator.providerSessionGeneration !== body.providerSessionGeneration ) continue; const observation = await this.observationFromAttached(locator); if ( observation.identity.sessionIdentityId !== body.sessionIdentityId || observation.binding.providerSessionGeneration !== body.providerSessionGeneration ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'An active managed Flex root differs from its retained generation.', ); } resolvedRoots.push(root); } resolvedRoots.sort((left, right) => compareCodeUnits(left.sessionId, right.sessionId)); assertControllerFlexCleanupCohort(resolvedRoots); return cloneControllerFlexCleanupCohort(resolvedRoots); }, ); } public retireProjectManagedSessions( inputArg: IRetireControllerProjectManagedSessionsInput, ): Promise { const retiredAt = requireDate(inputArg.retiredAt, 'Project managed session retirement time'); return this.runProjectHarnessScopesOperation( inputArg.projectIdentityId, undefined, async () => { const stored = await this.readManagedSessionStatePages( inputArg.projectIdentityId, undefined, ['active', 'deleting'], inputArg.signal, ); const unresolved: IControllerManagedSessionDeletionObligation[] = []; for (const entry of stored) { inputArg.signal?.throwIfAborted(); const body = ControllerManagedSessionModel.exact.toPersisted(entry); if (retiredAt.getTime() < body.managedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Project session retirement precedes managed admission.', ); } if (body.state === 'deleting' && !body.deletion) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Deleting project managed session has no deletion obligation.', ); } if (body.runtimeId.harnessId !== 'flex') { const locatorInput = this.resolveLocatorInput( inputArg.projectIdentityId, body.runtimeId, ); let locatorStored = await this.requireLocator(locatorInput.locatorId); locatorStored = (await this.settleCoordinator(locatorStored)).stored; let locator = ControllerSessionLocatorModel.exact.toPersisted(locatorStored); this.assertLocatorScope(locator, locatorInput); if ( locator.sessionIdentityId !== body.sessionIdentityId || locator.providerSessionGeneration !== body.providerSessionGeneration ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Managed provider project membership differs from its stable identity state.', ); } if (body.state === 'deleting') { const deletion = body.deletion!; if (retiredAt.getTime() < deletion.startedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Project session retirement precedes deletion admission.', ); } const binding = ControllerSessionRuntimeBindingModel.exact.toPersisted( await this.requireBindingForLocator(locator, deletion.expectedBindingId), ); if ( binding.supervisorGeneration !== deletion.supervisorGeneration || binding.providerSessionGeneration !== deletion.providerSessionGeneration ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Managed provider project deletion differs from its immutable binding.', ); } await this.beginSessionDeletionInScope( locatorInput, deletion.expectedBindingId, deletion.operationId, deletion.startedAt, ); locator = ControllerSessionLocatorModel.exact.toPersisted( await this.requireLocator(locatorInput.locatorId), ); if (locator.state === 'deleting') { await this.requireIdentityPendingManagedDeletion(locatorInput, deletion); } else if ( locator.state !== 'tombstoned' || locator.deletion?.operationId !== deletion.operationId || locator.deletion.finalBindingId !== deletion.expectedBindingId || locator.deletion.priorState !== 'attached' || !datesEqual(locator.deletion.startedAt, deletion.startedAt) || deletion.dispatchStartedAt === undefined ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed provider project deletion is not crash-recoverable.', ); } unresolved.push(publicManagedDeletionObligation(body, deletion)); continue; } if (locator.state === 'attached' && locator.activeBindingId) { const observation = await this.observationFromAttached(locator); if ( observation.identity.sessionIdentityId !== body.sessionIdentityId || observation.binding.providerSessionGeneration !== body.providerSessionGeneration ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Attached managed provider project membership differs from its binding.', ); } const deletion: IControllerManagedSessionDeletion = { operationId: randomId(24), expectedBindingId: observation.binding.bindingId, supervisorGeneration: observation.binding.supervisorGeneration, providerSessionGeneration: body.providerSessionGeneration, startedAt: new Date(retiredAt), }; const transitioned = await this.transitionManagedSessionDocument( entry, (model) => { model.state = 'deleting'; model.deletion = structuredClone(deletion); }, (document) => document.state === 'deleting' && document.deletion !== undefined && managedDeletionFactsEqual(document.deletion, deletion), 'Managed provider project deletion admission changed concurrently.', true, ); await this.beginSessionDeletionInScope( locatorInput, deletion.expectedBindingId, deletion.operationId, deletion.startedAt, ); await this.requireIdentityPendingManagedDeletion(locatorInput, deletion); unresolved.push(publicManagedDeletionObligation( ControllerManagedSessionModel.exact.toPersisted(transitioned), deletion, )); continue; } if (locator.state === 'detached' && locator.detachedBinding) { const detachedBinding = ControllerSessionRuntimeBindingModel.exact.toPersisted( await this.requireBindingForLocator(locator, locator.detachedBinding.bindingId), ); if ( detachedBinding.detachedAt === undefined || !datesEqual(detachedBinding.detachedAt, locator.detachedBinding.detachedAt) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Detached managed provider project identity is not stable.', ); } } else if (locator.state === 'tombstoned') { await this.verifyTombstoneSideRecords(locator); } else { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed provider project identity is not stably present or absent.', ); } } else if (body.state === 'deleting' && body.deletion?.dispatchStartedAt !== undefined) { unresolved.push(publicManagedDeletionObligation(body, body.deletion)); continue; } else if (body.state === 'deleting' && body.deletion) { if (retiredAt.getTime() < body.deletion.startedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Project session retirement precedes deletion admission.', ); } const locatorInput = this.resolveLocatorInput( inputArg.projectIdentityId, body.runtimeId, ); await this.settleIdentityCancellationForManagedDeletion( locatorInput, body.deletion, retiredAt, ); } await this.transitionManagedSessionDocument( entry, (model) => { model.state = 'retired'; delete model.deletion; model.retiredAt = new Date(retiredAt); }, (document) => document.state === 'retired' && document.deletion === undefined && document.retiredAt !== undefined && datesEqual(document.retiredAt, retiredAt), 'Project managed session retirement changed concurrently.', ); } return unresolved; }, ); } public beginManagedSessionCreation( inputArg: IBeginControllerManagedSessionCreationInput, ): Promise { if (inputArg.runtimeId?.harnessId === 'codex') { return Promise.reject(new Error('Codex requires a server-assigned creation intent.')); } const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session creation operation ID is invalid.', )); } let expectedFlexSessionGenerationId: string | undefined; if (input.runtimeId.harnessId === 'flex') { try { assertControllerFlexSessionGenerationId(inputArg.expectedFlexSessionGenerationId); expectedFlexSessionGenerationId = inputArg.expectedFlexSessionGenerationId; } catch (errorArg) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Pending Flex creation requires an expected session generation ID.', { cause: errorArg }, )); } } else if (inputArg.expectedFlexSessionGenerationId !== undefined) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Pending OpenCode creation cannot carry a Flex generation ID.', )); } const requestedAt = requireDate(inputArg.requestedAt, 'Managed session creation request time'); return this.runScopedOperation(input.scopeKey, async () => { const candidate: IControllerSessionCreationObligationDocument = { id: controllerSessionCreationObligationDocumentId( this.issuerId, input.projectIdentityId, input.runtimeId, ), issuerId: this.issuerId, projectIdentityId: input.projectIdentityId, runtimeId: { ...input.runtimeId }, operationId: inputArg.operationId, state: 'pending', requestedAt: new Date(requestedAt), updateId: randomId(32), ...(expectedFlexSessionGenerationId === undefined ? {} : { expectedFlexSessionGenerationId }), }; let stored: TStoredSessionCreationObligation | undefined; try { const result = await ControllerSessionCreationObligationModel.exact.insert(candidate); stored = result.document; } catch (errorArg) { if (!isAmbiguousWrite(errorArg)) throw errorArg; stored = await this.readSessionCreationObligation( input.projectIdentityId, input.runtimeId, ); } if (!stored) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Managed session creation admission has an ambiguous outcome.', ); } const body = ControllerSessionCreationObligationModel.exact.toPersisted(stored); this.assertSessionCreationObligationScope(body, input.projectIdentityId, input.runtimeId); if ( body.state !== 'pending' || body.operationId !== inputArg.operationId || !datesEqual(body.requestedAt, requestedAt) || body.expectedFlexSessionGenerationId !== expectedFlexSessionGenerationId ) { throw new ControllerSessionIdentityError( body.state === 'retired' ? 'tombstoned' : 'concurrent_change', 'The runtime already has another or terminal session creation obligation.', ); } return publicCreationObligation(body); }); } public markManagedSessionCreationDispatched( inputArg: IMarkControllerManagedSessionCreationDispatchedInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session creation operation ID is invalid.', )); } const dispatchStartedAt = requireDate( inputArg.dispatchStartedAt, 'Managed session creation dispatch time', ); return this.runScopedOperation(input.scopeKey, async () => { const stored = await this.readSessionCreationObligation( input.projectIdentityId, input.runtimeId, ); if (!stored) { throw new ControllerSessionIdentityError( 'not_found', 'Session creation obligation was not found.', ); } const body = ControllerSessionCreationObligationModel.exact.toPersisted(stored); this.assertSessionCreationObligationScope(body, input.projectIdentityId, input.runtimeId); if (body.state !== 'pending' || body.operationId !== inputArg.operationId) { throw new ControllerSessionIdentityError( body.state === 'retired' ? 'tombstoned' : 'concurrent_change', 'Session creation dispatch does not match the pending obligation.', ); } if (dispatchStartedAt.getTime() < body.requestedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session creation dispatch precedes its request.', ); } if (body.dispatchStartedAt !== undefined) { if (!datesEqual(body.dispatchStartedAt, dispatchStartedAt)) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session creation was dispatched at a different time.', ); } return publicCreationObligation(body); } const transitioned = await this.transitionSessionCreationObligationDocument( stored, (model) => { model.dispatchStartedAt = new Date(dispatchStartedAt); }, (document) => document.state === 'pending' && document.operationId === inputArg.operationId && document.dispatchStartedAt !== undefined && datesEqual(document.dispatchStartedAt, dispatchStartedAt), 'Session creation dispatch changed concurrently.', ); return publicCreationObligation( ControllerSessionCreationObligationModel.exact.toPersisted(transitioned), ); }); } public completeManagedSessionCreationAdmission( inputArg: ICompleteControllerManagedSessionCreationAdmissionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session creation operation ID is invalid.', )); } if (!isBase64UrlBytes(inputArg.supervisorGeneration, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Supervisor generation is invalid.', )); } const generationFacts = requireManagedSessionGenerationFacts( input.runtimeId, inputArg.providerSessionGeneration, inputArg.sessionGenerationId, inputArg.sessionGenerationSequence, ); const providerSessionGeneration = generationFacts.providerSessionGeneration; const terminalAt = requireDate( inputArg.terminalAt, 'Managed session creation admission time', ); return this.runScopedOperation(input.scopeKey, async () => { const stored = await this.readSessionCreationObligation( input.projectIdentityId, input.runtimeId, ); if (!stored) { throw new ControllerSessionIdentityError( 'not_found', 'Session creation obligation was not found.', ); } const body = ControllerSessionCreationObligationModel.exact.toPersisted(stored); this.assertSessionCreationObligationScope(body, input.projectIdentityId, input.runtimeId); if (body.operationId !== inputArg.operationId) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session creation admission belongs to another operation.', ); } if (body.state === 'retired') { throw new ControllerSessionIdentityError( 'tombstoned', 'The session creation obligation is retired.', ); } if (body.state === 'admitted') { if ( body.providerSessionGeneration !== providerSessionGeneration || body.terminalAt === undefined || !datesEqual(body.terminalAt, terminalAt) || body.sessionIdentityId === undefined ) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session creation was admitted with different terminal facts.', ); } const result = await this.resolveManagedSessionInScope( input, inputArg.supervisorGeneration, providerSessionGeneration, ); const observation = this.managedObservationFromLookupResult(result); if (observation.identity.sessionIdentityId !== body.sessionIdentityId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Admitted creation obligation does not match managed membership.', ); } return observation; } if ( body.dispatchStartedAt === undefined || terminalAt.getTime() < body.dispatchStartedAt.getTime() ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session creation admission requires a completed dispatch.', ); } if ( input.runtimeId.harnessId === 'flex' && body.expectedFlexSessionGenerationId !== generationFacts.sessionGenerationId ) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'Pending Flex creation obligation observed another generation ID.', ); } const identityObservation = await this.observeSessionInScope( input, inputArg.supervisorGeneration, providerSessionGeneration, terminalAt, false, inputArg.signal, ); const managedObservation = await this.admitManagedMembershipInScope( input, identityObservation, generationFacts, 'controller-created', terminalAt, ); const sessionIdentityId = managedObservation.identity.sessionIdentityId; const transitioned = await this.transitionSessionCreationObligationDocument( stored, (model) => { model.state = 'admitted'; delete model.expectedFlexSessionGenerationId; model.providerSessionGeneration = providerSessionGeneration; model.sessionIdentityId = sessionIdentityId; model.terminalAt = new Date(terminalAt); }, (document) => document.state === 'admitted' && document.operationId === inputArg.operationId && document.expectedFlexSessionGenerationId === undefined && document.providerSessionGeneration === providerSessionGeneration && document.sessionIdentityId === sessionIdentityId && document.terminalAt !== undefined && datesEqual(document.terminalAt, terminalAt), 'Session creation admission changed concurrently.', ); const admitted = ControllerSessionCreationObligationModel.exact.toPersisted(transitioned); if (admitted.sessionIdentityId !== sessionIdentityId) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Another session identity won creation admission.', ); } return managedObservation; }); } public retireManagedSessionCreation( inputArg: IRetireControllerManagedSessionCreationInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Managed session creation operation ID is invalid.', )); } const terminalAt = requireDate( inputArg.terminalAt, 'Managed session creation retirement time', ); return this.runScopedOperation(input.scopeKey, async () => { const stored = await this.readSessionCreationObligation( input.projectIdentityId, input.runtimeId, ); if (!stored) { throw new ControllerSessionIdentityError( 'not_found', 'Session creation obligation was not found.', ); } const body = ControllerSessionCreationObligationModel.exact.toPersisted(stored); this.assertSessionCreationObligationScope(body, input.projectIdentityId, input.runtimeId); if (body.operationId !== inputArg.operationId) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session creation retirement belongs to another operation.', ); } if (body.state === 'admitted') { throw new ControllerSessionIdentityError( 'concurrent_change', 'An admitted session creation obligation cannot be retired as absent.', ); } if (body.state === 'retired') { if (body.terminalAt === undefined || !datesEqual(body.terminalAt, terminalAt)) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session creation was retired at a different time.', ); } return publicCreationObligation(body); } if ( terminalAt.getTime() < body.requestedAt.getTime() || ( body.dispatchStartedAt !== undefined && terminalAt.getTime() < body.dispatchStartedAt.getTime() ) ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session creation retirement precedes its durable obligation.', ); } const transitioned = await this.transitionSessionCreationObligationDocument( stored, (model) => { model.state = 'retired'; delete model.expectedFlexSessionGenerationId; delete model.providerSessionGeneration; delete model.sessionIdentityId; model.terminalAt = new Date(terminalAt); }, (document) => document.state === 'retired' && document.operationId === inputArg.operationId && document.expectedFlexSessionGenerationId === undefined && document.providerSessionGeneration === undefined && document.sessionIdentityId === undefined && document.terminalAt !== undefined && datesEqual(document.terminalAt, terminalAt), 'Session creation retirement changed concurrently.', ); return publicCreationObligation( ControllerSessionCreationObligationModel.exact.toPersisted(transitioned), ); }); } public listPendingSessionCreationObligations( inputArg: IListControllerSessionCreationObligationsInput, ): Promise { return this.runProjectHarnessScopesOperation( inputArg.projectIdentityId, inputArg.harnessId, async () => { const stored = await this.readSessionCreationObligationStatePages( inputArg.projectIdentityId, inputArg.harnessId, ['pending'], inputArg.signal, ); return stored.map((entry) => publicCreationObligation( ControllerSessionCreationObligationModel.exact.toPersisted(entry), )); }, ); } public getSessionCreationObligation( inputArg: IGetControllerSessionCreationObligationInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); return this.runScopedOperation(input.scopeKey, async () => { const stored = await this.readSessionCreationObligation( input.projectIdentityId, input.runtimeId, ); if (!stored) return undefined; const body = ControllerSessionCreationObligationModel.exact.toPersisted(stored); this.assertSessionCreationObligationScope(body, input.projectIdentityId, input.runtimeId); return publicCreationObligation(body); }); } /** DB-only bootstrap authority; it does not infer or grant managed membership. */ public resolvePendingFlexProjectManagementLoadAuthority( inputArg: IResolveControllerPendingFlexProjectManagementLoadAuthorityInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (input.runtimeId.harnessId !== 'flex') { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Pending Flex project-management load authority requires a Flex runtime ID.', )); } try { assertControllerFlexSessionGenerationId(inputArg.expectedFlexSessionGenerationId); } catch (errorArg) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Pending Flex project-management load authority requires a generation ID.', { cause: errorArg }, )); } return this.runScopedOperation(input.scopeKey, async () => { inputArg.signal?.throwIfAborted(); const stored = await this.readSessionCreationObligation( input.projectIdentityId, input.runtimeId, inputArg.signal, ); if (!stored) return 'definitively_unmanaged'; const body = ControllerSessionCreationObligationModel.exact.toPersisted(stored); this.assertSessionCreationObligationScope(body, input.projectIdentityId, input.runtimeId); return body.state === 'pending' && body.dispatchStartedAt !== undefined && body.expectedFlexSessionGenerationId === inputArg.expectedFlexSessionGenerationId ? 'pending_creation_load' : 'definitively_unmanaged'; }); } /** * DB-only registration authority. Empty loads expose no persisted project-management state and * never grant managed membership; the controller retains the exact host admission while loading. */ public resolveFlexProjectManagementRegistrationLoadAuthority( inputArg: IResolveControllerFlexProjectManagementRegistrationLoadAuthorityInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (input.runtimeId.harnessId !== 'flex') { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex project-management registration authority requires a Flex runtime ID.', )); } const providerSessionGeneration = requireProviderGeneration( inputArg.providerSessionGeneration, ); if (providerSessionGeneration === undefined) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex project-management registration authority requires an exact provider generation.', )); } try { assertControllerFlexSessionGenerationId(inputArg.expectedFlexSessionGenerationId); } catch (errorArg) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Flex project-management registration authority requires a generation ID.', { cause: errorArg }, )); } return this.runScopedOperation(input.scopeKey, async () => { inputArg.signal?.throwIfAborted(); if (await this.hasDispatchedFlexCleanupAuthority(input.projectIdentityId, { sessionId: input.runtimeId.nativeId, providerSessionGeneration, }, inputArg.signal)) { throw new ControllerSessionIdentityError( 'deleting', 'The Flex session has dispatched cleanup authority.', ); } const storedLocator = await this.readLocator(input.locatorId, inputArg.signal); if (storedLocator) { let locator = ControllerSessionLocatorModel.exact.toPersisted(storedLocator); this.assertLocatorScope(locator, input); if (!providerGenerationsEqual( locator.providerSessionGeneration, providerSessionGeneration, )) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'The Flex registration generation differs from its retained locator.', ); } // Registration precedes snapshot reconciliation, so finish only its fenced binding. if (locator.state === 'binding') { const settled = await this.settleCoordinator(storedLocator); locator = ControllerSessionLocatorModel.exact.toPersisted(settled.stored); this.assertLocatorScope(locator, input); if (!providerGenerationsEqual( locator.providerSessionGeneration, providerSessionGeneration, )) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'The Flex registration generation differs from its retained locator.', ); } } let sessionIdentityId: string; if (locator.state === 'attached' && locator.activeBindingId) { const observation = await this.observationFromAttached(locator, inputArg.signal); sessionIdentityId = observation.identity.sessionIdentityId; } else if (locator.state === 'detached' && locator.detachedBinding) { const identity = ControllerSessionIdentityModel.exact.toPersisted( await this.requireIdentityForLocator(locator, inputArg.signal), ); const binding = ControllerSessionRuntimeBindingModel.exact.toPersisted( await this.requireBindingForLocator( locator, locator.detachedBinding.bindingId, inputArg.signal, ), ); if ( identity.retiredAt !== undefined || binding.detachedAt === undefined || !datesEqual(binding.detachedAt, locator.detachedBinding.detachedAt) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'The detached Flex registration locator is inconsistent.', ); } sessionIdentityId = locator.sessionIdentityId; } else { throw new ControllerSessionIdentityError( locator.state === 'tombstoned' ? 'tombstoned' : 'concurrent_change', 'The Flex registration locator is not stable for project-management migration.', ); } const storedMembership = await this.readManagedSession( input.projectIdentityId, 'flex', sessionIdentityId, inputArg.signal, ); if (storedMembership) { const membership = ControllerManagedSessionModel.exact.toPersisted(storedMembership); this.assertManagedSessionScope( membership, input.projectIdentityId, input.runtimeId, sessionIdentityId, ); if (membership.providerSessionGeneration !== providerSessionGeneration) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'The managed Flex registration belongs to another provider generation.', ); } if (membership.sessionGenerationId !== inputArg.expectedFlexSessionGenerationId) { throw new ControllerSessionIdentityError( 'provider_generation_mismatch', 'The managed Flex registration belongs to another session generation.', ); } if (membership.state === 'active') return 'active_load'; throw new ControllerSessionIdentityError( membership.state === 'deleting' ? 'deleting' : 'tombstoned', 'The managed Flex registration is not active.', ); } } const storedObligation = await this.readSessionCreationObligation( input.projectIdentityId, input.runtimeId, inputArg.signal, ); if (storedObligation) { const obligation = ControllerSessionCreationObligationModel.exact.toPersisted( storedObligation, ); this.assertSessionCreationObligationScope( obligation, input.projectIdentityId, input.runtimeId, ); if ( obligation.state === 'pending' && obligation.dispatchStartedAt !== undefined && obligation.expectedFlexSessionGenerationId === inputArg.expectedFlexSessionGenerationId ) return 'pending_creation_empty_load'; throw new ControllerSessionIdentityError( 'concurrent_change', 'The Flex registration creation obligation does not authorize migration load.', ); } const memberships = await ControllerManagedSessionModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: input.projectIdentityId, harnessId: 'flex', 'runtimeId.harnessId': 'flex', 'runtimeId.nativeId': input.runtimeId.nativeId, }, sort: { id: 1 }, limit: 1, signal: inputArg.signal, }); if (memberships.length > 0) { throw new ControllerSessionIdentityError( 'tombstoned', 'The historical Flex registration retains managed membership state.', ); } return 'historical_unmanaged_empty_load'; }); } private async detachSessionInScope( input: IResolvedLocatorInput, expectedBindingId: string, detachedAt: Date, ): Promise { for (let attempt = 0; attempt < maximumReconciliationAttempts; attempt += 1) { let current = await this.requireLocator(input.locatorId); let settled = await this.settleCoordinator(current); current = settled.stored; const body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, input); if (body.state === 'detached' && body.detachedBinding) { if (body.detachedBinding.bindingId !== expectedBindingId) { throw new ControllerSessionIdentityError( 'concurrent_change', 'A newer session binding is already detached.', ); } const binding = await this.requireBindingForLocator(body, expectedBindingId); return publicBinding(ControllerSessionRuntimeBindingModel.exact.toPersisted(binding)); } if (body.state !== 'attached' || body.activeBindingId !== expectedBindingId) { throw new ControllerSessionIdentityError( body.state === 'tombstoned' ? 'tombstoned' : 'concurrent_change', 'The expected session binding is no longer active.', ); } const activeBinding = await this.requireBindingForLocator(body, expectedBindingId); const activeBindingBody = ControllerSessionRuntimeBindingModel.exact.toPersisted( activeBinding, ); if ( activeBindingBody.detachedAt !== undefined || detachedAt.getTime() < activeBindingBody.attachedAt.getTime() || detachedAt.getTime() < body.updatedAt.getTime() ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session detachment precedes the active binding state.', ); } current = await this.transitionLocator(current, (model) => { if ( model.state === 'attached' && model.activeBindingId === expectedBindingId && !model.bindingCleanup ) { model.state = 'detaching'; model.bindingCleanup = { bindingId: expectedBindingId, detachedAt: new Date(detachedAt), }; model.updatedAt = new Date(detachedAt); } }); settled = await this.settleCoordinator(current); const result = ControllerSessionLocatorModel.exact.toPersisted(settled.stored); if ( result.state === 'detached' && result.detachedBinding?.bindingId === expectedBindingId ) { const binding = await this.requireBindingForLocator(result, expectedBindingId); return publicBinding(ControllerSessionRuntimeBindingModel.exact.toPersisted(binding)); } } throw new ControllerSessionIdentityError( 'concurrent_change', 'Session binding detachment did not converge.', ); } public detachSession( inputArg: IDetachControllerSessionIdentityInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.expectedBindingId, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Expected binding ID is invalid.', )); } const detachedAt = requireDate(inputArg.detachedAt, 'Session detachment time'); return this.runScopedOperation( input.scopeKey, () => this.detachSessionInScope(input, inputArg.expectedBindingId, detachedAt), ); } private async reconcileFencedSnapshotInScope( scopeArg: IResolvedSnapshotScope, supervisorGenerationArg: string, sessionsArg: IResolvedSnapshotSession[], observedAtArg: Date, signalArg?: AbortSignal, managedMembershipsOnlyArg = false, ): Promise { signalArg?.throwIfAborted(); const managedRuntimeKeys = managedMembershipsOnlyArg ? new Set() : undefined; const managedLocatorIds: string[] | undefined = managedMembershipsOnlyArg ? [] : undefined; let activeMemberships: TStoredManagedSession[] = []; if (managedRuntimeKeys && managedLocatorIds) { activeMemberships = await this.readManagedSessionStatePages( scopeArg.projectIdentityId, scopeArg.harnessId, ['active'], signalArg, ); for (const stored of activeMemberships) { const membership = ControllerManagedSessionModel.exact.toPersisted(stored); const runtimeKey = controllerRuntimeIdKey(membership.runtimeId); if (managedRuntimeKeys.has(runtimeKey)) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Multiple active managed memberships claim one runtime locator.', ); } managedRuntimeKeys.add(runtimeKey); managedLocatorIds.push(controllerSessionLocatorDocumentId( this.issuerId, scopeArg.projectIdentityId, membership.runtimeId, )); } } const preflightLocators = managedLocatorIds === undefined ? await this.readSnapshotLocators(scopeArg, signalArg) : await this.readSnapshotLocatorsByIds(scopeArg, managedLocatorIds, signalArg); const pendingDeletions = preflightLocators .map((storedArg) => this.pendingDeletionFromLocator( ControllerSessionLocatorModel.exact.toPersisted(storedArg), )) .filter((entryArg): entryArg is IControllerSessionPendingDeletion => entryArg !== undefined) .sort((leftArg, rightArg) => compareRuntimeIds(leftArg.runtimeId, rightArg.runtimeId)); if (pendingDeletions.length > 0) { return { status: 'blocked_by_deletion', observations: [], detachedBindings: [], pendingDeletions, }; } let sessions = sessionsArg; if (managedRuntimeKeys) { const locatorByRuntimeKey = new Map(preflightLocators.map((storedArg) => { const body = ControllerSessionLocatorModel.exact.toPersisted(storedArg); return [controllerRuntimeIdKey(body.runtimeId), body] as const; })); for (const stored of activeMemberships) { const membership = ControllerManagedSessionModel.exact.toPersisted(stored); const runtimeKey = controllerRuntimeIdKey(membership.runtimeId); const locator = locatorByRuntimeKey.get(runtimeKey); if ( !locator || (!snapshotLocatorStates.includes(locator.state) && locator.state !== 'detached') || locator.sessionIdentityId !== membership.sessionIdentityId || !providerGenerationsEqual( locator.providerSessionGeneration, membership.providerSessionGeneration, ) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'An active managed membership does not match one exact runtime locator.', ); } } sessions = sessionsArg.filter((sessionArg) => managedRuntimeKeys.has( controllerRuntimeIdKey(sessionArg.runtimeId), )); } const scopedRuntimeIds = new Set(preflightLocators.map((storedArg) => controllerRuntimeIdKey( ControllerSessionLocatorModel.exact.toPersisted(storedArg).runtimeId, ))); for (const session of sessions) { scopedRuntimeIds.add(controllerRuntimeIdKey(session.runtimeId)); } if (scopedRuntimeIds.size > controllerSessionIdentityScopedLocatorLimit) { throw new ControllerSessionIdentityError( 'limit_exceeded', 'The reconciled session identity locator scope would exceed its limit.', ); } const observations: IControllerSessionSnapshotObservation[] = []; for (const session of sessions) { signalArg?.throwIfAborted(); const input = this.resolveLocatorInput(scopeArg.projectIdentityId, session.runtimeId); const observation = await this.observeSessionInScope( input, supervisorGenerationArg, session.providerSessionGeneration, observedAtArg, scopeArg.harnessId === 'flex', signalArg, ); signalArg?.throwIfAborted(); const managed = await this.snapshotMembershipIsActive( scopeArg, session.runtimeId, observation.identity.sessionIdentityId, signalArg, ); if (managedMembershipsOnlyArg && !managed) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A managed-only snapshot observation lost its active membership.', ); } observations.push({ runtimeId: { ...session.runtimeId }, ...observation, managed, }); } for (let index = 0; index < sessions.length; index += 1) { signalArg?.throwIfAborted(); const parentNativeId = sessions[index].parentNativeId; if ( managedRuntimeKeys && parentNativeId !== undefined && !managedRuntimeKeys.has(controllerRuntimeIdKey({ harnessId: scopeArg.harnessId, nativeId: parentNativeId, })) ) continue; await this.reconcileSnapshotParentRelationship( scopeArg, sessions[index], observations[index], observedAtArg, ); } signalArg?.throwIfAborted(); const presentRuntimeIds = new Set( sessions.map((entryArg) => controllerRuntimeIdKey(entryArg.runtimeId)), ); const postObservationLocators = managedLocatorIds === undefined ? await this.readSnapshotLocators(scopeArg, signalArg) : await this.readSnapshotLocatorsByIds(scopeArg, managedLocatorIds, signalArg); const unexpectedPendingDeletion = postObservationLocators .map((storedArg) => this.pendingDeletionFromLocator( ControllerSessionLocatorModel.exact.toPersisted(storedArg), )) .find((entryArg) => entryArg !== undefined); if (unexpectedPendingDeletion) { throw new ControllerSessionIdentityError( 'concurrent_change', 'A session deletion entered the fenced snapshot scope unexpectedly.', ); } const detachedBindings: IControllerSessionRuntimeBinding[] = []; for (const stored of postObservationLocators) { signalArg?.throwIfAborted(); let current = stored; let body = ControllerSessionLocatorModel.exact.toPersisted(current); if ( managedRuntimeKeys && !managedRuntimeKeys.has(controllerRuntimeIdKey(body.runtimeId)) ) continue; if (presentRuntimeIds.has(controllerRuntimeIdKey(body.runtimeId))) continue; current = (await this.settleCoordinator(current)).stored; body = ControllerSessionLocatorModel.exact.toPersisted(current); if (body.state === 'detached' || body.state === 'tombstoned') continue; if (body.state === 'deleting' || body.state === 'completing') { throw new ControllerSessionIdentityError( 'concurrent_change', 'A session deletion entered the fenced snapshot scope unexpectedly.', ); } if (body.state !== 'attached' || !body.activeBindingId) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A scoped session locator did not settle to an attachable state.', ); } const input = this.resolveLocatorInput(scopeArg.projectIdentityId, body.runtimeId); detachedBindings.push(await this.detachSessionInScope( input, body.activeBindingId, observedAtArg, )); } detachedBindings.sort((leftArg, rightArg) => compareRuntimeIds( leftArg.runtimeId, rightArg.runtimeId, )); return { status: 'reconciled', observations, detachedBindings, }; } /** * Reconciles only a complete provider snapshot captured while the caller's * provider mutation admission is sealed and drained. Live periodic snapshots * must not use this method because absence is authoritative only under that fence. */ public reconcileFencedProviderSnapshot( inputArg: IReconcileControllerSessionSnapshotInput, ): Promise { const scope = this.resolveSnapshotScope(inputArg.projectIdentityId, inputArg.harnessId); if (inputArg.sourceAdmissionFenced !== true || inputArg.snapshotComplete !== true) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Session snapshot reconciliation requires a complete source-admission fence.', )); } if (!isBase64UrlBytes(inputArg.supervisorGeneration, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Supervisor generation is invalid.', )); } if ( !Array.isArray(inputArg.sessions) || inputArg.sessions.length > controllerSessionIdentitySnapshotEntryLimit ) { return Promise.reject(new ControllerSessionIdentityError( 'limit_exceeded', 'The complete provider session snapshot exceeds its entry limit.', )); } inputArg.signal?.throwIfAborted(); const seenRuntimeIds = new Set(); const sessions = inputArg.sessions.map((entryArg) => { if (!isPlainObject(entryArg) || !hasExactKeys( entryArg, ['nativeId', 'providerSessionGeneration'], ['sessionGenerationId', 'sessionGenerationSequence', 'parentNativeId'], )) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session snapshot entries must use the exact canonical shape.', ); } const runtimeId = requireRuntimeId({ harnessId: scope.harnessId, nativeId: entryArg.nativeId as string, }); const providerSessionGeneration = requireProviderGeneration( entryArg.providerSessionGeneration as string, ); if (providerSessionGeneration === undefined) { throw new ControllerSessionIdentityError( 'invalid_input', 'Snapshot provider session generation is required.', ); } const hasSessionGenerationId = Object.hasOwn(entryArg, 'sessionGenerationId'); const hasSessionGenerationSequence = Object.hasOwn( entryArg, 'sessionGenerationSequence', ); if ( hasSessionGenerationId !== hasSessionGenerationSequence || (scope.harnessId === 'opencode' && hasSessionGenerationId) ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Snapshot raw generation fields do not match the session harness.', ); } if (hasSessionGenerationId) { try { assertControllerFlexSessionGeneration( entryArg.sessionGenerationId, entryArg.sessionGenerationSequence, providerSessionGeneration, ); } catch (errorArg) { throw new ControllerSessionIdentityError( 'invalid_input', 'Snapshot Flex generation facts are inconsistent.', { cause: errorArg }, ); } } const key = controllerRuntimeIdKey(runtimeId); if (seenRuntimeIds.has(key)) { throw new ControllerSessionIdentityError( 'invalid_input', 'The complete provider session snapshot contains a duplicate runtime ID.', ); } seenRuntimeIds.add(key); let parentNativeId: string | undefined; if (entryArg.parentNativeId !== undefined) { parentNativeId = requireRuntimeId({ harnessId: scope.harnessId, nativeId: entryArg.parentNativeId as string, }).nativeId; } return { runtimeId, providerSessionGeneration, ...(parentNativeId === undefined ? {} : { parentNativeId }), }; }).sort((leftArg, rightArg) => compareRuntimeIds(leftArg.runtimeId, rightArg.runtimeId)); assertSnapshotParentGraph(sessions); const observedAt = requireDate(inputArg.observedAt, 'Session snapshot observation time'); return this.runScopedOperation( scope.scopeKey, () => this.reconcileFencedSnapshotInScope( scope, inputArg.supervisorGeneration, sessions, observedAt, inputArg.signal, inputArg.managedMembershipsOnly === true, ), ); } private async beginSessionDeletionInScope( inputArg: IResolvedLocatorInput, expectedBindingIdArg: string, operationIdArg: string, startedAtArg: Date, ): Promise { for (let attempt = 0; attempt < maximumReconciliationAttempts; attempt += 1) { let current = await this.requireLocator(inputArg.locatorId); current = (await this.settleCoordinator(current)).stored; const body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, inputArg); if ( (body.state === 'deleting' || body.state === 'completing' || body.state === 'tombstoned') && body.deletion?.operationId === operationIdArg ) { if (body.deletion.finalBindingId !== expectedBindingIdArg) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session deletion operation is bound to another runtime binding.', ); } return; } let deletion: IControllerSessionDeletionRecord; if (body.state === 'attached' && body.activeBindingId === expectedBindingIdArg) { const activeBinding = await this.requireBindingForLocator(body, expectedBindingIdArg); const activeBindingBody = ControllerSessionRuntimeBindingModel.exact.toPersisted( activeBinding, ); if ( activeBindingBody.detachedAt !== undefined || startedAtArg.getTime() < activeBindingBody.attachedAt.getTime() || startedAtArg.getTime() < body.updatedAt.getTime() ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session deletion admission precedes the active binding state.', ); } deletion = { operationId: operationIdArg, startedAt: new Date(startedAtArg), priorState: 'attached', finalBindingId: expectedBindingIdArg, }; } else if ( body.state === 'detached' && body.detachedBinding?.bindingId === expectedBindingIdArg ) { if ( startedAtArg.getTime() < body.detachedBinding.detachedAt.getTime() || startedAtArg.getTime() < body.updatedAt.getTime() ) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session deletion admission precedes the detached binding state.', ); } deletion = { operationId: operationIdArg, startedAt: new Date(startedAtArg), priorState: 'detached', finalBindingId: expectedBindingIdArg, priorDetachedAt: new Date(body.detachedBinding.detachedAt), }; } else { throw new ControllerSessionIdentityError( body.state === 'tombstoned' ? 'tombstoned' : 'concurrent_change', 'The expected session binding cannot begin deletion.', ); } current = await this.transitionLocator(current, (model) => { if ( (model.state === 'attached' && model.activeBindingId === expectedBindingIdArg) || ( model.state === 'detached' && model.detachedBinding?.bindingId === expectedBindingIdArg ) ) { model.state = 'deleting'; model.deletion = deletion; model.updatedAt = new Date(startedAtArg); } }); const result = ControllerSessionLocatorModel.exact.toPersisted(current); if (result.state === 'deleting' && result.deletion?.operationId === operationIdArg) { return; } } throw new ControllerSessionIdentityError( 'concurrent_change', 'Session deletion admission did not converge.', ); } public beginSessionDeletion( inputArg: IBeginControllerSessionDeletionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.expectedBindingId, 32)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Expected deletion binding ID is invalid.', )); } if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Session deletion operation ID is invalid.', )); } const startedAt = requireDate(inputArg.startedAt, 'Session deletion start time'); return this.runScopedOperation( input.scopeKey, () => this.beginSessionDeletionInScope( input, inputArg.expectedBindingId, inputArg.operationId, startedAt, ), ); } private async cancelSessionDeletionInScope( inputArg: IResolvedLocatorInput, operationIdArg: string, cancelledAtArg: Date, ): Promise { let current = await this.requireLocator(inputArg.locatorId); const body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, inputArg); if (body.state !== 'deleting' || body.deletion?.operationId !== operationIdArg) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session deletion can no longer be cancelled.', ); } if (cancelledAtArg.getTime() < body.deletion.startedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session deletion cancellation precedes admission.', ); } const identity = await this.requireIdentityForLocator(body); if (ControllerSessionIdentityModel.exact.toPersisted(identity).retiredAt !== undefined) { throw new ControllerSessionIdentityError( 'corrupt_state', 'A retired session identity cannot cancel deletion.', ); } const binding = await this.requireBindingForLocator(body, body.deletion.finalBindingId); const bindingBody = ControllerSessionRuntimeBindingModel.exact.toPersisted(binding); if ( body.deletion.priorState === 'attached' ? bindingBody.detachedAt !== undefined : bindingBody.detachedAt === undefined || !datesEqual(bindingBody.detachedAt, body.deletion.priorDetachedAt!) ) { throw new ControllerSessionIdentityError( 'corrupt_state', 'Session deletion prior binding state cannot be restored.', ); } const deletion = body.deletion; current = await this.transitionLocator(current, (model) => { if (model.state === 'deleting' && model.deletion?.operationId === operationIdArg) { model.state = deletion.priorState; if (deletion.priorState === 'attached') { model.activeBindingId = deletion.finalBindingId; } else { model.detachedBinding = { bindingId: deletion.finalBindingId, detachedAt: new Date(deletion.priorDetachedAt!), }; } delete model.deletion; model.updatedAt = new Date(cancelledAtArg); } }); const result = ControllerSessionLocatorModel.exact.toPersisted(current); if (result.state !== deletion.priorState || result.deletion !== undefined) { throw new ControllerSessionIdentityError( 'concurrent_change', 'Session deletion completion won the cancellation race.', ); } } public cancelSessionDeletion( inputArg: ICancelControllerSessionDeletionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Session deletion operation ID is invalid.', )); } const cancelledAt = requireDate(inputArg.cancelledAt, 'Session deletion cancellation time'); return this.runScopedOperation( input.scopeKey, () => this.cancelSessionDeletionInScope(input, inputArg.operationId, cancelledAt), ); } private async verifyTombstoneSideRecords( locatorArg: IControllerSessionLocatorDocument, ): Promise { if (locatorArg.state !== 'tombstoned' || !locatorArg.deletion?.completedAt) { throw new ControllerSessionIdentityError('corrupt_state', 'Session locator is not tombstoned.'); } await this.detachBinding(locatorArg, { bindingId: locatorArg.deletion.finalBindingId, detachedAt: this.finalDetachedAt(locatorArg.deletion), }); await this.retireIdentity(locatorArg, locatorArg.deletion.completedAt); } /** * Call only after the exact admitted provider delete is confirmed complete or * confirms that exact native session absent. Snapshot absence is only detach. */ private async completeSessionDeletionInScope( inputArg: IResolvedLocatorInput, operationIdArg: string, completedAtArg: Date, ): Promise { for (let attempt = 0; attempt < maximumReconciliationAttempts; attempt += 1) { let current = await this.requireLocator(inputArg.locatorId); let body = ControllerSessionLocatorModel.exact.toPersisted(current); this.assertLocatorScope(body, inputArg); if (body.state === 'tombstoned' && body.deletion?.operationId === operationIdArg) { await this.verifyTombstoneSideRecords(body); return; } if (body.state === 'deleting' && body.deletion?.operationId === operationIdArg) { if (completedAtArg.getTime() < body.deletion.startedAt.getTime()) { throw new ControllerSessionIdentityError( 'invalid_input', 'Session deletion completion precedes admission.', ); } current = await this.transitionLocator(current, (model) => { if (model.state === 'deleting' && model.deletion?.operationId === operationIdArg) { model.state = 'completing'; model.deletion = { ...model.deletion, completedAt: new Date(completedAtArg), }; model.updatedAt = new Date(completedAtArg); } }); body = ControllerSessionLocatorModel.exact.toPersisted(current); } if (body.state === 'completing' && body.deletion?.operationId === operationIdArg) { current = await this.finishCompletion(current); body = ControllerSessionLocatorModel.exact.toPersisted(current); if (body.state === 'tombstoned' && body.deletion?.operationId === operationIdArg) { await this.verifyTombstoneSideRecords(body); return; } continue; } throw new ControllerSessionIdentityError( 'concurrent_change', 'Session deletion was cancelled or replaced before completion.', ); } throw new ControllerSessionIdentityError( 'concurrent_change', 'Session deletion completion did not converge.', ); } public completeSessionDeletion( inputArg: ICompleteControllerSessionDeletionInput, ): Promise { const input = this.resolveLocatorInput(inputArg.projectIdentityId, inputArg.runtimeId); if (!isBase64UrlBytes(inputArg.operationId, 24)) { return Promise.reject(new ControllerSessionIdentityError( 'invalid_input', 'Session deletion operation ID is invalid.', )); } const completedAt = requireDate(inputArg.completedAt, 'Session deletion completion time'); return this.runScopedOperation( input.scopeKey, () => this.completeSessionDeletionInScope(input, inputArg.operationId, completedAt), ); } } import { assertCodexOrigin, codexOriginsEqual, type IControllerCodexOrigin } from './classes.codexconnectionmodels.js'; import { codexQualifiedIdentity } from './functions.codexidentity.js';