oficina / alta Public

Plan rev 3: fix the 13 pre-flight conflicts in the adoption plan

Reorder so each task consumes only earlier tasks' outputs: a shared
types and delivery-probe task (4) comes before the store (5); restart
and witness (8) come before the write and rollback (9). Declare
Preserved in Task 7. Add the HomePreflight phase and getter, and say how
adopt.Schema is applied through provision.NewStore. CheckHome takes the
operator client (one inspect per role) and Alta's journal heads. Move
make adopt to Task 14, add compat_test.go to Task 2, name the adverse
tests TestAdverse*, and route rollback restarts through
RestartCanonical's dry run. Bind the witness to the identity and
delivery it observed instead of a 24 h limit, since the spec sets none.
Reuse PublicOrigin/PublicHost/ConsumerID, provision.App and teamKeys.
Add agent-access.git to GOPRIVATE, the fakehome request log, and an
--apply table with tests. 15 tasks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 951b3c763b99924e770ca8b400815f97fd57f315 parent 6e07f3c
1 file changed, +652 −455
  • docs/superpowers/plans/2026-11-16-adoption-runner.md +652 −455
diff --git a/docs/superpowers/plans/2026-11-16-adoption-runner.md b/docs/superpowers/plans/2026-11-16-adoption-runner.md
index f658f28..3eee6a3 100644
--- a/docs/superpowers/plans/2026-11-16-adoption-runner.md
+++ b/docs/superpowers/plans/2026-11-16-adoption-runner.md
@@ -2,18 +2,29 @@
> **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.
+**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, 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.
+- **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`, Home `internal/operator` through `homecompat`, and agent-access `client` (module `amadan.net/oficina/agent-access.git` at `e4ea914`) for the live checks only.
+**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.
-**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.
+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.
---
@@ -21,418 +32,561 @@
**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_*`).
+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 the app's own 401 changing to agent-access's challenge.
+- **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 display name is "Oficina".
+- **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 Paul's per-app witnessed checks don't fit in one window, so there are three plans after initialize:
+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 5) |
-| 0b CARLOS preflight | none | per app: 522 reads, prospective key inheritance, identity, delivery baseline (Task 6) |
+| 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, after snapshot, delivery probe, Paul's witness |
+| 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** |
+| 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:** 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.
+- **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.
-- **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.
+- `<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.
-- **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.
+- **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 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`.
+- **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 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).
+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 | 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 |
+| 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 check targets, and `existing_team` in Alta's protocol mirror and fake Home
+### 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`.
-**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 (produced):**
-**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`.
+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 encoded bytes contain `"display_name":"Oficina","existing_team":"Uk","issued_at"`, and with `ExistingTeam == ""` the key is absent.
+ - `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 is allowed only at the proposed SQID;
- - provision refuses a non-canonical consumer or origin;
- - register returns the manifest digest without inserting;
+ - 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.
-- [ ] **Step 2:** `make check PKG=./homeop/... RUN='TestPlanExistingTeam|TestFakeHomeAdoptionScope'` → FAIL (unknown field).
+ - `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:** the same command → PASS. Then `make ci`.
-- [ ] **Step 5: Commit:** `homeop: existing_team on plans; make check targets`.
+- [ ] **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`). Create `homecompat/adopt_test.go`.
+**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`.** 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 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` = the directory's proposed SQID verifies under Home's `VerifyPlan` on both roles;
+ - 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:** `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`.
+- [ ] **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 for the 522 doors and the host-scoped restart, with its fake
+### Task 3: `carlosop`: an in-memory Admin client and 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`.
+**Files:** Create `carlosop/client.go`, `carlosop/digest.go`, `carlosop/fakecarlos/fakecarlos.go`. Test: `carlosop/client_test.go`, `carlosop/digest_test.go`.
-**Interfaces:**
+**Interfaces (produced):**
```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"
+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; Set map[string]string; Unset []string; IfVersion string }
+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
+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) // IfVersion required; env vars only
+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)
-func (c *Client) RestartHost(ctx context.Context, app, host string, dryRun bool) ([]RestartRoute, error) // POST …/restart/scope {"host","dry_run"}; 404/503 → ErrNoScopedRestart
+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 keeps per-host layer chains (default, named environment, owned environment, overlay). Its hooks are `BeforePut`, `LoseNextAnswer`, `SetSecret`, `PlatformWrite`, `FailRestart`, `RestartCount(host)` and `NoScopedRestart()`.
+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`: 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.
+- [ ] **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`.
- - `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`.
+- [ ] **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: Adoption state, journalled and sealed
+### Task 4: Shared adoption types and the delivery probe
-**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`.
+All types that later tasks store or pass around are defined here.
-**Interfaces:**
+**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
-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>")
+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, app, state string, sent map[string]string, rc *carlosop.Receipt) error // "sent","landed","stopped"
+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, app, state string, rc *carlosop.Receipt) error // "sent","unset","restarted","stopped"
+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, app string, w Witness) 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) LivePassed(ctx context.Context) (bool, error) // every RequiredLiveChecks name recorded "passed", none "failed"
+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));`
-- [ ] **Step 1: Write the failing tests:**
+`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`.
- - `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`.
+ - `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
-### Task 5: Home preflight with a supported evidence source
+The spec's preflight checks `teams`, `memberships`, `team_instances` and both streams.
-**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`.
+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.
-**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.
+It does **not** supply `memberships` or `team_instances`.
-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).
+**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 in `adopt/homepreflight_test.go`.
+**Files:** Create `adopt/homepreflight.go`. Test: `adopt/homepreflight_test.go`.
-**Interfaces:**
+**Interfaces.**
+
+Consumed: Task 4's `HomePreflight`, Task 5's store, `homeop.Client` (whose `Roles` holds both roles), and `provision.Store.Stream`.
+
+Produced:
```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)
+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)
```
-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>`.
+`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.
-- [ ] **Step 1: Write the failing tests:**
- - `TestHomePreflightBeforeInitializeRefusesAnyRow`: a non-zero membership count gives `memberships-nonzero`.
+**`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`.
- - `TestHomePreflightRecordsAttestationSealed`.
-- [ ] **Step 2:** `make check PKG=./adopt/... RUN=HomePreflight` → FAIL.
+ - `TestHomePreflightPrePlanAAcceptsOwnInitialize`.
+ - `TestHomePreflightPrePlanARefusesForeignDirectoryHead`.
+ - `TestHomePreflightPrePlanARefusesExtraReceipt`.
+- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestHomePreflight` and expect FAIL.
- [ ] **Step 3: Implement.**
-- [ ] **Step 4:** PASS.
-- [ ] **Step 5: Commit:** `adopt: Home preflight from inspect and attested read-only counts`.
+- [ ] **Step 4:** Expect PASS.
+- [ ] **Step 5: Commit.** `adopt: Home preflight from inspect and attested counts`
+
+### Task 7: Snapshots, preservation and CARLOS preflight
-### Task 6: Identity, snapshots and CARLOS preflight
+**Files:** Create `adopt/snapshot.go`. Test: `adopt/snapshot_test.go`.
-**Files:** Create `adopt/identity.go` and `adopt/snapshot.go`. Tests in `adopt/identity_test.go` and `adopt/snapshot_test.go`.
+**Interfaces.**
-**Interfaces:**
+Consumed: Tasks 3 and 4, plus `provision.App` and `provision.TeamKeyNames`.
+
+Produced:
```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)
+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)
```
-**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>`.
+- 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`: `DOCS_TEAM_ID` is refused, `MEMORIA_TEAM` alone passes.
+ - `TestPreflightRefusesTeamMode` (`MEMORIA_TEAM` alone passes).
- `TestPreflightRefusesForeignAgentKeys`.
- - `TestSameIdentityFlagsEachField`: one test per field.
- - `TestIdentityRefusesMovingInstance`.
+ - `TestPreflightRefusesMovingInstance`.
+ - `TestPreservedReportsEachViolation`.
+ - `TestPreservedIgnoresNewUnrelatedKey`.
- `TestPreflightOutputHasNoValuesOrDigests`.
-- [ ] **Step 2:** `make check PKG=./adopt/... RUN='Preflight|Identity'` → FAIL.
+- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Preflight|Preserved'` and expect FAIL.
- [ ] **Step 3: Implement.**
-- [ ] **Step 4:** PASS.
-- [ ] **Step 5: Commit:** `adopt: identity, snapshots, prospective-inheritance preflight`.
+- [ ] **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`.
-### Task 7: Configure's conditional write, and the journalled rollback
+**Interfaces.**
-**Files:** Create `adopt/write.go`. Test in `adopt/write_test.go`.
+Consumed: Tasks 3–7.
-**Interfaces:**
+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, t Target, sqid string, apply bool) (string, error)
+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, 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
+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:**
+**`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}`.
+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;
- - 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`.
+ - `Digests[k] == EnvDigest(sent[k])` for both keys;
+ - `Others` has before == after.
-### Task 8: Delivery probe, host-scoped restart, witness
+ 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.
-**Files:** Create `adopt/delivery.go`, `adopt/restart.go` and `adopt/words.go`. Test in `adopt/delivery_test.go`.
+**`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.
-**Interfaces:**
+Only then is the after snapshot stored. Otherwise return `ErrStopPreserved` and store nothing.
-```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
-```
+**`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)`.
-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.
+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:**
- - `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 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:** PASS.
-- [ ] **Step 5: Commit:** `adopt: delivery probe, host-scoped restart, witness`.
+- [ ] **Step 4:** Expect PASS.
+- [ ] **Step 5: Commit.** `adopt: conditional write, preserved after snapshot, rollback`
+
+### Task 10: Environment binding and the activation gate (Observer)
-### Task 9: 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`.
-**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.**
-**Interfaces:**
+Consumed: Tasks 3–9.
+
+Produced:
```go
// provision
@@ -442,264 +596,307 @@ type Observer interface { Observe(ctx context.Context, app, teamSQID string) (Ob
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 */ }
+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:
+**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;
+3. the before and after var lists, each sorted as `[key, kind, digest, from]`;
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.
+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`.
-- [ ] **Step 2:** `make check PKG=./adopt/... RUN='Binding|ObserverHappy'` → FAIL.
+ - `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:** PASS.
-- [ ] **Step 5: Commit:** `adopt: environment binding with witness; activation gate`.
+- [ ] **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`.
-### Task 10: Home half: adoption runs in Alta's engine
+**Interfaces.**
-**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`.
+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.
-**Interfaces:**
+Produced:
```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
+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: `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:**
+- 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`: no activate request is signed.
+ - `TestActivateAdoptedParksOnObserverRefusal`: `fakehome.Requests()` has no `directory.activate-consumer`.
- `TestActivateAdoptedStartedNotBeforeRecordedIssued`.
- `TestActivateAdoptedReverifiesLapsedAttempt`.
- `TestOrdinaryRunsStillRefuseOficina`.
- `TestDisableAdoptedRequiresTypedLabel`.
- - `TestAdoptionCrashAfterEveryAct`.
-- [ ] **Step 2:** `make check PKG=./provision/... RUN='Adoption|Adopted|Oficina'` → FAIL.
+ - `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:** PASS, then `make ci`.
-- [ ] **Step 5: Commit:** `provision: adoption runs for the canonical apps`.
+- [ ] **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
-### Task 11: 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.
-**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.**
-**Interfaces:**
+Consumed: Tasks 4 and 5 (`RequiredLiveChecks`, `SaveCheck`).
+
+Produced:
```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
+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
```
-Every step records `SaveCheck(name, "passed"|"failed:<code>")`, codes only.
+Each step records `SaveCheck(name, "passed" | "failed:<code>" | "inconclusive")`.
+
+**Before the checks:** the test account must have signed in to calendar.oficina.works once.
-**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`.** 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.
-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.
+ **`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.
-- [ ] **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.
+ **`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`.
- - `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.
+ - `TestLiveDryRunContactsNothing`.
+- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestLive` and expect 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`.
+- [ ] **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:** `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`.
+- [ ] **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 13: `cmd/alta-adopt`
+### Task 14: `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`.
+**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`.
-**Subcommands.** Every one that writes needs `--apply`.
+**`--apply` coverage.** Without `--apply`, every subcommand prints what it would do and writes nothing anywhere, the adoption journal included.
-| Subcommand | What it does |
+| Subcommand | Writes (only with `--apply`) |
|---|---|
-| `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`.
+| `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`: across a full fake run's stdout, stderr and logs, there is no `vd1:`, `cv1:`, binding, token, prefilter, owner canary or plain-value canary.
+ - `TestOutputScrub`.
- `TestTokenNeverInEnvOrDisk`.
-- [ ] **Step 2:** `make check PKG=./cmd/... RUN=.` → FAIL.
+- [ ] **Step 2:** Run `make check PKG=./cmd/... RUN=.` and expect 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.
+- [ ] **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
-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.
+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:** 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.
+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). 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.**
+| 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
-14 tasks, about 4½–5½ agent days including one Astra round per task, branch review and CI:
+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 | ½ 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.
+| 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). What remains:
+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.
-- **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`.
+**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 starting implementation.
+Nothing blocks implementation.