run

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 35 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 run implements the run lifecycle: start a harness in a tmux window on a workspace, follow it through normalized hook events, and end it with done, fail, stop or a crash. Every state change is a CAS update plus an events row in one transaction; task status follows the run (see docs/ADAPTERS.md, "State machine").

Index

Constants

View Source
const (
	CallerHuman       = "human"
	CallerCoordinator = "coordinator"
	CallerChild       = "child"
)

Push callers (PushInput.Caller).

View Source
const (
	PrimeChild       = "child"
	PrimeReview      = "review"
	PrimeCoordinator = "coordinator"
	PrimeProject     = "project" // outside a run, inside a registered project
	PrimeNone        = "none"    // outside a run and any project
)

Prime kinds: who `otag prime` talks to.

View Source
const (
	Accept = "accept"
	Reject = "reject"
)

Review verdicts (reviews.verdict).

View Source
const (
	Queued   = "queued"   // row created, nothing launched yet
	Starting = "starting" // pane launched, no session event yet
	Idle     = "idle"     // harness alive, turn finished, waiting for input
	Running  = "running"  // turn in progress
	Waiting  = "waiting"  // blocked on a question or permission decision
	Parked   = "parked"   // session closed on purpose, resumable (phase 4)
	Stopping = "stopping" // `otag run stop` in progress
	Ended    = "ended"    // see ended_reason
)

Run statuses.

View Source
const (
	ReasonDone         = "done"          // child called `otag done`
	ReasonFailed       = "failed"        // child called `otag fail`
	ReasonStopped      = "stopped"       // `otag run stop` on a live run
	ReasonCrashed      = "crashed"       // pane/process died without done/fail (found by stop or liveness)
	ReasonExited       = "exited"        // harness reported session_end without done/fail
	ReasonLaunchFailed = "launch_failed" // workspace, adapter or tmux failed during start, or the harness died before its first event
	ReasonStalled      = "stalled"       // daemon: running with no event for too long
	ReasonQuota        = "quota"         // a turn failed on a rate/usage limit
	ReasonSuperseded   = "superseded"    // migration v3: a second active run of a task
)

Ended reasons.

View Source
const (
	CauseHarness   = "harness"   // adapter, harness server/sidecar, or the harness died during startup
	CauseWorkspace = "workspace" // git worktree
	CauseTmux      = "tmux"
	// CauseInterrupted: the launching process (CLI or daemon) died before the pane was
	// recorded; the daemon ends such runs after its launch_timeout.
	CauseInterrupted = "interrupted"
)

Launch failure causes, recorded as data.cause on the run.status event that ends a launch_failed run. Only CauseHarness makes the daemon fall back to another profile.

View Source
const CleanupRetry = 30 * time.Second

CleanupRetry spaces the daemon's attempts at a cleanup that failed (runs.cleanup_after).

View Source
const DefaultCooldown = 30 * time.Minute

DefaultCooldown is how long an account (Claude, Codex) or a profile (other harnesses) rests after a turn failed on a rate limit whose reset time is unknown.

View Source
const DefaultQuotaThreshold = 90.0

DefaultQuotaThreshold is the used_percent at or above which a quota window makes a profile unavailable.

View Source
const DeliverTimeout = 20 * time.Second

DeliverTimeout bounds one adapter delivery call.

View Source
const InboxDir = "inbox"

InboxDir is the run dir's delivery inbox (the Claude mod's, see the claude adapter): files an injected attempt left for an in-session reader.

View Source
const ReasonParked = "parked"

ReasonParked ends a run that was parked while its task waits for an answer (`otag ask --park`, `otag run stop --park`, or the daemon's park_after). The task stays waiting; the answer resumes the harness session in a new run (Resume).

View Source
const StopBlockLimit = 3

StopBlockLimit caps consecutive Stop blocks in one turn (since its prompt).

View Source
const TokenEnv = "OTAG_RUN_TOKEN"

TokenEnv carries a run's secret token in its environment. The run row keeps only its hash; `otag event` and the child commands present the token, so a hook or a command that names another run (a confused child's `otag --run other done`) is refused. It is a speed bump for accidents, not a security boundary: the child can read the database file. A later broker can authenticate runs by the same token.

Variables

View Source
var ChildCommands = []Command{
	{"otag task me", "show your task, workspace and rules again"},
	{`otag done "summary"`, "finish: commit first; records the summary and HEAD commit, task goes to review/done"},
	{`otag fail "reason"`, "give up: the task goes back to the queue for another run"},
	{`otag ask "question" [--park]`, "ask the coordinator, then end your turn; the answer is your next message " +
		"(--park: otag closes the session and resumes it with the answer)"},
}

ChildCommands are the commands a child agent is told about.

View Source
var CoordinatorHarnesses = []string{"claude"}

CoordinatorHarnesses are the harnesses a coordinator may run on (v1: Claude only).

View Source
var ErrChanged = apperr.Retryable(apperr.Conflict, "run changed since it was checked; not stopped")

ErrChanged means StopOptions.Expect no longer held: nothing was stopped.

Statuses lists every run status.

Functions

func CheckLive

func CheckLive(ctx context.Context, tc *tmux.Client, runs []*Run)

CheckLive fills Live for every run that has a pane, with one tmux call, and AuxDown for a live run whose main pane is alive but one of its server or sidecar windows is not (exited or gone; a check that cannot tell is not "down").

func CheckToken

func CheckToken(ctx context.Context, q db.Querier, runID, token string) error

CheckToken verifies that token belongs to run runID. A run created before tokens (no hash) accepts any caller.

func Details

func Details(ctx context.Context, q db.Querier, r *Run, n int) error

Details fills usage totals, outputs and the last n events of r.

func Ingest

func Ingest(ctx context.Context, tx *sql.Tx, h Hook) (int64, error)

Ingest applies normalized events to the run inside tx. Each event is recorded as hook.<type> with dedupe key EventID[#i]; a duplicate is skipped entirely. It returns the id of the first new events row (0 if none).

func LiveCoordinator

func LiveCoordinator(ctx context.Context, q db.Querier, projectID int64) (string, error)

LiveCoordinator returns the project's coordinator run that has not ended ("" when there is none).

func NotifyDone

func NotifyDone(ctx context.Context, tx *sql.Tx, taskID string, a Actor) error

NotifyDone tells the project's coordinator (the human while none is live) that task taskID is done and ready to deliver: an info message with its branch, the commits since its base and its run's summary. It runs in the caller's transaction, the one that moved the task to done, and sends at most one message per time the task is done (client_msg_id done:<task>, then done:<task>:<n> for the n-th done after a reopen). A review task gets none: the task it reviews is the one to deliver.

func PendingCleanups

func PendingCleanups(ctx context.Context, q db.Querier, now time.Time, limit int) ([]string, error)

PendingCleanups lists ended runs whose cleanup has not been confirmed and is due at now (a failed one waits until runs.cleanup_after), the longest waiting first, so runs that keep failing never hold back the others.

func ProfileAvailable

func ProfileAvailable(ctx context.Context, q db.Querier, profileID int64) (ok bool, reason string)

ProfileAvailable reports whether new runs may use the profile now, with the default policy. reason explains a false.

func ReviewRules

func ReviewRules(rules []string, reviewOf string) []string

ReviewRules turns a child's rules (Rules) into a reviewer's: the last rule, which tells a child to commit and finish with otag done, becomes the review verdict.

func Rules

func Rules(mode, path, branch string, deny []string) []string

Rules returns the rules a child must follow in workspace ws.

func SessionName

func SessionName(project string) string

SessionName is the tmux session of a project.

func SetCooldown

func SetCooldown(ctx context.Context, q db.Querier, accountID, profileID int64, until time.Time, reason string) error

SetCooldown makes the account (when accountID != 0) and the profile (when profileID != 0) unavailable until `until`. An existing later cooldown is kept: cooldowns only grow. It also records reason as the last error. Quota collectors use the same function (quota.SetCooldown).

func StopTaskRun

func StopTaskRun(ctx context.Context, tx *sql.Tx, taskID, reason string, a Actor) (string, error)

StopTaskRun is the run side of cancelling or blocking a task (`otag task cancel`, `otag task block`), called inside the caller's transaction that changes the task: the task's active run, if any, moves to stopping with the intent to end as stopped, so the task change and the stop commit together. It returns that run's id ("" when the task has no active run). The caller then finishes the stop with StopWith (Expect Status stopping); if it dies first, the daemon does (ResumeStop). Meanwhile the run's `otag done` is refused, and when the run ends it leaves the task alone: the task is no longer in progress.

A cancelled task's open ask is closed too (its parked run, if any, has no live run left to stop).

func SweepInboxes

func SweepInboxes(ctx context.Context, q db.Querier, getenv func(string) string, now time.Time, settle time.Duration) error

SweepInboxes drops the inbox of runs that ended (cleanup confirmed) between an hour ago and settle ago: a Claude mod still alive for a moment after its own `otag done` rewrites its ready file after the cleanup removed the inbox.

Types

type Actor

type Actor struct {
	Name   string // user:<name> | run:<id> | daemon
	Source string // events.source: cli | hook:<harness> | daemon
}

Actor is who changes a run; recorded on events.

type AuxDown

type AuxDown struct {
	Role string        `json:"role"`
	Name string        `json:"name"`
	Live tmux.Liveness `json:"live"`
}

AuxDown is a dead server or sidecar window of a run.

type AuxPane

type AuxPane struct {
	Role string `json:"role"` // server | sidecar
	Name string `json:"name"`
	Pane string `json:"pane"`
	PID  int    `json:"pid"`
	// Birth is the start time of PID (proc.TimeFormat), "" when unknown; with PID it
	// identifies the process even after its window is gone.
	Birth string `json:"birth,omitempty"`
}

AuxPane is a server or sidecar window started for a run.

type Availability

type Availability struct {
	QuotaThreshold float64          // used_percent that blocks; default DefaultQuotaThreshold
	SnapshotMaxAge time.Duration    // a snapshot without resets_at older than this is ignored; default 6h
	Now            func() time.Time // default time.Now
}

Availability decides whether a profile may take a new run. The zero value uses the defaults.

func (Availability) Check

func (av Availability) Check(ctx context.Context, q db.Querier, profileID int64) (bool, string)

Check reports whether new runs may use the profile now. It is unavailable when:

  • the profile or its account is retired (or unknown);
  • profile_state.cooldown_until or account_state.cooldown_until is in the future;
  • the latest quota_snapshots row of some (source, quota_window) of its account, account-wide (profile_id NULL) or for this profile, has used_percent >= the threshold and has not reset yet (resets_at in the future, or no resets_at and observed within SnapshotMaxAge).

A database error counts as unavailable (the reason says why).

type BranchState

type BranchState struct {
	Task     string `json:"task"`
	Branch   string `json:"branch"`
	Exists   bool   `json:"exists"`
	Unmerged *int   `json:"unmerged"` // commits the target branch does not contain (nil = unknown)
	Deleted  bool   `json:"deleted"`
}

BranchState is a task branch after DeliverTask.

type Command

type Command struct {
	Cmd string `json:"cmd"`
	Use string `json:"use"`
}

Command is a otag command a child may use.

type CoordInput

type CoordInput struct {
	Project string
	Profile string // "" = the project's coordinator_profile, else its default_profile
}

CoordInput selects the coordinator to start.

type DeliverInput

type DeliverInput struct {
	Task string
	Note string // kept as the status reason and on the task.delivered event
	// DeleteBranch deletes the task's branch when the default branch contains it
	// (`git branch -d` semantics); an unmerged branch is kept with a warning, unless
	// Force (`git branch -D`: a squash merge never contains the branch).
	DeleteBranch bool
	// Force removes worktrees even with uncommitted changes (they are lost) and, with
	// DeleteBranch, deletes an unmerged branch.
	Force bool
}

DeliverInput is `otag task deliver`.

type DeliverResult

type DeliverResult struct {
	Task        string `json:"task"`
	TaskStatus  string `json:"task_status"`
	DeliveredAt string `json:"delivered_at"`
	// Delivered: this call moved the task from done (false when it was delivered before
	// and the call only finished the cleanup).
	Delivered bool `json:"delivered"`
	// ReviewTasks are the task's done review tasks, delivered (and cleaned up) with it.
	ReviewTasks []string          `json:"review_tasks"`
	Target      string            `json:"target_branch"` // the default branch merges are checked against ("" = none)
	Worktrees   []WorktreeCleanup `json:"worktrees"`
	Branches    []BranchState     `json:"branches"`
	Warnings    []string          `json:"warnings"`
}

DeliverResult reports `otag task deliver`.

type Dispatcher

type Dispatcher struct {
	DB       *db.DB
	Adapters *adapter.Registry
	Getenv   func(string) string
	Actor    msg.Actor
	// Timeout bounds one adapter call (0 = DeliverTimeout). The call is never cut
	// short by a caller's budget: an interrupted send has an unknown outcome.
	Timeout time.Duration
}

Dispatcher delivers queued messages into live sessions over injected channels (docs/MESSAGES.md): a Claude session's mod ($.prompt.submit), Codex's control socket (turn/start, turn/steer) and OpenCode's prompt API. It implements msg.Dispatcher for the CLI's synchronous attempt; the daemon calls Dispatch.

One attempt is: Claim (a transaction), the adapter call outside any transaction, Settle (another transaction). msg.Claim keeps one injected attempt in flight per run. Nothing is typed into a pane: a run whose harness has no injected channel in its current state keeps its messages queued for its hooks or `otag inbox`.

func (*Dispatcher) Attempt

func (d *Dispatcher) Attempt(ctx context.Context, deliveryID int64) msg.AttemptResult

Attempt implements msg.Dispatcher: one attempt for the run delivery deliveryID is bound to (or, when that run has gone, its task's current run). The attempt carries every due delivery of that run, deliveryID among them when it is due.

func (*Dispatcher) AttemptRun

func (d *Dispatcher) AttemptRun(ctx context.Context, runID string) []msg.AttemptResult

AttemptRun implements msg.RunDispatcher: one Dispatch into run runID, reported per delivery: those the attempt carried, else the run's queued ones with the reason nothing was sent.

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(ctx context.Context, runID string) RunAttempt

Dispatch makes one injected delivery attempt into run runID: it claims the run's due queued deliveries (when the run can take them now), sends them in one text and settles the attempt.

func (*Dispatcher) Eligible

func (d *Dispatcher) Eligible(ctx context.Context, runID string) bool

Eligible reports whether run runID could take an injected delivery now (see injectPlan): the daemon leaves the others out of msg.DueRuns, so runs that only their hooks or `otag inbox` serve never crowd out those it can serve.

type DoneResult

type DoneResult struct {
	Run          string   `json:"run"`
	Task         string   `json:"task"`
	TaskStatus   string   `json:"task_status"`
	Summary      string   `json:"summary"`
	Commit       string   `json:"commit,omitempty"`
	CommitsAhead int      `json:"commits_ahead"`
	Dirty        bool     `json:"dirty"`                 // uncommitted changes were left in the workspace
	ReviewTask   string   `json:"review_task,omitempty"` // created when the project has a review profile
	Closed       []string `json:"closed_panes"`          // windows killed after the run ended
	// CleanupError: something of the run could not be killed or verified gone; the
	// daemon retries (runs.cleanup_pending).
	CleanupError string `json:"cleanup_error,omitempty"`
}

DoneResult reports `otag done`.

type EventRow

type EventRow struct {
	ID         int64           `json:"id"`
	Source     string          `json:"source"`
	Kind       string          `json:"kind"`
	FromStatus string          `json:"from_status,omitempty"`
	ToStatus   string          `json:"to_status,omitempty"`
	Data       json.RawMessage `json:"data"`
	CreatedAt  string          `json:"created_at"`
}

EventRow is an events row of a run.

type Expect

type Expect struct {
	Status      string
	HeartbeatAt string // runs.heartbeat_at as read ("" = none)
	NoPane      bool   // no main pane was recorded (a launch that may still record one)
}

Expect is the state a caller of StopWith saw.

type Filter

type Filter struct {
	ProjectID int64 // 0 = all
	TaskID    string
	Active    bool // not ended
	Limit     int  // 0 = 50
}

Filter selects runs for List.

type Hook

type Hook struct {
	Harness string
	Kind    string
	RunID   string
	EventID string // dedupe base; "" = no dedupe
	Events  []adapter.Event
}

Hook is one hook invocation resolved to a run, ready to apply.

type HookRequest

type HookRequest struct {
	Harness string
	Kind    string
	RunID   string // from --run / OTAG_RUN_ID; "" = resolve through the payload's session id
	EventID string // from --event-id; overrides the adapter's EventID
	Payload []byte
	Getenv  func(string) string
	// Tmux, when set, lets a hook that ends a live run (session_end: the harness exited
	// without done/fail) close the run's other windows, as done/fail/stop do: a server
	// or sidecar must not keep working in a worktree whose task is back in the queue.
	Tmux *tmux.Client
	// RawPayloads stores the payload itself (redacted) in raw_hook_payloads, for
	// debugging ([daemon] raw_payloads); otherwise only a compact allowlisted extract.
	RawPayloads bool
}

HookRequest is one `otag event <harness> <kind>` invocation.

type HookResponse

type HookResponse struct {
	Output  []byte // printed on stdout
	RunID   string // resolved run ("" = unknown)
	EventID int64  // first new events row (0: unknown run, duplicate or nothing to record)
	// Delivered, when set, settles the messages Output carries; the caller runs it
	// right after printing Output (hook context counts as delivered once printed).
	Delivered func(ctx context.Context) error
	// MsgErr is a messaging failure (proof, claim) for the log; the hook went on
	// without messaging.
	MsgErr error
}

HookResponse is what the bridge did.

func HandleHook

func HandleHook(ctx context.Context, d *db.DB, reg *adapter.Registry, req HookRequest) (resp HookResponse, err error)

HandleHook stores the payload and applies the adapter's events in one transaction.

Guarded kinds (adapter.Guarder: pre-tool and permission hooks) fail closed: the decision is made before, and independently of, the write, so a failed transaction never drops a deny; and when the run's policy cannot be applied (no database, a schema newer than this binary, an unknown or ended run, an unreadable payload, a token of another run) the hook answers the adapter's DenyOutput.

Every other kind keeps the harness-safe no-op on failure: the adapter's output (additionalContext, ...) is returned only when the run is known and everything was recorded. err reports the failure for logging; the hook itself must still succeed.

type Manager

type Manager struct {
	DB       *db.DB
	Adapters *adapter.Registry
	Tmux     *tmux.Client
	Getenv   func(string) string
	Actor    Actor
}

Manager starts and stops runs. Getenv provides the otag environment (paths and the OTAG_* variables passed on to children).

func (*Manager) Cleanup

func (m *Manager) Cleanup(ctx context.Context, runID string) ([]string, error)

Cleanup kills what is left of a run: every recorded window and every process of it (see reap). For an ended run it then settles the cleanup obligation: when nothing is left, runs.cleanup_pending is cleared; a failure is kept in runs.cleanup_error for the next try (the daemon's, or the next start in the workspace). It returns the panes whose windows it killed. When called from inside the run's pane (`otag done` run by the agent) the caller dies with its pane; the daemon then confirms the cleanup.

func (*Manager) DeliverTask

func (m *Manager) DeliverTask(ctx context.Context, in DeliverInput) (*DeliverResult, error)

DeliverTask delivers a done task: in one transaction it moves the task (and its done review tasks) done -> delivered with delivered_at and a task.delivered event, then removes their worktrees (`git worktree remove`) and records them cleaned in workspaces. Branches stay; with DeleteBranch a branch the default branch contains is deleted, an unmerged one is kept with a warning. Delivering an unmerged branch is a warning, not an error.

It refuses (changing nothing) while a run of the task or of a review task has not ended, while any run that has not ended (any project, any role) works in one of their worktrees, when a worktree has uncommitted changes unless Force, and when what is left of their ended runs cannot be cleaned up (or tmux cannot be asked). A worktree is removed only inside otag's worktree root of the project and only while git lists it on the task's branch (workspace.Remove); a path that is another worktree now is left alone and only recorded cleaned. Called again on a delivered task it finishes what is left (worktrees, branches): a removal that failed after the commit returns the result with a retryable error.

func (*Manager) Done

func (m *Manager) Done(ctx context.Context, runID, summary string) (*DoneResult, error)

Done finishes a live run: records the summary and the workspace HEAD, ends the run (done), moves the task to review (creating a linked review task) when the project has a review profile, else to done, and closes the run's windows. Transcripts stay with the harness, so the session can be resumed later. A review run's task goes to done: a review is never reviewed again.

func (*Manager) Fail

func (m *Manager) Fail(ctx context.Context, runID, reason string) (*Run, error)

Fail ends a run as failed, puts its task back in the queue and closes its windows, so nothing keeps writing to the worktree the next attempt will use.

func (*Manager) KillOrphan

func (m *Manager) KillOrphan(ctx context.Context, o Orphan) error

KillOrphan kills an orphan window (if it still runs o.PID and is still tagged for o.Run and this database) and every process of it (proc.Family).

func (*Manager) Orphans

func (m *Manager) Orphans(ctx context.Context) ([]Orphan, error)

Orphans lists the orphan windows of this database. A window whose run is still active is never one, recorded or not (its launch may still record it).

func (*Manager) Park

func (m *Manager) Park(ctx context.Context, ref string, o ParkOptions) (*StopResult, error)

Park ends a child or review run whose task waits for the answer to the run's open ask: the run's windows are closed through the normal stop (cleanup included), the run ends with ended_reason parked, and the task stays waiting with the ask open. A coordinator is never parked. The guard is checked again in the transaction that moves the run to stopping: an answered ask or a task that moved on stops nothing.

func (*Manager) PushTask added in v0.1.2

func (m *Manager) PushTask(ctx context.Context, in PushInput) (*PushResult, error)

PushTask pushes the task's branch (its stored branch) to the project's remote: `git push <remote> <sha>:refs/heads/<branch>`, the same branch name on the remote, never another ref and no tags. Who may push is the project's push setting: none (nobody), coordinator (the project's coordinator and the human; default) or child (also the task's own child run). With Force it is --force-with-lease against the commit otag recorded at its last push of that branch to that remote; when otag never pushed it, only a remote without the branch is accepted. Uncommitted changes in the task's worktree are not pushed (a warning says so). The push is recorded on the task (remote, branch, commit, time) with a task.pushed event.

func (*Manager) Quiesce

func (m *Manager) Quiesce(ctx context.Context, runID string) error

Quiesce makes sure nothing of a run is left before another run uses its worktree. It is Cleanup with an error whenever something could not be killed or verified gone within ctx (the daemon gives it 15 s).

func (*Manager) Reopen added in v0.1.2

func (m *Manager) Reopen(ctx context.Context, in ReopenInput) (*ReopenResult, error)

Reopen moves a done task back to ready in one transaction (task.Reopen): the same worktree and branch get the next run, whose prior-attempt summary carries the reason. The task's accepted reviews become stale (they no longer satisfy the review gate, and a new review task is created when the task is done again), and its done notice is retracted: queued deliveries expire and its notifications are acknowledged. A delivered task, a review task and a task with a live run are refused.

func (*Manager) Resume

func (m *Manager) Resume(ctx context.Context, ref string) (*StartResult, error)

Resume continues a parked task (a task id, or a run id of it) in a new run on the same harness session: same profile revision, same workspace path and an available account, else ResumeBlocked. The task goes waiting -> claimed (task.ClaimWaiting), the new run claims the answer as its first prompt (launch_prompt), and the launch moves the task to running; without the answer nothing is created.

func (*Manager) ResumeStop

func (m *Manager) ResumeStop(ctx context.Context, runID string) (*StopResult, error)

ResumeStop finishes a run left in stopping (the process that stopped it died, or killing its windows failed) with the intent recorded on its run.status → stopping event: the same reason, end reason and cause.

func (*Manager) Review

func (m *Manager) Review(ctx context.Context, in ReviewInput) (*ReviewResult, error)

Review records a verdict on a task in review, in one transaction: a reviews row linked to the reviewed task's latest done run (and so to its profile), and the task to done (accept; ready to deliver, so the coordinator is told: NotifyDone) or back to ready (reject, with the reason; its next run sees it in the prior-attempt summary). Called from a review run, that run also finishes (done, through the same completion as `otag done`, never creating another review). Called by the human or the coordinator, review tasks of the task that have not started are cancelled; one with a live run is a CONFLICT (it is reviewing).

func (*Manager) Start

func (m *Manager) Start(ctx context.Context, in StartInput) (*StartResult, error)

Start claims the task (if ready), creates the run, prepares the workspace, launches the harness in a tmux window and returns once the pane runs (and, for adapters with a trust dialog, once the first hook event arrived or the startup timeout passed). Messages queued for the task go into the first prompt.

func (*Manager) StartCoordinator

func (m *Manager) StartCoordinator(ctx context.Context, in CoordInput) (*StartResult, error)

StartCoordinator starts the project's coordinator: a task-less run (role coordinator) whose workspace is the project checkout itself. A project has at most one coordinator that has not ended (CONFLICT; also a unique index). While it runs, the checkout is its own: same-mode children are refused (sameWorkspaceFree), and it cannot start while one works there. Messages to coord that wait unrouted go into its first prompt.

func (*Manager) Stop

func (m *Manager) Stop(ctx context.Context, ref, reason string) (*StopResult, error)

Stop kills the run's windows. A live run ends as stopped (crashed when its pane was already dead) and its task goes back to ready; on an ended run it only cleans up panes.

func (*Manager) StopWith

func (m *Manager) StopWith(ctx context.Context, ref string, o StopOptions) (*StopResult, error)

StopWith is Stop with options: the adapter's Stopper gets a chance to exit gracefully, then every window of the run is killed and a live run ends.

type Me

type Me struct {
	Task      *task.Task `json:"task"`
	Run       *Run       `json:"run"`
	Rules     []string   `json:"rules"`
	Commands  []Command  `json:"commands"`
	Workspace *Workspace `json:"workspace,omitempty"`
}

Me is what a child sees with `otag task me`.

func TaskMe

func TaskMe(ctx context.Context, q db.Querier, runID string) (*Me, error)

TaskMe returns the task, workspace and rules of a run.

type Orphan

type Orphan struct {
	Pane      string `json:"pane"`
	PID       int    `json:"pid"`
	Run       string `json:"run"`
	RunStatus string `json:"run_status"` // ended, or "" when the run does not exist
}

Orphan is a window tagged for a run of this database (tmux options @otag_run and @otag_db) whose run has ended or does not exist: a launch that died between creating the window and recording it, or a cleanup that never happened.

type Output

type Output struct {
	Kind      string          `json:"kind"`
	Value     string          `json:"value"`
	Data      json.RawMessage `json:"data"`
	CreatedAt string          `json:"created_at"`
}

Output is a run_outputs row.

type ParkOptions

type ParkOptions struct {
	Reason string  // default "parked: waiting for an answer to #<ask>"
	Expect *Expect // see StopOptions.Expect (the daemon parks an idle run it saw)
	// SkipDispatched refuses to park a run with a dispatched delivery (it is working on a
	// message, whatever its status says); checked in the same transaction as the stop.
	SkipDispatched bool
}

ParkOptions tune Park.

type PrimeInfo

type PrimeInfo struct {
	Kind     string     `json:"kind"`
	Run      *Run       `json:"run,omitempty"`
	Task     *task.Task `json:"task,omitempty"`
	ReviewOf *task.Task `json:"review_of,omitempty"`
	Rules    []string   `json:"rules,omitempty"`
	Commands []Command  `json:"commands,omitempty"`
	// Rejected is the last review rejection of the task (a retry after a review).
	Rejected string `json:"rejected,omitempty"`
	// Reopened is why the task was reopened before this run (`otag task reopen`).
	Reopened string     `json:"reopened,omitempty"`
	Messages []PrimeMsg `json:"messages"`
	// Project summary (coordinator, project): counts by status, live runs, needs.
	Project  string         `json:"project,omitempty"`
	Counts   map[string]int `json:"counts,omitempty"`
	Live     []PrimeRun     `json:"live_runs,omitempty"`
	Needs    int            `json:"needs,omitempty"`
	Projects []string       `json:"projects,omitempty"` // PrimeNone: registered projects
}

PrimeInfo is the data behind `otag prime`.

func BuildPrime

func BuildPrime(ctx context.Context, q db.Querier, in PrimeInput) (*PrimeInfo, error)

BuildPrime gathers the orientation for in. The caller has verified the run token.

func (*PrimeInfo) Text

func (p *PrimeInfo) Text() string

Text renders the orientation (aim: under 60 lines).

type PrimeInput

type PrimeInput struct {
	RunID     string
	ProjectID int64
}

PrimeInput selects the orientation: a verified run (RunID), else the project found from the working directory (ProjectID, 0 = none).

type PrimeMsg

type PrimeMsg struct {
	ID       int64  `json:"id"`
	Headline string `json:"headline"`
}

PrimeMsg is a pending message: id and headline only (prime never marks it read).

type PrimeRun

type PrimeRun struct {
	ID     string `json:"id"`
	Task   string `json:"task,omitempty"`
	Status string `json:"status"`
}

PrimeRun is a live run in a project summary.

type PushInput added in v0.1.2

type PushInput struct {
	Task  string
	Force bool // --force-with-lease against the last push otag recorded
	// Caller is who pushes (CallerHuman, CallerCoordinator, CallerChild); the CLI
	// verified a run caller's token. CallerRun is the caller's run (coordinator or
	// child).
	Caller    string
	CallerRun *Run
}

PushInput is `otag task push`.

type PushResult added in v0.1.2

type PushResult struct {
	Task        string   `json:"task"`
	Remote      string   `json:"remote"`
	Branch      string   `json:"branch"`
	SHA         string   `json:"sha"`
	PreviousSHA string   `json:"previous_sha,omitempty"` // the last push otag recorded, if any
	Forced      bool     `json:"forced"`
	At          string   `json:"at"`
	Warnings    []string `json:"warnings"`
	Output      string   `json:"output"` // git's porcelain report
}

PushResult reports `otag task push`.

type ReopenInput added in v0.1.2

type ReopenInput struct {
	Task          string
	Reason        string
	ExpectVersion int64 // 0 = no check
}

ReopenInput is `otag task reopen`.

type ReopenResult added in v0.1.2

type ReopenResult struct {
	Task *task.Task `json:"task"`
	// StaleReviews are the accepted reviews that no longer count: the task is reviewed
	// again when it is done again (when review applies).
	StaleReviews int `json:"stale_reviews"`
	// RetractedNotices counts the deliveries of its done notice that were still queued
	// (they expire: the task is not ready to deliver any more).
	RetractedNotices int `json:"retracted_notices"`
}

ReopenResult reports `otag task reopen`.

func ReopenTask added in v0.1.2

func ReopenTask(ctx context.Context, tx *sql.Tx, in ReopenInput, a Actor) (*ReopenResult, error)

ReopenTask is Reopen inside the caller's write transaction.

type Resumable

type Resumable struct {
	TaskID    string
	RunID     string // the parked run
	ProjectID int64
}

Resumable is a parked task whose answer is queued (the daemon resumes these).

func ParkedWithAnswer

func ParkedWithAnswer(ctx context.Context, q db.Querier, limit int, skip ...string) ([]Resumable, error)

ParkedWithAnswer lists parked tasks (waiting, their current run ended parked) whose answer is queued, oldest first.

type ResumeBlocked

type ResumeBlocked struct {
	Task   string
	Reason string
	Retry  bool // it may clear by itself (the account is cooling down)
}

ResumeBlocked means a parked task cannot resume (now). It leaves the task waiting: `otag needs` lists its answer, and nothing starts a fresh run in its place.

func (*ResumeBlocked) Error

func (e *ResumeBlocked) Error() string

func (*ResumeBlocked) Unwrap

func (e *ResumeBlocked) Unwrap() error

Unwrap gives the CLI its stable code.

type ReviewInput

type ReviewInput struct {
	Task    string // the reviewed task, or a review task (then the task it reviews)
	Verdict string // Accept | Reject
	Reason  string // required for Reject
	RunID   string // the calling run; "" = the human. A review run finishes with its verdict.
}

ReviewInput is `otag review`.

type ReviewResult

type ReviewResult struct {
	Review      int64       `json:"review"` // reviews.id
	Task        string      `json:"task"`   // the reviewed task
	TaskStatus  string      `json:"task_status"`
	ReviewedRun string      `json:"reviewed_run,omitempty"`
	Profile     string      `json:"profile,omitempty"` // the reviewed run's profile
	Verdict     string      `json:"verdict"`
	Reason      string      `json:"reason"`
	Cancelled   []string    `json:"cancelled_review_tasks,omitempty"` // review tasks a human review made moot
	Done        *DoneResult `json:"done,omitempty"`                   // the review run, finished with its verdict
}

ReviewResult reports `otag review`.

type Run

type Run struct {
	ID              string         `json:"id"`
	Project         string         `json:"project"`
	ProjectID       int64          `json:"-"`
	TaskID          string         `json:"task_id"`
	TaskStatus      string         `json:"task_status,omitempty"`
	TaskTitle       string         `json:"task_title,omitempty"`
	Role            string         `json:"role"`
	Attempt         int            `json:"attempt"`
	RetryOf         string         `json:"retry_of,omitempty"`
	FallbackOrigin  string         `json:"fallback_origin,omitempty"` // profile whose fallback list started this run (daemon)
	Profile         string         `json:"profile"`
	ProfileID       int64          `json:"-"`
	RevisionID      int64          `json:"profile_revision_id"`
	Account         string         `json:"account"`
	Harness         string         `json:"harness"`
	Model           string         `json:"model"`
	Effort          string         `json:"effort"`
	Guard           string         `json:"guard"` // the guard level the run started with (light|strict)
	Status          string         `json:"status"`
	EndedReason     string         `json:"ended_reason,omitempty"`
	Error           string         `json:"error,omitempty"`
	Version         int64          `json:"version"`
	QueuedAt        string         `json:"queued_at"`
	StartedAt       string         `json:"started_at,omitempty"`
	FirstActivityAt string         `json:"first_activity_at,omitempty"`
	LastProgressAt  string         `json:"last_progress_at,omitempty"`
	HeartbeatAt     string         `json:"heartbeat_at,omitempty"`
	EndedAt         string         `json:"ended_at,omitempty"`
	CleanupPending  bool           `json:"cleanup_pending,omitempty"` // ended, windows/processes not confirmed gone yet
	CleanupError    string         `json:"cleanup_error,omitempty"`   // the last failed cleanup
	Session         *Session       `json:"session,omitempty"`
	Workspace       *Workspace     `json:"workspace,omitempty"`
	Live            *tmux.Liveness `json:"live,omitempty"`
	Usage           *UsageTotal    `json:"usage,omitempty"`
	Outputs         []Output       `json:"outputs,omitempty"`
	Events          []EventRow     `json:"events,omitempty"`
	// AuxDown is the first server or sidecar window found dead while the main pane
	// lives (CheckLive).
	AuxDown *AuxDown `json:"aux_down,omitempty"`
}

Run is a run with its current session and workspace.

func Get

func Get(ctx context.Context, q db.Querier, id string) (*Run, error)

Get returns a run by id.

func List

func List(ctx context.Context, q db.Querier, f Filter) ([]Run, error)

List returns runs, newest first.

func Resolve

func Resolve(ctx context.Context, q db.Querier, ref string) (*Run, error)

Resolve accepts a run id or a task id (its current, else latest, run).

func (*Run) Dead

func (r *Run) Dead() bool

Dead reports a run that should be working but whose pane is not alive.

type RunAttempt

type RunAttempt struct {
	RunID      string  `json:"run"`
	Channel    string  `json:"channel,omitempty"`
	Nonce      string  `json:"nonce,omitempty"`
	Deliveries []int64 `json:"deliveries,omitempty"` // the deliveries the attempt carried
	// Result: skipped (nothing claimed), dispatched (sent, proof to come), delivered
	// (proven already), queued (definitely not sent; retried later or dead) or failed
	// (outcome unknown, or otag could not record the attempt).
	Result string `json:"result"`
	Reason string `json:"reason,omitempty"`
}

RunAttempt is the outcome of one Dispatch.

type Session

type Session struct {
	ID               int64     `json:"id"`
	HarnessSessionID string    `json:"harness_session_id,omitempty"`
	Status           string    `json:"status"`
	TmuxSession      string    `json:"tmux_session,omitempty"`
	TmuxWindow       string    `json:"tmux_window,omitempty"`
	TmuxPane         string    `json:"tmux_pane,omitempty"`
	PID              int       `json:"pid,omitempty"`
	PIDStartedAt     string    `json:"pid_started_at,omitempty"` // the process's birth (since v5)
	AuxPanes         []AuxPane `json:"aux_panes,omitempty"`
	ServerURL        string    `json:"server_url,omitempty"`
	TranscriptPath   string    `json:"transcript_path,omitempty"`
	StartedAt        string    `json:"started_at"`
	EndedAt          string    `json:"ended_at,omitempty"`
	EndReason        string    `json:"end_reason,omitempty"`
}

Session is the latest harness session of a run.

type StartInput

type StartInput struct {
	TaskID  string
	Profile string // "" = task profile, else project default
	// FallbackOrigin marks a run the daemon starts as a fallback: the profile whose
	// fallback list the chain walks (runs.fallback_origin_profile_id). 0 = a new chain.
	FallbackOrigin int64
	// Guard, when set, runs first inside the transaction that claims the task and
	// creates the run; an error aborts the start with nothing written. The daemon
	// checks that its fallback decision still holds there and records it, so the
	// decision and the run it started commit together.
	Guard func(tx *sql.Tx) error
	// contains filtered or unexported fields
}

StartInput selects what to start.

type StartResult

type StartResult struct {
	Run       *Run   `json:"run"`
	Trust     string `json:"trust,omitempty"`  // accepted | timeout | ""
	FirstSeen bool   `json:"first_event_seen"` // a hook event arrived before start returned
	Attach    string `json:"attach_command"`   // shell command to attach
	Warning   string `json:"warning,omitempty"`
	// Messages are the queued deliveries the first prompt carries (launch_prompt).
	Messages []int64 `json:"messages,omitempty"`
}

StartResult reports a started run.

type StopOptions

type StopOptions struct {
	Reason string // why; stored as runs.error and on the task
	// EndReason replaces the ended_reason of a live run (default: stopped, or crashed
	// when the pane was already dead), e.g. stalled for the daemon's watchdog.
	EndReason string
	Cause     string // data.cause on the ending run.status event (launch_failed causes)
	// Expect, when set, is a precondition checked inside the transaction that moves
	// the run to stopping: the run must still have this status and heartbeat. If a
	// hook changed it after the caller looked (a new event, waiting, ended), StopWith
	// changes nothing and returns ErrChanged. The daemon decides on a snapshot and
	// uses it so a run that just came back to life is never killed.
	Expect *Expect
	// Guard, when set, runs inside that same transaction after Expect: an error stops
	// nothing and is returned (Park checks the ask is still open there).
	Guard func(tx *sql.Tx) error
}

StopOptions tune StopWith.

type StopResult

type StopResult struct {
	Run    *Run          `json:"run"`
	Before tmux.Liveness `json:"before"` // pane state before stopping
	Killed []string      `json:"killed"` // panes whose windows were killed
	// CleanupError: a process of the run could not be killed or verified gone after
	// the run ended; the daemon retries (runs.cleanup_pending).
	CleanupError string `json:"cleanup_error,omitempty"`
}

StopResult reports `otag run stop`.

type UsageTotal

type UsageTotal struct {
	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"`
	CostUSD          *float64 `json:"cost_usd,omitempty"`
	Rows             int      `json:"rows"`
}

UsageTotal sums run_usage.

type Workspace

type Workspace struct {
	ID      int64  `json:"id"`
	Mode    string `json:"mode"`
	Path    string `json:"path"`
	Branch  string `json:"branch,omitempty"`
	BaseRef string `json:"base_ref,omitempty"`
	BaseSHA string `json:"base_sha,omitempty"`
	HeadSHA string `json:"head_sha,omitempty"`
	Status  string `json:"status"`
}

Workspace is the latest workspace row of a run.

type WorktreeCleanup

type WorktreeCleanup struct {
	Task   string `json:"task"`
	Path   string `json:"path"`
	Result string `json:"result"` // removed | gone (deleted before; pruned) | failed
	Error  string `json:"error,omitempty"`
}

WorktreeCleanup is one worktree DeliverTask removed (or tried to).

Jump to

Keyboard shortcuts

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