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 / agent-execution

Agent execution architecture

The agent runtime turns an operator request into a controlled sequence of model decisions, tool actions, evidence gathering, and user-facing output. It keeps session state and turn context stable while isolating provider, host, tool, and operational-domain concerns behind clear boundaries. Skill release work is part of the wider operational flow; see skill lifecycle and releases for that release path.

Runtime responsibilities

Execution shapes

The runtime supports two agent shapes. A tool-calling agent uses the ReAct loop to select tools and inspect their results. A direct-answer path makes one grounded text request when no tool work is needed. The action, evidence, and investigation paths use the tool-calling shape; guidance and final answer work can use the direct-answer shape. The reusable Agent holds run settings and builds one validated AgentRunInput for each run before handing it to the loop. See agent harness execution and LLM invocation for the child-page view of these paths.

References: core/…/agent.py• L34-39 core/…/agent.py• L81-139 core/…/react_loop.py• L165-215

Runtime boundaries

The runtime separates the work into a host layer, a turn layer, an agent loop, a tool layer, and a provider layer. Hosts supply session, output, tool, prompt, accounting, and error ports. Turn orchestration chooses the work path. The shared loop handles model turns and tool results. Provider clients handle the external model protocol.

The public host shape is AgentSession with repeated chat calls. Gateway and shell hosts use a shared turn runner and keep one headless agent per logical session. They serialize turns for the same session and apply process capacity limits around the agent. Scripted and one-shot callers use the direct session API instead. This lets each host share the same execution model without sharing surface-specific state.

References: core/…/AGENTS.md• L19-23 core/…/AGENTS.md• L34-51 core/…/AGENTS.md• L444-489 core/…/ports.py• L1-9 core/…/ports.py• L233-318

Domain model

Alert source routing

Alert source routing connects an incoming vendor alert to the evidence sources that should matter during operational work. Core keeps the routing mechanism vendor-neutral, while integration packages register source detectors, aliases, relevance sources, and the smaller set of sources that are safe to seed first.

The runtime can therefore use explicit source labels when an alert provides them and registered detectors when it does not. Declared context sources take priority over text matches, and generic secondary sources remain fallbacks rather than primary evidence.

References: core/…/alert_source.py• L1-21 core/…/alert_source.py• L53-78 core/…/alert_source.py• L140-165 core/…/alert_source.py• L192-243

Repository preferences

Repository preferences define organization-wide choices about which repositories the agent should favor and which it must never change. They are shared by members, shell runs, and scheduled work, so repository choice remains stable across sessions and gateway rollouts.

Primary repositories resolve requests that use only a short repository name or no full name. Excluded repositories remain outside agent write actions, including branch, push, pull request, and issue changes. Repository notes provide bounded context for a selected repository.

References: core/…/preferences.py• L1-15 core/…/preferences.py• L35-49 core/…/preferences.py• L74-99 core/…/preferences.py• L135-199 core/…/__init__.py• L1-23

Operational evidence contracts

Shared domain types give planning, tools, and state one language for evidence. An evidence source is an open integration key rather than a fixed vendor list. Tools can map raw results into citeable evidence entries, while retrieval intent can narrow a query by time, filters, result size, fields, or aggregation.

The incident window gives time-aware work one bounded interval. It uses an operator override when present, otherwise anchors the interval to an alert timestamp and falls back to a limited current-time window. The interval is half-open and normalized to UTC, so tools can share the same time boundary without each choosing its own default.

Pipeline span projection is another domain contract for operational evidence. It reduces trace data to named pipeline stages and the run metadata that downstream evidence views need.

References: core/…/evidence.py• L1-19 core/…/evidence.py• L25-68 core/…/retrieval.py• L109-166 core/…/incident_window.py• L70-93 core/…/incident_window.py• L238-340 core/…/pipeline_spans.py• L1-15 core/…/pipeline_spans.py• L26-45

Runbook selection

Runbook selection connects a normalized incident identity to one operational guide before the agent performs guided work. A runbook source supplies a trusted catalog and bounded document content at an immutable revision, while the shared domain contract keeps source details outside the runtime.

Selection uses exact alert name, service, and label matches. The most specific unique match wins; no match returns not_found, and equal best matches return ambiguous so the runtime does not silently choose the wrong procedure.

References: core/…/contracts.py• L9-11 core/…/contracts.py• L13-41 core/…/contracts.py• L49-127 core/…/selection.py• L13-82 core/…/__init__.py• L1-28

Memory context

Long-term memory is optional context that can be available to a turn. The runtime enables it for local surfaces when the feature is on, but shared gateway surfaces require explicit opt-in so one principal's facts do not enter another principal's prompt. See agent memory for the memory-specific view.

Memory records are stored in a separate directory for each principal and are read from that directory when the runtime builds prompt context. The prompt uses two views: a stable index with a consolidated summary and one bounded line per live memory, plus a per-turn block with the small set of records relevant to the request. The index is ordered by memory type and update time, while use counts do not reorder it. Relevant records are limited by item and text budgets, and a recall pointer covers records that do not fit. Search and prompt reads exclude fenced demo or sample records, and relevant full-text reads record best-effort usage for later age-based upkeep. Each record carries a small type and optional provenance, while malformed or unsafe content is left out or refused. Writes and deletes use a directory lock and atomic replacement. The generated MEMORY.md index is a human-facing view that can be rebuilt from the records.

Memory upkeep keeps long-term context useful without deleting its history. Periodic consolidation archives fenced or stale records, folds safe duplicates into a newer record, and can create a bounded summary from current memories and recent session summaries. An audit reports issues such as duplicates, stale facts, missing provenance, local paths, transient status, and oversized bodies without exposing full memory bodies to summary consumers.

References: core/…/settings.py• L22-51 core/…/models.py• L9-75 core/…/files.py• L8-18 core/…/index.py• L1-10 core/…/index.py• L67-132 core/…/index.py• L146-187 core/…/recall.py• L1-7 core/…/recall.py• L122-164 core/…/store.py• L95-132 core/…/store.py• L192-220 core/…/store.py• L391-443 core/…/usage.py• L1-7 core/…/usage.py• L72-96 core/…/assemble.py• L198-209 core/…/assemble.py• L454-479 core/…/memory_extraction.py• L88-141 core/…/memory_extraction.py• L346-366

Workspace knowledge

Organization-wide context

Workspace knowledge is shared context about an organization rather than a fact about one member. Integration scans write organization and integration entries into a store separate from personal memory, so every permitted member can use the same view of the organization and its connected services. Scans can report deterministic facts even when no summarizer is available, and can optionally include channel-message context. See workspace knowledge for its operational view.

References: core/…/__init__.py• L1-11 core/…/scans.py• L1-21 core/…/settings.py• L18-38 core/…/store.py• L1-12 core/…/store.py• L35-49

Workspace access

Workspace knowledge follows the same memory gate as personal memory and adds an organization membership check. Full members and the organization's own application actors may read it, while guests and external connected users cannot; a local turn with no organization scope remains available to its operator. Reads and prompt rendering apply this rule through one availability check, so a permitted store cannot be used accidentally by a surface that should not expose it.

References: core/…/access.py• L1-19 core/…/access.py• L83-105 core/…/reading.py• L1-36 core/…/settings.py• L26-34

Workspace prompt views

The workspace prompt uses two views for different stability needs. A cached block includes the organization entry and compact lines for other entries, while a per-turn view includes only the full entries relevant to the request. Reader membership is recorded by scans and refreshed as scan results change. The generated index and change generation support human and web-app views, but agent reads use the live entry files.

References: core/…/access.py• L46-90 core/…/render.py• L1-12 core/…/render.py• L43-92 core/…/store.py• L52-109 core/…/changes.py• L1-10

Turn model

Session state

SessionCore is the durable, surface-neutral state for a logical conversation. It holds the conversation view, the last investigation state, reusable infrastructure context, integration state, token totals, task state, grounding state, and pending user actions. A later turn can therefore use facts from an earlier turn without rebuilding the conversation from the host.

The session also owns the boundary between in-memory state and persistence. A session record can preserve the conversation, investigation results, session-goal state, task-plan state, and pending user-choice state. The shell and gateway may add their own surface state, but they share this core state model.

References: core/…/session_core.py• L57-76 core/…/session_core.py• L84-156 core/…/lifecycle.py• L301-366

Runtime state

AgentState is the flat, shared state envelope for chat and investigation work. AgentStateModel supplies its defaults and validates its values, while typed slices group fields by domain without changing the flat shape used at runtime. This gives orchestration stages a common state contract while keeping chat data separate from alert input, plans, investigation evidence, diagnosis, and delivery output.

Investigation stages typically move state forward through a clear set of domains: caller metadata and alert input establish the run, planning selects work, investigation collects evidence, diagnosis forms the result, and delivery prepares the output. The state also carries resolved integrations, cancellation-independent run metadata, masking data, and evaluation fields when those concerns apply. The context field remains a legacy investigation evidence envelope and is not the general store for session state or prompt grounding.

References: core/…/models.py• L38-56 core/…/models.py• L62-142 core/…/runtime_slices.py• L1-14 core/…/runtime_slices.py• L26-139

Turn context

Each turn starts with an immutable TurnSnapshot, which is the read view of the session at turn start. A TurnPlan adds the resolved integration view for that turn. The action, gather, and answer stages all read this plan, while the live session remains available for writes such as history and result updates.

This model prevents one stage from seeing a different set of integrations or a different conversation state from another stage. It also gives the runtime a single place to carry cancellation resources, active tools, model choice, and the iteration budget.

References: core/…/turn_snapshot.py• L117-188 core/…/turn_snapshot.py• L190-240 core/…/turn_plan.py• L29-63

Conversation history

Conversation history is replayed as typed messages rather than quoted as one text block. A recorded turn keeps the user message, bounded assistant tool-call batches, matching tool results, and the assistant reply. The next turn can therefore preserve tool-call structure while still limiting the size of old arguments and results.

When history exceeds its budget, compaction replaces older turns with a handoff summary and keeps a recent whole-turn tail with its evidence. The compaction record stores the replacement state so a resumed session starts from the same view as the live session. If model summarization is unavailable, the runtime uses a deterministic summary instead of failing the turn.

References: core/…/structured_history.py• L1-13 core/…/structured_history.py• L87-171 core/…/structured_history.py• L202-277 core/…/transcript_compaction.py• L1-9 core/…/transcript_compaction.py• L109-166 core/…/transcript_compaction.py• L216-264

Turn lifecycle

The turn lifecycle opens one prompt-capture and trace scope, binds one skill catalog snapshot, prepares memory and history, then lets an action agent decide whether operational work is needed. The result either becomes the answer or sends the request to evidence gathering and grounded answer generation. Nested turns inherit the active trace and turn-bound skill view, so a release pulled during a turn applies to the next turn rather than changing the current work.

This diagram shows how a request moves from turn setup through operational work and into a recorded response.

flowchart TD
    A[Inbound message] --> B[Bind prompt, trace, and skill scopes]
    B --> C[Prepare memory and history]
    C --> D[Build turn snapshot and plan]
    D --> E[Action agent]
    E --> F{Action outcome}
    F -->|Handled| G[Return action result]
    F -->|Observation| H[Summarize observation]
    F -->|Needs evidence| I[Bounded evidence gather]
    I --> J[Grounded direct answer]
    H --> K[Finalize response]
    J --> K
    G --> K
    K --> L[Record result and update session]

Before dispatch, the runtime can consolidate memory, compact an oversized transcript, and expand an affirmative reply against a pending offer. It clears an unconfirmed offer when the new request is unrelated. After the action run, host cancellation becomes a cancelled result, while an iteration-cap stop receives an explicit incomplete message when no response was streamed. A successful confirmation consumes its pending offer, and a response is recorded with its tool evidence for later turns.

The route is based on typed handoff data and action results. It does not infer an operational route from keywords in the user's prose. A pending choice or offer can end the turn at a structured host boundary and resume from persisted state when the user responds.

References: core/…/orchestrator.py• L112-165 core/…/orchestrator.py• L189-256 core/…/pending_offer.py• L44-68 core/…/transcript_compaction.py• L109-166

Plan evidence

Task plans make multi-step skill work visible and keep progress tied to observed work. The host counts successful non-bookkeeping tool returns during the action turn. A plan write that completes a step without fresh evidence is refused, and a failed work result does not complete a step.

The host can advance an earned step when the first work call provides the required evidence. A blocked step needs a user choice rather than a silent skip. Deliverable steps must reach the user before the plan settles, and verification steps need their own tool return. Plan ownership also keeps an unrelated request from moving an older skill plan. These are host rules, so skills cannot override them.

References: core/…/AGENTS.md• L79-124 core/…/evidence.py• L1-6 core/…/evidence.py• L58-80 core/…/required.py• L33-49 core/…/goal_review.py• L304-317

Agent loop

ReAct cycle

The ReAct loop is the shared execution primitive for operational agents. It receives one resolved AgentRunInput with the model, prompt, tools, integrations, resources, messages, and run limits. On each iteration it sends the current transcript to the model, receives either text or tool calls, executes the requested tools, appends their results, and repeats.

The loop stops when the model reaches an accepted conclusion, a tool ends the turn, cancellation is requested, repeated observations reach the stagnation limit, or the iteration budget is reached. It refreshes a live tool catalog when the available tools change, then applies the host's tool filter before building the next provider request. Provider-reported input counts calibrate the local context estimate for later requests, within bounded limits. If the provider rejects a request because it is too large, calibration is disabled, the runtime lowers the budget, trims low-value exchanges, and retries once. When the loop stops at a safety limit, it makes one tool-disabled handoff request. That request turns partial work and the stop reason into a visible response without allowing the model to start more work. If that request fails, the runtime returns a fixed incomplete-work message.

The loop does not decide which tools are valid for a host or whether a conclusion is acceptable. A LoopHost supplies those policies through narrow callbacks. This keeps the algorithm reusable for action work, evidence gathering, and investigation work.

References: core/…/run_io.py• L19-59 core/…/run_io.py• L61-106 core/…/react_loop.py• L199-249 core/…/react_loop.py• L324-384 core/…/react_loop.py• L424-593 core/…/react_loop.py• L608-721 core/…/react_loop.py• L723-794 core/…/progressive_tool_catalog.py• L147-190

Goal acceptance

A Goal is a structured objective that can require evidence and a defined success check before a no-tool reply ends the run. A reviewed goal supplies a verifier and may supply its own nudge; when the verifier rejects a conclusion, the loop adds a user-role nudge and continues gathering evidence or taking action.

The host-owned review rejects an unfinished task plan, a failed last work tool, and evidence gathering that stopped at discovery without running the requested query. The optional model review is bounded and fail-open. The hard iteration ceiling always wins. An unmet goal stays unverified at that ceiling, so the loop emits an incomplete safety handoff instead of accepting an unsupported conclusion. A goal without a verifier is descriptive only in the normal Agent loop and does not gate a no-tool conclusion.

References: core/…/goals.py• L18-99 core/…/agent.py• L141-180 core/…/react_loop.py• L537-606 core/…/goal_review.py• L278-337 core/…/work_outcome.py• L92-151

Run outcomes

An agent run returns the full runtime transcript together with its final text, ordered tool history, structured tool results, stop state, iteration count, and provider-reported token totals when available. The explicit stop_reason identifies a normal conclusion, no-tool work, tool termination, cancellation, iteration-cap stop, goal-verification stop, or stagnation stop. Callers can therefore distinguish a normal conclusion from an incomplete safety stop. A safety handoff makes a capped, stagnant, or unverified run visible as incomplete rather than presenting it as a completed operational result.

References: core/…/run_io.py• L19-46 core/…/react_loop.py• L889-933

Runtime controls

The loop exposes control points for live operation without changing its core algorithm. A host can inject a steering message before the next model turn, queue a follow-up after a provisional conclusion, narrow the tool set, observe typed lifecycle events, apply a per-run iteration limit, and reject a no-tool conclusion when a reviewed goal is not complete.

The run can receive its system prompt, tools, resolved integrations, resources, messages, and limits as one validated runtime request. AgentRunInput resolves that request once before the loop starts, while raw message calls remain available through construction-time settings. The runtime request's iteration limit becomes the effective limit for both the loop and goal acceptance, so a goal check uses the budget that the run will actually consume. This lets turn orchestration use current context without rebuilding the agent object. The resulting AgentRunResult keeps the transcript and structured tool outcomes together with the final prompt and usage totals needed by callers and operations views.

These controls support interactive approval, progress display, goal review, cancellation, and telemetry. Observer failures do not stop the operational run.

References: core/…/mixins.py• L32-69 core/…/mixins.py• L79-109 core/…/loop_host.py• L23-74 core/…/agent.py• L81-139 core/…/agent.py• L141-180 core/…/run_io.py• L19-106

Turn durability

Tool execution uses a write-ahead record around the shared runtime events. The runtime records tool intent before surface observers react, then records a bounded result after the call ends. If a process stops between those records, recovery can identify interrupted work and rediscover current state instead of replaying an uncertain side effect.

Durability bookkeeping is separate from the user-facing observer. A storage failure is logged and ignored so a logging problem cannot break the operational turn.

References: core/…/wal_recorder.py• L1-11 core/…/wal_recorder.py• L48-90 core/…/wal_recorder.py• L93-112 core/…/action_driver.py• L891-904

Messaging model

Runtime transcript

The loop uses provider-neutral runtime messages as its source transcript. User messages, assistant messages, tool-result messages, and internal application messages remain typed until the runtime reaches the provider boundary. Assistant messages preserve requested tool calls so the next model turn can follow the same conversation.

References: core/…/__init__.py• L1-22 core/…/message_mapper.py• L25-40 core/…/message_mapper.py• L75-93

Provider conversion

MessageMapper converts the runtime transcript into the wire shape required by the selected model provider. It also converts provider responses back into runtime assistant and tool-result messages. Provider-specific payloads can be retained when a provider needs them for the next request, while internal runtime markers are removed from outbound messages.

This boundary keeps provider message formats out of the agent algorithm. It also gives each provider a place to preserve features such as tool-call identifiers or provider-specific response data without changing the shared transcript model.

References: core/…/message_mapper.py• L42-73 core/…/message_mapper.py• L95-115 core/…/message_mapper.py• L120-159

User handoff

User decisions and affirmative offers use structured state rather than prose scraping. A pending choice stores its question, options, and workflow context. The host renders the menu and serializes the selected answer into the next user message. A pending schedule or integration offer expands a confirmed answer into a fixed dispatch message.

This keeps a response tied to the question that created it and prevents a later bare yes from confirming stale work after the user starts another request.

References: core/…/pending_choice.py• L1-11 core/…/pending_choice.py• L34-80 core/…/handoff.py• L1-20 core/…/pending_offer.py• L1-11 core/…/pending_offer.py• L197-215

Tool execution

Tool contract

A runtime tool is a model-visible operation with a name, description, public input schema, source, and execution policy. Tools can be read-only or have side effects. They can declare approval needs, required data sources, result types, and whether they are safe to run in parallel.

The model sees only the public schema. Runtime-only values such as connection details and host resources are supplied by the execution layer. Large catalogs use progressive disclosure: a compact core and tool_search are visible first, a successful search activates specialist schemas on the next reasoning step, and workflow-local helpers appear while their skill is active. The catalog is refreshed when visibility or detail changes, so the model sees the current capability set without receiving every schema at the start.

References: core/…/contracts.py• L210-229 core/…/contracts.py• L244-290 core/…/contracts.py• L702-757 core/…/progressive_tool_catalog.py• L87-114 core/…/progressive_tool_catalog.py• L147-190

Tool call lifecycle

When the model requests a tool, the runtime checks that the tool exists and that its public input is valid. It then runs approval and pre-call policy, invokes the tool with resolved integrations and runtime resources, applies post-call policy, and returns a structured result to the model. The result records content, details, error state, termination state, and metadata.

Independent calls can run in parallel when every tool permits it. One sequential tool makes the provider batch sequential. The returned list keeps provider order so the model sees a stable mapping between calls and results. The provider builds the catalog from the live session and turn, while unattended runs use a fail-closed safe subset. See tool framework behavior for the detailed tool contract and execution rules.

References: core/…/execution.py• L87-156 core/…/execution.py• L226-288 core/…/execution.py• L338-479 core/…/tool_provider.py• L90-179

Tool failure handling

Tool failures become structured error results instead of breaking the whole agent loop. Unknown tools, invalid input, blocked calls, raised tool errors, and failed lifecycle hooks each have a defined result path. Sensitive inputs and outputs are redacted before runtime events expose them to observers.

The host also checks the last work outcome before accepting a conclusion. A failed command remains incomplete until later work succeeds, unless the failure is already a classified work outcome or a tool-unavailable result names a setup action that the user must perform first. Host-rendered results are not shown again, while large or data-only results are reduced to a bounded user-facing preview; the model and persisted history retain the fuller result where needed.

References: core/…/execution.py• L319-335 core/…/execution.py• L349-425 core/…/execution.py• L517-587 core/…/work_outcome.py• L77-151 core/…/display_text.py• L24-47 core/…/display_text.py• L103-185

Provider boundary

Model roles

The LLM factory assigns a model role to each kind of work. The agent role provides tool calling for action, gather, and investigation loops. Reasoning, classification, and lightweight tool-call roles use the reasoning-family client for their narrower tasks. Callers select a role without selecting a vendor or transport.

References: core/…/factory.py• L39-53 core/…/factory.py• L115-127 core/…/types.py• L102-139

Provider routing

The factory makes one provider and transport decision from the active configuration, then builds the client family needed by the role. The route may use a provider SDK, LiteLLM, or a subprocess-backed model client. Native SDK routing is the default; the configured transport or provider rules can select LiteLLM instead.

Keeping routing in one factory prevents action, investigation, and answer paths from silently using different provider decisions. Client instances are cached by role and current provider configuration. A model or environment change clears that cache.

References: core/…/factory.py• L1-23 core/…/factory.py• L56-72 core/…/factory.py• L115-132 core/…/transport_mode.py• L1-29

Request hooks

Provider hooks are an optional boundary around each model request. They can transform runtime messages, convert messages, adjust the outgoing request, or inspect the response. The standard message mapper remains the fallback when a custom hook is absent or fails.

Hook errors are fail-open because hooks provide customization and observation rather than the core execution result. A provider request still contains the converted messages, system prompt, tool schemas, and turn metadata before it reaches the client.

References: core/provider.py• L13-37 core/provider.py• L40-69 core/…/provider_hooks.py• L27-61 core/…/react_loop.py• L386-495

Operational work

Action stage

The action stage is the first model-driven stage for a chat turn. It exposes the tools available to the host and lets the agent perform operational actions such as commands, integrations, scheduling, or investigation dispatch. It returns a facts-oriented result that tells the turn router whether the action handled the request, left an observation to summarize, or handed the request to another stage.

The action stage uses the turn plan's resolved integrations when it builds tools. Its prompt combines stable rules with live integrations, repository context, memory, current skill guidance, structured prior turns, and task-plan state. Explicit ! shell commands and literal slash commands use deterministic tool dispatch, while natural-language requests still use the action agent. Tool intent is recorded before observers and provider usage is recorded as calls finish, so audit and cost views remain useful when a later call fails.

References: core/…/action_driver.py• L767-829 core/…/action_driver.py• L834-929 core/…/action_driver.py• L990-1017 core/…/action_driver.py• L1181-1199 core/…/wal_recorder.py• L93-112 core/…/assemble.py• L105-169 core/…/assemble.py• L198-250

Evidence stage

The evidence stage gives a conversational request a bounded read-only pass over investigation tools. It gathers current evidence and returns both a compact observation for the answer model and structured tool results for policy and status decisions. It does not replace the larger investigation pipeline.

The stage can stop early when no usable source or model is available. It also records unreachable sources and limits discovery and observation size so a live chat turn stays responsive. Its goal gate rejects a pass that only lists tools or schemas without running the requested query. On the chat path, the action agent owns the available tools rather than handing control to a second independent gather loop.

References: core/…/evidence_driver.py• L1-13 core/…/evidence_driver.py• L282-301 core/…/evidence_driver.py• L304-409 core/…/goal_review.py• L479-509 core/…/AGENTS.md• L139-143

Answer stage

The answer stage is a direct, no-tool model call. It receives the user's request, turn snapshot, action observation, and any handoff guidance. It streams a grounded response through the host output sink and records the answer as part of the session conversation.

The stage is used after evidence gathering or when the action handoff says that fresh evidence is not needed. It does not run a ReAct loop and cannot call integrations by itself. See LLM invocation for provider and streaming details.

References: core/…/orchestrator.py• L202-260 core/…/ports.py• L256-280 core/…/orchestrator.py• L321-435

Host lifecycle

Session startup

AgentSession is the public host API for starting a logical session and running chat or investigation work. Startup resolves process and environment state, creates or restores the session, loads prompt context, and attaches the default headless agent. The same attached agent can then handle many turns.

A one-shot scheduled run may use a throwaway session. A multi-turn host should create once and reuse the session and agent so conversation state, integration caches, and accounting remain continuous.

References: core/…/harness.py• L75-112 core/…/harness.py• L123-198 core/…/harness.py• L200-243 core/…/AGENTS.md• L34-51

Session lifecycle

SessionManager owns creation, restore, rotation, flush, and close. A fresh session is bootstrapped with runtime metadata and integration state. A resumed session restores its saved conversation, evidence, task plan, pending choices, and session-goal state before it handles new work. Rotation and close flush state and release resources.

This shared lifecycle keeps gateway, shell, and headless hosts aligned. Hosts add their own output or UI concerns after the core session is ready instead of copying session bootstrap logic. Close and rotation can schedule final memory extraction without holding the active host when responsiveness matters.

References: core/…/lifecycle.py• L1-29 core/…/lifecycle.py• L90-113 core/…/lifecycle.py• L117-185 core/…/lifecycle.py• L284-421

Agent reuse

A HeadlessAgent is built from a port family and receives one message at a time. Gateway and shell hosts keep one agent per logical session and bind the current session, output, console, accounting, and hooks for each turn. The agent rejects overlapping turns because its per-turn binding is mutable.

Cancellation uses the host's shared cancel signal. The action stage, evidence stage, stream path, and tools read that same signal so a stop request ends the whole turn rather than only one layer. Scheduled and cloud hosts add bounded concurrency around this session-level serialization instead of creating a new chat API.

References: core/…/headless_agent.py• L61-87 core/…/headless_agent.py• L124-212 core/…/headless_agent.py• L214-300 core/…/AGENTS.md• L471-489 core/…/ports.py• L321-340

Skill release lifecycle

Catalog snapshots

The skill system validates workflow cards, resolves their bodies and references, renders the discovery index, and builds one immutable catalog snapshot. The active source is an explicit skills directory, the newest verified stored release, or the bundled tree in that order. A turn binds one snapshot, so an authoring edit or pulled release applies on the next turn rather than midway through current work.

The skills package exposes catalog lookup and content loading through one public facade. The compact index names workflows and loads full bodies on demand. Invalid cards are excluded at runtime with diagnostics, while CI checks the unfiltered catalog so invalid content cannot be published unnoticed.

References: core/…/AGENTS.md• L46-72 core/…/AGENTS.md• L105-111 core/…/__init__.py• L1-35 core/…/index.py• L9-16 core/…/index_render.py• L14-53

Release publication

Skill releases are signed content packages rather than binary application releases. A push publishes cards whose metadata version is newer than the live version. Hosts pull releases in the background, and rollback republishes an earlier release as the newest one.

Clients verify the release signature and reject a release that is unsupported, incomplete, or has catalog diagnostics. Because the version gate controls publication, changing a card without increasing its version does not ship that change. A release must retain every bundled skill name that host code relies on.

References: core/…/AGENTS.md• L74-90 core/…/AGENTS.md• L58-70

Skill workflow execution

Before a card becomes active, host-owned prerequisite checks can withhold its body and queue setup. After setup, the blocked request resumes. Skill-local helper tools appear while the skill is active and are retired when the skill changes or its plan settles. Execution rechecks the active session so an older tool snapshot cannot keep using retired helpers.

The interactive catalog starts with universal controls and a compact set of tools. A successful tool_search exposes specialist schemas on the next reasoning step. A new user request clears active skill context, while menu answers and slash commands retain it. Scheduled ticks can disable skill discovery while retaining the tools for a skill explicitly bound to that tick.

The onboarding flow uses structured menus. Its workflow tests exercise the real loop and confirm that a menu ends the turn before work begins, that the user's selection starts the child workflow, and that a provider blocker can resume the same repository without losing the workflow state.

References: core/…/AGENTS.md• L147-161 core/…/AGENTS.md• L169-193 core/…/progressive_tool_catalog.py• L147-190 core/…/tool_provider.py• L157-177 core/…/test_onboarding_workflow.py• L71-171 core/…/test_workflow.py• L140-171

Change checklist

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

  • If the TurnSnapshot, TurnPlan, or AgentRuntimeRequest contract changes, check that action, evidence, and answer stages still use one turn-wide integration view and budget.
  • If AgentRunInput or AgentRunResult changes, check both direct callers and runtime-request callers so per-run limits, resources, transcripts, final prompts, usage totals, and stop states remain aligned.
  • If loop stop rules change, check safety handoff behavior and ensure capped, stagnant, cancelled, and tool-terminated runs remain distinct to callers.
  • If goal verification or conclusion nudges change, check the effective per-run iteration limit, the last-lap ceiling rule, queued follow-ups, failed-work handling, and the caller's interpretation of incomplete work.
  • If context-budget or overflow handling changes, check request trimming, provider-count calibration, the single retry, token accounting, and the tool-disabled safety handoff together.
  • If LoopHost callbacks change, update every loop host and preserve the provider hook, tool filter, steering, conclusion, and event seams.
  • If the runtime transcript or provider message shapes change, update both the provider client and MessageMapper so tool calls and tool results remain round-trip compatible.
  • If structured history or compaction changes, check whole-turn evidence pairing, bounded tool arguments and results, summary replacement records, restore behavior, and the text-history kill switch together.
  • If tool visibility or execution policy changes, check public schemas, approval behavior, progressive activation, injected runtime values, active-session rechecks, and parallel execution decisions together.
  • If tool-result display changes, check host-rendered suppression, data-blob hiding, output caps, persisted response text, and non-TTY output together.
  • If alert-source routing changes, check source detection, explicit context-source precedence, seed-source selection, and the integration catalog together.
  • If repository preference handling changes, check shared organization scope, short-name resolution, exclusion enforcement, repository normalization, and atomic persistence together.
  • If evidence or retrieval contracts change, check evidence mappers, citeable catalog entries, retrieval controls, incident-window serialization, and tool declarations together.
  • If session, pending-choice, or AgentState fields change, update restore and flush paths plus the matching validation model and state slice so resumed runs do not lose conversation, workflow, investigation, or goal state.
  • If WAL events or recovery records change, check intent-before-observer order, bounded result storage, interrupted-call recovery, and the rule that recovery rediscovers state instead of replaying side effects.
  • If memory scope or gating changes, check prompt injection and memory writes for local and shared gateway surfaces so principal boundaries remain intact.
  • If memory extraction changes, check digest snapshots, provenance checks, demo filtering, per-session coalescing, and final close behavior together.
  • If memory index or prompt rendering changes, check the stable summary and index cache, live-memory filtering, type and recency ordering, relevant-memory ranking, body and total prompt limits, recall pointers, usage recording, and the memory-recall path together.
  • If workspace knowledge changes, check the separate store root, workspace-only entry types, member-reader records, memory gates, prompt-cache view, relevant-entry view, and scan outcomes together.
  • If memory storage or consolidation changes, check personal stores and workspace knowledge together because both use the shared file format, locks, indexes, caches, change generation, and safety rules.
  • If turn entry setup changes, check one prompt recorder, one root trace observation, inherited nested-turn correlation, the turn-bound skill catalog, pre-turn memory and compaction work, and final result recording together.
  • If pending offers or cancellation handling changes, check confirmation consumption, stale-offer clearing, host cancellation, iteration-cap messaging, accounting finalization, and conversation recording together.
  • If a new host or agent entry point is added, keep it on one of the two existing agent shapes and route construction through the shared harness ports.
  • If model or transport selection changes, check the shared route, role-specific client builders, and cache reset behavior as one contract.
  • If skill release or catalog loading changes, check validation diagnostics, snapshot binding, version gating, signature verification, bundled-skill completeness, progressive activation, and helper retirement together.

Important failure modes

TriggerConsequenceGuard
A stage resolves integrations again after the turn plan is builtThe prompt and tool execution can use different connection stateBuild the plan once and pass its resolved view to every stage
A provider returns a tool message shape that the mapper cannot preserveThe next ReAct request loses tool-call context or sends an invalid provider payloadKeep provider conversion in MessageMapper and its provider adapter boundary
A provider reports token counts that differ from the local estimateLater requests can be trimmed too early or can exceed the provider's real context limitCalibrate from provider counts within bounded limits and fall back to the conservative estimate after an overflow
A provider rejects a request after the local context estimate allows itThe run can fail even though the configured budget appeared validLower the run ceiling and retry once after enforcing the smaller context budget
A tool call names a missing tool or fails input validationThe model receives an error result and may recover on a later iteration; the loop does not run an unsafe callValidate the public schema and resolve the tool map before invocation
A non-parallel-safe tool shares a provider batch with other callsConcurrent execution can cause unsafe ordering or conflicting side effectsForce the whole batch into sequential execution
The runtime request and construction-time settings use different limits or contextA turn can run with the wrong budget or resource setValidate the runtime request and build one AgentRunInput before the loop starts
A reviewed goal uses a stale construction-time limit during conclusion reviewThe goal can be checked against the wrong last lap and produce the wrong incomplete-work behaviorSet the effective goal-check limit from the validated per-run input
A skill work step is marked complete without a successful tool returnThe plan reports progress that the agent did not performRequire plan evidence and reject failed work as completion
A failed work tool is followed by a conclusionThe user sees a completed-looking answer for work that did not succeedKeep the goal open until later work succeeds or a classified blocker names the real setup need
A short repository name matches a fork or mirror before the organization's primary repositoryWork can target the wrong repositoryResolve primary repositories before ambiguous short-name matches
An excluded repository reaches a write-capable actionThe agent can change a repository that the organization marked off limitsEnforce exclusions across branches, pushes, pull requests, and issues
Retrieval controls are requested without a matching tool capabilityThe query loses its intended time, filter, field, limit, or aggregation scopeKeep retrieval intent and tool-declared support aligned; ignore unsupported controls explicitly
An incident window is missing or invalidTime-aware evidence uses a broad or inconsistent rangeResolve a bounded UTC window and preserve its source and confidence
A runbook catalog has no exact match or has several equally specific matchesGuided operational work has no safe procedure to follow or may choose the wrong oneReturn not_found or ambiguous and require the caller to handle that status
Repeated tool calls produce the same observationThe agent spends its budget without making progressTrack observation fingerprints and stop at the configured stagnation limit
A capped, stagnant, or unverified run cannot produce its final handoffThe caller gets no clear explanation that work is incompleteUse the tool-disabled safety handoff and deterministic fallback message
A process stops after tool intent is recorded but before its commitRecovery cannot know whether the side effect completedTreat the unmatched intent as interrupted work and rediscover state rather than replaying the call
A host-rendered result is also added to the generic closingThe user sees duplicate output or a model summary that conflicts with the screenMark host-rendered results and suppress them from generic display while retaining needed errors
Structured history loses a tool result or mismatches a call idA resumed or later turn receives an invalid tool transcriptKeep call/result pairs complete, normalize replay ids, and fall back to text for incomplete batches
A resumed session is read without restoring its contextFollow-up questions lose prior investigation facts and conversation stateResolve through SessionManager and restore context before dispatch
A pending choice or offer is not restored with its workflow contextThe answer can be detached from its question or a stale yes can trigger old workPersist structured pending state and clear unconfirmed offers on a new request
Shared gateway memory is enabled without principal-aware scopeOne user's facts can enter another user's promptRequire gateway opt-in and keep memory stores separated by principal
A memory claim is not supported by the session digestUnsupported assistant wording becomes durable user or repository factCheck provenance and reject unsafe, fenced, demo, or synthetic output
The prompt index includes fenced records or changes when a memory is only readDemo data can reach the model or a session can resend a stable context block every turnBuild views from live records, keep use counts outside index ordering, and cache by memory-file signatures
The relevant-memory block exceeds its item or text budgetCurrent turn context becomes too large or later evidence loses roomRank live matches, cap each body, cap the full block, and point to memory_recall for hidden entries
A memory usage update waits behind a busy store lockA slow bookkeeping write delays the turnUse the short lock timeout and skip usage recording on timeout or storage error
A workspace scan records a user who is not a full memberA guest or external user can receive organization-wide contextRecord only full members and preserve the scan's listed users when judging partial reads
Workspace knowledge is read without the availability gateOrganization facts can enter a guest, external, or memory-disabled turnRoute turn-facing reads and prompt rendering through knowledge_available_here
Workspace and personal memory share a root or cache keyOne principal or tier can receive another tier's factsBind each store to its own directory and include that directory in cache identity
A workspace entry uses a personal memory typeA scan or mirror can write member-specific facts into shared contextAccept only workspace entry types in the workspace store
Consolidation writes a summary after the store changesA forgotten or newer fact can return through an old summaryRecheck the input fingerprint under the memory lock before writing the summary
A nested turn opens a separate prompt or trace scopePrompt records and traces split across one logical dispatch, or a skill release changes mid-turnLet the outer turn own capture, correlation, and the bound catalog; nested turns inherit them
A confirmed pending offer is consumed before its work succeedsA retry loses the user's confirmation and cannot resume the requested dispatchConsume the offer only after a successful action result
A host cancellation is checked only inside the action agentThe final result can report completion after the host has already stopped the turnCheck the shared host cancel signal after the action run and return a cancelled result
A release changes a skill without a metadata version bumpHosts continue to serve the older skillTreat the metadata version as the publication gate
A stored release drops a bundled skill or fails verificationThe client rejects the whole release and uses an older sourceVerify signature, API support, diagnostics, and required skill names before activation
Two turns use one mutable agent at the same timeOne turn can read another turn's session or output bindingSerialize turns per agent and handle AgentBusyError
The model reaches the iteration cap or cancellation is requestedThe result is incomplete and must not be treated as a normal conclusionInspect stop_reason, hit_iteration_cap, and cancelled in AgentRunResult and TurnResult

Key files

FileWhy to read it
core/…/AGENTS.mdHost API, layer boundaries, session reuse, plan guards, and skill-tool policy
core/…/harness.pyPublic session API and host startup sequence
core/…/orchestrator.pyTurn entry point, turn-bound catalog, prompt and trace scopes, pre-turn preparation, cancellation, and result recording
core/…/agent.pyThin runtime facade that validates per-run context and starts the loop
core/…/react_loop.pyShared think, tool, observe, context-budget, safety handoff, and stop cycle
core/…/run_io.pyPer-run input and outcome contracts
core/…/turn_snapshot.pyImmutable turn-start context model
core/…/turn_plan.pySingle resolved integration view for a turn
core/…/models.pyUnified validated state envelope for chat and investigation work
core/…/runtime_slices.pyDomain groupings and typical investigation stage ownership
core/…/structured_history.pyTyped history replay and bounded tool evidence
core/…/transcript_compaction.pyHistory budget, handoff summaries, and persisted compaction
core/…/wal_recorder.pyTool intent and result durability boundary
core/…/alert_source.pyVendor-neutral alert source detection and evidence-source routing
core/…/preferences.pyShared repository targeting and exclusion preferences
core/…/evidence.pyEvidence source and citeable evidence-entry contract
core/…/retrieval.pyStructured retrieval intent and tool capability contract
core/…/incident_window.pyAlert-anchored time window used by operational evidence work
core/…/settings.pySurface-specific memory gates and shared-host opt-in
core/…/access.pyOrganization membership records and workspace-reader authorization
core/…/settings.pyWorkspace knowledge and scan-message gates
core/…/store.pySeparate organization store and workspace-only entry contract
core/…/reading.pyTurn-facing workspace reads with access checks
core/…/render.pyCached organization context and per-turn relevant workspace context
core/…/scans.pyShared scan outcome contract for integration writers
core/…/index.pyGenerated memory index and bounded stable and relevant prompt views
core/…/recall.pyLive-memory filtering, ranking, search, prompt rendering, and recall usage recording
core/…/usage.pyBest-effort usage counts used by memory upkeep
core/…/store.pyPer-scope memory read, write, delete, and prompt-index behavior
core/…/files.pyStore layout, private file permissions, locks, and atomic writes
core/…/models.pyMemory types, provenance, and personal versus workspace scope
core/…/consolidation.pyPeriodic archive, duplicate merge, and summary lifecycle
core/…/audit.pyMemory quality findings and safe aggregate reporting
core/…/members.pyPer-member store discovery for organization-wide views
core/…/memory_extraction.pySession digest, provenance checks, and durable fact extraction
core/…/contracts.pyProvider-neutral runbook identity, catalog, document, and source contracts
core/…/selection.pyDeterministic exact-match runbook selection and ambiguity result
core/…/message_mapper.pyProvider-neutral transcript boundary
core/…/contracts.pyModel-visible tool contract and policy metadata
core/…/execution.pyValidation, hooks, concurrency, and structured results
core/…/progressive_tool_catalog.pyProgressive specialist-tool discovery and live catalog snapshots
core/…/tool_provider.pyPer-turn tool catalog and unattended safety filtering
core/…/display_text.pyUser-facing tool-result shaping and output limits
core/…/factory.pyShared provider route and role-specific client entry point
core/…/lifecycle.pySession create, restore, rotate, flush, and close behavior
core/…/jsonl_repo.pyBranch-based session restore and recovery state
core/…/pending_choice.pyStructured user choices and persistence shape
core/…/pending_offer.pyStructured confirmation offers and dispatch expansion
core/…/assemble.pyAction prompt context, memory, and skill gating
core/…/__init__.pyPublic skill catalog and content facade
core/…/index_render.pyCompact workflow discovery prompt
core/…/AGENTS.mdSkill validation, snapshots, prerequisites, and release contract
core/…/goal_review.pyHost-owned conclusion gates and goal review
core/…/evidence.pyEvidence rules for plan progress
core/…/work_outcome.pyFailed-work and classified-blocker handling
core/…/headless_agent.pyReusable host agent and per-turn binding model