feat(archie): the single binary's skeleton: bootstrap config, migrations under an advisory lock, health (#1977)

This commit is contained in:
sam committed 2026-11-15 16:59:21 +11:00
1 parent 9cd31e48ca
commit a69a0ea942
11 files changed
+391 -17

No files matched your search

+19
View File
@@ -97,6 +97,25 @@ linters:
- {pkg: "github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore", desc: "reach the State Store through its contract"}
- {pkg: "github.com/samcharles93/archie-core/internal/domain/workflow", desc: "the workflow engine is the daemon's"}
- {pkg: "github.com/samcharles93/archie-core/internal/agentexec", desc: "agent execution is the daemon's"}
# The single binary replaces the services slice by slice. It never
# imports their packages, so each old path can be deleted outright.
single-binary:
files: ["**/cmd/archie/**", "**/internal/app/archie/**", "**/internal/platform/**", "**/modules/**"]
deny:
- {pkg: "github.com/samcharles93/archie-core/internal/app/archied", desc: "an old service; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/app/statestore", desc: "an old service; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/app/archiegateway", desc: "an old service; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/app/archiemessaging", desc: "an old service; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/app/archieui", desc: "an old service; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/app/servicekit", desc: "old service plumbing"}
- {pkg: "github.com/samcharles93/archie-core/internal/daemon", desc: "old service code; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/gateway", desc: "old service code; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/webui", desc: "old service code; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/domain", desc: "old domain code; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/infrastructure", desc: "old infrastructure; move what you need into a module"}
- {pkg: "github.com/samcharles93/archie-core/internal/contracts", desc: "internal service contracts are being deleted"}
- {pkg: "github.com/samcharles93/archie-core/internal/config", desc: "the single binary has its own bootstrap config"}
- {pkg: "github.com/nats-io", desc: "the single binary has no message bus"}
shared:
files: ["**/internal/app/servicekit/**"]
deny:
+32 -16
View File
@@ -5,14 +5,32 @@ here changes a decision. If a rule stops changing decisions, delete it.
## What this is
**archie-core** is event-driven agentic automation. An event (an issue, PR,
webhook, schedule, chat message) is matched to a workflow, the workflow runs an
agent or tool in an isolated container, and the result lands somewhere for
review or action. A repository is an optional input to a workflow, not the point
of the product. A forge is one of many inputs or outputs; core code never
assumes one.
**archie-core** is event-driven agentic automation. An event (an alert, a
webhook, a schedule, a chat message, an issue) is matched to a workflow, the
workflow runs an agent whose every action is judged before it runs, and the
result lands somewhere for review or action. A repository is an optional input
to a workflow, not the point of the product. A forge is one of many inputs or
outputs; core code never assumes one.
## Services and layout
## Layout
Main is becoming one binary, `archie`. The design is ARCHITECTURE.md in the
private sam/archie-product repo, and the work is epic #1977. New work goes
there:
- `cmd/archie` parses flags and calls `internal/app/archie`, the composition
root.
- Each module is `modules/<name>/`: an API package and an `internal/` directory
nothing outside the module can import. Modules reach each other only through
API packages, own their schema and tables, and keep no state only in memory.
- `internal/platform/` holds the few leaf packages every module may use.
- The new code never imports the old services' packages (depguard enforces it);
move what you need instead.
### The services being replaced
The six services below are deleted slice by slice as the binary replaces them.
Don't add features to them; fix them only when a bug blocks work.
Each service is a gRPC contract in `proto/<service>/v1`, generated into
`internal/contracts/<service>/v1`, and one binary in `cmd/` that parses flags
@@ -81,11 +99,10 @@ When sources disagree, the higher one wins:
breaking changes need no compatibility shims.
- **Finish before starting.** Prefer completing a half-built feature end to end
over starting a new one.
- **Services own contracts.** A service is a gRPC contract in
`proto/<service>/v1` and one binary that serves it. Services reach each other
only through those contracts, never through another service's tables or
packages. A new command is a subcommand of an existing binary. A new binary
exists only for a new service or a real process boundary.
- **Modules own their API and tables.** A module reaches another only through
its API package, never its tables or `internal/`. The only real process
boundaries are extensions and the runner. A new command is a subcommand of
`archie`.
- **No compensating tools.** Do not write a linter, checker or generator to
enforce something a simpler design would make unnecessary. Fix the design.
- **A setting must work end to end.** A config field that parses but has no
@@ -153,10 +170,9 @@ How to write one:
These protect users. Do not weaken them without the maintainer's say-so.
- Failure stays local. Any service may crash, restart or be absent without
losing accepted work or taking another service down. Callers retry, degrade
and report the dependency as unhealthy; they never exit because a peer is
missing, and work is acknowledged only once it is durable.
- A crash loses no accepted work, and a restart resumes every run. Work is
acknowledged only once it is durable. A missing dependency is reported
unhealthy and retried, never a reason to exit.
- The model never runs git. Commits and pushes go through the daemon.
- The daemon's own credentials never enter an agent container. Containers get
task-scoped grants that are revoked when the task ends.
+2 -1
View File
@@ -255,10 +255,11 @@ tasks:
- "{{.BIN_DIR}}/archie-ui"
- "{{.BIN_DIR}}/archie-messaging"
- "{{.BIN_DIR}}/archie-agent"
- "{{.BIN_DIR}}/archie"
cmds:
# One flag set for every service, matching the release workflow, so each
# binary reports the same version.
- for: [archied, archie-gateway, archie-state-store, archie-ui, archie-messaging]
- for: [archie, archied, archie-gateway, archie-state-store, archie-ui, archie-messaging]
cmd: go build -trimpath -ldflags "{{.SERVICE_LDFLAGS}}" -o {{.BIN_DIR}}/{{.ITEM}} ./cmd/{{.ITEM}}
- go build -trimpath -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-agent ./cmd/archie-agent
+33
View File
@@ -0,0 +1,33 @@
// Command archie is the single Archie binary. It parses flags and hands over to
// the composition root.
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/samcharles93/archie-core/internal/app/archie"
"github.com/samcharles93/archie-core/internal/buildinfo"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "archie:", err)
os.Exit(1)
}
}
func run() error {
configPath := flag.String("config", archie.DefaultConfigPath(), "path to the bootstrap config file")
showVersion := buildinfo.RegisterVersionFlag("archie")
flag.Parse()
showVersion()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.Run(ctx, *configPath)
}
+1
View File
@@ -80,6 +80,7 @@ require (
github.com/hashicorp/go-plugin v1.8.0
github.com/hiddeco/sshsig v0.2.0
github.com/jackc/pgx/v5 v5.13.0
github.com/jmoiron/sqlx v1.4.0
github.com/klauspost/compress v1.20.4
github.com/moby/moby/api v1.56.1
github.com/moby/moby/client v0.6.2
+12
View File
@@ -4,6 +4,9 @@ cel.dev/expr v0.26.0 h1:oLXvOF0jiYA5A/tmzU91pLEWZkKynhLJlC9Gw7PrKvs=
cel.dev/expr v0.26.0/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/Microsoft/go-winio v0.6.4 h1:kJF2pamtYCWXf0xAT8sAkwKC0pMl2HYBrRPHAqyUc+g=
@@ -76,6 +79,9 @@ github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-webauthn/webauthn v0.18.2 h1:0BeftmEHU7i3Dv0VFwBtidy/ba37Vcdjvqst9EYu8Sk=
@@ -116,6 +122,8 @@ github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jhump/protoreflect v1.17.0 h1:qOEr613fac2lOuTgWN4tPAtLL7fUSbuJL5X5XumQh94=
github.com/jhump/protoreflect v1.17.0/go.mod h1:h9+vUUL38jiBzck8ck+6G/aeMX8Z4QUY/NiJPwPNi+8=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
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/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
@@ -127,6 +135,8 @@ 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/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
@@ -135,6 +145,8 @@ github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Ky
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
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-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
+64
View File
@@ -0,0 +1,64 @@
package archie
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
)
// Config is the bootstrap configuration: only what the binary needs before it
// can reach its database. Everything else is a setting in the control plane.
type Config struct {
Listen string `toml:"listen"`
Database DatabaseConfig `toml:"database"`
}
// DatabaseConfig holds the two connection URLs. The owner runs migrations at
// boot and nothing else; the runtime URL never holds DDL rights.
type DatabaseConfig struct {
URL string `toml:"url"`
OwnerURL string `toml:"owner_url"`
}
// DefaultConfigPath is ${XDG_CONFIG_HOME:-~/.config}/archie/config.toml.
func DefaultConfigPath() string {
dir, err := os.UserConfigDir()
if err != nil {
return filepath.Join("archie", "config.toml")
}
return filepath.Join(dir, "archie", "config.toml")
}
// LoadConfig reads and validates the bootstrap config at path.
func LoadConfig(path string) (Config, error) {
cfg := Config{Listen: "127.0.0.1:8080"}
if _, err := toml.DecodeFile(path, &cfg); err != nil {
return Config{}, fmt.Errorf("read config %s: %w", path, err)
}
if err := cfg.validate(); err != nil {
return Config{}, fmt.Errorf("config %s: %w", path, err)
}
return cfg, nil
}
func (c Config) validate() error {
var errs []error
if c.Listen == "" {
errs = append(errs, errors.New("listen is empty"))
}
if c.Database.URL == "" {
errs = append(errs, errors.New("database.url is required"))
}
// The owner URL has no fallback to the runtime URL: a runtime connection
// that can run DDL defeats the role split.
if c.Database.OwnerURL == "" {
errs = append(errs, errors.New("database.owner_url is required"))
}
if c.Database.URL != "" && c.Database.URL == c.Database.OwnerURL {
errs = append(errs, errors.New("database.url and database.owner_url must name different roles"))
}
return errors.Join(errs...)
}
+76
View File
@@ -0,0 +1,76 @@
// Package archie is the composition root of the single Archie binary. It loads
// the bootstrap config, migrates and opens the database, and serves until the
// context ends. Modules wire themselves in here as they land.
package archie
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"time"
"github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/platform/health"
"github.com/samcharles93/archie-core/internal/platform/pg"
)
const shutdownGrace = 10 * time.Second
// Run boots the binary from the config at configPath and blocks until ctx ends
// or the server fails.
func Run(ctx context.Context, configPath string) error {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version)
cfg, err := LoadConfig(configPath)
if err != nil {
return err
}
if err := pg.Migrate(ctx, log, cfg.Database.OwnerURL); err != nil {
return err
}
db, err := pg.Open(ctx, cfg.Database.URL)
if err != nil {
return err
}
defer func() { _ = db.Close() }()
checks := health.NewRegistry()
checks.Register("database", db.PingContext)
mux := http.NewServeMux()
checks.Routes(mux)
return serve(ctx, log, cfg.Listen, mux)
}
func serve(ctx context.Context, log *slog.Logger, addr string, handler http.Handler) error {
var lc net.ListenConfig
listener, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
return fmt.Errorf("listen on %s: %w", addr, err)
}
server := &http.Server{
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
BaseContext: func(net.Listener) context.Context { return ctx },
}
failed := make(chan error, 1)
go func() { failed <- server.Serve(listener) }()
log.InfoContext(ctx, "serving", "addr", listener.Addr().String())
select {
case err := <-failed:
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownGrace)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("shut down: %w", err)
}
log.InfoContext(ctx, "stopped")
return nil
}
+76
View File
@@ -0,0 +1,76 @@
// Package health serves liveness and readiness. Each module registers the
// check that says whether it can do its work.
package health
import (
"context"
"encoding/json"
"net/http"
"sort"
"sync"
"time"
)
// Check reports whether one part of the binary is ready.
type Check func(context.Context) error
// Registry holds the named readiness checks.
type Registry struct {
mu sync.RWMutex
checks map[string]Check
}
// NewRegistry returns an empty registry.
func NewRegistry() *Registry {
return &Registry{checks: map[string]Check{}}
}
// Register adds or replaces the check for name.
func (r *Registry) Register(name string, check Check) {
r.mu.Lock()
defer r.mu.Unlock()
r.checks[name] = check
}
// Routes adds /healthz and /readyz to mux.
func (r *Registry) Routes(mux *http.ServeMux) {
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
})
mux.HandleFunc("GET /readyz", r.ready)
}
func (r *Registry) ready(w http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
defer cancel()
failures := map[string]string{}
for _, name := range r.names() {
if err := r.check(name)(ctx); err != nil {
failures[name] = err.Error()
}
}
w.Header().Set("Content-Type", "application/json")
if len(failures) > 0 {
w.WriteHeader(http.StatusServiceUnavailable)
}
_ = json.NewEncoder(w).Encode(map[string]any{"ready": len(failures) == 0, "failures": failures})
}
func (r *Registry) names() []string {
r.mu.RLock()
defer r.mu.RUnlock()
names := make([]string, 0, len(r.checks))
for name := range r.checks {
names = append(names, name)
}
sort.Strings(names)
return names
}
func (r *Registry) check(name string) Check {
r.mu.RLock()
defer r.mu.RUnlock()
return r.checks[name]
}
@@ -0,0 +1,5 @@
# Migrations
One ordered series for the whole binary, applied once at boot by the owner role
under an advisory lock. Name files `NNNNN_<module>_<change>.sql` and never edit
one that has shipped.
+71
View File
@@ -0,0 +1,71 @@
// Package pg opens Archie's Postgres connections and applies its one ordered
// migration series.
package pg
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
"log/slog"
// Registers the "pgx" database/sql driver that sqlx and goose use.
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/jmoiron/sqlx"
"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock"
)
//go:embed migrations
var migrationFiles embed.FS
// Open connects with the runtime URL and checks the connection.
func Open(ctx context.Context, url string) (*sqlx.DB, error) {
db, err := sqlx.Open("pgx", url)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, fmt.Errorf("reach database: %w", err)
}
return db, nil
}
// Migrate applies every pending migration as the owner, under a session
// advisory lock, so two instances starting together never race. A failed
// migration returns an error and the boot stops.
func Migrate(ctx context.Context, log *slog.Logger, ownerURL string) error {
db, err := Open(ctx, ownerURL)
if err != nil {
return fmt.Errorf("owner connection: %w", err)
}
defer func() { _ = db.Close() }()
files, err := fs.Sub(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("migration files: %w", err)
}
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return fmt.Errorf("migration lock: %w", err)
}
provider, err := goose.NewProvider(goose.DialectPostgres, db.DB, files, goose.WithSessionLocker(locker))
if errors.Is(err, goose.ErrNoMigrations) {
// The series is empty until the first module adds its schema.
log.InfoContext(ctx, "no migrations to apply")
return nil
}
if err != nil {
return fmt.Errorf("migration provider: %w", err)
}
results, err := provider.Up(ctx)
if err != nil {
return fmt.Errorf("apply migrations: %w", err)
}
for _, r := range results {
log.InfoContext(ctx, "migration applied", "version", r.Source.Version, "file", r.Source.Path, "took", r.Duration)
}
return nil
}