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-harness

Agent harness and turn execution

The agent harness is the shared runtime that turns an inbound message into one controlled agent turn. It keeps the session, prompt, grounding facts, tools, model messages, host controls, and result aligned while connecting the core ReAct agent to execution services. It serves interactive shell, gateway, headless, and scheduled hosts. This page is a child view of agent execution; see LLM invocation, tool framework, agent memory, skill lifecycle and releases, and workspace knowledge for adjacent systems.

Harness boundary

Host session contract

AgentSession is the public host contract for starting a session and running chat turns. A host starts it once, attaches the default agent, and calls chat for each message so the conversation and warm session state continue. A scheduled one-shot may use run_headless_turn; a multi-turn loop keeps one session and one agent instead of rebuilding them for every message.

Process boot and agent construction are separate concerns. The host may provide a boot action, environment loading, session creation or restore, prompt context, tools, output, and cancellation policy. The harness then builds the default headless agent from those choices without importing a surface or owning process-profile code. The shared AgentConfig and build_agent path is the single construction seam for the core agent.

References: core/…/AGENTS.md• L32-51 core/…/AGENTS.md• L331-366 core/…/agent_builder.py• L25-67

Host adapters

The harness exposes host capabilities through ports. A port is a small contract for output, session state, prompt surface, tool access, approval, accounting, error reporting, or cancellation. This keeps the turn engine independent of terminal UI, gateway transport, integration code, and tool registry details.

The normal lifetime is construct once and run many turns:

HostAgent entryLifetime
Shell and gatewayTurnRunner and a per-session pooled HeadlessAgentOne agent per logical session; same-session turns are serialized
Embedded script or CLI askAgentSession.start() then chat()One session for the call or script
Scheduled one-shotAgentSession.run_headless_turn()Throwaway session for one turn
Test or isolated headless callerInMemoryHeadlessBuildIn-memory ports with no external side effects

Concurrent hosts do not call the unguarded scripted API directly. They bind the current session and transport to the pooled agent, apply host capacity limits, and call handle. Different sessions can run at the same time.

References: core/…/AGENTS.md• L32-51 core/…/AGENTS.md• L475-485 core/…/AGENTS.md• L502-518 core/…/headless_adapters.py• L1-5 core/…/headless_adapters.py• L27-47

Core agent connection

The harness prepares a run for core.agent.Agent; it does not implement a second reasoning loop. The core agent performs the ReAct cycle: it receives messages and tools, calls tools, observes results, and accepts a final answer. The harness supplies the per-turn system prompt, user message, tool resources, resolved integrations, iteration limits, event hooks, and conclusion gates through AgentConfig.

The action path has three explicit routes. A user-written !shell command or literal slash command is dispatched as the command the user supplied. Natural-language requests go to the model-driven action agent. The accepted conclusion returns through the harness; the host does not call another model to rewrite it. Literal commands can still run when the action-agent model is unavailable because they use deterministic tool dispatch.

References: core/…/AGENTS.md• L19-23 core/…/AGENTS.md• L436-440 core/…/action_driver.py• L796-829 core/…/action_driver.py• L831-920 core/…/agent_builder.py• L46-67

Session context

Session state

SessionCore is the durable working context for one logical conversation. It holds the transcript and turn evidence together with integration state, repository scopes, token totals, task plans, pending user choices, active skill state, session-goal state, and recovery notes. A later turn reads this state so it can answer follow-up requests and continue work without rebuilding the host context.

The session separates facts that describe the installation from facts that describe one request. Integration names and resolved settings are session state, while the active repository target and the turn's surface policy belong to the current turn view. This separation lets a session remember repositories and connections without letting stale or surface-private data leak into a new request.

References: core/…/session_core.py• L44-59 core/…/session_core.py• L70-199 core/…/session_core.py• L300-391 core/…/session_core.py• L393-447

Session lifecycle

SessionManager owns session creation, restore, rotation, flush, refresh, and close for every host. Shell-specific UI state and gateway-specific metadata are layered on top of this shared lifecycle instead of reimplementing it. A gateway can refresh a cached session from storage after it obtains the session lease, so a turn sees state written by another host.

Startup refreshes safe runtime metadata and integration names. Resumed sessions restore their conversation and workflow state before the next turn. A fresh session can warm integrations lazily, while a resumed session normally warms them before use because its tools must be ready immediately. Rotation and close also take a final memory snapshot without making the live session object part of the background job.

References: core/…/lifecycle.py• L1-29 core/…/lifecycle.py• L60-120 core/…/lifecycle.py• L124-185 core/…/lifecycle.py• L187-233 core/…/lifecycle.py• L271-383 core/…/lifecycle.py• L385-426

Session persistence

Persistence lets a conversation resume after process exit and lets hosts query stored sessions. The storage contract separates writes for one live session from reads across sessions. Production storage uses an append-only JSONL session tree; in-memory storage provides the same state shape for tests and isolated headless runs.

The repository rebuilds the selected branch rather than treating every record as current state. It restores messages, turn evidence, plans, goals, pending choices, accumulated context, history, and recovery notes from that branch. A requested historical entry does not consume live session controls, so inspection cannot accidentally apply a pending pause or clear request.

Persisted state includes messages, bounded tool evidence, plans, session goals, pending choices, accumulated context, history, and compaction records. A write-ahead tool intent is durable before a side-effecting tool starts. If no matching tool call commits before a crash, resume shows recovery context instead of replaying the unknown action. Goal controls and pending setup or schedule offers also persist as durable state. Clearing the last goal state writes a tombstone when needed, so resume does not revive it.

References: core/…/contracts.py• L1-54 core/…/contracts.py• L57-177 core/…/lifecycle.py• L301-371 core/…/jsonl_store.py• L76-87 core/…/jsonl_store.py• L250-323 core/…/jsonl_repo.py• L64-123 core/…/jsonl_repo.py• L228-298 core/…/memory.py• L16-20

Integration resolution

Integration resolution supplies the connection settings that both the prompt and tools use. The session keeps configured service names for capability checks and a cache of resolved settings for later turns. A source stamp invalidates that cache when the local integration store or remote connection set changes, while an explicit empty cache records a known no-integration state.

The turn resolves integrations once and enriches that view with repository scopes inferred from the request, recent conversation, environment, or working directory. The resulting view is frozen in the turn plan. Prompt assembly and tool construction both read it, so the model does not plan with one connection or repository and execute with another. Hosts can select a connection explicitly; otherwise the workspace default is used.

References: core/…/integration_resolution.py• L1-11 core/…/integration_resolution.py• L49-128 core/…/integration_resolution.py• L142-170 core/…/integration_resolution.py• L176-276 core/…/action_driver.py• L729-743 core/…/AGENTS.md• L239-254

Turn snapshot

TurnSnapshot is the immutable read view captured at turn start. It contains the current message, bounded conversation, turn evidence, integration facts, repository targets, surface, runtime request, active skill, task plan, session-goal brief, interaction availability, and recovery note. Prompt assembly and tool setup use this same view while the live session remains available for writes.

The snapshot also carries whether the host can accept a structured user choice. Interactive shell turns can open a picker. Headless or gateway turns may defer a choice only when their capability policy allows it. An unknown surface receives no setup or host measurement facts. This keeps the prompt honest about what the receiving host can do and prevents private installation data from being exposed by a missing surface value.

The relationship is:

flowchart LR
    A[Session state] --> B[Turn snapshot]
    B --> C[Turn plan]
    C --> D[Prompt and tools]
    D --> E[Session updates]

References: core/…/turn_snapshot.py• L1-5 core/…/turn_snapshot.py• L30-43 core/…/turn_snapshot.py• L120-143 core/…/turn_snapshot.py• L147-246 core/…/turn_snapshot.py• L248-317

Pending choices and setup resume

Structured choices make user decisions part of the session contract instead of free text that the model must interpret. ask_user_choice stores one question or a batch of questions with workflow context, the host presents the menu, and the selected answers return as framed structured conversation input. Pending choices and their active workflow survive restore when a host must defer them.

Integration setup can park one shell user turn when a skill prerequisite is not ready. After setup passes its check, the shell replays that request at most once. A new request, closed menu, or new session clears the parked turn; headless and gateway sessions do not park it.

References: core/…/pending_choice.py• L1-12 core/…/pending_choice.py• L34-80 core/…/pending_choice.py• L100-141 core/…/pending_choice.py• L251-325 core/…/setup_resume.py• L1-12 core/…/setup_resume.py• L23-87

Turn execution

Turn lifecycle

run_turn owns one complete turn. It binds the turn's skill catalog, prompt recorder, and trace scope before it performs background memory upkeep, compacts history when needed, expands a structured affirmative offer, builds the turn plan, runs the action stage, checks cancellation, records the conversation, and finalizes accounting. Nested dispatch reuses the outer prompt and trace correlation instead of creating a second logical turn.

The main sequence is:

flowchart TD
    A[Inbound message] --> B[Bind catalog, prompt, and trace]
    B --> C[Memory upkeep and context compaction]
    C --> D[Expand pending offer and build turn plan]
    D --> E[Run action agent]
    E --> F{Cancelled?}
    F -->|Yes| G[Return cancelled result]
    F -->|No| H[Record response and finalize accounting]
    G --> I[Host result]
    H --> I

The harness uses structured pending offers for a bare affirmative such as yes. A schedule offer or an integration setup offer owns that confirmation. Only the current offer can expand it into a deterministic command, and successful dispatch consumes the offer. Natural-language intent is not routed by keyword scanning.

The turn's prompt and trace records use the inbound text as input and the accepted assistant response as output. A session identifier groups turns in one conversation, while nested turns inherit the outer correlation. Outcome metadata records cancellation, iteration limits, and action counts without changing the neutral result returned to the host.

References: core/…/orchestrator.py• L112-165 core/…/orchestrator.py• L189-259 core/…/AGENTS.md• L25-30 core/…/pending_offer.py• L1-20 core/…/pending_offer.py• L57-74 core/…/pending_offer.py• L134-214

Action execution

The action stage connects the core agent to the tools for the current turn. The tool provider builds tools from the turn plan's resolved integrations and adds the resources for output, approval, cancellation, host capabilities, and tool hooks. The agent then chooses tools, observes their results, and decides whether the request is complete.

Each action call can record its intent before a side effect, report tool progress, and contribute bounded evidence to the turn result. Results marked for the model only guide the agent but do not become generic user-facing display rows. Host-rendered results are not repeated, while explicit shell and slash output can remain grounded in the output the model observed. The conclusion gate keeps the turn open until later work succeeds, the failure is classified as the answer, or the user must perform named setup.

References: core/…/tool_provider.py• L58-186 core/…/ports.py• L152-179 core/…/action_driver.py• L757-920 core/…/action_driver.py• L1475-1559 core/…/display_text.py• L24-46 core/…/display_text.py• L117-170 core/…/display_text.py• L173-205 core/…/turn_results.py• L24-56

Task plans

A task plan is the live execution checklist for multi-step work. It makes the expected work and its progress visible across turns and after history compaction. The plan can mark a step pending, in progress, completed, or blocked. A blocked step records that work could not happen and names the blocker; it is not treated as completed.

The host enforces the important completion rules. A work result earns progress, a verification step needs its own tool result, a deliverable reply can earn a declared report step, and a second work tool without an open plan is refused during a loaded skill workflow. Ordinary turns and turns with an attached session goal execute directly without that second-work guard. The host can advance an earned active step when the next work tool starts, but it never settles a plan or silently skips a blocked step. A plan with only completed or blocked steps no longer keeps the action loop running, but a step newly blocked this turn still requires a user choice or a reply that names the blocker when no menu is available.

References: core/…/plan.py• L1-7 core/…/plan.py• L18-32 core/…/plan.py• L82-114 core/…/plan.py• L153-168 core/…/plan.py• L201-247 core/…/required.py• L1-55 core/…/conclusion.py• L12-54 core/…/plan_hooks.py• L35-114 core/…/advance.py• L1-11 core/…/completion.py• L34-63

Conclusion review

Conclusion review is the host-side check that separates a valid answer from a tool loop that stopped too early. Deterministic gates cover unfinished plans, newly blocked steps that still need a user choice, a demo that only loaded a skill, failed work, and discovery-only gathering. An optional bounded model review can reject a clearly incomplete conclusion, but it fails open when its own call or parsing fails.

The session-goal review uses a separate observation reading when tool evidence is available. That reading does not see the assistant reply, so the judge can compare the reply with an independent view of the facts. The judge returns GOAL_REACHED, NOT_REACHED, or IMPOSSIBLE, must quote supporting evidence for a reached or impossible result, and flags contradictions or repeated blocking reasons. A reached verdict still needs successful tool evidence; missing, truncated, or contradictory observations keep the goal open.

The review does not replace the core agent's answer. It sends a nudge back into the same ReAct turn when more work is required, so the next action uses the existing context and evidence. A classified work result or a named setup requirement can end a failed work path because those results already explain why normal retry cannot proceed.

References: core/…/goal_review.py• L1-27 core/…/goal_review.py• L265-337 core/…/goal_review.py• L378-469 core/…/goal_review.py• L478-509 core/…/judge.py• L1-7 core/…/judge.py• L21-31 core/…/judge.py• L34-92 core/…/judge.py• L96-129 core/…/judge.py• L231-324 core/…/work_outcome.py• L102-137

Cancellation and concurrency

One host-cancel event belongs to the output sink for a turn. The console exposed to tools, the orchestrator, the ReAct resources, and stream guards read that same event. Its reason distinguishes an ordinary stop from a session-goal pause or clear without creating a second cancellation channel.

One mutable headless agent handles one turn at a time. Shell and gateway hosts serialize turns for the same logical session through their pool and host loop. Different sessions remain concurrent under the host's capacity controls.

References: core/…/AGENTS.md• L187-208 core/…/orchestrator.py• L229-235 core/…/AGENTS.md• L502-518

Turn results and activity

The harness returns neutral facts about the turn rather than a surface-specific display object. A TurnResult separates the final intent, assistant text, action counts, tool evidence, cancellation, iteration limits, and accounting status. A headless caller can render those facts itself, while a shell can omit text that a tool already showed.

Shared plain-text activity gives the shell and hosted gateway feed the same compact progress wording. Display shaping omits model-only and already-rendered results, hides raw data blobs, caps verbose output, and removes task-plan snapshots from replies because the plan has its own host display. Host-rendered failures still surface because the host may have stopped before it painted the error. Quiet commands keep their closing text when live output was withheld. Plan updates and user-choice menus remain host-owned interaction rather than ordinary tool rows.

Provider token counts are recorded after each completed model call. Exact provider counts stay distinct from text estimates, so a later model failure does not hide spend from earlier calls.

References: core/…/turn_results.py• L1-18 core/…/turn_results.py• L24-80 core/…/action_driver.py• L1127-1304 core/…/activity_display.py• L1-6 core/…/activity_display.py• L41-70 core/…/token_accounting.py• L111-146 core/…/token_accounting.py• L149-193

Prompt and grounding

Prompt envelope

The action prompt combines stable operating rules with current session and turn context. A PromptEnvelope is the structured collection of prompt blocks. Each block has an identity, role, provenance, and change tier. Stable, session or project context, and explicitly rebuilt volatile blocks can share the provider's cached prefix, while per-turn blocks remain ephemeral.

The action assembly includes the shared system rules, a host-owned goal kernel, vendor rules, runtime facts, compact skill index, setup and integration state, repository context, shared workspace knowledge, durable memory, active skill, interaction facts, conversation context, recovery notes, relevant memory and workspace entries, and the current task plan. The stable goal kernel states that the user request is the success criterion and that a failed tool is not completion. A second short kernel block is placed after any active skill, so skill guidance cannot replace those rules. The current user message remains first in its user envelope, followed by newest-first ephemeral context.

Runtime facts have separate stable and live blocks. Static installation facts remain in the cacheable prompt portion, while the current clock and permitted host measurements stay per-turn. The rendered facts tell the model to quote authoritative values and not guess missing fields or re-read blocked facts through a sandbox. Runtime fact capture is best effort, so unavailable facts do not stop a turn. If skill discovery is disabled, the prompt states that the host supplied a complete task and prevents workflow discovery instead of exposing the normal skill index.

References: core/…/envelope.py• L11-39 core/…/envelope.py• L45-84 core/…/envelope.py• L90-123 core/…/envelope.py• L180-220 core/…/__init__.py• L1-29 core/…/assemble.py• L47-71 core/…/assemble.py• L106-183 core/…/assemble.py• L190-263 core/…/assemble.py• L264-355 core/…/assemble.py• L580-614

Surface grounding

Grounding gives the model bounded facts about the installation and the current host. The prompt surface names whether the turn is an interactive shell, headless CLI, or shared gateway chat. Shell and headless CLI prompts may include local setup state and host measurements; gateway prompts keep installation-private setup, disk, memory, and host identity out of shared chat while retaining the current clock. An unknown surface omits setup and host measurements rather than assuming shell access.

Runtime facts are rendered as quotable values with rules that stop the model from guessing missing fields or re-reading authoritative facts through a sandbox. Static facts can include the version, environment, host OS, process identity, cloud detection, workspace default, installed tools, and capability warnings. Live facts include the current time and, only where allowed, uptime, disk, and memory. Repository context keeps one active target per vendor while retaining a bounded set of repositories the session has seen. Repository AGENTS.md files are local coding-agent instructions and are not loaded into the OpenSRE prompt.

The prompt grounding provider only names the session's surface. The turn snapshot and prompt assembler own the facts. This keeps surface policy explicit and prevents a missing surface from accidentally exposing installation state.

References: core/…/surfaces.py• L14-63 core/…/__init__.py• L13-29 core/…/provider.py• L1-21 core/…/assemble.py• L58-79 core/…/assemble.py• L367-435 core/…/AGENTS.md• L176-178

Conversation context

Earlier turns are replayed as typed user, assistant, and tool-result messages when structured history is enabled. This preserves tool calls and their bounded results as model-readable evidence instead of quoting an undifferentiated text transcript. The turn's own message is kept separate so callers can distinguish current output from replayed history.

When the conversation grows beyond its history budget, compaction writes a handoff summary and keeps the newest complete turns with their evidence. The compaction record stores what was kept so restore produces the same context. A single prompt-size measurement covers envelope blocks, replayed history, the current request, and tool schemas for both prompt logging and context preview.

Conversation recording appends the user and assistant pair to the bounded message window. With structured history enabled, it also stores the turn's tool evidence beside the pair and queues best-effort memory extraction. Memory bookkeeping cannot make turn recording fail.

References: core/…/structured_history.py• L1-17 core/…/structured_history.py• L141-228 core/…/structured_history.py• L293-383 core/…/transcript_compaction.py• L1-9 core/…/transcript_compaction.py• L110-167 core/…/transcript_compaction.py• L217-265 core/…/prompt_size.py• L1-8 core/…/prompt_size.py• L49-127 core/…/conversation_recording.py• L16-56 core/…/conversation_recording.py• L59-114

Workflow skills

Workflow skills are natural-language instruction cards for action-shaped work. The prompt first exposes a compact validated catalog. The action agent loads one full card only when the request needs it, then uses its workflow steps, prerequisites, plan, helper tools, and success criteria as guidance.

The host owns the execution boundaries. A new user request clears active skill context, an answer to a skill question continues that skill, and changing or settling a skill refreshes its helper-tool set. Skills cannot override the goal kernel, task-plan guards, failed-work gate, or user-choice rules. Self-contained scheduled turns disable discovery while retaining the tools named for the scheduled task.

The runtime excludes invalid cards from discovery but keeps the unfiltered catalog subject to validation. This separates safe runtime service from release and CI checks that must detect every invalid card. A loaded skill changes the next request's helper-tool set, and execution checks the active session again before using an older tool snapshot.

References: core/…/AGENTS.md• L46-72 core/…/AGENTS.md• L105-121 core/…/AGENTS.md• L147-167 core/…/AGENTS.md• L185-193 core/…/reader.py• L22-87 core/…/render.py• L22-40 core/…/active_skill.py• L23-46 core/…/assemble.py• L155-169 core/…/test_local_repositories_workflow.py• L154-317 core/…/test_merge_conflicts_workflow.py• L1-7

Skill catalog releases

The active skill catalog is one immutable snapshot for a turn. It validates cards, renders bodies and references, builds the compact index, and records per-skill source digests before the turn uses it. An edit or newly activated release applies at the next turn boundary, so one turn cannot mix cards from two catalog versions.

Catalog selection prefers an explicit local override, then the newest stored release that verifies, declares a supported API version, contains the bundled skills, and builds without diagnostics, and finally the bundled cards. Remote releases are accepted as a whole only after signature, path, size, API-version, validation, and required-skill checks pass. This gives scheduled work a stable approved skill revision and prevents a partial release from changing the tool or prompt contract.

References: core/…/AGENTS.md• L58-90 core/…/active_catalog.py• L1-7 core/…/active_catalog.py• L34-71 core/…/catalog_snapshot.py• L24-45 core/…/build.py• L26-69 core/…/sources.py• L1-6 core/…/sources.py• L112-170 core/…/release.py• L1-7 core/…/release.py• L167-207 core/…/skill_releases.py• L1-53

Multi-turn controls

Session goals

SessionGoal is the outer keep-going flow across several chat turns. It is separate from the per-turn ReAct conclusion review and from the live task plan. A goal is attached through /goal, an explicit host API, or a structured tool handoff; the harness does not infer it from keywords in user prose.

The first message always runs through the action agent. Later iterations use continuation prompts and the same chat path. Completion uses checklist ticks, qualifying tool evidence retained across turns, and an optional classification-tier judge. A goal can finish, pause, cancel, exhaust its turn budget, or remain active for the next message. Its state, host controls, and pending setup or schedule offers persist so a process or host handoff does not silently restart the work. Clearing the goal persists an empty state when needed so restore does not bring back a cleared goal.

References: core/…/AGENTS.md• L53-75 core/…/run_until.py• L1-7 core/…/run_until.py• L573-589 core/…/run_until.py• L603-773 core/…/persist.py• L21-44 core/…/persist.py• L145-168 core/…/control.py• L13-23

Memory lifecycle

The harness connects session turns to durable memory without making memory upkeep block the user turn. At turn start it may launch scoped background consolidation. After a set of non-demo turns, and again when a session closes or rotates, it queues extraction from a bounded digest of user messages, tool results, and assistant replies. Each pass can save at most five durable memories and can also record a short session summary with an outcome.

Extraction jobs are coalesced per session and run in order, so a newer pass for one session does not replace another session's work. Passes for one session never overlap, and a queued job captures the transcript and storage scope at queue time. The close path can wait for its final pass, while interactive rotation and inbound handling normally remain responsive. The captured scope keeps extracted facts with the member whose turns produced them.

The memory pipeline drops demo, sample, and synthetic turns, redacts unsafe text, checks claimed provenance against the digest, and saves only bounded reusable facts. User claims need matching user words, while tool claims need verified tool evidence; assistant prose alone does not prove a fact. It also records a short session summary and outcome for later consolidation. Failures or unusable model output are ignored so memory upkeep cannot fail the user turn.

References: core/…/memory_consolidation.py• L1-17 core/…/memory_consolidation.py• L80-115 core/…/memory_digest.py• L1-22 core/…/memory_digest.py• L324-385 core/…/memory_extraction.py• L1-34 core/…/memory_extraction.py• L144-179 core/…/memory_extraction.py• L188-253 core/…/memory_extraction.py• L272-319 core/…/memory_extraction.py• L336-366 core/…/memory_extraction.py• L458-511 core/…/memory_turns.py• L1-17

Model and message boundary

The action driver receives an explicit LLM factory at the composition boundary and keeps runtime messages provider-neutral while the core agent runs. The selected provider converts those messages and responses at the LLM boundary. The harness owns when the model is called and what session context surrounds the call; provider selection, retries, and transport details belong to LLM invocation.

The same boundary supports provider usage events, prompt-size records, write-ahead tool recording, and host observers. These hooks add accounting and safety signals without changing the order of the model's tool calls and tool results.

References: core/…/agent_builder.py• L25-67 core/…/ports.py• L29-32 core/…/action_driver.py• L883-908 core/…/action_driver.py• L979-1005 core/…/action_driver.py• L1536-1559 core/…/token_accounting.py• L174-193

Execution service connections

The default tool provider is the bridge from the harness to execution services. It receives the turn's resolved integrations and builds the action tools with a per-turn scope for output, confirmation, cancellation, host capabilities, and tool hooks. The harness reaches integration and tool behavior through provider ports rather than importing surface or vendor modules.

Hosts can replace the tool provider, prompt provider, capability policy, error reporter, or LLM factory through the build configuration. The shared build path keeps shell and gateway construction aligned. Unattended work receives a safe tool subset, and an active skill may add declared helper tools for that skill's turn.

References: core/…/headless_build.py• L94-114 core/…/headless_build.py• L136-218 core/…/tool_provider.py• L58-186 core/…/AGENTS.md• L180-185

Change checklist

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

  • If the turn snapshot or plan changes, keep prompt blocks, tool selection, repository scope, surface visibility, interaction availability, and conclusion review on the same turn-start view.
  • If session state or persistence records change, keep create, restore, flush, rotate, and refresh aligned for messages, evidence, plans, goals, choices, recovery notes, memory jobs, and cleared-state tombstones.
  • If integration resolution changes, keep source-stamp invalidation, background warming, active repository selection, and the turn plan's single resolved view aligned.
  • If a host binding changes, keep per-session agent reuse, session rebinding, output retargeting, same-session serialization, cancellation, approval, and result delivery aligned.
  • If prompt assembly changes, check stable versus per-turn blocks, goal-kernel ordering, structured history, prompt-size measurement, runtime fact disclosure, gateway privacy, workspace knowledge placement, and scheduled skill discovery.
  • If skill catalog or turn instrumentation changes, keep one catalog, prompt recorder, and trace correlation bound to the whole turn and restore the parent correlation for nested turns.
  • If skills or releases change, keep card validation, snapshot pinning, release verification, required skill names, helper-tool refresh, recurring revision pins, and next-turn activation aligned.
  • If task-plan or session-goal rules change, keep evidence, plan ownership, verification, blocked-step questions, retained findings, judges, pause controls, pending offers, cleared-state persistence, and stored state aligned.
  • If display shaping changes, keep host-rendered and model-only results out of duplicate transcript output while preserving errors, the full response for history, and the visible answer for non-TTY hosts.
  • If accounting or activity wording changes, keep provider-measured usage separate from estimates and keep shell and hosted activity redaction consistent.
  • If the message boundary changes, preserve provider-neutral message order and the write-ahead intent-before-side-effect contract.

Important failure modes

TriggerConsequenceGuard
A host rebuilds an agent for every messageFollow-up context and warm state disappearConstruct one agent per logical session and call chat or handle for later messages
Prompt assembly and tool construction use different integration viewsThe agent plans against one connection or repository and executes against anotherResolve once in the turn plan and pass that view to both
A session uses a cache after integration sources changeNew or changed credentials are invisibleCompare the source stamp and resolve again
A gateway or unknown surface receives local setup factsShared chat can disclose installation stateApply the explicit surface profile and omit private facts when the surface is unknown
A host measurement block is rendered for a shared or unknown surfaceHost identity, disk, or memory can leak into a shared promptRender only the clock unless the surface profile allows host measurements
A skill is placed after the closing goal kernel or the kernel is omittedA skill can weaken the user's success criterion or failed-tool ruleKeep the stable kernel before skills and the short kernel after the active skill
A nested turn creates a new prompt or trace scopeOne logical turn is split across records and correlation is lostBind the outer scope and inherit it for nested turns
A stale schedule or setup offer captures a later bare affirmativeAn unrelated command can runClear unconfirmed offers on a new request and consume only the matching structured offer
A bare affirmative is parsed from ordinary numbered proseAn unrelated request can be treated as a menu answerRequire the current framed choice payload when deciding from text alone
A work tool fails and the agent concludesIncomplete work is reported as doneUse the failed-work conclusion gate and require later success, a classified outcome, or named setup
A second work tool runs with no open plan during a loaded skill workflowMulti-step work becomes invisible to the user and hostRefuse the call and require a plan in the same response
A plan closes a verification step without its own tool returnThe plan claims a check that never ranRequire evidence for verifies steps and never let the host settle a plan
A newly blocked step ends without asking the userThe workflow can stop with an unresolved blockerQueue a choice when the host can do so, or expose the blocker in the reply
A new workflow answers a question from an old planStale steps can be advanced for unrelated workAdvance only a plan written this turn or owned by the active skill that asked the question
A session-goal judge trusts the assistant reply or a truncated observation aloneA goal can close on unsupported or incomplete factsRead retained tool observations independently and require evidence, with contradiction checks
Two turns overlap on one mutable headless agentBindings and session writes can cross between conversationsSerialize same-session turns and reject overlapping agent use
A second cancellation signal is introducedA tool, stream, or orchestrator can continue after the host stoppedShare the output sink's single cancel event and its reason
A resumed session has an uncommitted tool intentThe harness can treat an interrupted side effect as complete or replay itShow recovery context and do not replay unknown actions automatically
A skill release is only partly valid or drops a required cardOne host can run a prompt or workflow contract that the binary cannot supportVerify the signed release and accept it only as a complete validated snapshot
A skill release changes during a turnPrompt and helper tools can come from different revisionsBind one catalog snapshot for the whole turn and activate changes at the next boundary
Memory extraction trusts assistant prose aloneUnsupported or unsafe facts enter durable memoryRequire digest-backed provenance, redact inputs, and drop demo or synthetic turns
Provider usage is recorded only after the whole runA later model error hides spend from completed callsTap each completed provider request and keep estimates distinct

Key files

FileWhy to read it
core/…/AGENTS.mdCanonical host API, layering rules, lifecycle boundaries, and core-agent relationship
core/…/agent_builder.pySingle construction seam for the core agent
core/…/ports.pyHost seams for output, session state, prompt context, tools, accounting, and turn binding
core/…/headless_build.pyShared construction seam for product and in-memory headless agents
core/…/headless_agent.pyPer-message binding, dispatch, session-goal looping, and one-agent concurrency boundary
core/…/orchestrator.pyComplete turn order, prompt and trace capture, pending offers, cancellation, persistence, and result finalization
core/…/turn_plan.pyOne resolved integration and repository view shared by the turn's prompt and tools
core/…/turn_snapshot.pyImmutable turn-start context for grounding, plans, goals, interaction, and recovery
core/…/action_driver.pyCommand routing, action-agent setup, tool execution, prompt sizing, conclusion review, and response shaping
core/…/turn_results.pySurface-neutral turn outcome contract
core/…/structured_history.pyReplay of prior tool calls and bounded results as provider messages
core/…/transcript_compaction.pyLong-session handoff summaries and restore-safe context compaction
core/…/conversation_recording.pyShared recording path for bounded messages, turn evidence, and memory handoff
core/…/prompt_size.pyShared prompt and history size measurement
core/…/session_core.pyShared cross-turn state for conversations, integrations, plans, goals, choices, and recovery
core/…/lifecycle.pySession create, resolve, rotate, restore, flush, refresh, and close ownership
core/…/integration_resolution.pyIntegration cache, source invalidation, warming, connection selection, and repository scope state
core/…/assemble.pyAction prompt blocks, goal rules, context, skills, memory, runtime facts, and interaction policy
core/…/envelope.pyPrompt block identity and cacheable versus per-turn layers
core/…/__init__.pyShared prompt type facade and surface profile exports
core/…/tool_provider.pyExecution-service bridge, tool scope, and unattended safety policy
core/…/progressive_tool_catalog.pyPer-conversation tool discovery and stable visibility
core/…/required.pyRule for when loaded skill workflows must open a plan
core/…/plan_hooks.pyPlan evidence, refusal, and host advancement hooks
core/…/headless_adapters.pySide-effect-free session and output adapters for headless runs