import {
  emptyRowFailureCounts,
  readRowFailureCounts,
  type RowFailureCounts,
} from '../row-failure-summary';
import { RUN_EVENT_KIND } from '../run-event-catalog';
import { hydratePlayRunnerConfig } from '../protocol';
import { appendFileSync, createReadStream, writeFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { dirname, isAbsolute, resolve } from 'node:path';
import { createRequire } from 'node:module';
import { createHash, randomUUID } from 'node:crypto';
import { formatWithOptions } from 'node:util';
import { compileFunction } from 'node:vm';
import { gunzipSync } from 'node:zlib';
import { Readable } from 'node:stream';
import { parse } from 'csv-parse';
import { csvInputTextOptions } from '../../plays/csv-text-repair';
import { install as installSourceMapSupport } from 'source-map-support';
import {
  createDeferredPlayDataset,
  setPlayDatasetSourceRowIdentity,
  isPlayDataset,
  isSerializedPlayDataset,
  iteratePlayDatasetInputPages,
  type PlayDataset,
} from '../../plays/dataset';
import { AppRuntimeRateStateBackend } from '../governor/app-runtime-rate-state-backend';
import { AppRuntimeBudgetStateBackend } from '../governor/app-runtime-budget-state-backend';
import {
  parseCtxFetchHttpFailureDiagnostic,
  type CtxFetchHttpFailureDiagnostic,
} from '../log-provenance';
import type {
  PlayRunnerEvent,
  PlayRunnerExecutionConfig,
  PlayRunOutputWarning,
  PlayRunnerResult,
} from '../protocol';
import {
  DURABLE_INVOCATION_FENCE_ATTESTATION_HEADER,
  DURABLE_INVOCATION_FENCE_ATTESTATION_VALUE,
} from '../durable-invocation-fence';
import type { PlayRunInputPayload } from '../play-input';
import type {
  PlayLogContext,
  PlayLogMetadata,
} from '../log-context';
import { playRunInputObjectView } from '../play-input';
import {
  normalizePlayRunFailure,
  runtimeLimitExceededCause,
  runtimeLimitExceededFailure,
} from '../run-failure';
import { createPlayContext } from '../context';
import {
  isHtmlErrorBody,
  normalizeToolHttpErrorMessage,
  summarizeHtmlErrorBody,
} from '../tool-http-errors';
import { augmentSheetContractWithDatasetFields } from '../../play-data-plane/sheet-contract';
import { nextWorkCounterInvocationSeq } from '../runtime-work-counters';
import type { RuntimeApiResponseMeta } from '../app-runtime-api';
import { onMemoryPressure } from '../memory-pressure-signal';
import {
  shouldEmitProgressSidecarEvent,
  shouldEmitStdoutEvent,
} from './progress-sidecar';
import {
  startRunnerHeartbeatLoop,
  type RunnerHeartbeatStop,
} from './runtime-heartbeat';
import {
  formatRunnerGatewayTransportSummary,
  isRunnerGatewayNoResponseError,
  type RunnerGatewayTransportEvent,
} from './runtime-gateway-transport';
import { startConfiguredPlayRunnerRuntimeDeadline } from './runtime-deadline';
import {
  createRunnerProgressPusher,
  type RunnerProgressPusher,
} from './runtime-progress-push';
import { collectStartupEgressProbeLines } from './egress-probe';
import {
  pushRunnerTerminal,
  runnerTerminalResultForTransport,
  runnerTerminalHandoffForTransport,
  type PushRunnerTerminalOptions,
  type PlayRunnerTerminalTransportResult,
  type PlayRunnerTerminalTransportEvent,
} from './runtime-terminal-push';
import { vercelProtectionBypassHeader } from '../vercel-protection';
import {
  createRuntimeToolHooks,
  type RuntimeToolMetadata,
} from './runtime-tool-hooks';
import type {
  ContextOptions,
  RuntimeSheetDatasetPageReaderScope,
  IntegrationEventWaitBoundary,
  IntegrationEventWaitHandler,
  IntegrationEventWaitRuntimeContext,
  PlayRowUpdate,
  ResolvedPlayExecution,
  RuntimeStepReceipt,
  PlayExecutionEvent,
} from '../ctx-types';
import {
  applyCsvRenameProjection,
  type CsvRenameOptions,
} from '../csv-rename';
import { isPlayExecutionSuspendedError } from '../suspension';
import { assertNoSecretTaint } from '../secret-capability';
import { PLAY_ARTIFACT_KINDS } from '../backend';
import { assertNodeRunnableArtifact } from '../../plays/artifact-kind-guard';
import { createRuntimeDatasetId } from '../dataset-id';
import {
  formatDatasetAvailabilityLog,
  formatDatasetRegistrationLog,
} from '../dataset-lifecycle-log';
import {
  RUNTIME_RECEIPT_COMPLETION_BUFFER_MAX_BYTES,
  RUNTIME_RECEIPT_COMPLETION_BUFFER_MAX_ITEMS,
  RUNTIME_RECEIPT_COMPLETION_MAX_IN_FLIGHT_BATCHES,
  RUNTIME_RECEIPT_CONTROL_BUFFER_MAX_BYTES,
  RUNTIME_RECEIPT_CONTROL_BUFFER_MAX_ITEMS,
  RUNTIME_RECEIPT_CONTROL_MAX_IN_FLIGHT_BATCHES,
  RUNNER_POST_TERMINAL_DIAGNOSTIC_MAX_BYTES,
  truncateCustomerPlayReturnWithinLimit,
} from '../output-size-limits';
import {
  resolveRuntimeReferencedPlay,
  getRuntimeArrayInputManifest,
  beginRuntimeArrayInput,
  putRuntimeArrayInputPage,
  sealRuntimeArrayInput,
  readRuntimeArrayInputPage,
  createCompleteRuntimeMapRowsOperation,
  finishRuntimeSheetRunMembership,
  createRuntimeSheetDatasetPageReader,
  type RuntimeSheetDatasetPageReader,
  readRuntimeSheetDatasetRowKeys,
  readRuntimeSheetDatasetRows,
  releaseRuntimeWorkReceipts,
  startRuntimeSheetDataset,
  startRuntimeSheetDatasetPages,
  supersededRuntimeMapRows,
  type RuntimeMapRowsStaleRow,
  type RuntimeMapRowsWriteResult,
} from '../runtime-api';
import { installPgRuntimePoolDriver } from '../runtime-pg-driver-pg';
import { createRuntimeToolAuthScopeDigestResolver } from '../auth-scope-resolver';
import { RUNTIME_ASYNC_EXECUTION_RECOVERY_TRANSPORT_HEADER } from '../durable-invocation-fence';
import { createRunScopedChildPlayResolver } from './child-play-resolver';
import { normalizePlayContractCompatibility } from '../../plays/contracts';
import { ToolExecutionError } from '../../plays/tool-execution-error';
import {
  SLACK_HITL_TIMEOUT_ERROR_CODE,
  SlackHitlTimeoutError,
} from '../../plays/slack-hitl-timeout-error';
import { resolvePlayArtifactRuntimeContract } from '../play-artifact-runtime-contract';
import { validateOptionalPlayAuthoringField } from '../../plays/authoring-contract';
import { retryRuntimeSheetPersistence } from './runtime-sheet-persistence-retry';
import {
  resolveMaxConcurrentExternalCalls,
  resolveMaxConcurrentRows,
} from '../governor/policy';
import {
  STANDARD_PLAY_SANDBOX_RUNTIME_LIMITS,
  validatePlaySandboxRuntimeLimits,
} from '../sandbox-runtime-limits';
import {
  runtimeSheetPageTailHoldCompletedEvent,
  runtimeSheetPageTailWriteMarkerEvent,
} from '../test-runtime-seams';

// Node-runtime play-runner uses the `pg` library for direct Postgres writes
// against per-run scoped Neon roles. Register the driver eagerly at module
// load so the first call into runtime-api.ts has a pool factory available.
installPgRuntimePoolDriver();

type SafeOutboundFetchModule =
  typeof import('../../security/safe-outbound-fetch');
let safeOutboundFetchModule: Promise<SafeOutboundFetchModule> | null = null;

function loadSafeOutboundFetch(): Promise<SafeOutboundFetchModule> {
  safeOutboundFetchModule ??= import('../../security/safe-outbound-fetch');
  return safeOutboundFetchModule;
}

type ReceiptGatewayResponseObserverTarget = Pick<
  ReturnType<typeof createPlayContext>,
  'observeRuntimeGatewayResponse'
>;

/**
 * The receipt adapter is created before the Play Context because the Context
 * needs its durable handlers. Keep the response observer late-bound so those
 * completion requests still contribute their gateway/transport split to the
 * Context's terminal runtime summary.
 */
export function createReceiptGatewayResponseObserver(): {
  attach: (target: ReceiptGatewayResponseObserverTarget) => void;
  onResponseMeta: (meta: RuntimeApiResponseMeta) => void;
} {
  let target: ReceiptGatewayResponseObserverTarget | null = null;
  return {
    attach: (nextTarget) => {
      target = nextTarget;
    },
    onResponseMeta: (meta) => {
      target?.observeRuntimeGatewayResponse(meta);
    },
  };
}

async function safeNodeOutboundFetch(
  input: string | URL,
  init?: RequestInit,
): Promise<Response> {
  const { safeOutboundFetch } = await loadSafeOutboundFetch();
  return safeOutboundFetch(input, init);
}

async function safeNodeStreamingOutboundFetch(
  input: string | URL,
  init?: RequestInit,
): Promise<Response> {
  const { safeOutboundFetch } = await loadSafeOutboundFetch();
  return safeOutboundFetch(input, init, { streamResponseBody: true });
}

import {
  resolveSheetContractForTableNamespace,
  sqlSafePlayColumnName,
  type PlaySheetContract,
} from '../../plays/static-pipeline';
import { type PlayBundleArtifact } from '../../plays/artifact-types';
import {
  RuntimeReceiptStoreAdapter,
  type RuntimeReceiptStoreHandlers,
} from '../runtime-receipt-store-adapter';
import {
  applyRowUpdatesViaAppRuntime,
  launchPlayAsyncViaAppRuntime,
  observeDocflowNodeViaAppRuntime,
} from '../app-runtime-api';
import { RUNTIME_CAPACITY_POLICY } from '../runtime-capacity-policy';
import { RUNTIME_RELIABILITY_POLICY } from '../runtime-reliability-policy';
import { RUNNER_GATEWAY_CONNECTION_RETRY_BUDGET_MS } from '../runtime-constants';

const playRuntimeRequire = createRequire(`${process.cwd()}/package.json`);
const moduleRuntime = playRuntimeRequire('module') as {
  Module: {
    new (
      id: string,
      parent?: unknown,
    ): {
      exports: unknown;
      filename: string;
      paths: string[];
      require: (id: string) => unknown;
    };
    _nodeModulePaths: (from: string) => string[];
  };
};
let sourceMapSupportInstalled = false;
const runtimeSourceMaps = new Map<string, string>();
const runtimeSourceFiles = new Map<string, string>();
const runtimeArtifactReferences = new Map<
  string,
  { artifactHash: string; sourceMapHash: string; count: number }
>();
const CSV_NAMESPACE_PREFIX = 'csv';

function assertBundledRuntimeRequire(id: string): void {
  if (
    id === '.' ||
    id.startsWith('./') ||
    id.startsWith('../') ||
    isAbsolute(id) ||
    id.startsWith('file:')
  ) {
    throw new Error(
      `Runtime require("${id}") cannot load a local file. Local play dependencies must be bundled before execution.`,
    );
  }
}

function createPlayRuntimeRequire(): ReturnType<typeof createRequire> {
  const runtimeRequire = ((id: string) => {
    assertBundledRuntimeRequire(id);
    return playRuntimeRequire(id);
  }) as ReturnType<typeof createRequire>;
  runtimeRequire.resolve = Object.assign(
    (id: string, options?: { paths?: string[] }) => {
      assertBundledRuntimeRequire(id);
      return playRuntimeRequire.resolve(id, options);
    },
    {
      paths: (id: string) => {
        assertBundledRuntimeRequire(id);
        return playRuntimeRequire.resolve.paths(id);
      },
    },
  );
  runtimeRequire.main = playRuntimeRequire.main;
  runtimeRequire.extensions = playRuntimeRequire.extensions;
  runtimeRequire.cache = playRuntimeRequire.cache;
  return runtimeRequire;
}
const WAIT_CONFIG_POLL_MS = 25;
const WAIT_CONFIG_TIMEOUT_MS = 120_000;
// Outlasts the claim lease, because an unanswered heartbeat says nothing about
// the park. A stall shorter than the lease keeps this sandbox, and a longer one
// reaches the heartbeat loop's own guard and is reported as an outage.
export const RUNNER_EXECUTION_ACK_TIMEOUT_MS =
  (RUNTIME_RELIABILITY_POLICY.worker.claimLeaseSeconds + 30) * 1_000;
const RUNNER_RUNTIME_CONTROL_MAX_ATTEMPTS =
  RUNTIME_RELIABILITY_POLICY.gateway.runnerControlMaxAttempts;
const RUNNER_RUNTIME_CONTROL_RETRY_DELAYS_MS = [100, 250] as const;
export const RUNNER_RUNTIME_CONTROL_REQUEST_TIMEOUT_MS =
  RUNTIME_RELIABILITY_POLICY.gateway.runnerControlRequestTimeoutMs;
const RUNTIME_RECEIPT_GATEWAY_BATCH_SIZE = 200;
const RUNTIME_RECEIPT_GATEWAY_BATCH_MAX_WAIT_MS = 15;
const RUNTIME_RECEIPT_GATEWAY_REQUEST_TIMEOUT_MS =
  RUNTIME_CAPACITY_POLICY.receiptGateway.requestTimeoutMs;
// Slack's native action wait persists its interaction intent before posting or
// updating a card. Replaying the same boundary either reuses its bound message
// or refuses an ambiguous unbound post, so transient gateway responses are safe
// to retry without creating a second card.
const RETRY_SAFE_EVENT_WAIT_ARM_TOOLS = new Set([
  'test_wait_for_event',
  'slack_wait_for_action',
]);

/**
 * The Context already bounds receipt completion to sixteen flights. The
 * adapter is the same receipt writer at the gateway boundary, so leaving its
 * default single flight serializes those independent batches again after they
 * have left the Context. Keep the two writers on the same bounded lanes and
 * make the adapter's retained command envelope explicit.
 */
export function playRunnerReceiptStoreAdapterOptions() {
  return {
    maxBatchSize: RUNTIME_RECEIPT_GATEWAY_BATCH_SIZE,
    maxFlushMs: RUNTIME_RECEIPT_GATEWAY_BATCH_MAX_WAIT_MS,
    maxInFlightBatches:
      RUNTIME_RECEIPT_COMPLETION_MAX_IN_FLIGHT_BATCHES +
      RUNTIME_RECEIPT_CONTROL_MAX_IN_FLIGHT_BATCHES,
    maxBufferedItems:
      RUNTIME_RECEIPT_COMPLETION_BUFFER_MAX_ITEMS +
      RUNTIME_RECEIPT_CONTROL_BUFFER_MAX_ITEMS,
    maxBufferedBytes:
      RUNTIME_RECEIPT_COMPLETION_BUFFER_MAX_BYTES +
      RUNTIME_RECEIPT_CONTROL_BUFFER_MAX_BYTES,
    maxCompletionInFlightBatches:
      RUNTIME_RECEIPT_COMPLETION_MAX_IN_FLIGHT_BATCHES,
    maxControlInFlightBatches: RUNTIME_RECEIPT_CONTROL_MAX_IN_FLIGHT_BATCHES,
    maxCompletionBufferedItems: RUNTIME_RECEIPT_COMPLETION_BUFFER_MAX_ITEMS,
    maxCompletionBufferedBytes: RUNTIME_RECEIPT_COMPLETION_BUFFER_MAX_BYTES,
    maxControlBufferedItems: RUNTIME_RECEIPT_CONTROL_BUFFER_MAX_ITEMS,
    maxControlBufferedBytes: RUNTIME_RECEIPT_CONTROL_BUFFER_MAX_BYTES,
  };
}

// The one receipt backend: one Play Durability Store Adapter bound to the
// co-located receipt gateway. There is no host-injected or app-runtime path.
type RuntimeStepReceiptHandlers = RuntimeReceiptStoreHandlers;

type RuntimeToolAuthScope = {
  digest?: unknown;
  managedAsyncExecutionRecovery?: unknown;
  managedAsyncExecutionRecoveryOrigin?: unknown;
  rateScope?: {
    bucketId?: unknown;
    provider?: unknown;
    token?: unknown;
  };
};

export function assertRuntimeSheetAttemptPersistedTerminalRows(input: {
  tableNamespace: string;
  runId: string;
  attemptId?: string | null;
  updatedRows: number;
  expectedRows: number;
  persistedTerminalRows?: number | null;
  fencedKeys?: string[];
}): void {
  // Kept as a temporary source-compatible seam for callers compiled against
  // the lease model. A partial update is classified from the terminal-write
  // result, never from this count.
  void input;
}

export function deterministicRuntimeSheetAttemptId(input: {
  playName: string;
  runId: string;
  tableNamespace: string;
  attemptSeq: number;
}): string {
  const digest = createHash('sha256')
    .update(input.playName)
    .update('\0')
    .update(input.runId)
    .update('\0')
    .update(input.tableNamespace)
    .update('\0')
    .update(String(input.attemptSeq))
    .digest('hex')
    .slice(0, 32);
  return `sheet-attempt:${digest}`;
}

/** The sheet's admission version for one table; a value, not a wire marker. */
type SheetWriteVersionValue = number;

export type RunnerRuntimeSheetAttempt = {
  attemptId: string;
  attemptOwnerRunId: string;
  attemptExpiresAt: string;
  attemptSeq: number;
  writeVersion?: SheetWriteVersionValue;
};

/**
 * The sheet attempt record to keep after a map start admitted one source page
 * of a table. A runtime-sheet-backed map admits its source one page at a time
 * while earlier pages' rows are still executing, and every terminal write is
 * fenced by the write version the runner sends. If each page minted its own
 * version, every completion flushed after the next page's admission would
 * carry a version the earlier rows were never admitted under and be rejected
 * as stale (the 2026-09-18 20,000-row incident: 4,350 rows executed, 45
 * persisted). So the first admission's write version is requested again for
 * every later page (see `runtimeSheetStartWriteVersion`) and must come back
 * unchanged; anything else means the sheet no longer belongs to this runner.
 */
export function runtimeSheetAttemptForMapStart(input: {
  tableNamespace: string;
  runId: string;
  existing: RunnerRuntimeSheetAttempt | undefined;
  mapStartResult: {
    attemptId: string;
    attemptOwnerRunId: string;
    attemptExpiresAt: string;
    attemptSeq?: number | null;
    writeVersion?: SheetWriteVersionValue | null;
  };
  runnerRunAttempt: number;
}): RunnerRuntimeSheetAttempt {
  const requested = input.existing?.writeVersion;
  const returned = input.mapStartResult.writeVersion ?? undefined;
  if (requested != null && returned !== requested) {
    throw new Error(
      `Runtime sheet start for table "${input.tableNamespace}" (run ${input.runId}) ` +
        `was asked to keep write version ${requested} for a later source page but ` +
        `returned ${returned ?? 'none'}; the runner cannot persist rows under two ` +
        `write versions, so this map cannot continue.`,
    );
  }
  return {
    attemptId: input.mapStartResult.attemptId,
    attemptOwnerRunId: input.mapStartResult.attemptOwnerRunId,
    attemptExpiresAt: input.mapStartResult.attemptExpiresAt,
    attemptSeq: input.mapStartResult.attemptSeq ?? input.runnerRunAttempt,
    ...(returned != null ? { writeVersion: returned } : {}),
  };
}

/** The write version a later source page of the same table must be admitted under. */
export function runtimeSheetStartWriteVersion(
  existing: RunnerRuntimeSheetAttempt | undefined,
): { writeVersion: SheetWriteVersionValue } | Record<string, never> {
  return existing?.writeVersion != null
    ? { writeVersion: existing.writeVersion }
    : {};
}

/** Stale latest-view rows are reported, not escalated to a run failure. */
export function runtimeSheetTerminalWriteStaleRows(input: {
  result: Pick<RuntimeMapRowsWriteResult, 'staleKeys' | 'staleRows'>;
  recoveredStaleKeys: Iterable<string>;
}): RuntimeMapRowsStaleRow[] {
  return supersededRuntimeMapRows(input.result, {
    exceptKeys: input.recoveredStaleKeys,
  });
}

/** Only accepted current-sheet rows contribute to persisted lifecycle counts. */
export function runtimeSheetTerminalWriteCounts(input: {
  rows: ReadonlyArray<{ key: string; status?: string }>;
  committedKeys: Iterable<string>;
  recoveredStaleKeys: Iterable<string>;
}): { persistedRows: number; succeededRows: number; failedRows: number } {
  const acceptedKeys = new Set([
    ...input.committedKeys,
    ...input.recoveredStaleKeys,
  ]);
  const acceptedRows = new Map(
    input.rows
      .filter((row) => acceptedKeys.has(row.key))
      .map((row) => [row.key, row]),
  );
  const failedRows = [...acceptedRows.values()].filter(
    (row) => row.status === 'failed',
  ).length;
  return {
    persistedRows: acceptedRows.size,
    succeededRows: acceptedRows.size - failedRows,
    failedRows,
  };
}

/** Distinct settled counts include saved siblings, never skipped input duplicates. */
export function runtimeSheetTerminalMapCounts(
  current: { persistedRows: number; succeededRows: number; failedRows: number },
  map: { succeededRows: number; failedRows: number },
): { persistedRows: number; succeededRows: number; failedRows: number } {
  const succeededRows = Math.max(current.succeededRows, map.succeededRows);
  const failedRows = Math.max(current.failedRows, map.failedRows);
  return {
    persistedRows: Math.max(current.persistedRows, succeededRows + failedRows),
    succeededRows,
    failedRows,
  };
}

async function vercelBypassHeaders(
  config: Pick<PlayRunnerExecutionConfig, 'context'>,
): Promise<Record<string, string>> {
  return vercelProtectionBypassHeader(
    config.context.vercelProtectionBypassToken,
  );
}

function isRetryableRuntimeControlStatus(status: number): boolean {
  return (
    status === 408 ||
    status === 429 ||
    (status >= 520 && status <= 524) ||
    status === 502 ||
    status === 503 ||
    status === 504
  );
}

async function sleepRunnerRuntimeControlRetry(ms: number): Promise<void> {
  await new Promise<void>((resolve) => setTimeout(resolve, ms));
}

function runnerRuntimeControlUrlHost(url: string): string {
  try {
    return new URL(url).host;
  } catch {
    return '<unparseable-url>';
  }
}

/**
 * Thrown when a sandbox -> receipt-gateway runtime-control call is redirected
 * (any 3xx). This is a deterministic wiring failure, never a transient one, so
 * it must escape the retry loop immediately without being re-wrapped as a
 * transport error.
 */
export class RunnerRuntimeControlRedirectError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'RunnerRuntimeControlRedirectError';
  }
}

export async function fetchRunnerRuntimeControl(input: {
  url: string;
  init: RequestInit;
  description: string;
  retrySafe: boolean;
  /** Injectable fetch for unit tests; defaults to the global fetch. */
  fetchImpl?: typeof fetch;
  /** Injectable retry sleep for unit tests; defaults to a real timer. */
  sleepImpl?: (ms: number) => Promise<void>;
  /** Per-attempt transport deadline; injectable only to keep timeout tests fast. */
  timeoutMs?: number;
}): Promise<Response> {
  const fetchImpl = input.fetchImpl ?? fetch;
  const sleepImpl = input.sleepImpl ?? sleepRunnerRuntimeControlRetry;
  const startedAt = Date.now();
  // Error responses spend the ordinary attempts. A request that gets no
  // response at all keeps retrying through a sandbox network cut.
  let respondedAttempts = 0;
  for (let attempt = 1; ; attempt += 1) {
    const timeoutMs =
      input.timeoutMs ?? RUNNER_RUNTIME_CONTROL_REQUEST_TIMEOUT_MS;
    const timeoutSignal = AbortSignal.timeout(timeoutMs);
    const signal = input.init.signal
      ? AbortSignal.any([input.init.signal, timeoutSignal])
      : timeoutSignal;
    try {
      // Never follow redirects on the sandbox -> receipt-gateway control plane.
      // Every runtime-control call from the Daytona sandbox targets the gateway
      // (context.baseUrl is rewritten to the gateway URL, and the sandbox holds
      // NO Vercel protection-bypass credential). A 3xx therefore means the
      // request escaped the gateway and hit Vercel Deployment Protection bare,
      // whose SSO redirect drops our Authorization/bypass headers. Following it
      // would swallow the failure into an opaque "307 Redirecting..." body from
      // the wrong host. Surface it loudly with the target host instead.
      const response = await fetchImpl(input.url, {
        ...input.init,
        redirect: 'manual',
        signal,
      });
      if (response.status >= 300 && response.status < 400) {
        const location = response.headers.get('location') ?? '<none>';
        await response.text().catch(() => '');
        throw new RunnerRuntimeControlRedirectError(
          `${input.description} was redirected (${response.status}) by host ` +
            `${runnerRuntimeControlUrlHost(input.url)} -> ${location}. Sandbox ` +
            `runtime-control calls must terminate at the receipt gateway; a ` +
            `redirect means the request reached Vercel Deployment Protection ` +
            `without a bypass credential. Confirm context.baseUrl points at the ` +
            `gateway and the launch carries vercelProtectionBypassToken.`,
        );
      }
      respondedAttempts += 1;
      if (
        input.retrySafe &&
        respondedAttempts < RUNNER_RUNTIME_CONTROL_MAX_ATTEMPTS &&
        isRetryableRuntimeControlStatus(response.status)
      ) {
        await response.text().catch(() => '');
        await sleepImpl(
          RUNNER_RUNTIME_CONTROL_RETRY_DELAYS_MS[respondedAttempts - 1] ?? 250,
        );
        continue;
      }
      // `fetch()` resolves once headers arrive. Leaving the body for callers
      // means this attempt's timeout signal can fire during `response.json()`
      // outside this retry loop. That turns a recoverable, partially delivered
      // gateway response into a terminal child-run failure under a large HITL
      // fanout. Buffer the deliberately small runtime-control response before
      // returning it so one attempt owns both headers and body.
      const body = await response.arrayBuffer();
      return new Response(body, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
      });
    } catch (error) {
      // A redirect is a deterministic wiring failure, not a transient transport
      // fault. Surface it immediately with its host-named message intact.
      if (error instanceof RunnerRuntimeControlRedirectError) {
        throw error;
      }
      const message = error instanceof Error ? error.message : String(error);
      const transportMessage = timeoutSignal.aborted
        ? `timed out after ${timeoutMs}ms`
        : message;
      const failure = new Error(
        `${input.description} transport failed: ${transportMessage}`,
      );
      if (!input.retrySafe || input.init.signal?.aborted) throw failure;
      const delayMs =
        RUNNER_RUNTIME_CONTROL_RETRY_DELAYS_MS[attempt - 1] ??
        Math.min(
          8_000,
          1_000 * (attempt - RUNNER_RUNTIME_CONTROL_RETRY_DELAYS_MS.length),
        );
      const outageRetryAllowed =
        (timeoutSignal.aborted || isRunnerGatewayNoResponseError(error)) &&
        Date.now() - startedAt + delayMs <=
          RUNNER_GATEWAY_CONNECTION_RETRY_BUDGET_MS;
      if (
        attempt >= RUNNER_RUNTIME_CONTROL_MAX_ATTEMPTS &&
        !outageRetryAllowed
      ) {
        throw failure;
      }
      await sleepImpl(delayMs);
    }
  }
}

function createRuntimeToolMetadataResolver(config: PlayRunnerExecutionConfig) {
  const cached = new Map<string, Promise<RuntimeToolMetadata>>();

  return async (toolId: string): Promise<RuntimeToolMetadata> => {
    const normalizedToolId = String(toolId || '').trim();
    if (
      !normalizedToolId ||
      !config.context.executorToken ||
      !config.context.baseUrl
    ) {
      throw new Error(
        `Runtime metadata lookup for tool ${normalizedToolId || '<empty>'} requires executorToken and baseUrl.`,
      );
    }

    const cachedMetadata = cached.get(normalizedToolId);
    if (cachedMetadata) {
      return await cachedMetadata;
    }

    const promise = (async () => {
      const url = `${config.context.baseUrl}/api/v2/plays/runtime-tools/${encodeURIComponent(normalizedToolId)}`;
      const response = await fetchRunnerRuntimeControl({
        url,
        description: `Runtime metadata lookup for tool ${normalizedToolId}`,
        retrySafe: true,
        init: {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${config.context.executorToken}`,
            ...(await vercelBypassHeaders(config)),
          },
        },
      });
      if (!response.ok) {
        throw await runtimeControlHttpError({
          description: `Runtime metadata lookup for tool ${normalizedToolId}`,
          toolId: normalizedToolId,
          response,
        });
      }
      return (await response.json()) as RuntimeToolMetadata;
    })();

    cached.set(normalizedToolId, promise);
    return await promise;
  };
}

export function createAppRuntimeToolAuthScopeDigestResolver(
  config: Pick<PlayRunnerExecutionConfig, 'context'>,
) {
  const asyncRecoveryOrigins = new Map<string, string>();
  const executionRelayRecovery = new Map<
    string,
    Promise<{ origin: string } | null>
  >();
  const rateScopes = new Map<
    string,
    { bucketId: string; provider: string; token: string }
  >();
  const digestResolver = createRuntimeToolAuthScopeDigestResolver({
    missingToolIdMessage: 'Runtime auth scope lookup requires tool id.',
    retryDelaysMs: [],
    fetchDigest: async (normalizedToolId) => {
      if (!config.context.executorToken || !config.context.baseUrl) {
        throw new Error(
          `Runtime auth scope lookup for tool ${normalizedToolId || '<empty>'} requires executorToken and baseUrl.`,
        );
      }
      const url = `${config.context.baseUrl}/api/v2/plays/runtime-tools/${encodeURIComponent(normalizedToolId)}/auth-scope`;
      const response = await fetchRunnerRuntimeControl({
        url,
        description: `Runtime auth scope lookup for tool ${normalizedToolId}`,
        retrySafe: true,
        init: {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${config.context.executorToken}`,
            ...(await vercelBypassHeaders(config)),
          },
        },
      });
      if (!response.ok) {
        throw await runtimeControlHttpError({
          description: `Runtime auth scope lookup for tool ${normalizedToolId}`,
          toolId: normalizedToolId,
          response,
        });
      }
      const body = (await response.json()) as RuntimeToolAuthScope;
      const digest = typeof body.digest === 'string' ? body.digest.trim() : '';
      if (!digest) {
        throw new Error(
          `Runtime auth scope lookup for tool ${normalizedToolId} returned no digest.`,
        );
      }
      const rateScope = body.rateScope;
      const bucketId =
        typeof rateScope?.bucketId === 'string'
          ? rateScope.bucketId.trim()
          : '';
      const provider =
        typeof rateScope?.provider === 'string'
          ? rateScope.provider.trim()
          : '';
      const token =
        typeof rateScope?.token === 'string' ? rateScope.token.trim() : '';
      if (!bucketId || !provider || !token) {
        throw new Error(
          `Runtime auth scope lookup for tool ${normalizedToolId} returned no rate scope.`,
        );
      }
      rateScopes.set(normalizedToolId, { bucketId, provider, token });
      if (
        response.headers.get(
          RUNTIME_ASYNC_EXECUTION_RECOVERY_TRANSPORT_HEADER,
        ) === 'true' &&
        body.managedAsyncExecutionRecovery === true &&
        typeof body.managedAsyncExecutionRecoveryOrigin === 'string'
      ) {
        asyncRecoveryOrigins.set(
          normalizedToolId,
          body.managedAsyncExecutionRecoveryOrigin,
        );
      }
      return digest;
    },
  });
  const invalidateDigest = digestResolver.invalidate;
  return Object.assign(digestResolver, {
    invalidate: (toolId?: string | null) => {
      invalidateDigest(toolId);
      const normalized = String(toolId || '').trim();
      if (normalized) rateScopes.delete(normalized);
      else rateScopes.clear();
      if (normalized) asyncRecoveryOrigins.delete(normalized);
      else asyncRecoveryOrigins.clear();
      if (normalized) executionRelayRecovery.delete(normalized);
      else executionRelayRecovery.clear();
    },
    rateScope: async (toolId: string, expectedProvider: string) => {
      await digestResolver(toolId);
      const scope = rateScopes.get(toolId.trim());
      if (!scope || scope.provider !== expectedProvider) {
        throw new Error(
          `Runtime rate scope provider mismatch for tool ${toolId}.`,
        );
      }
      return { bucketId: scope.bucketId, token: scope.token };
    },
    asyncExecutionRecovery: async (toolId: string) => {
      const normalized = toolId.trim();
      const digest = await digestResolver(normalized);
      const receiptBase = config.context.baseUrl!.trim().replace(/\/$/, '');
      const executionBase =
        config.context.executionGatewayBaseUrl?.trim().replace(/\/$/, '') ||
        receiptBase;
      if (executionBase === receiptBase) {
        const origin = asyncRecoveryOrigins.get(normalized);
        return origin ? { origin } : null;
      }
      // Receipt and execution fleets roll independently. Keep canonical
      // digest/rate truth on the receipt owner, but never treat its transport
      // capability as proof that the execution relay forwards the app ACK.
      let proof = executionRelayRecovery.get(normalized);
      if (!proof) {
        proof = (async () => {
          const response = await fetchRunnerRuntimeControl({
            url: `${executionBase}/api/v2/plays/runtime-tools/${encodeURIComponent(normalized)}/auth-scope`,
            description: `Runtime async recovery capability for tool ${normalized}`,
            retrySafe: true,
            init: {
              method: 'GET',
              headers: {
                Authorization: `Bearer ${config.context.executorToken}`,
                ...(await vercelBypassHeaders(config)),
              },
            },
          });
          if (
            !response.ok ||
            response.headers.get(
              RUNTIME_ASYNC_EXECUTION_RECOVERY_TRANSPORT_HEADER,
            ) !== 'true'
          )
            return null;
          const body = (await response.json()) as RuntimeToolAuthScope;
          return body.digest === digest &&
            body.managedAsyncExecutionRecovery === true &&
            typeof body.managedAsyncExecutionRecoveryOrigin === 'string'
            ? { origin: body.managedAsyncExecutionRecoveryOrigin }
            : null;
        })().catch(() => {
          // This optional capability cannot authorize replay on an unavailable
          // hop. Preserve the existing unkeyed path and allow later discovery.
          if (executionRelayRecovery.get(normalized) === proof) {
            executionRelayRecovery.delete(normalized);
          }
          return null;
        });
        executionRelayRecovery.set(normalized, proof);
      }
      return await proof;
    },
  });
}

function createRateStateBackendForConfig(
  config: PlayRunnerExecutionConfig,
): Pick<
  ContextOptions,
  'rateState' | 'budgetState' | 'requireSharedRateState'
> {
  const backend = config.context.rateStateBackend;
  if (!backend || backend.kind === 'in_memory') return {};
  const baseUrl = config.context.baseUrl?.trim();
  const executorToken = config.context.executorToken?.trim();
  if (!baseUrl || !executorToken) {
    throw new Error(
      'Node play runtime requires baseUrl and executorToken for shared rate state.',
    );
  }
  const runtimeApi = {
    baseUrl,
    executorToken,
    vercelProtectionBypassToken:
      config.context.vercelProtectionBypassToken ?? null,
    integrationMode: config.context.integrationMode,
    connectionRetryBudgetMs: RUNNER_GATEWAY_CONNECTION_RETRY_BUDGET_MS,
  };
  return {
    requireSharedRateState: true,
    rateState: new AppRuntimeRateStateBackend(runtimeApi, {
      schedulerSchema: backend.schedulerSchema ?? null,
    }),
    budgetState: new AppRuntimeBudgetStateBackend(
      runtimeApi,
      backend.schedulerSchema ?? null,
    ),
  };
}

export function createRuntimeEventWaitHandler(
  config: PlayRunnerExecutionConfig,
  toolId: string,
): IntegrationEventWaitHandler | null {
  const normalizedToolId = String(toolId || '').trim();
  if (
    !normalizedToolId ||
    !config.context.executorToken ||
    !config.context.baseUrl
  ) {
    return null;
  }

  async function callRuntimeEventWaitEndpoint(
    input:
      | {
          phase: 'prepare';
          payload: Record<string, unknown>;
          context: IntegrationEventWaitRuntimeContext;
        }
      | {
          phase: 'arm';
          payload: Record<string, unknown>;
          context: IntegrationEventWaitRuntimeContext;
          boundary: IntegrationEventWaitBoundary;
        }
      | {
          phase: 'timeout';
          payload: Record<string, unknown>;
          context: IntegrationEventWaitRuntimeContext;
          boundary: IntegrationEventWaitBoundary;
        },
  ): Promise<IntegrationEventWaitBoundary> {
    const url = `${config.context.baseUrl}/api/v2/plays/runtime-tools/${encodeURIComponent(normalizedToolId)}/event-wait`;
    const response = await fetchRunnerRuntimeControl({
      url,
      description: `Event wait runtime call for tool ${normalizedToolId}`,
      retrySafe:
        input.phase === 'prepare' ||
        RETRY_SAFE_EVENT_WAIT_ARM_TOOLS.has(normalizedToolId),
      init: {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${config.context.executorToken}`,
          ...(await vercelBypassHeaders(config)),
        },
        body: JSON.stringify(input),
      },
    });
    if (response.status === 404) {
      throw new Error(`No event wait handler for tool ${normalizedToolId}.`);
    }
    if (!response.ok) {
      const bodyText = await response.text();
      const timeoutError = runtimeControlSlackHitlTimeoutError({
        toolId: normalizedToolId,
        phase: input.phase,
        status: response.status,
        bodyText,
      });
      if (timeoutError) throw timeoutError;
      throw new Error(
        formatRuntimeControlFailure({
          description: `Event wait runtime call for tool ${normalizedToolId}`,
          status: response.status,
          bodyText,
        }),
      );
    }
    return (await response.json()) as IntegrationEventWaitBoundary;
  }

  const handler: IntegrationEventWaitHandler = {
    provider: 'runtime',
    toolId: normalizedToolId,
    prepare: async ({ payload, context }) => {
      const boundary = await callRuntimeEventWaitEndpoint({
        phase: 'prepare',
        payload,
        context,
      });
      // The app owns provider-specific timeout semantics. An older app omits
      // this additive field, retaining its legacy replay behavior safely.
      handler.suspendAfterTimeoutMs =
        boundary.timeoutPolicy?.suspendAfterTimeoutMs;
      return boundary;
    },
    arm: async ({ payload, context, boundary }) =>
      await callRuntimeEventWaitEndpoint({
        phase: 'arm',
        payload,
        context,
        boundary,
      }),
    onTimeout: async ({ payload, context, boundary }) => {
      // Only a newer app advertises this phase. Do not send a new request to an
      // older app during the rollout-skew window.
      if (boundary.timeoutPolicy?.finalizeOnTimeout !== true) return;
      await callRuntimeEventWaitEndpoint({
        phase: 'timeout',
        payload,
        context,
        boundary,
      });
    },
  };
  return handler;
}

export function formatRuntimeControlFailure(input: {
  description: string;
  status: number;
  bodyText: string;
}): string {
  let message = input.bodyText;
  try {
    const parsed = JSON.parse(input.bodyText) as Record<string, unknown>;
    const code =
      typeof parsed.code === 'string' && parsed.code.trim()
        ? parsed.code.trim()
        : null;
    const error =
      typeof parsed.error === 'string' && parsed.error.trim()
        ? parsed.error.trim()
        : typeof parsed.message === 'string' && parsed.message.trim()
          ? parsed.message.trim()
          : null;
    const operatorHint =
      typeof parsed.operator_hint === 'string' && parsed.operator_hint.trim()
        ? parsed.operator_hint.trim()
        : null;
    if (code && error) {
      message = [code, error, operatorHint].filter(Boolean).join(': ');
    }
  } catch {
    // Not JSON. An edge proxy's HTML error page (a tunnel or gateway that
    // never reached the app) is kilobytes of markup with nothing in it but a
    // title and a Ray ID: name the failure and keep those, never the page —
    // it was stored verbatim as every failed row's error (6.7 KB a row).
    message = isHtmlErrorBody(input.bodyText)
      ? `${runtimeControlStatusLabel(input.status)} — ${summarizeHtmlErrorBody(input.bodyText)}`
      : input.bodyText.replace(/\s+/g, ' ').trim().slice(0, 500);
  }
  return `${input.description} failed (${input.status}): ${message}`;
}

/** What a gateway status means, for a reader who sees only the message. */
function runtimeControlStatusLabel(status: number): string {
  switch (status) {
    case 502:
      return 'Bad gateway';
    case 503:
      return 'Service unavailable';
    case 504:
      return 'Gateway timeout';
    case 520:
    case 521:
    case 522:
    case 523:
    case 524:
    case 525:
    case 526:
    case 530:
      return 'Origin unreachable';
    default:
      return `HTTP ${status}`;
  }
}

/**
 * A failed runtime-control call as an Error that says WHICH call, HOW it
 * failed (`status`) and for WHICH tool — never the raw response body.
 */
export async function runtimeControlHttpError(input: {
  description: string;
  toolId: string;
  response: Response;
}): Promise<Error> {
  const bodyText = await input.response.text().catch(() => '');
  const message = formatRuntimeControlFailure({
    description: input.description,
    status: input.response.status,
    bodyText,
  });
  const toolError = normalizeToolHttpErrorMessage({
    toolId: input.toolId,
    status: input.response.status,
    attempt: 1,
    maxAttempts: 1,
    bodyText,
  });
  // Only the serving route can attribute a control failure to a provider
  // connection. Older and unclassified responses retain their fatal error.
  if (
    toolError instanceof ToolExecutionError &&
    toolError.origin !== 'unknown' &&
    toolError.category !== 'unknown'
  ) {
    toolError.message = message;
    return toolError;
  }
  return Object.assign(new Error(message), {
    status: input.response.status,
    toolId: input.toolId,
  });
}

function runtimeControlSlackHitlTimeoutError(input: {
  toolId: string;
  phase: 'prepare' | 'arm' | 'timeout';
  status: number;
  bodyText: string;
}): SlackHitlTimeoutError | null {
  if (
    input.toolId !== 'slack_message_with_hitl' ||
    input.phase !== 'timeout' ||
    input.status !== 408
  ) {
    return null;
  }
  try {
    const body = JSON.parse(input.bodyText) as Record<string, unknown>;
    if (body.code !== SLACK_HITL_TIMEOUT_ERROR_CODE) return null;
    const message =
      typeof body.message === 'string' && body.message.trim()
        ? body.message.trim()
        : typeof body.error === 'string' && body.error.trim()
          ? body.error.trim()
          : undefined;
    return new SlackHitlTimeoutError(
      message?.replace(
        new RegExp(`^${SLACK_HITL_TIMEOUT_ERROR_CODE}:\\s*`),
        '',
      ),
    );
  } catch {
    return null;
  }
}

function inferCsvSheetContract(input: {
  tableNamespace: string;
  rows: readonly Record<string, unknown>[];
}): PlaySheetContract {
  const seen = new Set<string>();
  const columns = input.rows.flatMap((row) =>
    Object.keys(row).flatMap((field) => {
      const normalizedField = field.trim();
      if (!normalizedField || seen.has(normalizedField)) {
        return [];
      }
      seen.add(normalizedField);
      return [
        {
          id: normalizedField,
          sqlName: sqlSafePlayColumnName(normalizedField),
          source: 'input' as const,
          field: normalizedField,
        },
      ];
    }),
  );
  return {
    tableNamespace: input.tableNamespace,
    columns,
  };
}

type ReplayableCsvSource = {
  iterate: () => AsyncIterable<Record<string, unknown>>;
};

async function createStreamingCsvDataset(input: {
  playName: string;
  tableNamespace: string;
  source: ReplayableCsvSource;
  sourceLabel: string;
  options?: CsvRenameOptions;
}): Promise<PlayDataset<Record<string, unknown>>> {
  let cachedCount: number | null = null;
  const datasetId = createRuntimeDatasetId(
    input.playName,
    input.tableNamespace,
  );
  const iterateProjected = () =>
    ({
      async *[Symbol.asyncIterator]() {
        let rowIndex = 0;
        for await (const row of input.source.iterate()) {
          yield setPlayDatasetSourceRowIdentity(
            applyCsvRenameProjection([row], input.options)[0]!,
            { datasetId, rowIndex: rowIndex++ },
          );
        }
      },
    }) as AsyncIterable<Record<string, unknown>>;
  const collect = async (limit?: number) => {
    const rows: Record<string, unknown>[] = [];
    if (limit !== undefined && limit <= 0) return rows;
    for await (const row of iterateProjected()) {
      rows.push(row);
      if (limit !== undefined && rows.length >= limit) break;
    }
    return rows;
  };
  const previewRows = await collect(10);
  return createDeferredPlayDataset({
    datasetKind: 'csv',
    datasetId,
    count: 0,
    knownCount: null,
    previewRows,
    sourceLabel: input.sourceLabel,
    tableNamespace: input.tableNamespace,
    resolvers: {
      count: async () => {
        if (cachedCount !== null) return cachedCount;
        let count = 0;
        for await (const _row of iterateProjected()) count += 1;
        cachedCount = count;
        return count;
      },
      peek: async (limit) => await collect(Math.max(0, limit)),
      materialize: collect,
      iterate: iterateProjected,
    },
  });
}

export interface ExecutePlayRunnerOptions {
  emitEvent?: (event: PlayRunnerEvent) => void;
  signal?: AbortSignal;
  /** Stops future row admission while already admitted rows can persist. */
  rowAdmissionSignal?: AbortSignal;
  executionDrainAtMs?: number;
  /** Runner-local terminal state made available to the deadline drain. */
  onRuntimeReady?: (runtime: {
    log: (line: string) => void;
    timeoutResult: (runtimeLimitSeconds: number) => PlayRunnerResult;
  }) => void;
}

function emitRunnerEvent(
  event: PlayRunnerEvent,
  options?: ExecutePlayRunnerOptions,
): void {
  if (options?.emitEvent) {
    options.emitEvent(event);
    return;
  }
  emit(event);
}

/**
 * In-flight durable docflow observation posts (ADR 0016 rule 2). The wrapper
 * fires them fire-and-forget, but a detached push run's terminal WAKES the
 * parked worker, whose finalize immediately reads the observations table — so
 * a post still in flight over the tunnel loses the race and the terminal
 * ledger misses its nodeIo. Before the graceful terminal emit the runner
 * drains these with a hard cap: the terminal is never failed or delayed
 * beyond the cap, and hard-kill paths (runtime deadline, heartbeat stop,
 * crash epilogue) never wait at all. Empty for undiagrammed plays.
 */
const pendingDocflowObservationPosts = new Set<Promise<unknown>>();
const DOCFLOW_OBSERVATION_TERMINAL_DRAIN_CAP_MS = 2_000;

async function drainPendingDocflowObservationPosts(
  options?: ExecutePlayRunnerOptions,
): Promise<void> {
  if (pendingDocflowObservationPosts.size === 0) {
    return;
  }
  const pendingCount = pendingDocflowObservationPosts.size;
  let capTimer: ReturnType<typeof setTimeout> | null = null;
  const capped = await Promise.race([
    Promise.allSettled([...pendingDocflowObservationPosts]).then(
      () => 'drained' as const,
    ),
    new Promise<'capped'>((resolve) => {
      capTimer = setTimeout(
        () => resolve('capped'),
        DOCFLOW_OBSERVATION_TERMINAL_DRAIN_CAP_MS,
      );
    }),
  ]).catch(() => 'drained' as const);
  if (capTimer) clearTimeout(capTimer);
  if (capped === 'capped') {
    emitWorkerLog(
      `[warn] docflow observation drain hit the ${DOCFLOW_OBSERVATION_TERMINAL_DRAIN_CAP_MS}ms terminal cap with ${pendingDocflowObservationPosts.size}/${pendingCount} posts still in flight; the worker-side retry fold covers the stragglers`,
      options,
    );
  }
}

function emitWorkerLog(line: string, options?: ExecutePlayRunnerOptions): void {
  emitRunnerEvent(
    {
      type: 'log',
      at: new Date().toISOString(),
      source: 'worker',
      line,
    },
    options,
  );
}

function emitSystemLog(line: string, options?: ExecutePlayRunnerOptions): void {
  emitRunnerEvent(
    {
      type: 'log',
      at: new Date().toISOString(),
      source: 'system',
      line,
    },
    options,
  );
}

export function playRunnerContextCachePolicy(
  context: PlayRunnerExecutionConfig['context'],
): ContextOptions['cachePolicy'] | undefined {
  if (context.forceToolRefresh) {
    return {
      ...(context.force ? { forceStepRefresh: true } : {}),
      forceToolRefresh: true,
      forceFailedToolRefresh: true,
    };
  }
  if (context.force) {
    return { forceStepRefresh: true, forceFailedToolRefresh: true };
  }
  return undefined;
}

export function playRunnerContextRuntimeSheetForce(
  context: PlayRunnerExecutionConfig['context'],
): boolean {
  return context.force === true || context.forceToolRefresh === true;
}

export function playRunnerInvocationFenceFlags(
  context: PlayRunnerExecutionConfig['context'],
): Pick<
  ContextOptions,
  'requestDurableInvocationFence' | 'durableInvocationFence'
> {
  return {
    requestDurableInvocationFence:
      context.requestDurableInvocationFence === true ||
      (Boolean(context.receiptGatewayBaseUrl?.trim()) &&
        context.baseUrl?.replace(/\/$/, '') ===
          context.receiptGatewayBaseUrl?.trim().replace(/\/$/, '')),
    durableInvocationFence: context.durableInvocationFence === true,
  };
}

export function playRunnerRuntimeReceiptsEnabled(
  context: PlayRunnerExecutionConfig['context'],
): boolean {
  return Boolean(
    context.orgId &&
    context.playName &&
    context.baseUrl &&
    context.executorToken &&
    context.baseUrl.trim(),
  );
}

/**
 * Runtime Sheets belong to an organization and Play, not to the human who
 * initiated the run. Triggered runs intentionally have no actor email.
 */
export function assertPlayRunnerRuntimeSheetPersistenceContext(
  context: PlayRunnerExecutionConfig['context'],
): asserts context is PlayRunnerExecutionConfig['context'] & {
  orgId: string;
  playName: string;
  baseUrl: string;
  executorToken: string;
} {
  const missing = [
    !context.orgId?.trim() ? 'organization id' : null,
    !context.playName?.trim() ? 'Play name' : null,
    !(context.runId?.trim() || context.workflowId?.trim()) ? 'run id' : null,
    !context.baseUrl?.trim() ? 'runtime API origin' : null,
    !context.executorToken?.trim() ? 'executor token' : null,
  ].filter((field): field is string => field !== null);
  if (missing.length > 0) {
    throw new Error(
      `Runtime Sheet persistence is required for ctx.dataset() and ctx.csv(); run launch is missing ${missing.join(', ')}.`,
    );
  }
}

/** Keep launch-scoped database authority in the runner that admitted it. */
export function createPlayRunnerRuntimeSheetDatasetPageReader(input: {
  context: PlayRunnerExecutionConfig['context'];
  preloadedDbSessions: PlayRunnerExecutionConfig['context']['preloadedDbSessions'];
  postgresSessionUnwrapKey: string | null;
  abortSignal: AbortSignal;
  scope: RuntimeSheetDatasetPageReaderScope;
}): RuntimeSheetDatasetPageReader {
  const { context, scope } = input;
  assertPlayRunnerRuntimeSheetPersistenceContext(context);
  const rootRunId = context.runId ?? context.workflowId;
  if (
    scope.orgId !== context.orgId ||
    scope.playName !== context.playName ||
    scope.runId !== rootRunId ||
    scope.executorToken !== context.executorToken
  ) {
    throw new Error(
      'Runtime Sheet reader scope does not match the run launch authority.',
    );
  }
  return createRuntimeSheetDatasetPageReader({
    context: {
      baseUrl: context.baseUrl,
      executorToken: scope.executorToken,
      orgId: scope.orgId,
      playName: scope.playName,
      runId: scope.runId,
      userEmail: context.userEmail,
      dbSessionStrategy: context.dbSessionStrategy,
      preloadedDbSessions: input.preloadedDbSessions,
      postgresSessionUnwrapKey: input.postgresSessionUnwrapKey,
      vercelProtectionBypassToken: context.vercelProtectionBypassToken,
      runtimeTestFaultHeader: context.runtimeTestFaultHeader ?? null,
      abortSignal: input.abortSignal,
    },
    tableNamespace: scope.tableNamespace,
    runId: scope.runId,
    rowMode: scope.rowMode,
  });
}

function collectReturnedDatasets(value: unknown): unknown[] {
  const datasets: unknown[] = [];
  const seen = new Set<unknown>();

  const visit = (entry: unknown) => {
    if (!entry || typeof entry !== 'object' || seen.has(entry)) {
      return;
    }
    seen.add(entry);
    if (isPlayDataset(entry)) {
      datasets.push(entry);
      return;
    }
    if (Array.isArray(entry)) {
      for (const item of entry) {
        visit(item);
      }
      return;
    }
    for (const child of Object.values(entry as Record<string, unknown>)) {
      visit(child);
    }
  };

  visit(value);
  return datasets;
}

// Absorb ENOBUFS / EPIPE on stdout — the parent reads stdout chunks anyway,
// and crashing the runner process on backpressure loses the entire run.
process.stdout.on('error', (err: NodeJS.ErrnoException) => {
  if (err.code === 'ENOBUFS' || err.code === 'EPIPE') return;
  throw err;
});

// Push-execution live progress channel. When the launch enables push execution
// (Daytona sandbox runner), progress events are PUSHED to the receipt gateway
// instead of polled out of a sidecar file by the worker. Set once in main().
let runnerProgressPusher: RunnerProgressPusher | null = null;

function emit(event: PlayRunnerEvent): void {
  emitProgressSidecarEvent(event);
  if (runnerProgressPusher && shouldEmitProgressSidecarEvent(event)) {
    runnerProgressPusher.enqueue(event);
  }
  if (!shouldEmitStdoutEvent(event)) {
    return;
  }
  try {
    process.stdout.write(`${JSON.stringify(event)}\n`);
  } catch (err: unknown) {
    const code = (err as NodeJS.ErrnoException).code;
    if (code === 'ENOBUFS' || code === 'EPIPE') return;
    throw err;
  }
}

const PROGRESS_SIDECAR_SEGMENT_BYTES = 256 * 1024;
let progressSidecarState: {
  basePath: string;
  segment: number;
  segmentBytes: number;
} | null = null;

function emitProgressSidecarEvent(event: PlayRunnerEvent): void {
  if (!shouldEmitProgressSidecarEvent(event)) {
    return;
  }
  const progressPath =
    process.env.DEEPLINE_PLAY_RUNNER_PROGRESS_EVENT_PATH?.trim();
  if (!progressPath) {
    return;
  }
  try {
    const line = `${JSON.stringify(event)}\n`;
    const lineBytes = Buffer.byteLength(line);
    if (
      !progressSidecarState ||
      progressSidecarState.basePath !== progressPath
    ) {
      progressSidecarState = {
        basePath: progressPath,
        segment: 0,
        segmentBytes: 0,
      };
      writeFileSync(progressPath, '0', 'utf-8');
    }
    if (
      progressSidecarState.segmentBytes > 0 &&
      progressSidecarState.segmentBytes + lineBytes >
        PROGRESS_SIDECAR_SEGMENT_BYTES
    ) {
      progressSidecarState.segment += 1;
      progressSidecarState.segmentBytes = 0;
      writeFileSync(
        progressPath,
        String(progressSidecarState.segment),
        'utf-8',
      );
    }
    const segmentPath = `${progressPath}.${String(
      progressSidecarState.segment,
    ).padStart(6, '0')}`;
    appendFileSync(segmentPath, line, 'utf-8');
    progressSidecarState.segmentBytes += lineBytes;
  } catch {
    // Best-effort live observability. The normal stdout result stream remains
    // authoritative, so a sidecar write failure must not fail the play.
  }
}

async function writeRunnerEventToStdout(
  event: PlayRunnerEvent | PlayRunnerTerminalTransportEvent,
): Promise<void> {
  await new Promise<void>((resolve, reject) => {
    process.stdout.write(`${JSON.stringify(event)}\n`, (error) => {
      if (error) {
        reject(error);
        return;
      }
      resolve();
    });
  });
}

function truncateUtf8Prefix(value: string, maxBytes: number): string {
  if (Buffer.byteLength(value, 'utf8') <= maxBytes) return value;
  const encoded = Buffer.from(value, 'utf8');
  for (let end = Math.min(encoded.length, maxBytes); end > 0; end -= 1) {
    const candidate = encoded.subarray(0, end).toString('utf8');
    if (Buffer.byteLength(candidate, 'utf8') <= maxBytes) return candidate;
  }
  return '';
}

/**
 * The Daytona crash pusher reads a bounded tail of merged stdout/stderr. Once
 * its authoritative `result` event is written, no runner-owned diagnostic may
 * push that event out of the tail. The normal progress pusher is stopped before
 * the result; this bounds only terminal-push retry diagnostics that follow it.
 */
function createPostTerminalDiagnosticWriter(): NonNullable<
  PushRunnerTerminalOptions['warn']
> {
  let remaining = RUNNER_POST_TERMINAL_DIAGNOSTIC_MAX_BYTES;
  return (message, detail) => {
    if (remaining <= 1) return;
    const prefix = `[play-runner.terminal-push] ${message} `;
    const prefixBytes = Buffer.byteLength(prefix, 'utf8');
    if (remaining <= prefixBytes + 1) return;
    const formatted = formatWithOptions(
      {
        breakLength: Infinity,
        colors: false,
        compact: true,
        depth: 4,
        maxArrayLength: 20,
        maxStringLength: 4_096,
      },
      detail,
    );
    const suffix = truncateUtf8Prefix(formatted, remaining - prefixBytes - 1);
    const line = `${prefix}${suffix}\n`;
    const bytes = Buffer.byteLength(line, 'utf8');
    if (bytes > remaining) return;
    remaining -= bytes;
    try {
      process.stderr.write(line);
    } catch (error: unknown) {
      const code = (error as NodeJS.ErrnoException).code;
      if (code !== 'ENOBUFS' && code !== 'EPIPE') throw error;
    }
  };
}

async function exitRunner(exitCode: number): Promise<never> {
  await Promise.race([
    Promise.resolve(),
    new Promise<void>((resolve) => setTimeout(resolve, 1_000)),
  ]);

  process.exit(exitCode);
}

async function emitAndExit(
  event: PlayRunnerEvent | PlayRunnerTerminalTransportEvent,
  exitCode: number,
): Promise<never> {
  await writeRunnerEventToStdout(event);
  return exitRunner(exitCode);
}

function parseCsvStream(
  source: NodeJS.ReadableStream,
): AsyncIterable<Record<string, unknown>> {
  // Every Play's CSV input passes through here, so this is where a customer
  // file's BOM and mis-decoded UTF-8 ("jÃ©rÃ´me", "o‚Äômalley") get fixed before
  // any row reaches a provider. See ../../plays/csv-text-repair.
  const parser = parse({
    ...csvInputTextOptions(),
    skip_empty_lines: true,
    trim: true,
  });
  // `Readable.pipe()` does not forward source errors to the destination. A
  // missing staged file therefore used to emit an unhandled `error` from
  // createReadStream and kill the Daytona process outside main().catch().
  // Route it through the parser's async iterator so normal runner failure
  // handling can push an actionable terminal instead.
  source.once('error', (error) => parser.destroy(error));
  return source.pipe(parser) as AsyncIterable<Record<string, unknown>>;
}

function createCsvSource(input: {
  path?: string;
  url?: string;
  contentBase64?: string;
}): ReplayableCsvSource {
  return {
    iterate: () => {
      if (input.contentBase64) {
        return parseCsvStream(
          Readable.from([Buffer.from(input.contentBase64, 'base64')]),
        );
      }
      if (input.url) {
        return {
          async *[Symbol.asyncIterator]() {
            const response = await fetch(input.url!);
            if (!response.ok || !response.body) {
              throw new Error(
                `CSV source URL failed with status ${response.status}.`,
              );
            }
            yield* parseCsvStream(
              Readable.fromWeb(
                response.body as Parameters<typeof Readable.fromWeb>[0],
              ),
            );
          },
        } as AsyncIterable<Record<string, unknown>>;
      }
      if (!input.path) throw new Error('CSV source path is required.');
      return parseCsvStream(createReadStream(input.path));
    },
  };
}

/**
 * Serialize a runner failure with the message guaranteed present. Bun can
 * surface `error.stack` without the leading "Error: <message>" line (seen on
 * governor guard errors thrown deep in async chains), and the run's terminal
 * error text is what users and the guard e2e assertions read — so never trust
 * the stack alone to carry the message.
 */
function formatRunnerFailure(error: unknown): string {
  if (!(error instanceof Error)) {
    return String(error);
  }
  const stack = error.stack ?? '';
  if (!error.message.trim()) {
    return stack || String(error);
  }
  if (stack.includes(error.message)) {
    return stack;
  }
  const headline = `${error.name || 'Error'}: ${error.message}`;
  if (!stack) {
    return headline;
  }
  const frames = stack.startsWith(`${error.name || 'Error'}\n`)
    ? stack.slice((error.name || 'Error').length + 1)
    : stack;
  return `${headline}\n${frames}`;
}

function ensureSourceMapSupport(): void {
  if (sourceMapSupportInstalled) {
    return;
  }
  installSourceMapSupport({
    environment: 'node',
    handleUncaughtExceptions: false,
    // A runner can execute many Play revisions. `source-map-support` otherwise
    // caches forever by virtual filename and can map a later revision through
    // an older artifact's map. Stack formatting is synchronous, so clearing
    // this internal cache between operations is concurrency-safe.
    emptyCacheBetweenOperations: true,
    retrieveFile(source) {
      return runtimeSourceFiles.get(source) ?? '';
    },
    retrieveSourceMap(source) {
      const map = runtimeSourceMaps.get(source);
      if (!map) {
        return null;
      }
      return {
        url: source,
        map,
      };
    },
  });
  sourceMapSupportInstalled = true;
}

function retainRuntimeArtifact(artifact: PlayBundleArtifact): () => void {
  const existing = runtimeArtifactReferences.get(artifact.virtualFilename);
  if (
    existing &&
    (existing.artifactHash !== artifact.artifactHash ||
      existing.sourceMapHash !== artifact.sourceMapHash)
  ) {
    throw new Error(
      `Concurrent Play artifacts cannot share virtual filename ${artifact.virtualFilename} with different contents.`,
    );
  }
  runtimeSourceFiles.set(artifact.virtualFilename, artifact.bundledCode);
  runtimeSourceMaps.set(artifact.virtualFilename, artifact.sourceMap);
  runtimeArtifactReferences.set(artifact.virtualFilename, {
    artifactHash: artifact.artifactHash,
    sourceMapHash: artifact.sourceMapHash,
    count: (existing?.count ?? 0) + 1,
  });

  let released = false;
  return () => {
    if (released) return;
    released = true;
    const current = runtimeArtifactReferences.get(artifact.virtualFilename);
    if (
      !current ||
      current.artifactHash !== artifact.artifactHash ||
      current.sourceMapHash !== artifact.sourceMapHash
    ) {
      return;
    }
    if (current.count > 1) {
      runtimeArtifactReferences.set(artifact.virtualFilename, {
        ...current,
        count: current.count - 1,
      });
      return;
    }
    runtimeArtifactReferences.delete(artifact.virtualFilename);
    runtimeSourceFiles.delete(artifact.virtualFilename);
    runtimeSourceMaps.delete(artifact.virtualFilename);
  };
}

async function executeRuntimePlayCode(input: {
  artifact: PlayBundleArtifact;
  ctx: ReturnType<typeof createPlayContext>;
  runtimeInput: PlayRunInputPayload;
  options?: ExecutePlayRunnerOptions;
}): Promise<unknown> {
  const compileStartedAt = Date.now();
  // Defense-in-depth at the load seam: this runner compiles play code with
  // Module._compile, which cannot resolve `cloudflare:workers` scheme imports.
  // If a historical or malformed bundle reaches here, fail loudly with a
  // directional artifact mismatch instead of the opaque scheme error thrown at
  // compile time.
  assertNodeRunnableArtifact({
    artifact: input.artifact,
    expectedKind: PLAY_ARTIFACT_KINDS.cjsNode20,
    context: `play-runner ${input.artifact.virtualFilename}`,
  });
  ensureSourceMapSupport();
  const releaseRuntimeArtifact = retainRuntimeArtifact(input.artifact);
  try {
    const runtimeModule = new moduleRuntime.Module(
      input.artifact.virtualFilename,
    );
    runtimeModule.filename = input.artifact.virtualFilename;
    runtimeModule.paths = moduleRuntime.Module._nodeModulePaths(process.cwd());
    // Bun's `Module` compatibility object does not install `module.require`.
    // Install a fresh package-only wrapper for both CommonJS entry points. Local
    // files belong in the bundle; resolving them from the host repo would cross
    // the artifact boundary, and sharing one function would leak mutations.
    const runtimeRequire = createPlayRuntimeRequire();
    runtimeModule.require = runtimeRequire;
    // Resolve free `console` references through a per-run context extension.
    // This keeps directive prologues and customer-declared top-level `console`
    // bindings intact, while avoiding a process-global console swap that could
    // mix concurrent Absurd claims.
    const compiled = compileFunction(
      input.artifact.bundledCode,
      ['exports', 'require', 'module', '__filename', '__dirname'],
      {
        filename: input.artifact.virtualFilename,
        contextExtensions: [
          { console: createCapturedCustomerConsole(input.ctx) },
        ],
      },
    );
    compiled.call(
      runtimeModule.exports,
      runtimeModule.exports,
      runtimeRequire,
      runtimeModule,
      input.artifact.virtualFilename,
      dirname(input.artifact.virtualFilename),
    );
    emitWorkerLog(
      `[perf] artifact compile elapsed_ms=${Date.now() - compileStartedAt}`,
      input.options,
    );

    const candidate =
      typeof runtimeModule.exports === 'function'
        ? runtimeModule.exports
        : (runtimeModule.exports as { default?: unknown }).default;

    if (typeof candidate !== 'function') {
      throw new Error(
        'Bundled play module must default export an async function.',
      );
    }

    const userFunctionStartedAt = Date.now();
    const result = await (
      candidate as (
        ctx: unknown,
        runtimeInput: PlayRunInputPayload,
      ) => Promise<unknown>
    )(input.ctx, input.runtimeInput);
    // A Play may catch an individual tool failure, but a runner-owned fatal
    // tool failure still cannot settle as a normal result. Today this covers
    // Deepline's own insufficient-credit denial and a Slack HITL deadline
    // whose Slack-card replacement was confirmed. Provider capacity remains a
    // normal typed waterfall miss.
    input.ctx.assertNoRunFatalToolFailure();
    emitWorkerLog(
      `[perf] user function returned elapsed_ms=${Date.now() - userFunctionStartedAt}`,
      input.options,
    );
    return result;
  } catch (error) {
    // Error.stack is lazy in V8. Materialize it while this artifact's source
    // map is still registered; the mapped string remains on the Error after
    // the in-memory artifact is released and crosses the runner boundary.
    if (error instanceof Error) void error.stack;
    throw error;
  } finally {
    releaseRuntimeArtifact();
  }
}

const CAPTURED_CONSOLE_MAX_CHARS = 2_000;
const CAPTURED_CONSOLE_PREFIX_RESERVE_CHARS = 64;
const CAPTURED_CONSOLE_SHORTENED_MARKER =
  '… [log shortened; save complete values in a dataset and use runs export]';
const CAPTURED_CONSOLE_MAX_MESSAGE_CHARS =
  CAPTURED_CONSOLE_MAX_CHARS - CAPTURED_CONSOLE_PREFIX_RESERVE_CHARS;
const CAPTURED_CONSOLE_FORMAT_TRUNCATION =
  /(\.\.\.|…)\s*\d+\s+more\s+(?:characters?|items?)/i;

function logLevelForCapturedConsoleMethod(
  method: string,
): 'debug' | 'info' | 'warn' | 'error' {
  if (method === 'debug' || method === 'trace') return 'debug';
  if (method === 'warn') return 'warn';
  if (method === 'error' || method === 'assert') return 'error';
  return 'info';
}

function createCapturedCustomerConsole(
  ctx: ReturnType<typeof createPlayContext>,
): Console {
  const counters = new Map<string, number>();
  const timers = new Map<string, number>();
  const capture =
    (method: string) =>
    (...args: unknown[]) => {
      assertNoSecretTaint(args, `console.${method}`);
      const formatted = formatWithOptions(
        {
          breakLength: Infinity,
          colors: false,
          compact: true,
          depth: 4,
          maxArrayLength: 20,
          maxStringLength: CAPTURED_CONSOLE_MAX_MESSAGE_CHARS,
        },
        ...args,
      );
      const shortened =
        formatted.length > CAPTURED_CONSOLE_MAX_MESSAGE_CHARS ||
        CAPTURED_CONSOLE_FORMAT_TRUNCATION.test(formatted);
      const message = shortened
        ? `${formatted.slice(
            0,
            CAPTURED_CONSOLE_MAX_MESSAGE_CHARS -
              CAPTURED_CONSOLE_SHORTENED_MARKER.length,
          )}${CAPTURED_CONSOLE_SHORTENED_MARKER}`
        : formatted;
      ctx.log(`[console.${method}] ${message}`, {
        level: logLevelForCapturedConsoleMethod(method),
      });
    };

  const captured = {
    assert(condition?: boolean, ...args: unknown[]) {
      if (!condition) {
        capture('assert')('Assertion failed', ...args);
      }
    },
    clear() {},
    count(label = 'default') {
      const next = (counters.get(label) ?? 0) + 1;
      counters.set(label, next);
      capture('count')(`${label}: ${next}`);
    },
    countReset(label = 'default') {
      counters.delete(label);
    },
    debug: capture('debug'),
    dir: capture('dir'),
    dirxml: capture('dirxml'),
    error: capture('error'),
    group: capture('group'),
    groupCollapsed: capture('groupCollapsed'),
    groupEnd() {},
    info: capture('info'),
    log: capture('log'),
    profile() {},
    profileEnd() {},
    table: capture('table'),
    time(label = 'default') {
      timers.set(label, Date.now());
    },
    timeEnd(label = 'default') {
      const startedAt = timers.get(label);
      timers.delete(label);
      capture('timeEnd')(
        `${label}: ${startedAt === undefined ? 0 : Date.now() - startedAt}ms`,
      );
    },
    timeLog(label = 'default', ...args: unknown[]) {
      const startedAt = timers.get(label);
      capture('timeLog')(
        `${label}: ${startedAt === undefined ? 0 : Date.now() - startedAt}ms`,
        ...args,
      );
    },
    timeStamp() {},
    trace: capture('trace'),
    warn: capture('warn'),
  };

  // Deliberately use no Console prototype. Any method inherited from Node's
  // process-global console can write to shared stdout/stderr, bypassing both
  // the run log and secret-taint validation.
  return Object.assign(Object.create(null), captured) as Console;
}

/**
 * Release attempt-scoped leases when a run settles. Terminal runs no longer own
 * rows, so their sheet fences must not delay an immediate repair run. A
 * suspension keeps its sheet fences because the same run will resume.
 */
async function releaseRuntimeLeasesOnAppRunnerSettlement(input: {
  config: PlayRunnerExecutionConfig;
  runtimeSheetAttempts: Map<
    string,
    {
      attemptId: string;
      attemptOwnerRunId: string;
      attemptExpiresAt: string;
      attemptSeq: number;
      writeVersion?: number;
    }
  >;
  runnerRunAttempt: number;
  preloadedDbSessions: PlayRunnerExecutionConfig['context']['preloadedDbSessions'];
  postgresSessionUnwrapKey: string | null;
  emitWorkerLog: (message: string) => void;
  reason: 'completed' | 'suspension' | 'run-fatal';
}): Promise<void> {
  const { config } = input;
  const reasonLabel =
    input.reason === 'completed'
      ? 'completed settlement'
      : `${input.reason} teardown`;
  const orgId = config.context.orgId;
  const playName = config.context.playName;
  const runId =
    config.context.runId ?? config.context.workflowId ?? 'anonymous-run';
  if (!orgId || !playName) return;
  const runtimeContext = {
    executorToken: config.context.executorToken,
    baseUrl: config.context.baseUrl,
    ...playRunnerInvocationFenceFlags(config.context),
    runtimeTestFaultHeader: config.context.runtimeTestFaultHeader ?? null,
    vercelProtectionBypassToken: config.context.vercelProtectionBypassToken,
    orgId,
    playName,
    runId,
    userEmail: config.context.userEmail,
    dbSessionStrategy: config.context.dbSessionStrategy,
    preloadedDbSessions: input.preloadedDbSessions,
    postgresSessionUnwrapKey: input.postgresSessionUnwrapKey ?? undefined,
  };
  // Runtime Sheet rows use schedule-time write versions. They have no lease
  // to heartbeat or release; late writers are rejected by the write fence.
  void input.runtimeSheetAttempts;
  try {
    const released = await releaseRuntimeWorkReceipts(runtimeContext, {
      playName,
      runId,
      runAttempt: input.runnerRunAttempt,
    });
    if (released.released > 0) {
      input.emitWorkerLog(
        `[info] released ${released.released} completed-work lease(s) on ${reasonLabel}`,
      );
    }
  } catch (releaseError) {
    input.emitWorkerLog(
      `[warn] completed-work lease release failed on ${reasonLabel} (rerun falls back to lease-TTL expiry): ${
        releaseError instanceof Error
          ? releaseError.message
          : String(releaseError)
      }`,
    );
  }
}

function terminalLogIdsWithPhaseSummary(ctx: {
  getLogIds(): string[];
}): string[] {
  // Summaries are new occurrences at result construction. Terminal retries
  // reuse that result and its IDs, including the frozen summary bodies.
  return [...ctx.getLogIds(), crypto.randomUUID(), crypto.randomUUID()];
}

function terminalLogsWithPhaseSummary(ctx: {
  getLogs(): string[];
  getRuntimeResourceSnapshot(): unknown;
  getLogDiagnostics(): unknown;
}): string[] {
  return [
    ...ctx.getLogs(),
    `[runtime.logs] ${JSON.stringify(ctx.getLogDiagnostics())}`,
    `[runtime.phase_summary] ${JSON.stringify(ctx.getRuntimeResourceSnapshot())}`,
  ];
}

function terminalLogMetadataWithPhaseSummary(ctx: {
  getLogMetadata(): Array<PlayLogMetadata | null>;
}): Array<PlayLogMetadata | null> | undefined {
  const metadata = ctx.getLogMetadata();
  return metadata.some(Boolean) ? [...metadata, null, null] : undefined;
}

function terminalLogContextsWithPhaseSummary(ctx: {
  getLogContexts(): Array<PlayLogContext | null>;
}): Array<PlayLogContext | null> | undefined {
  const contexts = ctx.getLogContexts();
  return contexts.some(Boolean) ? [...contexts, null, null] : undefined;
}

function rowOutcomesFromCheckpoint(checkpoint: {
  mapFrames?: Record<
    string,
    {
      completedRowsCount?: number;
      completedRowKeys?: string[];
      failedRowsCount?: number;
      failureCounts?: RowFailureCounts;
      totalRows?: number;
      supersededRows?: number;
    }
  >;
}): {
  completedRows: number;
  failedRows: number;
  totalRows: number;
  supersededRows?: number;
  failureCounts: RowFailureCounts;
} | null {
  const frames = Object.values(checkpoint.mapFrames ?? {});
  if (frames.length === 0) return null;
  let completedRows = 0;
  let failedRows = 0;
  let totalRows = 0;
  let supersededRows = 0;
  const failureCounts = emptyRowFailureCounts();
  for (const frame of frames) {
    const completed = Number.isFinite(frame.completedRowsCount)
      ? Math.max(0, Math.floor(frame.completedRowsCount ?? 0))
      : Math.max(0, frame.completedRowKeys?.length ?? 0);
    const failed = Number.isFinite(frame.failedRowsCount)
      ? Math.max(0, Math.floor(frame.failedRowsCount ?? 0))
      : 0;
    const superseded = Number.isFinite(frame.supersededRows)
      ? Math.max(0, Math.floor(frame.supersededRows ?? 0))
      : 0;
    completedRows += completed;
    failedRows += failed;
    const frameCounts = readRowFailureCounts(frame.failureCounts, failed);
    for (const key of Object.keys(failureCounts) as Array<
      keyof RowFailureCounts
    >)
      failureCounts[key] += frameCounts[key];
    supersededRows += superseded;
    totalRows +=
      Number.isFinite(frame.totalRows) && (frame.totalRows ?? 0) >= 0
        ? Math.floor(frame.totalRows ?? 0)
        : completed + failed + superseded;
  }
  return {
    completedRows,
    failedRows,
    totalRows,
    supersededRows,
    failureCounts,
  };
}

async function run(
  config: PlayRunnerExecutionConfig,
  options?: ExecutePlayRunnerOptions,
): Promise<PlayRunnerResult> {
  config = hydratePlayRunnerConfig(config);
  const runStartedAt = Date.now();
  const runnerRunAttempt =
    typeof config.context.runAttempt === 'number' &&
    Number.isFinite(config.context.runAttempt)
      ? Math.max(0, Math.floor(config.context.runAttempt))
      : 0;
  const workCounterInvocationSeq = nextWorkCounterInvocationSeq(
    config.checkpoint,
    runnerRunAttempt,
  );
  const workCounterSegmentId = randomUUID();
  const runtimeLimitMs =
    validatePlaySandboxRuntimeLimits(
      config.context.sandboxRuntimeLimits ??
        STANDARD_PLAY_SANDBOX_RUNTIME_LIMITS,
    ).timeoutSeconds * 1_000;
  const persistenceSignal =
    options?.signal ?? AbortSignal.timeout(runtimeLimitMs);
  const executionDrainAtMs =
    options?.executionDrainAtMs ?? runStartedAt + runtimeLimitMs;
  const contextSetupStartedAt = Date.now();
  const getRuntimeToolMetadata = createRuntimeToolMetadataResolver(config);
  const getRuntimeToolAuthScopeDigest =
    createAppRuntimeToolAuthScopeDigestResolver(config);
  let totalRows = 0;
  let inserted = 0;
  let skipped = 0;
  const runtimePreloadedDbSessions = config.context.preloadedDbSessions;
  const runtimePostgresSessionUnwrapKey =
    // Preloaded sessions are sealed with the immutable submit-time token, which
    // may differ from the per-attempt `executorToken` durable schedulers
    // re-mint. Prefer the pinned unwrap key; fall back for legacy launches.
    config.context.postgresSessionUnwrapKey ??
    config.context.executorToken ??
    process.env.DEEPLINE_INTERNAL_TOKEN ??
    null;
  const runtimeCsvDatasets = new Map<
    string,
    {
      tableNamespace: string;
      dataset: PlayDataset<Record<string, unknown>>;
      sheetContract: PlaySheetContract;
      sourceLabel: string;
    }
  >();
  const appRuntimeApiContext = {
    baseUrl: config.context.baseUrl ?? '',
    executorToken: config.context.executorToken ?? '',
    vercelProtectionBypassToken: config.context.vercelProtectionBypassToken,
    runtimeTestFaultHeader: config.context.runtimeTestFaultHeader ?? null,
    connectionRetryBudgetMs: RUNNER_GATEWAY_CONNECTION_RETRY_BUDGET_MS,
  };
  const receiptGatewayResponseObserver = createReceiptGatewayResponseObserver();
  const receiptGatewayBaseUrl = config.context.receiptGatewayBaseUrl?.trim();
  // Receipt state has exactly two backends: handlers provided by the host
  // process (inline executor) or the co-located receipt gateway named by the
  // launch context. There is deliberately no fallback onto the app runtime
  // API and no env-var switch here.
  const runtimeReceiptApiContext = receiptGatewayBaseUrl
    ? {
        ...appRuntimeApiContext,
        baseUrl: receiptGatewayBaseUrl,
        boundary: 'receipt_gateway' as const,
        requestTimeoutMs: RUNTIME_RECEIPT_GATEWAY_REQUEST_TIMEOUT_MS,
        onResponseMeta: receiptGatewayResponseObserver.onResponseMeta,
      }
    : null;
  const canUseRuntimeStepReceipts = playRunnerRuntimeReceiptsEnabled(
    config.context,
  );
  const receiptStoreAdapter =
    runtimeReceiptApiContext &&
    canUseRuntimeStepReceipts &&
    config.context.playName &&
    config.context.orgId
      ? new RuntimeReceiptStoreAdapter({
          context: runtimeReceiptApiContext,
          playName: config.context.playName,
          runId:
            config.context.runId ??
            config.context.workflowId ??
            'anonymous-run',
          ...playRunnerReceiptStoreAdapterOptions(),
          onRetryTelemetry: (line) => emitSystemLog(line, options),
        })
      : null;
  const receiptGatewayHandlers: RuntimeStepReceiptHandlers | null =
    receiptStoreAdapter?.handlers ?? null;
  if (canUseRuntimeStepReceipts && !receiptGatewayHandlers) {
    throw new Error(
      'Play runner has no receipt backend: the launch context must carry ' +
        'receiptGatewayBaseUrl. Runtime receipts have exactly one path — ' +
        'the receipt gateway — never the app runtime API.',
    );
  }
  const receiptHandlers = receiptGatewayHandlers;
  emitWorkerLog(
    `[perf] runtime state=${
      receiptGatewayHandlers ? 'durable' : 'disabled'
    } db_session_strategy=${config.context.dbSessionStrategy ?? 'unset'} preloaded_db_sessions=${runtimePreloadedDbSessions?.length ?? 0}`,
    options,
  );
  const runtimeSheetAttempts = new Map<
    string,
    {
      attemptId: string;
      attemptOwnerRunId: string;
      attemptExpiresAt: string;
      attemptSeq: number;
      writeVersion?: number;
    }
  >();
  const membershipCapturingMaps = new Set<string>();
  const runtimeMapDatasetSettlements = new Map<
    string,
    {
      datasetId: string;
      path: string;
      tableNamespace: string;
      runId: string;
      persistedRows: number;
      succeededRows: number;
      failedRows: number;
    }
  >();
  const runtimeSheetAttemptKey = (input: {
    playName: string;
    runId: string;
    tableNamespace: string;
  }) => `${input.playName}\u0000${input.runId}\u0000${input.tableNamespace}`;
  const cachePolicy = playRunnerContextCachePolicy(config.context);
  const rateStateBackend = createRateStateBackendForConfig(config);
  const runtimeInput = config.input ?? {};
  const runtimeInputObject: Record<string, unknown> =
    playRunInputObjectView(runtimeInput);
  const importedArtifactOptions = (playRef: string) =>
    config.artifact.importedPlayArtifacts &&
    Object.hasOwn(config.artifact.importedPlayArtifacts, playRef)
      ? { resolveImportedArtifact: true as const }
      : {};
  const resolveChildPlay =
    createRunScopedChildPlayResolver<ResolvedPlayExecution>({
      resolvePlay: async (playRef) => {
        if (!config.context.orgId) {
          return null;
        }
        // Child plays always resolve through the server's CJS-only path.
        try {
          const resolved = await resolveRuntimeReferencedPlay(
            {
              executorToken: config.context.executorToken,
              baseUrl: config.context.baseUrl,
              vercelProtectionBypassToken:
                config.context.vercelProtectionBypassToken,
              playName: config.context.playName,
              userEmail: config.context.userEmail,
            },
            playRef,
            importedArtifactOptions(playRef),
          );
          if (resolved?.resolutionDiagnostics) {
            emitWorkerLog(
              `[runtime.resolve-play-contract] ${JSON.stringify({
                playRef,
                ...resolved.resolutionDiagnostics,
                runnerPipeline: Boolean(resolved.staticPipeline),
              })}`,
              options,
            );
          }
          return resolved as ResolvedPlayExecution | null;
        } catch (error) {
          const message =
            error instanceof Error ? error.message : String(error);
          throw new Error(
            `ctx.runPlay failed to resolve child play "${playRef}" via runtime API baseUrl=${config.context.baseUrl ?? '<missing>'}: ${message}`,
          );
        }
      },
    });
  const maxConcurrentExternalCalls = resolveMaxConcurrentExternalCalls(
    config.context.maxConcurrentExternalCalls,
  );
  const maxConcurrentRows = resolveMaxConcurrentRows(
    config.context.maxConcurrentRows,
  );
  emitWorkerLog(
    `[runtime.resource-policy] max_concurrent_external_calls=${maxConcurrentExternalCalls} max_concurrent_rows=${maxConcurrentRows ?? 'map_default'}`,
    options,
  );
  const artifactCompatibility = normalizePlayContractCompatibility(
    config.artifact.compatibility,
  );
  const artifactRuntimeContract = resolvePlayArtifactRuntimeContract({
    authoringContractEdition: artifactCompatibility.authoringContractEdition,
    slackHitlTimeoutOutcome: artifactCompatibility.slackHitlTimeoutOutcome,
    datasetRowInput: artifactCompatibility.datasetRowInput,
    toolResponseContract: config.context.toolResponseContract,
    toolResponseReceiptRevision: config.context.toolResponseReceiptRevision,
  });
  const arrayInputRuntimeContext = (scope: {
    playName: string;
    runId: string;
  }) => ({
    baseUrl: receiptGatewayBaseUrl || config.context.baseUrl,
    executorToken: config.context.executorToken,
    // Input snapshots must cross the gateway's current-attempt fence, even
    // when ordinary row persistence can use a preloaded tenant session.
    dbSessionStrategy: 'gateway_only' as const,
    preloadedDbSessions: runtimePreloadedDbSessions,
    postgresSessionUnwrapKey: runtimePostgresSessionUnwrapKey,
    abortSignal: persistenceSignal,
    playName: scope.playName,
    runId: scope.runId,
    orgId: config.context.orgId,
    userEmail: config.context.userEmail,
    vercelProtectionBypassToken: config.context.vercelProtectionBypassToken,
  });
  const ctx = createPlayContext({
    artifactRuntimeContract,
    rowAdmissionSignal: options?.rowAdmissionSignal,
    executionSignal: persistenceSignal,
    executionDrainAtMs,
    executorToken: config.context.executorToken,
    baseUrl: config.context.baseUrl,
    // Runtime control stays on baseUrl (the receipt gateway); provider calls
    // alone use this separate relay origin.
    executionGatewayBaseUrl: config.context.executionGatewayBaseUrl,
    ...playRunnerInvocationFenceFlags(config.context),
    runtimeTestFaultHeader: config.context.runtimeTestFaultHeader ?? null,
    integrationMode: config.context.integrationMode,
    docflowEnabled: config.context.docflowEnabled === true,
    fixtureBehavior: config.context.fixtureBehavior,
    maxConcurrentExternalCalls,
    maxConcurrentRows,
    verifyDurableInvocationFence: async (signal) => {
      const gatewayBaseUrl =
        config.context.executionGatewayBaseUrl?.trim().replace(/\/$/, '') ||
        config.context.receiptGatewayBaseUrl?.trim().replace(/\/$/, '') ||
        '';
      const hasExplicitFence =
        config.context.requestDurableInvocationFence === true;
      if (
        !gatewayBaseUrl ||
        (!hasExplicitFence &&
          config.context.baseUrl?.replace(/\/$/, '') !== gatewayBaseUrl)
      ) {
        return false;
      }
      try {
        const timeoutSignal = AbortSignal.timeout(
          RUNNER_RUNTIME_CONTROL_REQUEST_TIMEOUT_MS,
        );
        const response = await safeNodeOutboundFetch(
          `${gatewayBaseUrl}/healthz`,
          {
            redirect: 'manual',
            signal: signal
              ? AbortSignal.any([signal, timeoutSignal])
              : timeoutSignal,
          },
        );
        return (
          response.ok &&
          response.headers.get(DURABLE_INVOCATION_FENCE_ATTESTATION_HEADER) ===
            DURABLE_INVOCATION_FENCE_ATTESTATION_VALUE
        );
      } catch {
        return false;
      }
    },
    dbSessionStrategy: config.context.dbSessionStrategy,
    createRuntimeSheetDatasetPageReader: (scope) =>
      createPlayRunnerRuntimeSheetDatasetPageReader({
        context: config.context,
        preloadedDbSessions: runtimePreloadedDbSessions,
        postgresSessionUnwrapKey: runtimePostgresSessionUnwrapKey,
        abortSignal: persistenceSignal,
        scope,
      }),
    fetchImpl: safeNodeStreamingOutboundFetch,
    vercelProtectionBypassToken: config.context.vercelProtectionBypassToken,
    orgId: config.context.orgId,
    userEmail: config.context.userEmail,
    runActor: config.context.runActor
      ? Object.freeze({ ...config.context.runActor })
      : null,
    playName: config.context.playName,
    graphHash: config.artifact.graphHash,
    artifactHash: config.artifact.artifactHash,
    convexUrl: config.context.convexUrl,
    runtimeSchedulerSchema: config.context.runtimeSchedulerSchema ?? null,
    runtimeSheetBackedMapDatasets: true,
    runtimeArrayInputStagingEnabled: true,
    runtimeArrayInputStore: {
      getManifest: (scope) =>
        retryRuntimeSheetPersistence({
          description: `runtime array input getManifest table=${scope.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            getRuntimeArrayInputManifest(
              arrayInputRuntimeContext(scope),
              scope,
            ),
        }),
      begin: (input) =>
        retryRuntimeSheetPersistence({
          description: `runtime array input begin table=${input.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            beginRuntimeArrayInput(arrayInputRuntimeContext(input), input),
        }),
      putPage: (input) =>
        retryRuntimeSheetPersistence({
          description: `runtime array input putPage table=${input.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            putRuntimeArrayInputPage(arrayInputRuntimeContext(input), input),
        }),
      seal: (input) =>
        retryRuntimeSheetPersistence({
          description: `runtime array input seal table=${input.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            sealRuntimeArrayInput(arrayInputRuntimeContext(input), input),
        }),
      readPage: (input) =>
        retryRuntimeSheetPersistence({
          description: `runtime array input readPage table=${input.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            readRuntimeArrayInputPage(arrayInputRuntimeContext(input), input),
        }),
    },
    runtimeReceiptClaimsEstablishExecutionFence:
      receiptStoreAdapter?.claimsEstablishExecutionFence === true,
    workflowId: config.context.workflowId,
    playId: config.context.playId ?? config.context.workflowId,
    runId: config.context.runId ?? config.context.workflowId,
    rootRunId:
      config.context.rootRunId ??
      config.context.runId ??
      config.context.workflowId,
    runAttempt: runnerRunAttempt,
    staticPipeline: config.context.staticPipeline,
    checkpoint: config.checkpoint ?? undefined,
    durableBoundaries: true,
    governance: config.context.governance ?? undefined,
    ...rateStateBackend,
    ...(cachePolicy ? { cachePolicy } : {}),
    ...(receiptHandlers ?? {}),
    resolvePlay: resolveChildPlay,
    launchPlayAsync: async (request) =>
      await launchPlayAsyncViaAppRuntime(
        {
          ...appRuntimeApiContext,
          requestTimeoutMs: RUNNER_RUNTIME_CONTROL_REQUEST_TIMEOUT_MS,
        },
        { ...request, ...importedArtifactOptions(request.playRef) },
      ),
    onBatchComplete: (checkpoint) => {
      emitRunnerEvent(
        {
          type: 'checkpoint',
          checkpoint,
        },
        options,
      );
    },
    ...createRuntimeToolHooks({
      getRuntimeToolMetadata,
      createEventWaitHandler: (toolId) =>
        createRuntimeEventWaitHandler(config, toolId),
    }),
    getToolAuthScopeDigest: getRuntimeToolAuthScopeDigest,
    getToolAsyncExecutionRecovery:
      getRuntimeToolAuthScopeDigest.asyncExecutionRecovery,
    getToolRateScope: getRuntimeToolAuthScopeDigest.rateScope,
    invalidateToolAuthScopeDigest: (toolId) =>
      getRuntimeToolAuthScopeDigest.invalidate?.(toolId),
    onRowUpdate: (() => {
      let rowUpdateCount = 0;
      let lastEmitAt = 0;
      const ROW_UPDATE_EMIT_INTERVAL_MS = 200;
      const ROW_UPDATE_EMIT_SAMPLE_RATE = 100;
      const terminalCellStates = new Set([
        'completed',
        'failed',
        'cached',
        'missed',
        'skipped',
      ]);
      return (update: PlayRowUpdate) => {
        rowUpdateCount++;
        const now = Date.now();
        const hasTerminalCellUpdate = Object.values(
          update.cellMetaPatch ?? {},
        ).some((cell) => terminalCellStates.has(cell.status));
        const isTerminalUpdate =
          update.status === 'completed' ||
          update.status === 'failed' ||
          hasTerminalCellUpdate;
        if (
          isTerminalUpdate ||
          rowUpdateCount === 1 ||
          rowUpdateCount % ROW_UPDATE_EMIT_SAMPLE_RATE === 0 ||
          now - lastEmitAt >= ROW_UPDATE_EMIT_INTERVAL_MS
        ) {
          lastEmitAt = now;
          emitRunnerEvent({ type: 'row_update', update }, options);
        }
      };
    })(),
    onExecutionEvent: (() => {
      // map.row.updated fires for every cell-state change of every row (~7x
      // per row in a multi-column map) with no terminal semantics — unsampled
      // it floods the event transport at 150k-row scale. Sample it like row
      // updates; every other event type passes through untouched.
      let mapRowUpdatedCount = 0;
      let lastMapRowUpdatedEmitAt = 0;
      const MAP_ROW_UPDATED_EMIT_INTERVAL_MS = 200;
      const MAP_ROW_UPDATED_EMIT_SAMPLE_RATE = 100;
      return (event: PlayExecutionEvent) => {
        if (event.type === 'map.suspended') {
          const datasetId = createRuntimeDatasetId(
            config.context.playName!,
            event.artifactTableNamespace,
          );
          const settlement = runtimeMapDatasetSettlements.get(datasetId);
          if (settlement) {
            // This event follows the map writer's durability barrier. Only
            // report accepted writes, not progress (which includes duplicates).
            emitRunnerEvent(
              {
                type: 'execution_event',
                event: {
                  type: RUN_EVENT_KIND.datasetLifecycle,
                  datasetId,
                  path: settlement.path,
                  tableNamespace: settlement.tableNamespace,
                  phase: 'registered',
                  persistedRows: settlement.persistedRows,
                  succeededRows: settlement.succeededRows,
                  failedRows: settlement.failedRows,
                  complete: false,
                  at: event.at,
                },
              },
              options,
            );
          }
        }
        if (event.type === 'map.row.updated') {
          mapRowUpdatedCount++;
          const now = Date.now();
          if (
            mapRowUpdatedCount !== 1 &&
            mapRowUpdatedCount % MAP_ROW_UPDATED_EMIT_SAMPLE_RATE !== 0 &&
            now - lastMapRowUpdatedEmitAt < MAP_ROW_UPDATED_EMIT_INTERVAL_MS
          ) {
            return;
          }
          lastMapRowUpdatedEmitAt = now;
        }
        emitRunnerEvent(
          {
            type: 'execution_event',
            event,
          },
          options,
        );
      };
    })(),
    // Durable docflow observation sink (ADR 0016 rule 2). Present only when the
    // co-located receipt gateway is wired (same durable path as receipts) and
    // the play carries an org/play scope. The compiler injects the observation
    // wrapper ONLY into instrumented (diagrammed) plays, so an undiagrammed play
    // never invokes this sink — the gating is at the wrapper. Fire-and-forget:
    // any transport failure is swallowed-and-logged so the play body is never
    // affected. The live docflow.node.* event stream is unchanged.
    onDocflowObservation:
      runtimeReceiptApiContext && config.context.playName
        ? (observation) => {
            // Tracked so the graceful terminal path can drain in-flight posts
            // (bounded) before the terminal wakes the parked worker's finalize
            // read. Still strictly fire-and-forget from the play body.
            const post = observeDocflowNodeViaAppRuntime(
              runtimeReceiptApiContext,
              {
                playName: config.context.playName!,
                runId:
                  observation.runId ||
                  config.context.runId ||
                  config.context.workflowId ||
                  'anonymous-run',
                nodeId: observation.nodeId,
                attempt: observation.attempt,
                invocationSeq: observation.invocationSeq,
                invocationId: observation.invocationId ?? null,
                status: observation.status,
                inputs: observation.inputs ?? null,
                outputs: observation.outputs ?? null,
                inputsTruncated: observation.inputsTruncated === true,
                outputsTruncated: observation.outputsTruncated === true,
                error: observation.error ?? null,
                at: observation.at,
              },
            ).catch((error) => {
              emitWorkerLog(
                `[error] docflow observation write failed node=${observation.nodeId} status=${observation.status}: ${
                  error instanceof Error ? error.message : String(error)
                }`,
                options,
              );
            });
            pendingDocflowObservationPosts.add(post);
            void post.finally(() => {
              pendingDocflowObservationPosts.delete(post);
            });
          }
        : undefined,
    onLog: (line, context, entryId, metadata) => {
      const timestampMatch = line.match(/^\[([^\]]+)\]/);
      const timestamp = timestampMatch?.[1];
      const at =
        timestamp && !Number.isNaN(new Date(timestamp).getTime())
          ? new Date(timestamp).toISOString()
          : new Date().toISOString();
      emitRunnerEvent(
        {
          type: 'log',
          at,
          source: 'play',
          line,
          ...(config.context.runtimeLogIdentity === 'origin' && entryId
            ? { entryId }
            : {}),
          ...(context ? { context } : {}),
          ...(metadata ? { metadata } : {}),
        },
        options,
      );
    },
    onMapStartPages: async function* (items, tableNamespace, mapContext) {
      assertPlayRunnerRuntimeSheetPersistenceContext(config.context);
      const { baseUrl, orgId } = config.context;
      const startedAt = Date.now();
      totalRows += items.length;
      const userEmail = config.context.userEmail;
      const playName = mapContext.playName ?? config.context.playName;
      const runId =
        mapContext.runId ??
        config.context.runId ??
        config.context.workflowId ??
        'anonymous-run';
      const executorToken =
        mapContext.executorToken ?? config.context.executorToken;
      const rootRunId =
        config.context.runId ?? config.context.workflowId ?? 'anonymous-run';
      const canUseRootPreloadedDbSessions =
        executorToken === config.context.executorToken && runId === rootRunId;

      const sheetContract = resolveSheetContractForTableNamespace(
        mapContext.staticPipeline ?? config.context.staticPipeline,
        tableNamespace,
      );
      if (!sheetContract) {
        throw new Error(
          `Missing sheet contract for play "${playName}" and table namespace "${tableNamespace}".`,
        );
      }
      const attemptKey = runtimeSheetAttemptKey({
        playName,
        runId,
        tableNamespace,
      });
      // The admission owner durably pins one write intent per run/table, also
      // after a scheduler wake recreates this Map. Retain the local version as
      // an additional consistency check across pages of this runner.
      const existingAttempt = runtimeSheetAttempts.get(attemptKey);
      const admissionPages = startRuntimeSheetDatasetPages(
        {
          executorToken,
          baseUrl,
          vercelProtectionBypassToken:
            config.context.vercelProtectionBypassToken,
          orgId,
          playName,
          runId,
          userEmail,
          dbSessionStrategy: config.context.dbSessionStrategy,
          preloadedDbSessions: canUseRootPreloadedDbSessions
            ? runtimePreloadedDbSessions
            : undefined,
          postgresSessionUnwrapKey: canUseRootPreloadedDbSessions
            ? runtimePostgresSessionUnwrapKey
            : executorToken,
          abortSignal: persistenceSignal,
        },
        {
          playName,
          tableNamespace,
          sheetContract: augmentSheetContractWithDatasetFields({
            contract: sheetContract,
            rows: items,
            columnTypes: mapContext.columnTypes,
          }),
          rows: items,
          stableWriteIntent: true,
          pendingRerunAdmission: true,
          includePreviousCells: mapContext.includePreviousCells,
          previousCellsBudgetBytes: mapContext.previousCellsBudgetBytes,
          inputOffset: mapContext.inputOffset,
          mode: mapContext.mode,
          runId,
          attemptId: deterministicRuntimeSheetAttemptId({
            playName,
            runId,
            tableNamespace,
            attemptSeq: runnerRunAttempt,
          }),
          attemptOwnerRunId: runId,
          attemptSeq: runnerRunAttempt,
          ...runtimeSheetStartWriteVersion(existingAttempt),
          ...(playRunnerContextRuntimeSheetForce(config.context)
            ? { force: true }
            : {}),
        },
        {
          runPage: (run) =>
            retryRuntimeSheetPersistence({
              description: `runtime map start table=${tableNamespace}`,
              log: (line) => emitWorkerLog(line, options),
              signal: persistenceSignal,
              run,
            }),
        },
      );
      let registered = false;
      for await (const mapStartResult of admissionPages) {
        if (mapStartResult.membershipCapture === true)
          membershipCapturingMaps.add(attemptKey);
        if (!registered) {
          registered = true;
          const datasetId = createRuntimeDatasetId(playName, tableNamespace);
          const datasetPath = `datasets.${tableNamespace}`;
          const settlement = runtimeMapDatasetSettlements.get(datasetId) ?? {
            datasetId,
            path: datasetPath,
            tableNamespace,
            runId,
            persistedRows: 0,
            succeededRows: 0,
            failedRows: 0,
          };
          // `completedRows` is the sheet admission result, not a terminal write
          // for this run. Normal maps still execute every admitted row (the tool
          // receipt may be reused inside that execution), and their terminal
          // callback below is the authoritative settlement. Counting these rows
          // here as well would report N rows at map start and another N rows at
          // terminal persistence, advertising 2N rows for an N-row Dataset Handle.
          // `net_new` maps exclude these rows before execution, so they must not
          // be counted here either.
          runtimeMapDatasetSettlements.set(datasetId, settlement);
          emitRunnerEvent(
            {
              type: 'execution_event',
              event: {
                type: RUN_EVENT_KIND.datasetLifecycle,
                datasetId,
                path: datasetPath,
                tableNamespace,
                phase: 'registered',
                persistedRows: 0,
                succeededRows: 0,
                failedRows: 0,
                complete: false,
                // ADR 0019 dataset-grain row birth. These rows entered from
                // play-body code, so the only witnessed fact is how many arrived at
                // this table — never a per-row source mapping, which the runtime
                // does not see here. `rowCountIn` counts rows admitted through this
                // boundary so far, so a paged dataset converges upward instead of
                // reporting only its last page.
                bornFrom: {
                  table: tableNamespace,
                  rowCountIn: (mapContext.inputOffset ?? 0) + items.length,
                },
                at: Date.now(),
              },
            },
            options,
          );
          emitRunnerEvent(
            {
              type: 'log',
              at: new Date().toISOString(),
              source: 'play',
              line: formatDatasetRegistrationLog({
                dataset: { path: datasetPath, tableNamespace },
                rows: items.length,
              }),
            },
            options,
          );
        }
        if (
          mapStartResult.attemptId &&
          mapStartResult.attemptOwnerRunId &&
          mapStartResult.attemptExpiresAt
        ) {
          runtimeSheetAttempts.set(
            attemptKey,
            runtimeSheetAttemptForMapStart({
              tableNamespace,
              runId,
              existing: runtimeSheetAttempts.get(attemptKey),
              mapStartResult: {
                attemptId: mapStartResult.attemptId,
                attemptOwnerRunId: mapStartResult.attemptOwnerRunId,
                attemptExpiresAt: mapStartResult.attemptExpiresAt,
                attemptSeq: mapStartResult.attemptSeq,
                writeVersion: mapStartResult.writeVersion,
              },
              runnerRunAttempt,
            }),
          );
        }
        inserted += mapStartResult.inserted;
        skipped += mapStartResult.skipped;
        yield mapStartResult;
      }
      emitWorkerLog(
        `[perf] runtime map setup table=${tableNamespace} rows=${items.length} elapsed_ms=${Date.now() - startedAt}`,
        options,
      );
    },
    onMapRowsCheckpoint: async (input) => {
      if (input.updates.length === 0) return;
      assertPlayRunnerRuntimeSheetPersistenceContext(config.context);
      const playName = input.playName ?? config.context.playName;
      const userEmail = config.context.userEmail;
      const { runId, tableNamespace, updates } = input;
      const baseUrl = config.context.baseUrl;
      const executorToken = input.executorToken ?? config.context.executorToken;
      if (!baseUrl || !executorToken) {
        throw new Error(
          `Runtime map checkpoint for "${playName}" requires the runtime API origin and executor token.`,
        );
      }
      const sheetContract = resolveSheetContractForTableNamespace(
        input.staticPipeline ?? config.context.staticPipeline,
        tableNamespace,
      );
      if (!sheetContract) {
        throw new Error(
          `Missing sheet contract for play "${playName}" and table namespace "${tableNamespace}" while checkpointing partial rows.`,
        );
      }
      const attempt = runtimeSheetAttempts.get(
        runtimeSheetAttemptKey({
          playName,
          runId,
          tableNamespace,
        }),
      );
      const checkpointUpdates = updates.map((update) => ({
        ...update,
        attemptId: attempt?.attemptId ?? null,
        attemptOwnerRunId: attempt?.attemptOwnerRunId ?? null,
        attemptExpiresAt: attempt?.attemptExpiresAt ?? null,
        attemptSeq: attempt?.attemptSeq ?? runnerRunAttempt,
        writeVersion: attempt?.writeVersion ?? null,
      }));
      await retryRuntimeSheetPersistence({
        description: `runtime map checkpoint table=${tableNamespace}`,
        log: (line) => emitWorkerLog(line, options),
        signal: persistenceSignal,
        run: () =>
          applyRowUpdatesViaAppRuntime(
            {
              baseUrl,
              executorToken,
              vercelProtectionBypassToken:
                config.context.vercelProtectionBypassToken,
              signal: persistenceSignal,
              connectionRetryBudgetMs:
                RUNNER_GATEWAY_CONNECTION_RETRY_BUDGET_MS,
            },
            {
              playName,
              tableNamespace,
              sheetContract,
              contractSnapshot: {
                staticPipeline:
                  input.staticPipeline ?? config.context.staticPipeline ?? null,
              },
              runId,
              userEmail,
              updates: checkpointUpdates,
            },
          ),
      });
    },
    onMapRowsSettled: async (input) => {
      const playName = input.playName ?? config.context.playName!;
      const runId =
        input.runId ??
        config.context.runId ??
        config.context.workflowId ??
        'anonymous-run';
      const mapKey = runtimeSheetAttemptKey({
        playName,
        runId,
        tableNamespace: input.tableNamespace,
      });
      if (
        membershipCapturingMaps.has(mapKey) &&
        input.expectedRows !== undefined
      ) {
        const sheetContract = resolveSheetContractForTableNamespace(
          input.staticPipeline ?? config.context.staticPipeline,
          input.tableNamespace,
        );
        if (!sheetContract)
          throw new Error(
            `Missing sheet contract while finishing membership for ${input.tableNamespace}.`,
          );
        const canUseRoot =
          runId === (config.context.runId ?? config.context.workflowId);
        await retryRuntimeSheetPersistence({
          description: `runtime membership finish table=${input.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            finishRuntimeSheetRunMembership(
              {
                executorToken: config.context.executorToken,
                baseUrl: config.context.baseUrl!,
                orgId: config.context.orgId!,
                playName,
                runId,
                userEmail: config.context.userEmail,
                vercelProtectionBypassToken:
                  config.context.vercelProtectionBypassToken,
                dbSessionStrategy: config.context.dbSessionStrategy,
                preloadedDbSessions: canUseRoot
                  ? runtimePreloadedDbSessions
                  : undefined,
                postgresSessionUnwrapKey: canUseRoot
                  ? runtimePostgresSessionUnwrapKey
                  : config.context.executorToken,
                abortSignal: persistenceSignal,
              },
              {
                runId,
                tableNamespace: input.tableNamespace,
                sheetContract,
                expectedRows: input.expectedRows!,
              },
            ),
        });
      }
      const datasetId = createRuntimeDatasetId(playName, input.tableNamespace);
      const settlement = runtimeMapDatasetSettlements.get(datasetId);
      if (settlement && (!input.runId || settlement.runId === input.runId)) {
        Object.assign(
          settlement,
          runtimeSheetTerminalMapCounts(settlement, input),
        );
      }
    },
    onMapRowsCompleted: async (input) => {
      // Persist executed rows (data + cell meta) into the tenant sheet —
      // the sheet is the source of truth for dataset state, and the
      // deterministic row keys make this write idempotent across retries
      // and reruns. An actor email is optional attribution, never durability
      // authority for a scheduler-backed Play run.
      assertPlayRunnerRuntimeSheetPersistenceContext(config.context);
      const playName = input.playName ?? config.context.playName;
      const runId =
        input.runId ??
        config.context.runId ??
        config.context.workflowId ??
        'anonymous-run';
      const executorToken = input.executorToken ?? config.context.executorToken;
      const rootRunId =
        config.context.runId ?? config.context.workflowId ?? 'anonymous-run';
      const canUseRootPreloadedDbSessions =
        executorToken === config.context.executorToken && runId === rootRunId;
      const sheetContract = resolveSheetContractForTableNamespace(
        input.staticPipeline ?? config.context.staticPipeline,
        input.tableNamespace,
      );
      if (!sheetContract) {
        throw new Error(
          `Missing sheet contract for play "${playName}" and table namespace "${input.tableNamespace}" while persisting executed rows.`,
        );
      }
      const persistStartedAt = Date.now();
      const attempt = runtimeSheetAttempts.get(
        runtimeSheetAttemptKey({
          playName,
          runId,
          tableNamespace: input.tableNamespace,
        }),
      );
      const runtimeSheetContext = {
        executorToken,
        baseUrl: config.context.baseUrl,
        vercelProtectionBypassToken: config.context.vercelProtectionBypassToken,
        orgId: config.context.orgId,
        playName,
        runId,
        userEmail: config.context.userEmail,
        dbSessionStrategy: config.context.dbSessionStrategy,
        runtimeTestFaultHeader: config.context.runtimeTestFaultHeader ?? null,
        preloadedDbSessions: canUseRootPreloadedDbSessions
          ? runtimePreloadedDbSessions
          : undefined,
        postgresSessionUnwrapKey: canUseRootPreloadedDbSessions
          ? runtimePostgresSessionUnwrapKey
          : executorToken,
        abortSignal: persistenceSignal,
      };
      const pageTailWriteMarker = runtimeSheetPageTailWriteMarkerEvent(
        config.context.runtimeTestFaultHeader,
        input.rows,
        input.tableNamespace,
        config.context.dbSessionStrategy,
      );
      if (pageTailWriteMarker) {
        // Authorized synthetic fault only. Source "play" is intentional: the
        // direct-worker reporter drops host diagnostics, while this one marker
        // is the durable proof that the page-tail terminal write was admitted.
        emitRunnerEvent(pageTailWriteMarker, options);
      }
      emitWorkerLog(
        `[perf] runtime map persist:start table=${input.tableNamespace} rows=${input.rows.length}`,
        options,
      );
      const completeRows = createCompleteRuntimeMapRowsOperation(
        runtimeSheetContext,
        {
          tableNamespace: input.tableNamespace,
          sheetContract,
          rows: input.rows,
          outputFields: input.outputFields,
          runId,
          attemptId: attempt?.attemptId ?? null,
          attemptOwnerRunId: attempt?.attemptOwnerRunId ?? null,
          attemptExpiresAt: attempt?.attemptExpiresAt ?? null,
          attemptSeq: attempt?.attemptSeq ?? runnerRunAttempt,
          writeVersion: attempt?.writeVersion ?? null,
        },
      );
      const result = await retryRuntimeSheetPersistence({
        description: `runtime map persist table=${input.tableNamespace}`,
        log: (line) => emitWorkerLog(line, options),
        signal: persistenceSignal,
        run: completeRows,
      });
      const pageTailHoldCompleted = runtimeSheetPageTailHoldCompletedEvent(
        result.runtimeTestPageTailHoldMs,
        input.tableNamespace,
      );
      if (pageTailHoldCompleted) {
        emitRunnerEvent(pageTailHoldCompleted, options);
      }
      emitWorkerLog(
        `[perf] runtime map persist:write_done table=${input.tableNamespace} rows=${input.rows.length} updated=${result.updated} elapsed_ms=${Date.now() - persistStartedAt}`,
        options,
      );
      const staleKeys = new Set(result.staleKeys);
      const staleDropped = staleKeys.size;
      let recoveredStaleKeys: string[] = [];
      if (staleDropped > 0) {
        // A terminal retry can lose the SQL mutation race to its own earlier
        // commit. The Context must not turn that already-durable row into an
        // empty successful dataset. Verify ownership through the runner's
        // preloaded session (never by minting a new database authority), then
        // return only the same-run terminal keys as idempotent settlements.
        const recovered = await retryRuntimeSheetPersistence({
          description: `runtime map stale settlement reconcile table=${input.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            readRuntimeSheetDatasetRowKeys(runtimeSheetContext, {
              tableNamespace: input.tableNamespace,
              runId,
              keys: [...staleKeys],
              rowMode: 'all',
            }),
        });
        recoveredStaleKeys = recovered.keys;
        for (const key of recoveredStaleKeys) staleKeys.delete(key);
      }
      if (staleDropped > 0) {
        emitWorkerLog(
          `[info] dropped ${staleKeys.size} stale runtime sheet write(s) for table=${input.tableNamespace}; ${recoveredStaleKeys.length} same-run terminal write(s) were accepted idempotently`,
          options,
        );
        const supersededRows = runtimeSheetTerminalWriteStaleRows({
          result,
          recoveredStaleKeys,
        });
        if (supersededRows.length > 0) {
          emitWorkerLog(
            `[info] ${supersededRows.length} Runtime Sheet row write(s) did not own the latest view; ` +
              `the existing latest-view values were preserved and this run will continue`,
            options,
          );
        }
      }
      const {
        persistedRows: committedTerminalRows,
        succeededRows,
        failedRows,
      } = runtimeSheetTerminalWriteCounts({
        rows: input.rows,
        committedKeys: result.committedKeys,
        recoveredStaleKeys,
      });
      const datasetPath = `datasets.${input.tableNamespace}`;
      const datasetId = createRuntimeDatasetId(playName, input.tableNamespace);
      const settlement = runtimeMapDatasetSettlements.get(datasetId) ?? {
        datasetId,
        path: datasetPath,
        tableNamespace: input.tableNamespace,
        runId,
        persistedRows: 0,
        succeededRows: 0,
        failedRows: 0,
      };
      // Rejected stale rows have no retained copy. Verified same-run terminal
      // replays count as accepted even when they performed no physical update.
      settlement.persistedRows += committedTerminalRows;
      settlement.succeededRows += succeededRows;
      settlement.failedRows += failedRows;
      runtimeMapDatasetSettlements.set(datasetId, settlement);
      emitWorkerLog(
        `[perf] runtime map persist table=${input.tableNamespace} rows=${input.rows.length} updated=${result.updated} accepted=${committedTerminalRows} stale=${staleKeys.size} elapsed_ms=${Date.now() - persistStartedAt}`,
        options,
      );
      return {
        updated: result.updated,
        staleDroppedKeys: [...staleKeys],
        ...(recoveredStaleKeys.length > 0 ? { recoveredStaleKeys } : {}),
      };
    },
  });
  receiptGatewayResponseObserver.attach(ctx);

  const csvSourceCache = new Map<string, ReplayableCsvSource>();
  const csvDatasetCache = new Map<
    string,
    import('../../plays/dataset').PlayDataset<Record<string, unknown>>
  >();
  const csvDatasetNamespaceByCacheKey = new Map<string, string>();
  const runtimeInputAlias = config.runtimeInputAlias ?? null;
  const csvSourcePath = config.csvSourcePath ?? null;
  const csvSourceUrl = config.csvSourceUrl ?? null;
  const csvSourceContentBase64 = config.csvSourceContentBase64 ?? null;

  (
    ctx as unknown as {
      csv: (
        requestedPath: string,
        options?: CsvRenameOptions,
      ) => Promise<
        import('../../plays/dataset').PlayDataset<Record<string, unknown>>
      >;
    }
  ).csv = async (requestedPath: string, csvOptions?: CsvRenameOptions) => {
    if (csvOptions) {
      for (const [field, value] of [
        ['ctx.csv.options.columns', csvOptions.columns],
        ['ctx.csv.options.rename', csvOptions.rename],
        ['ctx.csv.options.required', csvOptions.required],
      ] as const) {
        validateOptionalPlayAuthoringField(field, value);
      }
    }
    const resolvedRequestedPath =
      typeof requestedPath === 'string' && requestedPath.trim().length > 0
        ? requestedPath
        : runtimeInputAlias;

    if (!resolvedRequestedPath) {
      throw new Error(
        'ctx.csv(...) requires a path, or the play run must provide an input file.',
      );
    }

    const shouldUseInlineCsvSource =
      Boolean(csvSourceContentBase64) &&
      (!runtimeInputAlias || resolvedRequestedPath === runtimeInputAlias);
    const shouldUseCsvSourceUrl =
      Boolean(csvSourceUrl) &&
      (!runtimeInputAlias || resolvedRequestedPath === runtimeInputAlias);
    const targetPath = shouldUseInlineCsvSource
      ? `inline:${resolvedRequestedPath}`
      : shouldUseCsvSourceUrl
        ? csvSourceUrl!
        : (config.materializedFiles[resolvedRequestedPath] ??
          config.materializedFiles[
            resolvedRequestedPath.replace(/^\.\//, '')
          ] ??
          resolve(config.workspaceRoot, resolvedRequestedPath));

    if (
      !shouldUseInlineCsvSource &&
      !shouldUseCsvSourceUrl &&
      !targetPath.startsWith(config.workspaceRoot)
    ) {
      throw new Error(
        `ctx.csv("${resolvedRequestedPath}") resolved outside the packaged play workspace.`,
      );
    }

    if (!csvSourceCache.has(targetPath)) {
      try {
        csvSourceCache.set(
          targetPath,
          createCsvSource(
            shouldUseInlineCsvSource
              ? { contentBase64: csvSourceContentBase64! }
              : shouldUseCsvSourceUrl
                ? { url: targetPath }
                : { path: targetPath },
          ),
        );
      } catch {
        const knownFiles = Object.keys(config.materializedFiles)
          .filter((key) => !key.includes('/'))
          .sort()
          .join(', ');
        throw new Error(
          `ctx.csv("${resolvedRequestedPath}") could not be resolved in the packaged play workspace. ` +
            `Known packaged files: ${knownFiles || 'none'}.`,
        );
      }
    }

    const csvProjectionIdentity = `${JSON.stringify(csvOptions?.columns ?? {})}:${JSON.stringify(csvOptions?.rename ?? {})}:${JSON.stringify(csvOptions?.required ?? [])}`;
    const datasetCacheKey = `${resolvedRequestedPath}:${targetPath}:${csvProjectionIdentity}`;
    let tableNamespace = csvDatasetNamespaceByCacheKey.get(datasetCacheKey);
    if (!tableNamespace) {
      const baseTableNamespace = `${CSV_NAMESPACE_PREFIX}_${createHash('sha1').update(resolvedRequestedPath).digest('hex').slice(0, 12)}`;
      const baseAlreadyAssigned = [
        ...csvDatasetNamespaceByCacheKey.values(),
      ].some((assigned) => assigned === baseTableNamespace);
      tableNamespace = baseAlreadyAssigned
        ? `${baseTableNamespace}_${createHash('sha1').update(csvProjectionIdentity).digest('hex').slice(0, 12)}`
        : baseTableNamespace;
      csvDatasetNamespaceByCacheKey.set(datasetCacheKey, tableNamespace);
    }

    assertPlayRunnerRuntimeSheetPersistenceContext(config.context);

    assertPlayRunnerRuntimeSheetPersistenceContext(config.context);
    const cachedDataset = csvDatasetCache.get(datasetCacheKey);
    if (cachedDataset) {
      return cachedDataset;
    }

    const playName = config.context.playName;
    const dataset = await createStreamingCsvDataset({
      playName,
      tableNamespace,
      source: csvSourceCache.get(targetPath)!,
      sourceLabel: resolvedRequestedPath,
      options: csvOptions,
    });
    const sheetContract = inferCsvSheetContract({
      tableNamespace,
      rows: await dataset.peek(10),
    });
    runtimeCsvDatasets.set(dataset.datasetId, {
      tableNamespace,
      dataset,
      sheetContract,
      sourceLabel: resolvedRequestedPath,
    });
    csvDatasetCache.set(datasetCacheKey, dataset);
    return dataset;
  };
  emitWorkerLog(
    `[perf] context setup elapsed_ms=${Date.now() - contextSetupStartedAt}`,
    options,
  );
  for (const line of await collectStartupEgressProbeLines({
    enabled: process.env.DEEPLINE_RUNTIME_RECEIPT_TRACE === '1',
    // A local/direct executor can use baseUrl without a receipt gateway.
    // Probe only the explicit data-plane hop in explicit diagnostic mode.
    receiptGatewayBaseUrl: config.context.receiptGatewayBaseUrl ?? null,
    executionRelayBaseUrl: config.context.executionGatewayBaseUrl ?? null,
    executorToken: config.context.executorToken ?? null,
  })) {
    ctx.logRunnerDiagnostic(line);
  }
  const logRecovery = () => {
    const runId = config.context.runId ?? config.context.workflowId;
    for (const saved of [...runtimeMapDatasetSettlements.values()].slice(
      0,
      16,
    )) {
      ctx.logRunnerDiagnostic(
        formatDatasetAvailabilityLog({
          runId: saved.runId,
          dataset: saved,
          persistedRows: saved.persistedRows,
        }),
      );
    }
    if (runId) {
      ctx.logRunnerDiagnostic(
        `Run stopped before returning. Inspect saved datasets: deepline runs get ${runId}. Export saved data before rerunning unfinished work.`,
      );
    }
  };
  const runtimeStats = () => ({
    ...ctx.getStats(),
    runtimeWorkCounterSegment: {
      invocationSeq: workCounterInvocationSeq,
      segmentId: workCounterSegmentId,
    },
  });
  options?.onRuntimeReady?.({
    log: (line) => ctx.logRunnerDiagnostic(line),
    timeoutResult: (runtimeLimitSeconds) => {
      logRecovery();
      return {
        status: 'failed',
        error: runtimeLimitExceededCause(runtimeLimitSeconds),
        errors: [runtimeLimitExceededFailure(runtimeLimitSeconds)],
        logs: terminalLogsWithPhaseSummary(ctx),
        ...(config.context.runtimeLogIdentity === 'origin'
          ? { logIds: terminalLogIdsWithPhaseSummary(ctx) }
          : {}),
        logContexts: terminalLogContextsWithPhaseSummary(ctx),
        logMetadata: terminalLogMetadataWithPhaseSummary(ctx),
        stats: runtimeStats(),
        steps: ctx.getSteps(),
        tableNamespace: null,
        totalRows,
        inserted,
        skipped,
      };
    },
  });

  const playInput: PlayRunInputPayload =
    runtimeInputAlias && !Array.isArray(runtimeInput)
      ? {
          ...runtimeInputObject,
          file: runtimeInputAlias,
        }
      : runtimeInput;

  // Sample scalar counters, not the potentially large resource snapshot. The
  // reporter coalesces transport updates; this timer emits no event if no
  // counter changed and cannot hold the runner process open.
  let lastWorkCounterKey: string | null = null;
  const emitWorkCounters = () => {
    const counters = ctx.getRuntimeWorkCounters();
    const key = `${counters.logicalCalls}:${counters.providerRequests}:${counters.provider429s}`;
    if (key === lastWorkCounterKey) return;
    lastWorkCounterKey = key;
    emitRunnerEvent(
      {
        type: 'work_counters',
        attempt: runnerRunAttempt,
        invocationSeq: workCounterInvocationSeq,
        segmentId: workCounterSegmentId,
        ...counters,
      },
      options,
    );
  };
  emitWorkCounters();
  const workCounterTimer = setInterval(emitWorkCounters, 1_500);
  workCounterTimer.unref();

  try {
    emitWorkerLog('Play started', options);
    const rawResult = await executeRuntimePlayCode({
      artifact: config.artifact,
      ctx,
      runtimeInput: playInput,
      options,
    });
    ctx.assertRowAdmissionOpen();
    // A durable ctx boundary deliberately unwinds execution. Customer code can
    // catch that error, so the context keeps a sticky handoff that remains
    // authoritative until this invocation returns it to the scheduler.
    ctx.assertNoPendingDurableSuspension();
    emitWorkerLog(
      `[perf] play body returned elapsed_ms=${Date.now() - runStartedAt}`,
      options,
    );
    for (const settlement of runtimeMapDatasetSettlements.values()) {
      emitRunnerEvent(
        {
          type: 'execution_event',
          event: {
            type: RUN_EVENT_KIND.datasetLifecycle,
            datasetId: settlement.datasetId,
            path: settlement.path,
            tableNamespace: settlement.tableNamespace,
            phase: 'available',
            persistedRows: settlement.persistedRows,
            succeededRows: settlement.succeededRows,
            failedRows: settlement.failedRows,
            complete: true,
            at: Date.now(),
          },
        },
        options,
      );
      emitRunnerEvent(
        {
          type: 'log',
          at: new Date().toISOString(),
          source: 'play',
          line: formatDatasetAvailabilityLog({
            runId: settlement.runId,
            dataset: {
              path: settlement.path,
              tableNamespace: settlement.tableNamespace,
            },
            persistedRows: settlement.persistedRows,
          }),
        },
        options,
      );
    }
    await receiptStoreAdapter?.close();
    const result = normalizeTopLevelPlayReturn(rawResult);
    for (const returnedDataset of collectReturnedDatasets(result)) {
      if (!isPlayDataset<Record<string, unknown>>(returnedDataset)) {
        continue;
      }
      const csvDataset = runtimeCsvDatasets.get(returnedDataset.datasetId);
      if (!csvDataset) {
        continue;
      }
      const persistStartedAt = Date.now();
      const csvRunId =
        config.context.runId ?? config.context.workflowId ?? 'anonymous-run';
      const csvRuntimeContext = {
        executorToken: config.context.executorToken,
        baseUrl: config.context.baseUrl,
        vercelProtectionBypassToken: config.context.vercelProtectionBypassToken,
        orgId: config.context.orgId,
        playName: config.context.playName!,
        runId: csvRunId,
        userEmail: config.context.userEmail,
        dbSessionStrategy: config.context.dbSessionStrategy,
        preloadedDbSessions: runtimePreloadedDbSessions,
        postgresSessionUnwrapKey: runtimePostgresSessionUnwrapKey,
        abortSignal: persistenceSignal,
      };
      let csvRowsPersisted = 0;
      for await (const page of iteratePlayDatasetInputPages(
        csvDataset.dataset,
      )) {
        await retryRuntimeSheetPersistence({
          description: `runtime csv persist table=${csvDataset.tableNamespace}`,
          log: (line) => emitWorkerLog(line, options),
          signal: persistenceSignal,
          run: () =>
            startRuntimeSheetDataset(csvRuntimeContext, {
              playName: config.context.playName!,
              tableNamespace: csvDataset.tableNamespace,
              playInput: runtimeInputObject,
              sheetContract: csvDataset.sheetContract,
              rows: page.rows,
              runId: csvRunId,
              inputOffset: page.offset,
            }),
        });
        csvRowsPersisted += page.rows.length;
        page.rows.length = 0;
      }
      emitWorkerLog(
        `[perf] runtime csv persist table=${csvDataset.tableNamespace} rows=${csvRowsPersisted} elapsed_ms=${Date.now() - persistStartedAt}`,
        options,
      );
      const csvDatasetPath = `datasets.${csvDataset.tableNamespace}`;
      emitRunnerEvent(
        {
          type: 'execution_event',
          event: {
            type: RUN_EVENT_KIND.datasetLifecycle,
            datasetId: createRuntimeDatasetId(
              config.context.playName!,
              csvDataset.tableNamespace,
            ),
            path: csvDatasetPath,
            tableNamespace: csvDataset.tableNamespace,
            phase: 'available',
            persistedRows: csvRowsPersisted,
            succeededRows: csvRowsPersisted,
            failedRows: 0,
            complete: true,
            at: Date.now(),
          },
        },
        options,
      );
      emitRunnerEvent(
        {
          type: 'log',
          at: new Date().toISOString(),
          source: 'play',
          line: formatDatasetAvailabilityLog({
            runId: csvRunId,
            dataset: {
              path: csvDatasetPath,
              tableNamespace: csvDataset.tableNamespace,
            },
            persistedRows: csvRowsPersisted,
          }),
        },
        options,
      );
    }
    emitWorkerLog(`Play finished in ${Date.now() - runStartedAt}ms`, options);
    const normalizeStartedAt = Date.now();
    const outputRows = normalizeOutputRows(result);
    const outputRowCount = deriveOutputRowCount(result, outputRows);
    emitWorkerLog(
      `[perf] output normalize rows=${outputRowCount} elapsed_ms=${Date.now() - normalizeStartedAt}`,
      options,
    );
    const serializeStartedAt = Date.now();
    const projectedResult = projectPlayResultForTransport(result);
    const compactedResult = projectedResult.output;
    const serializedResult = serializePlayResult(compactedResult);
    emitWorkerLog(
      `[perf] result serialize elapsed_ms=${Date.now() - serializeStartedAt}`,
      options,
    );
    if (!totalRows) {
      totalRows = outputRowCount;
    }
    const resultTableNamespace = extractResultTableNamespace(serializedResult);
    ctx.recordReturn(outputRowCount);

    await releaseRuntimeLeasesOnAppRunnerSettlement({
      config,
      runtimeSheetAttempts,
      runnerRunAttempt,
      preloadedDbSessions: runtimePreloadedDbSessions,
      postgresSessionUnwrapKey: runtimePostgresSessionUnwrapKey,
      emitWorkerLog: (message) => emitWorkerLog(message, options),
      reason: 'completed',
    });

    const logs = terminalLogsWithPhaseSummary(ctx);
    const runtimeDiagnostics = Array.from(
      new Map(
        logs
          .map((line) => parseCtxFetchHttpFailureDiagnostic(line))
          .filter((diagnostic): diagnostic is CtxFetchHttpFailureDiagnostic =>
            Boolean(diagnostic),
          )
          .map((diagnostic) => [
            `${diagnostic.key}\u0000${diagnostic.method}\u0000${diagnostic.url}\u0000${diagnostic.http_status}`,
            diagnostic,
          ]),
      ).values(),
    ).slice(0, 16);
    const checkpoint = ctx.getCheckpoint();
    const rowOutcomes = rowOutcomesFromCheckpoint(checkpoint);

    return {
      status: 'completed' as const,
      output: serializedResult,
      ...(projectedResult.warnings.length > 0
        ? { outputWarnings: projectedResult.warnings }
        : {}),
      outputRowCount,
      logs,
      ...(config.context.runtimeLogIdentity === 'origin'
        ? { logIds: terminalLogIdsWithPhaseSummary(ctx) }
        : {}),
      logContexts: terminalLogContextsWithPhaseSummary(ctx),
      logMetadata: terminalLogMetadataWithPhaseSummary(ctx),
      ...(runtimeDiagnostics.length > 0 ? { runtimeDiagnostics } : {}),
      ...(rowOutcomes ? { rowOutcomes } : {}),
      stats: runtimeStats(),
      steps: ctx.getSteps(),
      checkpoint,
      tableNamespace: resultTableNamespace,
      totalRows,
      inserted,
      skipped,
    };
  } catch (caughtError) {
    // `ctx.sleep()` deliberately unwinds with an exception. Customer code may
    // catch it and throw a different exception instead, but the invocation's
    // sticky handoff is still authoritative until this runner returns it to
    // the scheduler. Resolve that precedence before classifying the terminal
    // result so a replacement error cannot turn a suspended run into failed.
    let error: unknown = options?.rowAdmissionSignal?.aborted
      ? options.rowAdmissionSignal.reason
      : caughtError;
    try {
      if (!options?.rowAdmissionSignal?.aborted) {
        ctx.assertNoPendingDurableSuspension();
      }
    } catch (suspension) {
      error = suspension;
    }
    try {
      await receiptStoreAdapter?.close();
    } catch (closeError) {
      emitWorkerLog(
        `[warn] runtime receipt writer close failed during teardown: ${
          closeError instanceof Error ? closeError.message : String(closeError)
        }`,
        options,
      );
    }
    if (isPlayExecutionSuspendedError(error)) {
      // Suspension is a controlled handoff to the scheduler. Promise.all siblings may
      // still hold runtime receipt leases when the first branch suspends; release
      // this attempt's leases so the resumed task can reclaim and reconcile
      // already-terminal child work instead of waiting for stale running receipts.
      await releaseRuntimeLeasesOnAppRunnerSettlement({
        config,
        runtimeSheetAttempts,
        runnerRunAttempt,
        preloadedDbSessions: runtimePreloadedDbSessions,
        postgresSessionUnwrapKey: runtimePostgresSessionUnwrapKey,
        emitWorkerLog: (message) => emitWorkerLog(message, options),
        reason: 'suspension',
      });
      return {
        status: 'suspended',
        suspension: error.suspension,
        logs: terminalLogsWithPhaseSummary(ctx),
        ...(config.context.runtimeLogIdentity === 'origin'
          ? { logIds: terminalLogIdsWithPhaseSummary(ctx) }
          : {}),
        logContexts: terminalLogContextsWithPhaseSummary(ctx),
        logMetadata: terminalLogMetadataWithPhaseSummary(ctx),
        stats: runtimeStats(),
        steps: ctx.getSteps(),
        checkpoint: ctx.getCheckpoint(),
        tableNamespace: null,
        totalRows,
        inserted,
        skipped,
      };
    }

    // Controlled run-fatal teardown: release the runtime-sheet row leases and
    // work-receipt leases this attempt still holds so an immediate rerun is not
    // blocked for the full lease TTL. Best-effort but LOUD — a release failure
    // is logged and never masks the original run-fatal error. TTL expiry stays
    // the recovery path for true crashes where this teardown never runs.
    await releaseRuntimeLeasesOnAppRunnerSettlement({
      config,
      runtimeSheetAttempts,
      runnerRunAttempt,
      preloadedDbSessions: runtimePreloadedDbSessions,
      postgresSessionUnwrapKey: runtimePostgresSessionUnwrapKey,
      emitWorkerLog: (message) => emitWorkerLog(message, options),
      reason: 'run-fatal',
    });

    ensureSourceMapSupport();
    const failure = normalizePlayRunFailure(error);
    logRecovery();
    const checkpoint = ctx.getCheckpoint();
    const rowOutcomes = rowOutcomesFromCheckpoint(checkpoint);
    return {
      status: 'failed',
      error: formatRunnerFailure(error),
      errors: [failure],
      logs: terminalLogsWithPhaseSummary(ctx),
      ...(config.context.runtimeLogIdentity === 'origin'
        ? { logIds: terminalLogIdsWithPhaseSummary(ctx) }
        : {}),
      logContexts: terminalLogContextsWithPhaseSummary(ctx),
      logMetadata: terminalLogMetadataWithPhaseSummary(ctx),
      ...(rowOutcomes ? { rowOutcomes } : {}),
      stats: runtimeStats(),
      steps: ctx.getSteps(),
      checkpoint,
      tableNamespace: null,
      totalRows,
      inserted,
      skipped,
    };
  } finally {
    clearInterval(workCounterTimer);
    emitWorkCounters();
  }
}

export async function executePlayRunner(
  config: PlayRunnerExecutionConfig,
  options?: ExecutePlayRunnerOptions,
): Promise<PlayRunnerResult> {
  const emissionOptions: ExecutePlayRunnerOptions = {
    ...options,
    emitEvent: (event) =>
      emitRunnerEvent(
        config.context.runtimeLogIdentity === 'origin' &&
          event.type === 'log' &&
          !event.entryId
          ? { ...event, entryId: crypto.randomUUID() }
          : event,
        options,
      ),
  };
  const result = await run(config, emissionOptions);
  // Inline-executor mirror of the child terminal drain: the caller's finalize
  // reads the observations table right after this returns, so land in-flight
  // observation posts first (bounded, best-effort, docflow-gated by emptiness).
  await drainPendingDocflowObservationPosts(emissionOptions);
  return result;
}

function normalizeOutputRows(result: unknown): Record<string, unknown>[] {
  if (result && typeof result === 'object') {
    const record = result as Record<string, unknown>;
    if (isPlayDataset<Record<string, unknown>>(record.rows)) {
      return [];
    }
    if (isPlayDataset<Record<string, unknown>>(record.results)) {
      return [];
    }
    if (isPlayDataset<Record<string, unknown>>(record.leads)) {
      return [];
    }
    if (isPlayDataset<Record<string, unknown>>(record.contacts)) {
      return [];
    }
    if (Array.isArray(record.leads)) {
      return record.leads as Record<string, unknown>[];
    }
    if (Array.isArray(record.contacts)) {
      return record.contacts as Record<string, unknown>[];
    }
    if (Array.isArray(record.rows)) {
      return record.rows as Record<string, unknown>[];
    }
    if (Array.isArray(record.results)) {
      return record.results as Record<string, unknown>[];
    }
    return [record];
  }

  return [];
}

type PlayResultTransportProjection = {
  output: Record<string, unknown>;
  warnings: PlayRunOutputWarning[];
};

function normalizeTopLevelPlayReturn(value: unknown): Record<string, unknown> {
  if (value === null || value === undefined) {
    return {};
  }
  if (Array.isArray(value)) {
    return { rows: value };
  }
  if (isPlayDataset(value) || isSerializedPlayDataset(value)) {
    return { rows: value };
  }
  if (typeof value !== 'object') {
    return { value };
  }

  const record = { ...(value as Record<string, unknown>) };
  if (Object.prototype.hasOwnProperty.call(record, '_metadata')) {
    record.metadata = record._metadata;
    delete record._metadata;
  }
  return record;
}

export function compactPlayResultForTransport(value: unknown): unknown {
  return projectPlayResultForTransport(value).output;
}

export function projectPlayResultForTransport(
  value: unknown,
): PlayResultTransportProjection {
  const record = normalizeTopLevelPlayReturn(value);
  const output: Record<string, unknown> = {};

  for (const [key, entry] of Object.entries(record)) {
    if (isPlayDataset(entry)) {
      output[key] = entry.toJSON();
      continue;
    }
    if (isSerializedPlayDataset(entry)) {
      output[key] = entry;
      continue;
    }
    output[key] = entry;
  }

  const boundedOutput = truncateCustomerPlayReturnWithinLimit({
    value: output,
  });
  return {
    output: boundedOutput.value,
    warnings: boundedOutput.truncated
      ? [
          {
            code: 'RUN_OUTPUT_TRUNCATED',
            reason: 'byte_limit',
            message:
              'The Play return was truncated to fit the output limit. Return a Dataset Handle to keep a large result recoverable.',
            originalBytesAtLeast: boundedOutput.originalBytesAtLeast,
            retainedBytes: boundedOutput.retainedBytes,
            limitBytes: boundedOutput.limitBytes,
            retryable: false,
            recoverableFrom: 'none',
          },
        ]
      : [],
  };
}

function serializePlayResult<T>(value: T): T {
  return JSON.parse(JSON.stringify(value)) as T;
}

export function deriveOutputRowCount(
  result: unknown,
  normalizedRows: Record<string, unknown>[],
): number {
  if (result && typeof result === 'object' && !Array.isArray(result)) {
    const record = result as Record<string, unknown>;
    if (isPlayDataset(record.rows)) {
      return record.rows.toJSON().count;
    }
    if (isPlayDataset(record.results)) {
      return record.results.toJSON().count;
    }
    if (isPlayDataset(record.leads)) {
      return record.leads.toJSON().count;
    }
    if (isPlayDataset(record.contacts)) {
      return record.contacts.toJSON().count;
    }
    if (isSerializedPlayDataset(record.rows)) {
      return record.rows.count;
    }
    if (isSerializedPlayDataset(record.results)) {
      return record.results.count;
    }
    if (isSerializedPlayDataset(record.leads)) {
      return record.leads.count;
    }
    if (isSerializedPlayDataset(record.contacts)) {
      return record.contacts.count;
    }
  }
  return normalizedRows.length;
}

export function extractResultTableNamespace(result: unknown): string | null {
  if (result && typeof result === 'object' && !Array.isArray(result)) {
    const record = result as Record<string, unknown>;
    for (const candidate of [
      record.rows,
      record.results,
      record.leads,
      record.contacts,
    ]) {
      if (isPlayDataset(candidate)) {
        return candidate.toJSON().tableNamespace ?? null;
      }
    }
    for (const candidate of [
      record.rows,
      record.results,
      record.leads,
      record.contacts,
    ]) {
      if (isSerializedPlayDataset(candidate)) {
        return candidate.tableNamespace ?? null;
      }
    }
  }
  return null;
}

async function waitForConfigFile(configPath: string): Promise<void> {
  const startedAt = Date.now();
  for (;;) {
    try {
      await readFile(configPath);
      return;
    } catch (error) {
      const code = (error as { code?: unknown }).code;
      if (code !== 'ENOENT') {
        throw error;
      }
      if (Date.now() - startedAt > WAIT_CONFIG_TIMEOUT_MS) {
        throw new Error(
          `Timed out waiting for play runner config at ${configPath}.`,
        );
      }
      await new Promise((resolve) => setTimeout(resolve, WAIT_CONFIG_POLL_MS));
    }
  }
}

export async function materializeTransportedArtifact(
  config: PlayRunnerExecutionConfig,
): Promise<PlayRunnerExecutionConfig> {
  const bundledCodePath = config.artifactTransport?.bundledCodePath?.trim();
  if (!bundledCodePath) {
    if (!config.artifact.bundledCode) {
      throw new Error('Play runner config is missing artifact bundledCode.');
    }
    return config;
  }

  const artifactBuffer = await readFile(bundledCodePath);
  const bundledCode =
    config.artifactTransport?.bundledCodeEncoding === 'gzip'
      ? gunzipSync(artifactBuffer).toString('utf-8')
      : artifactBuffer.toString('utf-8');
  if (!bundledCode) {
    throw new Error(
      `Play runner artifact file ${bundledCodePath} did not contain bundledCode.`,
    );
  }
  const sourceMapPath = config.artifactTransport?.sourceMapPath?.trim();
  const sourceMap = sourceMapPath
    ? await readFile(sourceMapPath, 'utf-8')
    : config.artifact.sourceMap;

  return {
    ...config,
    artifact: {
      ...config.artifact,
      bundledCode,
      sourceMap,
    },
  };
}

async function main() {
  emitWorkerLog(
    `[perf] process main elapsed_ms=${Math.round(performance.now())}`,
  );
  const waitForConfig = process.argv[2] === '--wait-config';
  const configPath = waitForConfig ? process.argv[3] : process.argv[2];
  if (!configPath) {
    throw new Error(
      'Usage: node play-runner.cjs [--wait-config] <config.json|config.json.gz>',
    );
  }
  if (waitForConfig) {
    await waitForConfigFile(configPath);
  }
  const configLoadStartedAt = Date.now();
  const configBuffer = await readFile(configPath);
  const configJson = configPath.endsWith('.gz')
    ? gunzipSync(configBuffer).toString('utf-8')
    : configBuffer.toString('utf-8');
  const parsedConfig = JSON.parse(configJson) as PlayRunnerExecutionConfig;
  writeRunnerStartupDiagnostic(
    process.env.DEEPLINE_PLAY_RUNNER_STARTUP_DIAGNOSTIC_PATH,
    { phase: 'booted' },
  );
  emitWorkerLog(
    `[perf] config load elapsed_ms=${Date.now() - configLoadStartedAt}`,
  );

  // Set terminal push wiring before any startup work that can fail. A failed
  // artifact materialization can then report its terminal whenever the gateway
  // is reachable instead of relying only on the detached ceiling salvage.
  runnerTerminalPushContext = terminalPushContextFromConfig(parsedConfig);
  const executionController = new AbortController();
  const rowAdmissionController = new AbortController();
  let runtimeState:
    | Parameters<NonNullable<ExecutePlayRunnerOptions['onRuntimeReady']>>[0]
    | undefined;
  const heartbeat = startRunnerPushHeartbeatFromConfig(parsedConfig, () => {
    executionController.abort(
      new Error('Play runner stopped by the runtime heartbeat channel.'),
    );
  });
  try {
    const artifactMaterializeStartedAt = Date.now();
    const config = await materializeTransportedArtifactWhileRunnerParks(
      parsedConfig,
      heartbeat,
    );
    emitWorkerLog(
      `[perf] artifact materialize elapsed_ms=${Date.now() - artifactMaterializeStartedAt}`,
    );

    runnerProgressPusher = startRunnerProgressPusherFromConfig(config);
    const runtimeDeadline = startConfiguredPlayRunnerRuntimeDeadline({
      config,
      onDrain: (runtimeLimitSeconds) => {
        runtimeState?.log(
          `[runtime.log_transport] ${JSON.stringify(runnerProgressPusher?.snapshot() ?? null)}`,
        );
        runtimeState?.log(
          `Runtime limit approaching (${runtimeLimitSeconds}s configured); stopping new rows and saving started work for up to 4 seconds.`,
        );
        rowAdmissionController.abort(
          new Error(runtimeLimitExceededCause(runtimeLimitSeconds)),
        );
      },
      onDeadline: async (runtimeLimitSeconds) => {
        runtimeState?.log(
          `[runtime.log_transport] ${JSON.stringify(runnerProgressPusher?.snapshot() ?? null)}`,
        );
        executionController.abort(
          new Error(
            `Play runner reached its ${runtimeLimitSeconds}-second runtime limit.`,
          ),
        );
        heartbeat?.stop();
        await terminateRunnerForRuntimeDeadline(
          runtimeLimitSeconds,
          runtimeState?.timeoutResult(runtimeLimitSeconds),
        );
      },
      onError: (error) => {
        console.error('[play-runner.runtime-deadline] terminal_failed', {
          error: error instanceof Error ? error.message : String(error),
        });
        process.exit(1);
      },
    });
    // The Daytona watchdog is a separate process and can keep runner liveness
    // advancing while synchronous customer JavaScript occupies this process's
    // event loop. Hand off only after the existing durable `waiting` fence and
    // immediately before the marker that starts customer execution.
    const lastHeartbeatAtMs = heartbeat?.lastSuccessAtMs();
    heartbeat?.stop();
    writeRunnerRuntimeStartedMarker(
      process.env.DEEPLINE_PLAY_RUNNER_RUNTIME_STARTED_PATH,
      lastHeartbeatAtMs === undefined ? {} : { lastHeartbeatAtMs },
    );
    let result: PlayRunnerResult | null = null;
    let executionFailed = false;
    let executionError: unknown = undefined;
    try {
      result = await executePlayRunner(config, {
        signal: executionController.signal,
        rowAdmissionSignal: rowAdmissionController.signal,
        executionDrainAtMs: runtimeDeadline.drainAtMs,
        onRuntimeReady: (runtime) => {
          runtimeState = runtime;
        },
      });
    } catch (error) {
      executionFailed = true;
      executionError = error;
    }
    if (!runtimeDeadline.claimCompletion()) {
      await runtimeDeadline.deadlineSettled;
      throw new Error(
        'Runtime deadline handler returned without terminating the runner.',
      );
    }
    // claimCompletion() is the exact customer-execution boundary. Publish the
    // external fence immediately, before formatting failures or serializing the
    // terminal payload, so a run that finishes at the deadline receives the
    // terminal-settlement grace instead of being reclassified as a timeout.
    const workCompletedAtMs = Date.now();
    writeRunnerRuntimeCompletedMarker(
      process.env.DEEPLINE_PLAY_RUNNER_RUNTIME_COMPLETED_PATH,
      { at: workCompletedAtMs },
    );
    if (executionFailed) {
      ensureSourceMapSupport();
      const message = formatRunnerFailure(executionError);
      result = {
        status: 'failed',
        error: message,
        errors: [normalizePlayRunFailure(executionError)],
        logs: [],
        stats: {},
        steps: [],
        tableNamespace: null,
      };
    }
    if (!result) {
      throw new Error('Play runner completed without a result.');
    }
    (
      result as PlayRunnerResult & { workCompletedAtMs?: number }
    ).workCompletedAtMs = workCompletedAtMs;
    if (runnerTerminalPushContext?.sandboxProvider) {
      result.stats = {
        ...result.stats,
        sandboxProvider: runnerTerminalPushContext.sandboxProvider,
      };
    }
    const terminalResult = runnerTerminalPushContext
      ? runnerTerminalResultForTransport(result)
      : null;
    heartbeat?.stop();
    // Ordering guarantee for the durable trace (ADR 0016): the pushed terminal
    // wakes the parked worker whose finalize reads the observations table, so
    // in-flight observation posts must land first. Bounded — never fails or
    // delays the terminal beyond the cap; no-op for undiagrammed plays.
    // Runner progress joins the same terminal handoff immediately below.
    await drainPendingDocflowObservationPosts();
    const terminalHandoff = terminalResult
      ? runnerTerminalHandoffForTransport(terminalResult, runnerProgressPusher)
      : null;
    if (terminalHandoff) runnerProgressPusher = null;
    if (terminalHandoff) {
      // Persist the exact terminal line locally before any network settlement.
      // If the gateway remains unavailable through the grace period, the shell
      // epilogue can still salvage this authored result instead of inventing a
      // runtime-limit failure after customer code already finished.
      await writeRunnerEventToStdout(terminalHandoff.event);
    }
    // Push execution (B2-final): the pushed terminal is what WAKES the parked
    // worker attempt. Push before exiting; on exhaustion the captured output
    // file remains the ceiling-timeout salvage source.
    if (runnerTerminalPushContext && terminalHandoff) {
      // Every terminal boundary can wake a successor attempt. Transfer all
      // unacknowledged observations into that same ordered handoff before the
      // wake is visible; draining a suspended/failed attempt afterward lets
      // the successor claim the log channel and fence its predecessor's tail.
      await pushRunnerTerminalIfConfigured(terminalHandoff.event.result, {
        warn: createPostTerminalDiagnosticWriter(),
        finalProgressLogOffset: terminalHandoff.progress?.liveLogOffset ?? 0,
        finalProgressEvents: terminalHandoff.progress?.events,
      });
      return exitRunner(0);
    }
    await runnerProgressPusher?.stop();
    runnerProgressPusher = null;
    // The parent process owns play status from the structured result event.
    // Keep the process exit clean so remote command transports do not drop the
    // final JSON line on non-zero exits.
    await emitAndExit(
      {
        type: 'result',
        result,
      },
      0,
    );
  } finally {
    heartbeat?.stop();
    const pusher = runnerProgressPusher;
    runnerProgressPusher = null;
    await pusher?.stop().catch(() => undefined);
  }
}

export async function waitForRunnerExecutionAcknowledgement(
  heartbeat: ReturnType<typeof startRunnerPushHeartbeatFromConfig>,
  timeoutMs = RUNNER_EXECUTION_ACK_TIMEOUT_MS,
): Promise<void> {
  if (!heartbeat) return;
  heartbeat.requestHeartbeat();
  let timeout: ReturnType<typeof setTimeout> | undefined;
  try {
    await Promise.race([
      heartbeat.executionAcknowledged,
      new Promise<never>((_resolve, reject) => {
        timeout = setTimeout(
          () =>
            reject(
              new Error(
                `RUNTIME_SANDBOX_START_FAILED: scheduler did not acknowledge the detached runner park within ${Math.max(1, timeoutMs)}ms. Customer play code was not started.`,
              ),
            ),
          Math.max(1, timeoutMs),
        );
      }),
    ]);
  } finally {
    if (timeout) clearTimeout(timeout);
  }
}

/**
 * Begins local artifact readback as soon as the runner has parsed its config,
 * while preserving the durable runner-park fence before customer code receives
 * that artifact. The artifact contains source text only; materializing it does
 * not evaluate user code or make any runtime-state transition.
 *
 * Keep a handled materialization result while waiting for the acknowledgement:
 * a failed read must still wait for the initial heartbeat so the configured
 * terminal push can report the authored failure through the normal path.
 */
export async function materializeTransportedArtifactWhileRunnerParks(
  parsedConfig: PlayRunnerExecutionConfig,
  heartbeat: ReturnType<typeof startRunnerPushHeartbeatFromConfig>,
  materialize: (
    config: PlayRunnerExecutionConfig,
  ) => Promise<PlayRunnerExecutionConfig> = materializeTransportedArtifact,
): Promise<PlayRunnerExecutionConfig> {
  const materialization = materialize(parsedConfig).then(
    (config) => ({ ok: true as const, config }),
    (error) => ({ ok: false as const, error }),
  );

  // The first gateway heartbeat is the durable readiness fence. The worker
  // observes that same Postgres fact directly. It still gates every call to
  // executePlayRunner; only file I/O overlaps the handoff.
  await heartbeat?.firstHeartbeat;
  await waitForRunnerExecutionAcknowledgement(heartbeat);

  const outcome = await materialization;
  if ('config' in outcome) {
    return outcome.config;
  }
  throw outcome.error;
}

export function writeRunnerRuntimeStartedMarker(
  path: string | null | undefined,
  detail: { pid?: number; at?: number; lastHeartbeatAtMs?: number } = {},
): void {
  const runtimeStartedPath = path?.trim();
  if (!runtimeStartedPath) return;
  writeFileSync(
    runtimeStartedPath,
    JSON.stringify({
      started: true,
      pid: detail.pid ?? process.pid,
      at: detail.at ?? Date.now(),
      ...(typeof detail.lastHeartbeatAtMs === 'number'
        ? { lastHeartbeatAtMs: detail.lastHeartbeatAtMs }
        : {}),
    }),
    'utf-8',
  );
}

export function writeRunnerRuntimeCompletedMarker(
  path: string | null | undefined,
  detail: { pid?: number; at?: number } = {},
): void {
  const runtimeCompletedPath = path?.trim();
  if (!runtimeCompletedPath) return;
  writeFileSync(
    runtimeCompletedPath,
    JSON.stringify({
      completed: true,
      pid: detail.pid ?? process.pid,
      at: detail.at ?? Date.now(),
    }),
    'utf-8',
  );
}

/**
 * A tiny, strictly non-secret handoff record for detached Daytona startup.
 * The worker reads it only when the scheduler did not see the first heartbeat;
 * stdout is deliberately not inspected because it may contain customer data.
 */
export function writeRunnerStartupDiagnostic(
  path: string | null | undefined,
  detail:
    | { phase: 'booted' }
    | { phase: 'heartbeat_transport'; event: RunnerGatewayTransportEvent },
): void {
  const diagnosticPath = path?.trim();
  if (!diagnosticPath) return;
  try {
    writeFileSync(
      diagnosticPath,
      JSON.stringify({ schemaVersion: 1, at: Date.now(), ...detail }),
      'utf-8',
    );
  } catch {
    // Diagnostics must never affect the runner's durable control path.
  }
}

/** Terminal push wiring (set once in main after the config loads). */
let runnerTerminalPushContext: {
  gatewayBaseUrl: string;
  executorToken: string;
  runId: string;
  sandboxProvider?: 'daytona' | 'modal';
} | null = null;

function terminalPushContextFromConfig(
  config: PlayRunnerExecutionConfig,
): typeof runnerTerminalPushContext {
  const push = config.context.runnerPushExecution;
  const gatewayBaseUrl = config.context.receiptGatewayBaseUrl?.trim();
  const executorToken = config.context.executorToken?.trim();
  if (!push || !gatewayBaseUrl || !executorToken) {
    return null;
  }
  return {
    gatewayBaseUrl,
    executorToken,
    runId: push.runId,
    ...(push.sandboxProvider ? { sandboxProvider: push.sandboxProvider } : {}),
  };
}

async function pushRunnerTerminalIfConfigured(
  result: PlayRunnerResult | PlayRunnerTerminalTransportResult,
  options?: Pick<
    PushRunnerTerminalOptions,
    'warn' | 'finalProgressEvents' | 'finalProgressLogOffset'
  >,
): Promise<void> {
  const context = runnerTerminalPushContext;
  if (!context) return;
  await pushRunnerTerminal({
    gatewayBaseUrl: context.gatewayBaseUrl,
    executorToken: context.executorToken,
    runId: context.runId,
    result,
    runtimeCompletedPath:
      process.env.DEEPLINE_PLAY_RUNNER_RUNTIME_COMPLETED_PATH,
    ...options,
  });
}

/**
 * Start the push-execution live progress pusher when the launch enabled push
 * execution (Daytona sandbox runner). Returns null for worker-babysat backends,
 * which keep their sidecar-file progress path.
 */
function startRunnerProgressPusherFromConfig(
  config: PlayRunnerExecutionConfig,
): RunnerProgressPusher | null {
  const push = config.context.runnerPushExecution;
  const gatewayBaseUrl = config.context.receiptGatewayBaseUrl?.trim();
  const executorToken = config.context.executorToken?.trim();
  const playName = config.context.playName?.trim();
  if (!push || !gatewayBaseUrl || !executorToken || !playName) {
    return null;
  }
  return createRunnerProgressPusher({
    gatewayBaseUrl,
    executorToken,
    runId: push.runId,
    playName,
  });
}

/**
 * Start the push-execution lease heartbeat when the launch enabled it (Daytona
 * sandbox runner). Returns null for worker-babysat backends. On the gateway's
 * terminal cancellation channel — or a gateway that stays unreachable past the
 * lease window — the loop calls back here to terminate the runner loudly, the
 * same way the worker's CancelledTask path aborts the attempt today.
 */
function startRunnerPushHeartbeatFromConfig(
  config: PlayRunnerExecutionConfig,
  onSelfTerminate?: (stop: RunnerHeartbeatStop) => void,
): ReturnType<typeof startRunnerHeartbeatLoop> | null {
  const push = config.context.runnerPushExecution;
  const gatewayBaseUrl = config.context.receiptGatewayBaseUrl?.trim();
  const executorToken = config.context.executorToken?.trim();
  if (!push || !gatewayBaseUrl || !executorToken) {
    return null;
  }
  return startRunnerHeartbeatLoop({
    gatewayBaseUrl,
    executorToken,
    runId: push.runId,
    leaseSeconds: push.leaseSeconds,
    waitForSchedulerPark: true,
    onSelfTerminate: (stop) => {
      onSelfTerminate?.(stop);
      void terminateRunnerForHeartbeatStop(stop);
    },
    onTransport: (event) => {
      writeRunnerStartupDiagnostic(
        process.env.DEEPLINE_PLAY_RUNNER_STARTUP_DIAGNOSTIC_PATH,
        { phase: 'heartbeat_transport', event },
      );
    },
  });
}

function terminateRunnerForHeartbeatStop(
  stop: RunnerHeartbeatStop,
): Promise<never> {
  const error =
    stop.reason === 'terminal'
      ? stop.terminal === 'cancelled'
        ? 'Play run was cancelled; sandbox runner self-terminated on the receipt gateway heartbeat cancellation channel.'
        : 'Play run already failed in the scheduler; sandbox runner self-terminated on the receipt gateway heartbeat cancellation channel.'
      : `RUNTIME_CONTROL_PLANE_UNAVAILABLE: Sandbox runner could not reach the receipt gateway for ${stop.reason === 'unreachable' ? stop.sinceMs : 0}ms (past the lease window); self-terminating — the parked attempt's ceiling timeout salvages this result from the captured output. ${formatRunnerGatewayTransportSummary(stop.reason === 'unreachable' ? stop.gatewayTransport : undefined)}`;
  const failedResult = runnerTerminalResultForTransport({
    status: 'failed',
    error,
    logs: [],
    stats: {},
    steps: [],
    tableNamespace: null,
  });
  return emitAndExit(
    {
      type: 'result',
      result: failedResult,
    },
    stop.reason === 'terminal' && stop.terminal === 'cancelled' ? 0 : 1,
  );
}

async function terminateRunnerForRuntimeDeadline(
  runtimeLimitSeconds: number,
  snapshot?: PlayRunnerResult,
): Promise<never> {
  const error = runtimeLimitExceededCause(runtimeLimitSeconds);
  const failedResult = runnerTerminalResultForTransport(
    snapshot ?? {
      status: 'failed',
      error,
      errors: [runtimeLimitExceededFailure(runtimeLimitSeconds, error)],
      logs: [],
      stats: {},
      steps: [],
      tableNamespace: null,
    },
  );
  // Stop customer code immediately. The structured stdout event is captured by
  // the Daytona shell wrapper, whose crash epilogue owns the bounded gateway
  // push during the outer grace period. Awaiting network/progress work here
  // would let customer code continue dispatching after its deadline.
  const terminalHandoff = runnerTerminalHandoffForTransport(
    failedResult,
    runnerProgressPusher,
  );
  runnerProgressPusher = null;
  return emitAndExit(terminalHandoff.event, 0);
}

// The external watchdog samples the sandbox cgroup and raises SIGUSR2 at its
// pressure threshold. Register at module load: Node would otherwise terminate
// before map admission can react and release retained result bodies.
onMemoryPressure((sample) => {
  emitWorkerLog(
    `[memory] pressure signal received usage=${sample.usageBytes ?? 'unknown'} limit=${sample.limitBytes ?? 'unknown'}`,
  );
  // The shared sandbox argv enables explicit collection for this recovery path.
  (globalThis as { gc?: () => void }).gc?.();
});

export function runPlayRunnerMain(): void {
  main().catch(async (error) => {
    ensureSourceMapSupport();
    const message = formatRunnerFailure(error);
    const failedResult: PlayRunnerResult = {
      status: 'failed',
      error: message,
      errors: [normalizePlayRunFailure(error)],
      logs: [],
      stats: {},
      steps: [],
      tableNamespace: null,
    };
    const terminalResult = runnerTerminalResultForTransport(failedResult);
    // Write the salvageable terminal before its gateway push. Startup failures
    // and unexpected settlement failures must retain their real diagnosis even
    // if the push itself stalls or exhausts retries.
    await writeRunnerEventToStdout({
      type: 'result',
      result: terminalResult,
    }).catch(() => undefined);
    // Push execution: wake the parked worker attempt NOW instead of making it
    // wait for the ceiling-timeout salvage. Best-effort — the output file
    // still carries this result for the salvage path.
    await pushRunnerTerminalIfConfigured(terminalResult, {
      warn: createPostTerminalDiagnosticWriter(),
    }).catch(() => undefined);
    void exitRunner(0);
  });
}
