# Hosted runners, slice 1a: adapter and controller core (plan, 2026-11-19, revision 4)

**Status:** Reviewed by Astra (3 rounds), approved after round-3 fixes 2026-11-19; awaiting Paul's go to build.

> **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.

**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.

**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).

**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.

**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.

**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.

## Global constraints

- 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.
- Launch request shape, sizes, region and the 28,800 s limit: spec §3 and §2, enforced by Task 7.
- Controller deadlines, grace periods and timeouts use controller time (Task 9), never the wall clock.
- A provider state the adapter does not recognise is `unknown`: neither live nor terminal, never stop proof.
- 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).
- Elapsed time across a controller restart is untrusted unless the provider establishes it (Tasks 9, 11, 13).
- Pause barrier and resume epoch rules: spec §3. Resume prepares its new epoch durably before calling the provider (Task 12).
- 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.
- 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.
- 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`).
- 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`.
- 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`.
- Commit subjects under 80 characters. Never merge, push the default branch or deploy without Paul's GO.

## Review focus

1. A VM ends while the controller is down: `TestRestartFindsVMGone`, `TestUnknownStateIsNeverProof` (Task 11).
2. The wall clock goes backwards during a run or across a restart: `TestRollbackThenElapsedTime`, `TestRestartDowntimeExceedsWallDelta` (Tasks 9, 11), `TestReaperUnderRollback` (Task 13).
3. A crash or lost reply during resume: `TestResumeCrashBeforeProvider`, `TestResumeCrashAfterProvider`, `TestResumeLostReply` (Task 12).
4. Two retries of one launch race: `TestConcurrentLaunchSameAttempt` (Task 10).
5. A plausible VM found by `List` that a pending intent will claim: `TestReapReplaysIntentFirst`, `TestReapRechecksOwnership` (Task 13).

---

## H2: rulings before Task 17 (HUMAN, Paul)

- [ ] Answer or accept the open questions at the end.
- [ ] Decide who creates the throwaway dev network for Task 17 and whether agents may run its live steps.

## Phase A: containment suite fixes (spec §7)

### Task 1: Retry `poll` on `EINTR`, on Linux and Darwin

**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).

**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`.

- [ ] **Red:** `TestPollRetriesEINTR` (two `EINTR`, then `(1, nil)`: three calls). `TestPollRetryKeepsDeadline` (endless `EINTR` at 30 ms, 100 ms timeout: returns `n == 0` within 200 ms).
- [ ] **Implement**; today an `EINTR` in `recovery.go` reports `errIdentity`.
- [ ] **Green:** `go test ./internal/runner/containment -run 'TestPollRetr' -count=1`; `make build vet` (includes darwin vet of `./internal/runner/...`).
- [ ] **Mutation:** return on the first `EINTR`; `TestPollRetriesEINTR` fails.
- [ ] **Commit:** `containment: retry poll on EINTR on Linux and Darwin`.

### Task 2: Source-reading tests run from the source tree only

**Files:** Modify `internal/runner/containment/helper_version_test.go`, `bubblewrap_pin_test.go`; `scripts/ci-test.py` only where a lane names either test.

**Interfaces:** the `TestSource` prefix; a compiled test binary run outside the tree uses `-test.skip '^TestSource'`.

- [ ] **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).
- [ ] **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).
- [ ] **Mutation:** put the `ci-box.json` read back in `TestBubblewrapPins`; `TestSourceTestsAreNamed` fails.
- [ ] **Commit:** `containment: name the source-reading tests TestSource`.

### Task 3: Skip the delegated-cgroup test without a user session

**Files:** Modify `internal/runner/containment/linux_test.go`, `Makefile` (`runner-namespace-test` sets `EQUIPO_REQUIRE_USER_SESSION=1`).

**Interfaces:** `cgroupSkip(base string, stat func(string) error, require bool) (skip bool, reason string, fail bool)`.

- [ ] **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.
- [ ] **Green:** `go test ./internal/runner/containment -run TestCgroupSessionRule -count=1`; on docs-t1 `TestNamespaceCgroupMoveKeepsMembership` still passes.
- [ ] **Mutation:** ignore `require`; the test fails.
- [ ] **Commit:** `containment: skip the cgroup test without a user session`.

## Phase B: the isolated job runner adapter (spec §2)

### Task 4: Record the MicroVM API facts first

**Files:** Create `internal/isolatedjob/awsjob/doc.go` (package comment only).

- [ ] 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.
- [ ] A fact that contradicts this plan (no client token, no start time, no idempotent resume) stops the work; ask Paul.
- [ ] **Commit:** `awsjob: record the MicroVM API facts the adapter relies on`.

### Task 5: Types, validation and the two-part clock

**Files:** Create `internal/isolatedjob/{isolatedjob.go,validate.go,clock.go,isolatedjob_test.go}`.

**Interfaces:** spec §2's `Runner`, `LaunchSpec`, `Job`, `Limits`, plus:

```go
type Ref string
type ImageDigest string // "sha256:" + 64 lower-case hex
type Size string        // SizeSmall "small", SizeLarge "large" (spec §2)
type State string       // starting running suspending suspended stopping stopped failed unknown
func (State) Live() bool; func (State) Terminal() bool // unknown is neither
// Job gains: ProviderAge time.Duration; AgeKnown bool (provider server time minus provider start time, Task 7)
const HardMaxLifetime = 28800 * time.Second
var ErrNotFound, ErrInvalid, ErrConflict, ErrThrottled, ErrIncomplete, ErrBootstrapTooLarge error
func (s LaunchSpec) Validate(l Limits) error
type Clock interface{ Wall() time.Time; Mono() time.Duration } // Mono never decreases
type NetworkAuditor interface{ AuditNetwork(ctx context.Context) (NetworkAudit, error) }
type NetworkAudit struct{ ResolverDisabled, IngressClosed, RouteOutAbsent bool; EgressOnly []netip.AddrPort }
func (NetworkAudit) OK(want []netip.AddrPort) error
```

- [ ] **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`.
- [ ] **Green:** `go test ./internal/isolatedjob -count=1`.
- [ ] **Mutations:** make `unknown` terminal (`TestStateSets` fails); `>=` on the lifetime limit (at-limit row fails).
- [ ] **Commit:** `isolatedjob: runner interface, validation and two-part clock`.

### Task 6: In-memory fake and the contract suite

**Files:** Create `internal/isolatedjob/{fake.go,fake_test.go}`, `internal/isolatedjob/isolatedjobtest/{contract.go,clock.go}`.

**Interfaces:**

```go
func NewFake(c Clock, l Limits) *Fake // Runner and NetworkAuditor; limits as the spike found (spec §15)
func (*Fake) Inject(op Op, f Fault)   // FaultThrottle, FaultLostReply (apply, then error), FaultIncompleteList, FaultUnknownState, FaultAgeUnknown
func (*Fake) Tick(); func (*Fake) SetBackstop(on bool); func (*Fake) Plant(s LaunchSpec) Ref
func (*Fake) LiveByAttempt() map[string]int; func (*Fake) StopsIssued() []Ref
// isolatedjobtest:
type FakeClock struct{ /* SetWall, AdvanceMono */ }
type Harness struct{ Runner isolatedjob.Runner; Image isolatedjob.ImageDigest; Settle func(context.Context, isolatedjob.Ref, func(isolatedjob.State) bool) (isolatedjob.Job, error) }
func Contract(t *testing.T, h Harness)
```

- [ ] **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).
- [ ] **Green:** `go test ./internal/isolatedjob/... -count=1`.
- [ ] **Mutations:** key idempotency on Ref (`LaunchIdempotentOnAttempt` fails); exclude suspended time from `Tick` (`TestFakeFaults` fails).
- [ ] **Commit:** `isolatedjob: in-memory fake and adapter contract suite`.

### Task 7: AWS adapter and the provider guard

**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`.

**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`.

- [ ] **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.
- [ ] **Green:** `go test ./internal/isolatedjob/... -count=1`; `make build vet govulncheck`.
- [ ] **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.
- [ ] **Commit:** `isolatedjob: AWS MicroVM adapter and provider guard`.

## Phase C: the controller (spec §2, §3, §10)

### Task 8: Signed requests and wire types (`hostedwire`)

**Files:** Create `internal/hostedwire/{sign.go,verify.go,api.go,sign_test.go}`.

**Interfaces:**

```go
type KeyID string; type Role string // RoleInstance, RoleOperator
func SignRequest(r *http.Request, body []byte, id KeyID, key ed25519.PrivateKey, now time.Time, nonce string) error
type NonceStore interface{ Remember(ctx context.Context, id KeyID, nonce string, until time.Time) (bool, error) }
type Verifier struct{ Keys map[KeyID]VerifyKey; Nonces NonceStore; Now func() time.Time } // VerifyKey{Public; Role}
func (*Verifier) Verify(r *http.Request, body []byte) (KeyID, VerifyKey, error)
func SignResponse(h http.Header, status int, requestNonce string, body []byte, key ed25519.PrivateKey)
func VerifyResponse(resp *http.Response, body []byte, requestNonce string, pub ed25519.PublicKey) error
const MaxBody = 1 << 20
type Bootstrap struct{ Version int; LaunchID string; InstanceCode string } // slice 1b adds ProxyCode
// api.go: strict-JSON request and response types for every Task 15 route
```

Signed 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.

- [ ] **Red:** `TestSignedRequestRoundTrip`, `TestSignatureCoversEveryField`, `TestSkewRefused`, `TestNonceReplayRefused`, `TestNonceStoreErrorDenies`, `TestResponseBoundToRequestNonce`, `TestOversizeBodyRefused`.
- [ ] **Green:** `go test ./internal/hostedwire -count=1`.
- [ ] **Mutations:** drop the body hash; skip `Remember`; treat a store error as fresh. Each fails its test.
- [ ] **Commit:** `hostedwire: signed requests and responses for the controller`.

### Task 9: Store, controller time and the controller skeleton

**Files:** Create `internal/hostedctl/{store.go,clock.go,controller.go,schema/0001_jobs.sql,store_test.go,clock_test.go}`.

**Interfaces:**

```go
type T time.Duration // controller time
type CtlClock struct{ /* restored base + Clock.Mono() */ }
func (*CtlClock) Now() T
func Open(ctx context.Context, path string, c isolatedjob.Clock) (*Store, error)
func (*Store) Tx(ctx context.Context, fn func(*sql.Tx) error) error
func (*Store) Clock() *CtlClock
func (*Store) Restarted() bool // true after Open finds prior state: elapsed time across the restart is untrusted
func (*Store) Remember(...)          // hostedwire.NonceStore
func appendAudit(tx *sql.Tx, a Audit) error // Audit{Actor hostedwire.KeyID; Account, Task, Attempt, Action, Reason string; At T}
type Alert struct{ Kind, Detail string; At T }
type Alerter interface{ Alert(ctx context.Context, a Alert) error }
type Config struct{ Enabled bool; Images map[isolatedjob.ImageDigest]bool } // later tasks add fields
type Deps struct{ Store *Store; Runner isolatedjob.Runner; Auditor isolatedjob.NetworkAuditor; Alerter Alerter }
func New(cfg Config, d Deps) (*Controller, error) // refuses a nil dependency
```

Controller time:
- While running, `T` advances only with `Mono()`. Every reaper pass checkpoints `(T, wall)`.
- 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.
- 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.

Tables: `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`.

- [ ] **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.
- [ ] **Green:** `go test ./internal/hostedctl -run 'TestStore|TestAudit|TestSpecImmutable|TestRollback|TestRestart' -count=1`.
- [ ] **Mutations:** derive `T` from the wall clock (`TestRollbackThenElapsedTime`); leave `Restarted()` false when the wall clock moved forward (`TestRestartMarksElapsedUntrusted`); drop the trigger (`TestSpecImmutable`).
- [ ] **Commit:** `hostedctl: store, controller time and controller skeleton`.

### Task 10: Launch with intents and replay

**Files:** Create `internal/hostedctl/{launch.go,launch_test.go}`.

**Interfaces:**

```go
type LaunchRequest struct{ AttemptID, TaskID, Account, Replaces string; Image isolatedjob.ImageDigest; Size isolatedjob.Size; MaxLifetime time.Duration; InstanceCode string }
type JobView struct{ AttemptID, LaunchID, State string; VMRef isolatedjob.Ref; Epoch int64; DeadlineIn, DrainIn, StopIn time.Duration }
func (*Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, q LaunchRequest) (JobView, error)
func (*Controller) Replay(ctx context.Context) error
func Deadlines(launched T, max time.Duration) (deadline, drain, stop T) // drain = deadline−45m, stop = deadline−10m, clamped
var ErrDisabled, ErrImageNotAllowed, ErrNetworkAudit, ErrReplacementLive error
```

`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`.

`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).

- [ ] **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).
- [ ] **Green:** `go test ./internal/hostedctl -run 'TestLaunch|TestConcurrentLaunch|TestCrashBetween|TestThrottle|TestDeadlines' -count=1`.
- [ ] **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`).
- [ ] **Commit:** `hostedctl: launch intents and replay`.

### Task 11: Get, stop, stop proof and restart reconciliation

**Files:** Create `internal/hostedctl/{stop.go,refresh.go,stop_test.go}`.

**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`.

Stop 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.

`Refresh` reconciles every live job with `Get`. After any restart (`Restarted()`), the elapsed time of each job that existed before the restart is untrusted:
- With a trusted provider age, set `launched_t = min(launched_t, now − age)` and recompute `deadline_t`, `drain_t` and `stop_t` with `Deadlines`.
- Without one, the job is stopped with the reason `elapsed_unknown`.

- [ ] **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).
- [ ] **Green:** `go test ./internal/hostedctl -run 'TestStop|TestUnknownState|TestLostStop|TestRestart' -count=1`.
- [ ] **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`).
- [ ] **Commit:** `hostedctl: stop proof, unknown states and restart reconciliation`.

### Task 12: Pause generations and prepared resume epochs

**Files:** Create `internal/hostedctl/{pause.go,resume.go,pause_test.go,resume_test.go}`.

**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`.

Suspend records `suspending` before calling the provider; `Refresh` settles it from `Get`.

Resume runs in three steps:
1. **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`.
2. **Provider.** Call `Runner.Resume`.
3. **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`.

Slice 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`:
- `suspended`: call `Runner.Resume` again;
- `running`: commit;
- `unknown`: leave it pending and retry next pass;
- terminal: record proof and mark the job stopped.

- [ ] **Red:**
  - `TestSuspendNeedsCurrentAck`: no acknowledgement, an older generation, the next generation and a cancelled generation are each refused.
  - `TestLateAckIgnored` (an acknowledgement at 2 min 1 s).
  - `TestSuspendedTimeCountsToDeadline`.
  - `TestResumePreparesEpochBeforeProvider`: the stub sees the pending epoch in the store.
  - `TestResumeCrashBeforeProvider`, `TestResumeCrashAfterProvider` and `TestResumeLostReply`: each ends with one provider resume (or a no-op) and the epoch raised exactly once.
  - `TestResumeRetrySameOperation`.
  - `TestResumeOperationsRemembered`: operation A completes, then B completes, then A is retried. There is no provider call, and A's original epoch is returned.
  - `TestResumeOtherOperationWhilePending`.
  - `TestResumePastDeadlineRefused`.
- [ ] **Green:** `go test ./internal/hostedctl -run 'TestSuspend|TestLateAck|TestResume' -count=1`.
- [ ] **Mutations:**
  - Compare generations with `>=`: the next-generation row fails.
  - Call the provider before preparing: `TestResumePreparesEpochBeforeProvider` fails.
  - Raise the epoch on each call: `TestResumeRetrySameOperation` fails.
  - Commit without `Get` showing `running`: `TestResumeLostReply` fails.
  - Look up only the latest operation: `TestResumeOperationsRemembered` fails.
- [ ] **Commit:** `hostedctl: pause generations and prepared resume epochs`.

### Task 13: Reaper and the network audit loop

**Files:** Create `internal/hostedctl/{reaper.go,reaper_test.go}`.

**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`.

Each pass runs in this order:
1. Checkpoint the clock.
2. `Replay`, with Task 10's gates.
3. `Refresh`.
4. 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.
5. 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.
6. Run the audit. While it fails, refuse launches and alert once per episode.

- [ ] **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`.
- [ ] **Green:** `go test ./internal/hostedctl -run 'TestReap|TestOrphanGrace|TestUnknownStateRetried|TestFailingAudit' -count=1`.
- [ ] **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`).
- [ ] **Commit:** `hostedctl: leaked-VM reaper and network audit loop`.

### Task 14: Lifecycle simulation with invariants (spec §14)

**Files:** Create `internal/hostedctl/{sim_test.go,sim_model_test.go}`.

**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.

Each step picks one operation at random:
- launch: fresh, replacement, or a concurrent duplicate;
- crash and reopen at any point, including between a provider call and its follow-up transaction;
- provider faults: lost reply on Launch, Stop or Resume; throttle; incomplete `List`; unknown state; unknown age;
- pause and resume: drain; an acknowledgement (current, stale, next or late); suspend; resume (new or repeated operation ID);
- plant an orphan; stop;
- a wall-clock jump of up to 3 h either way;
- a time advance of up to 9 h.

A 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.

| ID | Invariant, checked after every step | Mutation that must break it |
| --- | --- | --- |
| I1 | At most one live VM per attempt ID | Replay with a fresh client token |
| 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 |
| 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 |
| 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 |
| I5 | A provider Suspend happens only with an acknowledgement for the current, uncancelled generation | Accept `>=` generations |
| I6 | A replacement launches only after stop proof, and proof never comes from `unknown` | Treat `unknown` as terminal |
| 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 |

- [ ] **Red:** write the model; apply each mutation alone and see it fail within the default seeds (record the seed).
- [ ] **Green:** `go test ./internal/hostedctl -run TestLifecycleSimulation -count=1`, then once with `EQUIPO_SIM_SEEDS=5000`.
- [ ] **Commit:** `hostedctl: randomised lifecycle simulation with seven invariants`.

### Task 15: Controller HTTP API, command and metrics

**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}`.

**Interfaces:** strict JSON, `MaxBody`, every response signed; the creating instance only for job routes.

| Route | Role |
| --- | --- |
| `POST /v1/jobs`; `GET /v1/jobs/{attempt}`; `POST /v1/jobs/{attempt}/stop`, `/drain`, `/quiescent`, `/suspend`, `/reopen`, `/resume` | instance |
| `GET /v1/vms` | operator |

Metrics 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`.

- [ ] **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).
- [ ] **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.
- [ ] **Mutation:** drop the creator check; `TestInstanceKeySeesOnlyItsJobs` fails.
- [ ] **Commit:** `hosted controller: signed HTTPS API, command and metrics`.

### Task 16: Instance-side client behind its flag

**Files:** Create `internal/hostedclient/{client.go,client_test.go}`.

**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.

- [ ] **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).
- [ ] **Green:** `go test ./internal/hostedclient -count=1`.
- [ ] **Mutation:** skip response verification; `TestClientRefusesUnsignedResponse` fails.
- [ ] **Commit:** `hostedclient: signed controller client behind a flag`.

### Task 17: Live check in the dev account (HUMAN-gated)

- [ ] **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.
- [ ] **Agent, with GO:** `AWS_PROFILE=kass go test -tags hostedlive ./internal/isolatedjob/awsjob -run TestLiveContract -count=1`, then `List` to confirm teardown.
- [ ] **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.
- [ ] **HUMAN GO, then agent:** plant an orphan with the AWS CLI and watch the reaper stop it after 10 minutes.
- [ ] **HUMAN:** tear the network down. The agent confirms by type and tag, and records the dev spend.
- [ ] One whole-branch review (Astra or Fable, as Paul directs); Paul lands it.

**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.

---

## Slice 1b outline (planned after 1a lands)

1b gets its own plan once 1a is merged. It ends where slice 2 can start (spec §8 lists slice 2's needs).

**Components:**
- egress policy with immutable per-launch snapshots;
- the authenticated proxy:
  - its bootstrap listener (server TLS only, three routes) and its egress listener (mTLS);
  - the signed launch feed;
  - CONNECT, SNI, Host and `:authority` inspection, and origin TLS;
  - decision logs and revocation of open tunnels;
- the resolver: plain DNS answers nothing; DNS over TLS answers per launch;
- per-VM keys: redeem, challenge and exchange, and lapse stops;
- the root init with its hooks, and the foundation probe standing in for the runner;
- the end-to-end test over real TLS;
- the image inventory and reproducible build;
- the hosted admission check (forged-image hello);
- certification:
  - the trusted matrix with positive controls;
  - the report route with provenance;
  - the mutation-evidence registry and replay;
  - online collection and offline signing;
- OpenTofu for dev, release artifacts and CI wiring, and the dev bring-up drills.

**Open findings from Astra rounds 1 and 2 that 1b must close:**
- **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.
- **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.
- **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.
- **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.
- **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.
- **Ordering:** define the release provenance and the `Upstream` and `DecisionLog` contracts before the tasks that consume them.
- **Provider guard:** add `cmd/equipo-vm-init` and `cmd/equipo-hosted-image` as composition points.
- **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.
- **Q3, controller outage versus a stale feed:** bounded continuation needs Paul's approval. Astra's conditions:
  - access ends at the earliest of credential expiry, feed expiry or known revocation;
  - feed freshness is measured on the monotonic clock;
  - existing tunnels are closed at expiry;
  - 15 minutes is a maximum stale window, not guaranteed continuation;
  - a test covers a partitioned proxy while the controller stays up.
- **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.

**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.

## Before slice 2 production (HUMAN, deferred)

- [ ] 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.

## Open questions

1. **MicroVM SDK.** *Recommendation:* the SDK package if one exists, otherwise SigV4 calls inside `awsjob`. Task 4 settles the facts first, as Astra asked.
2. **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.
3. **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.
