Files
archie/internal/domain/storecontract/task.go
T
sam 4728c8c253 feat(usage): report model usage per org with identity and cost (#1855)
Model usage was recorded per call and never read, so an org could not see
what it spent. Add the read side:

- model_usage carries identity_id. Task calls take it from the task row,
  chat and curator calls from the calling principal carried in the usage
  record, so an outbox replay keeps its attribution. Existing task rows are
  backfilled from tasks.
- StatsService.UsageTotals sums the caller org's rows by UTC day, source,
  provider, model and identity. The org comes from the principal, with no
  org parameter, so cross-org reads do not exist.
- GET /api/usage prices tokens at the catalog's list rate, netting cache
  hits, and reports calls to unpriced models as tokens only. The published
  catalog view now carries each model's cost.
- A new org Usage page behind a read_usage grant: admin and owner only,
  with a 7, 30 or 90 day range, totals, the daily series, and model, source
  and identity breakdowns. The org shell keeps it on the caller's own org.
2026-11-11 02:15:29 +11:00

210 lines
9.4 KiB
Go

package storecontract
import (
"context"
"io"
"time"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
// TaskLifecycle manages the core task state machine and enqueuing.
// Binding-triggered task creation lives on BindingTaskCreator, not here,
// so the lifecycle surface stays narrow and non-binding consumers (forge
// poll, chat spawn, drain loop) do not acquire a binding-specific shape.
type TaskLifecycle interface {
EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error)
EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*task.Task, error)
ClaimNext(ctx context.Context) (*task.Task, error)
ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
Transition(ctx context.Context, taskID int64, from, to, detail string) error
Update(ctx context.Context, t *task.Task) error
Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error
RecoverStale(ctx context.Context) (int64, error)
}
// TaskParker parks a task with a park class and the blocker the park site
// knows, if any. Unknown classes become needs_decision.
type TaskParker interface {
ParkTask(ctx context.Context, taskID int64, from, detail, class, blocker string) error
}
// StepRecorder records a running execution's steps.
type StepRecorder interface {
StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error)
FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error)
}
// ExecutionCanceller cancels an execution and its current attempt's open
// steps in one transaction. It also cancels the callees the execution was
// waiting on, and returns their ids (nested callees included) so the caller
// can stop their runs too.
type ExecutionCanceller interface {
CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error)
}
// StepReader lists one execution's recorded steps.
type StepReader interface {
ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error)
}
// TaskArchiver removes one terminal task's local record with an optimistic
// status guard. It is separate from the already broad lifecycle contract so
// consumers that only run tasks do not acquire an operator-only capability.
type TaskArchiver interface {
OutcomePoster
ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error)
ClearTerminalTasks(ctx context.Context) (int64, error)
}
// TaskRetryer atomically requeues recoverable work and accounts for the new
// attempt so a partial write cannot evade the retry cap. retryMode is the
// operator's worktree choice for the next dispatch (taskstate.RetryMode),
// persisted on the row so the daemon reads it instead of inferring it. resume
// is where the attempt starts; a resume whose After stage did not complete in
// its last run is refused with ErrResumeIncomplete.
type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string, resume task.Resume, currentDefinition bool) error
}
// ReviewGateResponder records the operator's review-gate answer. A re-review
// increments rereview_rounds and requeues; one past the cap returns
// ErrRereviewCapReached and writes nothing.
type ReviewGateResponder interface {
RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error
}
// RemediationStarter queues a review-triggered remediation for an Archie-owned
// open-PR task: one guarded transition that carries the JSON-encoded review
// unit in the same write, so a claimed remediation always has its input. Runs
// for one task are serialised, so a distinct review that arrives while a
// remediation owns the task is queued behind it and remediated once that run
// finishes; a re-delivered unit is absorbed, not queued twice.
// UpdateReviewPayload merges late-arriving comments into the unclaimed unit
// for the same review, active or queued behind a running remediation.
type RemediationStarter interface {
BeginRemediation(ctx context.Context, taskID int64, payload string) error
UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error
// SetReviewCursors persists the poll backstop's per-task review and
// comment high-water marks (pr-review-remediation.md decision 2). The
// pr_open guard is part of the contract: cursors only move while no
// remediation run owns the task.
SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error
}
// OutcomePoster tracks which finished chat tasks have reported back to their
// conversation.
type OutcomePoster interface {
// UnpostedOutcomes returns finished chat tasks whose outcome has not been
// posted to the conversation that created them.
UnpostedOutcomes(ctx context.Context) ([]*task.Task, error)
// MarkOutcomePosted records that the task's state at status was posted.
MarkOutcomePosted(ctx context.Context, taskID int64, status string) error
}
// TaskQueries groups read-only task accessors.
type TaskQueries interface {
TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*task.Task, error)
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
OpenPRs(ctx context.Context) ([]task.Task, error)
// ActiveTasksByOrigin returns the queued and running tasks the
// conversation origin created, for its /stop.
ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error)
// Tasks returns the most recently updated tasks.
Tasks(ctx context.Context, limit int) ([]task.Task, error)
// TasksPage returns one page of tasks, most recently updated first.
TasksPage(ctx context.Context, page TaskPage) ([]task.Task, error)
StatusCounts(ctx context.Context) (map[string]int, error)
}
// TaskEvents groups observability and lifecycle methods.
type TaskEvents interface {
InsertEvent(ctx context.Context, e events.Event) (int64, error)
EventsSince(ctx context.Context, cursor string, limit int) ([]events.Event, error)
// TaskEvents returns a task's timeline, without agent transcripts.
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
// TaskTranscript returns one attempt's agent transcript entries in order.
TaskTranscript(ctx context.Context, taskID int64, attempt int) ([]events.Event, error)
WorkflowStats(ctx context.Context) ([]WorkflowStat, error)
StageStats(ctx context.Context) ([]StageStat, error)
TokensByDay(ctx context.Context, days int) ([]DayTokens, error)
Close() error
}
// UsageStore reads an org's recorded model usage. It is separate from
// TaskEvents so a reader that only reports usage does not acquire the task
// lifecycle surface.
type UsageStore interface {
// UsageTotals sums the caller org's model usage over the last days days,
// one row per day, source, model and identity. The org comes from the
// caller, so no call reads another org's usage.
UsageTotals(ctx context.Context, days int) ([]usage.TotalRow, error)
}
// TaskPage selects one page of the task list. Empty Statuses matches every
// status. A zero After starts at the newest task; otherwise the page begins
// after the task it names, in (updated_at, id) descending order.
type TaskPage struct {
Statuses []string
// Workflow, when set, keeps only that workflow's tasks.
Workflow string
After TaskCursor
Limit int
}
// TaskCursor is the position of the last task a page returned.
type TaskCursor struct {
UpdatedAt time.Time
ID int64
}
// WorkflowCaller starts a workflow.call callee and reads it back.
type WorkflowCaller = task.Caller
// TaskLogStore reads one task attempt's log. Found=false means no log;
// ErrTaskLogsUnavailable means this process cannot read logs.
type TaskLogStore interface {
// TaskLog returns a page of one attempt's decoded log. attempt 0 selects
// the task's current attempt.
TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error)
// TaskLogContent writes one attempt's log verbatim to w, for a download.
// found is false, with a nil error, when the attempt has no log file.
TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (found bool, err error)
}
// WorkflowStat is one row of the per-workflow metrics table.
type WorkflowStat struct {
Workflow string `json:"workflow"`
Runs int `json:"runs"`
Merged int `json:"merged"`
Completed int `json:"completed"`
PROpen int `json:"pr_open"`
Parked int `json:"parked"`
AvgTokens int `json:"avg_tokens"`
AvgSteps float64 `json:"avg_steps"`
TotalToken int `json:"total_tokens"`
// Running and LastStatus describe the workflow now: how many of its runs
// are working, and how its newest one ended.
Running int `json:"running"`
LastStatus string `json:"last_status"`
}
// StageStat is average stage duration and failure counts per stage.
type StageStat struct {
Workflow string `json:"workflow"`
Stage string `json:"stage"`
Runs int `json:"runs"`
AvgMs int `json:"avg_ms"`
Errors int `json:"errors"`
}
// DayTokens is token spend per UTC day.
type DayTokens struct {
Day string `json:"day"`
Tokens int `json:"tokens"`
}