Oblive Docs

Historical data preservation

Scoped connector captures, immutable observations, and honest historical coverage for future replay.

The history layer preserves external data for inspection, recovery and replay. See the daily S3 sync for the daily collection and full snapshot. Capture itself does not execute agents, simulate writes, restore production databases, or reconstruct a whole business from its current data. CWM business models and pinned analytical inputs remain separate contracts.

@oblive/types/history-capture exports capture policies, connector snapshots, archive references, coverage diagnostics, and WorldSnapshot. A world snapshot links immutable manifests and initial agent context; it does not embed every database record or create a new CWM model revision.

Storage read and publication behavior

Packet and archive input reads reuse verified object bytes for that operation only. They still check current permissions, archive metadata and retention on each authorized read. Separate operations fetch the bytes again; reuse does not grant access after permission revocation. Memory reuse is bounded and larger operations continue with ordinary verified reads.

Worker capture checks its lease against the database clock after waiting for locks and again in the final publication update. Expired workers cannot publish through an earlier successful check. Capture and permission changes use a consistent lock order; failed capture does not change task outcome.

Historical meaning

A provider date filter is useful only for the fields it actually dates. For example, a subscription created before October 15 may contain a cancellation recorded on October 20. Filtering its creation date cannot establish its subscription state on October 15.

There are three distinct outcomes:

OutcomeWhat it establishes
historical_state_verifiedProvider-backed proof establishes the selected state at the exact asOf instant.
observation_preservedThe retained bytes are what a specific read returned during its capture interval.
Incomplete coverageA required page, field, permission, historical source, or retention guarantee is missing.

Capture start/end, provider snapshot time, and the requested historical window are separate fields. Daily paginated observations are not atomic point-in-time snapshots. Historical selection refuses to promote them into exact state. An explicitly allowed observed selection retains an incomplete coverage report, rather than claiming an equivalent historical environment.

Initial preservation starts when capture is enabled. Older data is usable only with trustworthy provider history or previously retained observations. This layer does not backdate CWM availability receipts or silently fetch current data to fill historical gaps.

Capture policy and archive ownership

Policies identify an organization, integration, and explicit resources. Each resource has an ID, reviewed operation, bounded arguments, and optional requested fields. The backend validates the operation and resource against the integration’s current scope. Unsupported field projections fail explicitly; they do not cause a broader export. For a resource with selected fields, dependent reads require explicit childFields entries such as { "operation": "gmail_attachment", "fields": ["data", "size"] }. The collector refuses a child without that selection before calling it. Same-operation directory traversal keeps the parent’s fields. Unrestricted parent policies keep their existing behavior. Connector manifests preserve both selections, and restricted projections keep only reviewed pagination metadata outside records. AWS error responses fail collection; explicit truncation remains incomplete coverage.

When a requested projection excludes a record’s identity, coverage includes unsupported_fields: the retained fields cannot be presented as a reconstructable full record.

The following policy is entirely synthetic:

{
  "schemaVersion": 1,
  "organizationId": "00000000-0000-4000-8000-000000000001",
  "integrationId": "00000000-0000-4000-8000-000000000002",
  "providerKey": "lemon-squeezy",
  "enabled": false,
  "resources": [
    {
      "id": "store-123/subscriptions",
      "operation": "ls_list_subscriptions",
      "arguments": { "storeId": "123" }
    }
  ],
  "schedule": { "hourUtc": 2, "minuteUtc": 0, "staggerMinutes": 5 },
  "retentionDays": 90
}

Defaults are disabled capture, 02:00 UTC daily, and 90-day retention. Assign different staggerMinutes to integrations to spread API traffic. historicalWindow contains collection filters; requestedAsOf requests historical proof. Setting either field does not establish proof.

Archive objects use an organization-owned history namespace and carry SHA-256, size, and media type. Readers validate namespace ownership, bytes, and current authorization. Database archive payloads, identities, and dependencies are immutable; retention pins and deletion state are separate mutable fields. Provider backup references include hashed metadata and an explicit expiry, rather than pretending that metadata is a backup of the database itself. Connector snapshots also retain an encrypted sourceConfiguration reference for the selected settings, enabled operations, permission grants, and connection revision. This preserves the configuration that shaped collection without retaining authentication secrets. Historical grants do not override the current access checks required to read an archive.

Stored arguments and provider data can contain business-sensitive information. Keep credentials out of capture policies and manifests. The archive store encrypts each object with AES-256-GCM using INTEGRATION_CREDENTIAL_KEY, binding the ciphertext to its organization and object key. Manifests retain plaintext content hashes and sizes. A missing encryption key or object-store bucket blocks readiness. Keep the bucket private and restrict archive access; application encryption does not replace storage access controls. Retain the encryption key for the entire archive lifetime: replacing it without migrating the encrypted objects makes existing history unreadable. Backup-management credentials use the existing credential encryption mechanism and remain separate from database read credentials.

Operator command

Run from the repository root with a private JSON configuration file:

bun run history:capture seed /private/history-config.json
bun run history:capture gmail-labels /private/history-config.json
bun run history:capture readiness /private/history-config.json
bun run history:capture configure /private/history-config.json
bun run history:capture capture /private/history-config.json
bun run history:capture inspect /private/history-config.json
bun run history:capture verify /private/history-config.json
bun run history:capture select /private/history-config.json

The command configuration includes organizationId and the applicable integrationId, policy, managementCredential, snapshotId, snapshotIds, contextIds, or asOf. allowObserved explicitly permits an incomplete observed selection. Keep the file outside Git, especially when it contains backup-management credentials. Command output contains status, identities, hashes, counts, and safe error paths; it does not print captured business content or credentials.

configure stores the policy and encrypted management credential. It does not change provider plans or restore a database. Start with enabled: false, inspect readiness, then deliberately enable the policy and the backend’s HISTORY_CAPTURE_ENABLED flag. Stack-managed installations set historyCaptureEnabled: true in config/local-stack.json before generating the backend environment and restarting through their normal deployment procedure. The default is false, and the setting is forwarded only to the backend. Configuring a policy does not restart or deploy an installation. Default policy seeding assigns a stable five-minute slot between 02:00 and 02:55 UTC from the integration ID; an explicit schedule takes precedence. With the daily S3 sync this independent schedule is disabled; the sync collects from 00:15 UTC instead.

seed accepts organizationId, integrationId, and an explicit output filePath. It writes a disabled policy proposal from existing selected database, store, repository, or project scopes into that private file, creating it exclusively with mode 0600. It refuses to overwrite an existing file and prints only safe status and coverage gaps. It makes no provider calls or database configuration writes. Broad integrations still need explicit resource selections; exceeding the collection limit fails instead of dropping resources.

readiness checks configuration without contacting providers. A ready configuration does not prove provider permissions, backup recoverability, or account capabilities; collection and verification check those against the selected source. inspect reports capture age, coverage, counts, and provider backups approaching expiry within seven days.

capture advances one configured integration by a bounded work unit. A pending result requires another invocation or the enabled background scheduler to resume it. The scheduler processes enabled policies with at most two workers per organization, using database leases across processes. It does not configure missing resource scopes or credentials. There is no command that automatically exports every connected account and guarantees complete business coverage.

verify checks retained bytes and current access. select freezes the requested sources and reports their coverage; an observed selection can reproduce the same hash and still exit with code 2 because coverage is incomplete. Treat that as a coverage result, not as permission to discard gaps or claim the whole business was captured.

select-recorded finds an exact retained observation using integrationId, operation, normalized request, and observedAt. It never sends a missing request to a live provider. pin and unpin manage evaluation retention for snapshotId; cleanup removes eligible owned archive data. These commands are backend operator operations; there is no new public HTTP route, agent tool, or installed oblive CLI command.

import-redis is a Redis-only alias of the shared saved-backup importer (import-backup). Its private configuration requires organizationId, sourceArchiveId (the retained upstash_backup capture), filePath, the expected sha256, and databaseVersion. It verifies that source, checks RDB header/footer and file hash, and writes the same chunked saved_database archive used by preparation. The limit is 20 GiB, with chunks of at most 32 MiB. This command never restores Redis.

Earlier configurations using only integrationId and backupId must be updated with the retained source archive ID and exact Redis version; the importer does not guess either. Previously stored redis_export archives remain inspectable, but do not contain the restore metadata required by preparation. Import the private RDB through the shared importer to prepare it for replay. A supplied file hash still does not prove historical association: imports remain observations dated at import.

Independent recording settings

Actual-use recording and scheduled acquisition are separate controls. observation-configure selects exact integration surface/operation bindings and content classes; run-configure selects initial prompt, manifest, hydrated files and optional private worker execution events. Neither command starts a daily collector. Both require explicit enabled, retention and expected revision: null creates only when absent; an integer updates only that exact current revision. Conflicts return source_changed.

The following synthetic file is passed to bun run history:capture observation-configure /private/observation.json:

{
  "organizationId": "00000000-0000-4000-8000-000000000001",
  "expectedRevision": null,
  "observationPolicy": {
    "schemaVersion": 1,
    "organizationId": "00000000-0000-4000-8000-000000000001",
    "integrationId": "00000000-0000-4000-8000-000000000002",
    "enabled": false,
    "retentionDays": 90,
    "bindings": [{ "surface": "mcp", "operation": "list_tools", "content": ["response_body"] }]
  }
}

Bindings use mcp, cli, git or action with exact operation names. Content selections are request_arguments, response_body, returned_files; an empty selection retains metadata only. Custom MCP read bindings additionally require the exact existing reviewed contractHash; saving history settings does not review or authorize a tool. Gateway hooks record the actual tool contract. Native CLI/Git bindings reuse the existing integration’s grants; action evidence requires its real succeeded receipt and execution owner. Backend-owned research/metrics are not admitted through a fake integration; their authority and capture hooks remain follow-up work.

For run-configure, the JSON uses organizationId, expectedRevision and runInputPolicy: {schemaVersion: 1, organizationId, enabled, retentionDays, content}. Run content is selected from prompt, manifest, hydrated_files, execution_events. The last selection independently opts in to private worker execution capture; it is absent from existing policies and does not grant upstream tool access. Enabled run policies need at least one selection. Files are not fetched when hydration is unselected. Acquisition pins its policy revision; a later change rejects publication. Missing required input classes remain explicit incomplete coverage.

bun run history:capture policies /private/organization.json reports configuration only: independent policies/revisions, effective legacy overrides and the global recording flag. It does not establish source connectivity, completed capture, path coverage or live acceptance. No raw payloads, source configuration or credentials are included in that report.

An independent row, even disabled, overrides legacy recording. If none exists, the current legacy policy continues to control its existing hooks; there is no automatic migration or dual recording. Scheduled collection remains unchanged, including existing saved search schedules. The planned CP1b cutover must explicitly migrate consent and suspend proactive search operations; this release must not be presented as completing that cutover.

V2 archives bind the business/source or real task/run/chat/message owner. Initial inputs with zero integrations are valid only with a checked run owner. Restore rechecks current permissions and ownership after reading encrypted bytes; stopping recording alone does not revoke old archives. Reversible Trash does not revoke private operator audit history, while physical owner deletion, foreign ownership, organization deactivation or changed source permissions deny access. Ordinary application visibility and replay-case eligibility remain separate checks.

Publication serializes history policy/archive mutations, then checks current source/owner and policy revision in the insert transaction. Object uploads occur outside that transaction and remain journaled for cleanup if publication is rejected. Read-only database sessions can verify archives. V1 reads remain supported, and every present unsupported formatVersion is rejected. After any V2 archive exists, rollback must retain this version check or disable all archive reads. Disabling new recording alone does not make an old permissive reader safe.

Connector collection boundaries

For Gmail gmail_messages, select a saved query, a non-empty labelIds array, or both. When both are supplied, every page must match the query and all selected labels; neither filter is dropped during pagination. An empty selection is rejected instead of exporting the mailbox.

Gmail labels each business keeps

The nightly Gmail copy is a workspace_gmail_changes feed per label, so each business keeps its own labels in its own capture policy; nothing is shared between businesses. A feed’s labelIds selects messages carrying all of its labels, so keep one label per feed: a message in any chosen label is then kept. Without a choice the seed proposes the whole inbox.

  1. List the mailbox’s labels with their message counts (names and counts only, never a message): bun run history:capture gmail-labels /private/history-config.json with organizationId and integrationId. fits: false marks a label holding more messages than one trial can load (1,500).
  2. Seed with the chosen label ids, "gmailLabelIds": ["Label_…", "Label_…"], review the proposal, then configure it as usual. To change an existing policy, replace its workspace_gmail_changes resources the same way and configure; other feeds are unchanged.

A label too large for a trial is skipped after one request each night, with limit_exceeded for that feed, instead of being downloaded in full and never completing; the business’s other feeds still run. Spam and Trash can’t be chosen: Gmail leaves them out of its lists, so a feed of either would look complete and empty. Labels may overlap. When a message is in two chosen labels and changed between the two feeds’ captures (read, say), a trial uses the latest version captured before its cutoff for both, and lists the message under a label only while that version still carries it. To keep only some messages, such as alerts by subject, a Gmail filter that applies a label is the selection; the copy then keeps that label.

The reviewed operation registry lives beside the capture adapters. It is an allowlist, not a generic HTTP, SQL, CLI, or agent-tool dispatcher.

ConnectorPreserved scope and main limitation
MongoDB AtlasSelected cluster native backup identity and metadata. Requires management access and sufficient retention. Ordinary collection reads do not become an atomic backup.
Upstash RedisSelected database native backup identity and metadata. Without a provider retention guarantee or retained RDB, a backup name alone cannot satisfy 90-day preservation.
Lemon SqueezySelected store’s paginated billing objects. Mutable fields are observed values, not reconstructed historical subscription state.
CrispSelected website’s conversations/messages, people, and helpdesk content. Reporting access must be configured; update-date filters are not historical state.
GitHubSelected repository refs, Git trees/blobs, issues, pull requests, comments, reviews, and workflow runs. Mutable metadata requires retained observations.
PostHogSelected project’s events, people, dashboards, insights, and definitions. Event time and ingestion time must remain distinct; current people data is not a historical profile.
SocialKit AdminExplicit saved report queries and actual reads. Responses cover those arguments, not arbitrary future queries.
XReviewed reads for selected accounts/posts/queries. Metrics and relationships remain dated observations.
ExaSaved searches/content requests; historical requests require snapshotAsOf and account support. Missing historical content is a gap, never a current-page replacement.
Google WorkspaceExplicit selected files, documents, messages, calendars, sheets, slides, and permission reads; task lists, selected forms with their responses, and transcripts and participants of meetings the connected user organized. The collector does not export the entire connected account.
AWSReviewed resource, log, and metric reads within selected account/resource scope. Arbitrary scripts are recorded only when an agent actually executes them.

Native backup readiness and source retention must be checked independently from database read access. The encrypted native management configuration must include fullSourceApproved: true only after confirming that the entire Atlas cluster or Redis database belongs to the approved business scope. A selected MongoDB collection list or Redis key prefix does not authorize a whole-source backup. Without that confirmation, native capture and imports remain blocked; a scoped export/restore adapter is required for shared sources. Upstash daily backup creation is disabled because its management API does not prove 90-day retention or provide an automated RDB export path. Explicit existing backup IDs and private RDB imports are supported; automatic daily Redis preservation remains unverified. A native backup cannot be declared indefinitely pinned merely by retaining its metadata. Export or extend its owned backup before promising preservation beyond the provider expiry. Atlas capture on dedicated clusters records configured PITR support and the configured restore-window length when exposed; these fields are not proof that every instant in that window is currently restorable. Real restore validation belongs in isolated disposable targets; no capture operation restores over a source.

New daily captures require historyArchiveS3 in the private stack configuration. The stack emits HISTORY_ARCHIVE_S3 only into backend environments. Configure the existing private S3 bucket and region with a dedicated archive identity, not a personal AWS identity:

{
  "historyArchiveS3": {
    "bucket": "example-private-history",
    "region": "us-east-1",
    "accessKeyId": "replace-with-archive-identity",
    "secretAccessKey": "replace-with-private-secret"
  }
}

New history keys include history/s3/<bucket>/<region>/ before the immutable ID/hash. The archive writer encrypts each bounded object in memory and writes directly to S3; no local durable copy is created. Legacy keys retain their original object store, including when verifying old frozen model inputs. Configuration changes cannot redirect a saved reference to a different bucket or region. Missing S3 configuration, objects or access fail explicitly without local fallback. Preserve the archive encryption key in the private recovery backup. Agent containers receive no archive credentials.

Use a private encrypted bucket, block public access, and scope the archive identity to the approved organization’s organizations/<organizationId>/history/s3/ prefix. Reads require s3:GetObject, writes s3:PutObject, and dependency-aware cleanup s3:DeleteObject; do not grant account-wide access. The backend owns 90-day retention and pin protection: never apply current-object expiration to this prefix. On a versioned bucket, configure noncurrent-version expiration for this dedicated prefix so deletion of an unpinned object does not leave billed versions forever. Object keys are immutable; noncurrent versions are not the pin mechanism. Preserve the bucket/region mapping during recovery.

Readable daily exports fetch only frozen archive objects. Backup-based exports keep application services isolated; when their frozen configuration names S3 archives, only the exporter receives archive configuration and outbound access. No provider collection or agent execution is started. For a rotated archive identity, scripts/history_export.py --archive-credentials <private-json> accepts current credentials only for the same frozen bucket and region; it does not rewrite the backup manifest. Prefer a read-only archive identity for exports. Temporary export/restore files are removed after verified delivery; the local disk is not a 90-day archive. Existing manually requested export outputs remain under operator control.

For Flex, set managementCredential.clusterType to flex, with the exact groupId and clusterName. Use clientId and clientSecret for unattended service-account authentication; the older accessToken option remains available for short-lived operator checks. Provide exactly one authentication method. Tokens are cached only in process memory and renewed before expiry; credentials and signed download links never enter archives, cursors or diagnostics.

The Flex collector freezes the newest completed, unexpired snapshot no more than 36 hours old (or the explicit backupId), checks it against the connected Mongo hostname, and downloads up to 2 MiB per work unit. It preserves the provider’s start, finish and scheduled timestamps and Mongo version. Requests stay on reviewed MongoDB/AWS download origins and never create a new snapshot, restore a cluster or change its plan. Source metadata and authorization are rechecked between parts.

Each part retains its offset, total size, SHA-256 and native bytes in encrypted archive storage. Part progress advances only with the existing collection transaction. Atlas may omit an ETag; the exact snapshot, download job and hashed download URL remain fixed instead. An expired or changed grant after partial download requires a new collection attempt; bytes from separate grants are never combined. Missing ranges, changed sizes, missing parts or unavailable bytes remain explicit failures. The existing total collection limits and retention/pinning rules apply to these owned objects.

A dedicated cluster (M10 and above) is copied by reading it directly instead: give the policy a mongodb_database resource, "arguments": { "database": "<name>" }. Each night’s collection reads every ordinary collection of that database in full, in _id order, with the integration’s own read-only connection string, from a secondary over compressed connections. One night therefore holds the whole database; nothing depends on an earlier night. Each page holds one collection’s next documents as their stored BSON bytes, gzip-compressed (at most 8 MiB per page), in the format mongodump writes a collection’s .bson file, so mongorestore loads them with every type intact and bsondump prints them as JSON. A collection’s first page also keeps its index definitions, and each page records its document count and SHA-256 digests of its first and last _id; an _id can be a session or API token and page metadata stays in the readable export, so only the private resume cursor holds the value itself, and a rerun resumes after the last saved document. Documents are kept whole, like a backup, so the policy needs the same whole-source approval (managementCredential.fullSourceApproved) as atlas_backup. That approval names one Atlas project and cluster: every page first asks Atlas’s management API for that cluster’s SRV host and refuses (forbidden_source) an integration connection string for any other cluster, so reconnecting the integration elsewhere never carries the approval along. Collections are read one after another over several minutes, so the copy is observation_preserved, not one point in time. Time series collections and a collection whose _id values have different BSON types cannot be paged this way and are reported (unsupported_operation, incomplete_pagination) instead of half copied. On 17 November a trial against SocialKit’s production database (43 collections, 5.1 million documents, 4.6 GB) read about 50 MB per page in about 11 seconds from India; a full night is about 160 pages, 30 minutes and 560 MB compressed. Atlas’s own snapshot download suited this badly: a 5.3 GB snapshot arrived at about 1 MB/s through an hour-long link, stalled twice and never finished (decision D108). Without such a resource, a dedicated cluster’s atlas_backup keeps the earlier behavior: it creates its own on-demand snapshot and retains only its identity and metadata, not the bytes.

A management API failure is reported by what it means, not as internal_error: settings that no longer match the cluster type (a Flex cluster upgraded to dedicated, or the reverse) and rejected credentials as needs_configuration, a missing role (403, or Atlas’s 401 USER_UNAUTHORIZED) as missing_permission, 404 as missing_source, 429 as rate_limited and server errors as source_unavailable; only the last two are retried.

Flex has no PITR and cannot schedule a new backup for the daily workflow’s start time. Coverage is observation_preserved, with provider backup timing retained separately; requestedAsOf is rejected instead of claiming arbitrary historical state. Daily exports include the original native parts and their reconstruction metadata. They do not turn physical Mongo files into JSON or start a database. Exa historical content retrieval pins exact URLs with snapshotAsOf; account capability and missing pages are checked during capture. Historical search results remain observations because archived page content does not establish historical search ranking. Published-date filters alone prove neither.

GitHub capture retains objects reachable from the selected current refs’ commits and trees. It does not export full commit ancestry; submodule repositories and Git LFS payloads remain explicit gaps. Missing commit ancestry is reported as missing_history. Crisp helpdesk capture follows selected article listings through nested directories and retains the article bodies. Selected Gmail queries and messages retain full message contents and referenced attachments. Attachment reads remain bound to the selected message identity; missing bytes or more than 2,000 MIME parts produce an explicit gap instead of a silently incomplete message.

Execution and failure behavior

createHistoryCaptureService coordinates readiness, bounded collection, immutable verification, historical selection, recording, and retention cleanup. PostgreSQL jobs retain the policy revision, page cursor, counters, archive dependencies, and expiring lease. Organization-level locking limits concurrent capture to two integrations, with one active job per integration. Failed work resumes its saved cursor; a changed policy invalidates the old job rather than silently changing its scope.

The backend journals each intended object before upload, then persists a page and its cursor progress in one transaction after verifying the stored bytes. Unreferenced upload journals become eligible for cleanup after 24 hours, so a crash between upload and publication does not leave bytes without a cleanup path. A stale lease cannot publish progress. Successfully retained connector data survives failures elsewhere; overall coverage remains incomplete when any requested source has a gap. Deleting an organization removes its archive records and access, but preserves the minimal object journal until the retention worker deletes the encrypted bytes. A database trigger prevents new journals for missing organizations. Cleanup also discovers deleted owners; it does not require restoring the organization or granting historical read access.

Passive recording covers integration MCP calls, Workspace CLI output/files, Git reads, executed-action results, and initial agent context. A recording failure does not change a successful business operation into a failed operation. It creates a safe coverage diagnostic where storage is available and emits a classified log when persistence itself fails. Logs must not include response bodies, arguments, credentials, or arbitrary exception messages.

Capture is opt-in through HISTORY_CAPTURE_ENABLED and enabled organization policies. Recovery mode keeps provider execution disabled. Daily collection must not invoke the full-instance backup flow, which drains and pauses a running installation.

Retention, selection, and validation

Cleanup considers archive dependencies as well as pins. A retained world snapshot keeps its referenced connector manifests and page data. Pinning and cleanup are serialized; once deletion owns an archive, new pins or dependency references fail. Cleanup only deletes archive-owned objects. Provider retention is a separate promise and must not be inferred from the local expiry field.

Historical selection freezes source references and canonical hashes. JSON keys are canonicalized; ordered arrays and decimal strings retain their meaning. Request JSON is limited to 256 KiB and 16 levels; canonical manifest JSON has a separate 16 MiB budget. Projected snapshots retain selectedFields, so partial records cannot be mistaken for complete records. Missing bytes or revoked access produce a failure instead of replacement evidence. Repeating a selection from the same frozen source references must preserve the resulting manifest hash.

Focused tests cover strict contracts, tenant ownership, authorization changes, immutable archives, lease recovery, pagination and request limits, stale writers, dependency retention, and provider faults. PostgreSQL tests require TEST_DATABASE_URL pointing to a disposable database on localhost; they never create fixtures in the running business.

The opt-in Redis roundtrip test requires local redis-server and redis-cli binaries:

TEST_HISTORY_REDIS=1 bun test apps/backend/tests/services/history-redis-restore.test.ts

It starts two disposable Unix-socket instances, imports a synthetic RDB through the real import reader, and checks Redis value types, decimal strings, absolute expiry times, and independent mutations. This validates local RDB preservation; it does not establish that an operator-supplied file belongs to a historical provider backup, or freeze Redis’s runtime clock. MongoDB native restore acceptance requires a separately provisioned isolated restore target and is not established by metadata-reader tests.

Integration status must distinguish implemented capture support from activated and verified captures. Missing management credentials, provider capability, scope, or restore evidence remains an explicit acceptance gap. A replay runner, mutable isolated environments, arbitrary-query replay adapters, and a full-day external event timeline are follow-up work.

Business identity in archived evidence

Each business uses its own Oblive organization. New connector/world snapshots and recorded bodies/envelopes include business: { id, name, observedAt }, derived by the server. The ID equals organizationId; integrationId distinguishes the connection within that organization. The copied name remains unchanged after a rename. observedAt dates the metadata lookup, not historical state at requestedAsOf. Never use a label to authorize access or as pre-cutoff agent evidence when it was observed later. Existing archives may omit this field; readers do not invent historical names. Selecting the same world inputs reuses the first stored label and hash. No migration or separate business registry is required. This does not mean all business sources have been captured.

Durable MCP call history

MCP reads with an enabled independent observation binding now reserve an occurrence before the provider call. occurrence.id identifies that invocation; producerId and sequence order entry into one backend process. Concurrent producers have no invented total order. Archive commit order and request hashes are not call order.

The metadata journal separates intent (started), actual callback outcome (outcome), storage allocation, archive publication, recording failure and interruption. An outcome records whether provider dispatch occurred; a fresh authorization rejection has dispatched: false. Returned MCP isError responses differ from throws, cancellations and timeouts. Starts prove intent only. Late evidence appends a new fact and leaves earlier interruption/failure facts visible. An archived receipt commits atomically with archive metadata. Existing actions and runs still own external execution/retry/reconciliation; history never reruns a provider operation.

Known credentials are removed before an explicitly selected error_details message is shortened. This new content class is opt-in; existing grants do not silently acquire thrown messages or stacks. Thrown/cancelled/timed-out evidence is incomplete and cannot satisfy successful exact-request replay. Returned provider-error responses can still be replayed as returned responses.

History waiting shares a 5-second additional budget per call, excluding provider execution. There are 8 active recording slots per process and 2 per organization; saturation skips capture without a queue. A timed-out operation keeps its slot until actual history I/O settles. Late start commits retain the observed outcome but do not acquire payload after the wait budget is spent. Separate optional health writes have one 100-ms total wait and 8 active groups per process.

Before selected content is sorted, parsed or copied, admission bounds depth, nodes, strings and containers. Decoded files and embedded JSON share the same processing counters. Limits are 16,384 nodes, depth 24, 1,024 keys per object, 512 KiB code units per string, 1 MiB cumulative string code units, 16 files, 1 MiB per file and 16 MiB total file bytes. Omitted content is never inspected. These are bounded synchronous inputs, not a hard CPU/memory preemption guarantee.

PostgreSQL owns UTC-hour organization and integration reservations across processes. Limits are 10,000/2,000 starts, 256/64 MiB payload allocation and 40,000/8,000 object operations respectively. Allocation uses actual sanitized bytes plus a conservative 1-MiB metadata allowance and 16 + 8 * fileCount object operations. The same occurrence cannot charge twice or move to a new hour. Reservations are not refunded after failures. The allowance means the source byte ceiling can limit a small-record source to fewer than 64 archives/hour; measure real scope/volume before activation and review any quota change. Safe diagnostics are coalesced and capacity-bounded.

Metadata maintenance rechecks current run/message ownership under row locks, records interrupted intent without asserting success, and never invokes a provider. It continues when new recording is disabled; recovery mode suppresses maintenance writes. Retention keeps start records until their child events have been removed. Journal methods append rather than update; direct privileged SQL updates are not prevented by a new database trigger. Existing payload/object immutability rules remain authoritative for encrypted evidence.

firstAvailableAt is the database wall clock at insertion, after lock waits. It is not an exact PostgreSQL commit-visibility timestamp. Future cutoff-safe dataset builders must use retained membership/availability evidence and must not infer pre-cutoff knowledge from this field alone. An archived event is a historical receipt: payloadAvailability describes current metadata availability, while verify separately checks actual retained bytes and authority.

Legacy-only policy calls keep their earlier completed-call path. Workspace and Git upload-pack now share the lifecycle for independently configured read policies, with selected settlement projection inside the shared wait budget. Projection slots and Workspace directory lifetime survive timeouts until actual I/O settles. OAuth-refresh waits are followed by fresh native authorization. Analytics/backend research, action-disposition linking and complete run tracing still require their planned contracts. Deploy compatible readers/writers together before enabling the stack.

The scheduled capability registry exhaustively accounts for catalog connectors and separates raw collection from existing metric reuse. Legacy Exa/X search archive schemas remain readable, but those operations fail scheduled configuration, claim, dispatch and publication. Data-page retry cursors remain at the committed page on storage failure; only approved native no-artifact reconciliation checkpoints advance separately. Retry-After delays are honored without replacing existing backoff.

Archive publication queues the existing evidence_availability durability protocol with source kind history. Confirmation runs in a different transaction and compares immutable archive identity. The existing scheduler recovers pending confirmation; createdAt, source event dates and occurrence insert timestamps are not substitutes. Older strict source-kind readers are not compatible rollback targets once these records are emitted.

services/history/overview.service.ts builds closed-UTC-day partial evidence packets through existing world archive publication. Optional observations and daily metadata retain exact membership, times, declarations, exclusions and bounds. Source completion and confirmed availability must both precede cutoff. Limits are 2,000 scanned rows, 200 members, 1,999 dependency nodes plus root, 4,096 objects and 64 MiB declared retained verification bytes. Missing required sources and unscanned remainder stay explicit. Every packet remains partial; future internal-state/trajectory fidelity is not inferred.

Private commands overview, show, content and daily provide inspection. Overview has lossless PostgreSQL timestamp cursors and live-census semantics. Content reads an explicitly listed verified object, at most 1 MiB output, and rechecks hash/authority after read. No public HTTP or installed oblivectl changes apply. The deferred replay reader must reject unsupported daily worlds rather than silently ignoring observations or treating partial packets as complete benchmark inputs.

Background analytical MCP reads

Database, Crisp MCP and Reach MCP analytics can preserve their actual MCP call results before JSON parsing, error replacement or conversion to metric totals. Retention requires an enabled independent MCP operation/content binding; a legacy scheduled policy does not authorize this new raw-data path. Crisp REST conversation reporting, other HTTP/SDK analytical adapters, tool discovery and research remain outside this slice. Calls by raw history collectors and connection checks do not become nested analytical observations.

The recorded analytical identity contains a generation digest, adapter version, hashed work lease and its expiry. Collection also records source, checkpoint version, phase and the preallocated batch UUID. Raw lease tokens and provider credentials are only transient sanitizer inputs. The source integration and current background work are checked before each actual provider call, independently of recording admission. Admission and archive publication check the same owner. Historical readback checks preserved integrity and current integration access; a completed work lease need not stay live.

The existing analytical receipt uses the same batch UUID if publication succeeds. It proves metric publication, not that every raw call was retained. Discovery and failures need not have a collection receipt. A returned MCP result can still fail later JSON parsing or contain a nested provider error; keep those stages distinct when inspecting an incident.

Optional recording adds at most its five-second wait per call, plus mandatory authority checks; storage failure does not make analytical publication depend on history. Existing work-unit budgets can end a batch earlier, leaving a continuation. Unfinished analytical starts expire no later than the captured lease expiry (currently 90 seconds from claim). Recovery uses the existing bounded deadline scan and classifies a known lost owner then; it does not promise immediate detection of a replaced token or checkpoint. Capture volume, quota and provider behavior still require live acceptance.

Use overview, show and content to inspect retained evidence. show exposes the safe work identity under manifest.analytical; read the body only through its exact listed object key. The shared operator-validation plan describes a tenant-scoped query joining its batch UUID to the existing analytical_receipt. Partial daily packets continue to report remaining raw-acquisition coverage gaps.

Scheduled collection progress

The existing collection job remains the only owner of scheduling, continuation and retries. Scheduled work now saves an encrypted collection_attempt before each work unit and confirms its availability in a separate transaction before calling the provider. A work unit can contain several bounded provider requests. Failure to save or confirm its start prevents provider dispatch. The active lease, source permissions and policy are checked again before dispatch.

Each job has a backend-assigned generation number; pages and retries keep it. Immutable events have a sequence, an explicit terminal value and one entry for every selected resource. Resources record exact identity and contract hashes and reference the resulting connector archives. This is separate from the actual-use MCP call journal and does not add provider calls or another scheduler.

Content archives, progress evidence and the saved continuation commit together. Starts, successful completion, partial progress, failure and interruption remain distinct. Maintenance records abandoned work without calling a provider. Final partial outcomes are not treated as abandoned. Jobs past their retention deadline are marked incomplete without publishing an already-expired object; they cannot block a new scheduled refresh or unrelated retention cleanup.

A storage outage or revoked publication authority can leave only an earlier unfinished event. Recording is not lossless. Total job/organization collection budgets and provider coverage remain separate work. No source is enabled by these schema changes.

Daily Insights publication copies

A capture policy can also keep a daily copy of Insights. Set the optional insights flag to true. It is off when absent, so existing policies are unchanged. Turning it on for a business needs the project owner’s approval.

Collection itself never freezes Insights. A separate observationbeat stage looks for collection jobs whose policy has the flag on, that started within the last six hours and that have no copy yet. On each tick it freezes at most one, the oldest, under a 40-second deadline. It writes one history archive of kind insight_publication per job. The archive id comes from the organization and the job, so a retry or a concurrent freeze returns the same archive and never writes a second one. A failed freeze writes no archive. It is retried on a later tick until six hours after the job started; after that the day has no copy.

The copy is read in one consistent database transaction. It holds the organization-observations revision, the definition state, the active built-in metric definitions for the integration’s connector, the source checkpoints without leases or pending reports, and the live segment rows. Sources that live access would not allow are left out: one collected with an old credential, or one whose coverage reason is missing_permission. Each segment file is copied into the archive after its size and SHA-256 are checked.

Collection receipts are read newest first, in pages, and only those that can change an answer are kept. Receipts with a snapshot id or a report window are always kept. Any other receipt is only used for coverage, where the newest receipt that spans a period wins, so a receipt inside a newer receipt’s coverage is dropped. The kept receipts are stored as receipts.jsonl. One copy holds at most 48 MiB of segment files and 10,000 kept receipts; a larger copy fails with limit_exceeded and writes nothing.

The payload is validated by insightPublicationArchiveSchema. It records the job’s UTC day, a fixed dayTimezone of UTC, the job’s captureStartedAt, the database frozenAt time, the integration’s history permissions, each definition’s hash and each source’s checkpoint coverage. Reading the copy requires the integration’s permissions unchanged, as for connector archives. Like every archive, it gets its own evidence-availability record, and its confirmedAt is the time the copy became available. It expires retentionDays after frozenAt, unless a pin, a dependency or a replay hold keeps it.

A failed copy is logged without its contents. It does not change the collection job, its pages, gaps or retries. services/insight-publication.service.ts answers Insights list() and query() from one verified copy, through the live query code. Current access still applies: a source the current authority no longer allows is hidden, and before an answer is returned the live access check runs again. The reader stores no query receipt. Replay uses the same reader over several copies; see the replay environments guide.

Business-day copies after replays:setup

A business that completed replays:setup gets Insights copies without a collection policy. A second observationbeat stage, gated like the first on historyCaptureEnabled and recovery mode, lists organizations with a completed setup event. For each, it takes the business day that ended last in UTC. If that day ended less than six hours ago, it freezes one copy for each enabled integration that feeds Insights, at most one copy per tick. After six hours the day has no copy, and a later day is never backdated. Organization timezone settings do not affect these copies.

The payload has trigger: "business_day", the UTC day, dayTimezone: "UTC" and dayEndedAt in place of captureJobId and captureStartedAt. The schema checks that dayEndedAt is the next midnight in the recorded timezone and that frozenAt is not before it. The archive id comes from the organization, integration, day and time zone, so a retry returns the same archive. The copy expires after the run-input policy’s retentionDays, or 90 days without one.

A day already has its copy when any Insights copy of that integration was frozen at or after the day ended, or when a collection job with insights on started since then, since that job takes its own copy. A collection copy frozen before the day ended does not count. In the other order, a collection job that starts within six hours after a day ended, once that day’s copy exists, takes no second copy. A failure is logged and retried five minutes later, within the same six hours. Readers treat both kinds alike: replay takes the newest copy confirmed before the cutoff.

Managed AWS response formats

The reviewed AWS collector accepts the usual JSON result and the managed EKS server’s Python-style literal response text. It decodes only bounded JSON-shaped literals to validate source identity, counts, errors and pagination; it never evaluates code. The original MCP response remains in the archive and replay response. Expressions, unsupported syntax, duplicate keys and oversized/deep representations fail explicitly. A successful prose message alone does not establish complete data. Selected Kubernetes events are observations of the provider’s retained events, not a full AWS backup.

PostHog event windows

Event collection sends an explicit after/before range. A configured historical window wins; otherwise it uses the 24 hours ending at the saved collection generation’s start. Resumed pages reuse that boundary even after a process restart. Provider cursors may express the same lower boundary with a different UTC offset, but cannot expand the window or change selected filters. Descending event boundaries preserve up to nanosecond precision.

This is a bounded observation of events currently returned for that interval, not a complete project export or proof of historical availability. Late-ingested events outside the selected window require a separate, explicitly dated collection. Keep event and ingestion times distinct. An older incomplete collection remains incomplete; do not combine its pages with a new window.

SocialKit selected reads and Apollo

SocialKit Admin’s reviewed selected-read operations include get_billing_observations. Request logs use the source’s nested page, limit, total and totalPages contract with a fixed UTC window. Without explicit from/to, days selects completed UTC days ending immediately before the collection generation’s UTC date. This avoids paging over the current day’s filling log buffer; it does not guarantee that older records cannot change. Retries reuse the generation’s dates, and explicit windows and saved continuation windows retain their original meaning. The collector retains each page and refuses inconsistent continuation rather than treating the first page as complete. Multi-page reads remain non-atomic observations. Pagination by itself does not make successfully retained observations incomplete; strict historical selection still rejects these as exact point-in-time state. Billing accepts an inclusive range of at most 366 UTC dates, validates version/completeness metadata and preserves missing days as gaps. A provider observation timestamp does not backdate Oblive’s own confirmed availability.

Apollo is used for people/lead search and enrichment. Retain permitted actual MCP invocations under independent recording consent; do not schedule proactive enumeration. Existing processing limits remain in place. These changes do not activate sources or establish live account parity.

X mentions request public post fields and public metrics. Private organic/non-public metrics belong to the post’s author; requesting them for other authors’ mentions causes partial permission errors. Owned-post and analytics reads retain their existing metric fields. Other provider errors and incomplete pagination still prevent a complete capture.

Analytical and backend response recording

Analytical HTTP/SDK reads use independent http and sdk observation bindings with operation analytical_read. Existing MCP or collection consent does not enable these bindings. Retention records the decoded response before metric normalization; intentionally discarded malformed/error bodies and responses beyond existing storage limits are not lossless wire captures. Every real provider dispatch still checks the current analytical work lease, even when recording is disabled.

Authenticated business metrics responses use source backend, operation business_metrics.read, and the configured business as their owner. The exact returned JSON envelope, including cached responses and public errors, uses the existing encrypted observation archive. The real GA4 integration remains an access dependency; no synthetic integration is created.

Use the private history:capture backend-binding command with {organizationId,businessId} to read current non-secret binding hashes. The optional runInputPolicy.backendMetrics section independently selects enabled business bindings and retained request/response/error content. Apply changes through run-configure with the expected policy revision, preserving other policy sections. A token/configuration change needs an authorized binding refresh; current permissions are checked on retained reads.

A required business packet can select a served response with an external requirement:

{
  "kind": "backend",
  "businessId": "socialkit",
  "requestSha256": "<64-character hash of the exact recorded request>"
}

This is served-response evidence, not proof that all provider data was collected. Failed or interrupted newer reads block an older successful selection. An unfinished occurrence has no retained request hash, so it may conservatively block another query for the same business. Selection uses the strict cutoff; frozen packet reads do not select later evidence. Backend/HTTP/SDK executable replay adapters are not supplied by this recording increment.

Internal business state revisions

The organization run-input policy can separately opt into internalState with enabled, selected scopes (organization, profile, task_spec, profile_memory) and retentionDays. It defaults off, requires global history capture, and stays disabled in recovery mode. Disabling the policy or removing a scope also revokes retained reads for that scope.

After configuration, establish a prospective baseline for each owner using bun run history:capture internal-checkpoint <configuration.json>. The configuration contains organizationId and internalStateOwner: { "scope": "organization", "id": "<organization UUID>" } (or the selected profile/task UUID). This records the current state at checkpoint time without backdating or changing the source. Subsequent relevant mutations append revisions atomically. Missing baselines remain missing; enabling a policy does not assert historical completeness.

Private packets can select { "kind": "internal_state", "owner": { "scope": "profile", "id": "<profile UUID>" } }. Selection uses post-commit confirmation before the cutoff and current permissions. Org/profile configuration excludes credential and storage plumbing. Canonical learned memory includes evidence references and bounded learning metadata. Task projections explicitly mark omitted manual values or acceptance arguments; these produce partial packet slots. Existing Context goals/priorities retain their existing publication history. Arbitrary memory file writes are outside this mutation recorder. Formal goal and KPI tables are separate operational state and are not covered by these four internal revision scopes. Their presence in the application must not be interpreted as historical capture.

Retained content expires even if a packet is pinned. Expired owner markers prevent silently selecting older state, while the existing scheduler removes expired content. Organization deletion uses bounded, delete-specific contention recovery; persistent contention is an explicit failure. Raw SQL deletion requires equivalent handling and is not guaranteed free of lock cycles.

Export a frozen backup as readable integration files

scripts/history_export.py is an operator command for a private S3 instance backup. It downloads the exact versioned manifest, installation configuration and three data volumes, verifies checksums, and restores PostgreSQL/Garage into fresh temporary volumes on an internal Docker network. It starts no backend server, agents, scheduler, Redis or provider collector. Matching retained Docker images are reused or downloaded by immutable identity; the Docker CPU architecture must match the backup. Install Python 3.11+, AWS CLI and Docker Compose. Run from a checkout containing this exporter.

Prepare a private file containing the current authorization database URL, reachable from the authorization helper (on Docker Desktop, normally host.docker.internal and the published database port). The offline reader reaches a separate authenticated helper that accepts only integration IDs and returns current source fingerprints. Only this helper has an outbound network and the current database credential; it has no archived-data mounts. No ports are published. Its database connection is only used for organization/source authorization queries, with database read-only mode and a statement timeout. Never commit the file or include it in the recipient ZIP. The restored database supplies historical content; current source identity must still agree before and after every archive read. A revoked or changed source is reported as unavailable, never replaced.

python3 scripts/history_export.py \
  --bucket PRIVATE_BACKUP_BUCKET --account AWS_ACCOUNT_ID --region us-east-1 \
  --profile OPERATOR_PROFILE --snapshot 2026-10-29T14-19-03.817Z \
  --organization ORGANIZATION_UUID --authority-url-file /private/source-authority-url \
  --output /private/new-export-directory --publish

The output directory must be new. An optional --download-cache /private/cache can reuse artifacts named by their full SHA-256; every cached file is size/hash verified against the freshly verified S3 manifest. Cached backups are private and are not included in the ZIP. Omit --publish for local verification. Allow space for compressed archives, restored volumes and the readable ZIP. The command cleans up its temporary services, volumes and working files; it never deletes the source backup or any existing instance volume. Publication uses exports/<snapshot>/<organization>/<zip-sha256>.zip, server-side encryption and a versioned object reference. It downloads the uploaded version again and verifies its full SHA-256. export-report.json records the result. download-link.txt holds a private, time-limited download URL (requested lifetime 24 hours; signing credential expiry can shorten it). Share that link through an authorized channel, or use read-only AWS access to the exported object. No receiver-side key or runtime installation is needed. The command never prints the URL or credentials to logs.

The ZIP contains README.md, manifest.json, coverage.json and integration folders. The manifest lists every output file’s checksum and provenance. Each archive.json maps the capture metadata and original object references to readable local JSON/text/binary files. Original bytes and decimal strings are preserved. Repeated pages, observations and collection attempts are retained separately. The census pages through all retained integration-owned connector/page/collection-attempt records; it does not stop at the ordinary inspector’s first page or exclude unfinished collections.

The scope is retained integration evidence, not the complete application database, agent memory, prompts or a reconstructed provider database. Capture redactions stay in place; business/customer content is still private. Native backup references that require provider verification cannot be exported offline as restored data. Missing, damaged or unauthorized archives are explicit export failures, while valid partial captures remain available. exportComplete means all selected records were readable; coverageComplete remains false because daily observations do not prove complete historical state. The current engineering bounds are 100,000 archives and 10 GiB of output; a limit failure aborts publication instead of truncating.

Business world snapshots, worker execution capture and replay environments retain their own interfaces and authorization rules. The daily S3 sync shares their archive storage; it does not enable replay execution or change a running initiative. Large connector captures use ordered manifest parts; the same verified page resolver supplies capture verification and replay dataset readers.