| 1 | package adopt |
| 2 | |
| 3 | // The adoption journal: what the CARLOS half observed, wrote and was |
| 4 | // told, kept in Alta's database beside the engine's own state. Every |
| 5 | // payload is sealed under ALTA_DEK with the purpose |
| 6 | // alta/adopt/<table>/<key> before it is stored, so no vd1: digest, cv1: |
| 7 | // version, agent key value or Home head is ever on disk in the clear. |
| 8 | |
| 9 | import ( |
| 10 | "context" |
| 11 | "database/sql" |
| 12 | "embed" |
| 13 | "encoding/json" |
| 14 | "errors" |
| 15 | "slices" |
| 16 | |
| 17 | "amadan.net/oficina/alta/provision" |
| 18 | "amadan.net/rastrillo/rastrillo/migrate" |
| 19 | ) |
| 20 | |
| 21 | //go:embed migrations/*.sql |
| 22 | var migrationFS embed.FS |
| 23 | |
| 24 | // Schema is the journal's migration set. The command applies it beside |
| 25 | // Alta's own: provision.NewStore(ctx, db, dek, now, adopt.Schema). |
| 26 | var Schema = migrate.MustFromFS(migrationFS, "adopt") |
| 27 | |
| 28 | var ( |
| 29 | // ErrSchemaMissing is a database without the journal's migrations. |
| 30 | // NewStore applies nothing itself. |
| 31 | ErrSchemaMissing = errors.New("adopt: the adoption journal's schema is not applied") |
| 32 | // ErrBaselineExists is a second baseline for an app: a baseline is |
| 33 | // captured once and never rebaselined. |
| 34 | ErrBaselineExists = errors.New("adopt: the app already has its baseline") |
| 35 | // ErrCanaryNotActive is Plan C's gate closed: Plan B has not |
| 36 | // activated the canary, or the canary has since been rolled back or |
| 37 | // disabled. |
| 38 | ErrCanaryNotActive = errors.New("canary-not-active") |
| 39 | ) |
| 40 | |
| 41 | // Home preflight phases. |
| 42 | const ( |
| 43 | PhasePreInitialize = "pre-initialize" |
| 44 | PhasePrePlanA = "pre-plan-a" |
| 45 | ) |
| 46 | |
| 47 | // CanaryApp is the app Plan B activates alone, before Plan C. |
| 48 | const CanaryApp = "calendar" |
| 49 | |
| 50 | // Store is the adoption journal over Alta's provision store. |
| 51 | type Store struct { |
| 52 | ps *provision.Store |
| 53 | db *sql.DB |
| 54 | } |
| 55 | |
| 56 | // NewStore opens the journal over ps. It refuses with ErrSchemaMissing |
| 57 | // unless every one of Schema's migrations is in the database's ledger. |
| 58 | func NewStore(ps *provision.Store) (*Store, error) { |
| 59 | if ps == nil { |
| 60 | return nil, errors.New("adopt: no provision store") |
| 61 | } |
| 62 | db := ps.DB() |
| 63 | ctx := context.Background() |
| 64 | var n int |
| 65 | if err := db.QueryRowContext(ctx, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='rastrillo_migrations'").Scan(&n); err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | if n == 0 { |
| 69 | return nil, ErrSchemaMissing |
| 70 | } |
| 71 | for _, m := range Schema.All() { |
| 72 | if err := db.QueryRowContext(ctx, "SELECT count(*) FROM rastrillo_migrations WHERE id=?", m.ID).Scan(&n); err != nil { |
| 73 | return nil, err |
| 74 | } |
| 75 | if n == 0 { |
| 76 | return nil, ErrSchemaMissing |
| 77 | } |
| 78 | } |
| 79 | return &Store{ps: ps, db: db}, nil |
| 80 | } |
| 81 | |
| 82 | // Tables, and so the middle of each payload's purpose. |
| 83 | const ( |
| 84 | tHomePreflights = "adopt_home_preflights" |
| 85 | tBaselines = "adopt_baselines" |
| 86 | tWrites = "adopt_writes" |
| 87 | tRollbacks = "adopt_rollbacks" |
| 88 | tAfters = "adopt_afters" |
| 89 | // The delivery check takes the place, and the table, of Paul's |
| 90 | // witness (Home discussion 103, 2026-11-17): the payload changed |
| 91 | // shape, the purpose did not. adopt_checks, the live checks' table, |
| 92 | // is no longer written or read. Both stay, by name, for compatibility: |
| 93 | // the production state already holds them, and a rename or drop is |
| 94 | // not an additive migration. |
| 95 | tWitnesses = "adopt_witnesses" |
| 96 | ) |
| 97 | |
| 98 | func purpose(table, key string) string { return "alta/adopt/" + table + "/" + key } |
| 99 | |
| 100 | func knownApp(app string) error { |
| 101 | if _, ok := provision.AppBySlug(app); !ok { |
| 102 | return errors.New("adopt: not an Oficina app") |
| 103 | } |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | // exec runs one statement on a connection with secure_delete on, however |
| 108 | // the database was opened: a replaced record is overwritten, not left in |
| 109 | // a free page. |
| 110 | func (s *Store) exec(ctx context.Context, q string, args ...any) (sql.Result, error) { |
| 111 | conn, err := s.db.Conn(ctx) |
| 112 | if err != nil { |
| 113 | return nil, err |
| 114 | } |
| 115 | defer conn.Close() |
| 116 | if _, err := conn.ExecContext(ctx, "PRAGMA secure_delete=ON"); err != nil { |
| 117 | return nil, err |
| 118 | } |
| 119 | return conn.ExecContext(ctx, q, args...) |
| 120 | } |
| 121 | |
| 122 | func (s *Store) sealed(table, key string, v any) ([]byte, error) { |
| 123 | b, err := json.Marshal(v) |
| 124 | if err != nil { |
| 125 | return nil, err |
| 126 | } |
| 127 | return s.ps.SealAdoption(purpose(table, key), b) |
| 128 | } |
| 129 | |
| 130 | // put replaces table's row for key with v, sealed. |
| 131 | func (s *Store) put(ctx context.Context, table, col, key string, v any) error { |
| 132 | sealed, err := s.sealed(table, key, v) |
| 133 | if err != nil { |
| 134 | return err |
| 135 | } |
| 136 | _, err = s.exec(ctx, "INSERT INTO "+table+"("+col+",sealed) VALUES(?,?) ON CONFLICT("+col+") DO UPDATE SET sealed=excluded.sealed", key, sealed) |
| 137 | return err |
| 138 | } |
| 139 | |
| 140 | // get opens table's row for key into v; false when there is none. |
| 141 | func (s *Store) get(ctx context.Context, table, col, key string, v any) (bool, error) { |
| 142 | var sealed []byte |
| 143 | err := s.db.QueryRowContext(ctx, "SELECT sealed FROM "+table+" WHERE "+col+"=?", key).Scan(&sealed) |
| 144 | if errors.Is(err, sql.ErrNoRows) { |
| 145 | return false, nil |
| 146 | } |
| 147 | if err != nil { |
| 148 | return false, err |
| 149 | } |
| 150 | b, err := s.ps.OpenAdoption(purpose(table, key), sealed) |
| 151 | if err != nil { |
| 152 | return false, errors.New("adopt: a journal row does not open") |
| 153 | } |
| 154 | if err := json.Unmarshal(b, v); err != nil { |
| 155 | return false, errors.New("adopt: a journal row does not decode") |
| 156 | } |
| 157 | return true, nil |
| 158 | } |
| 159 | |
| 160 | func homePhase(phase string) error { |
| 161 | if phase != PhasePreInitialize && phase != PhasePrePlanA { |
| 162 | return errors.New("adopt: not a Home preflight phase") |
| 163 | } |
| 164 | return nil |
| 165 | } |
| 166 | |
| 167 | // SaveHomePreflight records Home's state before r.Phase, replacing an |
| 168 | // earlier preflight for the same phase. |
| 169 | func (s *Store) SaveHomePreflight(ctx context.Context, r HomePreflight) error { |
| 170 | if err := homePhase(r.Phase); err != nil { |
| 171 | return err |
| 172 | } |
| 173 | return s.put(ctx, tHomePreflights, "phase", r.Phase, r) |
| 174 | } |
| 175 | |
| 176 | // HomePreflight reads the preflight recorded before phase. |
| 177 | func (s *Store) HomePreflight(ctx context.Context, phase string) (HomePreflight, bool, error) { |
| 178 | if err := homePhase(phase); err != nil { |
| 179 | return HomePreflight{}, false, err |
| 180 | } |
| 181 | var r HomePreflight |
| 182 | ok, err := s.get(ctx, tHomePreflights, "phase", phase, &r) |
| 183 | return r, ok, err |
| 184 | } |
| 185 | |
| 186 | // SaveBaseline records app's baseline. It is captured once: a second |
| 187 | // one is refused with ErrBaselineExists, and the table refuses any |
| 188 | // update, delete or replacement of a stored one. |
| 189 | func (s *Store) SaveBaseline(ctx context.Context, app string, snap Snapshot) error { |
| 190 | if err := knownApp(app); err != nil { |
| 191 | return err |
| 192 | } |
| 193 | sealed, err := s.sealed(tBaselines, app, snap) |
| 194 | if err != nil { |
| 195 | return err |
| 196 | } |
| 197 | conn, err := s.db.Conn(ctx) |
| 198 | if err != nil { |
| 199 | return err |
| 200 | } |
| 201 | defer conn.Close() |
| 202 | if _, err := conn.ExecContext(ctx, "PRAGMA secure_delete=ON"); err != nil { |
| 203 | return err |
| 204 | } |
| 205 | tx, err := conn.BeginTx(ctx, nil) |
| 206 | if err != nil { |
| 207 | return err |
| 208 | } |
| 209 | defer tx.Rollback() |
| 210 | var n int |
| 211 | if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM adopt_baselines WHERE app=?", app).Scan(&n); err != nil { |
| 212 | return err |
| 213 | } |
| 214 | if n > 0 { |
| 215 | return ErrBaselineExists |
| 216 | } |
| 217 | if _, err := tx.ExecContext(ctx, "INSERT INTO adopt_baselines(app,sealed) VALUES(?,?)", app, sealed); err != nil { |
| 218 | return err |
| 219 | } |
| 220 | return tx.Commit() |
| 221 | } |
| 222 | |
| 223 | // Baseline reads app's baseline. |
| 224 | func (s *Store) Baseline(ctx context.Context, app string) (Snapshot, bool, error) { |
| 225 | var snap Snapshot |
| 226 | ok, err := s.get(ctx, tBaselines, "app", app, &snap) |
| 227 | return snap, ok, err |
| 228 | } |
| 229 | |
| 230 | var ( |
| 231 | writeStates = []string{"sent", "landed", "stopped"} |
| 232 | rollbackStates = []string{"sent", "unset", "restarted", "stopped"} |
| 233 | ) |
| 234 | |
| 235 | // SaveWrite records the latest state of r.App's write. |
| 236 | func (s *Store) SaveWrite(ctx context.Context, r WriteRecord) error { |
| 237 | if err := knownApp(r.App); err != nil { |
| 238 | return err |
| 239 | } |
| 240 | if !slices.Contains(writeStates, r.State) { |
| 241 | return errors.New("adopt: not a write state") |
| 242 | } |
| 243 | return s.put(ctx, tWrites, "app", r.App, r) |
| 244 | } |
| 245 | |
| 246 | // Write reads app's write record. |
| 247 | func (s *Store) Write(ctx context.Context, app string) (WriteRecord, bool, error) { |
| 248 | var r WriteRecord |
| 249 | ok, err := s.get(ctx, tWrites, "app", app, &r) |
| 250 | return r, ok, err |
| 251 | } |
| 252 | |
| 253 | // SaveRollback records the latest state of r.App's rollback. |
| 254 | func (s *Store) SaveRollback(ctx context.Context, r RollbackRecord) error { |
| 255 | if err := knownApp(r.App); err != nil { |
| 256 | return err |
| 257 | } |
| 258 | if !slices.Contains(rollbackStates, r.State) { |
| 259 | return errors.New("adopt: not a rollback state") |
| 260 | } |
| 261 | return s.put(ctx, tRollbacks, "app", r.App, r) |
| 262 | } |
| 263 | |
| 264 | // Rollback reads app's rollback record. |
| 265 | func (s *Store) Rollback(ctx context.Context, app string) (RollbackRecord, bool, error) { |
| 266 | var r RollbackRecord |
| 267 | ok, err := s.get(ctx, tRollbacks, "app", app, &r) |
| 268 | return r, ok, err |
| 269 | } |
| 270 | |
| 271 | // SaveAfter records app's after snapshot, replacing an earlier one. |
| 272 | func (s *Store) SaveAfter(ctx context.Context, app string, snap Snapshot) error { |
| 273 | if err := knownApp(app); err != nil { |
| 274 | return err |
| 275 | } |
| 276 | return s.put(ctx, tAfters, "app", app, snap) |
| 277 | } |
| 278 | |
| 279 | // After reads app's after snapshot. |
| 280 | func (s *Store) After(ctx context.Context, app string) (Snapshot, bool, error) { |
| 281 | var snap Snapshot |
| 282 | ok, err := s.get(ctx, tAfters, "app", app, &snap) |
| 283 | return snap, ok, err |
| 284 | } |
| 285 | |
| 286 | // SaveDeliveryCheck records c.App's delivery check, replacing an |
| 287 | // earlier one. |
| 288 | func (s *Store) SaveDeliveryCheck(ctx context.Context, c DeliveryCheck) error { |
| 289 | if err := knownApp(c.App); err != nil { |
| 290 | return err |
| 291 | } |
| 292 | return s.put(ctx, tWitnesses, "app", c.App, c) |
| 293 | } |
| 294 | |
| 295 | // DeliveryCheck reads app's delivery check. |
| 296 | func (s *Store) DeliveryCheck(ctx context.Context, app string) (DeliveryCheck, bool, error) { |
| 297 | var c DeliveryCheck |
| 298 | ok, err := s.get(ctx, tWitnesses, "app", app, &c) |
| 299 | return c, ok, err |
| 300 | } |
| 301 | |
| 302 | // CanaryGate is Plan C's gate, the one implementation of it (Paul, |
| 303 | // 2026-11-17: Plan C waits on Plan B alone). The canary is never gated. |
| 304 | // Every other app is admitted only once Plan B's activation of the |
| 305 | // canary is done in the engine's steps, and only while the canary has |
| 306 | // neither a rollback in the journal (in any state) nor a done disable; |
| 307 | // otherwise ErrCanaryNotActive. |
| 308 | func (s *Store) CanaryGate(ctx context.Context, app string) error { |
| 309 | if app == CanaryApp { |
| 310 | return nil |
| 311 | } |
| 312 | if knownApp(app) != nil { |
| 313 | return ErrCanaryNotActive |
| 314 | } |
| 315 | _, active, err := s.ps.Done(ctx, provision.AdoptionLabel, CanaryApp, provision.StepActivate) |
| 316 | if err != nil { |
| 317 | return err |
| 318 | } |
| 319 | _, disabled, err := s.ps.Done(ctx, provision.AdoptionLabel, CanaryApp, provision.StepDisable) |
| 320 | if err != nil { |
| 321 | return err |
| 322 | } |
| 323 | _, rolledBack, err := s.Rollback(ctx, CanaryApp) |
| 324 | if err != nil { |
| 325 | return err |
| 326 | } |
| 327 | if !active || disabled || rolledBack { |
| 328 | return ErrCanaryNotActive |
| 329 | } |
| 330 | return nil |
| 331 | } |
| 332 | |