Documentation
¶
Index ¶
- Constants
- Variables
- func FormatTS(t time.Time) string
- func IsSyntheticSpend(taskID string) bool
- func ParseTS(s string) (time.Time, bool)
- func ReviewSpendID(taskID string, attempt int) string
- func SummarySpendID(runID string) string
- type Attempt
- type AttemptFinding
- type Backend
- type DB
- type Dispatch
- type Event
- type FiledFinding
- type KnowledgeDoc
- type Note
- type OrphanRows
- type ProviderQuota
- type ProviderState
- type QueueEntry
- type QueuedFinding
- type QuotaWindow
- type Run
- type SQLite
- func (b *SQLite) AddNote(ctx context.Context, id string, note Note) error
- func (b *SQLite) AllEvents(ctx context.Context, n int) ([]Event, error)
- func (b *SQLite) AllSpend(ctx context.Context, since time.Time) ([]Spend, error)
- func (b *SQLite) AppendEvent(ctx context.Context, runID string, e Event) error
- func (b *SQLite) Attempts(ctx context.Context) ([]Attempt, error)
- func (b *SQLite) Bootstrap(ctx context.Context, tasks []model.Task) error
- func (b *SQLite) ClearDispatch(ctx context.Context, runID, taskID string) error
- func (b *SQLite) CountDoneLastNDays(ctx context.Context, days int) (int, error)
- func (b *SQLite) Enqueue(ctx context.Context, taskID, prURL string, at time.Time) (bool, error)
- func (b *SQLite) Events(ctx context.Context, taskID string, n int) ([]Event, error)
- func (b *SQLite) EventsSince(ctx context.Context, afterID int64, limit int) ([]Event, error)
- func (b *SQLite) FiledFindings(ctx context.Context) ([]FiledFinding, error)
- func (b *SQLite) FirstEventBackend(ctx context.Context, eventType string) (backend string, ok bool, err error)
- func (b *SQLite) InFlightDispatches(ctx context.Context) ([]Dispatch, error)
- func (b *SQLite) IncrementCIAttempts(ctx context.Context, taskID string) (int, error)
- func (b *SQLite) LastEventByTask(ctx context.Context, taskIDs []string) (map[string]Event, error)
- func (b *SQLite) LatestEventID(ctx context.Context) (int64, error)
- func (b *SQLite) LatestQuota(ctx context.Context, backend string) (ProviderQuota, bool, error)
- func (b *SQLite) LatestRun(ctx context.Context) (Run, error)
- func (b *SQLite) MarkMigrated(ctx context.Context, ts string) error
- func (b *SQLite) MigratedAt(ctx context.Context) (string, error)
- func (b *SQLite) OrphanRows(ctx context.Context) (OrphanRows, error)
- func (b *SQLite) ProviderStates(ctx context.Context) ([]ProviderState, error)
- func (b *SQLite) QueueEntries(ctx context.Context) ([]QueueEntry, error)
- func (b *SQLite) QueueFinding(ctx context.Context, f QueuedFinding) (int64, error)
- func (b *SQLite) QueuedFindings(ctx context.Context) ([]QueuedFinding, error)
- func (b *SQLite) RankKnowledge(ctx context.Context, docs []KnowledgeDoc, query string, limit int) ([]string, error)
- func (b *SQLite) RecordAttempt(ctx context.Context, a Attempt) error
- func (b *SQLite) RecordDispatch(ctx context.Context, d Dispatch) error
- func (b *SQLite) RecordFiledFinding(ctx context.Context, f FiledFinding) error
- func (b *SQLite) RecordSpend(ctx context.Context, s Spend) error
- func (b *SQLite) Runs(ctx context.Context) ([]Run, error)
- func (b *SQLite) SetFindingStatus(ctx context.Context, id int64, status, url string) error
- func (b *SQLite) SetProviderState(ctx context.Context, backend string, disabled bool, reason string, ...) error
- func (b *SQLite) SetQueueState(ctx context.Context, taskID, state, reason string, at time.Time) error
- func (b *SQLite) SetStakeholderToken(ctx context.Context, tokenHash string, rotatedAt time.Time) error
- func (b *SQLite) SetTaskCIStatus(ctx context.Context, taskID, status string) error
- func (b *SQLite) SetTaskPR(ctx context.Context, taskID, prURL string) error
- func (b *SQLite) SpendSince(ctx context.Context, backend string, since time.Time) ([]Spend, error)
- func (b *SQLite) StakeholderToken(ctx context.Context) (tokenHash string, rotatedAt time.Time, ok bool, err error)
- func (b *SQLite) StartRun(ctx context.Context, runID, mode string) error
- func (b *SQLite) Task(ctx context.Context, id string) (TaskRuntime, error)
- func (b *SQLite) Tasks(ctx context.Context, filter TaskFilter) ([]TaskRuntime, error)
- func (b *SQLite) TasksWithPendingCI(ctx context.Context) ([]TaskRuntime, error)
- func (b *SQLite) TotalSpendUSD(ctx context.Context, since time.Time) (float64, error)
- func (b *SQLite) Transition(ctx context.Context, id string, to model.Status, note Note) error
- type Spend
- type TaskFilter
- type TaskRuntime
Constants ¶
const ( FindingQueued = "queued" FindingSent = "sent" FindingDismissed = "dismissed" )
The statuses of a queued finding.
const ( QueueQueued = "queued" QueueMerged = "merged" QueueEjected = "ejected" )
Merge queue states (migration 017, #522).
const NoteKindOperator = "operator_note"
NoteKindOperator is the `kind` of a note the operator wrote for a task's agent: `orch task note`, `orch task stop --note`, orch_task_note and the dashboard (#356).
Variables ¶
var ( // ErrTaskNotFound means the id is not in tasks_runtime for this project. ErrTaskNotFound = errors.New("task not found") // ErrIllegalTransition means the move is not in the transition table. // The message names the legal destinations, because the caller is // usually a human who just typed a status. ErrIllegalTransition = errors.New("illegal transition") // ErrUnknownEventType means the event type is outside FR-STATE-7's set. ErrUnknownEventType = errors.New("unknown event type") )
Sentinel errors callers act on. Everything else is wrapped context.
var ErrNoRuns = errors.New("no runs recorded for this project")
ErrNoRuns means the project has never been run.
Distinct from an empty result so a caller can tell "nothing has happened yet" from "the query found nothing", which read differently to an operator looking at `orch status`.
Functions ¶
func FormatTS ¶ added in v0.31.0
FormatTS is the one spelling of a timestamp in an orch.db: `2026-09-11T18:30:00Z`, second precision, always UTC. The format is shared with `scripts/task-*.sh`, so it is a contract, not a preference; migration 015 rewrote every older spelling to it. Every writer goes through this.
func IsSyntheticSpend ¶
IsSyntheticSpend reports whether a spend row's task id is one of the above.
func ParseTS ¶
ParseTS reads the two timestamp forms that coexist in a real orch.db.
This is not defensive coding, it is a fact about the file: the same database written by one Python version holds `2026-09-01T10:30:00+00:00` in `spend.ts` and `2026-09-11T18:32:54Z` in `runs.started_at`, because different call sites reach for `datetime.isoformat()` and `strftime("...Z")`. Python's `budget._parse_ts` accepts both and says why: "robustness with older rows".
It is also why the window is filtered in Go rather than with `ts >= ?` in SQL. Lexically, "+" (0x2B) sorts before "Z" (0x5A), so a cutoff formatted one way silently drops rows stored the other way — under-reporting spend, which is precisely how a budget guardrail stops guarding without any error. The spend table is tens of rows, so parsing them is not a cost worth a correctness risk.
Exported so `internal/budget` can date the rows it gets back without writing a second parser. A second parser is how the two forms would start disagreeing again: this is the only place that knows what an orch.db actually contains, so it is the only place that should be reading a timestamp out of one.
func ReviewSpendID ¶
ReviewSpendID names the spend of the local verify's review of a task's attempt. Under ORCH_FAKE_PROVIDER it is also the reviewer's canned response name.
func SummarySpendID ¶
SummarySpendID names the spend of the AI summary of run runID.
Types ¶
type Attempt ¶ added in v0.31.0
type Attempt struct {
ID int64
RunID string
TaskID string
Attempt int
// Backend, Model and Tier are the route it ran on; Effort and
// ServiceTier the reasoning effort and codex service tier the route
// asked for ("" when it set none).
Backend, Model, Tier string
Effort, ServiceTier string
// EffectiveModel, EffectiveEffort and EffectiveServiceTier are what the
// CLI reported running (#580); "" when it reported nothing.
EffectiveModel, EffectiveEffort, EffectiveServiceTier string
// Result is the dispatch's outcome: success, fail, timeout or stopped.
Result string
FailureClass string
Reason string
TokensIn int
TokensOut int
CostUSD float64
DurationS float64
// Verify is the local verify's verdict: "" when it did not run, pass or
// fail. Review is the reviewer's: "" when none completed, pass or blocks.
Verify, Review, Reviewer string
Findings []AttemptFinding
// CI is how the PR's CI went, on the attempt that pushed: "", success or
// failure.
CI string
FinishedAt string
}
Attempt is one finished attempt at a task (#538): how it ended, what it cost, and what the local verify, its review and CI said about it.
type AttemptFinding ¶ added in v0.31.0
type AttemptFinding struct {
Severity string `json:"severity"`
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
Title string `json:"title"`
}
AttemptFinding is one review finding, as engine.VerifyFinding has it minus the detail.
type Backend ¶
type Backend interface {
// Bootstrap seeds `projects`, `tasks_definition` and `tasks_runtime`
// from tasks.json. Idempotent: re-running never overwrites a runtime
// status, so it is safe on every startup.
Bootstrap(ctx context.Context, tasks []model.Task) error
// Tasks returns the runtime rows matching filter, ordered by task id.
Tasks(ctx context.Context, filter TaskFilter) ([]TaskRuntime, error)
// Task returns one task. ErrTaskNotFound when it does not exist.
Task(ctx context.Context, id string) (TaskRuntime, error)
// Transition moves a task, enforcing the legal-transition table and
// recording note in the task's comments.
Transition(ctx context.Context, id string, to model.Status, note Note) error
// AddNote appends note to the task's comments without moving it.
// ErrTaskNotFound when it does not exist.
AddNote(ctx context.Context, id string, note Note) error
// StartRun opens a run, or leaves an existing one alone. `dispatches`
// has a foreign key onto `runs`, so this is RecordDispatch's
// precondition rather than a separate concern.
StartRun(ctx context.Context, runID, mode string) error
// RecordDispatch marks a subprocess in flight.
RecordDispatch(ctx context.Context, d Dispatch) error
// ClearDispatch removes an in-flight record once the process is reaped.
ClearDispatch(ctx context.Context, runID, taskID string) error
// InFlightDispatches returns the dispatches still marked in flight for
// this project, across runs — what a resumed run reconciles against.
InFlightDispatches(ctx context.Context) ([]Dispatch, error)
// TasksWithPendingCI returns the tasks whose PR is open and whose CI has
// not finished — what the CI poller iterates.
TasksWithPendingCI(ctx context.Context) ([]TaskRuntime, error)
// SetTaskPR records a task's pull request and marks its CI pending.
SetTaskPR(ctx context.Context, taskID, prURL string) error
// SetTaskCIStatus records how a task's CI finished: pending, success,
// failure or skipped.
SetTaskCIStatus(ctx context.Context, taskID, status string) error
// IncrementCIAttempts bumps the retry counter and returns its new value —
// the number of the attempt that just started.
IncrementCIAttempts(ctx context.Context, taskID string) (int, error)
// RecordSpend appends a completed dispatch's cost, de-duplicated.
RecordSpend(ctx context.Context, s Spend) error
// AppendEvent appends one event, de-duplicated.
AppendEvent(ctx context.Context, runID string, e Event) error
// Events returns the last n events for a task, oldest first. n <= 0
// means every event.
Events(ctx context.Context, taskID string, n int) ([]Event, error)
// AllEvents returns events across every task, oldest first. n <= 0 means
// every event; n > 0 returns the newest n in chronological order.
AllEvents(ctx context.Context, n int) ([]Event, error)
// SpendSince returns one backend's spend rows newer than `since`,
// oldest first — the rolling window the budget gate reads.
SpendSince(ctx context.Context, backend string, since time.Time) ([]Spend, error)
// TotalSpendUSD sums cost across every backend since `since`.
TotalSpendUSD(ctx context.Context, since time.Time) (float64, error)
// AllSpend returns every spend row newer than `since`, across every
// backend, oldest first. The zero Time means all of history.
AllSpend(ctx context.Context, since time.Time) ([]Spend, error)
// LatestRun returns the most recently started run. ErrNoRuns when the
// project has never been run.
LatestRun(ctx context.Context) (Run, error)
// Runs returns every run, newest first.
Runs(ctx context.Context) ([]Run, error)
// CountDoneLastNDays counts tasks at `done` whose row was touched in the
// last n days — the numerator of the sprint velocity figure.
CountDoneLastNDays(ctx context.Context, days int) (int, error)
// LastEventByTask returns the newest event per task id. A nil list means
// every task; an empty one means none, and asks nothing of the database.
LastEventByTask(ctx context.Context, taskIDs []string) (map[string]Event, error)
// LatestEventID is the id of the newest event, or 0 for a project with
// none — where a live tail starts.
LatestEventID(ctx context.Context) (int64, error)
// EventsSince returns events newer than afterID, oldest first, at most
// limit rows. Keyed on the id rather than on a timestamp: see the
// implementation for the same-second window that closes.
EventsSince(ctx context.Context, afterID int64, limit int) ([]Event, error)
// OrphanRows reports runtime and definition rows with no project row.
OrphanRows(ctx context.Context) (OrphanRows, error)
// StakeholderToken returns this project's stored stakeholder token hash
// and when it was last rotated (G8.2/F3.3). ok is false when no row
// exists — the caller falls back to config.yaml/--token. See
// internal/dashboard.HashToken for how the hash is computed on both the
// write side (`orch dashboard token rotate`) and the read side (the
// dashboard's access middleware).
StakeholderToken(ctx context.Context) (tokenHash string, rotatedAt time.Time, ok bool, err error)
// SetStakeholderToken stores a freshly rotated token's hash, replacing
// any row this project already had.
SetStakeholderToken(ctx context.Context, tokenHash string, rotatedAt time.Time) error
// ProviderStates lists the providers the operator turned off or back
// on; a backend with no row is enabled.
ProviderStates(ctx context.Context) ([]ProviderState, error)
// SetProviderState turns a backend off (with a reason) or back on.
SetProviderState(ctx context.Context, backend string, disabled bool, reason string, at time.Time) error
// FiledFindings lists the issues orch_report_finding filed for this
// project; RecordFiledFinding adds one (#441).
FiledFindings(ctx context.Context) ([]FiledFinding, error)
RecordFiledFinding(ctx context.Context, f FiledFinding) error
// QueueFinding, QueuedFindings and SetFindingStatus are the review queue
// between an agent's report and a public issue (#536).
QueueFinding(ctx context.Context, f QueuedFinding) (int64, error)
QueuedFindings(ctx context.Context) ([]QueuedFinding, error)
SetFindingStatus(ctx context.Context, id int64, status, url string) error
// RecordAttempt appends one finished attempt; Attempts lists them, oldest
// first — what `orch metrics` reads (#538).
RecordAttempt(ctx context.Context, a Attempt) error
Attempts(ctx context.Context) ([]Attempt, error)
}
Backend is the only way anything reads or writes orch's state.
The shape comes from the migration plan's interface sketch, widened with what `orch doctor` and `orch init` need. Everything takes a context: a dispatch loop draining on SIGINT has to be able to abandon a query rather than block on a busy writer.
Nothing here knows about tasks.json. Since F-12 the database is the source of truth for runtime status, and tasks.json is read only for the DAG's shape — Bootstrap is the one place the two meet.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is a handle on one project's orch.db.
Two pools, deliberately:
- write is capped at a single connection. SQLite serialises writers anyway; capping the pool means the queue forms in Go, where it is fair and cancellable, instead of inside SQLite as a storm of SQLITE_BUSY retries. The engine, the MCP server and `orch task set` all write, so this is the mechanism the "one writer" rule rests on.
- read is a normal pool. WAL lets readers run while a write is in flight, which is the whole reason the dashboard can poll a live run.
Both point at the same file.
func Open ¶
Open opens (creating if needed) the SQLite database at path and applies any pending migrations. It returns the number of migrations applied so callers can log a first-run differently from a no-op.
Opening a database written by orch v0.11.0 (Python) must apply zero.
type Dispatch ¶
type Dispatch struct {
RunID string
TaskID string
Backend string
PID int
SessionID string
StartedAt string
PromptPath string
LogPath string
OutputPath string
Attempt int
// ProcStart is when the process started, as the OS reports it (#541):
// crash recovery compares it to tell a reused PID from the dispatch.
// Opaque; "" when it could not be read.
ProcStart string
}
Dispatch is one in-flight subprocess.
type Event ¶
type Event struct {
ID int64
RunID string
EventType string
TaskID string
Backend string
TS string
Extra map[string]any
}
Event is one line of a run's history.
EventType is constrained to a closed set — see eventTypes. Extra is free-form per type; the `pid` key in a dispatch event feeds the dedup hash.
type FiledFinding ¶
FiledFinding is an issue orch_report_finding filed for this project.
type KnowledgeDoc ¶
type KnowledgeDoc struct {
ID, Title, Body, Tags, Area string
}
KnowledgeDoc is one lesson as the search index sees it (#451).
type Note ¶
type Note struct {
// Author is who moved it: "orch" for the engine, a CLI name for an
// agent, a person's handle for a manual `orch task set`.
Author string
// Body is free text. Empty is allowed and means "no explanation"; the
// status name is recorded in its place, matching Python.
Body string
// At is the timestamp. Zero means "now", resolved by the backend so a
// caller never has to reach for a clock.
At time.Time
// KeepPR keeps the task's PR, CI status and CI attempts on a move to
// todo. Only the engine sets it: its CI retry reopens the task to work on
// the SAME PR (#276). Everyone else resetting a task means the old PR is
// no longer its work, and the move clears it (#255).
KeepPR bool
// Kind marks a comment that is not a transition's trail. Empty for
// every transition; NoteKindOperator for an operator's note to the
// task's agent (#356), which the prompt renders and the dependency
// block skips.
Kind string
}
Note is the trail a transition leaves. It becomes an entry in the task's `comments_json`, which is what `orch events` and the dashboard read back to explain why a task moved.
type OrphanRows ¶
OrphanRows reports rows whose project_id has no row in `projects`, keyed by table and then by project_id.
With `PRAGMA foreign_keys = ON` this should be impossible, but it has been seen after direct sqlite3-CLI edits and after a bootstrap from a version that predated FK enforcement (F-9, issue #73). Orphaned runtime rows make a DAG look stalled with no error anywhere, so doctor reports them — and never deletes them, because the operator has to look first.
func (OrphanRows) Total ¶
func (o OrphanRows) Total() int
Total counts every orphan row across every table.
type ProviderQuota ¶ added in v0.31.0
type ProviderQuota struct {
Windows []QuotaWindow
SeenAt time.Time
}
ProviderQuota is the newest report of one backend's subscription windows. It counts every use of the account, inside orch or not, and is only as fresh as the last dispatch to that backend: SeenAt.
type ProviderState ¶
ProviderState is one backend the operator turned off or back on. A backend with no row is enabled.
type QueueEntry ¶ added in v0.31.0
type QueueEntry struct {
TaskID string `json:"task_id"`
PRURL string `json:"pr_url"`
EnqueuedAt time.Time `json:"enqueued_at"`
State string `json:"state"`
Requeues int `json:"requeues"`
Reason string `json:"reason"`
UpdatedAt time.Time `json:"updated_at"`
}
QueueEntry is one task's place in the merge queue.
type QueuedFinding ¶ added in v0.31.0
type QueuedFinding struct {
ID int64
Title string
Body string
Summary string
TaskID string
QueuedAt time.Time
Status string
URL string
}
QueuedFinding is an agent's report about orch waiting for the operator (#536). Title and Body are redacted and are exactly what sending files.
type QuotaWindow ¶ added in v0.31.0
type QuotaWindow struct {
Window string `json:"window"`
// Utilization is the used fraction, 0 to 1.
Utilization float64 `json:"utilization"`
// ResetsAt is when the window resets, Unix seconds; 0 when not given.
ResetsAt int64 `json:"resets_at"`
}
QuotaWindow is one window of a provider's subscription as a dispatch's outcome event recorded it (extra.quota): the shape providers.QuotaWindow marshals to, read back without importing the providers package.
type Run ¶
type Run struct {
RunID string
StartedAt string
UpdatedAt string
Mode string
Status string
ParentPID int
// InFlight counts dispatches still marked in_flight for this run. A
// non-zero value on a run whose process is gone is what the reconciler
// cleans up after a crash.
InFlight int
// The three tallies `runs` keeps as JSON arrays of task ids, reported as
// lengths because that is all any caller wants — `orch status --json`
// renders them and nothing reads the ids back out of here.
//
// A column holding JSON that does not parse counts as 0 rather than
// failing the read. Python's `list_runs` lets the `json.loads` raise, so
// one corrupt column takes down `orch status` entirely; trading "a tally
// says 0" for "orch cannot tell you anything about this project" is the
// wrong trade for three numbers that feed no decision. Where these lists
// DO feed a decision — `blocked_json` in the reconciler — the error has
// to surface, and that path is not this one.
CompletedCount int
BlockedCount int
DeferredCount int
}
Run is one dispatch session.
type SQLite ¶
type SQLite struct {
// contains filtered or unexported fields
}
SQLite implements Backend over one project's orch.db.
A single database can hold several projects; every statement is scoped by projectID, and `TestTasksAreScopedToTheProject` is what keeps that true.
func (*SQLite) AddNote ¶
AddNote appends a note to a task's comments and leaves everything else as it was, updated_at included: CountDoneLastNDays reads that column, and a note on a finished task must not count it as finished again.
func (*SQLite) AllEvents ¶
AllEvents returns events across every task, oldest first. n <= 0 means all; n > 0 returns the TAIL — the newest n, still in chronological order.
`Events` answers "what happened to this task"; this answers "what happened", which is the question a log view and any per-task aggregate both start from. Doing it as one query rather than a loop over `Events` matters at both ends: a project with 400 tasks is 400 round trips, and a log view that fetched per task could not order the result without reading everything anyway.
Ordering ¶
By time, then by `id`. Python sorts its merged JSONL + SQLite rows with `sort(key=ts)`, which is stable, so rows sharing a timestamp keep the order they were read in — insertion order, which is `id`. Two events inside the same second are not rare: a dispatch and its block land together all the time. Ordering by `id` alone would be right for one project and wrong for one that migrated from JSONL, where ids were assigned at import.
Sorted in Go on the parsed time, not with `ORDER BY ts`: migration 015 made every stored spelling canonical, but an older orch still running against the same file can write `+00:00` after it, and as text `...09:00:00Z` sorts after `...10:00:00+02:00`. The tail is cut after the sort, so it reads every row; a project's events are thousands, not millions.
func (*SQLite) AllSpend ¶
AllSpend returns every spend row newer than `since`, across every backend, oldest first. The zero Time means all of history.
`SpendSince` answers "what has this provider spent", which is the budget gate's question. This answers "what has been spent", which is the metrics page's — by model, by day, in total. Doing it per backend would be one query per name in a list this package would then have to keep current, and a row written by a backend nobody listed would silently stop counting.
Ordering matches `SpendSince`: by timestamp, then by task id, so two rows written in the same second land in a fixed order rather than SQLite's.
A row whose timestamp does not parse is DROPPED, not dated to the epoch. Same rule as `SpendSince`: a row that cannot be placed in time cannot honour a `since`, and counting it anyway would put spend in a window it may not belong to.
func (*SQLite) AppendEvent ¶
func (*SQLite) Attempts ¶ added in v0.31.0
Attempts returns every attempt of this project, oldest first.
func (*SQLite) Bootstrap ¶
Bootstrap seeds the project and its tasks.
Every insert is `INSERT OR IGNORE`, which is what makes re-running safe: tasks.json's `status` is used only on a task's very first insert. After that the database owns it, and a hand-edit of tasks.json cannot silently resurrect a finished task.
func (*SQLite) ClearDispatch ¶
func (*SQLite) CountDoneLastNDays ¶
CountDoneLastNDays counts tasks that FINISHED within the last n days. It is the numerator of velocity, and of every ETA the dashboard projects from it.
A deliberate divergence from Python (bug 21) ¶
Python counts `updated_at >= datetime('now', -N days)`, which is the row's mtime, not a completion. A task that finished three weeks ago and was edited yesterday counts as finished yesterday; a burst of edits on old rows reads as a productive week. Velocity is the one number in the dashboard that claims to be a measurement, and it was measuring touches.
This counts `finished_at`, falling back to `updated_at` only where `finished_at` is missing — rows written before the column was populated. Those rows keep the old, wrong-ish answer because there is nothing better to ask them; every row written since is counted by when the work actually finished.
`finished_at` holds the MOST RECENT entry into done, not the first (see Transition, where the order of the COALESCE arguments is deliberate and pinned by a Python-generated fixture). So a task re-opened and finished again counts ONCE, on the day it was finished the second time — which is the answer that keeps velocity meaning "work completed in this window".
Not fixed in Python: it would move the figures of every project on the legacy branch, and the migration is where the corrected version belongs.
The window is closed in Go, like every other window in this package ¶
The cutoff used to be `datetime('now', '-N days')`, which took it from SQLite's own clock and compared it as a string. Both halves were wrong:
- SQLite's clock is not `b.now()`, so a frozen clock could not move the window. The tests froze time at 2026-09-11 and the real clock walked past it, so on 2026-09-18 they started counting 0 — green in CI one week, red the next, with no commit in between.
- Stored timestamps come in two spellings (`Z` and `+00:00`), and "+" sorts before "Z", so a string cutoff silently drops rows written the other way. See ParseTS, which says the same thing about spend.
So the rows are read and dated in Go with ParseTS, against a cutoff from `b.now()` — one clock, one parser, no lexical comparison. A row whose timestamp ParseTS cannot read is not counted, the same choice SpendSince makes: an unreadable date cannot be placed inside a window. The table is one row per task, so reading them is not a cost worth a correctness risk.
func (*SQLite) Enqueue ¶ added in v0.31.0
Enqueue puts taskID in the merge queue at `at`, unless it is already queued; an entry merged or ejected before enters again, at the back. Reports whether it entered now.
func (*SQLite) Events ¶
Events returns a task's history oldest-first.
With a limit it returns the TAIL — the most recent n, still in chronological order. "Show me the last 5 events" means the newest five, and reading them forwards is how a human follows what happened.
func (*SQLite) EventsSince ¶
EventsSince returns events with an id greater than afterID, oldest first, at most limit rows (limit <= 0 means no cap).
This is what a live tail polls. It is keyed on the row ID, not on the timestamp, and that is a deliberate divergence from Python — see bug 25 in docs/brainstorm/go-migration-notes/opus.md.
Why not `ts > last_ts` ¶
Event timestamps have SECOND precision (`utcNow`, a format shared with scripts/task-*.sh, so it is a contract). Python's SQLite tailer remembers the last timestamp it delivered and polls `WHERE ts > last_ts`, which silently drops any event written in the same second as the last one delivered but after the poll that delivered it. A dispatch and the block it causes land in the same second all the time.
The id is monotonic and unique, so `id > afterID` has no such window: every row is delivered exactly once, whatever the clock's resolution.
func (*SQLite) FiledFindings ¶
func (b *SQLite) FiledFindings(ctx context.Context) ([]FiledFinding, error)
FiledFindings lists the issues this project's agents filed, newest first.
func (*SQLite) FirstEventBackend ¶
func (b *SQLite) FirstEventBackend(ctx context.Context, 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, by id: what the onboarding progress reads (#378) — "has this project ever dispatched", and with which CLI.
func (*SQLite) InFlightDispatches ¶
InFlightDispatches returns every dispatch this project still has marked in flight, across all runs, ordered by run then task.
The read half of RecordDispatch/ClearDispatch. `state.Backend` could write a dispatch and clear one but not see one, which is the third time the port has landed a writer without its reader — spend and runs were the first two, and each hole surfaced weeks later blocking a different lane.
What this deliberately does not do ¶
It does not probe whether the PIDs are alive, and it does not act on the answer. `reconcile_in_flight` in Python does all three inside one method; here the aliveness check and the orphan policy live in `internal/engine`, which is where the rest of the run loop's policy lives and where the queue that reverts a task's status already is. State says which rows exist; the engine decides what they mean.
A caller writing that check should know the probe has THREE outcomes, not two: ESRCH means the process is gone, EPERM means it is alive and owned by another user, and any other error means neither — skip the row rather than guess. Reading EPERM as "dead" would revert tasks whose processes are running perfectly well.
Rows are returned whatever their PID, including zero. A dispatch recorded without a usable PID is a real row that something has to decide about, and dropping it here would hide it from the only code that can.
func (*SQLite) IncrementCIAttempts ¶
IncrementCIAttempts bumps the retry counter and returns its new value.
Returning the new count is a deliberate difference from Python, which returns nothing and leaves the caller to reason about it. The retry branch there compares `ci_attempts` BEFORE incrementing and then emits an event carrying `ci_attempts + 1` — the number of the attempt just started, not the counter as stored. That arithmetic is done by hand at the call site and only goes wrong when `ci_max_retries > 1`, which is not the default, so an off-by-one there would sit unnoticed.
Handing back the post-increment value removes the hand arithmetic: it IS the number of the attempt that just started. The read and the write share one transaction, so a concurrent poller cannot see or skip a number.
func (*SQLite) LastEventByTask ¶
LastEventByTask returns the newest event for each of the given task ids.
One query, not one per id: the caller is the sprint page asking about every blocked task at once, and a project with thirty blockers would otherwise be thirty round trips to render one panel.
An empty id list returns an empty map without touching the database — that is a project with nothing blocked, which is the common case and does not deserve a query. A nil list means EVERY task, matching Python's `task_ids=None`.
"Newest" is by row id, not by timestamp. Two events written in the same second are ordered by insertion, and insertion order is the truth about which happened last; a timestamp comparison would pick one of them at random.
func (*SQLite) LatestEventID ¶
LatestEventID is the id of the newest event, or 0 for a project that has none.
A live tail starts here so it carries only what happens AFTER the client connected. Python starts from an empty timestamp, which replays the entire log as "new" on every connect — the SPA then deduplicates it against the history it already fetched, and the metrics page invalidates its task query once per replayed row.
func (*SQLite) LatestQuota ¶ added in v0.31.0
LatestQuota is the newest quota a backend reported in this project, from the extra.quota of its outcome events (#417, #577). ok is false when it never reported one.
func (*SQLite) LatestRun ¶
LatestRun returns the most recently started run, with its in-flight count.
ErrNoRuns when the project has never been run.
func (*SQLite) MarkMigrated ¶
MarkMigrated timestamps a one-shot file-to-sqlite import as done. Not part of the Backend interface for the same reason as MigratedAt, but a genuine method (not a raw connection `orch migrate` opens itself): rule 17 requires every write to go through the single writer pool, and this is the one write `orch migrate` needs beyond Bootstrap/AppendEvent/ RecordSpend.
func (*SQLite) MigratedAt ¶
MigratedAt returns the project's `projects.migrated_at` timestamp, or ("", nil) if the project has no row yet OR has one but was never migrated — both are the ordinary "not migrated" case, not an error a caller failed to check. A plain read, so it goes through the read pool like every other query in this file (rule 17 only constrains writes).
func (*SQLite) OrphanRows ¶
func (b *SQLite) OrphanRows(ctx context.Context) (OrphanRows, error)
OrphanRows finds rows whose project_id has no row in `projects`.
Read-only by design: it never deletes. Orphans mean somebody edited the database by hand or bootstrapped with a version that lacked FK enforcement, and in either case the operator has to look at the rows before losing them (F-9, issue #73).
func (*SQLite) ProviderStates ¶
func (b *SQLite) ProviderStates(ctx context.Context) ([]ProviderState, error)
ProviderStates lists this project's provider rows, by backend name.
func (*SQLite) QueueEntries ¶ added in v0.31.0
func (b *SQLite) QueueEntries(ctx context.Context) ([]QueueEntry, error)
QueueEntries lists this project's merge queue rows, oldest first.
func (*SQLite) QueueFinding ¶ added in v0.31.0
QueueFinding stores a report for the operator to review and returns its id.
func (*SQLite) QueuedFindings ¶ added in v0.31.0
func (b *SQLite) QueuedFindings(ctx context.Context) ([]QueuedFinding, error)
QueuedFindings lists this project's queued reports in every status, newest first.
func (*SQLite) RankKnowledge ¶
func (b *SQLite) RankKnowledge(ctx context.Context, docs []KnowledgeDoc, query string, limit int) ([]string, error)
RankKnowledge rebuilds the lesson index from docs and returns the ids of the lessons matching the FTS5 query, best BM25 first, at most limit. The files under .orch/knowledge/ are the truth and the index is their cache: rebuilding and querying in one transaction means a reader never ranks against another worktree's set of lessons.
ponytail: a full rebuild per search, fine for the tens to hundreds of lessons a project has; index incrementally (by file mtime) past that.
func (*SQLite) RecordAttempt ¶ added in v0.31.0
RecordAttempt appends one finished attempt.
func (*SQLite) RecordDispatch ¶
RecordDispatch marks a subprocess in flight. StartRun must have been called for d.RunID: `dispatches` references `runs`, and without the parent row SQLite reports a bare foreign-key failure that says nothing about what is missing.
func (*SQLite) RecordFiledFinding ¶
func (b *SQLite) RecordFiledFinding(ctx context.Context, f FiledFinding) error
RecordFiledFinding remembers an issue orch_report_finding filed.
func (*SQLite) RecordSpend ¶
RecordSpend appends a cost row, ignoring an exact duplicate.
The dedup hash is the compatibility-critical part — see dedup.go. Replaying a run after a crash must not double the reported spend, and the budget gate reads these rows.
func (*SQLite) Runs ¶
Runs returns every run for the project, newest first — what `orch status` and the dashboard list.
Sorted in Go rather than with `ORDER BY started_at DESC`, for the same reason SpendSince filters in Go: a lexical sort over mixed timestamp forms puts `+00:00` before `Z` regardless of the actual times. Python sorts in SQL here and would mis-order such a database; the rows in `runs` happen to be written by one call site today, but `spend` is the proof that "one call site" is not a guarantee across versions.
run_id breaks a tie. Two runs can share a started_at at second precision, and without a second key "latest" would vary between calls and `orch status` would flicker between them.
func (*SQLite) SetFindingStatus ¶ added in v0.31.0
SetFindingStatus records the operator's decision on a queued report: sent (with the issue's URL) or dismissed.
func (*SQLite) SetProviderState ¶
func (b *SQLite) SetProviderState(ctx context.Context, backend string, disabled bool, reason string, at time.Time) error
SetProviderState turns backend off (with the reason the operator gave) or back on for this project.
func (*SQLite) SetQueueState ¶ added in v0.31.0
func (b *SQLite) SetQueueState(ctx context.Context, taskID, state, reason string, at time.Time) error
SetQueueState moves taskID's queue entry to state (merged or ejected), with the reason; ejected also counts a requeue.
func (*SQLite) SetStakeholderToken ¶
func (b *SQLite) SetStakeholderToken(ctx context.Context, tokenHash string, rotatedAt time.Time) error
SetStakeholderToken stores a freshly rotated token's hash, replacing any row this project already had. tokenHash must be non-empty — an empty hash would mean "no token", which is what deleting the row (not this method) would express, and this method has no caller that means that.
func (*SQLite) SetTaskCIStatus ¶
SetTaskCIStatus records how a task's CI finished.
The value is checked here as well as by the schema's CHECK constraint. The constraint would catch it, but as a bare "constraint failed" naming neither the column nor what was allowed — and this is a string a caller composes, so a typo is the likely way it goes wrong.
func (*SQLite) SetTaskPR ¶
SetTaskPR records the pull request opened for a task AND marks its CI pending, in one write.
The second half is not incidental: `ci_status = 'pending'` is what puts the task into TasksWithPendingCI's filter, so a version of this that stored only the URL would open a PR nobody ever polls. Python does both in the same UPDATE for the same reason.
func (*SQLite) SpendSince ¶
SpendSince returns the spend rows for one backend newer than `since`, oldest first.
The signature mirrors what `budget.BudgetGate._entries_since` needs — a provider and a cutoff — rather than a general query, because the budget gate is the caller that matters and a rolling window is the only shape it asks for.
Python reads those rows from `state/spend-<date>.jsonl` and NOT from SQLite, which is why its budget gate sees nothing on a sqlite project and never trips (reported separately; the fix is in flight on the Python side). Go has one source of spend, so the class of bug cannot recur here: there is nowhere else for a spend row to hide.
The window is applied in Go, not with `ts >= ?` in SQL. See ParseTS for why: the stored timestamps are not in one canonical form, and a lexical comparison silently drops rows.
A row with an unparseable or empty ts is EXCLUDED rather than assumed recent. Both choices are wrong in some direction — excluding under-reports usage, including over-reports it and stalls dispatch on a guess — and this is the one Python makes, so the two agree about a database neither wrote cleanly.
func (*SQLite) StakeholderToken ¶
func (b *SQLite) StakeholderToken(ctx context.Context) (tokenHash string, rotatedAt time.Time, ok bool, err error)
StakeholderToken returns this project's stored token hash and when it was last rotated. ok is false when no row exists yet — a fresh project, or one that has never called `orch dashboard token rotate` — and the caller falls back to config.yaml/--token.
func (*SQLite) StartRun ¶
StartRun opens a run. Idempotent, so resuming an interrupted run with `--resume <id>` reattaches to the existing row instead of failing.
It seeds the `projects` row too. Python does the same in `create_run`, as a fallback for the case where bootstrap has not run — without it, a first dispatch fails on a foreign key with nothing useful in the message.
func (*SQLite) Tasks ¶
func (b *SQLite) Tasks(ctx context.Context, filter TaskFilter) ([]TaskRuntime, error)
func (*SQLite) TasksWithPendingCI ¶
func (b *SQLite) TasksWithPendingCI(ctx context.Context) ([]TaskRuntime, error)
TasksWithPendingCI returns the tasks whose PR is open and whose CI has not finished, ordered by task id.
Filtered on BOTH columns, which is the part that matters: a task with no PR has no CI to look at, and one whose CI already resolved must not come back round. Filtering on `ci_status` alone would feed the poller rows with an empty `pr_url` and it would ask the forge about a blank URL once per tick.
`pr_url IS NOT NULL AND pr_url != ""` — Python checks only the NULL, which is enough there because nothing writes the empty string. The extra clause costs nothing and removes a row that would otherwise be a silent no-op forever.
func (*SQLite) TotalSpendUSD ¶
TotalSpendUSD sums cost across every backend since `since`.
Separate from SpendSince because `orch status` wants one number across every provider, not a window per provider.
func (*SQLite) Transition ¶
Transition moves a task and records why.
Three things here are load-bearing, all of them learned the hard way:
- The read and the write are in ONE transaction. A check-then-write across two connections lets a concurrent transition slip between them and produce a move the table forbids.
- Legality comes from model.CanTransition, not a table copied into this file. One definition of what is legal, and it is the one verified against Python.
- A zero rowcount on the UPDATE is an error (F-13, issue #81). The SELECT above already proved the row exists, so this can only mean it vanished mid-transaction — and the caller must never print success for a write that did nothing.
type Spend ¶
type Spend struct {
ProjectID string // empty means "this backend's project"
TS string
TaskID string
Backend string
Model string
// TokensIn is every input token the dispatch processed, cache included.
TokensIn int
TokensOut int
// CacheReadTokens and CacheCreationTokens are the part of TokensIn that
// was read from or written to the prompt cache. The budget gate weights
// them; everything else reports TokensIn as is.
CacheReadTokens int
CacheCreationTokens int
// ReasoningTokens is the part of TokensOut the model spent reasoning, 0
// when the CLI does not say (#417).
ReasoningTokens int
// Attempt is the task's attempt this dispatch was; 0 on rows from before
// migration 008.
Attempt int
CostUSD float64
DurationS float64
// Estimated marks a row whose token counts orch inferred because the
// provider reported none. Downstream surfaces flag it so nobody reads
// an invented number as telemetry.
Estimated bool
}
Spend is one completed dispatch's cost.
CostUSD and DurationS feed the dedup hash through pyFloat, so their exact float values matter beyond arithmetic — see dedup.go.
type TaskFilter ¶
type TaskFilter struct {
// Statuses, when non-empty, restricts to those statuses.
Statuses []model.Status
// IDs, when non-empty, restricts to those task ids.
IDs []string
}
TaskFilter narrows a Tasks query. A zero filter returns every task in the project.
type TaskRuntime ¶
type TaskRuntime struct {
ID string
Status model.Status
// Comments are kept as raw JSON, matching model.Task: Python types them
// `list[dict]` with no fixed shape, so parsing them would only create a
// way to lose data.
Comments []json.RawMessage
StartedAt string // first transition into in-progress; empty if never
FinishedAt string // first transition into done; empty if never
UpdatedAt string
Attempts int
LastModel string
LastBackend string
// PR tracking (migration 005). Empty when the task has no PR.
PRURL string
CIStatus string
CIAttempts int
}
TaskRuntime is a task's mutable half — what the database owns. The static half (title, deps, estimate) lives in `tasks_definition` and mirrors tasks.json.
Since the SQLite backend became the source of truth (F-12), tasks.json is read for the DAG's shape and nothing else: its `status` field is ignored on every load after the first bootstrap.