oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1# Hosted runners, slice 1a: adapter and controller core (plan, 2026-11-19, revision 4)
2
3**Status:** Reviewed by Astra (3 rounds), approved after round-3 fixes 2026-11-19; awaiting Paul's go to build.
4
5> **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. Steps marked **HUMAN** are not agent work: stop and ask Paul.
6
7**Goal:** The provider-neutral isolated job runner and the controller core, tested in depth and checked once against real VMs in the dev account. Nothing user-facing; off unless flagged.
8
9**Architecture:** `isolatedjob.Runner` (spec §2) has an in-memory fake, a shared contract suite and an AWS adapter. `equipo-hosted-controller` owns the job table, controller time, launch intents, stop proof, pause generations, resume epochs and the reaper, behind a signed HTTPS API that the instance reaches through a flag-gated client. Egress, credentials, the image and certification are slice 1b (outline at the end).
10
11**Tech stack:** Go (floor 1.26.0, gate `GOTOOLCHAIN=go1.26.11`, `CGO_ENABLED=0`), modernc SQLite through `database/sql`, `crypto/ed25519`, aws-sdk-go-v2 only in the AWS adapter.
12
13**Spec:** `docs/superpowers/specs/2026-11-18-hosted-runners-microvms.md` (approved 2026-11-19). §2, §3, §10 and §14 drive this plan; read them with it.
14
15**Baseline:** `design-hosted-runners` at `bb8e73b6`. Tasks 1 to 17, in order; each builds and tests only with earlier tasks' code. Revision 3 narrowed the plan to slice 1a after Astra round 2; revision 4 applies Astra's six round-3 fixes.
16
17## Global constraints
18
19- AWS SDK types appear only under `internal/isolatedjob/awsjob/` and in the composition commands listed in Task 7's guard. Core packages stay provider-neutral.
20- Launch request shape, sizes, region and the 28,800 s limit: spec §3 and §2, enforced by Task 7.
21- Controller deadlines, grace periods and timeouts use controller time (Task 9), never the wall clock.
22- A provider state the adapter does not recognise is `unknown`: neither live nor terminal, never stop proof.
23- Reaper rules (60 s pass, intents replayed first, orphans stopped after 10 min once ownership is rechecked): spec §10. An incomplete `List` skips orphan processing only; deadlines for recorded jobs are enforced regardless (Task 13).
24- Elapsed time across a controller restart is untrusted unless the provider establishes it (Tasks 9, 11, 13).
25- Pause barrier and resume epoch rules: spec §3. Resume prepares its new epoch durably before calling the provider (Task 12).
26- The controller refuses launches unless `EQUIPO_HOSTED_ENABLED=1`; get, stop and reaping work regardless. The instance client refuses construction unless `EQUIPO_HOSTED_RUNNERS=1`, and nothing in the instance calls it in this slice.
27- Slice 1a holds no egress stack, so a launched VM has no route anywhere and cannot enrol. Launches admit only image digests in the controller's configured allowlist; slice 1b replaces that with certificates.
28- AWS work is in the dev account `640012953448` (profile `kass`) only, with Paul's GO for every change (Task 17). Nothing touches `149757027610` (`equipo-hosted`).
29- Tests first. Each guard gets a mutation check: break it, watch the named test fail, restore (spec §17). Record commands and results in `docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md`.
30- Local runs are targeted (`go test ./internal/<pkg> -run 'TestX' -count=1`); CI runs everything. No sudo; scratch under `$TMPDIR`; test servers on `127.0.0.1`; default Go caches; 10 s and 5,000-line budgets per package. Live AWS tests use build tag `hostedlive`.
31- Commit subjects under 80 characters. Never merge, push the default branch or deploy without Paul's GO.
32
33## Review focus
34
351. A VM ends while the controller is down: `TestRestartFindsVMGone`, `TestUnknownStateIsNeverProof` (Task 11).
362. The wall clock goes backwards during a run or across a restart: `TestRollbackThenElapsedTime`, `TestRestartDowntimeExceedsWallDelta` (Tasks 9, 11), `TestReaperUnderRollback` (Task 13).
373. A crash or lost reply during resume: `TestResumeCrashBeforeProvider`, `TestResumeCrashAfterProvider`, `TestResumeLostReply` (Task 12).
384. Two retries of one launch race: `TestConcurrentLaunchSameAttempt` (Task 10).
395. A plausible VM found by `List` that a pending intent will claim: `TestReapReplaysIntentFirst`, `TestReapRechecksOwnership` (Task 13).
40
41---
42
43## H2: rulings before Task 17 (HUMAN, Paul)
44
45- [ ] Answer or accept the open questions at the end.
46- [ ] Decide who creates the throwaway dev network for Task 17 and whether agents may run its live steps.
47
48## Phase A: containment suite fixes (spec §7)
49
50### Task 1: Retry `poll` on `EINTR`, on Linux and Darwin
51
52**Files:** Create `internal/runner/containment/poll_unix.go` (`//go:build linux || darwin`), `poll_unix_test.go`. Modify `linux_test.go` (`exited`, `alive`, the stop check near line 489) and `recovery.go:78-79` (no build constraint; builds for the Mac runner).
53
54**Interfaces:** `pollRetry(fds []unix.PollFd, timeout time.Duration, poll func([]unix.PollFd, int) (int, error)) (int, error)` retries `EINTR` within the original timeout; `pollFD(fds, timeout)` wraps `unix.Poll`.
55
56- [ ] **Red:** `TestPollRetriesEINTR` (two `EINTR`, then `(1, nil)`: three calls). `TestPollRetryKeepsDeadline` (endless `EINTR` at 30 ms, 100 ms timeout: returns `n == 0` within 200 ms).
57- [ ] **Implement**; today an `EINTR` in `recovery.go` reports `errIdentity`.
58- [ ] **Green:** `go test ./internal/runner/containment -run 'TestPollRetr' -count=1`; `make build vet` (includes darwin vet of `./internal/runner/...`).
59- [ ] **Mutation:** return on the first `EINTR`; `TestPollRetriesEINTR` fails.
60- [ ] **Commit:** `containment: retry poll on EINTR on Linux and Darwin`.
61
62### Task 2: Source-reading tests run from the source tree only
63
64**Files:** Modify `internal/runner/containment/helper_version_test.go`, `bubblewrap_pin_test.go`; `scripts/ci-test.py` only where a lane names either test.
65
66**Interfaces:** the `TestSource` prefix; a compiled test binary run outside the tree uses `-test.skip '^TestSource'`.
67
68- [ ] **Red:** rename `TestNamespaceVersionTracksImplementation` to `TestSourceNamespaceVersionTracksImplementation`; move the `ci-box.json` comparison out of `TestBubblewrapPins` into `TestSourceBubblewrapPinsMatchCIBox`; add `TestSourceTestsAreNamed` (parses the package's test files; fails if a test outside the prefix opens a relative path literal).
69- [ ] **Green:** `go test ./internal/runner/containment -run 'TestSource|TestBubblewrapPins' -count=1`; `python3 scripts/ci-test.py check`; a `go test -c` binary in `$TMPDIR` passes `-test.run TestBubblewrapPins -test.skip '^TestSource'` (then remove it).
70- [ ] **Mutation:** put the `ci-box.json` read back in `TestBubblewrapPins`; `TestSourceTestsAreNamed` fails.
71- [ ] **Commit:** `containment: name the source-reading tests TestSource`.
72
73### Task 3: Skip the delegated-cgroup test without a user session
74
75**Files:** Modify `internal/runner/containment/linux_test.go`, `Makefile` (`runner-namespace-test` sets `EQUIPO_REQUIRE_USER_SESSION=1`).
76
77**Interfaces:** `cgroupSkip(base string, stat func(string) error, require bool) (skip bool, reason string, fail bool)`.
78
79- [ ] **Red:** `TestCgroupSessionRule`: no session gives skip with reason `no systemd user session; production containment does not use cgroups`; with `require` it fails instead; a session gives neither.
80- [ ] **Green:** `go test ./internal/runner/containment -run TestCgroupSessionRule -count=1`; on docs-t1 `TestNamespaceCgroupMoveKeepsMembership` still passes.
81- [ ] **Mutation:** ignore `require`; the test fails.
82- [ ] **Commit:** `containment: skip the cgroup test without a user session`.
83
84## Phase B: the isolated job runner adapter (spec §2)
85
86### Task 4: Record the MicroVM API facts first
87
88**Files:** Create `internal/isolatedjob/awsjob/doc.go` (package comment only).
89
90- [ ] From AWS documentation and the SDK module list, record: whether aws-sdk-go-v2 has a MicroVM package; operation names; where `additionalOsCapabilities`, the connector and maximum duration go; the client-token idempotency window and the mismatch error; the full state vocabulary; whether `Get` returns a start time and whether responses carry a server `Date`; whether `Resume` on a running VM succeeds; the hook transport and how the VM learns its ID (for slice 1b); the run-payload limit.
91- [ ] A fact that contradicts this plan (no client token, no start time, no idempotent resume) stops the work; ask Paul.
92- [ ] **Commit:** `awsjob: record the MicroVM API facts the adapter relies on`.
93
94### Task 5: Types, validation and the two-part clock
95
96**Files:** Create `internal/isolatedjob/{isolatedjob.go,validate.go,clock.go,isolatedjob_test.go}`.
97
98**Interfaces:** spec §2's `Runner`, `LaunchSpec`, `Job`, `Limits`, plus:
99
100```go
101type Ref string
102type ImageDigest string // "sha256:" + 64 lower-case hex
103type Size string // SizeSmall "small", SizeLarge "large" (spec §2)
104type State string // starting running suspending suspended stopping stopped failed unknown
105func (State) Live() bool; func (State) Terminal() bool // unknown is neither
106// Job gains: ProviderAge time.Duration; AgeKnown bool (provider server time minus provider start time, Task 7)
107const HardMaxLifetime = 28800 * time.Second
108var ErrNotFound, ErrInvalid, ErrConflict, ErrThrottled, ErrIncomplete, ErrBootstrapTooLarge error
109func (s LaunchSpec) Validate(l Limits) error
110type Clock interface{ Wall() time.Time; Mono() time.Duration } // Mono never decreases
111type NetworkAuditor interface{ AuditNetwork(ctx context.Context) (NetworkAudit, error) }
112type NetworkAudit struct{ ResolverDisabled, IngressClosed, RouteOutAbsent bool; EgressOnly []netip.AddrPort }
113func (NetworkAudit) OK(want []netip.AddrPort) error
114```
115
116- [ ] **Red:** `TestLaunchSpecValidate` (table: bad AttemptID, image, size; lifetime zero, over the limit, 28,801 s; bootstrap empty or one byte over; a passing row at each limit). `TestStateSets`. `TestNetworkAuditOK`.
117- [ ] **Green:** `go test ./internal/isolatedjob -count=1`.
118- [ ] **Mutations:** make `unknown` terminal (`TestStateSets` fails); `>=` on the lifetime limit (at-limit row fails).
119- [ ] **Commit:** `isolatedjob: runner interface, validation and two-part clock`.
120
121### Task 6: In-memory fake and the contract suite
122
123**Files:** Create `internal/isolatedjob/{fake.go,fake_test.go}`, `internal/isolatedjob/isolatedjobtest/{contract.go,clock.go}`.
124
125**Interfaces:**
126
127```go
128func NewFake(c Clock, l Limits) *Fake // Runner and NetworkAuditor; limits as the spike found (spec §15)
129func (*Fake) Inject(op Op, f Fault) // FaultThrottle, FaultLostReply (apply, then error), FaultIncompleteList, FaultUnknownState, FaultAgeUnknown
130func (*Fake) Tick(); func (*Fake) SetBackstop(on bool); func (*Fake) Plant(s LaunchSpec) Ref
131func (*Fake) LiveByAttempt() map[string]int; func (*Fake) StopsIssued() []Ref
132// isolatedjobtest:
133type FakeClock struct{ /* SetWall, AdvanceMono */ }
134type Harness struct{ Runner isolatedjob.Runner; Image isolatedjob.ImageDigest; Settle func(context.Context, isolatedjob.Ref, func(isolatedjob.State) bool) (isolatedjob.Job, error) }
135func Contract(t *testing.T, h Harness)
136```
137
138- [ ] **Red:** `Contract` subtests: `LaunchIdempotentOnAttempt`, `ChangedSpecConflicts`, `StopTwice`, `StopUnknownRef`, `GetAfterStop` (terminal or `ErrNotFound`, never `unknown`), `SuspendResumeRoundTrip`, `ResumeRunningIsNoop`, `OversizeBootstrapRefusedBeforeProvider`, `LimitsAreSane`. `TestFakeContract`. `TestFakeFaults` (one row per fault; `Tick` counts suspended time).
139- [ ] **Green:** `go test ./internal/isolatedjob/... -count=1`.
140- [ ] **Mutations:** key idempotency on Ref (`LaunchIdempotentOnAttempt` fails); exclude suspended time from `Tick` (`TestFakeFaults` fails).
141- [ ] **Commit:** `isolatedjob: in-memory fake and adapter contract suite`.
142
143### Task 7: AWS adapter and the provider guard
144
145**Files:** Create `internal/isolatedjob/awsjob/{runner.go,network.go,errors.go,publish.go,runner_test.go,network_test.go,live_test.go}`, `internal/isolatedjob/providerguard_test.go`, `internal/isolatedjob/guardfixture/doc.go` (an empty, dependency-free leaf package that exists only as the guard's mutation target). Modify `go.mod`, `go.sum`.
146
147**Interfaces:** `New(cfg Config, api API) (*Runner, error)` with `Config{Region, ConnectorID, VPCID, VMSubnetID, VMSecurityGroupID string; Images map[isolatedjob.ImageDigest]string; Egress []netip.AddrPort}`; `API` is a narrow interface in SDK types (or SigV4 calls, per Task 4); `SNSPublisher{TopicARN string}` with `Publish(ctx context.Context, kind, detail string) error`. It knows nothing of `hostedctl`; Task 15's command wraps it as the controller's `Alerter`.
148
149- [ ] **Red:** `TestRunRequestShape` (every spec §3 field: `NO_INGRESS`, connector-only egress, no role, no idle policy, maximum duration, x86_64, `additionalOsCapabilities: ["ALL"]`, memory by size, client token = AttemptID, payload byte for byte, image version from the map; an unmapped digest gives `ErrInvalid`). `TestStateMapping` (an unfamiliar state gives `unknown`, raw value in `Reason`). `TestProviderAge` (age from the response's server time minus the VM's start time; either missing gives `AgeKnown false`). `TestErrorMapping`. `TestListAllPages` (a page-two error gives `ErrIncomplete`, no jobs). `TestAuditNetwork`. `TestProviderTypesStayInAdapter`: over `go list -deps ./...`, only `internal/isolatedjob/awsjob/...` and the composition points `cmd/equipo-hosted-controller` (slice 1b adds `cmd/equipo-vm-init` and `cmd/equipo-hosted-image`) may depend on `github.com/aws/` or `awsjob`; the allowed list itself may contain only `cmd/` paths. Its failure message names each offending package.
150- [ ] **Green:** `go test ./internal/isolatedjob/... -count=1`; `make build vet govulncheck`.
151- [ ] **Mutations:** set a role, an idle policy, or drop the capabilities field (`TestRunRequestShape`); map an unfamiliar state to `failed` (`TestStateMapping`); take age from the local clock (`TestProviderAge`); return partial pages (`TestListAllPages`). Guard: add `import _ "github.com/aws/aws-sdk-go-v2/aws"` to `guardfixture`; `go build ./internal/isolatedjob/guardfixture` succeeds, and `TestProviderTypesStayInAdapter` then fails with its assertion naming `guardfixture` (a compile error does not count). Separately, add `internal/isolatedjob/guardfixture` to the allowed list; the `cmd/`-only assertion fails.
152- [ ] **Commit:** `isolatedjob: AWS MicroVM adapter and provider guard`.
153
154## Phase C: the controller (spec §2, §3, §10)
155
156### Task 8: Signed requests and wire types (`hostedwire`)
157
158**Files:** Create `internal/hostedwire/{sign.go,verify.go,api.go,sign_test.go}`.
159
160**Interfaces:**
161
162```go
163type KeyID string; type Role string // RoleInstance, RoleOperator
164func SignRequest(r *http.Request, body []byte, id KeyID, key ed25519.PrivateKey, now time.Time, nonce string) error
165type NonceStore interface{ Remember(ctx context.Context, id KeyID, nonce string, until time.Time) (bool, error) }
166type Verifier struct{ Keys map[KeyID]VerifyKey; Nonces NonceStore; Now func() time.Time } // VerifyKey{Public; Role}
167func (*Verifier) Verify(r *http.Request, body []byte) (KeyID, VerifyKey, error)
168func SignResponse(h http.Header, status int, requestNonce string, body []byte, key ed25519.PrivateKey)
169func VerifyResponse(resp *http.Response, body []byte, requestNonce string, pub ed25519.PublicKey) error
170const MaxBody = 1 << 20
171type Bootstrap struct{ Version int; LaunchID string; InstanceCode string } // slice 1b adds ProxyCode
172// api.go: strict-JSON request and response types for every Task 15 route
173```
174
175Signed message: `"equipo-hosted-request-v1\n" + method + "\n" + escaped path and raw query + "\n" + timestamp + "\n" + nonce + "\n" + hex(sha256(body))`; responses: `"equipo-hosted-response-v1\n" + status + "\n" + request nonce + "\n" + hex(sha256(body))`. Skew 60 s; nonces kept 10 min.
176
177- [ ] **Red:** `TestSignedRequestRoundTrip`, `TestSignatureCoversEveryField`, `TestSkewRefused`, `TestNonceReplayRefused`, `TestNonceStoreErrorDenies`, `TestResponseBoundToRequestNonce`, `TestOversizeBodyRefused`.
178- [ ] **Green:** `go test ./internal/hostedwire -count=1`.
179- [ ] **Mutations:** drop the body hash; skip `Remember`; treat a store error as fresh. Each fails its test.
180- [ ] **Commit:** `hostedwire: signed requests and responses for the controller`.
181
182### Task 9: Store, controller time and the controller skeleton
183
184**Files:** Create `internal/hostedctl/{store.go,clock.go,controller.go,schema/0001_jobs.sql,store_test.go,clock_test.go}`.
185
186**Interfaces:**
187
188```go
189type T time.Duration // controller time
190type CtlClock struct{ /* restored base + Clock.Mono() */ }
191func (*CtlClock) Now() T
192func Open(ctx context.Context, path string, c isolatedjob.Clock) (*Store, error)
193func (*Store) Tx(ctx context.Context, fn func(*sql.Tx) error) error
194func (*Store) Clock() *CtlClock
195func (*Store) Restarted() bool // true after Open finds prior state: elapsed time across the restart is untrusted
196func (*Store) Remember(...) // hostedwire.NonceStore
197func appendAudit(tx *sql.Tx, a Audit) error // Audit{Actor hostedwire.KeyID; Account, Task, Attempt, Action, Reason string; At T}
198type Alert struct{ Kind, Detail string; At T }
199type Alerter interface{ Alert(ctx context.Context, a Alert) error }
200type Config struct{ Enabled bool; Images map[isolatedjob.ImageDigest]bool } // later tasks add fields
201type Deps struct{ Store *Store; Runner isolatedjob.Runner; Auditor isolatedjob.NetworkAuditor; Alerter Alerter }
202func New(cfg Config, d Deps) (*Controller, error) // refuses a nil dependency
203```
204
205Controller time:
206- While running, `T` advances only with `Mono()`. Every reaper pass checkpoints `(T, wall)`.
207- On `Open`, `T0 = T + max(0, wall now − checkpoint wall)`, so `T` never decreases. A wall clock behind the checkpoint also raises a `clock_rollback` alert. The wall delta is never trusted as the real downtime, because the clock can move backwards during downtime and still be ahead of the checkpoint. After any restart, `Restarted()` is true. Task 11 then re-bases existing jobs only from trusted provider age, and stops jobs without it. Task 13 treats the grace of existing orphans as expired.
208- Provider-reported age (Task 7) is trusted only when one provider response carries both the provider's server time and the VM's start time. It never uses this host's clock.
209
210Tables: `jobs` (attempt_id primary key; launch_id unique; vm_ref unique nullable; task_id, account_id, actor_key, purpose, replaces_attempt; spec_json and spec_sha256, immutable by trigger; state; launched_t, deadline_t, drain_t, stop_t; epoch; pause_generation, pause_started_t, pause_quiescent, pause_cancelled; stop_requested_t, stop_reason, stop_proof_json; revision), `resume_ops` (primary key (attempt_id, operation_id); status `pending`, `done` or `failed`; prepared_epoch, result_epoch, prepared_t, completed_t; kept for the attempt's lifetime), `unmatched_vms` (vm_ref, first_seen_t), `nonces`, `audit`, `clock`.
211
212- [ ] **Red:** `TestStoreMigratesTwice`, `TestStoreRefusesNewerSchema`, `TestAuditRollsBackWithTx`, `TestSpecImmutable`. `TestRollbackThenElapsedTime`: the wall clock goes back 1 h mid-run, Mono advances 10 min, and `Now` advances exactly 10 min. `TestRestartMarksElapsedUntrusted`: a restart with the wall clock 30 min ahead gives `T` +30 min and `Restarted()` true. `TestRestartWithRollback`: the wall clock behind the checkpoint gives `T` unchanged, `Restarted()` true and one alert.
213- [ ] **Green:** `go test ./internal/hostedctl -run 'TestStore|TestAudit|TestSpecImmutable|TestRollback|TestRestart' -count=1`.
214- [ ] **Mutations:** derive `T` from the wall clock (`TestRollbackThenElapsedTime`); leave `Restarted()` false when the wall clock moved forward (`TestRestartMarksElapsedUntrusted`); drop the trigger (`TestSpecImmutable`).
215- [ ] **Commit:** `hostedctl: store, controller time and controller skeleton`.
216
217### Task 10: Launch with intents and replay
218
219**Files:** Create `internal/hostedctl/{launch.go,launch_test.go}`.
220
221**Interfaces:**
222
223```go
224type LaunchRequest struct{ AttemptID, TaskID, Account, Replaces string; Image isolatedjob.ImageDigest; Size isolatedjob.Size; MaxLifetime time.Duration; InstanceCode string }
225type JobView struct{ AttemptID, LaunchID, State string; VMRef isolatedjob.Ref; Epoch int64; DeadlineIn, DrainIn, StopIn time.Duration }
226func (*Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, q LaunchRequest) (JobView, error)
227func (*Controller) Replay(ctx context.Context) error
228func Deadlines(launched T, max time.Duration) (deadline, drain, stop T) // drain = deadline−45m, stop = deadline−10m, clamped
229var ErrDisabled, ErrImageNotAllowed, ErrNetworkAudit, ErrReplacementLive error
230```
231
232`Launch` order: refuse when the flag is off; require `RoleInstance`; require the image in `Config.Images`; require a passing audit at most 5 min old; require stop proof for `Replaces`; transaction 1 saves the intent (exact spec, deadlines) or returns the matching one (a different request hash gives `ErrConflict`); `Runner.Launch`; transaction 2 saves the Ref and `starting`. `ErrThrottled` leaves state `waiting` for `Replay`.
233
234`Replay` re-checks the gates before every call that could create a VM (an intent with no Ref): the flag on, the image still allowed, a passing audit at most 5 min old, no stop or cancellation requested, and `stop_t` (from the intent's time) not passed. If a gate fails, `Replay` makes no provider call and keeps the intent for reconciliation. A transient failure (flag, image, audit) leaves it `waiting`. Cancellation or a passed `stop_t` marks it `abandoned`, never replayed again. Any VM that an earlier lost reply created for it then shows up as an orphan and is reaped (Task 13).
235
236- [ ] **Red:** `TestLaunchSavesIntentBeforeProvider`, `TestLaunchIdempotentOnAttempt`, `TestLaunchConflictOnChangedRequest`, `TestConcurrentLaunchSameAttempt` (20 goroutines: one intent, one VM), `TestCrashBetweenLaunchAndSave` (lost reply, reopen, `Replay`: one VM, Ref saved), `TestLaunchRefusals` (table: flag off, operator role, image not allowed, stale audit, failing audit, live replaced attempt), `TestThrottleWaitsThenReplays`, `TestThrottleThenRefusal` (table: after a throttle, flag off, image removed, stale audit, failing audit, stop requested, `stop_t` passed; each gives no provider call and the intent kept, `waiting` or `abandoned` as above), `TestDeadlines` (8 h gives 7 h 15 and 7 h 50; 15 min gives 0 and 5 min).
237- [ ] **Green:** `go test ./internal/hostedctl -run 'TestLaunch|TestConcurrentLaunch|TestCrashBetween|TestThrottle|TestDeadlines' -count=1`.
238- [ ] **Mutations:** save the intent after the provider call (`TestLaunchSavesIntentBeforeProvider`); skip the image check or the Replaces check (`TestLaunchRefusals`); replay without re-checking the gates (`TestThrottleThenRefusal`).
239- [ ] **Commit:** `hostedctl: launch intents and replay`.
240
241### Task 11: Get, stop, stop proof and restart reconciliation
242
243**Files:** Create `internal/hostedctl/{stop.go,refresh.go,stop_test.go}`.
244
245**Interfaces:** `Get(ctx, by, attemptID) (JobView, error)`; `Stop(ctx, by, key, attemptID, reason string) (StopProof, error)` (the creating instance only); `StopProof{AttemptID string; VMRef isolatedjob.Ref; State isolatedjob.State; ObservedAt T}`; `Refresh(ctx) error`; `ErrStopPending`, `ErrStateUnknown`.
246
247Stop records `stop_requested_t`, then calls `Runner.Stop`, then `Runner.Get`. Proof needs a terminal state, or `ErrNotFound` after the request. `unknown` gives `ErrStateUnknown` and no proof.
248
249`Refresh` reconciles every live job with `Get`. After any restart (`Restarted()`), the elapsed time of each job that existed before the restart is untrusted:
250- With a trusted provider age, set `launched_t = min(launched_t, now − age)` and recompute `deadline_t`, `drain_t` and `stop_t` with `Deadlines`.
251- Without one, the job is stopped with the reason `elapsed_unknown`.
252
253- [ ] **Red:** `TestStopRecordsRequestBeforeProvider`, `TestStopProofNeedsTerminalState`, `TestUnknownStateIsNeverProof` (no proof; a replacement is refused), `TestLostStopReplyRetries`, `TestStopOfGoneVMSucceeds`, `TestRestartFindsVMGone`, `TestRestartUsesProviderAge` (all three deadlines recomputed; earlier, never later), `TestRestartDowntimeExceedsWallDelta` (2 h real downtime but the wall clock only 10 min ahead: a job with trusted age gets deadlines from that age, a job without it is stopped, and an orphan's grace is expired), `TestRestartStopsWhenElapsedUnknown`, `TestStopRoles` (another instance and an operator are refused).
254- [ ] **Green:** `go test ./internal/hostedctl -run 'TestStop|TestUnknownState|TestLostStop|TestRestart' -count=1`.
255- [ ] **Mutations:** accept `stopping` or `unknown` as proof; use `max` instead of `min` when re-basing, or skip recomputing `stop_t` (`TestRestartUsesProviderAge`); trust the wall delta for jobs without age (`TestRestartDowntimeExceedsWallDelta`); keep jobs whose elapsed time is unknown (`TestRestartStopsWhenElapsedUnknown`).
256- [ ] **Commit:** `hostedctl: stop proof, unknown states and restart reconciliation`.
257
258### Task 12: Pause generations and prepared resume epochs
259
260**Files:** Create `internal/hostedctl/{pause.go,resume.go,pause_test.go,resume_test.go}`.
261
262**Interfaces:** `Drain(ctx, by, attemptID) (generation int64, error)`; `Quiescent(ctx, by, attemptID string, generation int64) error`; `Suspend(ctx, by, attemptID string, generation int64) error`; `Reopen(ctx, by, attemptID string, generation int64) error`; `Resume(ctx, by, attemptID, operationID string) (epoch int64, error)`; `ErrGenerationCancelled`, `ErrNotQuiescent`, `ErrPastDeadline`, `ErrResumePending`; `PauseAckTimeout = 2 * time.Minute`.
263
264Suspend records `suspending` before calling the provider; `Refresh` settles it from `Get`.
265
266Resume runs in three steps:
2671. **Prepare.** One transaction inserts `resume_ops(attempt_id, operation_id)` as `pending` with `prepared_epoch = epoch + 1` and sets the job `resuming`. A call whose `(attempt_id, operation_id)` row is `done` returns that row's `result_epoch` with no provider call, however many later operations have completed. A `pending` row carries on with its prepared epoch. A new ID while another is pending gives `ErrResumePending`.
2682. **Provider.** Call `Runner.Resume`.
2693. **Commit.** Once `Get` reports `running`, one transaction sets the job's `epoch = prepared_epoch` and marks the row `done` with `result_epoch`. A terminal VM marks the row `failed`.
270
271Slice 1b issues new-epoch credentials from the prepared epoch, so the VM's resume hook can complete synchronously before the commit. If the controller crashes or the provider reply is lost, `Refresh` finishes the operation from `Get`:
272- `suspended`: call `Runner.Resume` again;
273- `running`: commit;
274- `unknown`: leave it pending and retry next pass;
275- terminal: record proof and mark the job stopped.
276
277- [ ] **Red:**
278 - `TestSuspendNeedsCurrentAck`: no acknowledgement, an older generation, the next generation and a cancelled generation are each refused.
279 - `TestLateAckIgnored` (an acknowledgement at 2 min 1 s).
280 - `TestSuspendedTimeCountsToDeadline`.
281 - `TestResumePreparesEpochBeforeProvider`: the stub sees the pending epoch in the store.
282 - `TestResumeCrashBeforeProvider`, `TestResumeCrashAfterProvider` and `TestResumeLostReply`: each ends with one provider resume (or a no-op) and the epoch raised exactly once.
283 - `TestResumeRetrySameOperation`.
284 - `TestResumeOperationsRemembered`: operation A completes, then B completes, then A is retried. There is no provider call, and A's original epoch is returned.
285 - `TestResumeOtherOperationWhilePending`.
286 - `TestResumePastDeadlineRefused`.
287- [ ] **Green:** `go test ./internal/hostedctl -run 'TestSuspend|TestLateAck|TestResume' -count=1`.
288- [ ] **Mutations:**
289 - Compare generations with `>=`: the next-generation row fails.
290 - Call the provider before preparing: `TestResumePreparesEpochBeforeProvider` fails.
291 - Raise the epoch on each call: `TestResumeRetrySameOperation` fails.
292 - Commit without `Get` showing `running`: `TestResumeLostReply` fails.
293 - Look up only the latest operation: `TestResumeOperationsRemembered` fails.
294- [ ] **Commit:** `hostedctl: pause generations and prepared resume epochs`.
295
296### Task 13: Reaper and the network audit loop
297
298**Files:** Create `internal/hostedctl/{reaper.go,reaper_test.go}`.
299
300**Interfaces:** `Reap(ctx) (ReapReport, error)`, `ReapReport{Skipped bool; Replayed, Drained, Stopped, OrphansSeen, OrphansStopped, Unknown int}`; `Loop(ctx, every time.Duration)`; `ReapInterval = 60 * time.Second`; `OrphanGrace = 10 * time.Minute`.
301
302Each pass runs in this order:
3031. Checkpoint the clock.
3042. `Replay`, with Task 10's gates.
3053. `Refresh`.
3064. Recorded jobs, by their saved Ref, whatever `List` returns: mark jobs past `drain_t` as draining; stop jobs past `stop_t`; re-issue Stop for `unknown` and alert after three passes.
3075. Orphans, only when `List` is complete; an `ErrIncomplete` skips this step alone. Record `first_seen_t` for each. After `OrphanGrace`, replay again, re-read the table and `List` again before calling `Stop`. After a restart, orphans recorded before it treat their grace as expired; the recheck still applies.
3086. Run the audit. While it fails, refuse launches and alert once per episode.
309
310- [ ] **Red:** `TestIncompleteListSkipsOrphansOnly`, `TestDeadlineEnforcedDuringIncompleteLists` (consecutive incomplete Lists across `stop_t`; the provider Stop succeeds and the job gets proof), `TestReapReplaysIntentFirst`, `TestReapStopsOrphanAfterTenMinutes` (9 min 59 s no, 10 min yes), `TestReapRechecksOwnership`, `TestReapDrainsThenStops`, `TestReaperUnderRollback` (the wall clock goes back 2 h mid-run; the orphan is still stopped at 10 min of Mono time), `TestOrphanGraceExpiresAfterRestart`, `TestUnknownStateRetriedAndAlerted`, `TestFailingAuditBlocksLaunchAndAlertsOnce`.
311- [ ] **Green:** `go test ./internal/hostedctl -run 'TestReap|TestOrphanGrace|TestUnknownStateRetried|TestFailingAudit' -count=1`.
312- [ ] **Mutations:** reap orphans on an incomplete `List` (`TestIncompleteListSkipsOrphansOnly`); skip deadline stops on an incomplete `List` (`TestDeadlineEnforcedDuringIncompleteLists`); drop the recheck (`TestReapRechecksOwnership`); use wall time for grace (`TestReaperUnderRollback`).
313- [ ] **Commit:** `hostedctl: leaked-VM reaper and network audit loop`.
314
315### Task 14: Lifecycle simulation with invariants (spec §14)
316
317**Files:** Create `internal/hostedctl/{sim_test.go,sim_model_test.go}`.
318
319**Interfaces:** `TestLifecycleSimulation`: 200 seeds by default within the 10 s budget, `EQUIPO_SIM_SEEDS=n` for more; a failure prints its seed and step log.
320
321Each step picks one operation at random:
322- launch: fresh, replacement, or a concurrent duplicate;
323- crash and reopen at any point, including between a provider call and its follow-up transaction;
324- provider faults: lost reply on Launch, Stop or Resume; throttle; incomplete `List`; unknown state; unknown age;
325- pause and resume: drain; an acknowledgement (current, stale, next or late); suspend; resume (new or repeated operation ID);
326- plant an orphan; stop;
327- a wall-clock jump of up to 3 h either way;
328- a time advance of up to 9 h.
329
330A time advance moves Mono in steps of at most `ReapInterval` and runs the scheduled reaper pass at each step, as `Loop` would. The fake's own lifetime backstop is off.
331
332| ID | Invariant, checked after every step | Mutation that must break it |
333| --- | --- | --- |
334| I1 | At most one live VM per attempt ID | Replay with a fresh client token |
335| I2 | Every VM the fake holds is a saved Ref, matches a stored intent's attempt, or is a planted orphan | Save the intent after the provider call |
336| I3 | Orphan cleanup stops only VMs with no job or intent, and none before 10 min of controller time, except orphans recorded before a restart, whose grace may be expired early | Stop orphans on first sight; drop the recheck |
337| I4 | No recorded job's VM is live past its `stop_t` plus one reaper interval, even across consecutive incomplete Lists | Reap at `deadline_t`; use wall time; skip deadline stops on an incomplete List |
338| I5 | A provider Suspend happens only with an acknowledgement for the current, uncancelled generation | Accept `>=` generations |
339| I6 | A replacement launches only after stop proof, and proof never comes from `unknown` | Treat `unknown` as terminal |
340| I7 | Each resume operation ID raises the epoch exactly once, prepared before the provider call and committed only after `running` | Raise the epoch before preparing; commit on a lost reply |
341
342- [ ] **Red:** write the model; apply each mutation alone and see it fail within the default seeds (record the seed).
343- [ ] **Green:** `go test ./internal/hostedctl -run TestLifecycleSimulation -count=1`, then once with `EQUIPO_SIM_SEEDS=5000`.
344- [ ] **Commit:** `hostedctl: randomised lifecycle simulation with seven invariants`.
345
346### Task 15: Controller HTTP API, command and metrics
347
348**Files:** Create `internal/hostedctl/{http.go,metrics.go,http_test.go}`, `cmd/equipo-hosted-controller/{main.go,config.go,alerter.go,config_test.go,alerter_test.go}`.
349
350**Interfaces:** strict JSON, `MaxBody`, every response signed; the creating instance only for job routes.
351
352| Route | Role |
353| --- | --- |
354| `POST /v1/jobs`; `GET /v1/jobs/{attempt}`; `POST /v1/jobs/{attempt}/stop`, `/drain`, `/quiescent`, `/suspend`, `/reopen`, `/resume` | instance |
355| `GET /v1/vms` | operator |
356
357Metrics on a separate listener: jobs by state, launches and errors by kind, orphans stopped, audit status, alerts by kind. `main` is the composition point that wires `awsjob`. Its `snsAlerter` (in `cmd/equipo-hosted-controller/alerter.go`) implements `hostedctl.Alerter` by calling `awsjob.SNSPublisher.Publish(ctx, a.Kind, a.Detail)`. Config comes from the file `-config`: listen address (required, no default), TLS files, database path, signing key, verify keys with roles, image allowlist, region and network IDs; `Enabled` only from `EQUIPO_HOSTED_ENABLED=1`.
358
359- [ ] **Red:** `TestRoutesEnforceRoles` (403 and audited), `TestInstanceKeySeesOnlyItsJobs`, `TestUnknownFieldsRefused`, `TestResponsesSigned`, `TestConfigRefusesMissingListenOrKeys`, `TestConfigRefusesWildcardListen` (`0.0.0.0`, `::`, bare `:port`), `TestDisabledRefusesLaunchButServesStop`, `TestMetricsCountJobsByState`, `TestAlerterWrapsPublisher` (in the command, with a recording publisher).
360- [ ] **Green:** `go test ./internal/hostedctl ./cmd/equipo-hosted-controller -run 'TestRoutes|TestInstanceKey|TestUnknownFields|TestResponsesSigned|TestConfig|TestDisabled|TestMetrics' -count=1`; `make build vet`; the Task 7 guard still passes.
361- [ ] **Mutation:** drop the creator check; `TestInstanceKeySeesOnlyItsJobs` fails.
362- [ ] **Commit:** `hosted controller: signed HTTPS API, command and metrics`.
363
364### Task 16: Instance-side client behind its flag
365
366**Files:** Create `internal/hostedclient/{client.go,client_test.go}`.
367
368**Interfaces:** `New(cfg Config) (*Client, error)`, `Config{BaseURL string; KeyID hostedwire.KeyID; Key ed25519.PrivateKey; ControllerKey ed25519.PublicKey; HTTP *http.Client}`; refuses without `EQUIPO_HOSTED_RUNNERS=1`; one method per instance route, each verifying the response against its own request nonce.
369
370- [ ] **Red:** `TestClientAgainstController` (real handler over `httptest` TLS, fake runner: launch, get, drain, quiescent, suspend, resume, stop with proof), `TestClientRefusesUnsignedResponse`, `TestClientRefusesWithoutFlag`, `TestInstanceDoesNotCallHostedClient` (`go list -deps ./cmd/equipo`; slice 2 deletes it).
371- [ ] **Green:** `go test ./internal/hostedclient -count=1`.
372- [ ] **Mutation:** skip response verification; `TestClientRefusesUnsignedResponse` fails.
373- [ ] **Commit:** `hostedclient: signed controller client behind a flag`.
374
375### Task 17: Live check in the dev account (HUMAN-gated)
376
377- [ ] **HUMAN:** a throwaway network in `kass` (`eu-west-1`): a VPC with DNS support off, a VM subnet with no default route, a security group with no rules, one connector, tagged `purpose=equipo-hosted-dev`. Record it in the progress file. A minimal image is registered by hand and its digest is added to the allowlist.
378- [ ] **Agent, with GO:** `AWS_PROFILE=kass go test -tags hostedlive ./internal/isolatedjob/awsjob -run TestLiveContract -count=1`, then `List` to confirm teardown.
379- [ ] **Agent, with GO:** run the controller on docs-t1 bound to `127.0.0.1`, with `kass` credentials and `EQUIPO_HOSTED_ENABLED=1`. Through `hostedclient`: launch a Small VM, drain, quiescent, suspend, resume (record epoch and timings) and stop with proof. Kill the controller between the provider call and transaction 2, restart, and see one VM.
380- [ ] **HUMAN GO, then agent:** plant an orphan with the AWS CLI and watch the reaper stop it after 10 minutes.
381- [ ] **HUMAN:** tear the network down. The agent confirms by type and tag, and records the dev spend.
382- [ ] One whole-branch review (Astra or Fable, as Paul directs); Paul lands it.
383
384**Slice 1a is done when** the contract suite passes against the fake and AWS, the simulation passes 5,000 seeds, the live check is recorded with nothing left running, and everything is off unless flagged.
385
386---
387
388## Slice 1b outline (planned after 1a lands)
389
3901b gets its own plan once 1a is merged. It ends where slice 2 can start (spec §8 lists slice 2's needs).
391
392**Components:**
393- egress policy with immutable per-launch snapshots;
394- the authenticated proxy:
395 - its bootstrap listener (server TLS only, three routes) and its egress listener (mTLS);
396 - the signed launch feed;
397 - CONNECT, SNI, Host and `:authority` inspection, and origin TLS;
398 - decision logs and revocation of open tunnels;
399- the resolver: plain DNS answers nothing; DNS over TLS answers per launch;
400- per-VM keys: redeem, challenge and exchange, and lapse stops;
401- the root init with its hooks, and the foundation probe standing in for the runner;
402- the end-to-end test over real TLS;
403- the image inventory and reproducible build;
404- the hosted admission check (forged-image hello);
405- certification:
406 - the trusted matrix with positive controls;
407 - the report route with provenance;
408 - the mutation-evidence registry and replay;
409 - online collection and offline signing;
410- OpenTofu for dev, release artifacts and CI wiring, and the dev bring-up drills.
411
412**Open findings from Astra rounds 1 and 2 that 1b must close:**
413- **Certificate verification inputs:** verify the canonical certification snapshot (purpose, version), not only its digest. Bind the allowed deployment names, and define the certification launch's target host for operator keys.
414- **TLS-stage refusal outcomes:** missing or expired client certificates, and refused ClientHellos, fail at the TLS layer. A cross-host redirect gives 502. Define outcomes and controls per stage, and test real TLS failures.
415- **Mutation evidence:** a guard counts only if its named test compiled, ran (at least one test executed) and failed with its assertion. Build errors, infrastructure errors and zero-test runs are rejected.
416- **Outage recovery and VM-key persistence:** keep the trusted renewal process and VM key alive while work stops, or terminate and replace the VM. Persist an explicit recovery-window deadline of one 2-minute window, not a reset lifetime.
417- **Resume hook:** the exchange issues credentials for 1a's prepared epoch, so the hook completes before the epoch commits (Task 12). Test the synchronous hook.
418- **Ordering:** define the release provenance and the `Upstream` and `DecisionLog` contracts before the tasks that consume them.
419- **Provider guard:** add `cmd/equipo-vm-init` and `cmd/equipo-hosted-image` as composition points.
420- **Certification evidence from round 1:** the trusted matrix decides expected outcomes, never the report. Include direct IPv4 and IPv6 bypass probes, root probes run before the privilege drop, and the forged-image hello test.
421- **Q3, controller outage versus a stale feed:** bounded continuation needs Paul's approval. Astra's conditions:
422 - access ends at the earliest of credential expiry, feed expiry or known revocation;
423 - feed freshness is measured on the monotonic clock;
424 - existing tunnels are closed at expiry;
425 - 15 minutes is a maximum stale window, not guaranteed continuation;
426 - a test covers a partitioned proxy while the controller stays up.
427- **Moved to slice 4:** the checkpoint boundary-injection and task or hash mismatch tests (§17), together with round 2's substitution finding (render only verified checkpoint contents). Slice 4 is where checkpoints are built.
428
429**1b decisions to carry:** OpenTofu lives in `infra/hosted/` here (Astra agrees); Paul or a named operator holds the certification key offline; collection and signing are separate; the image includes the pinned codex and every executable the suite runs; gateway and mirror use an explicit `none`, which needs Paul's approval, and setting either forces recertification; the upstream resolver for the proxies is pinned by address and TLS name, with no fallback; the controller's production durability is SQLite plus continuous replication to S3 before slice 2 production.
430
431## Before slice 2 production (HUMAN, deferred)
432
433- [ ] A profile `equipo-hosted` for `149757027610` via `titogo`, with MFA; the state bucket; the applied MicroVM quota in `eu-west-1` (spec §10); CloudTrail data events (spec §11); the production OpenTofu environment, deployment and certification there.
434
435## Open questions
436
4371. **MicroVM SDK.** *Recommendation:* the SDK package if one exists, otherwise SigV4 calls inside `awsjob`. Task 4 settles the facts first, as Astra asked.
4382. **Restart with unknown elapsed time.** When the wall clock went back across a restart and AWS gives no trusted age, Task 11 stops the job. *Recommendation:* accept this. It is rare, and the alternative is guessing a lifetime. Paul should know it can stop work after a clock fault.
4393. **Where the 1a controller runs for the live check.** *Recommendation:* on docs-t1, bound to `127.0.0.1`, using `kass` credentials, for Task 17 only. The controller host in the hosted account is a 1b decision.
440