agents

package
v0.208.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agents dispatches one bounded coding task to one configured agent harness running inside an isolated WB worktree, and reports the execution facts of that run to whoever asks later.

It is deliberately the deterministic execution layer only: it resolves an agent profile, creates or resolves a worktree through WB's existing worktree service, launches the harness as a detached child, and records what happened. It never judges whether the work is correct. A PASS/FAIL/ESCALATE verdict on a diff is a semantic decision that belongs to the supervisor above WB, not to WB.

Index

Constants

View Source
const (
	ModeNew      = "new"
	ModeExisting = "existing"
)

Worktree modes. Exactly one is required: creating a new isolated workspace and modifying an existing one have materially different intent, so they stay two explicit options rather than one ambiguous --worktree.

View Source
const (
	AttemptPlanned      = "planned"
	AttemptDispatched   = "dispatched"
	AttemptBaseMismatch = "base_mismatch"
	AttemptFailed       = "failed"
)

Attempt states inside one experiment. An attempt that fails before it starts is still recorded: an experiment that silently drops a planned comparison would misreport itself.

View Source
const (
	EffortConfig      = "config"
	EffortVariant     = "variant"
	EffortUnsupported = "unsupported"

	TaskDeliveryStdin       = "stdin"
	TaskDeliveryArgv        = "argv"
	TaskDeliveryPrivateFile = "private-file"

	UsageFromEvents      = "events"
	UsageUnavailable     = "unavailable"
	CostHarnessEstimated = "harness-estimated"
	CostUnavailable      = "unavailable"

	CredentialWBInjected   = "wb-injected"
	CredentialHarnessStore = "harness-store"

	IsolationPrivateHome = "private-home"
	IsolationUserHome    = "user-home"
	// IsolationLinuxContainer is the isolation a contained execution actually
	// provides: the worker runs inside the verified Linux container, not in the
	// host user's home.
	IsolationLinuxContainer = "linux-container"
)

Harness capability vocabulary. A capability is declared by the adapter, not guessed from the configuration, so an unsupported setting is refused or recorded instead of being silently dropped.

View Source
const (
	SourceExplicit           = "explicit"
	SourceTaskType           = "task_type"
	SourceTaskTypeComplexity = "task_type_complexity"
	SourceProfile            = "profile"
	SourceDefault            = "default"
	SourceSynthesized        = "synthesized"
	SourceOverridden         = "overridden"
	SourceFallback           = "fallback"
	SourceNone               = "none"
)

Value sources recorded in a plan. They are the audit trail that answers "why did this run use this model", which a resolved snapshot alone cannot.

View Source
const (
	HarnessCodex       = "codex"
	HarnessOpenCode    = "opencode"
	HarnessDSH         = "dsh"
	HarnessAntigravity = "antigravity"
)

Harness names a coding-agent environment and tool loop. Each name is an adapter in this package; the field exists so provider and model are not collapsed into the harness name.

View Source
const (
	WireAPIResponses = "responses"
	WireAPIChat      = "chat"
)

Wire protocols the Codex harness can speak. The set is closed because it is the harness's own contract, not a user extension point.

View Source
const (
	FallbackPreflight = "preflight"
	FallbackRuntime   = "runtime"
)

Fallback triggers. Preflight is a capability WB can prove before a worktree exists; runtime is a failure the harness reported after it started.

View Source
const (
	RemoteDispatch = "dispatch"
	RemoteStatus   = "status"
	RemoteAwait    = "await"
	RemoteList     = "list"
	RemoteLogs     = "logs"
	RemoteStop     = "stop"
)

Remote operations, one per local command that can address another machine.

View Source
const (
	DefaultRemoteTimeout = 10 * time.Minute

	// MaxRemoteLogBytes bounds a remote transcript fetch. `wb agent logs --raw`
	// over a link is the one operation that could pull an entire run into a
	// caller's context, so it is refused past this rather than truncated.
	MaxRemoteLogBytes = 2 << 20
)

Remote bounds and limits. A remote reply is a small protocol document, so the caps are generous for it and deliberately not generous for a transcript.

View Source
const (
	FailureUsage        = "usage"
	FailureConfig       = "config"
	FailureCredential   = "credential"
	FailureProvider     = "provider"
	FailureHarnessMiss  = "harness_missing"
	FailureHarness      = "harness_failed"
	FailureValidation   = "validation_failed"
	FailureTimeout      = "timeout"
	FailureCancelled    = "cancelled"
	FailureBaseMismatch = "base_mismatch"
	FailureWorktree     = "worktree"
	FailureInternal     = "internal"
)

Failure categories are a closed vocabulary: an orchestration decision can branch on the category without parsing a message.

View Source
const (
	ValidationPending = "pending"
	ValidationRunning = "running"
	ValidationPassed  = "passed"
	ValidationFailed  = "failed"
	ValidationSkipped = "skipped"
)

Validation statuses. Validation is its own axis: a process can exit zero and still fail the objective checks.

View Source
const (
	ReviewPending     = "pending"
	ReviewAccepted    = "accepted"
	ReviewRejected    = "rejected"
	ReviewNeedsChange = "needs_changes"
)

Review statuses. Review is the third axis and is written only by an explicit review command.

View Source
const (
	ModeAuto    = "auto"
	ModeCurrent = "current"
	ModePath    = "path"
)

Worktree modes for `run`/`compare`. ModeNew and ModeExisting predate them and stay supported by `dispatch`.

View Source
const (
	AcceptanceRequired = "required"
	AcceptanceOptional = "optional"
)

Acceptance policies a task type can declare.

View Source
const DefaultTimeout = 30 * time.Minute

DefaultTimeout bounds a dispatched run when the caller names no bound.

View Source
const DirName = "agents"

DirName is the directory under WB's home that holds dispatched agent runs.

View Source
const ExecutionModeLinuxContainer = "linux-container"

ExecutionModeLinuxContainer is the only mandatory sandbox mode this WB build knows. A mode it does not know is refused rather than approximated by a weaker one.

View Source
const IDPrefix = "agt-"

IDPrefix begins every agent run ID. The shape follows WB's existing random session-ID convention rather than a timestamp, so an ID never encodes — and therefore never leaks — when or where the work happened.

View Source
const OwnerArgument = "--wb-internal-agent-run"

OwnerArgument selects the private, detached run-owner command. It is handled before normal command dispatch, following WB's existing self-exec convention for internal child processes: the dispatching process re-invokes its own executable with this argument rather than depending on a daemon.

View Source
const ProviderCredentialEnv = "WB_AGENT_PROVIDER_CREDENTIAL"

ProviderCredentialEnv is the environment variable WB synthesises when a provider supplies its credential as a file. The harness is told this name — never a value — so the same per-process mechanism serves both sources.

View Source
const ProviderDshDefault = "deepseek-official"

ProviderDshDefault is the only inference provider the `dsh` compose tree names, so it is the only one this build can prove for that harness. It is not a built-in provider entry: an operator must declare it explicitly under a mandatory execution policy, where the host credential store is unavailable.

View Source
const RemoteArgument = "--wb-internal-agent-remote"

RemoteArgument selects the private remote entry point. It is handled before normal command dispatch on the target machine, so the request can only be a validated protocol value read from stdin — never text the remote shell parsed.

Variables

View Source
var ErrLeaseUnsupported = errors.New("exclusive worktree leases are not supported on this platform")

ErrLeaseUnsupported reports that this platform cannot express an exclusive file lock, so shared-checkout execution must be refused rather than raced.

Functions

func AllHarnesses

func AllHarnesses() []string

AllHarnesses is the ordered list of harness names this build can launch.

func BoundResult

func BoundResult(message string) string

BoundResult trims the worker's final message so the one free-text artefact of a run cannot become the transcript it exists to replace.

func CodexArgv

func CodexArgv(options HarnessOptions) ([]string, error)

CodexArgv builds the exact non-interactive Codex invocation.

The task is deliberately absent: it is delivered on stdin (a trailing "-"), so task text never appears in the process table. Values are JSON-encoded because the harness parses each override value as TOML, where a bare word and a quoted string are different things.

func ContainedLifetime

func ContainedLifetime(runTimeoutMS int64, steps []ValidationStep) (time.Duration, error)

ContainedLifetime returns the finite maximum wall time a contained execution may occupy: the setup pool, the run bound, every validation step's finite/default bound and the cleanup pool. It refuses an unbounded, overflowing or above-maximum total rather than rounding or silently shrinking any part. The addition is overflow-safe by construction: the maximum is subtracted as each component is admitted, so no intermediate or final value can exceed maxContainerLifetime. The setup and cleanup pools are fixed constants validated by test to stay below that maximum.

This is the total-vs-stage contract: the returned value is the whole execution's outer deadline and the container's kernel timeout, not the harness stage alone. Legacy host timeout semantics are untouched.

func ContainedRecordLifetime

func ContainedRecordLifetime(record Record) (time.Duration, error)

ContainedRecordLifetime applies ContainedLifetime to an admitted record's persisted run bound and snapshotted validation steps. It is the convenience entry point a contained owner uses so the same finite bound is computed from exactly what the record carries.

func ContainerSlotStateDir

func ContainerSlotStateDir() (string, error)

ContainerSlotStateDir resolves the fixed per-user default state directory. It is anchored to the trusted owner home, never to XDG_CONFIG_HOME, a worktree, profile, image, project root or policy: a variable configuration directory must not create several independent single-container slots for one user.

func DetectVersion

func DetectVersion(ctx context.Context, harness string, deps PreflightDeps) string

DetectVersion reads the installed harness version, best effort. An unknown version is recorded as absent rather than guessed.

func HarnessCapabilityFor

func HarnessCapabilityFor(harness string) string

HarnessCapabilityFor answers the effort question without instantiating an adapter, so configuration validation and planning share one answer.

func IsRequestError

func IsRequestError(err error) bool

IsRequestError reports whether an error refused the invocation.

func IsUnknownAgent

func IsUnknownAgent(err error) bool

IsUnknownAgent reports whether an error is a lookup miss rather than a corrupt record. A miss is a finding — the invocation was admitted and the named run does not exist — so the CLI can use the findings exit code instead of pretending the caller mistyped.

func IsUnknownExperiment

func IsUnknownExperiment(err error) bool

IsUnknownExperiment reports whether an error is a lookup miss.

func LoadRemoteTargets

func LoadRemoteTargets(configPath string) (map[string]RemoteTarget, error)

LoadRemoteTargets reads the configured machines WB may dispatch to.

It reuses WB's session_move target map on purpose. A machine and its courier address are one fact about the fleet; a second list would be a second place to be wrong, and the operator would have to keep them in step by hand.

func NewExperimentID

func NewExperimentID() string

NewExperimentID mints a fresh experiment ID.

func NewID

func NewID() (string, error)

NewID mints a fresh agent run ID.

func NewRequestError

func NewRequestError(message string) error

NewRequestError marks an error as a refused invocation (exit 2) rather than a finding, for callers outside this package.

func NormalizeState

func NormalizeState(result *Result)

NormalizeState makes this process's closed state vocabulary authoritative for a result that arrived from somewhere else. A remote answer carries a state; whether that state is terminal is WB's rule, so it is derived here rather than trusted from the wire, where a version skew could disagree.

func OwnerCLI

func OwnerCLI(arguments []string, deps OwnerDeps) int

OwnerCLI runs the private owner command line:

wb --wb-internal-agent-run --run-dir <absolute run directory>

It is called from main before cobra parses anything, so the owner can never be affected by, or accidentally honour, a user-facing flag contract.

func Preflight

func Preflight(ctx context.Context, resolved Resolved, deps PreflightDeps) error

Preflight proves an execution can start before anything is created: the harness binary exists, a Codex run has a resolvable credential, and a `dsh` run can prove the model its overlay asks for.

func ReadCredentialFile

func ReadCredentialFile(path string) (string, error)

ReadCredentialFile reads a credential file, refusing anything that is not a private regular file WB itself would have written.

The permission check is deliberate: a credential readable by another account on the machine is not a credential, and discovering that at dispatch time is far better than discovering it in a log.

func RecentActions

func RecentActions(reader io.Reader, limit int) []string

RecentActions condenses the harness event stream into the last few things the worker actually did. It exists so `wb agent logs` can show a human something useful without printing an entire run into a caller's context.

func RedactText

func RedactText(text, secret string) (string, int)

RedactText applies the same rule to a whole value, such as the harness's own final-message file, which it writes itself and which the stream writer never sees.

func RenderDiff

func RenderDiff(ctx context.Context, record Record, patch bool, deps TargetDeps) (string, error)

RenderDiff builds the `wb agent diff` document for one finished run. The short form reports the stat and the untracked paths; the patch form prints the bounded patch itself.

func RequireRunnableExecution

func RequireRunnableExecution(configured, snapshot *ExecutionPolicy, subject, harness string) error

RequireRunnableExecution is the single admission authority for the mandatory sandbox policy. Every host entry point calls it rather than restating the rules: plan admission, the run planner's preflight boundary, runtime failover and the detached run owner.

The user's configuration is the authority, so a snapshot that does not carry exactly the policy this process loaded is refused rather than trusted: a hand-built or stale plan must not become a way to run outside the sandbox. Equality is value equality, because the snapshot is what the record claims. The subject names the document being admitted so a refusal points at the right one.

A matching, valid policy now admits exactly the one harness this build can execute inside the sandbox. Any other harness still refuses: the operator marked the sandbox mandatory, and running a different harness on the host instead would silently weaken it. A fallback profile goes through this same gate, so it cannot become a way around the policy.

func RunOwner

func RunOwner(ctx context.Context, store Store, agentID string, deps OwnerDeps) error

RunOwner executes one dispatched run to completion and records its terminal state. It is the process that outlives the dispatching CLI, so everything a later `status` or `await` can learn about the run is written here.

func SafeCallerID

func SafeCallerID(raw string) string

SafeCallerID returns only short, non-sensitive identifier-shaped metadata. It is used for harness environment values and the remote dispatch boundary.

func SpawnOwner

func SpawnOwner(runDir string, executable func() (string, error), extraFiles []*os.File) (int, error)

SpawnOwner starts the detached run owner for a persisted run and returns without waiting for it. The owner is this same WB executable re-invoked with the private owner argument, so a dispatched run needs no daemon and survives the dispatching CLI exiting.

func SplitAgentRef

func SplitAgentRef(reference string) (machine, agentID string, err error)

SplitAgentRef accepts either a bare agent run ID or the machine-qualified form a remote dispatch prints, so a supervisor can pass back exactly what it was given. An agent ID contains only the prefix and hexadecimal, so the colon is unambiguous.

func SummaryLine

func SummaryLine(task string) string

SummaryLine is the one-line non-sensitive description stored beside the private task so listings and cross-machine checks can name the work without republishing it.

func TaskIdentity

func TaskIdentity(task string) (digest string, size int)

TaskIdentity returns the identity of the exact task bytes without keeping a second copy of them.

func ValidationBudget

func ValidationBudget(steps []ValidationStepResult) time.Duration

ValidationBudget is the worst-case time the snapshotted steps can take, so a caller waiting for a run can bound validation as well as the harness.

func VerifyContainerImage

func VerifyContainerImage(policy ExecutionPolicy, dockerInspectJSON []byte) (string, error)

VerifyContainerImage checks that the inspected image is exactly the immutable image the mandatory policy requested. It returns the runtime's config image ID only after the OS, ID and repository-digest evidence all agree.

A bare policy image (sha256:<64 hex>) must equal the reported config ID. A digest reference (repository@sha256:<64 hex>) must appear verbatim in RepoDigests. A manifest digest is not a config image ID, so neither form is ever satisfied by the other.

func WorkerEnvironment

func WorkerEnvironment(credential Credential) []string

WorkerEnvironment builds the child harness environment.

It is an allowlist, following WB's existing detached-worker convention: a delegated worker gets the variables it genuinely needs and nothing else. That is a stronger guarantee than any deny-list, because a secret this machine happens to export tomorrow is excluded by default rather than by pattern.

Neither a whole-environment copy nor an ambient-agent-variable inheritance is acceptable here: the first hands a model-driven process every credential on the machine, and the second would make a dispatched worker look like the parent session it must not disturb.

Types

type Attempt

type Attempt struct {
	Profile     string `json:"profile"`
	RepeatIndex int    `json:"repeat_index"`
	AgentID     string `json:"agent_id"`
	Operation   string `json:"operation"`
	BaseSHA     string `json:"base_sha,omitempty"`
	Status      string `json:"status"`
	Failure     string `json:"failure,omitempty"`
}

Attempt is one planned execution inside an experiment.

type CallerSession

type CallerSession struct {
	ID              string `json:"session_id,omitempty"`
	WBSessionID     string `json:"wb_session_id,omitempty"`
	NativeHarnessID string `json:"native_harness_id,omitempty"`
	Name            string `json:"name,omitempty"`
	Runtime         string `json:"runtime,omitempty"`
	Source          string `json:"source,omitempty"`
}

CallerSession identifies the session that invoked WB to dispatch this run. The native ID wins when a harness exposes one: several Codex chats can share one app-server PID and therefore one PID-based WB registration.

func (CallerSession) Validate

func (caller CallerSession) Validate() error

Validate constrains caller metadata before another machine persists it.

type ChangeSummary

type ChangeSummary struct {
	FilesChanged int      `json:"files_changed"`
	Files        []string `json:"files,omitempty"`
	Insertions   int      `json:"insertions,omitempty"`
	Deletions    int      `json:"deletions,omitempty"`
	Commits      int      `json:"commits,omitempty"`
	Truncated    bool     `json:"files_truncated,omitempty"`
	// Untracked lists paths Git does not include in a diff, so a reader knows
	// the patch is incomplete rather than assuming a small change.
	Untracked []string `json:"untracked,omitempty"`
}

ChangeSummary is a cheap, deterministic description of what the worker left behind in its worktree.

func SummarizeChangesWith

func SummarizeChangesWith(ctx context.Context, worktreeDir, baseSHA string, preexisting []string) *ChangeSummary

SummarizeChanges derives a cheap, deterministic description of what a worker left behind in its worktree. It reads Git state only; it never reads file contents, so it cannot grow into a transcript and cannot be mistaken for a review of the change.

A failure to read Git state yields no summary rather than a failed run: the worktree is the artefact and a missing diff stat must not hide it. SummarizeChangesWith describes what a worker left behind. The preexisting paths are the ones that were already dirty before it started: when a base commit is known the changed files come from the diff, which includes the worker's commits and excludes pre-existing uncommitted work; otherwise Git status is the only evidence available.

type Config

type Config struct {
	Providers map[string]Provider
	Profiles  map[string]Profile
	TaskTypes map[string]TaskType
	// ConfiguredTaskTypes records which task types came from the operator, so
	// discovery can tell an override from a built-in.
	ConfiguredTaskTypes map[string]bool
	Validations         map[string][]ValidationStep
	Defaults            Defaults
	Fallback            []string
	// Execution is the operator's mandatory execution sandbox, read only from
	// the user's wb.yaml. Nil means the operator configured none, which keeps
	// WB's existing host execution unchanged; a declared policy is never
	// reachable from a profile, a task type or a command-line override.
	Execution *ExecutionPolicy
}

Config is the resolved user agent configuration: providers, profiles, task types, named validation suites, defaults and the ordered fallback list.

func LoadConfigFile

func LoadConfigFile(path string) (Config, error)

LoadConfigFile reads the agent configuration from a wb.yaml document. A missing file is not an error: it yields the built-in provider registry and no profiles, so "no such profile" stays the actionable message rather than "no such file".

func (Config) ProfileNames

func (config Config) ProfileNames() []string

ProfileNames returns every configured profile in name order.

func (Config) ProviderNames

func (config Config) ProviderNames() []string

ProviderNames returns every provider (built-in or overridden) in name order.

func (Config) Resolve

func (config Config) Resolve(name string) (Resolved, error)

Resolve turns a requested profile name into an executable configuration, failing closed on anything it cannot execute.

func (Config) TaskTypesInOrder

func (config Config) TaskTypesInOrder() []string

TaskTypes returns every task type, built-in or configured, in name order.

type ContainedDshLaunch

type ContainedDshLaunch struct {
	Workspace *ContainerWorkspace
	Launch    HarnessLaunch
}

ContainedDshLaunch is one prepared contained launch: the exact trusted workspace (with the newly generated scoped input directory) and the harness invocation whose patch path is the fixed in-container target.

func PrepareContainedDshLaunch

func PrepareContainedDshLaunch(fields ContainedDshLaunchFields) (ContainedDshLaunch, error)

PrepareContainedDshLaunch writes the exact scoped input directory and returns the workspace and harness launch. It creates no other file or mount, so a caller cannot add an input file, reuse the run store or point the harness at a host harness home.

func PrepareContainedDshLaunchFromRecord

func PrepareContainedDshLaunchFromRecord(record Record, runDir, credentialEnvName string) (ContainedDshLaunch, error)

PrepareContainedDshLaunchFromRecord prepares a launch from an admitted run record. It trusts only the record's snapped workspace, refuses any input directory the record tries to supply, and requires the resolved credential name to match the record's own routing.

type ContainedDshLaunchFields

type ContainedDshLaunchFields struct {
	RunDir            string
	WorktreeDir       string
	GitCommonDir      string
	Provider          string
	Harness           string
	Model             string
	Task              string
	BaseURL           string
	CredentialEnvName string
}

ContainedDshLaunchFields are the exact public inputs to one contained dsh preparation. Provider and Harness are exact names, not aliases; Model is passed through verbatim. CredentialEnvName is a variable *name*; the value is never an input here.

type ContainerCgroupValues

type ContainerCgroupValues struct {
	MemoryMax     string
	MemorySwapMax string
	CPUMax        string
	PIDsMax       string
}

ContainerCgroupValues carries the raw, untrimmed contents of the four cgroup files that prove a container received the mandatory bounds. They are kept as raw text rather than parsed values so the verifier remains the only parser and can report a field-specific refusal.

type ContainerReservation

type ContainerReservation struct {
	RunID       string `json:"run_id"`
	Name        string `json:"name"`
	Nonce       string `json:"nonce"`
	ContainerID string `json:"container_id,omitempty"`
	DaemonID    string `json:"daemon_id,omitempty"`
}

ContainerReservation is the durable identity of the one container the slot is about to create, or has created. It carries no credentials, no argv and no raw Docker output. ContainerID is empty until RecordContainerID records what the runtime returned. DaemonID binds the reservation to the exact Docker Engine that owns the container, so absence on a different daemon can never clear it.

type ContainerRuntime

type ContainerRuntime struct {
	// contains filtered or unexported fields
}

ContainerRuntime is one open, verified contained execution. It owns the durable reservation, the attach pipe and the exact container identity until Close proves the container absent and clears the reservation.

func OpenContainerRuntime

func OpenContainerRuntime(ctx context.Context, options ContainerRuntimeOptions) (*ContainerRuntime, error)

OpenContainerRuntime admits exactly one contained execution. The durable global slot is taken before any Docker probe, a prior reservation is either recovered from a proven-stopped exact owned container or blocks, and the returned runtime is ready only after the image identity, the actual HostConfig bounds and the four cgroup files have been verified.

Every error after the reservation is made runs the same independent cleanup: close the writer, remove only the exact owned container, prove absence, then clear the reservation. A cleanup failure is joined into the returned error and leaves the durable reservation in place, so the next attempt is blocked until someone proves absence.

func (*ContainerRuntime) Close

func (runtime *ContainerRuntime) Close() error

Close cleans up the exact owned container and releases the slot. It is idempotent; a repeated Close returns the first result rather than pretending a failed cleanup succeeded. Cleanup uses its own finite context, so a canceled caller cannot shorten the absence proof.

func (*ContainerRuntime) ContainerID

func (runtime *ContainerRuntime) ContainerID() string

ContainerID returns the full Docker ID of the verified container.

func (*ContainerRuntime) ExecArgv

func (runtime *ContainerRuntime) ExecArgv(argv []string) ([]string, error)

ExecArgv is the narrow builder a later owner uses to run one worker command. It fixes the exact container ID and the current owner's numeric UID/GID, and passes argv through without a shell. It adds no environment, mount or user-supplied Docker option.

func (*ContainerRuntime) ImageID

func (runtime *ContainerRuntime) ImageID() string

ImageID returns the immutable config image ID the container was created from.

func (*ContainerRuntime) PrepareWorkerHome

func (runtime *ContainerRuntime) PrepareWorkerHome(ctx context.Context) error

PrepareWorkerHome creates the private worker HOME and every fixed /tmp cache directory inside the already verified container, as the unprivileged owner. The template is copied with a plain recursive copy, which does not attempt to preserve host ownership, and no host home, session or credential is copied.

func (*ContainerRuntime) ValidationTransport

func (runtime *ContainerRuntime) ValidationTransport() ValidationCommandFactory

ValidationTransport returns the credential-free command factory a contained validation run uses. The factory receives only the step argv, targets the same verified container and worktree as the harness, and keeps the bounded Docker client transport captured by this runtime. It cannot fall back to a host command: a runtime that cannot build the command returns the error instead.

func (*ContainerRuntime) VerifiedLimits

func (runtime *ContainerRuntime) VerifiedLimits() ContainerVerifiedLimits

VerifiedLimits returns the bounds independently read from the container's cgroup files. It is only meaningful once Open has returned successfully.

func (*ContainerRuntime) WorkerCommand

func (runtime *ContainerRuntime) WorkerCommand(ctx context.Context, credential Credential, argv []string) (*exec.Cmd, error)

WorkerCommand builds the one Docker exec client a later owner uses for a worker command. The argv carries the exact verified container ID, the numeric owner and an explicit workdir, and passes the supplied argv without a shell. The credential contributes only its environment name to argv; its value travels in the Docker client environment and is never stored on the runtime or in a log.

type ContainerRuntimeOptions

type ContainerRuntimeOptions struct {
	Policy    ExecutionPolicy
	RunID     string
	Lifetime  time.Duration
	Workspace *ContainerWorkspace
	// contains filtered or unexported fields
}

ContainerRuntimeOptions is the complete input to one contained execution. There is no field for extra Docker arguments, mounts, ports, environment or credentials: an unsupported need is refused later, not smuggled through here.

Workspace is the one closed set of trusted host paths a later admission layer supplies. A nil Workspace keeps the lifecycle-only probe behaviour and plans no host mounts at all.

The unexported fields are private dependency seams for focused tests. A production caller leaves them empty, which selects the fixed per-user state directory, the real docker binary and the current owner's UID/GID.

type ContainerSlot

type ContainerSlot struct {
	// contains filtered or unexported fields
}

ContainerSlot is one retained holder. The open descriptor and its kernel lock are the authority; the reservation file is the durable record a later holder must see.

func OpenContainerSlot

func OpenContainerSlot(stateDir string) (*ContainerSlot, error)

OpenContainerSlot takes the durable slot under stateDir. An empty stateDir means the fixed per-user default, which is what production always uses; a non-empty one is the focused-test seam. A held slot is reported as *ContainerSlotBusyError, and a platform without an inherited exclusive lock fails closed rather than pretending to serialize.

func (*ContainerSlot) ClearReservation

func (slot *ContainerSlot) ClearReservation(confirmAbsent func(ContainerReservation) error) error

ClearReservation removes the durable reservation only after confirmAbsent proves, under the retained lock, that the exact prior container is gone. The callback is mandatory: there is no boolean bypass and no Docker assumption. A callback error leaves the reservation unchanged.

func (*ContainerSlot) Close

func (slot *ContainerSlot) Close() error

Close releases the kernel lock and descriptor but never clears the reservation. The next holder sees it and must explicitly prove absence.

func (*ContainerSlot) RecordContainerID

func (slot *ContainerSlot) RecordContainerID(containerID string) error

RecordContainerID persists the runtime's ID for the existing reservation. It refuses to record anything without one, so an ID never becomes an orphan authority of its own. The assignment is single: re-recording the same ID is an idempotent success, but a different ID is refused so the first container identity can never be orphaned.

func (*ContainerSlot) Reservation

func (slot *ContainerSlot) Reservation() (ContainerReservation, bool)

Reservation returns a value copy of the reservation, or false when the slot holds none. A caller never receives a mutable alias into the authority.

func (*ContainerSlot) Reserve

func (slot *ContainerSlot) Reserve(reservation ContainerReservation) error

Reserve claims the slot for a container that does not exist yet. It refuses any existing reservation and persists the new one before a runtime may create a container. A failed save leaves the reservation pending, so an uncertain save can never look like a free slot.

type ContainerSlotBusyError

type ContainerSlotBusyError struct {
	Path string
}

ContainerSlotBusyError reports that another live holder owns the slot. It is a refusal, not a queue: await or stop the current owner instead of racing it.

func (*ContainerSlotBusyError) Error

func (err *ContainerSlotBusyError) Error() string

type ContainerVerifiedLimits

type ContainerVerifiedLimits struct {
	MemoryBytes     int64 `json:"memory_bytes"`
	MemorySwapBytes int64 `json:"memory_swap_bytes"`
	CPUCount        int   `json:"cpu_count"`
	PIDsLimit       int   `json:"pids_limit"`
}

ContainerVerifiedLimits is the typed set of bounds observed in cgroup files. It is returned only when all four limits verified, so a caller can never hold a partially verified result. The fields carry no paths, IDs or secrets.

func VerifyContainerCgroup

func VerifyContainerCgroup(policy ExecutionPolicy, values ContainerCgroupValues) (ContainerVerifiedLimits, error)

VerifyContainerCgroup checks that the four raw cgroup files apply exactly the mandatory policy: memory.max equals memory_bytes, memory.swap.max is zero, pids.max equals pids_limit, and cpu.max is a finite quota/period pair whose ratio is exactly cpu_count.

type ContainerWorkspace

type ContainerWorkspace struct {
	WorktreeDir  string `json:"worktree_dir"`
	GitCommonDir string `json:"git_common_dir"`
	InputDir     string `json:"input_dir,omitempty"`
}

ContainerWorkspace is the complete and closed set of host paths a contained execution may mount. It is trusted admission data produced from WB's canonical/worktree metadata; it is not repository configuration, a profile field or a command-line option.

WorktreeDir is the exact linked worktree and the only read-write host path. GitCommonDir is the canonical git directory that worktree's .git pointer names; it is read-only. InputDir is an optional directory already scoped to this run, mounted read-only at the fixed /wb-input target. Empty InputDir means no input mount.

func SnapshotExecutionWorkspace

func SnapshotExecutionWorkspace(workspace *ContainerWorkspace) *ContainerWorkspace

SnapshotExecutionWorkspace copies a workspace by value. Admission snapshots the trusted paths into the durable record, so a later mutation of the source value cannot rewrite what a run was required to mount.

type CostRecord

type CostRecord struct {
	USD            *float64   `json:"usd,omitempty"`
	Kind           string     `json:"kind"`
	Source         string     `json:"source"`
	PricingVersion string     `json:"pricing_version,omitempty"`
	EstimatedAt    *time.Time `json:"estimated_at,omitempty"`
	Note           string     `json:"note,omitempty"`
}

CostRecord is an API-equivalent estimate, never a billed amount. A nil USD means no per-run price was observed.

type Credential

type Credential struct {
	EnvName string
	Value   string
}

Credential is a resolved provider credential: the environment variable name the harness must read it from, and the value WB injects under that name. The value never leaves the child's environment.

func ResolveCredential

func ResolveCredential(provider Provider) (Credential, error)

ResolveCredential reads the credential a provider names, from whichever source that provider configured. It fails closed with a message naming the exact source, because a missing credential is the single most likely reason a dispatch cannot start.

type Defaults

type Defaults struct {
	TaskType string `yaml:"task_type,omitempty" json:"task_type,omitempty"`
	Profile  string `yaml:"profile,omitempty" json:"profile,omitempty"`
}

Defaults are the values a request inherits when it names neither a task type nor a profile. They exist so an operator can make one command the default without editing every task type.

type DispatchDeps

type DispatchDeps struct {
	ConfigPath   string
	LoadConfig   func() (Config, error)
	ProjectsRoot string
	Home         string
	Caller       CallerSession
	// BeforeCreate refreshes managed hooks in the canonical clones, exactly as
	// `wb worktree create` does before it creates anything.
	BeforeCreate func(repositories []string) error
	// AfterCreate writes the checkout marker exactly as `wb worktree create`
	// does after creation. It MUST be best-effort: a marker WB could not write
	// does not make a checkout unusable.
	AfterCreate func(repositories []string, results []worktrees.CreateResult)
	// CreateWorktree, ListWorktrees, and OriginSlug default to WB's own
	// worktree service. They are injectable only so the orchestration above them
	// can be exercised without a live fleet; production never replaces them.
	CreateWorktree func(context.Context, []string, worktrees.CreateOptions) ([]worktrees.CreateResult, error)
	ListWorktrees  func(context.Context, worktrees.ListOptions) ([]worktrees.ListResult, error)
	OriginSlug     func(context.Context, string) (string, error)
	// SpawnOwner starts the detached run owner for a persisted run and returns
	// its process ID. extraFiles carry the inherited writer lease, so the claim
	// lives exactly as long as the owner or anything it starts.
	SpawnOwner func(agentID string, extraFiles []*os.File) (int, error)
	// Preflight proves the resolved profile can start before a worktree exists.
	Preflight func(context.Context, Resolved) error
	// DetectVersion reads the installed harness version, best effort.
	DetectVersion func(context.Context, string) string
	Now           func() time.Time
}

DispatchDeps are the seams dispatch needs from the command layer. Only the things internal/agents cannot know about — WB's CLI-layer worktree side effects, and how a detached owner is started — are injected; everything else is reused directly.

type DispatchRequest

type DispatchRequest struct {
	Mode     string
	Worktree string

	// Plan is the resolved execution plan. When it is nil the request is the
	// legacy `dispatch` shape and Profile is resolved on its own.
	Plan    *Plan
	Profile string
	Task    string

	// Repository is owner/repository. Empty means "derive it from the invoking
	// checkout's origin", exactly as `wb worktree create` does.
	Repository string
	// Branch and Base are optional pass-throughs to WB's existing worktree
	// naming policy; empty leaves that policy in charge.
	Branch string
	Base   string

	Timeout        time.Duration
	AllowCanonical bool
	AllowDirty     bool

	// AgentID lets a caller pre-allocate the identity, which an experiment must
	// do before it records its plan. Empty mints a fresh one.
	AgentID string
	// ExperimentID and RepeatIndex place this execution in a comparison.
	ExperimentID string
	RepeatIndex  int

	// RetryOf, FallbackFrom and FallbackReason describe an infrastructure
	// failover: this execution replaces another one after its provider failed.
	RetryOf        string
	FallbackFrom   string
	FallbackReason string
}

DispatchRequest is one requested offload.

type ExecutionPolicy

type ExecutionPolicy struct {
	// Mode is the sandbox kind. Only linux-container is accepted.
	Mode string `yaml:"mode" json:"mode"`
	// Image is an immutable container image identity: a reference pinned by a
	// sha256 digest, or a sha256 image ID. A mutable tag such as :latest is
	// refused because it can change between two runs.
	Image string `yaml:"image" json:"image"`
	// MemoryBytes is the hard memory limit the container runtime must apply.
	MemoryBytes int64 `yaml:"memory_bytes" json:"memory_bytes"`
	// MemorySwapBytes is the *total* memory-plus-swap limit. Mandatory policy
	// requires it to equal MemoryBytes, so a run can never borrow swap beyond
	// its memory bound.
	MemorySwapBytes int64 `yaml:"memory_swap_bytes" json:"memory_swap_bytes"`
	// CPUCount is the number of CPUs the sandbox may use.
	CPUCount int `yaml:"cpu_count" json:"cpu_count"`
	// PIDsLimit bounds the processes one sandbox may create.
	PIDsLimit int `yaml:"pids_limit" json:"pids_limit"`
	// MaxParallel is how many container executions may run at once. This build
	// supports exactly one.
	MaxParallel int `yaml:"max_parallel" json:"max_parallel"`
}

ExecutionPolicy is the operator's mandatory execution sandbox, declared once at the top level of the user's wb.yaml under agents.execution.

It is deliberately independent of profiles, task types and command-line overrides: nothing below a run request can reach these fields, and there is no field here that lowers, replaces or disables another one. Absent means the operator declared no mandatory sandbox and WB keeps its existing host behaviour; present means every field must be usable exactly as written.

func LoadDefaultExecutionPolicy

func LoadDefaultExecutionPolicy() (*ExecutionPolicy, error)

LoadDefaultExecutionPolicy reads the operator's authoritative mandatory execution policy from the user's wb.yaml. A missing configuration declares no policy and is not an error; a configuration that cannot be read is, because the owner must not fall back to "no policy" on a broken file.

func SnapshotExecution

func SnapshotExecution(policy *ExecutionPolicy) *ExecutionPolicy

SnapshotExecution copies a configured policy so a plan or record keeps the exact values that were resolved, even if the caller's configuration value is later reused or mutated.

func (*ExecutionPolicy) UnmarshalYAML

func (policy *ExecutionPolicy) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML refuses an unsupported key instead of ignoring it. Arbitrary runtime arguments, mounts and security options are exactly what must never reach the container runtime through a policy, and a silently dropped key would make a weakened policy look accepted.

type ExecutionRuntimeFacts

type ExecutionRuntimeFacts struct {
	ContainerID     string                   `json:"container_id,omitempty"`
	ResolvedImageID string                   `json:"resolved_image_id,omitempty"`
	VerifiedLimits  *ContainerVerifiedLimits `json:"verified_limits,omitempty"`
	CleanupPending  bool                     `json:"cleanup_pending,omitempty"`
	CleanupVerified bool                     `json:"cleanup_verified,omitempty"`
	CleanupFailed   bool                     `json:"cleanup_failed,omitempty"`
	CleanupFailure  string                   `json:"cleanup_failure,omitempty"`
}

ExecutionRuntimeFacts is the runtime identity and cleanup evidence for one contained execution. It is written only after the verified runtime has actually opened, and it carries no credential, argv or raw transcript: only the exact identities and verified limits a later reader needs to trust the run.

A nil value means no fully verified runtime receipt was written, not that no container ever existed: a refused or failed open can still have created a container, and in that case cleanup failure is held in the durable per-user slot rather than in this record. Once the field exists, exactly one cleanup field is true: CleanupPending until cleanup starts, then CleanupVerified or CleanupFailed. CleanupFailure is the bounded reason a failed cleanup could not prove the container absent.

func SnapshotExecutionRuntimeFacts

func SnapshotExecutionRuntimeFacts(facts *ExecutionRuntimeFacts) *ExecutionRuntimeFacts

SnapshotExecutionRuntimeFacts copies runtime facts by value, including the verified limits, so a rendered result never aliases a durable record.

type ExecutionStatus

type ExecutionStatus string

ExecutionStatus is the richer, additive status of one execution. It never replaces State: an older build must still be able to list and await a record this build wrote.

const (
	StatusQueued    ExecutionStatus = "queued"
	StatusRunning   ExecutionStatus = "running"
	StatusCompleted ExecutionStatus = "completed"
	StatusFailed    ExecutionStatus = "failed"
	StatusCancelled ExecutionStatus = "cancelled"
	StatusTimedOut  ExecutionStatus = "timed_out"
	// StatusAbandoned is derived at read time when the owner process vanished
	// without recording a terminal status. It is never stored.
	StatusAbandoned ExecutionStatus = "abandoned"
)

func (ExecutionStatus) String

func (status ExecutionStatus) String() string

String is the string form of an execution status.

func (ExecutionStatus) Terminal

func (status ExecutionStatus) Terminal() bool

Terminal reports whether an execution status is final.

type Experiment

type Experiment struct {
	SchemaVersion int       `json:"schema_version"`
	ExperimentID  string    `json:"experiment_id"`
	TaskSHA256    string    `json:"task_sha256"`
	TaskBytes     int       `json:"task_bytes"`
	TaskType      string    `json:"task_type"`
	Complexity    string    `json:"complexity,omitempty"`
	Base          string    `json:"base,omitempty"`
	BaseSHA       string    `json:"base_sha,omitempty"`
	Profiles      []string  `json:"profiles"`
	Repeat        int       `json:"repeat"`
	Concurrency   int       `json:"concurrency"`
	Attempts      []Attempt `json:"attempts"`
	CreatedAt     time.Time `json:"created_at"`
	// UncontrolledDifferences states what WB could not hold equal across
	// attempts, so a reader never mistakes a comparison for a controlled trial.
	UncontrolledDifferences []string `json:"uncontrolled_differences,omitempty"`
}

Experiment is the immutable description of one comparison: one task, one base, several profiles and repeats. It is written once, before any execution starts, and never rewritten; member results live in their own run records.

type ExperimentReport

type ExperimentReport struct {
	Experiment
	Runs      []Result         `json:"runs"`
	Summaries []ProfileSummary `json:"summaries"`
}

ExperimentReport is the persisted experiment plus its member results and the per-profile rollup.

type Harness

type Harness interface {
	Name() string
	Capabilities() HarnessCapabilities
	Prepare(Launch) (HarnessLaunch, error)
	Summarize(io.Reader) HarnessSummary
	Actions(io.Reader, int) []string
}

Harness is one coding-agent adapter. Each implementation has its own file in this package and a name in supportedHarnesses.

func HarnessFor

func HarnessFor(name string) (Harness, error)

HarnessFor returns the adapter for a harness name.

type HarnessCapabilities

type HarnessCapabilities struct {
	Harness      string `json:"harness"`
	JSONEvents   bool   `json:"json_events"`
	TaskDelivery string `json:"task_delivery"`
	TokenUsage   string `json:"token_usage"`
	Cost         string `json:"cost"`
	Effort       string `json:"effort"`
	Credential   string `json:"credential_source"`
	Isolation    string `json:"isolation"`
	// Version is filled from the installed binary at dispatch time; it is
	// empty in a dry run, which starts no process.
	Version string `json:"version,omitempty"`
}

HarnessCapabilities is what WB can prove about one adapter. It is recorded on every run so a comparison can state which differences were not controlled.

type HarnessLaunch

type HarnessLaunch struct {
	Argv  []string
	Env   []string
	Stdin string
	// PrivateFiles are paths the adapter wrote for this launch, recorded so a
	// reader can find them; they live under the private run directory.
	PrivateFiles []string
	// SplitStderr keeps stderr out of the captured result stream. An adapter
	// whose stdout *is* the final message needs it: merged diagnostics would
	// become part of the answer.
	SplitStderr bool
}

HarnessLaunch is the exact process an adapter wants WB to start. Nothing about a harness's flag spelling lives above this boundary.

type HarnessOptions

type HarnessOptions struct {
	WorktreeDir string
	Model       string
	Reasoning   string
	// ProviderName keys the provider registry entry, and Provider carries the
	// routing. The credential itself is never here — only the environment
	// variable name the harness must read it from.
	ProviderName string
	Provider     Provider
	// LastMessagePath asks the harness to write its final message there, which
	// is the one bounded, non-transcript result channel.
	LastMessagePath string
}

HarnessOptions is everything the Codex harness needs that is not in the process environment. It exists so every harness-specific flag and configuration-key spelling lives in exactly one file: a harness version change is a one-file change.

type HarnessSummary

type HarnessSummary struct {
	TurnCompleted bool
	TurnFailed    bool
	// Tokens is nil when the harness reported no usage at all; a harness that
	// reports zeros fills the pointers with zeros.
	Tokens *Tokens
	// CostUSD is a per-run cost the harness itself estimated. It is nil when the
	// harness reports none, and zero values are rejected by CostRecord.
	CostUSD *float64
	// CostNote explains a reported-but-unusable cost, such as a zero cost on a
	// subscription plan.
	CostNote  string
	ToolCalls int
	// Diagnostics are non-fatal harness messages worth keeping in the record.
	Diagnostics []string
	// MalformedLines counts lines that look like harness events but could not
	// be decoded. Ordinary non-JSON output is a harness's own stderr sharing the
	// file and is expected; a malformed *event* is not.
	MalformedLines int
	// FinalMessage is set by adapters whose only output is the final message,
	// such as `dsh`.
	FinalMessage string
}

HarnessSummary is what the run owner extracts from one harness stream. It is execution metadata only: nothing here judges whether the work is correct.

func SummarizeEvents

func SummarizeEvents(reader io.Reader) HarnessSummary

SummarizeEvents parses the Codex JSONL event stream.

type Launch

type Launch struct {
	Timeout         time.Duration
	RunDir          string
	WorktreeDir     string
	Model           string
	Variant         string
	Effort          string
	ProviderName    string
	Provider        Provider
	LastMessagePath string
	// Task is used only by adapters that deliver the task on the command line.
	Task string
}

Launch is everything an adapter needs to build one non-interactive run.

type Lease

type Lease struct {
	// contains filtered or unexported fields
}

Lease is an exclusive writer claim on one worktree. The open descriptor is what holds the claim, so the claim survives as long as any process inheriting it lives.

func (*Lease) File

func (lease *Lease) File() *os.File

File is the descriptor a dispatcher passes to the detached owner. Inheriting it is what keeps the claim held until the last worker process exits.

func (*Lease) Path

func (lease *Lease) Path() string

Path is the retained lease file path.

func (*Lease) Release

func (lease *Lease) Release() error

Release drops the claim. The file is never removed, so a concurrent acquirer can never lock a different inode than the one it opened.

func (*Lease) SetOwner

func (lease *Lease) SetOwner(ownerPID int) error

SetOwner records the detached owner's PID for diagnostics after the spawn.

type LeaseHeldError

type LeaseHeldError struct {
	Info LeaseInfo
	Path string
}

LeaseHeldError reports that another live execution owns a worktree. It names the owner so the caller can await or stop that run instead of guessing.

func (*LeaseHeldError) Error

func (err *LeaseHeldError) Error() string

type LeaseInfo

type LeaseInfo struct {
	SchemaVersion int       `json:"schema_version"`
	AgentID       string    `json:"agent_id"`
	ExperimentID  string    `json:"experiment_id,omitempty"`
	Repository    string    `json:"repository,omitempty"`
	WorktreeDir   string    `json:"worktree_dir"`
	OwnerPID      int       `json:"owner_pid,omitempty"`
	ClaimedAt     time.Time `json:"claimed_at"`
}

LeaseInfo is the diagnostic body of a lease file. It is never the authority: the authority is the kernel's lock on the retained inode.

type OwnerDeps

type OwnerDeps struct {
	// LookPath resolves the harness executable. Resolving it by name through
	// PATH is what lets a test substitute a fake harness without a production
	// override flag.
	LookPath func(string) (string, error)
	// Now is the clock, injected for deterministic tests.
	Now func() time.Time
	// Sleep is StopRun's grace-period poll seam, injected for deterministic
	// tests. A test exercising a worker that ignores termination shrinks
	// StopGrace/StopPollInterval instead of leaving Sleep real, because that
	// path genuinely waits on a real OS process; every other test replaces
	// Sleep with a recorder.
	Sleep func(time.Duration)
	// StopGrace and StopPollInterval configure StopRun's escalation wait.
	// Both are struct fields, not package-level mutable vars, so a test
	// cannot leave shared package state mutated for another test running in
	// parallel. StopRun does not default a zero OwnerDeps -- every caller
	// (production and test) builds on DefaultOwnerDeps, which already
	// populates every field, so StopRun trusts deps as given.
	StopGrace        time.Duration
	StopPollInterval time.Duration
	// Lease is the inherited worktree claim. Production reads the descriptor the
	// dispatcher passed; a test supplies a file it already holds a lock on.
	Lease *os.File
	// Validation runs the snapshotted objective checks. It is a seam so a test
	// can assert the environment and the inherited lease without spawning a
	// process tree.
	Validation func(context.Context, ValidationOptions) ValidationRecord
	// LoadExecutionPolicy re-reads the operator's authoritative mandatory
	// execution policy before this owner starts anything. A nil seam is
	// defaulted by RunOwner to LoadDefaultExecutionPolicy: an owner must never
	// treat "no loader injected" as "no mandatory sandbox". Tests that need the
	// historical host behaviour inject an explicit loader that returns nil.
	LoadExecutionPolicy func() (*ExecutionPolicy, error)
	// CancelPollInterval is how often a contained execution checks the durable
	// cancellation sentinel during setup, the harness and validation. Zero
	// selects the production default. It is a struct field, not package state.
	CancelPollInterval time.Duration
	// contains filtered or unexported fields
}

OwnerDeps are the seams the run owner needs. They are injected so the whole owner can be exercised deterministically against a fake harness.

func DefaultOwnerDeps

func DefaultOwnerDeps() OwnerDeps

DefaultOwnerDeps returns the production seams. Lease is deliberately not set here: only OwnerCLI, the detached entry point, may adopt an inherited descriptor, because a test process's fd 3 is not a lease.

LoadExecutionPolicy is deliberately not set here even though RunOwner defaults a nil seam to the authoritative loader: keeping it absent lets a test see whether it injected an explicit policy seam, and ProductionOwnerDeps makes the production wiring unambiguous.

func ProductionOwnerDeps

func ProductionOwnerDeps() OwnerDeps

ProductionOwnerDeps is DefaultOwnerDeps plus the authoritative policy loader. It is the wiring the detached owner entry point uses, and a direct RunOwner gets the same authority because a nil loader is defaulted rather than read as "no mandatory sandbox".

type Plan

type Plan struct {
	TaskType       string   `json:"task_type"`
	TaskTypeSource string   `json:"task_type_source"`
	Profile        Resolved `json:"profile"`
	ProfileSource  string   `json:"profile_source"`

	// Execution is the user-level mandatory execution policy snapshotted from
	// configuration. It is absent when the operator configured none, and it is
	// never derived from the resolved profile, task type or request, so no
	// fallback or override can change it.
	Execution *ExecutionPolicy `json:"execution,omitempty"`

	Complexity           string `json:"complexity,omitempty"`
	ComplexitySource     string `json:"complexity_source,omitempty"`
	ComplexityOverridden bool   `json:"complexity_overridden,omitempty"`

	EffortRequested string `json:"effort_requested,omitempty"`
	EffortSource    string `json:"effort_source,omitempty"`
	EffortEffective string `json:"effort_effective,omitempty"`
	EffortApplied   bool   `json:"effort_applied"`
	EffortVariant   string `json:"effort_variant,omitempty"`
	EffortNote      string `json:"effort_note,omitempty"`

	WorktreeMode   string `json:"worktree_mode"`
	WorktreeSource string `json:"worktree_source"`

	TimeoutMS     int64  `json:"timeout_ms"`
	TimeoutSource string `json:"timeout_source"`

	Validation       []string         `json:"validation,omitempty"`
	ValidationSource string           `json:"validation_source"`
	ValidationSteps  []ValidationStep `json:"validation_steps,omitempty"`

	AcceptanceRequired bool `json:"acceptance_required"`

	// FallbackFrom names the profile the plan would have used when preflight
	// substituted a configured fallback. Empty means no substitution happened.
	FallbackFrom string `json:"fallback_from,omitempty"`
	// FallbackReason explains a preflight substitution: why the chosen profile
	// was unusable.
	FallbackReason string `json:"fallback_reason,omitempty"`
	// FallbackChain is the remaining ordered profiles a runtime failover may
	// use, after the chosen one. Empty when the task type declares none.
	FallbackChain []string `json:"fallback_chain,omitempty"`
	// FallbackOn records which triggers are enabled for this plan.
	FallbackOn []string `json:"fallback_on,omitempty"`
	// contains filtered or unexported fields
}

Plan is one fully resolved execution. It is the `--dry-run` document and the provenance snapshot a run record keeps for each resolved value.

func (Plan) AllowsFallback

func (plan Plan) AllowsFallback(trigger string) bool

AllowsFallback reports whether a plan permits the given trigger.

type Planner

type Planner struct {
	Config Config
	Probe  func(Resolved) error
}

Planner resolves requests against one configuration. Probe is the preflight a caller can supply — harness present, credential resolvable — and is the only reason a plan can fall back to another configured profile.

func (Planner) Plan

func (planner Planner) Plan(request RunRequest) (Plan, error)

Plan resolves one request, failing closed on anything it cannot execute.

type PreflightDeps

type PreflightDeps struct {
	LookPath          func(string) (string, error)
	ResolveCredential func(Provider) (Credential, error)
	Run               func(ctx context.Context, name string, args ...string) ([]byte, error)
	TempDir           func() (string, error)
}

PreflightDeps are the seams preflight needs.

func DefaultPreflightDeps

func DefaultPreflightDeps() PreflightDeps

DefaultPreflightDeps returns the production seams.

type PreparedRun

type PreparedRun struct {
	Record Record
	Lease  *Lease
	// Store is the run store the record lives in, so an aborted preparation can
	// still be recorded as a terminal failure.
	Store Store
}

PreparedRun is an admitted execution: resolved, recorded, leased and waiting for its owner. Splitting preparation from start is what lets a comparison create every worktree — and therefore pin every base — before any worker runs.

func PrepareRun

func PrepareRun(ctx context.Context, request DispatchRequest, deps DispatchDeps) (*PreparedRun, error)

PrepareRun resolves the plan, proves it can start, resolves or creates the worktree, takes the writer lease, and persists the run record. It starts no process, so a caller can prepare several attempts and start them later.

func (*PreparedRun) Fail

func (prepared *PreparedRun) Fail(state State, failure, category string, now func() time.Time) error

Fail records a terminal failure for a run that never started, or whose owner could not be launched.

type Profile

type Profile struct {
	Harness  string `yaml:"harness" json:"harness"`
	Provider string `yaml:"provider,omitempty" json:"provider,omitempty"`
	Model    string `yaml:"model" json:"model"`
	// Variant is an OpenCode model variant, passed as --variant when the
	// argv is built. It is a separate field because "#" is not a legal
	// execution identifier and because a variant name is model-specific.
	Variant string `yaml:"variant,omitempty" json:"variant,omitempty"`
	// EffortVariants maps a WB effort level to the harness's own variant name.
	// An effort with no mapping is not applied to OpenCode.
	EffortVariants map[string]string `yaml:"effort_variants,omitempty" json:"effort_variants,omitempty"`
	// Effort is the profile's default reasoning effort. Reasoning is the
	// legacy spelling of the same thing; naming both is an error.
	Effort    string `yaml:"effort,omitempty" json:"effort,omitempty"`
	Reasoning string `yaml:"reasoning,omitempty" json:"reasoning,omitempty"`
	// Timeout is a Go duration string bounding one run with this profile.
	Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}

Profile is a named agent execution configuration. It is intentionally this small: harness + provider + model + optional effort and timeout, and nothing else. Nothing here names a model WB ships: the operator's configuration is the only place a model identifier exists.

type ProfileSummary

type ProfileSummary struct {
	Profile   string `json:"profile"`
	Attempts  int    `json:"attempts"`
	Completed int    `json:"completed"`
	Failed    int    `json:"failed"`
	Validated int    `json:"validated"`
	Accepted  int    `json:"accepted"`
	// MeanDurationMS is the mean wall time of terminal attempts, or nil when
	// none finished.
	MeanDurationMS *int64 `json:"mean_duration_ms,omitempty"`
	// TotalTokens is nil unless every completed attempt reported usage.
	TotalTokens *int `json:"total_tokens,omitempty"`
}

ProfileSummary aggregates the attempts of one profile.

type Provider

type Provider struct {
	BaseURL string `yaml:"base_url" json:"base_url"`
	// CredentialEnv is the *name* of the environment variable holding the
	// credential. The value is read from the process environment at launch and
	// never persisted.
	CredentialEnv string `yaml:"credential_env,omitempty" json:"credential_env,omitempty"`
	// CredentialFile is an absolute path to a private file holding the
	// credential, following WB's existing credential-file convention (a path in
	// configuration, the secret in a 0600 file under
	// ~/.config/wb/credentials). It exists because a dispatched worker needs its
	// credential in the harness's environment, and a remote machine reachable
	// only over non-interactive SSH has no reliable place to export one.
	CredentialFile string `yaml:"credential_file,omitempty" json:"credential_file,omitempty"`
	WireAPI        string `yaml:"wire_api" json:"wire_api"`
}

Provider is one entry in the provider registry: where inference lives, which environment variable carries its credential, and which wire protocol the harness must use. It never carries the credential itself.

type Record

type Record struct {
	SchemaVersion int    `json:"schema_version"`
	AgentID       string `json:"agent_id"`
	State         State  `json:"state"`
	// ExecutionStatus is the additive status; empty on a record written before
	// this field existed, in which case it is derived from State.
	ExecutionStatus ExecutionStatus `json:"execution_status,omitempty"`
	FailureCategory string          `json:"failure_category,omitempty"`

	// RequestedProfile is what the caller asked for. Resolved is what actually
	// ran; keeping both is what makes a later profile edit harmless.
	RequestedProfile string   `json:"requested_profile"`
	Resolved         Resolved `json:"resolved"`

	// Routing provenance: every resolved value says where it came from.
	TaskType       string `json:"task_type,omitempty"`
	TaskTypeSource string `json:"task_type_source,omitempty"`
	ProfileSource  string `json:"profile_source,omitempty"`
	RoutingReason  string `json:"routing_reason,omitempty"`

	Complexity           string `json:"complexity,omitempty"`
	ComplexitySource     string `json:"complexity_source,omitempty"`
	ComplexityOverridden bool   `json:"complexity_overridden,omitempty"`

	EffortRequested string `json:"effort_requested,omitempty"`
	EffortSource    string `json:"effort_source,omitempty"`
	EffortEffective string `json:"effort_effective,omitempty"`
	EffortApplied   bool   `json:"effort_applied,omitempty"`
	EffortNote      string `json:"effort_note,omitempty"`

	WorktreeSource string `json:"worktree_source,omitempty"`
	TimeoutSource  string `json:"timeout_source,omitempty"`

	HarnessVersion      string              `json:"harness_version,omitempty"`
	HarnessCapabilities HarnessCapabilities `json:"harness_capabilities"`

	// Execution is the mandatory execution policy snapshotted at admission, so
	// a later edit to the user's configuration cannot rewrite what this run was
	// required to respect. Absent when the operator declared no sandbox.
	Execution *ExecutionPolicy `json:"execution,omitempty"`
	// ExecutionWorkspace is the exact trusted mount set a contained execution
	// may use. It is populated only under a mandatory policy, from WB's managed
	// worktree inventory rather than an editable marker. The scoped input
	// directory stays empty at admission and is generated by the owner later.
	ExecutionWorkspace *ContainerWorkspace `json:"execution_workspace,omitempty"`
	// ExecutionRuntime carries the container identity, verified limits and
	// cleanup evidence. It stays absent until a runtime has fully opened; a
	// planned or refused run must never claim a verified container. Absence is
	// not proof that no container exists: a partial open can have created one
	// and left its cleanup failure held in the durable per-user slot.
	ExecutionRuntime *ExecutionRuntimeFacts `json:"execution_runtime,omitempty"`

	// Task is the exact originating request. It is private: it is never
	// rendered by status or await, only persisted here.
	Task string `json:"task"`
	// TaskSummary is a bounded, single-line form of Task for a human reading
	// the record. It is derived from the task, so it is private for exactly the
	// same reason Task is, and is likewise never rendered.
	TaskSummary string `json:"task_summary,omitempty"`
	// TaskSHA256 is the identity of the exact task bytes, so two executions can
	// be proven comparable without republishing the task.
	TaskSHA256 string `json:"task_sha256,omitempty"`
	TaskBytes  int    `json:"task_bytes,omitempty"`

	Repository   string        `json:"repository"`
	Caller       CallerSession `json:"caller_session,omitzero"`
	WorktreeMode string        `json:"worktree_mode"`
	Worktree     string        `json:"worktree"`
	WorktreeDir  string        `json:"worktree_dir,omitempty"`
	Branch       string        `json:"branch,omitempty"`
	Base         string        `json:"base,omitempty"`
	BaseSHA      string        `json:"base_sha,omitempty"`

	// SourceSHA is the commit the writable checkout was at when the run
	// started, and SnapshotSHA the stash commit a dirty checkout produced, so a
	// later diff separates the worker's change from what was already there.
	SourceSHA   string   `json:"source_sha,omitempty"`
	SnapshotSHA string   `json:"snapshot_sha,omitempty"`
	SourceDirty bool     `json:"source_dirty,omitempty"`
	DirtyFiles  []string `json:"source_dirty_files,omitempty"`

	// WorkLogClaimPath links this run to the immutable Work Log claim the
	// worktree service already publishes, so one dispatch never produces two
	// unreferenced records of the same piece of work.
	WorkLogClaimPath string `json:"work_log_claim_path,omitempty"`
	WorkLogRunID     string `json:"work_log_run_id,omitempty"`

	// LeasePath is the retained writer-lease file this run holds, if any.
	LeasePath string `json:"lease_path,omitempty"`

	// ExperimentID and RepeatIndex place this execution in a comparison. Both
	// are empty for a standalone run.
	ExperimentID string `json:"experiment_id,omitempty"`
	RepeatIndex  int    `json:"repeat_index,omitempty"`

	// RetryOf is the execution this one replaces after an infrastructure
	// failover, and FallbackFrom/FallbackReason say which profile failed and why.
	// A retry is a new execution with its own worktree, never a resumed one.
	RetryOf        string `json:"retry_of,omitempty"`
	FallbackFrom   string `json:"fallback_from,omitempty"`
	FallbackReason string `json:"fallback_reason,omitempty"`

	// TimeoutMS bounds the run. It is persisted because the owner, not the
	// dispatcher, enforces it.
	TimeoutMS int64 `json:"timeout_ms,omitempty"`

	// StartedAt is when the run was admitted. ExecutionStartedAt is when the
	// harness itself started, so queue time never inflates wall time.
	StartedAt          time.Time `json:"started_at"`
	ExecutionStartedAt time.Time `json:"execution_started_at,omitempty"`
	FinishedAt         time.Time `json:"finished_at,omitempty"`
	DurationMS         int64     `json:"duration_ms,omitempty"`
	// QueueDurationMS is how long an execution waited behind a concurrency
	// bound before its harness started.
	QueueDurationMS int64 `json:"queue_duration_ms,omitempty"`
	// TimeToFirstOutputMS is how long the harness ran before its first byte.
	TimeToFirstOutputMS int64 `json:"time_to_first_output_ms,omitempty"`

	// QueueOwnerPID is the dispatching process while a run is queued behind a
	// concurrency bound. It is the only liveness evidence a queued run has.
	QueueOwnerPID int            `json:"queue_owner_pid,omitempty"`
	OwnerPID      int            `json:"owner_pid,omitempty"`
	WorkerPID     int            `json:"worker_pid,omitempty"`
	ExitCode      *int           `json:"exit_code,omitempty"`
	Failure       string         `json:"failure,omitempty"`
	Result        string         `json:"result,omitempty"`
	ToolCalls     int            `json:"tool_calls,omitempty"`
	Usage         *Usage         `json:"usage,omitempty"`
	Changes       *ChangeSummary `json:"changes,omitempty"`
	HarnessEvents []string       `json:"harness_diagnostics,omitempty"`

	// Telemetry and Cost carry the provenance the legacy Usage cannot express.
	Telemetry  Telemetry        `json:"telemetry"`
	Cost       CostRecord       `json:"cost"`
	Validation ValidationRecord `json:"validation"`

	// DiffPath is the private patch artefact for this run, when one was written.
	DiffPath string `json:"diff_path,omitempty"`

	// AcceptanceRequired records the task type's policy at dispatch time, so a
	// later configuration change cannot make an unreviewed run look complete.
	AcceptanceRequired bool `json:"acceptance_required,omitempty"`
	// Retries counts automatic retries attempted. This build performs none.
	Retries int `json:"retries"`

	// TaskVisibility states how the task reached the harness. `stdin` keeps it
	// off the process table; `argv` does not.
	TaskVisibility string `json:"task_visibility,omitempty"`
	TaskNormalized bool   `json:"task_normalized,omitempty"`

	LogPath string `json:"log_path,omitempty"`
}

Record is the durable description of one dispatched run. It is private: it holds the original task, which never travels back out through status or await.

func Dispatch

func Dispatch(ctx context.Context, request DispatchRequest, deps DispatchDeps) (Record, error)

Dispatch admits one run, creates or resolves its worktree, persists the run, and starts the detached owner. It returns as soon as the owner is started: the caller is never attached to the worker's stdout and never waits for it.

func StartRun

func StartRun(prepared *PreparedRun, deps DispatchDeps) (Record, error)

StartRun starts the detached owner for a prepared run and returns without waiting. The run is already durable, so a launch failure is diagnosable.

func StopRun

func StopRun(store Store, agentID string, deps OwnerDeps) (Record, error)

StopRun terminates a running worker's process group. The owner is left alive deliberately: it observes the non-zero exit and records the terminal state, so a stopped run reports a real outcome instead of vanishing into "abandoned". A contained execution is stopped only through the durable cancellation sentinel: its owner cancels the whole runtime, because a host PID is either absent during setup or not authoritative for the container.

type RemoteDeps

type RemoteDeps struct {
	// LookPath resolves the local ssh executable.
	LookPath func(string) (string, error)
	// Runner executes it. Replacement is for tests only.
	Runner remotessh.Runner
	// Timeout bounds one remote call when the operation has no bound of its own.
	Timeout time.Duration
}

RemoteDeps are the seams the local side needs to reach another machine.

func DefaultRemoteDeps

func DefaultRemoteDeps() RemoteDeps

DefaultRemoteDeps returns the production seams.

type RemoteRequest

type RemoteRequest struct {
	SchemaVersion int    `json:"schema_version"`
	Operation     string `json:"operation"`

	// dispatch
	Mode       string        `json:"mode,omitempty"`
	Worktree   string        `json:"worktree,omitempty"`
	Profile    string        `json:"profile,omitempty"`
	Task       string        `json:"task,omitempty"`
	Repository string        `json:"repository,omitempty"`
	Branch     string        `json:"branch,omitempty"`
	Base       string        `json:"base,omitempty"`
	TimeoutMS  int64         `json:"timeout_ms,omitempty"`
	Caller     CallerSession `json:"caller_session,omitzero"`

	// status, await, logs, stop
	AgentID       string `json:"agent_id,omitempty"`
	WaitTimeoutMS int64  `json:"wait_timeout_ms,omitempty"`
	Raw           bool   `json:"raw,omitempty"`
	Tail          int    `json:"tail,omitempty"`
}

RemoteRequest is the exact request a local WB sends to a remote WB. The remote validates it with the same code that validates local flags, so a request can never reach a state a local invocation could not.

func (RemoteRequest) Validate

func (request RemoteRequest) Validate() error

Validate refuses a request that is not a well-formed WB agent protocol value. It is deliberately independent of the local flag parser: a hand-written request must satisfy exactly the same constraints.

type RemoteResponse

type RemoteResponse struct {
	SchemaVersion int     `json:"schema_version"`
	Operation     string  `json:"operation"`
	Result        *Result `json:"result,omitempty"`
	// Results deliberately has no omitempty: an empty inventory must travel as
	// an empty list, not disappear into a null the caller has to special-case.
	Results []Result `json:"results"`
	Logs    string   `json:"logs,omitempty"`
	Failure string   `json:"failure,omitempty"`
}

RemoteResponse is the exact reply a remote WB sends back. A refusal on the remote side travels as Failure rather than as a transport error, so the caller can tell "the remote refused" apart from "the remote was unreachable".

func CallRemote

func CallRemote(ctx context.Context, target RemoteTarget, request RemoteRequest, deps RemoteDeps) (RemoteResponse, error)

CallRemote performs one remote WB agent operation over SSH and returns the decoded reply. A non-empty reply Failure is returned as an error: the remote ran and refused, which is a finding rather than a transport failure.

type RemoteTarget

type RemoteTarget struct {
	Machine string
	Host    string
	User    string
	WBPath  string
}

RemoteTarget is one configured machine WB can dispatch to. It is derived from WB's existing session_move target map, so there is one host list rather than a second one that can drift from it.

func ResolveRemoteTarget

func ResolveRemoteTarget(configPath, machine string) (RemoteTarget, error)

ResolveRemoteTarget looks up one configured machine, naming the alternatives when it is unknown so a typo is one command away from being fixed.

func (RemoteTarget) Validate

func (target RemoteTarget) Validate() error

Validate refuses a target whose configured address could be reinterpreted by OpenSSH. The values come from WB configuration, but the remote command line is the one place a configuration typo could become a remote shell command.

type RequestError

type RequestError struct {
	// contains filtered or unexported fields
}

RequestError marks a refusal of the invocation itself: the caller asked for something WB cannot even attempt, such as an unconfigured profile. It is deliberately distinguishable from a run that started and then failed, because the two need different exit codes and different caller responses.

func (*RequestError) Error

func (err *RequestError) Error() string

type Resolved

type Resolved struct {
	Profile  string `json:"profile"`
	Harness  string `json:"harness"`
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model"`
	// Variant is the OpenCode model variant exactly as configured; it is never
	// folded into Model, so Model stays a valid execution identifier.
	Variant string `json:"variant,omitempty"`
	// Effort is the profile's own default. The effort a run actually requested
	// and whether it was applied are recorded separately from this snapshot.
	Effort string `json:"effort,omitempty"`
	// EffortVariants snapshots the profile's effort→variant map, so a plan can
	// still resolve an effort after the configuration file changes.
	EffortVariants map[string]string `json:"effort_variants,omitempty"`
	// Routing is the provider registry entry a Codex run will be configured
	// with, or the explicit official entry a contained dsh run needs. It carries
	// no credential, only the name of the variable holding it, and is absent for
	// a host harness that uses its own auth store.
	Routing Provider `json:"routing,omitempty"`
	// TimeoutMS is the profile's own bound, when configured.
	TimeoutMS int64 `json:"timeout_ms,omitempty"`
}

Resolved is one profile after resolution: the requested name plus what will actually execute, snapshotted so a later edit to the profile cannot rewrite what a finished run did.

type Result

type Result struct {
	AgentID string `json:"agent_id"`
	// Machine names the machine that holds this run's record and worktree. It
	// is empty for a run dispatched by this machine and is stamped by the caller
	// that asked another machine, so a result always says where its artefact
	// lives.
	Machine             string                 `json:"machine,omitempty"`
	State               State                  `json:"state"`
	Status              ExecutionStatus        `json:"execution_status"`
	Terminal            bool                   `json:"terminal"`
	FailureCategory     string                 `json:"failure_category,omitempty"`
	RequestedProfile    string                 `json:"profile"`
	Resolved            Resolved               `json:"resolved"`
	TaskType            string                 `json:"task_type,omitempty"`
	TaskTypeSource      string                 `json:"task_type_source,omitempty"`
	ProfileSource       string                 `json:"profile_source,omitempty"`
	Complexity          string                 `json:"complexity,omitempty"`
	ComplexitySource    string                 `json:"complexity_source,omitempty"`
	EffortRequested     string                 `json:"effort_requested,omitempty"`
	EffortEffective     string                 `json:"effort_effective,omitempty"`
	EffortApplied       bool                   `json:"effort_applied"`
	EffortNote          string                 `json:"effort_note,omitempty"`
	WorktreeSource      string                 `json:"worktree_source,omitempty"`
	TimeoutSource       string                 `json:"timeout_source,omitempty"`
	HarnessVersion      string                 `json:"harness_version,omitempty"`
	HarnessCapabilities HarnessCapabilities    `json:"harness_capabilities"`
	Execution           *ExecutionPolicy       `json:"execution,omitempty"`
	ExecutionWorkspace  *ContainerWorkspace    `json:"execution_workspace,omitempty"`
	ExecutionRuntime    *ExecutionRuntimeFacts `json:"execution_runtime,omitempty"`
	Repository          string                 `json:"repository"`
	Caller              CallerSession          `json:"caller_session,omitzero"`
	WorktreeMode        string                 `json:"worktree_mode"`
	Worktree            string                 `json:"worktree"`
	WorktreeDir         string                 `json:"worktree_dir,omitempty"`
	Branch              string                 `json:"branch,omitempty"`
	Base                string                 `json:"base,omitempty"`
	BaseSHA             string                 `json:"base_sha,omitempty"`
	SourceSHA           string                 `json:"source_sha,omitempty"`
	SnapshotSHA         string                 `json:"snapshot_sha,omitempty"`
	SourceDirty         bool                   `json:"source_dirty,omitempty"`
	ExperimentID        string                 `json:"experiment_id,omitempty"`
	RepeatIndex         int                    `json:"repeat_index,omitempty"`
	RetryOf             string                 `json:"retry_of,omitempty"`
	FallbackFrom        string                 `json:"fallback_from,omitempty"`
	FallbackReason      string                 `json:"fallback_reason,omitempty"`
	StartedAt           time.Time              `json:"started_at"`
	ExecutionStartedAt  *time.Time             `json:"execution_started_at,omitempty"`
	FinishedAt          *time.Time             `json:"finished_at,omitempty"`
	DurationMS          int64                  `json:"duration_ms,omitempty"`
	QueueDurationMS     int64                  `json:"queue_duration_ms,omitempty"`
	TimeToFirstOutputMS int64                  `json:"time_to_first_output_ms,omitempty"`
	QueueOwnerPID       int                    `json:"queue_owner_pid,omitempty"`
	OwnerPID            int                    `json:"owner_pid,omitempty"`
	WorkerPID           int                    `json:"worker_pid,omitempty"`
	OwnerAlive          bool                   `json:"owner_alive"`
	// WorkerAlive reports whether the recorded harness transport process is
	// still alive. For a contained run that process is the host Docker client,
	// which is reaped during contained validation even though the validation
	// namespace keeps running, so this can be false while work continues. It is
	// not a workload probe: State/Status and Validation describe the remaining
	// work, and contained workload liveness must not be derived from this field.
	WorkerAlive        bool             `json:"worker_alive"`
	ExitCode           *int             `json:"exit_code,omitempty"`
	Failure            string           `json:"failure,omitempty"`
	Result             string           `json:"result,omitempty"`
	ToolCalls          int              `json:"tool_calls,omitempty"`
	Usage              *Usage           `json:"usage,omitempty"`
	Telemetry          Telemetry        `json:"telemetry"`
	Cost               CostRecord       `json:"cost"`
	Validation         ValidationRecord `json:"validation"`
	Review             ReviewRecord     `json:"review"`
	Changes            *ChangeSummary   `json:"changes,omitempty"`
	HarnessDiagnostics []string         `json:"harness_diagnostics,omitempty"`
	DiffPath           string           `json:"diff_path,omitempty"`
	AcceptanceRequired bool             `json:"acceptance_required"`
	Retries            int              `json:"retries"`
	TaskVisibility     string           `json:"task_visibility,omitempty"`
	TaskNormalized     bool             `json:"task_normalized,omitempty"`
	LogPath            string           `json:"log_path,omitempty"`
}

Result is the rendered projection of a Record, and the machine-readable document `status` and `await` emit. It is written out field by field rather than derived by embedding, so the private task can never reach a caller by accident: adding a field to Record does not add it here.

type ReviewEntry

type ReviewEntry struct {
	Status    string    `json:"status"`
	Evaluator string    `json:"evaluator"`
	Note      string    `json:"note,omitempty"`
	At        time.Time `json:"at"`
}

ReviewEntry is one acceptance decision.

type ReviewRecord

type ReviewRecord struct {
	Status    string        `json:"status"`
	Evaluator string        `json:"evaluator,omitempty"`
	Note      string        `json:"note,omitempty"`
	At        time.Time     `json:"at,omitempty"`
	History   []ReviewEntry `json:"history,omitempty"`
}

ReviewRecord is the review axis of one execution. Status is `pending` until a reviewer appends an entry, and always reflects the most recent decision.

func (ReviewRecord) Latest

func (record ReviewRecord) Latest() ReviewRecord

Latest projects the current decision without the history.

func (ReviewRecord) Reviewed

func (record ReviewRecord) Reviewed() bool

Reviewed reports whether a human decided something about this run.

type RunRequest

type RunRequest struct {
	Task string

	TaskType   string
	Complexity string
	Effort     string

	Profile  string
	Harness  string
	Model    string
	Provider string
	Variant  string

	// WorktreeMode is auto, current, path, new or existing. Worktree is an
	// operation name, an absolute path, or an existing worktree name depending
	// on the mode.
	WorktreeMode   string
	Worktree       string
	AllowCanonical bool
	AllowDirty     bool

	Timeout    time.Duration
	TimeoutSet bool

	Validate    []string
	ValidateSet bool
	NoValidate  bool

	Repository string
	Base       string
	Branch     string

	// Acceptance overrides the task type's acceptance policy when set.
	Acceptance string
}

RunRequest is everything a caller can decide about one execution. Every field is optional: the point of a task type is that the caller can name the work and nothing else.

type State

type State string

State is the closed lifecycle vocabulary of one dispatched run. It is the legacy spelling kept for records an older WB wrote and read; new records also carry ExecutionStatus, which distinguishes cancellation from failure without adding a value an older build would not recognise as terminal.

const (
	StateRunning   State = "running"
	StateCompleted State = "completed"
	StateFailed    State = "failed"
	StateTimeout   State = "timeout"
	StateAbandoned State = "abandoned"
)

func (State) Terminal

func (state State) Terminal() bool

Terminal reports whether a state is final. Exactly one state — running — is not terminal, so a caller can never mistake a stalled run for a finished one.

type StatsBucket

type StatsBucket struct {
	SessionID        string  `json:"session_id"`
	SessionName      string  `json:"session_name,omitempty"`
	Repository       string  `json:"repository"`
	Runs             int     `json:"runs"`
	Completed        int     `json:"completed"`
	Failed           int     `json:"failed"`
	Pending          int     `json:"pending"`
	DurationMS       int64   `json:"duration_ms"`
	ToolCalls        int     `json:"tool_calls"`
	UsageRuns        int     `json:"usage_runs"`
	InputTokens      int64   `json:"input_tokens"`
	OutputTokens     int64   `json:"output_tokens"`
	CacheReadTokens  int64   `json:"cache_read_tokens"`
	CacheWriteTokens int64   `json:"cache_write_tokens"`
	ReasoningTokens  int64   `json:"reasoning_tokens"`
	CostRuns         int     `json:"cost_runs"`
	EstimatedUSD     float64 `json:"estimated_usd"`
}

StatsBucket sums observed execution facts. UsageRuns and CostRuns make missing harness telemetry distinct from a measured zero.

type StatsReport

type StatsReport struct {
	Total               StatsBucket   `json:"total"`
	BySession           []StatsBucket `json:"by_session"`
	ByRepository        []StatsBucket `json:"by_repository"`
	BySessionRepository []StatsBucket `json:"by_session_repository"`
}

func SummarizeRuns

func SummarizeRuns(runs []Result) StatsReport

SummarizeRuns groups each durable run once along each requested dimension. Older records without caller identity remain in an explicit empty-ID group.

type Store

type Store struct {
	Root string
}

Store persists agent run records under one root directory.

func NewStore

func NewStore(home string) Store

NewStore returns the store for a WB home directory.

func (Store) AcquireLease

func (store Store) AcquireLease(worktreeDir, agentID, experimentID, repository string, now time.Time) (*Lease, error)

AcquireLease takes the exclusive writer claim for a worktree, failing with LeaseHeldError when another execution holds it.

func (Store) AppendReview

func (store Store) AppendReview(agentID string, entry ReviewEntry) (ReviewRecord, error)

AppendReview adds one decision and returns the resulting review record. The caller has already established that the execution is terminal, so nothing here can race an owner's save.

func (Store) BuildReport

func (store Store) BuildReport(experiment Experiment) ExperimentReport

BuildReport joins an experiment with its member records. A run that cannot be loaded is skipped rather than failing the whole report: a partially completed experiment is exactly what an operator needs to see after a crash.

func (Store) Create

func (store Store) Create(record Record) error

Create prepares the run directory and persists the initial record before any process is started, so a launch that fails still leaves something to diagnose.

func (Store) CreateExperiment

func (store Store) CreateExperiment(experiment Experiment) error

CreateExperiment writes the document once. A second write is refused so a planned experiment cannot be rewritten after results exist.

func (Store) Dir

func (store Store) Dir(agentID string) string

Dir is the private directory holding one run's record and artefacts.

func (Store) ExperimentDir

func (store Store) ExperimentDir(experimentID string) string

ExperimentDir is the private directory holding one experiment document.

func (Store) ExperimentPath

func (store Store) ExperimentPath(experimentID string) string

ExperimentPath is the experiment document path.

func (Store) HarnessHomePath

func (store Store) HarnessHomePath(agentID string) string

HarnessHomePath is the private per-run harness home. Pointing the harness at its own home is what keeps a dispatched worker from reading or writing the user's harness state while the parent harness keeps running normally.

func (Store) LastMessagePath

func (store Store) LastMessagePath(agentID string) string

LastMessagePath is where the harness is asked to write its final message.

func (Store) LeaseLive

func (store Store) LeaseLive(worktreeDir string) (bool, error)

LeaseLive reports whether some process currently holds the writer claim. The lease file is retained after Release, so its existence alone proves nothing: only a failed non-blocking lock does.

func (Store) LeasePath

func (store Store) LeasePath(worktreeDir string) (string, error)

LeasePath is the retained lease file for a worktree directory. It is keyed on the symlink-resolved path so two spellings of one checkout cannot take two leases.

func (Store) List

func (store Store) List() ([]Record, error)

List returns every run record, newest first. A directory that cannot be read is reported rather than silently skipped.

func (Store) ListSince

func (store Store) ListSince(since time.Time) ([]Record, error)

ListSince avoids decoding run records in directories that have not changed since the requested window. It still checks StartedAt after loading because an older run may have a recently updated record.

func (Store) Load

func (store Store) Load(agentID string) (Record, error)

Load reads one run record, failing actionably when it does not exist.

func (Store) LoadExperiment

func (store Store) LoadExperiment(experimentID string) (Experiment, error)

LoadExperiment reads one experiment document.

func (Store) LoadReview

func (store Store) LoadReview(agentID string) (ReviewRecord, error)

LoadReview reads the review sidecar. An absent sidecar is not an error: it means the execution has not been reviewed.

func (Store) LogPath

func (store Store) LogPath(agentID string) string

LogPath is the captured harness event stream for one agent ID.

func (Store) RecordPath

func (store Store) RecordPath(agentID string) string

RecordPath is the persisted run record for one agent ID.

func (Store) Render

func (store Store) Render(record Record) Result

Render projects a record for output, resolving a run whose owner vanished without recording a terminal state to the honest answer: abandoned. A run is never reported as completed merely because nothing contradicted it.

Abandoned is derived from the owner, not the worker: the owner is the only process that will ever record a terminal state, so once it is gone the run has no outcome and reporting it "running" indefinitely would be a lie. A harness transport process that outlived its owner is still surfaced, through WorkerAlive, so a caller knows a stray process exists and can stop it. WorkerAlive describes only that recorded transport process, never the contained workload: during contained validation the transport client is reaped while the validation namespace keeps running.

func (Store) ReviewPath

func (store Store) ReviewPath(agentID string) string

ReviewPath is the sidecar path for one execution.

func (Store) Save

func (store Store) Save(record Record) error

Save atomically replaces the record, so a reader never observes a partially written run.

func (Store) WriteDiff

func (store Store) WriteDiff(ctx context.Context, agentID, worktreeDir, baseSHA string, deps TargetDeps) (string, error)

WriteDiff stores the run's patch under its private directory and returns the path. A failure to write is not a failed run: the worktree is the artefact.

type Target

type Target struct {
	Repository string
	Dir        string
	Branch     string
	Base       string
	BaseSHA    string

	HeadSHA     string
	SnapshotSHA string
	Dirty       bool
	DirtyFiles  []string

	Managed   bool
	Canonical bool

	ClaimPath  string
	ClaimRunID string

	// WorktreeName is the WB task name when the checkout carries a marker.
	WorktreeName string
}

Target is one resolved writable directory and the facts that make a later diff and a cleanup decision honest.

func ResolveTarget

func ResolveTarget(ctx context.Context, path string, allowCanonical, allowDirty bool, deps TargetDeps) (Target, error)

ResolveTarget inspects a directory a caller wants a worker to write in.

type TargetDeps

type TargetDeps struct {
	Git        func(ctx context.Context, dir string, args ...string) (string, error)
	ReadFile   func(string) ([]byte, error)
	OriginSlug func(context.Context, string) (string, error)
}

TargetDeps are the seams target resolution needs. They exist so the whole resolution can be exercised without a live Git checkout.

func DefaultTargetDeps

func DefaultTargetDeps() TargetDeps

DefaultTargetDeps returns the production seams.

type TaskType

type TaskType struct {
	Profile    string            `yaml:"profile,omitempty" json:"profile,omitempty"`
	Complexity map[string]string `yaml:"complexity,omitempty" json:"complexity,omitempty"`
	// Fallback is the ordered list of profiles to try after Profile, so one
	// provider or model being down does not stop the work. Order is the
	// operator's cost decision: WB never reorders it.
	Fallback []string `yaml:"fallback,omitempty" json:"fallback,omitempty"`
	// FallbackOn selects when fallback applies: "preflight" (a capability WB
	// can check before starting) and/or "runtime" (the provider failed the run
	// itself). Preflight is the default; runtime is opt-in because it starts a
	// second execution.
	FallbackOn []string `yaml:"fallback_on,omitempty" json:"fallback_on,omitempty"`
	Effort     string   `yaml:"effort,omitempty" json:"effort,omitempty"`
	Worktree   string   `yaml:"worktree,omitempty" json:"worktree,omitempty"`
	Timeout    string   `yaml:"timeout,omitempty" json:"timeout,omitempty"`
	Validate   []string `yaml:"validate,omitempty" json:"validate,omitempty"`
	Acceptance string   `yaml:"acceptance,omitempty" json:"acceptance,omitempty"`
}

TaskType is a named execution policy. It names no model: it points at profiles the operator configured.

type Telemetry

type Telemetry struct {
	Available         bool            `json:"available"`
	Source            string          `json:"source"`
	UnavailableReason string          `json:"unavailable_reason,omitempty"`
	Tokens            *Tokens         `json:"tokens,omitempty"`
	Raw               json.RawMessage `json:"raw,omitempty"`
}

Telemetry is what the harness reported about usage, with its provenance. Available is explicit: a nil Tokens means "not reported", never zero.

type Tokens

type Tokens struct {
	Input      *int `json:"input,omitempty"`
	Output     *int `json:"output,omitempty"`
	CacheRead  *int `json:"cache_read,omitempty"`
	CacheWrite *int `json:"cache_write,omitempty"`
	Reasoning  *int `json:"reasoning,omitempty"`
}

Tokens is usage exactly as the harness reported it. Every field is a pointer so "not reported" stays distinguishable from a reported zero.

type UnknownAgentError

type UnknownAgentError struct {
	AgentID string
	Root    string
}

UnknownAgentError is returned when a named run does not exist.

func (*UnknownAgentError) Error

func (err *UnknownAgentError) Error() string

type UnknownExperimentError

type UnknownExperimentError struct {
	ExperimentID string
	Root         string
}

UnknownExperimentError is returned when a named experiment does not exist.

func (*UnknownExperimentError) Error

func (err *UnknownExperimentError) Error() string

type Usage

type Usage struct {
	InputTokens           int `json:"input_tokens"`
	CachedInputTokens     int `json:"cached_input_tokens,omitempty"`
	CacheWriteInputTokens int `json:"cache_write_input_tokens,omitempty"`
	OutputTokens          int `json:"output_tokens"`
	ReasoningOutputTokens int `json:"reasoning_output_tokens,omitempty"`
}

Usage is what the harness reported about the run. Every field is copied verbatim from the harness; a field the harness did not report stays absent rather than being estimated.

type ValidationCommandFactory

type ValidationCommandFactory func(ctx context.Context, argv []string) (*exec.Cmd, error)

ValidationCommandFactory builds one validation step command from the step's argv alone. It is the contained-execution seam: a factory from a verified container runtime returns a credential-free Docker client command whose environment is already the bounded Docker transport. RunValidation never replaces that environment with the host worker environment, so a validation step cannot regain host variables or a provider credential.

type ValidationOptions

type ValidationOptions struct {
	WorktreeDir string
	RunDir      string
	Steps       []ValidationStep
	// Lease is inherited by every step, so a validation process still holds the
	// worktree claim until it exits.
	Lease *os.File
	Now   func() time.Time
	// Command builds the process; it is a seam for tests, never a production
	// override.
	Command func(ctx context.Context, name string, args ...string) *exec.Cmd
	// Transport builds a contained step's command from argv alone. When it is
	// set it is the only command source: there is no host fallback, and the
	// returned command keeps the environment and directory its factory chose.
	// Nil keeps the legacy host Command behaviour exactly.
	Transport ValidationCommandFactory
	// FailFast stops the sequence after the first failed or timed-out step, so
	// no later step starts while a contained step's command may still be
	// winding down inside the same namespace. It is set only for contained
	// validation; false preserves the legacy host behaviour of running and
	// reporting every configured step.
	FailFast bool
}

ValidationOptions is one validation run's inputs.

type ValidationRecord

type ValidationRecord struct {
	Status     string                 `json:"status"`
	Steps      []ValidationStepResult `json:"steps,omitempty"`
	Reason     string                 `json:"reason,omitempty"`
	StartedAt  *time.Time             `json:"started_at,omitempty"`
	FinishedAt *time.Time             `json:"finished_at,omitempty"`
}

ValidationRecord is the objective-validation axis of one execution.

func RunValidation

func RunValidation(ctx context.Context, options ValidationOptions) ValidationRecord

RunValidation executes the snapshotted steps and reports one record. It never takes a credential: a validation is repository-owned code, not a provider call, and the worker's credential must not reach it.

type ValidationStep

type ValidationStep struct {
	Name    string   `yaml:"name" json:"name"`
	Argv    []string `yaml:"argv" json:"argv"`
	Timeout string   `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}

ValidationStep is one objective check a task type may require. Argv is a literal argument list, never a shell string, so a validation cannot smuggle quoting or piping into the worker's environment.

type ValidationStepResult

type ValidationStepResult struct {
	Name       string   `json:"name"`
	Argv       []string `json:"argv"`
	Timeout    string   `json:"timeout,omitempty"`
	Status     string   `json:"status"`
	ExitCode   *int     `json:"exit_code,omitempty"`
	DurationMS int64    `json:"duration_ms,omitempty"`
	LogPath    string   `json:"log_path,omitempty"`
}

ValidationStepResult is one executed objective check.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL