# Existing-team adoption runner (`alta-adopt`) Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Revision 3 (2026-11-16).** Answers Astra's review and re-review, Paul's answers to Q1–Q5, and the 13 conflicts the pre-flight scan found (`.superpowers/sdd/2026-11-16-adoption-runner/preflight.md`). The task order changed: every task now consumes only what an earlier task produces.

**Goal:** A local operator command that adopts the six existing canonical Oficina apps (docs, sheets, slides, calendar, calls, memoria) into a Home directory team labelled `oficina`, so oficina-connect can route delegated calls to them. It writes only `<P>_AGENT_ISSUER` and `<P>_AGENT_TEAM`, and proves that nothing else changed.

**Architecture:** The runner lives in **oficina/alta** as a second binary, `cmd/alta-adopt`. It is never built into or deployed with the served `alta` binary.

- **Home's half** is a new adoption run in Alta's existing `provision` engine: signed `existing_team` plans, owner-seed, seed-team, provision, register, verify and activate. It therefore uses Alta's one operator signer, stream, journal, exact replay and resync.
- **CARLOS's half** is a new `adopt` package over a new `carlosop` client. It holds a short-lived Admin credential in memory only (Paul, 2026-11-16). It covers:
  - 522 Plan 1 snapshots and conditional writes;
  - the narrowed per-host restart;
  - the delivery probe and Paul's witnessed check;
  - the live checks and re-observation.
- `adopt` plugs into the engine through a one-method `provision.Observer` interface. The activation gate lives there, so nothing activates without complete, fresh evidence.

**Tech Stack:** Go 1.26.5 (`GOTOOLCHAIN` pinned by Alta's Makefile), `CGO_ENABLED=0`, rastrillo migrate/db/crypto, Alta `homeop`/`provision`, and Home `internal/operator` through `homecompat`. The live checks alone use agent-access `client` (module `amadan.net/oficina/agent-access.git` at `e4ea914`).

**Spec:** Home `implementation/existing-team-adoption.md` at oficina/home main `16da7ba`. Read it with `git -C /home/paulca/amadan.net/oficina/home show origin/main:implementation/existing-team-adoption.md`, without changing that checkout's branch.

Also read:
- the doors: carlos/platform `docs/superpowers/specs/2026-11-02-config-receipts-design.md` §4;
- the narrowed restart: `internal/console/apirestartscope.go` (branch `config-receipts-1`, worktree `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/config-receipts-1`);
- the rulings on oficina/home 103 and carlos/platform 522 (Paul, 2026-11-16);
- Alta's `AGENTS.md` and `README.md`, first.

---

## Where the runner lives, and why

**In oficina/alta, as a separate binary `cmd/alta-adopt`. Not in Home.**

1. **One signer, one stream, one journal.** The design requires that "Adoption and Alta share exactly one operator signer, installation, registry and device on both roles". Alta already holds that key and pins, and the stream machinery: `provision/engine.go` `op`, `replayHeld`, `signAndSend` and `windows`. Home has no client side of this protocol.
2. **The test doubles exist.** `homecompat` runs Alta's engine against Home's real `internal/operator`. The engine's `Config.AfterAct` hook injects a crash after any act (`provision/harness_test.go`).
3. **Alta already knows each app.** `provision.App` holds the `Prefix`, and `teamKeys` lists the team-mode keys.
4. **Home stays small and holds no platform credential** (Home AGENTS.md; home-provisioner: "Home keeps no platform provisioning credential").
5. **Initialize can run now.** Alta isn't deployed, so its web Initialize page can't be reached. `alta-adopt initialize` wraps the existing `StartInitialize`.

**Paul's rulings (2026-11-16), which this plan relies on:**
- **Q1:** `alta-adopt` may hold a short-lived Admin CARLOS credential in memory only. The served `alta` stays credential-free, and a test enforces that.
- **Q2:** For Slides and Calls, the delivery observable is their own 401 changing to agent-access's challenge.
- **Q3:** If another instance would receive the keys, the run stops.
- **Q4:** Paul creates a throwaway Oficina ID test account.
- **Q5:** The team's display name is "Oficina".

## Run shape

Home windows last 15 min (`WindowLifetime = 900`) and are never extended. A verify attempt lasts at most 600 s, and activation's `completed_at` must be within 300 s of now. Restarts and the per-app witnessed checks don't fit in one window, so there are three plans after initialize:

| Phase | Window | What happens |
|---|---|---|
| 0a Home preflight | none | signed inspect of both roles, plus Paul's read-only `carlos db query` counts (Task 6) |
| 0b CARLOS preflight | none | per app: 522 reads, prospective key inheritance, identity, delivery baseline (Task 7) |
| 1 initialize | directory `initialize` | sequence 1 on the directory stream, Paul's typed §12 attestation |
| 2 Plan A | `create-team`, `existing_team=<proposed SQID>`, label `oficina`, name "Oficina", six apps, owner Paul | owner-seed, seed-team, provision ×6, register ×6 (verified, nothing inserted) |
| 3 configure | none | per app: mandatory preflight, sealed baseline, conditional PUT, receipt, host-scoped restart, preserved after snapshot, Paul's witness |
| 4 Plan B | `add-apps`, `existing_team=<SQID>`, `calendar` | verify, re-observe, activate under `oficina/existing-app-activation/v1` |
| 5 live checks | none | revocation and permission checks against connect for calendar. **Plan C is refused until they are recorded as passed.** |
| 6 Plan C | `add-apps`, `existing_team=<SQID>`, the other five | verify, re-observe, activate |

**Phases may span sessions and days.** The spec sets no age limit on the witness. It requires that activation is blocked until the check "is witnessed and recorded", and that the observation describes the running app. So the witness is bound to what it observed:
- the instance identity;
- the delivered version and header;
- the after snapshot's config.

Activation re-observes all three. Any change voids the witness and asks for a new one. There is no wall-clock limit.

## Global Constraints

- **Never print, log or store unsealed** any of these:
  - a secret, or a plain var's value;
  - any `vd1:` digest or `cv1:` version;
  - `environment_binding`;
  - a roster bearer, the operator key or the prefilter;
  - the CARLOS token or an access token;
  - the owner's address.

  Output carries key names, kinds, hosts, fixed codes and states only.
- **Never hold or hash a secret's plaintext.** Preservation is proved only with 522 `vd1:` digests. `EnvDigest` is applied only to the two agent keys' plain values, which the runner itself sends.
- **Dry-run by default.** Every subcommand that writes anywhere needs `--apply`: Home, CARLOS, connect, or the adoption journal. Task 14 has the table.
- **Every CARLOS config write is conditional.** It is `PUT /config` with `if_version` set to the version just read, and never `exec_delivery`. A 400 that refuses `if_version` stops the run.
- **Configure enforces every preflight refusal itself**, on a fresh read, immediately before its first PUT.
- **Baseline:** captured once per app, sealed before storage, never rebaselined. Retries follow 522 §4.7: the first matching branch wins, preserved keys first.
- **Preservation holds along the whole chain**, baseline → after snapshot → fresh, for every key in the baseline's effective config except the two added.
- **Both keys or neither** (Memoria refuses to boot with one). Write and unset them in one request.
- `<P>_AGENT_ISSUER = https://connect.oficina.works`, and `<P>_AGENT_TEAM` = the seeded SQID, equal to the plans' `existing_team`.
- **No team mode.** Refuse any key named by `provision.TeamKeyNames(app)`, and any other `<P>_TEAM_` key. `MEMORIA_TEAM` is not a team-mode key.
- **Canonical tuple only:** label `oficina`, consumer = app slug, origin `https://<app>.oficina.works`. These come from Alta's existing `PublicOrigin`, `PublicHost` and `ConsumerID`, which answer the canonical values for label `oficina` (Task 1). There are no parallel helpers.
- **Every restart, rollback included, goes through `RestartCanonical`.** It calls `POST …/restart/scope {"host"}` only after a `dry_run` that resolves exactly the canonical record host. A 404 (old console), a 503 or any other resolution stops the run. The app-wide `/restart` is never called, and nothing else calls `carlosop.RestartHost`.
- **Delivery:** the `/api/version` body and `X-Carlos-Version` equal the before snapshot, no redirect is followed, and `/healthz` returns 200.
- **Home requests:** nothing is inferred from a timeout, a lost answer is recovered only by exact replay, and nothing is deleted to clean up.
- **Not done:** no instance creation, storage swap, Home key change or `HOME_CONSUMERS` change.
- **The served binary stays clean:** `cmd/alta` must not import `adopt`, `carlosop` or agent-access.
- **Copy:** CLI strings live in `adopt/words.go` and go through the copy-review skill before merge.
- **Checks go through the Makefile only:** `make check PKG=<pkg> RUN=<regex>`, `make compat-check RUN=<regex>`, and `make ci`. Never bare `go test`.
- **Process:** branch `adopt-runner`, an Astra review recorded on home 103 and on the Alta branch discussion, CI green, then squash-merge. Leave `GOCACHE` at its default.

## Review Focus

1. **Another instance would inherit a new key** through a layer it shares with the canonical host. The run stops (Task 7, `TestPreflightRefusesInheritanceDespiteOtherOverride`).
2. **A platform writer touches the bundle around the write.** An unrelated key is reported but is not fatal. A preserved key resealed between the PUT and the after snapshot stops the run (Task 9, `TestAfterSnapshotRefusesSecretResealedBeforeCapture`).
3. **Slides and Calls already return their own 401.** Only agent-access's challenge counts as delivered (Task 4, `TestOperationsShapeDistinguishesAppMiddleware`).
4. **Revocation isn't enforced.** The membership check repeats the same call on the same connection. The owner check replays the saved authenticated request after revoke. Plan C is refused otherwise (Task 12; Task 13, `TestAdversePlanCRefusedWithoutLiveSuccess`).
5. **The run stops halfway.** On resume the runner classifies by rereading. It never double-writes, rebaselines or unsets a value it did not write (Tasks 9 and 15).

---

## File structure (oficina/alta)

| File | Task | Responsibility |
|---|---|---|
| `Makefile` | 1, 14 | `check`, `compat-check`, `GOPRIVATE` (Task 1); `adopt` target (Task 14) |
| `homeop/protocol.go`, `homeop/fakehome/fakehome.go` | 1 | `Plan.ExistingTeam`, `ExistingActivationPolicy`, `CanonicalOrigin`; fake adoption scope and ordered request log |
| `provision/apps.go` | 1 | `PublicOrigin`, `PublicHost`, `ConsumerID` answer canonically for `oficina`; `TeamKeyNames` |
| `homecompat/go.mod`, `homecompat/compat_test.go`, `homecompat/adopt_test.go` | 2 | pin Home ≥ `16da7ba`; harness; adoption against Home's real operator |
| `carlosop/*` | 3 | 522 doors, instance/channel reads, scoped restart; fake |
| `adopt/types.go`, `adopt/delivery.go` | 4 | shared types; delivery probe |
| `provision/migrations/0003_adoption.sql`, `provision/store.go`, `adopt/migrations/0001_adopt.sql`, `adopt/store.go` | 5 | `runs.adoption`, `CreateAdoption`; sealed journal |
| `adopt/homepreflight.go` | 6 | Home preflight |
| `adopt/snapshot.go` | 7 | snapshots, preservation, CARLOS preflight |
| `adopt/restart.go`, `adopt/witness.go`, `adopt/words.go` | 8 | `RestartCanonical`, `RestartAndWait`, witness |
| `adopt/write.go` | 9 | conditional write, `CaptureAfter`, rollback |
| `adopt/binding.go`, `adopt/observer.go`, `provision/adopt.go` (interface) | 10 | binding, activation gate |
| `provision/adopt.go`, `provision/engine.go`, `provision/steps.go` | 11 | Home-half adoption runs |
| `adopt/live.go`, `go.mod` | 12 | live checks |
| `adopt/gate_adverse_test.go`, `provision/adopt_adverse_test.go` | 13 | adverse suite |
| `cmd/alta-adopt/*`, `cmd/alta/imports_test.go` | 14 | the command |
| `adopt/rehearsal_test.go`, `homecompat/adopt_flow_test.go`, `README.md` | 15 | rehearsal, runbook |

---

### Task 1: Makefile, protocol mirror, canonical values in Alta's own helpers, fake Home

**Files:**
- Modify: `Makefile`, `homeop/protocol.go` (Plan ~l.132; consts ~l.61), `homeop/fakehome/fakehome.go`, `provision/apps.go` (~l.130–134, `teamKeys` ~l.421).
- Test: `homeop/protocol_test.go`, `homeop/fakehome/fakehome_test.go`, `provision/apps_test.go`.

**Interfaces (produced):**

Makefile:
- `check:` runs `CGO_ENABLED=0 go test $(PKG) -run '$(RUN)' -count=1`. `PKG` is required.
- `compat-check:` runs `cd homecompat && CGO_ENABLED=0 go test ./... -run '$(RUN)' -count=1`.
- Add both to `.PHONY`.
- `export GOPRIVATE := $(GOPRIVATE),amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git`, so that Task 12's dependency is fetched directly. (The `adopt` target is created in Task 14.)

`homeop`:
- `Plan.ExistingTeam string`, tagged `json:"existing_team,omitzero"`, placed after `Owner`, as Home's `internal/operator/plan.go` does.
- `ExistingActivationPolicy = "oficina/existing-app-activation/v1"`.
- `func CanonicalOrigin(app string) string`. This is the one Alta copy of Home's `internal/home/directorydata/canonical.go`. It lives in `homeop` because `provision`'s in-package tests import `fakehome`, so `fakehome` cannot import `provision`.

`provision`:
- `const AdoptionLabel = "oficina"`.
- `PublicOrigin(AdoptionLabel, app) == homeop.CanonicalOrigin(app)`.
- `PublicHost(AdoptionLabel, app) == app + ".oficina.works"`.
- `ConsumerID(AdoptionLabel, app) == app`.
- Every other label is unchanged.
- `func TeamKeyNames(app App) []string` returns the names `teamKeys` produces.

`fakehome`:
- Follows Home's `valid`, `routeScope`, the verify-only `register` branch, and the policy choice made by the window.
- `func (h *Home) Requests() []string` is the ordered list of committed actions with app, for example `"directory.activate-consumer:calendar"`. It is consumed by Tasks 11, 13 and 15.

- [ ] **Step 1: Write the failing tests.**
  - `TestPlanExistingTeamEncodesLikeHome`: the bytes contain `"display_name":"Oficina","existing_team":"Uk","issued_at"`, and the key is absent when the field is empty.
  - `TestCanonicalHelpersForOficina`: for each of the six apps, check the three helpers; for label `acme`, check they are unchanged.
  - `TestTeamKeyNamesMatchesRecipe`.
  - `TestFakeHomeAdoptionScope`:
    - seed happens only at the proposed SQID;
    - a non-canonical consumer or origin is refused;
    - register inserts nothing;
    - activate refuses `oficina/team-activation/v1` and accepts the existing policy;
    - ordinary create-team or add-apps under `oficina` is refused.
  - `TestFakeHomeRequestsOrdered`.
- [ ] **Step 2:** Run `make check PKG=./homeop/... RUN='TestPlanExistingTeam|TestFakeHome'` and `make check PKG=./provision/... RUN='TestCanonicalHelpers|TestTeamKeyNames'`. Expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Run the same commands and expect PASS. Then run `make ci`; existing engine tests are unchanged.
- [ ] **Step 5: Commit.** `homeop: existing_team; canonical values in Alta's helpers`

### Task 2: homecompat on Home's adoption code

**Files:**
- Modify: `homecompat/go.mod` and `go.sum` (Home, `home/roster` and `home/handoff` at oficina/home main `16da7ba`), and the harness in `homecompat/compat_test.go`.
- Modify if needed: `homeop/protocol.go`, to repair the mirror.
- Create: `homecompat/adopt_test.go`.

- [ ] **Step 1:** Bump the pin and run `make compat`. Existing tests should pass, or fail only where Home has since reserved `oficina` or changed an encoding. Fix the mirror in `homeop/protocol.go`, not the tests. Re-read `git diff 0cee9ba 16da7ba -- internal/operator` against `homeop/protocol.go`.
- [ ] **Step 2: Write the failing test** `TestHomeAcceptsAltaSignedExistingTeamPlan`:
  - an Alta-signed plan with `ExistingTeam` set to the proposed SQID verifies on both roles;
  - `PlanStore` keeps `existing_team`;
  - an ordinary create-team under `oficina` is refused.
- [ ] **Step 3:** Run `make compat-check RUN=TestHomeAcceptsAltaSigned` and expect FAIL until `compat_test.go`'s harness applies Home's adoption migration.
- [ ] **Step 4:** Fix the harness in `compat_test.go`. Expect PASS.
- [ ] **Step 5: Commit.** `homecompat: pin Home with existing-team adoption`

### Task 3: `carlosop`: an in-memory Admin client and its fake

**Files:** Create `carlosop/client.go`, `carlosop/digest.go`, `carlosop/fakecarlos/fakecarlos.go`. Test: `carlosop/client_test.go`, `carlosop/digest_test.go`.

**Interfaces (produced):**

```go
func New(console, account string, token []byte) *Client // Q1: token from an fd; never env/disk/log
func (c *Client) Close()                                 // zeroes the token
type Var struct { Key, Kind, Value, Digest string }      // Value only for kind "env"
type Layer struct { Bundle, Version string; Vars []Var }
type EffectiveVar struct { Key, Kind, Digest, From string; Shadows []string }
type Effective struct { Host, Environment string; Owned bool; Layers map[string]string; Vars []EffectiveVar }
type Receipt struct { Bundle, VersionBefore, VersionAfter string; Changed bool; Set, Unset, UnsetAbsent []string; Digests map[string]string; Others map[string]struct{ Before, After string } }
type Instance struct { Host, PublicHost, Account, App, Slug, Environment, Channel, Region string; CreatedAt time.Time; RecordSeq uint64; Move, ReplicaAssignment, Seed json.RawMessage }
type PutRequest struct { Environment string /* "" = default bundle */; Set map[string]string; Unset []string; IfVersion string }
type RestartRoute struct { Host, Environment, Unit string; Hibernate bool }
var ErrVersionMismatch, ErrNoConditional, ErrNotFound, ErrNoScopedRestart error // the only declarations; adopt reuses them
func (c *Client) Config(ctx context.Context, app, env string) (Layer, error)
func (c *Client) Effective(ctx context.Context, app, host string) (Effective, error)
func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, error)
func (c *Client) Instances(ctx context.Context, app string) ([]Instance, error)
func (c *Client) Instance(ctx context.Context, app, host string) (Instance, error)
func (c *Client) ChannelDigest(ctx context.Context, app, channel, version string) (string, error) // normalised: 64 lowercase hex, else error
func (c *Client) RestartHost(ctx context.Context, app, host string, dryRun bool) ([]RestartRoute, error) // only adopt.RestartCanonical calls this
func EnvDigest(value string) string // "vd1:"+hex sha256("carlos.config.var.v1"\0"env"\0value\0""\0"")
```

The fake (`fakecarlos`) keeps per-host layer chains: default, named, owned and overlay. Its hooks are `BeforePut`, `LoseNextAnswer`, `SetSecret`, `PlatformWrite`, `FailRestart`, `RestartCount(host)`, `AppWideRestarts()` and `NoScopedRestart()`.

- [ ] **Step 1: Write the failing tests.**
  - `TestEnvDigestMatchesPlatformVector` (the golden value comes from platform `internal/appconfig` at the merged Plan 1 commit).
  - `TestPutSendsIfVersionInBodyOnly`.
  - `TestPut412IsVersionMismatch`.
  - `TestPut400OnConditionalIsNoConditional`.
  - `TestRestartHostUsesScopeDoorOnly`.
  - `TestRestartHostOldConsoleFailsClosed`.
  - `TestChannelDigestNormalisesHex`.
  - `TestClientNeverFollowsRedirect`.
  - `TestErrorsCarryNoTokenOrValue`.
  - `TestTokenZeroedOnClose`.
- [ ] **Step 2:** Run `make check PKG=./carlosop/... RUN=.` and expect FAIL.
- [ ] **Step 3: Implement.** Model it on `console/fakeconsole`. `cv1:` is computed over the stored bytes; `vd1:` per 522 §4.3.
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `carlosop: 522 config doors, host-scoped restart, fake console`

### Task 4: Shared adoption types and the delivery probe

All types that later tasks store or pass around are defined here.

**Files:** Create `adopt/types.go`, `adopt/delivery.go`. Test: `adopt/types_test.go`, `adopt/delivery_test.go`.

**Interfaces (produced):**

```go
const Issuer = "https://connect.oficina.works"
func AgentKeys(app provision.App) [2]string                  // {Prefix+"_AGENT_ISSUER", Prefix+"_AGENT_TEAM"}
func CanonicalHost(app provision.App) string                 // provision.PublicHost(provision.AdoptionLabel, app.Slug)
type OpsShape string                                         // "absent", "app-401", "agent-401", "agent-200", "other"
type Delivery struct { Version, Header string; Redirected bool; Health int; Ops OpsShape; At time.Time }
func Probe(ctx context.Context, h *http.Client, origin string) (Delivery, error)
func Delivered(before, now Delivery) error // equal version+header, no redirect, health 200, now agent-shaped, before not
func Reverted(before, now Delivery) error  // equal version+header, health 200, now.Ops == before.Ops (rollback completion)
type Identity struct { Account, App, RecordHost, PublicHost, Slug, Environment, Channel, Region string; Owned, Moving bool
	CreatedAt time.Time; RecordSeq uint64; ReplicaAssignment, Seed string /* canonical JSON */ }
func IdentityOf(in carlosop.Instance, eff carlosop.Effective) Identity   // Moving = Move non-null; never errors
func SameIdentity(a, b Identity) []string // codes: storage (slug, created_at, replica, seed), instance (record host), alias (public host), environment, owned, channel, region, moving, record
type Snapshot struct { Identity Identity; WriteLayer string; Layer carlosop.Layer; Layers map[string]string; Vars []carlosop.EffectiveVar; HomeIssuer, HomeConsumer string; Delivery Delivery; At time.Time }
type Witness struct { App, Typed string; Identity Identity; Delivery Delivery; AfterVersion string /* the after snapshot's write-layer version, sealed */; At time.Time }
type HomePreflight struct { Phase string /* "pre-initialize" | "pre-plan-a" */; CredentialSeq, DirectorySeq int64; CredentialHead string; Generation *string
	ProposedID int64; ProposedSQID string; Pending, Open bool; Counts map[string]int64; AttestedAt time.Time }
type WriteRecord struct { App, State string /* sent, landed, stopped */; Sent map[string]string; Receipt *carlosop.Receipt; Code string }
type RollbackRecord struct { App, State string /* sent, unset, restarted, stopped */; Receipt *carlosop.Receipt; Code string }
var RequiredLiveChecks = []string{"non-member-refused", "member-allowed", "member-no-local-permission-refused", "revoked-membership-refused", "local-access-kept", "owner-allowed", "owner-revoked-refused", "owner-local-access-kept"}
```

**`agent-401`** means all of the following: status 401, `WWW-Authenticate` begins with `Bearer`, `Cache-Control: no-store`, and the body is `{"error":{"code":"unauthenticated",…}}`.

**Storage identity, decided here.** An instance's persistent storage is identified by the record's `Slug`, `CreatedAt`, `ReplicaAssignment` and `Seed`:
- recreating the instance, or swapping its storage, gives a new record or a new assignment;
- a move changes `Region` and sets `Move`.

`RecordSeq` is compared unless Task 7's step 0 shows that the runner's own write or restart bumps it.

- [ ] **Step 1: Write the failing tests.**
  - `TestOperationsShapeDistinguishesAppMiddleware`: `{"error":"unauthorized"}` is `app-401`.
  - `TestDeliveredRefusesVersionOrHeaderChange`.
  - `TestProbeRefusesRedirect`.
  - `TestRevertedRequiresBeforeShape`.
  - `TestSameIdentityFlagsEachField`: one subtest per code, including `owned` and `moving`.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='OperationsShape|Delivered|Probe|Reverted|SameIdentity'` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: shared types and delivery probe`

### Task 5: Adoption state, journalled and sealed

**Files:**
- Create: `provision/migrations/0003_adoption.sql`, `adopt/migrations/0001_adopt.sql`, `adopt/store.go`.
- Modify: `provision/store.go`.
- Test: `provision/store_adopt_test.go`, `adopt/store_test.go`.

**Interfaces.**

Consumed: Task 4's types.

Produced:

```go
// provision
type Run struct { /* existing fields */; Adoption bool } // scanRun reads the new column
func (s *Store) CreateAdoption(ctx context.Context, name, owner string, apps []string) error // teams/team_apps/owner_inputs; environment ""; NO environments rows
func (s *Store) NewAdoptionRun(ctx context.Context, kind string, apps []string) (int64, error)
// adopt — payloads sealed under "alta/adopt/<table>/<key>"
var Schema *migrate.Set
func NewStore(ps *provision.Store) (*Store, error)
func (s *Store) SaveHomePreflight(ctx context.Context, r HomePreflight) error
func (s *Store) HomePreflight(ctx context.Context, phase string) (HomePreflight, bool, error)
func (s *Store) SaveBaseline(ctx context.Context, app string, snap Snapshot) error // insert-only → ErrBaselineExists
func (s *Store) Baseline(ctx context.Context, app string) (Snapshot, bool, error)
func (s *Store) SaveWrite(ctx context.Context, r WriteRecord) error
func (s *Store) Write(ctx context.Context, app string) (WriteRecord, bool, error)
func (s *Store) SaveRollback(ctx context.Context, r RollbackRecord) error
func (s *Store) Rollback(ctx context.Context, app string) (RollbackRecord, bool, error)
func (s *Store) SaveAfter(ctx context.Context, app string, snap Snapshot) error
func (s *Store) After(ctx context.Context, app string) (Snapshot, bool, error)
func (s *Store) SaveWitness(ctx context.Context, w Witness) error
func (s *Store) Witness(ctx context.Context, app string) (Witness, bool, error)
func (s *Store) SaveCheck(ctx context.Context, name, outcome string) error
func (s *Store) LiveGate(ctx context.Context, app string) error // nil for "calendar"; else every RequiredLiveChecks name "passed", none failed → or "live-checks-missing"
```

**Migration wiring.** The caller (Task 14) opens the database with `provision.NewStore(ctx, db, dek, now, adopt.Schema)`. That applies `adopt.Schema` beside Alta's own migrations, using the existing `extra ...*migrate.Set` parameter. `adopt.NewStore` then confirms that the `adopt` migration ledger is present, and refuses with `ErrSchemaMissing` if not. It applies nothing itself.

`0003_adoption.sql`: `ALTER TABLE runs ADD COLUMN adoption INTEGER NOT NULL DEFAULT 0 CHECK (adoption IN (0, 1));`

`LiveGate` is the one implementation of the live-check rule. It is used by both `Observer` (Task 10) and the command (Task 14).

- [ ] **Step 1: Write the failing tests.**
  - `TestCreateAdoptionWritesNoEnvironmentRows`: `Guard.Environment` refuses every app for `oficina`.
  - `TestAdoptionRunColumnScanned`.
  - `TestAdoptStoreRefusesUnmigratedDB`.
  - `TestBaselineIsInsertOnly`.
  - `TestHomePreflightByPhase`.
  - `TestLiveGateCanaryAndRest`.
  - `TestAdoptRowsAreSealed`: the raw database file and WAL hold no `vd1:`, `cv1:`, value canary or owner canary.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Store|HomePreflightByPhase|LiveGate|Sealed|Baseline'` and `make check PKG=./provision/... RUN='Adoption'`. Expect FAIL.
- [ ] **Step 3: Implement.** Turn `secure_delete` on.
- [ ] **Step 4:** Expect PASS, then run `make ci`.
- [ ] **Step 5: Commit.** `Adoption state: sealed journal`

### Task 6: Home preflight with a supported evidence source

The spec's preflight checks `teams`, `memberships`, `team_instances` and both streams.

Signed inspect (`http_verbs.go` `HTTPInspection`) supplies:
- each role's `sequence` and `head`;
- `generation`;
- `proposed_team_id`/`_sqid` (a proposed id of 1 means `teams` is empty and `sqlite_sequence` is unused);
- pending and open plans.

It does **not** supply `memberships` or `team_instances`.

**Source: Paul's read-only `carlos db query`.** The db doors admit people only; `routedecls.go` says "admin is refused with the rest". So the runner prints the exact queries and records the counts Paul pastes back. A reviewed Home change that adds those counts to `directory.inspect` is the alternative. It is not planned (Q7).

**Files:** Create `adopt/homepreflight.go`. Test: `adopt/homepreflight_test.go`.

**Interfaces.**

Consumed: Task 4's `HomePreflight`, Task 5's store, `homeop.Client` (whose `Roles` holds both roles), and `provision.Store.Stream`.

Produced:

```go
func HomeQueries() []string // "SELECT count(*) FROM <t>" for teams, memberships, team_instances, operator_http_teams, roster_generation, roster_consumers, roster_tokens, roster_operator_receipts
func CheckHome(ctx context.Context, h *homeop.Client, ps *provision.Store, counts map[string]int64, phase string) (HomePreflight, []string, error)
```

`CheckHome` calls `h.Inspect(ctx, homeop.Credential)` and `h.Inspect(ctx, homeop.Directory)`, one call per role. For Alta's own journal it reads `ps.Stream(ctx, homeop.Credential)` and `ps.Stream(ctx, homeop.Directory)`.

**`pre-initialize`** requires all of:
- both inspected sequences are 0 with an empty head;
- `Generation` is nil;
- `ProposedID` is 1;
- there is no pending or open plan;
- every count is 0.

**`pre-plan-a`** requires all of:
- the directory's inspected `(sequence, head)` equals Alta's journal stream for the directory (only Alta's initialize so far);
- the credential's is `(0, "")`, or equals Alta's journal stream for the credential;
- `Generation` is set;
- `ProposedID` is 1;
- every count is 0, except `roster_generation = 1` and `roster_operator_receipts = 1`.

A count missing from the paste gives `count-missing-<t>`.

- [ ] **Step 1: Write the failing tests.**
  - `TestHomePreflightBeforeInitializeRefusesAnyRow`.
  - `TestHomePreflightRefusesUsedStreams`.
  - `TestHomePreflightRefusesProposedNotOne`.
  - `TestHomePreflightRefusesMissingCount`.
  - `TestHomePreflightPrePlanAAcceptsOwnInitialize`.
  - `TestHomePreflightPrePlanARefusesForeignDirectoryHead`.
  - `TestHomePreflightPrePlanARefusesExtraReceipt`.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestHomePreflight` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: Home preflight from inspect and attested counts`

### Task 7: Snapshots, preservation and CARLOS preflight

**Files:** Create `adopt/snapshot.go`. Test: `adopt/snapshot_test.go`.

**Interfaces.**

Consumed: Tasks 3 and 4, plus `provision.App` and `provision.TeamKeyNames`.

Produced:

```go
func Observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, error)
func Preserved(before, after Snapshot, added [2]string) []string // violations: "changed:<KEY>", "gone:<KEY>", "kind:<KEY>", "from:<KEY>", "layer:<name>" (untouched layer's version moved), plus SameIdentity codes; empty = preserved. New unrelated keys are not violations.
func NewKeys(before, after Snapshot, added [2]string) []string // "added:<KEY>", reported only
func TeamModeKeys(app provision.App, vars []carlosop.EffectiveVar) []string
func Preflight(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, mine map[string]string) (Snapshot, []string, error)
```

- The **write layer** is the layer `effective` names as the source of `<P>_HOME_ISSUER` for the canonical host: `""` (default) or the environment name. An overlay source is refused.
- **Prospective inheritance.** Take each agent key `k`, and each other instance `H` from `Instances(app)` with its `Effective(H)`. `H` would receive `k` when both hold:
  1. the write layer is in `H`'s chain (default: `H` is not owned; named: `H`'s environment equals it);
  2. no layer above it in `H`'s chain already sets `k`.

  Overrides of other keys are irrelevant. Any such `H` gives `inherits-<host>`.
- **Refusals:**
  - `agent-keys-present`, unless their digests equal `EnvDigest(mine[k])`;
  - `team-mode-<KEY>`;
  - `home-issuer-mismatch`;
  - `home-consumer-mismatch`;
  - `layer-overlay`;
  - `owned-environment`;
  - `instance-missing`;
  - `instance-moving`;
  - `inherits-<host>`;
  - `version-header-mismatch`;
  - `healthz`.

- [ ] **Step 0:** Read platform `internal/provision`, `internal/console/apiconfig.go` and `apirestartscope.go`. Record in a comment on `SameIdentity` whether a config PUT or a scoped restart changes `record_seq`. If one does, `record` is dropped from `SameIdentity`, and the reason is posted on home 103.
- [ ] **Step 1: Write the failing tests.**
  - `TestPreflightRefusesInheritanceDespiteOtherOverride`: a neighbour overrides `DOCS_HOME_ISSUER` but inherits both agent keys.
  - `TestPreflightAllowsOwnedEnvironmentNeighbour`.
  - `TestPreflightAllowsNeighbourThatAlreadyShadowsBothKeys`.
  - `TestPreflightRefusesTeamMode` (`MEMORIA_TEAM` alone passes).
  - `TestPreflightRefusesForeignAgentKeys`.
  - `TestPreflightRefusesMovingInstance`.
  - `TestPreservedReportsEachViolation`.
  - `TestPreservedIgnoresNewUnrelatedKey`.
  - `TestPreflightOutputHasNoValuesOrDigests`.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Preflight|Preserved'` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: snapshots, preservation, prospective-inheritance preflight`

### Task 8: Host-scoped restart and the witness

**Files:** Create `adopt/restart.go`, `adopt/witness.go`, `adopt/words.go`. Test: `adopt/restart_test.go`, `adopt/witness_test.go`.

**Interfaces.**

Consumed: Tasks 3–7.

Produced:

```go
func RestartCanonical(ctx context.Context, c *carlosop.Client, app provision.App, id Identity, apply bool) error // dry run must resolve exactly [id.RecordHost], else "restart-scope-<n>"; ErrNoScopedRestart passes through; then the real request
func RestartAndWait(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, id Identity, until func(Delivery) error, apply bool) (Delivery, error) // poll Probe every 5 s, ≤ 5 min, until `until` returns nil
func WitnessSentence(app provision.App) string // words.go, copy-reviewed
func RecordWitness(ctx context.Context, s *Store, c *carlosop.Client, h *http.Client, app provision.App, typed string, apply bool) error
```

`RecordWitness` refuses unless all of these hold:
- `typed` equals the sentence;
- the after snapshot exists;
- a fresh `Probe` passes `Delivered` against the baseline;
- a fresh identity equals the after snapshot's.

It stores `Witness{Identity, Delivery, AfterVersion}`. A `Hibernate: true` route in the dry run is accepted, because the probe wakes it and `Delivered` must still pass.

- [ ] **Step 1: Write the failing tests.**
  - `TestRestartCanonicalLeavesOtherInstancesUntouched`: `RestartCount` is 0 for every other host, and `AppWideRestarts()` is 0.
  - `TestRestartCanonicalRefusesWiderDryRun`.
  - `TestRestartCanonicalFailsClosedOnOldConsole`.
  - `TestRestartAndWaitTimesOut`.
  - `TestWitnessRefusesWrongAppSentence`.
  - `TestWitnessRefusesWithoutAgentShape`.
  - `TestWitnessRefusesIdentityChangedSinceAfter`.
  - `TestWitnessDryRunRecordsNothing`.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='RestartCanonical|RestartAndWait|Witness'` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: host-scoped restart and witness`

### Task 9: Configure's conditional write, `CaptureAfter`, and the journalled rollback

**Files:** Create `adopt/write.go`. Test: `adopt/write_test.go`.

**Interfaces.**

Consumed: Tasks 3–8. `carlosop.ErrNoConditional` and `ErrVersionMismatch` are reused, not redeclared.

Produced:

```go
type Branch int // Landed, Retry, StopPreservedChanged, StopConflict
func Classify(baseline, read carlosop.Layer, sent map[string]string) Branch
func WriteAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, sqid string, apply bool) (summary string, err error) // summary: the dry-run description, e.g. "set DOCS_AGENT_ISSUER, DOCS_AGENT_TEAM on default"
func CaptureAfter(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App) (Snapshot, error)
type RollbackBranch int // RolledBack, RetryUnset, StopForeign, StopPreservedChanged
func ClassifyRollback(baseline, read carlosop.Layer, sent map[string]string) RollbackBranch
func RollbackAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, apply bool) error
var ErrStopPreserved, ErrStopConflict, ErrStopForeign error
```

**`WriteAgentKeys`:**
1. If the journal says `landed`, return.
2. Run `Preflight` with `mine` set to the journal's sent values. Any code stops it, and nothing is written.
3. Load the baseline from the journal, or capture it and seal it.
4. Save the write as `sent`, then send `Put{Environment: baseline.WriteLayer, IfVersion: baseline.Layer.Version, Set: both}`.
5. On 200, require all of:
   - `Set` is exactly the two keys;
   - `Unset` and `UnsetAbsent` are empty;
   - `Digests[k] == EnvDigest(sent[k])` for both keys;
   - `Others` has before == after.

   Otherwise stop with `ErrStopConflict`.
6. On 412, or a lost answer, reread and `Classify`. On `Retry`, use the version just read. Give up after 3 attempts (`retry-exhausted`). Never rebaseline.

**`CaptureAfter`**, run after `RestartAndWait(…, until = Delivered vs baseline)`:
- observe;
- require `Preserved(baseline, after, AgentKeys)` to be empty;
- require both agent keys to carry the sent digests;
- require that no team-mode key is present.

Only then is the after snapshot stored. Otherwise return `ErrStopPreserved` and store nothing.

**`RollbackAgentKeys`**, journalled:
1. Reread and run `ClassifyRollback`:
   - **RetryUnset:** both keys hold exactly the sent digests.
   - **RolledBack:** both keys are absent and the preserved keys are equal.
   - **StopForeign:** either key holds another digest or kind, or only one is present.
   - **StopPreservedChanged:** a preserved key changed.
2. Save the rollback as `sent`, then send `Put{Environment, IfVersion: current, Unset: both}`. Accept a receipt in which `Unset ∪ UnsetAbsent` is exactly the two keys and `Set` is empty, so a retry after a lost committed answer passes.
3. Then **`RestartCanonical`**, through the same dry-run-resolves-one-route path. Never call `RestartHost` directly. Then `RestartAndWait(…, until = Reverted vs baseline)`.

Removing the stored keys alone doesn't stop the running process. The rollback is `restarted` only after `Reverted` passes. A failed restart leaves the record at `unset` with code `restart-failed`, so a resume continues from there.

- [ ] **Step 1: Write the failing tests.**

  Configure:
  - `TestConfigureCallsPreflightEvenWhenInvokedDirectly`, `TestConfigureRefusesForeignAgentKeys`, `TestConfigureRefusesTeamMode`, `TestConfigureRefusesInheritingNeighbour`: each makes zero PUTs.
  - `TestWriteHappyPathReceiptChecked`.
  - `TestWriteLostAnswerLanded`: exactly one PUT.
  - `TestWriteRetriesAfterUnrelatedKeyAdded`: the baseline bytes are unchanged.
  - `TestWriteStopsWhenPreservedKeyResealed`.
  - `TestWriteStopsOnPartialOrForeignAgentKeys`.
  - `TestWriteRejectsMalformedReceipts`: subtests for an extra `Set` key, a missing digest, a wrong digest, a non-empty `Unset`, and `Others` moved.
  - `TestWriteRefusesWithoutConditionalSupport`.
  - `TestWriteDryRunSendsNothing`.
  - `TestAfterSnapshotRefusesSecretResealedBeforeCapture`.

  Rollback:
  - `TestRollbackLostAnswerRetryAcceptsUnsetAbsent`.
  - `TestRollbackRefusesForeignValue`: zero PUTs.
  - `TestRollbackConflict412Rereads`.
  - `TestRollbackCrashAfterUnsetResumesToRestart`.
  - `TestRollbackRestartFailureLeavesUnsetState`.
  - `TestRollbackUsesScopedDryRun`: the fake sees a dry run before the restart, and no app-wide restart.
  - `TestRollbackCompleteOnlyWhenReverted`.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Configure|TestWrite|AfterSnapshot|TestRollback'` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: conditional write, preserved after snapshot, rollback`

### Task 10: Environment binding and the activation gate (Observer)

**Files:**
- Create: `adopt/binding.go`, `adopt/observer.go`, `provision/adopt.go` (the interface only).
- Test: `adopt/binding_test.go`, `adopt/observer_test.go`.

**Interfaces.**

Consumed: Tasks 3–9.

Produced:

```go
// provision
type Observation struct { AppVersion, ArtifactDigest, EnvironmentBinding string }
type Observer interface { Observe(ctx context.Context, app, teamSQID string) (Observation, error) }
// adopt
type BindingInput struct { Before, After Identity; BeforeVars, AfterVars []carlosop.EffectiveVar; BeforeLayers, AfterLayers map[string]string
	TeamSQID, Issuer, ArtifactSHA256, Version string; BeforeDelivery, AfterDelivery, NowDelivery Delivery; Witness Witness; HomePreflightAt time.Time }
func EnvironmentBinding(in BindingInput) string
type Observer struct { C *carlosop.Client; H *http.Client; S *Store; Artifacts map[string]string /* app → 64 lowercase hex */; Now func() time.Time }
func (o *Observer) Observe(ctx context.Context, app, teamSQID string) (provision.Observation, error)
```

**The binding** is `base64url(sha256(encoding/json.Marshal([]any{…})))` over these parts, in order:
1. `"oficina/existing-app-observation/v1"`;
2. the before and after identities;
3. the before and after var lists, each sorted as `[key, kind, digest, from]`;
4. the before and after layers;
5. the SQID, the issuer, the artifact SHA-256 and the version;
6. the before, after and now delivery observations;
7. the witness: app, sentence, identity, delivery, after version and time.

This puts Paul's witness and the delivery observations inside the signed observation.

**`Observe`** refuses, each time with a fixed code, unless every one of these holds:
- **Evidence present:** the `pre-plan-a` Home preflight, the baseline, a `landed` write, the after snapshot and the witness (`missing-<x>`).
- **Identity:** a fresh `IdentityOf` equals the baseline's, the after snapshot's and the witness's (`identity-<code>`).
- **Preservation:** `Preserved(baseline, after)` and `Preserved(baseline, fresh)` are both empty (`after-not-preserved`, `drift-<key>`).
- **Config:** the fresh read equals the after snapshot digest for digest. No team-mode key is present. Both agent keys carry the sent digests.
- **Witness still current:** the witness's `AfterVersion` equals the fresh write-layer version, and the witness's delivery version and header equal the fresh ones (`witness-superseded`). There is no wall-clock limit.
- **Delivery:** a fresh `Probe` passes `Delivered` against the baseline. The version matches `^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`.
- **Artifact:** `ChannelDigest(channel, version)` equals `Artifacts[app]`, both as 64 lowercase hex. `ArtifactDigest` is base64url of the same 32 bytes.
- **Live checks:** `S.LiveGate(ctx, app)` passes.

- [ ] **Step 1: Write the failing tests.**
  - `TestBindingIncludesWitnessAndDelivery`.
  - `TestBindingIsOrderIndependent`.
  - `TestObserverHappyPathEvidenceTokens`.
  - `TestObserverAcceptsWitnessFromEarlierSession`: the clock is moved forward 3 days and nothing else changes, so the gate passes.
  - `TestObserverRefusesSupersededWitness`.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Binding|TestObserver'` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: environment binding with witness; activation gate`

### Task 11: Home half: adoption runs in Alta's engine

**Files:**
- Modify: `provision/adopt.go`, `provision/engine.go` (`Config.Observer`; `Advance` dispatches on `run.Adoption`), `provision/steps.go`.
- Test: `provision/adopt_test.go`.

**Interfaces.**

Consumed: Tasks 1, 5 and 10. The canonical consumer, origin and host come from the existing `ConsumerID`, `PublicOrigin` and `PublicHost` with `AdoptionLabel`. No new helpers are added.

Produced:

```go
func (e *Engine) StartAdoption(ctx context.Context, name, owner string) (int64, error) // name must be "Oficina"; existing_team = directory inspect's proposed_team_sqid, read inside this call
func (e *Engine) ActivateAdopted(ctx context.Context, apps []string) (int64, error)    // add-apps, both roles, existing_team = stored team SQID, no owner
func (e *Engine) DisableAdopted(ctx context.Context, app, typed string) (int64, error) // retire-apps, label oficina, directory.disable-consumer only; typed must equal "oficina"
```

**Plan A:**
- owner-seed, with `TeamSQID == ExistingTeam` and `ExistingOnly`;
- seed-team as `Label "oficina"`, `Name "Oficina"`;
- for each app, the consumer and register steps;
- the run ends `done` with code `awaiting-configuration`;
- no console calls are made, and the owner's address is forgotten after the seed.

**Plan B/C, for each app:**
- `StepVerify` runs without the `/api/team` probe.
  - Timestamps follow the existing conservative approach. Home's verify result has no `issued_at`, so the step records the `Issued` the runner signed. For a held attempt recovered by replay, it records a later local time (`provision/steps.go:735–741`).
  - `started_at ≥ issued_at` holds, because the recorded value is never earlier than Home's.
- `StepActivate` uses `ExistingActivationPolicy` and the canonical consumer and audience. Its evidence comes from `Observer.Observe`, called after verify, with `Started` = the recorded issued time and `Completed` = now − `Skew`.
- A nil Observer gives `no-observer`, as in served Alta. An Observer refusal parks with its code and never activates.

- [ ] **Step 1: Write the failing tests.**
  - `TestAdoptionPlanACarriesExistingTeamOnBothRoles`.
  - `TestAdoptionSeedsAtProposedSQIDOnly`.
  - `TestAdoptionRegisterInsertsNothing`.
  - `TestAdoptionMakesNoConsoleCalls`.
  - `TestActivateAdoptedUsesExistingPolicy`.
  - `TestActivateAdoptedWithoutObserverFails`.
  - `TestActivateAdoptedParksOnObserverRefusal`: `fakehome.Requests()` has no `directory.activate-consumer`.
  - `TestActivateAdoptedStartedNotBeforeRecordedIssued`.
  - `TestActivateAdoptedReverifiesLapsedAttempt`.
  - `TestOrdinaryRunsStillRefuseOficina`.
  - `TestDisableAdoptedRequiresTypedLabel`.
  - `TestAdoptionCrashAfterEveryAct`: `Config.AfterAct` fails at each act key in turn, then the run resumes. Assert one team, six pending rows, and `Requests()` with no action repeated beyond its exact replays (the count per (action, app) is 1).
- [ ] **Step 2:** Run `make check PKG=./provision/... RUN='TestAdoption|TestActivateAdopted|TestOrdinaryRuns|TestDisableAdopted'` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS, then run `make ci`.
- [ ] **Step 5: Commit.** `provision: adoption runs for the canonical apps`

### Task 12: Live checks that prove revocation

**Files:**
- Create: `adopt/live.go`.
- Modify: `go.mod` (require `amadan.net/oficina/agent-access.git@e4ea914`; `GOPRIVATE` was set in Task 1).
- Test: `adopt/live_test.go`, using an httptest fake of connect.

**Interfaces.**

Consumed: Tasks 4 and 5 (`RequiredLiveChecks`, `SaveCheck`).

Produced:

```go
type MemoryStore struct{ /* client.Credentials in memory only */ }
type Prompter interface { Ask(ctx context.Context, sentence string) error }
func RunLive(ctx context.Context, server, sqid string, p Prompter, s *Store, open func(string) error, foreignEventID string, apply bool) error // apply=false: prints the steps, contacts nothing
```

Each step records `SaveCheck(name, "passed" | "failed:<code>" | "inconclusive")`.

**Before the checks:** the test account must have signed in to calendar.oficina.works once.

1. **`non-member-refused`.** The test account logs in (connection A). `Connection().Teams` does not contain the SQID. `calendar_free_busy` on its own range with `team=<sqid>` is refused.
2. **Paul adds the member.** When prompted, he adds the test account on the Team page. The test account reconnects and ticks the team (connection B).
3. **`member-allowed`.** Connection B calls `calendar_free_busy` on its own range, and it **must succeed**. The runner saves that exact authenticated request `C` (method, URL, body, bearer) and the token's expiry.
4. **`member-no-local-permission-refused`.** `calendar_get_event` with `foreignEventID` is refused with `not_found` or `forbidden`.
5. **Paul removes the member.** When prompted, he removes the test account. **`revoked-membership-refused`:** the runner replays `C` exactly, with the same bearer, before it expires, and requires a server authorization refusal: a 401 with the agent-access challenge, or a 403 with an agent-access error body.
6. **`local-access-kept`.** Paul types the sentence.
7. **`owner-allowed`.** Paul's own connection makes the same kind of call successfully, and the runner saves that request and token. Then it calls `Logout`. At `e4ea914`, `Logout` also deletes the local store.

   **`owner-revoked-refused`:** the runner replays the saved request with a plain `http.Client` (no redirects, same bearer) and requires a server authorization refusal. A transport error, a 5xx, or a replay after the token expires counts as `inconclusive`, and the step repeats with a fresh connection.

   **`owner-local-access-kept`:** Paul types the sentence.
8. **Always:** `Logout` every connection. Saved requests and tokens are zeroed when `RunLive` returns.

- [ ] **Step 1: Write the failing tests.**
  - `TestLiveFailsWhenRevocationNotEnforced`.
  - `TestLiveFailsWhenMemberCannotCallBeforeRemoval`: later steps are skipped and not passed.
  - `TestLiveRepeatsExactRequest`: the fake asserts the same bearer and body.
  - `TestLiveFailsWhenNonMemberSucceeds`.
  - `TestLiveFailsWhenForeignEventReadable`.
  - `TestLiveFailsWhenRevokeLeavesAccessValid`.
  - `TestLiveOwnerRevokeReplaysSavedRequest`.
  - `TestLiveReplayAfterExpiryIsInconclusive`.
  - `TestLiveRecordsCodesOnly`.
  - `TestLiveAlwaysLogsOut`.
  - `TestLiveDryRunContactsNothing`.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestLive` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: live checks proving revocation`

### Task 13: Activation-gate adverse suite

**Files:** Create `adopt/gate_adverse_test.go`, `provision/adopt_adverse_test.go`.

Every test name starts with `TestAdverse`. Each case is a subtest that asserts a specific code. It also asserts that `fakehome.Requests()` contains no `directory.activate-consumer` for that app.

- [ ] **Step 1: Write the tests.**
  - **Missing evidence:** no `pre-plan-a` Home preflight; no baseline; a write that is `sent` but not `landed`; no after snapshot; no witness. Also `TestAdversePlanCRefusedWithoutLiveSuccess`: a non-canary app with live checks missing, failed or inconclusive.
  - **Changed identity**, one each: slug, created_at, replica assignment, seed, record host, public alias, environment, owned, channel, region, moving, and record_seq. The record_seq case only applies if Task 7 step 0 kept it; otherwise `t.Skip` with the recorded reason.
  - **Changed config:**
    - a preserved secret resealed between the PUT and the after snapshot (a hand-written after row that bypassed `CaptureAfter`, so `after-not-preserved`);
    - a preserved secret resealed after the after snapshot;
    - a plain value changed; a key removed;
    - a new team-mode key;
    - an agent key with another digest;
    - an overlay that shadows an agent key.
  - **Superseded witness:** the after version changed, or the delivered version or header changed since the witness.
  - **Changed delivery:** the version body; the header; a redirect; healthz 503; ops reverted to `app-401`.
  - **Artifact:** the channel digest differs; the version is malformed.
  - **Malformed receipts:** each one from Task 9 leaves the write not `landed`, so `missing-write`.
  - **Failed local-permission check:** `member-no-local-permission-refused` failed, so Plan C is refused.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestAdverse` and `make check PKG=./provision/... RUN=TestAdverse`. A case that already passes is valid only if it fails when its guard is deliberately removed. Temporarily comment out that guard in `observer.go` or `adopt.go`, see the case fail, and restore the guard. Note each case checked this way in the commit body.
- [ ] **Step 3:** Fix any real gap in Task 10's or Task 11's files.
- [ ] **Step 4:** Expect PASS.
- [ ] **Step 5: Commit.** `adopt: activation gate adverse suite`

### Task 14: `cmd/alta-adopt`

**Files:**
- Create: `cmd/alta-adopt/main.go`, `cmd/alta-adopt/config.go`, `cmd/alta/imports_test.go`.
- Modify: `Makefile`. Add an `adopt:` target that builds `./cmd/alta-adopt` natively, stamped like `release`, and add it to `.PHONY`.
- Test: `cmd/alta-adopt/main_test.go`.

**`--apply` coverage.** Without `--apply`, every subcommand prints what it would do and writes nothing anywhere, the adoption journal included.

| Subcommand | Writes (only with `--apply`) |
|---|---|
| `home-preflight --phase pre-initialize\|pre-plan-a` | journal (the attestation); without it, prints the queries and checks the pasted counts |
| `preflight` | none (always read-only) |
| `initialize` | Home (initialize plan and operation), journal. Refuses without a recorded `pre-initialize` |
| `plan-a` | Home (plans), journal. Refuses without `pre-plan-a` |
| `advance --run <id>` | Home (operations), journal |
| `configure --app <a>` | CARLOS (PUT, restart), journal |
| `witness --app <a>` | journal; without it, shows what was observed and asks for no typed sentence |
| `activate --apps <list>` | Home (plans), journal. Non-canary apps are checked through `Store.LiveGate`, the same function `Observer` uses |
| `live` | connect (logins, calls, revokes), journal |
| `rollback-config --app <a>` | CARLOS, journal |
| `disable --app <a>` | Home; `typed` is read from the terminal and must equal "oficina" |
| `status` | none |

**Config.** `--config <file>` must be mode 0600 and owned by the user. It holds `alta_dek`, `operator_key`, `operator_prefilter`, the pins, `directory_provisioning_public_key`, `home_issuer`, `home_directory`, `carlos_console`, `carlos_account`, `state` and `artifacts {app: hex}`.

The command opens the store with `provision.NewStore(ctx, db, dek, now, adopt.Schema)` and then `adopt.NewStore`. The token is read from `--carlos-token-fd N` into a `[]byte`, which is zeroed on exit.

- [ ] **Step 1: Write the failing tests.**
  - `TestServedAltaImportsNoAdoptionCode`.
  - `TestWritesNeedApply`: table-driven over every row above. Without `--apply`, assert zero `fakehome.Requests()`, zero fake console writes or restarts, zero connect calls, and an unchanged journal row count.
  - `TestInitializeRefusedWithoutHomePreflight`.
  - `TestActivateNonCanaryRefusedWithoutLive`.
  - `TestConfigFileModeRefused`.
  - `TestOutputScrub`.
  - `TestTokenNeverInEnvOrDisk`.
- [ ] **Step 2:** Run `make check PKG=./cmd/... RUN=.` and expect FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4:** Expect PASS. Then run `make adopt` and `make ci`.
- [ ] **Step 5: Copy review.** Take `adopt/words.go` and the help text through the copy-review skill, and apply Paul's edits verbatim.
- [ ] **Step 6: Commit.** `alta-adopt: the local adoption command`

### Task 15: Rehearsal, homecompat flow, runbook

**Files:** Create `adopt/rehearsal_test.go`, `homecompat/adopt_flow_test.go`. Modify `README.md`.

- [ ] **Step 1: Write the tests.**
  - **`TestRehearsalFullRun`.** The full run, in order: Home preflights, initialize, Plan A, configure ×6, witness ×6, Plan B for calendar, the live checks, Plan C. At the end:
    - six routes are live;
    - every preserved digest is equal;
    - each layer differs only by the two keys;
    - every other host's `RestartCount` is 0 and `AppWideRestarts()` is 0.
  - **`TestRehearsalCrashAfterEveryAct`.** A crash at each Home act (`AfterAct`) and at each CARLOS act: before and after the PUT, after the restart, and mid-rollback. On resume, assert:
    - PUT count per app ≤ 2, and exactly 1 when the first answer was only lost;
    - the sealed baseline bytes are unchanged;
    - no unset of a foreign value;
    - `Requests()` has each (action, app) committed once.
  - **homecompat `TestAdoptionFlowAgainstRealHome`** runs against real Home. At the end, canonical `team_instances` are live, credential `consumers` is empty, and the manifest digest is unchanged.
- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestRehearsal` and `make compat-check RUN=TestAdoptionFlow`. Fix anything they find in the owning task's file.
- [ ] **Step 3:** Write the README runbook: phases, Paul's steps and the rollback table. Then run `make ci` and expect PASS.
- [ ] **Step 4: Read-only production rehearsal.** Run `alta-adopt home-preflight --phase pre-initialize`; Paul pastes the counts, and there is no `--apply`. Then run `alta-adopt preflight`. Record the codes on home 103.
- [ ] **Step 5:** Commit and push. Then the Alta branch discussion, Astra's branch review, CI green and squash-merge.

---

## Paul's action points, in order

Phases may fall in separate sessions on separate days. A witness stays valid until something it observed changes.

1. **Shared production keyset** (critical path step 5). OK one `alta keygen` plus `home team-keygen -subject pr_tsoeky4xus2habsdlun2jvzmku`, applied to `oficina-id` and then `oficina` (home 101 §5). Name the machine that holds the operator key.
2. **CARLOS credential.** Run `carlos services create --account oficina --role admin oficina-adoption`, and pass the result to `alta-adopt` only on a file descriptor.
3. **Home counts, before initialize.** Run the read-only `carlos db query` lines printed by `alta-adopt home-preflight --phase pre-initialize` and paste the counts. Then rerun it with `--apply` to record them.
4. **Watch the CARLOS preflight.** Any `inherits-<host>` stops the run (Q3).
5. **§12 attestation.** Run `alta-adopt initialize --apply` and type the attestation. Then confirm on [https://oficina.works/operator/confirm](https://oficina.works/operator/confirm) with a fresh passkey, in the system browser.
6. **Home counts, before Plan A.** Run `home-preflight --phase pre-plan-a --apply`.
7. **Plan A.** Run `alta-adopt plan-a --apply` and type the owner (his own address). Confirm on [https://oficina.works/operator/confirm](https://oficina.works/operator/confirm), then on [https://id.oficina.works/operator/confirm](https://id.oficina.works/operator/confirm), retyping the owner. Both pages should show the SQID, the six canonical hosts, "Oficina" and the same 8-hex prefix.
8. **Configure.** OK `configure --app <a> --apply` for each app. That is one config write and one restart, of that host only.
9. **Witness each app.** Sign in at `https://<app>.oficina.works` in the system browser, then run `witness --app <a> --apply` and type the sentence.
10. **Plan B.** Run `activate --apps calendar --apply`, then make the two confirmations.
11. **Test account.** Create the throwaway Oficina ID account, sign it in to calendar.oficina.works once, and pick one of his own events.
12. **Live checks** (oficina-connect deployed and `HOME_AGENT_DIRECTORY_TOKEN_SHA256` set). Run `live --apply`:
    - sign the test account in to connect;
    - add, then remove, the test account on the Team page;
    - witness both local sign-ins;
    - connect his own account, then revoke it.
13. **Plan C.** Run `activate --apps docs,sheets,slides,calls,memoria --apply`, then make the two confirmations. It is refused unless every live check passed.
14. **Clean up.** Run `carlos services delete oficina-adoption`, back up the state database, and delete the test account if he wishes.

## Every production write, in order, with rollback

| # | Write | Where | Rollback |
|---|---|---|---|
| 1 | `directory.initialize` | Home directory | **None** (by design). It is gated on the Home preflight and the §12 attestation. |
| 2 | Plan submissions for initialize, A, B and C, both roles | Home `operator_plans` | An unconfirmed plan expires after 15 min and is swept. |
| 3 | `credential.owner-seed` | Home credential | None needed: the receipt expires after 300 s. |
| 4 | `directory.seed-team` `oficina` / "Oficina", Paul as owner | Home directory | None (no deletes). The team is inert without a live instance, and the label is reserved. |
| 5 | `directory.provision-consumer` ×6 | Home directory | `alta-adopt disable --app <a> --apply`: a retire-apps plan, then `directory.disable-consumer`. |
| 6 | `credential.register-consumer` ×6 (verify only, nothing inserted) | Home credential | None needed. |
| 7 | Conditional `PUT /config` of `<P>_AGENT_ISSUER` and `<P>_AGENT_TEAM`, one per app | CARLOS `oficina`, on the canonical host's layer | `rollback-config --app <a> --apply`: a journalled conditional unset that refuses foreign values, **then the scoped restart (dry run first)**. It is complete only when the probe shows the old ops shape again. |
| 8 | `POST …/restart/scope {"host"}` after the dry run, one per app | CARLOS, that host only | Restart again after the rollback. |
| 9 | `directory.verify-consumer` for each app | Home directory | Expires after 600 s. |
| 10 | `directory.activate-consumer` for each app (live) | Home directory | Immediately: row 7's rollback, which stops delegated access at the app. Then `disable`. A revoke at connect also works. |
| 11 | Test connections at connect, and the membership add and remove (Paul) | connect, Home directory | The runner always revokes its connections. Paul removes the member. |

From row 4 onward, keep Home on an adoption-capable build: **never downgrade it, restore an older snapshot, or delete rows.**

## Effort

15 tasks, about 5–6 agent days in all. That includes one Astra round per task, the branch review and CI:

| Tasks | Effort |
|---|---|
| 1–2 | ½ day |
| 3 | ½ day |
| 4–5 | ¾ day |
| 6 | ¼ day |
| 7 | ½ day |
| 8 | ½ day |
| 9 | ¾ day |
| 10 | ½ day |
| 11 | ½–¾ day |
| 12 | ½ day |
| 13 | ½ day |
| 14–15 | ¾ day |

The production run is then about ½ agent day over four or more short Paul sessions, roughly 75–100 minutes of his time. Sessions may be days apart.

It is gated on 522 Plan 1 (the doors and `restart/scope`) being released to the production console. Phase 5 also needs oficina-connect live.

## Open questions

All of Q1–Q5 are answered (see "Paul's rulings" above). Two defaults remain, which Paul may override:

- **Q6:** calendar goes first as a canary, and Plan C is gated on the live checks.
- **Q7:** the Home table counts come from Paul's read-only `carlos db query`. A reviewed Home inspect change is the alternative, and is not planned.

**Dependency:** 522 Plan 1 must be released before Task 15's step 4. Task 7's step 0 checks `record_seq` against that release.

Nothing blocks implementation.
