oficina / alta Public

Plan the existing-team adoption runner (home 103)

Implementation plan for cmd/alta-adopt, reviewed by Astra (two rounds,
findings addressed), with Paul's 2026-11-16 rulings folded in.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 6e07f3c62f0d89c3ae457cd031abf75f51eb7cfc parent 916aac3
1 file changed, +705 −0
  • docs/superpowers/plans/2026-11-16-adoption-runner.md +705 −0
diff --git a/docs/superpowers/plans/2026-11-16-adoption-runner.md b/docs/superpowers/plans/2026-11-16-adoption-runner.md
new file mode 100644
index 0000000..f658f28
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-adoption-runner.md
@@ -0,0 +1,705 @@
+# 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 2 (2026-11-16).** Answers Astra's NEEDS CHANGES review (`runner-plan-review.md`) and folds in Paul's answers to Q1–Q5.
+
+**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, which Paul allowed on 2026-11-16. It covers 522 Plan 1 snapshots, conditional writes, the narrowed per-host restart, the delivery probe, 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`, Home `internal/operator` through `homecompat`, and agent-access `client` (module `amadan.net/oficina/agent-access.git` at `e4ea914`) for the live checks only.
+
+**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. The doors are in carlos/platform `docs/superpowers/specs/2026-11-02-config-receipts-design.md` §4, and the narrowed restart is `internal/console/apirestartscope.go` (branch `config-receipts-1`, worktree `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/config-receipts-1`). Rulings: oficina/home 103 and carlos/platform 522 (Paul, 2026-11-16). Read 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. It also has the stream machinery the runner needs: requests sealed before sending, exact replay of a lost answer, resync when Home's head moves, and plan resubmission (`provision/engine.go`: `op`, `replayHeld`, `signAndSend`, `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`. `homeop/fakehome` and `console/fakeconsole` have crash-after-every-act hooks.
+3. **Alta already knows each app.** `provision/apps.go` has each app's env prefix and its team-mode keys (`<P>_TEAM_*`).
+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 the app's 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 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 Paul's 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 5) |
+| 0b CARLOS preflight | none | per app: 522 reads, prospective key inheritance, identity, delivery baseline (Task 6) |
+| 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, after snapshot, delivery probe, 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 |
+
+## Global Constraints
+
+- **Never print, log or store unsealed:** a secret, a plain var's value, any `vd1:` digest, any `cv1:` version, `environment_binding`, a roster bearer, the operator key, the prefilter, the CARLOS token, an access token or 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.
+- **Dry-run by default.** Every subcommand that writes (Home or CARLOS) needs `--apply`.
+- **Every CARLOS config write is conditional:** `PUT /config` with `if_version` = the version just read, 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. It never trusts an earlier preflight.
+- **Baseline:** captured once per app, sealed before storage, never rebaselined. Retries follow 522 §4.7: first matching branch, preserved keys first.
+- **Both keys or neither** (Memoria refuses to boot with one). Write and unset them in one request.
+- **Values:** `<P>_AGENT_ISSUER = https://connect.oficina.works`; `<P>_AGENT_TEAM` = the seeded SQID, equal to the plans' `existing_team`.
+- **No team mode:** no `<P>_TEAM_*` key before or after. (`MEMORIA_TEAM` is not a team-mode key.)
+- **Canonical tuple only:** label `oficina`, consumer = app slug, origin `https://<app>.oficina.works`.
+- **Restart only through `POST /api/cli/apps/{account}/{app}/restart/scope`** with `{"host": <canonical record host>}`, after a `dry_run` that resolves exactly that one route. 404 (old console), 503 or any other resolution stops the run. Never fall back to the app-wide `/restart`.
+- **Delivery:** `/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.
+- **No** instance creation, storage swap, Home key change or `HOME_CONSUMERS` change.
+- **The served binary is 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 run through the Makefile only:** `make check PKG=<pkg> RUN=<regex>`, `make compat-check RUN=<regex>` (both added in Task 1) and `make ci`. Never bare `go test`.
+- **Process:** branch, Astra review recorded on home 103 and the Alta branch discussion, CI green, squash-merge. Default `GOCACHE`.
+
+## Review Focus
+
+1. **Another instance would inherit a new key** through a layer the canonical host also reads (default bundle, shared named environment), even when that instance overrides other keys. The run stops (Task 6, `TestPreflightRefusesInheritanceDespiteOtherOverride`).
+2. **A platform writer touches the bundle between baseline and write.** An unrelated key is reported but not fatal, the retry uses the new version, and the baseline is unchanged (Task 7, `TestWriteRetriesAfterUnrelatedKeyAdded`).
+3. **Slides and Calls already return their own 401.** Only agent-access's challenge counts as delivered (Task 8, `TestOperationsShapeDistinguishesAppMiddleware`).
+4. **Membership revocation isn't enforced.** The live check must see the same call on the same connection succeed before removal and fail after it. Plan C is refused otherwise (Task 11, `TestLiveFailsWhenRevocationNotEnforced`; Task 12, `TestPlanCRefusedWithoutLiveSuccess`).
+5. **The run stops halfway:** after a committed PUT or rollback whose answer was lost, or after a restart. The resume classifies by rereading. It never double-writes, rebaselines or unsets a value it did not write (Task 7, Task 14).
+
+---
+
+## File structure (oficina/alta)
+
+| File | Responsibility |
+|---|---|
+| `Makefile` (modify) | `check`, `compat-check`, `adopt` targets |
+| `homeop/protocol.go`, `homeop/fakehome/fakehome.go` (modify) | `Plan.ExistingTeam`, `ExistingActivationPolicy`, canonical helpers; fake adoption scope |
+| `homecompat/go.mod`, `homecompat/adopt_test.go` | pin Home ≥ `16da7ba`; adoption against Home's real operator |
+| `carlosop/client.go`, `carlosop/digest.go`, `carlosop/fakecarlos/fakecarlos.go` | 522 doors, instance/channel reads, scoped restart; fake with hooks |
+| `provision/migrations/0003_adoption.sql`, `provision/store.go`, `provision/adopt.go` | `runs.adoption`, `CreateAdoption`, Home-half adoption runs, `Observer` |
+| `adopt/migrations/0001_adopt.sql`, `adopt/store.go` | sealed journal: home preflight, baselines, writes, rollbacks, after snapshots, witnesses, live checks |
+| `adopt/homepreflight.go` | Home preflight (inspect + Paul's attested counts) |
+| `adopt/identity.go`, `adopt/snapshot.go` | instance/storage/environment/alias identity; snapshots; CARLOS preflight; prospective inheritance |
+| `adopt/write.go` | configure's conditional write and the journalled rollback |
+| `adopt/delivery.go`, `adopt/restart.go` | probe, ops shape, host-scoped restart, witness |
+| `adopt/binding.go`, `adopt/observer.go` | environment binding (including witness and delivery); activation gate |
+| `adopt/live.go` | live checks through agent-access `client` with an in-memory store |
+| `adopt/words.go` | every CLI string |
+| `cmd/alta-adopt/*.go`, `cmd/alta/imports_test.go` | the command; served-binary import guard |
+| `README.md` (modify) | "Adopting the canonical apps" runbook |
+
+---
+
+### Task 1: Makefile check targets, and `existing_team` in Alta's protocol mirror and fake Home
+
+**Files:** Modify `Makefile`, `homeop/protocol.go` (Plan ~l.132, consts ~l.61) and `homeop/fakehome/fakehome.go`. Tests in `homeop/protocol_test.go` and `homeop/fakehome/fakehome_test.go`.
+
+**Interfaces:**
+- **Makefile:**
+ - `check:` runs `CGO_ENABLED=0 go test $(PKG) -run '$(RUN)' -count=1` (requires `PKG`).
+ - `compat-check:` runs `cd homecompat && CGO_ENABLED=0 go test ./... -run '$(RUN)' -count=1`.
+ - `adopt:` does a native build of `./cmd/alta-adopt`, stamped like `release`.
+- **Plan field:** `homeop.Plan.ExistingTeam string`, tagged `json:"existing_team,omitzero"`, placed after `Owner`, as in Home `internal/operator/plan.go`.
+- **Constant:** `homeop.ExistingActivationPolicy = "oficina/existing-app-activation/v1"`.
+- **Helpers:** `homeop.CanonicalOrigin(app string) string` and `homeop.CanonicalBinding(label, app, consumer, origin string) bool`, copied from Home `directorydata/canonical.go`.
+- **fakehome:** follows Home's `plan.go` `valid`, `existing.go` `routeScope`, the verify-only `register` branch in `http_verbs.go`, and the policy choice in `verification.go`.
+
+- [ ] **Step 1: Write the failing tests.**
+ - `TestPlanExistingTeamEncodesLikeHome`: the encoded bytes contain `"display_name":"Oficina","existing_team":"Uk","issued_at"`, and with `ExistingTeam == ""` the key is absent.
+ - `TestFakeHomeAdoptionScope`:
+ - seed is allowed only at the proposed SQID;
+ - provision refuses a non-canonical consumer or origin;
+ - register returns the manifest digest without inserting;
+ - activate refuses `oficina/team-activation/v1` and accepts the existing policy;
+ - ordinary create-team or add-apps under `oficina` is refused.
+- [ ] **Step 2:** `make check PKG=./homeop/... RUN='TestPlanExistingTeam|TestFakeHomeAdoptionScope'` → FAIL (unknown field).
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** the same command → PASS. Then `make ci`.
+- [ ] **Step 5: Commit:** `homeop: existing_team on plans; make check targets`.
+
+### 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`). Create `homecompat/adopt_test.go`.
+
+- [ ] **Step 1: Bump the pin and run `make compat`.** Expected: existing tests pass, or fail only where Home since reserved `oficina` or changed an encoding. Fix the mirror in `homeop`, not the test. 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` = the directory's proposed SQID verifies under Home's `VerifyPlan` on both roles;
+ - `PlanStore` keeps `existing_team`;
+ - an ordinary create-team under `oficina` is refused.
+- [ ] **Step 3:** `make compat-check RUN=TestHomeAcceptsAltaSigned` → FAIL until the harness applies Home's adoption migration.
+- [ ] **Step 4:** fix the harness and rerun → PASS.
+- [ ] **Step 5: Commit:** `homecompat: pin Home with existing-team adoption`.
+
+### Task 3: `carlosop`, an in-memory Admin client for the 522 doors and the host-scoped restart, with its fake
+
+**Files:** Create `carlosop/client.go`, `carlosop/digest.go` and `carlosop/fakecarlos/fakecarlos.go`. Tests in `carlosop/client_test.go` and `carlosop/digest_test.go`.
+
+**Interfaces:**
+
+```go
+// Token is set from a file descriptor by cmd/alta-adopt (Paul's Q1 ruling): never read from env or disk, never logged, zeroed by Close.
+type Client struct { HTTP *http.Client; Console, Account string; token []byte }
+func New(console, account string, token []byte) *Client
+func (c *Client) Close()
+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; Set map[string]string; Unset []string; IfVersion string }
+type RestartRoute struct { Host, Environment, Unit string; Hibernate bool }
+var ErrVersionMismatch, ErrNoConditional, ErrNotFound, ErrNoScopedRestart error
+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) // IfVersion required; env vars only
+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)
+func (c *Client) RestartHost(ctx context.Context, app, host string, dryRun bool) ([]RestartRoute, error) // POST …/restart/scope {"host","dry_run"}; 404/503 → ErrNoScopedRestart
+func EnvDigest(value string) string // "vd1:"+hex sha256("carlos.config.var.v1"\0"env"\0value\0""\0"")
+```
+
+The fake keeps per-host layer chains (default, named environment, owned environment, overlay). Its hooks are `BeforePut`, `LoseNextAnswer`, `SetSecret`, `PlatformWrite`, `FailRestart`, `RestartCount(host)` and `NoScopedRestart()`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestEnvDigestMatchesPlatformVector`: golden value from platform `internal/appconfig` digest tests at the merged Plan 1 commit.
+ - `TestPutSendsIfVersionInBodyOnly`: no `If-Match`, no `exec_delivery`.
+ - `TestPut412IsVersionMismatch` and `TestPut400OnConditionalIsNoConditional`.
+ - `TestRestartHostUsesScopeDoorOnly`: the fake records zero calls to `/restart`.
+ - `TestRestartHostOldConsoleFailsClosed`: a 404 on `/restart/scope` gives `ErrNoScopedRestart`, and there is no other call.
+ - `TestClientNeverFollowsRedirect`.
+ - `TestErrorsCarryNoTokenOrValue`.
+ - `TestTokenZeroedOnClose`.
+ - `TestFakeVersionMovesOnlyWithBytes`.
+- [ ] **Step 2:** `make check PKG=./carlosop/... RUN=.` → FAIL.
+- [ ] **Step 3: Implement.** Model it on `console/fakeconsole`. `cv1:` is over the stored bytes; `vd1:` follows 522 §4.3.
+- [ ] **Step 4:** the same command → PASS.
+- [ ] **Step 5: Commit:** `carlosop: 522 config doors, host-scoped restart, fake console`.
+
+### Task 4: Adoption state, journalled and sealed
+
+**Files:** Create `provision/migrations/0003_adoption.sql`, `adopt/migrations/0001_adopt.sql` and `adopt/store.go`. Modify `provision/store.go`. Tests in `provision/store_adopt_test.go` and `adopt/store_test.go`.
+
+**Interfaces:**
+
+```go
+// provision
+const AdoptionLabel = "oficina"
+func (s *Store) CreateAdoption(ctx context.Context, name, owner string, apps []string) error // teams/team_apps/owner_inputs only; environment ""; NO environments rows
+func (s *Store) NewAdoptionRun(ctx context.Context, kind string, apps []string) (int64, error) // runs.adoption = 1
+// adopt (all payloads sealed under purpose "alta/adopt/<table>/<app>")
+var Schema *migrate.Set
+func NewStore(ps *provision.Store) (*Store, error)
+func (s *Store) SaveHomePreflight(ctx context.Context, r HomePreflight) 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, app, state string, sent map[string]string, rc *carlosop.Receipt) error // "sent","landed","stopped"
+func (s *Store) Write(ctx context.Context, app string) (WriteRecord, bool, error)
+func (s *Store) SaveRollback(ctx context.Context, app, state string, rc *carlosop.Receipt) error // "sent","unset","restarted","stopped"
+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, app string, 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) LivePassed(ctx context.Context) (bool, error) // every RequiredLiveChecks name recorded "passed", none "failed"
+```
+
+`0003_adoption.sql`: `ALTER TABLE runs ADD COLUMN adoption INTEGER NOT NULL DEFAULT 0 CHECK (adoption IN (0, 1));`
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestCreateAdoptionWritesNoEnvironmentRows`: `Guard.Environment` refuses every app for `oficina`.
+ - `TestBaselineIsInsertOnly`.
+ - `TestAdoptRowsAreSealed`: the raw DB and WAL contain no `vd1:`, `cv1:`, var-value canary or owner canary.
+ - `TestAdoptionRunColumn`.
+ - `TestLivePassedRequiresEveryCheck`.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN=Store` and `make check PKG=./provision/... RUN=Adoption` → FAIL.
+- [ ] **Step 3: Implement** (`secure_delete` on).
+- [ ] **Step 4:** the same commands → PASS, then `make ci`.
+- [ ] **Step 5: Commit:** `Adoption state: sealed journal`.
+
+### Task 5: Home preflight with a supported evidence source
+
+**The gap:** the design's preflight checks `teams`, `memberships`, `team_instances` and both operator streams. Signed inspect (`http_verbs.go` `HTTPInspection`) shows each role's `sequence` and `head`, the directory's `generation` and `proposed_team_id`/`_sqid`, and pending or open plans. A proposed id of 1 means `teams` is empty and `sqlite_sequence` was never used. Inspect does **not** show `memberships` or `team_instances`.
+
+**Source for those, with no Home change:** Paul runs a read-only `carlos db query` against the directory's live database. The CARLOS db read doors admit people only, deliberately: `routedecls.go` "admin is refused with the rest". So the runner's Admin credential cannot read them, and must not try. The runner prints the exact queries, Paul pastes back the counts, and the runner records his attestation with a timestamp.
+
+The alternative is a reviewed Home change that adds `teams`, `memberships` and `team_instances` counts to `directory.inspect`. It is **not** planned, because the people-only read already exists. Paul can choose it instead (Q7).
+
+**Files:** Create `adopt/homepreflight.go`. Test in `adopt/homepreflight_test.go`.
+
+**Interfaces:**
+
+```go
+type HomePreflight struct { CredentialSeq, DirectorySeq int64; Generation *string; ProposedID int64; ProposedSQID string
+ Pending, Open bool; Counts map[string]int64 /* teams, memberships, team_instances, operator_http_teams, roster_generation, roster_consumers, roster_tokens, roster_operator_receipts */; AttestedAt time.Time }
+func HomeQueries() []string // exactly: "SELECT count(*) FROM <t>" for each table above, against host oficina.works
+func CheckHome(ctx context.Context, h *homeop.Client, counts map[string]int64, phase string) (HomePreflight, []string, error)
+```
+
+Refusal codes depend on the phase:
+- **Before initialize:** both sequences must be 0 with an empty head, `Generation` nil, `ProposedID` 1, no pending or open plan, and every count 0.
+- **Before Plan A:** the directory sequence must be ≥ 1 and the credential's 0 or Alta's own journal head, `Generation` set, `ProposedID` 1, and every count 0 except `roster_generation = 1` and `roster_operator_receipts = 1`.
+- **At any phase:** a count missing from the paste gives `count-missing-<t>`.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestHomePreflightBeforeInitializeRefusesAnyRow`: a non-zero membership count gives `memberships-nonzero`.
+ - `TestHomePreflightRefusesUsedStreams`.
+ - `TestHomePreflightRefusesProposedNotOne`.
+ - `TestHomePreflightRefusesMissingCount`.
+ - `TestHomePreflightRecordsAttestationSealed`.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN=HomePreflight` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS.
+- [ ] **Step 5: Commit:** `adopt: Home preflight from inspect and attested read-only counts`.
+
+### Task 6: Identity, snapshots and CARLOS preflight
+
+**Files:** Create `adopt/identity.go` and `adopt/snapshot.go`. Tests in `adopt/identity_test.go` and `adopt/snapshot_test.go`.
+
+**Interfaces:**
+
+```go
+const Issuer = "https://connect.oficina.works"
+type Target struct { App, Prefix, CanonicalHost string }
+func AgentKeys(prefix string) [2]string
+type Identity struct { Account, App, RecordHost, PublicHost, Slug, Environment, Channel, Region string; Owned bool
+ CreatedAt time.Time; RecordSeq uint64; ReplicaAssignment, Seed string /* canonical JSON */ }
+func IdentityOf(in carlosop.Instance, eff carlosop.Effective) (Identity, error) // refuses an instance with Move non-null
+func SameIdentity(a, b Identity) []string // "storage", "instance", "environment", "alias", "channel", "region", "record"
+type Snapshot struct { Identity Identity; WriteLayer string /* "default" or environment name */; Layer carlosop.Layer
+ Layers map[string]string; Vars []carlosop.EffectiveVar; HomeIssuer, HomeConsumer string; Delivery Delivery; At time.Time }
+func Observe(ctx context.Context, c *carlosop.Client, t Target) (Snapshot, error)
+func Preflight(ctx context.Context, c *carlosop.Client, h *http.Client, t Target, mine map[string]string) (Snapshot, []string, error)
+```
+
+**Storage identity, decided here.** Persistent storage is identified by the instance record's `Slug`, `CreatedAt` and `ReplicaAssignment` (plus `Seed`). Recreating an instance or swapping its storage makes a new record or a new assignment. A move changes `Region` and sets `Move`. All of these are in `Identity`, and any difference stops the run.
+
+`RecordSeq` is included **unless** step 0 shows the runner's own config write or scoped restart bumps it. In that case it is excluded, and the reason goes in a code comment and on home 103.
+
+**Prospective inheritance.** For each agent key `k` and each other instance `H` of the app:
+1. `H` would receive `k` from the write layer `L` if `L` is in `H`'s chain:
+ - `L` = `default`: `H` is not on an owned environment.
+ - `L` = a named environment: `H`'s environment is `L`.
+2. Even then, `H` does not receive it if a higher layer in `H`'s chain already sets `k` (`Effective(H)` shows `k` with a `from` above `L`).
+3. Other keys `H` overrides, such as `HOME_ISSUER`, are irrelevant.
+
+Any `H` that would receive either key gives `inherits-<host>`.
+
+**Preflight refusals:**
+- `agent-keys-present` (unless they equal `mine`, which is the journal's own sent values on a resume)
+- `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 code and record in a comment which record fields a `config PUT` and a `restart/scope` write change.** Read `internal/provision`, `internal/console/apiconfig.go` and `apirestartscope.go`.
+- [ ] **Step 1: Write the failing tests:**
+ - `TestPreflightRefusesInheritanceDespiteOtherOverride`: the counterexample. A second docs instance on a named environment overrides `DOCS_HOME_ISSUER` but not the agent keys, so the default write would reach it: `inherits-<host>`.
+ - `TestPreflightAllowsOwnedEnvironmentNeighbour`.
+ - `TestPreflightAllowsNeighbourThatAlreadyShadowsBothKeys`.
+ - `TestPreflightRefusesTeamMode`: `DOCS_TEAM_ID` is refused, `MEMORIA_TEAM` alone passes.
+ - `TestPreflightRefusesForeignAgentKeys`.
+ - `TestSameIdentityFlagsEachField`: one test per field.
+ - `TestIdentityRefusesMovingInstance`.
+ - `TestPreflightOutputHasNoValuesOrDigests`.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN='Preflight|Identity'` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS.
+- [ ] **Step 5: Commit:** `adopt: identity, snapshots, prospective-inheritance preflight`.
+
+### Task 7: Configure's conditional write, and the journalled rollback
+
+**Files:** Create `adopt/write.go`. Test in `adopt/write_test.go`.
+
+**Interfaces:**
+
+```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, t Target, sqid string, apply bool) (string, 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, t Target, apply bool) error
+// CaptureAfter observes after the restart and stores the after snapshot only if Preserved(baseline, after) is empty
+// and both agent keys carry the sent digests; otherwise ErrStopPreserved, and nothing is stored.
+func CaptureAfter(ctx context.Context, c *carlosop.Client, s *Store, t Target) (Snapshot, error)
+var ErrStopPreserved, ErrStopConflict, ErrStopForeign, ErrNoConditional error
+```
+
+**WriteAgentKeys:**
+1. If the journal says `landed`, return.
+2. Call **`Preflight` with `mine` = the journal's sent values.** Any code stops the run, before anything is written.
+3. Take the baseline from the journal, or capture and seal it.
+4. Record `SaveWrite("sent")`, then `Put{IfVersion: baseline.Layer.Version, Set: both}`.
+5. On 200, require all of:
+ - `Set` is exactly the two keys;
+ - `Unset` and `UnsetAbsent` are empty;
+ - each `Digests[k] == EnvDigest(sent[k])`;
+ - `Others` before == after.
+ Otherwise `ErrStopConflict`.
+6. On 412 or a lost answer, reread and `Classify`. On `Retry`, use the version just read. Stop after 3 attempts (`retry-exhausted`). Never rebaseline.
+
+**RollbackAgentKeys** (journalled like the write):
+1. Reread and `ClassifyRollback`:
+ - both keys present with exactly the sent digests: `RetryUnset`;
+ - both absent and preserved keys equal: `RolledBack`;
+ - either key present with another digest or kind, or only one present: `StopForeign` (never unset a value this adoption didn't write);
+ - a preserved key changed: `StopPreservedChanged`.
+2. Record `SaveRollback("sent")`, then `Put{IfVersion: current, Unset: both}`.
+3. Accept a receipt where `Unset ∪ UnsetAbsent` equals the two keys and `Set` is empty. This is retry-safe: after a committed rollback whose answer was lost, the retry's receipt shows the keys as `unset_absent`.
+4. Then **restart through `RestartHost`** and probe. Removing the stored keys alone does not stop the running process, which keeps them until restarted. Rollback is complete only when the probe shows the before snapshot's ops shape again (`restarted`). A failed restart leaves the state `unset` with the code `restart-failed` for a resume.
+
+- [ ] **Step 1: Write the failing tests:**
+ - **Write:**
+ - `TestConfigureCallsPreflightEvenWhenInvokedDirectly`, `TestConfigureRefusesForeignAgentKeys`, `TestConfigureRefusesTeamMode` and `TestConfigureRefusesInheritingNeighbour`: each has zero PUTs.
+ - `TestWriteHappyPathReceiptChecked`.
+ - `TestWriteLostAnswerLanded`: one PUT.
+ - `TestWriteRetriesAfterUnrelatedKeyAdded`: the sealed baseline bytes are unchanged.
+ - `TestWriteStopsWhenPreservedKeyResealed`.
+ - `TestWriteStopsOnPartialOrForeignAgentKeys`.
+ - `TestWriteRejectsMalformedReceipts`: subtests for an extra key in `Set`, a missing digest, a wrong digest, a non-empty `Unset`, and `Others` moved.
+ - `TestWriteRefusesWithoutConditionalSupport`.
+ - `TestAfterSnapshotRefusesSecretResealedBeforeCapture`: the PUT lands with a valid receipt, the fake reseals a preserved secret before `CaptureAfter`, and the result is `ErrStopPreserved` with no after snapshot stored.
+ - `TestWriteDryRunSendsNothing`.
+ - **Rollback:**
+ - `TestRollbackLostAnswerRetryAcceptsUnsetAbsent`.
+ - `TestRollbackRefusesForeignValue`: zero PUTs.
+ - `TestRollbackConflict412Rereads`.
+ - `TestRollbackCrashAfterUnsetResumesToRestart`.
+ - `TestRollbackRestartFailureLeavesUnsetState`.
+ - `TestRollbackCompleteOnlyWhenOpsShapeReverts`.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN='Configure|Write|Rollback'` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS.
+- [ ] **Step 5: Commit:** `adopt: conditional write with mandatory preflight; journalled rollback`.
+
+### Task 8: Delivery probe, host-scoped restart, witness
+
+**Files:** Create `adopt/delivery.go`, `adopt/restart.go` and `adopt/words.go`. Test in `adopt/delivery_test.go`.
+
+**Interfaces:**
+
+```go
+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.Ops ∈ {agent-401, agent-200}, before.Ops ∉ that set (Q2: app-401 → agent-401 counts)
+func RestartCanonical(ctx context.Context, c *carlosop.Client, t Target, id Identity, apply bool) error // dry run must return exactly [id.RecordHost]; else "restart-scope-<n>" / ErrNoScopedRestart; then the write
+func RestartAndWait(ctx context.Context, c *carlosop.Client, h *http.Client, t Target, id Identity, before Delivery, apply bool) (Delivery, error) // poll every 5 s, up to 5 min
+type Witness struct { App, Typed string; Delivery Delivery; At time.Time }
+func WitnessSentence(app string) string // words.go, copy-reviewed
+func RecordWitness(ctx context.Context, s *Store, h *http.Client, t Target, typed string, now time.Time) error
+```
+
+The agent-access challenge (`agent-401`) is a 401 with `WWW-Authenticate` starting `Bearer`, `Cache-Control: no-store`, and a body of `{"error":{"code":"unauthenticated",…}}`. A route answering `Hibernate: true` in the dry run is accepted only because the probe wakes it, and `Delivered` must still pass.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestOperationsShapeDistinguishesAppMiddleware`.
+ - `TestDeliveredRefusesVersionOrHeaderChange`.
+ - `TestProbeRefusesRedirect`.
+ - `TestRestartCanonicalLeavesOtherInstancesUntouched`: the fake's `RestartCount` is 0 for every other host, and the app-wide door was never called.
+ - `TestRestartCanonicalRefusesWiderDryRun`.
+ - `TestRestartCanonicalFailsClosedOnOldConsole`.
+ - `TestRestartAndWaitTimesOutWithoutAgentShape`.
+ - `TestWitnessRefusesWrongAppSentence`.
+ - `TestWitnessRefusesWithoutAgentShape`.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN='Delivered|Probe|Restart|Witness|OperationsShape'` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS.
+- [ ] **Step 5: Commit:** `adopt: delivery probe, host-scoped restart, witness`.
+
+### Task 9: Environment binding and the activation gate (Observer)
+
+**Files:** Create `adopt/binding.go` and `adopt/observer.go`. Modify (or create) `provision/adopt.go` with the interface only. Tests in `adopt/binding_test.go` and `adopt/observer_test.go`.
+
+**Interfaces:**
+
+```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; Canary string /* "calendar" */; Now func() time.Time; MaxWitnessAge time.Duration /* 24h */ }
+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 sorted `[key, kind, digest, from]` var lists, before then after;
+4. the before and after layers;
+5. the SQID, issuer, artifact SHA256 and version;
+6. **the before, after and now delivery observations;**
+7. **the witness: app, typed sentence, the delivery Paul witnessed, and when.**
+
+This puts Paul's witnessed check and the delivery observations inside the signed observation, as the design requires.
+
+**`Observe` refuses with a fixed code unless every one of these holds:**
+- A Home preflight, baseline, `landed` write, after snapshot and witness are all present (`missing-<x>`).
+- The witness is younger than 24 h (`witness-stale`).
+- A **fresh** `IdentityOf` equals both the baseline's and the after snapshot's identity: storage, instance, environment, alias host and target, channel, region, record (`identity-<field>`).
+- Preservation holds along the whole chain, for **every key in the baseline's effective config** except the two added: `Preserved(baseline, after)` is empty **and** `Preserved(baseline, fresh)` is empty. Drift between the successful PUT and the after-snapshot capture is therefore refused (`drift-<key>`, `after-not-preserved`). The fresh config read must also equal the after snapshot digest for digest (`drift-<key>`).
+- No `<P>_TEAM_*` key is present.
+- Both agent keys carry the sent digests.
+- A fresh `Probe` passes `Delivered` against the baseline.
+- The `/api/version` body matches `^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`.
+- `ChannelDigest(record channel, version)` equals `Artifacts[app]`.
+- For any app other than `Canary`, `S.LivePassed` (`live-checks-missing`).
+
+`ArtifactDigest` is base64url of the 32 raw bytes.
+
+- [ ] **Step 1: Write the failing tests** (the gate's positive path; the adverse matrix is Task 12):
+ - `TestBindingIncludesWitnessAndDelivery`: changing any witness or delivery field changes the binding.
+ - `TestBindingIsOrderIndependent`.
+ - `TestObserverHappyPathEvidenceTokens`.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN='Binding|ObserverHappy'` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS.
+- [ ] **Step 5: Commit:** `adopt: environment binding with witness; activation gate`.
+
+### Task 10: Home half: adoption runs in Alta's engine
+
+**Files:** Create or modify `provision/adopt.go`. Modify `provision/engine.go` (`Config.Observer`; `Advance` dispatches on `run.Adoption`) and `provision/steps.go` (consumer and origin helpers). Test in `provision/adopt_test.go`.
+
+**Interfaces:**
+
+```go
+func (e *Engine) StartAdoption(ctx context.Context, name, owner string) (int64, error) // Plan A; name must be "Oficina"
+func (e *Engine) ActivateAdopted(ctx context.Context, apps []string) (int64, error) // Plan B/C, add-apps, both roles, no owner
+func (e *Engine) DisableAdopted(ctx context.Context, app, typed string) (int64, error) // retire-apps, label oficina, directory.disable-consumer only; typed == "oficina"
+func ConsumerFor(run Run, app string) string
+func OriginFor(run Run, app string) string
+```
+
+**Plan A:**
+- owner-seed: `TeamSQID == ExistingTeam`, `ExistingOnly`.
+- seed-team: `Label "oficina"`, `Name "Oficina"`.
+- Per app, consumer and register with canonical bindings.
+- The run ends `done` with code `awaiting-configuration`. There are no console calls, and the owner's address is forgotten after the seed.
+
+**Plan B/C, per app:**
+- `StepVerify` without the `/api/team` probe (adopted apps are not team mode). Timestamps use **the existing conservative approach**: Home's verify result carries no `issued_at`, so record the `Issued` the runner signed. For a held attempt recovered by replay, record a later local timestamp (`provision/steps.go:735–741`). Activation's `started_at ≥ issued_at` still holds, because the recorded value is never earlier than Home's.
+- `StepActivate` with `ExistingActivationPolicy`, consumer = app, audience = `CanonicalOrigin(app)`, `AliasHost = "<app>.oficina.works"`. The evidence comes from `Observer.Observe`, called after verify. `Started` = the recorded `issued_at`; `Completed` = now − `Skew`.
+- A nil Observer fails with `no-observer`. That is always the case in served Alta.
+- An `Observe` refusal parks with its code. It never activates.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestAdoptionPlanACarriesExistingTeamOnBothRoles`.
+ - `TestAdoptionSeedsAtProposedSQIDOnly`.
+ - `TestAdoptionRegisterInsertsNothing`.
+ - `TestAdoptionMakesNoConsoleCalls`.
+ - `TestActivateAdoptedUsesExistingPolicy`.
+ - `TestActivateAdoptedWithoutObserverFails`.
+ - `TestActivateAdoptedParksOnObserverRefusal`: no activate request is signed.
+ - `TestActivateAdoptedStartedNotBeforeRecordedIssued`.
+ - `TestActivateAdoptedReverifiesLapsedAttempt`.
+ - `TestOrdinaryRunsStillRefuseOficina`.
+ - `TestDisableAdoptedRequiresTypedLabel`.
+ - `TestAdoptionCrashAfterEveryAct`.
+- [ ] **Step 2:** `make check PKG=./provision/... RUN='Adoption|Adopted|Oficina'` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS, then `make ci`.
+- [ ] **Step 5: Commit:** `provision: adoption runs for the canonical apps`.
+
+### Task 11: Live checks that prove revocation
+
+**Files:** Create `adopt/live.go`. Modify `go.mod` (require `amadan.net/oficina/agent-access.git@e4ea914`). Test in `adopt/live_test.go`, against an httptest connect fake.
+
+**Interfaces:**
+
+```go
+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"}
+type MemoryStore struct{ /* client.Credentials in memory only */ }
+type Prompter interface { Ask(ctx context.Context, sentence string) error } // exact typed sentence (words.go)
+func RunLive(ctx context.Context, server, sqid string, p Prompter, s *Store, open func(string) error, foreignEventID string) error
+```
+
+Every step records `SaveCheck(name, "passed"|"failed:<code>")`, codes only.
+
+**Paul's throwaway test account** (Q4) must first have signed in to calendar.oficina.works once, so it has a local, admitted account.
+
+1. **`non-member-refused`.** Login A (the test account, in a separate browser profile) runs `Connection()`. Its teams must not include the SQID. `calendar_free_busy` for the test account's own range, with `team=<sqid>`, is refused.
+2. **Prompt:** Paul adds the test account on the Team page. Login B: the test account reconnects and ticks the team.
+3. **`member-allowed`.** Using connection B, the test account calls `calendar_free_busy` on its own range. It **must succeed.** The exact call (operation and input bytes) is stored in memory as `C`.
+4. **`member-no-local-permission-refused`.** Using connection B, `calendar_get_event` with `foreignEventID` (Paul's event) is refused with `not_found` or `forbidden`.
+5. **Prompt:** Paul removes the test account on the Team page. **`revoked-membership-refused`:** the identical call `C` on the identical connection B is now refused.
+6. **`local-access-kept`.** The test account still signs in at calendar.oficina.works. Paul types the sentence.
+7. **`owner-allowed`.** Paul's own connection makes the same kind of call, which succeeds. Before revoking, the runner copies that call's exact authenticated request into memory: method, URL, body and the access token it carried. It also records the token's expiry. Then `Logout` (revoke). At `e4ea914`, `Logout` also deletes the local credential store, so the client itself can no longer repeat the call. **`owner-revoked-refused`:** the runner replays the saved request with a plain `http.Client` (no redirects, same bearer) and requires a **server authorization refusal**: 401 with agent-access's challenge, or 403 with an agent-access error body. A transport error, a 5xx, or a replay after the token's own expiry counts as inconclusive, not passed; the step is then repeated with a fresh connection. **`owner-local-access-kept`:** Paul types the sentence.
+8. **Always:** `Logout` every connection made, whatever failed. The saved request and token are zeroed when `RunLive` returns.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestLiveFailsWhenRevocationNotEnforced`: the fake keeps allowing `C` after removal, giving `revoked-membership-refused` = failed, and `LivePassed` is false.
+ - `TestLiveFailsWhenMemberCannotCallBeforeRemoval`: no positive baseline means the step fails, and later steps are skipped and not passed.
+ - `TestLiveRepeatsExactCallAndConnection`: the fake asserts the same access token and body.
+ - `TestLiveFailsWhenNonMemberSucceeds`.
+ - `TestLiveFailsWhenForeignEventReadable`.
+ - `TestLiveRecordsCodesOnly`.
+ - `TestLiveAlwaysLogsOut`.
+ - `TestLiveFailsWhenRevokeLeavesAccessValid`: the fake's revoke endpoint answers success but keeps accepting the token, so the replay succeeds and `owner-revoked-refused` = failed.
+ - `TestLiveOwnerRevokeReplaysSavedRequest`: the fake asserts the replay carries the pre-revoke bearer and body after the store was deleted.
+ - `TestLiveReplayAfterExpiryIsInconclusive`: a refusal only because the token expired is not recorded as passed.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN=Live` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS.
+- [ ] **Step 5: Commit:** `adopt: live checks proving revocation`.
+
+### Task 12: Activation-gate adverse suite
+
+**Files:** Create `adopt/gate_adverse_test.go` and `provision/adopt_adverse_test.go`.
+
+Each case below is its own subtest. Each asserts a specific refusal code, **and that no `directory.activate-consumer` request was signed** (checked in the fakehome request log).
+
+- [ ] **Step 1: Write the tests:**
+ - **Missing evidence:** no Home preflight, no baseline, write `sent` but not `landed`, no after snapshot, no witness, stale witness, and live checks missing or failed for a non-canary app (`TestPlanCRefusedWithoutLiveSuccess`).
+ - **Changed identity**, one each: slug, created_at, replica assignment, seed, record host, public alias host, environment, owned flag, channel, region, `Move` set, record_seq (if kept per Task 6).
+ - **Changed config:** a preserved secret resealed between the PUT and the after-snapshot capture (a hand-written after row that bypassed `CaptureAfter`, so `Observe` gives `after-not-preserved`), a preserved secret resealed after the after snapshot, a plain value changed, a key removed, a new `<P>_TEAM_*` key, an agent key with another digest, an overlay now shadowing an agent key.
+ - **Changed delivery:** version body changed, header changed, a redirect, healthz 503, ops shape reverted to `app-401`.
+ - **Artifact:** the channel digest differs from `Artifacts[app]`; the version is malformed.
+ - **Malformed receipts reach no activation:** the write's malformed-receipt stops (Task 7) leave the journal not `landed`, so `Observe` gives `missing-write`.
+ - **Failed local-permission check:** `member-no-local-permission-refused` failed, so Plan C is refused.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN=Adverse` and `make check PKG=./provision/... RUN=Adverse` → FAIL where the gate is incomplete.
+- [ ] **Step 3: Fix** in Tasks 9 and 10's files.
+- [ ] **Step 4:** PASS.
+- [ ] **Step 5: Commit:** `adopt: activation gate adverse suite`.
+
+### Task 13: `cmd/alta-adopt`
+
+**Files:** Create `cmd/alta-adopt/main.go`, `cmd/alta-adopt/config.go` and `cmd/alta/imports_test.go`. Test in `cmd/alta-adopt/main_test.go`.
+
+**Subcommands.** Every one that writes needs `--apply`.
+
+| Subcommand | What it does |
+|---|---|
+| `home-preflight --phase pre-initialize\|pre-plan-a` | prints `HomeQueries()`, reads the pasted counts, calls `CheckHome` |
+| `preflight` | the CARLOS preflight, all six apps |
+| `initialize` | the typed `provision.InitializeAttestation`; refuses without a recorded `pre-initialize` Home preflight |
+| `plan-a` | owner read from the terminal; refuses without `pre-plan-a`; prints both confirm URLs and the plan prefix |
+| `advance --run` | runs the engine |
+| `configure --app` | Task 7, then `RestartAndWait`, then `CaptureAfter` (refuses unless baseline→after is preserved) |
+| `witness --app` | the witnessed check |
+| `activate --apps` | refuses non-canary apps unless `LivePassed`, the same gate as `Observe` |
+| `live` | the live checks |
+| `rollback-config --app` | the journalled rollback |
+| `disable --app` | the directory disable |
+| `status` | per-app states |
+
+**Config file:** `--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: sha256hex}`.
+
+**Credential:** the Admin token comes from `--carlos-token-fd N` (Q1), is held as `[]byte`, and is zeroed on exit.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestServedAltaImportsNoAdoptionCode`: `go list -deps ./cmd/alta` contains none of `adopt`, `carlosop` or `agent-access.git`.
+ - `TestWritesNeedApply`.
+ - `TestInitializeRefusedWithoutHomePreflight`.
+ - `TestActivateNonCanaryRefusedWithoutLive`.
+ - `TestConfigFileModeRefused`.
+ - `TestOutputScrub`: across a full fake run's stdout, stderr and logs, there is no `vd1:`, `cv1:`, binding, token, prefilter, owner canary or plain-value canary.
+ - `TestTokenNeverInEnvOrDisk`.
+- [ ] **Step 2:** `make check PKG=./cmd/... RUN=.` → FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4:** PASS, then `make ci`.
+- [ ] **Step 5: Copy review** of `adopt/words.go` and the help text with the copy-review skill. Apply Paul's edits verbatim.
+- [ ] **Step 6: Commit:** `alta-adopt: the local adoption command`.
+
+### Task 14: Rehearsal, homecompat flow, runbook
+
+**Files:** Create `adopt/rehearsal_test.go` and `homecompat/adopt_flow_test.go`. Modify `README.md`.
+
+- [ ] **Step 1: Write the tests:**
+ - `TestRehearsalFullRun` (the happy path). Home preflight, initialize, Plan A, configure ×6, witness ×6, Plan B for calendar, live, Plan C. At the end: six live routes, every preserved digest equal, each layer differing only by the two keys, and every other instance's restart count 0.
+ - `TestRehearsalCrashAfterEveryAct`. A crash at each Home act and each CARLOS act (before and after PUT, after restart, mid-rollback). The resume never rebaselines, double-writes or unsets a foreign value.
+ - homecompat `TestAdoptionFlowAgainstRealHome`. Real `PlanStore`, confirm with the typed owner index, and both `ExecuteHTTP`s. At the end: canonical `team_instances` live, the credential `consumers` table empty, and the manifest digest unchanged.
+- [ ] **Step 2:** `make check PKG=./adopt/... RUN=Rehearsal` and `make compat-check RUN=AdoptionFlow`, then fix in the owning task's file.
+- [ ] **Step 3: Runbook.** `make ci` → PASS. Write the README runbook: phases, Paul's steps and the rollbacks below.
+- [ ] **Step 4: Production read-only rehearsal.** Run `alta-adopt home-preflight --phase pre-initialize` (Paul pastes the counts) and `alta-adopt preflight`. Record the codes on home 103.
+- [ ] **Step 5: Merge.** Commit, push, open the Alta branch discussion, get Astra's branch review, wait for CI green, squash-merge.
+
+---
+
+## Paul's action points, in order
+
+1. **Shared production keyset** (critical path step 5): OK the one `alta keygen` plus `home team-keygen -subject pr_tsoeky4xus2habsdlun2jvzmku`, applied to `oficina-id` then `oficina` (home 101 §5 order). Name the machine that holds the operator key for `alta-adopt`.
+2. **CARLOS credential:** `carlos services create --account oficina --role admin oficina-adoption`, passed to `alta-adopt` on a file descriptor only.
+3. **Home counts, before initialize:** run the read-only `carlos db query` lines `alta-adopt home-preflight` prints, signed in as himself, and paste the counts.
+4. **Watch the CARLOS preflight.** Any `inherits-<host>` stops the run (Q3).
+5. **§12 attestation:** type it at `alta-adopt initialize`, then confirm on [https://oficina.works/operator/confirm](https://oficina.works/operator/confirm) (fresh passkey, system browser).
+6. **Home counts, before Plan A:** run the queries again and paste the counts.
+7. **Plan A:** `alta-adopt plan-a --apply`, typing his own address as owner. Confirm on [https://oficina.works/operator/confirm](https://oficina.works/operator/confirm), then [https://id.oficina.works/operator/confirm](https://id.oficina.works/operator/confirm) (retyping the owner). Check that both pages 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, per app:** sign in at `https://<app>.oficina.works` in the system browser, then type the app's sentence.
+10. **Plan B (calendar):** 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 calendar events for the "no local permission" check.
+12. **Live checks** (oficina-connect deployed, `HOME_AGENT_DIRECTORY_TOKEN_SHA256` set): sign the test account in to connect when prompted, add and remove it on the Team page, witness both local sign-ins, then connect and revoke his own account.
+13. **Plan C (other five):** two confirmations. It is refused unless every live check passed.
+14. **Clean up:** `carlos services delete oficina-adoption`; keep a backup of the state DB (the sealed journal); delete the test account if he wants.
+
+## Every production write, in order, with rollback
+
+| # | Write | Where | Rollback |
+|---|---|---|---|
+| 1 | `directory.initialize` | Home directory | **None** (by design). Gated on the Home preflight and the §12 attestation. |
+| 2 | Plan submissions (initialize, A, B, C), both roles | Home `operator_plans` | Unconfirmed plans expire after 15 min and are swept. |
+| 3 | `credential.owner-seed` | Home credential (stream result) | None needed (the receipt expires after 300 s). |
+| 4 | `directory.seed-team`: `oficina` / "Oficina", Paul as owner | Home directory | None (no deletes). Inert without live instances; the label is reserved. |
+| 5 | `directory.provision-consumer` ×6 (pending rows, tokens, receipts) | Home directory | `alta-adopt disable --app <a> --apply` (retire-apps plan, `directory.disable-consumer`). |
+| 6 | `credential.register-consumer` ×6 (verify only, nothing inserted) | Home credential (stream result) | None needed. |
+| 7 | Conditional `PUT /config`: `<P>_AGENT_ISSUER` + `<P>_AGENT_TEAM`, one per app | CARLOS `oficina`, canonical host's layer | `alta-adopt rollback-config --app <a> --apply`: journalled conditional unset of both (refuses foreign values), **then the host-scoped restart**, complete only when the probe shows the old ops shape. |
+| 8 | `POST …/restart/scope {"host": <canonical>}`, one per app | CARLOS (that host only) | Restart again after rollback. |
+| 9 | `directory.verify-consumer` per app | Home directory | Expires after 600 s. |
+| 10 | `directory.activate-consumer` per app, which makes it live | Home directory | Immediately: row 7's rollback, including the restart, stops delegated access at the app. Then `disable`. Revoking at connect also works. |
+| 11 | Test connections at connect; Team membership add/remove (Paul) | connect, Home directory | The runner always revokes its connections; Paul removes the test member. |
+
+From row 4 onward, keep Home on an adoption-capable build: **never downgrade it, restore an older snapshot or delete rows.**
+
+## Effort
+
+14 tasks, about 4½–5½ agent days including one Astra round per task, branch review and CI:
+
+| Tasks | Effort |
+|---|---|
+| 1–2 | ½ d |
+| 3 | ½ d |
+| 4–5 | ½ d |
+| 6 | ½ d |
+| 7 | ¾ d |
+| 8 | ½ d |
+| 9 | ½ d |
+| 10 | ½–¾ d |
+| 11 | ½ d |
+| 12 | ½ d |
+| 13–14 | ¾ d |
+
+The production run is about ½ day of agent time over four short Paul sessions, roughly 75–100 minutes of his time. It is gated on 522 Plan 1 being released to the production console (doors and `restart/scope`), and phase 5 also needs oficina-connect live.
+
+## Open questions
+
+All of Q1–Q5 are answered (see "Paul's rulings" above). What remains:
+
+- **Q6 (default chosen):** calendar first as a canary, so Plan C is gated on the live checks.
+- **Q7 (default chosen, Paul may override):** the Home table counts come from Paul's read-only `carlos db query`, since the db doors admit people only, Admin included in the refusal. The alternative is a reviewed Home change that adds counts to `directory.inspect`. It is not planned.
+- **Dependency:** 522 Plan 1 merged and released to the production console before Task 14's read-only rehearsal. Task 6 step 0 confirms on that release whether a config write or scoped restart bumps `record_seq`.
+
+Nothing blocks starting implementation.