store

package
v2.6.2 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 12 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 store is lectern's SQLite persistence layer: schema, typed row accessors, and the small JSON helpers the rest of the service shares.

Index

Constants

View Source
const DefaultCIMaxAttempts = 3

DefaultCIMaxAttempts is the fix-request cap a project gets when it has not set one (docs/ci-loop.md).

View Source
const Schema = `` /* 39736-byte string literal not displayed */

Schema is the whole database. Plain SQL, WAL, homelab scale, zero magic.

Variables

View Source
var ErrDuplicateEvent = errors.New("event already recorded")

ErrDuplicateEvent is returned by InsertTriggerEvent when this source has already recorded this external id — the whole point of the ledger: an event is never acted on twice.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned by the One* accessors when a row does not exist. It is deliberately distinct from sql.ErrNoRows so callers never have to import database/sql just to branch on "missing".

Functions

func J

func J(v any) string

J marshals to a compact JSON string for a *_json column.

func Median added in v2.4.0

func Median(rates []float64) float64

Median returns the middle value of a sorted copy of rates, 0 for an empty slice.

func Now

func Now() float64

Now is the float epoch seconds every timestamp column stores.

func UnjList

func UnjList(s string) []any

UnjList parses a *_json column into a list. diff_stat_json defaults to '{}' before a diff is captured, which parses as an object — returning an empty list there is what keeps a running card renderable.

func UnjObj

func UnjObj(s string) map[string]any

UnjObj parses a *_json column into an object, tolerating empty and malformed values — a bad blob must degrade a card, never take down the board.

It never returns nil, including for the literal "null", which unmarshals into a nil map without erroring. Callers write into the result (the scheduler adds an "error" key when finalising, and a "review" key when a reviewer gate lands), and writing to a nil map panics — inside the scheduler tick, which would stall every other running attempt.

func UnjStrings

func UnjStrings(s string) []string

UnjStrings parses a *_json column into a string list (context paths, labels).

Types

type Account added in v2.6.0

type Account struct {
	ID           int64    `json:"id"`
	TargetID     int64    `json:"target_id"`
	Agent        string   `json:"agent"`
	Label        string   `json:"label"`
	Dir          string   `json:"-"`
	Position     int      `json:"position"`
	LimitedAt    *float64 `json:"limited_at,omitempty"`
	LimitedUntil *float64 `json:"limited_until,omitempty"`
	CreatedAt    float64  `json:"created_at"`
	UpdatedAt    float64  `json:"updated_at"`
}

Account is one registered login of an agent CLI on a target — see schema.go's agent_accounts comment and docs/accounts.md. Dir is where its config and credentials live on the target; it never leaves the server: the API, relay clients and the chat connector only ever see the label.

func (*Account) Default added in v2.6.0

func (a *Account) Default() bool

Default reports whether this row stands for the CLI's own login (no config directory override).

type ActiveRate added in v2.4.0

type ActiveRate struct {
	Kind    string
	ID      int64
	Name    string
	Elapsed float64 // seconds
	Rate    float64 // USD per hour
}

ActiveRate is one currently-running session or task attempt's live spend rate — this run's own cost divided by its own elapsed hours so far.

type Approval

type Approval struct {
	ID        int64    `json:"id"`
	AttemptID int64    `json:"attempt_id,omitempty"`
	SessionID int64    `json:"session_id,omitempty"`
	ToolName  string   `json:"tool_name"`
	InputJSON string   `json:"-"`
	Status    string   `json:"status"`
	DecidedBy string   `json:"decided_by"`
	Note      string   `json:"note"`
	CreatedAt float64  `json:"created_at"`
	DecidedAt *float64 `json:"decided_at"`

	Input       map[string]any `json:"input"`
	TaskID      int64          `json:"task_id,omitempty"`
	AttemptN    int            `json:"attempt_n,omitempty"`
	TaskTitle   string         `json:"task_title,omitempty"`
	SessionName string         `json:"session_name,omitempty"`
}

Approval is one tool call a gated agent is blocked on. It belongs to exactly one of a task attempt (AttemptID) or an interactive session (SessionID) — docs/agent-events.md section 3. Both id fields keep the existing "0 means absent" convention TaskID already used, so nothing that already reads AttemptID as a plain int64 needs to change: the zero value only ever shows up on a session-scoped row, and the DB column underneath it is genuinely NULL there (see migrate_approvals.go) so foreign-key enforcement never sees a false attempt id 0.

type Attempt

type Attempt struct {
	ID            int64    `json:"id"`
	TaskID        int64    `json:"task_id"`
	N             int      `json:"n"`
	Status        string   `json:"status"`
	Token         string   `json:"token"`
	Prompt        string   `json:"prompt"`
	ResumeSession string   `json:"resume_session"`
	Model         string   `json:"model"`
	SandboxVMID   string   `json:"sandbox_vmid"`
	WorktreePath  string   `json:"worktree_path"`
	Branch        string   `json:"branch"`
	TmuxSession   string   `json:"tmux_session"`
	SessionID     string   `json:"session_id"`
	LogOffset     int64    `json:"log_offset"`
	StartedAt     *float64 `json:"started_at"`
	FinishedAt    *float64 `json:"finished_at"`
	ExitCode      *int     `json:"exit_code"`
	ResultJSON    string   `json:"result_json"`
	DiffStatJSON  string   `json:"diff_stat_json"`
	VerifyJSON    string   `json:"verify_json"`
	// MCPJSON and StrictMCP snapshot the project launch policy for takeover;
	// they are internal because MCP declarations can contain credentials.
	MCPJSON          string `json:"-"`
	StrictMCP        int    `json:"-"`
	MCPSnapshot      int    `json:"-"`
	LaunchConfigJSON string `json:"-"`
	// Driver is the internal/drivers.Kind chosen for this attempt at queue
	// time (e.g. "claude-exec", "claude-steer", "codex-appserver"), so later
	// workers and the UI can see and reuse the choice without re-deriving it
	// from the agent name and permission mode.
	Driver string `json:"driver"`
	// Agent and PermissionMode let a Best-of-N variant pick its own agent or
	// gating instead of inheriting the task's; empty means "use the task's"
	// (see scheduler.effAgent/effPermissionMode), which is what every
	// pre-existing single-attempt task and model-only A/B dispatch already is.
	Agent          string `json:"agent,omitempty"`
	PermissionMode string `json:"permission_mode,omitempty"`
	// LiveCostUSD (docs/budgets.md) is this attempt's own cumulative cost so
	// far, updated by the scheduler as it parses streamed 'result' events —
	// see the column's own comment in store/schema.go for why this exists
	// separately from ResultJSON, which only ever lands once, at finish.
	LiveCostUSD float64 `json:"live_cost_usd,omitempty"`
	// NotBefore holds a queued attempt back until its provider's usage limit
	// has reset (docs/rate-limits.md); nil promotes it as soon as a slot frees.
	NotBefore *float64 `json:"not_before,omitempty"`
	// AccountID is the registered login this attempt runs under (docs/accounts.md);
	// nil is the CLI's own default login.
	AccountID *int64 `json:"account_id,omitempty"`
}

Attempt is a single agent run against a task. Retries, follow-ups and the parallel B side of an A/B dispatch are all attempts.

type CIWatch added in v2.4.0

type CIWatch struct {
	ID          int64   `json:"id"`
	TaskID      *int64  `json:"task_id"`
	SessionID   *int64  `json:"session_id"`
	ProjectID   *int64  `json:"project_id"`
	TargetID    int64   `json:"target_id"`
	Branch      string  `json:"branch"`
	PRURL       string  `json:"pr_url"`
	State       string  `json:"state"`
	Attempts    int     `json:"attempts"`
	MaxAttempts int     `json:"max_attempts"`
	HeadSHA     string  `json:"head_sha"`
	AskedSHA    string  `json:"asked_sha"`
	FailingJSON string  `json:"-"`
	Detail      string  `json:"detail"`
	Errors      int     `json:"-"`
	IntervalS   float64 `json:"-"`
	NextPollAt  float64 `json:"next_poll_at"`
	// PushedAttemptID is the task fix attempt Lectern last committed and pushed.
	PushedAttemptID int64   `json:"-"`
	LastChangeAt    float64 `json:"last_change_at"`
	CreatedAt       float64 `json:"created_at"`
	UpdatedAt       float64 `json:"updated_at"`
}

CIWatch is one pull request the CI loop is watching — see the ci_watches table in schema.go and internal/ciloop.

type Claim added in v2.4.0

type Claim struct {
	ID         int64    `json:"id"`
	RepoKey    string   `json:"repo_key"`
	ScopeKind  string   `json:"scope_kind"`
	Scope      string   `json:"scope"`
	Holder     string   `json:"holder"`
	HolderKind string   `json:"holder_kind"`
	SessionID  *int64   `json:"session_id,omitempty"`
	AttemptID  *int64   `json:"attempt_id,omitempty"`
	Agent      string   `json:"agent,omitempty"`
	Intent     string   `json:"intent"`
	Auto       bool     `json:"auto"`
	CreatedAt  float64  `json:"created_at"`
	ExpiresAt  float64  `json:"expires_at"`
	ReleasedAt *float64 `json:"released_at,omitempty"`
	TTLSeconds float64  `json:"-"`
}

Claim is one entry on the Claim board (docs/claims.md, docs/agent-events.md "Cross-agent awareness"): a vendor-neutral record of who is doing what in a repository, so agents from different vendors — and humans — coordinate instead of duplicating work. See schema.go's claims table comment for the column-by-column contract.

type ConversationRef added in v2.4.0

type ConversationRef struct {
	ID, TargetID int64
	Agent        string
	CIDs         []string
}

ConversationRef is a session's bound native conversation, for telling which closed records a later session already continued.

type DB

type DB struct{ *sql.DB }

DB wraps the connection pool.

func Open

func Open(path string) (*DB, error)

Open creates (or migrates) the database at path.

The pragmas go through modernc's `_pragma=` DSN parameter: the cgo driver's `_journal_mode=`/`_busy_timeout=` spelling is silently IGNORED here, which leaves the database in rollback-journal mode with no busy timeout — writes then fail under any concurrency instead of waiting.

func (*DB) Account added in v2.6.0

func (db *DB) Account(id int64) (*Account, error)

Account fetches one account by id.

func (*DB) Accounts added in v2.6.0

func (db *DB) Accounts() ([]*Account, error)

Accounts lists every account, in rotation order per target and agent.

func (*DB) AccountsFor added in v2.6.0

func (db *DB) AccountsFor(targetID int64, agent string) ([]*Account, error)

AccountsFor lists one CLI's accounts on one target in rotation order.

func (*DB) ActiveClaims added in v2.4.0

func (db *DB) ActiveClaims(now float64) ([]*Claim, error)

ActiveClaims returns every un-released, unexpired claim across every repository — the board-wide list a human's Claims panel starts from before filtering by repo.

func (*DB) ActiveClaimsForAttempt added in v2.4.0

func (db *DB) ActiveClaimsForAttempt(attemptID int64, now float64) ([]*Claim, error)

ActiveClaimsForAttempt returns a task attempt's own active claims.

func (*DB) ActiveClaimsForRepo added in v2.4.0

func (db *DB) ActiveClaimsForRepo(repoKey string, now float64) ([]*Claim, error)

ActiveClaimsForRepo returns every un-released, unexpired claim in a repository, oldest first — what a briefing/warning/panel reads.

func (*DB) ActiveClaimsForSession added in v2.4.0

func (db *DB) ActiveClaimsForSession(sessionID int64, now float64) ([]*Claim, error)

ActiveClaimsForSession returns a session's own active claims.

func (*DB) ActiveHourlyRates added in v2.4.0

func (db *DB) ActiveHourlyRates(now, minSeconds float64) ([]ActiveRate, error)

ActiveHourlyRates computes a live $/hour for every live session and running task attempt that has spent something and run at least minSeconds — the anomaly check's other half (FinishedHourlyRates supplies the baseline this compares against).

func (*DB) AddAgentLineMarks added in v2.6.0

func (db *DB) AddAgentLineMarks(sessionID int64, path string, hashes []string) error

AddAgentLineMarks records hashes of lines an agent wrote into path (an absolute path on the session's target).

func (*DB) AgentLineMarkPaths added in v2.6.0

func (db *DB) AgentLineMarkPaths(sessionID int64, dir string) ([]string, error)

AgentLineMarkPaths lists the paths a session has marks for below dir (an absolute directory, without a trailing slash).

func (*DB) AgentLineMarks added in v2.6.0

func (db *DB) AgentLineMarks(sessionID int64, paths []string) (map[string]map[string]bool, error)

AgentLineMarks returns every recorded line hash for the given absolute paths, keyed by path.

func (*DB) AllTriggerSources added in v2.4.0

func (db *DB) AllTriggerSources() ([]*TriggerSource, error)

AllTriggerSources lists every configured source across every project — what the poller ticks over.

func (*DB) Approval

func (db *DB) Approval(id int64) (*Approval, error)

Approval fetches one approval by id, joined with its owning task or session — whichever of attempt_id/session_id is set (LEFT JOIN: the other side's columns come back NULL, per scanApproval).

func (*DB) ApprovalsByStatus

func (db *DB) ApprovalsByStatus(status string) ([]*Approval, error)

ApprovalsByStatus lists approvals in one state, newest first.

func (*DB) Attempt

func (db *DB) Attempt(id int64) (*Attempt, error)

Attempt fetches one attempt by id.

func (*DB) AttemptByToken

func (db *DB) AttemptByToken(token string) (*Attempt, error)

AttemptByToken resolves the per-attempt hook token an agent presents.

func (*DB) AttemptEnv added in v2.6.0

func (db *DB) AttemptEnv(attemptID int64) string

AttemptEnv is the environment a dispatch gave an attempt ("{}" when none).

func (*DB) AttemptsWhere

func (db *DB) AttemptsWhere(where string, args ...any) ([]*Attempt, error)

AttemptsWhere runs an arbitrary predicate against the attempts table.

func (*DB) BeginWorkspaceOperation

func (db *DB) BeginWorkspaceOperation(sessionID int64, oldPlan, newPlan string) (*WorkspaceOperation, error)

Reserve the operation and its intended allocation in one durable transaction.

func (*DB) CIWatch added in v2.4.0

func (db *DB) CIWatch(id int64) (*CIWatch, error)

CIWatch fetches one watch by id.

func (*DB) CIWatchByURL added in v2.4.0

func (db *DB) CIWatchByURL(url string) (*CIWatch, error)

CIWatchByURL fetches the watch for one pull request URL.

func (*DB) CancelWorkspaceOperation

func (db *DB) CancelWorkspaceOperation(id int64) error

func (*DB) Claim added in v2.4.0

func (db *DB) Claim(id int64) (*Claim, error)

Claim fetches one claim by id.

func (*DB) ClearAccountLimit added in v2.6.0

func (db *DB) ClearAccountLimit(id int64) error

ClearAccountLimit forgets an account's limit (it was seen working again).

func (*DB) ConversationRefs added in v2.4.0

func (db *DB) ConversationRefs() ([]ConversationRef, error)

ConversationRefs lists every session with a bound native conversation.

func (*DB) Count

func (db *DB) Count(table, where string, args ...any) (int, error)

Count runs a COUNT(*) with the given WHERE clause.

func (*DB) CountAgentLineMarks added in v2.6.0

func (db *DB) CountAgentLineMarks(sessionID int64) (int, error)

CountAgentLineMarks is how many line hashes a session has recorded at all — zero means its agent never reported an edit, so uncommitted lines cannot be attributed either way.

func (*DB) DefaultAccountFor added in v2.6.0

func (db *DB) DefaultAccountFor(targetID int64, agent string) (*Account, error)

DefaultAccountFor is the row standing for the CLI's own login on a target, or ErrNotFound when none is registered.

func (*DB) DeleteAccount added in v2.6.0

func (db *DB) DeleteAccount(id int64) error

DeleteAccount removes an account's record. Sessions that ran under it keep their account_id; they read as "unknown account" afterwards.

func (*DB) DeleteAgentLineMarks added in v2.6.0

func (db *DB) DeleteAgentLineMarks(sessionID int64, path string, hashes []string) error

DeleteAgentLineMarks drops the given hashes recorded for one path.

func (*DB) DeleteAgentLineMarksForPaths added in v2.6.0

func (db *DB) DeleteAgentLineMarksForPaths(sessionID int64, paths []string) error

DeleteAgentLineMarksForPaths drops every mark a session holds for these paths.

func (*DB) DeleteEvalCase added in v2.4.0

func (db *DB) DeleteEvalCase(id int64) error

func (*DB) DeleteEvalSuite added in v2.4.0

func (db *DB) DeleteEvalSuite(id int64) error

func (*DB) DeleteLaunchProfile

func (db *DB) DeleteLaunchProfile(id int64) error

func (*DB) DeleteMaterialization

func (db *DB) DeleteMaterialization(id int64) error

func (*DB) DeleteMedia

func (db *DB) DeleteMedia(id int64) error

func (*DB) DeletePlugin added in v2.6.0

func (db *DB) DeletePlugin(id string) error

DeletePlugin removes a row, its consent and its hook history.

func (*DB) DeletePluginSource added in v2.6.0

func (db *DB) DeletePluginSource(name string) error

func (*DB) DeleteProject added in v2.4.0

func (db *DB) DeleteProject(id int64) error

DeleteProject removes a project, its tasks and everything that references either, all or nothing: a failure part-way leaves the project exactly as it was. A project's skill materializations must already be cleaned up; if any are left, the foreign key fails and nothing is deleted.

func (*DB) DeleteProjectSkill

func (db *DB) DeleteProjectSkill(id int64) error

func (*DB) DeleteReviewComment added in v2.6.0

func (db *DB) DeleteReviewComment(id int64) error

DeleteReviewComment removes one comment.

func (*DB) DeleteTasks added in v2.4.0

func (db *DB) DeleteTasks(ids ...int64) error

DeleteTasks removes tasks and every row that references them or their attempts, all or nothing. Files and worktrees are the caller's.

func (*DB) DeleteTrackerConnection added in v2.6.0

func (db *DB) DeleteTrackerConnection(id int64) error

DeleteTrackerConnection removes one connection.

func (*DB) DeleteTriggerSource added in v2.4.0

func (db *DB) DeleteTriggerSource(id int64) error

DeleteTriggerSource removes a source and its event history.

func (*DB) DeleteUIPref added in v2.6.0

func (db *DB) DeleteUIPref(owner, key string) error

DeleteUIPref removes one preference; a missing row is not an error.

func (*DB) DueCIWatches added in v2.4.0

func (db *DB) DueCIWatches(now float64) ([]*CIWatch, error)

DueCIWatches lists active watches whose next poll time has passed.

func (*DB) DueRoutines

func (db *DB) DueRoutines(now float64) ([]*Routine, error)

DueRoutines returns the enabled, scheduled routines whose time has come.

func (*DB) EvalCase added in v2.4.0

func (db *DB) EvalCase(id int64) (*EvalCase, error)

func (*DB) EvalCases added in v2.4.0

func (db *DB) EvalCases(suiteID int64) ([]*EvalCase, error)

func (*DB) EvalResult added in v2.4.0

func (db *DB) EvalResult(id int64) (*EvalResult, error)

func (*DB) EvalResultByTaskID added in v2.4.0

func (db *DB) EvalResultByTaskID(taskID int64) (*EvalResult, error)

EvalResultByTaskID finds the cell one dispatched task belongs to — used by scheduler.applyEvalJudgeVerdict to find its way back from a headless judge task's ParentTaskID (the cell's own task id) to the eval_results row its verdict gets recorded on.

func (*DB) EvalResults added in v2.4.0

func (db *DB) EvalResults(runID int64) ([]*EvalResult, error)

EvalResults lists a run's cells, ordered so a matrix render can group by case then variant then repeat without re-sorting client-side.

func (*DB) EvalRun added in v2.4.0

func (db *DB) EvalRun(id int64) (*EvalRun, error)

func (*DB) EvalRuns added in v2.4.0

func (db *DB) EvalRuns(suiteID int64) ([]*EvalRun, error)

func (*DB) EvalSuite added in v2.4.0

func (db *DB) EvalSuite(id int64) (*EvalSuite, error)

func (*DB) EvalSuites added in v2.4.0

func (db *DB) EvalSuites(projectID int64) ([]*EvalSuite, error)

EvalSuites lists suites, optionally scoped to one project (projectID<=0 for all).

func (*DB) EventsInWindow added in v2.4.0

func (db *DB) EventsInWindow(sourceID int64, since float64) (int, error)

EventsInWindow counts this source's task_created events since `since` — the per-source rate limit's own counter.

func (*DB) Exists

func (db *DB) Exists(table, where string, args ...any) bool

Exists reports whether any row matches.

func (*DB) ExpireClaims added in v2.4.0

func (db *DB) ExpireClaims(now float64) (int64, error)

ExpireClaims releases every active claim whose expires_at has passed — the TTL-lapse half of auto-release. Returns how many were released, so a sweep can log something worth reading.

func (*DB) FinalizeTriggerEvent added in v2.4.0

func (db *DB) FinalizeTriggerEvent(id int64, action, reason string, taskID *int64) error

FinalizeTriggerEvent records the outcome of a reserved event: what happened (action/reason) and, when a task was created, its id.

func (*DB) FinishWorkspaceOperation

func (db *DB) FinishWorkspaceOperation(id int64, state, detail, actualPlan string) error

func (*DB) FinishedHourlyRates added in v2.4.0

func (db *DB) FinishedHourlyRates(startUnix, endUnix float64, minSeconds float64) ([]HourlyRateSample, error)

FinishedHourlyRates collects a per-hour spend rate for every session and task attempt that finished within [startUnix, endUnix) and ran at least minSeconds — too short a run makes an hourly rate meaningless (a five second attempt that cost $0.01 is not "$7.20/hour").

func (*DB) InsertAccount added in v2.6.0

func (db *DB) InsertAccount(a *Account) (*Account, error)

InsertAccount records a new account at the end of its rotation.

func (*DB) InsertApproval

func (db *DB) InsertApproval(attemptID int64, tool, inputJSON string) (int64, error)

InsertApproval records a tool call awaiting a decision, scoped to a task attempt.

func (*DB) InsertAttempt

func (db *DB) InsertAttempt(a *Attempt) (*Attempt, error)

InsertAttempt writes a new attempt and returns it with its assigned id.

func (*DB) InsertClaim added in v2.4.0

func (db *DB) InsertClaim(c *Claim) (*Claim, error)

InsertClaim creates a new claim. CreatedAt/ExpiresAt are expected to already be set by the caller (internal/claims computes them against its own TTL rules); Now() is not implicitly used here so a test can control both.

func (*DB) InsertEvalCase added in v2.4.0

func (db *DB) InsertEvalCase(c *EvalCase) (*EvalCase, error)

func (*DB) InsertEvalResult added in v2.4.0

func (db *DB) InsertEvalResult(r *EvalResult) (*EvalResult, error)

func (*DB) InsertEvalRun added in v2.4.0

func (db *DB) InsertEvalRun(r *EvalRun) (*EvalRun, error)

func (*DB) InsertEvalSuite added in v2.4.0

func (db *DB) InsertEvalSuite(e *EvalSuite) (*EvalSuite, error)

func (*DB) InsertEvent

func (db *DB) InsertEvent(attemptID int64, seq int64, typ string, payloadJSON string) error

InsertEvent appends one normalised agent event.

func (*DB) InsertLimitHold added in v2.4.0

func (db *DB) InsertLimitHold(h *LimitHold) (*LimitHold, bool, error)

InsertLimitHold records a new hold. At most one hold per session or attempt may be open (a partial unique index enforces it), so a detection that races another one returns the hold that won instead of an error.

func (*DB) InsertMedia

func (db *DB) InsertMedia(m *Media) (*Media, error)

func (*DB) InsertMemoryDelivery added in v2.4.0

func (db *DB) InsertMemoryDelivery(d MemoryDelivery) (*MemoryDelivery, error)

InsertMemoryDelivery records one delivery and returns the stored row.

func (*DB) InsertNote

func (db *DB) InsertNote(projectID int64, note string, attemptID *int64) (int64, error)

InsertNote records a durable project note left by an agent.

func (*DB) InsertPluginHookRun added in v2.6.0

func (db *DB) InsertPluginHookRun(r *PluginHookRun) error

func (*DB) InsertProject

func (db *DB) InsertProject(p *Project) (*Project, error)

InsertProject writes a new project and returns it with its assigned id.

func (*DB) InsertProjectSkill

func (db *DB) InsertProjectSkill(x *ProjectSkill) (*ProjectSkill, error)

func (*DB) InsertReviewComment added in v2.6.0

func (db *DB) InsertReviewComment(c *ReviewComment) (*ReviewComment, error)

InsertReviewComment stores a new draft comment.

func (*DB) InsertRoutine

func (db *DB) InsertRoutine(r *Routine) (*Routine, error)

InsertRoutine saves a new routine.

func (*DB) InsertSandbox added in v2.6.0

func (db *DB) InsertSandbox(b *Sandbox) (*Sandbox, error)

InsertSandbox records a sandbox that now exists.

func (*DB) InsertSession

func (db *DB) InsertSession(s *Session) (*Session, error)

InsertSession writes a new session row.

func (*DB) InsertSessionApproval added in v2.4.0

func (db *DB) InsertSessionApproval(sessionID int64, tool, inputJSON string) (int64, error)

InsertSessionApproval records a tool call awaiting a decision, scoped to an interactive session's PermissionRequest hook rather than a task attempt (docs/agent-events.md section 3). attempt_id is left NULL — see the package doc on Approval for why that is safe under foreign-key enforcement, unlike a 0 sentinel would be.

func (*DB) InsertSessionCheck added in v2.4.0

func (db *DB) InsertSessionCheck(c *SessionCheck) (*SessionCheck, error)

InsertSessionCheck records a new check row, normally in status "running" — the runner fills in the result with Update("session_checks", id, ...) once the command finishes, the same generic-Update pattern every other table uses.

func (*DB) InsertTarget

func (db *DB) InsertTarget(t *Target) (*Target, error)

InsertTarget writes a new target and returns it with its assigned id.

func (*DB) InsertTask

func (db *DB) InsertTask(t *Task) (*Task, error)

InsertTask writes a new task and returns it with its assigned id.

func (*DB) InsertTrackerConnection added in v2.6.0

func (db *DB) InsertTrackerConnection(c *TrackerConnection) (*TrackerConnection, error)

InsertTrackerConnection saves a new connection.

func (*DB) InsertTriggerEvent added in v2.4.0

func (db *DB) InsertTriggerEvent(e *TriggerEvent) (*TriggerEvent, error)

InsertTriggerEvent records one seen event. A second insert of the same (source_id, external_id) pair returns ErrDuplicateEvent instead of a row — dedup enforced by the database, not by a caller remembering to check first.

func (*DB) InsertTriggerSource added in v2.4.0

func (db *DB) InsertTriggerSource(s *TriggerSource) (*TriggerSource, error)

InsertTriggerSource saves a new source.

func (*DB) InsertWrap

func (db *DB) InsertWrap(w *Wrap) (int64, error)

InsertWrap records a handoff summary.

func (*DB) LatestAccountUsage added in v2.6.0

func (db *DB) LatestAccountUsage(targetID int64, agent string, accountID int64, dflt bool) (*Session, error)

LatestAccountUsage is the most recent statusline or rollout usage reading from any session that ran under the account (accountID 0 with dflt: the CLI's own login), or nil when none has reported one.

func (*DB) LatestAttempt

func (db *DB) LatestAttempt(taskID int64) (*Attempt, error)

LatestAttempt is the highest-numbered attempt of a task.

func (*DB) LatestCIWatch added in v2.4.0

func (db *DB) LatestCIWatch(column string, ownerID int64) (*CIWatch, error)

LatestCIWatch is the newest watch owned by a task (column "task_id") or a session ("session_id"); nil with no error when there is none.

func (*DB) LatestLimitHoldForSession added in v2.4.0

func (db *DB) LatestLimitHoldForSession(sessionID int64) (*LimitHold, error)

LatestLimitHoldForSession is the session's newest hold, open or not.

func (*DB) LatestLimitHoldForTask added in v2.4.0

func (db *DB) LatestLimitHoldForTask(taskID int64) (*LimitHold, error)

LatestLimitHoldForTask is the task's newest hold, open or not, for its card.

func (*DB) LatestSessionCheck added in v2.4.0

func (db *DB) LatestSessionCheck(sessionID int64) (*SessionCheck, error)

LatestSessionCheck is the most recent check for a session, of any status — what the fingerprint-skip compares against and what a session's card badge shows. Returns (nil, nil) when the session has never been checked.

func (*DB) LaunchProfile

func (db *DB) LaunchProfile(id int64) (*LaunchProfile, error)

func (*DB) LaunchProfiles

func (db *DB) LaunchProfiles() ([]*LaunchProfile, error)

func (*DB) LimitHold added in v2.4.0

func (db *DB) LimitHold(id int64) (*LimitHold, error)

LimitHold fetches one hold by id.

func (*DB) LimitHoldsAfter added in v2.6.0

func (db *DB) LimitHoldsAfter(after int64) ([]*LimitHold, error)

LimitHoldsAfter lists holds with an id above after, oldest first — how plugin hooks see each new limit hit once.

func (*DB) LimitPolicyJSON added in v2.4.0

func (db *DB) LimitPolicyJSON(scope string, scopeID int64) string

LimitPolicyJSON is the stored policy for one scope, or "" when none is set.

func (*DB) LiveSessionByTmux

func (db *DB) LiveSessionByTmux(name string) (int64, error)

LiveSessionByTmux resolves the session an agent is posting from. Tmux names are reused across a session's life only by that session, but an ended row can share one, so the live row wins and the newest breaks a tie.

func (*DB) LiveSessions

func (db *DB) LiveSessions() ([]*Session, error)

LiveSessions are the ones the poller still has to watch.

func (*DB) MarkAccountLimited added in v2.6.0

func (db *DB) MarkAccountLimited(id int64, at float64, until *float64) error

MarkAccountLimited records that an account hit its usage limit, with the reset when one is known (nil keeps "limited, reset unknown").

func (*DB) MarkBudgetAlertSent added in v2.4.0

func (db *DB) MarkBudgetAlertSent(scopeKey, periodKey string, threshold int) (bool, error)

MarkBudgetAlertSent records scope/period/threshold as notified, returning true only when THIS call is the one that recorded it — the UNIQUE index backing it is the actual dedup mechanism, so two concurrent callers (or a restart mid-period re-running the same check) can never double-send.

func (*DB) MarkPostback added in v2.4.0

func (db *DB) MarkPostback(id int64, status, note string) error

MarkPostback records the result of posting a trigger-created task's outcome back to its source (a PR link, a comment reply, or why it could not send).

func (*DB) MarkReviewCommentsSent added in v2.6.0

func (db *DB) MarkReviewCommentsSent(ids []int64, round int) error

MarkReviewCommentsSent moves the given comments to status "sent" in one round, all or nothing.

func (*DB) Materializations

func (db *DB) Materializations(attachmentID int64) ([]*SkillMaterialization, error)

func (*DB) MaterializationsAt

func (db *DB) MaterializationsAt(targetID int64, path string) ([]*SkillMaterialization, error)

func (*DB) MaxEventSeq

func (db *DB) MaxEventSeq(attemptID int64) (int64, error)

MaxEventSeq is the highest sequence number stored for an attempt.

func (*DB) MediaByID

func (db *DB) MediaByID(id int64) (*Media, error)

func (*DB) MediaList

func (db *DB) MediaList(sessionID int64, limit int) ([]*Media, error)

MediaList is newest first. sessionID 0 means every session.

func (*DB) MemoryDeliveriesForSession added in v2.4.0

func (db *DB) MemoryDeliveriesForSession(sessionID int64, limit int) ([]*MemoryDelivery, error)

MemoryDeliveriesForSession lists what a session's agent was given, newest first. A limit of zero or less means no limit.

func (*DB) MemoryDeliveriesForTask added in v2.4.0

func (db *DB) MemoryDeliveriesForTask(taskID int64, limit int) ([]*MemoryDelivery, error)

MemoryDeliveriesForTask lists what every attempt of one task was given, newest first. The attempt each delivery went to is on the row, so an operator looking at a re-dispatched task can still tell them apart.

func (*DB) NoteWorkspaceOperation

func (db *DB) NoteWorkspaceOperation(id int64, detail string) error

func (*DB) OneAttemptWhere

func (db *DB) OneAttemptWhere(where string, args ...any) (*Attempt, error)

OneAttemptWhere returns the first matching attempt, or ErrNotFound.

func (*DB) OpenLimitHoldForAttempt added in v2.4.0

func (db *DB) OpenLimitHoldForAttempt(attemptID int64) (*LimitHold, error)

OpenLimitHoldForAttempt is the attempt's unresolved hold, or ErrNotFound.

func (*DB) OpenLimitHoldForSession added in v2.4.0

func (db *DB) OpenLimitHoldForSession(sessionID int64) (*LimitHold, error)

OpenLimitHoldForSession is the session's unresolved hold, or ErrNotFound.

func (*DB) OpenLimitHolds added in v2.4.0

func (db *DB) OpenLimitHolds() ([]*LimitHold, error)

OpenLimitHolds lists every unresolved hold, oldest first.

func (*DB) OtelAttemptUsageRow added in v2.4.0

func (db *DB) OtelAttemptUsageRow(attemptID int64) (*OtelAttemptUsage, error)

OtelAttemptUsageRow reads one attempt's OTel reading, if any — nil, nil when the attempt's agent never reported in over OTLP.

func (*DB) OtelAttemptUsageSince added in v2.4.0

func (db *DB) OtelAttemptUsageSince(cutoff float64) (map[int64]*OtelAttemptUsage, error)

OtelAttemptUsageSince lists every attempt's OTel reading updated at or after cutoff — internal/outcomes' bulk read for Rebuild, one query instead of one per attempt.

func (*DB) OutcomeFactsSince added in v2.4.0

func (db *DB) OutcomeFactsSince(cutoffDate string) ([]*OutcomeFact, error)

OutcomeFactsSince lists every fact dated at or after cutoffDate (a UTC yyyy-mm-dd string, inclusive) — the read half of GET /api/outcomes.

func (*DB) PendingPostbackEvents added in v2.4.0

func (db *DB) PendingPostbackEvents() ([]*TriggerEvent, error)

PendingPostbackEvents lists events that created a task which has since left queued/running, but nothing has been posted back to the source yet.

func (*DB) Plugin added in v2.6.0

func (db *DB) Plugin(id string) (*Plugin, error)

Plugin returns one row, or ErrNotFound.

func (*DB) PluginHookRuns added in v2.6.0

func (db *DB) PluginHookRuns(pluginID string, limit int) ([]*PluginHookRun, error)

func (*DB) PluginSources added in v2.6.0

func (db *DB) PluginSources() ([]*PluginSource, error)

func (*DB) Plugins added in v2.6.0

func (db *DB) Plugins() ([]*Plugin, error)

Plugins lists every plugin row.

func (*DB) Project

func (db *DB) Project(id int64) (*Project, error)

Project fetches one project by id.

func (*DB) ProjectForAttempt

func (db *DB) ProjectForAttempt(attemptID int64) (*Project, error)

ProjectForAttempt resolves the project an attempt is running for.

func (*DB) ProjectForTask

func (db *DB) ProjectForTask(taskID int64) (*Project, error)

ProjectForTask resolves the project a task belongs to.

func (*DB) ProjectNotes

func (db *DB) ProjectNotes(projectID int64, limit int) ([]*Memory, error)

ProjectNotes lists a project's agent-written notes, newest first.

func (*DB) ProjectSkill

func (db *DB) ProjectSkill(id int64) (*ProjectSkill, error)

func (*DB) ProjectSkills

func (db *DB) ProjectSkills(projectID int64, agent string) ([]*ProjectSkill, error)

func (*DB) Projects

func (db *DB) Projects() ([]*Project, error)

Projects lists projects joined with their target's name and kind.

func (*DB) PromoteNewProjectAndBind

func (db *DB) PromoteNewProjectAndBind(ctx context.Context, p *Project, sessionID int64, tmux, originalBoot, boot, originalTracking, newTracking, cid, launchConfig string) (*Project, error)

PromoteNewProjectAndBind atomically creates a project and binds one exact live session. A stale preview cannot leave an orphan project behind.

func (*DB) PruneBudgetAlerts added in v2.4.0

func (db *DB) PruneBudgetAlerts(beforeUnix float64) error

PruneBudgetAlerts drops dedup rows older than the given cutoff — they exist only to block a resend within their own now-passed period, so nothing reads them again once that period is long gone.

func (*DB) PruneEndedAgentLineMarks added in v2.6.0

func (db *DB) PruneEndedAgentLineMarks(cutoff float64) (int64, error)

PruneEndedAgentLineMarks drops the marks of sessions that ended before cutoff (epoch seconds); attribution is only ever asked of a live diff.

func (*DB) PruneSessionFileEdits added in v2.4.0

func (db *DB) PruneSessionFileEdits(before float64) error

PruneSessionFileEdits deletes edit records older than `before` — run opportunistically on every write (internal/awareness), matching the "plain SQL, homelab scale" philosophy elsewhere in this store rather than standing up a separate janitor goroutine for one small table.

func (*DB) RecentClosedSessions

func (db *DB) RecentClosedSessions(limit int) ([]*Session, error)

RecentClosedSessions returns the newest ended, non-archived interactive records. Ordering by ended_at preserves the operator's actual recent history; session IDs are allocation order and can be misleading after long uptime.

func (*DB) RecentLimitHolds added in v2.4.0

func (db *DB) RecentLimitHolds(limit int) ([]*LimitHold, error)

RecentLimitHolds lists the newest holds, open or resolved.

func (*DB) RecentTriggerEvents added in v2.4.0

func (db *DB) RecentTriggerEvents(projectID int64, limit int) ([]*TriggerEvent, error)

RecentTriggerEvents lists a project's last N events across all its sources, newest first — what the settings UI shows next to each source.

func (*DB) RecordPoll added in v2.4.0

func (db *DB) RecordPoll(id int64, cursorJSON, status, lastError string) error

RecordPoll updates a source's polling state after one poll attempt: the cursor it should resume from, whether it succeeded, and why if not.

func (*DB) RelaunchedSessions added in v2.4.0

func (db *DB) RelaunchedSessions(since float64) ([]*Session, error)

RelaunchedSessions lists sessions restart recovery relaunched after since, newest first.

func (*DB) ReleaseClaim added in v2.4.0

func (db *DB) ReleaseClaim(id int64, at float64) error

ReleaseClaim marks one claim released, unless it already was.

func (*DB) ReleaseClaimsForAttempt added in v2.4.0

func (db *DB) ReleaseClaimsForAttempt(attemptID int64, at float64) (int64, error)

ReleaseClaimsForAttempt releases every active claim a task attempt holds.

func (*DB) ReleaseClaimsForSession added in v2.4.0

func (db *DB) ReleaseClaimsForSession(sessionID int64, at float64) (int64, error)

ReleaseClaimsForSession releases every active claim a session holds — a session ending (docs/claims.md) or an explicit "release all" call.

func (*DB) ReleaseDeadSessionClaims added in v2.4.0

func (db *DB) ReleaseDeadSessionClaims(now float64) (int64, error)

ReleaseDeadSessionClaims releases every claim held by a session that has ended (agent_state='ended', the SessionEnd hook's mapping) or gone dead (the older screen-scraped status column) — a belt-and-braces sweep for the case the immediate SessionEnd-hook release (internal/api's hook handler) never fires, e.g. a tmux session killed outright.

func (*DB) ReleaseFinishedAttemptClaims added in v2.4.0

func (db *DB) ReleaseFinishedAttemptClaims(now float64) (int64, error)

ReleaseFinishedAttemptClaims releases every claim held by an attempt whose task attempt is no longer queued/running — the "auto-release ... when a task attempt finishes" clause in docs/claims.md.

func (*DB) RenewClaim added in v2.4.0

func (db *DB) RenewClaim(id int64, expiresAt float64) error

RenewClaim extends one claim's expiry — the TTL is "renewed by activity" clause in docs/claims.md.

func (*DB) RenewClaimsForSession added in v2.4.0

func (db *DB) RenewClaimsForSession(sessionID int64, now float64) (int64, error)

RenewClaimsForSession extends every active claim a session holds by that claim's own ttl_seconds — called on hook activity (PreToolUse/PostToolUse/ UserPromptSubmit) so a working session's claims never lapse mid-task.

func (*DB) ReopenedAs added in v2.4.0

func (db *DB) ReopenedAs() (map[int64]int64, error)

ReopenedAs maps each record Restore replaced to the session it started.

func (*DB) ReserveTriggerEvent added in v2.4.0

func (db *DB) ReserveTriggerEvent(sourceID, projectID int64, externalID, kind, author, summary, rawJSON string) (int64, error)

ReserveTriggerEvent claims (source_id, external_id) before any decision is made about it, so a redelivery is refused before it can ever cause a second CreateTask call — not just recorded after the fact. Returns the reserved row's id, or ErrDuplicateEvent if another call already claimed it. Callers finish the row with FinalizeTriggerEvent once they know the outcome.

func (*DB) RestorableSessions added in v2.4.0

func (db *DB) RestorableSessions(limit int) ([]*Session, error)

RestorableSessions returns every record Restore can offer, newest first: ended ones (archived included) except launches that never started, and live rows a restart left interrupted. A row from before end_reason existed that never showed a screen or bound a conversation is a launch that never started, and is left out too.

func (*DB) ReviewComment added in v2.6.0

func (db *DB) ReviewComment(id int64) (*ReviewComment, error)

ReviewComment fetches one comment.

func (*DB) ReviewComments added in v2.6.0

func (db *DB) ReviewComments(sessionID int64) ([]*ReviewComment, error)

ReviewComments lists a session's comments, oldest first.

func (*DB) ReviewFileMarks added in v2.6.0

func (db *DB) ReviewFileMarks(sessionID int64) ([]ReviewFileMark, error)

ReviewFileMarks lists the files a session's reviewer marked viewed.

func (*DB) Routine

func (db *DB) Routine(id int64) (*Routine, error)

Routine fetches one by id.

func (*DB) Routines

func (db *DB) Routines() ([]*Routine, error)

Routines lists every saved routine, newest first.

func (*DB) Sandbox added in v2.6.0

func (db *DB) Sandbox(id int64) (*Sandbox, error)

Sandbox fetches one sandbox record.

func (*DB) SandboxForAttempt added in v2.6.0

func (db *DB) SandboxForAttempt(attemptID int64) (*Sandbox, error)

SandboxForAttempt is the live sandbox an attempt runs in, if any.

func (*DB) Sandboxes added in v2.6.0

func (db *DB) Sandboxes(includeDestroyed bool) ([]*Sandbox, error)

Sandboxes lists sandboxes, live ones first, newest first.

func (*DB) SaveLaunchProfile

func (db *DB) SaveLaunchProfile(p *LaunchProfile) (*LaunchProfile, error)

func (*DB) SavePlugin added in v2.6.0

func (db *DB) SavePlugin(p *Plugin) error

SavePlugin inserts or replaces a row whole.

func (*DB) SavePluginSource added in v2.6.0

func (db *DB) SavePluginSource(s *PluginSource) error

func (*DB) ScratchSessions

func (db *DB) ScratchSessions() ([]*ScratchSession, error)

ScratchSessions lists every session, ended ones included: an ended session is what makes a directory's history knowable.

func (*DB) Session

func (db *DB) Session(id int64) (*Session, error)

Session fetches one session by id.

func (*DB) SessionByTmux

func (db *DB) SessionByTmux(targetID int64, tmuxName string) (*Session, error)

SessionByTmux finds a live session by its tmux name on a target. Discovery uses it to tell "already adopted" from "new to us".

func (*DB) SessionCheck added in v2.4.0

func (db *DB) SessionCheck(id int64) (*SessionCheck, error)

SessionCheck fetches one check by id.

func (*DB) SessionChecks added in v2.4.0

func (db *DB) SessionChecks(sessionID int64, limit int) ([]*SessionCheck, error)

SessionChecks lists a session's checks, newest first.

func (*DB) SessionFileEditsFor added in v2.4.0

func (db *DB) SessionFileEditsFor(sessionID int64, since float64) ([]*SessionFileEdit, error)

SessionFileEditsFor returns one session's own recent file edits, newest first — what a card's "edited N files recently" summary reads.

func (*DB) SessionFileEditsForRepo added in v2.4.0

func (db *DB) SessionFileEditsForRepo(repoKey string, since float64) ([]*SessionFileEdit, error)

SessionFileEditsForRepo returns every file edit in a repo (across every session that has ever worked in it, live or not — the caller filters to live peers) at or after `since`, newest first. Used to build a session's peer summary: "who else touched what, recently".

func (*DB) SessionFileEditsSince added in v2.4.0

func (db *DB) SessionFileEditsSince(since float64) ([]*SessionFileEdit, error)

SessionFileEditsSince returns every session's file edits at or after `since`, newest first — one query for a whole session list's overlap chips (awareness.Overlaps) instead of one per row and peer.

func (*DB) SessionWorkdir

func (db *DB) SessionWorkdir(targetID int64, path string) bool

Session workspaces remain the operator's even after a terminal is closed.

func (*DB) SessionWraps

func (db *DB) SessionWraps(sessionID int64) ([]*Wrap, error)

SessionWraps lists the handoffs a single session produced.

func (*DB) Sessions

func (db *DB) Sessions(includeEnded bool) ([]*Session, error)

Sessions lists sessions newest first, joined with their project and target. `includeEnded` brings back the ones whose process is gone — the record is the point, so a dead session is still worth showing until it is dismissed.

func (*DB) SetAttemptEnv added in v2.6.0

func (db *DB) SetAttemptEnv(attemptID int64, envJSON string) error

SetAttemptEnv stores a dispatch's own environment for one attempt.

func (*DB) SetLimitPolicyJSON added in v2.4.0

func (db *DB) SetLimitPolicyJSON(scope string, scopeID int64, raw string) error

SetLimitPolicyJSON stores (or, with an empty value, clears) one scope's policy.

func (*DB) SetReviewFileMark added in v2.6.0

func (db *DB) SetReviewFileMark(sessionID int64, repo, path, fingerprint string) error

SetReviewFileMark marks a file viewed at fingerprint, or clears the mark when fingerprint is empty.

func (*DB) SetSandboxStatus added in v2.6.0

func (db *DB) SetSandboxStatus(id int64, status string) error

SetSandboxStatus moves a sandbox to a new state; "destroyed" also stamps it.

func (*DB) SetSetting

func (db *DB) SetSetting(key, value string) error

SetSetting upserts one settings row.

func (*DB) SetUIPref added in v2.6.0

func (db *DB) SetUIPref(owner, key, value string) (float64, error)

SetUIPref upserts one preference.

func (*DB) Setting

func (db *DB) Setting(key string) string

Setting reads one settings row, returning "" when unset.

func (*DB) SpendByAgent added in v2.4.0

func (db *DB) SpendByAgent(startUnix float64) (map[string]float64, error)

SpendByAgent buckets the same two sources (usage_daily sessions, finished task attempts) by agent, for per-agent budgets and the Usage page's bars.

func (*DB) SpendSince added in v2.4.0

func (db *DB) SpendSince(startUnix float64, agent string) (float64, error)

SpendSince sums cost across usage_daily (interactive sessions) and finished task attempts from startUnix (inclusive) through now, optionally narrowed to one agent ("" = every agent). The session half is day-granular — like GET /api/usage before it, usage_daily has no per-row timestamp, only a date bucket, so a startUnix that falls mid-day is rounded down to that day's start.

func (*DB) Takeover

func (db *DB) Takeover(taskID int64) (*Takeover, error)

func (*DB) Target

func (db *DB) Target(id int64) (*Target, error)

Target fetches one target by id.

func (*DB) TargetByName

func (db *DB) TargetByName(name string) (*Target, error)

TargetByName fetches one target by its unique name.

func (*DB) Targets

func (db *DB) Targets() ([]*Target, error)

Targets lists every target, name-ordered — the order the UI renders.

func (*DB) Task

func (db *DB) Task(id int64) (*Task, error)

Task fetches one task by id.

func (*DB) TaskAttempts

func (db *DB) TaskAttempts(taskID int64) ([]*Attempt, error)

TaskAttempts lists a task's attempts oldest first.

func (*DB) TaskEvents

func (db *DB) TaskEvents(taskID int64, afterSeq int64, attemptN *int) ([]*Event, error)

TaskEvents returns a task's timeline, optionally one attempt's slice of it and optionally only what follows a sequence number (SSE catch-up).

func (*DB) TaskMessages

func (db *DB) TaskMessages(taskID int64) ([]*TaskMessage, error)

func (*DB) Tasks

func (db *DB) Tasks(f TaskFilter) ([]*Task, error)

Tasks lists the board in render order: priority first, then most recent.

func (*DB) TasksWhere

func (db *DB) TasksWhere(where string, args ...any) ([]*Task, error)

TasksWhere runs an arbitrary predicate against the tasks table. Used by the scheduler for the handful of queries that don't fit TaskFilter.

func (*DB) TrackerConnection added in v2.6.0

func (db *DB) TrackerConnection(id int64) (*TrackerConnection, error)

TrackerConnection reads one connection.

func (*DB) TrackerConnections added in v2.6.0

func (db *DB) TrackerConnections(projectID int64) ([]*TrackerConnection, error)

TrackerConnections lists a project's connections, oldest first.

func (*DB) TransitionLimitHold added in v2.4.0

func (db *DB) TransitionLimitHold(id int64, fromState string, fields map[string]any) (bool, error)

TransitionLimitHold is the compare-and-swap every automatic action goes through: it applies fields only if the hold is still open and still in fromState, and reports whether this caller won. Two Lectern processes, or one process before and after a restart, can therefore never both act on the same hold state.

func (*DB) TriggerEvent added in v2.4.0

func (db *DB) TriggerEvent(id int64) (*TriggerEvent, error)

TriggerEvent fetches one event by id.

func (*DB) TriggerSource added in v2.4.0

func (db *DB) TriggerSource(id int64) (*TriggerSource, error)

TriggerSource fetches one source by id.

func (*DB) TriggerSources added in v2.4.0

func (db *DB) TriggerSources(projectID int64) ([]*TriggerSource, error)

TriggerSources lists every configured source for one project, newest first.

func (*DB) UIPrefCount added in v2.6.0

func (db *DB) UIPrefCount(owner string) (int, error)

UIPrefCount is how many keys the owner has, for the per-owner cap.

func (*DB) UIPrefs added in v2.6.0

func (db *DB) UIPrefs(owner string) ([]UIPref, error)

UIPrefs returns every preference the owner has stored.

func (*DB) Update

func (db *DB) Update(table string, id int64, fields map[string]any) error

Update sets the given columns on one row by id. Column names come only from call sites in this repo, never from request data.

func (*DB) UpsertCIWatch added in v2.4.0

func (db *DB) UpsertCIWatch(w *CIWatch) (*CIWatch, error)

UpsertCIWatch starts watching w.PRURL. A PR already being watched keeps its row and counters but is polled again straight away: arming comes right after a push, so its backoff is stale. One whose watch had finished is re-armed from scratch, since a new push to a closed-out PR is a new round.

func (*DB) UpsertEstimatedUsageDelta added in v2.4.0

func (db *DB) UpsertEstimatedUsageDelta(date string, sessionID int64, agent, model string, estimatedUSD float64, inputTokens, outputTokens int) error

UpsertEstimatedUsageDelta is UpsertUsageDelta for a slice whose cost was estimated from the model price table (an agent that reports tokens only). The estimate is added to cost_usd, so budgets and totals include it, and to estimated_usd, so readers can label it.

func (*DB) UpsertMaterialization

func (db *DB) UpsertMaterialization(x *SkillMaterialization) error

func (*DB) UpsertOtelAttemptUsage added in v2.4.0

func (db *DB) UpsertOtelAttemptUsage(attemptID int64, model string, costUSD float64,
	inputTokens, outputTokens, linesAdded, linesRemoved, pullRequests, commits int64, at float64) error

UpsertOtelAttemptUsage overwrites the latest OTLP metrics reading for one headless task attempt (see schema.go's otel_attempt_usage comment). Unlike UpsertUsageDelta this is NOT additive: a Claude Code OTLP export reports cumulative totals for the whole attempt process, and the attempt's process is short-lived and never resumed, so the newest export is simply the most accurate one — there is no baseline to diff against and nothing to double count.

func (*DB) UpsertOutcomeFact added in v2.4.0

func (db *DB) UpsertOutcomeFact(f *OutcomeFact) error

UpsertOutcomeFact writes or replaces the one fact row for (scope, ref_id). Rebuild calls this once per attempt/session it recomputes; a stale row for a ref no longer in the recomputed window simply ages out of every query that filters by `date`, so nothing here needs to delete it.

func (*DB) UpsertSessionFileEdit added in v2.4.0

func (db *DB) UpsertSessionFileEdit(sessionID int64, repoKey, relPath string, at float64) error

UpsertSessionFileEdit records (or refreshes) the latest edit time for one (session, rel_path) pair. ON CONFLICT keeps exactly one row per file per session — a file touched five times in a row is one row with a moving timestamp, not five.

func (*DB) UpsertUsageDelta added in v2.4.0

func (db *DB) UpsertUsageDelta(date string, sessionID int64, agent, model string, costUSD float64, inputTokens, outputTokens int) error

UpsertUsageDelta accumulates one incremental slice of usage into today's usage_daily bucket for a session. Callers pass DELTAS, already computed against whatever baseline they track (see internal/agentevents), never the agent's raw cumulative totals — this function has no way to tell a repeat call from a genuinely new one, so double-counting is the caller's to avoid. A no-op delta is skipped so an idle session's repeated statusline pings don't grow the table for nothing.

func (*DB) UsageDailySessionEstimated added in v2.4.0

func (db *DB) UsageDailySessionEstimated(sessionID int64) (usd float64, err error)

UsageDailySessionEstimated sums the estimated cost already booked for a session, the baseline a cumulative price estimate is diffed against.

func (*DB) UsageDailySessionTotals added in v2.4.0

func (db *DB) UsageDailySessionTotals(sessionID int64) (inputTokens, outputTokens int, err error)

UsageDailySessionTotals sums every usage_daily row ever booked for a session (across all dates), so a delta source with no cumulative field of its own — Claude's statusline reports request-footprint, not a running total; see agentevents.IngestStatusline — has a persistent baseline to diff against without needing its own tracking column.

func (*DB) WakeCIWatches added in v2.4.0

func (db *DB) WakeCIWatches(column string, ownerID int64, now float64) error

WakeCIWatches makes an owner's active watches (column "task_id" or "session_id") due now with their backoff reset — Lectern just pushed to the branch, so a new commit is about to show up on the PR.

func (*DB) WorkspaceOperation

func (db *DB) WorkspaceOperation(id int64) (*WorkspaceOperation, error)

func (*DB) WorkspaceOperations

func (db *DB) WorkspaceOperations(sessionID int64, activeOnly bool) ([]*WorkspaceOperation, error)

func (*DB) WrapPredecessor added in v2.4.0

func (db *DB) WrapPredecessor(sessionID int64) (*Wrap, error)

WrapPredecessor returns the newest wrap that started this session, so a successor can point back at the conversation that handed the work over.

func (*DB) Wraps

func (db *DB) Wraps(projectID int64, limit int) ([]*Wrap, error)

Wraps lists a project's handoffs, newest first — the thread of a long project across every context that has worked on it.

type EvalCase added in v2.4.0

type EvalCase struct {
	ID             int64  `json:"id"`
	SuiteID        int64  `json:"suite_id"`
	Name           string `json:"name"`
	Prompt         string `json:"prompt"`
	BaseRef        string `json:"base_ref"`
	CheckCommand   string `json:"check_command"`
	TimeoutS       int    `json:"timeout_s"`
	SetupCommand   string `json:"setup_command"`
	IsReplay       bool   `json:"is_replay"`
	SourcePRNumber int    `json:"source_pr_number,omitempty"`
	ReferenceDiff  string `json:"-"`
}

EvalCase is one scenario in a suite: a prompt run from base_ref and graded by check_command (falling back to the project's own VerifyCmd when empty).

IsReplay/SourcePRNumber/ReferenceDiff are set only for a "replay eval" case built from the project's own merged-PR history (docs/replay-evals.md, internal/replay) — an ordinary hand-written or YAML-imported case leaves all three at their zero value. ReferenceDiff is intentionally excluded from JSON (it can be large, and every response that lists cases would otherwise carry it); the API layer computes a split, display-ready ReferenceFiles view only where a case is actually being shown (see internal/api/evals.go's replayCaseView).

type EvalResult added in v2.4.0

type EvalResult struct {
	ID              int64    `json:"id"`
	RunID           int64    `json:"run_id"`
	CaseID          int64    `json:"case_id"`
	VariantIdx      int      `json:"variant_idx"`
	RepeatIdx       int      `json:"repeat_idx"`
	TaskID          *int64   `json:"task_id"`
	AttemptID       *int64   `json:"attempt_id"`
	Status          string   `json:"status"`
	DurationS       *float64 `json:"duration_s"`
	CostUSD         *float64 `json:"cost_usd"`
	InputTokens     *int     `json:"input_tokens"`
	OutputTokens    *int     `json:"output_tokens"`
	DiffFiles       *int     `json:"diff_files"`
	DiffLines       *int     `json:"diff_lines"`
	CheckRC         *int     `json:"check_rc"`
	CheckOutputTail string   `json:"check_output_tail"`
	SimilarityFiles *float64 `json:"similarity_files"`
	SimilarityLines *float64 `json:"similarity_lines"`
	SizeRatio       *float64 `json:"size_ratio"`
	JudgeStatus     string   `json:"judge_status"`
	JudgeMatch      *int     `json:"judge_match"` // nil = not judged, 0 = no_match, 1 = match
	JudgeReason     string   `json:"judge_reason"`
}

EvalResult is one cell of a run's matrix: one case, one variant, one repeat. The Similarity*/SizeRatio/Judge* fields are populated only for a replay case's cell (see internal/replay.Score and gradeEvalResult in internal/api/evals_engine.go); they stay nil/empty for an ordinary case, which has no reference diff to score against.

type EvalRun added in v2.4.0

type EvalRun struct {
	ID           int64   `json:"id"`
	SuiteID      int64   `json:"suite_id"`
	CreatedAt    float64 `json:"created_at"`
	Status       string  `json:"status"`
	VariantsJSON string  `json:"-"`
	Repeats      int     `json:"repeats"`
	Notes        string  `json:"notes"`
	WithJudge    bool    `json:"with_judge"`
}

EvalRun is one execution of a suite: cases x variants x repeats.

WithJudge opts a run into spawning a headless judge (the same machinery internal/api/bestofn.go's judgeTask uses, judge_agent/judge_model settings) over every replay cell once it finishes, comparing the attempt's diff against its case's reference diff — see internal/scheduler's applyEvalJudgeVerdict. It has no effect on a case that isn't a replay case (no reference diff to compare against).

type EvalSuite added in v2.4.0

type EvalSuite struct {
	ID          int64   `json:"id"`
	Name        string  `json:"name"`
	ProjectID   int64   `json:"project_id"`
	Description string  `json:"description"`
	CreatedAt   float64 `json:"created_at"`
}

EvalSuite is a named set of agent test cases against one project.

type EvalVariant added in v2.4.0

type EvalVariant struct {
	Agent          string `json:"agent"`
	Model          string `json:"model"`
	LaunchProfile  string `json:"launch_profile,omitempty"`
	PermissionMode string `json:"permission_mode,omitempty"`
}

EvalVariant is one agent/model/permission combination a run scores every case against — the same shape a Best-of-N dispatch variant takes.

type Event

type Event struct {
	ID          int64   `json:"id"`
	AttemptID   int64   `json:"attempt_id"`
	Seq         int64   `json:"seq"`
	TS          float64 `json:"ts"`
	Type        string  `json:"type"`
	PayloadJSON string  `json:"-"`

	// filled by the API layer
	Payload  map[string]any `json:"payload"`
	AttemptN int            `json:"attempt_n"`
}

Event is one normalised line of an agent's output stream.

type HourlyRateSample added in v2.4.0

type HourlyRateSample struct {
	Kind string // "session" | "task"
	ID   int64
	Rate float64 // USD per hour
}

HourlyRateSample is one finished unit of work's average cost per hour of wall time it ran — the raw material for a cost-anomaly baseline.

type LaunchProfile

type LaunchProfile struct {
	ID           int64  `json:"id"`
	Name         string `json:"name"`
	Agent        string `json:"agent"`
	Command      string `json:"command"`
	Model        string `json:"model"`
	EnvJSON      string `json:"env_json"`
	Description  string `json:"description"`
	Instructions string `json:"instructions"`
}

LaunchProfile holds explicit overrides for future interactive sessions. Environment values are configuration data and must not enter session events. Description and Instructions are the human-facing parts: Instructions is a launch briefing typed to the agent when a session starts, and never a configuration or privilege change.

type LimitHold added in v2.4.0

type LimitHold struct {
	ID              int64    `json:"id"`
	SessionID       *int64   `json:"session_id,omitempty"`
	TaskID          *int64   `json:"task_id,omitempty"`
	AttemptID       *int64   `json:"attempt_id,omitempty"`
	Agent           string   `json:"agent"`
	Source          string   `json:"source"`
	Pattern         string   `json:"pattern"`
	Message         string   `json:"message"`
	DetectedAt      float64  `json:"detected_at"`
	ResetAt         *float64 `json:"reset_at,omitempty"`
	Policy          string   `json:"policy"`
	State           string   `json:"state"`
	DueAt           *float64 `json:"due_at,omitempty"`
	Tries           int      `json:"tries"`
	NudgedAt        *float64 `json:"nudged_at,omitempty"`
	ResetNotifiedAt *float64 `json:"-"`
	ResolvedAt      *float64 `json:"resolved_at,omitempty"`
	SuccessorID     *int64   `json:"successor_id,omitempty"`
	// AccountFrom and AccountTo are the two ends of an account swap
	// (docs/accounts.md): the login that hit the limit and the one the work
	// moved to. 0 is the CLI's default login; both nil until a swap starts.
	AccountFrom *int64  `json:"account_from,omitempty"`
	AccountTo   *int64  `json:"account_to,omitempty"`
	Note        string  `json:"note,omitempty"`
	CreatedAt   float64 `json:"created_at"`
	UpdatedAt   float64 `json:"updated_at"`
}

LimitHold is one time an agent was stopped by its provider's usage limit — see schema.go's limit_holds comment and internal/limits for the lifecycle.

func (*LimitHold) Open added in v2.4.0

func (h *LimitHold) Open() bool

Open reports whether the hold still needs something to happen.

type Media

type Media struct {
	ID        int64   `json:"id"`
	SessionID *int64  `json:"session_id"`
	Kind      string  `json:"kind"`
	Title     string  `json:"title"`
	Note      string  `json:"note"`
	Name      string  `json:"name"`
	Mime      string  `json:"mime"`
	Size      int64   `json:"size"`
	Blob      string  `json:"-"`
	URL       string  `json:"url"`
	Source    string  `json:"source"`
	CreatedAt float64 `json:"created_at"`

	// joined so the feed can say who posted without a second request
	SessionName string `json:"session_name,omitempty"`
}

Media is one thing an agent posted for the operator to look at.

type Memory

type Memory struct {
	ID               int64   `json:"id"`
	ProjectID        int64   `json:"project_id"`
	Note             string  `json:"note"`
	CreatedByAttempt *int64  `json:"created_by_attempt"`
	CreatedAt        float64 `json:"created_at"`
}

Memory is a durable note an agent left for the agents that come after it.

type MemoryDelivery added in v2.4.0

type MemoryDelivery struct {
	ID        int64   `json:"id"`
	SessionID *int64  `json:"session_id"`
	TaskID    *int64  `json:"task_id"`
	AttemptID *int64  `json:"attempt_id"`
	At        float64 `json:"at"`
	Mode      string  `json:"mode"`
	// Bytes is the byte length of the context block that was injected — the
	// same bound Automatic applies, not a model token count.
	Bytes int `json:"bytes"`
	// ItemsJSON is the provider's own list of what went out. Kept as text here
	// and parsed at the API boundary so a malformed blob can only degrade the
	// Memory section, never the read that would have shown it.
	ItemsJSON string `json:"-"`
}

MemoryDelivery is one time lectern injected project memory into a session or a task attempt. SessionID and TaskID/AttemptID are pointers because a row is exactly one of the two and the other is genuinely absent.

type OtelAttemptUsage added in v2.4.0

type OtelAttemptUsage struct {
	AttemptID    int64
	Model        string
	CostUSD      float64
	InputTokens  int64
	OutputTokens int64
	LinesAdded   int64
	LinesRemoved int64
	PullRequests int64
	Commits      int64
	UpdatedAt    float64
}

OtelAttemptUsage is one attempt's latest OTel reading.

type OutcomeFact added in v2.4.0

type OutcomeFact struct {
	ID          int64
	Scope       string // "attempt" | "session"
	RefID       int64
	Date        string
	TaskID      *int64
	ProjectID   *int64
	Agent       string
	Model       string
	CostUSD     float64
	CostSource  string
	CheckPassed *bool
	Accepted    bool
	LinesKept   *int64
	EvalPass    *bool
	TimeToPassS *float64
	// PullRequests/Commits come from Claude Code's OTel counters; nil when
	// the attempt or session never reported OTel metrics.
	PullRequests *int64
	Commits      *int64
	UpdatedAt    float64
}

OutcomeFact is one row of outcome_facts — see schema.go's comment for what each column means and why the table is a recomputed cache rather than an append-only ledger. internal/outcomes owns the derivation; this file is just the store half (upsert, range read), the same split usage.go and session_checks.go use for their own tables.

type Plugin added in v2.6.0

type Plugin struct {
	ID                string   `json:"id"`
	SourceKind        string   `json:"source_kind"` // bundled | path | git | index
	Source            string   `json:"source"`
	Ref               string   `json:"ref"`
	IndexName         string   `json:"index_name"`
	Subdir            string   `json:"subdir"`
	CommitSHA         string   `json:"commit"`
	TreeSHA           string   `json:"tree"`
	ContentHash       string   `json:"content_hash"`
	Format            string   `json:"format"`
	ConsentedHash     string   `json:"consented_hash"`
	ConsentedCapsJSON string   `json:"-"`
	ConsentedBy       string   `json:"consented_by"`
	ConsentedAt       *float64 `json:"consented_at"`
	Enabled           int      `json:"enabled"`
	ProjectIDsJSON    string   `json:"-"`
	SecretsJSON       string   `json:"-"`
	InstalledAt       float64  `json:"installed_at"`
	UpdatedAt         float64  `json:"updated_at"`
}

Plugin is one row of plugins: an installed plugin and the consent that pins it (docs/plugins.md). ContentHash is what is installed; ConsentedHash is what a person agreed to. They differ only while a change waits for consent, and nothing of the plugin runs then.

type PluginHookRun added in v2.6.0

type PluginHookRun struct {
	ID         int64   `json:"id"`
	PluginID   string  `json:"plugin_id"`
	Event      string  `json:"event"`
	Run        string  `json:"run"`
	ProjectID  *int64  `json:"project_id"`
	StartedAt  float64 `json:"started_at"`
	DurationMS int64   `json:"duration_ms"`
	OK         bool    `json:"ok"`
	Message    string  `json:"message"`
	Error      string  `json:"error"`
}

PluginHookRun is one execution of a plugin hook.

type PluginSource added in v2.6.0

type PluginSource struct {
	Name    string  `json:"name"`
	URL     string  `json:"url"`
	Ref     string  `json:"ref"`
	AddedAt float64 `json:"added_at"`
}

PluginSource is a marketplace: a git repository with an index file.

type Project

type Project struct {
	SetupCmd          string `json:"setup_cmd"`
	ID                int64  `json:"id"`
	Name              string `json:"name"`
	TargetID          int64  `json:"target_id"`
	RepoPath          string `json:"repo_path"`
	DefaultBaseBranch string `json:"default_base_branch"`
	WorkrootOverride  string `json:"workroot_override"`
	PolicyJSON        string `json:"policy_json"`
	VerifyCmd         string `json:"verify_cmd"`
	KeepWorktrees     int    `json:"keep_worktrees"`
	ReviewGate        int    `json:"review_gate"`
	EnvJSON           string `json:"env_json"`
	ContextJSON       string `json:"context_json"`
	// MCPJSON is credential-bearing storage and is exposed only through the
	// redacted /projects/{id}/mcp endpoint. Never serialize it in a project row.
	MCPJSON               string `json:"-"`
	StrictMCP             int    `json:"strict_mcp"`
	PermissionsJSON       string `json:"permissions_json"`
	GateMatcher           string `json:"gate_matcher"`
	DefaultAgent          string `json:"default_agent"`
	CapabilityProfile     string `json:"capability_profile"`
	DefaultPermissionMode string `json:"default_permission_mode"`
	// DefaultIsolationJSON is this project's default isolation.Config
	// (json-encoded) for a new session or task launch — see
	// internal/isolation. A launch's explicit override still wins; this is
	// only what a launch gets when it names none.
	DefaultIsolationJSON string `json:"default_isolation_json"`
	SkillSourcesJSON     string `json:"skill_sources_json"`
	MemoryTopic          string `json:"memory_topic"`
	MemoryStatus         string `json:"memory_status"`
	// RepoKey/RepoToplevel are cross-agent awareness's cache (see
	// internal/awareness and schema.go's session_file_edits comment):
	// backfilled from the first session in this project to resolve its own
	// git common dir, so every task attempt of this project can be matched
	// to a peer session without an extra git call. Never serialized: it is
	// an internal join key, not something a settings form edits.
	RepoKey      string `json:"-"`
	RepoToplevel string `json:"-"`
	// CILoop opts this project into the CI-aware PR loop (docs/ci-loop.md);
	// CIMaxAttempts caps the fix requests it sends per pull request.
	CILoop        int `json:"ci_loop"`
	CIMaxAttempts int `json:"ci_max_attempts"`
	// ComputerUse lets agents operate this project's live desktops
	// (docs/browser.md). Only a person can turn it on.
	ComputerUse int `json:"computer_use"`
	// ClaudeTerminalMouse overrides the global "claude_terminal_mouse"
	// setting for this project: "" follows it, "1" or "0" force it.
	ClaudeTerminalMouse string  `json:"claude_terminal_mouse"`
	CreatedAt           float64 `json:"created_at"`

	// joined for the projects list — the UI names a project's target inline
	TargetName string `json:"target_name,omitempty"`
	TargetKind string `json:"target_kind,omitempty"`
}

Project is a repository on a target, plus every policy that governs agents dispatched against it.

type ProjectSkill

type ProjectSkill struct {
	ID            int64   `json:"id"`
	ProjectID     int64   `json:"project_id"`
	TargetID      int64   `json:"target_id"`
	Agent         string  `json:"agent"`
	SkillID       string  `json:"skill_id"`
	SourceID      string  `json:"source_id"`
	SourcePath    string  `json:"source_path"`
	EntryName     string  `json:"entry_name"`
	TargetRel     string  `json:"target_rel"`
	SourceDigest  string  `json:"source_digest"`
	ExcludeMarker string  `json:"exclude_marker"`
	CreatedAt     float64 `json:"created_at"`
}

ProjectSkill is a desired project attachment. The source is deliberately target-local: it is never copied into the control plane or another user's home directory.

type ReviewComment added in v2.6.0

type ReviewComment struct {
	ID            int64    `json:"id"`
	SessionID     int64    `json:"session_id"`
	Repo          string   `json:"repo"`
	File          string   `json:"file"`
	Side          string   `json:"side"`
	Line          int      `json:"line"`
	Code          string   `json:"code"`
	ContextBefore string   `json:"context_before"`
	ContextAfter  string   `json:"context_after"`
	Text          string   `json:"text"`
	Status        string   `json:"status"` // draft | sent | resolved
	Round         int      `json:"round"`
	Author        string   `json:"author"`
	CreatedAt     float64  `json:"created_at"`
	SentAt        *float64 `json:"sent_at"`
	ResolvedAt    *float64 `json:"resolved_at"`
}

ReviewComment is one inline comment on one diff line. Code and the two context strings are what the reviewer saw when commenting: the client uses them to find the same line again after the agent edits the file, and to tell whether a sent comment's code has since changed.

type ReviewFileMark added in v2.6.0

type ReviewFileMark struct {
	Repo        string  `json:"repo"`
	Path        string  `json:"path"`
	Fingerprint string  `json:"fingerprint"`
	At          float64 `json:"at"`
}

ReviewFileMark records that a reviewer marked one file viewed while its diff had this fingerprint. A different fingerprint means the file changed since, and the mark no longer applies.

type Routine

type Routine struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	// Prompt is what the agent is asked to do, once per project.
	Prompt string `json:"prompt"`
	// Title prefixes the tasks it creates, so a board full of them is readable.
	Title string `json:"title"`
	// ProjectIDs is every project this runs against — one task each.
	ProjectIDs []int64 `json:"project_ids"`

	Agent          string `json:"agent"`
	Model          string `json:"model"`
	PermissionMode string `json:"permission_mode"`

	// Schedule empty means manual only. See routines.ParseSchedule.
	Schedule string `json:"schedule"`
	Enabled  bool   `json:"enabled"`
	// Dispatch runs the tasks immediately rather than leaving them queued.
	Dispatch bool `json:"dispatch"`

	LastRunAt *float64 `json:"last_run_at"`
	NextRunAt *float64 `json:"next_run_at"`
	CreatedAt float64  `json:"created_at"`
}

Routine is a job you saved because you keep asking for it.

It is the difference between typing "go through every open PR on librarr, sglang and gamarr, test it end to end, fix what is wrong, and merge once CI is green" for the fifth time, and pressing one button. A routine carries the prompt and everything a dispatch needs, and can run on a schedule or only when you ask.

type Sandbox added in v2.6.0

type Sandbox struct {
	ID          int64    `json:"id"`
	TargetID    int64    `json:"target_id"`
	Provider    string   `json:"provider"`
	ExtID       string   `json:"ext_id"`
	AttemptID   *int64   `json:"attempt_id"`
	Status      string   `json:"status"`
	Note        string   `json:"note"`
	CreatedAt   float64  `json:"created_at"`
	UpdatedAt   float64  `json:"updated_at"`
	DestroyedAt *float64 `json:"destroyed_at"`
}

Sandbox is one sandbox Lectern made (docs/sandboxes.md), kept so its lifecycle — suspend, resume, destroy — can be driven from the UI and so a kept sandbox is never forgotten.

type ScratchSession

type ScratchSession struct {
	ID        int64
	TargetID  int64
	Name      string
	Agent     string
	Workdir   string
	ProjectID *int64
	EndedAt   *float64
	LastSeen  float64
	ResumeID  string
	NativeCID string
}

ScratchSession is the little the scratch sweep needs from a session row: who claims a directory, whether they still do, and whether a conversation was ever recorded there.

type Session

type Session struct {
	SetupCancelRequested bool     `json:"setup_cancel_requested,omitempty"`
	SetupState           string   `json:"setup_state,omitempty"`
	SetupError           string   `json:"setup_error,omitempty"`
	LaunchConfigJSON     string   `json:"-"`
	ArchivedAt           *float64 `json:"archived_at"`
	ResumeID             string   `json:"resume_id,omitempty"`
	NativeRecoveryCID    string   `json:"-"`
	BootID               string   `json:"-"`
	TrackingIdentity     string   `json:"-"`
	GroupPath            string   `json:"group_path"`
	WorktreeJSON         string   `json:"-"`
	ID                   int64    `json:"id"`
	ProjectID            *int64   `json:"project_id"`
	TargetID             int64    `json:"target_id"`
	Name                 string   `json:"name"`
	Agent                string   `json:"agent"`
	Model                string   `json:"model"`
	Workdir              string   `json:"workdir"`
	TmuxSession          string   `json:"tmux_session"`
	Status               string   `json:"status"`
	Origin               string   `json:"origin"`
	PaneHash             string   `json:"-"`
	PaneTail             string   `json:"pane_tail"`
	ContextPct           *int     `json:"context_pct"`
	LastActivityAt       *float64 `json:"last_activity_at"`
	CreatedAt            float64  `json:"created_at"`
	UpdatedAt            float64  `json:"updated_at"`
	EndedAt              *float64 `json:"ended_at"`
	// EndReason says how the record ended: stopped (someone ended it),
	// exited (its process went away on its own), released (tracking stopped,
	// process left running), handed_off, dismissed or failed (a launch that
	// never started). Empty on rows that ended before this column existed.
	EndReason string `json:"end_reason,omitempty"`
	// AgentExitedAt is set while the agent has exited but its terminal is
	// still open at a shell prompt; nil while the agent runs.
	AgentExitedAt *float64 `json:"agent_exited_at,omitempty"`
	// RelaunchedAt is when restart recovery last relaunched this session.
	RelaunchedAt *float64 `json:"relaunched_at,omitempty"`
	// ResumeGuess is the conversation a lost adopted session most likely had:
	// the only one in its folder last written when it was last active.
	ResumeGuess string `json:"-"`
	// AccountID is the registered login (agent_accounts, docs/accounts.md)
	// this session's agent runs under; nil is the CLI's own default login.
	AccountID *int64 `json:"account_id,omitempty"`

	// HookToken authenticates POST /api/hook/session/{id}/* (see
	// internal/agentevents). Never serialized: it is a bearer secret handed to
	// the target process via LECTERN_HOOK_TOKEN, not something the API repeats
	// back to a browser.
	HookToken string `json:"-"`
	// PermissionMode is this session's resolved launch-time choice, "bypass"
	// or "ask" (docs/agent-events.md section 3); empty on a row launched
	// before this column existed, which every reader treats as "bypass".
	PermissionMode string `json:"permission_mode,omitempty"`
	// AgentState/StateSource/StateAt/HookSeenAt are the hook-driven lifecycle
	// signal described in docs/agent-events.md section 2, kept alongside the
	// older screen-scraped Status. StateSource says who wrote AgentState last
	// (hook|screen); HookSeenAt is when a hook last reached this session at
	// all, which is what poll.go's applyPane checks before screen-scraping is
	// allowed to overwrite AgentState again.
	AgentState  string   `json:"agent_state,omitempty"`
	StateSource string   `json:"state_source,omitempty"`
	StateAt     *float64 `json:"state_at,omitempty"`
	HookSeenAt  *float64 `json:"hook_seen_at,omitempty"`

	// Usage — latest values only, from the agent's own statusline/rollout.
	// History lives in usage_daily (see store/usage.go).
	// ContextUsedPct is the agent's "percent of context window used" —
	// distinct from the older, screen-scraped ContextPct above ("percent
	// left until auto-compact"); see the schema comment on context_used_pct.
	ContextUsedPct *int     `json:"context_used_pct,omitempty"`
	ContextTokens  *int     `json:"context_tokens,omitempty"`
	ContextSize    *int     `json:"context_size,omitempty"`
	CostUSD        *float64 `json:"cost_usd,omitempty"`
	LinesAdded     *int     `json:"lines_added,omitempty"`
	LinesRemoved   *int     `json:"lines_removed,omitempty"`
	Rate5hPct      *int     `json:"rate_5h_pct,omitempty"`
	Rate5hReset    *float64 `json:"rate_5h_reset,omitempty"`
	Rate7dPct      *int     `json:"rate_7d_pct,omitempty"`
	Rate7dReset    *float64 `json:"rate_7d_reset,omitempty"`
	UsageAt        *float64 `json:"usage_at,omitempty"`
	// CodexThreadID is the codex rollout session id (see schema.go). Never
	// serialized: it is an internal handle for the rollout reader, not
	// something a card needs to render.
	CodexThreadID string `json:"-"`
	// PrecompactAt is the last PreCompact hook time, for a brief
	// "compacting" card warning (see schema.go comment).
	PrecompactAt *float64 `json:"precompact_at,omitempty"`

	// RepoKey/RepoToplevel/AwarenessBriefingHash/AwarenessBriefingAt are
	// cross-agent awareness's state (internal/awareness, docs/agent-events.md
	// "Cross-agent awareness"). RepoKey IS serialized (unlike the others,
	// which are dedup bookkeeping/paths nobody needs) because the frontend
	// groups live sessions by it client-side to render the "possible
	// duplicate work" notice without a second board-wide endpoint; it is an
	// opaque "<target id>:<git common dir>" string, not a credential.
	RepoKey               string   `json:"repo_key,omitempty"`
	RepoToplevel          string   `json:"-"`
	AwarenessBriefingHash string   `json:"-"`
	AwarenessBriefingAt   *float64 `json:"-"`
	// LastPromptExcerpt/LastPromptAt are the latest UserPromptSubmit prompt,
	// clipped to ~200 chars — "what is this session working on" for a peer
	// summary (internal/awareness).
	LastPromptExcerpt string   `json:"last_prompt_excerpt,omitempty"`
	LastPromptAt      *float64 `json:"last_prompt_at,omitempty"`
	// OtelActiveAt (docs/outcomes.md) is when this session's Claude Code OTLP
	// exporter last reported in. Non-nil is the precedence signal: once set,
	// IngestStatusline stops booking its own usage_daily deltas for this
	// session (the exact OTel numbers own that job from here on).
	OtelActiveAt *float64 `json:"otel_active_at,omitempty"`

	// joined for the UI, which groups sessions by project and names their host
	ProjectName string `json:"project_name,omitempty"`
	TargetName  string `json:"target_name,omitempty"`
	TargetKind  string `json:"target_kind,omitempty"`
}

Session is an interactive agent the operator works WITH, as opposed to a task, which is work they hand OFF. Its tmux session is the process; this row is the durable record that outlives it.

type SessionCheck added in v2.4.0

type SessionCheck struct {
	ID          int64    `json:"id"`
	SessionID   int64    `json:"session_id"`
	Fingerprint string   `json:"-"`
	Command     string   `json:"command"`
	Status      string   `json:"status"`
	ExitCode    *int     `json:"exit_code"`
	OutputTail  string   `json:"output_tail"`
	StartedAt   float64  `json:"started_at"`
	FinishedAt  *float64 `json:"finished_at"`
	Reason      string   `json:"reason"`
}

SessionCheck is one run of a session's check command — see internal/checks and schema.go's session_checks table doc comment.

type SessionFileEdit added in v2.4.0

type SessionFileEdit struct {
	ID        int64   `json:"id"`
	SessionID int64   `json:"session_id"`
	RepoKey   string  `json:"-"`
	RelPath   string  `json:"rel_path"`
	At        float64 `json:"at"`
}

SessionFileEdit is the latest edit of one file by one session — see internal/awareness and schema.go's session_file_edits comment.

type SkillMaterialization

type SkillMaterialization struct {
	ID           int64  `json:"id"`
	AttachmentID int64  `json:"attachment_id"`
	TargetID     int64  `json:"target_id"`
	WorktreePath string `json:"worktree_path"`
	TargetPath   string `json:"target_path"`
	SourcePath   string `json:"source_path"`
	TargetRel    string `json:"target_rel"`
	// State records the filesystem fact separately from desired attachment
	// intent. pending means the link has not been proven; owned means Lectern
	// created it; preexisting means the destination was native and must never
	// be removed during detach.
	State     string  `json:"state"`
	CreatedAt float64 `json:"created_at"`
}

type Takeover

type Takeover struct {
	TaskID    int64  `json:"task_id"`
	AttemptID int64  `json:"attempt_id"`
	SessionID *int64 `json:"session_id"`
	Status    string `json:"status"`
	Error     string `json:"error"`
}

type Target

type Target struct {
	ID            int64  `json:"id"`
	Name          string `json:"name"`
	Kind          string `json:"kind"`
	Host          string `json:"host"`
	Port          int    `json:"port"`
	User          string `json:"user"`
	KeyPath       string `json:"key_path"`
	Workroot      string `json:"workroot"`
	MaxConcurrent int    `json:"max_concurrent"`
	Sandbox       int    `json:"sandbox"`
	Status        string `json:"status"`
	InfoJSON      string `json:"info_json"`
	ContextJSON   string `json:"context_json"`
	MemoryDir     string `json:"memory_dir"`
	// CommandPrefix wraps every command run on this target. It exists for hosts
	// whose SSH lands somewhere other than where the work is — a Windows box
	// where the toolchain lives in WSL needs `wsl -e bash -lc`, and without it
	// the target probes as "no tmux, no python3" and nothing can run.
	CommandPrefix string  `json:"command_prefix"`
	CreatedAt     float64 `json:"created_at"`
	// SSHJSON holds the SSH connection options beyond host/user/port/key
	// (docs/ssh.md): an ssh_config alias, ProxyJump, agent use and forwarding,
	// extra OpenSSH options and which transport runs the commands.
	SSHJSON string `json:"ssh_json"`
	// SandboxJSON configures a sandbox target's provider (docs/sandboxes.md).
	// Empty means the original Proxmox linked-clone provider with the
	// template vmid in Host.
	SandboxJSON string `json:"sandbox_json"`
}

Target is a machine lectern can dispatch onto.

type Task

type Task struct {
	ID               int64   `json:"id"`
	ProjectID        int64   `json:"project_id"`
	Title            string  `json:"title"`
	Prompt           string  `json:"prompt"`
	Status           string  `json:"status"`
	Priority         int     `json:"priority"`
	LabelsJSON       string  `json:"labels_json"`
	Agent            string  `json:"agent"`
	Model            string  `json:"model"`
	PermissionMode   string  `json:"permission_mode"`
	BaseBranch       string  `json:"base_branch"`
	ParentTaskID     *int64  `json:"parent_task_id"`
	CreatedBy        string  `json:"created_by"`
	CreatedByAttempt *int64  `json:"created_by_attempt"`
	CreatedAt        float64 `json:"created_at"`
	UpdatedAt        float64 `json:"updated_at"`
	// CheckCommand overrides the project's own VerifyCmd for auto-verify on
	// this one task, when set — empty means "use the project's", which is
	// every task that predates this field. It exists for evals: a case's own
	// check_command needs to run instead of the project default, without
	// mutating shared project state for the run's duration.
	CheckCommand string `json:"check_command,omitempty"`
	// SetupCommand, when set, is run for real by the scheduler in the
	// attempt's own worktree, on its target, after the worktree is created
	// and before the agent starts — a non-zero exit fails the attempt and the
	// agent never runs. Empty (every task that predates this field) skips the
	// step entirely. It exists for evals: a case's own setup_command used to
	// be folded into the prompt as an instruction for the agent to run itself;
	// this is the real host-side pre-step instead.
	SetupCommand string `json:"setup_command,omitempty"`
	// SetupTimeoutS bounds how long SetupCommand may run, in seconds. The eval
	// engine sets it to min(case.timeout_s, 600); zero falls back to a 600s
	// default inside the scheduler.
	SetupTimeoutS int `json:"setup_timeout_s,omitempty"`
	// BudgetUSD (docs/budgets.md) is this task's own spend cap, settable at
	// create or dispatch time. Nil/0 means "no per-task cap".
	BudgetUSD *float64 `json:"budget_usd,omitempty"`
}

Task is one unit of work on the board.

type TaskFilter

type TaskFilter struct {
	Status    string
	ProjectID int64
}

TaskFilter narrows the board query. A zero value lists everything.

type TaskMessage

type TaskMessage struct {
	ID        int64   `json:"id"`
	TaskID    int64   `json:"task_id"`
	RequestID string  `json:"request_id"`
	Text      string  `json:"text"`
	Interrupt bool    `json:"interrupt"`
	Status    string  `json:"status"`
	AttemptID *int64  `json:"attempt_id"`
	Error     string  `json:"error,omitempty"`
	CreatedAt float64 `json:"created_at"`
}

TaskMessage is an operator instruction and its delivery receipt.

type TrackerConnection added in v2.6.0

type TrackerConnection struct {
	ID        int64  `json:"id"`
	ProjectID int64  `json:"project_id"`
	Kind      string `json:"kind"` // github | gitlab | linear | jira
	Name      string `json:"name"`
	// ConfigJSON is the non-secret settings; the API returns it parsed.
	ConfigJSON string `json:"-"`
	// SecretsJSON holds the API key/token. It is never serialized: the API
	// reports only which fields are set, exactly like trigger sources.
	SecretsJSON string  `json:"-"`
	CreatedAt   float64 `json:"created_at"`
	UpdatedAt   float64 `json:"updated_at"`
}

TrackerConnection is how a project reaches an external tracker for the Tasks hub (docs/trackers.md): a Linear workspace or a Jira site with its credentials, or an override of the GitHub/GitLab repository Lectern otherwise detects from the clone's origin remote.

type TriggerEvent added in v2.4.0

type TriggerEvent struct {
	ID             int64   `json:"id"`
	SourceID       int64   `json:"source_id"`
	ProjectID      int64   `json:"project_id"`
	ExternalID     string  `json:"external_id"`
	Kind           string  `json:"kind"`
	Author         string  `json:"author"`
	Summary        string  `json:"summary"`
	Action         string  `json:"action"` // task_created | skipped | ignored
	Reason         string  `json:"reason"`
	TaskID         *int64  `json:"task_id"`
	PostbackStatus string  `json:"postback_status"`
	PostbackNote   string  `json:"postback_note"`
	RawJSON        string  `json:"-"`
	CreatedAt      float64 `json:"created_at"`
}

TriggerEvent is one inbound event a source saw — matched (and possibly a task) or not (and why). This is the ledger dedup reads and the audit trail the settings UI shows as "recent events".

type TriggerSource added in v2.4.0

type TriggerSource struct {
	ID        int64  `json:"id"`
	ProjectID int64  `json:"project_id"`
	Kind      string `json:"kind"` // github | slack | linear
	Name      string `json:"name"`
	Enabled   bool   `json:"enabled"`
	// ConfigJSON is the non-secret, kind-specific shape (repo, label, mention
	// handle, allowed authors, ...) — safe to return from the API, but the
	// API layer parses it into "config" on triggerSourceView instead of
	// exposing the raw string a second time.
	ConfigJSON string `json:"-"`
	// SecretsJSON holds tokens/keys. Never serialize this field raw to the
	// API — internal/api/triggers.go redacts it, the same pattern
	// Project.MCPJSON already uses for MCP server credentials.
	SecretsJSON string   `json:"-"`
	IntervalS   int      `json:"interval_s"`
	CursorJSON  string   `json:"-"`
	Status      string   `json:"status"`
	LastPollAt  *float64 `json:"last_poll_at"`
	LastError   string   `json:"last_error"`
	CreatedAt   float64  `json:"created_at"`
	UpdatedAt   float64  `json:"updated_at"`
}

TriggerSource is one inbound connection a project watches for work to pick up on its own: a GitHub repo, a Slack workspace, or a Linear team. See internal/triggers for the polling/socket engines and internal/api/triggers.go for the HTTP surface.

type UIPref added in v2.6.0

type UIPref struct {
	Key       string  `json:"key"`
	Value     string  `json:"value"`
	UpdatedAt float64 `json:"updated_at"`
}

UIPref is one stored preference.

type WorkspaceOperation

type WorkspaceOperation struct {
	ID              int64   `json:"id"`
	SessionID       int64   `json:"session_id"`
	PlanJSON        string  `json:"-"`
	State           string  `json:"state"`
	Error           string  `json:"error,omitempty"`
	CancelRequested bool    `json:"cancel_requested"`
	CreatedAt       float64 `json:"created_at"`
	UpdatedAt       float64 `json:"updated_at"`
}

func (*WorkspaceOperation) Active

func (o *WorkspaceOperation) Active() bool

type Wrap

type Wrap struct {
	ID            int64   `json:"id"`
	SessionID     int64   `json:"session_id"`
	ProjectID     *int64  `json:"project_id"`
	Summary       string  `json:"summary"`
	Transcript    string  `json:"transcript,omitempty"`
	NextSessionID *int64  `json:"next_session_id"`
	CreatedAt     float64 `json:"created_at"`
}

Wrap is one session handoff: the summary an agent wrote for its successor.

Jump to

Keyboard shortcuts

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