Introducing a new way to review your PRs.

Read the announcement

tracer-cloud / opensre

The open-source agent for CI/CD reliability.

View on GitHub

25 documents · Updated Nov 23, 2026

docs / state-and-evidence

State, evidence, and file storage

OpenSRE keeps the facts needed for a turn in a shared state model, records the evidence used by investigations, and persists user-owned context so later turns can continue. Local setup data, conversation state, incident data, and optional remote copies have different ownership and safety rules.

State model

The state model gives chat and investigation work a common runtime envelope. It keeps per-turn inputs separate from values that must survive across turns, while still letting pipeline stages share one state shape.

Cross-turn conversation state

MutableAgentState holds the conversation transcript and the last observation that must remain available after a turn ends. It does not hold temporary tool choices or prompt data. When the transcript grows beyond its window, older messages become a leading session summary while recent user and assistant turns stay readable.

References: core/…/agent_state.py• L1-7 core/…/agent_state.py• L22-69 core/…/transcript_window.py• L34-68

Session persistence

Session persistence gives the in-memory conversation a durable record that can be restored after a process ends. The JSONL session store appends conversation entries, tool calls and results, compaction records, and hidden session state to a session tree. Sidecar records stay outside the conversation parent chain so durability and diagnostics do not change the user-visible flow.

Tool execution has a write-ahead boundary. The store records and flushes a bounded tool intent before execution, then records the matching tool call as its commit. An intent without a commit marks an interrupted action for recovery rather than an action to replay. The in-memory store follows the same record contract for short-lived sessions and tests, but its records do not survive process exit.

Both stores make flush idempotent and preserve live goal, task-plan, and pending-choice state when those values change between turns. The durable store can serialize writes from separate processes when scale-out needs it; a lock timeout skips the write instead of corrupting the session file.

The session persistence boundary is:

flowchart LR
    A[Live session state] --> B[Session record contract]
    B --> C[Durable JSONL session tree]
    B --> D[In-memory session records]
    C --> E[Restore after restart]
    D --> F[Ephemeral host or test]

References: core/…/jsonl_store.py• L76-87 core/…/jsonl_store.py• L294-323 core/…/jsonl_store.py• L425-639 core/…/jsonl_store.py• L656-715 core/…/memory.py• L16-34 core/…/memory.py• L227-296 core/…/memory.py• L426-472

Investigation runtime state

AgentState is the flat runtime envelope used by both chat and investigation flows. Named state slices group related facts such as alert input, plans, collected evidence, diagnosis, masking, delivery output, and completed pipeline stages. The model validates defaults and rejects unknown fields so a stage cannot silently introduce an unsupported state value.

Investigation stages normally pass partial updates. Most fields use the newest value, while messages grows by appending. The runtime also records host stage span names in pipeline_steps, which gives the investigation run a small record of its completed stages without changing the flat state shape.

References: core/…/models.py• L38-65 core/…/models.py• L67-139 core/…/runtime_slices.py• L1-14 core/…/runtime_slices.py• L67-88 core/…/updates.py• L11-28

Setup state

Setup state is a prompt-ready view of what the operator has connected and scheduled. It joins the integrations already known by the session with live scheduler facts so the agent can describe the real setup instead of guessing from the conversation.

Setup snapshot

The snapshot reports connected integrations, configured schedules, schedules with a reachable delivery target, and the result of the most recent completed delivery. A missing task store is treated as empty only when the run database has no scheduler history. If history exists, the combined snapshot is incomplete so setup cannot report a known scheduler as empty.

The rendered block is cached for a session. A small fingerprint of the scheduler stores invalidates the cache when a task or delivery changes, including changes first written to the database write-ahead log.

References: infrastructure/setup_state.py• L21-29 infrastructure/setup_state.py• L41-71 infrastructure/setup_state.py• L105-149 infrastructure/setup_state.py• L158-212 infrastructure/…/backlog_status.py• L20-53

Task definition persistence

The task store keeps scheduled task definitions separate from their execution history. A snapshot distinguishes a missing store from unreadable or invalid data, so setup can tell a new empty scheduler from a damaged source. Reads normalize legacy entries before validation. Writes use a lock and an atomic replacement, while an unreadable store is preserved for recovery instead of being silently overwritten.

Schedule identity covers the work, destination, and owning organization rather than display fields or run bookkeeping. Confirming an existing schedule therefore updates its pinned skill revision instead of creating a duplicate. Organization-scoped tasks retain their owner so one organization cannot read another organization's schedules. Removing a task leaves its run history available for diagnosis and prevents its queued work from running; schedule changes wake the scheduler to reload its active jobs.

References: infrastructure/…/task_store.py• L34-75 infrastructure/…/task_store.py• L105-205 infrastructure/…/task_store.py• L221-300 infrastructure/…/task_store.py• L303-366 infrastructure/…/__init__.py• L33-42

Database-backed scheduling storage

The scheduler keeps durable execution state in a SQLite run database under the OpenSRE home. This record links each scheduled fire to its attempts, claim lease, delivery result, per-target outcomes, and generated report so later scheduler work can coordinate safely and explain what happened. The scheduling lifecycle is described with alert intake in Alert intake and scheduling.

Run history and recovery

Each task fire has a unique attempt record. The scheduler first records pending work, then claims it with a time-limited owner lease. An expired lease becomes an abandoned attempt before a new attempt can run, while completion and report writes are accepted only from the current lease owner. This prevents two workers from treating the same scheduled work as active at the same time.

The run record also preserves the target filter and per-destination delivery outcomes. Recovery can therefore retry only the destinations known to have failed instead of widening an uncertain retry to every destination. Setup state reads completed runs by finish time, so it can report the latest delivery outcome even when runs overlap.

References: infrastructure/…/run_store.py• L27-37 infrastructure/…/run_store.py• L164-265 infrastructure/…/run_store.py• L389-458 infrastructure/…/run_store.py• L608-639 infrastructure/setup_state.py• L96-122

Backlog status

Backlog status combines task definitions with run history to describe waiting scheduler work without confusing missing setup with a lost store. It counts pending ticks and expired claims for eligible tasks and reports the oldest waiting age. If the run database cannot be inspected while a missing task store is being checked, the status service raises a storage error rather than claiming that no backlog exists.

References: infrastructure/…/backlog_status.py• L16-53 infrastructure/…/run_store.py• L99-149 infrastructure/…/__init__.py• L3-6

Schema migration boundary

Every scheduler database connection creates or updates the run schema before use. Migrations preserve legacy run history, add fields introduced by newer scheduler behavior, and create indexes for recovery, live-owner checks, and recent history. They run inside one SQLite write transaction.

When another scheduler process is changing the schema, migration waits for a bounded period and then raises if the database remains stuck. Older rows receive a closed target scope by default, which prevents automatic recovery from silently expanding delivery to all targets.

Legacy task entries are normalized before strict task validation. Retired investigation task kinds become manual-loop entries; only a custom investigation with a usable prompt remains enabled. Other retired kinds are disabled with a migration notice so an old schedule cannot run with behavior that no longer exists. Legacy work-item reminders receive an absolute fire time when the work item can be read and its reminder time can be resolved; entries that cannot be resolved remain unchanged for safe follow-up.

References: infrastructure/…/database.py• L19-39 infrastructure/…/migrations.py• L13-75 infrastructure/…/migrations.py• L91-214 infrastructure/…/task_store.py• L168-205 infrastructure/…/legacy_task_migration.py• L30-61 infrastructure/…/legacy_task_migration.py• L64-100

Evidence capture

Evidence connects an agent claim to the tool work that produced it. The investigation state can retain evidence entries, hypotheses, and results, while conversational turns use a bounded gather pass to obtain current read-only facts before the answer stage.

Evidence provenance

An EvidenceEntry is a provenance record for one tool call. It carries a key and data value with optional tool name, arguments, source, timestamp, loop iteration, and confidence. These fields let later stages distinguish observed data from an unsupported statement without prescribing how a vendor stores its result.

EvidenceSource is an open string type. Each integration owns the source names for its tools, so the core does not need a fixed list of vendors. An EvidenceMapper is a tool-owned function that converts raw tool output into citeable report entries and adds them to the shared evidence record. record_evidence_entry stores a source key, label, and optional supporting detail for the report catalog. The first entry for a source wins, while a dedicated catalog reader for that source takes precedence.

When a tool can run more than once in one investigation, unique_evidence_source adds a #N suffix to repeated source keys. This keeps each call as a separate citeable entry instead of silently dropping later results. Keeping the mapping with the tool means vendor knowledge stays at the source boundary rather than in a shared report stage.

References: core/…/evidence.py• L1-21 core/…/evidence.py• L13-22 core/…/evidence.py• L25-48 core/…/evidence.py• L50-69 core/…/runtime_slices.py• L67-88 core/…/models.py• L101-121

Bounded evidence gathering

The evidence gatherer gives a conversational turn access to the same registered investigation tools used by the larger investigation path. It runs a short think, call, and observe cycle, then returns both a compact observation for the answer model and structured tool results for policy decisions.

Gathering is optional and fail-safe. It stops when no usable source or model is available, records unreachable sources for later turns, limits discovery and output size, and returns no gathered evidence when the pass cannot execute a tool. A failed gather therefore falls back to the normal answer path instead of breaking the conversation.

The flow from a user question to grounded answer context is:

flowchart LR
    A[User question] --> B[Resolve available sources]
    B --> C[Bounded tool gather]
    C --> D[Structured tool results]
    C --> E[Compact observation]
    D --> F[Evidence policy]
    E --> G[Grounded answer]
    F --> G

References: core/…/evidence_driver.py• L1-13 core/…/evidence_driver.py• L282-301 core/…/evidence_driver.py• L304-409 core/…/gather_observation.py• L28-43

Evidence result boundary

Gathered evidence keeps raw tool results beside the rendered prompt text. Policy should use the structured results when they exist. The rendered Tool and Result blocks are a compatibility fallback for older callers, so a roster listing or a typed unavailable result is not mistaken for useful evidence.

The report layer builds a catalog from the evidence envelope and maps source names to display IDs such as E1. It uses a specific reader when one exists, then accepts generic entries recorded by tool evidence mappers. Claims receive the IDs and labels for the sources they name, while source names are removed from the final claim shape.

References: core/…/gather_observation.py• L45-107 core/…/gather_observation.py• L110-152 tools/…/evidence_catalog.py• L399-481

Evidence compaction

Compaction reduces noisy integration output before it reaches the model. It preserves counts, time ranges, representative samples, and summary statistics so the agent sees the shape of a large result without receiving every raw item.

Collection limits

High-volume logs, traces, metrics, and invocation results have bounded item counts. Individual log messages and nested trace, metric, or invocation data also have limits. When data is cut, summaries can state how many items were available and how many were returned.

References: infrastructure/…/evidence_compaction.py• L12-18 infrastructure/…/evidence_compaction.py• L20-51 infrastructure/…/evidence_compaction.py• L75-157 infrastructure/…/evidence_compaction.py• L160-208

Log grouping and error taxonomy

Log compaction has two related views. Deduplication groups repeated or near-repeated messages by source and level, then keeps a representative message with its count and first-to-last time range. Error taxonomy groups error logs by broad error type and adds affected components and representative samples. Together these views prevent a repeated failure burst from hiding less common failure types.

References: infrastructure/…/log_compaction.py• L1-21 infrastructure/…/log_compaction.py• L67-91 infrastructure/…/log_compaction.py• L222-246 infrastructure/…/log_compaction.py• L322-348

Metric summaries

Time-series evidence becomes a compact metric record with its labels, point count, first and latest values, minimum and maximum, mean, percentile, trend, and change over the observed window. This gives diagnosis enough context to compare a metric over time without carrying the full series into the prompt.

References: infrastructure/…/metric_summary.py• L87-138 infrastructure/…/metric_summary.py• L141-171 infrastructure/…/metric_summary.py• L206-229

File storage

File storage gives workflows durable local context and an optional user-owned remote mirror. The system separates setup and credential data from conversation and memory data, then applies the active storage scope before it resolves paths.

Local setup persistence

The setup store is a versioned JSON record under the OpenSRE home. It preserves onboarding choices for the local model target, probes, remote endpoints, and remote operations scope. Reads tolerate a missing or malformed file by returning an empty configuration, while writes merge the relevant sections and keep unrelated choices.

The setup store is not a secret store. It records names and choices such as provider, model, authentication method, and environment-variable names. Secret values remain in the separate credential path described in Configuration and security boundaries.

References: config/setup_store.py• L1-27 config/setup_store.py• L30-47 config/setup_store.py• L50-85 config/setup_store.py• L117-205

Remote context mirror

Remote sync is an opt-in mirror for conversation sessions and memory files. It supports pull, push, and two-way sync through one object-store contract, so the workflow can use a cloud bucket or compatible backend without changing how local context is selected.

Sync is additive: a file missing on one side is copied, and a newer copy wins when both sides changed. Two-way sync pulls before it pushes. Downloads use an atomic local replacement, and a dry run can show the planned changes without writing either side.

The normal flow is:

flowchart TD
    A[Load remote-sync settings] --> B{Sync enabled?}
    B -->|No| C[Keep context local]
    B -->|Yes| D[Resolve session and memory roots]
    D --> E[Build configured object store]
    E --> F[Compare local and remote objects]
    F --> G[Pull newer remote files]
    G --> H[Push newer local files]
    H --> I[Return sync report]

References: infrastructure/…/engine.py• L1-18 infrastructure/…/engine.py• L313-365 infrastructure/…/engine.py• L393-437 infrastructure/…/operations.py• L147-187

Storage provider boundary

The sync engine talks to an ObjectStore through four needs: list objects, read an object, write an object, and describe the destination. A provider registry maps the configured provider name to that contract and can add provider-specific setup fields, exposure checks, and upload limits without changing the sync flow.

Azure Blob Storage is one provider behind this boundary. It identifies the storage account from setup or the environment and uses an ambient Azure identity for access. Its remote metadata uses a content MD5 when Azure provides a valid value; when that fingerprint is unavailable, sync can use its time-based comparison instead of an incompatible provider tag.

Remote-sync setup validates the provider and stores only non-secret settings such as the store name, prefix, region, profile, and enabled flag. Ambient credentials remain outside the OpenSRE settings file. Environment values can override saved settings for a one-off run, as described in Configuration resolution and identity.

References: infrastructure/…/contracts.py• L1-7 infrastructure/…/contracts.py• L16-56 infrastructure/…/registry.py• L83-115 infrastructure/…/azure.py• L22-29 infrastructure/…/azure.py• L36-76 infrastructure/…/azure.py• L145-189 infrastructure/…/setup.py• L29-85

Storage safety boundary

Only the sessions and memory roots are eligible for remote sync. Credential and configuration files are denied even if a future path or custom root would otherwise include them. User exclusion patterns can hold back more files, but they cannot widen the set of files that may leave the machine.

Remote sync is for a personal machine. Organization-scoped turns are refused because their history already lives in the shared organization context root and object keys do not include a principal or actor. Public-store checks are best effort and report unknown when a provider cannot prove whether the destination is private.

References: infrastructure/…/syncable.py• L1-12 infrastructure/…/syncable.py• L24-35 infrastructure/…/operations.py• L98-110 infrastructure/…/exposure.py• L1-16 infrastructure/…/registry.py• L192-218

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to AgentStateModel or a state slice must keep defaults, validation, and stage ownership aligned. A field present in only one of these views can disappear at a stage boundary.
  • Changes to transcript limits or summary format must preserve both the recent turn window and the ability to merge an existing leading summary.
  • Changes to session persistence records must keep the JSONL and in-memory stores aligned. Parent links, sidecar records, compaction replacements, and hidden state must restore the same session meaning in both backends.
  • Changes to tool-intent or tool-call persistence must keep the write-ahead intent, durable commit, and recovery boundary aligned. Intent arguments and user text must remain bounded before they enter the session log.
  • Changes to session flush behavior must preserve the single closing leaf and must not lose live goal, task-plan, or pending-choice state after a prior flush.
  • Changes to evidence result shapes must keep structured tool results and rendered observation blocks semantically aligned. Unavailable or discovery-only results must not count as collected evidence.
  • Changes to tool evidence mappers or catalog readers must keep source keys aligned with claim aliases and preserve the precedence of specific readers over generic mapped entries. Repeated tool calls must also use distinct source keys when each call produces separate evidence.
  • Changes to compaction limits or grouping keys must preserve count and time-range metadata. A source boundary must not be lost when logs are grouped.
  • Changes to syncable roots or exclusion rules must retain the credential deny-list. The allowlist and the deny-list are separate protection layers.
  • Changes to remote-sync settings must keep environment precedence, secret-free persistence, provider validation, and provider-specific setup fields aligned.
  • Changes to provider metadata or fingerprint handling must remain compatible with local comparison. Azure must use a valid content MD5 or leave the fingerprint unavailable so sync can use its time fallback.
  • Changes to scoped path resolution must keep remote sync refused for organization-scoped turns unless object keys gain an explicit owner boundary.
  • Changes to task-store completeness or missing-store handling must preserve the distinction between a new empty scheduler and a missing definition store with existing run history.
  • Changes to schedule identity or task-store writes must keep organization ownership, duplicate confirmation, unreadable-file recovery, atomic replacement, scheduler reload signals, and queued-run handling aligned.
  • Changes to the scheduler run schema must keep migration defaults, selected column order, row decoding, and recovery scope aligned. A field that exists only in the database can shift run history into the wrong state shape.
  • Changes to legacy run migration must preserve attempt history and keep old rows from widening a targeted retry when their delivery scope is unknown.
  • Changes to legacy task normalization must keep retired kinds safe to load, preserve usable custom prompts, and leave unresolved work-item reminders unchanged rather than inventing a fire time.
  • Changes to migration locking or retry timing must keep concurrent startup bounded. A stuck database must fail clearly rather than leave the scheduler waiting forever.

Important failure modes

TriggerConsequenceGuard
A state field is added without the matching validation or slice updateA stage may reject the state or lose the field during construction or serializationKeep AgentStateModel, the owning slice, and the flat AgentState contract aligned
Transcript growth is handled by dropping old messages without a summaryEarly user facts disappear from later turnsCompact overflow into the leading session summary and keep recent turn pairs
A durable and in-memory session backend implement different record meaningsA resumed session can differ from an ephemeral session or a test can miss a restore defectKeep both backends on the same session persistence contract
A tool runs before its durable intent is written, or its commit is not recordedRecovery cannot tell an interrupted action from a completed action and may repeat or lose workFlush the intent before execution and match it to a later tool-call record
A session flush appends a second closing leaf or omits live control stateRestore can stop at the wrong tip or lose a paused goal, plan, or user choiceKeep flush idempotent and persist live state after the previous leaf when needed
A roster probe or tool_unavailable result is counted as evidencePolicy can claim that a live source was checked when it was notCount structured tool results first and exclude discovery and unavailable envelopes
Repeated calls use the same evidence source keyLater evidence can be silently dropped from the citeable catalogUse a unique source key for each repeated call
Repeated error logs consume the whole evidence limitLess common error types are hidden from diagnosisGroup repeated messages before applying output caps and retain an error taxonomy
A credential or configuration file enters a sync rootSensitive local data can reach the remote storeApply the root allowlist and the independent denied-filename check
Remote sync runs for an organization-scoped turnMembers can read or write the same unscoped object keysRefuse organization scope and use the shared context root instead
A remote store is newer than a local file but push runs firstA stale local copy can replace newer remote workPull before push for two-way sync and compare modification times
A downloaded file is interrupted during writeA session or memory file can remain partially writtenWrite to a temporary file and replace the target atomically
Azure returns a missing or malformed Last-Modified valueThe provider cannot safely rank the remote object and sync stops at the provider boundaryTreat the timestamp as unavailable instead of guessing that the object is newest
Azure has no valid Content-MD5 for a blobAn opaque Azure tag could look like a local MD5 and cause false change detectionLeave the fingerprint empty so the sync engine uses its timestamp path
A session JSONL tail is torn or a line is not valid JSONThe unreadable record is skipped and restored context can be incompleteRecord the decode failure and treat the session log as a recovery source rather than silently assuming full history
A cross-process session lock times outThe attempted session write is skipped and the session may lack the latest recordKeep same-session writes serialized and inspect the recorded lock-timeout event before retrying
A process uses the in-memory store for a long-lived sessionAll session records disappear when the process endsUse the durable JSONL backend for sessions that must resume
A missing task store hides an existing run databaseSetup or backlog status can falsely report that no schedules existInspect run history and mark the task snapshot incomplete when history exists
A corrupt task store is overwritten during a writeScheduled definitions may be lost before an operator can recover themQuarantine the unreadable file, then write a fresh file by atomic replacement
A schedule is confirmed more than once without identity matchingDuplicate task entries can fire parallel work or make delivery unclearMatch the full schedule identity, including its owner, and update the existing revision
An organization-scoped task is stored without its owner boundaryOne organization can see or change another organization's scheduleStamp the bound organization on newly stored tasks and include it in schedule identity
A schedule change is saved without notifying the schedulerThe active scheduler can continue using an old job or fire removed workRequest a scheduler reload and skip queued runs when a task is removed or disabled
A run schema column is added without updating the selected columns or row decoderRun history can be misread or fail when reports, outcomes, or target results are loadedTreat migrations and the run-store read contract as one change
Legacy rows receive an open target scope during migrationRecovery can resend work to destinations that already received itUse the empty target scope for old attempts until usable per-target history exists
A retired task kind is loaded as if its old scheduler still existsThe scheduler can attempt unsupported work or silently run the wrong task behaviorNormalize retired entries before validation, keep only usable custom investigations enabled, and disable the rest with a repair notice
A legacy work-item reminder has no resolvable source timeThe scheduler can fire at an invented or incorrect timeAdd an absolute fire time only after the work item and its reminder time resolve successfully
A competing process holds the SQLite schema lock past the migration limitScheduler startup raises instead of hiding a stuck database behind delayed firingRetry schema changes for the bounded migration window and surface the failure after it expires

Key files

FileWhy to read it
core/…/models.pyDefines the validated flat runtime state used by chat and investigation flows.
core/…/agent_state.pyShows which conversation facts survive across turns and when the transcript compacts.
core/…/runtime_slices.pyMaps investigation facts to the stages that usually read or write them.
core/…/jsonl_store.pyDefines durable session records, tool write-ahead evidence, restore boundaries, and flush behavior.
core/…/memory.pyShows the ephemeral backend that mirrors the durable session record contract.
core/…/evidence.pyDefines the provenance record for one tool observation.
core/…/evidence.pyDefines the open evidence source and tool-owned mapping contract, plus helpers for distinct citeable entries.
core/…/evidence_driver.pyShows how a conversational turn performs bounded evidence gathering.
core/…/gather_observation.pyDefines the structured and rendered evidence result boundary.
tools/…/evidence_catalog.pyBuilds report evidence IDs and attaches them to claims.
infrastructure/…/evidence_compaction.pyDefines general size limits for high-volume evidence.
infrastructure/…/log_compaction.pyDefines grouped log views and error taxonomy summaries.
infrastructure/…/metric_summary.pyDefines the compact time-series view used by diagnosis.
config/setup_store.pyDefines durable onboarding, endpoint, and remote-operation choices.
infrastructure/…/task_store.pyDefines durable schedule definitions, ownership, completeness reporting, safe recovery and replacement, schedule identity, and scheduler reload behavior.
infrastructure/…/backlog_status.pyCombines task-store status with run history so missing setup cannot hide an existing scheduler backlog.
infrastructure/…/database.pyDefines the scheduler run database location, connection mode, and migration boundary.
infrastructure/…/migrations.pyDefines the durable run schema and the safe upgrade path for older scheduler databases.
infrastructure/…/legacy_task_migration.pyNormalizes retired task entries and fills resolvable legacy reminder times before task validation.
infrastructure/…/run_store.pyDefines leased execution claims, recovery attempts, delivery history, and report persistence.
infrastructure/…/__init__.pyExposes the task, backlog, and run storage contracts through the scheduler storage boundary.
infrastructure/…/operations.pyProvides the shared status and sync service used by hosts.
infrastructure/…/engine.pyDefines additive pull, push, conflict, and atomic-write behavior.
infrastructure/…/syncable.pyDefines which local roots may be mirrored and which names are always denied.
infrastructure/…/config.pyDefines remote-sync enablement and environment-over-file resolution.
infrastructure/…/registry.pyDefines the provider extension boundary and safety-related provider capabilities.
infrastructure/…/azure.pyShows the Azure Blob provider's identity, object metadata, and exposure checks.