Files
archie/internal/domain/storecontract/storecontract.go
T
sam 845b192a89 feat(taskstate): count completed runs in the per-workflow stats
The transition table moved the no-change outcomes to StatusCompleted, so a
run that opens no pull request now ends in a status the per-workflow stats
did not count at all: it was not merged, not in review, not parked, and the
workflows page would have shown it as a run that went nowhere. The count
travels the whole State Store path, since every dashboard consumer reads it
through the gRPC client rather than the local store.

- WorkflowStats filters `completed` beside merged and pr_open; the SQL is
  the count, so a wrong filter reads as zero rather than failing, and
  TestWorkflowStatsCountsCompletedRuns holds it against a real store.
- storecontract.WorkflowStat gains Completed (json "completed"), the proto
  message gains field 9, and workflowStatProto/workflowStatValue carry it;
  TestWorkflowStatProtoCarriesEveryField round-trips every field by name.
- The gateway's chat task report names the status.
- The dashboard counts a completed run as delivered in GatePulseCard's
  totals and badge numerator, and the WorkflowStat/WorkflowStats/WorkflowRow
  interfaces carry the field.
- TestOutcomeSitesAreTransitionsFromRunning is the guard that keeps the
  producer and the table agreeing: it re-reads this package's tc.Outcome
  assignment sites from source and requires each status to be one
  internal/taskstate allows from running, so a new or moved site has to be
  adjudicated against the table instead of discovered on a live run.
2026-09-26 04:01:08 +10:00

487 lines
23 KiB
Go

// Package storecontract is the ratified State Store contract as its
// consumers reference it: the producer-owned daemon/webui/intake store
// surfaces (docs/prds/state-store-contract.md §1, §2). It carries no
// persistence -- internal/infrastructure/postgres and *staterpc.Client (the
// remote adapter) both satisfy these interfaces --
// so a process that only holds the contracts, such as the archie-ui
// dashboard process, can reference them without linking the SQL
// implementation.
//
// It is hand-written and lives in the domain layer (which owns required
// contracts), NOT under internal/contracts: that tree is the buf generate
// output and is wiped and regenerated by tools/proto.sh, which would
// delete a hand-written file there (archie-core-8cda.5.6).
package storecontract
import (
"context"
"errors"
"io"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
// TaskStore is the full store surface the daemon needs.
// Consumers depend on TaskStore, never on a concrete type.
type TaskStore interface {
TaskLifecycle
TaskParker
TaskEvents
TaskQueries
TaskArchiver
TaskRetryer
RemediationStarter
}
// 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 string) (*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 is the classified park write, kept off TaskLifecycle so that
// interface stays under the repo's 8-method cap. It mirrors Transition with
// a park class attached (taskstate.ParkClass); the class is normalized
// store-side, so an empty or unknown value becomes needs_human rather than
// an error -- a park that predates classification must not fail because its
// caller did not know the vocabulary.
type TaskParker interface {
ParkTask(ctx context.Context, taskID int64, from, detail, class string) 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 {
ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error)
}
// TaskRetryer atomically requeues recoverable work and accounts for the new
// attempt so a partial write cannot evade the retry cap.
type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) 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. UpdateReviewPayload appends late-arriving comments
// to a still-queued unit. Both guards are the reaction consumer's dedup and
// are documented in docs/prds/pr-review-remediation.md decisions 3 and 5.
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
}
// 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)
ClearTerminalTasks(ctx context.Context) (int64, error)
Tasks(ctx context.Context, limit int) ([]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(ctx context.Context, taskID int64) ([]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
}
// CaptureStore persists unbound inbound webhook captures -- events with no
// workflow binding and no task association. Deliberately separate from
// TaskStore: a consumer that only needs capture (the intake HTTP handler)
// should not acquire the full task-lifecycle surface, mirroring why
// TaskArchiver is split out above. See docs/prds/event-capture-storage.md.
type CaptureStore interface {
InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (string, error)
ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error)
}
// ConfigSnapshotStore holds the running configuration as the dashboard
// renders it: the owner of configuration publishes, the process that displays
// it reads. Separate from every other store surface because it is the only
// one whose writer is the daemon and whose reader is the UI, and because a
// task-scoped credential must never reach the writer.
// See docs/architecture/migration-decisions.md, "Dashboard configuration page".
type ConfigSnapshotStore interface {
PutConfigSnapshot(ctx context.Context, snapshot ConfigSnapshot) error
ConfigSnapshot(ctx context.Context) (ConfigSnapshot, bool, error)
}
// ChannelStatusStore holds channel runtime state as the process HOSTING the
// channels observes it. Same split as ConfigSnapshotStore and for the same
// reason: the writer is the Messaging Service, the reader is the UI process, and
// a task-scoped credential must reach neither.
//
// It is runtime state rather than a settings document -- a channel that is
// failed is not a document anybody edits -- which is why it is not a
// ControlPlaneService resource kind.
// See docs/architecture/migration-decisions.md, "Channel state to the dashboard".
type ChannelStatusStore interface {
// PutChannelStatus records the reporting process's whole set: a channel it no
// longer reports is removed rather than left behind, because a stale "running"
// row is a lie the dashboard would show indefinitely.
PutChannelStatus(ctx context.Context, channels []ChannelStatus) error
ChannelStatus(ctx context.Context) ([]ChannelStatus, error)
}
// ApplyStatusStore holds which version of each control-plane resource each
// process is running. Same split as ConfigSnapshotStore and for the same
// reason: the writers are the processes that apply a resource, the reader is
// the UI, and a task-scoped credential must reach neither.
// See docs/prds/control-plane-apply-status.md.
type ApplyStatusStore interface {
PutApplyStatus(ctx context.Context, status ApplyStatus) error
ListApplyStatus(ctx context.Context) ([]ApplyStatus, error)
}
// MappingStore persists payload field mappings (t2db.3). Deliberately
// separate from TaskStore and CaptureStore for the same reason those are
// split: the dashboard's mapping editor should only acquire the mapping
// surface, not the full task or capture APIs. See
// docs/prds/payload-field-mapping.md.
type MappingStore interface {
InsertMapping(ctx context.Context, m mapping.Mapping) (string, error)
GetMapping(ctx context.Context, id string) (*mapping.Mapping, error)
ListMappings(ctx context.Context) ([]mapping.Mapping, error)
UpdateMapping(ctx context.Context, m mapping.Mapping) error
DeleteMapping(ctx context.Context, id string) error
}
// MappingMatchRecorder counts the events each mapping resolved, which the
// store reports as Mapping.MatchCount and LastMatchedAt. Recording the same
// (mapping, capture) twice counts once.
type MappingMatchRecorder interface {
RecordMappingMatch(ctx context.Context, mappingID, captureID string) error
}
// EventTypeStore persists event types (docs/prds/event-automation.md, "Event
// types"). Insert and Update refuse a type whose rule overlaps another on the
// same source with eventtype.ErrOverlap, and a malformed one with
// eventtype.ErrInvalid. Update rewrites the name and rule; the schema is the
// one the type was created with.
type EventTypeStore interface {
InsertEventType(ctx context.Context, t eventtype.EventType) (string, error)
UpdateEventType(ctx context.Context, t eventtype.EventType) error
DeleteEventType(ctx context.Context, id string) error
ListEventTypes(ctx context.Context) ([]eventtype.EventType, error)
}
// BindingStore persists playbook bindings (t2db.4 Phase B): CRUD and the
// draft -> pending_approval -> armed state machine. Split off from
// TaskStore and MappingStore so the webui binding editor does not acquire
// the full task or mapping surfaces. Dispatch-time helpers live in
// BindingDispatcher; the daemon depends on both. See
// docs/prds/playbook-binding.md.
type BindingStore interface {
InsertBinding(ctx context.Context, b binding.Binding) (string, error)
GetBinding(ctx context.Context, id string) (*binding.Binding, error)
ListBindings(ctx context.Context) ([]binding.Binding, error)
UpdateBinding(ctx context.Context, b binding.Binding) error
DeleteBinding(ctx context.Context, id string) error
ApproveBinding(ctx context.Context, id string) error
}
// SourceStore persists capture sources and their signing setting
// (docs/prds/event-automation.md "Sources"). The path is the key and never
// changes. Secrets cross this surface in plaintext; the store encrypts them
// at rest. Signing transitions are decided by the source domain and written
// with an expected-from guard, so two operators cannot race an approval.
type SourceStore interface {
InsertSource(ctx context.Context, s source.Source) error
// GetSource returns (nil, nil) for an unknown path.
GetSource(ctx context.Context, path string) (*source.Source, error)
ListSources(ctx context.Context) ([]source.Source, error)
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
SetSourceSecret(ctx context.Context, path, secret string) error
}
// BindingDispatcher is the dispatch-loop surface over the bindings store:
// look up armed bindings for HMAC verification, list captures that still
// need dispatching, and record the at-most-once ledger row. The
// dispatcher's task-creation call (EnqueueBindingTask) lives on a separate
// BindingTaskCreator interface so the dispatcher does not depend on the
// full TaskStore just to spawn one task.
type BindingDispatcher interface {
ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error)
RecordDispatch(
ctx context.Context,
bindingID string,
bindingVersion int64,
captureID string,
// taskID addresses the SQLite-owned task tables, which are not
// migrating: it stays an integer on purpose. The binding dispatch
// loop claims before it enqueues, so it records 0.
taskID int64,
) error
ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]CapturedEvent, error)
}
// BindingTaskCreator is the single-method consumer-facing surface for
// enqueueing a task triggered by a binding. Splitting it off TaskLifecycle
// keeps the lifecycle surface narrow (8 methods, the interfacebloat limit)
// and keeps the binding-specific shape on the binding interfaces.
type BindingTaskCreator interface {
EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, inputs map[string]any) (*task.Task, error)
}
// PlaybookDispatcher is the idempotency-ledger surface for side-effecting
// playbook actions (docs/prds/eda-playbook-engine.md gap 2).
// RecordPlaybookDispatch writes the (playbook, version, event, action) row
// BEFORE the action's side effect fires -- the deliberate reverse of
// BindingDispatcher.RecordDispatch -- so a duplicate returns
// ErrAlreadyDispatched and the caller skips the invoke rather than repeating
// a non-revocable side effect. DeletePlaybookDispatches deletes one
// playbook's ledger rows on explicit request only: a playbook file missing at
// boot may be an unmounted directory, and reclaiming on that would let
// redelivered events fire again. There is deliberately no *sql.Tx: any
// transaction stays server-side inside the store.
type PlaybookDispatcher interface {
RecordPlaybookDispatch(ctx context.Context, playbookID, playbookVersion, eventID, actionID string) error
DeletePlaybookDispatches(ctx context.Context, playbookID string) error
}
// TaskLogStore reads one task attempt's persisted log. Deliberately separate
// from TaskQueries: the log is not a row, it is a file the logging package
// owns the format of, and a process that can read the task board should not
// have to acquire a log reader to do it. The dashboard's UI process is the
// consumer this exists for -- it holds no daemon-local file handle, so the
// read crosses the State Store contract (docs/prds/ui-service-boundary.md).
//
// Found=false with a nil error is the not-found convention every read here
// uses, and it is load-bearing: "this attempt has no log" is not "this
// process cannot read logs". The second one is an error
// (logging.ErrTaskLogsUnavailable), because a caller that conflates them
// reports a configuration change where none is needed.
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)
}
// CapturedEvent is one unbound inbound webhook capture: no workflow binding,
// no forge/task association -- just what arrived, from where, and when.
// See docs/prds/event-capture-storage.md.
type CapturedEvent struct {
ID string `json:"id"`
ReceivedAt time.Time `json:"received_at"`
Source string `json:"source"`
RemoteAddr string `json:"remote_addr"`
ContentType string `json:"content_type"`
// Headers and Body are redacted (webhookguard.RedactPayload) before
// they ever reach InsertCapture; the store persists what it is given.
Headers string `json:"headers"`
Body string `json:"body"`
Authenticated bool `json:"authenticated"`
// EventType is the ID of the event type the capture was identified as
// when it arrived, or empty when it matched none. An unidentified capture
// is never dispatched.
EventType string `json:"event_type"`
// Unsigned marks an event that arrived on an approved unsigned source.
// It dispatches without Authenticated and is flagged wherever it shows.
Unsigned bool `json:"unsigned"`
}
// Dispatchable reports whether a binding may start a task from this event:
// a valid signature, or a source approved to take unsigned events.
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
// ConfigSnapshot is the running configuration as the dashboard renders it,
// published by whoever owns configuration for whoever displays it.
//
// Document is opaque here on purpose: its shape belongs to the producer and
// the page that reads it, not to storage, and Schema names that shape so a
// reader can refuse a document it does not understand. It is secret-free by
// construction at the producer (the projection carries an API key's
// environment variable name and whether it resolved, never a value).
type ConfigSnapshot struct {
Schema string
Document []byte
PublishedAt time.Time
}
// ChannelStatus is one channel's runtime state as the process hosting it
// reports it. ReloadSupported is a capability declaration rather than a request:
// asking for a reload travels on its own surface, because a transient request and
// a durable state do not share a lifetime.
type ChannelStatus struct {
ID string
Name string
State string
Detail string
Configured bool
ReloadSupported bool
ObservedAt time.Time
}
// ApplyStatus is one process's report about one control-plane resource kind.
//
// AppliedVersion is the version that process is running. Error is set when the
// process could not apply what the store returned, and leaves AppliedVersion
// at the last version it did apply, so a rejected edit never erases the fact
// that an older one is live. ReportedAt is re-stamped on an interval: a record
// older than the staleness window belongs to a process that has stopped
// running, which is the only way this surface can tell a live process from a
// dead one.
type ApplyStatus struct {
Process string `json:"process"`
Kind string `json:"kind"`
AppliedVersion int64 `json:"applied_version"`
Error string `json:"error,omitempty"`
ReportedAt time.Time `json:"reported_at"`
}
// 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"`
}
// 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"`
}
// Sentinel errors, part of the wire contract: staterpc's
// mapError/unmapError match these by (code, canonical message) across the
// gRPC boundary, so their message strings are load-bearing and must never
// change (docs/prds/state-store-contract.md §4).
var (
// ErrStaleTransition is returned when a task transition's expected
// from status does not match the task's current status.
ErrStaleTransition = errors.New("store: stale transition: task status does not match expected from status")
// ErrBindingNotFound is returned when a binding ID does not exist.
ErrBindingNotFound = errors.New("store: binding not found")
// ErrBindingOverlap is returned when a binding's matcher overlaps an
// existing binding for the same source.
ErrBindingOverlap = errors.New("store: binding overlaps existing binding for source")
// ErrBindingTransition is returned when a binding state transition is
// rejected by the draft -> pending_approval -> armed machine.
ErrBindingTransition = errors.New("store: binding state transition rejected")
// ErrAlreadyDispatched is returned when a dedup ledger already holds the
// dispatch key: binding_dispatches for the (binding_id, capture_id) pair,
// or playbook_dispatches for the (playbook_id, playbook_version,
// event_id, action_id) tuple. Both ledgers are at-most-once guarantees;
// the sentinel is shared so a caller treats "already recorded" the same
// way across the two surfaces.
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
// ErrMappingNotFound is returned when a mapping ID does not exist.
ErrMappingNotFound = errors.New("store: mapping not found")
// ErrEventTypeNotFound is returned when an event type ID does not exist.
ErrEventTypeNotFound = errors.New("store: event type not found")
// ErrSourceNotFound is returned when a source path does not exist.
ErrSourceNotFound = errors.New("store: source not found")
// ErrSourcePathTaken is returned when a new source's path is in use.
ErrSourcePathTaken = errors.New("store: source path already taken")
// ErrSourceSigningStale is returned when a signing write's expected
// from state does not match the stored one.
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
// ErrResourceNotFound is returned when a control-plane resource kind has
// no stored document. It is in-process only (not on the gRPC wire): the
// control plane runs in the daemon against the local store.
ErrResourceNotFound = errors.New("resource not found")
// ErrResourceVersionConflict is returned when a resource write carries an
// expected version that does not match the stored revision.
ErrResourceVersionConflict = errors.New("resource version conflict")
)
// Resource is one control-plane resource document: the stored value for a
// kind, its revision, and the audit record written with the last write.
// Resource and ResourceWrite live here so the UI-side consumers can reference
// them without linking the PostgreSQL implementation.
type Resource struct {
Kind string
Value []byte
Version int64
Actor string
Source string
RequestID string
ExpectedVersion int64
CurrentVersion int64
At time.Time
}
// AuditTableResources is the sys_audit table name for control-plane resources,
// keyed by resource kind.
const AuditTableResources = "resources"
// AuditEntry is one changed field of one record, as sys_audit holds it. Any
// store table may write entries; Table and RecordKey locate the record.
// OldValue and NewValue are JSON; an absent side is empty.
type AuditEntry struct {
ID int64
Table string
RecordKey string
Field string
OldValue []byte
NewValue []byte
Version int64
Actor string
Source string
RequestID string
At time.Time
}
// ResourceWrite is a control-plane resource write request. ExpectedVersion is
// the optimistic-concurrency guard: a write whose expectation does not match
// the stored revision is refused with ErrResourceVersionConflict.
type ResourceWrite struct {
Kind string
Value []byte
Actor string
Source string
RequestID string
ExpectedVersion int64
At time.Time
}