refactor(store)!: remove the SQLite task store, the PocketBase event store and the SQLite session store
The State Store, event capture and Gateway conversations already serve from PostgreSQL. This deletes internal/store and internal/infrastructure/edastore, the SQLite gateway session store and openProductionTaskStore, and the -db recovery path on a legacy task file; backup, restore, validate and rollback work on the database database_url names. - The binding-secret cipher moves to internal/infrastructure/bindingcipher and ToolCall to internal/infrastructure/postgres. - NewSessionStoreMemory is now a pure in-memory store that passes the shared SessionStore conformance suite. - Tests run against PostgreSQL through internal/infrastructure/postgres/pgstore; legacyimport/legacyfixture writes the legacy files the import and the boot gate read. - The cron dialect is owned in internal/domain/scheduling, so github.com/pocketbase/pocketbase and pocketbase/dbx leave go.mod. modernc.org/sqlite stays for the one-time import (legacyread). - The UI and Messaging architecture gates ban the Postgres and legacy readers in place of internal/store.
This commit is contained in:
1 parent
dda12dcdba
commit
ae552db7e0
90 files changed
+1022
-1453
No files matched your search
@@ -1,4 +1,6 @@
|
||||
package edastore
|
||||
// Package bindingcipher seals binding secrets at rest with AES-256-GCM under
|
||||
// a rotatable keyring.
|
||||
package bindingcipher
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package edastore
|
||||
package bindingcipher
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -121,110 +120,6 @@ func TestBindingCipherDerivesDistinctKeys(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// openWithCipher builds a store whose binding secrets are encrypted at rest.
|
||||
func openWithCipher(t *testing.T, cipher BindingCipher) *Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
s, err := Open(Config{
|
||||
DBPath: filepath.Join(dir, "eda.sqlite"),
|
||||
DataDir: filepath.Join(dir, "pb_data"),
|
||||
Cipher: cipher,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Open() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func sampleBinding() bindingInput {
|
||||
return bindingInput{Name: "n", Source: "sentry", Workflow: "implement", Secret: "supersecretvalue0123"}
|
||||
}
|
||||
|
||||
// TestBindingSecretIsEncryptedAtRest pins that the plaintext secret never
|
||||
// reaches the database file. Reading the column directly is the point: a
|
||||
// round-trip through the store would decrypt and prove nothing.
|
||||
func TestBindingSecretIsEncryptedAtRest(t *testing.T) {
|
||||
cipher, err := NewBindingCipher(testBindingKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
s := openWithCipher(t, cipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
var stored string
|
||||
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
|
||||
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
if stored == in.Secret {
|
||||
t.Fatal("secret is stored as plaintext; it must be encrypted at rest")
|
||||
}
|
||||
if !strings.Contains(stored, ":") {
|
||||
t.Errorf("stored secret %q does not look like a cipher envelope", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBindingSecretDecryptsOnRead pins the other half: what was encrypted
|
||||
// comes back as the original plaintext.
|
||||
func TestBindingSecretDecryptsOnRead(t *testing.T) {
|
||||
cipher, _ := NewBindingCipher(testBindingKey, nil)
|
||||
s := openWithCipher(t, cipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
got, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() error = %v", err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret = %q, want %q", got.Secret, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNoCipherKeepsPlaintext pins the behaviour that predates encryption: a
|
||||
// deployment with no configured key still works, storing plaintext.
|
||||
func TestNoCipherKeepsPlaintext(t *testing.T) {
|
||||
s := openWithCipher(t, nil)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
var stored string
|
||||
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
|
||||
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
if stored != in.Secret {
|
||||
t.Errorf("stored secret = %q, want the plaintext %q with no cipher configured", stored, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRotatedKeyStillReadsOldRows pins key rotation: a secret written under
|
||||
// the previous key must stay readable once a new active key is installed,
|
||||
// otherwise a rotation silently bricks every armed binding.
|
||||
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, _ := NewBindingCipher(oldKey, nil)
|
||||
s := openWithCipher(t, oldCipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
rotated, err := NewBindingCipher(testBindingKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
s.cipher = rotated
|
||||
|
||||
got, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() after rotation error = %v", err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret after rotation = %q, want %q: the previous key must still decrypt", got.Secret, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// tamperEnvelope flips one byte inside the ciphertext region so Decrypt must
|
||||
// fail authentication rather than return altered plaintext.
|
||||
func tamperEnvelope(t *testing.T, envelope string) string {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package captureintake
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -14,9 +14,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
@@ -39,7 +40,7 @@ type testReceiver struct {
|
||||
*Receiver
|
||||
// store is the event-capture store the receiver writes through, kept so a
|
||||
// test asserts on persisted rows rather than on a mock's recollection.
|
||||
store *edastore.Store
|
||||
store *postgres.EDA
|
||||
}
|
||||
|
||||
// Handler serves the receiver's route the way its host process mounts it,
|
||||
@@ -60,7 +61,7 @@ func captureTestServerWithoutStore(t *testing.T) testReceiver {
|
||||
|
||||
func captureTestServer(t *testing.T) testReceiver {
|
||||
t.Helper()
|
||||
s := edastore.OpenTest(t)
|
||||
s := pgstore.EDA(t, nil)
|
||||
return testReceiver{
|
||||
Receiver: &Receiver{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
@@ -131,7 +132,7 @@ func (s *stubBindingStore) RecordDispatch(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) ListUndispatchedCaptures(_ context.Context, _ []string, _ int) ([]store.CapturedEvent, error) {
|
||||
func (s *stubBindingStore) ListUndispatchedCaptures(_ context.Context, _ []string, _ int) ([]storecontract.CapturedEvent, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -420,10 +421,10 @@ func TestHandleCaptureWithoutCapturesConfiguredIs503(t *testing.T) {
|
||||
// captureInsertErrorStore forces InsertCapture to fail so the handler's
|
||||
// error path is exercised without relying on a real storage failure.
|
||||
type captureInsertErrorStore struct {
|
||||
store.CaptureStore
|
||||
storecontract.CaptureStore
|
||||
}
|
||||
|
||||
func (captureInsertErrorStore) InsertCapture(context.Context, store.CapturedEvent, time.Duration, int) (string, error) {
|
||||
func (captureInsertErrorStore) InsertCapture(context.Context, storecontract.CapturedEvent, time.Duration, int) (string, error) {
|
||||
return "", errors.New("boom")
|
||||
}
|
||||
|
||||
|
||||
@@ -15,9 +15,9 @@ import (
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -213,7 +213,7 @@ func TestTaskActionErrorsKeepTheirSentinelOverGRPC(t *testing.T) {
|
||||
}{
|
||||
{name: "not found", err: fmt.Errorf("task 7: %w", taskactions.ErrNotFound)},
|
||||
{name: "conflict", err: fmt.Errorf("%w: action \"approve\" is not available while task is parked", taskactions.ErrConflict)},
|
||||
{name: "stale transition", err: fmt.Errorf("stop task 7: %w", store.ErrStaleTransition)},
|
||||
{name: "stale transition", err: fmt.Errorf("stop task 7: %w", storecontract.ErrStaleTransition)},
|
||||
{name: "unavailable", err: taskactions.ErrUnavailable},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
// Package legacyfixture writes the legacy SQLite files an existing install
|
||||
// holds, for tests of the one-time import and the boot gate that requires it.
|
||||
package legacyfixture
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// StateStoreDDL, EDADDL and GatewayDDL apply the legacy schemas as their production openers leave
|
||||
// them, columns added by ALTER TABLE included, with values in the layouts the
|
||||
// production writers used.
|
||||
const StateStoreDDL = `
|
||||
CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, repo TEXT NOT NULL,
|
||||
issue_number INTEGER NOT NULL, title TEXT DEFAULT '', body TEXT DEFAULT '', labels TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'queued', workflow TEXT DEFAULT '', stage TEXT DEFAULT '', branch TEXT DEFAULT '',
|
||||
plan TEXT DEFAULT '', notes TEXT DEFAULT '', pr_number INTEGER DEFAULT 0, tokens_used INTEGER DEFAULT 0,
|
||||
iterations INTEGER DEFAULT 0, attempt INTEGER DEFAULT 0, park_reason TEXT DEFAULT '',
|
||||
watch_comment_id INTEGER DEFAULT 0, park_class TEXT DEFAULT 'needs_human', remediation_rounds INTEGER DEFAULT 0,
|
||||
retry_count INTEGER DEFAULT 0, source TEXT DEFAULT 'forge', identity TEXT DEFAULT '', binding_id TEXT DEFAULT '',
|
||||
binding_version INTEGER DEFAULT 0, review_payload TEXT DEFAULT '', workflow_definition_version INTEGER DEFAULT 0,
|
||||
workflow_definition_digest TEXT DEFAULT '', workflow_definition_yaml TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')));
|
||||
ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE TABLE transitions (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL,
|
||||
at TEXT DEFAULT (datetime('now')), from_status TEXT NOT NULL, to_status TEXT NOT NULL, detail TEXT DEFAULT '');
|
||||
CREATE TABLE events (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
task_id INTEGER DEFAULT 0, repo TEXT DEFAULT '', issue INTEGER DEFAULT 0, workflow TEXT DEFAULT '',
|
||||
stage TEXT DEFAULT '', attempt INTEGER DEFAULT 0, actor_id TEXT DEFAULT '', actor_kind TEXT DEFAULT '',
|
||||
principal_id TEXT DEFAULT '', detail TEXT DEFAULT '', data TEXT DEFAULT '{}');
|
||||
CREATE TABLE resources (kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE resource_history (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
|
||||
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL,
|
||||
expected_version INTEGER NOT NULL, current_version INTEGER NOT NULL, at TEXT NOT NULL);
|
||||
CREATE TABLE channel_status (id TEXT PRIMARY KEY, name TEXT DEFAULT '', state TEXT DEFAULT '', detail TEXT DEFAULT '',
|
||||
configured INTEGER NOT NULL DEFAULT 0, reload_supported INTEGER NOT NULL DEFAULT 0, observed_at TEXT NOT NULL);
|
||||
CREATE TABLE apply_status (process TEXT NOT NULL, kind TEXT NOT NULL, applied_version INTEGER DEFAULT 0,
|
||||
error TEXT DEFAULT '', reported_at TEXT NOT NULL, PRIMARY KEY (process, kind));
|
||||
CREATE TABLE config_snapshot (id INTEGER PRIMARY KEY CHECK (id = 1), schema TEXT DEFAULT '', document TEXT DEFAULT '',
|
||||
published_at TEXT NOT NULL);
|
||||
CREATE TABLE identities (id TEXT PRIMARY KEY, kind TEXT NOT NULL, display_name TEXT NOT NULL, lifecycle TEXT NOT NULL,
|
||||
version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE identity_aliases (alias TEXT PRIMARY KEY COLLATE NOCASE, identity_id TEXT NOT NULL REFERENCES identities(id));
|
||||
CREATE TABLE identity_events (id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
|
||||
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL, actor_id TEXT NOT NULL,
|
||||
source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL);
|
||||
CREATE TABLE identity_subjects (issuer TEXT NOT NULL, subject TEXT NOT NULL,
|
||||
identity_id TEXT NOT NULL REFERENCES identities(id), bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject));
|
||||
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, review_cursor, created_at, updated_at) VALUES
|
||||
(1, 'o', 'r', 7, 3, '2026-01-01 00:00:00', '2026-01-01 00:00:01'),
|
||||
(4, 'o', 'r', 1000000000000000, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00'),
|
||||
(9, 'o', 'r', 8, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00');
|
||||
DELETE FROM tasks WHERE id = 9;
|
||||
INSERT INTO transitions (task_id, at, from_status, to_status) VALUES (1, '2026-01-01 00:00:00', 'queued', 'running');
|
||||
INSERT INTO events (id, at, kind, data) VALUES
|
||||
(1, '2026-01-01T00:00:00.000000100Z', 'a', 'null'),
|
||||
(2, '2026-01-01T00:00:01.000000000Z', 'b', '{"k":1}'),
|
||||
(5, '2026-01-01T00:00:00.500000000Z', 'c', '{}');
|
||||
INSERT INTO resources VALUES ('config', X'00ff10', 2, '2026-01-01T00:00:00.123456789Z');
|
||||
INSERT INTO resource_history (kind, value, version, actor, source, request_id, expected_version, current_version, at)
|
||||
VALUES ('config', X'00ff10', 2, 'sam', 'ui', 'req-1', 1, 1, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO channel_status VALUES ('tg', 'Telegram', 'up', '', 1, 0, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO apply_status VALUES ('daemon', 'config', 2, '', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO config_snapshot VALUES (1, 's', '{}', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identities VALUES ('id-1', 'agent', 'Archie', 'active', 1, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_aliases VALUES ('archie', 'id-1');
|
||||
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
|
||||
VALUES ('id-1', 'created', '', 'active', 'Archie', 'sam', 'boot', 'rq-1', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_subjects VALUES ('https://issuer', 'sub-1', 'id-1', '2026-01-01T00:00:00Z');
|
||||
`
|
||||
|
||||
// Secret is an encrypted binding secret envelope; it must arrive unchanged.
|
||||
const Secret = "arcie-binding:v1:0123456789abcdef:AbC-_dEf012"
|
||||
|
||||
const EDADDL = `
|
||||
CREATE TABLE captures (id TEXT PRIMARY KEY NOT NULL, authenticated BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
body TEXT DEFAULT '' NOT NULL, content_type TEXT DEFAULT '' NOT NULL, headers JSON DEFAULT NULL,
|
||||
received_at TEXT DEFAULT '' NOT NULL, remote_addr TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE mappings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, fields JSON DEFAULT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, source_hint TEXT DEFAULT '' NOT NULL, updated_at TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE bindings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, mapping TEXT DEFAULT '' NOT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, owner TEXT DEFAULT '' NOT NULL, repo TEXT DEFAULT '' NOT NULL,
|
||||
secret TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL, status TEXT DEFAULT '' NOT NULL,
|
||||
updated_at TEXT DEFAULT '' NOT NULL, version NUMERIC DEFAULT 0 NOT NULL, workflow TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE binding_dispatches (id TEXT PRIMARY KEY NOT NULL, binding TEXT DEFAULT '' NOT NULL,
|
||||
binding_version NUMERIC DEFAULT 0 NOT NULL, capture TEXT DEFAULT '' NOT NULL, dispatched_at TEXT DEFAULT '' NOT NULL,
|
||||
task_id NUMERIC DEFAULT 0 NOT NULL);
|
||||
CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, capture);
|
||||
CREATE TABLE playbook_dispatches (id TEXT PRIMARY KEY NOT NULL, action_id TEXT DEFAULT '' NOT NULL,
|
||||
dispatched_at TEXT DEFAULT '' NOT NULL, event_id TEXT DEFAULT '' NOT NULL, playbook_id TEXT DEFAULT '' NOT NULL,
|
||||
playbook_version TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE tool_calls (id TEXT PRIMARY KEY NOT NULL, args JSON DEFAULT NULL, attempt NUMERIC DEFAULT 0 NOT NULL,
|
||||
called_at TEXT DEFAULT '' NOT NULL, duration_ms NUMERIC DEFAULT 0 NOT NULL, error TEXT DEFAULT '' NOT NULL,
|
||||
result JSON DEFAULT NULL, task_id NUMERIC DEFAULT 0 NOT NULL, tool TEXT DEFAULT '' NOT NULL);
|
||||
|
||||
INSERT INTO captures VALUES ('rcap1', 1, '{}', 'application/json', '{"x":["1"]}', '2026-01-01T00:00:00.000000000Z', '127.0.0.1', 'gh');
|
||||
INSERT INTO captures VALUES ('rcap2', 0, '', '', NULL, '2026-01-01T00:00:01.000000000Z', '', 'gh');
|
||||
INSERT INTO mappings VALUES ('rmap1', '2026-01-01 00:00:00.000Z', '[]', 'm', 'gh', '2026-01-01 00:00:00.000Z');
|
||||
INSERT INTO bindings VALUES ('rbind1', '2026-01-01 00:00:00.000Z', 'rmap1', 'b', 'o', 'r', '` + Secret + `', 'gh', 'armed', '2026-01-01 00:00:00.000Z', 1, 'implement');
|
||||
INSERT INTO binding_dispatches VALUES ('rdisp1', 'rbind1', 1, 'rcap1', '2026-01-01 00:00:00.000Z', 4);
|
||||
INSERT INTO playbook_dispatches VALUES ('rpb1', 'act', '2026-01-01 00:00:00.000Z', 'ev', 'pb', 'v1');
|
||||
INSERT INTO tool_calls VALUES ('rtool1', NULL, 1, '2026-01-01 00:00:00.000Z', 12, '', '"exit 0"', 4, 'bash');
|
||||
`
|
||||
|
||||
const GatewayDDL = `
|
||||
CREATE TABLE sessions (session_id TEXT PRIMARY KEY, platform TEXT NOT NULL DEFAULT '', bot_user TEXT NOT NULL DEFAULT '',
|
||||
channel_id TEXT NOT NULL DEFAULT '', thread_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '',
|
||||
parent_session_id TEXT NOT NULL DEFAULT '', branch_name TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL DEFAULT 0, last_active_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
|
||||
source_id TEXT NOT NULL DEFAULT '', sender TEXT NOT NULL DEFAULT '', text TEXT NOT NULL DEFAULT '', ts INTEGER NOT NULL,
|
||||
UNIQUE(session_id, message_id));
|
||||
ALTER TABLE messages ADD COLUMN role TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE messages ADD COLUMN sender_id TEXT NOT NULL DEFAULT '';
|
||||
CREATE VIRTUAL TABLE messages_fts USING fts5(sender, text, content='messages', content_rowid='id');
|
||||
CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN
|
||||
INSERT INTO messages_fts(rowid, sender, text) VALUES (new.id, new.sender, new.text);
|
||||
END;
|
||||
CREATE TABLE turns (turn_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, source_id TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0, owner_id TEXT NOT NULL DEFAULT '',
|
||||
input_message_id TEXT NOT NULL DEFAULT '', assistant_message_id TEXT NOT NULL DEFAULT '',
|
||||
partial_text TEXT NOT NULL DEFAULT '', response_text TEXT NOT NULL DEFAULT '', tool_calls TEXT NOT NULL DEFAULT '[]',
|
||||
error TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
||||
|
||||
INSERT INTO sessions VALUES ('s1', 'telegram', 'bot', 'c1', '', 'Chat', '', '', 1000, 2000);
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m1', 's1', 'sam', 'hello there', 1000, 'user');
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m2', 's1', 'archie', 'hi', 1001, 'assistant');
|
||||
INSERT INTO turns VALUES ('t1', 's1', '', 'done', 1, '', 'm1', 'm2', '', 'hi', '[]', '', 1000, 1001);
|
||||
`
|
||||
|
||||
// Install writes the three legacy files the configured db_path names in dir
|
||||
// and returns their paths.
|
||||
func Install(t testing.TB, dbPath string) (stateStore, eda, gateway string) {
|
||||
t.Helper()
|
||||
stateStore, eda, gateway = dbPath+"-tasks.sqlite", dbPath+"-eda.sqlite", dbPath+"-conversations.sqlite"
|
||||
Exec(t, stateStore, StateStoreDDL)
|
||||
Exec(t, eda, EDADDL)
|
||||
Exec(t, gateway, GatewayDDL)
|
||||
return stateStore, eda, gateway
|
||||
}
|
||||
|
||||
// Exec runs stmt against the SQLite file at path, creating it if absent.
|
||||
func Exec(t testing.TB, path, stmt string) {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path)
|
||||
if err != nil {
|
||||
t.Fatalf("open fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if _, err := db.ExecContext(t.Context(), stmt); err != nil {
|
||||
t.Fatalf("fixture %s: %v", filepath.Base(path), err)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package legacyimport
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -11,175 +10,34 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/legacyimport/legacyfixture"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
|
||||
// The fixtures apply the legacy schemas as their production openers leave
|
||||
// them, columns added by ALTER TABLE included, with values in the layouts the
|
||||
// production writers used.
|
||||
const stateStoreDDL = `
|
||||
CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, repo TEXT NOT NULL,
|
||||
issue_number INTEGER NOT NULL, title TEXT DEFAULT '', body TEXT DEFAULT '', labels TEXT DEFAULT '',
|
||||
status TEXT DEFAULT 'queued', workflow TEXT DEFAULT '', stage TEXT DEFAULT '', branch TEXT DEFAULT '',
|
||||
plan TEXT DEFAULT '', notes TEXT DEFAULT '', pr_number INTEGER DEFAULT 0, tokens_used INTEGER DEFAULT 0,
|
||||
iterations INTEGER DEFAULT 0, attempt INTEGER DEFAULT 0, park_reason TEXT DEFAULT '',
|
||||
watch_comment_id INTEGER DEFAULT 0, park_class TEXT DEFAULT 'needs_human', remediation_rounds INTEGER DEFAULT 0,
|
||||
retry_count INTEGER DEFAULT 0, source TEXT DEFAULT 'forge', identity TEXT DEFAULT '', binding_id TEXT DEFAULT '',
|
||||
binding_version INTEGER DEFAULT 0, review_payload TEXT DEFAULT '', workflow_definition_version INTEGER DEFAULT 0,
|
||||
workflow_definition_digest TEXT DEFAULT '', workflow_definition_yaml TEXT DEFAULT '',
|
||||
created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')));
|
||||
ALTER TABLE tasks ADD COLUMN review_cursor INTEGER NOT NULL DEFAULT 0;
|
||||
CREATE TABLE transitions (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL,
|
||||
at TEXT DEFAULT (datetime('now')), from_status TEXT NOT NULL, to_status TEXT NOT NULL, detail TEXT DEFAULT '');
|
||||
CREATE TABLE events (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, kind TEXT NOT NULL,
|
||||
task_id INTEGER DEFAULT 0, repo TEXT DEFAULT '', issue INTEGER DEFAULT 0, workflow TEXT DEFAULT '',
|
||||
stage TEXT DEFAULT '', attempt INTEGER DEFAULT 0, actor_id TEXT DEFAULT '', actor_kind TEXT DEFAULT '',
|
||||
principal_id TEXT DEFAULT '', detail TEXT DEFAULT '', data TEXT DEFAULT '{}');
|
||||
CREATE TABLE resources (kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE resource_history (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
|
||||
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL,
|
||||
expected_version INTEGER NOT NULL, current_version INTEGER NOT NULL, at TEXT NOT NULL);
|
||||
CREATE TABLE channel_status (id TEXT PRIMARY KEY, name TEXT DEFAULT '', state TEXT DEFAULT '', detail TEXT DEFAULT '',
|
||||
configured INTEGER NOT NULL DEFAULT 0, reload_supported INTEGER NOT NULL DEFAULT 0, observed_at TEXT NOT NULL);
|
||||
CREATE TABLE apply_status (process TEXT NOT NULL, kind TEXT NOT NULL, applied_version INTEGER DEFAULT 0,
|
||||
error TEXT DEFAULT '', reported_at TEXT NOT NULL, PRIMARY KEY (process, kind));
|
||||
CREATE TABLE config_snapshot (id INTEGER PRIMARY KEY CHECK (id = 1), schema TEXT DEFAULT '', document TEXT DEFAULT '',
|
||||
published_at TEXT NOT NULL);
|
||||
CREATE TABLE identities (id TEXT PRIMARY KEY, kind TEXT NOT NULL, display_name TEXT NOT NULL, lifecycle TEXT NOT NULL,
|
||||
version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE identity_aliases (alias TEXT PRIMARY KEY COLLATE NOCASE, identity_id TEXT NOT NULL REFERENCES identities(id));
|
||||
CREATE TABLE identity_events (id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
|
||||
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL, actor_id TEXT NOT NULL,
|
||||
source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL);
|
||||
CREATE TABLE identity_subjects (issuer TEXT NOT NULL, subject TEXT NOT NULL,
|
||||
identity_id TEXT NOT NULL REFERENCES identities(id), bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject));
|
||||
|
||||
INSERT INTO tasks (id, owner, repo, issue_number, review_cursor, created_at, updated_at) VALUES
|
||||
(1, 'o', 'r', 7, 3, '2026-01-01 00:00:00', '2026-01-01 00:00:01'),
|
||||
(4, 'o', 'r', 1000000000000000, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00'),
|
||||
(9, 'o', 'r', 8, 0, '2026-01-02 00:00:00', '2026-01-02 00:00:00');
|
||||
DELETE FROM tasks WHERE id = 9;
|
||||
INSERT INTO transitions (task_id, at, from_status, to_status) VALUES (1, '2026-01-01 00:00:00', 'queued', 'running');
|
||||
INSERT INTO events (id, at, kind, data) VALUES
|
||||
(1, '2026-01-01T00:00:00.000000100Z', 'a', 'null'),
|
||||
(2, '2026-01-01T00:00:01.000000000Z', 'b', '{"k":1}'),
|
||||
(5, '2026-01-01T00:00:00.500000000Z', 'c', '{}');
|
||||
INSERT INTO resources VALUES ('config', X'00ff10', 2, '2026-01-01T00:00:00.123456789Z');
|
||||
INSERT INTO resource_history (kind, value, version, actor, source, request_id, expected_version, current_version, at)
|
||||
VALUES ('config', X'00ff10', 2, 'sam', 'ui', 'req-1', 1, 1, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO channel_status VALUES ('tg', 'Telegram', 'up', '', 1, 0, '2026-01-01T00:00:00Z');
|
||||
INSERT INTO apply_status VALUES ('daemon', 'config', 2, '', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO config_snapshot VALUES (1, 's', '{}', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identities VALUES ('id-1', 'agent', 'Archie', 'active', 1, '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_aliases VALUES ('archie', 'id-1');
|
||||
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
|
||||
VALUES ('id-1', 'created', '', 'active', 'Archie', 'sam', 'boot', 'rq-1', '2026-01-01T00:00:00Z');
|
||||
INSERT INTO identity_subjects VALUES ('https://issuer', 'sub-1', 'id-1', '2026-01-01T00:00:00Z');
|
||||
`
|
||||
|
||||
// secret is an encrypted binding secret envelope; it must arrive unchanged.
|
||||
const secret = "arcie-binding:v1:0123456789abcdef:AbC-_dEf012"
|
||||
|
||||
const edaDDL = `
|
||||
CREATE TABLE captures (id TEXT PRIMARY KEY NOT NULL, authenticated BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
body TEXT DEFAULT '' NOT NULL, content_type TEXT DEFAULT '' NOT NULL, headers JSON DEFAULT NULL,
|
||||
received_at TEXT DEFAULT '' NOT NULL, remote_addr TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE mappings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, fields JSON DEFAULT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, source_hint TEXT DEFAULT '' NOT NULL, updated_at TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE bindings (id TEXT PRIMARY KEY NOT NULL, created_at TEXT DEFAULT '' NOT NULL, mapping TEXT DEFAULT '' NOT NULL,
|
||||
name TEXT DEFAULT '' NOT NULL, owner TEXT DEFAULT '' NOT NULL, repo TEXT DEFAULT '' NOT NULL,
|
||||
secret TEXT DEFAULT '' NOT NULL, source TEXT DEFAULT '' NOT NULL, status TEXT DEFAULT '' NOT NULL,
|
||||
updated_at TEXT DEFAULT '' NOT NULL, version NUMERIC DEFAULT 0 NOT NULL, workflow TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE binding_dispatches (id TEXT PRIMARY KEY NOT NULL, binding TEXT DEFAULT '' NOT NULL,
|
||||
binding_version NUMERIC DEFAULT 0 NOT NULL, capture TEXT DEFAULT '' NOT NULL, dispatched_at TEXT DEFAULT '' NOT NULL,
|
||||
task_id NUMERIC DEFAULT 0 NOT NULL);
|
||||
CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, capture);
|
||||
CREATE TABLE playbook_dispatches (id TEXT PRIMARY KEY NOT NULL, action_id TEXT DEFAULT '' NOT NULL,
|
||||
dispatched_at TEXT DEFAULT '' NOT NULL, event_id TEXT DEFAULT '' NOT NULL, playbook_id TEXT DEFAULT '' NOT NULL,
|
||||
playbook_version TEXT DEFAULT '' NOT NULL);
|
||||
CREATE TABLE tool_calls (id TEXT PRIMARY KEY NOT NULL, args JSON DEFAULT NULL, attempt NUMERIC DEFAULT 0 NOT NULL,
|
||||
called_at TEXT DEFAULT '' NOT NULL, duration_ms NUMERIC DEFAULT 0 NOT NULL, error TEXT DEFAULT '' NOT NULL,
|
||||
result JSON DEFAULT NULL, task_id NUMERIC DEFAULT 0 NOT NULL, tool TEXT DEFAULT '' NOT NULL);
|
||||
|
||||
INSERT INTO captures VALUES ('rcap1', 1, '{}', 'application/json', '{"x":["1"]}', '2026-01-01T00:00:00.000000000Z', '127.0.0.1', 'gh');
|
||||
INSERT INTO captures VALUES ('rcap2', 0, '', '', NULL, '2026-01-01T00:00:01.000000000Z', '', 'gh');
|
||||
INSERT INTO mappings VALUES ('rmap1', '2026-01-01 00:00:00.000Z', '[]', 'm', 'gh', '2026-01-01 00:00:00.000Z');
|
||||
INSERT INTO bindings VALUES ('rbind1', '2026-01-01 00:00:00.000Z', 'rmap1', 'b', 'o', 'r', '` + secret + `', 'gh', 'armed', '2026-01-01 00:00:00.000Z', 1, 'implement');
|
||||
INSERT INTO binding_dispatches VALUES ('rdisp1', 'rbind1', 1, 'rcap1', '2026-01-01 00:00:00.000Z', 4);
|
||||
INSERT INTO playbook_dispatches VALUES ('rpb1', 'act', '2026-01-01 00:00:00.000Z', 'ev', 'pb', 'v1');
|
||||
INSERT INTO tool_calls VALUES ('rtool1', NULL, 1, '2026-01-01 00:00:00.000Z', 12, '', '"exit 0"', 4, 'bash');
|
||||
`
|
||||
|
||||
const gatewayDDL = `
|
||||
CREATE TABLE sessions (session_id TEXT PRIMARY KEY, platform TEXT NOT NULL DEFAULT '', bot_user TEXT NOT NULL DEFAULT '',
|
||||
channel_id TEXT NOT NULL DEFAULT '', thread_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '',
|
||||
parent_session_id TEXT NOT NULL DEFAULT '', branch_name TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL DEFAULT 0, last_active_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
|
||||
source_id TEXT NOT NULL DEFAULT '', sender TEXT NOT NULL DEFAULT '', text TEXT NOT NULL DEFAULT '', ts INTEGER NOT NULL,
|
||||
UNIQUE(session_id, message_id));
|
||||
ALTER TABLE messages ADD COLUMN role TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE messages ADD COLUMN sender_id TEXT NOT NULL DEFAULT '';
|
||||
CREATE VIRTUAL TABLE messages_fts USING fts5(sender, text, content='messages', content_rowid='id');
|
||||
CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN
|
||||
INSERT INTO messages_fts(rowid, sender, text) VALUES (new.id, new.sender, new.text);
|
||||
END;
|
||||
CREATE TABLE turns (turn_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, source_id TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0, owner_id TEXT NOT NULL DEFAULT '',
|
||||
input_message_id TEXT NOT NULL DEFAULT '', assistant_message_id TEXT NOT NULL DEFAULT '',
|
||||
partial_text TEXT NOT NULL DEFAULT '', response_text TEXT NOT NULL DEFAULT '', tool_calls TEXT NOT NULL DEFAULT '[]',
|
||||
error TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
||||
|
||||
INSERT INTO sessions VALUES ('s1', 'telegram', 'bot', 'c1', '', 'Chat', '', '', 1000, 2000);
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m1', 's1', 'sam', 'hello there', 1000, 'user');
|
||||
INSERT INTO messages (message_id, session_id, sender, text, ts, role) VALUES ('m2', 's1', 'archie', 'hi', 1001, 'assistant');
|
||||
INSERT INTO turns VALUES ('t1', 's1', '', 'done', 1, '', 'm1', 'm2', '', 'hi', '[]', '', 1000, 1001);
|
||||
`
|
||||
|
||||
// install writes the three legacy files the way an existing install holds
|
||||
// them and returns their paths. mutate runs extra statements against a file
|
||||
// before the import sees it.
|
||||
func install(t *testing.T, mutate map[string]string) Sources {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
src := Sources{
|
||||
StateStore: filepath.Join(dir, "archie.db-tasks.sqlite"),
|
||||
EDA: filepath.Join(dir, "archie.db-eda.sqlite"),
|
||||
Gateway: filepath.Join(dir, "archie.db-conversations.sqlite"),
|
||||
}
|
||||
for path, ddl := range map[string]string{src.StateStore: stateStoreDDL, src.EDA: edaDDL, src.Gateway: gatewayDDL} {
|
||||
sqliteExec(t, path, ddl)
|
||||
}
|
||||
var src Sources
|
||||
src.StateStore, src.EDA, src.Gateway = legacyfixture.Install(t, filepath.Join(t.TempDir(), "archie.db"))
|
||||
for path, stmt := range mutate {
|
||||
switch path {
|
||||
case "state":
|
||||
sqliteExec(t, src.StateStore, stmt)
|
||||
legacyfixture.Exec(t, src.StateStore, stmt)
|
||||
case "eda":
|
||||
sqliteExec(t, src.EDA, stmt)
|
||||
legacyfixture.Exec(t, src.EDA, stmt)
|
||||
case "gateway":
|
||||
sqliteExec(t, src.Gateway, stmt)
|
||||
legacyfixture.Exec(t, src.Gateway, stmt)
|
||||
}
|
||||
}
|
||||
return src
|
||||
}
|
||||
|
||||
func sqliteExec(t *testing.T, path, stmt string) {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path)
|
||||
if err != nil {
|
||||
t.Fatalf("open fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
if _, err := db.ExecContext(t.Context(), stmt); err != nil {
|
||||
t.Fatalf("fixture %s: %v", filepath.Base(path), err)
|
||||
}
|
||||
}
|
||||
|
||||
func hashFiles(t *testing.T, dir string) map[string][32]byte {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(dir)
|
||||
@@ -297,8 +155,8 @@ func TestImportCopiesEverySourceAndLeavesThemUntouched(t *testing.T) {
|
||||
if !bytes.Equal(value, []byte{0x00, 0xff, 0x10}) {
|
||||
t.Errorf("resource_history.value = %x, want 00ff10", value)
|
||||
}
|
||||
if gotSecret != secret {
|
||||
t.Errorf("binding secret = %q, want %q", gotSecret, secret)
|
||||
if gotSecret != legacyfixture.Secret {
|
||||
t.Errorf("binding secret = %q, want %q", gotSecret, legacyfixture.Secret)
|
||||
}
|
||||
if headers != "" || result != "exit 0" || !configured {
|
||||
t.Errorf("headers %q, result %q, configured %v; want \"\", \"exit 0\", true", headers, result, configured)
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// Package postgres opens archie's PostgreSQL database and applies its schema
|
||||
// migrations. This file is the PostgreSQL implementation of the EDA
|
||||
// persistence contracts (captures, mappings, bindings and the two dispatch
|
||||
// ledgers) plus the tool_calls transcript, mirroring the PocketBase-backed
|
||||
// internal/infrastructure/edastore.Store it will replace in the cutover wave.
|
||||
// ledgers) plus the tool_calls transcript.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
@@ -20,14 +19,12 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
// EDA is the PostgreSQL implementation of every event-capture contract, plus
|
||||
// the tool_calls transcript the composition projection writes through. It
|
||||
// satisfies the same surface as *edastore.Store, so the cutover wave can swap
|
||||
// one for the other behind storecontract without touching the consumers.
|
||||
// the tool_calls transcript the composition projection writes through.
|
||||
var (
|
||||
_ storecontract.CaptureStore = (*EDA)(nil)
|
||||
_ storecontract.MappingStore = (*EDA)(nil)
|
||||
@@ -40,26 +37,23 @@ var (
|
||||
type EDA struct {
|
||||
pool *pgxpool.Pool
|
||||
q *postgresdb.Queries
|
||||
cipher edastore.BindingCipher
|
||||
cipher bindingcipher.BindingCipher
|
||||
notify func(events.Event)
|
||||
}
|
||||
|
||||
// NewEDA builds an EDA store over pool. A nil cipher keeps binding secrets in
|
||||
// plaintext (the behaviour that predates the option); the caller resolves the
|
||||
// keyring through edastore.NewBindingCipher, exactly as the PocketBase store
|
||||
// does. The pool is owned by the caller, not this store.
|
||||
func NewEDA(pool *pgxpool.Pool, cipher edastore.BindingCipher) *EDA {
|
||||
// plaintext; the caller resolves the keyring through
|
||||
// bindingcipher.NewBindingCipher. The pool is owned by the caller, not this store.
|
||||
func NewEDA(pool *pgxpool.Pool, cipher bindingcipher.BindingCipher) *EDA {
|
||||
return &EDA{pool: pool, q: postgresdb.New(pool), cipher: cipher}
|
||||
}
|
||||
|
||||
// SetNotify wires the change-event callback that the PocketBase store's
|
||||
// Config.Notify provides. It is the same injection point: nil is a silent
|
||||
// no-op, which is what every production construction gets today.
|
||||
// SetNotify wires the change-event callback. nil is a silent no-op, which is
|
||||
// what every production construction gets today.
|
||||
func (s *EDA) SetNotify(fn func(events.Event)) { s.notify = fn }
|
||||
|
||||
// notifyWrite announces one successful write on the bindings or mappings
|
||||
// tables. It mirrors edastore.(*Store).notifyWrite byte-for-byte: the data
|
||||
// carries the record id and action, and consumers refetch the row themselves.
|
||||
// tables. The data carries the record id and action, and consumers refetch the row themselves.
|
||||
func (s *EDA) notifyWrite(kind, subject, action, id string) {
|
||||
if s.notify == nil {
|
||||
return
|
||||
@@ -77,8 +71,7 @@ func newRecordID() string { return uuid.NewString() }
|
||||
// --- captures ---
|
||||
|
||||
// InsertCapture stores one inbound event verbatim. retention and maxEvents are
|
||||
// accepted for contract compatibility and applied as a prune after the insert,
|
||||
// exactly as the PocketBase store does.
|
||||
// applied as a prune after the insert.
|
||||
func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) {
|
||||
received := c.ReceivedAt
|
||||
if received.IsZero() {
|
||||
@@ -208,8 +201,8 @@ func (s *EDA) InsertMapping(ctx context.Context, m mapping.Mapping) (string, err
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// GetMapping returns (nil, nil) for an absent mapping, matching the
|
||||
// PocketBase store's found=false convention the gRPC layer translates.
|
||||
// GetMapping returns (nil, nil) for an absent mapping, the found=false
|
||||
// convention the gRPC layer translates.
|
||||
func (s *EDA) GetMapping(ctx context.Context, id string) (*mapping.Mapping, error) {
|
||||
r, err := s.q.GetMapping(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -347,8 +340,8 @@ func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, err
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// GetBinding returns (nil, nil) for an absent binding, matching the
|
||||
// PocketBase store's found=false convention the gRPC layer translates.
|
||||
// GetBinding returns (nil, nil) for an absent binding, the found=false
|
||||
// convention the gRPC layer translates.
|
||||
func (s *EDA) GetBinding(ctx context.Context, id string) (*binding.Binding, error) {
|
||||
r, err := s.q.GetBinding(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -522,8 +515,21 @@ func ledgerWrite(err error, what string) error {
|
||||
|
||||
// --- tool calls ---
|
||||
|
||||
// ToolCall is one completed tool invocation during an agent stage run, as the
|
||||
// tool_call event projection stores it: a tool's output summary in Result, a
|
||||
// failure's detail in Error.
|
||||
type ToolCall struct {
|
||||
ID string
|
||||
TaskID int64
|
||||
Attempt int
|
||||
Tool string
|
||||
Result string
|
||||
Error string
|
||||
CalledAt time.Time
|
||||
}
|
||||
|
||||
// InsertToolCall appends one row to the tool_calls transcript.
|
||||
func (s *EDA) InsertToolCall(ctx context.Context, tc edastore.ToolCall) error {
|
||||
func (s *EDA) InsertToolCall(ctx context.Context, tc ToolCall) error {
|
||||
calledAt := tc.CalledAt
|
||||
if calledAt.IsZero() {
|
||||
calledAt = time.Now()
|
||||
@@ -543,14 +549,14 @@ func (s *EDA) InsertToolCall(ctx context.Context, tc edastore.ToolCall) error {
|
||||
}
|
||||
|
||||
// TaskToolCalls returns one task's tool calls in call order.
|
||||
func (s *EDA) TaskToolCalls(ctx context.Context, taskID int64) ([]edastore.ToolCall, error) {
|
||||
func (s *EDA) TaskToolCalls(ctx context.Context, taskID int64) ([]ToolCall, error) {
|
||||
rows, err := s.q.TaskToolCalls(ctx, taskID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list tool calls: %w", err)
|
||||
}
|
||||
out := make([]edastore.ToolCall, 0, len(rows))
|
||||
out := make([]ToolCall, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, edastore.ToolCall{
|
||||
out = append(out, ToolCall{
|
||||
ID: r.ID,
|
||||
TaskID: r.TaskID,
|
||||
Attempt: int(r.Attempt),
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
const edaTestKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
@@ -24,7 +24,7 @@ func edaFor(t *testing.T) *EDA {
|
||||
return NewEDA(pool, nil)
|
||||
}
|
||||
|
||||
func edaWithCipher(t *testing.T, cipher edastore.BindingCipher) (*pgxpool.Pool, *EDA) {
|
||||
func edaWithCipher(t *testing.T, cipher bindingcipher.BindingCipher) (*pgxpool.Pool, *EDA) {
|
||||
t.Helper()
|
||||
pool, _ := migrated(t)
|
||||
return pool, NewEDA(pool, cipher)
|
||||
@@ -131,7 +131,7 @@ func TestConcurrentInsertBindingSameSource(t *testing.T) {
|
||||
// untouched, so an edit form that does not echo the secret cannot blank an
|
||||
// armed binding's HMAC key.
|
||||
func TestUpdateBindingEmptySecretPreservesStored(t *testing.T) {
|
||||
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
@@ -173,7 +173,7 @@ func readRawSecret(t *testing.T, pool *pgxpool.Pool, id string) string {
|
||||
// The cipher path must keep decrypt-in-store: what is stored is an envelope,
|
||||
// what reads back is the plaintext HMAC key the intake verifies with.
|
||||
func TestBindingSecretEncryptedAtRestAndDecryptedOnRead(t *testing.T) {
|
||||
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
|
||||
cipher, err := bindingcipher.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
@@ -200,6 +200,50 @@ func TestBindingSecretEncryptedAtRestAndDecryptedOnRead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A deployment with no configured key stores plaintext.
|
||||
func TestNoCipherKeepsPlaintext(t *testing.T) {
|
||||
pool, s := edaWithCipher(t, nil)
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-plain"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
if stored := readRawSecret(t, pool, id); stored != "supersecretvalue0123" {
|
||||
t.Errorf("stored secret = %q, want the plaintext with no cipher configured", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// A secret written under the previous key stays readable once a new active
|
||||
// key is installed; otherwise rotation bricks every armed binding.
|
||||
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, err := bindingcipher.NewBindingCipher(oldKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(old) error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, oldCipher)
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-rotate"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
rotated, err := bindingcipher.NewBindingCipher(edaTestKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
got, err := NewEDA(pool, rotated).GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() after rotation error = %v", err)
|
||||
}
|
||||
if got.Secret != "supersecretvalue0123" {
|
||||
t.Errorf("Secret after rotation = %q: the previous key must still decrypt", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// The lifecycle gate survives the port: pending_approval -> armed, and only
|
||||
// from pending_approval.
|
||||
func TestBindingLifecycle(t *testing.T) {
|
||||
@@ -308,13 +352,13 @@ func TestToolCallRoundTrip(t *testing.T) {
|
||||
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
|
||||
|
||||
for range 2 {
|
||||
if err := s.InsertToolCall(t.Context(), edastore.ToolCall{
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 42, Attempt: 2, Tool: "shell", Result: "all checks passed", CalledAt: at,
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall() error = %v", err)
|
||||
}
|
||||
}
|
||||
if err := s.InsertToolCall(t.Context(), edastore.ToolCall{
|
||||
if err := s.InsertToolCall(t.Context(), ToolCall{
|
||||
TaskID: 7, Attempt: 1, Tool: "read_file", Error: "no such file", CalledAt: at.Add(time.Second),
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertToolCall(other task) error = %v", err)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Package pgstore opens migrated PostgreSQL stores on a throwaway pgtest
|
||||
// database, for tests outside internal/infrastructure/postgres. A package
|
||||
// using it calls pgtest.Main from TestMain.
|
||||
package pgstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// TaskDB is the State Store's task database: the task, event, status and
|
||||
// identity surface plus the control-plane resources, over one pool.
|
||||
type TaskDB struct {
|
||||
*postgres.Store
|
||||
*postgres.Resources
|
||||
Pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// Pool opens a pool on a fresh migrated database, closed when t ends.
|
||||
func Pool(t testing.TB) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
return PoolAt(t, pgtest.URL(t))
|
||||
}
|
||||
|
||||
// PoolAt opens a pool on url and migrates it, closed when t ends. Opening a
|
||||
// second pool on the same url is how a test models a restart.
|
||||
func PoolAt(t testing.TB, url string) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
pool, err := postgres.Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatalf("pgstore: open: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
|
||||
t.Fatalf("pgstore: migrate: %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
// On returns the task database over pool.
|
||||
func On(pool *pgxpool.Pool) *TaskDB {
|
||||
return &TaskDB{Store: postgres.New(pool), Resources: postgres.NewResources(pool), Pool: pool}
|
||||
}
|
||||
|
||||
// Open returns the task database on a fresh migrated database.
|
||||
func Open(t testing.TB) *TaskDB {
|
||||
t.Helper()
|
||||
return On(Pool(t))
|
||||
}
|
||||
|
||||
// EDA returns the event-capture store on a fresh migrated database. A nil
|
||||
// cipher keeps binding secrets in plaintext.
|
||||
func EDA(t testing.TB, cipher bindingcipher.BindingCipher) *postgres.EDA {
|
||||
t.Helper()
|
||||
return postgres.NewEDA(Pool(t), cipher)
|
||||
}
|
||||
@@ -14,8 +14,7 @@ import (
|
||||
)
|
||||
|
||||
// Resources is the PostgreSQL implementation of the State Store's
|
||||
// control-plane resource document operations. It is separate while the rest
|
||||
// of the transitional SQLite Store is still being ported.
|
||||
// control-plane resource document operations.
|
||||
type Resources struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// TestEventAttributionSurvivesTheStateStoreBoundary runs the same insert through
|
||||
@@ -28,7 +28,7 @@ func TestEventAttributionSurvivesTheStateStoreBoundary(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
var c contract = local
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, local, nil, nil)
|
||||
|
||||
@@ -6,16 +6,16 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
local := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
body := strings.Repeat("x", 256<<10)
|
||||
for range 20 {
|
||||
if _, err := eda.InsertCapture(t.Context(), store.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
if _, err := eda.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
}
|
||||
remote := remoteEDA(t, local, eda)
|
||||
for _, undispatched := range []bool{false, true} {
|
||||
var captures []store.CapturedEvent
|
||||
var captures []storecontract.CapturedEvent
|
||||
var err error
|
||||
if undispatched {
|
||||
captures, err = remote.ListUndispatchedCaptures(t.Context(), []string{"large"}, 20)
|
||||
|
||||
@@ -13,56 +13,57 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// contract is the union of every store surface staterpc fronts (minus the
|
||||
// playbook-dispatch ledger, split out below to keep the interface under the
|
||||
// repo's 8-method cap), so the same test battery drives both the local
|
||||
// *store.Store and the remote *Client through one interface value, per
|
||||
// *pgstore.TaskDB and the remote *Client through one interface value, per
|
||||
// docs/prds/state-store-contract.md §11's conformance requirement.
|
||||
type contract interface {
|
||||
store.TaskStore
|
||||
store.BindingTaskCreator
|
||||
store.ConfigSnapshotStore
|
||||
store.ApplyStatusStore
|
||||
storecontract.TaskStore
|
||||
storecontract.BindingTaskCreator
|
||||
storecontract.ConfigSnapshotStore
|
||||
storecontract.ApplyStatusStore
|
||||
}
|
||||
|
||||
// edaContract is the event-capture half, which the PocketBase store serves.
|
||||
// It is a separate interface because no single type implements both halves
|
||||
// any more: that split is the point of the migration, not an accident.
|
||||
type edaContract interface {
|
||||
store.CaptureStore
|
||||
store.MappingStore
|
||||
store.BindingStore
|
||||
store.BindingDispatcher
|
||||
storecontract.CaptureStore
|
||||
storecontract.MappingStore
|
||||
storecontract.BindingStore
|
||||
storecontract.BindingDispatcher
|
||||
}
|
||||
|
||||
// playbookContract is the playbook-dispatch idempotency-ledger surface, split
|
||||
// out from contract so each aggregate stays under the repo's interfacebloat
|
||||
// cap without weakening what the conformance battery proves.
|
||||
type playbookContract interface {
|
||||
store.PlaybookDispatcher
|
||||
storecontract.PlaybookDispatcher
|
||||
}
|
||||
|
||||
// taskLogContract is the task-log read group, driven separately because it is
|
||||
// not a *store.Store surface: the reader is internal/logging's own registry,
|
||||
// not a *pgstore.TaskDB surface: the reader is internal/logging's own registry,
|
||||
// which owns the log format, so the local side of this contract is a registry
|
||||
// rather than a store.
|
||||
type taskLogContract interface {
|
||||
store.TaskLogStore
|
||||
storecontract.TaskLogStore
|
||||
}
|
||||
|
||||
// remoteEDA fronts both stores for a battery that exercises event-capture
|
||||
// surfaces over the wire.
|
||||
func remoteEDA(t *testing.T, local *store.Store, eda *edastore.Store) *Client {
|
||||
func remoteEDA(t *testing.T, local *pgstore.TaskDB, eda *postgres.EDA) *Client {
|
||||
t.Helper()
|
||||
return remoteTaskStore(t, local, nil, eda)
|
||||
}
|
||||
|
||||
func remoteContract(t *testing.T, local *store.Store) contract {
|
||||
func remoteContract(t *testing.T, local *pgstore.TaskDB) contract {
|
||||
t.Helper()
|
||||
return remoteTaskStore(t, local, nil, nil)
|
||||
}
|
||||
@@ -75,7 +76,7 @@ func remoteContract(t *testing.T, local *store.Store) contract {
|
||||
// task store for the task surfaces, the event-capture store for captures,
|
||||
// mappings, bindings and the dispatch ledgers. eda may be nil for a battery
|
||||
// that exercises only task surfaces.
|
||||
func remoteTaskStore(t *testing.T, local *store.Store, logs store.TaskLogStore, eda *edastore.Store) *Client {
|
||||
func remoteTaskStore(t *testing.T, local *pgstore.TaskDB, logs storecontract.TaskLogStore, eda *postgres.EDA) *Client {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
@@ -112,8 +113,8 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
local := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
var c contract = local
|
||||
var ec edaContract = eda
|
||||
var pc playbookContract = eda
|
||||
@@ -168,7 +169,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
|
||||
// Stale transition: from no longer matches current status.
|
||||
err = c.Transition(ctx, task.ID, "queued", "merged", "")
|
||||
if !errors.Is(err, store.ErrStaleTransition) {
|
||||
if !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("Transition stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
|
||||
@@ -181,7 +182,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); err != nil {
|
||||
t.Fatalf("BeginRemediation: %v", err)
|
||||
}
|
||||
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); !errors.Is(err, store.ErrStaleTransition) {
|
||||
if err := c.BeginRemediation(ctx, task.ID, `{"review_id":7}`); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("BeginRemediation stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
remediated, err := c.TaskByID(ctx, task.ID)
|
||||
@@ -197,7 +198,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
if err := c.Transition(ctx, task.ID, "queued", "running", "claimed"); err != nil {
|
||||
t.Fatalf("claim: %v", err)
|
||||
}
|
||||
if err := c.UpdateReviewPayload(ctx, task.ID, `{}`); !errors.Is(err, store.ErrStaleTransition) {
|
||||
if err := c.UpdateReviewPayload(ctx, task.ID, `{}`); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("UpdateReviewPayload stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
|
||||
@@ -309,7 +310,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
if parked.Status != "parked" || parked.ParkClass != "transient" || parked.ParkReason != "container pool unavailable" {
|
||||
t.Fatalf("ParkTask row = status:%q class:%q reason:%q", parked.Status, parked.ParkClass, parked.ParkReason)
|
||||
}
|
||||
if err := c.ParkTask(ctx, claimed.ID, "running", "late park", "transient"); !errors.Is(err, store.ErrStaleTransition) {
|
||||
if err := c.ParkTask(ctx, claimed.ID, "running", "late park", "transient"); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("ParkTask stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
// An unclassified park normalizes to needs_human store-side rather
|
||||
@@ -371,11 +372,11 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("UpdateMapping: %v", err)
|
||||
}
|
||||
err = ec.UpdateMapping(ctx, mapping.Mapping{ID: "rabsent00000000", Name: "x", Fields: gotMapping.Fields})
|
||||
if !errors.Is(err, store.ErrMappingNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
t.Fatalf("UpdateMapping missing = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
err = ec.DeleteMapping(ctx, "rabsent00000000")
|
||||
if !errors.Is(err, store.ErrMappingNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrMappingNotFound) {
|
||||
t.Fatalf("DeleteMapping missing = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
|
||||
@@ -393,7 +394,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
Name: "b2", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
|
||||
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
})
|
||||
if !errors.Is(err, store.ErrBindingOverlap) {
|
||||
if !errors.Is(err, storecontract.ErrBindingOverlap) {
|
||||
t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err)
|
||||
}
|
||||
missingBinding, err := ec.GetBinding(ctx, "rabsent00000000")
|
||||
@@ -411,16 +412,16 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("ApproveBinding from pending_approval = %v", err)
|
||||
}
|
||||
err = ec.ApproveBinding(ctx, bindingID)
|
||||
if !errors.Is(err, store.ErrBindingTransition) {
|
||||
if !errors.Is(err, storecontract.ErrBindingTransition) {
|
||||
t.Fatalf("ApproveBinding when armed = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
err = ec.DeleteBinding(ctx, "rabsent00000000")
|
||||
if !errors.Is(err, store.ErrBindingNotFound) {
|
||||
if !errors.Is(err, storecontract.ErrBindingNotFound) {
|
||||
t.Fatalf("DeleteBinding missing = %v, want ErrBindingNotFound", err)
|
||||
}
|
||||
|
||||
// Capture + dispatch.
|
||||
captureID, err := ec.InsertCapture(ctx, store.CapturedEvent{Source: "sentry", Body: `{"id":1}`, Authenticated: true}, 0, 0)
|
||||
captureID, err := ec.InsertCapture(ctx, storecontract.CapturedEvent{Source: "sentry", Body: `{"id":1}`, Authenticated: true}, 0, 0)
|
||||
if err != nil || captureID == "" {
|
||||
t.Fatalf("InsertCapture: %v %v", captureID, err)
|
||||
}
|
||||
@@ -438,7 +439,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("RecordDispatch: %v", err)
|
||||
}
|
||||
err = ec.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID)
|
||||
if !errors.Is(err, store.ErrAlreadyDispatched) {
|
||||
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Fatalf("RecordDispatch dup = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
if _, err := ec.ListUndispatchedCaptures(ctx, []string{"sentry"}, 10); err != nil {
|
||||
@@ -466,7 +467,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("RecordPlaybookDispatch (distinct action_id) = %v, want success", err)
|
||||
}
|
||||
err = pc.RecordPlaybookDispatch(ctx, "pb.yaml", "v1", "archie:acme/widget/7", "notify")
|
||||
if !errors.Is(err, store.ErrAlreadyDispatched) {
|
||||
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
t.Fatalf("RecordPlaybookDispatch dup = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
if err := pc.DeletePlaybookDispatches(ctx, "pb.yaml"); err != nil {
|
||||
@@ -487,7 +488,7 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
func TestConfigSnapshotContract(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
var st contract = local
|
||||
if mode == "grpc" {
|
||||
st = remoteContract(t, local)
|
||||
@@ -498,7 +499,7 @@ func TestConfigSnapshotContract(t *testing.T) {
|
||||
t.Fatalf("unpublished snapshot = (found %v, %v), want (false, nil)", found, err)
|
||||
}
|
||||
|
||||
published := store.ConfigSnapshot{
|
||||
published := storecontract.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),
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// TestUnmapErrorPreservesContextIdentity pins the §6 deadline contract that
|
||||
@@ -34,7 +34,7 @@ func TestUnmapErrorPreservesContextIdentity(t *testing.T) {
|
||||
if !errors.Is(got, tt.want) {
|
||||
t.Fatalf("unmapError(%q) = %v, want errors.Is(err, %v)", tt.err, got, tt.want)
|
||||
}
|
||||
if errors.Is(got, store.ErrStaleTransition) {
|
||||
if errors.Is(got, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("unmapError(%q) = %v, must not map to a store sentinel", tt.err, got)
|
||||
}
|
||||
})
|
||||
@@ -75,12 +75,12 @@ func TestUnmapErrorSentinelFidelity(t *testing.T) {
|
||||
store error
|
||||
rehyd error
|
||||
}{
|
||||
{name: "stale transition", store: store.ErrStaleTransition, rehyd: store.ErrStaleTransition},
|
||||
{name: "binding not found", store: store.ErrBindingNotFound, rehyd: store.ErrBindingNotFound},
|
||||
{name: "mapping not found", store: store.ErrMappingNotFound, rehyd: store.ErrMappingNotFound},
|
||||
{name: "binding overlap", store: store.ErrBindingOverlap, rehyd: store.ErrBindingOverlap},
|
||||
{name: "binding transition", store: store.ErrBindingTransition, rehyd: store.ErrBindingTransition},
|
||||
{name: "already dispatched", store: store.ErrAlreadyDispatched, rehyd: store.ErrAlreadyDispatched},
|
||||
{name: "stale transition", store: storecontract.ErrStaleTransition, rehyd: storecontract.ErrStaleTransition},
|
||||
{name: "binding not found", store: storecontract.ErrBindingNotFound, rehyd: storecontract.ErrBindingNotFound},
|
||||
{name: "mapping not found", store: storecontract.ErrMappingNotFound, rehyd: storecontract.ErrMappingNotFound},
|
||||
{name: "binding overlap", store: storecontract.ErrBindingOverlap, rehyd: storecontract.ErrBindingOverlap},
|
||||
{name: "binding transition", store: storecontract.ErrBindingTransition, rehyd: storecontract.ErrBindingTransition},
|
||||
{name: "already dispatched", store: storecontract.ErrAlreadyDispatched, rehyd: storecontract.ErrAlreadyDispatched},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -104,7 +104,7 @@ func TestUnmapErrorDoesNotLeakInternalDetail(t *testing.T) {
|
||||
const detail = "sql: path=/var/lib/archie/archie.db secret=abcdef"
|
||||
internal := mapError(errors.New(detail))
|
||||
got := unmapError(internal)
|
||||
if errors.Is(got, store.ErrStaleTransition) || errors.Is(got, store.ErrBindingNotFound) || errors.Is(got, store.ErrAlreadyDispatched) {
|
||||
if errors.Is(got, storecontract.ErrStaleTransition) || errors.Is(got, storecontract.ErrBindingNotFound) || errors.Is(got, storecontract.ErrAlreadyDispatched) {
|
||||
t.Fatalf("unmapError(internal) = %v, must not map to a store sentinel", got)
|
||||
}
|
||||
if st, ok := status.FromError(got); !ok || st.Code() != codes.Internal {
|
||||
@@ -118,7 +118,7 @@ func TestUnmapErrorDoesNotLeakInternalDetail(t *testing.T) {
|
||||
// status or a store sentinel).
|
||||
raw := errors.New("transport failure")
|
||||
got = unmapError(raw)
|
||||
if errors.Is(got, store.ErrStaleTransition) {
|
||||
if errors.Is(got, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("unmapError(raw) = %v, must not map to a store sentinel", got)
|
||||
}
|
||||
if !errors.Is(got, raw) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -14,10 +14,10 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// grantsServer wires TaskGrants' Unary/Stream interceptors -- the same
|
||||
@@ -28,14 +28,14 @@ func grantsServer(t *testing.T, adminToken string) (grants *TaskGrants, dial fun
|
||||
t.Helper()
|
||||
grants = &TaskGrants{}
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
server := grpc.NewServer(
|
||||
grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(adminToken)),
|
||||
grpc.ChainStreamInterceptor(grants.StreamInterceptor(adminToken)),
|
||||
)
|
||||
// One event-capture store serves every EDA surface, as the real
|
||||
// composition does: separate instances would not share a database.
|
||||
eda := edastore.OpenTest(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
RegisterServer(server, Deps{
|
||||
Tasks: local, ConfigSnapshots: local, ApplyStatus: local,
|
||||
Captures: eda, Mappings: eda, Bindings: eda,
|
||||
@@ -79,7 +79,7 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
|
||||
|
||||
body := strings.Repeat("x", 256<<10)
|
||||
for range 20 {
|
||||
if _, err := admin.InsertCapture(ctx, store.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
if _, err := admin.InsertCapture(ctx, storecontract.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -114,10 +114,10 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
list func(context.Context) ([]store.CapturedEvent, error)
|
||||
list func(context.Context) ([]storecontract.CapturedEvent, error)
|
||||
}{
|
||||
{"ListCaptures", func(ctx context.Context) ([]store.CapturedEvent, error) { return admin.ListCaptures(ctx, 20) }},
|
||||
{"ListUndispatchedCaptures", func(ctx context.Context) ([]store.CapturedEvent, error) {
|
||||
{"ListCaptures", func(ctx context.Context) ([]storecontract.CapturedEvent, error) { return admin.ListCaptures(ctx, 20) }},
|
||||
{"ListUndispatchedCaptures", func(ctx context.Context) ([]storecontract.CapturedEvent, error) {
|
||||
return admin.ListUndispatchedCaptures(ctx, []string{"large"}, 20)
|
||||
}},
|
||||
} {
|
||||
@@ -263,7 +263,7 @@ func TestOnlyAdminPublishesTheConfigSnapshot(t *testing.T) {
|
||||
}
|
||||
worker := dial(t, workerToken)
|
||||
|
||||
snapshot := store.ConfigSnapshot{Schema: "webui.ConfigView/1", Document: []byte(`{}`)}
|
||||
snapshot := storecontract.ConfigSnapshot{Schema: "webui.ConfigView/1", Document: []byte(`{}`)}
|
||||
if err := admin.PutConfigSnapshot(ctx, snapshot); err != nil {
|
||||
t.Fatalf("admin PutConfigSnapshot: %v", err)
|
||||
}
|
||||
@@ -298,7 +298,7 @@ func TestOnlyAdminReportsApplyStatus(t *testing.T) {
|
||||
}
|
||||
worker := dial(t, workerToken)
|
||||
|
||||
status := store.ApplyStatus{Process: "archied", Kind: "tool-settings", AppliedVersion: 2}
|
||||
status := storecontract.ApplyStatus{Process: "archied", Kind: "tool-settings", AppliedVersion: 2}
|
||||
if err := admin.PutApplyStatus(ctx, status); err != nil {
|
||||
t.Fatalf("admin PutApplyStatus: %v", err)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// A decoded task-log page must never carry a nil slice for a collection field.
|
||||
@@ -54,7 +54,7 @@ func TestTaskLogPageCarriesNoNilCollectionFields(t *testing.T) {
|
||||
|
||||
var c taskLogContract = reader
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, store.OpenTest(t), reader, nil)
|
||||
c = remoteTaskStore(t, pgstore.Open(t), reader, nil)
|
||||
}
|
||||
|
||||
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{})
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// TestTaskLogContract drives the task-log read group through both adapters,
|
||||
@@ -41,7 +41,7 @@ func TestTaskLogContract(t *testing.T) {
|
||||
|
||||
var c taskLogContract = reader
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, store.OpenTest(t), reader, nil)
|
||||
c = remoteTaskStore(t, pgstore.Open(t), reader, nil)
|
||||
}
|
||||
|
||||
t.Run("a page carries the decoded entries and their fields", func(t *testing.T) {
|
||||
@@ -162,7 +162,7 @@ func TestTaskLogContract(t *testing.T) {
|
||||
// that has no log, and the dashboard rendered that as "task logging is
|
||||
// optional and was not enabled for this run".
|
||||
func TestTaskLogContractWithoutAReaderIsUnavailable(t *testing.T) {
|
||||
local := store.OpenTest(t)
|
||||
local := pgstore.Open(t)
|
||||
// remoteContract leaves Deps.TaskLogs nil, which is what a store service
|
||||
// sharing no state directory with the daemon looks like.
|
||||
c := remoteContract(t, local)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package taskactions
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
domain "github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -86,10 +86,10 @@ func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "store refused a stale transition",
|
||||
store: stubStore{task: running, err: store.ErrStaleTransition},
|
||||
store: stubStore{task: running, err: storecontract.ErrStaleTransition},
|
||||
cancel: func(int64) bool { return true },
|
||||
action: taskstate.ActionStop,
|
||||
want: store.ErrStaleTransition,
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user