Oblive Docs

Prepare historical replay environments

Freeze retained evidence, restore isolated databases, and prepare an initiative-ready runtime.

A replay environment connects a historical world snapshot to an isolated Oblive backend and worker. Preparation includes database restoration when MongoDB or Redis is selected. A manifest alone does not make an environment ready. CWM revisions still describe business models; they are not database backups or the runtime used here.

Import a reconstructed research ZIP

replay:environment import-zip brings a versioned historical-reconstruction ZIP from S3 into private local staging. This is an operator intake step, not an executable replay environment. It does not restore databases, select starting memory, grant access to integrations or bind tool readers. Its result always includes executionReady: false and those four outstanding checks. The existing strict replay selection rules below remain unchanged.

Use this path for format version 1, reconstruction method version 3 packages. It requires Python 3.11 or later, AWS CLI credentials with read access to the exact object version, and a private request file (chmod 600). Credentials are not part of the request. For example, using synthetic identities and replacing the object version, hash and size with independently verified values:

{
  "schemaVersion": 1,
  "organizationId": "00000000-0000-4000-8000-000000000001",
  "targetDay": "2026-10-07",
  "timezone": "Asia/Kolkata",
  "policy": "reconstructed_excluding_uncertain_v1",
  "source": {
    "bucket": "example-research-snapshots",
    "region": "us-east-1",
    "account": "123456789012",
    "key": "research/socialkit-2026-10-07.zip",
    "versionId": "replace-with-the-exact-s3-version",
    "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
    "size": 12345
  }
}
bun run replay:environment import-zip \
  --config /private/request.json \
  --organization 00000000-0000-4000-8000-000000000001 \
  --directory /private/replay-imports

bun run replay:environment inspect-import \
  --config /private/replay-imports/<source-sha256>/import.json \
  --organization 00000000-0000-4000-8000-000000000001

The importer checks the S3 owner, version, size, ZIP hash, organization, day and timezone cutoff, then verifies every declared file against its hash and size. Missing, extra, duplicate or unsafe members fail the entire import. Inspection repeats local verification without network access. Neither command requires a model, a database connection or a running Docker stack.

The staged directory contains source.zip, import.json, files.jsonl and coverage.json, all private. files.jsonl is a stable inventory, with one JSON object per line. Paths containing an uncertain segment are excluded from that inventory. Recovered versions have their own role; they are not merged or counted as new events. Original source content, dates and coverage remain unchanged. The original ZIP still contains excluded files and must remain operator-only: never mount it directly into an agent workspace. No source file is extracted or executed during intake.

importSha256 identifies the canonical import manifest, including its inventory and coverage hashes. A repeated import rechecks the same S3 pin and staged files; it does not select a newer object. S3 access proves permission to download the package, not permission to expose every source to an agent. Current integration access must be checked when constructing an executable environment.

Bounds are 10 GiB compressed, 64 GiB expanded, 8 GiB per member, 128 MiB per manifest or coverage file, 500,000 declared files and 256 sections. Preflight reserves the ZIP size plus 384 MiB of scratch space. At most four 8-MiB ranges download concurrently, with up to three attempts per range. Cancellation waits for in-flight reads to stop before removing temporary files. Cancellation and ordinary failures remove unpublished staging; a machine crash may leave a private .import-* directory for an operator to remove after confirming no import is active. S3 is never modified or deleted.

A verified import is labelled reconstructed history, with historical coverage incomplete. Integrity verification establishes which bytes were retained; it cannot establish that fields observed later had the same values on the requested day. Subsequent reader and starting-state selection must preserve that distinction and refuse missing data without using live APIs.

Prepare and inspect

The Replay control API uses the existing AGENT_SERVICE_TOKEN; scoped agent tokens cannot prepare, inspect, release, or create work in another environment. The organization is part of the URL.

POST /organizations/{organizationId}/replay-environments
Authorization: Bearer <operator-token>
Content-Type: application/json

{
  "schemaVersion": 1,
  "asOf": "2026-10-10T10:00:00Z",
  "requiredIntegrations": [
    { "integrationId": "00000000-0000-4000-8000-000000000001" }
  ],
  "memory": { "kind": "empty" },
  "idempotencyKey": "october-10-evaluation-a"
}

This synthetic example returns 202 with an environment ID. Poll GET /organizations/{organizationId}/replay-environments/{environmentId} for status, coverage, source times, frozen world hash, and readiness checks. Repeating the same idempotency key and request returns the same environment; changing the request under that key returns 409. A second environment requires a different key, even when its frozen world is identical.

The lifecycle is preparing, ready or ready_with_gaps, then releasing and released. Unrecoverable preparation failures become blocked. DELETE requests release asynchronously. It removes only containers, networks, volumes and private files carrying this environment’s matching ownership and world identity. Archive retention holds are released only after runtime cleanup succeeds. Export any evaluation outputs you need before release: the isolated task database and output bucket are removed with the runtime.

ready_with_gaps is usable with the explicitly reported limitations. Missing integrations are disabled; if no requested integration has a usable reader, preparation is blocked. Inspect coverage before submitting work. Readiness requires actual backend and worker probes, permission checks, archived reads, database access, write denial, historical clock checks, blocked direct network access, and a callback proving that the main API can reach the exact prepared runtime. It does not establish that every possible query has a recorded answer.

Eval trials

An environment can be one eval trial: one initiative in one fresh environment. Add a trial to the request with its purpose, an optional experiment label to group trials you compare, and the initiative it will run, in the same shape as the initiative route below:

"trial": {
  "purpose": "Compare the October 30 operator build",
  "experiment": "operator-october",
  "initiative": {
    "title": "Review yesterday's churn",
    "objective": "Find the accounts that churned and why.",
    "idempotencyKey": "october-10-churn"
  }
}

Trial-start retries resolve the existing idempotency key before selecting a snapshot. An identical request returns the original trial and pin, including pre-UTC cutoffs; changed day, initiative, purpose, experiment or harness mode is an idempotency conflict.

The trial row is written with the environment, in the business backend’s Postgres, and pinned to the initiative’s SHA-256. It records the snapshot ID and hash, asOf, and the business day and timezone from the frozen snapshot (empty without one). Before the environment is ready it records the agent build: the backend image’s org.opencontainers.image.revision (empty for an unlabelled local build), the backend and worker image digests, each enabled profile’s agent-pack revision with a hash of them all, and each profile’s model and reasoning settings with the model access mode.

POST .../initiatives on a trial environment accepts only that initiative. A different initiative is 400, and the same one while a send is still in flight is 409 trial_initiative_used. A refused or failed send leaves the initiative unused. Once its task exists, resending the same body is forwarded and the stack returns that task through its idempotency key; the trial never gets a second initiative.

When release exports the evidence, the same transaction finishes the trial: the initiative’s final status as outcome (not_started when none was sent), usage summed over the stack’s runs, the environment’s gaps, guard hits, and one artifact row per evidence part with its SHA-256, size, content type, the encryption envelope as key ID, and its stored chunk keys. Guard hits are the environment’s post_cutoff_evidence gaps: one per tool operation whose answer the cutoff guard refused. A request the guard refuses before calling the tool, for a time past the cutoff, is not counted. An environment released before its stack ran finishes its trial as not_started, with no artifacts. Rows hold keys and hashes, never URLs; the evidence route reads the parts. Deleting the organization deletes its trials. Retention and cleanup of trial artifacts are not decided yet.

The atif evidence part tags every trajectory with extra.origin: replay_eval and extra.environmentId. Live runs that retain their Codex sessions produce the same format tagged live; see run execution capture.

Selection and fidelity

latest-retained-v1 selects eligible, completed, retained sources known before the requested time T. A source qualifies only when it finished strictly before T and its evidence-availability record is confirmed with confirmedAt strictly before T. A record that finished exactly at T, or was confirmed at or after T, is not selected. A connector archive collected at or after T is refused even when it is a provider-verified export whose declared instant is T, because nobody could read it at T. The latest retained observations are selected with their original capture intervals and visible history gaps. Recordings retain exact request and tool-definition identities. Ties have a stable identity ordering. Selection is frozen before provisioning and never silently replaces a missing or corrupt pin. Release and retry do not rediscover a newer source.

MongoDB and Redis integrations each select one newest eligible saved_database image within the requested resource scope. An import’s source archive ID is provenance, not a separate database to restore. Older images and provider-only metadata are not pinned or downloaded for that environment. If the selected image fails verification, preparation fails without falling back to an older image.

Recorded MCP results have a 64 MiB canonical JSON budget; the complete private runtime file has a 128 MiB budget, including encoded attachments and starting memory. These replay budgets are separate from the 16 MiB history-manifest budget. Exceeding a byte or structural bound returns limit_exceeded; data is never truncated. The canonical JSON structural bounds remain 262,144 nodes and depth 32. When selection exceeds a total limit, the environment blocks with the stage path followed by the limit’s own name, such as ["prepare", "sources"]. Only limit_exceeded keeps its own path, and only when every segment is a fixed name. Other error paths can name archives, so they keep only the stage. Current permission checks run around tool inventory and each read, including after the read; authorization is not cached for the duration of an environment.

Each integration can optionally restrict resourceIds to retained capture-policy resource IDs. These are resource selections, not arbitrary URLs or queries. Context and memory are empty by default. memory: { "kind": "retained_run", "runId": "..." } selects that run’s retained initial context: its saved memory/ and organization/ files are mounted for the matching profile, and the original snapshot is retained separately as context/historical-start.json. The new run keeps its own task context; historical task state is reference material, not active work in the new database. Current business context, tasks, conversations, inbox entries, schedules and learned memory are not copied. Each new run retains its own context manifest and environment binding.

A frozen V4 packet can pin the business’s own setup at the cutoff, so a replay run starts the way a live run did then:

  • A pinned Context publication is written under organization/, one file per document, for each profile the live rules let read it. Two pinned publications are refused.
  • Pinned profile-memory revisions become memory/learned-lessons.md when some memory the profile may see holds a lesson. The same code renders it as in a live run, with the same rule for which profiles see which memory, and context/replay.json says initialMemory: "pinned_at_cutoff".
  • A pinned organization revision sets the isolated organization’s name, timezone, currency, departments, default profiles, limits and constraints. Missing fields use the neutral defaults below, described by the settings policy in context/replay.json.
  • A pinned profile revision sets that profile’s name, kind, department, model, reasoning effort, skills, tool policies, default run mode and agent-pack revision. A profile disabled or deleted at the cutoff isn’t created.
  • Preparation copies each pinned agent-pack revision from the main store and checks it against its hash, so the current image runs the instructions and skills that profile had at the cutoff. A revision missing from the main store stops preparation with missing_history.

Integration reconciliation runs get no pinned Context or lessons. A profile that starts from a retained run gets that run’s files and nothing from the packet. Without pinned revisions, profiles use the selected harness instructions. The organization uses Replay organization, snapshot timezone or UTC, no assumed currency, and limits of 5 task levels, 25 plan operations and 100 descendants. Integration labels are generic and current settings remain private reader restrictions. API response metadata uses the cutoff; stored record timestamps, business data and operational clocks stay unchanged. Pinning needs the organization’s internal-state history turned on before the cutoff, and its revisions within retention. Each profile’s run reads exactly the part of the packet a live run of that profile reads: the organization, its own profile and tasks, and its own and the operator’s memory. The source authority authorizes only that part, and context/historical-business-inputs.json holds that part without Context, which arrives under organization/ instead. The seed reads the whole packet.

ReaderSupported behavior
MongoDBRestored native database files, using the existing bounded, field-scoped read adapter. BSON, indexes and collection options remain native.
RedisRestored RDB with the existing bounded read adapter. Types and absolute expiries remain native; business time is frozen.
Lemon Squeezy product catalogueRetained complete product pages support the catalogue reader’s documented queries.
Lemon Squeezy customersComplete retained customer pages support ls_list_customers and ls_get_customer, including new customer IDs and pagination.
Selected tool datasetsReviewed paged queries retain the full tool contract and response; Tally form/submission and Resend sent-message collections include required children.
Other MCP readsExact retained operation, arguments and tool definition. Different arguments without a recording return missing_fixture.
Google Workspace CLIExact retained read invocation and output files; transport IDs are normalized. Uploads and action invocations are blocked.
GitExact retained advertise/upload-pack exchanges. This is not a general Git server over every retained object.

Other daily connector exports do not automatically become queryable datasets. Unsupported exports, missing pages, missing saved database bytes and unavailable adapters remain coverage gaps. Git and CLI misses, like MCP misses, are reported on the environment. No miss reaches a live provider.

Lemon customer and product datasets are independent. Customer reads do not require product data. Separate stores remain isolated even if record IDs overlap. Requests keep the live tool names, arguments, selected-store schema, pagination defaults and response fields. For example:

{ "storeId": "1", "customerId": "102" }

The example is a synthetic ls_get_customer request. If the authorized customer inventory is complete and customer 102 is absent, the reader returns the normal Lemon resource-not-found error. Missing inventory cannot establish absence. A request for a store/resource without a dataset may use an exact retained recording; incomplete or damaged selected data never triggers another source. Current permissions are checked before and after reads. Parent or child field projections that cannot supply the full tool response are rejected rather than silently returning fewer fields.

Newly prepared Lemon readers use internal catalogueVersion: 3 metadata for the expanded billing resources. Version 2 retains customer/multiple-store dispatch; earlier product runtimes retain their original routing. Archive formats and saved V3/V4 packet hashes are unchanged. Collection remains an observed interval unless the provider supplies verified point-in-time evidence; complete pagination alone does not prove the exact state at midnight.

Tool lists at the cutoff

The integration gateway saves each tool list it serves with request: { profileKey, mode }, when the integration’s recording policy has a list_tools binding. Replay selects the newest saved list before the cutoff for each profile and run mode, and a frozen snapshot can pin one with a recording requirement for list_tools. Lists saved before this key existed are not served.

With a pinned list, a replay run sees the same tools live saw: names, schemas, descriptions, annotations and writes. A write becomes an action in the isolated database, proposed under ask_user_on_write or approved under autonomous, with the result text a live run gets. Replay never executes an action. Without a pinned list, the agent sees only tools with saved answers, and the environment records a missing_history gap at ["integrations", id, "list_tools"].

Selected form and message collections

Tally collection can select list_forms with explicit workspace IDs, page: 1 and limit. It follows every page, loads each returned form and collects completed and partial submissions with fetch_submissions. Each child tool must also be enabled. For example, a synthetic resource selection is:

{
  "id": "tally/forms",
  "operation": "list_forms",
  "arguments": { "filter": { "workspaceIds": ["selected-workspace"] }, "page": 1, "limit": 100 }
}

Resend list-emails supports forward pagination and requires get-email details for every returned ID. list-received-emails retains metadata only; received bodies, raw MIME and attachments are not part of that collection. These lists cover records still retained by the provider, not lifetime account history.

Collection publishes only when all pages and required children are saved. Interrupted child writes retry from the saved cursor. Replay checks parent/child identity, workspace scope, generation, page totals and truncation, then returns the original saved response through the ordinary tool name. It does not recompute arbitrary filters or contact the provider. Existing standalone selected-object archives retain their prior contract. Real provider compatibility still needs account acceptance.

An event timestamp or date-filtered report does not establish what was available at an earlier cutoff. These collections preserve observations at collection time. Collect prospectively if the necessary earlier evidence was never saved; do not backdate a new export.

Retained GA4 country report

A configured GA4 integration can collect one reviewed report through the existing history scheduler: google_analytics_run_report, one property and one closed property-calendar day, country with sessions/activeUsers, ascending country ordering, limit 100 and keepEmptyRows false. Capture requires an explicitly enabled policy. Partial field selection and other report definitions are refused.

The day is an absolute date, or the rolling selector {"startDate": "yesterday", "endDate": "yesterday"}. A rolling window {"startDate": "NdaysAgo", "endDate": "yesterday"} (N from 2 to 90, 30 recommended) collects one exact single-day report per day in one generation. Days are never merged into one report (D047). A rolling resource reads the property timezone with google_analytics_get_property, which the integration must enable, and resolves the property day before the persisted job start. A retry after midnight keeps that day. The snapshot keeps the selector; each page keeps the absolute request it sent. Collection stops if the report’s timezone differs from the property’s (for a window, checked on its first page).

For example, the agent makes its ordinary call in both live and replay modes:

{
  "propertyId": "123",
  "dateRanges": [{ "startDate": "2026-10-20", "endDate": "2026-10-20" }],
  "dimensions": ["country"],
  "metrics": ["sessions", "activeUsers"],
  "orderBys": [{ "kind": "dimension", "fieldName": "country" }]
}

Replay returns the original public page, including quota, thresholding, sampling and truncation metadata. Default arguments and saved offsets match; a new page size, filter, dimension or date range needs its own exact retained recording. Incomplete/corrupt selected report data cannot fall back. Current property/profile access is checked before and after reads. The versioned internal reader is ga4_report with reportVersion: 1; old reader and packet formats remain supported.

Relative dates (yesterday, NdaysAgo) resolve against the replay cutoff in the property’s retained timezone and answer only an exactly retained single day. today, multi-day ranges, two date ranges, days that were not retained and properties retained in two timezones return missing_fixture. Replay never combines days: sessions and active users are approximate distinct counts, and each response carries metadata for its own query. When one day was collected more than once, the newest complete collection answers. An exact recording of a relative-date call answers only at a cutoff on the property day it was recorded.

GA4 days follow the property timezone. At a UTC snapshot cutoff, a GA4 day answers only when its property day closed before the cutoff. A collection refuses a day that was still open in the property timezone when it started, and selection admits only collections finished before the cutoff. For a property in America/Los_Angeles, the UTC cutoff for 28 October 2026 is 17:00 on 28 October in Los Angeles, so yesterday answers 27 October and 28 October is refused.

A 20 October report collected on 29 October is available only after its actual observation and durable storage. A later correction cannot change a frozen packet. A packet keeps the latest collection of each resource, so a rolling resource answers one day per packet. yesterday matches only when the collection started on the cutoff’s property day completed before the cutoff; otherwise it returns missing_fixture. Full provider/worker acceptance and other connectors remain separate; see the shared M2–M4 verification reports.

Trusted host runner

The main backend stores requests, leases and frozen archive references in PostgreSQL. A separate trusted host process owns Docker and performs preparation. Do not mount its Docker socket into the backend or agent containers.

Build this branch’s backend and agent images and docker/replay/redis.Dockerfile. Use explicit image IDs or repository@sha256:... digests for every image. The Mongo mapping must name the exact database version that created the backup. Images must already exist on the runner’s Docker host; preparation uses --pull never.

Create a private 0600 runner JSON file outside Git:

{
  "directory": "/private/oblive-replays",
  "sourceBackendOrigin": "http://host.docker.internal:3000",
  "backendReachableHost": "127.0.0.1",
  "images": {
    "backend": "repository/backend@sha256:<64-hex-digest>",
    "worker": "repository/agents@sha256:<64-hex-digest>",
    "postgres": "postgres@sha256:<64-hex-digest>",
    "queue": "redis@sha256:<64-hex-digest>",
    "garage": "dxflrs/garage@sha256:<64-hex-digest>",
    "redis": "repository/replay-redis@sha256:<64-hex-digest>",
    "mongo": { "8.0.16": "mongo@sha256:<64-hex-digest>" }
  }
}

The placeholders are not valid digests. The runner uses the main backend’s existing database, object-store and archive-encryption configuration; it needs those permissions to read selected archives and persist lifecycle state. The isolated stack receives newly generated credentials only. sourceBackendOrigin must reach the main backend from Docker. The main backend must be able to reach the runner’s loopback-published runtime port: use the same host/network namespace or an explicitly arranged private forwarding path. Merely changing backendReachableHost does not expose that port. When the main backend runs in Docker, as it does under bun run stack, set backendReachableHost to host.docker.internal: inside its container 127.0.0.1 is the container itself, so every readiness probe fails.

Check the setup before starting a trial. The preflight is read-only and prints no secrets:

bun run replay:preflight --config /private/replay-runner.json --organization <uuid>

It checks the runner configuration and images, the backend settings, database access, model access, the relay’s path to the main backend, the main backend’s path to a runner-published port, model egress, and how long the organization’s latest frozen day takes to authorize against its budget.

bun run replay:environment run --config /private/replay-runner.json
# Bounded operator invocation for one organization:
bun run replay:environment run --config /private/replay-runner.json --organization <uuid> --once

The runner uses expiring database leases and spends a preparation attempt when it claims one. A trial can prepare at most three times within one hour of its request. Retries reuse its source pins. The runner recreates only its own incomplete restore volumes. Run one invocation per trusted worker. Database claiming limits simultaneous preparation to two jobs per organization.

Before export stops services, the runner records unexpected container exit codes and whether Docker marked a container as out of memory. These diagnostics appear on the trial timeline. After five unsuccessful release attempts the environment becomes needs_attention. Its trial slot opens. The runner stops the owned containers and removes their live credential copies while preserving volumes, evidence files and source pins. The runner logs an error and the trial timeline shows whether containment was verified.

If containment failed, restore Docker or filesystem access and rerun containment on the original trusted host with the same private runner configuration:

bun run replay:environment contain --config /private/replay-runner.json --organization <uuid> --environment <uuid>

Confirmed containment frees reconstruction capacity. This command can be repeated and does not retry export or delete evidence. Recover retained evidence through a reviewed private process before removing the sandbox. Repeated DELETE requests leave a needs_attention environment in that state. Keep raw retained files private because archive redaction may not have completed.

Model access

The replay worker gets model access the way live agents do: from the codex section of config/local-stack.json, read with the same rules as bun run stack. The runner reads the repository’s config/local-stack.json unless the runner JSON names another absolute stackConfigFile. It reads only the codex section.

  • authMode: "local". The runner copies the ChatGPT login in localHome/auth.json (default ~/.codex) into the environment’s private directory as codex-auth.json (0600). It mounts the copy read-only as the worker’s CODEX_HOME/auth.json, so the worker’s Codex uses the same login as live agents. Live agents’ Codex home has no config.toml, and neither does the worker’s: both take their Codex settings from the agent runtime’s code. The copy keeps the access token, ID token and account. It leaves out the refresh token and any stored API key, which the sandbox can’t use. Codex sends the login to the model relay. The relay forwards POST /backend-api/codex/responses and GET /backend-api/codex/models to https://chatgpt.com, Codex’s default base URL with a ChatGPT login, and only with the copied access token, which it checks by hash. The relay holds no credential. A login whose access token Codex would refresh within the next hour is refused (Codex refreshes five minutes before the token’s exp, or after eight days when the token has no readable exp). The worker can’t reach the token endpoint, and a refresh would rotate the owner’s login. Use Codex locally to refresh it, then request a new environment. A ready environment works until the copied token expires; after that, release it and request another. Release deletes the copy with the environment directory, and a failed preparation deletes it and removes the worker at once. Rootless or user-remapped Docker can’t read the 0600 copy as container root.
  • authMode: "api_key". The runner reads the key from the variable named by apiKeyEnvironmentVariable in its own environment. Only the model relay receives it; the relay forwards to https://api.openai.com/v1, as live api_key mode does.
  • modelKeyFile (optional) overrides both with a private 0600 file holding a dedicated OpenAI API key. Existing runner configurations keep working.

A missing or unusable credential blocks preparation before any file or container is created, with a needs_configuration gap that names the setting: prepare.stackConfig, prepare.stackConfig.codex, prepare.codex.apiKeyEnvironmentVariable, prepare.codex.localHome, prepare.codex.localAuth, prepare.codex.localAuth.stale, prepare.modelKeyFile or prepare.modelKey. No credential reaches a log, an error, the runtime files or the Compose file.

In local mode the isolated worker holds a temporary copy of the owner’s Codex login, as live agents do, and anything the agent can read can read it: an access token valid until it expires, without the refresh token. Its firewall lets it reach only the in-stack backend, queue, object store and model relay. The relay forwards only the two model routes, with Codex’s request metadata, and drops its own token, cookies and forwarding headers.

Saved Mongo and Redis backups

Provider backup metadata alone is insufficient. The runner requires locally archived, chunked backup bytes. This milestone supports importing an operator-supplied Atlas native snapshot archive or RDB file associated with its selected retained backup metadata:

{
  "sourceArchiveId": "00000000-0000-4000-8000-000000000002",
  "path": "/private/downloaded-backup.tar.gz",
  "sha256": "<64-hex-digest>",
  "databaseVersion": "8.0.16"
}
bun run replay:environment import-backup --organization <uuid> --config /private/backup-import.json

history:capture import-redis uses this same importer and archive format. Its configuration uses organizationId and filePath instead of the organization flag and path, and always requires an Upstash source. Both commands require sourceArchiveId, sha256, and databaseVersion; optional providerKey on import-backup additionally constrains the source to mongodb or upstash.

Import requires an enabled current history policy selecting that source, unfiltered whole-source acquisition approval, and matching management source identity. Policy revision, credential identity, current permissions and source identity are checked again inside publication. Disabling or changing consent while bytes are being stored prevents publication.

The file is encrypted through the existing archive store, split into at most 32 MiB chunks, verified, and retained for the selected policy’s retentionDays, with existing packet/environment retention. Source metadata bytes remain owned by the import after the original metadata archives expire. Maximum backup size is 20 GiB. Imports record operator_attested association and their import observation time; a supplied checksum does not establish that these bytes came from the claimed provider backup. They therefore remain incomplete observations and cannot establish a historical date before the import. Automated provider download/attestation and Atlas PITR restore jobs are not implemented here. An exact historical Mongo/Redis replay remains blocked without eligible saved evidence; no fresh production export is silently substituted.

The importer verifies retained metadata without contacting a provider. Atlas provider references and new metadata with explicit obliveSource identity can be used; legacy Upstash metadata also binds through database_id. Legacy Atlas object-only metadata without source identity requires a new source-bound metadata collection before import. Existing saved imports remain readable.

Mongo archives are extracted with traversal/link/device checks and a 40 GiB expanded-size budget. The runner starts compatible mongod against its private volume, removes source users, roles, replication metadata and unselected databases/collections, validates selected collections, and creates a scoped read-only account. TTL deletion is disabled. It does not feed native database files to mongorestore, and it never connects the restored server to the original replica set.

The Redis image uses pinned libfaketime to freeze wall time while preserving monotonic time. RDB absolute expiries are evaluated at the requested historical clock; expired keys stay expired. Queue Redis has its own real clock and storage. Redis Functions are not supplied by an RDB export. Native restore compatibility must be checked with a representative isolated backup before activation.

Runtime boundaries and initiative API

Each environment owns separate PostgreSQL, queue Redis, object storage, worker workspace and restored database volumes. Container firewalls allow only the required in-stack destinations, then drop network administration capabilities. The worker cannot reach the source authority, restored databases or public Internet directly. A narrow source-authority relay checks current source access before and after historical reads. Historical permission grants never override revocation. A separate model relay permits Responses inference and rejects hosted search, remote MCP and other live provider tools. Replay workers use an explicit HTTP Responses provider that points at the relay, in the live Codex auth mode (see Model access). They keep the live worker’s other Codex settings, including bounded subagents. The relay checks both top-level tool definitions and additional_tools input items, including namespaces; remote image/file URLs and server-side conversation references are rejected.

The run context and prompt declare the historical business time, and a date shim exposes it to ordinary shell commands. This is not a global operating-system clock replacement: leases, timeouts, capability expiry and the operational queue use real time. Code that reads the system clock directly can observe operational time; arbitrary programs are not a deterministic time simulator.

The cutoff guard

No replay tool answer may hold a record from the historical time T or later. One guard, services/replay/sources/connectors/cutoff.ts, checks every replay MCP call, whichever reader answers it, and every Workspace gws output.

  • Requests. A declared time input may end at T, and anything after T is refused with post_cutoff_evidence. A refused request adds no environment gap.

    • A lookback such as days is treated as ending at T, and may not be negative. Each reader still decides how to answer it.
    • Days are UTC days: YYYY-MM-DD, YYYYMMDD, today, yesterday or NdaysAgo, counted from T.
    • Workspace gws inputs have no schema, so they aren’t checked; only their output is.
  • Answers. The guard reads an answer’s structured content and every JSON text block. If any record’s own time is at or after T, the whole call fails with post_cutoff_evidence and adds a gap. These count as record times:

    • common names that hold an ISO date-time, such as created_at, updatedAt and timestamp;
    • fields a tool declares.

    Future fields known at T, such as renews_at, don’t count.

  • Declaring rules. A new date filter declares its inputs before it ships:

    • A tool dataset connector sets timeRules, which holds timeInputs, recordTime and recordDays. A dedicated reader adds its rules to the registry’s reader table instead.
    • Input kinds are instant, start_day, end_day, lookback and not_time. Use not_time for a time-like name that isn’t time, such as a startRow offset.
    • Record kinds are iso, epoch_ms, epoch_s, day and future. future exempts a field known at T, such as a renewal date.
    • tests/services/replay-cutoff-guard.test.ts walks every dedicated reader’s tool schema, except Workspace’s commands, which have none. It fails on any date, date-time or duration-like input without a rule.
    • Exact recordings keep answering. Their undeclared time inputs show up in the environment’s coverage as undeclaredTimeInputs.

Saved evidence is checked separately. Selection applies its own time rules, and the recorded and SocialKit readers still refuse a page observed at or after T. A record-time check can’t see a state that changed after T without a timestamp, so the guard doesn’t replace these checks.

After readiness, use the environment’s initiative routes:

  • POST .../{environmentId}/initiatives: title, objective, optional task inputs/acceptance criteria, budget and priority, and a required idempotency key. Ownership and replay binding are backend-owned.
  • GET .../{environmentId}/initiatives/{id}, /graph, /runs; POST .../{id}/retry.
  • GET .../{environmentId}/runs/{id}, /logs, /outputs/{artifactIndex}.

The existing task scheduler, run queue, claims, context construction and worker execute the work. Children, review tasks and retries inherit an immutable binding. Mixing live and replay claims or manifests fails. Recurring schedules, learning, discovery, publication and external actions are blocked or disabled. Internal task progress and retained evaluation outputs still persist inside the isolated stack. Live initiatives continue on their original backend and worker.

Insights in replay

A replay agent reads Insights through the same three agent routes as live: GET .../insights/metrics, POST .../insights/query and GET .../insights/receipts/{receiptId}. Every other Insights route stays refused, including insights/refresh. Refusals match any casing and a trailing slash, because Express routes those to the same handler.

Preparation picks, for each requested integration, the newest daily Insights copy whose availability was confirmed strictly before T: the latest frozenAt, then the latest confirmedAt, then the highest archive id. Only copies that are not being deleted and are pinned, unexpired or already held by another environment count, so an expired copy is skipped for an older one. A copy confirmed at T or later is never picked. The copy is held beside the world snapshot, not inside it, in selection.insights, and keeps its own retention hold until release. A missing copy adds no preparation gap and never blocks the environment. A copy that expires or stops matching between selection and freeze is dropped at freeze and answered as missing when called.

The provisioner checks each pinned copy, then budgets the copies newest first against the rest of the 128 MiB runtime file, using the object sizes their archive rows record, and reads only the copies that fit. The budget is greedy: a newer copy that does not fit is skipped and an older, smaller one can still be kept. A copy left out for size is marked limit_exceeded with the ids of its sources. A copy that fails its checks or reads is marked unavailable with integrity_mismatch or source_unavailable. Inside the stack, services/replay/sources/insights.service.ts answers from the copies through the live query code. When two copies hold the same source, the newer copy answers for it.

Answers use the business clock. generatedAt equals T, and no time in an answer is after T. A window ending after T is refused with post_cutoff_evidence, and currency is refused with missing_history, because exchange rates would come from a live provider. Both answer 422.

Replay answers only for an agent profile; any other caller gets 403 insight_access_denied. The stack’s own integrations carry no credentials, so the source-authority relay decides access against the live backend. It confirms each named copy is pinned by the environment, each source is in a named copy and readable live, and that the live MongoDB connection still allows the creation field a new-documents metric counts by. A request names at most 1,000 sources, so larger sets are sent in chunks. metrics hides only the sources and metric-source pairs the relay refuses, and checks again after reading. query answers 403 insight_source_forbidden for a refused source and 422 insight_definition_unavailable for a refused field, as live does. The relay is asked again before the receipt record is written and before receipts/{receiptId} returns. A relay error answers source_unavailable.

Query receipts are kept in the stack’s own database and storage, so receipts/{receiptId} works during the run. The answer body is stored before the receipt record, so a refused read can leave the body without a receipt. The replay receipt store has no 30-second deadline, takes no organization lock and queues no evidence availability.

A query whose sources the copies hold records no gap. For a source no copy holds, the read records a gap at ["insights", integrationId] for each integration it touches: the one whose left-out copy held the source, and, if some source belongs to no left-out copy, every integration whose copy is unavailable or missing. Each gap carries its own code, and the environment becomes ready_with_gaps. The answer is 422 with the failed copy’s code, else missing_history, else limit_exceeded. A source no copy could have held answers 403 insight_source_forbidden. A metric list records a gap for every integration without a copy, and answers by the same rule when there is no copy at all.

Gaps: Insights exist only after a business enables daily copies, so earlier cutoffs have none. The list reports connected and preferred from the stack’s own integrations, so preferred is always false in replay.

Verification and operating limits

Focused tests cover deterministic selection, cutoff boundaries, archive retention, revoked access, request matching, binding inheritance, lifecycle retries and ownership. Disposable PostgreSQL tests exercise actual migrations and constraints. The opt-in Docker smoke test is apps/backend/tests/fixtures/replay-environment.smoke.ts; TEST_REPLAY_IMAGES names a JSON file containing the pinned images map above. It uses synthetic backups and an explicitly synthetic inference server; it exercises initiative scheduling, the real Codex client, a retained MCP read through the tool gateway, and a child’s inherited binding, without a paid model call. It does not validate model output quality or historical provider provenance.

Initial engineering bounds are 32 requested integrations, 200 resources per selection, 2,000 candidate archives, 200 selected sources per environment, 64 MiB of ordinary reader content and 128 MiB of runtime configuration. Limits fail explicitly. No truncation or fallback to current data occurs.

Preparing and retaining environments uses disk and memory independently of the history archive. Release unused environments; a retention pin cannot extend a provider’s expiring remote backup. Prompt-comparison orchestration, queryable adapters for other connector datasets, automated native backup download, and full-day event playback remain separate work.

For integrations with collection-attempt evidence available by the requested cutoff, supply a frozen business-world snapshot. Automatic legacy selection is refused with an unsupported_operation preparation gap, so it cannot overlook a newer failed refresh. Frozen intake verifies and retains attempt evidence with the world but creates historical tools only from the selected data members. Attempt progress records are not tool responses. Existing older frozen selections retain their original contract.

Frozen V4 business packet inputs

A replay may select a frozen V4 business/day packet by exact snapshot ID and manifest hash. The packet retains existing Context, insight and file bundles alongside external evidence. All required categories must be available and at least one category must be required. Missing optional evidence stays visible; an optional source explicitly requested as an executable reader must be available. Legacy V3 admission keeps its previous rules.

An internal-data-only packet can use requiredIntegrations: [] and memory: { "kind": "empty" }. The backend requires actual retained input bytes; an empty descriptor is insufficient. It copies the canonical input wrapper into one read-only context/historical-business-inputs.json reference file. Pinned Context documents and profile memory are also written to the workspace, at the fixed organization/ and memory/learned-lessons.md paths a live run uses, and pinned organization and profile revisions become the seeded rows. No other part of the wrapper is written to the workspace. Private execution descriptors, transcripts and later run outcomes never appear in that wrapper.

Preparation, dispatch and worker hydration recheck frozen root/input hashes and current source access. The consuming profile must still have source and field permission and the required retained file ownership. A profile without access cannot run silently with missing business inputs. An unrelated profile without access does not prevent other eligible profiles from using the environment. These checks do not establish live provider coverage or evaluation quality.

Connector dataset readers

A saved connector export is usable through the ordinary agent interface only when a reader supports its schema and query scope. The current branch adds expanded Lemon Squeezy billing readers, Paddle inventories, SocialKit reports/logs, X reads, selected Workspace JSON commands and selected retained MCP query pages. New runtime readers explicitly declare dataset version 1; expanded Lemon billing uses catalogue version 3. Earlier runtime versions retain their original tool sets.

Retained MCP pages include the discovered tool schema, original response, normalized root request, actual page request and continuation. Publication checks full page chains, identities/totals where available and bounded stored bytes. Replay checks current organization/source/profile access before and after a read and cannot contact providers. Selected-object and exact-query readers do not imply complete account inventories or arbitrary filtering.

Tally, Resend and GitHub list scopes also retain the children their saved list rows name. A GitHub pull-request list retains each PR’s pull_request_read detail, status, files, reviews, commits, comments, check runs and review threads. It publishes only when every chain is complete and the file, commit and comment pages match the detail’s counts. Each PR costs about eight pages against the 2,000-page limit, so select open pull requests or narrow branches for busy repositories.

SocialKit admin request logs answer date filters from the newest complete saved window with the same non-date filters (D047). An older collection never answers. A window holds nothing after its collection ran, so it covers from up to C, the earlier of its to and its collection time.

  • Items. Those with createdAt inside the request, both ends inclusive, newest first, with live paging and totals. Windows whose items lack times, or aren’t newest first, answer only whole.
  • Open ends. A request ending after C, including days counted back from the replay cutoff, answers up to C, and its echoed range ends at C, where a live call would echo the cutoff.
  • Starts. A start the newest window doesn’t cover returns missing_fixture.
  • Metrics tools. They answer only their exact saved days page.

Live replies warn that recently buffered requests may not have arrived yet, so a window near C can differ from what a live call would have returned.

GitHub list_commits answers from a collected commit window of one branch (D047). The policy uses {owner, repo, sha: <branch>, windowDays}, with at most 90 days.

  • What answers. The branch as sha, since/until on the committer date (both ends inclusive, a plain date as UTC midnight), author by login or commit email, and paging.
  • Open ends. An open until, or one after the collection, answers up to the collection. An until after the replay cutoff is refused with post_cutoff_evidence.
  • What doesn’t. path, fields, a commit SHA, a missing sha or since, a since outside the window, and a date that is neither RFC3339 nor YYYY-MM-DD return missing_fixture.

GitHub search_pull_requests answers only from exact recordings. Its live results are full issue objects, which the saved pull request inventory can’t reproduce.

Workspace uses ordinary gws reads, including retained JSON pagination. It does not add an MCP server. Binary downloads, recursive folders and new searches remain unsupported. X’s older multi-page archives without actual continuation arguments cannot establish a complete replay dataset.

The implementation and remaining connector scopes are recorded in docs/plans/replay-rsi-v2/connector-dataset-readers-implementation.md. Stripe’s hosted reader, legacy GitHub/PostHog/AWS/Crisp dataset conversions, broader hosted inventories and live-account verification remain incomplete. Existing exact call recordings remain available where authorized. No provider policy is automatically enabled by these changes.

Execute a reconstructed research ZIP

Reconstructed imports have a separate operator-only execution path. They do not become strict retained-evidence snapshots. Select dated/reconstructed files explicitly; uncertain/ is never admitted. For a daily ZIP the business clock is the final millisecond before its exclusive cutoff.

  1. Use replay:environment import-zip and inspect-import to verify the exact S3 object version.
  2. Write a private materialization request containing importManifest, importSha256 and selected logical paths. Run python3 scripts/replay_import.py materialize --config /private/request.json --organization <uuid> --directory /private/selection. It creates hash-named objects and a versioned selection.json, without extracting arbitrary archive paths.
  3. Write a private preparation configuration matching reconstructionRunnerSchema. It binds the selection hash, exact profile/memory paths, Mongo collections or billing files, pinned Docker images, model authentication and the current-permission connection. Credentials stay outside Git.
  4. Run bun run replay:reconstruction prepare --config /private/prepare.json. The returned private environment directory contains the frozen runtime, seed, ownership state and Compose definition. Preparation returns ready_with_gaps only after the existing database, worker, clock, write-denial and network-isolation probes pass.
  5. Run bun run replay:reconstruction run --directory /private/environments/<uuid> --request /private/initiative.json. The request uses the existing replay initiative contract. A different prompt comparison needs another preparation, so its database, memory and task history are isolated.
  6. Use status and inspect with the environment directory. Inspection writes the task graph to private graph.json, runs.json and per-run visible-log JSONL files. retry resumes the same failed initiative through the existing task API; a different objective requires a new environment. Use release to stop that project’s services and remove model access; evidence and owned volumes remain for inspection, rather than being silently deleted.

The first reconstructed readers support authorized Mongo collections and Lemon Squeezy records. Mongo loads Extended JSON into a new networkless database with TTL cleanup disabled, then grants read-only access. Historical indexes are not asserted. Billing datasets are explicitly partial: identical included records deduplicate; conflicting versions fail; absent records remain missing history. These readers support their normal query contracts, not just the original recorded call. Other connectors remain unavailable until their reconstructed data has a verified reader.

These operator runs are not registered in the browser’s Replays → Trials page. Use inspect for their task graph, run status and visible tool logs. Retained output files are readable through the existing isolated backend run-artifact endpoint; the main instance does not contain these tasks. An independently started frontend can display the isolated initiative through its ordinary /organizations/<organizationId>/tasks/<taskId> route. The replay backend admits authenticated reads of its own organization, inbox summary and initiative progress for that screen. Cross-tenant reads, organization enumeration and configuration writes remain blocked. For local inspection, bind the frontend and token-bearing read-only proxy to loopback, reach the backend through SSH, and keep the owner credential server-side. This does not register a Trial or expose a public replay service.

Starting memory comes from explicitly selected retained profile records, with source times recorded in context/replay.json. Prompts come from the pinned runtime build. Missing original Context, older memory baselines and reconstruction limitations remain visible. Current organization identity and execution limits do not establish historical business knowledge.

The current-permission bridge uses read-only PostgreSQL sessions and fixed metadata queries. Its connection is mounted only into a separate service outside the agent network. Each read compares current organization, profile and source permissions before and after reading; revocation or an unavailable bridge denies the read. The worker has no provider credentials or live-data fallback. No live backend upgrade, production restore, historical receipt creation or public API is required.

Start a reconstructed trial with a date and query

The Trial API also accepts reconstructed research ZIPs. This mode is separate from strict retained-evidence trials; the existing form and strict request remain unchanged.

{
  "day": "2026-10-07",
  "query": "Review the available business data and recommend our next focus.",
  "historyMode": "reconstructed",
  "idempotencyKey": "oct7-focus-v1"
}

Send this body to POST /organizations/{organizationId}/replay-trials, authenticated with REPLAY_TRIAL_TOKEN. The organization must have replays enabled. The API returns HTTP 202 with trialId, environmentId, asOf, timezone and the source ZIP hash. It does not wait for download or restoration. The date means the final millisecond of that completed business day in the UTC; current and future days are refused. Unlike the strict form’s 14-day window, older indexed reconstructed dates are allowed.

Retry the same request with the same key to retrieve the original identity and source selection. Changing the query or date requires a new key. The first accepted source wins concurrent retries. At most three trials can remain open per organization. Reconstructed stacks are serialized across one runner control database, including while an initiative is running; strict concurrency is unchanged. Each replay stack has one worker and a worker pool capacity of one. Use one runner host for reconstructed stacks and keep its directory stable across restarts. The queue does not require a second scheduler.

Operator configuration

Set REPLAY_RECONSTRUCTION_INDEX_FILE to an absolute, read-only mounted JSON index on the backend. The index is bounded to 1,000 organization/day entries and 2 MiB. Populate it from verified export metadata; the API never guesses keys or searches the bucket. Each entry uses the existing replayImportRequestSchema:

{
  "schemaVersion": 1,
  "revision": "2026-11-04-v1",
  "entries": [
    {
      "schemaVersion": 1,
      "organizationId": "11111111-1111-4111-8111-111111111111",
      "targetDay": "2026-10-07",
      "timezone": "UTC",
      "policy": "reconstructed_excluding_uncertain_v1",
      "source": {
        "bucket": "example-private-history",
        "region": "us-east-1",
        "account": "123456789012",
        "key": "history/example-2026-10-07.zip",
        "versionId": "REPLACE_WITH_EXACT_S3_VERSION",
        "sha256": "REPLACE_WITH_VERIFIED_64_CHARACTER_SHA256",
        "size": 123456
      }
    }
  ]
}

These are placeholders, not a usable snapshot. Duplicate organization/day entries fail. Replace the index atomically when registering new dates; accepted trials retain the revision, full index hash and exact object identity. Credentials do not belong in this file. The runner uses its own scoped S3 read access, Python 3 and AWS CLI through the existing import command. The indexed timezone must produce the same start and end instants for the requested day as the UTC calendar. Equivalent UTC aliases are accepted without changing the ZIP’s provenance.

Add this private section to the existing replay runner configuration:

{
  "reconstruction": {
    "cacheDirectory": "/private/replay-imports",
    "authorityDatabaseUrl": "postgresql://READ_ONLY_AUTHORITY_CONNECTION",
    "authorityContainerDatabaseUrl": "postgresql://CONTAINER_REACHABLE_READ_ONLY_AUTHORITY_CONNECTION",
    "mongoVersion": "8.0.12",
    "minimumFreeBytes": 2147483648
  }
}

Keep the existing pinned images, model authentication, stack directory and source backend settings. The Mongo version must have a matching image digest in images.mongo. The two authority addresses must reach the same current source organization and permit only permission-metadata reads; never point the authority at a historical business database. Only the separate permission bridge can reach that database. Agent containers receive no source credentials or provider network access.

Run the existing replay:environment run --config <private-runner.json> command. No initiative command, manually selected source files or second runtime is needed. The importer verifies the S3 owner/version, ZIP and every member hash, then chooses currently permitted Mongo collections and partial Lemon Squeezy datasets. It chooses the newest eligible profile and memory baseline at or before the cutoff, rejects conflicting versions, and excludes uncertain/. An operator baseline, matching memory and at least one supported dataset are required. Missing optional integrations remain disabled and visible as gaps; unsupported tools never fall back to live APIs.

The immutable selected world is stored with the existing environment row before containers start. A retry reuses that world and environment ID, rechecks permissions and verifies the same bytes. Preparation can replace only its owned containers/volumes; it cannot reuse another trial’s mutable state. Scratch checks reserve space for selected data and restoration. Source ZIP caches are retained outside stack directories and are never deleted by trial release; manage their lifecycle separately.

Progress, results and fidelity

Use GET /organizations/{organizationId}/eval-runs/{trialId} with REPLAY_READ_TOKEN for progress, initiative identity, gaps and reconstructed provenance. Preparing events name downloading, selection, restore, startup and verification stages. The detail’s reconstruction field records partial coverage, ZIP/import/selection hashes and which readers are enabled. The supervisor sends one initiative when readiness passes. It follows the normal plan, child-task and review workflow; one worker processes that work sequentially. The existing trialTimeLimitMinutes defaults to 60 minutes after dispatch. A shorter budget can stop final review even when a research report exists. Existing trajectory/files APIs expose retained execution results after export; DELETE /organizations/{organizationId}/replay-trials/{trialId} cancels and requests release. Evidence must be stored and verified before a ready stack is removed.

historicalCoverageComplete is always false for this mode. A dated reconstruction may use later observations filtered by creation timestamps; it does not prove earlier mutable values. Older memory remains dated in the selected files, and prompts come from the pinned runtime build, not an invented historical prompt. Full-day event playback, additional connector readers and UI integration are separate work.

Historical harness work in reconstructed trials

New reconstructed selections also include eligible prior initiatives/tasks, run requests/runs, activity logs, chats/messages, actions and human-input records. The importer picks the newest record version strictly before the selected day ends. Equal-time conflicting versions fail; creation time alone cannot establish the earlier state of a mutable record. Missing required parents remove the affected records and produce coverage gaps. Missing optional navigation links become unavailable; original exported values remain in private provenance.

The isolated database serves these records through the existing task, run, chat and action read APIs. Historical statuses stay unchanged. Historical rows are immutable, cannot receive new work, and are excluded from dispatch, recovery and worker capacity. Create a new initiative to act on old findings. Schedules are not imported or activated. One worker executes new replay work.

Selected outputs and retained visible trajectories are copied into the isolated object store and verified. No production storage URL is fetched. The run context read surface lists available historical context/trajectory files; absent recordings stay absent. Raw SDK sessions and hidden reasoning are not imported. Files without a finished dated run owner are omitted as a coverage gap. The snapshot does not imply every old run has a full trajectory.

The initial context’s context/replay.json includes historical-work counts and gaps. Private replay_historical_records metadata preserves original rows, source paths, hashes and version timestamps. This table and its guards exist only inside a newly bootstrapped sandbox, with no production migration. Bootstrap retries never overwrite an environment that already contains work. Only operational compatibility fields are derived (task identifier parts/depth and inert lease or idempotency values); they are not claimed as historical evidence.

Bounds: 10,000 historical files within the 12,000-file execution selection and existing 4 GiB total; 128 MiB of record metadata, 100,000 records, 64 MiB per copied file. Breaches fail explicitly. These are engineering limits. Recreate an older empty replay environment to use the new import path; existing frozen selections and already-running stacks are not modified. Use a new idempotencyKey when starting the replacement trial. Strict replay is unchanged.

Some older exported activity details exceed the current activity-panel length limit. Their original text remains intact in the run context’s organization/historical-run/logs.jsonl; the native activity panel omits those entries and coverage reports activity_exceeds_display_limits. No historical text is truncated. A trajectory containing later or excluded reasoning events is not imported and is reported explicitly, rather than exposed as a complete visible trajectory.