From 983ddd7c4bb6e00c93e02666bd971bc905d7e484 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Thu, 10 Sep 2026 01:36:27 +1000 Subject: [PATCH] refactor(store): move the producer-owned contracts to internal/contracts/store/v1 The deletion gate for the UI Service (archie-core-8cda.5.6) is objective: go list -deps from cmd/archie-ui must show no SQL/store implementation. internal/store's hand-written contract surfaces (TaskStore and its component interfaces, CaptureStore, MappingStore, BindingStore, BindingDispatcher, BindingTaskCreator, ConfigSnapshotStore) move to internal/contracts/store/v1 (package storev1), alongside the value types they carry (CapturedEvent, ConfigSnapshot, WorkflowStat, StageStat, DayTokens) and the sentinel errors -- whose canonical message strings are the wire contract and are byte-identical after the move. internal/store keeps type aliases, so daemon-side callers (archied, the daemon, staterpc's server side, taskactions) are unaffected. The UI-facing packages switch to storev1 directly: webui, archieui, captureintake, gatewayrpc, and staterpc's client/values -- which drops internal/store and modernc.org/sqlite from the archie-ui binary's import closure. overlay.DeniedKeys moves to internal/infrastructure/configuration for the same reason: webui referenced the constant and that dragged the overlay package's SQLite store in. The chat-contract and remaining runtime-handle decoupling continues under the same bead. --- internal/app/archied/bootstrap.go | 18 +- internal/app/archied/main.go | 7 +- internal/app/archied/state_store.go | 15 +- internal/app/archied/telegram_setup.go | 4 +- internal/app/archieui/compose.go | 14 +- internal/app/archieui/readiness.go | 4 +- internal/contracts/store/v1/contracts.go | 242 ++++++++++++++++++ internal/daemon/daemon.go | 24 +- .../infrastructure/captureintake/receiver.go | 8 +- .../configuration/denied_keys.go | 14 + .../configuration/overlay/overlay.go | 16 +- .../gatewayrpc/task_action_errors.go | 4 +- internal/infrastructure/staterpc/client.go | 42 +-- internal/infrastructure/staterpc/server.go | 24 +- internal/infrastructure/staterpc/values.go | 68 ++--- internal/infrastructure/taskactions/rpc.go | 4 +- internal/infrastructure/taskactions/store.go | 4 +- internal/store/bindings.go | 4 - internal/store/captures.go | 16 -- internal/store/config_snapshot.go | 14 - internal/store/events.go | 27 -- internal/store/interface.go | 183 +++---------- internal/store/mappings.go | 1 - internal/store/store.go | 1 - internal/webui/api_binding.go | 16 +- internal/webui/api_config.go | 12 +- internal/webui/api_mapping.go | 8 +- internal/webui/api_tasks.go | 4 +- internal/webui/config_schema.go | 6 +- internal/webui/server.go | 10 +- internal/webui/sse.go | 6 +- 31 files changed, 455 insertions(+), 365 deletions(-) create mode 100644 internal/contracts/store/v1/contracts.go create mode 100644 internal/infrastructure/configuration/denied_keys.go diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 11614d388..d917b4680 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -29,6 +29,7 @@ import ( "github.com/samcharles93/archie-core/internal/channels/webhook" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/eda/module" @@ -60,7 +61,6 @@ import ( "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/skill" "github.com/samcharles93/archie-core/internal/storage" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/tools/minimax" toolprovider "github.com/samcharles93/archie-core/internal/tools/provider" @@ -99,7 +99,7 @@ type boot struct { playbooks *playbook.Store - st store.TaskStore + st storev1.TaskStore // stateStore is the State Store contract adapter every daemon and gateway // store consumer depends on. It is ALWAYS the remote *staterpc.Client // dialed to the standalone archie-state-store gRPC service at @@ -108,7 +108,7 @@ type boot struct { // by openStateStoreAdapter, which requires [services.state].target to be // set. The b.st field remains solely for the standalone archie-state-store // binary, which owns the single SQLite file. - stateStore store.TaskStore + stateStore storev1.TaskStore // stateStoreGrants issues per-task, scoped State Store credentials for // agent containers (daemon.StateStoreGrantIssuer), wrapping the same // *staterpc.Client as stateStore. Nil when the State Store adapter isn't @@ -1241,16 +1241,16 @@ func (b *boot) buildDaemon() { // Consumer mapping/binding surfaces resolve from b.stateStore (the State // Store contract adapter): local by default, remote *staterpc.Client when // [services.state].target is set. See docs/prds/state-store-contract.md §10. - if ms, ok := b.stateStore.(store.MappingStore); ok { + if ms, ok := b.stateStore.(storev1.MappingStore); ok { b.d.Mappings = ms } - if bs, ok := b.stateStore.(store.BindingStore); ok { + if bs, ok := b.stateStore.(storev1.BindingStore); ok { b.d.Bindings = bs } - if bd, ok := b.stateStore.(store.BindingDispatcher); ok { + if bd, ok := b.stateStore.(storev1.BindingDispatcher); ok { b.d.BindingDispatcher = bd } - if btc, ok := b.stateStore.(store.BindingTaskCreator); ok { + if btc, ok := b.stateStore.(storev1.BindingTaskCreator); ok { b.d.BindingTaskCreator = btc } b.setupForgeWebhook() @@ -1340,7 +1340,7 @@ func (b *boot) publishConfig(ctx context.Context, cfg config.Config, provenance // propagated: it must never fail the reload or dashboard write that produced // the new configuration, both of which have already taken effect. func (b *boot) publishConfigSnapshot(ctx context.Context) { - snapshots, ok := b.stateStore.(store.ConfigSnapshotStore) + snapshots, ok := b.stateStore.(storev1.ConfigSnapshotStore) if !ok || b.web == nil { return } @@ -1362,7 +1362,7 @@ func (b *boot) publishConfigSnapshot(ctx context.Context) { b.log.Warn("config snapshot not published", "err", err) return } - err = snapshots.PutConfigSnapshot(ctx, store.ConfigSnapshot{ + err = snapshots.PutConfigSnapshot(ctx, storev1.ConfigSnapshot{ Schema: webui.ConfigViewSchema, Document: document, PublishedAt: time.Now().UTC(), diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 68ad76fc0..729076b37 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -29,6 +29,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/workflow" @@ -286,7 +287,7 @@ func resolveForge(cfg config.Forge, secrets *secret.Registry, log *slog.Logger) return client, token } -func openProductionTaskStore(ctx context.Context, path string, opts ...store.OpenOption) (store.TaskStore, error) { +func openProductionTaskStore(ctx context.Context, path string, opts ...store.OpenOption) (storev1.TaskStore, error) { return store.Open(ctx, path, opts...) } @@ -303,7 +304,7 @@ func configDBPath(configuredPath string) string { return configuredPath + "-config.sqlite" } -func manualRequeueTask(ctx context.Context, st store.TaskStore, taskID int64) error { +func manualRequeueTask(ctx context.Context, st storev1.TaskStore, taskID int64) error { task, err := st.TaskByID(ctx, taskID) if err != nil { return err @@ -516,7 +517,7 @@ func recordBootOverlayError(p *atomic.Pointer[string], log *slog.Logger, err err // The insert deliberately outlives ctx: this loop ends when the bus closes, // which is part of shutdown, and the last events of a run are exactly the // ones an operator wants to read afterwards. -func persistEvents(ctx context.Context, sink *events.Sub, st store.TaskStore, log *slog.Logger) { +func persistEvents(ctx context.Context, sink *events.Sub, st storev1.TaskStore, log *slog.Logger) { ctx = context.WithoutCancel(ctx) for e := range sink.C { if e.ID != 0 { diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index e0be38c0b..3cff36505 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -20,6 +20,7 @@ import ( "google.golang.org/grpc" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" @@ -119,28 +120,28 @@ func (b *boot) openStateStore(ctx context.Context) error { } // stateStoreDeps assembles the store surfaces the StateStore service fronts. -// b.st is the narrow store.TaskStore; the wide *store.Store also implements +// b.st is the narrow storev1.TaskStore; the wide *store.Store also implements // the capture/mapping/binding surfaces, so each is asserted here (the same // pattern the daemon's wireWebStoreSurfaces uses) and a store that lacks one // degrades that group rather than aborting boot. func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants} - if cs, ok := b.st.(store.CaptureStore); ok { + if cs, ok := b.st.(storev1.CaptureStore); ok { deps.Captures = cs } - if ms, ok := b.st.(store.MappingStore); ok { + if ms, ok := b.st.(storev1.MappingStore); ok { deps.Mappings = ms } - if bs, ok := b.st.(store.BindingStore); ok { + if bs, ok := b.st.(storev1.BindingStore); ok { deps.Bindings = bs } - if bd, ok := b.st.(store.BindingDispatcher); ok { + if bd, ok := b.st.(storev1.BindingDispatcher); ok { deps.BindingDispatcher = bd } - if btc, ok := b.st.(store.BindingTaskCreator); ok { + if btc, ok := b.st.(storev1.BindingTaskCreator); ok { deps.BindingTaskCreator = btc } - if css, ok := b.st.(store.ConfigSnapshotStore); ok { + if css, ok := b.st.(storev1.ConfigSnapshotStore); ok { deps.ConfigSnapshots = css } return deps diff --git a/internal/app/archied/telegram_setup.go b/internal/app/archied/telegram_setup.go index eba96636b..7cbf6405b 100644 --- a/internal/app/archied/telegram_setup.go +++ b/internal/app/archied/telegram_setup.go @@ -16,6 +16,7 @@ import ( channelruntime "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/channels/telegram" "github.com/samcharles93/archie-core/internal/config" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" @@ -24,7 +25,6 @@ import ( "github.com/samcharles93/archie-core/internal/releaseannounce" "github.com/samcharles93/archie-core/internal/releaseupdate" "github.com/samcharles93/archie-core/internal/secret" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/tools" ) @@ -38,7 +38,7 @@ type telegramSetup struct { Cfg *config.Holder CfgPath string OverlayPath string - St store.TaskStore + St storev1.TaskStore LLM *runtime.Runtime ChatModels gateway.ModelManager ToolReg *tools.Registry diff --git a/internal/app/archieui/compose.go b/internal/app/archieui/compose.go index 05b1e88ac..46fb38fe4 100644 --- a/internal/app/archieui/compose.go +++ b/internal/app/archieui/compose.go @@ -5,11 +5,11 @@ import ( "log/slog" "time" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/captureintake" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/webhookguard" "github.com/samcharles93/archie-core/internal/webui" ) @@ -20,7 +20,7 @@ import ( type deps struct { Options Options Log *slog.Logger - Store store.TaskStore + Store storev1.TaskStore Chat gateway.ChatContract Health *health.Registry } @@ -61,17 +61,17 @@ func compose(d deps) *webui.Server { TrustForwardedHeaders: d.Options.trustForwardedHeaders(), Health: d.Health, } - if snapshots, ok := d.Store.(store.ConfigSnapshotStore); ok { + if snapshots, ok := d.Store.(storev1.ConfigSnapshotStore); ok { srv.ConfigSource = webui.RemoteConfigView(snapshots) } // Mappings and bindings are ratified State Store contracts, and the same // client already carries them: withholding them would degrade two pages // that have an owner, which is a different thing from the intake surfaces // below. - if mappings, ok := d.Store.(store.MappingStore); ok { + if mappings, ok := d.Store.(storev1.MappingStore); ok { srv.Mappings = mappings } - if bindings, ok := d.Store.(store.BindingStore); ok { + if bindings, ok := d.Store.(storev1.BindingStore); ok { srv.Bindings = bindings } if d.Chat != nil { @@ -88,8 +88,8 @@ func compose(d deps) *webui.Server { // implement one degrades that half with a warning rather than aborting the // process, mirroring the daemon's own adapter selection. func wireCaptureSurfaces(d deps, srv *webui.Server) { - captures, hasCaptures := d.Store.(store.CaptureStore) - bindings, hasBindings := d.Store.(store.BindingDispatcher) + captures, hasCaptures := d.Store.(storev1.CaptureStore) + bindings, hasBindings := d.Store.(storev1.BindingDispatcher) if !hasCaptures { d.Log.Warn("capture storage unavailable: state store does not implement CaptureStore") return diff --git a/internal/app/archieui/readiness.go b/internal/app/archieui/readiness.go index de1b7610d..f7d2c67aa 100644 --- a/internal/app/archieui/readiness.go +++ b/internal/app/archieui/readiness.go @@ -3,10 +3,10 @@ package archieui import ( "context" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" - "github.com/samcharles93/archie-core/internal/store" ) // newReadinessRegistry builds the registry behind GET /health/detailed. The @@ -17,7 +17,7 @@ import ( // // The component names match the daemon dashboard's, so the readiness view // reads the same whichever process serves it. -func newReadinessRegistry(o Options, tasks store.TaskStore, chat gateway.ChatContract) *health.Registry { +func newReadinessRegistry(o Options, tasks storev1.TaskStore, chat gateway.ChatContract) *health.Registry { return health.NewRegistry( readiness.NewContractProbe("state_db", o.DependencyTimeout, func(ctx context.Context) error { _, err := tasks.StatusCounts(ctx) diff --git a/internal/contracts/store/v1/contracts.go b/internal/contracts/store/v1/contracts.go new file mode 100644 index 000000000..a7f0af6e7 --- /dev/null +++ b/internal/contracts/store/v1/contracts.go @@ -0,0 +1,242 @@ +// Package storev1 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. +// +// The package is hand-written, unlike its proto-generated siblings under +// internal/contracts/{gateway,state}/v1: the gRPC fronting service +// (statev1.StateStoreService) is generated, but these Go consumer facades +// predate it and stay narrow (<= 8 methods except the TaskStore composite) +// per the same document. Relocated from internal/store by the UI Service +// deletion gate (archie-core-8cda.5.6); internal/store keeps type aliases so +// daemon-side callers are unaffected. +package storev1 + +import ( + "context" + "errors" + "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" + "github.com/samcharles93/archie-core/internal/events" +) + +// 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) (*workflow.Task, error) + ClaimNext(ctx context.Context) (*workflow.Task, error) + ClaimByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) + Transition(ctx context.Context, taskID int64, from, to, detail string) error + Update(ctx context.Context, t *workflow.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) (*workflow.Task, error) + TaskByID(ctx context.Context, taskID int64) (*workflow.Task, error) + OpenPRs(ctx context.Context) ([]workflow.Task, error) + ClearTerminalTasks(ctx context.Context) (int64, error) + Tasks(ctx context.Context, limit int) ([]workflow.Task, error) + StatusCounts(ctx context.Context) (map[string]int, error) + IncrementRetryCount(ctx context.Context, taskID int64) 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) (int64, 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) +} + +// 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) (int64, error) + GetMapping(ctx context.Context, id int64) (*mapping.Mapping, error) + ListMappings(ctx context.Context) ([]mapping.Mapping, error) + UpdateMapping(ctx context.Context, m mapping.Mapping) error + DeleteMapping(ctx context.Context, id int64) 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) (int64, error) + GetBinding(ctx context.Context, id int64) (*binding.Binding, error) + ListBindings(ctx context.Context) ([]binding.Binding, error) + UpdateBinding(ctx context.Context, b binding.Binding) error + DeleteBinding(ctx context.Context, id int64) error + ApproveBinding(ctx context.Context, id int64) 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 int64, + bindingVersion int64, + captureID int64, + 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 string, bindingID int64, bindingVersion int) (*workflow.Task, 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 int64 `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 +} + +// 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 capture already has a + // dispatch ledger row (at-most-once dispatch). + 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") +) diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index f694989c4..b258e3004 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -17,6 +17,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/mapping" @@ -29,7 +30,6 @@ import ( "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/storage" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskrun" "github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/worktree" @@ -100,26 +100,26 @@ type Daemon struct { // remote archie-state-store service; it is always the configured // [services.state].target after the in-process serving path is deleted. ConnectedStateStore StateStoreEndpoint - Store store.TaskStore + Store storev1.TaskStore // Mappings persists payload field mappings (docs/prds/payload-field-mapping.md). // Used by the binding dispatch loop to resolve capture bodies against // the mapping a binding names. Optional: nil disables the binding // dispatch loop (legacy behaviour). - Mappings store.MappingStore + Mappings storev1.MappingStore // Bindings persists playbook bindings (docs/prds/playbook-binding.md). // Optional: nil disables the binding dispatch loop (legacy behaviour). - Bindings store.BindingStore + Bindings storev1.BindingStore // BindingDispatcher is the dispatch-time helper surface for bindings: // list undispatched captures, look up armed bindings by source for the // matcher, and write the at-most-once dedup ledger row. Split from // BindingStore to keep the CRUD interface under the interfacebloat // limit. Optional: nil disables the dispatch loop. - BindingDispatcher store.BindingDispatcher + BindingDispatcher storev1.BindingDispatcher // BindingTaskCreator enqueues a task triggered by a binding. Split // off TaskLifecycle so the lifecycle surface stays narrow and the // dispatch loop does not acquire the full task-creation contract. // Optional: nil disables the dispatch loop. - BindingTaskCreator store.BindingTaskCreator + BindingTaskCreator storev1.BindingTaskCreator Forge forge.Forge Trees *worktree.Manager Bus *events.Bus @@ -517,7 +517,7 @@ const bindingDispatchBatchLimit = 100 // // The binding_dispatches ledger is the at-most-once guarantee across // cycles and daemon restarts: RecordDispatch returns -// store.ErrAlreadyDispatched on a duplicate (binding_id, capture_id) +// storev1.ErrAlreadyDispatched on a duplicate (binding_id, capture_id) // pair, and dispatchOneBinding treats that as a normal "another cycle // raced us" outcome rather than an error. // @@ -580,7 +580,7 @@ func (d *Daemon) dispatchBindings(ctx context.Context) { // repo (when exactly one is configured); binding.Owner/Repo is a // follow-up so multi-repo deployments don't have to live with the // ambiguity. -func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c store.CapturedEvent) { +func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storev1.CapturedEvent) { if d.Mappings == nil { d.Log.Warn("binding dispatch: mapping store unavailable", "binding", b.ID) return @@ -623,7 +623,7 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st } if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, task.ID); err != nil { - if errors.Is(err, store.ErrAlreadyDispatched) { + if errors.Is(err, storev1.ErrAlreadyDispatched) { // Another cycle or daemon instance raced us and already // recorded the dispatch. The duplicate task remains // queued (delete-on-races is its own can of worms), @@ -664,7 +664,7 @@ func hasBlockingFailure(fields []mapping.Field, failures []mapping.Failure) bool // resolved, one "key=value" pair per line. Empty maps still produce // a body that records the source capture id so the workflow has // provenance to hand back to the operator. -func renderBindingBody(values map[string]any, c store.CapturedEvent) string { +func renderBindingBody(values map[string]any, c storev1.CapturedEvent) string { if len(values) == 0 { return fmt.Sprintf("(no fields resolved from capture %d)", c.ID) } @@ -1283,7 +1283,7 @@ func (d *Daemon) acquireTaskContainer( // that survives cancellation while preserving values. // // The transition remains guarded from StatusRunning: if the worker already -// recorded a terminal state over storerpc, store.ErrStaleTransition is returned +// recorded a terminal state over storerpc, storev1.ErrStaleTransition is returned // and ignored. Unexpected store errors are logged as warnings. func (d *Daemon) parkRunningTask(ctx context.Context, taskID int64, reason string) { if d.Store == nil { @@ -1293,7 +1293,7 @@ func (d *Daemon) parkRunningTask(ctx context.Context, taskID int64, reason strin defer cancel() if err := d.Store.Transition(writeCtx, taskID, workflow.StatusRunning, workflow.StatusParked, reason); err != nil { - if !errors.Is(err, store.ErrStaleTransition) { + if !errors.Is(err, storev1.ErrStaleTransition) { d.Log.Warn("terminal park transition failed", "task", taskID, "reason", reason, "err", err) } } diff --git a/internal/infrastructure/captureintake/receiver.go b/internal/infrastructure/captureintake/receiver.go index bcc975018..24a247418 100644 --- a/internal/infrastructure/captureintake/receiver.go +++ b/internal/infrastructure/captureintake/receiver.go @@ -22,9 +22,9 @@ import ( "net/http" "time" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/webhookguard" ) @@ -37,7 +37,7 @@ type Receiver struct { // Captures persists what arrives. Nil answers 503 rather than failing // the process it is mounted in: capture is a precondition for the // no-code playbook epic, not a hard dependency of the daemon. - Captures store.CaptureStore + Captures storev1.CaptureStore // Limiter is the per-remote-address token bucket applied before a body // is read. Nil disables rate limiting, which composition never does in // production. @@ -45,7 +45,7 @@ type Receiver struct { // Bindings resolves the armed binding whose secret authenticates a // source. Nil disables per-source HMAC verification and every event // records as authenticated=false. - Bindings store.BindingDispatcher + Bindings storev1.BindingDispatcher // Retention and MaxEvents are passed straight to InsertCapture's // prune-on-write bounds. See config.CaptureConfig. Retention time.Duration @@ -135,7 +135,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { redactedBody = body } - c := store.CapturedEvent{ + c := storev1.CapturedEvent{ ReceivedAt: time.Now().UTC(), Source: source, RemoteAddr: r.RemoteAddr, diff --git a/internal/infrastructure/configuration/denied_keys.go b/internal/infrastructure/configuration/denied_keys.go new file mode 100644 index 000000000..935989947 --- /dev/null +++ b/internal/infrastructure/configuration/denied_keys.go @@ -0,0 +1,14 @@ +package configuration + +// DeniedKeys are the config keys the runtime overlay may never set, mapped +// to the reason shown to the operator. db_path is the daemon's own bootstrap +// path -- the daemon must read it before it can open the overlay store -- +// and work_dir pins the whole working layout. Enforced at write time (the +// API returns 4xx) and again in the overlay's Set, not silently dropped at +// read time. Owned here rather than in the overlay package so the webui +// config renderer can reference the policy without linking the overlay's +// SQLite store (archie-core-8cda.5.6). +var DeniedKeys = map[string]string{ + "db_path": "required for bootstrap; cannot be changed at runtime", + "work_dir": "pins the daemon's working layout; cannot be changed at runtime", +} diff --git a/internal/infrastructure/configuration/overlay/overlay.go b/internal/infrastructure/configuration/overlay/overlay.go index 2ad794e43..c65f1a864 100644 --- a/internal/infrastructure/configuration/overlay/overlay.go +++ b/internal/infrastructure/configuration/overlay/overlay.go @@ -22,18 +22,14 @@ import ( "time" _ "modernc.org/sqlite" + + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" ) -// DeniedKeys are the config keys the overlay may never set, mapped to -// the reason shown to the operator. db_path is the daemon's own -// bootstrap path -- the daemon must read it before it can open this -// store -- and work_dir pins the whole working layout. Enforced at -// write time (the API returns 4xx) and again in Set, not silently -// dropped at read time. -var DeniedKeys = map[string]string{ - "db_path": "required for bootstrap; cannot be changed at runtime", - "work_dir": "pins the daemon's working layout; cannot be changed at runtime", -} +// DeniedKeys moved to internal/infrastructure/configuration ( DeniedKeys): +// webui references the constant and must not link this package's SQLite +// store (archie-core-8cda.5.6). +var DeniedKeys = configuration.DeniedKeys // Store is the config overlay database. type Store struct{ db *sql.DB } diff --git a/internal/infrastructure/gatewayrpc/task_action_errors.go b/internal/infrastructure/gatewayrpc/task_action_errors.go index 970611246..07b4d658e 100644 --- a/internal/infrastructure/gatewayrpc/task_action_errors.go +++ b/internal/infrastructure/gatewayrpc/task_action_errors.go @@ -6,8 +6,8 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/taskactions" - "github.com/samcharles93/archie-core/internal/store" ) // taskActionCodes pairs each sentinel the daemon's action service reports @@ -22,7 +22,7 @@ var taskActionCodes = []struct { }{ {code: codes.NotFound, err: taskactions.ErrNotFound}, {code: codes.FailedPrecondition, err: taskactions.ErrConflict}, - {code: codes.Aborted, err: store.ErrStaleTransition}, + {code: codes.Aborted, err: storev1.ErrStaleTransition}, {code: codes.Unavailable, err: taskactions.ErrUnavailable}, } diff --git a/internal/infrastructure/staterpc/client.go b/internal/infrastructure/staterpc/client.go index 1f4b7f7e0..00a3a5cfd 100644 --- a/internal/infrastructure/staterpc/client.go +++ b/internal/infrastructure/staterpc/client.go @@ -9,11 +9,11 @@ import ( "google.golang.org/grpc" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/store" ) // Client is the single remote adapter wrapping one StateStoreServiceClient, @@ -34,14 +34,14 @@ func NewClient(conn grpc.ClientConnInterface) *Client { func (c *Client) Close() error { return nil } var ( - _ workflow.Store = (*Client)(nil) - _ store.TaskStore = (*Client)(nil) - _ store.CaptureStore = (*Client)(nil) - _ store.MappingStore = (*Client)(nil) - _ store.BindingStore = (*Client)(nil) - _ store.BindingDispatcher = (*Client)(nil) - _ store.BindingTaskCreator = (*Client)(nil) - _ store.ConfigSnapshotStore = (*Client)(nil) + _ workflow.Store = (*Client)(nil) + _ storev1.TaskStore = (*Client)(nil) + _ storev1.CaptureStore = (*Client)(nil) + _ storev1.MappingStore = (*Client)(nil) + _ storev1.BindingStore = (*Client)(nil) + _ storev1.BindingDispatcher = (*Client)(nil) + _ storev1.BindingTaskCreator = (*Client)(nil) + _ storev1.ConfigSnapshotStore = (*Client)(nil) ) // Lifecycle @@ -213,7 +213,7 @@ func (c *Client) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, return mapValues(r.Events, eventValue), nil } -func (c *Client) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, error) { +func (c *Client) WorkflowStats(ctx context.Context) ([]storev1.WorkflowStat, error) { r, err := c.client.WorkflowStats(ctx, &pb.WorkflowStatsRequest{}) if err != nil { return nil, unmapError(err) @@ -221,7 +221,7 @@ func (c *Client) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, error return mapValues(r.Stats, workflowStatValue), nil } -func (c *Client) StageStats(ctx context.Context) ([]store.StageStat, error) { +func (c *Client) StageStats(ctx context.Context) ([]storev1.StageStat, error) { r, err := c.client.StageStats(ctx, &pb.StageStatsRequest{}) if err != nil { return nil, unmapError(err) @@ -229,7 +229,7 @@ func (c *Client) StageStats(ctx context.Context) ([]store.StageStat, error) { return mapValues(r.Stats, stageStatValue), nil } -func (c *Client) TokensByDay(ctx context.Context, days int) ([]store.DayTokens, error) { +func (c *Client) TokensByDay(ctx context.Context, days int) ([]storev1.DayTokens, error) { r, err := c.client.TokensByDay(ctx, &pb.TokensByDayRequest{Days: int64(days)}) if err != nil { return nil, unmapError(err) @@ -239,7 +239,7 @@ func (c *Client) TokensByDay(ctx context.Context, days int) ([]store.DayTokens, // Capture -func (c *Client) InsertCapture(ctx context.Context, ce store.CapturedEvent, retention time.Duration, maxEvents int) (int64, error) { +func (c *Client) InsertCapture(ctx context.Context, ce storev1.CapturedEvent, retention time.Duration, maxEvents int) (int64, error) { r, err := c.client.InsertCapture(ctx, &pb.InsertCaptureRequest{Capture: capturedEventProto(ce), RetentionSeconds: int64(retention.Seconds()), MaxEvents: int64(maxEvents)}) if err != nil { return 0, unmapError(err) @@ -253,7 +253,7 @@ func (c *Client) InsertCapture(ctx context.Context, ce store.CapturedEvent, rete // PutConfigSnapshot publishes the dashboard's configuration projection. The // server admits it on the administrative token only; a task-scoped grant // cannot reach it (see TaskGrants). -func (c *Client) PutConfigSnapshot(ctx context.Context, snapshot store.ConfigSnapshot) error { +func (c *Client) PutConfigSnapshot(ctx context.Context, snapshot storev1.ConfigSnapshot) error { _, err := c.client.PutConfigSnapshot(ctx, &pb.PutConfigSnapshotRequest{Snapshot: configSnapshotProto(snapshot)}) if err != nil { return unmapError(err) @@ -263,23 +263,23 @@ func (c *Client) PutConfigSnapshot(ctx context.Context, snapshot store.ConfigSna // ConfigSnapshot reads the published projection. found is false, with a nil // error, before a daemon has published one. -func (c *Client) ConfigSnapshot(ctx context.Context) (store.ConfigSnapshot, bool, error) { +func (c *Client) ConfigSnapshot(ctx context.Context) (storev1.ConfigSnapshot, bool, error) { reply, err := c.client.GetConfigSnapshot(ctx, &pb.GetConfigSnapshotRequest{}) if err != nil { - return store.ConfigSnapshot{}, false, unmapError(err) + return storev1.ConfigSnapshot{}, false, unmapError(err) } if !reply.Found { - return store.ConfigSnapshot{}, false, nil + return storev1.ConfigSnapshot{}, false, nil } return configSnapshotValue(reply.Snapshot), true, nil } -func (c *Client) ListCaptures(ctx context.Context, limit int) ([]store.CapturedEvent, error) { +func (c *Client) ListCaptures(ctx context.Context, limit int) ([]storev1.CapturedEvent, error) { stream, err := c.client.StreamCaptures(ctx, &pb.StreamCapturesRequest{Limit: int64(limit)}) if err != nil { return nil, unmapError(err) } - var captures []store.CapturedEvent + var captures []storev1.CapturedEvent for { r, err := stream.Recv() if errors.Is(err, io.EOF) { @@ -394,12 +394,12 @@ func (c *Client) RecordDispatch(ctx context.Context, bindingID, bindingVersion, // ListUndispatchedCaptures calls StreamUndispatchedCaptures; see ListCaptures // above. -func (c *Client) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]store.CapturedEvent, error) { +func (c *Client) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storev1.CapturedEvent, error) { stream, err := c.client.StreamUndispatchedCaptures(ctx, &pb.StreamUndispatchedCapturesRequest{Sources: sources, Limit: int64(limit)}) if err != nil { return nil, unmapError(err) } - var captures []store.CapturedEvent + var captures []storev1.CapturedEvent for { r, err := stream.Recv() if errors.Is(err, io.EOF) { diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index 5d628690b..f4834d54f 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -14,9 +14,9 @@ import ( "google.golang.org/grpc/status" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" - "github.com/samcharles93/archie-core/internal/store" ) // Unavailable-capability errors, mirroring gatewayrpc's missing-session-store @@ -40,13 +40,13 @@ func timeSeconds(s int64) time.Duration { return time.Duration(s) * time.Second // nil Mappings/Bindings/BindingDispatcher/BindingTaskCreator as "disabled". type Deps struct { Grants *TaskGrants - Tasks store.TaskStore - Captures store.CaptureStore - ConfigSnapshots store.ConfigSnapshotStore - Mappings store.MappingStore - Bindings store.BindingStore - BindingDispatcher store.BindingDispatcher - BindingTaskCreator store.BindingTaskCreator + Tasks storev1.TaskStore + Captures storev1.CaptureStore + ConfigSnapshots storev1.ConfigSnapshotStore + Mappings storev1.MappingStore + Bindings storev1.BindingStore + BindingDispatcher storev1.BindingDispatcher + BindingTaskCreator storev1.BindingTaskCreator Log *slog.Logger } @@ -277,14 +277,14 @@ func (s *server) TokensByDay(ctx context.Context, r *pb.TokensByDayRequest) (*pb // Capture -func (s *server) capture() (store.CaptureStore, error) { +func (s *server) capture() (storev1.CaptureStore, error) { if s.deps.Captures == nil { return nil, errCaptureUnavailable } return s.deps.Captures, nil } -func (s *server) configSnapshots() (store.ConfigSnapshotStore, error) { +func (s *server) configSnapshots() (storev1.ConfigSnapshotStore, error) { if s.deps.ConfigSnapshots == nil { return nil, errConfigSnapshotsUnavailable } @@ -364,7 +364,7 @@ func (s *server) StreamCaptures(r *pb.StreamCapturesRequest, stream pb.StateStor // Mapping -func (s *server) mapping() (store.MappingStore, error) { +func (s *server) mapping() (storev1.MappingStore, error) { if s.deps.Mappings == nil { return nil, errMappingUnavailable } @@ -431,7 +431,7 @@ func (s *server) DeleteMapping(ctx context.Context, r *pb.DeleteMappingRequest) // Binding -func (s *server) binding() (store.BindingStore, error) { +func (s *server) binding() (storev1.BindingStore, error) { if s.deps.Bindings == nil { return nil, errBindingUnavailable } diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index c86dd1cf5..bb32a8522 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -12,11 +12,11 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/store" ) func timestamp(t time.Time) *timestamppb.Timestamp { @@ -119,7 +119,7 @@ func eventValue(e *pb.Event) events.Event { } } -func capturedEventProto(c store.CapturedEvent) *pb.CapturedEvent { +func capturedEventProto(c storev1.CapturedEvent) *pb.CapturedEvent { return &pb.CapturedEvent{ Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source, RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers, @@ -127,11 +127,11 @@ func capturedEventProto(c store.CapturedEvent) *pb.CapturedEvent { } } -func capturedEventValue(c *pb.CapturedEvent) store.CapturedEvent { +func capturedEventValue(c *pb.CapturedEvent) storev1.CapturedEvent { if c == nil { - return store.CapturedEvent{} + return storev1.CapturedEvent{} } - return store.CapturedEvent{ + return storev1.CapturedEvent{ ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source, RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers, Body: c.Body, Authenticated: c.Authenticated, @@ -193,7 +193,7 @@ func bindingValue(b *pb.Binding) binding.Binding { } } -func workflowStatProto(w store.WorkflowStat) *pb.WorkflowStat { +func workflowStatProto(w storev1.WorkflowStat) *pb.WorkflowStat { return &pb.WorkflowStat{ Workflow: w.Workflow, Runs: int64(w.Runs), Merged: int64(w.Merged), PrOpen: int64(w.PROpen), Parked: int64(w.Parked), AvgTokens: int64(w.AvgTokens), @@ -201,37 +201,37 @@ func workflowStatProto(w store.WorkflowStat) *pb.WorkflowStat { } } -func workflowStatValue(w *pb.WorkflowStat) store.WorkflowStat { +func workflowStatValue(w *pb.WorkflowStat) storev1.WorkflowStat { if w == nil { - return store.WorkflowStat{} + return storev1.WorkflowStat{} } - return store.WorkflowStat{ + return storev1.WorkflowStat{ Workflow: w.Workflow, Runs: int(w.Runs), Merged: int(w.Merged), PROpen: int(w.PrOpen), Parked: int(w.Parked), AvgTokens: int(w.AvgTokens), AvgSteps: w.AvgSteps, TotalToken: int(w.TotalTokens), } } -func stageStatProto(s store.StageStat) *pb.StageStat { +func stageStatProto(s storev1.StageStat) *pb.StageStat { return &pb.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int64(s.Runs), AvgMs: int64(s.AvgMs), Errors: int64(s.Errors)} } -func stageStatValue(s *pb.StageStat) store.StageStat { +func stageStatValue(s *pb.StageStat) storev1.StageStat { if s == nil { - return store.StageStat{} + return storev1.StageStat{} } - return store.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int(s.Runs), AvgMs: int(s.AvgMs), Errors: int(s.Errors)} + return storev1.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int(s.Runs), AvgMs: int(s.AvgMs), Errors: int(s.Errors)} } -func dayTokensProto(d store.DayTokens) *pb.DayTokens { +func dayTokensProto(d storev1.DayTokens) *pb.DayTokens { return &pb.DayTokens{Day: d.Day, Tokens: int64(d.Tokens)} } -func dayTokensValue(d *pb.DayTokens) store.DayTokens { +func dayTokensValue(d *pb.DayTokens) storev1.DayTokens { if d == nil { - return store.DayTokens{} + return storev1.DayTokens{} } - return store.DayTokens{Day: d.Day, Tokens: int(d.Tokens)} + return storev1.DayTokens{Day: d.Day, Tokens: int(d.Tokens)} } // Canonical public phrases for sentinel errors (rev. 2c §7). These strings @@ -271,17 +271,17 @@ func mapError(err error) error { return status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error()) } switch { - case errors.Is(err, store.ErrStaleTransition): + case errors.Is(err, storev1.ErrStaleTransition): return status.Error(codes.FailedPrecondition, msgStaleTransition) - case errors.Is(err, store.ErrBindingNotFound): + case errors.Is(err, storev1.ErrBindingNotFound): return status.Error(codes.NotFound, msgBindingNotFound) - case errors.Is(err, store.ErrMappingNotFound): + case errors.Is(err, storev1.ErrMappingNotFound): return status.Error(codes.NotFound, msgMappingNotFound) - case errors.Is(err, store.ErrBindingOverlap): + case errors.Is(err, storev1.ErrBindingOverlap): return status.Error(codes.FailedPrecondition, msgBindingOverlap) - case errors.Is(err, store.ErrBindingTransition): + case errors.Is(err, storev1.ErrBindingTransition): return status.Error(codes.FailedPrecondition, msgBindingTransition) - case errors.Is(err, store.ErrAlreadyDispatched): + case errors.Is(err, storev1.ErrAlreadyDispatched): return status.Error(codes.AlreadyExists, msgAlreadyDispatched) default: return status.Error(codes.Internal, msgInternal) @@ -289,7 +289,7 @@ func mapError(err error) error { } // unmapError rehydrates a gRPC status error back to the store sentinel it -// came from, so a caller's errors.Is(err, store.ErrX) keeps working across +// came from, so a caller's errors.Is(err, storev1.ErrX) keeps working across // the wire. A non-status error (e.g. a transport failure) is returned // unchanged. // @@ -317,22 +317,22 @@ func unmapError(err error) error { case codes.FailedPrecondition: switch st.Message() { case msgStaleTransition: - return store.ErrStaleTransition + return storev1.ErrStaleTransition case msgBindingOverlap: - return store.ErrBindingOverlap + return storev1.ErrBindingOverlap case msgBindingTransition: - return store.ErrBindingTransition + return storev1.ErrBindingTransition } case codes.NotFound: switch st.Message() { case msgBindingNotFound: - return store.ErrBindingNotFound + return storev1.ErrBindingNotFound case msgMappingNotFound: - return store.ErrMappingNotFound + return storev1.ErrMappingNotFound } case codes.AlreadyExists: if st.Message() == msgAlreadyDispatched { - return store.ErrAlreadyDispatched + return storev1.ErrAlreadyDispatched } } return fmt.Errorf("state store: %s: %w", st.Message(), err) @@ -341,7 +341,7 @@ func unmapError(err error) error { // configSnapshotProto and configSnapshotValue carry the dashboard's // configuration projection. document crosses as bytes, unread by either side // of this hop: the store holds it and the page renders it. -func configSnapshotProto(snapshot store.ConfigSnapshot) *pb.ConfigSnapshot { +func configSnapshotProto(snapshot storev1.ConfigSnapshot) *pb.ConfigSnapshot { return &pb.ConfigSnapshot{ Schema: snapshot.Schema, Document: snapshot.Document, @@ -349,11 +349,11 @@ func configSnapshotProto(snapshot store.ConfigSnapshot) *pb.ConfigSnapshot { } } -func configSnapshotValue(snapshot *pb.ConfigSnapshot) store.ConfigSnapshot { +func configSnapshotValue(snapshot *pb.ConfigSnapshot) storev1.ConfigSnapshot { if snapshot == nil { - return store.ConfigSnapshot{} + return storev1.ConfigSnapshot{} } - return store.ConfigSnapshot{ + return storev1.ConfigSnapshot{ Schema: snapshot.Schema, Document: snapshot.Document, PublishedAt: timeValue(snapshot.PublishedAt), diff --git a/internal/infrastructure/taskactions/rpc.go b/internal/infrastructure/taskactions/rpc.go index acd3acd0a..14d8db540 100644 --- a/internal/infrastructure/taskactions/rpc.go +++ b/internal/infrastructure/taskactions/rpc.go @@ -10,10 +10,10 @@ import ( "github.com/nats-io/nats.go" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/natsrpc" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -49,7 +49,7 @@ var actionErrorKinds = []struct { }{ {kind: "not_found", err: taskactions.ErrNotFound}, {kind: "conflict", err: taskactions.ErrConflict}, - {kind: "stale_transition", err: store.ErrStaleTransition}, + {kind: "stale_transition", err: storev1.ErrStaleTransition}, {kind: "unavailable", err: taskactions.ErrUnavailable}, } diff --git a/internal/infrastructure/taskactions/store.go b/internal/infrastructure/taskactions/store.go index 77b8afa8a..334cbb2d1 100644 --- a/internal/infrastructure/taskactions/store.go +++ b/internal/infrastructure/taskactions/store.go @@ -5,11 +5,11 @@ import ( "context" "github.com/samcharles93/archie-core/internal/config" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/taskactions" - "github.com/samcharles93/archie-core/internal/store" ) -type Store struct{ store.TaskStore } +type Store struct{ storev1.TaskStore } func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error) { t, err := s.TaskStore.TaskByID(ctx, id) diff --git a/internal/store/bindings.go b/internal/store/bindings.go index 87bfe7c4f..395e337d4 100644 --- a/internal/store/bindings.go +++ b/internal/store/bindings.go @@ -42,25 +42,21 @@ CREATE TABLE IF NOT EXISTS binding_dispatches ( // row matches the given ID. GetBinding uses (nil, nil) instead, matching // TaskByID's convention -- "not found" is the normal answer to "does a // binding with this ID currently exist," not an error. -var ErrBindingNotFound = errors.New("store: binding not found") // ErrBindingOverlap is returned by InsertBinding and UpdateBinding when a // different binding already covers the same source. Two bindings for one // source would race over the same inbound webhook; the store refuses rather // than picking an arbitrary winner. -var ErrBindingOverlap = errors.New("store: binding overlaps existing binding for source") // ErrBindingTransition is returned by ApproveBinding when the from-status // is anything other than pending_approval. Approve is the only sanctioned // transition into armed, and the guard is the SQL WHERE clause, not a // separate read. -var ErrBindingTransition = errors.New("store: binding state transition rejected") // ErrAlreadyDispatched is returned by RecordDispatch when the (binding_id, // capture_id) pair already exists in binding_dispatches. The dedup ledger is // the at-most-once guarantee per capture; the caller is expected to surface // this to the dispatch loop rather than retry. -var ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture") // bindingTimeLayout follows captureTimeLayout's reasoning: fixed-width // RFC3339 so string and chronological order agree. diff --git a/internal/store/captures.go b/internal/store/captures.go index 2bc063e55..8834d8938 100644 --- a/internal/store/captures.go +++ b/internal/store/captures.go @@ -21,22 +21,6 @@ CREATE TABLE IF NOT EXISTS captured_events ( CREATE INDEX IF NOT EXISTS idx_captured_events_source ON captured_events(source, id); ` -// 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 int64 `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"` -} - // captureTimeLayout is fixed-width (unlike time.RFC3339Nano, whose // fractional-seconds field is trimmed of trailing zeros and omitted // entirely when zero). A variable-width fractional part breaks lexicographic diff --git a/internal/store/config_snapshot.go b/internal/store/config_snapshot.go index 20c6c6d15..97dc680a7 100644 --- a/internal/store/config_snapshot.go +++ b/internal/store/config_snapshot.go @@ -17,20 +17,6 @@ CREATE TABLE IF NOT EXISTS config_snapshot ( ); ` -// 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 -} - // configSnapshotTimeLayout follows the rest of the store's timestamp columns: // fixed-width, so string and chronological order agree. const configSnapshotTimeLayout = time.RFC3339 diff --git a/internal/store/events.go b/internal/store/events.go index 46a39214e..94a734dde 100644 --- a/internal/store/events.go +++ b/internal/store/events.go @@ -150,18 +150,6 @@ func (s *Store) StatusCounts(ctx context.Context) (counts map[string]int, retErr return counts, rows.Err() } -// 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"` -} - // WorkflowStats aggregates outcomes and spend per workflow -- the // core "is archie getting better per dollar" table. func (s *Store) WorkflowStats(ctx context.Context) (stats []WorkflowStat, retErr error) { @@ -187,15 +175,6 @@ func (s *Store) WorkflowStats(ctx context.Context) (stats []WorkflowStat, retErr return stats, rows.Err() } -// 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"` -} - // StageStats aggregates stage_finish events -- where does time go, and // which stages fail. func (s *Store) StageStats(ctx context.Context) (stats []StageStat, retErr error) { @@ -223,12 +202,6 @@ func (s *Store) StageStats(ctx context.Context) (stats []StageStat, retErr error return stats, rows.Err() } -// DayTokens is token spend per UTC day. -type DayTokens struct { - Day string `json:"day"` - Tokens int `json:"tokens"` -} - // TokensByDay sums task token spend per UTC day. Agent-finish events are // the per-run accounting source; tasks.tokens_used is the durable fallback for // older or remote runs whose events were not persisted. diff --git a/internal/store/interface.go b/internal/store/interface.go index fd6f4ab5c..597b79df9 100644 --- a/internal/store/interface.go +++ b/internal/store/interface.go @@ -1,152 +1,51 @@ -// Package store defines the storage abstractions for archied's task and -// event data. TaskStore is the full surface the daemon needs and *Store is its -// SQLite implementation. +// Package store defines the task and event persistence for archied's data. +// TaskStore is the full surface the daemon needs and *Store is its SQLite +// implementation. +// +// REVISED (archie-core-8cda.5.6): the producer-owned contract surfaces this +// package used to define live in internal/contracts/store/v1 (package +// storev1) -- the approved contract location -- so the archie-ui process can +// reference the contract without linking this SQLite implementation. The +// definitions below are type aliases for compatibility with the daemon-side +// callers; new UI-process-facing code imports storev1 directly. package store import ( - "context" - "time" - - "github.com/samcharles93/archie-core/internal/domain/binding" - "github.com/samcharles93/archie-core/internal/domain/mapping" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/workflow" - "github.com/samcharles93/archie-core/internal/events" ) -// 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 -} +// Aliases: the daemon/webui/intake store surfaces moved to storev1. The +// message strings of the sentinel errors are the wire contract (see +// storev1's var block); the aliases change nothing observable. +type ( + TaskStore = storev1.TaskStore + TaskLifecycle = storev1.TaskLifecycle + TaskArchiver = storev1.TaskArchiver + TaskRetryer = storev1.TaskRetryer + TaskQueries = storev1.TaskQueries + TaskEvents = storev1.TaskEvents + CaptureStore = storev1.CaptureStore + ConfigSnapshotStore = storev1.ConfigSnapshotStore + MappingStore = storev1.MappingStore + BindingStore = storev1.BindingStore + BindingDispatcher = storev1.BindingDispatcher + BindingTaskCreator = storev1.BindingTaskCreator + CapturedEvent = storev1.CapturedEvent + ConfigSnapshot = storev1.ConfigSnapshot + WorkflowStat = storev1.WorkflowStat + StageStat = storev1.StageStat + DayTokens = storev1.DayTokens +) -// 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) (*workflow.Task, error) - ClaimNext(ctx context.Context) (*workflow.Task, error) - ClaimByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) - Transition(ctx context.Context, taskID int64, from, to, detail string) error - Update(ctx context.Context, t *workflow.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) (*workflow.Task, error) - TaskByID(ctx context.Context, taskID int64) (*workflow.Task, error) - OpenPRs(ctx context.Context) ([]workflow.Task, error) - ClearTerminalTasks(ctx context.Context) (int64, error) - Tasks(ctx context.Context, limit int) ([]workflow.Task, error) - StatusCounts(ctx context.Context) (map[string]int, error) - IncrementRetryCount(ctx context.Context, taskID int64) 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) (int64, 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) -} - -// 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) (int64, error) - GetMapping(ctx context.Context, id int64) (*mapping.Mapping, error) - ListMappings(ctx context.Context) ([]mapping.Mapping, error) - UpdateMapping(ctx context.Context, m mapping.Mapping) error - DeleteMapping(ctx context.Context, id int64) 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) (int64, error) - GetBinding(ctx context.Context, id int64) (*binding.Binding, error) - ListBindings(ctx context.Context) ([]binding.Binding, error) - UpdateBinding(ctx context.Context, b binding.Binding) error - DeleteBinding(ctx context.Context, id int64) error - ApproveBinding(ctx context.Context, id int64) 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 int64, - bindingVersion int64, - captureID int64, - 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 string, bindingID int64, bindingVersion int) (*workflow.Task, error) -} +var ( + ErrStaleTransition = storev1.ErrStaleTransition + ErrBindingNotFound = storev1.ErrBindingNotFound + ErrBindingOverlap = storev1.ErrBindingOverlap + ErrBindingTransition = storev1.ErrBindingTransition + ErrAlreadyDispatched = storev1.ErrAlreadyDispatched + ErrMappingNotFound = storev1.ErrMappingNotFound +) // Compile-time check: *Store satisfies TaskStore. var _ TaskStore = (*Store)(nil) diff --git a/internal/store/mappings.go b/internal/store/mappings.go index a8614a305..51e7221bd 100644 --- a/internal/store/mappings.go +++ b/internal/store/mappings.go @@ -26,7 +26,6 @@ CREATE TABLE IF NOT EXISTS field_mappings ( // row matches the given ID. GetMapping uses (nil, nil) instead, matching // TaskByID's convention -- "not found" is the normal answer to "does a // mapping with this ID currently exist," not an error. -var ErrMappingNotFound = errors.New("store: mapping not found") // mappingTimeLayout follows captureTimeLayout's reasoning: fixed-width so // string and chronological order agree, even though nothing here prunes on diff --git a/internal/store/store.go b/internal/store/store.go index 7c017d046..ab3a8068f 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -342,7 +342,6 @@ func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int // ErrStaleTransition is returned when a guarded transition fails because // the task's current status does not match the expected from status. -var ErrStaleTransition = errors.New("store: stale transition: task status does not match expected from status") // Transition moves a task to a new status and records the audit detail. The // from status guards the update; a mismatch returns ErrStaleTransition without diff --git a/internal/webui/api_binding.go b/internal/webui/api_binding.go index f646aecd9..dabbb391b 100644 --- a/internal/webui/api_binding.go +++ b/internal/webui/api_binding.go @@ -6,8 +6,8 @@ import ( "net/http" "strconv" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/binding" - "github.com/samcharles93/archie-core/internal/store" ) // bindingRequest is the wire shape POST /api/bindings and @@ -72,7 +72,7 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) { } id, err := s.Bindings.InsertBinding(r.Context(), b) if err != nil { - if errors.Is(err, store.ErrBindingOverlap) { + if errors.Is(err, storev1.ErrBindingOverlap) { http.Error(w, "binding source overlaps an existing binding", http.StatusConflict) return } @@ -150,9 +150,9 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) { } if err := s.Bindings.UpdateBinding(r.Context(), b); err != nil { switch { - case errors.Is(err, store.ErrBindingNotFound): + case errors.Is(err, storev1.ErrBindingNotFound): http.Error(w, "binding not found", http.StatusNotFound) - case errors.Is(err, store.ErrBindingOverlap): + case errors.Is(err, storev1.ErrBindingOverlap): http.Error(w, "binding source overlaps an existing binding", http.StatusConflict) default: s.Log.Error("update binding", "err", err, "id", id) @@ -181,7 +181,7 @@ func (s *Server) handleBindingDelete(w http.ResponseWriter, r *http.Request) { return } if err := s.Bindings.DeleteBinding(r.Context(), id); err != nil { - if errors.Is(err, store.ErrBindingNotFound) { + if errors.Is(err, storev1.ErrBindingNotFound) { http.Error(w, "binding not found", http.StatusNotFound) return } @@ -204,11 +204,11 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) { } if err := s.Bindings.ApproveBinding(r.Context(), id); err != nil { switch { - case errors.Is(err, store.ErrBindingNotFound): + case errors.Is(err, storev1.ErrBindingNotFound): http.Error(w, "binding not found", http.StatusNotFound) - case errors.Is(err, store.ErrBindingTransition): + case errors.Is(err, storev1.ErrBindingTransition): http.Error(w, "binding cannot be approved from its current state", http.StatusConflict) - case errors.Is(err, store.ErrBindingOverlap): + case errors.Is(err, storev1.ErrBindingOverlap): http.Error(w, "binding source overlaps an existing binding", http.StatusConflict) default: s.Log.Error("approve binding", "err", err, "id", id) diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index bb5045962..73e316265 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -12,9 +12,9 @@ import ( "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/secret" - "github.com/samcharles93/archie-core/internal/store" ) // Sentinel errors for handleConfigUpdate status classification. The @@ -359,7 +359,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { // LocalConfigView builds the projection from the configuration this process // holds. It is what the daemon serves and, byte for byte, what it publishes -// for the UI process to render (see store.ConfigSnapshot). +// for the UI process to render (see storev1.ConfigSnapshot). // // Every value here is read from one config snapshot taken up front: under the // Holder a reload swaps the whole value, which is what a read-only view @@ -437,7 +437,7 @@ func (s *Server) LocalConfigView(ctx context.Context) (ConfigView, bool, error) // RemoteConfigView reads the projection the configuration owner published. // The reading process cannot edit it: it has no update path, and the page is // told so rather than offering a control that would 503. -func RemoteConfigView(snapshots store.ConfigSnapshotStore) ConfigViewSource { +func RemoteConfigView(snapshots storev1.ConfigSnapshotStore) ConfigViewSource { return func(ctx context.Context) (ConfigView, bool, error) { snapshot, found, err := snapshots.ConfigSnapshot(ctx) if err != nil || !found { @@ -493,8 +493,8 @@ func (s *Server) handleConfigReset(w http.ResponseWriter, r *http.Request) { // bootstrap inputs; changing them from the dashboard could break the // next boot. func lockedConfigKeys() map[string]string { - out := make(map[string]string, len(overlay.DeniedKeys)) - maps.Copy(out, overlay.DeniedKeys) + out := make(map[string]string, len(configuration.DeniedKeys)) + maps.Copy(out, configuration.DeniedKeys) return out } diff --git a/internal/webui/api_mapping.go b/internal/webui/api_mapping.go index f4505e8ff..54c943055 100644 --- a/internal/webui/api_mapping.go +++ b/internal/webui/api_mapping.go @@ -7,8 +7,8 @@ import ( "net/http" "strconv" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/mapping" - "github.com/samcharles93/archie-core/internal/store" ) // mappingRequest is the wire shape POST /api/mappings and @@ -109,7 +109,7 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) { return } if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil { - if errors.Is(err, store.ErrMappingNotFound) { + if errors.Is(err, storev1.ErrMappingNotFound) { http.Error(w, "mapping not found", http.StatusNotFound) return } @@ -137,7 +137,7 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) { return } if err := s.Mappings.DeleteMapping(r.Context(), id); err != nil { - if errors.Is(err, store.ErrMappingNotFound) { + if errors.Is(err, storev1.ErrMappingNotFound) { http.Error(w, "mapping not found", http.StatusNotFound) return } @@ -192,7 +192,7 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) { // exactly one reader, the dashboard list view, so a by-ID lookup was never // needed until preview), so this scans the newest window rather than // adding a new store method for a single low-volume caller. -func (s *Server) captureByID(ctx context.Context, id int64) (*store.CapturedEvent, error) { +func (s *Server) captureByID(ctx context.Context, id int64) (*storev1.CapturedEvent, error) { captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents)) if err != nil { return nil, err diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 5dfbc82d5..13b402064 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -13,10 +13,10 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/config" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -152,7 +152,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { switch { case errors.Is(err, taskactions.ErrNotFound): http.Error(w, "task not found", http.StatusNotFound) - case errors.Is(err, taskactions.ErrConflict), errors.Is(err, store.ErrStaleTransition): + case errors.Is(err, taskactions.ErrConflict), errors.Is(err, storev1.ErrStaleTransition): http.Error(w, err.Error(), http.StatusConflict) case errors.Is(err, taskactions.ErrUnavailable): http.Error(w, err.Error(), http.StatusServiceUnavailable) diff --git a/internal/webui/config_schema.go b/internal/webui/config_schema.go index 5314e508d..53a255d50 100644 --- a/internal/webui/config_schema.go +++ b/internal/webui/config_schema.go @@ -46,10 +46,10 @@ type ConfigField struct { // cannot change yet (structured fields without an editor). It is // distinct from LockedReason: Editable is a schema-time property of // the field itself; LockedReason is a runtime property of the running - // config (overlay.DeniedKeys). + // config (configuration.DeniedKeys). Editable bool `json:"editable"` // LockedReason is set per instance from the running config's denied - // keys (overlay.DeniedKeys), not hand-authored here. + // keys (configuration.DeniedKeys), not hand-authored here. LockedReason string `json:"locked_reason,omitempty"` // Overridden is set per instance from the running config's overlay // state, not hand-authored here. @@ -94,7 +94,7 @@ type ConfigSection struct { // restart even though the dashboard already renders it as editable. // - Web, SkillsDir, PluginDir, SecretEngineDir are absent from both // allowlists entirely, so they require a restart. -// - WorkDir and DBPath are locked (overlay.DeniedKeys), not merely +// - WorkDir and DBPath are locked (configuration.DeniedKeys), not merely // restart-required -- the dashboard cannot change them at all. func configFieldDescriptors() []ConfigSection { return []ConfigSection{ diff --git a/internal/webui/server.go b/internal/webui/server.go index 0052ba829..c87033dac 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -18,6 +18,7 @@ import ( "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/config" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/workflow" @@ -25,12 +26,11 @@ import ( "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/memory" - "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/ui" ) type Server struct { - Store store.TaskStore + Store storev1.TaskStore Log *slog.Logger // Cfg backs the setup checklist and configuration views. Optional: the @@ -146,7 +146,7 @@ type Server struct { // GET /api/captures list and the mapping preview's by-ID scan // (docs/prds/event-capture-storage.md). Optional: nil makes the list // answer {"enabled": false} rather than the dashboard failing to start. - Captures store.CaptureStore + Captures storev1.CaptureStore // CaptureMaxEvents is the operator's configured [capture] max_events, // used to bound captureByID's scan window (api_mapping.go). // CaptureIntake is the write half's mount. @@ -167,13 +167,13 @@ type Server struct { // Mappings persists payload field mappings (docs/prds/payload-field-mapping.md). // Optional: nil makes every /api/mappings route answer 503 rather than // the dashboard failing to start. - Mappings store.MappingStore + Mappings storev1.MappingStore // Bindings persists playbook bindings: matcher + mapping + workflow // triples that turn a captured webhook into an archie task // (docs/prds/webhook-intake-security.md). Optional: nil makes every // /api/bindings route answer 503 rather than the dashboard failing to start. - Bindings store.BindingStore + Bindings storev1.BindingStore // TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard- // initiated update use the same post-restart notification route as a diff --git a/internal/webui/sse.go b/internal/webui/sse.go index 233f3b5a9..134afb053 100644 --- a/internal/webui/sse.go +++ b/internal/webui/sse.go @@ -7,8 +7,8 @@ import ( "net/http" "strconv" + storev1 "github.com/samcharles93/archie-core/internal/contracts/store/v1" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/store" ) // sseBacklogPageSize bounds one EventsSince fetch during catch-up. @@ -89,7 +89,7 @@ func (s *Server) registerSSEConn() (chan events.Event, func()) { // running "since" watermark that deduplicates the backlog against live // broadcasts covering the same event. type sseStream struct { - store store.TaskStore + store storev1.TaskStore log *slog.Logger w http.ResponseWriter fl http.Flusher @@ -98,7 +98,7 @@ type sseStream struct { // newSSEStream builds a stream over w, reporting false if w cannot be // flushed incrementally -- SSE does not work without that. -func newSSEStream(st store.TaskStore, log *slog.Logger, w http.ResponseWriter, since int64) (*sseStream, bool) { +func newSSEStream(st storev1.TaskStore, log *slog.Logger, w http.ResponseWriter, since int64) (*sseStream, bool) { fl, ok := w.(http.Flusher) if !ok { return nil, false