package adopt
// The adoption journal: what the CARLOS half observed, wrote and was
// told, kept in Alta's database beside the engine's own state. Every
// payload is sealed under ALTA_DEK with the purpose
// alta/adopt/
/ before it is stored, so no vd1: digest, cv1:
// version, agent key value or Home head is ever on disk in the clear.
import (
"context"
"database/sql"
"embed"
"encoding/json"
"errors"
"slices"
"amadan.net/oficina/alta/provision"
"amadan.net/rastrillo/rastrillo/migrate"
)
//go:embed migrations/*.sql
var migrationFS embed.FS
// Schema is the journal's migration set. The command applies it beside
// Alta's own: provision.NewStore(ctx, db, dek, now, adopt.Schema).
var Schema = migrate.MustFromFS(migrationFS, "adopt")
var (
// ErrSchemaMissing is a database without the journal's migrations.
// NewStore applies nothing itself.
ErrSchemaMissing = errors.New("adopt: the adoption journal's schema is not applied")
// ErrBaselineExists is a second baseline for an app: a baseline is
// captured once and never rebaselined.
ErrBaselineExists = errors.New("adopt: the app already has its baseline")
// ErrCanaryNotActive is Plan C's gate closed: Plan B has not
// activated the canary, or the canary has since been rolled back or
// disabled.
ErrCanaryNotActive = errors.New("canary-not-active")
)
// Home preflight phases.
const (
PhasePreInitialize = "pre-initialize"
PhasePrePlanA = "pre-plan-a"
)
// CanaryApp is the app Plan B activates alone, before Plan C.
const CanaryApp = "calendar"
// Store is the adoption journal over Alta's provision store.
type Store struct {
ps *provision.Store
db *sql.DB
}
// NewStore opens the journal over ps. It refuses with ErrSchemaMissing
// unless every one of Schema's migrations is in the database's ledger.
func NewStore(ps *provision.Store) (*Store, error) {
if ps == nil {
return nil, errors.New("adopt: no provision store")
}
db := ps.DB()
ctx := context.Background()
var n int
if err := db.QueryRowContext(ctx, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='rastrillo_migrations'").Scan(&n); err != nil {
return nil, err
}
if n == 0 {
return nil, ErrSchemaMissing
}
for _, m := range Schema.All() {
if err := db.QueryRowContext(ctx, "SELECT count(*) FROM rastrillo_migrations WHERE id=?", m.ID).Scan(&n); err != nil {
return nil, err
}
if n == 0 {
return nil, ErrSchemaMissing
}
}
return &Store{ps: ps, db: db}, nil
}
// Tables, and so the middle of each payload's purpose.
const (
tHomePreflights = "adopt_home_preflights"
tBaselines = "adopt_baselines"
tWrites = "adopt_writes"
tRollbacks = "adopt_rollbacks"
tAfters = "adopt_afters"
// The delivery check takes the place, and the table, of Paul's
// witness (Home discussion 103, 2026-11-17): the payload changed
// shape, the purpose did not. adopt_checks, the live checks' table,
// is no longer written or read. Both stay, by name, for compatibility:
// the production state already holds them, and a rename or drop is
// not an additive migration.
tWitnesses = "adopt_witnesses"
)
func purpose(table, key string) string { return "alta/adopt/" + table + "/" + key }
func knownApp(app string) error {
if _, ok := provision.AppBySlug(app); !ok {
return errors.New("adopt: not an Oficina app")
}
return nil
}
// exec runs one statement on a connection with secure_delete on, however
// the database was opened: a replaced record is overwritten, not left in
// a free page.
func (s *Store) exec(ctx context.Context, q string, args ...any) (sql.Result, error) {
conn, err := s.db.Conn(ctx)
if err != nil {
return nil, err
}
defer conn.Close()
if _, err := conn.ExecContext(ctx, "PRAGMA secure_delete=ON"); err != nil {
return nil, err
}
return conn.ExecContext(ctx, q, args...)
}
func (s *Store) sealed(table, key string, v any) ([]byte, error) {
b, err := json.Marshal(v)
if err != nil {
return nil, err
}
return s.ps.SealAdoption(purpose(table, key), b)
}
// put replaces table's row for key with v, sealed.
func (s *Store) put(ctx context.Context, table, col, key string, v any) error {
sealed, err := s.sealed(table, key, v)
if err != nil {
return err
}
_, err = s.exec(ctx, "INSERT INTO "+table+"("+col+",sealed) VALUES(?,?) ON CONFLICT("+col+") DO UPDATE SET sealed=excluded.sealed", key, sealed)
return err
}
// get opens table's row for key into v; false when there is none.
func (s *Store) get(ctx context.Context, table, col, key string, v any) (bool, error) {
var sealed []byte
err := s.db.QueryRowContext(ctx, "SELECT sealed FROM "+table+" WHERE "+col+"=?", key).Scan(&sealed)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
b, err := s.ps.OpenAdoption(purpose(table, key), sealed)
if err != nil {
return false, errors.New("adopt: a journal row does not open")
}
if err := json.Unmarshal(b, v); err != nil {
return false, errors.New("adopt: a journal row does not decode")
}
return true, nil
}
func homePhase(phase string) error {
if phase != PhasePreInitialize && phase != PhasePrePlanA {
return errors.New("adopt: not a Home preflight phase")
}
return nil
}
// SaveHomePreflight records Home's state before r.Phase, replacing an
// earlier preflight for the same phase.
func (s *Store) SaveHomePreflight(ctx context.Context, r HomePreflight) error {
if err := homePhase(r.Phase); err != nil {
return err
}
return s.put(ctx, tHomePreflights, "phase", r.Phase, r)
}
// HomePreflight reads the preflight recorded before phase.
func (s *Store) HomePreflight(ctx context.Context, phase string) (HomePreflight, bool, error) {
if err := homePhase(phase); err != nil {
return HomePreflight{}, false, err
}
var r HomePreflight
ok, err := s.get(ctx, tHomePreflights, "phase", phase, &r)
return r, ok, err
}
// SaveBaseline records app's baseline. It is captured once: a second
// one is refused with ErrBaselineExists, and the table refuses any
// update, delete or replacement of a stored one.
func (s *Store) SaveBaseline(ctx context.Context, app string, snap Snapshot) error {
if err := knownApp(app); err != nil {
return err
}
sealed, err := s.sealed(tBaselines, app, snap)
if err != nil {
return err
}
conn, err := s.db.Conn(ctx)
if err != nil {
return err
}
defer conn.Close()
if _, err := conn.ExecContext(ctx, "PRAGMA secure_delete=ON"); err != nil {
return err
}
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var n int
if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM adopt_baselines WHERE app=?", app).Scan(&n); err != nil {
return err
}
if n > 0 {
return ErrBaselineExists
}
if _, err := tx.ExecContext(ctx, "INSERT INTO adopt_baselines(app,sealed) VALUES(?,?)", app, sealed); err != nil {
return err
}
return tx.Commit()
}
// Baseline reads app's baseline.
func (s *Store) Baseline(ctx context.Context, app string) (Snapshot, bool, error) {
var snap Snapshot
ok, err := s.get(ctx, tBaselines, "app", app, &snap)
return snap, ok, err
}
var (
writeStates = []string{"sent", "landed", "stopped"}
rollbackStates = []string{"sent", "unset", "restarted", "stopped"}
)
// SaveWrite records the latest state of r.App's write.
func (s *Store) SaveWrite(ctx context.Context, r WriteRecord) error {
if err := knownApp(r.App); err != nil {
return err
}
if !slices.Contains(writeStates, r.State) {
return errors.New("adopt: not a write state")
}
return s.put(ctx, tWrites, "app", r.App, r)
}
// Write reads app's write record.
func (s *Store) Write(ctx context.Context, app string) (WriteRecord, bool, error) {
var r WriteRecord
ok, err := s.get(ctx, tWrites, "app", app, &r)
return r, ok, err
}
// SaveRollback records the latest state of r.App's rollback.
func (s *Store) SaveRollback(ctx context.Context, r RollbackRecord) error {
if err := knownApp(r.App); err != nil {
return err
}
if !slices.Contains(rollbackStates, r.State) {
return errors.New("adopt: not a rollback state")
}
return s.put(ctx, tRollbacks, "app", r.App, r)
}
// Rollback reads app's rollback record.
func (s *Store) Rollback(ctx context.Context, app string) (RollbackRecord, bool, error) {
var r RollbackRecord
ok, err := s.get(ctx, tRollbacks, "app", app, &r)
return r, ok, err
}
// SaveAfter records app's after snapshot, replacing an earlier one.
func (s *Store) SaveAfter(ctx context.Context, app string, snap Snapshot) error {
if err := knownApp(app); err != nil {
return err
}
return s.put(ctx, tAfters, "app", app, snap)
}
// After reads app's after snapshot.
func (s *Store) After(ctx context.Context, app string) (Snapshot, bool, error) {
var snap Snapshot
ok, err := s.get(ctx, tAfters, "app", app, &snap)
return snap, ok, err
}
// SaveDeliveryCheck records c.App's delivery check, replacing an
// earlier one.
func (s *Store) SaveDeliveryCheck(ctx context.Context, c DeliveryCheck) error {
if err := knownApp(c.App); err != nil {
return err
}
return s.put(ctx, tWitnesses, "app", c.App, c)
}
// DeliveryCheck reads app's delivery check.
func (s *Store) DeliveryCheck(ctx context.Context, app string) (DeliveryCheck, bool, error) {
var c DeliveryCheck
ok, err := s.get(ctx, tWitnesses, "app", app, &c)
return c, ok, err
}
// CanaryGate is Plan C's gate, the one implementation of it (Paul,
// 2026-11-17: Plan C waits on Plan B alone). The canary is never gated.
// Every other app is admitted only once Plan B's activation of the
// canary is done in the engine's steps, and only while the canary has
// neither a rollback in the journal (in any state) nor a done disable;
// otherwise ErrCanaryNotActive.
func (s *Store) CanaryGate(ctx context.Context, app string) error {
if app == CanaryApp {
return nil
}
if knownApp(app) != nil {
return ErrCanaryNotActive
}
_, active, err := s.ps.Done(ctx, provision.AdoptionLabel, CanaryApp, provision.StepActivate)
if err != nil {
return err
}
_, disabled, err := s.ps.Done(ctx, provision.AdoptionLabel, CanaryApp, provision.StepDisable)
if err != nil {
return err
}
_, rolledBack, err := s.Rollback(ctx, CanaryApp)
if err != nil {
return err
}
if !active || disabled || rolledBack {
return ErrCanaryNotActive
}
return nil
}