chore(state-store): remove the one-time SQLite import and db_path

Every install serves from Postgres, so the legacyread/legacyimport packages,
the archie-state-store import command, the boot gate that refused to serve
over unimported SQLite files, and db_path (which only located those files)
go. Migration 0010 drops the import_completion table.
This commit is contained in:
sam committed 2026-09-25 00:40:48 +10:00
1 parent 4479f212d7
commit c1cd5c8f5b
65 files changed
+138 -3350

No files matched your search

@@ -106,7 +106,7 @@ Do not expose these helper flags as daemon settings.
| Keys | Default, validation, and consumer | Status |
| --- | --- | --- |
| `work_dir`, `state_dir`, `db_path` | Derive from `$XDG_DATA_HOME/archie`, else `$HOME/.local/share/archie`; explicit `~` paths are home-expanded. `state_dir` holds the embedded NATS store and endpoint file, task logs and the readiness disk target. `db_path` only locates the legacy `<db_path>-tasks.sqlite`, `-eda.sqlite` and `-conversations.sqlite` files for `archie-state-store import` and the boot gate. | production-wired |
| `work_dir`, `state_dir` | Derive from `$XDG_DATA_HOME/archie`, else `$HOME/.local/share/archie`; explicit `~` paths are home-expanded. `state_dir` holds the embedded NATS store and endpoint file, task logs and the readiness disk target. | production-wired |
| `skills_dir` | Empty falls back to `work_dir` for startup workflow registry. | partially-wired |
| `plugin_dir` | Empty disables daemon plugin loading; configured directory loaded in `internal/app/archied`. | production-wired |
| `poll_interval` | Default `60s`; root poll loop uses it, identities may override only interval. | production-wired |
@@ -18,7 +18,7 @@ history.
| Stage request | One autonomous workflow stage sent on `archie.agent.<task-id>.request`. |
| Full-task handoff | A whole workflow sent on core NATS subject `archie.taskrun.<task-id>` to a task container. |
| Work directory | `work_dir`: task clones plus memory and candidate index artifacts. |
| State directory | `state_dir` (default `~/.local/share/archie`): embedded NATS store, task logs. Task, event, capture and conversation data live in the PostgreSQL database `database_url` names. `db_path` only locates pre-PostgreSQL files for `archie-state-store import`. |
| State directory | `state_dir` (default `~/.local/share/archie`): embedded NATS store, task logs. Task, event, capture and conversation data live in the PostgreSQL database `database_url` names. |
## Apply the operational safety boundary
+60 -37
View File
@@ -16,9 +16,10 @@ context of each event to decide how to accomplish the task.
Archie is under active development. The model below describes the project's
approved direction, with implementation progressing across event automation and
organization access control. The [event automation design](docs/prds/event-automation.md)
and [organizations and access design](docs/prds/orgs-and-access.md) describe
those capabilities and their delivery stages.
organisation access control. The
[event automation design](docs/prds/event-automation.md) and
[organisations and access design](docs/prds/orgs-and-access.md) describe those
capabilities and their delivery stages.
## From an event to an outcome
@@ -26,14 +27,14 @@ those capabilities and their delivery stages.
Event source → Event type → Mapping → Binding → Workflow → Agent
```
| Concept | Purpose |
| --- | --- |
| **Source** | Receive events from a system such as a firewall, monitoring stack, service desk, or forge. Configure its endpoint and signing requirements. |
| **Event type** | Identify which kind of event arrived from its headers and payload. Infer a schema from captured events or a pasted example. |
| **Mapping** | Extract named, typed parameters from the event. Reuse a mapping across bindings and see how often it matches. |
| **Binding** | Select a workflow, filter the events that should trigger it, and supply its inputs from mapped values or constants. |
| **Workflow** | Define the stages of work, their inputs and outputs, and the agent profile to use. Call other workflows when work needs another specialist or process. |
| **Agent** | Execute the work in a container with the tools for its purpose, acting under its own identity and granted permissions. |
| Concept | Purpose |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Source** | Receive events from a system such as a firewall, monitoring stack, service desk, or forge. Configure its endpoint and signing requirements. |
| **Event type** | Identify which kind of event arrived from its headers and payload. Infer a schema from captured events or a pasted example. |
| **Mapping** | Extract named, typed parameters from the event. Reuse a mapping across bindings and see how often it matches. |
| **Binding** | Select a workflow, filter the events that should trigger it, and supply its inputs from mapped values or constants. |
| **Workflow** | Define the stages of work, their inputs and outputs, and the agent profile to use. Call other workflows when work needs another specialist or process. |
| **Agent** | Execute the work in a container with the tools for its purpose, acting under its own identity and granted permissions. |
A single source can produce several event types. An event type can feed several
bindings, and each binding can apply its own conditions. This lets the same
@@ -49,7 +50,7 @@ workflow, subject to the permissions and approvals configured for that action.
The same model supports other processes:
- **Infrastructure operations:** A monitoring alert starts a diagnostic workflow
to inspect a service, collect evidence, and propose or perform an authorized
to inspect a service, collect evidence, and propose or perform an authorised
recovery action.
- **Service management:** An incoming request supplies the parameters for a
triage, investigation, or fulfilment workflow.
@@ -68,25 +69,26 @@ for an investigator, operational tooling for a systems agent, or a language
runtime and test framework for repository work.
Workflows declare structured inputs and can return structured outputs. They can
run with a scratch workspace, require a repository, or accept one optionally.
An investigation can finish with a report; a maintenance workflow can finish
with an operational result; a coding workflow can finish with a pull request.
run with a scratch workspace, require a repository, or accept one optionally. An
investigation can finish with a report; a maintenance workflow can finish with
an operational result; a coding workflow can finish with a pull request.
Workflows can also call other workflows and pass data between them. Each called
workflow has its own run and agent profile. A caller can wait for the result or
continue while the called workflow runs independently.
See the [firewall investigation example](examples/workflows/firewall-investigate.yaml)
See the
[firewall investigation example](examples/workflows/firewall-investigate.yaml)
for a workflow that uses typed inputs, a network investigator profile, and no
repository.
## Organizations, identities, and controlled execution
## Organisations, identities, and controlled execution
The approved access model organizes automation into **organizations** and
**workspaces**. An organization owns its members, agent identities, secrets,
The approved access model organises automation into **organisations** and
**workspaces**. An organisation owns its members, agent identities, secrets,
profiles, and workflows. Workspaces group sources, mappings, bindings, and runs
by team responsibility or environment, such as network operations in production.
Each organization can enable the default workflows it needs and add its own.
Each organisation can enable the default workflows it needs and add its own.
Agents act as their own identities. A workflow names the identity it runs as;
secrets and permissions are granted to that identity. Starting an agent is an
@@ -95,22 +97,22 @@ initiated it.
The design combines roles for routine administration with attribute-based
policies for resources and execution context. Policies apply from the instance
through the organization, workspace, identity, workflow, and individual object.
Lower levels can narrow access, and a denial takes precedence. Organization and
through the organisation, workspace, identity, workflow, and individual object.
Lower levels can narrow access, and a denial takes precedence. Organisation and
workspace policy also determines which actions require approval from another
member.
Authorized runs receive credentials scoped to their identity, workspace, and
Authorised runs receive credentials scoped to their identity, workspace, and
work. Event data supplies the task's inputs; it cannot grant additional access.
The [organizations and access design](docs/prds/orgs-and-access.md) defines this
The [organisations and access design](docs/prds/orgs-and-access.md) defines this
model; it remains an active implementation area.
## Building and operating automations
The dashboard brings together event inspection, mappings, bindings, workflows,
and task activity. The intended authoring path starts with a real payload or an
example: identify its structure, map the fields you need, select a workflow,
and approve the binding.
example: identify its structure, map the fields you need, select a workflow, and
approve the binding.
Sources default to signed delivery. The event automation design also allows an
explicitly approved unsigned source for systems that cannot sign payloads, with
@@ -118,18 +120,26 @@ that status visible to operators. Binding changes require re-approval before
they can dispatch work.
Playbooks and extension points provide additional orchestration through
workflows, modules, channels, and forges. The [playbook engine design](docs/prds/eda-playbook-engine.md)
describes how registered capabilities become actions that event rules can call.
workflows, modules, channels, and forges. The
[playbook engine design](docs/prds/eda-playbook-engine.md) describes how
registered capabilities become actions that event rules can call.
## Develop locally
The repository requires Go 1.27, [Task](https://taskfile.dev/), Node.js and npm, and Docker with a running daemon. The development stack starts PostgreSQL 18 through Docker Compose. Install the Go formatting and lint tools listed in [CLAUDE.md](CLAUDE.md#build--test) before running the full quality gate.
The repository requires Go 1.27, [Task](https://taskfile.dev/), Node.js and npm,
and Docker with a running daemon. The development stack starts PostgreSQL 18
through Docker Compose. Install the Go formatting and lint tools listed in
[CLAUDE.md](CLAUDE.md#build--test) before running the full quality gate.
```bash
task dev
```
Open <http://localhost:5173> for the dashboard with Vite hot reload. `task dev` starts the daemon, Gateway, State Store, UI service, and frontend development server; it uses [`deployments/dev.toml`](deployments/dev.toml) as a local configuration overlay. Set credentials and other required settings in your local Archie configuration as needed.
Open <http://localhost:5173> for the dashboard with Vite hot reload. `task dev`
starts the daemon, Gateway, State Store, UI service, and frontend development
server; it uses [`deployments/dev.toml`](deployments/dev.toml) as a local
configuration overlay. Set credentials and other required settings in your local
Archie configuration as needed.
Useful checks:
@@ -141,16 +151,29 @@ task check # run the repository quality gate
## Deploy
Start with the [deployment examples](deployments/README.md). They cover a single GitHub forge, multiple GitHub and Gitea identities, local Ollama, and an external NATS stack. Copy a suitable template to `${XDG_CONFIG_HOME:-~/.config}/archie/config.toml`, then set its repository, model, credential, and service settings for your environment. The examples describe the required PostgreSQL connection and how to start each process. A [systemd user service guide](deployments/systemd-user-service.md) is available, but systemd is optional.
Start with the [deployment examples](deployments/README.md). They cover a single
GitHub forge, multiple GitHub and Gitea identities, local Ollama, and an
external NATS stack. Copy a suitable template to
`${XDG_CONFIG_HOME:-~/.config}/archie/config.toml`, then set its repository,
model, credential, and service settings for your environment. The examples
describe the required PostgreSQL connection and how to start each process. A
[systemd user service guide](deployments/systemd-user-service.md) is available,
but systemd is optional.
## Documentation
- [Event automation](docs/prds/event-automation.md) — sources, schemas, mappings, bindings, workflows, and agent profiles.
- [Organizations and access](docs/prds/orgs-and-access.md) — tenancy, identities, permissions, approvals, and audit.
- [Playbook engine](docs/prds/eda-playbook-engine.md) — event rules and extensible actions.
- [Architecture decisions](docs/prds/01-project-management.md) — approved design and open migration questions.
- [Event automation](docs/prds/event-automation.md) — sources, schemas,
mappings, bindings, workflows, and agent profiles.
- [Organisations and access](docs/prds/orgs-and-access.md) — tenancy,
identities, permissions, approvals, and audit.
- [Playbook engine](docs/prds/eda-playbook-engine.md) — event rules and
extensible actions.
- [Architecture decisions](docs/prds/01-project-management.md) — approved design
and open migration questions.
- [Development guides](docs/development/index.md) — change checklists by area.
- [Deployment examples](deployments/README.md) — configuration templates and operating notes.
- [Deployment examples](deployments/README.md) — configuration templates and
operating notes.
- [Release process](RELEASING.md) — how releases are built and published.
Contributions should follow [CLAUDE.md](CLAUDE.md), including its testing, generated-file, and commit rules.
Contributions should follow [AGENTS.md](AGENTS.md), including its testing,
generated-file, and commit rules.
@@ -38,7 +38,6 @@ var deletionGate = []bannedCategory{
"modernc.org/sqlite",
"github.com/jackc/pgx",
modulePath + "internal/infrastructure/postgres",
modulePath + "internal/infrastructure/legacyread",
}},
{"daemon runtime", []string{
modulePath + "internal/daemon",
-46
View File
@@ -1,46 +0,0 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
"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)) }
// TestRecoveryImportMovesTheInstallOnce drives the import the way an operator
// does: the configured db_path locates every legacy file, and a second run
// against the same database is refused because the first one completed.
func TestRecoveryImportMovesTheInstallOnce(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "archie.db")
legacyfixture.Install(t, dbPath)
url := pgtest.URL(t)
code, stdout, stderr := runRecoveryCmd(t, "import", "-db-path", dbPath, "-database-url", url)
if code != 0 {
t.Fatalf("import exited %d; stderr = %q", code, stderr)
}
if !strings.Contains(stdout, "tasks=2") {
t.Errorf("import summary %q does not report the imported task", stdout)
}
pool, err := postgres.Open(t.Context(), url)
if err != nil {
t.Fatalf("postgres.Open: %v", err)
}
defer pool.Close()
var issue int64
if err := pool.QueryRow(t.Context(), "SELECT issue_number FROM tasks WHERE id = 1").Scan(&issue); err != nil || issue != 7 {
t.Fatalf("imported task 1 issue = %d, %v; want 7", issue, err)
}
code, _, stderr = runRecoveryCmd(t, "import", "-db-path", dbPath, "-database-url", url)
if code != 1 || !strings.Contains(stderr, "already holds a completed import") {
t.Fatalf("second import exited %d, stderr %q; want 1 naming the completed import", code, stderr)
}
}
+10
View File
@@ -0,0 +1,10 @@
package main
import (
"os"
"testing"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
)
func TestMain(m *testing.M) { os.Exit(pgtest.Main(m)) }
+4 -5
View File
@@ -89,7 +89,7 @@ func buildBinary(t *testing.T, dir string) string {
// while keeping the process minimal: the standalone binary takes its gRPC
// listen address from -listen or [services.state].listen, never from the
// target, so the config only needs the fields validation requires plus the
// db_path and database_url it owns. The
// database_url it owns. The
// forge token resolves from an env var, so no real credential is needed.
func writeMinimalConfig(t *testing.T, dir string) string {
t.Helper()
@@ -101,7 +101,6 @@ func writeConfigFor(t *testing.T, dir, url string) string {
t.Helper()
cfg := filepath.Join(dir, "config.toml")
content := fmt.Sprintf(`bot_user = "archie-bot"
db_path = %q
database_url = %q
[forge]
type = "github"
@@ -110,7 +109,7 @@ token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" }
[[repos]]
owner = "acme"
name = "widget"
`, filepath.Join(dir, "archie.db"), url)
`, url)
if err := os.WriteFile(cfg, []byte(content), 0o600); err != nil {
t.Fatalf("write config: %v", err)
}
@@ -437,7 +436,7 @@ func TestStateStoreRealProcessSmoke(t *testing.T) {
t.Run("serves_from_postgres_only", func(t *testing.T) {
// The binary serves every store from database_url: no SQLite file
// appears beside the configured db_path.
// appears in its directory.
for _, name := range []string{"archie.db", "archie.db-tasks.sqlite", "archie.db-eda.sqlite"} {
if _, err := os.Stat(filepath.Join(dir, name)); err == nil {
t.Fatalf("state store created %s; it serves from Postgres only", name)
@@ -472,7 +471,7 @@ func TestStateStoreRealProcessDeadline(t *testing.T) {
}
// TestStateStoreRealProcessRestartRecovery starts the process, writes a task,
// stops it (SIGTERM), restarts it on the same config/db_path, and verifies the
// stops it (SIGTERM), restarts it on the same config, and verifies the
// task and its events were recovered from the on-disk SQLite -- the
// restart/recovery path the runbook relies on when archie-state-store is
// restarted as a service.
+1 -9
View File
@@ -37,9 +37,6 @@ snapshot taken before it.
the configuration the daemon would boot with
rollback -kind KIND replay an earlier revision of a stored
[-revision N] resource through the ordinary replace
import [-db-path PATH] copy the legacy SQLite stores named from
[-database-url URL] db_path into an empty Postgres database,
once; refuses while any Archie service runs
Every command takes -config FILE and -config-overlay FILE: the configuration
the daemon boots with, which names the database.
@@ -56,8 +53,7 @@ func runRecovery(args []string, stdout, stderr io.Writer) int {
command := args[0]
options := archied.StateStoreRecoveryOptions{Operation: command}
switch command {
case archied.RecoveryBackup, archied.RecoveryRestore, archied.RecoveryValidate, archied.RecoveryRollback,
archied.RecoveryImport:
case archied.RecoveryBackup, archied.RecoveryRestore, archied.RecoveryValidate, archied.RecoveryRollback:
default:
fmt.Fprintf(stderr, "archie-state-store: unknown command %q\n\n", command)
fmt.Fprint(stderr, recoveryUsage)
@@ -71,10 +67,6 @@ func runRecovery(args []string, stdout, stderr io.Writer) int {
flags.StringVar(&options.From, "from", "", "snapshot file restore reads")
flags.StringVar(&options.Kind, "kind", "", "control-plane resource kind rollback replays")
flags.Int64Var(&options.Revision, "revision", 0, "revision rollback replays (default: the newest one older than the current value)")
if command == archied.RecoveryImport {
flags.StringVar(&options.DBPath, "db-path", "", "configured db_path the legacy files are named from (default: the configuration's)")
flags.StringVar(&options.DatabaseURL, "database-url", "", "Postgres URL to import into (default: the configuration's database_url)")
}
// The configuration names the PostgreSQL database, and validate also checks
// the stored settings against it.
flags.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory the daemon boots with")
+1 -1
View File
@@ -145,7 +145,7 @@ func TestRecoveryValidateAcceptsAnUnseededDatabase(t *testing.T) {
// path in the same binary exits 0 for the same request, so a script probing the
// recovery surface must not read a requested help as a failure.
func TestRecoveryHelpExitsZero(t *testing.T) {
commands := []string{archied.RecoveryBackup, archied.RecoveryRestore, archied.RecoveryValidate, archied.RecoveryRollback, archied.RecoveryImport}
commands := []string{archied.RecoveryBackup, archied.RecoveryRestore, archied.RecoveryValidate, archied.RecoveryRollback}
for _, command := range commands {
code, _, stderr := runRecoveryCmd(t, command, "-h")
if code != 0 {
-1
View File
@@ -30,7 +30,6 @@ var deletionGate = []bannedCategory{
"modernc.org/sqlite",
"github.com/jackc/pgx",
modulePath + "internal/infrastructure/postgres",
modulePath + "internal/infrastructure/legacyread",
}},
{"daemon runtime", []string{
modulePath + "internal/daemon",
+1 -2
View File
@@ -224,7 +224,6 @@ func writeUIConfig(t *testing.T, dir, stateTarget, gatewayTarget string) string
t.Helper()
path := filepath.Join(dir, "config.toml")
content := fmt.Sprintf(`bot_user = "archie-bot"
db_path = %q
[forge]
type = "github"
host = "https://github.example.com"
@@ -236,7 +235,7 @@ name = "widget"
target = %q
[services.gateway]
target = %q
`, filepath.Join(dir, "archie.db"), stateTarget, gatewayTarget)
`, stateTarget, gatewayTarget)
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatalf("write ui config: %v", err)
}
+2 -4
View File
@@ -14,13 +14,11 @@
# work_dir = "~/.local/share/archie/work" # default
# state_dir = "~/.local/share/archie" # default; embedded NATS store, task logs, disk probe
# db_path = "~/.local/share/archie/archie.db" # default; locates pre-PostgreSQL SQLite files for the import only
# The PostgreSQL connection archie-state-store, archied and archie-gateway
# serve from. Required: each fails closed without it.
# An install with SQLite stores under db_path runs `archie-state-store import`
# once, with archie stopped, before it starts. `docker compose up -d postgres` starts
# a matching local postgres:18 with this default URL.
# `docker compose up -d postgres` starts a matching local postgres:18 with this
# default URL.
# database_url = "postgres://archie:archie@127.0.0.1:5432/archie?sslmode=disable"
# skills_dir = "~/.local/share/archie/skills" # SKILL.md search path; defaults under work_dir when unset
-2
View File
@@ -16,8 +16,6 @@ bot_user = "archie"
diff_cap_lines = 0
work_dir = "~/.local/share/archie/work"
state_dir = "~/.local/share/archie" # NATS store, task logs
# db_path (default ~/.local/share/archie/archie.db) only locates pre-PostgreSQL
# files for `archie-state-store import`.
# The State Store's PostgreSQL connection (required; Postgres-only epic).
# `docker compose up -d postgres` provides this local default; point it at
# your own Postgres 18 server otherwise.
-2
View File
@@ -7,8 +7,6 @@
work_dir = "~/.local/share/archie/work"
state_dir = "~/.local/share/archie" # NATS store, task logs
# db_path (default ~/.local/share/archie/archie.db) only locates pre-PostgreSQL
# files for `archie-state-store import`.
# The State Store's PostgreSQL connection (required; Postgres-only epic).
# `docker compose up -d postgres` provides this local default; point it at
# your own Postgres 18 server otherwise.
@@ -8,8 +8,6 @@
work_dir = "~/.local/share/archie/work"
state_dir = "~/.local/share/archie" # NATS store, task logs
# db_path (default ~/.local/share/archie/archie.db) only locates pre-PostgreSQL
# files for `archie-state-store import`.
# The State Store's PostgreSQL connection (required; Postgres-only epic).
# `docker compose up -d postgres` provides this local default; point it at
# your own Postgres 18 server otherwise.
-2
View File
@@ -7,8 +7,6 @@
work_dir = "~/.local/share/archie/work"
state_dir = "~/.local/share/archie" # NATS store, task logs
# db_path (default ~/.local/share/archie/archie.db) only locates pre-PostgreSQL
# files for `archie-state-store import`.
# The State Store's PostgreSQL connection (required; Postgres-only epic).
# `docker compose up -d postgres` provides this local default; point it at
# your own Postgres 18 server otherwise.
+1 -2
View File
@@ -254,5 +254,4 @@ docker compose pull agent
```
`state_dir` and other paths are native host paths. Point `state_dir` at the
intended state directory (embedded NATS store, task logs); `db_path` only
locates pre-PostgreSQL files for `archie-state-store import`.
intended state directory (embedded NATS store, task logs).
+1 -1
View File
@@ -141,7 +141,7 @@ existing structure combines different owners.
| Current values | Current location | Target owner and requirement |
| ----------------------------------------------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WorkDir`, `StateDir`, `DBPath` | root `Config` | Workspace/storage infrastructure settings, bootstrap-only. `StateDir` holds the embedded NATS store and endpoint file, task logs and the readiness disk target. `DBPath` only locates the legacy SQLite files (`<db_path>-tasks.sqlite`, `-eda.sqlite`, `-conversations.sqlite`) for `archie-state-store import` and the boot gate that refuses to serve until it has run; it goes when the importer does. Defaults derive from the platform data directory. |
| `WorkDir`, `StateDir` | root `Config` | Workspace/storage infrastructure settings, bootstrap-only. `StateDir` holds the embedded NATS store and endpoint file, task logs and the readiness disk target. Defaults derive from the platform data directory. |
| `SkillsDir`, `PluginDir` | root `Config` | Skill and plugin infrastructure settings, independently typed. |
| `PollInterval` | root `Config` | Work-intake scheduling setting; not a daemon-wide constant. |
| `Label`, `BotUser`, `BotEmail` | root `Config` | Identity and dispatch associations. `BotEmail` may be derived from the selected forge account but remains overrideable. |
+2 -2
View File
@@ -223,8 +223,8 @@ pass today. `cmd/archie-messaging/architecture_test.go` does not exist, and the
check that section specifies -- `go list -deps ./cmd/archie-messaging` links
zero banned runtime packages -- reported four at the time (the task store was
then `internal/store` over `modernc.org/sqlite`; the gate now bans
`modernc.org/sqlite`, `github.com/jackc/pgx`, `internal/infrastructure/postgres`
and `internal/infrastructure/legacyread` in its place):
`modernc.org/sqlite`, `github.com/jackc/pgx` and
`internal/infrastructure/postgres` in its place):
| banned package | PRD category |
| --- | --- |
+4 -24
View File
@@ -121,31 +121,11 @@ file values would restore the second source of truth the control plane exists to
remove. The cost is that a bad stored value stops the daemon starting, and the
value can only be corrected through the daemon's own API.
### Upgrading an install from SQLite
### Serving from Postgres
The State Store, the daemon and the Gateway serve from `database_url` only. An
install that still holds the SQLite stores (`<db_path>-tasks.sqlite`,
`<db_path>-eda.sqlite`, `<db_path>-conversations.sqlite`) upgrades in three
steps:
1. Stop every archie process.
2. Run `archie-state-store import`. It moves all three stores into Postgres in
one transaction, verifies the rows, and records completion. The SQLite files
are read, never written.
3. Start archie.
`db_path` exists only to locate these files for the import and the boot gate
below, and goes with the importer. The embedded NATS store, its endpoint file
and task logs live under `state_dir` (default: the data home's `archie`
directory). An install whose `db_path` sat outside the data home sets
`state_dir` to that directory to keep them where they were.
Each serving process checks this at boot, after migrating the schema. With no
completion record and a non-empty legacy file it refuses to start and names the
files and the import command, rather than serve empty tables over existing
data. There is no override. With no legacy data it is a fresh install: it writes
the completion record itself, so a legacy file that appears later is ignored.
A database that recorded a fresh start refuses a later import.
The State Store, the daemon and the Gateway serve from `database_url` only; an
empty value is a startup error. The embedded NATS store, its endpoint file and
task logs live under `state_dir` (default: the data home's `archie` directory).
The Gateway holds a Postgres serve-ownership claim for its whole life, so a
second Gateway against the same database refuses to start (its turn recovery
+4 -4
View File
@@ -28,7 +28,7 @@
"url": "/dev/architecture/configuration/",
"title": "Configuration",
"section": "Architecture",
"body": "# Configuration\n\n**Status:** Approved; existing-type assignment is ongoing \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Ownership\n\nConfiguration has two separate responsibilities:\n\n1. `internal/infrastructure/configuration` loads files, environment variables,\n secret references, overlays, and compatibility representations.\n2. Each domain and plugin owns the typed runtime settings required for its\n behaviour.\n\n`internal/app` translates external input into those settings, validates\ncross-capability combinations, and supplies each component only its own\nsettings.\n\nThe following are prohibited:\n\n- passing complete application configuration into a domain;\n- making a domain depend on TOML, YAML, environment-variable names, secret\n references, or a configuration library;\n- defining a central runtime configuration type imported across the system;\n- placing plugin options in an unrelated global configuration model.\n\n## Private input document\n\n`internal/infrastructure/configuration` MAY use a complete decoded document\nwhile discovering files, decoding sections, and applying overlays. It is an\ninput-boundary DTO only.\n\nThe document:\n\n- remains private to the configuration infrastructure;\n- is composed from separately defined feature sections;\n- is immediately translated by application composition;\n- is never returned as the application's runtime model;\n- is never passed through runtime components.\n\nExternal DTOs and domain runtime settings are separate types.\n\nPlugins supply external configuration definitions through a narrow extension\ncontract. The core loader MUST NOT gain a field or recognized filename for every\nplugin.\n\nInvalid configuration input MUST NOT replace active valid settings or terminate\nunaffected capabilities. Configuration changes use the candidate validation,\npromotion, audit, and recovery requirements in\n[safe-change-and-recovery.md](/dev/architecture/safe-change-and-recovery/).\n\n## Dissolution of `internal/config`\n\n`internal/config` has no target location. It MUST be dissolved and MUST NOT\nsurvive as a shared package, configuration domain, or renamed global model.\n\nIts loading behaviour moves to `internal/infrastructure/configuration`. Existing\ntypes and methods are reassigned by behaviour. Repository execution policy,\ndispatch policy, retry policy, ecosystem defaults, tool policy, memory settings,\nprovider settings, and channel settings move to their\nrespective owners.\n\n## Repository settings\n\nThe existing `config.Repo` MUST NOT move intact into a repository domain or\nshared settings package. A managed repository is an application association:\n\n- work intake owns which repository references an identity monitors;\n- task execution owns gates, preflight, test protection, ecosystem behaviour,\n and change limits;\n- task lifecycle owns retry behaviour;\n- scheduling owns concurrency policy;\n- workspace management owns base branch and persistent-storage requirements.\n\nApplication composition correlates these settings by repository reference. No\ndomain receives a universal repository profile.\n\n## Documentation\n\nGenerated configuration reference describes external sections and their owning\ncapabilities. It MUST NOT establish a global Go configuration structure as the\npublic contract.\n\n## Value classification rule\n\nEvery value that controls behaviour MUST have an explicit owner and MUST be\nclassified as exactly one of:\n\n1. **Invariant** — changing it changes the meaning of the program, a wire\n protocol, or a domain concept. It may be a Go constant.\n2. **Runtime setting** — an operator, identity, domain, plugin, or deployment\n may legitimately choose a different value. It is typed configuration owned by\n the affected capability.\n3. **Policy value** — it expresses what is allowed, limited, routed, retried,\n protected, or gated. Its typed definition belongs to the owning domain and it\n is evaluated through the policy system.\n4. **Derived value** — it is computed from other settings and is not\n independently mutable.\n5. **Runtime state** — it changes as the application operates, such as the\n active model for a conversation. It is changed by a domain command and is not\n configuration merely because it can be changed.\n\nAn unclassified behavioural literal is a defect.\n\n`const` MUST NOT be used merely because a value currently has one default.\nConstants are reserved for actual invariants: enum discriminants, protocol\nversions, fixed compatibility tokens, and values whose alteration would change\nthe program's semantics rather than configure an installation.\n\nIn Go, a constant is a compile-time value and does not represent mutable runtime\nstorage. It generally has no address that can be observed or changed.\nArchitecturally, a constant therefore asserts that the value cannot change for\nthe lifetiLine truncated
"body": "# Configuration\n\n**Status:** Approved; existing-type assignment is ongoing \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Ownership\n\nConfiguration has two separate responsibilities:\n\n1. `internal/infrastructure/configuration` loads files, environment variables,\n secret references, overlays, and compatibility representations.\n2. Each domain and plugin owns the typed runtime settings required for its\n behaviour.\n\n`internal/app` translates external input into those settings, validates\ncross-capability combinations, and supplies each component only its own\nsettings.\n\nThe following are prohibited:\n\n- passing complete application configuration into a domain;\n- making a domain depend on TOML, YAML, environment-variable names, secret\n references, or a configuration library;\n- defining a central runtime configuration type imported across the system;\n- placing plugin options in an unrelated global configuration model.\n\n## Private input document\n\n`internal/infrastructure/configuration` MAY use a complete decoded document\nwhile discovering files, decoding sections, and applying overlays. It is an\ninput-boundary DTO only.\n\nThe document:\n\n- remains private to the configuration infrastructure;\n- is composed from separately defined feature sections;\n- is immediately translated by application composition;\n- is never returned as the application's runtime model;\n- is never passed through runtime components.\n\nExternal DTOs and domain runtime settings are separate types.\n\nPlugins supply external configuration definitions through a narrow extension\ncontract. The core loader MUST NOT gain a field or recognized filename for every\nplugin.\n\nInvalid configuration input MUST NOT replace active valid settings or terminate\nunaffected capabilities. Configuration changes use the candidate validation,\npromotion, audit, and recovery requirements in\n[safe-change-and-recovery.md](/dev/architecture/safe-change-and-recovery/).\n\n## Dissolution of `internal/config`\n\n`internal/config` has no target location. It MUST be dissolved and MUST NOT\nsurvive as a shared package, configuration domain, or renamed global model.\n\nIts loading behaviour moves to `internal/infrastructure/configuration`. Existing\ntypes and methods are reassigned by behaviour. Repository execution policy,\ndispatch policy, retry policy, ecosystem defaults, tool policy, memory settings,\nprovider settings, and channel settings move to their\nrespective owners.\n\n## Repository settings\n\nThe existing `config.Repo` MUST NOT move intact into a repository domain or\nshared settings package. A managed repository is an application association:\n\n- work intake owns which repository references an identity monitors;\n- task execution owns gates, preflight, test protection, ecosystem behaviour,\n and change limits;\n- task lifecycle owns retry behaviour;\n- scheduling owns concurrency policy;\n- workspace management owns base branch and persistent-storage requirements.\n\nApplication composition correlates these settings by repository reference. No\ndomain receives a universal repository profile.\n\n## Documentation\n\nGenerated configuration reference describes external sections and their owning\ncapabilities. It MUST NOT establish a global Go configuration structure as the\npublic contract.\n\n## Value classification rule\n\nEvery value that controls behaviour MUST have an explicit owner and MUST be\nclassified as exactly one of:\n\n1. **Invariant** — changing it changes the meaning of the program, a wire\n protocol, or a domain concept. It may be a Go constant.\n2. **Runtime setting** — an operator, identity, domain, plugin, or deployment\n may legitimately choose a different value. It is typed configuration owned by\n the affected capability.\n3. **Policy value** — it expresses what is allowed, limited, routed, retried,\n protected, or gated. Its typed definition belongs to the owning domain and it\n is evaluated through the policy system.\n4. **Derived value** — it is computed from other settings and is not\n independently mutable.\n5. **Runtime state** — it changes as the application operates, such as the\n active model for a conversation. It is changed by a domain command and is not\n configuration merely because it can be changed.\n\nAn unclassified behavioural literal is a defect.\n\n`const` MUST NOT be used merely because a value currently has one default.\nConstants are reserved for actual invariants: enum discriminants, protocol\nversions, fixed compatibility tokens, and values whose alteration would change\nthe program's semantics rather than configure an installation.\n\nIn Go, a constant is a compile-time value and does not represent mutable runtime\nstorage. It generally has no address that can be observed or changed.\nArchitecturally, a constant therefore asserts that the value cannot change for\nthe lifetiLine truncated
},
{
"url": "/dev/architecture/dashboard-agent-tools/",
@@ -64,7 +64,7 @@
"url": "/dev/architecture/migration-decisions/",
"title": "Architecture Migration Decisions",
"section": "Architecture",
"body": "# Architecture Migration Decisions\n\n**Status:** Active migration inventory \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nThis document records what remains to be decided before Archie's current\nimplementation can be migrated into the approved domain-oriented structure.\n\nThe product and core domain model are not being redesigned. Existing Archie\nbehaviour and the existing session implementation are the migration\nbaseline. Remaining decisions MUST be grounded in current packages, consumers,\ntests, persistence, and runtime wiring.\n\n## Confirmed domain packages\n\n```text\ninternal/domain/\n identity/ (approved, not yet materialised as a package)\n agent/ (approved, not yet materialised as a package)\n workflow/\n messaging/ (canonical Message/Conversation types only; gateway migration pending, see section 2)\n workintake/\n plugin/ (approved, not yet materialised as a package)\n curator/\n mapping/\n scheduling/\n```\n\n- `identity` owns persistent actors, lifecycle, ownership, attribution, and\n audit identity.\n- `agent` owns persistent assistants, specialisation, instructions,\n model-independent continuity, capability context, and associations with\n identity and memory.\n- `workflow` is a separate domain. It owns reusable, versioned Workflow\n definitions, WorkflowSteps, WorkflowExecutions, StepExecutions, Attempts,\n outcomes, and typed Workflow plugin contracts.\n- `messaging` owns canonical Messages, Conversations, branches, channel and\n source correlation, replies, acknowledgements, delivery attempts, events, and\n projections.\n- `workintake` owns admission, validation, deterministic routing, and accepted\n work requests for the optional transition into durable workflow-backed\n execution.\n- `plugin` owns generic plugin identity, discovery, compatibility, and lifecycle\n mechanics. It remains metadata-only; capability semantics and typed\n registration belong to the owning domain.\n- `curator` owns the curator engine family: long-running agent loops that\n reason over memory and perform maintenance tasks on a declared shape\n (check-in interval, tool set, attached memory engine). See epic\n archie-core-yp9.\n- `mapping` owns the payload field-mapping vocabulary: binding named fields to\n JSON paths inside a captured webhook payload, and detecting drift. See\n `docs/prds/payload-field-mapping.md`.\n- `scheduling` owns the ticker engine: deciding when a scheduled job runs and\n with what concurrency. It declares `JobSource`/`Runner` contracts and owns\n no storage or delivery. See epic archie-core-1786637496320-249-be6d9a20.\n\n**Reconciliation (2026-08-31):** `curator`, `mapping`, and `scheduling` existed\nin the tree without being added to this list when their epics landed. They are\nconfirmed as legitimate, narrowly-scoped domains under the same rules as the\noriginal six — each owns one capability family, declares typed contracts, and\nhas no cross-domain reach. This list was out of date, not the tree.\n\nConversely, `identity`, `agent`, `messaging`, and `plugin` are approved target\ndomains that do not yet exist as packages. Their behaviour currently lives in\npre-migration packages (see \"Complete package destination map\" below for the\nfull inventory). Do **not** create empty stub packages for them ahead of an\nactual migration PR — an unused stub is dead code and gives no test coverage.\nEach materialises when its corresponding migration decision below is resolved\nand implemented in the same change.\n\nMemory's final package placement remains undecided pending focused review of the\nexisting implementation.\n\nThe following are approved shared or composition packages, not domains:\n\n```text\ninternal/eventbus/\ninternal/policy/\ninternal/infrastructure/\ninternal/app/archied/\ninternal/app/agentworker/\n```\n\n## Remaining migration decisions\n\n### 1. Complete package destination map\n\nEvery current package MUST receive one explicit disposition:\n\n- move into a confirmed domain;\n- move under infrastructure as an implementation of a domain-owned contract;\n- move into application composition;\n- merge with an identified duplicate;\n- remain as an approved shared application contract;\n- move to a plugin, extra, deployment, example, or generated artifact;\n- be deleted after its replacement is proven.\n\nThe largest unreviewed areas include memory, tools and capabilities, workspace\nand worktree behaviour, gates, storage, events, web UI, containers, RPC\npackages, release management, and scheduling.\n\nThe destination matrix MUST name the behaviour owner, target path, dependencies\nto remove, state and contracts to preserve, migration prerequisites, and\ndeletion criteria.\n\n**`internal/webui` / UI Service — RATIFIED Phase 3 disposition (2026-09-07).**\nThe current owner is the in-process HTTP/SSE dashboard: SPA hosting, operator\nauthLine truncated
"body": "# Architecture Migration Decisions\n\n**Status:** Active migration inventory \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nThis document records what remains to be decided before Archie's current\nimplementation can be migrated into the approved domain-oriented structure.\n\nThe product and core domain model are not being redesigned. Existing Archie\nbehaviour and the existing session implementation are the migration\nbaseline. Remaining decisions MUST be grounded in current packages, consumers,\ntests, persistence, and runtime wiring.\n\n## Confirmed domain packages\n\n```text\ninternal/domain/\n identity/ (approved, not yet materialised as a package)\n agent/ (approved, not yet materialised as a package)\n workflow/\n messaging/ (canonical Message/Conversation types only; gateway migration pending, see section 2)\n workintake/\n plugin/ (approved, not yet materialised as a package)\n curator/\n mapping/\n scheduling/\n```\n\n- `identity` owns persistent actors, lifecycle, ownership, attribution, and\n audit identity.\n- `agent` owns persistent assistants, specialisation, instructions,\n model-independent continuity, capability context, and associations with\n identity and memory.\n- `workflow` is a separate domain. It owns reusable, versioned Workflow\n definitions, WorkflowSteps, WorkflowExecutions, StepExecutions, Attempts,\n outcomes, and typed Workflow plugin contracts.\n- `messaging` owns canonical Messages, Conversations, branches, channel and\n source correlation, replies, acknowledgements, delivery attempts, events, and\n projections.\n- `workintake` owns admission, validation, deterministic routing, and accepted\n work requests for the optional transition into durable workflow-backed\n execution.\n- `plugin` owns generic plugin identity, discovery, compatibility, and lifecycle\n mechanics. It remains metadata-only; capability semantics and typed\n registration belong to the owning domain.\n- `curator` owns the curator engine family: long-running agent loops that\n reason over memory and perform maintenance tasks on a declared shape\n (check-in interval, tool set, attached memory engine). See epic\n archie-core-yp9.\n- `mapping` owns the payload field-mapping vocabulary: binding named fields to\n JSON paths inside a captured webhook payload, and detecting drift. See\n `docs/prds/payload-field-mapping.md`.\n- `scheduling` owns the ticker engine: deciding when a scheduled job runs and\n with what concurrency. It declares `JobSource`/`Runner` contracts and owns\n no storage or delivery. See epic archie-core-1786637496320-249-be6d9a20.\n\n**Reconciliation (2026-08-31):** `curator`, `mapping`, and `scheduling` existed\nin the tree without being added to this list when their epics landed. They are\nconfirmed as legitimate, narrowly-scoped domains under the same rules as the\noriginal six — each owns one capability family, declares typed contracts, and\nhas no cross-domain reach. This list was out of date, not the tree.\n\nConversely, `identity`, `agent`, `messaging`, and `plugin` are approved target\ndomains that do not yet exist as packages. Their behaviour currently lives in\npre-migration packages (see \"Complete package destination map\" below for the\nfull inventory). Do **not** create empty stub packages for them ahead of an\nactual migration PR — an unused stub is dead code and gives no test coverage.\nEach materialises when its corresponding migration decision below is resolved\nand implemented in the same change.\n\nMemory's final package placement remains undecided pending focused review of the\nexisting implementation.\n\nThe following are approved shared or composition packages, not domains:\n\n```text\ninternal/eventbus/\ninternal/policy/\ninternal/infrastructure/\ninternal/app/archied/\ninternal/app/agentworker/\n```\n\n## Remaining migration decisions\n\n### 1. Complete package destination map\n\nEvery current package MUST receive one explicit disposition:\n\n- move into a confirmed domain;\n- move under infrastructure as an implementation of a domain-owned contract;\n- move into application composition;\n- merge with an identified duplicate;\n- remain as an approved shared application contract;\n- move to a plugin, extra, deployment, example, or generated artifact;\n- be deleted after its replacement is proven.\n\nThe largest unreviewed areas include memory, tools and capabilities, workspace\nand worktree behaviour, gates, storage, events, web UI, containers, RPC\npackages, release management, and scheduling.\n\nThe destination matrix MUST name the behaviour owner, target path, dependencies\nto remove, state and contracts to preserve, migration prerequisites, and\ndeletion criteria.\n\n**`internal/webui` / UI Service — RATIFIED Phase 3 disposition (2026-09-07).**\nThe current owner is the in-process HTTP/SSE dashboard: SPA hosting, operator\nauthLine truncated
},
{
"url": "/dev/architecture/observability/",
@@ -100,7 +100,7 @@
"url": "/dev/architecture/safe-change-and-recovery/",
"title": "Safe Change and Recovery",
"section": "Architecture",
"body": "# Safe Change and Recovery\n\n**Status:** Requirements approved; mechanics are under design. Database-backed settings are implemented through the control plane (2026-09): see the degrade/recovery section below, which records a gap rather than a solution. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design.\n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie is built and improved by agents as well as humans. The architecture MUST\nmake a change easy to locate, understand, test, audit, extend, and reverse\nwithout requiring its author to understand unrelated parts of the application.\n\nSeparation of concerns is therefore an operational safety boundary, not only a\ncode-organisation preference.\n\n## Required outcomes\n\n- An agent can improve a focused feature without receiving authority over\n unrelated domains.\n- Every event, function, action, setting, and policy has an identifiable owner\n and provenance.\n- Source and runtime changes pass deterministic checks outside the actor making\n the change.\n- A rejected or unhealthy candidate cannot replace the last known working\n version.\n- Invalid user configuration does not terminate an otherwise healthy\n application.\n- Configuration and service failures are observable, attributed, and eligible\n for bounded remediation or rollback.\n- The application continues serving unaffected capabilities when one\n capability is misconfigured or unhealthy.\n- Recovery failure is reported and contained rather than hidden in an\n unbounded retry loop.\n\n## Source changes\n\nAgent-authored source changes occur through the task-execution boundary in an\nisolated workspace. The agent does not directly mutate the running\ninstallation.\n\nPromotion is controlled by deterministic repository-owned policy, including\ntests, generated-reference drift checks, protected paths, change scope, and\nother required gates. The actor proposing a change cannot waive these checks.\n\nRepository and domain separation SHOULD allow a task to load and modify only\nthe governing requirements and code for its declared scope.\n\n## Runtime changes\n\nConfiguration and other runtime changes are proposed as candidates rather than\nmutating the active state in place.\n\nThe affected domain owns:\n\n- the command describing the semantic change;\n- validation of its typed settings;\n- health signals that demonstrate correct operation;\n- domain-specific remediation and rollback consequences.\n\nShared policy supplies consistent evaluation, evidence, and audit mechanics.\nIdentity supplies actor attribution. Infrastructure supplies external\nconfiguration storage, service control, and other operational adapters.\n\n## Runtime change protocol\n\nLast-known-good preservation and candidate promotion are the universal runtime\nchange protocol.\n\n1. An identity proposes an immutable candidate version.\n2. Infrastructure parses it without changing active state.\n3. Each affected domain validates its typed settings.\n4. Shared policy evaluates cross-cutting constraints.\n5. Each affected capability prepares the candidate without destroying its\n active instance.\n6. Capability-specific health checks prove the candidate works.\n7. Runtime supervision atomically promotes the candidate.\n8. A bounded observation period watches for delayed failure.\n9. Failure restores the last-known-good version and records the reason,\n evidence, actor, and involved versions.\n10. Repeated remediation failure stops retrying, isolates the capability, and\n reports the fault.\n\nThe affected domain owns the semantic change command, typed validation, health\nsignals, and remediation consequences. Shared runtime supervision owns the\npromotion transaction. Infrastructure performs storage and service-control\noperations.\n\nThe protocol's exact Go contracts, storage model, atomicity boundary, and\nobservation rules require a focused runtime-supervision design pass.\n\n## Failure isolation\n\nInvalid input MUST leave the active valid configuration unchanged and produce a\ndiagnostic record.\n\nA capability that cannot start or reload SHOULD fail independently where its\nabsence does not violate a declared application invariant. Unaffected\ncapabilities continue operating.\n\nRemediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT\nsilently oscillate between versions or retry forever.\n\n## Database settings: degrade paths and recovery (2026-09)\n\nThe control plane owns runtime-tunable settings and stores them in the State\nStore's PostgreSQL database.\nThis replaced a dashboard overlay store that degraded to file config on any\nfailure and had three documented ways back. The replacement has none, and the\nposture is the opposite: **the daemon fails closed.**\n\n### Degrade paths\n\n| Failure | Boot behaviour | Where the operator sees it |\n| --- | -Line truncated
"body": "# Safe Change and Recovery\n\n**Status:** Requirements approved; mechanics are under design. Database-backed settings are implemented through the control plane (2026-09): see the degrade/recovery section below, which records a gap rather than a solution. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design.\n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie is built and improved by agents as well as humans. The architecture MUST\nmake a change easy to locate, understand, test, audit, extend, and reverse\nwithout requiring its author to understand unrelated parts of the application.\n\nSeparation of concerns is therefore an operational safety boundary, not only a\ncode-organisation preference.\n\n## Required outcomes\n\n- An agent can improve a focused feature without receiving authority over\n unrelated domains.\n- Every event, function, action, setting, and policy has an identifiable owner\n and provenance.\n- Source and runtime changes pass deterministic checks outside the actor making\n the change.\n- A rejected or unhealthy candidate cannot replace the last known working\n version.\n- Invalid user configuration does not terminate an otherwise healthy\n application.\n- Configuration and service failures are observable, attributed, and eligible\n for bounded remediation or rollback.\n- The application continues serving unaffected capabilities when one\n capability is misconfigured or unhealthy.\n- Recovery failure is reported and contained rather than hidden in an\n unbounded retry loop.\n\n## Source changes\n\nAgent-authored source changes occur through the task-execution boundary in an\nisolated workspace. The agent does not directly mutate the running\ninstallation.\n\nPromotion is controlled by deterministic repository-owned policy, including\ntests, generated-reference drift checks, protected paths, change scope, and\nother required gates. The actor proposing a change cannot waive these checks.\n\nRepository and domain separation SHOULD allow a task to load and modify only\nthe governing requirements and code for its declared scope.\n\n## Runtime changes\n\nConfiguration and other runtime changes are proposed as candidates rather than\nmutating the active state in place.\n\nThe affected domain owns:\n\n- the command describing the semantic change;\n- validation of its typed settings;\n- health signals that demonstrate correct operation;\n- domain-specific remediation and rollback consequences.\n\nShared policy supplies consistent evaluation, evidence, and audit mechanics.\nIdentity supplies actor attribution. Infrastructure supplies external\nconfiguration storage, service control, and other operational adapters.\n\n## Runtime change protocol\n\nLast-known-good preservation and candidate promotion are the universal runtime\nchange protocol.\n\n1. An identity proposes an immutable candidate version.\n2. Infrastructure parses it without changing active state.\n3. Each affected domain validates its typed settings.\n4. Shared policy evaluates cross-cutting constraints.\n5. Each affected capability prepares the candidate without destroying its\n active instance.\n6. Capability-specific health checks prove the candidate works.\n7. Runtime supervision atomically promotes the candidate.\n8. A bounded observation period watches for delayed failure.\n9. Failure restores the last-known-good version and records the reason,\n evidence, actor, and involved versions.\n10. Repeated remediation failure stops retrying, isolates the capability, and\n reports the fault.\n\nThe affected domain owns the semantic change command, typed validation, health\nsignals, and remediation consequences. Shared runtime supervision owns the\npromotion transaction. Infrastructure performs storage and service-control\noperations.\n\nThe protocol's exact Go contracts, storage model, atomicity boundary, and\nobservation rules require a focused runtime-supervision design pass.\n\n## Failure isolation\n\nInvalid input MUST leave the active valid configuration unchanged and produce a\ndiagnostic record.\n\nA capability that cannot start or reload SHOULD fail independently where its\nabsence does not violate a declared application invariant. Unaffected\ncapabilities continue operating.\n\nRemediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT\nsilently oscillate between versions or retry forever.\n\n## Database settings: degrade paths and recovery (2026-09)\n\nThe control plane owns runtime-tunable settings and stores them in the State\nStore's PostgreSQL database.\nThis replaced a dashboard overlay store that degraded to file config on any\nfailure and had three documented ways back. The replacement has none, and the\nposture is the opposite: **the daemon fails closed.**\n\n### Degrade paths\n\n| Failure | Boot behaviour | Where the operator sees it |\n| --- | -Line truncated
},
{
"url": "/dev/development/",
@@ -142,7 +142,7 @@
"url": "/dev/development/state-store/",
"title": "State Store",
"section": "Development",
"body": "# State Store\n\nAuthority: `docs/prds/state-store-contract.md` and the State Store section of\n`CLAUDE.md`. All persistence is PostgreSQL behind the standalone State Store\nprocess; nothing else opens the database.\n\n## Adding a column\n\n1. Write the next migration in `internal/infrastructure/postgres/migrations/`\n (`00NN_name.sql`, goose Up and Down). Give the column a `NOT NULL DEFAULT`\n that is correct for existing rows.\n2. Update the queries in `internal/infrastructure/postgres/queries/` and\n regenerate with sqlc. A query that lists columns (`ListTaskSummaries`, the\n binding selects) does not pick the new one up; `SELECT *` queries do.\n3. Map it in the store (`taskFromRow`, `bindingValue` and friends). If the\n column holds encoded data, the package that owns the type owns the encoding\n (`task.EncodeInputs`), and the store and the wire both use it.\n4. Add the column to `newColumns` in\n `internal/infrastructure/legacyimport/load.go` if legacy data has no value\n for it. The importer refuses a target column it cannot fill otherwise.\n5. Carry it over the wire (next section) if any process other than the State\n Store reads it.\n\n## Adding a field to a wire message\n\n1. Add it to `proto/state/v1/state.proto` with a new field number. Never reuse\n a number; retire one with `deprecated = true`.\n2. `task proto:generate`, then map it both ways in\n `internal/infrastructure/staterpc/values.go`.\n3. `TestTaskProtoCarriesEveryDomainField` fills every `task.Task` field and\n fails on one the mapping forgets. If it cannot fill the field's kind, extend\n it. Other messages have no such test, so add a round trip to\n `conformance_test.go`.\n\n## Adding an RPC or a store method\n\n1. Put the Go method on the narrow consumer interface in\n `internal/domain/storecontract` (keep each at eight methods or fewer) and add\n the matching RPC. A Go method without an RPC does not cross the process.\n2. Implement it in the Postgres store, in `staterpc.Client` (with its `var _`\n assertion) and in `staterpc.server`. A missing dependency answers\n `codes.Unavailable`, never a fabricated default.\n3. Wire the dependency in every composition that serves or consumes it:\n `stateStoreDeps` in `internal/app/archied/state_store.go`, the daemon's\n assertions in `bootstrap.go`, and `internal/app/archieui/compose.go` for the\n dashboard process.\n4. Task-scoped tokens may call only `Update`, `Transition` and `InsertEvent` on\n their own task (`staterpc.TaskGrants`). A new RPC is admin-only unless it is\n added there deliberately.\n5. Add it to `conformance_test.go`, which runs every surface over a real gRPC\n connection.\n\n## Adding an error sentinel\n\nAdd the sentinel to `storecontract`, a row to `wireErrors` in `values.go`, and\na case to `error_test.go`. The canonical message is part of the wire contract:\nchanging it breaks `errors.Is` on the client silently.\n"
"body": "# State Store\n\nAuthority: `docs/prds/state-store-contract.md` and the State Store section of\n`CLAUDE.md`. All persistence is PostgreSQL behind the standalone State Store\nprocess; nothing else opens the database.\n\n## Adding a column\n\n1. Write the next migration in `internal/infrastructure/postgres/migrations/`\n (`00NN_name.sql`, goose Up and Down). Give the column a `NOT NULL DEFAULT`\n that is correct for existing rows.\n2. Update the queries in `internal/infrastructure/postgres/queries/` and\n regenerate with sqlc. A query that lists columns (`ListTaskSummaries`, the\n binding selects) does not pick the new one up; `SELECT *` queries do.\n3. Map it in the store (`taskFromRow`, `bindingValue` and friends). If the\n column holds encoded data, the package that owns the type owns the encoding\n (`task.EncodeInputs`), and the store and the wire both use it.\n4. Carry it over the wire (next section) if any process other than the State\n Store reads it.\n\n## Adding a field to a wire message\n\n1. Add it to `proto/state/v1/state.proto` with a new field number. Never reuse\n a number; retire one with `deprecated = true`.\n2. `task proto:generate`, then map it both ways in\n `internal/infrastructure/staterpc/values.go`.\n3. `TestTaskProtoCarriesEveryDomainField` fills every `task.Task` field and\n fails on one the mapping forgets. If it cannot fill the field's kind, extend\n it. Other messages have no such test, so add a round trip to\n `conformance_test.go`.\n\n## Adding an RPC or a store method\n\n1. Put the Go method on the narrow consumer interface in\n `internal/domain/storecontract` (keep each at eight methods or fewer) and add\n the matching RPC. A Go method without an RPC does not cross the process.\n2. Implement it in the Postgres store, in `staterpc.Client` (with its `var _`\n assertion) and in `staterpc.server`. A missing dependency answers\n `codes.Unavailable`, never a fabricated default.\n3. Wire the dependency in every composition that serves or consumes it:\n `stateStoreDeps` in `internal/app/archied/state_store.go`, the daemon's\n assertions in `bootstrap.go`, and `internal/app/archieui/compose.go` for the\n dashboard process.\n4. Task-scoped tokens may call only `Update`, `Transition` and `InsertEvent` on\n their own task (`staterpc.TaskGrants`). A new RPC is admin-only unless it is\n added there deliberately.\n5. Add it to `conformance_test.go`, which runs every surface over a real gRPC\n connection.\n\n## Adding an error sentinel\n\nAdd the sentinel to `storecontract`, a row to `wireErrors` in `values.go`, and\na case to `error_test.go`. The canonical message is part of the wire contract:\nchanging it breaks `errors.Is` on the client silently.\n"
},
{
"url": "/dev/development/wiring/",
+1 -4
View File
@@ -15,10 +15,7 @@ process; nothing else opens the database.
3. Map it in the store (`taskFromRow`, `bindingValue` and friends). If the
column holds encoded data, the package that owns the type owns the encoding
(`task.EncodeInputs`), and the store and the wire both use it.
4. Add the column to `newColumns` in
`internal/infrastructure/legacyimport/load.go` if legacy data has no value
for it. The importer refuses a target column it cannot fill otherwise.
5. Carry it over the wire (next section) if any process other than the State
4. Carry it over the wire (next section) if any process other than the State
Store reads it.
## Adding a field to a wire message
+1 -7
View File
@@ -35,7 +35,6 @@ require (
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/google/go-querystring v1.2.0 // indirect
github.com/google/go-tpm v0.9.8 // indirect
github.com/google/pprof v0.0.0-20260902005441-ca85771921e4 // indirect
github.com/hashicorp/go-version v1.9.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
@@ -45,7 +44,6 @@ require (
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5 // indirect
github.com/magiconair/properties v1.18.12 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/minio/highwayhash v1.0.4 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
@@ -58,13 +56,11 @@ require (
github.com/nats-io/jwt/v2 v2.8.2 // indirect
github.com/nats-io/nkeys v0.4.16 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pjbgf/sha1cd v0.6.0 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect
github.com/shirou/gopsutil/v4 v4.26.8 // indirect
@@ -89,8 +85,7 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect
modernc.org/libc v1.77.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.59.0 // indirect
)
require (
@@ -123,5 +118,4 @@ require (
google.golang.org/grpc v1.85.0-dev.0.20260825072537-93e31b48545e
google.golang.org/protobuf v1.36.12
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.59.0
)
-286
View File
@@ -1,62 +1,23 @@
4d63.com/gocheckcompilerdirectives v1.3.0/go.mod h1:ofsJ4zx2QAuIP/NO/NAh1ig6R1Fb18/GI7RVMwz7kAY=
4d63.com/gochecknoglobals v0.2.2/go.mod h1:lLxwTQjL5eIesRbvnzIP3jZtG140FnTdz+AlMa+ogt0=
cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
charm.land/lipgloss/v2 v2.0.3/go.mod h1:7myLU9iG/3xluAWzpY/fSxYYHCgoKTie7laxk6ATwXA=
cloud.google.com/go/auth v0.23.1/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE=
code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg=
codeberg.org/chavacava/garif v0.2.0/go.mod h1:P2BPbVbT4QcvLZrORc2T29szK3xEOlnl0GiPTJmEqBQ=
codeberg.org/polyfloyd/go-errorlint v1.9.0/go.mod h1:GPRRu2LzVijNn4YkrZYJfatQIdS+TrcK8rL5Xs24qw8=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
dev.gaijin.team/go/exhaustruct/v4 v4.0.0/go.mod h1:aZ/k2o4Y05aMJtiux15x8iXaumE88YdiB0Ai4fXOzPI=
dev.gaijin.team/go/golib v0.6.0/go.mod h1:uY1mShx8Z/aNHWDyAkZTkX+uCi5PdX7KsG1eDQa2AVE=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
github.com/4meepo/tagalign v1.4.3/go.mod h1:00WwRjiuSbrRJnSVeGWPLp2epS5Q/l4UEy0apLLS37c=
github.com/Abirdcfly/dupword v0.1.7/go.mod h1:K0DkBeOebJ4VyOICFdppB23Q0YMOgVafM0zYW0n9lF4=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/AdminBenni/iota-mixing v1.0.0/go.mod h1:i4+tpAaB+qMVIV9OK3m4/DAynOd5bQFaOu+2AhtBCNY=
github.com/AlwxSin/noinlineerr v1.0.5/go.mod h1:+QgkkoYrMH7RHvcdxdlI7vYYEdgeoFOVjU9sUhw/rQc=
github.com/Antonboom/errname v1.1.1/go.mod h1:gjhe24xoxXp0ScLtHzjiXp0Exi1RFLKJb0bVBtWKCWQ=
github.com/Antonboom/nilnil v1.1.1/go.mod h1:yCyAmSw3doopbOWhJlVci+HuyNRuHJKIv6V2oYQa8II=
github.com/Antonboom/testifylint v1.6.4/go.mod h1:YO33FROXX2OoUfwjz8g+gUxQXio5i9qpVy7nXGbxDD4=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY=
github.com/Azure/go-ansiterm v0.0.0-20260917205352-e937bb47801a h1:4hxax9ktNjSDoFn1tZSeL6gXMTRMpO0FzjdKfT01jgY=
github.com/Azure/go-ansiterm v0.0.0-20260917205352-e937bb47801a/go.mod h1:3EWSSOZ50kb+arhww0qIaEXHToib/3FjBj9Jj5lcP5g=
github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0/go.mod h1:Y33QHnf0FfdVewFFISOGe20mkZbxX4H839o955/PoeI=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/ClickHouse/ch-go v0.74.0/go.mod h1:sZ/r+8ttZMjyrP9PuFbgoVbth1ywIu2LIQNA2vgko6M=
github.com/ClickHouse/clickhouse-go-linter v1.2.0/go.mod h1:pLorS7ffPTfuUV9M0SJgfHA/h/WQPQUk2FWG9x74cQ4=
github.com/ClickHouse/clickhouse-go/v2 v2.48.0/go.mod h1:lBjUCPRG6RpRQdMbkXq+JV8rY0/O5lw+Z7jShgReFjM=
github.com/Djarvur/go-err113 v0.1.1/go.mod h1:IaWJdYFLg76t2ihfflPZnM1LIQszWOsFDh2hhhAVF6k=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM=
github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/MirrexOne/unqueryvet v1.5.4/go.mod h1:fs9Zq6eh1LRIhsDIsxf9PONVUjYdFHdtkHIgZdJnyPU=
github.com/OpenPeeDeeP/depguard/v2 v2.2.1/go.mod h1:q4DKzC4UcVaAvcfd41CZh0PWpGgzrVxUYBlgKNGquUo=
github.com/ProtonMail/go-crypto v1.5.1 h1:pTrLDQHyOT8y3DFYIpijgPBTw/7E2GLMimutvOlceuE=
github.com/ProtonMail/go-crypto v1.5.1/go.mod h1:/RaSu30DaKO4RY+XdV/ACcCcZkGr7AhUIduq5sjzzCo=
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
github.com/alecthomas/chroma/v2 v2.24.1/go.mod h1:l+ohZ9xRXIbGe7cIW+YZgOGbvuVLjMps/FYN/CwuabI=
github.com/alecthomas/go-check-sumtype v0.3.1/go.mod h1:A8TSiN3UPRw3laIgWEUOHHLPa6/r9MtoigdlP5h3K/E=
github.com/alexkohler/nakedret/v2 v2.0.6/go.mod h1:l3RKju/IzOMQHmsEvXwkqMDzHHvurNQfAgE1eVmT40Q=
github.com/alexkohler/prealloc v1.1.0/go.mod h1:fT39Jge3bQrfA7nPMDngUfvUbQGQeJyGQnR+913SCig=
github.com/alfatraining/structtag v1.0.0/go.mod h1:p3Xi5SwzTi+Ryj64DqjLWz7XurHxbGsq6y3ubePJPus=
github.com/alingse/asasalint v0.0.11/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I=
github.com/alingse/nilnesserr v0.2.0/go.mod h1:1xJPrXonEtX7wyTq8Dytns5P2hNzoWymVUIaKm4HNFg=
github.com/alitto/pond v1.9.2/go.mod h1:xQn3P/sHTYcU/1BR3i86IGIrilcrGC2LiS+E2+CJWsI=
github.com/andybalholm/brotli v1.2.3/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4=
@@ -65,41 +26,12 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/ashanbrown/forbidigo/v2 v2.3.1/go.mod h1:2QDkLTzU6TV937eFROamXrW92M3paehdae4HCDCOZCM=
github.com/ashanbrown/makezero/v2 v2.2.1/go.mod h1:aEGT/9q3S8DHeE57C88z2a6xydvgx8J5hgXIGWgo0MY=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bitfield/gotestdox v0.2.2/go.mod h1:D+gwtS0urjBrzguAkTM2wodsTQYFHdpx8eqRJ3N+9pY=
github.com/bkielbasa/cyclop v1.2.3/go.mod h1:kHTwA9Q0uZqOADdupvcFJQtp/ksSnytRMe8ztxG8Fuo=
github.com/blizzy78/varnamelen v0.8.0/go.mod h1:V9TzQZ4fLJ1DSrjVDfl89H7aMnTvKkApdHeyESmyR7k=
github.com/bombsimon/wsl/v4 v4.7.0/go.mod h1:uV/+6BkffuzSAVYD+yGyld1AChO7/EuLrCF/8xTiapg=
github.com/bombsimon/wsl/v5 v5.8.0/go.mod h1:AbOLsulgkqP4ZnitHf9gwPtCOGlrzkk0jb0uNxRSY0o=
github.com/breml/bidichk v0.3.3/go.mod h1:ISbsut8OnjB367j5NseXEGGgO/th206dVa427kR8YTE=
github.com/breml/errchkjson v0.4.1/go.mod h1:a23OvR6Qvcl7DG/Z4o0el6BRAjKnaReoPQFciAl9U3s=
github.com/butuzov/ireturn v0.4.1/go.mod h1:q+DXKzTDV5guNuXLnIab9fKXizTn2miZHLhxH7V/GB4=
github.com/butuzov/mirror v1.3.0/go.mod h1:AEij0Z8YMALaq4yQj9CPPVYOyJQyiexpQEQgihajRfI=
github.com/bwesterb/go-ristretto v1.2.4/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/catenacyber/perfsprint v0.10.1/go.mod h1:DJTGsi/Zufpuus6XPGJyKOTMELe347o6akPvWG9Zcsc=
github.com/ccojocar/zxcvbn-go v1.0.4/go.mod h1:3GxGX+rHmueTUMvm5ium7irpyjmm7ikxYFOSJB21Das=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charithe/durationcheck v0.0.11/go.mod h1:x5iZaixRNl8ctbM+3B2RrPG5t856TxRyVQEnbIEM2X4=
github.com/charlievieth/fastwalk v1.0.14/go.mod h1:diVcUreiU1aQ4/Wu3NbxxH4/KYdKpLDojrQ1Bb2KgNY=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/ultraviolet v0.0.0-20251205161215-1948445e3318/go.mod h1:Y6kE2GzHfkyQQVCSL9r2hwokSrIlHGzZG+71+wDYSZI=
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk=
github.com/ckaznocha/intrange v0.3.1/go.mod h1:QVepyz1AkUoFQkpEqksSYpNpUo3c5W7nWh/s6SHIJJk=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
@@ -108,25 +40,18 @@ github.com/containerd/log v0.2.0 h1:BewD/umNgVnoczglOpX8eRMyEy5t5iPlu5AIpnWDONc=
github.com/containerd/log v0.2.0/go.mod h1:/M7L7CXKcPTfNC74XzaK+5H5KbO5+4lJVpuVI6vRLoM=
github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A=
github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw=
github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g=
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/curioswitch/go-reassign v0.3.0/go.mod h1:nApPCCTtqLJN/s8HfItCcKV0jIPwluBOvZP+dsJGA88=
github.com/daixiang0/gci v0.13.7/go.mod h1:812WVN6JLFY9S6Tv76twqmNqevN0pa3SX3nih0brVzQ=
github.com/dave/dst v0.27.3/go.mod h1:jHh6EOibnHgcUW3WjKHisiooEkYwqpHLBSX1iOBhEyc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0=
github.com/davidmz/go-pageant v1.0.2/go.mod h1:P2EDDnMqIwG5Rrp05dTRITj9z2zpGcD9efWSkTNKLIE=
github.com/denis-tingaikin/go-header v0.5.0/go.mod h1:mMenU5bWrok6Wl2UsZjy+1okegmwQ3UgWl4V1D8gjlY=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dnephin/pflag v1.0.7/go.mod h1:uxE91IoWURlOiTUIA8Mq5ZZkAv3dPUfZNaT80Zm7OQE=
github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M=
github.com/docker/go-connections v0.8.1/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
@@ -135,28 +60,12 @@ github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/elastic/go-sysinfo v1.15.5/go.mod h1:ZBVXmqS368dOn/jvijV/zHLfakWTYHBZPk3G244lHrU=
github.com/elastic/go-windows v1.0.2/go.mod h1:bGcDpBzXgYSqM0Gx3DM4+UxFj300SZLixie9u9ixLM8=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
github.com/envoyproxy/go-control-plane/envoy v1.39.0/go.mod h1:5e4ylfTZO723MEEFsCpSW4ZEBWR8mwkEyXfwJBTCZ9c=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/firefart/nonamedreturns v1.0.6/go.mod h1:R8NisJnSIpvPWheCq0mNRXJok6D8h7fagJTF8EMEwCo=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA=
github.com/ghostiam/protogetter v0.3.20/go.mod h1:FjIu5Yfs6FT391m+Fjp3fbAYJ6rkL/J6ySpZBfnODuI=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
github.com/go-critic/go-critic v0.14.3/go.mod h1:xwntfW6SYAd7h1OqDzmN6hBX/JxsEKl5up/Y2bsxgVQ=
github.com/go-faster/city v1.0.1/go.mod h1:jKcUJId49qdW3L1qKHH/3wPeUstCVpVSXTM6vO3VcTw=
github.com/go-faster/errors v0.8.0/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo=
github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI=
github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM=
github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=
@@ -179,42 +88,10 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-telegram/bot v1.27.0 h1:PG9yBDzM8O26oUerE9SZwWlHon4RpH8WcNslZ7CEZmE=
github.com/go-telegram/bot v1.27.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
github.com/go-toolsmith/astcast v1.1.0/go.mod h1:qdcuFWeGGS2xX5bLM/c3U9lewg7+Zu4mr+xPwZIB4ZU=
github.com/go-toolsmith/astcopy v1.1.0/go.mod h1:hXM6gan18VA1T/daUEHCFcYiW8Ai1tIwIzHY6srfEAw=
github.com/go-toolsmith/astequal v1.2.0/go.mod h1:c8NZ3+kSFtFY/8lPso4v8LuJjdJiUFVnSuU3s0qrrDY=
github.com/go-toolsmith/astfmt v1.1.0/go.mod h1:OrcLlRwu0CuiIBp/8b5PYF9ktGVZUjlNMV634mhwuQ4=
github.com/go-toolsmith/astp v1.1.0/go.mod h1:0T1xFGz9hicKs8Z5MfAqSUitoUYS30pDMsRVIDHs8CA=
github.com/go-toolsmith/strparse v1.1.0/go.mod h1:7ksGy58fsaQkGQlY8WVoBFNyEPMGuJin1rfoPS4lBSQ=
github.com/go-toolsmith/typep v1.1.0/go.mod h1:fVIw+7zjdsMxDA3ITWnH1yOiw1rnTQKCsF/sk2H/qig=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-xmlfmt/xmlfmt v1.1.3/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/godoc-lint/godoc-lint v0.11.2/go.mod h1:iVpGdL1JCikNH2gGeAn3Hh+AgN5Gx/I/cxV+91L41jo=
github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/golangci/asciicheck v0.5.0/go.mod h1:5RMNAInbNFw2krqN6ibBxN/zfRFa9S6tA1nPdM0l8qQ=
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202/go.mod h1:NUw9Zr2Sy7+HxzdjIULge71wI6yEg1lWQr7Evcu8K0E=
github.com/golangci/go-printf-func-name v0.1.1/go.mod h1:Es64MpWEZbh0UBtTAICOZiB+miW53w/K9Or/4QogJss=
github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d/go.mod h1:ivJ9QDg0XucIkmwhzCDsqcnxxlDStoTl89jDMIoNxKY=
github.com/golangci/golangci-lint/v2 v2.12.2/go.mod h1:opqHHuIcTG2R+4akzWMd4o1BnD9/1LcjICWOujr91U8=
github.com/golangci/golines v0.15.0/go.mod h1:AZjXd23tbHMpowhtnGlj9KCNsysj72aeZVVHnVcZx10=
github.com/golangci/misspell v0.8.0/go.mod h1:WZyyI2P3hxPY2UVHs3cS8YcllAeyfquQcKfdeE9AFVg=
github.com/golangci/plugin-module-register v0.1.2/go.mod h1:1+QGTsKBvAIvPvoY/os+G5eoqxWn70HYDm2uvUyGuVw=
github.com/golangci/revgrep v0.8.0/go.mod h1:U4R/s9dlXZsg8uJmaR1GrloUr14D7qDl8gi2iPXJH8k=
github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba/go.mod h1:sCBNcpRmhJCtbFGz49+IM3ETTFf7QdJ30AeYCd43NKk=
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e/go.mod h1:Vrn4B5oR9qRwM+f54koyeH3yzphlecwERs0el27Fr/s=
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e/go.mod h1:h+wZwLjUTJnm/P2rwlbJdRPZXOzaT36/FwnPnY2inzc=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
@@ -224,29 +101,10 @@ github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfh
github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/pprof v0.0.0-20260902005441-ca85771921e4 h1:/6mPXfWmhv8eKck12I0YNIcIjwHtxP3YRIMKiEgTjWg=
github.com/google/pprof v0.0.0-20260902005441-ca85771921e4/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
github.com/gordonklaus/ineffassign v0.2.0/go.mod h1:TIpymnagPSexySzs7F9FnO1XFTy8IT3a59vmZp5Y9Lw=
github.com/gostaticanalysis/analysisutil v0.7.1/go.mod h1:v21E3hY37WKMGSnbsw2S/ojApNWb6C1//mXO48CXbVc=
github.com/gostaticanalysis/comment v1.5.0/go.mod h1:V6eb3gpCv9GNVqb6amXzEUX3jXLVK/AdA+IrAMSqvEc=
github.com/gostaticanalysis/forcetypeassert v0.2.0/go.mod h1:M5iPavzE9pPqWyeiVXSFghQjljW1+l/Uke3PXHS6ILY=
github.com/gostaticanalysis/nilerr v0.1.2/go.mod h1:A19UHhoY3y8ahoL7YKz6sdjDtduwTSI4CsymaC2htPA=
github.com/hashicorp/go-immutable-radix/v2 v2.1.0/go.mod h1:hgdqLXA4f6NIjRVisM1TJ9aOJVNRqKZj+xDGF6m7PBw=
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -255,16 +113,8 @@ github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jgautheron/goconst v1.10.0/go.mod h1:0p+wv1lFOiUr0IlNNT1nrm6+8DB8u2sU6KHGzFRXHDc=
github.com/jjti/go-spancheck v0.6.5/go.mod h1:aEogkeatBrbYsyW6y5TgDfihCulDYciL1B7rG2vSsrU=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
github.com/julz/importas v0.2.0/go.mod h1:pThlt589EnCYtMnmhmRYY/qn9lCf/frPOK+WMx3xiJY=
github.com/karamaru-alpha/copyloopvar v1.2.2/go.mod h1:oY4rGZqZ879JkJMtX3RRkcXRkmUvH0x35ykgaKgsgJY=
github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRgTaQBFY=
github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=
github.com/kisielk/errcheck v1.10.0/go.mod h1:kQxWMMVZgIkDq7U8xtG/n2juOjbLgZtedi0D+/VL/i8=
github.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg=
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
@@ -276,46 +126,20 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kulti/thelper v0.7.1/go.mod h1:NsMjfQEy6sd+9Kfw8kCP61W1I0nerGSYSFnGaxQkcbs=
github.com/kunwardeep/paralleltest v1.0.15/go.mod h1:di4moFqtfz3ToSKxhNjhOZL+696QtJGCFe132CbBLGk=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lasiar/canonicalheader v1.1.2/go.mod h1:qJCeLFS0G/QlLQ506T+Fk/fWMa2VmBUiEI2cuMK4djI=
github.com/ldez/exptostd v0.4.5/go.mod h1:QRjHRMXJrCTIm9WxVNH6VW7oN7KrGSht69bIRwvdFsM=
github.com/ldez/gomoddirectives v0.8.0/go.mod h1:jutzamvZR4XYJLr0d5Honycp4Gy6GEg2mS9+2YX3F1Q=
github.com/ldez/grignotin v0.10.1/go.mod h1:UlDbXFCARrXbWGNGP3S5vsysNXAPhnSuBufpTEbwOas=
github.com/ldez/structtags v0.6.1/go.mod h1:YDxVSgDy/MON6ariaxLF2X09bh19qL7MtGBN5MrvbdY=
github.com/ldez/tagliatelle v0.7.2/go.mod h1:PtGgm163ZplJfZMZ2sf5nhUT170rSuPgBimoyYtdaSI=
github.com/ldez/usetesting v0.5.0/go.mod h1:Spnb4Qppf8JTuRgblLrEWb7IE6rDmUpGvxY3iRrzvDQ=
github.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5 h1:eveIIGn4BGM3qknO74omf6HYr30/exH+eVUTuAgwjZ0=
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/macabu/inamedparam v0.2.0/go.mod h1:+Pee9/YfGe5LJ62pYXqB89lJ+0k5bsR8Wgz/C0Zlq3U=
github.com/magiconair/properties v1.18.12 h1:sT9zQpvTB3B4gzrX0tmZNTEaGyg8Zw55MFYRE32Mr9I=
github.com/magiconair/properties v1.18.12/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/manuelarte/embeddedstructfieldcheck v0.4.0/go.mod h1:z8dFSyXqp+fC6NLDSljRJeNQJJDWnY7RoWFzV3PC6UM=
github.com/manuelarte/funcorder v0.6.0/go.mod h1:id3NDhXdQBmeqXH7eVC6Z89xS6JxvZ8kF9xUxpArU/g=
github.com/maratori/testableexamples v1.0.1/go.mod h1:XE2F/nQs7B9N08JgyRmdGjYVGqxWwClLPCGSQhXQSrQ=
github.com/maratori/testpackage v1.1.2/go.mod h1:8F24GdVDFW5Ew43Et02jamrVMNXLUNaOynhDssITGfc=
github.com/matoous/godox v1.1.0/go.mod h1:jgE/3fUXiTurkdHOLT5WEkThTSuE7yxHv5iWPa80afs=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
github.com/mdelapenya/tlscert v0.2.0/go.mod h1:O4njj3ELLnJjGdkN7M/vIVCpZ+Cf0L6muqOG4tLSl8o=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mfridman/xflag v0.1.0/go.mod h1:/483ywM5ZO5SuMVjrIGquYNE5CzLrj5Ux/LxWWnjRaE=
github.com/mgechev/revive v1.15.0/go.mod h1:LlAKO3QQe9OJ0pVZzI2GPa8CbXGZ/9lNpCGvK4T/a8A=
github.com/microsoft/go-mssqldb v1.11.0/go.mod h1:goQLDOPlMN/l1REhnNPElMoY/yX+fUWn1+7UoFJPH9Y=
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/go-archive v0.3.3 h1:OxxR9paxsluYi+zDUEXTTaIxtkK3viymW+Ka7vRhhME=
@@ -330,7 +154,6 @@ github.com/moby/sys/mount v0.3.5 h1:eS3fsZTjHaBihwjp4/+5Z3jxqLXYsbwxqpVSfFv3M00=
github.com/moby/sys/mount v0.3.5/go.mod h1:WUQDO+/uCiCIkIztx8SrwIDVn2dtMFRBebRhpDFT71M=
github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg=
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
github.com/moby/sys/reexec v0.1.0/go.mod h1:EqjBg8F3X7iZe5pU6nRZnYCMUTXoxsjiIfHup5wYIN8=
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0=
@@ -339,9 +162,6 @@ github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8
github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/moricho/tparallel v0.3.2/go.mod h1:OQ+K3b4Ln3l2TZveGCywybl68glfLEwFGqvnjok8b+U=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE=
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
github.com/nats-io/nats-server/v2 v2.15.0 h1:M99yf0y05rTr46/qc/Is6ZAowI58Ryp2SjufLCUeVJc=
@@ -354,76 +174,33 @@ github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/nishanths/exhaustive v0.12.0/go.mod h1:mEZ95wPIZW+x8kC4TgC+9YCUgiST7ecevsVDTgc2obs=
github.com/nishanths/predeclared v0.2.2/go.mod h1:RROzoN6TnGQupbC+lqggsOlcgysk3LMK/HI84Mp280c=
github.com/nunnatsa/ginkgolinter v0.23.0/go.mod h1:9qN1+0akwXEccwV1CAcCDfcoBlWXHB+ML9884pL4SZ4=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/paulmach/orb v0.13.0/go.mod h1:6scRWINywA2Jf05dcjOfLfxrUIMECvTSG2MVbRLxu/k=
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 h1:XA01Vk/wv9YikCi1V51yRzIHPMT5of9+cMpZoZvDn/M=
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/pressly/goose/v3 v3.28.0 h1:D2M+iL31GmpZxSHOhX8mqyqAT3CXnokUmm0eKoSP+Vc=
github.com/pressly/goose/v3 v3.28.0/go.mod h1:v26MOuB8bL3kzzrt3Vqhb3R0PRVsl8hFQKdrht/L6Rk=
github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls=
github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
github.com/quasilyte/go-ruleguard v0.4.5/go.mod h1:Vl05zJ538vcEEwu16V/Hdu7IYZWyKSwIy4c88Ro1kRE=
github.com/quasilyte/go-ruleguard/dsl v0.3.23/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU=
github.com/quasilyte/gogrep v0.5.0/go.mod h1:Cm9lpz9NZjEoL1tgZ2OgeUKPIxL1meE7eo60Z6Sk+Ng=
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0=
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567/go.mod h1:DWNGW8A4Y+GyBgPuaQJuWiy0XYftx4Xm/y5Jqk9I6VQ=
github.com/raeperd/recvcheck v0.2.0/go.mod h1:n04eYkwIR0JbgD73wT8wL4JjPC3wm0nFtzBnWNocnYU=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
github.com/ryancurrah/gomodguard v1.4.1/go.mod h1:qnMJwV1hX9m+YJseXEBhd2s90+1Xn6x9dLz11ualI1I=
github.com/ryancurrah/gomodguard/v2 v2.1.3/go.mod h1:CQicdLGatWMxLX53JzoBjYlsNZhHbmLv2AVa0s2aivU=
github.com/ryanrolds/sqlclosecheck v0.6.0/go.mod h1:xyX16hsDaCMXHrMJ3JMzGf5OpDfHTOTTQrT7HOFUmeU=
github.com/samcharles93/ai-sdk v0.1.39 h1:gbNPYeA27MifReCruBiqMgb4fFSjCDi1Zv57a9bo0Vo=
github.com/samcharles93/ai-sdk v0.1.39/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk=
github.com/sanposhiho/wastedassign/v2 v2.1.0/go.mod h1:+oSmSC+9bQ+VUAxA66nBb0Z7N8CK7mscKTDYC6aIek4=
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84dxiN1iBi9+G8zZIhPVoNjQ=
github.com/sashamelentyev/usestdlibvars v1.29.0/go.mod h1:8PpnjHMk5VdeWlVb4wCdrB8PNbLqZ3wBZTZWkrpZZL8=
github.com/securego/gosec/v2 v2.26.1/go.mod h1:57UW4p0uoP3kxoTkhoo3axLdVAi+OWrLg/Ax/kdqtPE=
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/shirou/gopsutil/v4 v4.26.8 h1:YQMTF/1J50B5+Y0vlo1eDRf5DoR7Gk69hY+8wjYkQeo=
github.com/shirou/gopsutil/v4 v4.26.8/go.mod h1:5O9FjBiXoTDFatIWjZZosqj4pV0DRtLx598xGbBehzM=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
github.com/sivchari/containedctx v1.0.3/go.mod h1:c1RDvCbnJLtH4lLcYD/GqwiBSSf4F5Qk0xld2rBqzJ4=
github.com/sonatard/noctx v0.5.1/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas=
github.com/sourcegraph/go-diff v0.8.0/go.mod h1:hWlcO7Al+UZStZAP8rBumHpCK5ZHQ5BXsMls8p4+F5E=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.12.0/go.mod h1:b6COn30jlNxbm/V2IqWiNWkJ+vZNiMNksliPCiuKtSI=
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
github.com/ssgreg/nlreturn/v2 v2.2.1/go.mod h1:E/iiPB78hV7Szg2YfRgyIrk1AD6JVMTRkkxBiELzh2I=
github.com/stbenjam/no-sprintf-host-port v0.3.1/go.mod h1:ODbZesTCHMVKthBHskvUUexdcNHAQRXk9NpSsL8p/HQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
@@ -432,45 +209,18 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=
github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 h1:8fdv/9y3JMxjQ+ULAcOG8RtgeNu5t9XF9LolSXDuTwM=
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0/go.mod h1:CFr2LncGYokw+OKjXcr8ARCKG1SaC2UEnGxFBovE86g=
github.com/tetafro/godot v1.5.6/go.mod h1:eOkMrVQurDui411nBY2FA05EYH01r14LuWY/NrVDVcU=
github.com/timakin/bodyclose v0.0.0-20260129054331-73d1f95b84b4/go.mod h1:sDHLK7rb/59v/ZxZ7KtymgcoxuUMxjXq8gtu9VMOK8M=
github.com/timonwong/loggercheck v0.11.0/go.mod h1:HEAWU8djynujaAVX7QI65Myb8qgfcZ1uKbdpg3ZzKl8=
github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/tomarrell/wrapcheck/v2 v2.12.0/go.mod h1:AQhQuZd0p7b6rfW+vUwHm5OMCGgp63moQ9Qr/0BpIWo=
github.com/tommy-muehle/go-mnd/v2 v2.5.1/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw=
github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60/go.mod h1:08inkKyguB6CGGssc/JzhmQWwBgFQBgjlYFjxjRh7nU=
github.com/ultraware/funlen v0.2.0/go.mod h1:ZE0q4TsJ8T1SQcjmkhN/w+MceuatI6pBFSxxyteHIJA=
github.com/ultraware/whitespace v0.2.0/go.mod h1:XcP1RLD81eV4BW8UhQlpaR+SDc2givTvyI8a586WjW8=
github.com/uudashr/gocognit v1.2.1/go.mod h1:acaubQc6xYlXFEMb9nWX2dYBzJ/bIjEkc1zzvyIZg5Q=
github.com/uudashr/iface v1.4.2/go.mod h1:pbeBPlbuU2qkNDn0mmfrxP2X+wjPMIQAy+r1MBXSXtg=
github.com/vertica/vertica-sql-go v1.3.8/go.mod h1:c4OZ8lq1Ztc18w8a0nG+dzQh69BzJRcKN2LZOnYbERI=
github.com/xen0n/gosmopolitan v1.3.0/go.mod h1:rckfr5T6o4lBtM1ga7mLGKZmLxswUoH1zxHgNXOsEt4=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/yagipy/maintidx v1.0.0/go.mod h1:0qNf/I/CCZXSMhsRsrEPDZ+DkekpKLXAJfsTACwgXLk=
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260810123728-f0c151ab31b9/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
github.com/ydb-platform/ydb-go-sdk/v3 v3.151.1/go.mod h1:dJXJ1u00IqO8Vsph8fWmYj8b1E7jyphnvJPqA69emBY=
github.com/yeya24/promlinter v0.3.0/go.mod h1:cDfJQQYv9uYciW60QT0eeHlFodotkYZlL+YcPQN+mW4=
github.com/ykadowak/zerologlint v0.1.5/go.mod h1:KaUskqF3e/v59oPmdq1U1DnKcuHokl2/K1U4pmIELKg=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
github.com/zchee/goimports-rereviser/v4 v4.1.1/go.mod h1:wVyRWAl9QWy/5rjTRKraAijS41I7QDmc7nQkkZxFxGs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0=
gitlab.com/bosi/decorder v0.4.2/go.mod h1:muuhHoaJkA9QLcYHq4Mj8FJUwDZ+EirSHRiaTcTf6T8=
go-simpler.org/musttag v0.14.0/go.mod h1:uP8EymctQjJ4Z1kUnjX0u2l60WfUdQxCwSNKzE1JEOE=
go-simpler.org/sloglint v0.12.0/go.mod h1:jBjjC2bm8rYrs88oTRlFX497kWjJsyZWYoNaXkGRI6I=
go.augendre.info/arangolint v0.4.0/go.mod h1:l+f/b4plABuFISuKnTGD4RioXiCCgghv2xqst/xOvAA=
go.augendre.info/fatcontext v0.9.0/go.mod h1:L94brOAT1OOUNue6ph/2HnwxoNlds9aXDF2FcUntbNw=
go.lsp.dev/jsonrpc2 v1.0.1 h1:JZAchpm6RcOuwEOnZ7kF3kA1EpEjdJZ/6rMSfOF3+F4=
go.lsp.dev/jsonrpc2 v1.0.1/go.mod h1:WN+TesqrPumBmUdsuWyn9DHq3zl4i85L/qG0NLdj8qg=
go.lsp.dev/protocol v1.0.1 h1:kLWUIk1v/deXxo1D0VO4avjZnfeuZ82mouJgJd/NbdU=
@@ -479,7 +229,6 @@ go.lsp.dev/uri v1.0.1 h1:ywxJN1UXoQ+v0I9lkoQNMmsm7lub5G9ZG7KXT8YTx30=
go.lsp.dev/uri v1.0.1/go.mod h1:06a0ghafs4PuqkLsJGUmlgPHw6+kH79edRXjOT/rA8s=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
@@ -494,7 +243,6 @@ go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu6
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -504,9 +252,6 @@ golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU=
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E=
golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358/go.mod h1:4Mzdyp/6jzw9auFDJ3OMF5qksa7UvPnzKqTVGcb04ms=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
@@ -535,13 +280,8 @@ golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459 h1:GS9OIt/j7c8bvBjYNgnKQysVfmV7e4jM0H8ZK95G4t8=
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459/go.mod h1:PX5/4vemwVoXtwEcRDWwcR1/r0qrosfx3qoVADMwnVE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 h1:b0xCahf3FK2m2Cv0p4vTozGPWncCvLfwV86UNg8xWU8=
@@ -554,46 +294,20 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/gotestsum v1.13.0/go.mod h1:7f0NS5hFb0dWr4NtcsAsF0y1kzjEFfAil0HiBQJE03Q=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
honnef.co/go/tools v0.7.0/go.mod h1:pm29oPxeP3P82ISxZDgIYeOaf9ta6Pi0EWvCFoLG2vc=
howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg=
modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE=
modernc.org/ccgo/v4 v4.36.1/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.59.0 h1:X1es1GpqBlS/5T+vbM4HLUdaa8OtQx468DF2vrx+38A=
modernc.org/sqlite v1.59.0/go.mod h1:+paeT2A3iPRHkQDwG7oA6Tk0zQd5woMEI8q7orfry8k=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
mvdan.cc/gofumpt v0.10.0/go.mod h1:sU2ElXHzOEmvoPqfutYG7uunlueR4K2T1JFml40SzP4=
mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15/go.mod h1:4M5MMXl2kW6fivUT6yRGpLLPNfuGtU2Z0cPvFquGDYU=
pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=
pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=
+1 -1
View File
@@ -413,7 +413,7 @@ func (b *boot) openStateStoreAdapter() error {
// database_url. The daemon reads it (session curator) and the Gateway serves
// it; only the Gateway claims serve ownership (claimGatewayOwnership).
func (b *boot) openChatSessions(ctx context.Context) error {
pool, err := openServicePool(ctx, b.cfg.DatabaseURL, b.cfg.DBPath, "the conversation store")
pool, err := openServicePool(ctx, b.cfg.DatabaseURL, "the conversation store")
if err != nil {
return fmt.Errorf("open conversation store: %w", err)
}
-6
View File
@@ -145,12 +145,6 @@ func makeUpdateService(s chatSetup) *releaseupdate.Service {
return updates
}
// conversationDBPath is the legacy SQLite conversation database the one-time
// import reads.
func conversationDBPath(taskDBPath string) string {
return taskDBPath + "-conversations.sqlite"
}
func makeChatLLMResponder(
ctx context.Context,
channel string,
@@ -2,7 +2,6 @@ package archied
import (
"log/slog"
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/config"
@@ -13,7 +12,6 @@ import (
func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) {
cfg := config.Config{
DBPath: filepath.Join(t.TempDir(), "tasks.db"),
DatabaseURL: pgtest.URL(t),
Services: config.Services{config.ServiceNameGateway: {Target: "127.0.0.1:1"}},
}
@@ -103,8 +103,8 @@ func TestStateStoreBootsWithStaleDatabaseOwnedValues(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
body := fmt.Sprintf(
"bot_user = 'archie'\ndb_path = %q\ndatabase_url = %q\n%s[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n",
filepath.Join(dir, "state.db"), pgtest.URL(t), tt.body,
"bot_user = 'archie'\ndatabase_url = %q\n%s[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n",
pgtest.URL(t), tt.body,
)
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
-167
View File
@@ -1,167 +0,0 @@
package archied
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/config"
"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"
)
// seedLegacyConversation writes one session into the legacy SQLite
// conversation file beside dbPath, which is enough for the cutover gate to
// see legacy data.
func seedLegacyConversation(t *testing.T, dbPath string) {
t.Helper()
legacyfixture.Exec(t, conversationDBPath(dbPath), legacyfixture.GatewayDDL)
}
func testPool(t *testing.T, url string) *pgxpool.Pool {
t.Helper()
pool, err := postgres.Open(t.Context(), url)
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(pool.Close)
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
t.Fatalf("migrate: %v", err)
}
return pool
}
// TestCutoverGate pins D1.3 in both serving processes: a fresh install boots
// and records completion, legacy data without a completed import refuses with
// the operator's instruction, and a completed import boots over legacy files.
func TestCutoverGate(t *testing.T) {
processes := []struct {
name string
open func(*boot, context.Context) error
}{
{"state store", func(b *boot, ctx context.Context) error { return b.openStateStorePool(ctx) }},
{"gateway", func(b *boot, ctx context.Context) error { return b.openStores(ctx) }},
}
tests := []struct {
name string
legacy bool
complete bool
wantErr string
}{
{name: "fresh install"},
{name: "legacy data without import", legacy: true, wantErr: "run `archie-state-store import`"},
{name: "legacy data with completed import", legacy: true, complete: true},
}
for _, p := range processes {
for _, tt := range tests {
t.Run(p.name+"/"+tt.name, func(t *testing.T) {
url := pgtest.URL(t)
dbPath := filepath.Join(t.TempDir(), "archie.db")
if tt.legacy {
seedLegacyConversation(t, dbPath)
}
pool := testPool(t, url)
if tt.complete {
if _, err := pool.Exec(t.Context(),
"INSERT INTO import_completion (id, sources, report) VALUES (1, 's', 'r')"); err != nil {
t.Fatalf("seed completion: %v", err)
}
}
b := newBootstrap()
b.cfg = config.Config{DatabaseURL: url, DBPath: dbPath}
err := p.open(b, t.Context())
b.cleanup()
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("open = %v, want refusal containing %q", err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("open: %v", err)
}
done, err := postgres.ImportComplete(t.Context(), pool)
if err != nil {
t.Fatalf("ImportComplete: %v", err)
}
if !done {
t.Fatal("serving database has no completion record; a later legacy file would block it")
}
})
}
}
}
// TestFreshInstallIgnoresLaterLegacyFile pins the fresh-install record: once a
// database started with no legacy data, a stray legacy file does not block it.
func TestFreshInstallIgnoresLaterLegacyFile(t *testing.T) {
url := pgtest.URL(t)
dbPath := filepath.Join(t.TempDir(), "archie.db")
first := newBootstrap()
first.cfg = config.Config{DatabaseURL: url, DBPath: dbPath}
if err := first.openStateStorePool(t.Context()); err != nil {
t.Fatalf("fresh start: %v", err)
}
first.cleanup()
seedLegacyConversation(t, dbPath)
if _, err := os.Stat(conversationDBPath(dbPath)); err != nil {
t.Fatalf("legacy file not written: %v", err)
}
second := newBootstrap()
second.cfg = first.cfg
if err := second.openStateStorePool(t.Context()); err != nil {
t.Fatalf("restart with a stray legacy file: %v", err)
}
second.cleanup()
}
// TestGatewayRefusesASecondOwner pins D4.1: one Gateway serves a database, a
// second refuses while the first holds its claim, and one starts again once
// the first has shut down.
func TestGatewayRefusesASecondOwner(t *testing.T) {
cfg := config.Config{DatabaseURL: pgtest.URL(t), DBPath: filepath.Join(t.TempDir(), "archie.db")}
start := func() (*boot, error) {
b := newBootstrap()
b.cfg = cfg
if err := b.openChatSessions(t.Context()); err != nil {
b.cleanup()
return nil, err
}
if err := b.claimGatewayOwnership(t.Context()); err != nil {
b.cleanup()
return nil, err
}
return b, nil
}
first, err := start()
if err != nil {
t.Fatalf("first gateway: %v", err)
}
if _, err := start(); !errors.Is(err, postgres.ErrOwned) {
first.cleanup()
t.Fatalf("second gateway = %v, want ErrOwned", err)
}
first.cleanup()
third, err := start()
if err != nil {
t.Fatalf("gateway after the owner shut down: %v", err)
}
third.cleanup()
}
// TestConversationStoreFailsClosedWithoutURL: the conversation store is
// Postgres-only, so a missing database_url stops the process.
func TestConversationStoreFailsClosedWithoutURL(t *testing.T) {
b := newBootstrap()
defer b.cleanup()
err := b.openChatSessions(t.Context())
if err == nil || !strings.Contains(err.Error(), "database_url is required") {
t.Fatalf("openChatSessions = %v, want it to name the missing database_url", err)
}
}
-4
View File
@@ -283,10 +283,6 @@ func resolveForge(cfg config.Forge, secrets *secret.Registry, log *slog.Logger)
return client, token
}
func taskDBPath(configuredPath string) string {
return configuredPath + "-tasks.sqlite"
}
func manualRequeueTask(ctx context.Context, st storecontract.TaskStore, taskID int64) error {
task, err := st.TaskByID(ctx, taskID)
if err != nil {
+2 -4
View File
@@ -2,7 +2,6 @@ package archied
import (
"context"
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/config"
@@ -12,14 +11,14 @@ import (
)
func TestDiskProbePath_PrefersStateDir(t *testing.T) {
cfg := config.Config{StateDir: "/var/lib/archie", DBPath: "/data/archie/tasks.db", WorkDir: "/srv/archie"}
cfg := config.Config{StateDir: "/var/lib/archie", WorkDir: "/srv/archie"}
if got := diskProbePath(cfg); got != "/var/lib/archie" {
t.Fatalf("diskProbePath = %q, want /var/lib/archie", got)
}
}
func TestDiskProbePath_FallsBackToWorkDir(t *testing.T) {
cfg := config.Config{DBPath: "/data/archie/tasks.db", WorkDir: "/srv/archie"}
cfg := config.Config{WorkDir: "/srv/archie"}
if got := diskProbePath(cfg); got != "/srv/archie" {
t.Fatalf("diskProbePath = %q, want /srv/archie", got)
}
@@ -54,7 +53,6 @@ func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
cfg := config.Config{
BotUser: "archie-bot",
DBPath: filepath.Join(t.TempDir(), "tasks.db"),
PollInterval: config.Duration(60_000_000_000), // 60s, satisfies validate
Dispatch: config.Dispatch{Trigger: "assignee"},
Forge: config.Forge{Type: "none"},
+1 -2
View File
@@ -4,7 +4,6 @@ import (
"context"
"log/slog"
"os"
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/config"
@@ -33,7 +32,7 @@ func newTestBoot(t *testing.T, tasks gateway.TaskCreator) *boot {
log: slog.New(slog.NewTextHandler(os.Stderr, nil)),
bus: bus,
doc: &configuration.Document{},
cfg: config.Config{DBPath: filepath.Join(t.TempDir(), "archie.db")},
cfg: config.Config{},
chatTasks: tasks,
defaultChatIdentity: "primary",
}
-5
View File
@@ -43,11 +43,6 @@ func configuredIdentityNames(cfg config.Config) []string {
return names
}
// edaDBPath derives the event-capture database from the configured db_path,
// beside the task database rather than inside it: the two stores have separate
// lifecycles and only meet at binding_dispatches.task_id.
func edaDBPath(configuredPath string) string { return configuredPath + "-eda.sqlite" }
// StateStoreOptions contains process inputs for the standalone State Store.
type StateStoreOptions struct {
Config string
@@ -1,56 +0,0 @@
package archied
import (
"context"
"errors"
"fmt"
"github.com/samcharles93/archie-core/internal/infrastructure/legacyimport"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
)
// legacySources names an install's three legacy SQLite files from its
// configured db_path, the same derivation the legacy openers use, so an
// operator cannot import one store and forget another.
func legacySources(dbPath string) legacyimport.Sources {
return legacyimport.Sources{
StateStore: taskDBPath(dbPath),
EDA: edaDBPath(dbPath),
Gateway: conversationDBPath(dbPath),
}
}
// importLegacy runs the one-time import of the legacy files into Postgres.
// It is an offline command of the State Store binary, not of archied: offline
// maintenance of a store belongs to the process that owns it.
func importLegacy(ctx context.Context, options StateStoreRecoveryOptions) (string, error) {
dbPath, url := options.DBPath, options.DatabaseURL
if dbPath == "" || url == "" {
cfg, err := bootConfig(ctx, options)
if err != nil {
return "", err
}
if dbPath == "" {
dbPath = cfg.DBPath
}
if url == "" {
url = cfg.DatabaseURL
}
}
if dbPath == "" {
return "", errors.New("import requires db_path (-db-path or the configuration)")
}
if url == "" {
return "", errors.New("import requires database_url (-database-url or the configuration)")
}
pool, err := postgres.Open(ctx, url)
if err != nil {
return "", err
}
defer pool.Close()
report, err := legacyimport.Import(ctx, pool, legacySources(dbPath))
if err != nil {
return "", err
}
return fmt.Sprintf("imported %s into Postgres and recorded the completion: %s", dbPath, report), nil
}
+7 -37
View File
@@ -3,24 +3,22 @@ package archied
import (
"context"
"fmt"
"strings"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/infrastructure/legacyimport"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
)
// openStateStorePool opens the State Store process's one process-scoped
// PostgreSQL pool, applies the schema and claims serve ownership of the
// database for the process's life, so a second State Store against the same
// database refuses to start. A missing or invalid database_url, a migration
// failure or unimported legacy data is a startup failure.
// database refuses to start. A missing or invalid database_url or a migration
// failure is a startup failure.
//
// The pool is stored on boot.pg and closed at shutdown; nothing opens a second
// pool per subsystem.
func (b *boot) openStateStorePool(ctx context.Context) error {
pool, err := openServicePool(ctx, b.cfg.DatabaseURL, b.cfg.DBPath, "the State Store")
pool, err := openServicePool(ctx, b.cfg.DatabaseURL, "the State Store")
if err != nil {
b.log.Error("open state store postgres pool", "err", err)
return err
@@ -40,12 +38,11 @@ func (b *boot) openStateStorePool(ctx context.Context) error {
return nil
}
// openServicePool opens and migrates a serving process's pool and refuses to
// serve over legacy data the one-time import has not moved. service names the
// process in the error an operator reads.
func openServicePool(ctx context.Context, url, dbPath, service string) (*pgxpool.Pool, error) {
// openServicePool opens and migrates a serving process's pool. service names
// the process in the error an operator reads.
func openServicePool(ctx context.Context, url, service string) (*pgxpool.Pool, error) {
if url == "" {
return nil, fmt.Errorf("database_url is required: %s is Postgres-only and refuses to fall back to SQLite", service)
return nil, fmt.Errorf("database_url is required: %s is Postgres-only", service)
}
pool, err := postgres.Open(ctx, url)
if err != nil {
@@ -55,32 +52,5 @@ func openServicePool(ctx context.Context, url, dbPath, service string) (*pgxpool
pool.Close()
return nil, err
}
if err := refuseUnimportedLegacy(ctx, pool, dbPath); err != nil {
pool.Close()
return nil, err
}
return pool, nil
}
// refuseUnimportedLegacy is the cutover gate. A database with a completion
// record serves. Otherwise non-empty legacy SQLite files mean an upgrade whose
// import has not run, and serving would hide that data behind empty tables,
// so it refuses. With no legacy data it is a fresh install: the completion
// record is written so a legacy file that appears later cannot block it.
func refuseUnimportedLegacy(ctx context.Context, pool *pgxpool.Pool, dbPath string) error {
done, err := postgres.ImportComplete(ctx, pool)
if err != nil || done {
return err
}
sources := legacySources(dbPath)
has, err := legacyimport.HasLegacyData(ctx, sources)
if err != nil {
return fmt.Errorf("check for legacy SQLite data: %w", err)
}
if has {
return fmt.Errorf("legacy SQLite data found (%s) but this Postgres database has no completed import: "+
"stop every archie process, run `archie-state-store import`, then start archie again",
strings.Join([]string{sources.StateStore, sources.EDA, sources.Gateway}, ", "))
}
return postgres.RecordFreshInstall(ctx, pool)
}
@@ -47,7 +47,6 @@ const (
RecoveryRestore = "restore"
RecoveryValidate = "validate"
RecoveryRollback = "rollback"
RecoveryImport = "import"
)
// StateStoreRecoveryOptions are the process inputs for one offline recovery
@@ -70,21 +69,11 @@ type StateStoreRecoveryOptions struct {
// Revision is the revision rollback replays. Zero means the newest
// revision older than the one the resource carries now.
Revision int64
// DBPath and DatabaseURL are import's source and target: the configured
// db_path every legacy file is named from, and the Postgres URL. Either
// left empty is read from the configuration.
DBPath string
DatabaseURL string
}
// RunStateStoreRecovery performs one offline operation on the task database and
// returns the line the command reports on stdout.
func RunStateStoreRecovery(ctx context.Context, options StateStoreRecoveryOptions) (string, error) {
// import names its legacy sources from db_path and its target from
// database_url itself.
if options.Operation == RecoveryImport {
return importLegacy(ctx, options)
}
return runPostgresRecovery(ctx, options)
}
@@ -25,8 +25,8 @@ func pgRecoveryFixture(t *testing.T) (configPath string, pool *pgxpool.Pool, url
url = pgtest.URL(t)
dir := t.TempDir()
configPath = filepath.Join(dir, "config.toml")
body := fmt.Sprintf("bot_user = 'archie'\ndb_path = %q\ndatabase_url = %q\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n",
filepath.Join(dir, "archie.db"), url)
body := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n",
url)
if err := os.WriteFile(configPath, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
@@ -57,7 +57,7 @@ func TestRunStateStoreAcceptsEnvironmentToken(t *testing.T) {
t.Setenv("STATE_STORE_TOKEN", "environment-token")
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
data := fmt.Sprintf("bot_user = 'archie'\ndb_path = %q\ndatabase_url = %q\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n[[repos]]\nowner = 'acme'\nname = 'widget'\n", filepath.Join(dir, "state.db"), pgtest.URL(t))
data := fmt.Sprintf("bot_user = 'archie'\ndatabase_url = %q\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n[[repos]]\nowner = 'acme'\nname = 'widget'\n", pgtest.URL(t))
if err := os.WriteFile(path, []byte(data), 0o600); err != nil {
t.Fatal(err)
}
+1 -2
View File
@@ -167,7 +167,6 @@ func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) {
// the file rather than an in-memory or per-process store.
func TestStateStoreDataSurvivesRestart(t *testing.T) {
cfg := config.Config{
DBPath: filepath.Join(t.TempDir(), "archie"),
DatabaseURL: pgtest.URL(t),
}
@@ -208,7 +207,7 @@ func TestStateStoreDataSurvivesRestart(t *testing.T) {
// this would mean archie.db is opened by two processes at once.
func TestOpenStoresNeverOwnsTaskDB(t *testing.T) {
b := newBootstrap()
b.cfg = config.Config{DBPath: filepath.Join(t.TempDir(), "archie"), DatabaseURL: pgtest.URL(t)}
b.cfg = config.Config{DatabaseURL: pgtest.URL(t)}
if err := b.openStores(t.Context()); err != nil {
t.Fatalf("openStores: %v", err)
}
+2 -6
View File
@@ -441,17 +441,13 @@ type Config struct {
// SecretEngineDir contains Yaegi secret-engine plugins. Built-in env and
// bws engines remain available when this is empty.
SecretEngineDir string `toml:"secret_engine_dir" yaml:"secret_engine_dir"`
// DBPath locates the legacy SQLite files ("<db_path>-tasks.sqlite",
// "-eda.sqlite", "-conversations.sqlite") for the one-time import and the
// boot gate that refuses to serve until it has run. Nothing else reads it.
DBPath string `toml:"db_path" yaml:"db_path"`
// StateDir is the host directory archie keeps non-database state in: the
// embedded NATS store and its endpoint file, the task-log registry, and
// the readiness disk probe's data target. Bootstrap-only.
StateDir string `toml:"state_dir" yaml:"state_dir"`
// DatabaseURL is the PostgreSQL connection URL the standalone State Store
// process opens at boot. It is bootstrap-only (the same class as db_path
// and work_dir): the pool is opened once, so a runtime change cannot take
// process opens at boot. It is bootstrap-only (the same class as
// state_dir and work_dir): the pool is opened once, so a runtime change cannot take
// effect, and it is refused by the runtime overlay. It has no default --
// an empty value is a startup error for the State Store, which fails
// closed rather than fall back to SQLite (the epic is Postgres-only).
-1
View File
@@ -1955,7 +1955,6 @@ const (
func configWithCanarySecrets() config.Config {
return config.Config{
WorkDir: "/work/archie",
DBPath: "/work/archie/archie.db",
BotUser: "archie-bot",
BotEmail: "archie@example.com",
Label: "archie",
@@ -224,7 +224,6 @@ func DefaultConfigPath() string {
func (l *Loader) applyGeneralDefaults(cfg *config.Config) {
cfg.SecretEngineDir = expandHomePath(cfg.SecretEngineDir)
cfg.WorkDir = expandHomePath(cfg.WorkDir)
cfg.DBPath = expandHomePath(cfg.DBPath)
cfg.StateDir = expandHomePath(cfg.StateDir)
cfg.Chat.Workspace = expandHomePath(cfg.Chat.Workspace)
// DatabaseURL has no default and is not path-expanded: it is a connection
@@ -235,9 +234,6 @@ func (l *Loader) applyGeneralDefaults(cfg *config.Config) {
if cfg.WorkDir == "" {
cfg.WorkDir = filepath.Join(l.dataHome(), "archie", "work")
}
if cfg.DBPath == "" {
cfg.DBPath = filepath.Join(l.dataHome(), "archie", "archie.db")
}
if cfg.StateDir == "" {
cfg.StateDir = filepath.Join(l.dataHome(), "archie")
}
@@ -1,15 +1,14 @@
package configuration
// DeniedKeys are the config keys the runtime overlay may never set, mapped
// to the reason shown to the operator. db_path is the daemon's own bootstrap
// path -- the daemon must read it before it can open the overlay store --
// and work_dir pins the whole working layout. Enforced at write time (the
// to the reason shown to the operator. database_url and state_dir are read
// before the overlay store can be opened, and work_dir pins the whole working
// layout. Enforced at write time (the
// API returns 4xx) and again in the overlay's Set, not silently dropped at
// read time. Owned here rather than in the overlay package so the webui
// config renderer can reference the policy without linking the overlay's
// SQLite store (archie-core-8cda.5.6).
var DeniedKeys = map[string]string{
"db_path": "required for bootstrap; cannot be changed at runtime",
"database_url": "required for bootstrap; cannot be changed at runtime",
"state_dir": "required for bootstrap; cannot be changed at runtime",
"work_dir": "pins the daemon's working layout; cannot be changed at runtime",
@@ -51,7 +51,6 @@ func TestLoadExpandsConfiguredHomePaths(t *testing.T) {
contents := `
bot_user = "widget"
work_dir = "~/archie/work"
db_path = "~/archie/archie.db"
state_dir = "~/archie/state"
[chat]
@@ -74,7 +73,6 @@ name = "app"
want string
}{
"work_dir": {got: cfg.WorkDir, want: filepath.Join(home, "archie", "work")},
"db_path": {got: cfg.DBPath, want: filepath.Join(home, "archie", "archie.db")},
"state_dir": {got: cfg.StateDir, want: filepath.Join(home, "archie", "state")},
"chat.workspace": {got: cfg.Chat.Workspace, want: filepath.Join(home, "archie", "workspace")},
}
@@ -87,15 +85,13 @@ name = "app"
}
}
// state_dir defaults to archie's directory under the data home, independent
// of db_path, which only locates legacy files for the one-time import.
// state_dir defaults to archie's directory under the data home.
func TestStateDirDefaultsToTheDataHome(t *testing.T) {
dataHome := t.TempDir()
t.Setenv("XDG_DATA_HOME", dataHome)
path := filepath.Join(t.TempDir(), "config.toml")
contents := `
bot_user = "widget"
db_path = "/elsewhere/archie.db"
[[repos]]
owner = "acme"
@@ -1,157 +0,0 @@
// 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)
}
}
@@ -1,394 +0,0 @@
// Package legacyimport moves an existing install's SQLite stores (the State
// Store's task database, the PocketBase event store and the Gateway
// conversation store) into Postgres, once.
//
// The import is one transaction: it refuses a target that already holds data
// in a domain it imports, refuses rather than skips a row the target cannot
// hold, verifies what it wrote against what it read, and only then records a
// completion row and commits. A refusal at any point leaves the target as it
// was, migrated and empty, so a failed import is never serveable.
//
// It reads through legacyread, which never writes to the source files, and is
// deleted together with it.
package legacyimport
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"maps"
"os"
"slices"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/infrastructure/legacyread"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// ErrRefused wraps every refusal. The message names each offending table,
// row, value and rule.
var ErrRefused = errors.New("legacy import refused")
// Sources are the legacy files. A path whose file does not exist means that
// domain has nothing to import.
type Sources struct {
StateStore string
EDA string
Gateway string
}
type domain struct {
name string
path string
tables []legacyread.Table
}
func (s Sources) domains() []domain {
return []domain{
{"state-store", s.StateStore, legacyread.StateStoreTables},
{"eda", s.EDA, legacyread.EDATables},
{"gateway", s.Gateway, legacyread.GatewayTables},
}
}
// present returns the domains whose source file exists.
func (s Sources) present() ([]domain, error) {
var out []domain
for _, d := range s.domains() {
if d.path == "" {
continue
}
_, err := os.Stat(d.path)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, fmt.Errorf("legacy import: %w", err)
}
out = append(out, d)
}
return out, nil
}
// HasLegacyData reports whether any legacy source holds a row. With
// postgres.ImportComplete it is what decides whether a Postgres database may
// serve: legacy data without a completed import must be refused.
func HasLegacyData(ctx context.Context, src Sources) (bool, error) {
for _, d := range src.domains() {
if d.path == "" {
continue
}
has, err := legacyread.HasData(ctx, d.path, d.tables)
if err != nil || has {
return has, err
}
}
return false, nil
}
// Report is what an import wrote.
type Report struct {
// Rows is each imported table's row count.
Rows map[string]int
// UnindexedMessages are Gateway message ids the source's FTS5 index did
// not cover. The target derives its search column from every row, so
// these become searchable; the count says the source index was stale.
UnindexedMessages []string
}
func (r Report) String() string {
var b strings.Builder
for _, table := range slices.Sorted(maps.Keys(r.Rows)) {
fmt.Fprintf(&b, "%s=%d ", table, r.Rows[table])
}
fmt.Fprintf(&b, "unindexed_messages=%d", len(r.UnindexedMessages))
return b.String()
}
// refusal collects every problem found before giving up, so an operator fixes
// a source in one pass rather than one row per attempt.
type refusal []string
func (r *refusal) add(format string, args ...any) { *r = append(*r, fmt.Sprintf(format, args...)) }
func (r *refusal) err() error {
if len(*r) == 0 {
return nil
}
return fmt.Errorf("%w:\n %s", ErrRefused, strings.Join(*r, "\n "))
}
// Import runs the one-time import from src into the database behind pool.
// Every service that serves the database must be stopped: the import holds
// each service's ownership claim for its whole run and refuses if any is
// taken.
func Import(ctx context.Context, pool *pgxpool.Pool, src Sources) (Report, error) {
present, err := src.present()
if err != nil {
return Report{}, err
}
if len(present) == 0 {
return Report{}, fmt.Errorf("%w: no legacy source files found (%s, %s, %s)", ErrRefused, src.StateStore, src.EDA, src.Gateway)
}
before, err := hashSources(present)
if err != nil {
return Report{}, err
}
if err := postgres.Migrate(ctx, pool, postgres.Migrations()); err != nil {
return Report{}, err
}
release, err := claimServices(ctx, pool)
defer release()
if err != nil {
return Report{}, err
}
sources, closeSources, err := openSources(ctx, present)
defer closeSources()
if err != nil {
return Report{}, err
}
var problems refusal
if err := checkSources(ctx, sources, &problems); err != nil {
return Report{}, err
}
if err := problems.err(); err != nil {
return Report{}, err
}
tx, err := pool.Begin(ctx)
if err != nil {
return Report{}, fmt.Errorf("legacy import: begin: %w", err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
report, err := importInto(ctx, tx, present, sources, &problems)
if err != nil {
return Report{}, err
}
if err := checkUnchanged(before, present, &problems); err != nil {
return Report{}, err
}
if err := problems.err(); err != nil {
return Report{}, err
}
if err := complete(ctx, tx, present, report); err != nil {
return Report{}, err
}
return report, nil
}
// checkUnchanged refuses when a source's bytes moved during the import: a
// writer that was not stopped would leave the target short of its last writes.
func checkUnchanged(before map[string][32]byte, present []domain, problems *refusal) error {
after, err := hashSources(present)
if err != nil {
return err
}
for path, sum := range before {
if after[path] != sum {
problems.add("%s changed while it was read: stop the process writing it and import again", path)
}
}
return nil
}
// complete writes the completion record and commits, so the record exists
// exactly when the imported rows do.
func complete(ctx context.Context, tx pgx.Tx, present []domain, report Report) error {
paths := make([]string, len(present))
for i, d := range present {
paths[i] = d.path
}
if err := postgresdb.New(tx).InsertImportCompletion(ctx, postgresdb.InsertImportCompletionParams{
Sources: strings.Join(paths, "\n"),
Report: report.String(),
}); err != nil {
return fmt.Errorf("legacy import: completion record: %w", err)
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("legacy import: commit: %w", err)
}
return nil
}
// claimServices takes every service's ownership claim without waiting. The
// returned release is safe to call whether or not the claims were taken.
func claimServices(ctx context.Context, pool *pgxpool.Pool) (func(), error) {
var claims []*postgres.Ownership
release := func() {
for _, c := range claims {
_ = c.Release(context.WithoutCancel(ctx))
}
}
for _, name := range []string{postgres.OwnerStateStore, postgres.OwnerGateway} {
claim, err := postgres.AcquireOwnership(ctx, pool, name)
if err != nil {
return release, fmt.Errorf("legacy import: stop every Archie service first: %w", err)
}
claims = append(claims, claim)
}
return release, nil
}
// openSources opens each present source read-only, keyed by domain name.
func openSources(ctx context.Context, present []domain) (map[string]*legacyread.Source, func(), error) {
sources := map[string]*legacyread.Source{}
closeAll := func() {
for _, s := range sources {
_ = s.Close()
}
}
for _, d := range present {
s, err := legacyread.Open(ctx, d.path)
if err != nil {
return nil, closeAll, err
}
sources[d.name] = s
}
return sources, closeAll, nil
}
// importInto loads and verifies every present domain inside tx, adding to
// problems anything that must stop the commit.
func importInto(ctx context.Context, tx pgx.Tx, present []domain, sources map[string]*legacyread.Source, problems *refusal) (Report, error) {
if err := checkTarget(ctx, tx, present, problems); err != nil {
return Report{}, err
}
if err := problems.err(); err != nil {
return Report{}, err
}
report := Report{Rows: map[string]int{}}
var loaded []loadedTable
for _, d := range present {
for _, t := range d.tables {
lt, err := load(ctx, tx, sources[d.name], t, problems)
if err != nil {
return Report{}, err
}
loaded = append(loaded, lt)
report.Rows[t.Name] = len(lt.keys)
}
}
if err := problems.err(); err != nil {
return Report{}, err
}
for _, lt := range loaded {
if err := verify(ctx, tx, lt, problems); err != nil {
return Report{}, err
}
}
// Sources are derived, not imported: the migration derived them from an
// empty target, so derive again from what was just loaded.
if sources["eda"] != nil {
if err := postgresdb.New(tx).DeriveSources(ctx); err != nil {
return Report{}, fmt.Errorf("legacy import: derive sources: %w", err)
}
}
if gw := sources["gateway"]; gw != nil {
var err error
if report.UnindexedMessages, err = unindexedMessages(ctx, gw, loaded); err != nil {
return Report{}, err
}
}
return report, nil
}
// hashSources fingerprints each source and its WAL, so a writer that was not
// stopped is caught rather than assumed away.
func hashSources(present []domain) (map[string][32]byte, error) {
out := map[string][32]byte{}
for _, d := range present {
for _, path := range []string{d.path, d.path + "-wal"} {
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) && path != d.path {
continue
}
if err != nil {
return nil, fmt.Errorf("legacy import: %w", err)
}
h := sha256.New()
_, err = io.Copy(h, f)
_ = f.Close()
if err != nil {
return nil, fmt.Errorf("legacy import: hash %s: %w", path, err)
}
out[path] = [32]byte(h.Sum(nil))
}
}
return out, nil
}
// checkSources finds the source rows Postgres would reject or reorder.
func checkSources(ctx context.Context, sources map[string]*legacyread.Source, problems *refusal) error {
if s := sources["state-store"]; s != nil {
for _, fk := range legacyread.IdentityForeignKeys {
orphans, err := s.Orphans(ctx, fk)
if err != nil {
return err
}
for _, o := range orphans {
problems.add("%s %s: %s %q has no row in %s (foreign key)", fk.Table, o.Key, fk.Column, o.Parent, fk.Parent)
}
}
aliases, err := s.DuplicateAliases(ctx)
if err != nil {
return err
}
for _, d := range aliases {
problems.add("identity_aliases %s: aliases collide on unique lower(alias) %q", strings.Join(d.Values, ", "), d.Key)
}
collisions, err := s.MicrosecondCollisions(ctx)
if err != nil {
return err
}
for _, c := range collisions {
problems.add("events %d and %d: at differs only below a microsecond (%s) while ids run the other way, so (at, id) order would change",
c.EarlierID, c.LaterID, c.At.Format("2006-01-02T15:04:05.000000Z"))
}
}
if s := sources["eda"]; s != nil {
dups, err := s.DuplicateBindings(ctx)
if err != nil {
return err
}
for _, d := range dups {
problems.add("bindings %s: more than one binding for source %q (unique source); resolve them and import again",
strings.Join(d.Values, ", "), d.Key)
}
}
return nil
}
// checkTarget refuses a database that already completed an import, or that
// holds rows in a table owned by a domain being imported. The check is an
// allowlist of those tables, so goose's version table and other domains'
// tables never count.
func checkTarget(ctx context.Context, tx pgx.Tx, present []domain, problems *refusal) error {
done, err := postgresdb.New(tx).ImportCompleted(ctx)
if err != nil {
return fmt.Errorf("legacy import: completion record: %w", err)
}
if done {
problems.add("this database already holds a completed import")
return nil
}
for _, d := range present {
for _, t := range d.tables {
var rows bool
if err := tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM "+pgx.Identifier{t.Name}.Sanitize()+")").Scan(&rows); err != nil {
return fmt.Errorf("legacy import: %s: %w", t.Name, err)
}
if rows {
problems.add("%s is not empty: the %s target already holds data", t.Name, d.name)
}
}
}
return nil
}
@@ -1,375 +0,0 @@
package legacyimport
import (
"bytes"
"crypto/sha256"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"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)) }
// 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()
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":
legacyfixture.Exec(t, src.StateStore, stmt)
case "eda":
legacyfixture.Exec(t, src.EDA, stmt)
case "gateway":
legacyfixture.Exec(t, src.Gateway, stmt)
}
}
return src
}
func hashFiles(t *testing.T, dir string) map[string][32]byte {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read dir: %v", err)
}
out := map[string][32]byte{}
for _, e := range entries {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
t.Fatalf("read %s: %v", e.Name(), err)
}
out[e.Name()] = sha256.Sum256(b)
}
return out
}
func target(t *testing.T) *pgxpool.Pool {
t.Helper()
pool, err := postgres.Open(t.Context(), pgtest.URL(t))
if err != nil {
t.Fatalf("postgres.Open: %v", err)
}
t.Cleanup(pool.Close)
return pool
}
func migrated(t *testing.T) *pgxpool.Pool {
t.Helper()
pool := target(t)
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
t.Fatalf("Migrate: %v", err)
}
return pool
}
func count(t *testing.T, pool *pgxpool.Pool, table string) int {
t.Helper()
var n int
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM "+table).Scan(&n); err != nil {
t.Fatalf("count %s: %v", table, err)
}
return n
}
func TestImportCopiesEverySourceAndLeavesThemUntouched(t *testing.T) {
src := install(t, nil)
before := hashFiles(t, filepath.Dir(src.StateStore))
pool := target(t)
report, err := Import(t.Context(), pool, src)
if err != nil {
t.Fatalf("Import: %v", err)
}
if after := hashFiles(t, filepath.Dir(src.StateStore)); len(after) != len(before) {
t.Fatalf("source directory changed: %d files before, %d after", len(before), len(after))
} else {
for name, sum := range before {
if after[name] != sum {
t.Errorf("source %s changed during import", name)
}
}
}
done, err := postgres.ImportComplete(t.Context(), pool)
if err != nil || !done {
t.Fatalf("ImportComplete = %v, %v; want true", done, err)
}
counts := map[string]int{
"tasks": 2, "transitions": 1, "events": 3, "resources": 1, "resource_history": 1,
"channel_status": 1, "apply_status": 1, "config_snapshot": 1, "identities": 1,
"identity_aliases": 1, "identity_events": 1, "identity_subjects": 1,
"captures": 2, "mappings": 1, "bindings": 1, "binding_dispatches": 1, "playbook_dispatches": 1,
"tool_calls": 1, "sessions": 1, "messages": 2, "turns": 1,
}
for table, want := range counts {
if got := count(t, pool, table); got != want {
t.Errorf("%s rows = %d, want %d", table, got, want)
}
if got := report.Rows[table]; got != want {
t.Errorf("report rows[%s] = %d, want %d", table, got, want)
}
}
ctx := t.Context()
var (
reviewCursor int64
value []byte
gotSecret string
headers string
result string
configured bool
)
checks := []struct {
query string
dest any
}{
{"SELECT review_cursor FROM tasks WHERE id = 1", &reviewCursor},
{"SELECT value FROM resource_history WHERE id = 1", &value},
{"SELECT secret FROM sources WHERE path = 'gh'", &gotSecret},
{"SELECT headers FROM captures WHERE id = 'rcap2'", &headers},
{"SELECT result FROM tool_calls WHERE id = 'rtool1'", &result},
{"SELECT configured FROM channel_status WHERE id = 'tg'", &configured},
}
for _, c := range checks {
if err := pool.QueryRow(ctx, c.query).Scan(c.dest); err != nil {
t.Fatalf("%s: %v", c.query, err)
}
}
if reviewCursor != 3 {
t.Errorf("review_cursor = %d, want 3", reviewCursor)
}
if !bytes.Equal(value, []byte{0x00, 0xff, 0x10}) {
t.Errorf("resource_history.value = %x, want 00ff10", value)
}
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)
}
// Event order is (at, id) as the source had it, and the next event id
// follows AUTOINCREMENT's high-water mark rather than reusing one.
rows, err := pool.Query(ctx, "SELECT id FROM events ORDER BY at, id")
if err != nil {
t.Fatalf("events: %v", err)
}
var order []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
t.Fatalf("scan: %v", err)
}
order = append(order, id)
}
if want := []int64{1, 5, 2}; !equalInts(order, want) {
t.Errorf("event order = %v, want %v", order, want)
}
nextIDs := map[string]int64{"tasks": 10, "events": 6, "messages": 3}
for table, want := range nextIDs {
var got int64
if err := pool.QueryRow(ctx, "SELECT nextval(pg_get_serial_sequence($1, 'id'))", table).Scan(&got); err != nil {
t.Fatalf("nextval %s: %v", table, err)
}
if got != want {
t.Errorf("next %s id = %d, want %d", table, got, want)
}
}
var hits int
if err := pool.QueryRow(ctx, "SELECT count(*) FROM messages WHERE search @@ to_tsquery('simple', 'hello')").Scan(&hits); err != nil {
t.Fatalf("search: %v", err)
}
if hits != 1 {
t.Errorf("search hits for an imported message = %d, want 1", hits)
}
}
func equalInts(a, b []int64) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func TestImportRefuses(t *testing.T) {
tests := []struct {
name string
mutate map[string]string
seed func(t *testing.T, pool *pgxpool.Pool)
want []string
is error
}{
{
name: "non-empty target",
seed: func(t *testing.T, pool *pgxpool.Pool) {
mustExec(t, pool, "INSERT INTO transitions (task_id, from_status, to_status) VALUES (1, 'a', 'b')")
},
want: []string{"transitions", "not empty"},
},
{
name: "completed import",
seed: func(t *testing.T, pool *pgxpool.Pool) {
mustExec(t, pool, "INSERT INTO import_completion (id, sources, report) VALUES (1, 's', 'r')")
},
want: []string{"already"},
},
{
name: "live state store",
seed: func(t *testing.T, pool *pgxpool.Pool) { holdOwnership(t, pool, postgres.OwnerStateStore) },
want: []string{"state-store"},
is: postgres.ErrOwned,
},
{
name: "live gateway",
seed: func(t *testing.T, pool *pgxpool.Pool) { holdOwnership(t, pool, postgres.OwnerGateway) },
want: []string{"gateway"},
is: postgres.ErrOwned,
},
{
name: "orphaned alias",
mutate: map[string]string{"state": "INSERT INTO identity_aliases VALUES ('ghost', 'id-404')"},
want: []string{"identity_aliases", "ghost", "id-404"},
},
{
name: "duplicate bindings",
mutate: map[string]string{"eda": "INSERT INTO bindings VALUES ('rbind2', '2026-01-01 00:00:00.000Z', '', 'b2', 'o', 'r', '', 'gh', 'pending_approval', '2026-01-01 00:00:00.000Z', 1, 'implement')"},
want: []string{"bindings", "gh", "rbind1", "rbind2"},
},
{
name: "microsecond collision",
mutate: map[string]string{"state": "INSERT INTO events (id, at, kind) VALUES (7, '2026-01-01T00:00:00.000000050Z', 'd')"},
want: []string{"events", "7", "microsecond"},
},
{
name: "unparseable timestamp",
mutate: map[string]string{"eda": "UPDATE captures SET received_at = 'yesterday' WHERE id = 'rcap2'"},
want: []string{"captures", "rcap2", "yesterday", "received_at"},
},
{
name: "null in a required column",
mutate: map[string]string{"state": "UPDATE tasks SET title = NULL WHERE id = 4"},
want: []string{"tasks", "4", "title", "NULL"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
src := install(t, tt.mutate)
pool := migrated(t)
if tt.seed != nil {
tt.seed(t, pool)
}
_, err := Import(t.Context(), pool, src)
if err == nil {
t.Fatal("Import succeeded, want a refusal")
}
if tt.is != nil && !errors.Is(err, tt.is) {
t.Errorf("Import error %v, want %v", err, tt.is)
}
for _, w := range tt.want {
if !strings.Contains(err.Error(), w) {
t.Errorf("refusal %q does not name %q", err, w)
}
}
// Nothing of the import survives a refusal: the store stays
// unserveable rather than half-imported.
if got := count(t, pool, "tasks"); got != 0 {
t.Errorf("tasks rows after refusal = %d, want 0", got)
}
if got := count(t, pool, "import_completion"); tt.name != "completed import" && got != 0 {
t.Errorf("completion records after refusal = %d, want 0", got)
}
})
}
}
func mustExec(t *testing.T, pool *pgxpool.Pool, stmt string) {
t.Helper()
if _, err := pool.Exec(t.Context(), stmt); err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
// holdOwnership claims name from a separate pool, as a live service would.
func holdOwnership(t *testing.T, pool *pgxpool.Pool, name string) {
t.Helper()
other, err := pgxpool.New(t.Context(), pool.Config().ConnString())
if err != nil {
t.Fatalf("second pool: %v", err)
}
t.Cleanup(other.Close)
claim, err := postgres.AcquireOwnership(t.Context(), other, name)
if err != nil {
t.Fatalf("claim %s: %v", name, err)
}
t.Cleanup(func() { _ = claim.Release(t.Context()) })
}
// TestSiblingDomainDoesNotBlock pins that "non-empty" is per domain: a
// domain with no legacy source is not imported, so rows in its tables do not
// refuse the others.
func TestSiblingDomainDoesNotBlock(t *testing.T) {
src := install(t, nil)
src.Gateway = filepath.Join(t.TempDir(), "absent.sqlite")
pool := migrated(t)
mustExec(t, pool, "INSERT INTO sessions (session_id) VALUES ('live')")
if _, err := Import(t.Context(), pool, src); err != nil {
t.Fatalf("Import: %v", err)
}
if got := count(t, pool, "tasks"); got != 2 {
t.Fatalf("tasks rows = %d, want 2", got)
}
}
func TestImportRefusesWithNoSources(t *testing.T) {
dir := t.TempDir()
src := Sources{StateStore: filepath.Join(dir, "a"), EDA: filepath.Join(dir, "b"), Gateway: filepath.Join(dir, "c")}
if _, err := Import(t.Context(), migrated(t), src); err == nil || !strings.Contains(err.Error(), "no legacy") {
t.Fatalf("Import = %v, want a refusal naming no legacy sources", err)
}
}
func TestHasLegacyData(t *testing.T) {
dir := t.TempDir()
absent := Sources{StateStore: filepath.Join(dir, "a"), EDA: filepath.Join(dir, "b"), Gateway: filepath.Join(dir, "c")}
onlyGateway := absent
onlyGateway.Gateway = install(t, nil).Gateway
tests := []struct {
name string
src Sources
want bool
}{
{"fresh install", absent, false},
{"one source with rows", onlyGateway, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := HasLegacyData(t.Context(), tt.src)
if err != nil {
t.Fatalf("HasLegacyData: %v", err)
}
if got != tt.want {
t.Fatalf("HasLegacyData = %v, want %v", got, tt.want)
}
})
}
}
@@ -1,307 +0,0 @@
package legacyimport
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/infrastructure/legacyread"
)
// droppedColumns are legacy columns with no target column by design:
// PocketBase gave every ledger row a random record id, and the Postgres
// ledgers are keyed by their natural unique key instead.
var droppedColumns = map[string]bool{
"binding_dispatches.id": true,
"playbook_dispatches.id": true,
}
// newColumns are target columns added after the legacy stores, with no
// legacy value to carry; an imported row takes the column default. An
// imported capture has no event type, so it stays unidentified and never
// dispatches, and no legacy source could take unsigned events. An imported
// mapping has no event type, so no binding using it dispatches until it is
// given one, and an imported binding has no filter. Nor does an imported
// binding assign workflow inputs or read its repository from a parameter,
// and no legacy task carries inputs.
var newColumns = map[string]bool{
"captures.event_type": true,
"mappings.event_type": true,
"bindings.filter": true,
"captures.unsigned": true,
"bindings.inputs": true,
"bindings.repo_param": true,
"tasks.inputs": true,
}
// targetKeys override a table's legacy key where the target has no column
// for it.
var targetKeys = map[string][]string{
"binding_dispatches": {"binding", "capture"},
"playbook_dispatches": {"playbook_id", "playbook_version", "event_id", "action_id"},
}
// jsonColumns are PocketBase JSON fields, which may be NULL in the source and
// map to a NOT NULL text column defaulting to the empty string. unwrap marks the fields the legacy reader
// decoded from a JSON string (jsonTextToString) rather than returning raw.
var jsonColumns = map[string]struct{ unwrap bool }{
"captures.headers": {},
"mappings.fields": {},
"tool_calls.args": {unwrap: true},
"tool_calls.result": {unwrap: true},
}
// timeLayouts are every layout a legacy timestamp was written in: the
// fixed-width cursor layout, Go's RFC 3339 forms, PocketBase's autodate
// layout and SQLite's datetime('now').
var timeLayouts = []string{
"2006-01-02T15:04:05.000000000Z",
time.RFC3339Nano,
time.RFC3339,
"2006-01-02 15:04:05.999999999Z07:00",
"2006-01-02 15:04:05.999999999",
}
type column struct {
name string
dataType string
identity bool
source int // index into the legacy row
}
// loadedTable is what load wrote, for verify to check.
type loadedTable struct {
table legacyread.Table
rows legacyread.Rows
keys []string // target keys of the rows written, in source read order
keyCols []string
identity bool
}
// load reads t from src, converts every row to the target's types and copies
// them in with their historical ids. A row it cannot convert is added to
// problems and nothing of the table is written.
func load(ctx context.Context, tx pgx.Tx, src *legacyread.Source, t legacyread.Table, problems *refusal) (loadedTable, error) {
cols, err := plan(ctx, tx, t, problems)
if err != nil || cols == nil {
return loadedTable{table: t}, err
}
rows, err := src.Read(ctx, t)
if err != nil {
return loadedTable{}, err
}
lt := loadedTable{table: t, rows: rows, keyCols: t.Key}
if k, ok := targetKeys[t.Name]; ok {
lt.keyCols = k
}
names := make([]string, len(cols))
for i, c := range cols {
names[i] = c.name
lt.identity = lt.identity || c.identity
}
out, ok := convertRows(lt, cols, names, problems)
if !ok {
return lt, nil
}
for _, row := range out {
key := make([]string, len(lt.keyCols))
for j, k := range lt.keyCols {
key[j] = fmt.Sprint(row[slices.Index(names, k)])
}
lt.keys = append(lt.keys, strings.Join(key, "/"))
}
if len(out) > 0 {
if _, err := tx.CopyFrom(ctx, pgx.Identifier{t.Name}, names, pgx.CopyFromRows(out)); err != nil {
problems.add("%s: the target rejected the rows: %v", t.Name, err)
return lt, nil
}
}
if lt.identity {
return lt, advanceSequence(ctx, tx, src, t.Name)
}
return lt, nil
}
// convertRows converts every row of lt, adding each value it cannot convert
// to problems.
func convertRows(lt loadedTable, cols []column, names []string, problems *refusal) ([][]any, bool) {
sourceKeys := lt.rows.Keys()
out := make([][]any, 0, len(lt.rows.Rows))
ok := true
for i, row := range lt.rows.Rows {
converted := make([]any, len(cols))
for j, c := range cols {
v, err := convert(lt.table.Name+"."+c.name, c.dataType, row[c.source])
if err != nil {
problems.add("%s %s: column %s value %s: %v", lt.table.Name, sourceKeys[i], names[j], quote(row[c.source]), err)
ok = false
}
converted[j] = v
}
out = append(out, converted)
}
return out, ok
}
// advanceSequence sets table's identity sequence to hand out the id the
// legacy AUTOINCREMENT would have, even for a table whose rows were all
// deleted. is_called = false makes that id the next one, which keeps
// AUTOINCREMENT's promise that a deleted top id is never reused.
func advanceSequence(ctx context.Context, tx pgx.Tx, src *legacyread.Source, table string) error {
seq, err := src.SequenceOf(ctx, table)
if err != nil {
return err
}
if _, err := tx.Exec(ctx, "SELECT setval(pg_get_serial_sequence($1, 'id'), $2, false)", table, seq.Next); err != nil {
return fmt.Errorf("legacy import: advance %s sequence: %w", table, err)
}
return nil
}
// plan matches the target table's columns to the legacy ones. A column on
// either side with no counterpart is a schema gap the import refuses to
// guess about; it returns nil columns then.
func plan(ctx context.Context, tx pgx.Tx, t legacyread.Table, problems *refusal) ([]column, error) {
rows, err := tx.Query(ctx, `SELECT column_name, data_type, is_identity = 'YES'
FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = $1 AND is_generated = 'NEVER'
ORDER BY ordinal_position`, t.Name)
if err != nil {
return nil, fmt.Errorf("legacy import: %s columns: %w", t.Name, err)
}
cols, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (column, error) {
var c column
err := row.Scan(&c.name, &c.dataType, &c.identity)
return c, err
})
if err != nil {
return nil, fmt.Errorf("legacy import: %s columns: %w", t.Name, err)
}
gap := len(cols) == 0
if gap {
problems.add("%s: no target table", t.Name)
}
targetNames := map[string]bool{}
cols = slices.DeleteFunc(cols, func(c column) bool { return newColumns[t.Name+"."+c.name] })
for i := range cols {
targetNames[cols[i].name] = true
cols[i].source = slices.Index(t.Columns, cols[i].name)
if cols[i].source < 0 {
problems.add("%s.%s: the target column has no legacy column", t.Name, cols[i].name)
gap = true
}
}
for _, c := range t.Columns {
if !targetNames[c] && !droppedColumns[t.Name+"."+c] {
problems.add("%s.%s: the legacy column has no target column", t.Name, c)
gap = true
}
}
if gap {
return nil, nil
}
return cols, nil
}
// convert maps one SQLite value to the Go value pgx writes to a column of
// dataType. It never coerces: a value the column cannot hold is an error
// naming the rule it breaks.
func convert(qualified, dataType string, v any) (any, error) {
if j, ok := jsonColumns[qualified]; ok {
return convertJSON(v, j.unwrap)
}
if v == nil {
return nil, fmt.Errorf("NULL in a NOT NULL %s column", dataType)
}
conv, ok := converters[dataType]
if !ok {
return nil, fmt.Errorf("unsupported target type %s", dataType)
}
return conv(v)
}
func convertJSON(v any, unwrap bool) (any, error) {
switch s := v.(type) {
case nil:
return "", nil
case string:
if unwrap {
var decoded string
if json.Unmarshal([]byte(s), &decoded) == nil {
return decoded, nil
}
}
return s, nil
}
return nil, errors.New("text: not a string")
}
// converters are keyed by information_schema data_type.
var converters = map[string]func(any) (any, error){
"text": func(v any) (any, error) {
if s, ok := v.(string); ok {
return s, nil
}
return nil, errors.New("text: not a string")
},
"bigint": func(v any) (any, error) {
switch n := v.(type) {
case int64:
return n, nil
case float64:
if n == math.Trunc(n) && math.Abs(n) < 1<<63 {
return int64(n), nil
}
}
return nil, errors.New("bigint: not an integer")
},
"boolean": func(v any) (any, error) {
switch b := v.(type) {
case bool:
return b, nil
case int64:
if b == 0 || b == 1 {
return b == 1, nil
}
}
return nil, errors.New("boolean: not 0 or 1")
},
"bytea": func(v any) (any, error) {
switch b := v.(type) {
case []byte:
return b, nil
case string:
return []byte(b), nil
}
return nil, errors.New("bytea: not a blob")
},
"timestamp with time zone": func(v any) (any, error) {
if s, ok := v.(string); ok {
for _, layout := range timeLayouts {
if at, err := time.Parse(layout, s); err == nil {
return at.UTC(), nil
}
}
}
return nil, errors.New("timestamptz: not a timestamp in any legacy layout")
},
}
func quote(v any) string {
switch s := v.(type) {
case nil:
return "NULL"
case string:
return fmt.Sprintf("%q", s)
case []byte:
return fmt.Sprintf("x'%x'", s)
}
return fmt.Sprint(v)
}
@@ -1,171 +0,0 @@
package legacyimport
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/infrastructure/legacyread"
)
// blobColumns are the columns whose bytes must survive exactly: resource
// documents, and binding secrets, which stay decryptable by the configured
// keyring only if the envelope is untouched.
var blobColumns = map[string]string{
"resources": "value",
"resource_history": "value",
"bindings": "secret",
}
// verify reads back what load wrote for lt and compares it with the source:
// the key set (a count passes on a swallowed row when ids have gaps), the
// (at, id) event order, blob bytes and the identity sequence.
func verify(ctx context.Context, tx pgx.Tx, lt loadedTable, problems *refusal) error {
name := lt.table.Name
ident := pgx.Identifier{name}.Sanitize()
keyExprs := make([]string, len(lt.keyCols))
for i, k := range lt.keyCols {
keyExprs[i] = pgx.Identifier{k}.Sanitize() + "::text"
}
keyExpr := "concat_ws('/', " + strings.Join(keyExprs, ", ") + ")"
targetKeys, err := strs(ctx, tx, "SELECT "+keyExpr+" FROM "+ident)
if err != nil {
return fmt.Errorf("legacy import: verify %s: %w", name, err)
}
if len(targetKeys) != len(lt.keys) {
problems.add("%s: %d rows read, %d rows in the target", name, len(lt.keys), len(targetKeys))
}
if d := legacyread.CompareKeys(lt.keys, targetKeys); len(d.Missing)+len(d.Extra) > 0 {
problems.add("%s: rows missing from the target %v, rows only in the target %v", name, d.Missing, d.Extra)
}
if name == "events" {
if err := verifyEventOrder(ctx, tx, lt, problems); err != nil {
return err
}
}
if col, ok := blobColumns[name]; ok {
if err := verifyBlobs(ctx, tx, lt, col, keyExpr, problems); err != nil {
return err
}
}
if lt.identity {
return verifySequence(ctx, tx, name, problems)
}
return nil
}
// verifySequence asserts the next id the sequence hands out is above every
// imported id, reading its state rather than calling nextval.
func verifySequence(ctx context.Context, tx pgx.Tx, name string, problems *refusal) error {
var seq string
var maxID int64
if err := tx.QueryRow(ctx, "SELECT pg_get_serial_sequence($1, 'id'), (SELECT COALESCE(max(id), 0) FROM "+
pgx.Identifier{name}.Sanitize()+")", name).Scan(&seq, &maxID); err != nil {
return fmt.Errorf("legacy import: verify %s sequence: %w", name, err)
}
var (
last int64
called bool
)
// seq comes from pg_get_serial_sequence, which returns it quoted.
if err := tx.QueryRow(ctx, "SELECT last_value, is_called FROM "+seq).Scan(&last, &called); err != nil {
return fmt.Errorf("legacy import: verify %s sequence: %w", name, err)
}
next := last
if called {
next++
}
if next <= maxID {
problems.add("%s: next id %d would reuse an imported id (max %d)", name, next, maxID)
}
return nil
}
// verifyEventOrder compares the ids in (at, id) order on both sides. The
// source was read in that order; a difference means microsecond storage
// reordered history, and a cursor reader would skip a row.
func verifyEventOrder(ctx context.Context, tx pgx.Tx, lt loadedTable, problems *refusal) error {
source := make([]int64, len(lt.keys))
for i, k := range lt.keys {
id, err := strconv.ParseInt(k, 10, 64)
if err != nil {
return fmt.Errorf("legacy import: event key %q: %w", k, err)
}
source[i] = id
}
rows, err := tx.Query(ctx, "SELECT id FROM events ORDER BY at, id")
if err != nil {
return fmt.Errorf("legacy import: verify events order: %w", err)
}
target, err := pgx.CollectRows(rows, pgx.RowTo[int64])
if err != nil {
return fmt.Errorf("legacy import: verify events order: %w", err)
}
if d := legacyread.CompareOrder(source, target); d != nil {
problems.add("events: (at, id) order differs at position %d: source id %d, target id %d", d.Position, d.Source, d.Target)
}
return nil
}
func verifyBlobs(ctx context.Context, tx pgx.Tx, lt loadedTable, col, keyExpr string, problems *refusal) error {
source := map[string][]byte{}
for i, k := range lt.keys {
switch v := lt.rows.Value(i, col).(type) {
case []byte:
source[k] = v
case string:
source[k] = []byte(v)
}
}
rows, err := tx.Query(ctx, fmt.Sprintf("SELECT %s, %s FROM %s", keyExpr,
pgx.Identifier{col}.Sanitize(), pgx.Identifier{lt.table.Name}.Sanitize()))
if err != nil {
return fmt.Errorf("legacy import: verify %s.%s: %w", lt.table.Name, col, err)
}
target := map[string][]byte{}
for rows.Next() {
var (
k string
v []byte
)
if err := rows.Scan(&k, &v); err != nil {
rows.Close()
return fmt.Errorf("legacy import: verify %s.%s: %w", lt.table.Name, col, err)
}
target[k] = v
}
if err := rows.Err(); err != nil {
return fmt.Errorf("legacy import: verify %s.%s: %w", lt.table.Name, col, err)
}
if diff := legacyread.CompareBlobs(source, target); len(diff) > 0 {
problems.add("%s.%s: bytes differ from the source for %v", lt.table.Name, col, diff)
}
return nil
}
// unindexedMessages returns the source message ids the FTS5 index missed.
func unindexedMessages(ctx context.Context, gw *legacyread.Source, loaded []loadedTable) ([]string, error) {
indexed, err := gw.IndexedMessageIDs(ctx)
if err != nil {
return nil, err
}
for _, lt := range loaded {
if lt.table.Name == "messages" {
return legacyread.CompareKeys(indexed, lt.keys).Extra, nil
}
}
return nil, nil
}
func strs(ctx context.Context, tx pgx.Tx, query string) ([]string, error) {
rows, err := tx.Query(ctx, query)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowTo[string])
}
@@ -1,139 +0,0 @@
// Package legacyread reads an existing install's SQLite stores (the State
// Store's archie.db, the PocketBase event store and the Gateway conversation
// store) for the one-time import into Postgres, and verifies what was read.
//
// Every production opener of those files writes on open (schema migrations,
// PocketBase bootstrap, DDL and backfills), so this package never imports
// them: it opens each file read-only and issues only SELECT. It knows nothing
// about Postgres; values come back as the SQLite driver's native types
// (int64, float64, string, []byte, nil) under their legacy column names.
//
// The package exists only for the import and is deleted with it.
package legacyread
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"strings"
_ "modernc.org/sqlite"
)
// Source is one legacy SQLite file opened read-only. The process that owns
// the file must be stopped: a read-only open cannot checkpoint a WAL.
type Source struct {
db *sql.DB
}
// Open opens path read-only. It refuses a path that does not exist rather
// than letting SQLite create an empty database there.
func Open(ctx context.Context, path string) (*Source, error) {
if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf("legacyread: %w", err)
}
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
return nil, fmt.Errorf("legacyread: open %s: %w", path, err)
}
if err := db.PingContext(ctx); err != nil {
return nil, errors.Join(fmt.Errorf("legacyread: open %s: %w", path, err), db.Close())
}
return &Source{db: db}, nil
}
// Close closes the source.
func (s *Source) Close() error { return s.db.Close() }
// Table names one legacy table: its columns as the production code leaves
// them (columns added by ALTER TABLE included), the columns that identify a
// row, and the order it is read in.
type Table struct {
Name string
Columns []string
Key []string
OrderBy string
}
// Rows is one table's contents in read order.
type Rows struct {
Table Table
Rows [][]any
}
// Value returns column col of row i, or nil for an unknown column.
func (r Rows) Value(i int, col string) any {
for j, c := range r.Table.Columns {
if c == col {
return r.Rows[i][j]
}
}
return nil
}
// Keys returns each row's key, its key columns joined with "/", in read order.
func (r Rows) Keys() []string {
keys := make([]string, len(r.Rows))
for i := range r.Rows {
parts := make([]string, len(r.Table.Key))
for j, col := range r.Table.Key {
parts[j] = fmt.Sprint(r.Value(i, col))
}
keys[i] = strings.Join(parts, "/")
}
return keys
}
// Read returns every row of t.
func (s *Source) Read(ctx context.Context, t Table) (Rows, error) {
query := "SELECT " + strings.Join(t.Columns, ", ") + " FROM " + t.Name + " ORDER BY " + t.OrderBy
rows, err := s.db.QueryContext(ctx, query)
if err != nil {
return Rows{}, fmt.Errorf("legacyread: read %s: %w", t.Name, err)
}
defer func() { _ = rows.Close() }()
out := Rows{Table: t}
for rows.Next() {
row := make([]any, len(t.Columns))
ptrs := make([]any, len(row))
for i := range row {
ptrs[i] = &row[i]
}
if err := rows.Scan(ptrs...); err != nil {
return Rows{}, fmt.Errorf("legacyread: read %s: %w", t.Name, err)
}
out.Rows = append(out.Rows, row)
}
if err := rows.Err(); err != nil {
return Rows{}, fmt.Errorf("legacyread: read %s: %w", t.Name, err)
}
return out, nil
}
// IndexedMessageIDs returns the message ids the Gateway's FTS5 search index
// holds. messages_fts is an external-content index derived from messages, so
// it is rebuilt on the target rather than copied; what the import must account
// for is whether it covered every message, which comparing this set against
// the messages ids answers.
func (s *Source) IndexedMessageIDs(ctx context.Context) ([]string, error) {
return s.strings(ctx, "SELECT CAST(id AS TEXT) FROM messages_fts_docsize ORDER BY id")
}
func (s *Source) strings(ctx context.Context, query string) ([]string, error) {
rows, err := s.db.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("legacyread: %w", err)
}
defer func() { _ = rows.Close() }()
var out []string
for rows.Next() {
var v string
if err := rows.Scan(&v); err != nil {
return nil, fmt.Errorf("legacyread: %w", err)
}
out = append(out, v)
}
return out, rows.Err()
}
@@ -1,449 +0,0 @@
package legacyread
import (
"crypto/sha256"
"database/sql"
"os"
"path/filepath"
"slices"
"testing"
)
// The fixtures below apply the legacy schemas as their production openers
// leave them, columns added by ALTER TABLE included, without importing those
// openers.
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) VALUES (1, 'o', 'r', 7, 3), (4, 'o', 'r', 1000000000000000, 0);
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) VALUES
(1, '2026-01-01T00:00:00.000000100Z', 'a'),
(2, '2026-01-01T00:00:01.000000000Z', 'b');
INSERT INTO resources VALUES ('config', X'00ff10', 2, '2026-01-01T00:00:00Z');
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');
`
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 mappings VALUES ('rmap1', '2026-01-01', '[]', 'm', 'gh', '2026-01-01');
INSERT INTO bindings VALUES ('rbind1', '2026-01-01', 'rmap1', 'b', 'o', 'r', 'plaintext-secret', 'gh', 'armed', '2026-01-01', 1, 'implement');
INSERT INTO binding_dispatches VALUES ('rdisp1', 'rbind1', 1, 'rcap1', '2026-01-01', 4);
INSERT INTO playbook_dispatches VALUES ('rpb1', 'act', '2026-01-01', 'ev', 'pb', 'v1');
INSERT INTO tool_calls VALUES ('rtool1', '{}', 1, '2026-01-01', 12, '', '{}', 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);
`
// fixture writes a legacy database built from ddl and returns its path. It
// is checkpointed into a single file so a hash covers all of its state.
func fixture(t *testing.T, name, ddl string) string {
t.Helper()
path := filepath.Join(t.TempDir(), name)
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(), ddl); err != nil {
t.Fatalf("apply fixture DDL: %v", err)
}
return path
}
func exec(t *testing.T, path, stmt string) {
t.Helper()
db, err := sql.Open("sqlite", "file:"+path)
if err != nil {
t.Fatalf("open: %v", err)
}
defer func() { _ = db.Close() }()
if _, err := db.ExecContext(t.Context(), stmt); err != nil {
t.Fatalf("exec %q: %v", stmt, err)
}
}
func hashDir(t *testing.T, dir string) map[string][32]byte {
t.Helper()
sums := map[string][32]byte{}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read dir: %v", err)
}
for _, e := range entries {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
t.Fatalf("read %s: %v", e.Name(), err)
}
sums[e.Name()] = sha256.Sum256(b)
}
return sums
}
func openSource(t *testing.T, path string) *Source {
t.Helper()
src, err := Open(t.Context(), path)
if err != nil {
t.Fatalf("Open(%s): %v", path, err)
}
t.Cleanup(func() { _ = src.Close() })
return src
}
// TestReadersDoNotMutateSources reads every table of all three stores and
// asserts every file in each store's directory is byte-for-byte unchanged,
// including the FTS5 index read.
func TestReadersDoNotMutateSources(t *testing.T) {
stores := []struct {
name string
ddl string
tables []Table
rows map[string]int
}{
{"archie.db", stateStoreDDL, StateStoreTables, map[string]int{"tasks": 2, "events": 2, "identity_subjects": 1}},
{"archie.db-eda.sqlite", edaDDL, EDATables, map[string]int{"captures": 1, "bindings": 1, "tool_calls": 1}},
{"archie.db-conversations.sqlite", gatewayDDL, GatewayTables, map[string]int{"messages": 2, "turns": 1}},
}
for _, s := range stores {
t.Run(s.name, func(t *testing.T) {
path := fixture(t, s.name, s.ddl)
before := hashDir(t, filepath.Dir(path))
src := openSource(t, path)
for _, table := range s.tables {
rows, err := src.Read(t.Context(), table)
if err != nil {
t.Fatalf("Read(%s): %v", table.Name, err)
}
if want, ok := s.rows[table.Name]; ok && len(rows.Rows) != want {
t.Errorf("Read(%s) = %d rows, want %d", table.Name, len(rows.Rows), want)
}
}
if s.name == "archie.db-conversations.sqlite" {
if _, err := src.IndexedMessageIDs(t.Context()); err != nil {
t.Fatalf("IndexedMessageIDs: %v", err)
}
}
if err := src.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
if after := hashDir(t, filepath.Dir(path)); !mapsEqual(before, after) {
t.Fatalf("reading changed the source directory:\nbefore %x\nafter %x", before, after)
}
})
}
}
func mapsEqual(a, b map[string][32]byte) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if b[k] != v {
return false
}
}
return true
}
// TestOpenRefusesWrites pins the read-only open: a write through the
// source's connection is an error, not a silent mutation.
func TestOpenRefusesWrites(t *testing.T) {
src := openSource(t, fixture(t, "archie.db", stateStoreDDL))
if _, err := src.db.ExecContext(t.Context(), "DELETE FROM tasks"); err == nil {
t.Fatal("DELETE through the read-only source succeeded")
}
}
func TestReadCarriesAlteredColumnsAndBlobs(t *testing.T) {
src := openSource(t, fixture(t, "archie.db", stateStoreDDL))
tasks, err := src.Read(t.Context(), tableNamed(t, StateStoreTables, "tasks"))
if err != nil {
t.Fatalf("Read(tasks): %v", err)
}
if got := tasks.Value(0, "review_cursor"); got != int64(3) {
t.Errorf("tasks[0].review_cursor = %#v, want 3 (an ALTER TABLE column)", got)
}
if got := tasks.Value(1, "issue_number"); got != int64(1_000_000_000_000_000) {
t.Errorf("tasks[1].issue_number = %#v, want the chat seed", got)
}
res, err := src.Read(t.Context(), tableNamed(t, StateStoreTables, "resources"))
if err != nil {
t.Fatalf("Read(resources): %v", err)
}
if got, ok := res.Value(0, "value").([]byte); !ok || string(got) != "\x00\xff\x10" {
t.Errorf("resources[0].value = %#v, want the raw bytes 00 ff 10", res.Value(0, "value"))
}
}
func tableNamed(t *testing.T, tables []Table, name string) Table {
t.Helper()
i := slices.IndexFunc(tables, func(tb Table) bool { return tb.Name == name })
if i < 0 {
t.Fatalf("no table %q", name)
}
return tables[i]
}
func TestCompareKeys(t *testing.T) {
tests := []struct {
name string
source []string
target []string
missing, extra []string
}{
{name: "equal with the same gap", source: []string{"1", "2", "5"}, target: []string{"5", "1", "2"}},
{name: "swallowed row", source: []string{"1", "2", "3"}, target: []string{"1", "3"}, missing: []string{"2"}},
{name: "same count, different ids", source: []string{"1", "2"}, target: []string{"1", "9"}, missing: []string{"2"}, extra: []string{"9"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := CompareKeys(tt.source, tt.target)
if !slices.Equal(got.Missing, tt.missing) || !slices.Equal(got.Extra, tt.extra) {
t.Errorf("CompareKeys = %+v, want missing %v extra %v", got, tt.missing, tt.extra)
}
})
}
}
func TestCompareOrder(t *testing.T) {
if got := CompareOrder([]int64{1, 2, 3}, []int64{1, 2, 3}); got != nil {
t.Errorf("CompareOrder(equal) = %+v, want nil", got)
}
got := CompareOrder([]int64{1, 2, 3}, []int64{1, 3, 2})
if got == nil || got.Position != 1 || got.Source != 2 || got.Target != 3 {
t.Errorf("CompareOrder(swapped) = %+v, want the first divergence at position 1 (2 vs 3)", got)
}
if got := CompareOrder([]int64{1, 2}, []int64{1}); got == nil || got.Position != 1 {
t.Errorf("CompareOrder(short target) = %+v, want a divergence at position 1", got)
}
}
// TestMicrosecondCollisions constructs D3.8's condition: two events whose
// instants differ only below a microsecond, with the later instant carrying
// the lower id, so Postgres's (at, id) order would reverse them.
func TestMicrosecondCollisions(t *testing.T) {
path := fixture(t, "archie.db", stateStoreDDL)
exec(t, path, `INSERT INTO events (id, at, kind) VALUES
(10, '2026-02-01T00:00:00.000000900Z', 'later instant, lower id'),
(11, '2026-02-01T00:00:00.000000100Z', 'earlier instant, higher id'),
(12, '2026-02-01T00:00:05.000000100Z', 'same microsecond, ids in order'),
(13, '2026-02-01T00:00:05.000000900Z', 'same microsecond, ids in order')`)
src := openSource(t, path)
got, err := src.MicrosecondCollisions(t.Context())
if err != nil {
t.Fatalf("MicrosecondCollisions: %v", err)
}
if len(got) != 1 || got[0].EarlierID != 11 || got[0].LaterID != 10 {
t.Fatalf("MicrosecondCollisions = %+v, want exactly the pair (11 before 10)", got)
}
}
func TestOrphans(t *testing.T) {
path := fixture(t, "archie.db", stateStoreDDL)
src := openSource(t, path)
for _, fk := range IdentityForeignKeys {
got, err := src.Orphans(t.Context(), fk)
if err != nil || len(got) != 0 {
t.Fatalf("Orphans(%s) on a clean fixture = %v, %v; want none", fk.Table, got, err)
}
}
_ = src.Close()
exec(t, path, `INSERT INTO identity_aliases VALUES ('ghost', 'id-missing')`)
src = openSource(t, path)
got, err := src.Orphans(t.Context(), IdentityForeignKeys[0])
if err != nil {
t.Fatalf("Orphans: %v", err)
}
if len(got) != 1 || got[0].Key != "ghost" || got[0].Parent != "id-missing" {
t.Fatalf("Orphans(identity_aliases) = %+v, want the ghost alias", got)
}
}
// TestDuplicateAliases pins the case-folding hazard: SQLite's NOCASE folds
// ASCII only, so two aliases differing in non-ASCII case coexist there and
// collide under Postgres's Unicode lower().
func TestDuplicateAliases(t *testing.T) {
path := fixture(t, "archie.db", stateStoreDDL)
exec(t, path, `INSERT INTO identity_aliases VALUES ('ÉMILE', 'id-1'), ('émile', 'id-1')`)
src := openSource(t, path)
got, err := src.DuplicateAliases(t.Context())
if err != nil {
t.Fatalf("DuplicateAliases: %v", err)
}
if len(got) != 1 || got[0].Key != "émile" || len(got[0].Values) != 2 {
t.Fatalf("DuplicateAliases = %+v, want one group of two for émile", got)
}
}
func TestDuplicateArmedBindings(t *testing.T) {
path := fixture(t, "archie.db-eda.sqlite", edaDDL)
src := openSource(t, path)
if got, err := src.DuplicateBindings(t.Context()); err != nil || len(got) != 0 {
t.Fatalf("DuplicateBindings on a clean fixture = %v, %v; want none", got, err)
}
_ = src.Close()
exec(t, path, `INSERT INTO bindings VALUES ('rbind2', '', 'rmap1', 'b2', 'o', 'r', '', 'gh', 'pending_approval', '', 1, 'implement')`)
src = openSource(t, path)
got, err := src.DuplicateBindings(t.Context())
if err != nil {
t.Fatalf("DuplicateBindings: %v", err)
}
if len(got) != 1 || got[0].Key != "gh" || !slices.Equal(got[0].Values, []string{"rbind1", "rbind2"}) {
t.Fatalf("DuplicateBindings = %+v, want source gh held by rbind1 and rbind2", got)
}
}
func TestSequences(t *testing.T) {
src := openSource(t, fixture(t, "archie.db", stateStoreDDL))
got, err := src.Sequences(t.Context())
if err != nil {
t.Fatalf("Sequences: %v", err)
}
want := map[string]Sequence{
"tasks": {Table: "tasks", MaxID: 4, Next: 5},
"transitions": {Table: "transitions", MaxID: 1, Next: 2},
"events": {Table: "events", MaxID: 2, Next: 3},
"resource_history": {Table: "resource_history", MaxID: 1, Next: 2},
"identity_events": {Table: "identity_events", MaxID: 1, Next: 2},
}
if len(got) != len(want) {
t.Fatalf("Sequences = %+v, want %d tables", got, len(want))
}
for _, s := range got {
if want[s.Table] != s {
t.Errorf("Sequences[%s] = %+v, want %+v", s.Table, s, want[s.Table])
}
}
}
// TestSequenceNextSkipsDeletedTop pins that Next comes from AUTOINCREMENT's
// high-water mark, not max(id): a deleted top row still reserves its id.
func TestSequenceNextSkipsDeletedTop(t *testing.T) {
path := fixture(t, "archie.db", stateStoreDDL)
exec(t, path, `DELETE FROM tasks WHERE id = 4`)
src := openSource(t, path)
got, err := src.Sequences(t.Context())
if err != nil {
t.Fatalf("Sequences: %v", err)
}
i := slices.IndexFunc(got, func(s Sequence) bool { return s.Table == "tasks" })
if got[i].MaxID != 1 || got[i].Next != 5 {
t.Fatalf("Sequences[tasks] = %+v, want max 1, next 5", got[i])
}
}
func TestCompareBlobs(t *testing.T) {
src := map[string][]byte{"config": {0, 0xff}, "routing": {1}}
if got := CompareBlobs(src, map[string][]byte{"config": {0, 0xff}, "routing": {1}}); len(got) != 0 {
t.Errorf("CompareBlobs(equal) = %v, want none", got)
}
got := CompareBlobs(src, map[string][]byte{"config": {0, 0xfe}})
if !slices.Equal(got, []string{"config", "routing"}) {
t.Errorf("CompareBlobs = %v, want config (changed) and routing (missing)", got)
}
}
func TestIndexedMessageIDsFindsAStaleIndex(t *testing.T) {
path := fixture(t, "archie.db-conversations.sqlite", gatewayDDL)
exec(t, path, `DROP TRIGGER messages_ai; INSERT INTO messages (message_id, session_id, text, ts) VALUES ('m3', 's1', 'unindexed', 1002)`)
src := openSource(t, path)
indexed, err := src.IndexedMessageIDs(t.Context())
if err != nil {
t.Fatalf("IndexedMessageIDs: %v", err)
}
messages, err := src.Read(t.Context(), tableNamed(t, GatewayTables, "messages"))
if err != nil {
t.Fatalf("Read(messages): %v", err)
}
got := CompareKeys(messages.Keys(), indexed)
if !slices.Equal(got.Missing, []string{"3"}) {
t.Fatalf("CompareKeys(messages, index) = %+v, want message 3 missing from the index", got)
}
}
@@ -1,55 +0,0 @@
package legacyread
import (
"context"
"errors"
"fmt"
"os"
)
// HasData reports whether the legacy file at path holds any row in tables. A
// missing file, and a table the file never created, hold nothing. It is the
// legacy half of the boot gate: a Postgres database without a completed import
// must not serve while this is true for any source.
func HasData(ctx context.Context, path string, tables []Table) (bool, error) {
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
return false, nil
}
src, err := Open(ctx, path)
if err != nil {
return false, err
}
defer func() { _ = src.Close() }()
for _, t := range tables {
var present bool
if err := src.db.QueryRowContext(ctx,
"SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?)", t.Name).Scan(&present); err != nil {
return false, fmt.Errorf("legacyread: %s: %w", path, err)
}
if !present {
continue
}
var rows bool
if err := src.db.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM "+t.Name+")").Scan(&rows); err != nil {
return false, fmt.Errorf("legacyread: %s: %s: %w", path, t.Name, err)
}
if rows {
return true, nil
}
}
return false, nil
}
// SequenceOf returns the state of table's AUTOINCREMENT id column.
func (s *Source) SequenceOf(ctx context.Context, table string) (Sequence, error) {
seq := Sequence{Table: table}
var high int64
err := s.db.QueryRowContext(ctx, fmt.Sprintf(
"SELECT COALESCE((SELECT max(id) FROM %[1]s), 0), COALESCE((SELECT seq FROM sqlite_sequence WHERE name = '%[1]s'), 0)",
table)).Scan(&seq.MaxID, &high)
if err != nil {
return Sequence{}, fmt.Errorf("legacyread: sequence %s: %w", table, err)
}
seq.Next = max(seq.MaxID, high) + 1
return seq, nil
}
@@ -1,46 +0,0 @@
package legacyread
import (
"path/filepath"
"testing"
)
func TestHasData(t *testing.T) {
emptyGateway := `CREATE TABLE sessions (session_id TEXT PRIMARY KEY);
CREATE TABLE messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT);`
tests := []struct {
name string
path func(t *testing.T) string
tables []Table
want bool
}{
{"missing file", func(t *testing.T) string { return filepath.Join(t.TempDir(), "absent.sqlite") }, GatewayTables, false},
{"tables without rows", func(t *testing.T) string { return fixture(t, "gw.sqlite", emptyGateway) }, GatewayTables, false},
{"rows present", func(t *testing.T) string { return fixture(t, "gw.sqlite", gatewayDDL) }, GatewayTables, true},
{"rows in the state store", func(t *testing.T) string { return fixture(t, "archie.db", stateStoreDDL) }, StateStoreTables, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := HasData(t.Context(), tt.path(t), tt.tables)
if err != nil {
t.Fatalf("HasData: %v", err)
}
if got != tt.want {
t.Fatalf("HasData = %v, want %v", got, tt.want)
}
})
}
}
func TestSequenceOfMessages(t *testing.T) {
path := fixture(t, "gw.sqlite", gatewayDDL)
exec(t, path, `DELETE FROM messages WHERE message_id = 'm2'`)
src := openSource(t, path)
got, err := src.SequenceOf(t.Context(), "messages")
if err != nil {
t.Fatalf("SequenceOf: %v", err)
}
if want := (Sequence{Table: "messages", MaxID: 1, Next: 3}); got != want {
t.Fatalf("SequenceOf(messages) = %+v, want %+v", got, want)
}
}
@@ -1,73 +0,0 @@
package legacyread
func idTable(name string, columns ...string) Table {
return Table{Name: name, Columns: columns, Key: []string{columns[0]}, OrderBy: columns[0]}
}
// StateStoreTables are the twelve tables of the State Store's archie.db.
var StateStoreTables = []Table{
idTable("tasks", "id", "owner", "repo", "issue_number", "title", "body", "labels", "status",
"workflow", "stage", "branch", "plan", "notes", "pr_number", "tokens_used", "iterations",
"attempt", "park_reason", "watch_comment_id", "park_class", "remediation_rounds", "retry_count",
"source", "identity", "binding_id", "binding_version", "review_payload",
"workflow_definition_version", "workflow_definition_digest", "workflow_definition_yaml",
"created_at", "updated_at", "review_cursor"),
idTable("transitions", "id", "task_id", "at", "from_status", "to_status", "detail"),
{
Name: "events",
Columns: []string{
"id", "at", "kind", "task_id", "repo", "issue", "workflow", "stage", "attempt",
"actor_id", "actor_kind", "principal_id", "detail", "data",
},
Key: []string{"id"},
OrderBy: "at, id",
},
idTable("resources", "kind", "value", "version", "updated_at"),
idTable("resource_history", "id", "kind", "value", "version", "actor", "source", "request_id",
"expected_version", "current_version", "at"),
idTable("channel_status", "id", "name", "state", "detail", "configured", "reload_supported", "observed_at"),
{
Name: "apply_status",
Columns: []string{"process", "kind", "applied_version", "error", "reported_at"},
Key: []string{"process", "kind"},
OrderBy: "process, kind",
},
idTable("config_snapshot", "id", "schema", "document", "published_at"),
idTable("identities", "id", "kind", "display_name", "lifecycle", "version", "created_at", "updated_at"),
idTable("identity_aliases", "alias", "identity_id"),
idTable("identity_events", "id", "identity_id", "event_type", "from_lifecycle", "to_lifecycle",
"display_name", "actor_id", "source", "request_id", "at"),
{
Name: "identity_subjects",
Columns: []string{"issuer", "subject", "identity_id", "bound_at"},
Key: []string{"issuer", "subject"},
OrderBy: "issuer, subject",
},
}
// EDATables are the six app collections of the PocketBase event store.
// PocketBase's own tables (_collections, _params, _superusers, ...) are not
// archie data and are not read.
var EDATables = []Table{
idTable("captures", "id", "authenticated", "body", "content_type", "headers", "received_at",
"remote_addr", "source"),
idTable("mappings", "id", "created_at", "fields", "name", "source_hint", "updated_at"),
idTable("bindings", "id", "created_at", "mapping", "name", "owner", "repo", "secret", "source",
"status", "updated_at", "version", "workflow"),
idTable("binding_dispatches", "id", "binding", "binding_version", "capture", "dispatched_at", "task_id"),
idTable("playbook_dispatches", "id", "action_id", "dispatched_at", "event_id", "playbook_id",
"playbook_version"),
idTable("tool_calls", "id", "args", "attempt", "called_at", "duration_ms", "error", "result",
"task_id", "tool"),
}
// GatewayTables are the Gateway conversation store's three data tables. Its
// FTS5 index is read through IndexedMessageIDs.
var GatewayTables = []Table{
idTable("sessions", "session_id", "platform", "bot_user", "channel_id", "thread_id", "title",
"parent_session_id", "branch_name", "created_at", "last_active_at"),
idTable("messages", "id", "message_id", "session_id", "source_id", "sender", "text", "ts", "role", "sender_id"),
idTable("turns", "turn_id", "session_id", "source_id", "status", "attempt", "owner_id",
"input_message_id", "assistant_message_id", "partial_text", "response_text", "tool_calls",
"error", "created_at", "updated_at"),
}
@@ -1,270 +0,0 @@
package legacyread
import (
"bytes"
"context"
"fmt"
"maps"
"slices"
"strings"
"time"
)
// KeyDiff is the difference between two key sets. A count comparison alone
// passes on a swallowed row when ids have gaps; comparing the sets does not.
type KeyDiff struct {
Missing []string // in the source, not the target
Extra []string // in the target, not the source
}
// CompareKeys compares the source's key set with the target's.
func CompareKeys(source, target []string) KeyDiff {
var d KeyDiff
src := setOf(source)
tgt := setOf(target)
for k := range src {
if !tgt[k] {
d.Missing = append(d.Missing, k)
}
}
for k := range tgt {
if !src[k] {
d.Extra = append(d.Extra, k)
}
}
slices.Sort(d.Missing)
slices.Sort(d.Extra)
return d
}
func setOf(keys []string) map[string]bool {
set := make(map[string]bool, len(keys))
for _, k := range keys {
set[k] = true
}
return set
}
// Divergence is the first position at which two ordered id sequences differ.
// A missing element on one side reads as 0.
type Divergence struct {
Position int
Source, Target int64
}
// CompareOrder compares two id sequences read in cursor order, returning nil
// when they are identical.
func CompareOrder(source, target []int64) *Divergence {
for i := range max(len(source), len(target)) {
var s, t int64
if i < len(source) {
s = source[i]
}
if i < len(target) {
t = target[i]
}
if s != t || i >= len(source) || i >= len(target) {
return &Divergence{Position: i, Source: s, Target: t}
}
}
return nil
}
// Collision is two events whose instants differ only below a microsecond
// while their ids run the other way. Postgres stores microseconds, so its
// (at, id) order would put LaterID before EarlierID.
type Collision struct {
EarlierID, LaterID int64
At time.Time // the shared microsecond
}
// eventAtLayouts are the layouts events.at has been written in, newest first.
var eventAtLayouts = []string{"2006-01-02T15:04:05.000000000Z", time.RFC3339Nano, time.RFC3339}
func parseEventAt(s string) (time.Time, error) {
for _, layout := range eventAtLayouts {
if t, err := time.Parse(layout, s); err == nil {
return t.UTC(), nil
}
}
return time.Time{}, fmt.Errorf("unrecognised timestamp %q", s)
}
// MicrosecondCollisions returns every event pair that truncating events.at
// to microseconds would reorder.
func (s *Source) MicrosecondCollisions(ctx context.Context) ([]Collision, error) {
rows, err := s.db.QueryContext(ctx, "SELECT id, at FROM events ORDER BY id")
if err != nil {
return nil, fmt.Errorf("legacyread: events: %w", err)
}
defer func() { _ = rows.Close() }()
type event struct {
id int64
at time.Time
}
byMicro := map[time.Time][]event{}
for rows.Next() {
var (
id int64
raw string
)
if err := rows.Scan(&id, &raw); err != nil {
return nil, fmt.Errorf("legacyread: events: %w", err)
}
at, err := parseEventAt(raw)
if err != nil {
return nil, fmt.Errorf("legacyread: event %d: %w", id, err)
}
micro := at.Truncate(time.Microsecond)
byMicro[micro] = append(byMicro[micro], event{id, at})
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("legacyread: events: %w", err)
}
var out []Collision
for micro, events := range byMicro {
for i, a := range events {
for _, b := range events[i+1:] {
// Read in id order, so a.id < b.id.
if b.at.Before(a.at) {
out = append(out, Collision{EarlierID: b.id, LaterID: a.id, At: micro})
}
}
}
}
slices.SortFunc(out, func(x, y Collision) int { return int(x.EarlierID - y.EarlierID) })
return out, nil
}
// ForeignKey is a reference SQLite declared but never enforced (the State
// Store never set PRAGMA foreign_keys) and Postgres will.
type ForeignKey struct {
Table, Column string
KeyExpr string // SQL naming the child row in a report
Parent, ParentC string
}
// IdentityForeignKeys are the three identity references.
var IdentityForeignKeys = []ForeignKey{
{Table: "identity_aliases", Column: "identity_id", KeyExpr: "alias", Parent: "identities", ParentC: "id"},
{Table: "identity_events", Column: "identity_id", KeyExpr: "CAST(id AS TEXT)", Parent: "identities", ParentC: "id"},
{Table: "identity_subjects", Column: "identity_id", KeyExpr: "issuer || '/' || subject", Parent: "identities", ParentC: "id"},
}
// Orphan is a child row whose parent does not exist.
type Orphan struct {
Key, Parent string
}
// Orphans returns fk's child rows with no parent.
func (s *Source) Orphans(ctx context.Context, fk ForeignKey) ([]Orphan, error) {
query := fmt.Sprintf("SELECT %s, %s FROM %s WHERE %s NOT IN (SELECT %s FROM %s) ORDER BY 1",
fk.KeyExpr, fk.Column, fk.Table, fk.Column, fk.ParentC, fk.Parent)
rows, err := s.db.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("legacyread: orphans in %s: %w", fk.Table, err)
}
defer func() { _ = rows.Close() }()
var out []Orphan
for rows.Next() {
var o Orphan
if err := rows.Scan(&o.Key, &o.Parent); err != nil {
return nil, fmt.Errorf("legacyread: orphans in %s: %w", fk.Table, err)
}
out = append(out, o)
}
return out, rows.Err()
}
// Duplicate is a key the target will hold unique that more than one source
// row shares.
type Duplicate struct {
Key string
Values []string
}
// DuplicateAliases groups identity aliases by Unicode lower case. SQLite's
// NOCASE folds ASCII only, so aliases that differ in non-ASCII case coexist in
// the source and collide on the target's lower(alias) index.
func (s *Source) DuplicateAliases(ctx context.Context) ([]Duplicate, error) {
aliases, err := s.strings(ctx, "SELECT alias FROM identity_aliases ORDER BY alias")
if err != nil {
return nil, err
}
return duplicates(aliases, aliases, strings.ToLower), nil
}
// DuplicateBindings groups bindings by source. One binding per source is
// enforced in Go, not by the legacy schema, so a duplicate is possible and is
// refused rather than repaired (D4.2).
func (s *Source) DuplicateBindings(ctx context.Context) ([]Duplicate, error) {
rows, err := s.Read(ctx, Table{Name: "bindings", Columns: []string{"id", "source"}, OrderBy: "id"})
if err != nil {
return nil, err
}
ids := make([]string, len(rows.Rows))
sources := make([]string, len(rows.Rows))
for i := range rows.Rows {
ids[i] = fmt.Sprint(rows.Value(i, "id"))
sources[i] = fmt.Sprint(rows.Value(i, "source"))
}
return duplicates(sources, ids, func(s string) string { return s }), nil
}
// duplicates groups values by key(keys[i]) and returns the groups of two or
// more, sorted by key.
func duplicates(keys, values []string, key func(string) string) []Duplicate {
groups := map[string][]string{}
for i, k := range keys {
groups[key(k)] = append(groups[key(k)], values[i])
}
var out []Duplicate
for _, k := range slices.Sorted(maps.Keys(groups)) {
if len(groups[k]) > 1 {
out = append(out, Duplicate{Key: k, Values: groups[k]})
}
}
return out
}
// Sequence is an identity column's state: the highest id present and the id
// SQLite would assign next. Next comes from AUTOINCREMENT's high-water mark,
// so a deleted top row still reserves its id.
type Sequence struct {
Table string
MaxID, Next int64
}
// sequenceTables are the State Store tables with an AUTOINCREMENT id.
var sequenceTables = []string{"tasks", "transitions", "events", "resource_history", "identity_events"}
// Sequences returns the state of every State Store identity column.
func (s *Source) Sequences(ctx context.Context) ([]Sequence, error) {
out := make([]Sequence, 0, len(sequenceTables))
for _, table := range sequenceTables {
seq, err := s.SequenceOf(ctx, table)
if err != nil {
return nil, err
}
out = append(out, seq)
}
return out, nil
}
// CompareBlobs returns, sorted, every key whose bytes differ between source
// and target or that only one side holds.
func CompareBlobs(source, target map[string][]byte) []string {
var out []string
for k, v := range source {
if t, ok := target[k]; !ok || !bytes.Equal(v, t) {
out = append(out, k)
}
}
for k := range target {
if _, ok := source[k]; !ok {
out = append(out, k)
}
}
slices.Sort(out)
return out
}
@@ -1,31 +0,0 @@
package postgres
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// ImportComplete reports whether the one-time legacy import committed and
// verified against this migrated database. Serving over non-empty legacy
// files is refused without it.
func ImportComplete(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
done, err := postgresdb.New(pool).ImportCompleted(ctx)
if err != nil {
return false, fmt.Errorf("postgres: import completion: %w", err)
}
return done, nil
}
// RecordFreshInstall writes the completion record for a database that starts
// with no legacy data to import, so a legacy file that appears later cannot
// block it from serving. It leaves an existing record untouched.
func RecordFreshInstall(ctx context.Context, pool *pgxpool.Pool) error {
if err := postgresdb.New(pool).InsertFreshInstallCompletion(ctx); err != nil {
return fmt.Errorf("postgres: fresh install completion: %w", err)
}
return nil
}
@@ -1,39 +0,0 @@
package postgres
import (
"testing"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
)
func TestImportComplete(t *testing.T) {
tests := []struct {
name string
record bool
want bool
}{
{name: "migrated database without a record", want: false},
{name: "committed record", record: true, want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pool := openPool(t, pgtest.URL(t))
if err := Migrate(t.Context(), pool, Migrations()); err != nil {
t.Fatalf("Migrate: %v", err)
}
if tt.record {
if _, err := pool.Exec(t.Context(),
"INSERT INTO import_completion (id, sources, report) VALUES (1, 's', 'r')"); err != nil {
t.Fatalf("seed record: %v", err)
}
}
got, err := ImportComplete(t.Context(), pool)
if err != nil {
t.Fatalf("ImportComplete: %v", err)
}
if got != tt.want {
t.Fatalf("ImportComplete = %v, want %v", got, tt.want)
}
})
}
}
@@ -0,0 +1,15 @@
-- The one-time SQLite import is removed, and with it the completion record
-- that gated serving over unimported legacy files.
-- +goose Up
DROP TABLE import_completion;
-- +goose Down
CREATE TABLE import_completion (
id bigint PRIMARY KEY CHECK (id = 1),
completed_at timestamptz NOT NULL DEFAULT now(),
sources text NOT NULL,
report text NOT NULL
);
@@ -1,47 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: import.sql
package postgresdb
import (
"context"
)
const importCompleted = `-- name: ImportCompleted :one
SELECT EXISTS (SELECT 1 FROM import_completion)
`
func (q *Queries) ImportCompleted(ctx context.Context) (bool, error) {
row := q.db.QueryRow(ctx, importCompleted)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const insertFreshInstallCompletion = `-- name: InsertFreshInstallCompletion :exec
INSERT INTO import_completion (id, sources, report) VALUES (1, '', 'fresh install: no legacy data')
ON CONFLICT (id) DO NOTHING
`
func (q *Queries) InsertFreshInstallCompletion(ctx context.Context) error {
_, err := q.db.Exec(ctx, insertFreshInstallCompletion)
return err
}
const insertImportCompletion = `-- name: InsertImportCompletion :exec
INSERT INTO import_completion (id, sources, report) VALUES (1, $1, $2)
`
type InsertImportCompletionParams struct {
Sources string
Report string
}
// The one-time legacy import's completion record.
func (q *Queries) InsertImportCompletion(ctx context.Context, arg InsertImportCompletionParams) error {
_, err := q.db.Exec(ctx, insertImportCompletion, arg.Sources, arg.Report)
return err
}
@@ -134,13 +134,6 @@ type IdentitySubject struct {
BoundAt time.Time
}
type ImportCompletion struct {
ID int64
CompletedAt time.Time
Sources string
Report string
}
type Mapping struct {
ID string
Name string
@@ -1,11 +0,0 @@
-- The one-time legacy import's completion record.
-- name: InsertImportCompletion :exec
INSERT INTO import_completion (id, sources, report) VALUES (1, $1, $2);
-- name: ImportCompleted :one
SELECT EXISTS (SELECT 1 FROM import_completion);
-- name: InsertFreshInstallCompletion :exec
INSERT INTO import_completion (id, sources, report) VALUES (1, '', 'fresh install: no legacy data')
ON CONFLICT (id) DO NOTHING;
-2
View File
@@ -243,7 +243,6 @@ type BudgetsView struct {
type StorageView struct {
WorkDir string `json:"work_dir"`
StateDir string `json:"state_dir"`
DBPath string `json:"db_path"`
DatabaseURL string `json:"database_url"`
SkillsDir string `json:"skills_dir,omitempty"`
PluginDir string `json:"plugin_dir,omitempty"`
@@ -377,7 +376,6 @@ func BuildConfigView(in ConfigViewInput) ConfigView {
Storage: StorageView{
WorkDir: cfg.WorkDir,
StateDir: cfg.StateDir,
DBPath: cfg.DBPath,
DatabaseURL: cfg.DatabaseURL,
SkillsDir: cfg.SkillsDir,
PluginDir: cfg.PluginDir,
+1 -2
View File
@@ -30,7 +30,6 @@ func configWithFakeSecrets() *config.Holder {
return config.NewHolder(config.Config{
WorkDir: "/work/archie",
SkillsDir: "/work/archie/.agents/skills",
DBPath: "/work/archie/archie.db",
BotUser: "archie-bot",
BotEmail: "archie@example.com",
Label: "archie",
@@ -343,7 +342,7 @@ func TestHandleConfigReportsLockedKeys(t *testing.T) {
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
for _, key := range []string{"db_path", "database_url", "work_dir"} {
for _, key := range []string{"database_url", "work_dir"} {
if got.Locked[key] == "" {
t.Errorf("Locked[%q] is empty, want a reason", key)
}
+1 -3
View File
@@ -91,7 +91,7 @@ type ConfigSection struct {
// restart even though the dashboard already renders it as editable.
// - Web, SkillsDir, PluginDir, SecretEngineDir are absent from both
// allowlists entirely, so they require a restart.
// - WorkDir and DBPath are locked (configuration.DeniedKeys), not merely
// - WorkDir and DatabaseURL are locked (configuration.DeniedKeys), not merely
// restart-required -- the dashboard cannot change them at all.
func configFieldDescriptors() []ConfigSection {
return []ConfigSection{
@@ -148,7 +148,6 @@ func configFieldDescriptors() []ConfigSection {
Fields: []ConfigField{
{Key: "work_dir", Label: "Work directory", Type: FieldString, Editable: false},
{Key: "state_dir", Label: "State directory", Description: "Embedded NATS store, task logs and the readiness disk probe.", Type: FieldString, Editable: false},
{Key: "db_path", Label: "Legacy SQLite path prefix", Description: "Locates pre-PostgreSQL files for the one-time import only.", Type: FieldString, Editable: false},
{Key: "database_url", Label: "PostgreSQL URL", Description: "The State Store's database connection; set at boot, restart required.", Type: FieldString, Editable: false},
{Key: "skills_dir", Label: "Shared skills directory", Description: "Empty uses the work directory.", Type: FieldString, Editable: true, RestartRequired: true},
{Key: "plugin_dir", Label: "Daemon plugin directory", Description: "Empty means no daemon plugins.", Type: FieldString, Editable: true, RestartRequired: true},
@@ -194,7 +193,6 @@ func configFieldValues(view ConfigView) map[string]any {
"budgets.gate_max_failures": view.Budgets.GateMaxFailures,
"work_dir": view.Storage.WorkDir,
"state_dir": view.Storage.StateDir,
"db_path": view.Storage.DBPath,
"database_url": view.Storage.DatabaseURL,
"skills_dir": view.Storage.SkillsDir,
"plugin_dir": view.Storage.PluginDir,
+3 -4
View File
@@ -64,7 +64,7 @@ func TestConfigFieldDescriptorsAreComplete(t *testing.T) {
"bot_user", "bot_email", "label", "forge.type", "forge.host", "diff_cap_lines",
"repos", "models", "providers",
"budgets.max_steps", "budgets.wall_clock", "budgets.gate_max_failures",
"work_dir", "state_dir", "db_path", "database_url", "skills_dir", "plugin_dir", "secret_engine_dir",
"work_dir", "state_dir", "database_url", "skills_dir", "plugin_dir", "secret_engine_dir",
"containers.image", "containers.max_concurrency", "containers.max_uptime",
"containers.volume_ttl", "containers.pull_policy", "containers.network",
"web.listen",
@@ -101,7 +101,6 @@ func TestConfigFieldDescriptorsRestartRequiredIsDeliberate(t *testing.T) {
"budgets.gate_max_failures": false,
"work_dir": false, // locked, not merely restart-required
"state_dir": false, // locked, not merely restart-required
"db_path": false, // locked, not merely restart-required
"database_url": false, // locked, not merely restart-required
"skills_dir": true, // absent from reloadableFields
"plugin_dir": true,
@@ -144,13 +143,13 @@ func TestConfigFieldDescriptorsStructuredFieldsAreNotEditable(t *testing.T) {
}
// TestConfigFieldDescriptorsLockedStorageFieldsAreNotEditable pins
// work_dir/db_path as Editable: false in the static catalog. They are also
// work_dir/database_url as Editable: false in the static catalog. They are also
// reported LockedReason at runtime via overlay.DeniedKeys (api_config.go),
// but the catalog marks them non-editable independently so the generic
// renderer does not need runtime state to know not to offer an edit
// affordance for a key that can never succeed.
func TestConfigFieldDescriptorsLockedStorageFieldsAreNotEditable(t *testing.T) {
locked := map[string]bool{"work_dir": true, "state_dir": true, "db_path": true, "database_url": true}
locked := map[string]bool{"work_dir": true, "state_dir": true, "database_url": true}
for _, section := range configFieldDescriptors() {
for _, f := range section.Fields {
if locked[f.Key] && f.Editable {