feat(staterpc): carry the dashboard's configuration snapshot

archie-core-ymut decided the configuration page reads a projection the daemon
publishes rather than reaching into a shared config.Holder. This is the
carrier: a single-row store surface plus PutConfigSnapshot/GetConfigSnapshot,
taking the contract to 42 RPCs.

The document is opaque here. Its shape belongs to the daemon that builds it
and the page that renders it, so the store neither parses nor validates it,
and schema names the projection so a reader can refuse one it does not
understand. It is secret-free where it is built: the projection carries an API
key's environment variable name and whether it resolved, never a value.

Both RPCs are administrative. authorizesTaskScopedCall is deny-by-default, so
a container's task-scoped grant can neither rewrite what an operator reads nor
read a projection of the deployment it runs inside; a test pins both.

Nothing publishes or reads it yet -- the daemon's publisher and the UI's
read path land with the rest of the cutover.
This commit is contained in:
sam committed 2026-09-09 23:35:41 +10:00
1 parent 4cb912fb97
commit d32196f664
16 files changed
+1012 -307

No files matched your search

+1 -1
View File
@@ -187,7 +187,7 @@ structures found in legacy packages.
changing this package or its callers.
- The proto (`proto/state/v1/state.proto`, service `StateStoreService`,
package `statev1` in `internal/contracts/state/v1/`) is one gRPC service
fronting every ratified store contract (40 RPCs); the Go consumer facades
fronting every ratified store contract (42 RPCs); the Go consumer facades
stay narrow (`workflow.Store`, `store.TaskStore`, etc., all ≤8 methods
except the `TaskStore` composite) via `staterpc.Client`'s multiple `var _`
assertions -- never add a Go interface method without a matching RPC.
+1 -1
View File
@@ -201,7 +201,7 @@ recorded in [`ui-service-boundary.md`](ui-service-boundary.md).
**RATIFIED (2026-09-06, beads archie-core-8cda.4.1).** The authoritative
contract boundary & transport design for this is fixed in
`docs/prds/state-store-contract.md` (rev. 2c): one `StateStore` gRPC service,
40 RPCs; **ownership split** — consumer-owned `workflow.Store` +
42 RPCs; **ownership split** — consumer-owned `workflow.Store` +
`workflow.Task`/`Status`/`Source` in the workflow domain (dependency rules
#2/#7), producer-owned daemon/webui store surfaces in `internal/store`;
the `Task`/`Status`/`Source` + interface relocation is a Phase 2
+11 -2
View File
@@ -248,10 +248,19 @@ Methods are named after the store methods so the mapping is unambiguous. `workfl
| Binding | `InsertBinding`, `GetBinding`, `ListBindings`, `UpdateBinding`, `DeleteBinding`, `ApproveBinding` |
| Dispatch | `ArmedBindingsForSource`, `RecordDispatch`, `ListUndispatchedCaptures` |
| BindingTaskCreator | `EnqueueBindingTask` |
| Config snapshot | `PutConfigSnapshot`, `GetConfigSnapshot` |
That is **40 unique RPCs** across one service (the `TaskEvents.Close` method is dropped).
That is **42 unique RPCs** across one service (the `TaskEvents.Close` method is dropped).
`Close()` is **excluded** from the wire (it is server lifecycle, not a client call) — see §11.
The config-snapshot pair was added by `archie-core-ymut` (see
`docs/architecture/migration-decisions.md`, "Dashboard configuration page"). It is the one
surface whose writer is the daemon and whose reader is the UI process, and both RPCs are
administrative: `authorizesTaskScopedCall` is deny-by-default, so a task-scoped grant reaches
neither. `ConfigSnapshot.document` is opaque to this contract — the store neither parses nor
validates it, and `schema` names the projection so a reader can refuse a shape it does not
understand.
### Domain types and `values.go` mapping
`values.go` maps proto ⇄ these types. The task model for the **agent** path is the domain-owned
@@ -619,7 +628,7 @@ an explicit operator decision.
(`workflow.Store` + `workflow.Task`/`Status`/`Source`, per dependency rules #2 and #7);
daemon/webui store surfaces stay **producer-owned** in `internal/store`. `store.WorkflowStore`
is superseded by `workflow.Store`.
- **One `StateStore` gRPC service** (40 RPCs, grouped by contract) + narrow Go consumer facades
- **One `StateStore` gRPC service** (42 RPCs, grouped by contract) + narrow Go consumer facades
(≤8) on `staterpc.Client` — mirrors the single-`ChatService` precedent.
- **Domain type relocation** (`Task`/`Status`/`Source` → `internal/domain/workflow`) is a
Phase 2 prerequisite, pulled forward from migration-decisions §4 (minimal bound,
+3
View File
@@ -140,6 +140,9 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
if btc, ok := b.st.(store.BindingTaskCreator); ok {
deps.BindingTaskCreator = btc
}
if css, ok := b.st.(store.ConfigSnapshotStore); ok {
deps.ConfigSnapshots = css
}
return deps
}
File diff suppressed because it is too large. Load diff
@@ -44,6 +44,8 @@ const (
StateStoreService_WorkflowStats_FullMethodName = "/state.v1.StateStoreService/WorkflowStats"
StateStoreService_StageStats_FullMethodName = "/state.v1.StateStoreService/StageStats"
StateStoreService_TokensByDay_FullMethodName = "/state.v1.StateStoreService/TokensByDay"
StateStoreService_PutConfigSnapshot_FullMethodName = "/state.v1.StateStoreService/PutConfigSnapshot"
StateStoreService_GetConfigSnapshot_FullMethodName = "/state.v1.StateStoreService/GetConfigSnapshot"
StateStoreService_InsertCapture_FullMethodName = "/state.v1.StateStoreService/InsertCapture"
StateStoreService_ListCaptures_FullMethodName = "/state.v1.StateStoreService/ListCaptures"
StateStoreService_StreamCaptures_FullMethodName = "/state.v1.StateStoreService/StreamCaptures"
@@ -107,6 +109,13 @@ type StateStoreServiceClient interface {
WorkflowStats(ctx context.Context, in *WorkflowStatsRequest, opts ...grpc.CallOption) (*WorkflowStatsResponse, error)
StageStats(ctx context.Context, in *StageStatsRequest, opts ...grpc.CallOption) (*StageStatsResponse, error)
TokensByDay(ctx context.Context, in *TokensByDayRequest, opts ...grpc.CallOption) (*TokensByDayResponse, error)
// Configuration snapshot: the running configuration as the dashboard
// renders it, published by the owner of configuration for the process that
// displays it. PutConfigSnapshot is administrative; GetConfigSnapshot is
// the UI's read (docs/architecture/migration-decisions.md, "Dashboard
// configuration page").
PutConfigSnapshot(ctx context.Context, in *PutConfigSnapshotRequest, opts ...grpc.CallOption) (*PutConfigSnapshotResponse, error)
GetConfigSnapshot(ctx context.Context, in *GetConfigSnapshotRequest, opts ...grpc.CallOption) (*GetConfigSnapshotResponse, error)
// Capture
InsertCapture(ctx context.Context, in *InsertCaptureRequest, opts ...grpc.CallOption) (*InsertCaptureResponse, error)
// Deprecated: Do not use.
@@ -402,6 +411,26 @@ func (c *stateStoreServiceClient) TokensByDay(ctx context.Context, in *TokensByD
return out, nil
}
func (c *stateStoreServiceClient) PutConfigSnapshot(ctx context.Context, in *PutConfigSnapshotRequest, opts ...grpc.CallOption) (*PutConfigSnapshotResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(PutConfigSnapshotResponse)
err := c.cc.Invoke(ctx, StateStoreService_PutConfigSnapshot_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) GetConfigSnapshot(ctx context.Context, in *GetConfigSnapshotRequest, opts ...grpc.CallOption) (*GetConfigSnapshotResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetConfigSnapshotResponse)
err := c.cc.Invoke(ctx, StateStoreService_GetConfigSnapshot_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) InsertCapture(ctx context.Context, in *InsertCaptureRequest, opts ...grpc.CallOption) (*InsertCaptureResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(InsertCaptureResponse)
@@ -654,6 +683,13 @@ type StateStoreServiceServer interface {
WorkflowStats(context.Context, *WorkflowStatsRequest) (*WorkflowStatsResponse, error)
StageStats(context.Context, *StageStatsRequest) (*StageStatsResponse, error)
TokensByDay(context.Context, *TokensByDayRequest) (*TokensByDayResponse, error)
// Configuration snapshot: the running configuration as the dashboard
// renders it, published by the owner of configuration for the process that
// displays it. PutConfigSnapshot is administrative; GetConfigSnapshot is
// the UI's read (docs/architecture/migration-decisions.md, "Dashboard
// configuration page").
PutConfigSnapshot(context.Context, *PutConfigSnapshotRequest) (*PutConfigSnapshotResponse, error)
GetConfigSnapshot(context.Context, *GetConfigSnapshotRequest) (*GetConfigSnapshotResponse, error)
// Capture
InsertCapture(context.Context, *InsertCaptureRequest) (*InsertCaptureResponse, error)
// Deprecated: Do not use.
@@ -774,6 +810,12 @@ func (UnimplementedStateStoreServiceServer) StageStats(context.Context, *StageSt
func (UnimplementedStateStoreServiceServer) TokensByDay(context.Context, *TokensByDayRequest) (*TokensByDayResponse, error) {
return nil, status.Error(codes.Unimplemented, "method TokensByDay not implemented")
}
func (UnimplementedStateStoreServiceServer) PutConfigSnapshot(context.Context, *PutConfigSnapshotRequest) (*PutConfigSnapshotResponse, error) {
return nil, status.Error(codes.Unimplemented, "method PutConfigSnapshot not implemented")
}
func (UnimplementedStateStoreServiceServer) GetConfigSnapshot(context.Context, *GetConfigSnapshotRequest) (*GetConfigSnapshotResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetConfigSnapshot not implemented")
}
func (UnimplementedStateStoreServiceServer) InsertCapture(context.Context, *InsertCaptureRequest) (*InsertCaptureResponse, error) {
return nil, status.Error(codes.Unimplemented, "method InsertCapture not implemented")
}
@@ -1302,6 +1344,42 @@ func _StateStoreService_TokensByDay_Handler(srv interface{}, ctx context.Context
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_PutConfigSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PutConfigSnapshotRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).PutConfigSnapshot(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_PutConfigSnapshot_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).PutConfigSnapshot(ctx, req.(*PutConfigSnapshotRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_GetConfigSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetConfigSnapshotRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).GetConfigSnapshot(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_GetConfigSnapshot_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).GetConfigSnapshot(ctx, req.(*GetConfigSnapshotRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_InsertCapture_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(InsertCaptureRequest)
if err := dec(in); err != nil {
@@ -1737,6 +1815,14 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "TokensByDay",
Handler: _StateStoreService_TokensByDay_Handler,
},
{
MethodName: "PutConfigSnapshot",
Handler: _StateStoreService_PutConfigSnapshot_Handler,
},
{
MethodName: "GetConfigSnapshot",
Handler: _StateStoreService_GetConfigSnapshot_Handler,
},
{
MethodName: "InsertCapture",
Handler: _StateStoreService_InsertCapture_Handler,
+32 -7
View File
@@ -34,13 +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)
_ 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)
)
// Lifecycle
@@ -249,6 +250,30 @@ func (c *Client) InsertCapture(ctx context.Context, ce store.CapturedEvent, rete
// ListCaptures calls StreamCaptures, not the deprecated unary ListCaptures
// RPC: a batch of large capture bodies in one unary response can exceed
// gRPC's 4MiB message cap (docs/prds/state-store-contract.md).
// 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 {
_, err := c.client.PutConfigSnapshot(ctx, &pb.PutConfigSnapshotRequest{Snapshot: configSnapshotProto(snapshot)})
if err != nil {
return unmapError(err)
}
return nil
}
// 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) {
reply, err := c.client.GetConfigSnapshot(ctx, &pb.GetConfigSnapshotRequest{})
if err != nil {
return store.ConfigSnapshot{}, false, unmapError(err)
}
if !reply.Found {
return store.ConfigSnapshot{}, false, nil
}
return configSnapshotValue(reply.Snapshot), true, nil
}
func (c *Client) ListCaptures(ctx context.Context, limit int) ([]store.CapturedEvent, error) {
stream, err := c.client.StreamCaptures(ctx, &pb.StreamCapturesRequest{Limit: int64(limit)})
if err != nil {
@@ -5,6 +5,7 @@ import (
"errors"
"net"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
@@ -27,6 +28,7 @@ type contract interface {
store.BindingStore
store.BindingDispatcher
store.BindingTaskCreator
store.ConfigSnapshotStore
}
func remoteContract(t *testing.T, local *store.Store) contract {
@@ -35,7 +37,7 @@ func remoteContract(t *testing.T, local *store.Store) contract {
server := grpc.NewServer()
RegisterServer(server, Deps{
Tasks: local, Captures: local, Mappings: local, Bindings: local,
BindingDispatcher: local, BindingTaskCreator: local,
BindingDispatcher: local, BindingTaskCreator: local, ConfigSnapshots: local,
})
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
@@ -304,3 +306,48 @@ func TestTokenInterceptorRejectsMissingOrInvalidToken(t *testing.T) {
t.Fatalf("valid token rejected: %v", err)
}
}
// TestConfigSnapshotContract drives the published configuration projection
// through both the local store and the gRPC client. The document is opaque to
// this hop, so the test's whole claim is that it arrives unchanged: the UI
// process renders exactly what the daemon published, and an absent snapshot
// reads as "not published yet" rather than an error.
func TestConfigSnapshotContract(t *testing.T) {
for _, mode := range []string{"local", "grpc"} {
t.Run(mode, func(t *testing.T) {
local := store.OpenTest(t)
var st contract = local
if mode == "grpc" {
st = remoteContract(t, local)
}
ctx := t.Context()
if _, found, err := st.ConfigSnapshot(ctx); err != nil || found {
t.Fatalf("unpublished snapshot = (found %v, %v), want (false, nil)", found, err)
}
published := store.ConfigSnapshot{
Schema: "webui.ConfigView/1",
Document: []byte(`{"identity":{"bot_user":"archie"},"providers":{"openai":{"api_key_env":"OPENAI_API_KEY","configured":true}}}`),
PublishedAt: time.Date(2026, 9, 9, 12, 30, 0, 0, time.UTC),
}
if err := st.PutConfigSnapshot(ctx, published); err != nil {
t.Fatalf("PutConfigSnapshot: %v", err)
}
got, found, err := st.ConfigSnapshot(ctx)
if err != nil || !found {
t.Fatalf("ConfigSnapshot = (found %v, %v), want the published snapshot", found, err)
}
if got.Schema != published.Schema {
t.Errorf("schema = %q, want %q", got.Schema, published.Schema)
}
if string(got.Document) != string(published.Document) {
t.Errorf("document = %s, want %s", got.Document, published.Document)
}
if !got.PublishedAt.Equal(published.PublishedAt) {
t.Errorf("published at = %v, want %v", got.PublishedAt, published.PublishedAt)
}
})
}
}
@@ -25,6 +25,7 @@ import (
// rather than a nil-pointer panic.
var (
errCaptureUnavailable = status.Error(codes.Unavailable, "capture store unavailable")
errConfigSnapshotsUnavailable = status.Error(codes.Unavailable, "config snapshot store unavailable")
errMappingUnavailable = status.Error(codes.Unavailable, "mapping store unavailable")
errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable")
errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable")
@@ -41,6 +42,7 @@ type Deps struct {
Grants *TaskGrants
Tasks store.TaskStore
Captures store.CaptureStore
ConfigSnapshots store.ConfigSnapshotStore
Mappings store.MappingStore
Bindings store.BindingStore
BindingDispatcher store.BindingDispatcher
@@ -282,6 +284,39 @@ func (s *server) capture() (store.CaptureStore, error) {
return s.deps.Captures, nil
}
func (s *server) configSnapshots() (store.ConfigSnapshotStore, error) {
if s.deps.ConfigSnapshots == nil {
return nil, errConfigSnapshotsUnavailable
}
return s.deps.ConfigSnapshots, nil
}
func (s *server) PutConfigSnapshot(ctx context.Context, r *pb.PutConfigSnapshotRequest) (*pb.PutConfigSnapshotResponse, error) {
cs, err := s.configSnapshots()
if err != nil {
return nil, err
}
if err := cs.PutConfigSnapshot(ctx, configSnapshotValue(r.Snapshot)); err != nil {
return nil, s.logErr("PutConfigSnapshot", err)
}
return &pb.PutConfigSnapshotResponse{}, nil
}
func (s *server) GetConfigSnapshot(ctx context.Context, _ *pb.GetConfigSnapshotRequest) (*pb.GetConfigSnapshotResponse, error) {
cs, err := s.configSnapshots()
if err != nil {
return nil, err
}
snapshot, found, err := cs.ConfigSnapshot(ctx)
if err != nil {
return nil, s.logErr("GetConfigSnapshot", err)
}
if !found {
return &pb.GetConfigSnapshotResponse{}, nil
}
return &pb.GetConfigSnapshotResponse{Snapshot: configSnapshotProto(snapshot), Found: true}, nil
}
func (s *server) InsertCapture(ctx context.Context, r *pb.InsertCaptureRequest) (*pb.InsertCaptureResponse, error) {
cs, err := s.capture()
if err != nil {
@@ -28,7 +28,7 @@ func grantsServer(t *testing.T, adminToken string) (grants *TaskGrants, dial fun
grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(adminToken)),
grpc.ChainStreamInterceptor(grants.StreamInterceptor(adminToken)),
)
RegisterServer(server, Deps{Tasks: local, Grants: grants})
RegisterServer(server, Deps{Tasks: local, Grants: grants, ConfigSnapshots: local})
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
@@ -109,6 +109,41 @@ func TestTaskGrantScopesWorkerToItsOwnThreeRPCs(t *testing.T) {
}
}
// TestOnlyAdminPublishesTheConfigSnapshot: the published projection is the
// dashboard's whole view of the running configuration, so a container's
// task-scoped credential must not be able to rewrite what an operator reads,
// nor to read a projection describing the deployment it runs inside.
func TestOnlyAdminPublishesTheConfigSnapshot(t *testing.T) {
const adminToken = "daemon-admin-token"
_, dial := grantsServer(t, adminToken)
admin := dial(t, adminToken)
ctx := t.Context()
task, err := admin.EnqueueChatTask(ctx, "acme", "widget", "a", "body", "implement", "")
if err != nil {
t.Fatal(err)
}
workerToken, err := admin.RegisterTaskGrant(ctx, task.ID, time.Hour)
if err != nil {
t.Fatalf("RegisterTaskGrant: %v", err)
}
worker := dial(t, workerToken)
snapshot := store.ConfigSnapshot{Schema: "webui.ConfigView/1", Document: []byte(`{}`)}
if err := admin.PutConfigSnapshot(ctx, snapshot); err != nil {
t.Fatalf("admin PutConfigSnapshot: %v", err)
}
if err := worker.PutConfigSnapshot(ctx, snapshot); err == nil {
t.Fatal("a task grant must not authorize publishing the configuration snapshot")
}
if _, _, err := worker.ConfigSnapshot(ctx); err == nil {
t.Fatal("a task grant must not authorize reading the configuration snapshot")
}
if _, found, err := admin.ConfigSnapshot(ctx); err != nil || !found {
t.Fatalf("admin ConfigSnapshot = (found %v, %v), want the published snapshot", found, err)
}
}
func TestOnlyAdminCanRegisterOrRevokeTaskGrants(t *testing.T) {
const adminToken = "daemon-admin-token"
_, dial := grantsServer(t, adminToken)
@@ -337,3 +337,25 @@ func unmapError(err error) error {
}
return fmt.Errorf("state store: %s: %w", st.Message(), err)
}
// 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 {
return &pb.ConfigSnapshot{
Schema: snapshot.Schema,
Document: snapshot.Document,
PublishedAt: timestamp(snapshot.PublishedAt),
}
}
func configSnapshotValue(snapshot *pb.ConfigSnapshot) store.ConfigSnapshot {
if snapshot == nil {
return store.ConfigSnapshot{}
}
return store.ConfigSnapshot{
Schema: snapshot.Schema,
Document: snapshot.Document,
PublishedAt: timeValue(snapshot.PublishedAt),
}
}
+83
View File
@@ -0,0 +1,83 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)
const configSnapshotSchema = `
CREATE TABLE IF NOT EXISTS config_snapshot (
id INTEGER PRIMARY KEY CHECK (id = 1),
schema TEXT NOT NULL DEFAULT '',
document TEXT NOT NULL DEFAULT '',
published_at TEXT NOT NULL
);
`
// 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
// PutConfigSnapshot replaces the published snapshot. One running
// configuration means one row, so a republish overwrites rather than
// appending a history nothing reads.
func (s *Store) PutConfigSnapshot(ctx context.Context, snapshot ConfigSnapshot) error {
published := snapshot.PublishedAt
if published.IsZero() {
published = time.Now()
}
_, err := s.db.ExecContext(ctx, `
INSERT INTO config_snapshot (id, schema, document, published_at)
VALUES (1, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
schema=excluded.schema,
document=excluded.document,
published_at=excluded.published_at`,
snapshot.Schema, string(snapshot.Document), published.UTC().Format(configSnapshotTimeLayout))
if err != nil {
return fmt.Errorf("store: put config snapshot: %w", err)
}
return nil
}
// ConfigSnapshot returns the published snapshot. found is false, with a nil
// error, before anything has published one -- the normal state of a store
// whose daemon has not booted yet.
func (s *Store) ConfigSnapshot(ctx context.Context) (ConfigSnapshot, bool, error) {
var (
snapshot ConfigSnapshot
document string
published string
)
err := s.db.QueryRowContext(ctx, `
SELECT schema, document, published_at FROM config_snapshot WHERE id = 1`).
Scan(&snapshot.Schema, &document, &published)
if errors.Is(err, sql.ErrNoRows) {
return ConfigSnapshot{}, false, nil
}
if err != nil {
return ConfigSnapshot{}, false, fmt.Errorf("store: read config snapshot: %w", err)
}
snapshot.Document = []byte(document)
if at, err := time.Parse(configSnapshotTimeLayout, published); err == nil {
snapshot.PublishedAt = at
}
return snapshot, true, nil
}
+63
View File
@@ -0,0 +1,63 @@
package store
import (
"testing"
"time"
)
// TestConfigSnapshotRoundTrip: the daemon publishes the dashboard's
// configuration projection here and the UI process reads it, so the document
// has to come back byte-identical and the newest publish has to win. There is
// one running configuration, so there is one row.
func TestConfigSnapshotRoundTrip(t *testing.T) {
st := openTest(t)
ctx := t.Context()
if _, found, err := st.ConfigSnapshot(ctx); err != nil || found {
t.Fatalf("ConfigSnapshot on an empty store = (found %v, %v), want (false, nil)", found, err)
}
first := ConfigSnapshot{
Schema: "webui.ConfigView/1",
Document: []byte(`{"identity":{"bot_user":"archie"}}`),
PublishedAt: time.Date(2026, 9, 9, 10, 0, 0, 0, time.UTC),
}
if err := st.PutConfigSnapshot(ctx, first); err != nil {
t.Fatalf("PutConfigSnapshot: %v", err)
}
got, found, err := st.ConfigSnapshot(ctx)
if err != nil || !found {
t.Fatalf("ConfigSnapshot = (found %v, %v), want it stored", found, err)
}
if got.Schema != first.Schema || string(got.Document) != string(first.Document) {
t.Fatalf("snapshot = %+v, want %+v", got, first)
}
if !got.PublishedAt.Equal(first.PublishedAt) {
t.Fatalf("published at = %v, want %v", got.PublishedAt, first.PublishedAt)
}
second := ConfigSnapshot{
Schema: "webui.ConfigView/1",
Document: []byte(`{"identity":{"bot_user":"archie-2"}}`),
PublishedAt: first.PublishedAt.Add(time.Hour),
}
if err := st.PutConfigSnapshot(ctx, second); err != nil {
t.Fatalf("republish: %v", err)
}
got, found, err = st.ConfigSnapshot(ctx)
if err != nil || !found {
t.Fatalf("ConfigSnapshot after republish = (found %v, %v)", found, err)
}
if string(got.Document) != string(second.Document) {
t.Fatalf("document = %s, want the republished %s", got.Document, second.Document)
}
var rows int
if err := st.db.QueryRowContext(ctx, `SELECT count(*) FROM config_snapshot`).Scan(&rows); err != nil {
t.Fatal(err)
}
if rows != 1 {
t.Fatalf("config_snapshot holds %d rows, want exactly 1: republishing replaces, it does not accumulate", rows)
}
}
+11
View File
@@ -83,6 +83,17 @@ type CaptureStore interface {
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
+1 -1
View File
@@ -54,7 +54,7 @@ func Open(ctx context.Context, path string, opts ...OpenOption) (*Store, error)
return nil, err
}
db.SetMaxOpenConns(1)
if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema+mappingsSchema+bindingsSchema); err != nil {
if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema+mappingsSchema+bindingsSchema+configSnapshotSchema); err != nil {
return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close())
}
if err := migrateTasks(ctx, db); err != nil {
+27
View File
@@ -46,6 +46,14 @@ service StateStoreService {
rpc StageStats(StageStatsRequest) returns (StageStatsResponse);
rpc TokensByDay(TokensByDayRequest) returns (TokensByDayResponse);
// Configuration snapshot: the running configuration as the dashboard
// renders it, published by the owner of configuration for the process that
// displays it. PutConfigSnapshot is administrative; GetConfigSnapshot is
// the UI's read (docs/architecture/migration-decisions.md, "Dashboard
// configuration page").
rpc PutConfigSnapshot(PutConfigSnapshotRequest) returns (PutConfigSnapshotResponse);
rpc GetConfigSnapshot(GetConfigSnapshotRequest) returns (GetConfigSnapshotResponse);
// Capture
rpc InsertCapture(InsertCaptureRequest) returns (InsertCaptureResponse);
// ListCaptures is superseded by StreamCaptures (kept, unmodified, so an
@@ -349,6 +357,25 @@ message StageStatsResponse { repeated StageStat stats = 1; }
message TokensByDayRequest { int64 days = 1; }
message TokensByDayResponse { repeated DayTokens tokens = 1; }
// ConfigSnapshot carries the dashboard's configuration projection. document
// is opaque to the store: its shape belongs to the producer and the page that
// reads it, and schema names that shape so a reader can refuse one it does
// not understand. It is secret-free at the producer -- the projection carries
// an API key's environment variable name and whether it resolved, never a
// value.
message ConfigSnapshot {
string schema = 1;
bytes document = 2;
google.protobuf.Timestamp published_at = 3;
}
message PutConfigSnapshotRequest { ConfigSnapshot snapshot = 1; }
message PutConfigSnapshotResponse {}
message GetConfigSnapshotRequest {}
message GetConfigSnapshotResponse {
ConfigSnapshot snapshot = 1;
bool found = 2;
}
message InsertCaptureRequest {
CapturedEvent capture = 1;
int64 retention_seconds = 2;