project

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: 24 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 project is what the CLI and the dashboard share about a project: tasks.json hydrated with the live status from the state backend, plus the per-task figures that can only be derived from the event log.

It exists because both consumers were about to answer the same question in two places. `tasks.json` carries a task's status as it was when the file was written; the database carries what it is now. Every view that ships task rows has to overlay the second on the first, and Python learned that the hard way — `_load_tasks_hydrated` was extracted in sprint F-8 (issue #72) after three endpoints shipped stale statuses from the file.

Open is the front ends' door to a project: its config, its database and its tasks, hydrated (#550).

Imports config, model, graph and state; imported by cli, dashboard and mcp. Nothing here knows about HTTP or about a terminal.

Index

Constants

View Source
const (
	QueueQueued  = state.QueueQueued
	QueueMerged  = state.QueueMerged
	QueueEjected = state.QueueEjected
)

Merge queue states.

View Source
const (
	// RadarPRConflictReason starts a ci_blocked reason when a PR conflicted
	// with its base and no retry was left (or retry.conflict is off).
	RadarPRConflictReason = "the PR conflicts with its base branch"
	// RadarLandConflictReason starts a fail reason when a task's local land
	// (vcs.provider: local) conflicted and no retry was left.
	RadarLandConflictReason = "the work conflicts with "
)

Engine reasons the report reads collisions from. Engine strings, repeated here because project cannot import engine; engine's tests check that its reasons still start with these.

View Source
const (
	RadarPRConflict        = "pr_conflict"         // ci_conflict_retry: the PR conflicted, sent to the agent
	RadarPRConflictBlocked = "pr_conflict_blocked" // ci_blocked: the PR conflicted, task blocked
	RadarLandConflict      = "land_conflict"       // a local land conflicted (retry or block)
	RadarBaseBroke         = "base_broke_verify"   // the base merged cleanly but broke the local verify
	RadarSemantic          = "semantic_collision"  // a block rule stopped the merge (#522)
)

Collision kinds, as RadarCollision.Kind.

View Source
const (
	FindingQueued    = state.FindingQueued
	FindingSent      = state.FindingSent
	FindingDismissed = state.FindingDismissed
)

A queued finding's status.

View Source
const (
	EventTaskAdded  = "task_added"
	EventTaskEdited = "task_edited"
)

The events a task edit is recorded as.

View Source
const CIFeedbackFile = ".orch-ci-feedback.md"

CIFeedbackFile is where the failing CI logs and the verify's findings are left for the agent, inside its worktree; it is never committed. The name is Python's, and a contract with whatever the agent is told to read.

View Source
const EventMergedLocally = "merged_locally"

EventMergedLocally is a task squash-merged into the base here, in place of a PR (vcs.provider: local, #455): by the run, or by the operator's Accept.

View Source
const EventOperatorStop = "operator_stop"

EventOperatorStop is the event a stop request is written as, and the event the run that acted on it writes back (with `stopped` in its extra).

View Source
const EventPRMerged = "pr_merged"

EventPRMerged is the event an accepted task's merge is written as: the engine's own name for a PR merged outside the run.

View Source
const HeldReason = "held by the operator"

HeldReason is the note on a task the operator stopped and held.

View Source
const OperatorAuthor = "operator"

OperatorAuthor is the author of everything the operator writes through Steer.

View Source
const RunLockFile = "run.lock"

RunLockFile is the file under a project's state directory that one `orch run` holds while it runs (engine.AcquireRunLock, #344).

Variables

View Source
var (
	// ErrTaskNotFound means the id has no runtime row in the project.
	ErrTaskNotFound = state.ErrTaskNotFound
	// ErrIllegalTransition means the move is not in the transition table.
	// The error's message names the legal destinations.
	ErrIllegalTransition = state.ErrIllegalTransition
)

The sentinels a front end tests a status write's error against. They are the backend's own values, as io/fs.ErrNotExist is os.ErrNotExist: so errors.Is matches every error that carries one, whichever path wrapped it — SetStatus, Steer, TaskEditor or the engine — and the message, which `orch task set` prints as is, stays the backend's.

View Source
var ErrInvalidEdit = errors.New("the edit leaves tasks.json invalid")

ErrInvalidEdit is an edit the DAG would not survive: a missing dependency, a cycle, a model with no route. Nothing is written.

View Source
var ErrNoPR = errors.New("the task has no PR to merge")

ErrNoPR is Accept's answer for a task with no PR to merge.

View Source
var ErrRunOwnsTask = errors.New("only orch run starts or finishes a running task")

ErrRunOwnsTask is a move only `orch run` makes: starting a task, or finishing one that is running. 409 on the dashboard.

Providers are the backends orch has an adapter for, the names SetProvider accepts.

Functions

func AnyDone added in v0.31.0

func AnyDone(ctx context.Context, backend StatusReader) (bool, error)

AnyDone says whether the database has at least one task done.

func BaseRef

func BaseRef(dir, base string) string

BaseRef is the ref a task's worktree starts from, as far as the local repository knows: origin/<base> when that remote-tracking branch exists, else the local <base>, else "". dir must be inside the repository.

func Definitions added in v0.31.0

func Definitions(tasksJSON string) (model.TasksFile, error)

Definitions reads tasks.json exactly as written: the DAG's shape, with the status and comments the file was last saved with — stale as soon as a run moves a task. It is for callers that want definitions only and no database near them (validate, doctor, the router, a rewrite of the file, Bootstrap's seed). Anything that shows or decides on a status reads Tasks or Load instead (review checklist rule 30).

It is the front ends' only way to read the file (#550, TestFrontEndsGoThroughProject).

func DispatchAlive added in v0.31.0

func DispatchAlive(d state.Dispatch) bool

DispatchAlive reports whether a dispatch row's process is still the dispatch: its PID is alive and, when the start time was recorded, started when the dispatch's did.

func ExistsAtRef

func ExistsAtRef(dir, ref, relPath string) bool

ExistsAtRef says relPath (relative to dir, slash separated) exists in ref.

func FinishedAt

func FinishedAt(ctx context.Context, backend StatusReader) (map[string]string, error)

FinishedAt maps each task id to when it first reached done, for the tasks that have. An id with no finish time is absent.

func FirstEventBackend added in v0.31.0

func FirstEventBackend(ctx context.Context, b Backend, eventType string) (backend string, ok bool, err error)

FirstEventBackend reports whether the project has any event of eventType and the backend of the earliest one — the onboarding milestones (#378). ok is false, with no error, for a backend that cannot answer it.

func HasAnchor

func HasAnchor(markdown, anchor string) bool

HasAnchor reports whether markdown has a heading for anchor.

Three spellings count, because three kinds of spec reach tasks.json: a heading that starts with the anchor as its own word (`### F11.1.T1 — Load the dataset`, which is what `orch atomize` writes specRefs from; the next character must not continue the id, so F1.1.T1 does not match F1.1.T10), a GitHub-style slug of the whole heading (`#load-the-dataset`), and an explicit `{#id}` or `<a id="...">`. Fenced code blocks are skipped: a spec showing the format in an example is not a spec that has the section.

func HumanHoursByTask

func HumanHoursByTask(events []state.Event) map[string]float64

HumanHoursByTask sums wall-clock hours per task from dispatch → terminal pairs. Retries stack: three attempts contribute three intervals.

When the terminal event records `duration_s`, that is preferred over the wall-clock delta — it excludes the time the task spent queued, which is the difference between "how long did this take" and "how long was it in the system". Zero or unparseable falls back to the delta.

A task with no closed interval is absent from the map rather than present with 0.0. The distinction is real: "never dispatched" and "took no time" are different facts, and a column that renders 0.0 for the first one is wrong.

func Hydrate

func Hydrate(ctx context.Context, backend StatusReader, tasks []model.Task) ([]model.Task, error)

Hydrate overlays the live status AND comments on tasks.json's rows.

One query, not one per task. The per-task form is a round trip each and answers the same question; on a project of any size it is the difference between a page that loads and one that does not.

Why comments and not only status

Since F-12 the comments a task accumulates live in `tasks_runtime.comments_json` — every `Transition` appends one — while tasks.json keeps whatever it was seeded with, which for a scaffolded project is nothing. Overlaying only the status meant the dashboard's task detail served an empty `comments` array for a project orch had actually run, with the notes sitting in the database the same request had already opened.

Nothing is lost by overlaying: `Bootstrap` seeds `comments_json` FROM the file, so a runtime row's comments start as the file's and only grow.

(Python has the same hole for the same reason — `_load_tasks_hydrated` replaces `status` and nothing else. It is the second half of bug 24, and opus-2's notes carry the first.)

A task with no row in the database keeps what tasks.json gave it. That is the honest answer before `Bootstrap` has seeded the project — the file is the only thing that knows about the task at all.

Order, and everything else about the rows, is left alone: the caller's task order is the file's order, which is what every view renders in.

One caveat for a future caller: a hydrated Task is for READING. `model.Task` remembers which optional keys its source file had, so saving one back to tasks.json would not write comments the file never declared — this overlay is not a way to migrate them into the file, and nothing should treat it as one.

func InGitRepo

func InGitRepo(dir string) bool

InGitRepo says dir is inside a git work tree.

func IssueRef added in v0.31.0

func IssueRef(issueURL string) (string, bool)

IssueRef turns a GitHub issue URL into the `owner/repo#n` form GitHub's closing keywords take. The long form, not `#n`: it closes the issue whether the PR is in the issue's repository or another one.

func IssueSection added in v0.31.0

func IssueSection(task model.Task, openSiblings []string) string

IssueSection is what a task's PR body says about the GitHub issue it came from (`sourceIssue`, #525), or "" for a task with none.

`Closes owner/repo#n` when no other task of the issue is unfinished, so GitHub closes the issue when the PR merges, with the PR as the evidence. While others are (openSiblings, the ids of the issue's other tasks not done), `Refs`: closing on the first of several PRs would mark the issue done with most of it still to do. An issue URL that is not GitHub's is only linked — no keyword would act on it.

func LastUpdatedByTask

func LastUpdatedByTask(events []state.Event) map[string]string

LastUpdatedByTask is the newest event timestamp per task.

Compared as strings, which is what Python does and what the storage format makes correct: the timestamps are ISO-8601 UTC and sort lexicographically. It also means a row whose timestamp is malformed does not take the whole map down with it.

func LatestRun added in v0.31.0

func LatestRun(ctx context.Context, backend RunReader) (run state.Run, ok bool, err error)

LatestRun is the most recently started run; ok is false when the project has never been run (state.ErrNoRuns), which is not an error to a reader.

func Load

func Load(ctx context.Context, backend StatusReader, tasksJSON string) ([]model.Task, error)

Load reads tasks.json and hydrates it in one call, for a caller that already holds the backend (the dashboard's server, the MCP server). Everything else opens the project with Open and asks it for Tasks.

func MutateTasks added in v0.31.0

func MutateTasks(stateDir, path string, backup bool, change func(*model.TasksFile) error) (string, error)

MutateTasks is the one path for a wholesale rewrite of tasks.json — `orch atomize --apply`, `orch sync issues`, `orch start`, the welcome page. It holds the lock TaskEditor holds, reads the file, hands it to change and writes the result atomically, with a tasks.json.bak-<ts> first when backup is set. They used to read and write outside that lock, so one landing during a dashboard edit lost the other's write (#531). It returns the backup path, or "" when none was made.

func OpenIssueSiblings added in v0.31.0

func OpenIssueSiblings(task model.Task, tasks []model.Task, status func(id string) model.Status) []string

OpenIssueSiblings lists, in the order given, the ids of the tasks other than task that come from the same issue and are not done. status answers a task's current status.

func PIDAlive added in v0.31.0

func PIDAlive(pid int) bool

PIDAlive reports whether a process with this pid exists. 0 and below, what a dispatch row holds before its pid is known, are never alive.

func PIDReused added in v0.31.0

func PIDReused(row state.Dispatch) bool

PIDReused reports whether the live process under a dispatch row's PID started at another time than the dispatch's: the PID was reused after a crash. Without a recorded or readable start time it cannot tell, and says no — the PID-only check stands.

func PRText

func PRText(task model.Task) (title, body string)

PRText is a task's PR title and body, and its local squash commit's message: the run's and Accept's one spelling.

func PackageKey

func PackageKey(taskID string) string

PackageKey is the "<phase>.<package>" a task id like F6.1.T3 belongs to, or "" for an id outside the atomizer's scheme (a synced issue, a hand-added task).

func ParseTS added in v0.31.0

func ParseTS(ts string) (time.Time, bool)

ParseTS reads a timestamp out of the database (state.ParseTS): the one parser that knows every spelling an orch.db holds, so a front end never writes a second one.

func ProcStart added in v0.31.0

func ProcStart(pid int) string

ProcStart is when process pid started, as the OS reports it (#541): /proc/<pid>/stat's starttime (clock ticks since boot) on Linux, `ps -o lstart=` elsewhere. Opaque, only ever compared for equality with itself; "" when it cannot be read.

func ReadAtRef

func ReadAtRef(dir, ref, relPath string) (string, error)

ReadAtRef reads relPath (relative to dir) as it is in ref.

func RecordEvent added in v0.31.0

func RecordEvent(ctx context.Context, w EventWriter, taskID, eventType string, extra map[string]any) error

RecordEvent appends an event about a task from outside any run, stamped now. The type must be one the event log knows. The error is the backend's, for the caller to say what it was recording.

func RunLockHeld added in v0.31.0

func RunLockHeld(stateDir string) bool

RunLockHeld reports whether an `orch run` holds the project's run lock right now. The kernel drops the flock when the run dies however it dies, so this is the run's liveness, which a run row saying "live" is not.

func Runtime added in v0.31.0

func Runtime(ctx context.Context, backend StatusReader) ([]state.TaskRuntime, error)

Runtime is every task's runtime row in the database — status, PR, CI result, finish time — for a caller that reads those columns rather than the hydrated tasks.json (metrics, the stakeholder report's CI figures).

func SetStatus added in v0.31.0

func SetStatus(ctx context.Context, w StatusWriter, taskID string, to model.Status, note Note) error

SetStatus moves a task to `to`, recording note: ErrTaskNotFound when the task has no row, ErrIllegalTransition when the table forbids the move. For a caller that holds a backend (the MCP server); the rest call Project.SetStatus.

func SortQueue added in v0.31.0

func SortQueue(entries []QueueEntry, tasks []model.Task)

SortQueue puts merge queue entries in the order the queue merges them (#522 decision 1): phase first, then how many tasks depend on each, directly or not (more first: it unblocks more work), then when each entered, then id. The engine merges in this order and the dashboard shows it, so both read it from here.

func SpecSection added in v0.31.0

func SpecSection(dir, specRoot, specRef string) (string, error)

SpecSection is the part of the spec specRef points at, read under dir as CheckSpecRef resolves it: the anchor's heading down to the next heading of the same level or higher, or the whole file without an anchor. "" when the file or the anchor is not there (#539: what the reviewer is shown).

func Statuses added in v0.31.0

func Statuses(ctx context.Context, backend StatusReader) (map[string]model.Status, error)

Statuses maps each task id the database knows to its runtime status: what a run's queue starts from, since the database owns runtime status (F-12).

func SummarySpendID added in v0.31.0

func SummarySpendID(runID string) string

SummarySpendID is the synthetic task id the AI summary of run runID writes its spend under (`orch report summary --ai`, #461).

func TaskIDsIn added in v0.31.0

func TaskIDsIn(ctx context.Context, r StatusReader, status model.Status) ([]string, error)

TaskIDsIn lists the ids of the tasks the database has at status, in task id order: what `orch reset` reverts.

func TaskStatus added in v0.31.0

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

TaskStatus is a task's status in the database, which is its status (rule 30); ErrTaskNotFound when it has no row.

func TransitiveDependents added in v0.31.0

func TransitiveDependents(tasks []model.Task) map[string]int

TransitiveDependents counts, per task, the tasks that depend on it directly or through others.

Types

type Attempt added in v0.31.0

type Attempt = state.Attempt

Attempt is one finished attempt at a task, for the agent metrics.

type Backend added in v0.31.0

type Backend = state.Backend

Backend is the type of Project.Backend, for a helper handed an opened project's database rather than the whole project.

type Dispatch added in v0.31.0

type Dispatch = state.Dispatch

Dispatch is an agent process a run started and has not reaped.

type Document

type Document struct {
	ID        string
	Title     string
	UpdatedAt string
	Markdown  string
}

Document is one project file the client portal shows: a title, when it last changed, and its markdown. It carries no path — the portal names documents by title, and a path says where the operator keeps things.

func PortalDocuments

func PortalDocuments(projectRoot string, globs []string) ([]Document, error)

PortalDocuments reads the files `portal.documents` lists (globs relative to the project root), in the order the globs are listed and sorted within each, without duplicates. A glob or a match that resolves outside the project is skipped: the list is the operator's, but what it can publish is the project. Files over the size cap are skipped, and reading stops once the set reaches its cap.

type Event added in v0.31.0

type Event = state.Event

Event is one entry in the event log.

type EventWriter added in v0.31.0

type EventWriter interface {
	AppendEvent(ctx context.Context, runID string, e state.Event) error
}

EventWriter is the slice of the backend RecordEvent needs.

type Metrics added in v0.31.0

type Metrics struct {
	Total   MetricsRow   `json:"total"`
	ByRoute []MetricsRow `json:"by_route"`
	ByTier  []MetricsRow `json:"by_tier"`
}

Metrics is how good the agents' work is, from the attempts table (#538): in total, and by route (backend/model) and by tier.

func ComputeMetrics added in v0.31.0

func ComputeMetrics(attempts []state.Attempt, tasks []state.TaskRuntime) Metrics

ComputeMetrics derives the figures from every attempt, oldest first, and every task's runtime row.

type MetricsRow added in v0.31.0

type MetricsRow struct {
	Key      string `json:"key,omitempty"`
	Attempts int    `json:"attempts"`
	Tasks    int    `json:"tasks"`
	// DoneTasks are the tasks at done with at least one recorded attempt;
	// FirstAttempt those of them done in a single attempt.
	DoneTasks        int     `json:"done_tasks"`
	FirstAttempt     int     `json:"first_attempt"`
	FirstAttemptRate float64 `json:"first_attempt_rate"`
	// RetriesPerDone and CostPerDone count every attempt of a done task,
	// CI retries included.
	RetriesPerDone float64 `json:"retries_per_done"`
	CostPerDone    float64 `json:"cost_per_done_usd"`
	// Verified attempts went through the local verify; SentBack failed it.
	Verified     int     `json:"verified"`
	SentBack     int     `json:"sent_back"`
	SendBackRate float64 `json:"send_back_rate"`
	// A review finding is fixed when the task's next reviewed attempt no
	// longer has it, and ignored when it does, or when the task finished
	// with no later review. Findings of a task still in the works count in
	// neither.
	FindingsFixed   int `json:"findings_fixed"`
	FindingsIgnored int `json:"findings_ignored"`
	// CIAfterVerify are attempts that passed verify and whose CI finished;
	// CIFailedAfterVerify those whose CI failed anyway.
	CIAfterVerify       int     `json:"ci_after_verify"`
	CIFailedAfterVerify int     `json:"ci_failed_after_verify"`
	CIFailRate          float64 `json:"ci_fail_rate"`
	// ModelMismatches are attempts whose CLI reported running another
	// model, effort or service tier than their route asked for (#580).
	ModelMismatches int `json:"model_mismatches"`
	// contains filtered or unexported fields
}

MetricsRow is one group's figures. Task figures (Tasks, DoneTasks, FirstAttempt, RetriesPerDone, CostPerDone) put a task in the group of its first attempt, the route it was planned for; attempt figures (Attempts, verify, findings, CI) count each attempt in the group it ran on.

type Note added in v0.31.0

type Note struct {
	Author string
	Body   string
}

Note is why a task moved: recorded in its comments with the author. An empty Body records the status name; an empty Author is "orch".

type Outline

type Outline struct {
	// Phases maps a phase number to its `# F<n> — <title>` title.
	Phases map[int]string
	// Packages maps "<phase>.<package>" to its `## F<n>.<k> — <title>` title,
	// with a leading "Package: " dropped.
	Packages map[string]string
}

Outline is what the specs name that tasks.json does not: every phase and every package, by the titles people read.

func SpecOutline

func SpecOutline(projectRoot, specRoot string, tasks []model.Task) (Outline, error)

SpecOutline reads phase and package titles from the specs the tasks point at. A task with no specRef, or a spec that is not there, contributes nothing; a spec that exists and cannot be read is an error, because that is a broken project rather than an absent spec.

A specRef is tried under spec_root first and then as written, because specs from before bug 12 carry the `specs/` prefix themselves.

type Project added in v0.31.0

type Project struct {
	Paths   config.Paths
	Config  config.Config
	Backend state.Backend
	// contains filtered or unexported fields
}

Project is an opened project: where it lives, its config, and its database. Open is the door to it; Close releases the database.

func New added in v0.31.0

func New(paths config.Paths, cfg config.Config, backend state.Backend) *Project

New is a project over a backend the caller already holds and closes itself — `orch bench` and `orch knowledge curate` read through the run's own backend while it goes, so the file keeps one writer (CHECKLIST rule 17). Close does not close that backend.

func Open added in v0.31.0

func Open(ctx context.Context, paths config.Paths) (*Project, error)

Open loads the project's config.yaml and opens its database (creating and migrating it if needed). paths come from config.ResolvePaths; checking that they are a real project is the caller's (the CLI words that error itself).

func OpenWith added in v0.31.0

func OpenWith(ctx context.Context, paths config.Paths, cfg config.Config) (*Project, error)

OpenWith is Open for a caller that has already loaded cfg: `orch run` reads the config to decide whether it may start at all (the sandbox, the run lock) before it opens the database.

func (*Project) Close added in v0.31.0

func (p *Project) Close() error

Close closes the project's database, when Open opened it.

func (*Project) RecordEvent added in v0.31.0

func (p *Project) RecordEvent(ctx context.Context, taskID, eventType string, extra map[string]any) error

RecordEvent appends an event about one of the project's tasks; see the package function.

func (*Project) SetStatus added in v0.31.0

func (p *Project) SetStatus(ctx context.Context, taskID string, to model.Status, note Note) error

SetStatus moves one of the project's tasks; see the package function.

func (*Project) TaskStatus added in v0.31.0

func (p *Project) TaskStatus(ctx context.Context, taskID string) (model.Status, error)

TaskStatus is one of the project's tasks' status; see the package function.

func (*Project) Tasks added in v0.31.0

func (p *Project) Tasks(ctx context.Context) ([]model.Task, error)

Tasks is tasks.json hydrated with the database's live status and comments.

type ProviderState added in v0.31.0

type ProviderState = state.ProviderState

ProviderState is whether the operator turned a provider off.

type QueueEntry added in v0.31.0

type QueueEntry = state.QueueEntry

QueueEntry is one task's place in the merge queue (#522, migration 017).

type QueueReader added in v0.31.0

type QueueReader interface {
	QueueEntries(ctx context.Context) ([]QueueEntry, error)
}

QueueReader reads the merge queue; state.SQLite is one.

type QueuedFinding added in v0.31.0

type QueuedFinding = state.QueuedFinding

QueuedFinding is an agent's report about orch waiting in the review queue (#536).

type RadarCollision added in v0.31.0

type RadarCollision struct {
	TaskID    string   `json:"task_id"`
	Kind      string   `json:"kind"`
	EventType string   `json:"event_type"`
	At        string   `json:"at"`
	Files     []string `json:"files"`
	// With are the tasks it collided with, when the event says
	// (ci_conflict_retry's caused_by, a semantic collision's other branch).
	With      []string `json:"with"`
	Predicted bool     `json:"predicted"`
	// PredictedBy are the warned pairs that matched it, "A ~ B".
	PredictedBy []string `json:"predicted_by"`
	// Match is how the best one matched: "with" (the pair is the one it
	// collided with), "files" (a file in common) or "task" (the collision
	// names no file nor task, so any earlier warning on it counts); "" when
	// none did.
	Match string `json:"match"`
}

RadarCollision is one collision and whether it was predicted.

type RadarCollisions added in v0.31.0

type RadarCollisions struct {
	Total     int            `json:"total"`
	Predicted int            `json:"predicted"`
	Escaped   int            `json:"escaped"`
	ByKind    map[string]int `json:"by_kind"`
}

RadarCollisions counts what actually collided.

type RadarPair added in v0.31.0

type RadarPair struct {
	Tasks    [2]string `json:"tasks"`
	Kinds    []string  `json:"kinds"`
	Files    []string  `json:"files"`
	FirstAt  string    `json:"first_at"`
	Collided bool      `json:"collided"`
}

RadarPair is one pair of tasks the radar warned about.

type RadarPredictions added in v0.31.0

type RadarPredictions struct {
	FilesOverlap   int `json:"files_overlap"`
	BranchConflict int `json:"branch_conflict"`
	// Pairs is the distinct pairs of tasks warned about.
	Pairs int `json:"pairs"`
	// PairsCollided is how many of them collided after the warning.
	PairsCollided int `json:"pairs_collided"`
}

RadarPredictions counts the radar's warnings.

type RadarReport added in v0.31.0

type RadarReport struct {
	// From is the first instant counted, RFC 3339; "" for all of history.
	From        string           `json:"from"`
	Predictions RadarPredictions `json:"predictions"`
	Collisions  RadarCollisions  `json:"collisions"`
	// Recall is the share of collisions some earlier warning predicted;
	// null with no collision.
	Recall *float64 `json:"recall"`
	// Precision is the share of warned pairs that later collided; null
	// with no warning.
	Precision *float64 `json:"precision"`
	// Pairs are the warned pairs of tasks, oldest warning first.
	Pairs []RadarPair `json:"pairs"`
	// Events are the collisions, oldest first.
	Events []RadarCollision `json:"events"`
}

RadarReport is `orch radar report`.

func RadarEffectiveness added in v0.31.0

func RadarEffectiveness(events []state.Event, from time.Time) RadarReport

RadarEffectiveness reads the radar's warnings and the collisions in events (chronological, as AllEvents returns them) from `from` on (zero: all), and matches each collision with the warnings before it.

A collision on task T is predicted when an earlier warning names T (on either side) and either the other task is the one T collided with, or the warning and the collision share a file (a warned directory or glob covers the files under it). A collision that names neither files nor a task (a clean merge that broke the verify, an old conflict block) counts any earlier warning on T. A warned pair collided when a collision on either of its tasks matched it.

type Run added in v0.31.0

type Run = state.Run

Run is one `orch run`'s row.

type RunReader added in v0.31.0

type RunReader interface {
	LatestRun(ctx context.Context) (state.Run, error)
}

RunReader is the slice of the backend LatestRun needs.

type SpecGitState

type SpecGitState struct {
	// InRepo is false when the directory is not inside a git work tree; the
	// other fields are then meaningless.
	InRepo bool
	// Untracked and Modified describe the working tree against HEAD.
	Untracked bool
	Modified  bool
	// BaseRef is the ref the file was looked for in: origin/<base> when the
	// remote-tracking branch exists, else the local <base>, else "" (no base
	// to compare against, and OnBase is meaningless).
	BaseRef string
	// OnBase says the file exists in BaseRef.
	OnBase bool
}

SpecGitState is where a spec file stands in git, relative to the branch a task's worktree starts from.

func GitStateOf

func GitStateOf(dir, relPath, base string) SpecGitState

GitStateOf reports where relPath (relative to dir) stands against base.

type SpecRefCheck

type SpecRefCheck struct {
	// Ref is the specRef as written in tasks.json.
	Ref string
	// File is the spec's path relative to the directory checked, slash
	// separated: the candidate that exists, or spec_root/<file> when none
	// does. Empty when Ref names no file.
	File string
	// Anchor is what follows `#` in Ref, or "".
	Anchor string
	// FileFound says File exists in the directory checked.
	FileFound bool
	// AnchorFound says File has a heading for Anchor. True when there is no
	// anchor to look for, false when the file itself is missing.
	AnchorFound bool
}

SpecRefCheck is what a task's specRef resolves to inside one directory: a project root, or the worktree a task is about to run in (#341, #342).

The two directories can disagree, and that disagreement is the bug: `orch atomize` reads specs from the operator's working tree, while a task's worktree starts from the base branch, so a spec written but never committed and pushed is there for the first and missing for the second.

func CheckSpecRef

func CheckSpecRef(dir, specRoot, specRef string) (SpecRefCheck, error)

CheckSpecRef resolves specRef under dir the way SpecOutline does: under spec_root first, then as written, because specs from before bug 12 carry the `specs/` prefix themselves. A spec that exists and cannot be read is an error; one that is not there is a result.

func (SpecRefCheck) OK

func (c SpecRefCheck) OK() bool

OK is a spec ref an agent can follow: no ref at all, or a file that exists and holds its anchor.

type Spend added in v0.31.0

type Spend = state.Spend

Spend is one dispatch's cost and token row.

type StatusReader

type StatusReader interface {
	Tasks(ctx context.Context, filter state.TaskFilter) ([]state.TaskRuntime, error)
}

StatusReader is the slice of the backend Hydrate needs: one query for every task's current runtime row.

type StatusWriter added in v0.31.0

type StatusWriter interface {
	Transition(ctx context.Context, id string, to model.Status, note state.Note) error
}

StatusWriter is the slice of the backend SetStatus needs.

type Steer

type Steer struct {
	Backend  state.Backend
	StateDir string
	// Source names who asked, in the request's extra: cli, mcp, dashboard.
	Source string
	// VCS is vcs.provider and vcs.host: which merge Accept makes.
	VCS vcs.Config
	// Provider, when set, is used instead of the one VCS names (tests).
	Provider vcs.Provider
	// Root, BaseBranch and TasksJSON are what Accept lands a task with in
	// local mode: the project's repository, dispatch.base_branch ("" is
	// main), and where the squash message's title and spec come from.
	Root, BaseBranch, TasksJSON string
}

Steer is how the operator steers a task (#356): a note for its agent, or a stop. The CLI, the MCP server and the dashboard all go through it, so every source writes the same request and only `orch run` touches processes.

func (Steer) Accept

func (s Steer) Accept(ctx context.Context, taskID string) (string, error)

Accept merges the task's work. With a forge (vcs.provider github or gitlab) that is its PR, squashed, now: the operator has read the change. Which merge it is depends on the provider, and only here.

func (Steer) Move

func (s Steer) Move(ctx context.Context, taskID string, to model.Status, note string) (StopResult, error)

Move puts a task in another column of the board (v0.22): the dashboard's drag and its status picker. Blocking needs a reason, which becomes the task's note. A running task is not moved behind its run's back: to todo or blocked it is a Stop (redirect or hold), and nothing moves a task into in-progress or a running one to done but `orch run`.

func (Steer) Note

func (s Steer) Note(ctx context.Context, taskID, body string) error

Note records a note for the task's agent. It reaches the prompt of the task's next attempt, not the one running now.

func (Steer) SendBack

func (s Steer) SendBack(ctx context.Context, taskID, note string) (StopResult, error)

SendBack returns a finished or blocked task to its agent: the note reaches its next attempt's prompt, and the task goes back to todo for `orch run` to dispatch again.

func (Steer) SetProvider

func (s Steer) SetProvider(ctx context.Context, backend string, disabled bool, reason string) error

SetProvider turns dispatching to backend off (with the operator's reason) or back on for this project: `orch run` leaves the tasks routed to a disabled backend waiting, as it does for a capped budget. The one function behind `orch provider disable|enable` and the dashboard's switch.

func (Steer) Stop

func (s Steer) Stop(ctx context.Context, taskID string, hold bool, note string) (StopResult, error)

Stop ends the task's running attempt. hold keeps it from being dispatched again (blocked, HeldReason; Unblock is `orch task set --status todo`); without it the task is dispatched again, with note — when there is one — in its prompt.

With an `orch run` running it writes a request that run acts on. With none, nothing is running, so it is a plain status change, and says so.

func (Steer) WaitStopped

func (s Steer) WaitStopped(ctx context.Context, res StopResult, timeout time.Duration) (state.Event, bool, error)

WaitStopped waits up to timeout for the run's answer to a request Stop made, and returns it. ok is false when the run has not answered in time.

type StopResult

type StopResult struct {
	TaskID string `json:"task_id"`
	// Requested is true when a running `orch run` was asked to stop the
	// task; it acts on its next tick. RequestID is the event row after which
	// its answer lands (see WaitStopped).
	Requested bool  `json:"requested"`
	RequestID int64 `json:"-"`
	Hold      bool  `json:"hold"`
	// From and To are the plain status change made when no run is running;
	// equal when there was nothing to change.
	From    model.Status `json:"from,omitempty"`
	To      model.Status `json:"to,omitempty"`
	Message string       `json:"message"`
}

StopResult is what Stop did.

type TaskEditor

type TaskEditor struct {
	TasksJSON string
	StateDir  string
	// Routes are model_router.yaml's keys; a task's model must be one. Nil
	// skips the check, for a project with no router.
	Routes []string
	// Backend, when set, gets the edit at once: the definitions are synced
	// (Bootstrap upserts them) and the edit is recorded as an event.
	Backend state.Backend
	// Source names who edited, in the event: cli, dashboard.
	Source string
}

TaskEditor changes the task definitions in tasks.json — the one way the CLI and the dashboard do it (#390, v0.22), so both do exactly the same to a task. tasks.json stays the source of a task's definition, versioned with git; its status stays the database's, changed through state.Transition.

func (TaskEditor) Add

func (e TaskEditor) Add(ctx context.Context, t model.Task) (model.Task, error)

Add appends a new task. It starts as todo unless it says backlog.

func (TaskEditor) Update

func (e TaskEditor) Update(ctx context.Context, id string, p TaskPatch) (model.Task, error)

Update changes the fields p sets on task id.

type TaskPatch

type TaskPatch struct {
	Title         *string   `json:"title,omitempty"`
	Description   *string   `json:"description,omitempty"`
	Model         *string   `json:"model,omitempty"`
	Reason        *string   `json:"reason,omitempty"`
	SpecRef       *string   `json:"spec_ref,omitempty"`
	Phase         *int      `json:"phase,omitempty"`
	EstimateHours *float64  `json:"estimate_hours,omitempty"`
	Dependencies  *[]string `json:"dependencies,omitempty"`
	Files         *[]string `json:"files,omitempty"`
}

TaskPatch is a partial change to a task's definition; nil fields stay.

type TaskReader added in v0.31.0

type TaskReader interface {
	Task(ctx context.Context, id string) (state.TaskRuntime, error)
}

TaskReader is the slice of the backend TaskStatus needs.

type TaskRuntime added in v0.31.0

type TaskRuntime = state.TaskRuntime

TaskRuntime is a task's runtime row: live status, PR, CI, timings.

func DoneRuntime added in v0.31.0

func DoneRuntime(ctx context.Context, r StatusReader) ([]TaskRuntime, error)

DoneRuntime is the runtime rows of every task that is done.

func RuntimeOf added in v0.31.0

func RuntimeOf(ctx context.Context, r StatusReader, ids ...string) ([]TaskRuntime, error)

RuntimeOf is the runtime rows of the given task ids — fewer when the database has no row for one, and none for no ids (an empty filter would otherwise mean every task).

Jump to

Keyboard shortcuts

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