engine

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 42 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 engine runs dispatches: it spawns a provider's CLI, supervises it, and turns what comes back into a Result.

The split with internal/providers is deliberate. A provider is pure — it builds an argv and parses bytes — so every parser can be pinned against captured CLI output. Everything impure lives here: processes, signals, files, clocks.

Ported from the spawn and wait halves of orchestrator/dispatcher.py (`_spawn_generic`, `_wait_with_timeout`, `_signal_child_group`) and from `orchestrator/orch.py::_timeout_for`.

Index

Constants

View Source
const (
	CIStatusPending = "pending"
	CIStatusSuccess = "success"
	CIStatusFailure = "failure"
	// CIStatusSkipped is how a project with auto-PR but no CI configured
	// says there was never anything to wait for — a different answer from
	// success. The poller never sees it, because TasksWithPendingCI returns
	// only rows still `pending`; it is named here so the four values that
	// the column's CHECK constraint allows are all accounted for in one
	// place.
	CIStatusSkipped = "skipped"
)

CI status values, as written into `tasks_runtime.ci_status`. Python's strings, because the dashboard and `orch status` read the column.

View Source
const (
	EventCIRedispatch      = "ci_redispatch"
	EventCISuccess         = "ci_success"
	EventCIFailureRetry    = "ci_failure_retry"
	EventCIBlocked         = "ci_blocked"
	EventPRAutoMerged      = "pr_auto_merged"
	EventPRAutoMergeFailed = "pr_auto_merge_failed"
	// EventCINoChecks is Go only: a PR finished with no check ever reported.
	EventCINoChecks = "ci_no_checks"
	// EventPRMerged is Go only: the PR was merged outside orch while its CI
	// was still being watched (#255).
	EventPRMerged = "pr_merged"
	// EventCIConflictRetry is Go only: a PR that conflicted with its base was
	// brought up to date, by orch alone or through the agent (#438).
	EventCIConflictRetry = "ci_conflict_retry"
)

CI event types. Python's spellings, from the set orch.py emits.

View Source
const (
	// EventIssueClosed: the last task of a GitHub issue landed locally and
	// orch closed the issue with the evidence as its comment.
	EventIssueClosed = "issue_closed"
	// EventIssueCloseFailed: closing it did not work (gh missing, not
	// authenticated, no access). The task stays done; the issue stays open.
	EventIssueCloseFailed = "issue_close_failed"
)

Issue events (#525). Go only.

View Source
const (
	// EventQueueEnqueued: a green PR entered the queue.
	EventQueueEnqueued = "queue_enqueued"
	// EventQueueMerged: the queue merged it.
	EventQueueMerged = "queue_merged"
	// EventQueueEjected: it left the queue without merging — sent back to
	// its agent (a conflict, a semantic collision, a verify that failed on
	// the current base) or blocked; it enters again once green.
	EventQueueEjected = "queue_ejected"
)

Events the merge queue records (#522). Go only.

View Source
const (
	// EventFilesOverlap: a task about to dispatch declares files a running
	// task also declares. With radar: serialize it waits for that one.
	EventFilesOverlap = "files_overlap"
	// EventBranchConflict: the PR just opened conflicts with another open task
	// PR, on the files named. Not pr_*: the timeline credits those to CI, and
	// this is orch merging two branches.
	EventBranchConflict = "branch_conflict"
)

Events the conflict radar records (#482). Go only.

View Source
const (
	EventDispatch = "dispatch"
	EventSuccess  = "success"
	EventFail     = "fail"
	EventTimeout  = "timeout"
	EventIDSpoof  = "id_spoof_detected"
	EventRetry    = "retry"
	EventEscalate = "escalate"
	EventBlock    = "block"
	// EventBudgetPause marks the run parking until a provider window resets.
	EventBudgetPause = "budget_pause"
	// EventBudgetSkip marks a ready task deferred because its provider is
	// over the budget window. Written when the task starts waiting, with the
	// provider and reset estimate, so status and the dashboard can show it.
	EventBudgetSkip = "budget_skip"
	// EventProviderSkip marks a ready task deferred because the operator
	// turned its provider off (`orch provider disable`).
	EventProviderSkip = "provider_skip"
	// EventReconciled marks a dispatch row whose process was gone.
	EventReconciled = "reconciled"
	// EventPRCreated marks a pull request opened for a finished task.
	EventPRCreated = "pr_created"
	// EventMergedLocally marks a finished task squash-merged into the base
	// here, with nothing pushed (vcs.provider: local, #455). Go only.
	EventMergedLocally = project.EventMergedLocally

	// EventSprintDone marks the run whose queue emptied (F4.7). Run-level,
	// so its task_id is empty; the counts ride in `extra`. Go only —
	// Python declares no such type, which internal/state's
	// goOnlyEventTypes explains.
	EventSprintDone = "sprint_done"

	// EventModelMismatch warns that an attempt's CLI ran another model,
	// effort or service tier than its route asked for (#580): which fields,
	// both sides, and a one-line detail. Go only.
	EventModelMismatch = "model_mismatch"
)

Event types the dispatch path writes. They are Python's spellings, from EVENT_TYPES in orchestrator/state/file_backend.py, and this block is the one place the engine names them — a single mapping point, so a future rename is one edit and one test.

`success` and `fail`, NOT `exit_ok`/`exit_err`: those two came from the superseded FR-STATE-7 list in the plan and no version of orch has ever emitted them (#122 aligned the Go set; see bug 9 and bug 11 in docs/brainstorm/go-migration-notes.md).

View Source
const (
	EventAgentStalled = "agent_stalled"
	EventAgentLooping = "agent_looping"
	// EventAgentResumed follows an agent_stalled when the log grows again, so
	// the last event says whether the agent is still stuck (#533).
	EventAgentResumed = "agent_resumed"
)

Events the agent watch records about a running attempt (#487). Neither stops it: they say what the operator would otherwise learn at the timeout.

View Source
const CIFeedbackFile = project.CIFeedbackFile

CIFeedbackFile is where the failing CI logs are left for the agent, inside its own worktree (project.CIFeedbackFile, which Accept also leaves out).

View Source
const DefaultBudgetAlertPct = 80.0

DefaultBudgetAlertPct is the share of a provider's cap at which the first alert goes out, when config does not say.

View Source
const EventAgentWaiting = "agent_waiting"

EventAgentWaiting is an agent whose log is silent past watch.stall_after_s while its processes or its files show it working (#524): downloading data, running a long build. It is information, not a warning; only a silence with no sign of life at all is agent_stalled.

View Source
const EventBudgetAlert = "budget_alert"

EventBudgetAlert marks a budget alert sent to the notification channels, so a restarted run does not send it again. Go only, like sprint_done.

View Source
const EventE2EReport = "e2e_report"

EventE2EReport records the E2E results of one verified attempt: the counts, and the report the dashboard opens.

View Source
const EventSemanticCollision = "semantic_collision"

EventSemanticCollision records an identity a task's branch adds that the base or another open branch already claims (#522): two migrations 005 under different file names, which git merges without a conflict.

View Source
const EventSpecRefWarning = "spec_ref_warning"

EventSpecRefWarning records a dispatch whose spec ref did not resolve where the agent runs: the file is not there at all, or it has no heading for the ref's anchor. The task is dispatched anyway, with a prompt that says so. Go only (#341, #342).

View Source
const EventVerifyFailed = "verify_failed"

EventVerifyFailed records a local verify that failed an attempt: the reason the agent reads, and the review's findings uncut (#463).

View Source
const EventVerifyPassed = "verify_passed"

EventVerifyPassed records a local verify that passed an attempt: the commands it ran and the reviewer that read the diff (#463).

View Source
const ExitInterrupted = 130

ExitInterrupted is what `orch run` exits with after a signal drained it. 128 + SIGINT, the shell convention, and what the Python `orch run` returns.

View Source
const ExitZombied = -9

ExitZombied is the exit code reported when a process survives SIGKILL long enough that we stop waiting. Python returns -9 here; the value is a marker, not a real wait status.

View Source
const FakeProviderEnv = "ORCH_FAKE_PROVIDER"

FakeProviderEnv names the directory of canned CLI output that replaces every real provider. Set it and no coding CLI is ever executed.

This exists so the dispatch loop can be exercised end to end — spawn, timeout, parse, classify, record — without an API key, a network, or a dollar of spend. G2.6 formalises it; the hook lands here because the alternative is engine tests that can only run on a machine with every CLI installed and authenticated, which is no machine.

View Source
const FallbackTimeout = 60 * time.Second

FallbackTimeout is what a task with no usable estimate gets. Python's _timeout_for gives 60s to a task whose estimate_hours is 0 (a dry seed, or a typo) so the reap loop can still catch a child that hangs without emitting.

View Source
const HighEffortHours = 10.0

HighEffortHours is the estimate at which a task is gated on size alone (FR-C-1d).

View Source
const RunLockFile = project.RunLockFile

RunLockFile is the file under a project's state directory that one `orch run` holds for as long as it runs.

View Source
const TaskLocksDir = "task-locks"

TaskLocksDir is where the lock files live, under the state directory.

View Source
const TermToKillGrace = 10 * time.Second

TermToKillGrace is how long a child gets between SIGTERM and SIGKILL on timeout. Same 10 seconds as Python's _TERM_TO_KILL_GRACE_S (FR-D-3, AS-03).

View Source
const TimeoutReason = "orchestrator timeout"

TimeoutReason is the prefix Python's wait path writes into error_message, and the marker providers.Classify keys FailureTimeout on. Changing it silently turns every timeout into FailureOther.

Variables

View Source
var ErrNoTasks = errors.New("no tasks")

ErrNoTasks: the project has no task to run. The CLI words it with the planning steps that make some.

Functions

func ComposeProjectName

func ComposeProjectName(project, taskID string) string

ComposeProjectName is the docker compose project a task's containers run under: `<project>-<task id>`, lowercased, with every run of characters compose refuses in a project name (anything but a-z, 0-9, `-` and `_`) turned into one `-`, and starting with a letter or digit as compose requires. An empty half is left out; both empty is "orch".

func E2EArtifactsDir

func E2EArtifactsDir(stateDir, runID, taskID string, attempt int) string

E2EArtifactsDir is where one attempt's E2E report and files are kept: <state>/e2e/<run>/<task>/attempt-<n>.

func FakeProviderDir

func FakeProviderDir() (string, bool)

FakeProviderDir returns the configured fake directory and whether the hook is active.

func GateReason

func GateReason(task model.Task, routes map[string]model.RouteEntry, criticalPaths ...string) string

GateReason renders why the gate fired, for the operator's prompt. Only the first matching rule is reported — enough to know why — and the order is the spec's (FR-C-1).

func IsCritical

func IsCritical(task model.Task, routes map[string]model.RouteEntry, criticalPaths ...string) bool

IsCritical composes the four FR-C-1 rules. In semi mode, a task that answers true here is offered to the operator before it is dispatched. criticalPaths (gate.critical_paths) replace the built-in file rule.

Rule (c) — `phase == 10 && premium` — is subsumed by (a) and is kept only because the spec lists it separately; Python keeps it for the same reason.

func IsHighEffort

func IsHighEffort(task model.Task) bool

IsHighEffort reports whether the estimate alone gates the task (FR-C-1d).

func IsPremium

func IsPremium(task model.Task, routes map[string]model.RouteEntry) bool

IsPremium reports whether a task's route is the premium tier.

A task whose model has no route is not premium rather than an error: the run has already failed startup validation (FR-D-6) if that is true of a real task, so reaching here means an out-of-band Task, and refusing to gate it is the conservative answer.

func LogPathFor

func LogPathFor(stateDir, taskID string) string

LogPathFor is where a task's captured output goes: `<stateDir>/logs/<id>.log`, the same layout Python's _ensure_logs_dir builds.

func NewBudgetGate added in v0.31.0

func NewBudgetGate(paths config.Paths, cfg config.Config, spend budget.SpendReader, warn io.Writer) *budget.Gate

NewBudgetGate loads the provider guardrails, or returns nil when the project has none — which is every project that never opted in, and is why a missing budgets.yaml is not an error.

Read failures are reported on warn and treated as "no gate" rather than failing the run: a guardrail that cannot be loaded must not be able to stop work, the same fail-open the per-dispatch check takes when the window is unreadable. The path is budget.ResolvePath's, the one doctor and the dashboard read too.

func NewNotifier added in v0.31.0

func NewNotifier(cfg config.Config) *notify.Notifier

NewNotifier is the webhooks cfg names, a working no-op when it names none.

func PromptPathFor

func PromptPathFor(stateDir, taskID string) string

PromptPathFor is where a task's rendered prompt goes: `<stateDir>/prompts/<id>.txt`, matching Python's layout.

func ReadLog

func ReadLog(path string) string

ReadLog reads a dispatch's captured output back for parsing. Port of dispatcher.py's _read_log: a missing or unreadable file is "", never an error, because the reap loop must reach a verdict either way — and an empty capture is itself the verdict (FailureParser, or FailureTimeout once the wait path stamps its reason on top).

func RecordFinish

func RecordFinish(ctx context.Context, b state.Backend, runID string, d Dispatch, o Outcome, attempt int) error

RecordFinish writes the spend row and the outcome event, and clears the in-flight row.

Spend is recorded whether or not the dispatch succeeded: a failed run has usually already been paid for, and NFR-OBS-2 promises exactly one spend row per completed dispatch — including failures — so the cost view never misses a silent burn.

The spend row goes first. If the process dies between the two writes, the cost is already accounted for; the reverse order would lose real money from the budget guardrail's view.

func RecordStart

func RecordStart(ctx context.Context, b state.Backend, runID string, d Dispatch, sp *Spawned, attempt int) error

RecordStart writes the `dispatch` event and the in-flight row, in that order, before the child is known to be doing anything useful.

Both go through state.Backend rather than SQL, so the single writer stays single (checklist rule 17).

func TimeoutFor

func TimeoutFor(estimateHours, multiplier float64) time.Duration

TimeoutFor computes a dispatch's timeout: estimateHours × multiplier, in hours. Port of orchestrator/orch.py::_timeout_for.

A non-positive result — no estimate, or a multiplier someone zeroed in config — falls back to FallbackTimeout rather than to "no timeout at all", which would let one hung child hold a slot forever.

func TouchesCriticalFiles

func TouchesCriticalFiles(task model.Task) bool

TouchesCriticalFiles is the union of the three file predicates (FR-C-1b).

func TouchesEdgeFunctions

func TouchesEdgeFunctions(task model.Task) bool

TouchesEdgeFunctions reports whether a declared file is a `supabase/functions/*/index.ts`. Only the entry point counts — the other files in the same directory are helpers.

func TouchesMigrations

func TouchesMigrations(task model.Task) bool

TouchesMigrations reports whether a declared file lives under `supabase/migrations/`.

func TouchesPackagesCritical

func TouchesPackagesCritical(task model.Task) bool

TouchesPackagesCritical reports whether a declared file lives under `packages/*/lib/{auth,billing,security}/`.

Types

type AlertEvents

type AlertEvents interface {
	Events(ctx context.Context, taskID string, n int) ([]state.Event, error)
	AppendEvent(ctx context.Context, runID string, e state.Event) error
}

AlertEvents reads and writes the budget_alert events that make an alert once per window even across restarts. state.Backend and StateRecorder between them satisfy it; see NewBudgetAlerts.

type BudgetAlerts

type BudgetAlerts struct {
	Usage  BudgetUsage
	Notify BudgetNotifier
	Events AlertEvents
	RunID  string
	// Pct is the share of the cap (not of token_budget) that triggers the
	// first alert, in (0, 100].
	Pct float64
	Log *slog.Logger
	// contains filtered or unexported fields
}

BudgetAlerts sends one message when a provider's weighted window crosses Pct of its cap, and one when it reaches the cap and the gate starts deferring — each at most once per window length per provider.

ponytail: "once per window length" rather than tracking when usage drops back below the line, so a provider that dips and climbs again inside one window is not re-announced. Track the dip if that turns out to matter.

func (*BudgetAlerts) Check

func (a *BudgetAlerts) Check(ctx context.Context, now time.Time, waiting map[string]int)

Check reads every provider's window and sends what is due. waiting counts the ready tasks deferred per provider. Every failure is logged and swallowed.

type BudgetGate

type BudgetGate interface {
	CanDispatch(ctx context.Context, provider string) (budget.Decision, error)
}

BudgetGate is the slice of budget.Gate the scheduler uses. An interface so a test can drive the fail-open path without building a spend history, and so the scheduler does not care how the window is computed.

type BudgetNotifier

type BudgetNotifier interface {
	BudgetAlert(ctx context.Context, a budget.Alert)
}

BudgetNotifier is where the alerts go. No error, like Notifier: a broken webhook never reaches the loop.

type BudgetUsage

type BudgetUsage interface {
	Snapshot(ctx context.Context) (map[string]budget.ProviderSnapshot, error)
}

BudgetUsage is the part of budget.Gate the alerts read.

type BudgetWindow

type BudgetWindow interface {
	AllCapped(ctx context.Context) (bool, error)
	EarliestReset(ctx context.Context) (time.Time, error)
}

BudgetWindow is the part of budget.Gate the loop needs beyond the per-dispatch check.

type CIBackend

type CIBackend interface {
	// TasksWithPendingCI returns tasks that have a PR open and whose CI has
	// not resolved — both conditions, because a task with no PR has no CI to
	// poll and one whose CI finished must not come back round.
	TasksWithPendingCI(ctx context.Context) ([]state.TaskRuntime, error)
	SetTaskCIStatus(ctx context.Context, taskID, status string) error
	// IncrementCIAttempts bumps the counter and returns its new value —
	// which is the number of the attempt just started. Python compares the
	// stored counter, increments it, and then emits `ci_attempts + 1`
	// separately; having the write hand back the number removes the chance
	// of the event and the column disagreeing, and the arithmetic only ever
	// showed its off-by-one with ci_max_retries > 1.
	IncrementCIAttempts(ctx context.Context, taskID string) (int, error)
}

CIBackend is the slice of state.Backend the poller reads and writes. A narrow interface so the poller is testable without a database, and so every CI column this package touches is listed in one place.

type CIPoller

type CIPoller struct {
	Provider vcs.Provider
	Backend  CIBackend
	// Worktree recreates a task's worktree so the CI logs have somewhere to
	// live. Nil means worktree mode is off, and a CI failure then blocks the
	// task rather than retrying blind.
	Worktree CIWorktree

	// PollInterval is how often CI is actually asked. Python reads
	// `vcs.ci_poll_interval_s`; zero means the default.
	PollInterval time.Duration
	// MaxRetries is how many times a failing CI re-dispatches the task with
	// its logs before the task is blocked. Python reads `vcs.ci_max_retries`.
	MaxRetries int
	// ConflictRetries is how many times a PR that conflicts with its base is
	// handed to the agent to resolve before the task is blocked (#438). The
	// value is taken as is: 0 turns conflict retries off, clean merges
	// included, and blocks as before. `orch run` reads
	// retry.conflict.max_attempts.
	ConflictRetries int
	// AutoMerge merges a PR whose CI went green. Python reads
	// `github.auto_merge`.
	AutoMerge bool
	// Squash and MergeWhenPassing are passed to MergePR. Python hardcodes
	// both on (`gh pr merge --squash --auto`); internal/vcs made them
	// parameters, so they are surfaced here and `orch run` sets both. Both
	// off is a `gh pr merge` with no method, which gh refuses outside a
	// terminal (#232).
	Squash           bool
	MergeWhenPassing bool
	// MergeQueue merges green PRs through orch's queue (#522,
	// merge_queue.enabled): one at a time, in order, each brought up to date
	// with the base and re-verified first. Needs AutoMerge and a Queue store.
	MergeQueue bool
	// Reverify is merge_queue.reverify: when_base_moved or never.
	Reverify string
	// Queue keeps the queue across runs; state.SQLite is one.
	Queue MergeQueueStore
	// contains filtered or unexported fields
}

CIPoller watches the pull requests a run opened and acts on what CI says.

Port of orch.py's `_check_ci_once`. It is only ever active when worktree mode AND auto-PR are both on — without a PR there is nothing to poll — so a nil Provider or a nil Backend disables it entirely rather than being an error.

func (*CIPoller) Poll

func (p *CIPoller) Poll(ctx context.Context, s *Scheduler) (int, error)

Poll asks CI about every task waiting on it, if enough time has passed. Returns how many tasks it acted on.

Never returns an error for a CI outcome — a red build is a result, not a failure of the poller. It returns one only when the whole sweep could not happen, and even then the loop carries on: a CI poller that can end a run would be worse than one that is briefly blind.

type CIWorktree

type CIWorktree interface {
	Recreate(ctx context.Context, taskID string) (string, error)
	MergeBase(ctx context.Context, taskID, baseBranch string) (worktree.MergeResult, error)
	Push(ctx context.Context, taskID string) error
	Remove(ctx context.Context, taskID string) error
}

CIWorktree is the slice of internal/worktree the poller needs: bringing a removed worktree back so the failing logs can be left in it, and bringing a conflicting branch up to date with its base (#438).

type CommentReader

type CommentReader interface {
	TaskComments(ctx context.Context, taskID string) ([]json.RawMessage, error)
}

CommentReader reads a finished task's comment trail.

Separate from RecordBackend rather than a method on it: the concurrency tests build a RecordBackend double and none of them is about prompts, and this is read at one call site for one block of one file.

type CycleError

type CycleError struct{ Cycle []string }

CycleError reports a dependency cycle, naming the ring.

The message is copied from Python's TaskCycleError, closing node included, because scripts/parity.sh diffs the two binaries' output line for line.

func (*CycleError) Error

func (e *CycleError) Error() string

type Decision

type Decision string

Decision is what the operator answered at the semi-mode gate.

const (
	DecisionDispatch Decision = "dispatch" // y
	DecisionDefer    Decision = "defer"    // Enter or n — re-offered at the end of the run
	DecisionSkip     Decision = "skip"     // s — blocked permanently
	DecisionQuit     Decision = "quit"     // q — drain what is in flight and stop
)

type Dispatch

type Dispatch = contract.Dispatch

Dispatch is one task's run: which provider, with what, and for how long.

type DispatchReader

type DispatchReader interface {
	InFlightDispatches(ctx context.Context) ([]state.Dispatch, error)
	ClearDispatch(ctx context.Context, runID, taskID string) error
}

DispatchReader lists the dispatch rows a project still has in flight, and clears the ones whose process is gone. A narrow interface so the loop is testable without a database; state.Backend satisfies it (#148).

type E2ESummary

type E2ESummary = contract.E2ESummary

E2ESummary is an E2E run in counts, and where its full report is.

type Gate

type Gate interface {
	Ask(task model.Task, reason string) Decision
}

Gate asks the operator whether to dispatch one task.

An interface with a single method, rather than Python's SemiModeGate class that reads stdin directly, so the scheduler can be tested without a terminal. TerminalGate is the real one; tests supply their own.

`reason` is the already-rendered explanation of why the gate fired, so an implementation does not need the router to print something useful.

type InFlight

type InFlight struct {
	Task    model.Task
	Route   model.RouteEntry
	Attempt int
	Spawned *Spawned
	// Lock is the per-task flock, held for as long as the child runs. Nil
	// when task locks are off. The reaper releases it; see TaskLock.
	Lock *TaskLock
	// StartedAt is when the child was forked, for the spend row's duration.
	StartedAt time.Time
	// Dispatch is what was asked of the provider, kept so the reaper can
	// record the outcome against the same paths and route.
	Dispatch Dispatch
	// Conflict is the merge this attempt was asked to resolve (#438), nil
	// for any other attempt; a resolved one becomes a draft lesson (#451).
	Conflict *prompt.Conflict
	// GuardWarnings is what the pre-PR guard warned about, for the PR body.
	GuardWarnings []string
	// ReviewUnavailable is why the local review did not run, for the PR body
	// (#539).
	ReviewUnavailable string
	// VerifyNote is the verify's verdict in one line, for the closing
	// comment of the task's source issue (#525); "" with no verify.
	VerifyNote string
	// Evidence is the verified attempt's evidence manifest (#520), made the
	// task's evidence once the work is pushed; nil with no verify.
	Evidence *bundle.Manifest
}

InFlight is one dispatched task under supervision, and everything the reaper needs to finish it.

type IssueCloser added in v0.31.0

type IssueCloser interface {
	CloseIssue(issueURL, comment string) error
}

IssueCloser closes a GitHub issue with a closing comment; vcs's GitHubProvider is the real one.

type MergeQueueStore added in v0.31.0

type MergeQueueStore interface {
	Enqueue(ctx context.Context, taskID, prURL string, at time.Time) (bool, error)
	SetQueueState(ctx context.Context, taskID, state, reason string, at time.Time) error
	QueueEntries(ctx context.Context) ([]state.QueueEntry, error)
}

MergeQueueStore keeps the merge queue (migration 017). state.SQLite is one.

type MissingDepError

type MissingDepError struct {
	// Offenders are (task id, missing dependency) pairs, sorted.
	Offenders [][2]string
}

MissingDepError reports dependency references that name no task.

func (*MissingDepError) Error

func (e *MissingDepError) Error() string

type Mode

type Mode string

Mode is how much the operator is asked. Port of orch.py's `--mode`.

const (
	// ModeAuto dispatches everything that is ready.
	ModeAuto Mode = "auto"
	// ModeSemi offers every critical task to the operator first (FR-C-2).
	ModeSemi Mode = "semi"
)

type Notifier

type Notifier interface {
	Blocked(ctx context.Context, taskID, reason string)
	CIBlocked(ctx context.Context, taskID, prURL string, attempts int)
	// Stalled announces a live run that has made no progress for a while,
	// and what it is waiting on (#255).
	Stalled(ctx context.Context, stalledFor time.Duration, waitingOn string)
}

Notifier is the side channel the engine announces bad news on. An interface so the engine does not depend on internal/notify's transport, and so a test can assert that a block was announced without standing up an HTTP server.

No method returns an error, and that is the contract, not an oversight: a broken webhook must never be able to reach the dispatch loop.

type OneShot

type OneShot struct {
	State state.Backend
	Gate  *budget.Gate
}

OneShot runs one prompt outside the task loop (#461) — `orch report summary --ai` today — through the same spawn and supervision as a task, so it honours ORCH_FAKE_PROVIDER too.

The zero value only runs. With State set, the dispatch's spend row is written like a task attempt's, under the synthetic task id d.Req.TaskID (e.g. `summary-<run>`), so the cost views and the budget window see it; no event is written, as an outcome event would count the synthetic id as a task in the run's receipt. With Gate set, a provider over its budget window is refused before anything is spawned.

func (OneShot) Run

func (o OneShot) Run(ctx context.Context, d Dispatch) (Outcome, error)

Run checks the gate, runs d and records its spend, whether or not the dispatch succeeded: a failed run has usually been paid for already.

type OpenPRLister

type OpenPRLister interface {
	TasksWithPendingCI(ctx context.Context) ([]state.TaskRuntime, error)
}

OpenPRLister lists the tasks whose PR is open and still waiting on CI, the ones a new PR is checked against. state.SQLite is one.

type Outcome

type Outcome = contract.Outcome

Outcome is everything one completed dispatch produced.

func Run

func Run(ctx context.Context, d Dispatch) (Outcome, error)

Run spawns a dispatch, supervises it, and parses what it produced.

Recording the outcome in state is the caller's job: Run stays free of a state.Backend so it can be exercised without a database, and so the single writer stays single (checklist rule 17).

The ordering matches the Python reap loop: a timeout's reason wins over anything the CLI printed, because a killed child's output is whatever happened to be flushed before the signal — and TimeoutReason is what providers.Classify keys FailureTimeout on.

type PRRecorder

type PRRecorder interface {
	SetTaskPR(ctx context.Context, taskID, prURL string) error
}

PRRecorder writes a task's pull request URL. Separate from RecordBackend because only the auto-PR path needs it, and state.Backend's SetTaskPR moves ci_status to pending in the same write — the thing that makes the CI poller notice the task at all.

type ProjectRun added in v0.31.0

type ProjectRun struct {
	Project *project.Project
	// Tasks is the DAG the run walks, as defined (statuses are the Queue's).
	Tasks []model.Task
	// Queue starts from the database's statuses.
	Queue *TaskQueue
	// Router is model_router.yaml, empty when it does not load.
	Router router.Router
	RunID  string
	// Notifier posts to the configured webhooks: a no-op without any, and
	// always on an isolated run.
	Notifier *notify.Notifier
	// contains filtered or unexported fields
}

ProjectRun is a run wired from an opened project (#550): FromProject builds it, the caller may print what it likes about it, and Start runs it.

func FromProject added in v0.31.0

func FromProject(ctx context.Context, p *project.Project, opts RunOptions) (*ProjectRun, error)

FromProject wires a run of p: it seeds the database with the DAG, starts the queue from the database's statuses, and settles how the work is isolated and published (worktrees, pushes, PRs) from the config and opts. It refuses a worktree run whose base branch has no commit to branch from. Nothing is dispatched and no run is recorded until Start.

func (*ProjectRun) Start added in v0.31.0

func (r *ProjectRun) Start(ctx context.Context) (code int, err error)

Start records the run, wires its scheduler and loop over the project's backend, and walks the DAG to the end. code is the loop's exit code.

type ProviderGate

type ProviderGate interface {
	ProviderStates(ctx context.Context) ([]state.ProviderState, error)
}

ProviderGate lists the providers the operator turned off or back on.

type ReadyOpts

type ReadyOpts struct {
	// InFlight excludes tasks the caller has picked but not yet marked
	// in-progress, so one tick cannot dispatch the same task twice.
	InFlight map[string]bool
	// Only is an fnmatch-style glob on the task id. When set, only matching
	// tasks are candidates — but the WHOLE DAG still resolves dependencies,
	// so a task whose deps sit outside the glob becomes ready as soon as
	// those deps are done. Narrowing the candidate set is the right home for
	// --only; narrowing the graph would silently change readiness.
	Only string
	// Deferred excludes tasks the operator deferred at the semi gate.
	Deferred map[string]bool
	// Waiting excludes tasks another queue owns until it releases them —
	// today, the retry queue's backoff. Without it a task reset to todo for
	// a retry is dispatched by this pass before its backoff expires, and can
	// then be dispatched a second time when the retry fires.
	Waiting map[string]bool
}

ReadyOpts narrows what Ready considers.

type RecordBackend

type RecordBackend interface {
	// RecordDispatchAndEvent writes the in-flight row and the dispatch event.
	RecordDispatchAndEvent(ctx context.Context, runID string, d Dispatch, sp *Spawned, attempt int) error
	// RecordFinish writes the spend row and the outcome event, and clears
	// the in-flight row.
	RecordFinish(ctx context.Context, runID string, d Dispatch, o Outcome, attempt int) error
	// AppendEngineEvent writes one event of the engine's own (retry,
	// escalate, id_spoof_detected).
	AppendEngineEvent(ctx context.Context, runID, eventType, taskID, backend string, extra map[string]any) error
	// TaskStatus reads a task's current status back, for the guard that
	// respects a sub-agent which finished despite a wrapper failure.
	TaskStatus(ctx context.Context, taskID string) (model.Status, error)
	// Transition moves a task, recording the note.
	Transition(ctx context.Context, taskID string, to model.Status, note string) error
}

RecordBackend is the slice of state.Backend the engine writes through.

A narrow interface rather than state.Backend itself, so the concurrency and retry tests run without a database — they are about semaphores and policy, not about SQL — and so every write the engine performs is listed in one place.

type RetryDecision

type RetryDecision struct {
	// Retry is false when the task is terminal and should be blocked.
	Retry bool
	// Route is what the retry should use: the same one, the version-drift
	// fallback, or the escalation route.
	Route model.RouteEntry
	// Attempt is the number the retry will run as.
	Attempt int
	// Backoff is how long to wait first.
	Backoff time.Duration
	// Reason is the operator-facing explanation, already composed.
	Reason string
	// Escalated marks an attempt-3 promotion to another route, which emits
	// its own event before the retry event.
	Escalated bool
	// ToRouteKey is the escalation target's key in the router, for the
	// `escalate` event. Empty unless Escalated.
	ToRouteKey string
}

RetryDecision is what the reaper concluded about a failed dispatch.

func DecideRetry

func DecideRetry(in RetryInput) RetryDecision

DecideRetry applies the retry policy to one failed dispatch. Pure: no clocks, no I/O — Backoff is a duration, not a deadline, so the caller stamps it against its own clock and a test does not have to wait.

Port of the Fase B / FR-D-4 / FR-D-8 branch of orch.py's reap loop.

type RetryInput

type RetryInput struct {
	Task    model.Task
	Route   model.RouteEntry
	Attempt int
	Failure providers.Failure
	// Reason is the failure's message, already truncated by the caller.
	Reason string
	// SpentUSD is what this task has cost across every attempt so far.
	SpentUSD float64
	// Routes is the router, for resolving an escalation key.
	Routes map[string]model.RouteEntry
	Cfg    config.Config
}

RetryInput is everything the policy needs to decide.

type RetryItem

type RetryItem struct {
	Task    model.Task
	Route   model.RouteEntry
	Attempt int
	// EarliestAt is when the backoff expires. The refill loop skips an item
	// whose time has not come rather than sleeping — the loop already ticks.
	EarliestAt time.Time
}

RetryItem is one task waiting to be re-dispatched.

type RunLock

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

RunLock is the exclusive, per-project lock `orch run` holds (#344).

Two runs on one project raced over the same tasks: each adopted the other's status writes as "changed outside this run", re-dispatched work the other was already retrying, and one retried a task whose PR had just merged. A run that outlived its wrapper is the usual way to get there.

It is a flock, like TaskLock, so the kernel drops it when the process dies however it dies: a lock file left by a killed run holds no lock, and the next run takes it over. The pid and start time written into the file are for the error the second run prints, not for deciding anything. Go opens files close-on-exec, so the agents a run forks do not inherit the lock and cannot keep it alive after the run is gone.

Only `orch run` takes it. The dashboard and every read-only command read the database as before.

func AcquireRunLock

func AcquireRunLock(stateDir string) (*RunLock, error)

AcquireRunLock takes the run lock in stateDir, or returns a *RunLockHeldError naming the run that holds it. Any other error is a problem with the state directory itself.

func (*RunLock) Release

func (l *RunLock) Release()

Release drops the lock. Safe on a nil lock and safe to call twice. The file stays behind, emptied: deleting it would race a run that has just opened it, and emptying it is what tells the next run this one ended cleanly rather than died holding it.

type RunLockHeldError

type RunLockHeldError struct {
	Path string
	// PID and Started are what the holder wrote; zero and "" when the file
	// could not be read or predates them.
	PID     int
	Started string
}

RunLockHeldError is AcquireRunLock's answer when another run holds the lock.

func (*RunLockHeldError) Error

func (e *RunLockHeldError) Error() string

type RunOptions added in v0.31.0

type RunOptions struct {
	Mode Mode
	// MaxTasks starts at most this many tasks; 0 means no limit.
	MaxTasks int
	// Only dispatches only the tasks whose id matches this glob.
	Only string
	// TaskLocks takes a per-task lock, for several instances on one project.
	TaskLocks bool
	// WorktreeMode turns on dispatch.worktree_mode for this run.
	WorktreeMode bool
	// NoPush skips pushing task branches.
	NoPush bool
	// RunID names the run; empty means a fresh session id.
	RunID string
	// Isolated is `orch bench`'s run: no worktrees, no pushes, no PRs, no
	// CI polling and no notifications, whatever the project's config says.
	Isolated bool
	// Tasks, when set, is the whole DAG instead of tasks.json, which is then
	// neither read nor reloaded: `orch knowledge curate`'s one task (#452).
	Tasks []model.Task
	// Verifier, when set, is the only gate a task's work passes before it is
	// published, whatever verify.enabled says: curate's scope check.
	Verifier Verifier
	// In and Out are the terminal the semi-mode gate asks on.
	In  io.Reader
	Out io.Writer
	// Stderr takes the run's notes and warnings; nil is os.Stderr.
	Stderr io.Writer
}

RunOptions is what one run asks for on top of the project's config: `orch run`'s flags, and what `orch bench` and `orch knowledge curate` change.

type Runner

type Runner struct {
	Scheduler *Scheduler
	// Budget supplies the all-capped check. Nil disables the sleep.
	Budget BudgetWindow
	// Dispatches backs the orphan sweep. Nil disables it.
	Dispatches DispatchReader
	// CI watches the pull requests this run opened. Nil disables it, which
	// is every project not running worktree mode with auto-PR.
	CI *CIPoller
	// Alerts announces budget windows near or at their cap. Nil disables it.
	Alerts *BudgetAlerts
	// Statuses is the database's view of each task, which this run adopts
	// where it changed behind the run's back. Nil disables it.
	Statuses StatusReader
	// Requests is where the operator's stop requests are read from (#356).
	// Nil disables them.
	Requests StopRequests
	// ReloadTasks returns tasks.json's tasks when the file changed since it
	// last looked, and whether it did (v0.22): a task added or edited while
	// the run is going joins it. Nil disables it.
	ReloadTasks func(ctx context.Context) ([]model.Task, bool, error)

	// Signals, when non-nil, is used instead of installing real handlers —
	// the tests drive it directly rather than signalling the test binary.
	Signals <-chan os.Signal
	// contains filtered or unexported fields
}

Runner drives one `orch run`: it alternates reaping and refilling until the work is done or a signal arrives.

func NewRunner

func NewRunner(s *Scheduler) *Runner

NewRunner wires a runner over a scheduler.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context) (int, error)

Run walks the loop until there is nothing left to do, and returns the process exit code.

Port of orch.py's `while True:` in main(). The order inside a tick is the Python's and matters: reap first so finished children free their slots before the refill that wants them, then refill, then the budget sleep, then the termination test.

A signal drains rather than exits: children already running are given time to finish, because killing an agent mid-edit leaves a worktree in a state nobody asked for. A second signal escalates to SIGKILL on every process group. That is what makes Ctrl-C twice mean "I meant it".

type Scheduler

type Scheduler struct {
	Queue  *TaskQueue
	Routes map[string]model.RouteEntry
	Sems   *Sems
	Opts   SchedulerOptions

	// Gate is consulted in semi mode. Nil means every task is dispatched,
	// which is also what auto mode does.
	Gate Gate
	// Budget is consulted before the semaphores. Nil disables the check.
	Budget BudgetGate
	// Providers says which backends the operator turned off (`orch provider
	// disable`); their tasks wait. Nil means every provider is on.
	Providers ProviderGate
	// Notify announces blocked tasks on the operator's webhooks. The zero
	// value is a working no-op, so this is never nil-checked at the call
	// sites — which is the point: a side channel must not become a branch.
	Notify Notifier
	// Backend records dispatches, outcomes and events. Nil skips recording,
	// which is how the concurrency tests run without a database.
	Backend RecordBackend
	// Worktree isolates each task in its own git worktree when the project
	// asks for it. Nil turns the whole thing off, and the task runs in the
	// project root as it did before F-2.
	Worktree WorktreeManager
	// VCS opens the pull request after a successful push. Nil, or AutoPR
	// off, means no PR is opened and the task finishes normally.
	VCS vcs.Provider
	// CIRecorder writes the PR URL, which is also what puts the task into
	// the CI poller's filter. Without it a PR would be opened and never
	// watched, so openPR refuses to leave one in that state.
	CIRecorder PRRecorder
	// PRs reads a dependency's pull request URL, so a dependency whose PR is
	// already merged is not merged into its dependent's worktree again
	// (#345). Nil, or VCS nil, hands every dependency to the worktree.
	PRs TaskPRReader
	// Comments reads a finished dependency's notes for the prompt's
	// "Completed dependencies (context)" block. Nil falls back to whatever
	// tasks.json carried, which since F-12 is nothing — see completedDeps.
	Comments CommentReader
	// Verifier checks a clean exit's work in its worktree before the push
	// (verify.enabled). Nil, or worktree mode off, verifies nothing.
	Verifier Verifier
	// OpenPRs lists the open task PRs a new one is checked against for
	// conflicts (radar, #482). Nil skips that check.
	OpenPRs OpenPRLister
	// Knowledge ranks the project lessons a prompt carries (knowledge.enabled,
	// #451). Nil renders no lessons.
	Knowledge knowledge.Ranker
	// Issues closes the GitHub issue a task came from once its last task
	// lands locally (vcs.provider: local, #525); with a PR the body's
	// `Closes` keyword does it on merge. Nil closes nothing.
	Issues IssueCloser
	// Log receives the operator-facing lines. Nil uses slog's default.
	Log *slog.Logger
	// contains filtered or unexported fields
}

Scheduler decides what to dispatch and starts it. Port of orch.py's `_refill` and `_spawn_one`.

It does not reap: Refill starts children and records them in InFlight, and the reaper (G3.2) finishes them, releases their slots and their locks, and applies the retry policy. Splitting the two keeps the gating order — which is the part with the sharp edges — testable on its own.

func NewScheduler

func NewScheduler(q *TaskQueue, routes map[string]model.RouteEntry, opts SchedulerOptions) *Scheduler

NewScheduler wires a scheduler over a queue and a route table.

func (*Scheduler) CleanupWorktrees

func (s *Scheduler) CleanupWorktrees(ctx context.Context)

CleanupWorktrees runs RemoveAll. Call it after DrainWait, never from a signal handler.

func (*Scheduler) ClearDeferred

func (s *Scheduler) ClearDeferred() int

ClearDeferred forgets the operator's deferrals and returns how many there were, so semi mode can offer them again before the run ends.

func (*Scheduler) DeferReasons

func (s *Scheduler) DeferReasons() map[string]string

DeferReasons explains, per task id, why a ready task was skipped.

func (*Scheduler) Dispatched

func (s *Scheduler) Dispatched() int

Dispatched is how many children this run has started.

func (*Scheduler) DrainWait

func (s *Scheduler) DrainWait(ctx context.Context, timeout time.Duration) (int, error)

DrainWait blocks until every in-flight child has been reaped, or until the deadline passes. Returns how many it reaped.

Called when the run is winding down — the queue is empty, the operator quit at the gate, or a signal arrived. The worktree's RemoveAll belongs AFTER this returns, never inside a signal handler, because cleanup racing a still-draining task would delete a worktree a backend process is still writing into.

func (*Scheduler) Draining

func (s *Scheduler) Draining() bool

Draining reports whether the operator asked to stop.

func (*Scheduler) InFlight

func (s *Scheduler) InFlight() map[int]*InFlight

InFlight returns the live dispatches, keyed by pid. The map is the scheduler's own; the reaper mutates it through Reap, not directly.

func (*Scheduler) Reap

func (s *Scheduler) Reap(ctx context.Context) (int, error)

Reap handles every child that has finished since the last call, and returns how many it handled. It never blocks: a tick with nothing finished does nothing, which is what lets the caller alternate Reap and Refill.

func (*Scheduler) Refill

func (s *Scheduler) Refill(ctx context.Context) (int, error)

Refill dispatches as many ready tasks as capacity allows, and returns how many it started this tick.

The ready set is walked ONCE per tick: a task that cannot get a slot is skipped rather than waited on, so a project with 300 ready tasks does not turn one tick into a stall. The next tick retries it.

func (*Scheduler) RetryQueue

func (s *Scheduler) RetryQueue() []RetryItem

RetryQueue is what is waiting to be re-dispatched, for tests and for the status surface.

func (*Scheduler) SpentUSD

func (s *Scheduler) SpentUSD(taskID string) float64

SpentUSD is what a task has cost across every attempt.

func (*Scheduler) StartDraining

func (s *Scheduler) StartDraining()

StartDraining stops new dispatches while letting what is running finish.

func (*Scheduler) StopTask

func (s *Scheduler) StopTask(ctx context.Context, taskID string, hold bool)

StopTask ends a task's running attempt at the operator's request, and holds it or dispatches it again (#356). A task that is not running is held, or, waiting out a retry's backoff, dispatched now.

func (*Scheduler) WatchAgents

func (s *Scheduler) WatchAgents(ctx context.Context, now time.Time)

WatchAgents reads every running attempt's log, at most every watchInterval, and records agent_looping when the agent keeps making the same tool call (once per attempt) and, when the log has been silent for watch.stall_after_s, one of:

  • agent_waiting: with watch.liveness on, its process group still uses CPU or moves data, or files grow in its worktree or watch.data_dirs. The event carries the evidence ("downloading data: +163 MB in 1h0m0s") and is refreshed every stall_after_s while the wait lasts.
  • agent_stalled: no sign of life for stall_after_s. Recorded once, again only after the agent showed work and then stopped.

agent_resumed closes either when the log grows again. Called from the run loop, which owns inFlight.

ponytail: a 64 KiB tail read per attempt every 30 s, and for a silent one a /proc scan and a walk of its worktree; at a few parallel tasks that is nothing. Watch the files if runs get much wider.

type SchedulerOptions

type SchedulerOptions struct {
	// Mode is auto or semi.
	Mode Mode
	// GlobalMax and PerProvider are config's concurrency block.
	GlobalMax   int
	PerProvider map[string]int
	// TimeoutMultiplier is config's default_timeout_multiplier.
	TimeoutMultiplier float64
	// Cfg is the loaded config, for the retry policy and the budget cap.
	Cfg config.Config
	// BudgetUSD, when non-nil, is passed to providers that take a
	// per-dispatch cap.
	BudgetUSD *float64
	// UseTaskLocks turns on the per-task flock (Python's `--task-locks`).
	UseTaskLocks bool
	// Only narrows the candidate set to task ids matching this glob.
	Only string
	// MaxTasks caps how many distinct tasks one run starts. Retries of a
	// task already started (a failed attempt, a CI failure) do not count.
	// Zero means no cap.
	MaxTasks int
	// StateDir is where logs and task locks live.
	StateDir string
	// DBDir is the directory holding orch.db, which a sandboxed agent must be
	// able to write to report its task (#387). Empty means StateDir.
	DBDir string
	// Cwd is the project root. Children run in it, or in their worktree
	// when WorktreeMode is on.
	Cwd string
	// ProjectID is the project's id, handed to every child with Cwd as
	// ORCH_PROJECT_ID / ORCH_PROJECT_ROOT: see childEnv.
	ProjectID string
	// RunID ties every event and dispatch row to this run.
	RunID string

	// WorktreeMode gives each task its own git worktree and branch (F-2).
	WorktreeMode bool
	// BaseBranch is what a worktree branches from and what a PR targets.
	BaseBranch string
	// AutoPR opens a pull request after a successful push (F-4).
	AutoPR bool
	// LocalMerge squash-merges each finished task into BaseBranch here,
	// with no push and no PR (vcs.provider: local, #455). Needs WorktreeMode.
	LocalMerge bool
	// ConflictRetries caps the agent dispatches that resolve a task whose
	// local merge conflicts with the base (retry.conflict, #438).
	ConflictRetries int
}

SchedulerOptions configures one run.

type Sem

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

Sem is a counting semaphore with an observable count. Port of orch.py's `_Sem`.

Deliberately not `golang.org/x/sync/semaphore`, which the G3.1 brief suggested. That package has `TryAcquire`, but no way to read how much is currently held — and the current in-flight count is the whole point of AS-05, which is asserted between ticks and is what the concurrency test checks. Using it would mean keeping this counter alongside it anyway, so it would add a dependency and a second source of truth to save nothing.

Acquisition is always non-blocking: a tick that cannot get a slot skips the task and the next tick retries. Blocking here would stall the reap loop that is the only thing able to free a slot.

func NewSem

func NewSem(capacity int) *Sem

NewSem returns a semaphore with the given capacity. A capacity of zero or less admits nothing, which is what a config of `global_max: 0` asks for.

func (*Sem) Cap

func (s *Sem) Cap() int

Cap is the configured ceiling.

func (*Sem) Current

func (s *Sem) Current() int

Current is how many slots are held right now.

func (*Sem) Release

func (s *Sem) Release()

Release returns a slot. Releasing more than was acquired floors at zero rather than going negative, as Python's `max(0, ...)` does: a double release is a bug, but one that must not hand out phantom capacity.

func (*Sem) TryAcquire

func (s *Sem) TryAcquire() bool

TryAcquire takes a slot if one is free, reporting whether it did.

type Sems

type Sems struct {
	Global   *Sem
	Provider map[string]*Sem
}

Sems is the pair of gates every dispatch passes: one global ceiling across every backend, and one per backend (FR-D-5).

func NewSems

func NewSems(globalMax int, perProvider map[string]int) *Sems

NewSems builds the semaphores from a config's concurrency block.

func (*Sems) Knows

func (s *Sems) Knows(backend string) bool

Knows reports whether a backend has a configured cap.

func (*Sems) Release

func (s *Sems) Release(backend string)

Release returns both slots taken by a successful TryAcquire.

func (*Sems) TryAcquire

func (s *Sems) TryAcquire(backend string) bool

TryAcquire takes a slot for one backend, or reports that it could not.

The provider gate is checked first and released if the global gate then refuses, which is Python's order. It matters: doing it the other way lets a full provider consume and return a global slot on every tick, so a backend that is at its cap would keep flapping the global count that AS-05 reads.

An unknown backend is refused rather than admitted. A router entry naming a provider with no configured cap is a config error, and treating "no cap configured" as "no limit" is how a global_max quietly stops being a ceiling.

type SpawnRequest

type SpawnRequest struct {
	// Provider builds the argv and says how the prompt is delivered.
	Provider providers.Provider
	// Req is handed to Provider.Argv verbatim.
	Req providers.Request
	// PromptPath is the file whose bytes become the child's stdin, for a
	// provider on providers.PromptStdin, or Req.PromptText, for one on
	// providers.PromptArg when the caller left it empty, or Req.PromptPath,
	// for one on providers.PromptFile. Python pipes the file rather than
	// embedding the prompt in the argv or using an @file reference, both of
	// which hit escaping edge cases in practice.
	PromptPath string
	// LogPath receives stdout and stderr, merged. Its directory is created
	// if missing.
	LogPath string
	// Cwd is the child's working directory.
	Cwd string
	// Env, when non-nil, replaces the inherited environment. Spawn always
	// sets PWD to Cwd on top of it — see the note in Spawn.
	Env []string
	// Sandbox, when non-nil, runs the CLI under orch's Landlock launcher
	// confined to it (dispatch.sandbox, #481); nil runs it unconfined.
	Sandbox *sandbox.Policy
}

SpawnRequest is what Spawn needs beyond the provider's own argv.

type Spawned

type Spawned struct {
	// PID is the child's pid, which is also its process-group id because
	// the child is made a session leader.
	PID int
	// LogPath is the file receiving the child's merged stdout and stderr.
	LogPath string
	// StartedAt is when the child was forked, for the spend row's duration.
	StartedAt time.Time
	// contains filtered or unexported fields
}

Spawned is a child process under supervision, plus the handles Wait needs to clean up after it.

func Spawn

func Spawn(ctx context.Context, sr SpawnRequest) (*Spawned, error)

Spawn forks the provider's CLI and returns the supervised child.

The child is put in its own session, and therefore its own process group (checklist rule 18). Cleanup can then signal the whole group, catching the bash wrappers and sub-agents a coding CLI forks, rather than only the direct child — without it, killing the CLI leaves grandchildren orphaned in the user's login session (Sprint A / Issue #12).

On any error the caller gets no Spawned and no leaked handles.

func (*Spawned) Wait

func (s *Spawned) Wait(timeout time.Duration) (exitCode int, reason string, timedOut bool)

Wait blocks until the child exits or timeout elapses, and returns its exit code, a reason string (empty unless the timeout fired), and whether it timed out. Port of dispatcher.py's _wait_with_timeout.

The timeout path is SIGTERM to the process group, TermToKillGrace, then SIGKILL to the group, then a short reap window. Signalling the group rather than the pid is what makes this reach the bash wrappers and sub-agents a coding CLI forks; without it the CLI dies and its children are reparented to init, still holding the workspace (Sprint A / Issue #12, checklist rule 18).

Wait always closes the handles Spawn opened, on every path.

type StateRecorder

type StateRecorder struct{ Backend state.Backend }

StateRecorder adapts a state.Backend to the scheduler's RecordBackend.

The scheduler takes the narrow interface rather than state.Backend so the concurrency tests can run without a database — they are about semaphores, not about SQL — and so the one place that writes a dispatch row stays obvious.

func NewStateRecorder

func NewStateRecorder(b state.Backend) StateRecorder

NewStateRecorder wires a backend into the scheduler.

func (StateRecorder) AppendEngineEvent

func (r StateRecorder) AppendEngineEvent(ctx context.Context, runID, eventType, taskID, backend string, extra map[string]any) error

AppendEngineEvent writes one of the engine's own events.

func (StateRecorder) RecordDispatchAndEvent

func (r StateRecorder) RecordDispatchAndEvent(ctx context.Context, runID string, d Dispatch, sp *Spawned, attempt int) error

RecordDispatchAndEvent writes the in-flight row and the `dispatch` event.

func (StateRecorder) RecordFinish

func (r StateRecorder) RecordFinish(ctx context.Context, runID string, d Dispatch, o Outcome, attempt int) error

RecordFinish on the adapter writes the spend row, the outcome event and clears the in-flight row.

func (StateRecorder) TaskComments

func (r StateRecorder) TaskComments(ctx context.Context, taskID string) ([]json.RawMessage, error)

TaskComments reads a task's comment trail, for the prompt's dependency block. The rows are passed through as the JSON they already are: Python types a comment `list[dict]` with no fixed shape, and the renderer only needs two of its keys.

func (StateRecorder) TaskPR

func (r StateRecorder) TaskPR(ctx context.Context, taskID string) (string, error)

TaskPR reads the pull request URL recorded for a task; "" when it has none.

func (StateRecorder) TaskStatus

func (r StateRecorder) TaskStatus(ctx context.Context, taskID string) (model.Status, error)

TaskStatus reads a task's current status back.

func (StateRecorder) Transition

func (r StateRecorder) Transition(ctx context.Context, taskID string, to model.Status, note string) error

Transition moves a task, recording who moved it and why.

type StatusReader

type StatusReader interface {
	TaskStatus(ctx context.Context, taskID string) (model.Status, error)
}

StatusReader reads one task's status from the source of truth.

type StopRequests

type StopRequests interface {
	LatestEventID(ctx context.Context) (int64, error)
	EventsSince(ctx context.Context, afterID int64, limit int) ([]state.Event, error)
}

StopRequests is where the loop reads the operator's stop requests (#356): the event log, which `orch task stop`, orch_task_stop and the dashboard append to from their own processes. state.Backend satisfies it.

type TaskLock

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

TaskLock is an advisory, non-blocking, exclusive lock on one task id, so several orch instances can share a project as long as each takes a distinct set of tasks. Port of orchestrator/state/flock.py.

Opt-in: Python gates it behind `--task-locks`, and so does the scheduler.

The lock lives for as long as the open file does, which is the whole reason this is a struct and not a function returning a bool. The *os.File is held on the in-flight dispatch and released by the reaper — a local variable would be collected, the descriptor closed, and the lock quietly dropped while the child is still running.

func TryAcquireTaskLock

func TryAcquireTaskLock(stateDir, taskID string) (*TaskLock, error)

TryAcquireTaskLock takes the lock for one task, or returns nil when another orch already holds it.

An error is returned only for a problem that is not contention — an unwritable state directory, say. Contention is (nil, nil): the caller skips the task this tick and tries again on the next, which is not an error condition.

func (*TaskLock) Path

func (l *TaskLock) Path() string

Path is the lock file this lock holds, for diagnostics.

func (*TaskLock) Release

func (l *TaskLock) Release()

Release drops the lock. Safe on a nil lock, so callers do not have to guard the "task locks are off" case, and safe to call twice.

The lock file itself is left behind: flock is advisory and released when the descriptor closes, so deleting the file would race another orch that has just opened it and is about to lock it.

type TaskPRReader

type TaskPRReader interface {
	TaskPR(ctx context.Context, taskID string) (string, error)
}

TaskPRReader reads the pull request a task's work went up in; "" when it has none.

type TaskQueue

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

TaskQueue is the dispatch loop's live view of the DAG. Port of orchestrator/task_queue.py.

tasks.json is read-only from the orchestrator's point of view (FR-STATE-2): this holds the status map that reacts to MarkInFlight / MarkDone / MarkBlocked between reap ticks. Since F-12 the database is the source of truth for runtime status, so a queue built with Hydrate starts from what the backend says, not from what tasks.json says.

Not safe for concurrent use. The dispatch loop is single-threaded by design — the concurrency is in the child processes, not in the scheduler — and a mutex here would only hide a second scheduler that should not exist.

func NewTaskQueue

func NewTaskQueue(tasks []model.Task) (*TaskQueue, error)

NewTaskQueue builds a queue from tasks.json's rows.

Dependency and cycle validation happen here, as they do in Python's __init__: a DAG that cannot be walked should fail at startup, not at the first dispatch. Cycle detection delegates to internal/graph rather than carrying a second depth-first search that could disagree with `orch graph`.

func (*TaskQueue) AllTasks

func (q *TaskQueue) AllTasks() []model.Task

AllTasks returns every task in (phase, id) order — the same deterministic order the display commands use (FR-Q-2).

func (*TaskQueue) Hydrate

func (q *TaskQueue) Hydrate(runtime map[string]model.Status)

Hydrate overwrites the seeded statuses with the backend's, for the tasks the backend knows about.

Python does this inside the constructor and swallows a backend that cannot answer, falling back to the tasks.json seed so the dispatch loop still starts. Keeping it a separate call makes that choice the caller's: the scheduler logs and carries on, and a test can build a queue with no backend at all.

func (*TaskQueue) MarkBlocked

func (q *TaskQueue) MarkBlocked(id string) error

func (*TaskQueue) MarkDone

func (q *TaskQueue) MarkDone(id string) error

func (*TaskQueue) MarkInFlight

func (q *TaskQueue) MarkInFlight(id string) error

MarkInFlight, MarkDone and MarkBlocked move a task in the live view.

They do not write to the database. Python's queue mirrors each mark into the backend and swallows the error so a backend hiccup cannot stall the loop; here the scheduler owns that call, because it is the thing that knows what note to record and what to do when the write fails. A queue that silently diverged from the database would be the worst of both.

func (*TaskQueue) MarkTodo

func (q *TaskQueue) MarkTodo(id string) error

MarkTodo puts a task back in the ready set after a failed attempt.

Python reaches into TaskQueue._status directly here, with a comment saying retry is the only caller and the class has no mark_todo. It does now: a retry is a legitimate move in this view, and reaching through the struct would only hide who does it.

func (*TaskQueue) Pending

func (q *TaskQueue) Pending() bool

Pending reports whether any task is still todo or in-progress — the dispatch loop's "keep going" condition.

func (*TaskQueue) Ready

func (q *TaskQueue) Ready(opts ReadyOpts) []model.Task

Ready returns the tasks whose dependencies are all done and which are themselves todo, in (phase, id) order.

Pure with respect to its inputs (FR-Q-5): the same status map and the same options give the same answer.

func (*TaskQueue) Reload

func (q *TaskQueue) Reload(tasks []model.Task) (int, error)

Reload takes tasks.json as it is now (v0.22): new tasks join with their seeded status, edited ones take their new definition, and ones no longer in the file leave. Every task the queue already knew keeps the status this run gave it, and a running task keeps the definition it was dispatched with, and stays even if the file dropped it. A set the run could not walk (a cycle, a missing dependency) is refused and the queue is unchanged. Returns how many tasks are new.

func (*TaskQueue) Status

func (q *TaskQueue) Status(id string) (model.Status, bool)

Status returns a task's current status, and whether the task is known.

func (*TaskQueue) Task

func (q *TaskQueue) Task(id string) (model.Task, bool)

Task returns one task's definition.

type TaskSlots

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

TaskSlots hands each running task a small integer no other running task in this run holds. A task's slot is the lowest free one, starting at 1, and goes back to the pool when the task finishes, so a project can derive per-task host ports from it (`API_PORT=$((3000 + ORCH_TASK_SLOT))`) and two parallel tasks never publish the same one.

1, not 0: base + 0 is the port the operator's own stack in the main checkout already publishes.

func NewTaskSlots

func NewTaskSlots() *TaskSlots

NewTaskSlots returns an empty pool.

func (*TaskSlots) Acquire

func (t *TaskSlots) Acquire(taskID string) int

Acquire returns taskID's slot, taking the lowest free one if it holds none.

func (*TaskSlots) Release

func (t *TaskSlots) Release(taskID string)

Release gives taskID's slot back. A task holding none is a no-op.

func (*TaskSlots) Slot

func (t *TaskSlots) Slot(taskID string) (int, bool)

Slot reports taskID's slot, if it holds one.

type TerminalGate

type TerminalGate struct {
	In  io.Reader
	Out io.Writer
}

TerminalGate is the real semi-mode gate: it prints a summary and blocks on one keystroke. Port of checkpoints.py's SemiModeGate.prompt_operator.

It is the only thing in the engine that reads stdin, which is why it is behind the Gate interface and in its own file — the scheduler never has to care that a human exists.

func (TerminalGate) Ask

func (g TerminalGate) Ask(task model.Task, reason string) Decision

Ask shows the task and decodes the answer.

y            → dispatch
Enter or n   → defer   (offered again on the next run)
s            → skip    (blocked permanently)
q            → quit    (drain what is in flight, then stop)

Anything else re-prompts, because an operator can fat-finger a key and the wrong default here blocks a task or ends a run. End of input is read as quit, matching Python's handling of EOF and Ctrl-C: a gate with nobody at the keyboard must drain cleanly rather than dispatch unattended.

type Verifier

type Verifier interface {
	Verify(ctx context.Context, req VerifyRequest) VerifyResult
}

Verifier checks an agent's work in its worktree after a clean exit and before the push (verify.enabled). It returns what failed, written for the agent's next attempt, or "" when the work passes. internal/verify is the implementation; its request and result types live in internal/contract so it does not import this package.

type VerifyCommand

type VerifyCommand = contract.VerifyCommand

VerifyCommand is one check the verify ran.

type VerifyFinding

type VerifyFinding = contract.VerifyFinding

VerifyFinding is one review finding, as internal/ci's Finding has it.

type VerifyRequest

type VerifyRequest = contract.VerifyRequest

VerifyRequest is one clean exit's work to verify.

type VerifyResult

type VerifyResult = contract.VerifyResult

VerifyResult is the verdict on one attempt's work.

type WorktreeManager

type WorktreeManager interface {
	// Create branches taskID's worktree from baseBranch and merges in the
	// branches of deps the base does not contain yet (#322). setupEnv is
	// added to dispatch.worktree_setup's environment: the task's compose
	// project and slot (#343), so a setup that starts containers starts the
	// task's own.
	Create(ctx context.Context, taskID, baseBranch string, setupEnv []string, deps ...string) (string, error)
	CommitPending(ctx context.Context, taskID string) error
	Push(ctx context.Context, taskID string) error
	Remove(ctx context.Context, taskID string) error
	Recreate(ctx context.Context, taskID string) (string, error)
	// MergeBase merges the base into taskID's worktree, leaving a conflict
	// in progress for the agent (#438).
	MergeBase(ctx context.Context, taskID, baseBranch string) (worktree.MergeResult, error)
	// LandLocally squash-merges the task's branch into the base, here, with
	// nothing pushed (vcs.provider: local, #455).
	LandLocally(ctx context.Context, taskID, baseBranch, message string) (worktree.Landing, error)
	RemoveAll(ctx context.Context) error
	// BranchName is what a PR is opened from.
	BranchName(taskID string) string
	// ChangedFiles lists the files the task's own work changed since Create,
	// leaving out what the dependency merges brought in.
	ChangedFiles(ctx context.Context, taskID string) ([]string, error)
	// Diff is the same work as a patch, for the pre-PR guard (#484).
	Diff(ctx context.Context, taskID string) (string, error)
	// BranchConflicts names the files on which the two tasks' branches
	// conflict with each other (#482).
	BranchConflicts(ctx context.Context, taskID, otherID string) ([]string, error)
}

WorktreeManager is everything the engine asks of internal/worktree: the dispatch side creates one per task, the reap side commits, pushes and removes it, the CI poller brings it back, and the drain cleans up.

An interface rather than *worktree.Manager directly so the loop is testable without git — the ordering it has to honour is a contract the tests assert, and asserting it against real `git worktree add` would make them slow and dependent on a repo shape.

func NewWorktreeManager

func NewWorktreeManager(m *worktree.Manager) WorktreeManager

NewWorktreeManager adapts a worktree.Manager for the engine.

Jump to

Keyboard shortcuts

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