The event-capture tables (captures, mappings, bindings, binding_dispatches,
playbook_dispatches) now live in PocketBase-owned collections and their ids
are opaque record ids rather than autoincrement integers. The task lifecycle
stays on SQLite: tasks/transitions/events carry FIFO claim ordering, id-cursor
pagination and the task-grant map, none of which gain anything from being
hand-editable. binding_dispatches.task_id is the single seam and stays an
integer addressing that store.
BREAKING: CapturedEvent.Id, Mapping.Id, Binding.Id and Binding.MappingId are
strings on the wire, as are the ids in the capture/mapping/binding requests.
RecordDispatchRequest.task_id is deliberately unchanged.
What the collections buy, beyond storage: a payload nobody has modelled yet is
inspectable, a mapping is editable at runtime, and a binding's relation to its
mapping is enforced. The old schema declared no FOREIGN KEY on that link, so a
dangling mapping_id was previously possible and is now refused.
Behaviour preserved deliberately, each recovered from the SQLite version
rather than reimplemented from memory:
- draft -> pending_approval -> armed, with approval only from
pending_approval and an edit always returning a binding for re-approval
- one binding per source, guarded on insert, update and approve
- an empty secret on update keeps the stored one, so an edit form that does
not echo it back cannot silently disarm a binding
- ErrMappingNotFound / ErrBindingNotFound on a missing delete target
- sentinels are re-exported from storecontract, never redefined: staterpc
matches on exact canonical message to rehydrate them, so a second
definition would break errors.Is across the wire invisibly
Two implementation notes worth keeping:
- at-most-once dispatch is now a unique index rather than INSERT OR IGNORE.
Only the unique-violation maps to ErrAlreadyDispatched; any other save
error is returned, because treating them all as "already recorded" would
turn the ledger into a silent at-least-once dispatcher.
- captures store received_at themselves at nanosecond precision in a
fixed-width layout. PocketBase autodates are millisecond and record ids
are random, so same-millisecond captures would otherwise order
arbitrarily; the old store got insertion order free from autoincrement.
- ListUndispatchedCaptures is raw SQL: the anti-join is a subquery and
PocketBase's filter DSL is not SQL. A read fires no hooks either way.
Adds tool_calls, which had no persistence at all: tool calls only ever reached
the on-disk task log, readable as text but never queryable or watchable.
Nothing writes it yet.
The binding secret cipher moves with the bindings it protects.
346 lines
17 KiB
Go
346 lines
17 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 -- *store.Store (SQLite, transitional location) 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). Relocated from
|
|
// internal/store by the UI Service deletion gate; internal/store keeps
|
|
// type aliases so daemon-side callers are unaffected.
|
|
package storecontract
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"time"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/binding"
|
|
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
|
"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
|
|
TaskEvents
|
|
TaskQueries
|
|
TaskArchiver
|
|
TaskRetryer
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// 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, sinceID int64, 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
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// 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.
|
|
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) (*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 and is the reclamation primitive for when a playbook
|
|
// is removed from the configured directory -- a removal path that does not
|
|
// exist yet and is tracked by archie-core-t2db.30. There is deliberately no
|
|
// *sql.Tx: any transaction stays server-side inside internal/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"`
|
|
}
|
|
|
|
// 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"`
|
|
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")
|
|
)
|