oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1# Existing-team adoption runner (`alta-adopt`) Implementation Plan
2
3> **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.
4
5**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.
6
7**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.
8
9**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.
10
11- **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.
12- **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:
13 - 522 Plan 1 snapshots and conditional writes;
14 - the narrowed per-host restart;
15 - the delivery probe and Paul's witnessed check;
16 - the live checks and re-observation.
17- `adopt` plugs into the engine through a one-method `provision.Observer` interface. The activation gate lives there, so nothing activates without complete, fresh evidence.
18
19**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`).
20
21**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.
22
23Also read:
24- the doors: carlos/platform `docs/superpowers/specs/2026-11-02-config-receipts-design.md` §4;
25- the narrowed restart: `internal/console/apirestartscope.go` (branch `config-receipts-1`, worktree `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/config-receipts-1`);
26- the rulings on oficina/home 103 and carlos/platform 522 (Paul, 2026-11-16);
27- Alta's `AGENTS.md` and `README.md`, first.
28
29---
30
31## Where the runner lives, and why
32
33**In oficina/alta, as a separate binary `cmd/alta-adopt`. Not in Home.**
34
351. **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.
362. **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`).
373. **Alta already knows each app.** `provision.App` holds the `Prefix`, and `teamKeys` lists the team-mode keys.
384. **Home stays small and holds no platform credential** (Home AGENTS.md; home-provisioner: "Home keeps no platform provisioning credential").
395. **Initialize can run now.** Alta isn't deployed, so its web Initialize page can't be reached. `alta-adopt initialize` wraps the existing `StartInitialize`.
40
41**Paul's rulings (2026-11-16), which this plan relies on:**
42- **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.
43- **Q2:** For Slides and Calls, the delivery observable is their own 401 changing to agent-access's challenge.
44- **Q3:** If another instance would receive the keys, the run stops.
45- **Q4:** Paul creates a throwaway Oficina ID test account.
46- **Q5:** The team's display name is "Oficina".
47
48## Run shape
49
50Home 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:
51
52| Phase | Window | What happens |
53|---|---|---|
54| 0a Home preflight | none | signed inspect of both roles, plus Paul's read-only `carlos db query` counts (Task 6) |
55| 0b CARLOS preflight | none | per app: 522 reads, prospective key inheritance, identity, delivery baseline (Task 7) |
56| 1 initialize | directory `initialize` | sequence 1 on the directory stream, Paul's typed §12 attestation |
57| 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) |
58| 3 configure | none | per app: mandatory preflight, sealed baseline, conditional PUT, receipt, host-scoped restart, preserved after snapshot, Paul's witness |
59| 4 Plan B | `add-apps`, `existing_team=<SQID>`, `calendar` | verify, re-observe, activate under `oficina/existing-app-activation/v1` |
60| 5 live checks | none | revocation and permission checks against connect for calendar. **Plan C is refused until they are recorded as passed.** |
61| 6 Plan C | `add-apps`, `existing_team=<SQID>`, the other five | verify, re-observe, activate |
62
63**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:
64- the instance identity;
65- the delivered version and header;
66- the after snapshot's config.
67
68Activation re-observes all three. Any change voids the witness and asks for a new one. There is no wall-clock limit.
69
70## Global Constraints
71
72- **Never print, log or store unsealed** any of these:
73 - a secret, or a plain var's value;
74 - any `vd1:` digest or `cv1:` version;
75 - `environment_binding`;
76 - a roster bearer, the operator key or the prefilter;
77 - the CARLOS token or an access token;
78 - the owner's address.
79
80 Output carries key names, kinds, hosts, fixed codes and states only.
81- **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.
82- **Dry-run by default.** Every subcommand that writes anywhere needs `--apply`: Home, CARLOS, connect, or the adoption journal. Task 14 has the table.
83- **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.
84- **Configure enforces every preflight refusal itself**, on a fresh read, immediately before its first PUT.
85- **Baseline:** captured once per app, sealed before storage, never rebaselined. Retries follow 522 §4.7: the first matching branch wins, preserved keys first.
86- **Preservation holds along the whole chain**, baseline → after snapshot → fresh, for every key in the baseline's effective config except the two added.
87- **Both keys or neither** (Memoria refuses to boot with one). Write and unset them in one request.
88- `<P>_AGENT_ISSUER = https://connect.oficina.works`, and `<P>_AGENT_TEAM` = the seeded SQID, equal to the plans' `existing_team`.
89- **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.
90- **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.
91- **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`.
92- **Delivery:** the `/api/version` body and `X-Carlos-Version` equal the before snapshot, no redirect is followed, and `/healthz` returns 200.
93- **Home requests:** nothing is inferred from a timeout, a lost answer is recovered only by exact replay, and nothing is deleted to clean up.
94- **Not done:** no instance creation, storage swap, Home key change or `HOME_CONSUMERS` change.
95- **The served binary stays clean:** `cmd/alta` must not import `adopt`, `carlosop` or agent-access.
96- **Copy:** CLI strings live in `adopt/words.go` and go through the copy-review skill before merge.
97- **Checks go through the Makefile only:** `make check PKG=<pkg> RUN=<regex>`, `make compat-check RUN=<regex>`, and `make ci`. Never bare `go test`.
98- **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.
99
100## Review Focus
101
1021. **Another instance would inherit a new key** through a layer it shares with the canonical host. The run stops (Task 7, `TestPreflightRefusesInheritanceDespiteOtherOverride`).
1032. **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`).
1043. **Slides and Calls already return their own 401.** Only agent-access's challenge counts as delivered (Task 4, `TestOperationsShapeDistinguishesAppMiddleware`).
1054. **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`).
1065. **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).
107
108---
109
110## File structure (oficina/alta)
111
112| File | Task | Responsibility |
113|---|---|---|
114| `Makefile` | 1, 14 | `check`, `compat-check`, `GOPRIVATE` (Task 1); `adopt` target (Task 14) |
115| `homeop/protocol.go`, `homeop/fakehome/fakehome.go` | 1 | `Plan.ExistingTeam`, `ExistingActivationPolicy`, `CanonicalOrigin`; fake adoption scope and ordered request log |
116| `provision/apps.go` | 1 | `PublicOrigin`, `PublicHost`, `ConsumerID` answer canonically for `oficina`; `TeamKeyNames` |
117| `homecompat/go.mod`, `homecompat/compat_test.go`, `homecompat/adopt_test.go` | 2 | pin Home ≥ `16da7ba`; harness; adoption against Home's real operator |
118| `carlosop/*` | 3 | 522 doors, instance/channel reads, scoped restart; fake |
119| `adopt/types.go`, `adopt/delivery.go` | 4 | shared types; delivery probe |
120| `provision/migrations/0003_adoption.sql`, `provision/store.go`, `adopt/migrations/0001_adopt.sql`, `adopt/store.go` | 5 | `runs.adoption`, `CreateAdoption`; sealed journal |
121| `adopt/homepreflight.go` | 6 | Home preflight |
122| `adopt/snapshot.go` | 7 | snapshots, preservation, CARLOS preflight |
123| `adopt/restart.go`, `adopt/witness.go`, `adopt/words.go` | 8 | `RestartCanonical`, `RestartAndWait`, witness |
124| `adopt/write.go` | 9 | conditional write, `CaptureAfter`, rollback |
125| `adopt/binding.go`, `adopt/observer.go`, `provision/adopt.go` (interface) | 10 | binding, activation gate |
126| `provision/adopt.go`, `provision/engine.go`, `provision/steps.go` | 11 | Home-half adoption runs |
127| `adopt/live.go`, `go.mod` | 12 | live checks |
128| `adopt/gate_adverse_test.go`, `provision/adopt_adverse_test.go` | 13 | adverse suite |
129| `cmd/alta-adopt/*`, `cmd/alta/imports_test.go` | 14 | the command |
130| `adopt/rehearsal_test.go`, `homecompat/adopt_flow_test.go`, `README.md` | 15 | rehearsal, runbook |
131
132---
133
134### Task 1: Makefile, protocol mirror, canonical values in Alta's own helpers, fake Home
135
136**Files:**
137- Modify: `Makefile`, `homeop/protocol.go` (Plan ~l.132; consts ~l.61), `homeop/fakehome/fakehome.go`, `provision/apps.go` (~l.130–134, `teamKeys` ~l.421).
138- Test: `homeop/protocol_test.go`, `homeop/fakehome/fakehome_test.go`, `provision/apps_test.go`.
139
140**Interfaces (produced):**
141
142Makefile:
143- `check:` runs `CGO_ENABLED=0 go test $(PKG) -run '$(RUN)' -count=1`. `PKG` is required.
144- `compat-check:` runs `cd homecompat && CGO_ENABLED=0 go test ./... -run '$(RUN)' -count=1`.
145- Add both to `.PHONY`.
146- `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.)
147
148`homeop`:
149- `Plan.ExistingTeam string`, tagged `json:"existing_team,omitzero"`, placed after `Owner`, as Home's `internal/operator/plan.go` does.
150- `ExistingActivationPolicy = "oficina/existing-app-activation/v1"`.
151- `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`.
152
153`provision`:
154- `const AdoptionLabel = "oficina"`.
155- `PublicOrigin(AdoptionLabel, app) == homeop.CanonicalOrigin(app)`.
156- `PublicHost(AdoptionLabel, app) == app + ".oficina.works"`.
157- `ConsumerID(AdoptionLabel, app) == app`.
158- Every other label is unchanged.
159- `func TeamKeyNames(app App) []string` returns the names `teamKeys` produces.
160
161`fakehome`:
162- Follows Home's `valid`, `routeScope`, the verify-only `register` branch, and the policy choice made by the window.
163- `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.
164
165- [ ] **Step 1: Write the failing tests.**
166 - `TestPlanExistingTeamEncodesLikeHome`: the bytes contain `"display_name":"Oficina","existing_team":"Uk","issued_at"`, and the key is absent when the field is empty.
167 - `TestCanonicalHelpersForOficina`: for each of the six apps, check the three helpers; for label `acme`, check they are unchanged.
168 - `TestTeamKeyNamesMatchesRecipe`.
169 - `TestFakeHomeAdoptionScope`:
170 - seed happens only at the proposed SQID;
171 - a non-canonical consumer or origin is refused;
172 - register inserts nothing;
173 - activate refuses `oficina/team-activation/v1` and accepts the existing policy;
174 - ordinary create-team or add-apps under `oficina` is refused.
175 - `TestFakeHomeRequestsOrdered`.
176- [ ] **Step 2:** Run `make check PKG=./homeop/... RUN='TestPlanExistingTeam|TestFakeHome'` and `make check PKG=./provision/... RUN='TestCanonicalHelpers|TestTeamKeyNames'`. Expect FAIL.
177- [ ] **Step 3: Implement.**
178- [ ] **Step 4:** Run the same commands and expect PASS. Then run `make ci`; existing engine tests are unchanged.
179- [ ] **Step 5: Commit.** `homeop: existing_team; canonical values in Alta's helpers`
180
181### Task 2: homecompat on Home's adoption code
182
183**Files:**
184- 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`.
185- Modify if needed: `homeop/protocol.go`, to repair the mirror.
186- Create: `homecompat/adopt_test.go`.
187
188- [ ] **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`.
189- [ ] **Step 2: Write the failing test** `TestHomeAcceptsAltaSignedExistingTeamPlan`:
190 - an Alta-signed plan with `ExistingTeam` set to the proposed SQID verifies on both roles;
191 - `PlanStore` keeps `existing_team`;
192 - an ordinary create-team under `oficina` is refused.
193- [ ] **Step 3:** Run `make compat-check RUN=TestHomeAcceptsAltaSigned` and expect FAIL until `compat_test.go`'s harness applies Home's adoption migration.
194- [ ] **Step 4:** Fix the harness in `compat_test.go`. Expect PASS.
195- [ ] **Step 5: Commit.** `homecompat: pin Home with existing-team adoption`
196
197### Task 3: `carlosop`: an in-memory Admin client and its fake
198
199**Files:** Create `carlosop/client.go`, `carlosop/digest.go`, `carlosop/fakecarlos/fakecarlos.go`. Test: `carlosop/client_test.go`, `carlosop/digest_test.go`.
200
201**Interfaces (produced):**
202
203```go
204func New(console, account string, token []byte) *Client // Q1: token from an fd; never env/disk/log
205func (c *Client) Close() // zeroes the token
206type Var struct { Key, Kind, Value, Digest string } // Value only for kind "env"
207type Layer struct { Bundle, Version string; Vars []Var }
208type EffectiveVar struct { Key, Kind, Digest, From string; Shadows []string }
209type Effective struct { Host, Environment string; Owned bool; Layers map[string]string; Vars []EffectiveVar }
210type Receipt struct { Bundle, VersionBefore, VersionAfter string; Changed bool; Set, Unset, UnsetAbsent []string; Digests map[string]string; Others map[string]struct{ Before, After string } }
211type Instance struct { Host, PublicHost, Account, App, Slug, Environment, Channel, Region string; CreatedAt time.Time; RecordSeq uint64; Move, ReplicaAssignment, Seed json.RawMessage }
212type PutRequest struct { Environment string /* "" = default bundle */; Set map[string]string; Unset []string; IfVersion string }
213type RestartRoute struct { Host, Environment, Unit string; Hibernate bool }
214var ErrVersionMismatch, ErrNoConditional, ErrNotFound, ErrNoScopedRestart error // the only declarations; adopt reuses them
215func (c *Client) Config(ctx context.Context, app, env string) (Layer, error)
216func (c *Client) Effective(ctx context.Context, app, host string) (Effective, error)
217func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, error)
218func (c *Client) Instances(ctx context.Context, app string) ([]Instance, error)
219func (c *Client) Instance(ctx context.Context, app, host string) (Instance, error)
220func (c *Client) ChannelDigest(ctx context.Context, app, channel, version string) (string, error) // normalised: 64 lowercase hex, else error
221func (c *Client) RestartHost(ctx context.Context, app, host string, dryRun bool) ([]RestartRoute, error) // only adopt.RestartCanonical calls this
222func EnvDigest(value string) string // "vd1:"+hex sha256("carlos.config.var.v1"\0"env"\0value\0""\0"")
223```
224
225The 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()`.
226
227- [ ] **Step 1: Write the failing tests.**
228 - `TestEnvDigestMatchesPlatformVector` (the golden value comes from platform `internal/appconfig` at the merged Plan 1 commit).
229 - `TestPutSendsIfVersionInBodyOnly`.
230 - `TestPut412IsVersionMismatch`.
231 - `TestPut400OnConditionalIsNoConditional`.
232 - `TestRestartHostUsesScopeDoorOnly`.
233 - `TestRestartHostOldConsoleFailsClosed`.
234 - `TestChannelDigestNormalisesHex`.
235 - `TestClientNeverFollowsRedirect`.
236 - `TestErrorsCarryNoTokenOrValue`.
237 - `TestTokenZeroedOnClose`.
238- [ ] **Step 2:** Run `make check PKG=./carlosop/... RUN=.` and expect FAIL.
239- [ ] **Step 3: Implement.** Model it on `console/fakeconsole`. `cv1:` is computed over the stored bytes; `vd1:` per 522 §4.3.
240- [ ] **Step 4:** Expect PASS.
241- [ ] **Step 5: Commit.** `carlosop: 522 config doors, host-scoped restart, fake console`
242
243### Task 4: Shared adoption types and the delivery probe
244
245All types that later tasks store or pass around are defined here.
246
247**Files:** Create `adopt/types.go`, `adopt/delivery.go`. Test: `adopt/types_test.go`, `adopt/delivery_test.go`.
248
249**Interfaces (produced):**
250
251```go
252const Issuer = "https://connect.oficina.works"
253func AgentKeys(app provision.App) [2]string // {Prefix+"_AGENT_ISSUER", Prefix+"_AGENT_TEAM"}
254func CanonicalHost(app provision.App) string // provision.PublicHost(provision.AdoptionLabel, app.Slug)
255type OpsShape string // "absent", "app-401", "agent-401", "agent-200", "other"
256type Delivery struct { Version, Header string; Redirected bool; Health int; Ops OpsShape; At time.Time }
257func Probe(ctx context.Context, h *http.Client, origin string) (Delivery, error)
258func Delivered(before, now Delivery) error // equal version+header, no redirect, health 200, now agent-shaped, before not
259func Reverted(before, now Delivery) error // equal version+header, health 200, now.Ops == before.Ops (rollback completion)
260type Identity struct { Account, App, RecordHost, PublicHost, Slug, Environment, Channel, Region string; Owned, Moving bool
261 CreatedAt time.Time; RecordSeq uint64; ReplicaAssignment, Seed string /* canonical JSON */ }
262func IdentityOf(in carlosop.Instance, eff carlosop.Effective) Identity // Moving = Move non-null; never errors
263func SameIdentity(a, b Identity) []string // codes: storage (slug, created_at, replica, seed), instance (record host), alias (public host), environment, owned, channel, region, moving, record
264type Snapshot struct { Identity Identity; WriteLayer string; Layer carlosop.Layer; Layers map[string]string; Vars []carlosop.EffectiveVar; HomeIssuer, HomeConsumer string; Delivery Delivery; At time.Time }
265type Witness struct { App, Typed string; Identity Identity; Delivery Delivery; AfterVersion string /* the after snapshot's write-layer version, sealed */; At time.Time }
266type HomePreflight struct { Phase string /* "pre-initialize" | "pre-plan-a" */; CredentialSeq, DirectorySeq int64; CredentialHead string; Generation *string
267 ProposedID int64; ProposedSQID string; Pending, Open bool; Counts map[string]int64; AttestedAt time.Time }
268type WriteRecord struct { App, State string /* sent, landed, stopped */; Sent map[string]string; Receipt *carlosop.Receipt; Code string }
269type RollbackRecord struct { App, State string /* sent, unset, restarted, stopped */; Receipt *carlosop.Receipt; Code string }
270var 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"}
271```
272
273**`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",…}}`.
274
275**Storage identity, decided here.** An instance's persistent storage is identified by the record's `Slug`, `CreatedAt`, `ReplicaAssignment` and `Seed`:
276- recreating the instance, or swapping its storage, gives a new record or a new assignment;
277- a move changes `Region` and sets `Move`.
278
279`RecordSeq` is compared unless Task 7's step 0 shows that the runner's own write or restart bumps it.
280
281- [ ] **Step 1: Write the failing tests.**
282 - `TestOperationsShapeDistinguishesAppMiddleware`: `{"error":"unauthorized"}` is `app-401`.
283 - `TestDeliveredRefusesVersionOrHeaderChange`.
284 - `TestProbeRefusesRedirect`.
285 - `TestRevertedRequiresBeforeShape`.
286 - `TestSameIdentityFlagsEachField`: one subtest per code, including `owned` and `moving`.
287- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='OperationsShape|Delivered|Probe|Reverted|SameIdentity'` and expect FAIL.
288- [ ] **Step 3: Implement.**
289- [ ] **Step 4:** Expect PASS.
290- [ ] **Step 5: Commit.** `adopt: shared types and delivery probe`
291
292### Task 5: Adoption state, journalled and sealed
293
294**Files:**
295- Create: `provision/migrations/0003_adoption.sql`, `adopt/migrations/0001_adopt.sql`, `adopt/store.go`.
296- Modify: `provision/store.go`.
297- Test: `provision/store_adopt_test.go`, `adopt/store_test.go`.
298
299**Interfaces.**
300
301Consumed: Task 4's types.
302
303Produced:
304
305```go
306// provision
307type Run struct { /* existing fields */; Adoption bool } // scanRun reads the new column
308func (s *Store) CreateAdoption(ctx context.Context, name, owner string, apps []string) error // teams/team_apps/owner_inputs; environment ""; NO environments rows
309func (s *Store) NewAdoptionRun(ctx context.Context, kind string, apps []string) (int64, error)
310// adopt — payloads sealed under "alta/adopt/<table>/<key>"
311var Schema *migrate.Set
312func NewStore(ps *provision.Store) (*Store, error)
313func (s *Store) SaveHomePreflight(ctx context.Context, r HomePreflight) error
314func (s *Store) HomePreflight(ctx context.Context, phase string) (HomePreflight, bool, error)
315func (s *Store) SaveBaseline(ctx context.Context, app string, snap Snapshot) error // insert-only → ErrBaselineExists
316func (s *Store) Baseline(ctx context.Context, app string) (Snapshot, bool, error)
317func (s *Store) SaveWrite(ctx context.Context, r WriteRecord) error
318func (s *Store) Write(ctx context.Context, app string) (WriteRecord, bool, error)
319func (s *Store) SaveRollback(ctx context.Context, r RollbackRecord) error
320func (s *Store) Rollback(ctx context.Context, app string) (RollbackRecord, bool, error)
321func (s *Store) SaveAfter(ctx context.Context, app string, snap Snapshot) error
322func (s *Store) After(ctx context.Context, app string) (Snapshot, bool, error)
323func (s *Store) SaveWitness(ctx context.Context, w Witness) error
324func (s *Store) Witness(ctx context.Context, app string) (Witness, bool, error)
325func (s *Store) SaveCheck(ctx context.Context, name, outcome string) error
326func (s *Store) LiveGate(ctx context.Context, app string) error // nil for "calendar"; else every RequiredLiveChecks name "passed", none failed → or "live-checks-missing"
327```
328
329**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.
330
331`0003_adoption.sql`: `ALTER TABLE runs ADD COLUMN adoption INTEGER NOT NULL DEFAULT 0 CHECK (adoption IN (0, 1));`
332
333`LiveGate` is the one implementation of the live-check rule. It is used by both `Observer` (Task 10) and the command (Task 14).
334
335- [ ] **Step 1: Write the failing tests.**
336 - `TestCreateAdoptionWritesNoEnvironmentRows`: `Guard.Environment` refuses every app for `oficina`.
337 - `TestAdoptionRunColumnScanned`.
338 - `TestAdoptStoreRefusesUnmigratedDB`.
339 - `TestBaselineIsInsertOnly`.
340 - `TestHomePreflightByPhase`.
341 - `TestLiveGateCanaryAndRest`.
342 - `TestAdoptRowsAreSealed`: the raw database file and WAL hold no `vd1:`, `cv1:`, value canary or owner canary.
343- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Store|HomePreflightByPhase|LiveGate|Sealed|Baseline'` and `make check PKG=./provision/... RUN='Adoption'`. Expect FAIL.
344- [ ] **Step 3: Implement.** Turn `secure_delete` on.
345- [ ] **Step 4:** Expect PASS, then run `make ci`.
346- [ ] **Step 5: Commit.** `Adoption state: sealed journal`
347
348### Task 6: Home preflight with a supported evidence source
349
350The spec's preflight checks `teams`, `memberships`, `team_instances` and both streams.
351
352Signed inspect (`http_verbs.go` `HTTPInspection`) supplies:
353- each role's `sequence` and `head`;
354- `generation`;
355- `proposed_team_id`/`_sqid` (a proposed id of 1 means `teams` is empty and `sqlite_sequence` is unused);
356- pending and open plans.
357
358It does **not** supply `memberships` or `team_instances`.
359
360**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).
361
362**Files:** Create `adopt/homepreflight.go`. Test: `adopt/homepreflight_test.go`.
363
364**Interfaces.**
365
366Consumed: Task 4's `HomePreflight`, Task 5's store, `homeop.Client` (whose `Roles` holds both roles), and `provision.Store.Stream`.
367
368Produced:
369
370```go
371func HomeQueries() []string // "SELECT count(*) FROM <t>" for teams, memberships, team_instances, operator_http_teams, roster_generation, roster_consumers, roster_tokens, roster_operator_receipts
372func CheckHome(ctx context.Context, h *homeop.Client, ps *provision.Store, counts map[string]int64, phase string) (HomePreflight, []string, error)
373```
374
375`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)`.
376
377**`pre-initialize`** requires all of:
378- both inspected sequences are 0 with an empty head;
379- `Generation` is nil;
380- `ProposedID` is 1;
381- there is no pending or open plan;
382- every count is 0.
383
384**`pre-plan-a`** requires all of:
385- the directory's inspected `(sequence, head)` equals Alta's journal stream for the directory (only Alta's initialize so far);
386- the credential's is `(0, "")`, or equals Alta's journal stream for the credential;
387- `Generation` is set;
388- `ProposedID` is 1;
389- every count is 0, except `roster_generation = 1` and `roster_operator_receipts = 1`.
390
391A count missing from the paste gives `count-missing-<t>`.
392
393- [ ] **Step 1: Write the failing tests.**
394 - `TestHomePreflightBeforeInitializeRefusesAnyRow`.
395 - `TestHomePreflightRefusesUsedStreams`.
396 - `TestHomePreflightRefusesProposedNotOne`.
397 - `TestHomePreflightRefusesMissingCount`.
398 - `TestHomePreflightPrePlanAAcceptsOwnInitialize`.
399 - `TestHomePreflightPrePlanARefusesForeignDirectoryHead`.
400 - `TestHomePreflightPrePlanARefusesExtraReceipt`.
401- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestHomePreflight` and expect FAIL.
402- [ ] **Step 3: Implement.**
403- [ ] **Step 4:** Expect PASS.
404- [ ] **Step 5: Commit.** `adopt: Home preflight from inspect and attested counts`
405
406### Task 7: Snapshots, preservation and CARLOS preflight
407
408**Files:** Create `adopt/snapshot.go`. Test: `adopt/snapshot_test.go`.
409
410**Interfaces.**
411
412Consumed: Tasks 3 and 4, plus `provision.App` and `provision.TeamKeyNames`.
413
414Produced:
415
416```go
417func Observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, error)
418func 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.
419func NewKeys(before, after Snapshot, added [2]string) []string // "added:<KEY>", reported only
420func TeamModeKeys(app provision.App, vars []carlosop.EffectiveVar) []string
421func Preflight(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, mine map[string]string) (Snapshot, []string, error)
422```
423
424- 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.
425- **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:
426 1. the write layer is in `H`'s chain (default: `H` is not owned; named: `H`'s environment equals it);
427 2. no layer above it in `H`'s chain already sets `k`.
428
429 Overrides of other keys are irrelevant. Any such `H` gives `inherits-<host>`.
430- **Refusals:**
431 - `agent-keys-present`, unless their digests equal `EnvDigest(mine[k])`;
432 - `team-mode-<KEY>`;
433 - `home-issuer-mismatch`;
434 - `home-consumer-mismatch`;
435 - `layer-overlay`;
436 - `owned-environment`;
437 - `instance-missing`;
438 - `instance-moving`;
439 - `inherits-<host>`;
440 - `version-header-mismatch`;
441 - `healthz`.
442
443- [ ] **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.
444- [ ] **Step 1: Write the failing tests.**
445 - `TestPreflightRefusesInheritanceDespiteOtherOverride`: a neighbour overrides `DOCS_HOME_ISSUER` but inherits both agent keys.
446 - `TestPreflightAllowsOwnedEnvironmentNeighbour`.
447 - `TestPreflightAllowsNeighbourThatAlreadyShadowsBothKeys`.
448 - `TestPreflightRefusesTeamMode` (`MEMORIA_TEAM` alone passes).
449 - `TestPreflightRefusesForeignAgentKeys`.
450 - `TestPreflightRefusesMovingInstance`.
451 - `TestPreservedReportsEachViolation`.
452 - `TestPreservedIgnoresNewUnrelatedKey`.
453 - `TestPreflightOutputHasNoValuesOrDigests`.
454- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Preflight|Preserved'` and expect FAIL.
455- [ ] **Step 3: Implement.**
456- [ ] **Step 4:** Expect PASS.
457- [ ] **Step 5: Commit.** `adopt: snapshots, preservation, prospective-inheritance preflight`
458
459### Task 8: Host-scoped restart and the witness
460
461**Files:** Create `adopt/restart.go`, `adopt/witness.go`, `adopt/words.go`. Test: `adopt/restart_test.go`, `adopt/witness_test.go`.
462
463**Interfaces.**
464
465Consumed: Tasks 3–7.
466
467Produced:
468
469```go
470func 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
471func 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
472func WitnessSentence(app provision.App) string // words.go, copy-reviewed
473func RecordWitness(ctx context.Context, s *Store, c *carlosop.Client, h *http.Client, app provision.App, typed string, apply bool) error
474```
475
476`RecordWitness` refuses unless all of these hold:
477- `typed` equals the sentence;
478- the after snapshot exists;
479- a fresh `Probe` passes `Delivered` against the baseline;
480- a fresh identity equals the after snapshot's.
481
482It 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.
483
484- [ ] **Step 1: Write the failing tests.**
485 - `TestRestartCanonicalLeavesOtherInstancesUntouched`: `RestartCount` is 0 for every other host, and `AppWideRestarts()` is 0.
486 - `TestRestartCanonicalRefusesWiderDryRun`.
487 - `TestRestartCanonicalFailsClosedOnOldConsole`.
488 - `TestRestartAndWaitTimesOut`.
489 - `TestWitnessRefusesWrongAppSentence`.
490 - `TestWitnessRefusesWithoutAgentShape`.
491 - `TestWitnessRefusesIdentityChangedSinceAfter`.
492 - `TestWitnessDryRunRecordsNothing`.
493- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='RestartCanonical|RestartAndWait|Witness'` and expect FAIL.
494- [ ] **Step 3: Implement.**
495- [ ] **Step 4:** Expect PASS.
496- [ ] **Step 5: Commit.** `adopt: host-scoped restart and witness`
497
498### Task 9: Configure's conditional write, `CaptureAfter`, and the journalled rollback
499
500**Files:** Create `adopt/write.go`. Test: `adopt/write_test.go`.
501
502**Interfaces.**
503
504Consumed: Tasks 3–8. `carlosop.ErrNoConditional` and `ErrVersionMismatch` are reused, not redeclared.
505
506Produced:
507
508```go
509type Branch int // Landed, Retry, StopPreservedChanged, StopConflict
510func Classify(baseline, read carlosop.Layer, sent map[string]string) Branch
511func 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"
512func CaptureAfter(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App) (Snapshot, error)
513type RollbackBranch int // RolledBack, RetryUnset, StopForeign, StopPreservedChanged
514func ClassifyRollback(baseline, read carlosop.Layer, sent map[string]string) RollbackBranch
515func RollbackAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s *Store, app provision.App, apply bool) error
516var ErrStopPreserved, ErrStopConflict, ErrStopForeign error
517```
518
519**`WriteAgentKeys`:**
5201. If the journal says `landed`, return.
5212. Run `Preflight` with `mine` set to the journal's sent values. Any code stops it, and nothing is written.
5223. Load the baseline from the journal, or capture it and seal it.
5234. Save the write as `sent`, then send `Put{Environment: baseline.WriteLayer, IfVersion: baseline.Layer.Version, Set: both}`.
5245. On 200, require all of:
525 - `Set` is exactly the two keys;
526 - `Unset` and `UnsetAbsent` are empty;
527 - `Digests[k] == EnvDigest(sent[k])` for both keys;
528 - `Others` has before == after.
529
530 Otherwise stop with `ErrStopConflict`.
5316. 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.
532
533**`CaptureAfter`**, run after `RestartAndWait(…, until = Delivered vs baseline)`:
534- observe;
535- require `Preserved(baseline, after, AgentKeys)` to be empty;
536- require both agent keys to carry the sent digests;
537- require that no team-mode key is present.
538
539Only then is the after snapshot stored. Otherwise return `ErrStopPreserved` and store nothing.
540
541**`RollbackAgentKeys`**, journalled:
5421. Reread and run `ClassifyRollback`:
543 - **RetryUnset:** both keys hold exactly the sent digests.
544 - **RolledBack:** both keys are absent and the preserved keys are equal.
545 - **StopForeign:** either key holds another digest or kind, or only one is present.
546 - **StopPreservedChanged:** a preserved key changed.
5472. 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.
5483. Then **`RestartCanonical`**, through the same dry-run-resolves-one-route path. Never call `RestartHost` directly. Then `RestartAndWait(…, until = Reverted vs baseline)`.
549
550Removing 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.
551
552- [ ] **Step 1: Write the failing tests.**
553
554 Configure:
555 - `TestConfigureCallsPreflightEvenWhenInvokedDirectly`, `TestConfigureRefusesForeignAgentKeys`, `TestConfigureRefusesTeamMode`, `TestConfigureRefusesInheritingNeighbour`: each makes zero PUTs.
556 - `TestWriteHappyPathReceiptChecked`.
557 - `TestWriteLostAnswerLanded`: exactly one PUT.
558 - `TestWriteRetriesAfterUnrelatedKeyAdded`: the baseline bytes are unchanged.
559 - `TestWriteStopsWhenPreservedKeyResealed`.
560 - `TestWriteStopsOnPartialOrForeignAgentKeys`.
561 - `TestWriteRejectsMalformedReceipts`: subtests for an extra `Set` key, a missing digest, a wrong digest, a non-empty `Unset`, and `Others` moved.
562 - `TestWriteRefusesWithoutConditionalSupport`.
563 - `TestWriteDryRunSendsNothing`.
564 - `TestAfterSnapshotRefusesSecretResealedBeforeCapture`.
565
566 Rollback:
567 - `TestRollbackLostAnswerRetryAcceptsUnsetAbsent`.
568 - `TestRollbackRefusesForeignValue`: zero PUTs.
569 - `TestRollbackConflict412Rereads`.
570 - `TestRollbackCrashAfterUnsetResumesToRestart`.
571 - `TestRollbackRestartFailureLeavesUnsetState`.
572 - `TestRollbackUsesScopedDryRun`: the fake sees a dry run before the restart, and no app-wide restart.
573 - `TestRollbackCompleteOnlyWhenReverted`.
574- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Configure|TestWrite|AfterSnapshot|TestRollback'` and expect FAIL.
575- [ ] **Step 3: Implement.**
576- [ ] **Step 4:** Expect PASS.
577- [ ] **Step 5: Commit.** `adopt: conditional write, preserved after snapshot, rollback`
578
579### Task 10: Environment binding and the activation gate (Observer)
580
581**Files:**
582- Create: `adopt/binding.go`, `adopt/observer.go`, `provision/adopt.go` (the interface only).
583- Test: `adopt/binding_test.go`, `adopt/observer_test.go`.
584
585**Interfaces.**
586
587Consumed: Tasks 3–9.
588
589Produced:
590
591```go
592// provision
593type Observation struct { AppVersion, ArtifactDigest, EnvironmentBinding string }
594type Observer interface { Observe(ctx context.Context, app, teamSQID string) (Observation, error) }
595// adopt
596type BindingInput struct { Before, After Identity; BeforeVars, AfterVars []carlosop.EffectiveVar; BeforeLayers, AfterLayers map[string]string
597 TeamSQID, Issuer, ArtifactSHA256, Version string; BeforeDelivery, AfterDelivery, NowDelivery Delivery; Witness Witness; HomePreflightAt time.Time }
598func EnvironmentBinding(in BindingInput) string
599type Observer struct { C *carlosop.Client; H *http.Client; S *Store; Artifacts map[string]string /* app → 64 lowercase hex */; Now func() time.Time }
600func (o *Observer) Observe(ctx context.Context, app, teamSQID string) (provision.Observation, error)
601```
602
603**The binding** is `base64url(sha256(encoding/json.Marshal([]any{…})))` over these parts, in order:
6041. `"oficina/existing-app-observation/v1"`;
6052. the before and after identities;
6063. the before and after var lists, each sorted as `[key, kind, digest, from]`;
6074. the before and after layers;
6085. the SQID, the issuer, the artifact SHA-256 and the version;
6096. the before, after and now delivery observations;
6107. the witness: app, sentence, identity, delivery, after version and time.
611
612This puts Paul's witness and the delivery observations inside the signed observation.
613
614**`Observe`** refuses, each time with a fixed code, unless every one of these holds:
615- **Evidence present:** the `pre-plan-a` Home preflight, the baseline, a `landed` write, the after snapshot and the witness (`missing-<x>`).
616- **Identity:** a fresh `IdentityOf` equals the baseline's, the after snapshot's and the witness's (`identity-<code>`).
617- **Preservation:** `Preserved(baseline, after)` and `Preserved(baseline, fresh)` are both empty (`after-not-preserved`, `drift-<key>`).
618- **Config:** the fresh read equals the after snapshot digest for digest. No team-mode key is present. Both agent keys carry the sent digests.
619- **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.
620- **Delivery:** a fresh `Probe` passes `Delivered` against the baseline. The version matches `^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`.
621- **Artifact:** `ChannelDigest(channel, version)` equals `Artifacts[app]`, both as 64 lowercase hex. `ArtifactDigest` is base64url of the same 32 bytes.
622- **Live checks:** `S.LiveGate(ctx, app)` passes.
623
624- [ ] **Step 1: Write the failing tests.**
625 - `TestBindingIncludesWitnessAndDelivery`.
626 - `TestBindingIsOrderIndependent`.
627 - `TestObserverHappyPathEvidenceTokens`.
628 - `TestObserverAcceptsWitnessFromEarlierSession`: the clock is moved forward 3 days and nothing else changes, so the gate passes.
629 - `TestObserverRefusesSupersededWitness`.
630- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN='Binding|TestObserver'` and expect FAIL.
631- [ ] **Step 3: Implement.**
632- [ ] **Step 4:** Expect PASS.
633- [ ] **Step 5: Commit.** `adopt: environment binding with witness; activation gate`
634
635### Task 11: Home half: adoption runs in Alta's engine
636
637**Files:**
638- Modify: `provision/adopt.go`, `provision/engine.go` (`Config.Observer`; `Advance` dispatches on `run.Adoption`), `provision/steps.go`.
639- Test: `provision/adopt_test.go`.
640
641**Interfaces.**
642
643Consumed: 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.
644
645Produced:
646
647```go
648func (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
649func (e *Engine) ActivateAdopted(ctx context.Context, apps []string) (int64, error) // add-apps, both roles, existing_team = stored team SQID, no owner
650func (e *Engine) DisableAdopted(ctx context.Context, app, typed string) (int64, error) // retire-apps, label oficina, directory.disable-consumer only; typed must equal "oficina"
651```
652
653**Plan A:**
654- owner-seed, with `TeamSQID == ExistingTeam` and `ExistingOnly`;
655- seed-team as `Label "oficina"`, `Name "Oficina"`;
656- for each app, the consumer and register steps;
657- the run ends `done` with code `awaiting-configuration`;
658- no console calls are made, and the owner's address is forgotten after the seed.
659
660**Plan B/C, for each app:**
661- `StepVerify` runs without the `/api/team` probe.
662 - 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`).
663 - `started_at ≥ issued_at` holds, because the recorded value is never earlier than Home's.
664- `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`.
665- A nil Observer gives `no-observer`, as in served Alta. An Observer refusal parks with its code and never activates.
666
667- [ ] **Step 1: Write the failing tests.**
668 - `TestAdoptionPlanACarriesExistingTeamOnBothRoles`.
669 - `TestAdoptionSeedsAtProposedSQIDOnly`.
670 - `TestAdoptionRegisterInsertsNothing`.
671 - `TestAdoptionMakesNoConsoleCalls`.
672 - `TestActivateAdoptedUsesExistingPolicy`.
673 - `TestActivateAdoptedWithoutObserverFails`.
674 - `TestActivateAdoptedParksOnObserverRefusal`: `fakehome.Requests()` has no `directory.activate-consumer`.
675 - `TestActivateAdoptedStartedNotBeforeRecordedIssued`.
676 - `TestActivateAdoptedReverifiesLapsedAttempt`.
677 - `TestOrdinaryRunsStillRefuseOficina`.
678 - `TestDisableAdoptedRequiresTypedLabel`.
679 - `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).
680- [ ] **Step 2:** Run `make check PKG=./provision/... RUN='TestAdoption|TestActivateAdopted|TestOrdinaryRuns|TestDisableAdopted'` and expect FAIL.
681- [ ] **Step 3: Implement.**
682- [ ] **Step 4:** Expect PASS, then run `make ci`.
683- [ ] **Step 5: Commit.** `provision: adoption runs for the canonical apps`
684
685### Task 12: Live checks that prove revocation
686
687**Files:**
688- Create: `adopt/live.go`.
689- Modify: `go.mod` (require `amadan.net/oficina/agent-access.git@e4ea914`; `GOPRIVATE` was set in Task 1).
690- Test: `adopt/live_test.go`, using an httptest fake of connect.
691
692**Interfaces.**
693
694Consumed: Tasks 4 and 5 (`RequiredLiveChecks`, `SaveCheck`).
695
696Produced:
697
698```go
699type MemoryStore struct{ /* client.Credentials in memory only */ }
700type Prompter interface { Ask(ctx context.Context, sentence string) error }
701func 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
702```
703
704Each step records `SaveCheck(name, "passed" | "failed:<code>" | "inconclusive")`.
705
706**Before the checks:** the test account must have signed in to calendar.oficina.works once.
707
7081. **`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.
7092. **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).
7103. **`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.
7114. **`member-no-local-permission-refused`.** `calendar_get_event` with `foreignEventID` is refused with `not_found` or `forbidden`.
7125. **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.
7136. **`local-access-kept`.** Paul types the sentence.
7147. **`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.
715
716 **`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.
717
718 **`owner-local-access-kept`:** Paul types the sentence.
7198. **Always:** `Logout` every connection. Saved requests and tokens are zeroed when `RunLive` returns.
720
721- [ ] **Step 1: Write the failing tests.**
722 - `TestLiveFailsWhenRevocationNotEnforced`.
723 - `TestLiveFailsWhenMemberCannotCallBeforeRemoval`: later steps are skipped and not passed.
724 - `TestLiveRepeatsExactRequest`: the fake asserts the same bearer and body.
725 - `TestLiveFailsWhenNonMemberSucceeds`.
726 - `TestLiveFailsWhenForeignEventReadable`.
727 - `TestLiveFailsWhenRevokeLeavesAccessValid`.
728 - `TestLiveOwnerRevokeReplaysSavedRequest`.
729 - `TestLiveReplayAfterExpiryIsInconclusive`.
730 - `TestLiveRecordsCodesOnly`.
731 - `TestLiveAlwaysLogsOut`.
732 - `TestLiveDryRunContactsNothing`.
733- [ ] **Step 2:** Run `make check PKG=./adopt/... RUN=TestLive` and expect FAIL.
734- [ ] **Step 3: Implement.**
735- [ ] **Step 4:** Expect PASS.
736- [ ] **Step 5: Commit.** `adopt: live checks proving revocation`
737
738### Task 13: Activation-gate adverse suite
739
740**Files:** Create `adopt/gate_adverse_test.go`, `provision/adopt_adverse_test.go`.
741
742Every 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.
743
744- [ ] **Step 1: Write the tests.**
745 - **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.
746 - **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.
747 - **Changed config:**
748 - a preserved secret resealed between the PUT and the after snapshot (a hand-written after row that bypassed `CaptureAfter`, so `after-not-preserved`);
749 - a preserved secret resealed after the after snapshot;
750 - a plain value changed; a key removed;
751 - a new team-mode key;
752 - an agent key with another digest;
753 - an overlay that shadows an agent key.
754 - **Superseded witness:** the after version changed, or the delivered version or header changed since the witness.
755 - **Changed delivery:** the version body; the header; a redirect; healthz 503; ops reverted to `app-401`.
756 - **Artifact:** the channel digest differs; the version is malformed.
757 - **Malformed receipts:** each one from Task 9 leaves the write not `landed`, so `missing-write`.
758 - **Failed local-permission check:** `member-no-local-permission-refused` failed, so Plan C is refused.
759- [ ] **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.
760- [ ] **Step 3:** Fix any real gap in Task 10's or Task 11's files.
761- [ ] **Step 4:** Expect PASS.
762- [ ] **Step 5: Commit.** `adopt: activation gate adverse suite`
763
764### Task 14: `cmd/alta-adopt`
765
766**Files:**
767- Create: `cmd/alta-adopt/main.go`, `cmd/alta-adopt/config.go`, `cmd/alta/imports_test.go`.
768- Modify: `Makefile`. Add an `adopt:` target that builds `./cmd/alta-adopt` natively, stamped like `release`, and add it to `.PHONY`.
769- Test: `cmd/alta-adopt/main_test.go`.
770
771**`--apply` coverage.** Without `--apply`, every subcommand prints what it would do and writes nothing anywhere, the adoption journal included.
772
773| Subcommand | Writes (only with `--apply`) |
774|---|---|
775| `home-preflight --phase pre-initialize\|pre-plan-a` | journal (the attestation); without it, prints the queries and checks the pasted counts |
776| `preflight` | none (always read-only) |
777| `initialize` | Home (initialize plan and operation), journal. Refuses without a recorded `pre-initialize` |
778| `plan-a` | Home (plans), journal. Refuses without `pre-plan-a` |
779| `advance --run <id>` | Home (operations), journal |
780| `configure --app <a>` | CARLOS (PUT, restart), journal |
781| `witness --app <a>` | journal; without it, shows what was observed and asks for no typed sentence |
782| `activate --apps <list>` | Home (plans), journal. Non-canary apps are checked through `Store.LiveGate`, the same function `Observer` uses |
783| `live` | connect (logins, calls, revokes), journal |
784| `rollback-config --app <a>` | CARLOS, journal |
785| `disable --app <a>` | Home; `typed` is read from the terminal and must equal "oficina" |
786| `status` | none |
787
788**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}`.
789
790The 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.
791
792- [ ] **Step 1: Write the failing tests.**
793 - `TestServedAltaImportsNoAdoptionCode`.
794 - `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.
795 - `TestInitializeRefusedWithoutHomePreflight`.
796 - `TestActivateNonCanaryRefusedWithoutLive`.
797 - `TestConfigFileModeRefused`.
798 - `TestOutputScrub`.
799 - `TestTokenNeverInEnvOrDisk`.
800- [ ] **Step 2:** Run `make check PKG=./cmd/... RUN=.` and expect FAIL.
801- [ ] **Step 3: Implement.**
802- [ ] **Step 4:** Expect PASS. Then run `make adopt` and `make ci`.
803- [ ] **Step 5: Copy review.** Take `adopt/words.go` and the help text through the copy-review skill, and apply Paul's edits verbatim.
804- [ ] **Step 6: Commit.** `alta-adopt: the local adoption command`
805
806### Task 15: Rehearsal, homecompat flow, runbook
807
808**Files:** Create `adopt/rehearsal_test.go`, `homecompat/adopt_flow_test.go`. Modify `README.md`.
809
810- [ ] **Step 1: Write the tests.**
811 - **`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:
812 - six routes are live;
813 - every preserved digest is equal;
814 - each layer differs only by the two keys;
815 - every other host's `RestartCount` is 0 and `AppWideRestarts()` is 0.
816 - **`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:
817 - PUT count per app ≤ 2, and exactly 1 when the first answer was only lost;
818 - the sealed baseline bytes are unchanged;
819 - no unset of a foreign value;
820 - `Requests()` has each (action, app) committed once.
821 - **homecompat `TestAdoptionFlowAgainstRealHome`** runs against real Home. At the end, canonical `team_instances` are live, credential `consumers` is empty, and the manifest digest is unchanged.
822- [ ] **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.
823- [ ] **Step 3:** Write the README runbook: phases, Paul's steps and the rollback table. Then run `make ci` and expect PASS.
824- [ ] **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.
825- [ ] **Step 5:** Commit and push. Then the Alta branch discussion, Astra's branch review, CI green and squash-merge.
826
827---
828
829## Paul's action points, in order
830
831Phases may fall in separate sessions on separate days. A witness stays valid until something it observed changes.
832
8331. **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.
8342. **CARLOS credential.** Run `carlos services create --account oficina --role admin oficina-adoption`, and pass the result to `alta-adopt` only on a file descriptor.
8353. **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.
8364. **Watch the CARLOS preflight.** Any `inherits-<host>` stops the run (Q3).
8375. **§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.
8386. **Home counts, before Plan A.** Run `home-preflight --phase pre-plan-a --apply`.
8397. **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.
8408. **Configure.** OK `configure --app <a> --apply` for each app. That is one config write and one restart, of that host only.
8419. **Witness each app.** Sign in at `https://<app>.oficina.works` in the system browser, then run `witness --app <a> --apply` and type the sentence.
84210. **Plan B.** Run `activate --apps calendar --apply`, then make the two confirmations.
84311. **Test account.** Create the throwaway Oficina ID account, sign it in to calendar.oficina.works once, and pick one of his own events.
84412. **Live checks** (oficina-connect deployed and `HOME_AGENT_DIRECTORY_TOKEN_SHA256` set). Run `live --apply`:
845 - sign the test account in to connect;
846 - add, then remove, the test account on the Team page;
847 - witness both local sign-ins;
848 - connect his own account, then revoke it.
84913. **Plan C.** Run `activate --apps docs,sheets,slides,calls,memoria --apply`, then make the two confirmations. It is refused unless every live check passed.
85014. **Clean up.** Run `carlos services delete oficina-adoption`, back up the state database, and delete the test account if he wishes.
851
852## Every production write, in order, with rollback
853
854| # | Write | Where | Rollback |
855|---|---|---|---|
856| 1 | `directory.initialize` | Home directory | **None** (by design). It is gated on the Home preflight and the §12 attestation. |
857| 2 | Plan submissions for initialize, A, B and C, both roles | Home `operator_plans` | An unconfirmed plan expires after 15 min and is swept. |
858| 3 | `credential.owner-seed` | Home credential | None needed: the receipt expires after 300 s. |
859| 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. |
860| 5 | `directory.provision-consumer` ×6 | Home directory | `alta-adopt disable --app <a> --apply`: a retire-apps plan, then `directory.disable-consumer`. |
861| 6 | `credential.register-consumer` ×6 (verify only, nothing inserted) | Home credential | None needed. |
862| 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. |
863| 8 | `POST …/restart/scope {"host"}` after the dry run, one per app | CARLOS, that host only | Restart again after the rollback. |
864| 9 | `directory.verify-consumer` for each app | Home directory | Expires after 600 s. |
865| 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. |
866| 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. |
867
868From row 4 onward, keep Home on an adoption-capable build: **never downgrade it, restore an older snapshot, or delete rows.**
869
870## Effort
871
87215 tasks, about 5–6 agent days in all. That includes one Astra round per task, the branch review and CI:
873
874| Tasks | Effort |
875|---|---|
876| 1–2 | ½ day |
877| 3 | ½ day |
878| 4–5 | ¾ day |
879| 6 | ¼ day |
880| 7 | ½ day |
881| 8 | ½ day |
882| 9 | ¾ day |
883| 10 | ½ day |
884| 11 | ½–¾ day |
885| 12 | ½ day |
886| 13 | ½ day |
887| 14–15 | ¾ day |
888
889The 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.
890
891It is gated on 522 Plan 1 (the doors and `restart/scope`) being released to the production console. Phase 5 also needs oficina-connect live.
892
893## Open questions
894
895All of Q1–Q5 are answered (see "Paul's rulings" above). Two defaults remain, which Paul may override:
896
897- **Q6:** calendar goes first as a canary, and Plan C is gated on the live checks.
898- **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.
899
900**Dependency:** 522 Plan 1 must be released before Task 15's step 4. Task 7's step 0 checks `record_seq` against that release.
901
902Nothing blocks implementation.
903