import { childRequiresActionRouteTx, parentOutboxAuthorityTx, recordedChildNoticeTargetTx, type ChildRequiresActionRoute, } from "./child-outbox-authority"; import { lockSiteRuntimeAdmission } from "./site-runtime-admission"; import { createHash } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; import { boundWorkspaceControlEvent, childPausedClassification, workspaceControlUtf8Bytes, type WorkspacePauseTimerRequest, type SessionMcpApprovalPolicy, type TurnInitiatorContext, } from "@opengeni/contracts"; import { and, eq, getTableColumns, inArray, sql, type SQL } from "drizzle-orm"; import { anyOf } from "./sql-arrays"; import type { Database, SessionActivityDatabase } from "./database"; import { withLosslessContentWriteVersion } from "./lossless-json"; import { withBoundSessionEventPayloads } from "./session-event-write-bounds"; import { nestedPostgresSqlState } from "./persistence-errors"; import { getExternalLinkTurnAuthorization } from "./external-link-work"; import * as schema from "./schema"; import { boundedChildPausedReason, childLifecycleNoticesEnabled, childPausedDedupeKey, childPausedSummary, childRequiresActionDedupeKey, childRequiresActionResolvedDedupeKey, childRequiresActionResolvedSummary, } from "./child-lifecycle-notices"; import { closePendingSessionToolCallsInTransaction } from "./session-tool-call-settlement"; import { releaseCapacityWaitingTurnInTransaction } from "./capacity-wait-release"; import { copySubscriptionAuthorityCompatInTransaction } from "./subscription-core-acceptance-authority"; import { deleteSubscriptionCoreWaitersForTurns } from "./subscription-core/waiters"; import { mirrorSessionRealtimeContextInTransaction, renderRealtimeHumanInputResponseContext, } from "./session-realtime-mirror"; import { requestSessionBackgroundCommandCancellationsInTransaction, requestWorkspaceBackgroundCommandCancellationsInTransaction, } from "./session-background-commands"; type SessionEventInsertWithPayload = typeof schema.sessionEvents.$inferInsert & { payload: unknown; }; export const SESSION_ANCESTRY_LIMIT = 10_000; export type WorkspaceControlLockMode = "none" | "share" | "update"; export type EffectiveControlState = "active" | "paused"; export type SessionCommandActor = | { type: "human" | "operator"; subjectId: string } | { type: "service"; subjectId: string; subjectLabel?: string; context?: TurnInitiatorContext; } | { type: "agent_attempt"; attemptId: string; sessionId: string; turnId: string; executionGeneration: number; }; export type SessionTurnAttemptOutcome = | "completed" | "failed" | "cancelled" | "superseded" | "requires_action" | "waiting_capacity" | "interrupted_recoverable" | "lease_lost_recoverable" | "pre_cutover_closed"; export type EffectiveControlBlocker = { kind: "session" | "workspace"; sessionId?: string; displayName: string; actor: string | null; reason: string | null; changedAt: Date | null; revision: number; }; export type EffectiveControlResumeOption = { scope: "selected" | "session" | "workspace"; targetId?: string; selectedStateAfter: EffectiveControlState; remainingPrimaryBlocker?: EffectiveControlBlocker; impactCopy: string; }; export type EffectiveSessionControl = { state: EffectiveControlState; controlVersion: number; controlEtag: string; directState: EffectiveControlState; primaryBlocker: EffectiveControlBlocker | null; additionalBlockerCount: number; blockers: EffectiveControlBlocker[]; resumeOptions: EffectiveControlResumeOption[]; override: { rootSessionId: string; revision: number } | null; settlement: { state: "stopping"; attemptCount: number; interruptionPendingCount: number; quiescencePendingCount: number; } | null; backgroundCommandSettlement: { state: "stopping"; commandCount: number; } | null; }; /** * The bounded control projection required by a locked activity-write fence. * Settlement and background-command summaries are read-model concerns and must * not extend the session-event critical section when admission only needs the * effective run state and blocker scope. */ export type SessionWriteAdmissionControl = { state: EffectiveControlState; controlVersion: number; primaryBlockerKind: EffectiveControlBlocker["kind"] | null; }; type SettlementAttemptCounts = { attemptCount: number; interruptionPendingCount: number; quiescencePendingCount: number; }; const NO_SETTLEMENT_ATTEMPTS: SettlementAttemptCounts = { attemptCount: 0, interruptionPendingCount: 0, quiescencePendingCount: 0, }; export const SESSION_DISCOVERY_CONTROL_TITLE_MAX_CHARS = 200; export const SESSION_DISCOVERY_CONTROL_TARGET_LIMIT = 100; /** * Purpose-built control projection for session discovery. Full blocker evidence, * actors/reasons, resume options, etags, and settlement state remain available * from the ordinary session detail APIs; this shape is intentionally only what * `sessions_list` renders. */ export type SessionDiscoveryControl = { state: EffectiveControlState; primaryBlocker: { kind: "session" | "workspace"; sessionId?: string; displayName: string; displayNameOriginalChars: number; } | null; additionalBlockerCount: number; }; export function serializeEffectiveSessionControl(control: EffectiveSessionControl) { const blocker = ( value: EffectiveControlBlocker, ): Omit & { changedAt: string | null; } => ({ ...value, changedAt: value.changedAt?.toISOString() ?? null, }); return { ...control, primaryBlocker: control.primaryBlocker ? blocker(control.primaryBlocker) : null, blockers: control.blockers.map(blocker), resumeOptions: control.resumeOptions.map(({ remainingPrimaryBlocker, ...option }) => ({ ...option, ...(remainingPrimaryBlocker ? { remainingPrimaryBlocker: blocker(remainingPrimaryBlocker) } : {}), })), }; } export type WorkspaceControlRow = { workspaceId: string; accountId: string; revision: number | string; workspaceState: string; workspacePauseRevision: number | string | null; timerId: string | null; timerAction: string | null; timerDueAt: Date | string | null; timerPauseForSeconds: number | null; timerPauseRevision: number | string | null; reason: string | null; changedBy: string | null; changedAt: Date | string | null; }; type AncestryRow = { targetId: string; sessionId: string; parentSessionId: string | null; title: string | null; directState: string; directPauseRevision: number | string | null; subtreeRunOverrideRevision: number | string | null; controlVersion: number | string; directControlChangedBy: string | null; directControlReason: string | null; directControlChangedAt: Date | string | null; depth: number | string; cycle: boolean; }; type AncestryNode = Omit; export type SessionCommandReceiptRow = typeof schema.sessionCommandReceipts.$inferSelect; export class SessionControlInvariantError extends Error { readonly code = "SESSION_CONTROL_INVARIANT"; constructor(message: string) { super(message); this.name = "SessionControlInvariantError"; } } /** * The session is not in its workspace: it never was, or a concurrent deletion * committed while the caller waited on the workspace-control lock. Callers * that only catch the invariant error still see one; an HTTP surface answers * 404 instead of a server error. */ export class SessionMissingFromWorkspaceError extends SessionControlInvariantError { constructor(readonly sessionId: string) { super(`Session ${sessionId} does not exist in its workspace`); } } export class SessionControlConflictError extends Error { readonly code = "CONTROL_CHANGED"; constructor(message = "The workstream control changed") { super(message); this.name = "SessionControlConflictError"; } } export class SessionCommandIdempotencyError extends Error { readonly code = "IDEMPOTENCY_KEY_REUSED"; constructor() { super("The operation key was already used with different input"); this.name = "SessionCommandIdempotencyError"; } } export class AgentCommandAuthorityError extends Error { constructor( readonly code: | "CALLER_STALE" | "CALLER_INTERRUPTED" | "TARGET_NOT_VERTICAL" | "SELF_STEER" | "PERSONAL_MACHINE_OWNER_REQUIRED", message: string, ) { super(message); this.name = "AgentCommandAuthorityError"; } } export async function assertAgentCommandAuthorityInTransaction( db: Database, input: { workspaceId: string; actor: Extract; targetSessionId: string; action: | "pause" | "resume" | "steer" | "message" | "goal" | "wait" | "model_settings" | "context"; }, ): Promise { if ( ["goal", "wait", "context"].includes(input.action) && input.targetSessionId !== input.actor.sessionId ) { throw new SessionControlInvariantError("An agent self command must target its own session"); } // Every command caller establishes the control/workspace prefix first. // Reusing the event-write helper here keeps cross-session actor authority on // the same UUID-ordered session -> exact turn -> exact attempt suffix. const authorityLocks = await lockSessionEventWriteRows(db, { workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", sessionIds: [input.actor.sessionId, input.targetSessionId], turnIds: [input.actor.turnId], attemptIds: [input.actor.attemptId], }); const lockedSessions = authorityLocks.sessions; const callerSession = lockedSessions.find((row) => row.id === input.actor.sessionId); if (!callerSession) { throw new AgentCommandAuthorityError("CALLER_STALE", "The calling session no longer exists"); } const targetSession = lockedSessions.find((row) => row.id === input.targetSessionId); if (!targetSession) { throw new SessionControlInvariantError(`Target session not found: ${input.targetSessionId}`); } const rows = await db.execute<{ attemptId: string; attemptState: string; attemptSessionId: string; attemptTurnId: string; executionGeneration: number; activeAttemptId: string | null; turnStatus: string; activeTurnId: string | null; interrupted: boolean; }>(sql` select attempt.id as "attemptId", attempt.state as "attemptState", attempt.session_id as "attemptSessionId", attempt.turn_id as "attemptTurnId", attempt.execution_generation as "executionGeneration", turn.active_attempt_id as "activeAttemptId", turn.status as "turnStatus", session.active_turn_id as "activeTurnId", exists ( select 1 from ${schema.sessionAttemptInterruptions} interruption where interruption.workspace_id = ${input.workspaceId} and interruption.attempt_id = attempt.id and interruption.state in ('pending', 'delivered', 'acknowledged') ) as interrupted from ${schema.sessionTurnAttempts} attempt join ${schema.sessionTurns} turn on turn.workspace_id = attempt.workspace_id and turn.id = attempt.turn_id join ${schema.sessions} session on session.workspace_id = attempt.workspace_id and session.id = attempt.session_id where attempt.workspace_id = ${input.workspaceId} and attempt.id = ${input.actor.attemptId} `); const caller = rows[0]; if ( !caller || !["claimed", "running"].includes(caller.attemptState) || caller.attemptSessionId !== input.actor.sessionId || caller.attemptTurnId !== input.actor.turnId || Number(caller.executionGeneration) !== input.actor.executionGeneration || caller.activeAttemptId !== input.actor.attemptId || caller.activeTurnId !== input.actor.turnId || !["running", "requires_action", "recovering", "waiting_capacity"].includes(caller.turnStatus) ) { throw new AgentCommandAuthorityError( "CALLER_STALE", "The calling agent attempt no longer owns its turn", ); } if (caller.interrupted) { throw new AgentCommandAuthorityError( "CALLER_INTERRUPTED", "The calling agent attempt is being interrupted", ); } const linked = await getExternalLinkTurnAuthorization( db, { accountId: callerSession.accountId, workspaceId: input.workspaceId, }, input.actor.turnId, ); if (linked && !linked.authorized) throw new AgentCommandAuthorityError( "CALLER_STALE", "The calling agent's native identity link is no longer active", ); if (input.action === "steer" && input.targetSessionId === input.actor.sessionId) { throw new AgentCommandAuthorityError("SELF_STEER", "An agent cannot steer its own session"); } // Peer, parent, child, and unrelated-root targets are allowed here. Slack-private // and user_private denies remain in requireSessionAuthorization. } function asSafeRevision(value: number | string | null, label: string): number | null { if (value === null) return null; const revision = Number(value); if (!Number.isSafeInteger(revision) || revision < 0) { throw new SessionControlInvariantError(`${label} is not a safe non-negative revision`); } return revision; } function asDate(value: Date | string | null): Date | null { if (value === null) return null; return value instanceof Date ? value : new Date(value); } function canonicalize(value: unknown): unknown { if (Array.isArray(value)) return value.map(canonicalize); if (value && typeof value === "object") { return Object.fromEntries( Object.entries(value as Record) .sort(([left], [right]) => left.localeCompare(right)) .map(([key, item]) => [key, canonicalize(item)]), ); } return value; } export function canonicalSessionCommandHash(value: unknown): string { return createHash("sha256") .update(JSON.stringify(canonicalize(value))) .digest("hex"); } function controlEtag(value: unknown): string { return `sc1:${canonicalSessionCommandHash(value)}`; } function lockClause(mode: WorkspaceControlLockMode) { if (mode === "none") return sql.empty(); return mode === "update" ? sql.raw("for update") : sql.raw("for share"); } /** * Default bounded control-prefix wait for request-scoped API mutations (Send, * Steer, queued Steer, Pause/Resume/Cancel, workspace Pause/Resume, realtime * sync). The bound is one budget across every lock step of the admission * (advisory lock, row lock, and the savepoint escalation of a paused branch), * not a per-statement timeout. A request that cannot enter the workspace * control prefix within the budget fails with the typed, retryable * `WorkspaceControlBusyError` before any write instead of holding a pooled * connection and a snapshot for as long as the HTTP client (or ingress) keeps * the socket open. Worker settlement, claims, and event appends never pass a * bound: a legitimate wait there must not become a failed settlement. * The deployment value is `OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS`, parsed * and validated once at boot by `@opengeni/config` * (`settings.workspaceControlLockTimeoutMs`) and handed to this module through * `configureWorkspaceControlRequestLockTimeoutMs` when the API app is built. * This module never reads `process.env` per request. */ export const WORKSPACE_CONTROL_REQUEST_LOCK_TIMEOUT_MS = 20_000; let configuredRequestLockTimeoutMs = WORKSPACE_CONTROL_REQUEST_LOCK_TIMEOUT_MS; /** * Install the validated request-scoped budget for this process. The value is * process-global and last-writer-wins: the API calls this exactly once from * its settings at app composition (`createApp`), and every later * `workspaceControlRequestLockTimeoutMs()` read observes that value. Workers * never call it because they never pass a bound. A non-positive or * non-integer value is a programming error here (the config layer already * rejected it at boot). */ export function configureWorkspaceControlRequestLockTimeoutMs(lockTimeoutMs: number): void { if (!Number.isSafeInteger(lockTimeoutMs) || lockTimeoutMs <= 0) { throw new Error("Workspace control request lock timeout must be a positive integer (ms)"); } configuredRequestLockTimeoutMs = lockTimeoutMs; } /** The request-scoped budget in milliseconds currently configured for this process. */ export function workspaceControlRequestLockTimeoutMs(): number { return configuredRequestLockTimeoutMs; } export class WorkspaceControlBusyError extends Error { readonly code = "WORKSPACE_CONTROL_BUSY"; constructor( readonly workspaceId: string, readonly lockTimeoutMs: number, ) { super("The workspace control row is busy; retry shortly"); this.name = "WorkspaceControlBusyError"; } } /** * One wall-clock budget shared by every lock step of one control-prefix * acquisition. Each step sets `lock_timeout` to the remaining budget, so the * total wait never exceeds the requested bound even when the advisory lock, * the row lock, and a savepoint escalation each wait in turn. */ export type WorkspaceControlLockBudget = { readonly totalMs: number; readonly deadlineAt: number; }; export function workspaceControlLockBudget(lockTimeoutMs: number): WorkspaceControlLockBudget { if (!Number.isFinite(lockTimeoutMs) || lockTimeoutMs <= 0) { throw new Error("Workspace control lockTimeoutMs must be a positive number"); } const totalMs = Math.max(1, Math.floor(lockTimeoutMs)); return { totalMs, deadlineAt: Date.now() + totalMs }; } export type WorkspaceControlLockOptions = { /** * Bound the whole prefix acquisition in milliseconds. Omit for * worker/lifecycle writers. The previous `lock_timeout` is restored once the * prefix is held. */ lockTimeoutMs?: number; /** Share an already running budget (used by the admission helper). */ budget?: WorkspaceControlLockBudget; }; function advisoryLockFunction(mode: Exclude) { return mode === "update" ? sql.raw("pg_advisory_xact_lock") : sql.raw("pg_advisory_xact_lock_shared"); } function lockBudgetFor(options: WorkspaceControlLockOptions): WorkspaceControlLockBudget | null { if (options.budget) return options.budget; if (options.lockTimeoutMs === undefined) return null; return workspaceControlLockBudget(options.lockTimeoutMs); } /** Run one lock-acquiring statement under the remaining budget. */ export async function boundedLockStep( db: Database, workspaceId: string, budget: WorkspaceControlLockBudget | null, step: () => Promise, ): Promise { if (!budget) return await step(); const remainingMs = budget.deadlineAt - Date.now(); if (remainingMs <= 0) throw new WorkspaceControlBusyError(workspaceId, budget.totalMs); await db.execute( sql`select set_config('lock_timeout', ${`${Math.max(1, Math.floor(remainingMs))}ms`}, true)`, ); try { return await step(); } catch (error) { if (nestedPostgresSqlState(error) === "55P03") { // Deliberately no `cause`: the 55P03 must not stay reachable through the // cause chain, or persistence-retry classification and the delete-tree // `live_sandboxes` 55P03 mapping would reclassify this typed busy error. throw new WorkspaceControlBusyError(workspaceId, budget.totalMs); } throw error; } } /** * Lock the mandatory workspace inference-control row. * * `share` and `update` first take a transaction-scoped advisory lock on * `hashtextextended('workspace-control:', 0)` in the matching * mode and only then the row lock. The advisory lock is what makes the prefix * fair: PostgreSQL row locks let a new FOR SHARE requester join a share-locked * tuple without queueing behind an already waiting FOR UPDATE, so under * continuous share traffic (claims, settlement, appends across many sessions) * a genuine control mutation can starve indefinitely. Heavyweight locks have a * FIFO wait queue: a shared request conflicts with a waiting exclusive request * and queues behind it, so a mutator waits only for the holders that preceded * it, and sharers keep flowing between mutations. The row lock is retained * unchanged for FK/consistency semantics and for SQL-function writers that * lock the row directly (session-create triggers and capability functions). * * Invariant: a transaction that locks this row through any other path (a * SECURITY DEFINER function, a trigger, raw SQL) must already hold the prefix * through this helper or must never call this helper afterwards for the same * workspace. Requesting the advisory lock after holding the row lock can * deadlock against a mutator that holds the advisory lock and waits for the * row. Every current SQL-function locker either runs in its own transaction or * runs after this helper in the same transaction. */ export async function lockWorkspaceInferenceControl( db: Database, workspaceId: string, mode: WorkspaceControlLockMode, options: WorkspaceControlLockOptions = {}, ): Promise { // Some admission commands acquire control before the session writer helper. // Keep the Site conversation -> control -> session order on those paths too. await lockSiteRuntimeAdmission(db, workspaceId); const budget = lockBudgetFor(options); const [prior] = budget ? await db.execute<{ value: string }>(sql`select current_setting('lock_timeout') as value`) : []; if (mode !== "none") { await boundedLockStep(db, workspaceId, budget, () => db.execute( sql`select ${advisoryLockFunction(mode)}(hashtextextended(${`workspace-control:${workspaceId}`}, 0))`, ), ); } const rows = await boundedLockStep(db, workspaceId, budget, () => db.execute(sql` select workspace_id as "workspaceId", account_id as "accountId", revision, workspace_state as "workspaceState", workspace_pause_revision as "workspacePauseRevision", timer_id as "timerId", timer_action as "timerAction", timer_due_at as "timerDueAt", timer_pause_for_seconds as "timerPauseForSeconds", timer_pause_revision as "timerPauseRevision", reason, changed_by as "changedBy", changed_at as "changedAt" from ${schema.workspaceInferenceControls} where workspace_id = ${workspaceId} ${lockClause(mode)} `), ); if (budget) { await db.execute(sql`select set_config('lock_timeout', ${prior?.value ?? "0"}, true)`); } const row = rows[0]; if (!row) { throw new SessionControlInvariantError( `Workspace ${workspaceId} has no mandatory inference-control row`, ); } return row; } export type WorkspaceControlAdmissionLock = { control: WorkspaceControlRow; mode: "share" | "update"; }; const WORKSPACE_CONTROL_ADMISSION_SAVEPOINT = "opengeni_workspace_control_admission"; /** * Lock the workspace control prefix for an admission. Callers that may resume * a paused branch request escalation; inert queue admission stays shared. * * The common case (the target branch is active) holds only `FOR SHARE`. That * still excludes every control mutation (Pause/Resume/Cancel, workspace * control, auto-resume all take `FOR UPDATE`), so the effective state observed * here cannot change for the rest of the transaction, while other Sends, * Steers, claims, and event appends on the workspace proceed concurrently. * * When the branch is paused the admission must advance the workspace control * revision, so it needs `FOR UPDATE`. Upgrading in place would deadlock as soon * as two sharers decide to upgrade together (each waits for the other's share * lock), so the shared prefix is taken inside a savepoint and rolled back * before the exclusive prefix is requested: PostgreSQL releases row locks and * transaction-level advisory locks acquired inside a rolled-back savepoint, so * the exclusive request queues normally behind other holders. * * Callers that already hold the prefix exclusively (for example a realtime * sync that admitted a delegation) simply observe their own stronger lock. */ export async function lockWorkspaceInferenceControlForAdmission( db: Database, input: { workspaceId: string; sessionId: string; resumePausedBranch: boolean; } & WorkspaceControlLockOptions, ): Promise { // One budget spans the shared attempt and any escalation to the exclusive // prefix, so the caller's bound is the total wait, not a per-step timeout. const lockOptions: WorkspaceControlLockOptions = input.lockTimeoutMs === undefined ? {} : { budget: workspaceControlLockBudget(input.lockTimeoutMs) }; await db.execute(sql.raw(`savepoint ${WORKSPACE_CONTROL_ADMISSION_SAVEPOINT}`)); const shared = await lockWorkspaceInferenceControl(db, input.workspaceId, "share", lockOptions); if (!input.resumePausedBranch) { await db.execute(sql.raw(`release savepoint ${WORKSPACE_CONTROL_ADMISSION_SAVEPOINT}`)); return { control: shared, mode: "share" }; } const effective = await evaluateSessionControl(db, input.workspaceId, input.sessionId, { workspaceControl: shared, }); if (effective.state === "active") { await db.execute(sql.raw(`release savepoint ${WORKSPACE_CONTROL_ADMISSION_SAVEPOINT}`)); return { control: shared, mode: "share" }; } await db.execute(sql.raw(`rollback to savepoint ${WORKSPACE_CONTROL_ADMISSION_SAVEPOINT}`)); await db.execute(sql.raw(`release savepoint ${WORKSPACE_CONTROL_ADMISSION_SAVEPOINT}`)); return { control: await lockWorkspaceInferenceControl(db, input.workspaceId, "update", lockOptions), mode: "update", }; } export type SessionEventWriteLockInput = { workspaceId: string; /** * Control-aware writes take this lock first. Callers that already hold the * workspace control row (for example a Pause mutation under FOR UPDATE) say * `already_locked`; ordinary audit/title appends explicitly use `none`. */ controlLock: WorkspaceControlLockMode | "already_locked" | "none"; /** Used only when a staged caller already established the workspace prefix. */ workspaceLock?: "key_share" | "already_locked"; /** * Semantic writers retain FOR NO KEY UPDATE. Cursor-authoritative raw-only * appends need only the FK-compatible identity hold; KEY SHARE is compatible * with semantic NO KEY UPDATE and therefore removes the wide session row as * their serialization mutex without inverting the rolling lock order. */ sessionLock?: "no_key_update" | "key_share"; sessionIds?: string[]; turnIds?: string[]; attemptIds?: string[]; }; export type SessionEventWriteLocks = { control: WorkspaceControlRow | null; workspace: typeof schema.workspaces.$inferSelect | null; sessions: Array; cursors: Array; turns: Array; attempts: Array; }; type SessionEventWriteProjectionInput = SessionEventWriteLockInput & { /** Event-only appenders need identity, ownership and projection fields, not frozen inputs. */ rowProjection?: "full" | "event"; }; const eventWorkspaceColumns = { id: schema.workspaces.id, accountId: schema.workspaces.accountId, }; const eventSessionColumns = { id: schema.sessions.id, accountId: schema.sessions.accountId, workspaceId: schema.sessions.workspaceId, activeTurnId: schema.sessions.activeTurnId, lastSequence: schema.sessions.lastSequence, authorityEpoch: schema.sessions.authorityEpoch, executionAuthorityEpoch: schema.sessions.executionAuthorityEpoch, visibility: schema.sessions.visibility, ownerOrganizationMembershipId: schema.sessions.ownerOrganizationMembershipId, parentSessionId: schema.sessions.parentSessionId, directControlState: schema.sessions.directControlState, directPauseRevision: schema.sessions.directPauseRevision, subtreeRunOverrideRevision: schema.sessions.subtreeRunOverrideRevision, controlVersion: schema.sessions.controlVersion, }; const eventTurnColumns = { id: schema.sessionTurns.id, accountId: schema.sessionTurns.accountId, workspaceId: schema.sessionTurns.workspaceId, sessionId: schema.sessionTurns.sessionId, executionGeneration: schema.sessionTurns.executionGeneration, activeAttemptId: schema.sessionTurns.activeAttemptId, status: schema.sessionTurns.status, metadata: schema.sessionTurns.metadata, createdAt: schema.sessionTurns.createdAt, version: schema.sessionTurns.version, }; const eventAttemptColumns = { id: schema.sessionTurnAttempts.id, accountId: schema.sessionTurnAttempts.accountId, workspaceId: schema.sessionTurnAttempts.workspaceId, sessionId: schema.sessionTurnAttempts.sessionId, turnId: schema.sessionTurnAttempts.turnId, executionGeneration: schema.sessionTurnAttempts.executionGeneration, state: schema.sessionTurnAttempts.state, authorityEpoch: schema.sessionTurnAttempts.authorityEpoch, authorityVisibility: schema.sessionTurnAttempts.authorityVisibility, authorityOwnerOrganizationMembershipId: schema.sessionTurnAttempts.authorityOwnerOrganizationMembershipId, }; export type SessionEventWriteFenceLocks = { control: WorkspaceControlRow | null; workspace: Pick | null; sessions: Array>; cursors: SessionEventWriteLocks["cursors"]; turns: Array>; attempts: Array< Pick >; }; /** * Establish the one canonical lock prefix for every `session_events` writer: * * workspace-control advisory lock + workspace_inference_controls row * (when control-aware; see `lockWorkspaceInferenceControl`) * -> actual workspaces row FOR KEY SHARE * -> session rows FOR NO KEY UPDATE (semantic) or KEY SHARE (raw), UUID ordered * -> session event cursor rows FOR UPDATE, UUID ordered * -> exact turn rows FOR UPDATE, UUID ordered * -> exact attempt rows FOR UPDATE, UUID ordered * * Control-aware writers that do not mutate the control row take it `share`; * only genuine control mutations (Pause/Resume/Cancel, workspace control, * auto-resume, settings narrowing, quiescent tree deletion) take `update`. * Prompt admission declares whether it may resume a paused branch through * `lockWorkspaceInferenceControlForAdmission`. * * `FOR KEY SHARE` is deliberate. Event inserts need the workspace key to remain * stable for their FK, but they do not mutate the workspace. The old generic * `FOR UPDATE` lock serialized unrelated sessions and inverted the activity * path's session -> implicit workspace-FK edge. * * `FOR NO KEY UPDATE` is equally deliberate for semantic session writers. * Cursor-authoritative raw-only writers use `FOR KEY SHARE`: it preserves the * session identity against deletion while remaining compatible with semantic * `FOR NO KEY UPDATE`. Keeping this rolling session-before-cursor order avoids * an inversion with old binaries and quiescent cascade deletion; the compact * cursor row, not the wide session row, is the raw ordering mutex. * * Complex lifecycle transactions may acquire allocator/control locks before * this helper and may discover exact turn IDs only after locking the session. * They use the explicit `already_locked` stages, while retaining the same * monotonic table order. New event writers should prefer one complete call. * * Retained-screenshot and generated-image prepare are not event writers, but * their INSERTs KEY SHARE the turn and attempt through FKs. They take this prefix * first: PostgreSQL fires those FK checks in catalog name/OID order, which can * be attempt-then-turn and otherwise deadlocks against this helper. */ export function lockSessionEventWriteRows( db: Database, input: SessionEventWriteLockInput & { rowProjection: "event" }, ): Promise; export function lockSessionEventWriteRows( db: Database, input: SessionEventWriteLockInput & { rowProjection?: "full" }, ): Promise; export function lockSessionEventWriteRows( db: Database, input: SessionEventWriteProjectionInput, ): Promise; export async function lockSessionEventWriteRows( db: Database, input: SessionEventWriteProjectionInput, ): Promise { await lockSiteRuntimeAdmission(db, input.workspaceId, input.sessionIds ?? []); const controlLock = input.controlLock; const control = controlLock === "share" || controlLock === "update" ? await lockWorkspaceInferenceControl(db, input.workspaceId, controlLock) : null; const eventOnly = input.rowProjection === "event"; const sessionColumns = eventOnly ? eventSessionColumns : getTableColumns(schema.sessions); const sessionIds = [...new Set(input.sessionIds ?? [])].sort(); const sessionLock = input.sessionLock ?? "no_key_update"; // Submit in canonical lock order on the transaction-pinned connection. The // server still executes separate statements with fresh READ COMMITTED // snapshots; only the client waits overlap. Cursor-dependent work stays below. const [workspaces, lockedSessions] = await Promise.all([ (input.workspaceLock ?? "key_share") === "key_share" ? db .select(eventOnly ? eventWorkspaceColumns : getTableColumns(schema.workspaces)) .from(schema.workspaces) .where(eq(schema.workspaces.id, input.workspaceId)) .for("key share") .limit(1) : [], sessionIds.length > 0 ? db .select(sessionColumns) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), anyOf(schema.sessions.id, sessionIds), ), ) .orderBy(schema.sessions.id) .for(sessionLock === "key_share" ? "key share" : "no key update") : [], ]); const workspace = workspaces[0] ?? null; let sessions = lockedSessions; const cursors = sessions.length > 0 ? await db .select() .from(schema.sessionEventCursors) .where( and( eq(schema.sessionEventCursors.workspaceId, input.workspaceId), inArray( schema.sessionEventCursors.sessionId, sessions.map((session) => session.id), ), ), ) .orderBy(schema.sessionEventCursors.sessionId) .for("update") : []; if (cursors.length !== sessions.length) { throw new SessionControlInvariantError( `Session event cursor lock set was incomplete for workspace ${input.workspaceId}`, ); } if (sessionLock === "key_share" && sessions.length > 0) { // KEY SHARE is intentionally compatible with a semantic writer's NO KEY // UPDATE. If that writer reached the cursor first it may have committed a // control/authority/session-state change after our initial identity read. // Re-read only after owning the cursor so the attempt fence evaluates the // latest committed session state while later semantic writers wait here. sessions = await db .select(sessionColumns) .from(schema.sessions) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), anyOf(schema.sessions.id, sessionIds), ), ) .orderBy(schema.sessions.id) .for("key share"); } const canonicalSessions = sessions.map((session, index) => { const cursor = cursors[index]!; if ( cursor.sessionId !== session.id || cursor.accountId !== session.accountId || cursor.workspaceId !== session.workspaceId ) { throw new SessionControlInvariantError( `Session event cursor identity failed for session ${session.id}`, ); } // The cursor is the allocation authority. The wide session column remains // a rolling compatibility/read projection until every reader is cut over. // It may lag after the later pure-append activation, but it must never lead // the durable cursor or an old writer could have committed an unverified // sequence. if (cursor.lastSequence < session.lastSequence) { throw new SessionControlInvariantError( `Session event cursor is behind session projection for session ${session.id}`, ); } return { ...session, lastSequence: cursor.lastSequence }; }); const turnIds = [...new Set(input.turnIds ?? [])].sort(); const attemptIds = [...new Set(input.attemptIds ?? [])].sort(); const [turns, attempts] = await Promise.all([ turnIds.length > 0 ? db .select(eventOnly ? eventTurnColumns : getTableColumns(schema.sessionTurns)) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), anyOf(schema.sessionTurns.id, turnIds), ), ) .orderBy(schema.sessionTurns.id) .for("update") : [], attemptIds.length > 0 ? db .select(eventOnly ? eventAttemptColumns : getTableColumns(schema.sessionTurnAttempts)) .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), anyOf(schema.sessionTurnAttempts.id, attemptIds), ), ) .orderBy(schema.sessionTurnAttempts.id) .for("update") : [], ]); return { control, workspace, sessions: canonicalSessions, cursors, turns, attempts }; } export async function registerSessionTurnAttemptClaim( db: Database, input: { id: string; accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; temporalWorkflowId: string; temporalWorkflowRunId: string; temporalActivityId: string; verifiedControlRevision: number; authorityEpoch: number; authorityVisibility: "user_private" | "workspace_shared"; authorityOwnerOrganizationMembershipId: string | null; personalResourceProtocolVersion: number; mcpApprovalPolicies: Record; connectorActionPolicies: schema.ConnectorActionPolicySnapshotEntry[]; }, ): Promise { const authoritySnapshot = assertSessionAuthoritySnapshot({ attemptId: input.id, authorityEpoch: input.authorityEpoch, authorityVisibility: input.authorityVisibility, authorityOwnerOrganizationMembershipId: input.authorityOwnerOrganizationMembershipId, }); const [inserted] = await db .insert(schema.sessionTurnAttempts) .values({ ...input, ...authoritySnapshot, state: "claimed", }) // Only an idempotent replay of this exact preallocated attempt ID may // enter the comparison path below. A collision on live-session, live-turn, // or Temporal dispatch ownership is a distinct invariant violation and // must not be disguised as an attempt-ID conflict. .onConflictDoNothing({ target: schema.sessionTurnAttempts.id }) .returning(); if (inserted) return inserted; const [existing] = await db .select() .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.id, input.id), ), ) .for("update") .limit(1); const existingAuthoritySnapshot = existing ? assertSessionAuthoritySnapshot({ attemptId: existing.id, authorityEpoch: existing.authorityEpoch, authorityVisibility: existing.authorityVisibility, authorityOwnerOrganizationMembershipId: existing.authorityOwnerOrganizationMembershipId, }) : null; if ( !existing || existing.accountId !== input.accountId || existing.sessionId !== input.sessionId || existing.turnId !== input.turnId || existing.executionGeneration !== input.executionGeneration || !existingAuthoritySnapshot || !sessionAuthoritySnapshotsEqual(existingAuthoritySnapshot, authoritySnapshot) || existing.temporalWorkflowId !== input.temporalWorkflowId || existing.temporalWorkflowRunId !== input.temporalWorkflowRunId || existing.temporalActivityId !== input.temporalActivityId || existing.personalResourceProtocolVersion !== input.personalResourceProtocolVersion || // JSONB changes object key order; compare the immutable snapshot by value // so exact-attempt reentry remains idempotent after a database round trip. !isDeepStrictEqual(existing.connectorActionPolicies, input.connectorActionPolicies) || existing.state === "closed" ) { throw new SessionControlInvariantError( `Attempt ${input.id} conflicts with a different or closed ownership chain`, ); } return existing; } export type SessionAuthoritySnapshot = { authorityEpoch: number; authorityVisibility: "user_private" | "workspace_shared"; authorityOwnerOrganizationMembershipId: string | null; }; /** * Validate the complete accepted-attempt authority tuple. Missing or partial * values are not legacy defaults: current claim writers must provide the * exact locked session authority explicitly. */ export function assertSessionAuthoritySnapshot(input: { attemptId?: string; authorityEpoch: unknown; authorityVisibility: unknown; authorityOwnerOrganizationMembershipId: unknown; }): SessionAuthoritySnapshot { const valid = Number.isSafeInteger(input.authorityEpoch) && (input.authorityEpoch as number) > 0 && (input.authorityVisibility === "user_private" || input.authorityVisibility === "workspace_shared") && ((input.authorityVisibility === "user_private" && typeof input.authorityOwnerOrganizationMembershipId === "string") || (input.authorityVisibility === "workspace_shared" && (input.authorityOwnerOrganizationMembershipId === null || typeof input.authorityOwnerOrganizationMembershipId === "string"))); if (!valid) { throw new SessionControlInvariantError( `Attempt ${input.attemptId ?? "unknown"} has an invalid session authority snapshot`, ); } return { authorityEpoch: input.authorityEpoch as number, authorityVisibility: input.authorityVisibility as SessionAuthoritySnapshot["authorityVisibility"], authorityOwnerOrganizationMembershipId: input.authorityOwnerOrganizationMembershipId as | string | null, }; } export function sessionAuthoritySnapshotMatchesSession( snapshot: SessionAuthoritySnapshot, session: Pick< typeof schema.sessions.$inferSelect, "authorityEpoch" | "visibility" | "ownerOrganizationMembershipId" > & { executionAuthorityEpoch?: number }, ): boolean { return ( snapshot.authorityEpoch >= (session.executionAuthorityEpoch ?? session.authorityEpoch) && snapshot.authorityEpoch <= session.authorityEpoch && (snapshot.authorityVisibility === session.visibility || (snapshot.authorityVisibility === "user_private" && session.visibility === "workspace_shared" && snapshot.authorityEpoch < session.authorityEpoch)) && snapshot.authorityOwnerOrganizationMembershipId === (session.ownerOrganizationMembershipId ?? null) ); } export function sessionAuthoritySnapshotsEqual( left: Pick< SessionAuthoritySnapshot, "authorityEpoch" | "authorityVisibility" | "authorityOwnerOrganizationMembershipId" >, right: Pick< SessionAuthoritySnapshot, "authorityEpoch" | "authorityVisibility" | "authorityOwnerOrganizationMembershipId" >, ): boolean { return ( left.authorityEpoch === right.authorityEpoch && left.authorityVisibility === right.authorityVisibility && left.authorityOwnerOrganizationMembershipId === right.authorityOwnerOrganizationMembershipId ); } /** * Close the exact first-class owner while the caller still holds the owning * session/turn locks. Every path that clears `session_turns.active_attempt_id` * must call this in the same transaction; otherwise a later claim would either * collide with a zombie live owner or have to weaken the ownership fence. */ export async function closeSessionTurnAttemptInTransaction( db: Database, input: { id: string; accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; outcome: SessionTurnAttemptOutcome; closedAt?: Date; }, ): Promise<{ action: "closed" | "already_closed" }> { const [attempt] = await db .select() .from(schema.sessionTurnAttempts) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.id, input.id), ), ) .for("update") .limit(1); if ( !attempt || attempt.accountId !== input.accountId || attempt.sessionId !== input.sessionId || attempt.turnId !== input.turnId || attempt.executionGeneration !== input.executionGeneration ) { throw new SessionControlInvariantError( `Attempt ${input.id} does not own the expected session turn generation`, ); } if (attempt.state === "closed") { if (attempt.outcome !== input.outcome) { throw new SessionControlInvariantError( `Attempt ${input.id} is already closed as ${attempt.outcome ?? "unknown"}`, ); } return { action: "already_closed" }; } if (attempt.state !== "claimed" && attempt.state !== "running") { throw new SessionControlInvariantError( `Attempt ${input.id} has invalid live state ${attempt.state}`, ); } const now = input.closedAt ?? new Date(); const [closed] = await db .update(schema.sessionTurnAttempts) .set({ state: "closed", outcome: input.outcome, workerId: null, leaseId: null, leaseExpiresAt: null, closedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionTurnAttempts.workspaceId, input.workspaceId), eq(schema.sessionTurnAttempts.id, input.id), sql`${schema.sessionTurnAttempts.state} in ('claimed', 'running')`, ), ) .returning({ id: schema.sessionTurnAttempts.id }); if (!closed) { throw new SessionControlInvariantError(`Attempt ${input.id} changed while locked`); } return { action: "closed" }; } function targetValues(sessionIds: string[]) { if (sessionIds.length === 0) { throw new SessionControlInvariantError("At least one target session is required"); } return sql.join( sessionIds.map((id) => sql`(${id}::uuid)`), sql`, `, ); } // Who can read a session and who it controls are separate. A paused Only-me // ancestor still pauses a workspace-visible descendant. The control walk reads // under the caller's visibility first; only when that chain stops short of a // root is it re-read in full and the part the caller could not see redacted: // a hidden ancestor contributes its pause state, never its title, actor or // reason. The ordinary path costs no extra statement. // Same label the related-access projection uses for an ancestor the caller cannot read. const HIDDEN_ANCESTOR_DISPLAY_NAME = "An ancestor session"; /** * Re-run a read outside the active viewer's session visibility, then restore * it. Null when no viewer is set: a gap is then a genuine invariant failure. */ async function readOutsideViewerVisibility( db: Database, read: () => Promise, ): Promise { const [row] = await db.execute<{ subjectId: string | null }>( sql`select nullif(current_setting('opengeni.subject_id', true), '') as "subjectId"`, ); const viewer = row?.subjectId ?? null; if (!viewer) return null; const restore = () => db.execute(sql`select set_config('opengeni.subject_id', ${viewer}, true)`); await db.execute(sql`select set_config('opengeni.subject_id', '', true)`); let value: T; try { value = await read(); } catch (error) { await restore().catch(() => undefined); throw error; } await restore(); return value; } async function sessionsHiddenFromViewer( db: Database, workspaceId: string, sessionIds: Iterable, ): Promise> { const ids = [...new Set(sessionIds)]; if (ids.length === 0) return new Set(); const visible = await db.execute<{ id: string }>(sql` select session.id from ${schema.sessions} session where session.workspace_id = ${workspaceId} and session.id in (${sql.join( ids.map((id) => sql`${id}::uuid`), sql`, `, )}) `); const visibleIds = new Set(visible.map((row: { id: string }) => row.id)); return new Set(ids.filter((id) => !visibleIds.has(id))); } function redactHiddenAncestor(row: T): T { return { ...row, title: HIDDEN_ANCESTOR_DISPLAY_NAME, directControlChangedBy: null, directControlReason: null, }; } /** True when some target's visible chain ends below its root. */ function ancestryStopsShort(rows: AncestryRow[]): boolean { const deepest = new Map(); for (const row of rows) { const current = deepest.get(row.targetId); if (!current || Number(row.depth) > Number(current.depth)) deepest.set(row.targetId, row); } for (const row of deepest.values()) { if (row.parentSessionId !== null && !row.cycle && Number(row.depth) < SESSION_ANCESTRY_LIMIT) { return true; } } return false; } async function loadTargetAncestryRows( db: Database, workspaceId: string, sessionIds: string[], ): Promise { const visible = await queryTargetAncestryRows(db, workspaceId, sessionIds); if (!ancestryStopsShort(visible)) return visible; const complete = await readOutsideViewerVisibility(db, () => queryTargetAncestryRows(db, workspaceId, sessionIds), ); if (!complete) return visible; const visibleIds = new Set(visible.map((row) => row.sessionId)); return complete.map((row) => (visibleIds.has(row.sessionId) ? row : redactHiddenAncestor(row))); } async function loadAncestryNodes( db: Database, workspaceId: string, sessionIds: string[], ): Promise> { const visible = await queryAncestryNodes(db, workspaceId, sessionIds); const stopsShort = [...visible.values()].some( (node) => node.parentSessionId !== null && !visible.has(node.parentSessionId), ); if (!stopsShort) return visible; const complete = await readOutsideViewerVisibility(db, () => queryAncestryNodes(db, workspaceId, sessionIds), ); if (!complete) return visible; for (const [sessionId, node] of complete) { if (!visible.has(sessionId)) complete.set(sessionId, redactHiddenAncestor(node)); } return complete; } const TARGET_PATH_PROJECTION_LIMIT = 128; async function queryTargetAncestryRows( db: Database, workspaceId: string, sessionIds: string[], ): Promise { return await db.execute(sql` with recursive targets(id) as (values ${targetValues(sessionIds)}), ancestry as ( select target.id as target_id, session.id as session_id, session.parent_session_id, session.title, session.direct_control_state, session.direct_pause_revision, session.subtree_run_override_revision, session.control_version, session.direct_control_changed_by, session.direct_control_reason, session.direct_control_changed_at, 0::integer as depth, array[session.id]::uuid[] as path, false as cycle from targets target join ${schema.sessions} session on session.workspace_id = ${workspaceId} and session.id = target.id union all select child.target_id, parent.id, parent.parent_session_id, parent.title, parent.direct_control_state, parent.direct_pause_revision, parent.subtree_run_override_revision, parent.control_version, parent.direct_control_changed_by, parent.direct_control_reason, parent.direct_control_changed_at, child.depth + 1, child.path || parent.id, parent.id = any(child.path) from ancestry child join ${schema.sessions} parent on parent.workspace_id = ${workspaceId} and parent.id = child.parent_session_id where child.parent_session_id is not null and not child.cycle and child.depth < ${SESSION_ANCESTRY_LIMIT} ) select target_id as "targetId", session_id as "sessionId", parent_session_id as "parentSessionId", title, direct_control_state as "directState", direct_pause_revision as "directPauseRevision", subtree_run_override_revision as "subtreeRunOverrideRevision", control_version as "controlVersion", direct_control_changed_by as "directControlChangedBy", direct_control_reason as "directControlReason", direct_control_changed_at as "directControlChangedAt", depth, cycle from ancestry order by target_id, depth `); } async function queryAncestryNodes( db: Database, workspaceId: string, sessionIds: string[], ): Promise> { const rows = await db.execute(sql` with recursive targets(id) as (values ${targetValues(sessionIds)}), ancestry_ids(id) as ( select session.id from targets target join ${schema.sessions} session on session.workspace_id = ${workspaceId} and session.id = target.id union select parent.id from ancestry_ids child join ${schema.sessions} current on current.workspace_id = ${workspaceId} and current.id = child.id join ${schema.sessions} parent on parent.workspace_id = current.workspace_id and parent.id = current.parent_session_id ) select session.id as "sessionId", session.parent_session_id as "parentSessionId", session.title, session.direct_control_state as "directState", session.direct_pause_revision as "directPauseRevision", session.subtree_run_override_revision as "subtreeRunOverrideRevision", session.control_version as "controlVersion", session.direct_control_changed_by as "directControlChangedBy", session.direct_control_reason as "directControlReason", session.direct_control_changed_at as "directControlChangedAt" from ancestry_ids ancestry join ${schema.sessions} session on session.workspace_id = ${workspaceId} and session.id = ancestry.id `); return new Map(rows.map((row: AncestryNode) => [row.sessionId, row])); } function ancestryRowsForTarget(targetId: string, nodes: Map): AncestryRow[] { const rows: AncestryRow[] = []; const path = new Set(); let sessionId: string | null = targetId; for (let depth = 0; sessionId !== null; depth += 1) { const node = nodes.get(sessionId); if (!node) break; const cycle = path.has(sessionId); rows.push({ ...node, targetId, depth, cycle }); if (cycle || depth >= SESSION_ANCESTRY_LIMIT) break; path.add(sessionId); sessionId = node.parentSessionId; } return rows; } function assertCompleteAncestry(sessionId: string, rows: AncestryRow[]): void { if (rows.length === 0) { throw new SessionMissingFromWorkspaceError(sessionId); } if (rows.some((row) => row.cycle)) { throw new SessionControlInvariantError(`Session ${sessionId} has cyclic ancestry`); } const last = rows.at(-1)!; const depth = Number(last.depth); if (last.parentSessionId !== null) { throw new SessionControlInvariantError( depth >= SESSION_ANCESTRY_LIMIT ? `Session ${sessionId} ancestry exceeds ${SESSION_ANCESTRY_LIMIT}` : `Session ${sessionId} has a missing ancestor ${last.parentSessionId}`, ); } } function blockerForSession(row: AncestryRow, revision: number): EffectiveControlBlocker { return { kind: "session", sessionId: row.sessionId, displayName: row.title?.trim() || "Untitled session", actor: row.directControlChangedBy, reason: row.directControlReason, changedAt: asDate(row.directControlChangedAt), revision, }; } function projectEffectiveControl( workspace: WorkspaceControlRow, targetId: string, rows: AncestryRow[], settlementAttempts: SettlementAttemptCounts, stoppingBackgroundCommandCount: number, ): EffectiveSessionControl { assertCompleteAncestry(targetId, rows); const workspaceRevision = asSafeRevision(workspace.revision, "workspace control revision")!; const path = rows.map((row) => ({ row, depth: Number(row.depth), pauseRevision: asSafeRevision(row.directPauseRevision, "direct pause revision"), overrideRevision: asSafeRevision( row.subtreeRunOverrideRevision, "subtree run override revision", ), controlVersion: asSafeRevision(row.controlVersion, "session control version")!, })); const undefeated: Array<{ blocker: EffectiveControlBlocker; depth: number }> = []; for (const candidate of path) { if (candidate.row.directState !== "paused" || candidate.pauseRevision === null) continue; const defeated = path.some( (possibleOverride) => possibleOverride.depth < candidate.depth && possibleOverride.overrideRevision !== null && possibleOverride.overrideRevision > candidate.pauseRevision!, ); if (!defeated) { undefeated.push({ blocker: blockerForSession(candidate.row, candidate.pauseRevision), depth: candidate.depth, }); } } const workspacePauseRevision = asSafeRevision( workspace.workspacePauseRevision, "workspace pause revision", ); if (workspace.workspaceState === "paused") { if (workspacePauseRevision === null) { throw new SessionControlInvariantError("Paused workspace is missing its pause revision"); } const defeated = path.some( (candidate) => candidate.overrideRevision !== null && candidate.overrideRevision > workspacePauseRevision, ); if (!defeated) { undefeated.push({ blocker: { kind: "workspace", displayName: "Workspace", actor: workspace.changedBy, reason: workspace.reason, changedAt: asDate(workspace.changedAt), revision: workspacePauseRevision, }, depth: Number.POSITIVE_INFINITY, }); } } undefeated.sort((left, right) => left.depth - right.depth); const blockers = undefeated.map(({ blocker }) => blocker); const primaryBlocker = blockers[0] ?? null; const target = path[0]!; const override = path .filter((candidate) => candidate.overrideRevision !== null) .sort((left, right) => right.overrideRevision! - left.overrideRevision!)[0]; const options: EffectiveControlResumeOption[] = []; if (blockers.length > 0) { options.push({ scope: "selected", targetId, selectedStateAfter: "active", impactCopy: "Resume this session and its descendants without changing sibling workstreams.", }); for (const entry of undefeated) { if (entry.blocker.kind !== "session" || entry.blocker.sessionId === targetId) continue; const remaining = undefeated.find( (candidate) => candidate.depth < entry.depth && candidate.blocker.sessionId !== entry.blocker.sessionId, )?.blocker; options.push({ scope: "session", targetId: entry.blocker.sessionId!, selectedStateAfter: remaining ? "paused" : "active", ...(remaining ? { remainingPrimaryBlocker: remaining } : {}), impactCopy: `Resume the workstream rooted at ${entry.blocker.displayName}.`, }); } if (workspace.workspaceState === "paused") { const remaining = undefeated.find((entry) => entry.blocker.kind === "session")?.blocker; options.push({ scope: "workspace", selectedStateAfter: remaining ? "paused" : "active", ...(remaining ? { remainingPrimaryBlocker: remaining } : {}), impactCopy: "Resume the entire workspace; narrower session pauses remain in force.", }); } } const etagFacts = { workspace: { state: workspace.workspaceState, pauseRevision: workspacePauseRevision, }, path: path.map((candidate) => ({ sessionId: candidate.row.sessionId, directState: candidate.row.directState, pauseRevision: candidate.pauseRevision, overrideRevision: candidate.overrideRevision, })), }; return { state: blockers.length > 0 ? "paused" : "active", controlVersion: Math.max( workspaceRevision, ...path.map((candidate) => candidate.controlVersion), ), controlEtag: controlEtag(etagFacts), directState: target.row.directState === "paused" ? "paused" : "active", primaryBlocker, additionalBlockerCount: Math.max(0, blockers.length - 1), blockers, resumeOptions: options, override: override?.overrideRevision === null || !override ? null : { rootSessionId: override.row.sessionId, revision: override.overrideRevision, }, settlement: settlementAttempts.attemptCount > 0 ? { state: "stopping", ...settlementAttempts } : null, backgroundCommandSettlement: stoppingBackgroundCommandCount > 0 ? { state: "stopping", commandCount: stoppingBackgroundCommandCount } : null, }; } /** * Open settlement work (stopping background commands, unfinished * interruptions) is rare, while requested targets can root large subtrees with * long histories. Both summaries therefore start from the small open set and * walk parent edges upward to the requested targets. Sessions have one parent, * so a descendant within SESSION_ANCESTRY_LIMIT edges of a target is exactly an * open row whose bounded ancestor walk reaches that target; the path array * stops legacy cycles the same way the downward walk did. */ function openSettlementAncestorsSql(workspaceId: string, origins: SQL): SQL { return sql`ancestors(origin_session_id, session_id, depth, path) as ( select origin.session_id, origin.session_id, 0::integer, array[origin.session_id]::uuid[] from (select distinct session_id from ${origins}) origin union all select ancestor.origin_session_id, step.parent_session_id, ancestor.depth + 1, ancestor.path || step.parent_session_id from ancestors ancestor join ${schema.sessions} step on step.workspace_id = ${workspaceId} and step.id = ancestor.session_id where step.parent_session_id is not null and not step.parent_session_id = any(ancestor.path) and ancestor.depth < ${SESSION_ANCESTRY_LIMIT} )`; } async function stoppingBackgroundCommandCounts( db: Database, workspaceId: string, sessionIds: string[], ): Promise> { const rows = await db.execute<{ sessionId: string; commandCount: number | string }>(sql` with recursive targets(id) as (values ${targetValues(sessionIds)}), stopping as materialized ( -- session_background_commands_active_session_idx holds only running and -- stopping commands. select command.id, command.session_id from ${schema.sessionBackgroundCommands} command where command.workspace_id = ${workspaceId} and command.state = 'stopping' ), ${openSettlementAncestorsSql(workspaceId, sql`stopping`)} select target.id as "sessionId", count(distinct command.id)::integer as "commandCount" from targets target join ancestors ancestor on ancestor.session_id = target.id join stopping command on command.session_id = ancestor.origin_session_id group by target.id `); return new Map( rows.map((row: { sessionId: string; commandCount: number | string }) => [ row.sessionId, Number(row.commandCount), ]), ); } async function settlementAttemptCounts( db: Database, workspaceId: string, sessionIds: string[], ): Promise> { // session_attempt_interruptions_open_settlement_idx holds only interruptions // that are unsettled or whose attempt may not have quiesced yet, so this read // is proportional to open work, not to subtree size or interruption history. const rows = await db.execute<{ sessionId: string; attemptCount: number | string; interruptionPendingCount: number | string; quiescencePendingCount: number | string; }>(sql` with recursive targets(id) as (values ${targetValues(sessionIds)}), open_interruptions as materialized ( select interruption.session_id, interruption.attempt_id, interruption.state in ('pending', 'delivered', 'acknowledged') as interruption_pending, interruption.state in ('settled', 'rejected_stale') and attempt.quiesced_at is null as quiescence_pending from ${schema.sessionAttemptInterruptions} interruption join ${schema.sessionTurnAttempts} attempt on attempt.workspace_id = interruption.workspace_id and attempt.id = interruption.attempt_id where interruption.workspace_id = ${workspaceId} and ( interruption.state in ('pending', 'delivered', 'acknowledged') or not interruption.attempt_quiesced ) and ( interruption.state in ('pending', 'delivered', 'acknowledged') or ( interruption.state in ('settled', 'rejected_stale') and attempt.quiesced_at is null ) ) ), ${openSettlementAncestorsSql(workspaceId, sql`open_interruptions`)}, interruptions as ( select target.id as target_id, interruption.attempt_id, bool_or(interruption.interruption_pending) as interruption_pending, bool_or(interruption.quiescence_pending) as quiescence_pending from targets target join ancestors ancestor on ancestor.session_id = target.id join open_interruptions interruption on interruption.session_id = ancestor.origin_session_id group by target.id, interruption.attempt_id ) select target_id as "sessionId", count(attempt_id)::integer as "attemptCount", count(attempt_id) filter (where interruption_pending)::integer as "interruptionPendingCount", count(attempt_id) filter (where quiescence_pending)::integer as "quiescencePendingCount" from interruptions group by target_id `); return new Map( rows.map( (row: { sessionId: string; attemptCount: number | string; interruptionPendingCount: number | string; quiescencePendingCount: number | string; }) => [ row.sessionId, { attemptCount: Number(row.attemptCount), interruptionPendingCount: Number(row.interruptionPendingCount), quiescencePendingCount: Number(row.quiescencePendingCount), }, ], ), ); } type SingleTargetControlRow = AncestryRow & { hasChildren: boolean; attemptCount: number | string; interruptionPendingCount: number | string; quiescencePendingCount: number | string; commandCount: number | string; }; /** * A leaf's settlement summaries need no descendant walk. Detect children and * read its direct summaries in ONE statement: a separate EXISTS followed by * direct counts could miss a child committed between READ COMMITTED snapshots. * This is only a projection, never a subtree writer/admission shortcut. */ async function loadSingleTargetControlRow( db: Database, workspaceId: string, sessionId: string, ): Promise { const rows = await db.execute(sql` with target as materialized ( select session.id, session.parent_session_id, session.title, session.direct_control_state, session.direct_pause_revision, session.subtree_run_override_revision, session.control_version, session.direct_control_changed_by, session.direct_control_reason, session.direct_control_changed_at, exists ( select 1 from ${schema.sessions} child where child.workspace_id = ${workspaceId} and child.parent_session_id = session.id ) as has_children from ${schema.sessions} session where session.workspace_id = ${workspaceId} and session.id = ${sessionId} ) select target.id as "targetId", target.id as "sessionId", target.parent_session_id as "parentSessionId", target.title, target.direct_control_state as "directState", target.direct_pause_revision as "directPauseRevision", target.subtree_run_override_revision as "subtreeRunOverrideRevision", target.control_version as "controlVersion", target.direct_control_changed_by as "directControlChangedBy", target.direct_control_reason as "directControlReason", target.direct_control_changed_at as "directControlChangedAt", 0::integer as depth, false as cycle, target.has_children as "hasChildren", stopping.attempt_count as "attemptCount", stopping.interruption_pending_count as "interruptionPendingCount", stopping.quiescence_pending_count as "quiescencePendingCount", commands.command_count as "commandCount" from target cross join lateral ( select count(*)::integer as attempt_count, count(*) filter (where interruption_pending)::integer as interruption_pending_count, count(*) filter (where quiescence_pending)::integer as quiescence_pending_count from ( select interruption.attempt_id, bool_or(interruption.state in ('pending', 'delivered', 'acknowledged')) as interruption_pending, bool_or(interruption.state in ('settled', 'rejected_stale') and attempt.quiesced_at is null) as quiescence_pending from ${schema.sessionAttemptInterruptions} interruption join ${schema.sessionTurnAttempts} attempt on attempt.workspace_id = interruption.workspace_id and attempt.id = interruption.attempt_id where not target.has_children and interruption.workspace_id = ${workspaceId} and interruption.session_id = target.id and (interruption.state in ('pending', 'delivered', 'acknowledged') or (interruption.state in ('settled', 'rejected_stale') and attempt.quiesced_at is null)) group by interruption.attempt_id ) interruptions ) stopping cross join lateral ( select count(distinct command.id)::integer as command_count from ${schema.sessionBackgroundCommands} command where not target.has_children and command.workspace_id = ${workspaceId} and command.session_id = target.id and command.state = 'stopping' ) commands `); return rows[0]; } export async function evaluateSessionControls( db: Database, workspaceId: string, sessionIds: string[], options: { lock?: WorkspaceControlLockMode; /** Reuse a control row already locked before workspace/session/turn rows. */ workspaceControl?: WorkspaceControlRow | undefined; } = {}, ): Promise> { const uniqueIds = [...new Set(sessionIds)]; if (uniqueIds.length === 0) { return new Map(); } if (options.workspaceControl && options.workspaceControl.workspaceId !== workspaceId) { throw new SessionControlInvariantError( `Locked workspace control ${options.workspaceControl.workspaceId} does not match ${workspaceId}`, ); } const workspace = options.workspaceControl ?? (await lockWorkspaceInferenceControl(db, workspaceId, options.lock ?? "share")); if (uniqueIds.length === 1) { const sessionId = uniqueIds[0]!; const target = await loadSingleTargetControlRow(db, workspaceId, sessionId); if (!target) { throw new SessionMissingFromWorkspaceError(sessionId); } const stopping = target.hasChildren ? ((await settlementAttemptCounts(db, workspaceId, uniqueIds)).get(sessionId) ?? NO_SETTLEMENT_ATTEMPTS) : { attemptCount: Number(target.attemptCount), interruptionPendingCount: Number(target.interruptionPendingCount), quiescencePendingCount: Number(target.quiescencePendingCount), }; const stoppingCommands = target.hasChildren ? ((await stoppingBackgroundCommandCounts(db, workspaceId, uniqueIds)).get(sessionId) ?? 0) : Number(target.commandCount); // A root's control node is already complete; nonroots retain the bounded // recursive ancestry validation (including missing ancestors and cycles). const ancestry = target.parentSessionId === null ? [target] : await loadTargetAncestryRows(db, workspaceId, uniqueIds); return new Map([ [ sessionId, projectEffectiveControl(workspace, sessionId, ancestry, stopping, stoppingCommands), ], ]); } const stopping = await settlementAttemptCounts(db, workspaceId, uniqueIds); const stoppingCommands = await stoppingBackgroundCommandCounts(db, workspaceId, uniqueIds); const result = new Map(); if (uniqueIds.length <= TARGET_PATH_PROJECTION_LIMIT) { // PostgreSQL's direct target-path plan is substantially faster for the // ordinary one-session and paged-list cases. Keep its bounded row shape. const ancestry = await loadTargetAncestryRows(db, workspaceId, uniqueIds); const ancestryByTarget = new Map(); for (const row of ancestry) { const rows = ancestryByTarget.get(row.targetId); if (rows) rows.push(row); else ancestryByTarget.set(row.targetId, [row]); } for (const sessionId of uniqueIds) { result.set( sessionId, projectEffectiveControl( workspace, sessionId, ancestryByTarget.get(sessionId) ?? [], stopping.get(sessionId) ?? NO_SETTLEMENT_ATTEMPTS, stoppingCommands.get(sessionId) ?? 0, ), ); } return result; } // Large sets fetch each shared ancestor exactly once. Returning one row per // target/ancestor pair makes a 10k-session tree explode into millions of // protocol objects even though the tree itself contains only 10k nodes. const ancestry = await loadAncestryNodes(db, workspaceId, uniqueIds); for (const sessionId of uniqueIds) { result.set( sessionId, projectEffectiveControl( workspace, sessionId, ancestryRowsForTarget(sessionId, ancestry), stopping.get(sessionId) ?? NO_SETTLEMENT_ATTEMPTS, stoppingCommands.get(sessionId) ?? 0, ), ); } return result; } /** * Evaluate only the control facts needed to admit an already locked session * write. The workspace-control row must be reused when the caller established * the canonical prefix before session/turn/attempt locks. * * Deliberately omit settlementAttemptCounts and * stoppingBackgroundCommandCounts: those recursive summaries do not affect * effective pause state and their results are discarded by the write fence. */ export async function evaluateSessionWriteAdmissionControl( db: Database, workspaceId: string, sessionId: string, options: { lock?: WorkspaceControlLockMode; workspaceControl?: WorkspaceControlRow | undefined; /** Same-transaction NO KEY UPDATE row; KEY SHARE is not sufficient. */ lockedSession?: Pick< typeof schema.sessions.$inferSelect, | "id" | "workspaceId" | "parentSessionId" | "directControlState" | "directPauseRevision" | "subtreeRunOverrideRevision" | "controlVersion" >; } = {}, ): Promise { if (options.workspaceControl && options.workspaceControl.workspaceId !== workspaceId) { throw new SessionControlInvariantError( `Locked workspace control ${options.workspaceControl.workspaceId} does not match ${workspaceId}`, ); } const workspace = options.workspaceControl ?? (await lockWorkspaceInferenceControl(db, workspaceId, options.lock ?? "share")); const locked = options.lockedSession; if (locked && (locked.id !== sessionId || locked.workspaceId !== workspaceId)) { throw new SessionControlInvariantError("Locked session does not match write admission scope"); } if (locked?.parentSessionId === null) { // A locked root is its complete ancestry. Keep the same revision validation // and blocker precedence as projectEffectiveControl, without re-reading the // row or building display names, resume options and settlement projections. const workspaceRevision = asSafeRevision(workspace.revision, "workspace control revision")!; const pauseRevision = asSafeRevision(locked.directPauseRevision, "direct pause revision"); const overrideRevision = asSafeRevision( locked.subtreeRunOverrideRevision, "subtree run override revision", ); const controlVersion = asSafeRevision(locked.controlVersion, "session control version")!; const workspacePauseRevision = asSafeRevision( workspace.workspacePauseRevision, "workspace pause revision", ); if (workspace.workspaceState === "paused" && workspacePauseRevision === null) { throw new SessionControlInvariantError("Paused workspace is missing its pause revision"); } const primaryBlockerKind = locked.directControlState === "paused" && pauseRevision !== null ? "session" : workspace.workspaceState === "paused" && !(overrideRevision !== null && overrideRevision > workspacePauseRevision!) ? "workspace" : null; return { state: primaryBlockerKind === null ? "active" : "paused", controlVersion: Math.max(workspaceRevision, controlVersion), primaryBlockerKind, }; } const projected = projectEffectiveControl( workspace, sessionId, await loadTargetAncestryRows(db, workspaceId, [sessionId]), NO_SETTLEMENT_ATTEMPTS, 0, ); return { state: projected.state, controlVersion: projected.controlVersion, primaryBlockerKind: projected.primaryBlocker?.kind ?? null, }; } type SessionDiscoveryControlRow = { targetId: string; ancestryCount: number | string; reachedRoot: boolean; maxDepth: number | string | null; blockerCount: number | string; primaryKind: "session" | "workspace" | null; primarySessionId: string | null; primaryDisplayName: string | null; primaryDisplayNameOriginalChars: number | string | null; }; /** * Return one compact aggregate row per target for `sessions_list`. * * Unlike `evaluateSessionControls`, the database boundary never returns a row * per blocker/ancestor, nor does application code construct blocker or resume * option arrays. The recursive walk carries no growing visited-path array: a * missing ancestor stops below the limit, while a cycle cannot reach a root and * therefore runs into the hard `SESSION_ANCESTRY_LIMIT`. The externally * supplied target set is capped by `SESSION_DISCOVERY_CONTROL_TARGET_LIMIT`. */ export async function evaluateSessionDiscoveryControls( db: Database, workspaceId: string, sessionIds: string[], ): Promise> { const uniqueIds = [...new Set(sessionIds)]; if (uniqueIds.length === 0) return new Map(); if (uniqueIds.length > SESSION_DISCOVERY_CONTROL_TARGET_LIMIT) { throw new SessionControlInvariantError( `Session discovery control projection exceeds ${SESSION_DISCOVERY_CONTROL_TARGET_LIMIT} targets`, ); } // Discovery owns one read-only repeatable-read snapshot, so this projection // must not join the writer lock graph merely to keep workspace/session facts // coherent. The snapshot is the consistency boundary. const workspace = await lockWorkspaceInferenceControl(db, workspaceId, "none"); const workspacePauseRevision = asSafeRevision( workspace.workspacePauseRevision, "workspace pause revision", ); if (workspace.workspaceState === "paused" && workspacePauseRevision === null) { throw new SessionControlInvariantError("Paused workspace is missing its pause revision"); } const readRows = async () => [ ...(await db.execute(sql` with recursive targets(id) as (values ${targetValues(uniqueIds)}), ancestry as ( select target.id as target_id, session.id as session_id, session.parent_session_id, left(coalesce(nullif(btrim(session.title), ''), 'Untitled session'), ${SESSION_DISCOVERY_CONTROL_TITLE_MAX_CHARS}) as display_name, char_length(coalesce(nullif(btrim(session.title), ''), 'Untitled session'))::integer as display_name_original_chars, session.direct_control_state, session.direct_pause_revision, session.subtree_run_override_revision, 0::integer as depth from targets target join ${schema.sessions} session on session.workspace_id = ${workspaceId} and session.id = target.id union all select child.target_id, parent.id, parent.parent_session_id, left(coalesce(nullif(btrim(parent.title), ''), 'Untitled session'), ${SESSION_DISCOVERY_CONTROL_TITLE_MAX_CHARS}), char_length(coalesce(nullif(btrim(parent.title), ''), 'Untitled session'))::integer, parent.direct_control_state, parent.direct_pause_revision, parent.subtree_run_override_revision, child.depth + 1 from ancestry child join ${schema.sessions} parent on parent.workspace_id = ${workspaceId} and parent.id = child.parent_session_id where child.parent_session_id is not null and child.depth < ${SESSION_ANCESTRY_LIMIT} ), path as ( select ancestry.*, max(ancestry.subtree_run_override_revision) over ( partition by ancestry.target_id order by ancestry.depth rows between unbounded preceding and 1 preceding ) as descendant_override_revision from ancestry ), session_blockers as ( select path.target_id, 'session'::text as kind, path.session_id, path.display_name, path.display_name_original_chars, path.depth from path where path.direct_control_state = 'paused' and path.direct_pause_revision is not null and ( path.descendant_override_revision is null or path.descendant_override_revision <= path.direct_pause_revision ) ), workspace_blockers as ( select target.id as target_id, 'workspace'::text as kind, null::uuid as session_id, 'Workspace'::text as display_name, 9::integer as display_name_original_chars, ${SESSION_ANCESTRY_LIMIT + 1}::integer as depth from targets target where ${workspace.workspaceState === "paused"} and not exists ( select 1 from path where path.target_id = target.id and path.subtree_run_override_revision is not null and path.subtree_run_override_revision > ${workspacePauseRevision} ) ), blockers as ( select * from session_blockers union all select * from workspace_blockers ), primary_blockers as ( select distinct on (blockers.target_id) blockers.target_id, blockers.kind, blockers.session_id, blockers.display_name, blockers.display_name_original_chars from blockers order by blockers.target_id, blockers.depth ), blocker_counts as ( select blockers.target_id, count(*)::integer as blocker_count from blockers group by blockers.target_id ), ancestry_metadata as ( select ancestry.target_id, count(*)::integer as ancestry_count, bool_or(ancestry.parent_session_id is null) as reached_root, max(ancestry.depth)::integer as max_depth from ancestry group by ancestry.target_id ) select target.id as "targetId", coalesce(metadata.ancestry_count, 0)::integer as "ancestryCount", coalesce(metadata.reached_root, false) as "reachedRoot", metadata.max_depth as "maxDepth", coalesce(counts.blocker_count, 0)::integer as "blockerCount", primary_blocker.kind as "primaryKind", primary_blocker.session_id as "primarySessionId", primary_blocker.display_name as "primaryDisplayName", primary_blocker.display_name_original_chars as "primaryDisplayNameOriginalChars" from targets target left join ancestry_metadata metadata on metadata.target_id = target.id left join blocker_counts counts on counts.target_id = target.id left join primary_blockers primary_blocker on primary_blocker.target_id = target.id order by target.id `)), ]; let rows = await readRows(); const stopsShort = rows.some( (row) => !row.reachedRoot && Number(row.ancestryCount) > 0 && (row.maxDepth === null || Number(row.maxDepth) < SESSION_ANCESTRY_LIMIT), ); const complete = stopsShort ? await readOutsideViewerVisibility(db, readRows) : null; if (complete) { const hiddenBlockers = await sessionsHiddenFromViewer( db, workspaceId, complete.flatMap((row) => row.primarySessionId && row.primarySessionId !== row.targetId ? [row.primarySessionId] : [], ), ); rows = complete.map((row) => row.primarySessionId && hiddenBlockers.has(row.primarySessionId) ? { ...row, primaryDisplayName: HIDDEN_ANCESTOR_DISPLAY_NAME, primaryDisplayNameOriginalChars: HIDDEN_ANCESTOR_DISPLAY_NAME.length, } : row, ); } const result = new Map(); for (const row of rows) { const ancestryCount = Number(row.ancestryCount); const maxDepth = row.maxDepth === null ? null : Number(row.maxDepth); if (ancestryCount === 0) { throw new SessionMissingFromWorkspaceError(row.targetId); } if (!row.reachedRoot) { throw new SessionControlInvariantError( maxDepth !== null && maxDepth >= SESSION_ANCESTRY_LIMIT ? `Session ${row.targetId} ancestry exceeds ${SESSION_ANCESTRY_LIMIT}` : `Session ${row.targetId} has a missing ancestor`, ); } const blockerCount = Number(row.blockerCount); const primaryBlocker = row.primaryKind ? { kind: row.primaryKind, ...(row.primarySessionId ? { sessionId: row.primarySessionId } : {}), displayName: row.primaryDisplayName ?? (row.primaryKind === "workspace" ? "Workspace" : "Untitled session"), displayNameOriginalChars: Number( row.primaryDisplayNameOriginalChars ?? (row.primaryKind === "workspace" ? 9 : "Untitled session".length), ), } : null; if (blockerCount > 0 !== (primaryBlocker !== null)) { throw new SessionControlInvariantError( `Session ${row.targetId} discovery blocker aggregate is inconsistent`, ); } result.set(row.targetId, { state: blockerCount > 0 ? "paused" : "active", primaryBlocker, additionalBlockerCount: Math.max(0, blockerCount - 1), }); } if (result.size !== uniqueIds.length) { throw new SessionControlInvariantError("Session discovery control projection is incomplete"); } return result; } export async function evaluateSessionControl( db: Database, workspaceId: string, sessionId: string, options: { lock?: WorkspaceControlLockMode; workspaceControl?: WorkspaceControlRow | undefined; } = {}, ): Promise { return (await evaluateSessionControls(db, workspaceId, [sessionId], options)).get(sessionId)!; } async function findCommandReceipt( db: Database, input: { workspaceId: string; actor: SessionCommandActor; action: string; targetSessionId: string | null; targetTurnId: string | null; operationKey: string; identityScope: "actor" | "target_operation"; }, ): Promise { const actorSubjectId = input.actor.type === "agent_attempt" ? null : input.actor.subjectId; const actorAttemptId = input.actor.type === "agent_attempt" ? input.actor.attemptId : null; const identity = input.identityScope === "target_operation" ? and( eq(schema.sessionCommandReceipts.workspaceId, input.workspaceId), eq(schema.sessionCommandReceipts.actorType, "agent_attempt"), eq(schema.sessionCommandReceipts.action, input.action), eq(schema.sessionCommandReceipts.targetSessionId, input.targetSessionId!), sql`${schema.sessionCommandReceipts.targetTurnId} is null`, eq(schema.sessionCommandReceipts.operationKey, input.operationKey), ) : and( eq(schema.sessionCommandReceipts.workspaceId, input.workspaceId), eq(schema.sessionCommandReceipts.actorType, input.actor.type), sql`${schema.sessionCommandReceipts.actorSubjectId} is not distinct from ${actorSubjectId}`, sql`${schema.sessionCommandReceipts.actorAttemptId} is not distinct from ${actorAttemptId}::uuid`, eq(schema.sessionCommandReceipts.action, input.action), sql`${schema.sessionCommandReceipts.targetSessionId} is not distinct from ${input.targetSessionId}::uuid`, sql`${schema.sessionCommandReceipts.targetTurnId} is not distinct from ${input.targetTurnId}::uuid`, eq(schema.sessionCommandReceipts.operationKey, input.operationKey), ); const rows = await db.select().from(schema.sessionCommandReceipts).where(identity).for("update"); return rows[0] ?? null; } export type SessionPromptCommandAction = "prompt.send" | "prompt.steer"; async function findPromptCommandReceipts( db: Database, input: { workspaceId: string; actor: SessionCommandActor; operationKey: string; lock?: "none" | "update"; }, ): Promise { const actorSubjectId = input.actor.type === "agent_attempt" ? null : input.actor.subjectId; const actorAttemptId = input.actor.type === "agent_attempt" ? input.actor.attemptId : null; const query = db .select() .from(schema.sessionCommandReceipts) .where( and( eq(schema.sessionCommandReceipts.workspaceId, input.workspaceId), eq(schema.sessionCommandReceipts.actorType, input.actor.type), sql`${schema.sessionCommandReceipts.actorSubjectId} is not distinct from ${actorSubjectId}`, sql`${schema.sessionCommandReceipts.actorAttemptId} is not distinct from ${actorAttemptId}::uuid`, inArray(schema.sessionCommandReceipts.action, ["prompt.send", "prompt.steer"]), eq(schema.sessionCommandReceipts.operationKey, input.operationKey), ), ); const rows = input.lock === "update" ? await query.for("update") : await query; return rows; } function fingerprintedPromptCommandReceipt( receipts: readonly SessionCommandReceiptRow[], ): SessionCommandReceiptRow | null { const fingerprinted = receipts.filter( (receipt) => typeof receipt.result.boundaryRequestHash === "string", ); if (fingerprinted.length > 1) { throw new SessionControlInvariantError( "Prompt operation key resolved to multiple fingerprinted receipts", ); } return fingerprinted[0] ?? null; } function assertPromptCommandReceiptIdentity( receipt: SessionCommandReceiptRow, input: { action: SessionPromptCommandAction; targetSessionId: string; boundaryRequestHash: string; }, ): void { if ( receipt.action !== input.action || receipt.targetSessionId !== input.targetSessionId || receipt.targetTurnId !== null || (typeof receipt.result.boundaryRequestHash === "string" && receipt.result.boundaryRequestHash !== input.boundaryRequestHash) ) { throw new SessionCommandIdempotencyError(); } } /** * Prompt operation keys are actor-scoped across target sessions and across the * Send/Steer action pair. The advisory lock closes the gap left by the legacy * action/target-specific unique index without changing old receipt identities. */ export async function reserveSessionPromptCommandReceipt( db: Database, input: { accountId: string; workspaceId: string; actor: SessionCommandActor; action: SessionPromptCommandAction; targetSessionId: string; operationKey: string; canonicalRequestHash: string; boundaryRequestHash: string; }, ): Promise<{ receipt: SessionCommandReceiptRow; replay: boolean }> { await lockSessionPromptCommandOperation(db, input); const existingReceipts = await findPromptCommandReceipts(db, { workspaceId: input.workspaceId, actor: input.actor, operationKey: input.operationKey, lock: "update", }); const fingerprinted = fingerprintedPromptCommandReceipt(existingReceipts); if (fingerprinted) { assertPromptCommandReceiptIdentity(fingerprinted, input); return { receipt: fingerprinted, replay: true }; } const legacyExact = existingReceipts.find( (receipt) => receipt.action === input.action && receipt.targetSessionId === input.targetSessionId && receipt.targetTurnId === null, ); if (legacyExact) { if (legacyExact.canonicalRequestHash !== input.canonicalRequestHash) { throw new SessionCommandIdempotencyError(); } return { receipt: legacyExact, replay: true }; } return await reserveSessionCommandReceipt(db, { accountId: input.accountId, workspaceId: input.workspaceId, actor: input.actor, action: input.action, targetSessionId: input.targetSessionId, targetTurnId: null, operationKey: input.operationKey, canonicalRequestHash: input.canonicalRequestHash, ...(existingReceipts.length === 0 ? { initialResult: { boundaryRequestHash: input.boundaryRequestHash } } : {}), }); } /** Serialize one actor-scoped prompt operation before replay or reservation. */ export async function lockSessionPromptCommandOperation( db: Database, input: { workspaceId: string; actor: SessionCommandActor; operationKey: string; }, ): Promise { const actorIdentity = input.actor.type === "agent_attempt" ? `attempt:${input.actor.attemptId}` : `${input.actor.type}:${input.actor.subjectId}`; await db.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`session-prompt:${input.workspaceId}:${actorIdentity}:${input.operationKey}`}, 0))`, ); } /** Return only a fully committed exact prompt receipt with the new boundary fingerprint. */ export async function getCompletedSessionPromptCommandReceipt( db: Database, input: { workspaceId: string; actor: SessionCommandActor; action: SessionPromptCommandAction; targetSessionId: string; operationKey: string; boundaryRequestHash: string; }, ): Promise { const receipt = fingerprintedPromptCommandReceipt( await findPromptCommandReceipts(db, { workspaceId: input.workspaceId, actor: input.actor, operationKey: input.operationKey, }), ); if (!receipt) return null; assertPromptCommandReceiptIdentity(receipt, input); if ( typeof receipt.result.boundaryRequestHash !== "string" || receipt.appliedQueueVersion === null ) { return null; } return receipt; } export async function reserveSessionCommandReceipt( db: Database, input: { accountId: string; workspaceId: string; actor: SessionCommandActor; action: string; targetSessionId: string | null; targetTurnId: string | null; operationKey: string; canonicalRequestHash: string; identityScope?: "actor" | "target_operation"; initialResult?: Record; }, ): Promise<{ receipt: SessionCommandReceiptRow; replay: boolean }> { if (!input.operationKey.trim()) throw new Error("operationKey must not be empty"); const identityScope = input.identityScope ?? "actor"; if ( identityScope === "target_operation" && (input.actor.type !== "agent_attempt" || !["goal.update", "goal.progress", "session.wait_for_input"].includes(input.action) || input.targetSessionId === null || input.targetTurnId !== null) ) { throw new SessionControlInvariantError( "Target-scoped receipt identity is reserved for agent self commands", ); } const actorSubjectId = input.actor.type === "agent_attempt" ? null : input.actor.subjectId; const actorAttemptId = input.actor.type === "agent_attempt" ? input.actor.attemptId : null; const [inserted] = await db .insert(schema.sessionCommandReceipts) .values({ accountId: input.accountId, workspaceId: input.workspaceId, actorType: input.actor.type, actorSubjectId, actorAttemptId, action: input.action, targetSessionId: input.targetSessionId, targetTurnId: input.targetTurnId, operationKey: input.operationKey, canonicalRequestHash: input.canonicalRequestHash, result: input.initialResult ?? {}, }) .onConflictDoNothing() .returning(); const receipt = inserted ?? (await findCommandReceipt(db, { workspaceId: input.workspaceId, actor: input.actor, action: input.action, targetSessionId: input.targetSessionId, targetTurnId: input.targetTurnId, operationKey: input.operationKey, identityScope, })); if (!receipt) throw new SessionControlInvariantError("Command receipt conflict was not readable"); if (receipt.canonicalRequestHash !== input.canonicalRequestHash) { throw new SessionCommandIdempotencyError(); } return { receipt, replay: !inserted }; } function nextRevision(workspace: WorkspaceControlRow): number { const current = asSafeRevision(workspace.revision, "workspace control revision")!; if (current >= Number.MAX_SAFE_INTEGER) { throw new SessionControlInvariantError("Workspace control revision is exhausted"); } return current + 1; } async function advanceWorkspaceRevision( db: Database, workspaceId: string, revision: number, ): Promise { const rows = await db .update(schema.workspaceInferenceControls) .set({ revision, updatedAt: new Date() }) .where( and( eq(schema.workspaceInferenceControls.workspaceId, workspaceId), eq(schema.workspaceInferenceControls.revision, revision - 1), ), ) .returning({ workspaceId: schema.workspaceInferenceControls.workspaceId }); if (rows.length !== 1) { throw new SessionControlInvariantError( "Workspace control revision did not advance exactly once", ); } } async function registerContinuableWakes( db: Database, input: { workspaceId: string; rootSessionId: string | null; reason: string }, ): Promise { const rows = await db.execute<{ wakeCount: number | string }>(sql` with eligible as ( select * from opengeni_private.list_continuable_sessions( ${input.workspaceId}::uuid, ${input.rootSessionId}::uuid ) ), upserted as ( insert into ${schema.sessionWorkflowWakeOutbox} ( session_id, account_id, workspace_id, temporal_workflow_id, reason ) select session_id, account_id, workspace_id, temporal_workflow_id, ${input.reason} from eligible on conflict (session_id) do update set wake_revision = ${schema.sessionWorkflowWakeOutbox}.wake_revision + 1, temporal_workflow_id = excluded.temporal_workflow_id, reason = excluded.reason, attempts = 0, next_attempt_at = now(), last_error = null, updated_at = now() returning session_id ) select count(*)::bigint as "wakeCount" from upserted `); return Number(rows[0]?.wakeCount ?? 0); } async function registerDescendantWakes( db: Database, input: { workspaceId: string; sessionId: string; reason: string }, ): Promise { return await registerContinuableWakes(db, { workspaceId: input.workspaceId, rootSessionId: input.sessionId, reason: input.reason, }); } async function registerWorkspaceWakes( db: Database, input: { workspaceId: string; reason: string }, ): Promise { return await registerContinuableWakes(db, { workspaceId: input.workspaceId, rootSessionId: null, reason: input.reason, }); } /** * Pause never needs to rediscover ordinary continuable work: it closes * admission. Only workflows owning an interruption created by this exact * command must wake so they can settle their in-flight attempt. The operation * receipt is indexed and bounds this to the number of affected attempts rather * than the size or depth of the paused tree. */ async function registerInterruptionWakes( db: Database, input: { operationId: string; reason: string }, ): Promise { const rows = await db.execute<{ wakeCount: number | string }>(sql` with eligible as ( select distinct session.id as session_id, session.account_id, session.workspace_id, coalesce(session.temporal_workflow_id, 'session-' || session.id::text) as temporal_workflow_id from ${schema.sessionAttemptInterruptions} interruption join ${schema.sessions} session on session.workspace_id = interruption.workspace_id and session.id = interruption.session_id where interruption.operation_id = ${input.operationId}::uuid and interruption.state in ('pending', 'delivered', 'acknowledged') ), upserted as ( insert into ${schema.sessionWorkflowWakeOutbox} ( session_id, account_id, workspace_id, temporal_workflow_id, reason ) select session_id, account_id, workspace_id, temporal_workflow_id, ${input.reason} from eligible on conflict (session_id) do update set wake_revision = ${schema.sessionWorkflowWakeOutbox}.wake_revision + 1, temporal_workflow_id = excluded.temporal_workflow_id, reason = excluded.reason, attempts = 0, next_attempt_at = now(), last_error = null, updated_at = now() returning session_id ) select count(*)::bigint as "wakeCount" from upserted `); return Number(rows[0]?.wakeCount ?? 0); } /** * Terminal cancellation must wake every affected workflow, including sessions * parked at an approval, capacity, or other no-active-attempt boundary. Those * sessions have no new interruption row, so the ordinary Pause wake selector * cannot discover them. Signal-with-start is intentional here: a closed * workflow cheaply re-reads the terminal row and exits, while an open workflow * is released from an otherwise unbounded durable wait. * * A sub-chat whose content is already stored (or being stored) has no * workflow left to release and refuses new wakes, so it is left out; without * that, cancelling an archived chat with a stored sub-chat failed outright. */ async function registerCancellationWakes( db: Database, input: { workspaceId: string; sessionIds: string[] }, ): Promise { if (input.sessionIds.length === 0) return 0; const sessionIds = sql.join( input.sessionIds.map((id) => sql`${id}::uuid`), sql`, `, ); const rows = await db.execute<{ wakeCount: number | string }>(sql` with eligible as ( select session.id as session_id, session.account_id, session.workspace_id, coalesce(session.temporal_workflow_id, 'session-' || session.id::text) as temporal_workflow_id from ${schema.sessions} session where session.workspace_id = ${input.workspaceId} and session.id in (${sessionIds}) and session.content_archive_state is null ), upserted as ( insert into ${schema.sessionWorkflowWakeOutbox} ( session_id, account_id, workspace_id, temporal_workflow_id, reason, control_revision ) select session_id, account_id, workspace_id, temporal_workflow_id, 'session_cancelled', 1 from eligible on conflict (session_id) do update set wake_revision = ${schema.sessionWorkflowWakeOutbox}.wake_revision + 1, control_revision = ${schema.sessionWorkflowWakeOutbox}.wake_revision + 1, temporal_workflow_id = excluded.temporal_workflow_id, reason = excluded.reason, attempts = 0, next_attempt_at = now(), last_error = null, updated_at = now() returning session_id ) select count(*)::bigint as "wakeCount" from upserted `); return Number(rows[0]?.wakeCount ?? 0); } /** Register one exact post-commit Temporal nudge without encoding eligibility in * the transport. The workflow re-reads canonical Postgres state; coalescing is * revisioned so a lost or stale delivery cannot hide a later mutation. */ export async function registerSessionWorkflowWakeInTransaction( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; controlRequested?: boolean; }, ): Promise { const [row] = await db .insert(schema.sessionWorkflowWakeOutbox) .values({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: input.temporalWorkflowId, controlRevision: input.controlRequested ? 1 : 0, reason: input.reason, }) .onConflictDoUpdate({ target: schema.sessionWorkflowWakeOutbox.sessionId, set: { temporalWorkflowId: input.temporalWorkflowId, wakeRevision: sql`${schema.sessionWorkflowWakeOutbox.wakeRevision} + 1`, controlRevision: input.controlRequested ? sql`${schema.sessionWorkflowWakeOutbox.wakeRevision} + 1` : sql`${schema.sessionWorkflowWakeOutbox.controlRevision}`, reason: input.reason, attempts: 0, nextAttemptAt: new Date(), lastError: null, updatedAt: new Date(), }, }) .returning({ wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision }); if (!row) { throw new SessionControlInvariantError(`Failed to register wake for ${input.sessionId}`); } return Number(row.wakeRevision); } /** * Internal producers share one outstanding session-level receipt. While a wake * remains undelivered, another update makes that same batch richer instead of * manufacturing another transport revision or sequential model turn. * * Producers outside the workflow should signal after commit in both cases, so * `shouldSignal` is always `true`; the field stays for callers that read it. An * undelivered row is often a delayed wake that nothing signals before its time * (a `wait_for_input` deadline or goal idle backoff); pulling `next_attempt_at` * to now alone leaves the input waiting for the periodic dispatcher. The signal * is only a hint: the workflow re-reads PostgreSQL, one claim consumes the * whole pending batch, and the admission-aware acknowledgement keeps this * revision open until it does. Terminal background-command settlement returns * its committed wakes so each settlement caller signals them after commit; the * dispatcher delivers any a caller could not signal. */ export async function registerInternalUpdateWakeInTransaction( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; }, ): Promise<{ wakeRevision: number; shouldSignal: true }> { const [existing] = await db .select() .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, input.workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId), ), ) .for("update") .limit(1); if (existing && existing.wakeRevision > existing.deliveredRevision) { await db .update(schema.sessionWorkflowWakeOutbox) .set({ temporalWorkflowId: input.temporalWorkflowId, reason: "internal_update_batch", nextAttemptAt: new Date(), lastError: null, updatedAt: new Date(), }) .where(eq(schema.sessionWorkflowWakeOutbox.sessionId, input.sessionId)); return { wakeRevision: existing.wakeRevision, shouldSignal: true }; } return { wakeRevision: await registerSessionWorkflowWakeInTransaction(db, { ...input, reason: "internal_update_batch", }), shouldSignal: true, }; } async function interruptDescendantAttempts( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; operationId: string; kind: "session_pause" | "steer" | "maintenance"; controlRevision: number; }, ): Promise { const rows = await db.execute<{ count: number | string }>(sql` with recursive live_attempts as ( select attempt.id, attempt.account_id, attempt.workspace_id, attempt.session_id from ${schema.sessionTurnAttempts} attempt where attempt.workspace_id = ${input.workspaceId} and attempt.state in ('claimed', 'running') ), attempt_ancestry(attempt_id, account_id, workspace_id, session_id, ancestor_id, depth, path) as ( select attempt.id, attempt.account_id, attempt.workspace_id, attempt.session_id, attempt.session_id, 0::integer, array[attempt.session_id]::uuid[] from live_attempts attempt union all select ancestry.attempt_id, ancestry.account_id, ancestry.workspace_id, ancestry.session_id, current.parent_session_id, ancestry.depth + 1, ancestry.path || current.parent_session_id from attempt_ancestry ancestry join ${schema.sessions} current on current.workspace_id = ${input.workspaceId} and current.id = ancestry.ancestor_id where current.parent_session_id is not null and not current.parent_session_id = any(ancestry.path) and ancestry.depth < ${SESSION_ANCESTRY_LIMIT} ), inserted as ( insert into ${schema.sessionAttemptInterruptions} ( account_id, workspace_id, session_id, operation_id, attempt_id, kind, control_revision ) select ancestry.account_id, ancestry.workspace_id, ancestry.session_id, ${input.operationId}::uuid, ancestry.attempt_id, ${input.kind}, ${input.controlRevision} from attempt_ancestry ancestry where ancestry.ancestor_id = ${input.sessionId} on conflict (operation_id, attempt_id) do nothing returning id ) select count(*)::integer as count from inserted `); return Number(rows[0]?.count ?? 0); } async function interruptWorkspaceAttempts( db: Database, input: { workspaceId: string; operationId: string; controlRevision: number; }, ): Promise { const rows = await db.execute<{ count: number | string }>(sql` with inserted as ( insert into ${schema.sessionAttemptInterruptions} ( account_id, workspace_id, session_id, operation_id, attempt_id, kind, control_revision ) select attempt.account_id, attempt.workspace_id, attempt.session_id, ${input.operationId}::uuid, attempt.id, 'workspace_pause', ${input.controlRevision} from ${schema.sessionTurnAttempts} attempt where attempt.workspace_id = ${input.workspaceId} and attempt.state in ('claimed', 'running') on conflict (operation_id, attempt_id) do nothing returning id ) select count(*)::integer as count from inserted `); return Number(rows[0]?.count ?? 0); } export async function updateSessionCommandReceiptResult( db: Database, receiptId: string, input: { controlRevision?: number | null; queueVersion?: number | null; turnVersion?: number | null; draftRevision?: number | null; result: Record; }, ): Promise { const [receipt] = await db .update(schema.sessionCommandReceipts) .set({ ...(input.controlRevision !== undefined ? { appliedControlRevision: input.controlRevision } : {}), ...(input.queueVersion !== undefined ? { appliedQueueVersion: input.queueVersion } : {}), ...(input.turnVersion !== undefined ? { appliedTurnVersion: input.turnVersion } : {}), ...(input.draftRevision !== undefined ? { appliedDraftRevision: input.draftRevision } : {}), result: input.result, updatedAt: new Date(), }) .where(eq(schema.sessionCommandReceipts.id, receiptId)) .returning(); if (!receipt) throw new SessionControlInvariantError("Command receipt disappeared"); return receipt; } export type SessionControlMutationResult = { receipt: SessionCommandReceiptRow; control: EffectiveSessionControl; sessionControlEventId: string | null; workspaceControlEventId: string | null; interruptionCount: number; backgroundCommandCount: number; wakeCount: number; cancelledSessionCount: number; cancelledTurnCount: number; affectedSessionEvents: Array<{ sessionId: string; eventIds: string[] }>; workflowWake: SessionControlWorkflowWake | null; outcome: "changed" | "unchanged" | "replayed"; replay: boolean; }; export type SessionControlWorkflowWake = { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; wakeRevision: number; }; async function pendingSessionControlWorkflowWake( db: Database, workspaceId: string, sessionId: string, wakeCount: number, ): Promise { if (wakeCount === 0) return null; const [wake] = await db .select({ accountId: schema.sessionWorkflowWakeOutbox.accountId, workspaceId: schema.sessionWorkflowWakeOutbox.workspaceId, sessionId: schema.sessionWorkflowWakeOutbox.sessionId, temporalWorkflowId: schema.sessionWorkflowWakeOutbox.temporalWorkflowId, wakeRevision: schema.sessionWorkflowWakeOutbox.wakeRevision, deliveredRevision: schema.sessionWorkflowWakeOutbox.deliveredRevision, }) .from(schema.sessionWorkflowWakeOutbox) .where( and( eq(schema.sessionWorkflowWakeOutbox.workspaceId, workspaceId), eq(schema.sessionWorkflowWakeOutbox.sessionId, sessionId), ), ) .limit(1); if (!wake || wake.wakeRevision <= wake.deliveredRevision) return null; return { accountId: wake.accountId, workspaceId: wake.workspaceId, sessionId: wake.sessionId, temporalWorkflowId: wake.temporalWorkflowId, wakeRevision: wake.wakeRevision, }; } async function sessionPauseEffectsNeeded( db: Database, input: { workspaceId: string; sessionId: string; directPauseRevision: number }, ): Promise { const rows = await db.execute<{ needed: boolean }>(sql` with recursive subtree(id, path, cycle) as ( select session.id, array[session.id]::uuid[], false from ${schema.sessions} session where session.workspace_id = ${input.workspaceId} and session.id = ${input.sessionId} union all select child.id, parent.path || child.id, child.id = any(parent.path) from subtree parent join ${schema.sessions} child on child.workspace_id = ${input.workspaceId} and child.parent_session_id = parent.id where not parent.cycle and cardinality(parent.path) <= ${SESSION_ANCESTRY_LIMIT} ), scoped_sessions as ( select session.id, session.subtree_run_override_revision from subtree join ${schema.sessions} session on session.workspace_id = ${input.workspaceId} and session.id = subtree.id where not subtree.cycle ) select exists ( select 1 from scoped_sessions session where session.subtree_run_override_revision > ${input.directPauseRevision} union all select 1 from ${schema.sessionTurnAttempts} attempt join scoped_sessions session on session.id = attempt.session_id where attempt.workspace_id = ${input.workspaceId} and attempt.state in ('claimed', 'running') and not exists ( select 1 from ${schema.sessionAttemptInterruptions} interruption where interruption.workspace_id = attempt.workspace_id and interruption.attempt_id = attempt.id and interruption.kind in ('session_pause', 'workspace_pause') and interruption.state in ('pending', 'delivered', 'acknowledged') ) union all select 1 from ${schema.sessionBackgroundCommands} command join scoped_sessions session on session.id = command.session_id where command.workspace_id = ${input.workspaceId} and command.state = 'running' ) as needed `); return rows[0]?.needed ?? false; } async function workspacePauseEffectsNeeded( db: Database, input: { workspaceId: string; workspacePauseRevision: number }, ): Promise { const rows = await db.execute<{ needed: boolean }>(sql` select exists ( select 1 from ${schema.sessions} session where session.workspace_id = ${input.workspaceId} and session.subtree_run_override_revision > ${input.workspacePauseRevision} union all select 1 from ${schema.sessionTurnAttempts} attempt where attempt.workspace_id = ${input.workspaceId} and attempt.state in ('claimed', 'running') and not exists ( select 1 from ${schema.sessionAttemptInterruptions} interruption where interruption.workspace_id = attempt.workspace_id and interruption.attempt_id = attempt.id and interruption.kind in ('session_pause', 'workspace_pause') and interruption.state in ('pending', 'delivered', 'acknowledged') ) union all select 1 from ${schema.sessionBackgroundCommands} command where command.workspace_id = ${input.workspaceId} and command.state = 'running' ) as needed `); return rows[0]?.needed ?? false; } async function continuableWakeRepairNeeded( db: Database, input: { workspaceId: string; rootSessionId: string | null }, ): Promise { const rows = await db.execute<{ needed: boolean }>(sql` select exists ( select 1 from opengeni_private.list_continuable_sessions( ${input.workspaceId}::uuid, ${input.rootSessionId}::uuid ) eligible left join ${schema.sessionWorkflowWakeOutbox} wake on wake.workspace_id = eligible.workspace_id and wake.session_id = eligible.session_id where wake.session_id is null or wake.wake_revision <= wake.delivered_revision ) as needed `); return rows[0]?.needed ?? false; } async function loadSessionSubtreeIds( db: Database, workspaceId: string, rootSessionId: string, ): Promise<{ sessionIds: string[]; rootParentSessionId: string | null }> { const rows: Array<{ id: string; rootParentSessionId: string | null; depth: number | string; cycle: boolean; }> = await db.execute(sql` with recursive subtree(id, root_parent_session_id, depth, path, cycle) as ( select session.id, session.parent_session_id, 0::integer, array[session.id]::uuid[], false from ${schema.sessions} session where session.workspace_id = ${workspaceId} and session.id = ${rootSessionId} union all select child.id, parent.root_parent_session_id, parent.depth + 1, parent.path || child.id, child.id = any(parent.path) from subtree parent join ${schema.sessions} child on child.workspace_id = ${workspaceId} and child.parent_session_id = parent.id where parent.depth < ${SESSION_ANCESTRY_LIMIT} and not parent.cycle ) select id, root_parent_session_id as "rootParentSessionId", depth, cycle from subtree order by id `); if (rows.length === 0) { throw new SessionControlInvariantError(`Session ${rootSessionId} does not exist`); } if (rows.some((row) => row.cycle || Number(row.depth) >= SESSION_ANCESTRY_LIMIT)) { throw new SessionControlInvariantError(`Session ${rootSessionId} subtree is invalid`); } return { sessionIds: rows.map((row) => row.id), rootParentSessionId: rows[0]?.rootParentSessionId ?? null, }; } const TERMINAL_CANCELLATION_LIVE_TURN_STATUSES = [ "queued", "running", "requires_action", "recovering", "waiting_capacity", ]; async function loadCancellationTurnIds( db: Database, workspaceId: string, sessionIds: string[], ): Promise { const rows = await db .select({ id: schema.sessionTurns.id }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, workspaceId), inArray(schema.sessionTurns.sessionId, sessionIds), inArray(schema.sessionTurns.status, TERMINAL_CANCELLATION_LIVE_TURN_STATUSES), ), ) .orderBy(schema.sessionTurns.id); return rows.map((row) => row.id); } async function loadParentSessionId( db: Database, workspaceId: string, sessionId: string, ): Promise { const [row] = await db .select({ parentSessionId: schema.sessions.parentSessionId }) .from(schema.sessions) .where(and(eq(schema.sessions.workspaceId, workspaceId), eq(schema.sessions.id, sessionId))) .limit(1); return row?.parentSessionId ?? null; } /** * The sessions whose active turn waits for subscription capacity: among * `sessionIds`, or across the whole workspace when it is null. */ async function loadCapacityWaitingTurns( db: Database, workspaceId: string, sessionIds: string[] | null, ): Promise> { if (sessionIds !== null && sessionIds.length === 0) return []; const rows = await db .select({ sessionId: schema.sessions.id, turnId: schema.sessionTurns.id }) .from(schema.sessions) .innerJoin( schema.sessionTurns, and( eq(schema.sessionTurns.workspaceId, schema.sessions.workspaceId), eq(schema.sessionTurns.id, schema.sessions.activeTurnId), ), ) .where( and( eq(schema.sessions.workspaceId, workspaceId), sessionIds === null ? undefined : inArray(schema.sessions.id, sessionIds), eq(schema.sessions.status, "waiting_capacity"), eq(schema.sessionTurns.status, "waiting_capacity"), ), ) .orderBy(schema.sessions.id); return rows; } /** * The one control-plane child -> parent outbox insert (terminal cancellation, * direct Pause, and cancelled human-input resolutions). The caller holds the * canonical prefix with the child and its parent locked UUID-ordered; the * causal parent-turn personal delegation snapshot is copied verbatim. */ async function insertChildOutboxRowInTransaction( db: Database, input: { workspaceId: string; childSession: typeof schema.sessions.$inferSelect; parentSession: typeof schema.sessions.$inferSelect | null; dedupeKey: string; kind: "child_terminal_result" | "child_paused" | "child_requires_action_resolved"; classification: "info" | "action_required"; summary: string; payload: Record & { type: string }; lineage?: Record; /** A resolution follows its question to the ancestor that received it. */ route?: ChildRequiresActionRoute; }, ): Promise { const parentSessionId = input.childSession.parentSessionId; if (!parentSessionId) return; if (!input.parentSession || input.parentSession.id !== parentSessionId) { throw new SessionControlInvariantError( `Parent session ${parentSessionId} was not locked with child ${input.childSession.id}`, ); } if (input.parentSession.status === "cancelled") return; if (input.payload.type !== input.kind) { throw new SessionControlInvariantError( `Child outbox ${input.kind} payload discriminator mismatch`, ); } const targetSessionId = input.route?.targetSessionId ?? parentSessionId; const authority = await parentOutboxAuthorityTx(db, input.workspaceId, { ...(input.route?.via ?? input.childSession), parentSessionId: targetSessionId, }); const routeLineage = targetSessionId !== parentSessionId ? { childSessionId: input.childSession.id } : {}; const inserted = await db .insert(schema.sessionSystemUpdateOutbox) .values( withLosslessContentWriteVersion( withLosslessContentWriteVersion( { accountId: input.childSession.accountId, workspaceId: input.workspaceId, sourceSessionId: input.childSession.id, targetSessionId, dedupeKey: input.dedupeKey, kind: input.kind, classification: input.classification, sourceId: input.childSession.id, summary: input.summary, payload: input.payload, ...authority, lineage: { ...authority.lineage, ...routeLineage, ...(input.lineage ?? {}) }, }, "summary", "summaryCodecVersion", ), "payload", "payloadCodecVersion", ), ) .onConflictDoNothing({ target: [ schema.sessionSystemUpdateOutbox.workspaceId, schema.sessionSystemUpdateOutbox.dedupeKey, ], }) .returning({ id: schema.sessionSystemUpdateOutbox.id }); await copySubscriptionAuthorityCompatInTransaction( db, inserted.map((row) => ({ kind: "session_system_update_outbox" as const, workspaceId: input.workspaceId, id: row.id, })), ); } async function enqueueCancelledChildOutboxInTransaction( db: Database, input: { workspaceId: string; rootSession: typeof schema.sessions.$inferSelect; parentSession: typeof schema.sessions.$inferSelect | null; }, ): Promise { await insertChildOutboxRowInTransaction(db, { workspaceId: input.workspaceId, childSession: input.rootSession, parentSession: input.parentSession, dedupeKey: `child-completion:${input.rootSession.id}:cancelled`, kind: "child_terminal_result", classification: "info", summary: "Child session was terminally cancelled.", payload: { type: "child_terminal_result", childSessionId: input.rootSession.id, status: "cancelled", }, }); } /** child_paused notice for a direct Pause of a child; gated by the rollout flag. */ async function enqueueChildPausedOutboxInTransaction( db: Database, input: { workspaceId: string; childSession: typeof schema.sessions.$inferSelect; parentSession: typeof schema.sessions.$inferSelect; operationId: string; actorKind: "human" | "api" | "agent"; reason: string | null; }, ): Promise { if (!childLifecycleNoticesEnabled()) return; const payload = { type: "child_paused" as const, childSessionId: input.childSession.id, operationId: input.operationId, actorKind: input.actorKind, reason: boundedChildPausedReason(input.reason), }; await insertChildOutboxRowInTransaction(db, { workspaceId: input.workspaceId, childSession: input.childSession, parentSession: input.parentSession, dedupeKey: childPausedDedupeKey({ childSessionId: input.childSession.id, receiptId: input.operationId, }), kind: "child_paused", classification: childPausedClassification(input.actorKind), summary: childPausedSummary(input.childSession.id, payload), payload, }); } /** * Terminal cancellation of the selected root's pending human-input rows: each * becomes one child_requires_action_resolved notice for the surviving parent * so its pending child_requires_action can be superseded. Cancelled * descendants do not notify parents inside the same terminal subtree. */ async function enqueueCancelledChildRequiresActionResolvedOutboxInTransaction( db: Database, input: { workspaceId: string; rootSession: typeof schema.sessions.$inferSelect; parentSession: typeof schema.sessions.$inferSelect | null; cancelledHumanInputs: ReadonlyArray<{ id: string; sessionId: string; turnId: string; turnGeneration: number; }>; }, ): Promise { if (!childLifecycleNoticesEnabled() || !input.parentSession) return; for (const humanInput of input.cancelledHumanInputs) { if (humanInput.sessionId !== input.rootSession.id) continue; const payload = { type: "child_requires_action_resolved" as const, childSessionId: input.rootSession.id, childTurnId: humanInput.turnId, childTurnGeneration: humanInput.turnGeneration, requestId: humanInput.id, approvalId: null, outcome: "cancelled" as const, respondedByKind: "system" as const, }; const parentSessionId = input.rootSession.parentSessionId; const recordedTarget = parentSessionId ? await recordedChildNoticeTargetTx( db, input.workspaceId, childRequiresActionDedupeKey({ childSessionId: input.rootSession.id, turnId: humanInput.turnId, turnGeneration: humanInput.turnGeneration, }), ) : null; const route = parentSessionId && recordedTarget && recordedTarget !== parentSessionId ? await childRequiresActionRouteTx( db, input.workspaceId, { ...input.rootSession, parentSessionId }, recordedTarget, ) : undefined; await insertChildOutboxRowInTransaction(db, { workspaceId: input.workspaceId, childSession: input.rootSession, parentSession: input.parentSession, dedupeKey: childRequiresActionResolvedDedupeKey({ childSessionId: input.rootSession.id, turnId: humanInput.turnId, turnGeneration: humanInput.turnGeneration, requestId: humanInput.id, approvalId: null, }), kind: "child_requires_action_resolved", classification: "info", summary: childRequiresActionResolvedSummary(input.rootSession.id, payload), payload, lineage: { turnId: humanInput.turnId }, ...(route ? { route } : {}), }); } } async function assertSessionBranchIsNotCancelled( db: Database, workspaceId: string, sessionId: string, ): Promise { const rows = await db.execute<{ cancelled: boolean; invalid: boolean; }>(sql` with recursive ancestry(id, parent_id, status, depth, path, cycle) as ( select session.id, session.parent_session_id, session.status, 0::integer, array[session.id]::uuid[], false from ${schema.sessions} session where session.workspace_id = ${workspaceId} and session.id = ${sessionId} union all select parent.id, parent.parent_session_id, parent.status, child.depth + 1, child.path || parent.id, parent.id = any(child.path) from ancestry child join ${schema.sessions} parent on parent.workspace_id = ${workspaceId} and parent.id = child.parent_id where child.depth < ${SESSION_ANCESTRY_LIMIT} and not child.cycle ) select coalesce(bool_or(status = 'cancelled'), false) as cancelled, count(*) = 0 or coalesce(bool_or(cycle), false) or coalesce(max(depth), 0) >= ${SESSION_ANCESTRY_LIMIT} as invalid from ancestry `); if (rows[0]?.invalid) { throw new SessionControlInvariantError(`Session ${sessionId} ancestry is invalid`); } if (rows[0]?.cancelled) { throw new SessionControlConflictError("Cancelled session subtree cannot accept work"); } } async function cancelSessionSubtreeInTransaction( db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; rootSessionId: string; sessionIds: string[]; lockedSessions: Array; candidateTurnIds: string[]; lockedTurns: Array; actor: string; reason: string | null; operationId: string; rootControlEventId: string; }, ): Promise<{ cancelledSessionCount: number; cancelledTurnCount: number; affectedSessionEvents: Array<{ sessionId: string; eventIds: string[] }>; }> { const candidateTurnIdSet = new Set(input.candidateTurnIds); const candidateTurns = input.lockedTurns.filter((turn) => candidateTurnIdSet.has(turn.id)); if (candidateTurns.length !== candidateTurnIdSet.size) { throw new SessionControlInvariantError("Cancellation candidate turns changed while locking"); } // The outer command acquired every session and candidate turn in one UUID- // sorted call before the actor attempt. Repeat only those already-held locks // so this event-writing suffix retains a directly auditable lock contract; // this call must never discover or acquire a new row. const suffixLocks = await lockSessionEventWriteRows(db, { workspaceId: input.workspaceId, controlLock: "already_locked", workspaceLock: "already_locked", sessionIds: input.lockedSessions.map((session) => session.id), turnIds: input.candidateTurnIds, }); if ( suffixLocks.sessions.length !== input.lockedSessions.length || suffixLocks.turns.length !== candidateTurnIdSet.size ) { throw new SessionControlInvariantError("Cancellation rows changed under canonical locks"); } const sessionIdSet = new Set(input.sessionIds); const rootSession = input.lockedSessions.find((session) => session.id === input.rootSessionId); if (!rootSession) { throw new SessionControlInvariantError( `Cancellation root ${input.rootSessionId} was not locked with its subtree`, ); } const rootParentSession = rootSession.parentSessionId ? (input.lockedSessions.find((session) => session.id === rootSession.parentSessionId) ?? null) : null; const candidateTurnById = new Map(candidateTurns.map((turn) => [turn.id, turn])); const liveTurnIds = new Set( input.lockedSessions .filter((session) => session.activeTurnId !== null) .flatMap((session) => { const turn = session.activeTurnId ? candidateTurnById.get(session.activeTurnId) : undefined; if (turn?.activeAttemptId === null) return []; return turn ? [turn.id] : []; }), ); const immediatelyCancelledTurns = candidateTurns.filter((turn) => !liveTurnIds.has(turn.id)); const cancelledTurnsBySession = new Map(); for (const turn of immediatelyCancelledTurns) { const turns = cancelledTurnsBySession.get(turn.sessionId); if (turns) turns.push(turn); else cancelledTurnsBySession.set(turn.sessionId, [turn]); } const immediatelyCancelledTurnIds = immediatelyCancelledTurns.map((turn) => turn.id); const now = new Date(); let cancelledHumanInputs: Array<{ id: string; sessionId: string; turnId: string; turnGeneration: number; questions: (typeof schema.sessionHumanInputRequests.$inferSelect)["questions"]; }> = []; if (immediatelyCancelledTurnIds.length > 0) { await db .update(schema.sessionTurns) .set({ status: "cancelled", activeAttemptId: null, cancelledBy: input.actor, cancelReason: input.reason ?? "session_cancelled", version: sql`${schema.sessionTurns.version} + 1`, finishedAt: now, updatedAt: now, }) .where(inArray(schema.sessionTurns.id, immediatelyCancelledTurnIds)); cancelledHumanInputs = await db .update(schema.sessionHumanInputRequests) .set({ status: "cancelled", response: { outcome: "cancelled" }, respondedBy: input.actor, respondedAt: now, updatedAt: now, }) .where( and( eq(schema.sessionHumanInputRequests.workspaceId, input.workspaceId), inArray(schema.sessionHumanInputRequests.turnId, immediatelyCancelledTurnIds), eq(schema.sessionHumanInputRequests.status, "pending"), eq(schema.sessionHumanInputRequests.origin, "tool_call"), ), ) .returning({ id: schema.sessionHumanInputRequests.id, sessionId: schema.sessionHumanInputRequests.sessionId, turnId: schema.sessionHumanInputRequests.turnId, turnGeneration: schema.sessionHumanInputRequests.turnGeneration, questions: schema.sessionHumanInputRequests.questions, }); // A core waiter (of whichever provider) exists only while its turn // waits; cancelling the turn removes it (and its pending wake // deliveries) in the same commit. await deleteSubscriptionCoreWaitersForTurns(db, null, { workspaceId: input.workspaceId, turnIds: immediatelyCancelledTurnIds, }); } const cancelledSystemUpdates = await db .update(schema.sessionSystemUpdates) .set({ state: "cancelled" }) .where( and( eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), inArray(schema.sessionSystemUpdates.sessionId, input.sessionIds), eq(schema.sessionSystemUpdates.state, "pending"), ), ) .returning({ id: schema.sessionSystemUpdates.id, sessionId: schema.sessionSystemUpdates.sessionId, }); const humanInputsByTurn = new Map(); for (const humanInput of cancelledHumanInputs) { const inputs = humanInputsByTurn.get(humanInput.turnId); if (inputs) inputs.push(humanInput); else humanInputsByTurn.set(humanInput.turnId, [humanInput]); } const systemUpdatesBySession = new Map(); for (const update of cancelledSystemUpdates) { const updates = systemUpdatesBySession.get(update.sessionId); if (updates) updates.push(update); else systemUpdatesBySession.set(update.sessionId, [update]); } const affectedSessionEvents: Array<{ sessionId: string; eventIds: string[]; }> = []; for (const session of input.lockedSessions) { if (!sessionIdSet.has(session.id)) continue; let sequence = session.lastSequence + (session.id === input.rootSessionId ? 1 : 0); const cancelledTurns = cancelledTurnsBySession.get(session.id) ?? []; const preinsertedEvents: Array<{ id: string; sequence: number }> = []; // Closing a turn's pending tool calls inserts its events right away, so // it comes before every event batched below: the cursor accepts only // inserts that continue it exactly. for (const turn of cancelledTurns) { const closedTools = await closePendingSessionToolCallsInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, turnId: turn.id, reason: "session_cancelled", sequence, now, }); sequence = closedTools.sequence; preinsertedEvents.push( ...closedTools.events.map((event) => ({ id: event.id, sequence: event.sequence, })), ); } const eventValues: SessionEventInsertWithPayload[] = []; for (const update of (systemUpdatesBySession.get(session.id) ?? []).sort((left, right) => left.id.localeCompare(right.id), )) { eventValues.push({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "system.update.cancelled", payload: { updateId: update.id, reason: "session_cancelled" }, occurredAt: now, }); } for (const turn of cancelledTurns) { for (const humanInput of (humanInputsByTurn.get(turn.id) ?? []).sort((left, right) => left.id.localeCompare(right.id), )) { eventValues.push({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "user.humanInputResponse", turnId: turn.id, turnGeneration: turn.executionGeneration, ...(turn.id === session.activeTurnId ? { turnAssociation: "current" as const } : {}), payload: { requestId: humanInput.id, response: { outcome: "cancelled" }, }, occurredAt: now, }); } eventValues.push({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "turn.cancelled", turnId: turn.id, turnGeneration: turn.executionGeneration, ...(turn.id === session.activeTurnId ? { turnAssociation: "current" as const } : {}), payload: { reason: input.reason ?? "session_cancelled", operationId: input.operationId, }, occurredAt: now, }); } if (session.status !== "cancelled") { eventValues.push({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, sequence: ++sequence, type: "session.status.changed", payload: { status: "cancelled", reason: input.reason ?? "session_cancelled", operationId: input.operationId, }, occurredAt: now, }); } const inserted = eventValues.length > 0 ? await db .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( withBoundSessionEventPayloads(eventValues), "payload", "payloadCodecVersion", ), ) .returning({ id: schema.sessionEvents.id, sequence: schema.sessionEvents.sequence, type: schema.sessionEvents.type, turnId: schema.sessionEvents.turnId, payload: schema.sessionEvents.payload, }) : []; const cancelledHumanInputsById = new Map( cancelledHumanInputs .filter((request) => request.sessionId === session.id) .map((request) => [request.id, request]), ); for (const event of inserted) { if (event.type !== "user.humanInputResponse") continue; const payload = event.payload as { requestId?: unknown }; const request = typeof payload.requestId === "string" ? cancelledHumanInputsById.get(payload.requestId) : null; if (!request) continue; await mirrorSessionRealtimeContextInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: session.id, sourceKind: "human_input_response", sourceId: event.id, turnId: event.turnId, channel: null, text: renderRealtimeHumanInputResponseContext({ requestId: request.id, questions: request.questions, response: { outcome: "cancelled" }, }), payload: { requestId: request.id, outcome: "cancelled", sourceEventId: event.id, }, now, }); } const liveTurnId = session.activeTurnId && liveTurnIds.has(session.activeTurnId) ? session.activeTurnId : null; await db .update(schema.sessions) .set({ status: "cancelled", activeTurnId: liveTurnId, queueVersion: sql`${schema.sessions.queueVersion} + 1`, queueHeadPosition: 0, queueTailPosition: 0, // A cancelled chat has no turn left to wake: its input wait ends with // it, so it no longer counts as waiting (nor keeps it from storage). inputWaitTurnId: null, inputWaitUntil: null, inputWaitReason: null, inputWaitSetAt: null, lastSequence: sequence, updatedAt: now, }) .where( and(eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, session.id)), ); const eventIds = [...preinsertedEvents, ...inserted] .sort((left, right) => left.sequence - right.sequence) .map((event) => event.id); if (session.id === input.rootSessionId) eventIds.unshift(input.rootControlEventId); if (eventIds.length > 0) affectedSessionEvents.push({ sessionId: session.id, eventIds }); } await enqueueCancelledChildRequiresActionResolvedOutboxInTransaction(db, { workspaceId: input.workspaceId, rootSession, parentSession: rootParentSession, cancelledHumanInputs, }); await enqueueCancelledChildOutboxInTransaction(db, { workspaceId: input.workspaceId, rootSession, parentSession: rootParentSession, }); return { cancelledSessionCount: input.sessionIds.length, cancelledTurnCount: candidateTurns.length, affectedSessionEvents, }; } /** * Whether a chat or anything it started still has work: a turn, a wait for * input, an active goal or a running background command. Archive cancels such * work when its undo window ends. */ export async function sessionWorkstreamHasActiveWork( db: Database | SessionActivityDatabase, workspaceId: string, sessionId: string, ): Promise { const [activity] = await db.execute<{ active: boolean }>(sql` select exists ( select 1 from ${schema.sessions} session where session.workspace_id = ${workspaceId} and (session.id = ${sessionId} or session.root_session_id = ${sessionId}) and ( session.status in ('queued', 'running', 'requires_action', 'recovering', 'waiting_capacity') or session.active_turn_id is not null or session.input_wait_turn_id is not null or exists (select 1 from ${schema.sessionGoals} goal where goal.workspace_id = session.workspace_id and goal.session_id = session.id and goal.status = 'active') or exists (select 1 from ${schema.sessionBackgroundCommands} command where command.workspace_id = session.workspace_id and command.session_id = session.id and command.state in ('running', 'stopping')) ) ) as active `); return activity?.active === true; } export async function mutateSessionControlInTransaction( db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; actor: SessionCommandActor; operationKey: string; action: "pause" | "resume" | "cancel"; reason?: string | null; expectedControlEtag?: string | null; /** Request-scoped callers bound the control prefix wait; lifecycle callers omit it. */ controlLockTimeoutMs?: number; }, ): Promise { const workspace = await lockWorkspaceInferenceControl(db, input.workspaceId, "update", { ...(input.controlLockTimeoutMs !== undefined ? { lockTimeoutMs: input.controlLockTimeoutMs } : {}), }); const cancellationSubtree = input.action === "cancel" ? await loadSessionSubtreeIds(db, input.workspaceId, input.sessionId) : { sessionIds: [input.sessionId], rootParentSessionId: null }; const cancellationSessionIds = cancellationSubtree.sessionIds; const cancellationTurnIds = input.action === "cancel" ? await loadCancellationTurnIds(db, input.workspaceId, cancellationSessionIds) : []; // Pause stops turns parked on subscription capacity in the paused subtree // (a wait has no attempt to interrupt). The workspace control lock taken // above keeps any new wait from arming until this commit. const capacityWaitingTurns = input.action === "pause" ? await loadCapacityWaitingTurns( db, input.workspaceId, (await loadSessionSubtreeIds(db, input.workspaceId, input.sessionId)).sessionIds, ) : []; // A direct Pause of a child notifies its parent (child_paused) through the // outbox in this same commit, so the parent joins the UUID-ordered session // lock exactly like Cancel locks the root's surviving parent. const pauseParentSessionId = input.action === "pause" && childLifecycleNoticesEnabled() ? await loadParentSessionId(db, input.workspaceId, input.sessionId) : null; const lineageParentSessionId = cancellationSubtree.rootParentSessionId ?? pauseParentSessionId; const locks = await lockSessionEventWriteRows(db, { workspaceId: input.workspaceId, controlLock: "already_locked", sessionIds: input.actor.type === "agent_attempt" ? [ input.actor.sessionId, ...cancellationSessionIds, ...capacityWaitingTurns.map((row) => row.sessionId), ...(lineageParentSessionId ? [lineageParentSessionId] : []), ] : [ ...cancellationSessionIds, ...capacityWaitingTurns.map((row) => row.sessionId), ...(lineageParentSessionId ? [lineageParentSessionId] : []), ], turnIds: input.actor.type === "agent_attempt" ? [ input.actor.turnId, ...cancellationTurnIds, ...capacityWaitingTurns.map((row) => row.turnId), ] : [...cancellationTurnIds, ...capacityWaitingTurns.map((row) => row.turnId)], attemptIds: input.actor.type === "agent_attempt" ? [input.actor.attemptId] : [], }); if (input.action === "cancel" || pauseParentSessionId !== null) { const rootSession = locks.sessions.find((session) => session.id === input.sessionId); if (!rootSession || rootSession.parentSessionId !== lineageParentSessionId) { throw new SessionControlInvariantError( `Session ${input.sessionId} parent changed while establishing ${input.action} locks`, ); } } const hash = canonicalSessionCommandHash({ action: input.action, reason: input.reason ?? null, expectedControlEtag: input.expectedControlEtag ?? null, }); const reserved = await reserveSessionCommandReceipt(db, { accountId: input.accountId, workspaceId: input.workspaceId, actor: input.actor, action: `session.${input.action}`, targetSessionId: input.sessionId, targetTurnId: null, operationKey: input.operationKey, canonicalRequestHash: hash, }); if (reserved.replay) { const storedOutcome = reserved.receipt.result.outcome; const unchanged = storedOutcome === "unchanged" && reserved.receipt.appliedControlRevision === null; if (!unchanged && reserved.receipt.appliedControlRevision === null) { throw new SessionControlInvariantError( "Replayed session control receipt has no applied control revision", ); } const workspaceControlEventId = unchanged ? null : String(reserved.receipt.result.workspaceControlEventId ?? ""); if (!unchanged && !workspaceControlEventId) { throw new SessionControlInvariantError("Replayed session control receipt has no event"); } const sessionControlEventId = unchanged ? null : String(reserved.receipt.result.eventId ?? ""); if (!unchanged && !sessionControlEventId) { throw new SessionControlInvariantError( "Replayed session control receipt has no session event", ); } const wakeCount = Number(reserved.receipt.result.wakeCount ?? 0); return { receipt: reserved.receipt, control: await evaluateSessionControl(db, input.workspaceId, input.sessionId, { workspaceControl: workspace, }), sessionControlEventId, workspaceControlEventId, interruptionCount: Number(reserved.receipt.result.interruptionCount ?? 0), backgroundCommandCount: Number(reserved.receipt.result.backgroundCommandCount ?? 0), wakeCount, cancelledSessionCount: Number(reserved.receipt.result.cancelledSessionCount ?? 0), cancelledTurnCount: Number(reserved.receipt.result.cancelledTurnCount ?? 0), affectedSessionEvents: Array.isArray(reserved.receipt.result.affectedSessionEvents) ? (reserved.receipt.result.affectedSessionEvents as Array<{ sessionId: string; eventIds: string[]; }>) : sessionControlEventId ? [{ sessionId: input.sessionId, eventIds: [sessionControlEventId] }] : [], workflowWake: await pendingSessionControlWorkflowWake( db, input.workspaceId, input.sessionId, wakeCount, ), outcome: "replayed", replay: true, }; } if (input.actor.type === "agent_attempt") { await assertAgentCommandAuthorityInTransaction(db, { workspaceId: input.workspaceId, actor: input.actor, targetSessionId: input.sessionId, action: input.action === "cancel" ? "pause" : input.action, }); } if (input.action === "resume") { await assertSessionBranchIsNotCancelled(db, input.workspaceId, input.sessionId); } const before = await evaluateSessionControl(db, input.workspaceId, input.sessionId, { workspaceControl: workspace, }); if (input.expectedControlEtag && input.expectedControlEtag !== before.controlEtag) { throw new SessionControlConflictError(); } if (input.action !== "cancel") { const targetSession = locks.sessions.find((session) => session.id === input.sessionId); if (!targetSession) { throw new SessionControlInvariantError(`Session ${input.sessionId} disappeared`); } const directPauseRevision = asSafeRevision( targetSession.directPauseRevision, "direct pause revision", ); const changed = input.action === "pause" ? targetSession.directControlState !== "paused" || directPauseRevision === null || // Before Pause released waits, a paused chat could keep one. capacityWaitingTurns.length > 0 || (await sessionPauseEffectsNeeded(db, { workspaceId: input.workspaceId, sessionId: input.sessionId, directPauseRevision, })) : targetSession.admissionBlock != null || before.state === "paused" || (await continuableWakeRepairNeeded(db, { workspaceId: input.workspaceId, rootSessionId: input.sessionId, })); if (!changed) { // Repeating Pause may repair a lost reconciliation wake without changing // control authority. The exact closed attempt still needs the existing // worker's Temporal and writer-set proof; this is never new turn work. const [quiescence] = input.action === "pause" ? await db.execute<{ needed: boolean }>(sql` select exists ( select 1 from ${schema.sessionTurnAttempts} attempt where attempt.workspace_id = ${input.workspaceId} and attempt.session_id = ${input.sessionId} and attempt.state = 'closed' and attempt.quiesced_at is null and exists ( select 1 from ${schema.sessionAttemptInterruptions} interruption where interruption.workspace_id = attempt.workspace_id and interruption.session_id = attempt.session_id and interruption.attempt_id = attempt.id and interruption.state in ('settled', 'rejected_stale') ) ) as needed `) : []; const wakeCount = quiescence?.needed ? 1 : 0; if (wakeCount > 0) { await registerSessionWorkflowWakeInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, temporalWorkflowId: targetSession.temporalWorkflowId ?? `session-${input.sessionId}`, reason: "session_pause_quiescence_reconciliation", }); } const receipt = await updateSessionCommandReceiptResult(db, reserved.receipt.id, { result: { outcome: "unchanged", interruptionCount: 0, backgroundCommandCount: 0, wakeCount, cancelledSessionCount: 0, cancelledTurnCount: 0, affectedSessionEvents: [], }, }); return { receipt, control: before, sessionControlEventId: null, workspaceControlEventId: null, interruptionCount: 0, backgroundCommandCount: 0, wakeCount, cancelledSessionCount: 0, cancelledTurnCount: 0, affectedSessionEvents: [], workflowWake: await pendingSessionControlWorkflowWake( db, input.workspaceId, input.sessionId, wakeCount, ), outcome: "unchanged", replay: false, }; } } const targetSession = locks.sessions.find((session) => session.id === input.sessionId); if (!targetSession) { throw new SessionControlInvariantError(`Session ${input.sessionId} disappeared`); } const revision = nextRevision(workspace); await advanceWorkspaceRevision(db, input.workspaceId, revision); const updatedRows = await db .update(schema.sessions) .set( input.action === "pause" || input.action === "cancel" ? { directControlState: "paused", ...(input.action === "cancel" ? { admissionBlock: null } : {}), directPauseRevision: revision, controlVersion: revision, directControlReason: input.reason ?? null, directControlChangedBy: input.actor.type === "agent_attempt" ? `attempt:${input.actor.attemptId}` : input.actor.subjectId, directControlChangedAt: new Date(), updatedAt: new Date(), } : { directControlState: "active", ...(targetSession.admissionBlock ? { admissionBlock: null, status: targetSession.admissionBlock.previousStatus, } : {}), directPauseRevision: null, subtreeRunOverrideRevision: revision, controlVersion: revision, directControlReason: input.reason ?? null, directControlChangedBy: input.actor.type === "agent_attempt" ? `attempt:${input.actor.attemptId}` : input.actor.subjectId, directControlChangedAt: new Date(), updatedAt: new Date(), }, ) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), input.action === "cancel" ? inArray(schema.sessions.id, cancellationSessionIds) : eq(schema.sessions.id, input.sessionId), ), ) .returning({ id: schema.sessions.id }); const updated = updatedRows.find((row) => row.id === input.sessionId); if (!updated) throw new SessionControlInvariantError(`Session ${input.sessionId} disappeared`); const actor = input.actor.type === "agent_attempt" ? `attempt:${input.actor.attemptId}` : input.actor.subjectId; const backgroundCommandCount = input.action === "pause" || input.action === "cancel" ? await requestSessionBackgroundCommandCancellationsInTransaction(db, { workspaceId: input.workspaceId, rootSessionIds: [input.sessionId], subjectId: actor, }) : 0; const workspaceControlEventId = await insertWorkspaceControlEventInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, revision, scope: "session", rootSessionId: input.sessionId, action: input.action === "cancel" ? "pause" : input.action, automatic: false, reason: input.reason ?? null, actor, }); const interruptionCount = input.action === "pause" || input.action === "cancel" ? await interruptDescendantAttempts(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, operationId: reserved.receipt.id, kind: "session_pause", controlRevision: revision, }) : 0; const wakeCount = input.action === "cancel" ? await registerCancellationWakes(db, { workspaceId: input.workspaceId, sessionIds: cancellationSessionIds, }) : input.action === "pause" ? await registerInterruptionWakes(db, { operationId: reserved.receipt.id, reason: "session_pause_interruption", }) : await registerDescendantWakes(db, { workspaceId: input.workspaceId, sessionId: input.sessionId, reason: "session_resume", }); const [controlEvent] = await db .insert(schema.sessionEvents) .values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: targetSession.lastSequence + 1, type: input.action === "pause" || input.action === "cancel" ? "session.control.paused" : "session.control.resumed", payload: { operationId: reserved.receipt.id, revision, actor, ...(input.reason ? { reason: input.reason } : {}), ...(input.action === "cancel" ? { terminal: true } : {}), interruptionCount, }, occurredAt: new Date(), }, "payload", "payloadCodecVersion", ), ) .returning({ id: schema.sessionEvents.id }); if (!controlEvent) throw new SessionControlInvariantError("Session control event was not inserted"); await db .update(schema.sessions) .set({ lastSequence: targetSession.lastSequence + 1, updatedAt: new Date() }) .where(eq(schema.sessions.id, input.sessionId)); await db.insert(schema.auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: actor, action: `session.control.${input.action}`, targetType: "session", targetId: input.sessionId, metadata: { operationId: reserved.receipt.id, revision, interruptionCount, ...(input.actor.type === "agent_attempt" ? { callerSessionId: input.actor.sessionId, callerTurnId: input.actor.turnId, callerAttemptId: input.actor.attemptId, callerExecutionGeneration: input.actor.executionGeneration, } : {}), }, }, "metadata", "metadataCodecVersion", ), ); const cancellation = input.action === "cancel" ? await cancelSessionSubtreeInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, rootSessionId: input.sessionId, sessionIds: cancellationSessionIds, lockedSessions: locks.sessions, candidateTurnIds: cancellationTurnIds, lockedTurns: locks.turns, actor, reason: input.reason ?? null, operationId: reserved.receipt.id, rootControlEventId: controlEvent.id, }) : { cancelledSessionCount: 0, cancelledTurnCount: 0, affectedSessionEvents: [{ sessionId: input.sessionId, eventIds: [controlEvent.id] }], }; for (const waiting of capacityWaitingTurns) { const released = await releaseCapacityWaitingTurnInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: waiting.sessionId, turnId: waiting.turnId, trigger: "session_pause", }); if (!released) continue; const affected = cancellation.affectedSessionEvents.find( (entry) => entry.sessionId === waiting.sessionId, ); if (affected) affected.eventIds.push(...released.eventIds); else cancellation.affectedSessionEvents.push({ sessionId: waiting.sessionId, eventIds: released.eventIds, }); } if (input.action === "pause" && pauseParentSessionId !== null) { // Direct Pause only (a recursive ancestor pause never reaches this command // for the child), and never when the parent's own live attempt issued it: // that parent already knows. Human/API pauses are action-required for the // parent; an agent pause is informational. const pausedSession = locks.sessions.find((session) => session.id === input.sessionId); const parentSession = locks.sessions.find((session) => session.id === pauseParentSessionId); const issuedByParentAttempt = input.actor.type === "agent_attempt" && input.actor.sessionId === pauseParentSessionId; if (pausedSession && parentSession && !issuedByParentAttempt) { await enqueueChildPausedOutboxInTransaction(db, { workspaceId: input.workspaceId, childSession: pausedSession, parentSession, operationId: reserved.receipt.id, actorKind: input.actor.type === "agent_attempt" ? "agent" : input.actor.type === "service" ? "api" : "human", reason: input.reason ?? null, }); } } const receipt = await updateSessionCommandReceiptResult(db, reserved.receipt.id, { controlRevision: revision, result: { outcome: "changed", interruptionCount, backgroundCommandCount, wakeCount, eventId: controlEvent.id, workspaceControlEventId, cancelledSessionCount: cancellation.cancelledSessionCount, cancelledTurnCount: cancellation.cancelledTurnCount, affectedSessionEvents: cancellation.affectedSessionEvents, }, }); const control = await evaluateSessionControl(db, input.workspaceId, input.sessionId, { lock: "share", }); return { receipt, control, sessionControlEventId: controlEvent.id, workspaceControlEventId, interruptionCount, backgroundCommandCount, wakeCount, cancelledSessionCount: cancellation.cancelledSessionCount, cancelledTurnCount: cancellation.cancelledTurnCount, affectedSessionEvents: cancellation.affectedSessionEvents, workflowWake: await pendingSessionControlWorkflowWake( db, input.workspaceId, input.sessionId, wakeCount, ), outcome: "changed", replay: false, }; } export async function autoResumeSessionBranchInTransaction( db: SessionActivityDatabase, input: { workspaceId: string; sessionId: string; actor: string; reason: "human_steer" | "service_steer" | "agent_steer"; observedControlEtag?: string | null; /** * The admission prefix the caller already holds. A `share` admission * proves the branch was active under a lock that excludes every control * mutation, so it never needs to resume; only an `update` admission may * advance the workspace revision here. */ admission?: WorkspaceControlAdmissionLock; }, ): Promise<{ revision: number; control: EffectiveSessionControl; changed: boolean; workspaceControlEventId: string | null; }> { const workspace = input.admission?.control ?? (await lockWorkspaceInferenceControl(db, input.workspaceId, "update")); await assertSessionBranchIsNotCancelled(db, input.workspaceId, input.sessionId); const before = await evaluateSessionControl(db, input.workspaceId, input.sessionId, { workspaceControl: workspace, }); if (input.observedControlEtag && input.observedControlEtag !== before.controlEtag) { throw new SessionControlConflictError(); } if (before.state === "active") { return { revision: asSafeRevision(workspace.revision, "workspace control revision")!, control: before, changed: false, workspaceControlEventId: null, }; } if (input.admission?.mode === "share") { // Impossible by construction: the shared prefix observed an active branch // and excludes every control mutation until this transaction ends. throw new SessionControlInvariantError( `Session ${input.sessionId} became paused under a shared workspace control lock`, ); } const revision = nextRevision(workspace); await advanceWorkspaceRevision(db, input.workspaceId, revision); await db .update(schema.sessions) .set({ directControlState: "active", directPauseRevision: null, subtreeRunOverrideRevision: revision, controlVersion: revision, directControlReason: input.reason, directControlChangedBy: input.actor, directControlChangedAt: new Date(), updatedAt: new Date(), }) .where( and( eq(schema.sessions.workspaceId, input.workspaceId), eq(schema.sessions.id, input.sessionId), ), ); const workspaceControlEventId = await insertWorkspaceControlEventInTransaction(db, { accountId: workspace.accountId, workspaceId: input.workspaceId, revision, scope: "session", rootSessionId: input.sessionId, action: "resume", automatic: true, reason: input.reason, actor: input.actor, }); // The override unblocks the whole branch, exactly like an explicit Resume: // descendants whose workflows closed under the Pause (capacity waits, parked // recoveries, active goals, pending updates, decided approvals) need the // same fresh wake. The steered session's own input carries its wake too. await registerDescendantWakes(db, { workspaceId: input.workspaceId, sessionId: input.sessionId, reason: "session_auto_resume", }); return { revision, control: await evaluateSessionControl(db, input.workspaceId, input.sessionId, { lock: "share", }), changed: true, workspaceControlEventId, }; } export type WorkspaceControlMutationResult = { receipt: SessionCommandReceiptRow; revision: number; workspaceControlEventId: string | null; workspaceState: EffectiveControlState; interruptionCount: number; backgroundCommandCount: number; wakeCount: number; /** Session events the mutation appended (Pause releasing capacity waits), for live fanout. */ affectedSessionEvents: Array<{ sessionId: string; eventIds: string[] }>; outcome: "changed" | "unchanged" | "replayed"; replay: boolean; }; export async function mutateWorkspaceControlInTransaction( db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; actor: SessionCommandActor; operationKey: string; action: "pause" | "resume"; reason?: string | null; /** Internal timer executor retains/replaces its own timer atomically. */ timerExecution?: boolean; expectedRevision?: number | null; /** Request-scoped callers bound the control prefix wait; lifecycle callers omit it. */ controlLockTimeoutMs?: number; }, ): Promise { const workspace = await lockWorkspaceInferenceControl(db, input.workspaceId, "update", { ...(input.controlLockTimeoutMs !== undefined ? { lockTimeoutMs: input.controlLockTimeoutMs } : {}), }); const currentRevision = asSafeRevision(workspace.revision, "workspace control revision")!; const hash = canonicalSessionCommandHash({ action: input.action, reason: input.reason ?? null, expectedRevision: input.expectedRevision ?? null, }); const reserved = await reserveSessionCommandReceipt(db, { accountId: input.accountId, workspaceId: input.workspaceId, actor: input.actor, action: `workspace.${input.action}`, targetSessionId: null, targetTurnId: null, operationKey: input.operationKey, canonicalRequestHash: hash, }); if (reserved.replay) { const storedOutcome = reserved.receipt.result.outcome; const unchanged = storedOutcome === "unchanged" && reserved.receipt.appliedControlRevision === null; if (!unchanged && reserved.receipt.appliedControlRevision === null) { throw new SessionControlInvariantError( "Replayed workspace control receipt has no applied control revision", ); } const workspaceControlEventId = unchanged ? null : String(reserved.receipt.result.workspaceControlEventId ?? ""); if (!unchanged && !workspaceControlEventId) { throw new SessionControlInvariantError("Replayed workspace control receipt has no event"); } return { receipt: reserved.receipt, revision: reserved.receipt.appliedControlRevision === null ? currentRevision : Number(reserved.receipt.appliedControlRevision), workspaceControlEventId: workspaceControlEventId || null, workspaceState: workspace.workspaceState === "paused" ? "paused" : "active", interruptionCount: Number(reserved.receipt.result.interruptionCount ?? 0), backgroundCommandCount: Number(reserved.receipt.result.backgroundCommandCount ?? 0), wakeCount: Number(reserved.receipt.result.wakeCount ?? 0), affectedSessionEvents: Array.isArray(reserved.receipt.result.affectedSessionEvents) ? (reserved.receipt.result.affectedSessionEvents as Array<{ sessionId: string; eventIds: string[]; }>) : [], outcome: "replayed", replay: true, }; } if (input.expectedRevision !== null && input.expectedRevision !== undefined) { if (input.expectedRevision !== currentRevision) throw new SessionControlConflictError(); } // The workspace control lock held above keeps any new wait from arming // until this commit. const capacityWaitingTurns = input.action === "pause" ? await loadCapacityWaitingTurns(db, input.workspaceId, null) : []; const workspacePauseRevision = asSafeRevision( workspace.workspacePauseRevision, "workspace pause revision", ); const changed = (!input.timerExecution && workspace.timerId != null) || (input.action === "pause" ? workspace.workspaceState !== "paused" || workspacePauseRevision === null || // Before Pause released waits, a paused workspace could keep them. capacityWaitingTurns.length > 0 || (await workspacePauseEffectsNeeded(db, { workspaceId: input.workspaceId, workspacePauseRevision, })) : workspace.workspaceState !== "active" || (await continuableWakeRepairNeeded(db, { workspaceId: input.workspaceId, rootSessionId: null, }))); if (!changed) { const receipt = await updateSessionCommandReceiptResult(db, reserved.receipt.id, { result: { outcome: "unchanged", interruptionCount: 0, backgroundCommandCount: 0, wakeCount: 0, }, }); return { receipt, revision: currentRevision, workspaceControlEventId: null, workspaceState: workspace.workspaceState === "paused" ? "paused" : "active", interruptionCount: 0, backgroundCommandCount: 0, wakeCount: 0, affectedSessionEvents: [], outcome: "unchanged", replay: false, }; } const revision = nextRevision(workspace); const actor = input.actor.type === "agent_attempt" ? `attempt:${input.actor.attemptId}` : input.actor.subjectId; const backgroundCommandCount = input.action === "pause" ? await requestWorkspaceBackgroundCommandCancellationsInTransaction(db, { workspaceId: input.workspaceId, subjectId: actor, }) : 0; const [updated] = await db .update(schema.workspaceInferenceControls) .set({ ...(!input.timerExecution ? clearWorkspaceTimerFields : {}), revision, workspaceState: input.action === "pause" ? "paused" : "active", workspacePauseRevision: input.action === "pause" ? revision : null, reason: input.reason ?? null, changedBy: actor, changedAt: new Date(), updatedAt: new Date(), }) .where( and( eq(schema.workspaceInferenceControls.workspaceId, input.workspaceId), eq(schema.workspaceInferenceControls.revision, currentRevision), ), ) .returning({ workspaceId: schema.workspaceInferenceControls.workspaceId }); if (!updated) { throw new SessionControlInvariantError("Workspace control did not mutate exactly once"); } const workspaceControlEventId = await insertWorkspaceControlEventInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, revision, scope: "workspace", rootSessionId: null, action: input.action, automatic: input.timerExecution === true, reason: input.reason ?? null, actor, }); const interruptionCount = input.action === "pause" ? await interruptWorkspaceAttempts(db, { workspaceId: input.workspaceId, operationId: reserved.receipt.id, controlRevision: revision, }) : 0; // Pause stops the capacity waits it pauses, exactly as a chat's Pause does // (a wait has no attempt to interrupt): each waiting turn is released, its // person's "continues by itself" notice withdrawn, and Resume continues it. const affectedSessionEvents: Array<{ sessionId: string; eventIds: string[] }> = []; if (capacityWaitingTurns.length > 0) { await lockSessionEventWriteRows(db, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "already_locked", sessionIds: capacityWaitingTurns.map((row) => row.sessionId), turnIds: capacityWaitingTurns.map((row) => row.turnId), }); } for (const waiting of capacityWaitingTurns) { const released = await releaseCapacityWaitingTurnInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: waiting.sessionId, turnId: waiting.turnId, trigger: "session_pause", }); if (released) affectedSessionEvents.push({ sessionId: waiting.sessionId, eventIds: released.eventIds }); } const wakeCount = // Each release registered its own workflow wake. affectedSessionEvents.length + (input.action === "pause" ? await registerInterruptionWakes(db, { operationId: reserved.receipt.id, reason: "workspace_pause_interruption", }) : await registerWorkspaceWakes(db, { workspaceId: input.workspaceId, reason: "workspace_resume", })); const receipt = await updateSessionCommandReceiptResult(db, reserved.receipt.id, { controlRevision: revision, result: { outcome: "changed", interruptionCount, backgroundCommandCount, wakeCount, workspaceControlEventId, affectedSessionEvents, }, }); return { receipt, revision, workspaceControlEventId, workspaceState: input.action === "pause" ? "paused" : "active", interruptionCount, backgroundCommandCount, wakeCount, affectedSessionEvents, outcome: "changed", replay: false, }; } async function insertWorkspaceControlEventInTransaction( db: Database, input: { accountId: string; workspaceId: string; revision: number; scope: "workspace" | "session"; rootSessionId: string | null; action: "pause" | "resume" | "timer_set" | "timer_cancelled"; automatic: boolean; reason: string | null; actor: string; }, ): Promise { const projected = boundWorkspaceControlEvent( { id: crypto.randomUUID(), workspaceId: input.workspaceId, sequence: input.revision, revision: input.revision, type: "workspace.control.changed", scope: input.scope, rootSessionId: input.rootSessionId, action: input.action, automatic: input.automatic, reason: input.reason, actor: input.actor, occurredAt: new Date(0).toISOString(), }, { surface: "durable_control" }, ); const field = (name: "reason" | "actor") => projected.truncation?.fields.find((candidate) => candidate.field === name); const [event] = await db .insert(schema.workspaceControlEvents) .values({ ...input, reason: projected.reason, reasonOriginalBytes: input.reason === null ? null : (field("reason")?.originalBytes ?? workspaceControlUtf8Bytes(projected.reason!)), actor: projected.actor, actorOriginalBytes: field("actor")?.originalBytes ?? workspaceControlUtf8Bytes(projected.actor), }) .returning({ id: schema.workspaceControlEvents.id }); if (!event) { throw new SessionControlInvariantError("Workspace control event was not inserted"); } return event.id; } export class WorkspacePauseTimerInputError extends Error {} const clearWorkspaceTimerFields = { timerId: null, timerAction: null, timerDueAt: null, timerPauseForSeconds: null, timerPauseRevision: null, }; /** Called under workspace RLS. The same control fence serializes timers and human actions. */ export async function setWorkspacePauseTimerInTransaction( db: SessionActivityDatabase, input: WorkspacePauseTimerRequest & { accountId: string; workspaceId: string; subjectId: string }, ): Promise<{ workspaceControlEventId: string | null; affectedSessionEvents: WorkspaceControlMutationResult["affectedSessionEvents"]; }> { let workspace = await lockWorkspaceInferenceControl(db, input.workspaceId, "update", { lockTimeoutMs: workspaceControlRequestLockTimeoutMs(), }); const reserved = await reserveSessionCommandReceipt(db, { accountId: input.accountId, workspaceId: input.workspaceId, actor: { type: "human", subjectId: input.subjectId }, action: `workspace.timer.${input.action}`, targetSessionId: null, targetTurnId: null, operationKey: input.clientEventId, canonicalRequestHash: canonicalSessionCommandHash({ action: input.action, pauseInSeconds: input.pauseInSeconds ?? 0, pauseForSeconds: input.pauseForSeconds ?? null, expectedRevision: input.expectedRevision, }), }); if (reserved.replay) return { workspaceControlEventId: (reserved.receipt.result.workspaceControlEventId as string | null) ?? null, affectedSessionEvents: [], }; if (Number(workspace.revision) !== input.expectedRevision) throw new SessionControlConflictError(); let action: "pause" | "resume" = "pause"; let delay = input.pauseInSeconds ?? 0; let pauseRevision: number | null = null; let affectedSessionEvents: WorkspaceControlMutationResult["affectedSessionEvents"] = []; if (input.action === "set") { if (workspace.workspaceState === "paused") { if (delay !== 0 || input.pauseForSeconds == null) { throw new WorkspacePauseTimerInputError("A paused workspace requires a resume duration"); } action = "resume"; delay = input.pauseForSeconds; pauseRevision = Number(workspace.workspacePauseRevision); } else if (delay === 0) { const paused = await mutateWorkspaceControlInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, actor: { type: "human", subjectId: input.subjectId }, operationKey: `timer-pause:${reserved.receipt.id}`, action: "pause", }); affectedSessionEvents = paused.affectedSessionEvents; workspace = await lockWorkspaceInferenceControl(db, input.workspaceId, "update"); action = "resume"; delay = input.pauseForSeconds ?? 0; pauseRevision = Number(workspace.workspacePauseRevision); } } const hasTimer = input.action === "set" && delay > 0; const [clock] = await db.execute<{ now: Date }>(sql`select clock_timestamp() as now`); const revision = nextRevision(workspace); await db .update(schema.workspaceInferenceControls) .set({ ...clearWorkspaceTimerFields, ...(hasTimer ? { timerId: reserved.receipt.id, timerAction: action, timerDueAt: new Date(new Date(clock!.now).getTime() + delay * 1000), timerPauseForSeconds: action === "pause" ? (input.pauseForSeconds ?? null) : null, timerPauseRevision: pauseRevision, } : {}), revision, updatedAt: new Date(clock!.now), }) .where(eq(schema.workspaceInferenceControls.workspaceId, input.workspaceId)); const workspaceControlEventId = await insertWorkspaceControlEventInTransaction(db, { accountId: input.accountId, workspaceId: input.workspaceId, revision, scope: "workspace", rootSessionId: null, action: hasTimer ? "timer_set" : "timer_cancelled", automatic: false, reason: null, actor: input.subjectId, }); await updateSessionCommandReceiptResult(db, reserved.receipt.id, { controlRevision: revision, result: { workspaceControlEventId }, }); return { workspaceControlEventId, affectedSessionEvents }; } /** Discovery is a hint. Identity, deadline and pause ownership are rechecked under the fence. */ export async function fireWorkspacePauseTimerInTransaction( db: SessionActivityDatabase, input: { workspaceId: string; timerId: string }, ): Promise | null> { const workspace = await lockWorkspaceInferenceControl(db, input.workspaceId, "update", { lockTimeoutMs: 1000, }); const [clock] = await db.execute<{ now: Date }>(sql`select clock_timestamp() as now`); if ( workspace.timerId !== input.timerId || !workspace.timerDueAt || new Date(workspace.timerDueAt).getTime() > new Date(clock!.now).getTime() ) return null; const action = workspace.timerAction as "pause" | "resume"; // A superseding pause must never be undone by an old timer, even across rolling upgrades. if ( action === "resume" && (workspace.workspaceState !== "paused" || Number(workspace.workspacePauseRevision) !== Number(workspace.timerPauseRevision)) ) { await db .update(schema.workspaceInferenceControls) .set(clearWorkspaceTimerFields) .where(eq(schema.workspaceInferenceControls.workspaceId, input.workspaceId)); return null; } const result = await mutateWorkspaceControlInTransaction(db, { accountId: workspace.accountId, workspaceId: input.workspaceId, actor: { type: "service", subjectId: "service:workspace-pause-timer" }, operationKey: `timer:${input.timerId}:${action}`, action, timerExecution: true, }); // Use application time only for display elsewhere; deadlines are database-clock based. const [applied] = await db.execute<{ now: Date }>(sql`select clock_timestamp() as now`); await db .update(schema.workspaceInferenceControls) .set({ ...clearWorkspaceTimerFields, ...(action === "pause" && workspace.timerPauseForSeconds !== null ? { timerId: input.timerId, timerAction: "resume", timerDueAt: new Date( new Date(applied!.now).getTime() + workspace.timerPauseForSeconds * 1000, ), timerPauseRevision: result.revision, } : {}), }) .where(eq(schema.workspaceInferenceControls.workspaceId, input.workspaceId)); return result; }