| index 92ee38df..44742153 100644 |
| --- a/docs/superpowers/plans/2026-11-30-hosted-runners-slice-2.md |
| +++ b/docs/superpowers/plans/2026-11-30-hosted-runners-slice-2.md |
| @@ -1,354 +1,415 @@ |
| -# Hosted runners, slice 2: hosted checks (plan, 2026-11-30, revision 1) |
| +# Hosted runners, slice 2: hosted checks (plan, 2026-11-30, revision 2) |
| |
| -**Status:** draft for Astra review, then Paul. Nothing built, nothing run against AWS. |
| +**Status:** revision 2 after Astra round 1 (NOT READY: 4 Critical, 12 Important, 2 Minor, all taken; `.superpowers/sdd/2026-11-30-hosted-slice-2-plan/plan-r1.md`). Nothing built, nothing run against AWS. |
| |
| > **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:** A project owner turns on "Run checks in a hosted VM". From then on that project's checks steps run in a Lambda MicroVM in our AWS account, bound to that one step, and the result counts as a sandboxed, certified check, as if the person's own Linux runner had run it. Each person stays inside 2 running VMs, 8 VM-hours a day and $50 a month. |
| |
| -**Architecture:** The instance places a checks step on a hosted job, asks the controller (slice 1a) to launch a certified image, and hands the VM only a bootstrap code. Inside the VM, `equipo-vm-init` starts `equipo-runner` as an unprivileged worker. The runner gets a client certificate for the authenticated egress proxy, enrols with the instance as a worker bound to that one job, receives the candidate pack and a dependency bundle from the person's primary, and runs the checks offline in bubblewrap. The instance accepts the result as sandboxed only because the controller's launch record says the VM runs a certified image, never because the runner says so. The VM's one reachable destination is the Equipo instance, through the proxy. |
| +**Architecture:** The instance places a checks step on a hosted job, asks the controller (slice 1a) to launch a certified image, and hands the VM only a bootstrap code. Inside the VM, `equipo-vm-init` starts `equipo-runner` as an unprivileged worker. The runner gets a client certificate for the authenticated egress proxy, enrols with the instance as a worker bound to that one job, receives a pack of the base and candidate commits plus a dependency bundle from the person's primary, and runs the base gates and checks offline in bubblewrap. The instance counts the result as sandboxed only while the controller's admission record, refreshed at most two minutes earlier, says the VM runs a currently certified image; never because the runner says so. The VM's one reachable destination is the Equipo instance, through the proxy. |
| |
| -**Tech stack:** Go (floor 1.26.0, gate `GOTOOLCHAIN=go1.26.11`, `CGO_ENABLED=0`), modernc SQLite, `crypto/ed25519`, `crypto/x509`, `github.com/coder/websocket` (already the runner's), aws-sdk-go-v2 only under `internal/isolatedjob/awsjob` and the composition commands, OpenTofu 1.12 for `infra/hosted/`. |
| +**Tech stack:** Go (floor 1.26.0, gate `GOTOOLCHAIN=go1.26.11`, `CGO_ENABLED=0`), modernc SQLite, `crypto/ed25519`, `crypto/x509`, `github.com/coder/websocket` (the runner's), `golang.org/x/mod` (already required, v0.38.0), aws-sdk-go-v2 only under `internal/isolatedjob/awsjob` and the composition commands, OpenTofu 1.12 for `infra/hosted/`. |
| |
| -**Spec:** `docs/superpowers/specs/2026-11-18-hosted-runners-microvms.md` (approved 2026-11-19), with §6, §7, §8, §10, §14 and §17 driving this plan. The slice 1a plan's "Slice 1b outline" and its open findings are folded in here (Phase A to D), because slice 2 cannot run without them. |
| +**Spec:** `docs/superpowers/specs/2026-11-18-hosted-runners-microvms.md` (approved 2026-11-19); §5 to §8, §10, §14 and §17 drive this plan. The slice 1a plan's "Slice 1b outline" and its open findings are folded in (Phases A to D), because slice 2 cannot run without them. The production bring-up is `2026-11-30-hosted-prod-account-plan.md`; what slice 4 takes from this plan is `2026-11-30-hosted-slice-4-needs.md`. |
| |
| **Baseline:** `origin/main` at `27d50e7f`, which contains slice 1a (`dd66ff0c`). Tasks run in order unless a task says otherwise. |
| |
| ## Why this plan includes slice 1b |
| |
| -Slice 1a built the controller, the adapter and the reaper. It has no egress stack, so a launched VM has no route anywhere and cannot enrol (slice 1a plan, global constraints). The 1b work (proxy, per-VM credentials, root init, image pipeline, certification, OpenTofu) was outlined but never planned. Hosted checks need all of it, so Phases A to D build the part of 1b that checks need, cut to the smallest shape the spec allows (decisions S2-1 to S2-4 below). Nothing in 1b's outline is dropped without a decision. |
| +Slice 1a built the controller, the adapter and the reaper, with no egress stack: a launched VM has no route anywhere and cannot enrol. The 1b work (proxy, per-VM credentials, root init, image pipeline, certification, OpenTofu) was outlined but never planned. Hosted checks need all of it, so Phases A to D build the part of 1b that checks need, cut to the smallest shape the spec allows. Every 1b item is either built here or named below as a decision. |
| |
| ## Decisions this plan takes (Paul confirms or overrules; see "Decisions owed to Paul") |
| |
| -- **S2-1. Dependencies come from the person's primary, not a mirror service.** The primary already holds the module cache its own checks use. It sends a dependency bundle with the candidate pack; the runner (outside the sandbox) checks every file against the module hashes and mounts the result read-only. A missing module ends the step `cannot_run` with `needs_network`, exactly as on a personal runner today. The VM's only destination is the Equipo instance. This meets every property in spec §6 (trusted staging outside the sandbox, immutable, hash-verified, read-only, an explicit missing result, no fetch the sandbox can trigger), but it is not the separate importer service §6 describes. The importer is deferred until a hosted primary exists. Go modules only, as on personal runners today. |
| +- **S2-1. Dependencies come from the person's primary, not a mirror service.** The primary sends a bundle from the module cache its own checks use. The runner, outside the sandbox, accepts only modules pinned in the **base** commit's `go.sum`, verifies each against that pin, extracts them with `golang.org/x/mod/zip` into a fresh directory, and mounts it read-only. A candidate line that changes a base pin is a conflict, and the step ends `cannot_run` with reason `deps_conflict`. A module the base does not pin is never staged, and the step ends `cannot_run` `needs_network` with reason `deps_new_module`. So a candidate that adds a dependency cannot pass hosted checks in slice 2; the person's own runner still can. This keeps every property spec §6 asks of the mirror (staged outside the sandbox, immutable, hash-verified against a trusted pin, read-only, an explicit missing result, nothing the sandbox can fetch). It is not the importer service §6 describes, and spec §16 ruling 4 says "the read-only mirror is required before hosted code runs", so it is Paul's call. The importer is deferred until a hosted primary exists. Go modules only, as on personal runners today. |
| - **S2-2. No resolver in the VM network.** The runner dials the proxies by IP literal from the bootstrap; the proxy resolves the instance's name. The VM has no DNS at all. This removes the 1b resolver component. |
| -- **S2-3. No bounded continuation when the controller is unreachable** (1b open question Q3). The proxy refuses everything once its signed feed is older than 5 minutes on its monotonic clock, and closes open tunnels. A checks step then fails `hosted_unavailable` and retries once on a new VM. |
| -- **S2-4. Controller and proxies live in a services VPC with VPC DNS on, peered to a VM VPC with VPC DNS off.** VMs reach only the two proxies' addresses across the peering. The instance and the proxies reach the controller over public HTTPS with signed requests and a pinned certificate. |
| -- **S2-5. Checks VMs are Large (4 GB, 2 vCPU) with a 90-minute lifetime.** Go builds need the memory; a 10-minute run costs about $0.05. |
| -- **S2-6. No pause or resume in slice 2.** A checks VM is launched, used once and stopped. The slice 1a pause barrier stays unused until slice 4. |
| +- **S2-3. One expiry rule, no bounded continuation** (1b open question Q3). The controller signs each feed with a 5-minute lifetime; proxies poll every 30 s. A proxy closes a tunnel, and refuses new requests, at the earliest of: the client certificate's `NotAfter`, the feed's expiry measured from receipt on the proxy's monotonic clock, and the serial's revocation in a fresher feed. A checks step then fails `hosted_unavailable` and retries once on a new VM. |
| +- **S2-4. Controller and proxies live in a services VPC with VPC DNS on, peered to a VM VPC with VPC DNS off.** The VM subnet's routes are the local route plus one `/32` per proxy over that one peering; Task 9 extends the network audit to require exactly that. The proxies use the services VPC's AWS resolver; the 1b decision to pin an upstream resolver for the proxies is dropped with it (decision 4 below). The instance and the proxies reach the controller over public HTTPS with signed requests and a pinned certificate. |
| +- **S2-5. Checks VMs are Large (4 GB, 2 vCPU) with a 90-minute lifetime.** A 10-minute run costs about $0.05 at baseline. |
| +- **S2-6. No pause or resume in slice 2.** A checks VM is launched, used once and stopped. The slice 1a pause barrier stays unused until slice 4; the VM's `/suspend` and `/resume` hooks answer 409 in one place. |
| - **S2-7. The proxy speaks HTTP/1.1 only** (ALPN `http/1.1`), including the WebSocket upgrade the runner's link uses. HTTP/2 is refused, which removes `:authority` disagreement by construction. |
| - **S2-8. The controller is the client CA for proxy certificates.** It mints a 15-minute certificate per VM against the launch record; both proxies trust that CA and the signed feed. |
| -- **S2-9. Limits are held and settled.** Admission holds a job's full lifetime against the person's daily VM-hours and its full estimated cost against the monthly dollars, then settles to actual when the job ends. Limits can never be exceeded by jobs that run long. |
| +- **S2-9. Limits are held and settled, conservatively.** Admission holds a job's full lifetime against every UTC day it could touch, and its cost at four times the baseline rate (AWS bills burst up to 4x and does not report it) against every UTC month it could touch. Settling replaces the hold with the instance-observed span from admission to stop proof, at the baseline rate, split at day and month boundaries; the estimate is labelled an estimate. A job without stop proof keeps its hold. |
| +- **S2-10. No mutation-evidence registry in certification.** Certification judges the probe matrix and the containment suite inside a real VM; guard mutation evidence stays where the house keeps it, in the progress file, checked at review. The 1b outline listed a registry; this drops it. |
| |
| ## Global constraints |
| |
| -- AWS SDK types only under `internal/isolatedjob/awsjob/` and the composition commands. Task 9 adds `cmd/equipo-vm-init`, `cmd/equipo-hosted-image`, `cmd/equipo-hosted-proxy` and `cmd/equipo-hosted-certify` to `TestProviderTypesStayInAdapter`'s allowed list only where they import AWS packages (the proxy and the certifier must not). |
| -- Spec §17's five authority rules apply to every task. In particular: a hello is diagnostic only (rule 2, Fable M8); untrusted text enters prompts only through `wire.QuotedData` under a source label (rule 3, Fable M4); a sandbox that runs agent-chosen or candidate code has no network (rule 5, Fable H3). |
| +- AWS SDK types only under `internal/isolatedjob/awsjob/` and the composition commands. `cmd/equipo-hosted-image` joins `TestProviderTypesStayInAdapter`'s allowed list (Task 10); the proxy, `equipo-vm-init` and `equipo-hosted-certify` must not import AWS packages. |
| +- Spec §17's five rules apply to every task: a hello is diagnostic only (Fable M8); untrusted text enters prompts only through `wire.QuotedData` under a source label (Fable M4); a sandbox that runs candidate code has no network (Fable H3). |
| - Egress names are exact fully qualified hostnames on port 443, copied into each launch record. No wildcard, suffix match, IP literal or `amadan.net` in a VM's set. An unset name blocks launch. |
| - Every new instance route checks the current roster inside its transaction; lookup errors deny. An unknown count stays unknown and denies admission. |
| -- Migrations additive, one per task that needs one, the next free number at the time (latest on main is `0124_step_renders.sql`). Protocol: one new number, `wire.ProtocolHostedChecks`, the next free at build time (main's highest is 38); confirm with the coordinator before code, since other branches allocate numbers. |
| -- Package budgets (`.rastrillo/budgets.txt`): `internal/runner/thin`, `internal/runner`, `internal/wire` and `internal/runner/provider` sit exactly at their recorded sizes. New code goes in new packages; any line added to those four raises its record in the same commit, with the reason. |
| -- Copy: new runtime strings only in `internal/equipo/copy.go`, marked pending with `python3 scripts/copy-status.py pending`, and listed in `docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json` for review. Never accepted by an agent. Plain words, no em dashes, no exclamation marks. |
| +- Migrations additive, the next free number at the time (latest on main is `0124_step_renders.sql`). Protocol: one new number, `wire.ProtocolHostedChecks`, the next free at build time (main's highest is 38); confirm with the coordinator before code. Hosted placement requires it on both the primary and the hosted runner, so no older runner sees a hosted frame or transfer. |
| +- Package budgets (`.rastrillo/budgets.txt`): `internal/runner/thin`, `internal/runner`, `internal/wire`, `internal/runner/provider` and `internal/hostedctl` are at their recorded sizes. New code goes in new packages (each task names them); any line added to one of those five, or to `internal/equipo/chat`, raises its record in the same commit with the reason. |
| +- Copy: new runtime strings only in `internal/equipo/copy.go`, marked pending with `python3 scripts/copy-status.py pending`, listed in `docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json`. Never accepted by an agent. Plain words, no em dashes, no exclamation marks. |
| - Tests first. Each guard gets a mutation check: break it, watch the named test compile, run at least one test and fail on its assertion (a build error, an infrastructure error or a run of zero tests does not count), restore. Record commands and results in `docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md`. |
| -- Local runs are targeted (`go test ./internal/<pkg> -run 'TestX' -count=1`); `make ci` once before the whole-branch review. No sudo; scratch under `$TMPDIR` via `mktemp -d`; test servers on `127.0.0.1`; default Go caches. Live AWS tests use build tag `hostedlive` and run only inside Task 30's approved plan. |
| +- Local runs are targeted (`go test ./internal/<pkg> -run 'TestX' -count=1`). No sudo; scratch under `$TMPDIR` via `mktemp -d`; test servers on `127.0.0.1`; default Go caches. Live AWS tests use build tag `hostedlive` and run only inside Tasks 33 and 34's approved plans. |
| - Flags: the instance does nothing hosted unless `EQUIPO_HOSTED_RUNNERS=1`; the controller launches nothing unless `EQUIPO_HOSTED_ENABLED=1`; a project runs nothing hosted unless its owner turned the setting on. |
| -- Commit subjects under 80 characters, trailer `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. Never merge, push the default branch or deploy. No AWS call outside Tasks 30 and 31's approved plans. |
| +- Commit subjects under 80 characters, trailer `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. Never merge, push the default branch or deploy. No AWS call outside Tasks 33 and 34's approved plans. |
| |
| ## Review focus |
| |
| -1. **A forged or replayed identity.** A hello claiming `bubblewrap` and a certified image from an uncertified VM; another VM's bootstrap code, proxy certificate or enrolment replayed. Expected: refused, and no result counts as sandboxed. `TestHelloCannotCertify` (Task 21), `TestEnrolRefusesReplayAndWrongVM` (Task 19), `TestRedeemSingleUse` (Task 4). |
| -2. **The proxy as an exfiltration path.** An allowed SNI with another Host, a CONNECT to an IP literal, a redirect to another host, an encoded authority, a WebSocket upgrade to another host, HTTP/2. Expected: refused and logged by name. `TestFrontingMatrix` (Task 7). |
| -3. **Limits under concurrency and long jobs.** Two steps for one person dispatched at once with one slot left; a job that runs its full lifetime; a count query that fails. Expected: never 3 running, never over 8 VM-hours or $50, a failed count waits. `TestLimitsHoldAndSettle`, `TestLimitsRace`, `TestLimitCountErrorDenies` (Task 17). |
| -4. **A VM that never enrols or dies mid-step.** Expected: stopped with proof, retried once, then the step fails with a reason the person can read; the person's other work is unaffected. `TestEnrolTimeoutRetriesOnce`, `TestVMGoneMidStep` (Task 18). |
| -5. **A candidate that edits its own gates or dependency hashes.** Expected: base gates from BaseSHA still certify; a module whose bytes do not match the hash lines is refused, never staged. `TestHostedBaseGatesFromBase` (Task 14), `TestBundleRefusesHashMismatch` (Task 13). |
| +1. **A forged, replayed or stale identity.** A hello claiming `bubblewrap` and a certified image from an uncertified VM; another VM's bootstrap code, proxy certificate or enrolment replayed; a certification key withdrawn while a VM runs. Expected: refused, and no result counts as sandboxed. `TestHelloCannotCertify`, `TestStaleAdmissionNotCertified` (Task 24), `TestEnrolRefusesReplayAndWrongVM` (Task 22), `TestRedeemSingleUse` (Task 4). |
| +2. **The proxy as an exfiltration path.** An allowed SNI with another Host, a CONNECT to an IP literal, a redirect to another host, an encoded authority, a WebSocket upgrade to another host, HTTP/2, an open socket after its certificate expires. Expected: refused or closed, and logged by name. `TestFrontingMatrix`, `TestOpenSocketClosesAtCertExpiry` (Task 7). |
| +3. **Limits under concurrency and long jobs.** Two steps for one person at once with one slot left; a job crossing midnight; a lost stop reply. Expected: never 3 running, never over 8 VM-hours or $50, a failed count waits, a job without proof keeps its hold. `TestLimitsHoldAndSettle`, `TestLimitsRace`, `TestHoldSpansMidnight`, `TestLimitCountErrorDenies` (Task 20). |
| +4. **A VM that never enrols or dies mid-step, or a primary that goes away.** Expected: stopped with proof, retried once after the predecessor's proof, then the step fails with a reason the person can read. `TestEnrolTimeoutRetriesOnce`, `TestVMGoneMidStep`, `TestPrimaryLostDuringEnrolment` (Task 21). |
| +5. **A candidate that edits its own gates or dependency pins.** Expected: base gates from BaseSHA certify; a changed base pin is a conflict; a new module is not staged. `TestHostedBaseGatesFromBase` (Task 17), `TestBasePinWins`, `TestNewModuleNotStaged` (Task 16). |
| |
| --- |
| |
| ## Phase A: controller additions (spec §5, §6, §7) |
| |
| +New controller code lives in subpackages `internal/hostedctl/ctlegress`, `ctlcert` and `ctlproxy`, each with its own tables through the controller's `*Store`; `hostedctl` itself gains only wiring and routes, and its budget record rises in the commit that adds them. |
| + |
| ### Task 1: Wire contracts for hosted checks |
| |
| -**Files:** Modify `internal/hostedwire/api.go`, `internal/hostedwire/api_test.go`. Create `internal/wire/hosted.go`, `internal/wire/hosted_test.go`. Modify `internal/wire/runners.go` (protocol constant), `.rastrillo/budgets.txt`. |
| +**Files:** Modify `internal/hostedwire/api.go`, `api_test.go`. Create `internal/hostedwire/hosted.go`, `hosted_test.go`, `internal/wire/hosted.go`, `internal/wire/hosted_test.go`. Modify `internal/wire/runners.go` (protocol constant, transfer kinds), `.rastrillo/budgets.txt`. |
| |
| **Interfaces:** |
| |
| ```go |
| // hostedwire |
| const RoleProxy Role = "proxy" |
| +type Service struct{ Host string; Port uint16; Class string } // Class "instance" | "cert_report" (slice 4 adds "gateway") |
| type BootstrapV2 struct { |
| - Version int `json:"v"` // 2 |
| + Version int `json:"v"` // 2 |
| + Purpose string `json:"purpose"` // "checks" | "certification" |
| LaunchID string `json:"launch_id"` |
| AttemptID string `json:"attempt_id"` |
| - InstanceCode string `json:"instance_code"` // 32 bytes, base64url |
| - ProxyCode string `json:"proxy_code"` // 32 bytes, base64url |
| + InstanceCode string `json:"instance_code"` // 32 bytes base64url; "" for certification |
| + ProxyCode string `json:"proxy_code"` // 32 bytes base64url |
| Proxies []netip.AddrPort `json:"proxies"` // egress listeners, 1 or 2 |
| ProxyBoot []netip.AddrPort `json:"proxy_boot"` // bootstrap listeners, same hosts |
| - ProxyCAPin string `json:"proxy_ca_pin"` // sha256 of the proxy TLS CA's SPKI, hex |
| - InstanceHost string `json:"instance_host"` // exact FQDN |
| + ProxyCAPin string `json:"proxy_ca_pin"` // hex sha256 of the intercept CA's SPKI |
| + Services []Service `json:"services"` // the launch's snapshot (Task 2) |
| } |
| -func (b BootstrapV2) Encode() ([]byte, error) // ASCII JSON, refuses over 4096 bytes (live fact, Task 17) |
| -type Service struct{ Host string; Port uint16; Class string } // Class "instance" in slice 2 |
| -type LaunchRequest struct{ /* 1a fields */ Person string; Services []Service; Purpose string } // Purpose "checks" | "certification" |
| -type AdmissionView struct{ AttemptID, LaunchID, State string; VMRef isolatedjob.Ref; Epoch int64; Image isolatedjob.ImageDigest; CertDigest string; CertValid bool } |
| -type ProxyFeed struct{ Version int; Serial int64; IssuedAtNS int64; TTLMS int64; Launches []FeedLaunch; Revoked []string } |
| -type FeedLaunch struct{ LaunchID, AttemptID string; VMRef isolatedjob.Ref; Epoch int64; Services []Service; ProxyCodeHash string } |
| -type RedeemRequest struct{ LaunchID, VMRef, ProxyCode string; CSR []byte } // proxy forwards |
| +func (b BootstrapV2) Encode() ([]byte, error) // ASCII JSON; refuses over 4096 bytes (live fact, Task 17) |
| +// LaunchRequest gains: Person string; Purpose string. Services are not requested: the controller |
| +// derives them from its manifest (Task 2). |
| +type AdmissionView struct{ AttemptID, LaunchID, State string; VMRef isolatedjob.Ref; Epoch int64; Image isolatedjob.ImageDigest; CertDigest string; CertValid bool; CheckedNS int64 } |
| +type ProxyFeed struct{ Version int; Serial int64; IssuedNS int64; TTLMS int64; Launches []FeedLaunch; Revoked []string } |
| +type FeedLaunch struct{ LaunchID, AttemptID string; VMRef isolatedjob.Ref; Epoch int64; Services []Service; ProxyCodeHash string; DeadlineNS int64 } |
| +type RedeemRequest struct{ LaunchID string; VMRef isolatedjob.Ref; ProxyCode string; CSR []byte } |
| type RedeemResponse struct{ Cert []byte; NotAfterNS int64 } |
| -type RenewCertRequest struct{ LaunchID string; CertSerial string; CSR []byte; Proof []byte } |
| +type RenewCertRequest struct{ Serial string; CSR []byte } // sent over the current client certificate (Task 6) |
| +type CertLaunchRequest struct{ Image isolatedjob.ImageDigest; Size isolatedjob.Size } |
| // wire |
| const PlacementHosted = "waiting_hosted"; const PlacementHostedLimit = "hosted_limit" |
| -const TransferKindDeps = "deps" |
| -type HostedEnrolRequest struct{ Code, LaunchID, VMRef string; MachinePublicKey []byte } |
| -type HostedRenewRequest struct{ RunnerID string; Epoch int64; Challenge, Signature []byte } |
| +const TransferKindHostedPack, TransferKindDeps = "hosted_pack", "deps" |
| +const DepsTransferMax = 256 << 20 // its own limit; the 64 MiB limit stays for every other kind |
| +type HostedEnrolRequest struct{ Code, LaunchID string; VMRef string; MachinePublicKey []byte } |
| +type HostedChallenge struct{ Nonce []byte; ExpiresAt time.Time } |
| +type HostedRenewRequest struct{ RunnerID string; Epoch int64; Nonce, Signature []byte } // Ed25519 over "equipo-hosted-renew-v1\n"+runner+"\n"+epoch+"\n"+nonce |
| ``` |
| |
| -- [ ] **Red:** `TestBootstrapV2Limit` (a maximal valid bootstrap encodes under 4096 bytes; 4097 refused; non-ASCII refused). `TestLaunchRequestV2Strict` (unknown field, a wildcard or IP-literal host, port other than 443, empty `Services` for `checks`, unknown `Purpose`: each refused by `DecodeStrict` plus `Validate`). `TestHostedFramesOldProtocol` (`wire.Encode` at protocol 38 drops `TransferKindDeps` headers). |
| -- [ ] **Green:** `go test ./internal/hostedwire ./internal/wire -run 'TestBootstrapV2|TestLaunchRequestV2|TestHostedFrames' -count=1`. |
| -- [ ] **Mutations:** accept a `*.` host (`TestLaunchRequestV2Strict`); drop the size check (`TestBootstrapV2Limit`). |
| +- [ ] **Red:** `TestBootstrapV2Limit` (a maximal valid bootstrap with two proxies and two services encodes under 4096 bytes; 4097 refused; non-ASCII refused). `TestLaunchRequestV2Strict` (unknown field, unknown `Purpose`, empty `Person` for `checks`: refused). `TestDepsTransferLimit` (a `deps` header at 256 MiB accepted, one byte more refused; a `checks` header keeps 64 MiB). `TestHostedKindsNeedProtocol` (`wire.Encode` at protocol 38 refuses a `hosted_pack` or `deps` header with an error instead of dropping it). |
| +- [ ] **Green:** `go test ./internal/hostedwire ./internal/wire -run 'TestBootstrapV2|TestLaunchRequestV2|TestDepsTransfer|TestHostedKinds' -count=1`. |
| +- [ ] **Mutations:** drop the size check (`TestBootstrapV2Limit`); let `deps` use the 64 MiB limit (`TestDepsTransferLimit`). |
| - [ ] **Commit:** `hostedwire: bootstrap v2, services, admission and proxy feed types`. |
| |
| ### Task 2: Egress manifest and the per-launch snapshot |
| |
| -**Files:** Create `internal/hostedctl/egress.go`, `egress_test.go`, `schema/0002_egress.sql`. Modify `launch.go`, `cmd/equipo-hosted-controller/config.go`, `config_test.go`. |
| +**Files:** Create `internal/hostedctl/ctlegress/{manifest.go,manifest_test.go}`, `internal/hostedctl/schema/0002_egress.sql`. Modify `internal/hostedctl/launch.go`, `cmd/equipo-hosted-controller/config.go`, `config_test.go`. |
| |
| -**Interfaces:** `Config.Services map[string]hostedwire.Service` (class to service, from the deployment manifest); `Config.Proxies, ProxyBoot []netip.AddrPort`; `Config.ProxyCAPin string`. `func (c Config) servicesFor(purpose string) ([]hostedwire.Service, error)`; `ErrServiceUnset`. Launch intents gain an immutable `services_json` column under the 1a immutability trigger. |
| +**Interfaces:** `ctlegress.Manifest{Services map[string]hostedwire.Service; Proxies, ProxyBoot []netip.AddrPort; ProxyCAPin string}`; `func Load(raw []byte) (Manifest, error)`; `func (m Manifest) For(purpose string, reportHost string) ([]hostedwire.Service, error)` (`checks`: the `instance` class; `certification`: one `cert_report` service, the controller's own public host); `ErrServiceUnset`. Launch intents gain an immutable `services_json` column under the 1a immutability trigger; `Replay` uses it, never current config. |
| |
| -- [ ] **Red:** `TestManifestRefusesWildcardsAndLiterals` (`*.x`, `.x`, `1.2.3.4`, `[::1]`, `amadan.net`, a name with a trailing dot, upper case: each refused at config load). `TestUnsetServiceBlocksLaunch`. `TestLaunchSnapshotsServices` (the intent's services equal the config at launch; changing config afterwards does not change a saved intent; `Replay` uses the saved snapshot). `TestSnapshotImmutable`. |
| -- [ ] **Green:** `go test ./internal/hostedctl ./cmd/equipo-hosted-controller -run 'TestManifest|TestUnsetService|TestLaunchSnapshots|TestSnapshotImmutable' -count=1`. |
| -- [ ] **Mutations:** suffix match in validation; replay from current config instead of the snapshot. |
| +- [ ] **Red:** `TestManifestRefusesWildcardsAndLiterals` (`*.x`, `.x`, `1.2.3.4`, `[::1]`, `amadan.net`, a trailing dot, upper case, port 8443: each refused at load). `TestUnsetServiceBlocksLaunch`. `TestLaunchSnapshotsServices` (the intent's services equal config at launch; later config changes do not reach a saved intent; `Replay` sends the snapshot). `TestSnapshotImmutable`. |
| +- [ ] **Green:** `go test ./internal/hostedctl/... ./cmd/equipo-hosted-controller -run 'TestManifest|TestUnsetService|TestLaunchSnapshots|TestSnapshotImmutable' -count=1`. |
| +- [ ] **Mutations:** suffix match in `Load`; replay from current config. |
| - [ ] **Commit:** `hostedctl: exact-host egress manifest, snapshotted per launch`. |
| |
| -### Task 3: Image certificates replace the image allowlist |
| +### Task 3: Image certificates and the admission record |
| |
| -**Files:** Create `internal/hostedcert/{cert.go,cert_test.go}`, `internal/hostedctl/{certs.go,certs_test.go,admission.go,admission_test.go}`. Modify `controller.go`, `launch.go`, `http.go`, `cmd/equipo-hosted-controller/config.go`. |
| +**Files:** Create `internal/hostedcert/{cert.go,cert_test.go}`, `internal/hostedctl/ctlcert/{certs.go,certs_test.go}`, `internal/hostedctl/{admission.go,admission_test.go}`. Modify `controller.go` (replace `Config.Images`), `launch.go:152` (purpose-aware role check), `http.go` (routes), `internal/hostedclient/client.go` (`Admission`), `client_test.go`, `cmd/equipo-hosted-controller/config.go`. |
| |
| **Interfaces:** |
| |
| ```go |
| // hostedcert: the canonical certificate (1b finding: verify the snapshot, not only a digest) |
| type Snapshot struct { |
| - Purpose string // "equipo-hosted-image-cert" |
| - Version int // 1 |
| - Image isolatedjob.ImageDigest |
| - Runner string // sha256 of the runner binary in the image |
| - SandboxPolicy string // sha256 of the check policy digest set |
| - ProxyPolicy int // proxy policy version the matrix ran against |
| - Deps string // "primary-bundle-v1" (S2-1) |
| - Deployment []string // exact instance hosts this cert covers |
| - Profile string // "vm-boundary" |
| - IssuedAt time.Time |
| + Purpose string // "equipo-hosted-image-cert" |
| + Version int // 1 |
| + Image isolatedjob.ImageDigest |
| + ImageVersion string // the provider's image version ARN the evidence ran on |
| + Runner string // sha256 of the runner binary, measured in the VM by vm-init |
| + VMInit string // sha256 of equipo-vm-init, measured |
| + SandboxPolicy string // sha256 of the check policy set, measured |
| + ProxyPolicy int // proxy policy version the matrix ran against |
| + Deps string // "primary-bundle-v1" (S2-1) |
| + Deployment []string // exact instance hosts this certificate covers |
| + Profile string // "vm-boundary-checks" |
| + EvidenceID string // the controller-signed evidence this was judged from (Task 13) |
| } |
| -type Certificate struct{ Snapshot Snapshot; KeyID string; Sig []byte } |
| +type Certificate struct{ Snapshot Snapshot; KeyID string; IssuedAt time.Time; Sig []byte } |
| func Canonical(s Snapshot) []byte |
| -func Sign(s Snapshot, id string, k ed25519.PrivateKey) Certificate |
| -func Verify(c Certificate, keys map[string]ed25519.PublicKey, now time.Time) (Snapshot, error) |
| +func Sign(s Snapshot, id string, k ed25519.PrivateKey, at time.Time) Certificate |
| +func Verify(c Certificate, keys map[string]ed25519.PublicKey) (Snapshot, error) |
| func Digest(c Certificate) string |
| +// ctlcert |
| +type Set struct{ /* certificates + keys, loaded from the config files, replaced atomically on reload */ } |
| +func (s *Set) For(image isolatedjob.ImageDigest, hosts []string) (hostedcert.Certificate, error) |
| +func (s *Set) Valid(digest string) bool // false once the key or the certificate is removed |
| // hostedctl |
| -// Config.Images (map[digest]bool) is replaced by Config.Certificates []hostedcert.Certificate and Config.CertKeys. |
| var ErrNotCertified error |
| -func (*Controller) Admission(ctx context.Context, by hostedwire.KeyID, attemptID string) (hostedwire.AdmissionView, error) // creating instance only |
| +func (*Controller) Admission(ctx context.Context, by hostedwire.KeyID, attemptID string) (hostedwire.AdmissionView, error) // creating instance only; re-verifies on every call |
| +// hostedclient |
| +func (*Client) Admission(ctx context.Context, attempt string) (hostedwire.AdmissionView, error) // GET /v1/jobs/{attempt}/admission |
| ``` |
| |
| -`Launch` (purpose `checks`) requires a certificate whose snapshot names the image, covers every `Services` host of class `instance`, and verifies; it records the certificate digest on the intent. Purpose `certification` requires the image only in `Config.CertificationImages` (the operator's candidate list) and launches with the controller's own report host as its one service. `Admission` re-verifies the stored certificate against the current key set each call; a key removed from config makes `CertValid` false. |
| +`Launch` for `checks` (instance role) requires a certificate from `Set.For` whose snapshot names the image and covers every `instance` host in the snapshot; it records the certificate digest on the intent. `Admission` answers `CertValid` from `Set.Valid` at the moment of the call and stamps `CheckedNS` in controller time. |
| |
| -- [ ] **Red:** `TestCertificateCanonical` (field order, and every field covered: changing any one breaks `Verify`). `TestLaunchNeedsCertificate` (table: no certificate, wrong image, host not covered, unknown key, bad signature, purpose mismatch). `TestAdmissionRecordsCertDigest`. `TestAdmissionKeyRevoked`. `TestAdmissionCreatorOnly`. |
| -- [ ] **Green:** `go test ./internal/hostedcert ./internal/hostedctl -run 'TestCertificate|TestLaunchNeedsCertificate|TestAdmission' -count=1`; the 1a contract and simulation still pass (`-run 'TestLifecycleSimulation|TestLaunch'`). |
| -- [ ] **Mutations:** leave `Deployment` out of `Canonical`; skip re-verification in `Admission`. |
| +- [ ] **Red:** `TestCertificateCanonical` (every field covered: changing any one breaks `Verify`). `TestLaunchNeedsCertificate` (no certificate, wrong image, host not covered, unknown key, bad signature, purpose mismatch). `TestAdmissionRecordsCertDigest`. `TestAdmissionKeyRemoved` (reload without the key: `CertValid` false on the next call). `TestAdmissionCreatorOnly`. `TestClientAdmissionVerified` (the client checks the signed response against its own nonce). |
| +- [ ] **Green:** `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient -run 'TestCertificate|TestLaunchNeedsCertificate|TestAdmission|TestClientAdmission' -count=1`; the 1a simulation still passes (`-run TestLifecycleSimulation`). |
| +- [ ] **Mutations:** leave `Deployment` out of `Canonical`; cache `CertValid` from launch time. |
| - [ ] **Commit:** `hostedctl: certified images and the admission record`. |
| |
| ### Task 4: The controller as client CA, and the signed proxy feed |
| |
| -**Files:** Create `internal/hostedctl/{proxyca.go,proxyca_test.go,feed.go,feed_test.go}`, `schema/0003_proxy.sql`. Modify `http.go`, `stop.go`, `cmd/equipo-hosted-controller/config.go`. |
| +**Files:** Create `internal/hostedctl/ctlproxy/{ca.go,feed.go,ca_test.go,feed_test.go}`, `internal/hostedctl/schema/0003_proxy.sql`. Modify `internal/hostedctl/http.go:259` (accept `RoleProxy` on proxy routes only), `stop.go` (revoke on stop), `metrics.go`, `cmd/equipo-hosted-controller/config.go`. |
| |
| -**Interfaces:** routes `GET /v1/proxy/feed` (role proxy) returns `ProxyFeed`; `POST /v1/proxy/redeem` (role proxy) takes `RedeemRequest`; `POST /v1/proxy/renew` (role proxy) takes `RenewCertRequest`. `func (*Controller) Redeem(ctx, by hostedwire.KeyID, q hostedwire.RedeemRequest) (hostedwire.RedeemResponse, error)`; `CertLifetime = 15 * time.Minute`; `FeedTTL = 60 * time.Second`. The client certificate carries one URI SAN `equipo-launch://<launch_id>/<attempt_id>/<vm_ref>/<epoch>` and an ECDSA P-256 key from the VM's CSR. Proxy codes are stored as SHA-256 only, single use, valid 2 minutes from the moment the VM is first seen `running`, bound to the launch and the VM reference. Stop or epoch change revokes every serial for that launch, and the feed lists it. |
| +**Interfaces:** routes `GET /v1/proxy/feed`, `POST /v1/proxy/redeem`, `POST /v1/proxy/renew`, role `proxy` only. `CertLifetime = 15 * time.Minute`; `FeedLifetime = 5 * time.Minute`. A certificate's `NotAfter` is the earlier of 15 minutes and the job's deadline. It carries one URI SAN `equipo-launch://<launch_id>/<attempt_id>/<vm_ref>/<epoch>` and the VM's ECDSA P-256 key from the CSR. Proxy codes are stored as SHA-256 only, single use, valid 2 minutes from the moment the controller first sees the VM `running`, bound to the launch and the VM reference. Renewal is allowed once per serial, for the same launch, VM and epoch, before `NotAfter`; it revokes the old serial. Stop or epoch change revokes every serial of the launch. The controller records each proxy key's last feed request; `proxy_last_feed_seconds{proxy}` is a metric, and an alert `proxy_silent` fires once when a configured proxy has not polled for 3 minutes. |
| |
| -- [ ] **Red:** `TestRedeemSingleUse`, `TestRedeemBindsVMRef` (the right code from another VM is refused), `TestRedeemExpires` (2 min 1 s), `TestRenewNeedsCurrentEpoch`, `TestStopRevokesSerials`, `TestFeedSignedAndListsOnlyLive`, `TestFeedRoleProxyOnly`. |
| -- [ ] **Green:** `go test ./internal/hostedctl -run 'TestRedeem|TestRenew|TestStopRevokes|TestFeed' -count=1`. |
| -- [ ] **Mutations:** skip the VM reference check; keep revoked serials out of the feed. |
| +- [ ] **Red:** `TestRedeemSingleUse`, `TestRedeemBindsVMRef` (the right code from another VM: refused), `TestRedeemExpires` (2 min 1 s), `TestCertCappedAtDeadline`, `TestRenewOncePerSerial` (a replayed renewal is refused), `TestRenewNeedsCurrentEpoch`, `TestStopRevokesSerials`, `TestFeedSignedAndListsOnlyLive`, `TestProxyRoleOnlyOnProxyRoutes` (a proxy key on `/v1/jobs` and an instance key on `/v1/proxy/feed`: 403), `TestProxySilentAlertOnce`. |
| +- [ ] **Green:** `go test ./internal/hostedctl/... -run 'TestRedeem|TestCertCapped|TestRenew|TestStopRevokes|TestFeed|TestProxyRole|TestProxySilent' -count=1`. |
| +- [ ] **Mutations:** skip the VM reference check; allow a second renewal of a serial; keep revoked serials out of the feed. |
| - [ ] **Commit:** `hostedctl: proxy client certificates and the signed launch feed`. |
| |
| +### Task 5: Operator routes: certification launch, reload, alert test |
| + |
| +**Files:** Modify `internal/hostedctl/http.go`, `launch.go`, `cmd/equipo-hosted-controller/main.go`. Create `internal/hostedctl/operator_test.go`. |
| + |
| +**Interfaces:** operator role only: `POST /v1/cert/launch` (`CertLaunchRequest`; the image must be in the operator's `certification-images.json`; purpose `certification`, `Person` empty, services from `Manifest.For("certification")`); `GET /v1/certs` (active certificate digests and their snapshots); `POST /v1/admin/reload` (re-read the certificate and certification-image files; a file that fails to verify leaves the old set in place and returns the error); `POST /v1/admin/restart` (exit 0 after in-flight requests, so systemd restarts it and `ExecStartPre` re-fetches config); `POST /v1/admin/alert-test` (one `test` alert). `GET /v1/vms` already exists. |
| + |
| +- [ ] **Red:** `TestCertLaunchOperatorOnly`, `TestCertLaunchNeedsCandidateImage`, `TestReloadKeepsOldSetOnBadFile`, `TestAlertTestPublishesOnce`. |
| +- [ ] **Green:** `go test ./internal/hostedctl -run 'TestCertLaunch|TestReload|TestAlertTest' -count=1`. |
| +- [ ] **Mutation:** accept an instance key on `/v1/cert/launch`. |
| +- [ ] **Commit:** `hostedctl: operator routes for certification and reload`. |
| + |
| ## Phase B: the authenticated egress proxy (spec §6, Fable H3) |
| |
| -### Task 5: Proxy policy core |
| +### Task 6: Proxy policy core and data path |
| |
| -**Files:** Create `internal/hostedproxy/{policy.go,feed.go,policy_test.go,feed_test.go}`. |
| +**Files:** Create `internal/hostedproxy/{policy.go,feed.go,egress.go,boot.go,origin.go,log.go,policy_test.go,egress_test.go}`, `cmd/equipo-hosted-proxy/{main.go,config.go,config_test.go}`. |
| |
| **Interfaces:** |
| |
| ```go |
| -type Identity struct{ LaunchID, AttemptID string; VMRef isolatedjob.Ref; Epoch int64; Serial string } |
| +type Identity struct{ LaunchID, AttemptID string; VMRef isolatedjob.Ref; Epoch int64; Serial string; NotAfter time.Time } |
| func IdentityFromCert(c *x509.Certificate) (Identity, error) |
| -type Request struct{ Connect string; SNI string; Host string; Method, Path string; ALPN []string; ECH bool } |
| +type Request struct{ Connect, SNI, Host, Method, Path string; ALPN []string; ECH, Upgrade bool } |
| type Decision struct{ Allow bool; Reason string; Service hostedwire.Service } |
| -type Feed struct{ /* verified ProxyFeed + monotonic receipt time */ } |
| func (f *Feed) Decide(id Identity, r Request, mono time.Duration) Decision |
| -func VerifyFeed(raw []byte, sig []byte, pub ed25519.PublicKey) (hostedwire.ProxyFeed, error) |
| +func (f *Feed) Deadline(id Identity, mono time.Duration) time.Duration // earliest of cert NotAfter and feed expiry |
| +func Serve(ctx context.Context, cfg Config) error |
| +type Config struct{ Egress, Boot netip.AddrPort; ControllerURL string; ControllerKey ed25519.PublicKey; ControllerTLSPin string; KeyID hostedwire.KeyID; Key ed25519.PrivateKey; ClientCA *x509.CertPool; InterceptCA tls.Certificate; OriginRoots *x509.CertPool /* nil: system roots */; Log io.Writer } |
| ``` |
| |
| -Reasons are fixed strings: `stale_feed`, `unknown_launch`, `revoked`, `wrong_epoch`, `not_in_manifest`, `ip_literal`, `no_sni`, `ech`, `sni_mismatch`, `host_mismatch`, `bad_port`, `bad_method`, `bad_path`, `alpn`. Instance path class: `GET`/`POST` on `/api/runner/v2/` and its subpaths, `POST /api/hosted/enrol`, `POST /api/hosted/renew`; nothing else. |
| - |
| -- [ ] **Red:** `TestDecideTable` (one row per reason, plus the allowed row). `TestStaleFeedDeniesAll` (at TTL+1 ms on the monotonic clock; a wall clock jump forward or back changes nothing). `TestFeedSignature`. |
| -- [ ] **Green:** `go test ./internal/hostedproxy -run 'TestDecide|TestStaleFeed|TestFeedSignature' -count=1`. |
| -- [ ] **Mutations:** compare hosts case-insensitively by suffix; measure freshness on the wall clock. |
| -- [ ] **Commit:** `hostedproxy: decision core and signed feed`. |
| +Path classes, exact: `instance`: `GET /api/runner/stream` (WebSocket upgrade only), `GET /api/runner/protocol`, `POST /api/hosted/enrol`, `POST /api/hosted/challenge`, `POST /api/hosted/renew`; `cert_report`: `POST /v1/cert/report`. Reasons are fixed strings: `stale_feed`, `cert_expired`, `unknown_launch`, `revoked`, `wrong_epoch`, `not_in_manifest`, `ip_literal`, `no_sni`, `ech`, `sni_mismatch`, `host_mismatch`, `bad_port`, `bad_method`, `bad_path`, `alpn`, `redirect_refused`, `nested_tunnel`. |
| |
| -### Task 6: Proxy data path and bootstrap listener |
| +Egress listener: TLS requiring a client certificate from the controller CA; each tunnel is HTTP/1.1 `CONNECT host:443`; the proxy answers 200, terminates the inner TLS with a leaf for exactly that host minted from `InterceptCA` (ALPN `http/1.1` only), reads each request, applies `Decide` with CONNECT target, SNI, `Host`, method and path, and forwards over its own TLS to that exact host (SNI set, `OriginRoots`). A WebSocket upgrade is piped only after the same check. A 3xx naming another authority becomes 502. Every tunnel carries a timer at `Deadline`; at the deadline, or when a fresher feed revokes the identity, the tunnel and any piped WebSocket close. Bootstrap listener: server TLS only; `POST /redeem` (no client certificate) and `POST /renew` (requires the current client certificate, whose serial is sent), each forwarded to the controller under the proxy's signature. Decision log: one JSON line per decision with VM, launch, attempt, destination, method, path class, decision, reason, bytes in and out; never headers, bodies or tokens. `config.go` refuses wildcard listen addresses. |
| |
| -**Files:** Create `internal/hostedproxy/{egress.go,boot.go,origin.go,log.go,egress_test.go}`, `cmd/equipo-hosted-proxy/{main.go,config.go,config_test.go}`. |
| - |
| -**Interfaces:** `func Serve(ctx context.Context, cfg Config) error`; `Config{Egress, Boot netip.AddrPort; ControllerURL string; ControllerKey ed25519.PublicKey; ControllerTLSPin string; KeyID hostedwire.KeyID; Key ed25519.PrivateKey; ClientCA *x509.CertPool; InterceptCA tls.Certificate; Log io.Writer}`. |
| - |
| -Egress listener: TLS with a required client certificate from the controller CA; each tunnel is an HTTP/1.1 `CONNECT host:443`; the proxy answers 200, terminates the runner's inner TLS with a leaf for exactly that host minted from `InterceptCA` (ALPN `http/1.1` only), reads each request, applies `Decide` with CONNECT target, SNI, `Host` and path, then forwards to the origin over its own TLS to that exact host with system roots and SNI set. WebSocket upgrades are allowed only after the same check and are then piped. A 3xx whose `Location` names another authority becomes 502 `redirect_refused`. A feed change that revokes the identity closes its tunnels within one feed poll. Bootstrap listener: server TLS only, two routes (`POST /redeem`, `POST /renew`) forwarded to the controller with the proxy's own signature. Decision log: one JSON line per decision with VM, launch, attempt, destination, method, path class, decision, reason, bytes in and out; never headers, bodies or tokens. `config.go` refuses wildcard listen addresses, as the controller's does. |
| - |
| -- [ ] **Red:** `TestConfigRefusesWildcardListen`. `TestLogHasNoSecrets` (a request carrying `Authorization` and a body: neither appears in the log). `TestRevocationClosesTunnel`. `TestRedirectRefused`. |
| -- [ ] **Green:** `go test ./internal/hostedproxy ./cmd/equipo-hosted-proxy -run 'TestConfig|TestLogHasNoSecrets|TestRevocation|TestRedirect' -count=1`; `make build vet`. |
| -- [ ] **Mutations:** forward without the per-request `Host` check (Task 7's fronting rows fail); log the `Authorization` header. |
| +- [ ] **Red:** `TestDecideTable` (one row per reason, plus allowed rows for each path). `TestStaleFeedDeniesAll` (at lifetime + 1 ms on the monotonic clock; wall clock jumps change nothing). `TestConfigRefusesWildcardListen`. `TestLogHasNoSecrets`. `TestPathClassCoversRunner` (scans `internal/runner/...` and `internal/wire` for instance paths the hosted runner uses and fails if one is outside the `instance` class). |
| +- [ ] **Green:** `go test ./internal/hostedproxy ./cmd/equipo-hosted-proxy -run 'TestDecide|TestStaleFeed|TestConfig|TestLogHasNoSecrets|TestPathClass' -count=1`; `make build vet`. |
| +- [ ] **Mutations:** compare hosts by suffix; measure freshness on the wall clock; log the `Authorization` header. |
| - [ ] **Commit:** `hostedproxy: authenticated CONNECT proxy with origin TLS`. |
| |
| ### Task 7: Proxy end to end over real TLS |
| |
| -**Files:** Create `internal/hostedproxy/e2e_test.go`, `internal/hostedproxy/proxytest/{harness.go}`. |
| +**Files:** Create `internal/hostedproxy/e2e_test.go`, `internal/hostedproxy/proxytest/harness.go`. |
| |
| -**Interfaces:** `proxytest.Harness{Proxy, Origin, Other *httptest.Server; Controller *fakeController; Client func(id Identity) *http.Client}`, all on `127.0.0.1`. Origins use `httptest.NewTLSServer` with a test root the proxy trusts through a `Config.OriginRoots` override available only in tests. |
| +**Interfaces:** `proxytest.Harness{Proxy *hostedproxy.Server; Origin, Other *httptest.Server; Controller *FakeController; Clock *FakeMono}`, all on `127.0.0.1`. The client side is the real hosted transport from Task 12 once it exists; until then the harness's `Client(id)` builds the same `http.Transport`, and Task 12 replaces it (this test must still pass). |
| |
| -- [ ] **Red:** `TestFrontingMatrix`: allowed SNI with another `Host`; CONNECT to the allowed host then SNI of another; CONNECT to `127.0.0.1:443`, `[::1]:443`, the host on port 8443; no SNI; ALPN `h2` only; percent-encoded and userinfo authorities (`x@host`, `host%2Eexample`); absolute-form request URI naming another host; a WebSocket upgrade with another `Host`; a nested CONNECT inside the tunnel. Each refused with its reason, the origin sees nothing. Positive control: the allowed runner path succeeds, and a WebSocket echo works. `TestNoCertificate`, `TestCertFromOtherCA`, `TestReplayedCertAfterRevoke`, `TestWrongEpochCert`. `TestControllerDownThenStale` (the controller stops; requests pass until the feed is 5 min old on the monotonic clock, then all fail and open tunnels close). |
| -- [ ] **Green:** `go test ./internal/hostedproxy -run 'TestFronting|TestNoCertificate|TestCertFromOtherCA|TestReplayedCert|TestWrongEpoch|TestControllerDown' -count=1` within the 10 s package budget. |
| -- [ ] **Mutations:** accept `h2` in ALPN; skip the revoked-serial check. Each fails a named row. |
| -- [ ] **Commit:** `hostedproxy: fronting, revocation and staleness tests over TLS`. |
| +- [ ] **Red:** `TestFrontingMatrix`: allowed SNI with another `Host`; CONNECT to the allowed host then SNI of another; CONNECT to `127.0.0.1:443`, `[::1]:443`, the host on 8443; no SNI; ALPN `h2` only; `x@host` and `host%2Eexample`; an absolute-form URI naming another host; a WebSocket upgrade with another `Host`; a nested CONNECT. Each refused with its reason; the origin sees nothing. Positive control: the allowed runner path succeeds and a WebSocket round trip works. `TestNoCertificate`, `TestCertFromOtherCA`, `TestReplayedCertAfterRevoke`, `TestWrongEpochCert`. `TestOpenSocketClosesAtCertExpiry` (an upgraded WebSocket open across `NotAfter` is closed at it). `TestPartitionedProxy` (the controller is up but the proxy cannot reach it: open sockets close at the feed's expiry, new requests fail with `stale_feed`). `TestRenewalReplayRefused` (a captured renewal replayed through the bootstrap listener is refused). |
| +- [ ] **Green:** `go test ./internal/hostedproxy -run 'TestFronting|TestNoCertificate|TestCertFromOtherCA|TestReplayedCert|TestWrongEpoch|TestOpenSocket|TestPartitioned|TestRenewalReplay' -count=1` within the 10 s package budget. |
| +- [ ] **Mutations:** accept `h2`; skip the tunnel deadline timer. Each fails a named row. |
| +- [ ] **Commit:** `hostedproxy: fronting, expiry and revocation tests over TLS`. |
| |
| ## Phase C: the VM side (spec §3, §4, §7) |
| |
| ### Task 8: Root init and the lifecycle hooks |
| |
| -**Files:** Create `internal/vminit/{init.go,hooks.go,mounts_linux.go,reap_linux.go,init_test.go}`, `cmd/equipo-vm-init/main.go`. |
| +**Files:** Create `internal/vminit/{init.go,hooks.go,measure.go,mounts_linux.go,reap_linux.go,rootprobe_linux.go,init_test.go}`, `cmd/equipo-vm-init/main.go`. |
| |
| -**Interfaces:** `func Main(ctx context.Context, cfg Config) error`; `Config{HookAddr netip.AddrPort; RunnerUser string; RunnerBinary string; StateDir string; Mounts MountPlan}`; hook handlers for `POST /aws/lambda-microvms/runtime/v1/run`, `/resume`, `/suspend`, `/terminate` on the image's `hooks.port` (awsjob `doc.go` facts). `/run`: parse `{"microvmId","runHookPayload"}`, decode `BootstrapV2`, refuse if the runner state directory is not empty, write the bootstrap and the VM ID to a 0600 file owned by the runner user, start `equipo-runner hosted-run` as that user with no capabilities and an environment of exactly `HOME`, `PATH`, `TMPDIR`, `EQUIPO_HOSTED_BOOTSTRAP`, then return 200. `/ready` (image build only) fails unless the state directory is empty. `/suspend` and `/resume` answer 409 (S2-6). `/terminate` signals the runner and returns. Root init replaces the managed resolver mounts with an empty `resolv.conf`, overlays `/etc` from the image's copy, and reaps orphans as PID 1's child reaper. |
| +**Interfaces:** `func Main(ctx context.Context, cfg Config) error`; `Config{HookAddr netip.AddrPort; RunnerUser, RunnerBinary, StateDir, ResultsDir string; Mounts MountPlan}`. Hooks on the image's `hooks.port` (awsjob `doc.go`): `POST /aws/lambda-microvms/runtime/v1/run`, `/resume`, `/suspend`, `/terminate`. `/run`: parse `{"microvmId","runHookPayload"}`, decode `BootstrapV2`, refuse if the runner state directory is not empty, measure the runner binary, itself and the policy files (`measure.go`: SHA-256, written root-owned and read-only to `ResultsDir/measured.json`), and for `certification` also run the root-before-drop probes into `ResultsDir/root.json`; write the bootstrap and VM ID to a 0600 file owned by the runner user; start `equipo-runner hosted-run` (checks) or `equipo-runner hosted-certify` (certification) as that user with no capabilities, `NoNewPrivs`, and an environment of exactly `HOME`, `PATH`, `TMPDIR`, `EQUIPO_HOSTED_BOOTSTRAP`, `EQUIPO_HOSTED_RESULTS`; return 200. `/ready` (image build only) fails unless the state directory is empty. `/suspend` and `/resume` answer 409 (S2-6). `/terminate` signals the runner. Root init replaces the managed resolver mounts with an empty `resolv.conf`, overlays `/etc` from the image's copy, and reaps orphans. |
| |
| -- [ ] **Red:** `TestRunHookWritesBootstrapOnce` (a second `/run` is refused). `TestRunHookRefusesStateLeft`. `TestRunnerEnvironmentExact`. `TestMountPlanEmptiesResolver` (pure plan function over a fake FS). `TestSuspendRefused`. `TestRunnerDropsCapabilities` (plan: `SysProcAttr` with the user's uid and gid, `AmbientCaps` empty, `NoNewPrivs`). |
| +- [ ] **Red:** `TestRunHookOnce` (a second `/run` is refused). `TestRunHookRefusesStateLeft`. `TestRunnerEnvironmentExact`. `TestPurposeSelectsSubcommand`. `TestMeasurementsRootOwned`. `TestMountPlanEmptiesResolver` (plan function over a fake FS). `TestSuspendRefused`. `TestRunnerDropsCapabilities` (`SysProcAttr`: the runner's uid and gid, empty `AmbientCaps`, `NoNewPrivs`). |
| - [ ] **Green:** `go test ./internal/vminit -count=1`; `GOOS=linux go build ./cmd/equipo-vm-init`. |
| -- [ ] **Mutations:** accept a second `/run`; pass the parent environment through. |
| -- [ ] **Commit:** `vminit: root init, lifecycle hooks and the runner launch`. |
| +- [ ] **Mutations:** accept a second `/run`; pass the parent environment through; measure after the drop. |
| +- [ ] **Commit:** `vminit: root init, measurements, hooks and the runner launch`. |
| |
| -### Task 9: The image build |
| +### Task 9: The network audit accepts exactly the peered topology |
| |
| -**Files:** Create `internal/hostedimage/{manifest.go,build.go,manifest_test.go,build_test.go}`, `cmd/equipo-hosted-image/main.go`, `infra/hosted/image/{manifest.json,Dockerfile.tmpl}`. Modify `internal/isolatedjob/providerguard_test.go`, `.amadan/ci.d/` (secret scan of the image inputs), `Makefile` (`hosted-image-check`). |
| +**Files:** Modify `internal/isolatedjob/awsjob/network.go` (`onlyLocal` at `:198`, the audit), `network_test.go`, `internal/isolatedjob/isolatedjob.go` (`NetworkAudit`), `cmd/equipo-hosted-controller/config.go`. |
| |
| -**Interfaces:** `Manifest{RunnerRelease, RunnerSHA256, VMInitSHA256, BubblewrapSHA256, GoToolchain, GoToolchainSHA256, GitSHA256 string; Packages []Pinned}`; `func Build(m Manifest, out string) (Inventory, error)` writes a byte-reproducible zip (sorted entries, fixed times and modes) for `create-microvm-image`; `Inventory{ZipSHA256 string; Files map[string]string}`; `func (i Inventory) Digest() isolatedjob.ImageDigest`. The image holds no token, key, code, OAuth home, forge credential, person's configuration or repository (spec §4). The Go toolchain is the one the runner's checks use (`GOROOT=/opt/go`). |
| +**Interfaces:** `awsjob.Config` gains `PeeringID string; ProxyRoutes []netip.Prefix` (each a `/32`). The VM subnet's route table may hold the local route and, for each configured prefix, exactly one route to it via `PeeringID`; any other route, a different peering, a prefix wider than `/32`, or a missing proxy route fails the audit. The peering itself must be `active`, between the configured VPCs, in this account. The connector check keeps one VM subnet (`network.go:112`). |
| |
| -- [ ] **Red:** `TestBuildReproducible` (two builds, identical bytes). `TestManifestPinsEverything` (an unpinned package or an empty digest is refused). `TestImageInputsHaveNoSecrets` (runs the repo's gitleaks config over the build context). `TestProviderTypesStayInAdapter` updated for the new commands. |
| -- [ ] **Green:** `go test ./internal/hostedimage ./internal/isolatedjob -run 'TestBuild|TestManifest|TestImageInputs|TestProviderTypes' -count=1`; `make hosted-image-check`. |
| -- [ ] **Mutations:** use the file's own mtime in the zip; let an empty digest through. |
| -- [ ] **Commit:** `hostedimage: pinned, reproducible MicroVM image build`. |
| +- [ ] **Red:** `TestAuditAcceptsPinnedPeering`. `TestAuditRefusesOtherPeeringRoute` (a `/24` over the same peering; a `/32` to an address that is not a proxy; a second peering). `TestAuditRefusesMissingProxyRoute`. `TestAuditRefusesInactivePeering`. The existing audit tests still pass. |
| +- [ ] **Green:** `go test ./internal/isolatedjob/... -run 'TestAudit' -count=1`. |
| +- [ ] **Mutation:** accept any route via the peering. |
| +- [ ] **Commit:** `awsjob: audit the VM subnet's routes to the proxies over one peering`. |
| |
| -### Task 10: Certification run, report and offline signing |
| +### Task 10: The image build and publish tool |
| |
| -**Files:** Create `internal/hostedcert/{matrix.go,probe_linux.go,report.go,matrix_test.go,report_test.go}`, `internal/hostedctl/{certreport.go,certreport_test.go}`, `cmd/equipo-hosted-certify/main.go`. |
| +**Files:** Create `internal/hostedimage/{manifest.go,build.go,publish.go,manifest_test.go,build_test.go,publish_test.go}`, `cmd/equipo-hosted-image/main.go`, `infra/hosted/image/{manifest.json,Dockerfile.tmpl}`. Modify `internal/isolatedjob/providerguard_test.go`, `.amadan/ci.d/` (secret scan of the image inputs), `Makefile` (`hosted-image-check`). |
| |
| -**Interfaces:** the runner subcommand `equipo-runner hosted-certify` (Task 11 wires it) runs `hostedcert.Probes()` and posts `Report{LaunchID, Image, Results []ProbeResult; Containment string}` to `POST /v1/cert/report` through the proxy (the certification launch's one service is the controller's report host). Controller: `GET /v1/cert/reports/{launch}` (operator). Signer, offline: `equipo-hosted-certify sign -report r.json -snapshot s.json -key <file>` prints a `Certificate` only if `hostedcert.Judge(report, Matrix())` passes. The expected outcome of every probe lives in `Matrix()` in the signer, never in the report (1b finding). |
| +**Interfaces:** `Manifest{RunnerRelease, RunnerSHA256, VMInitSHA256, BubblewrapSHA256, GoToolchain, GoToolchainSHA256, GitSHA256, CodexSHA256, ContainmentTestSHA256 string; Packages []Pinned}`. The image carries the codex binary and the release's `containment.test` because certification runs the whole containment suite (spike: 5 tests need codex). `func Build(m Manifest, out string) (Inventory, error)` writes a byte-reproducible zip (sorted entries, fixed times and modes) with `hooks.port`, `X86_64` and `additionalOsCapabilities: ["ALL"]`; `Inventory{ZipSHA256 string; Files map[string]string}`; `func (i Inventory) Digest() isolatedjob.ImageDigest`. Subcommands: `build`, `list`, `publish`, `delete`, `connector-wait`; the AWS ones carry livectl's guards (static credentials resolved once, the account and region given as flags and checked by STS before any other call, one attempt per call, bounded waits, names with the given prefix only). The image holds no token, key, code, OAuth home, forge credential, person's configuration or repository (spec §4). |
| |
| -Probes (each from the sandbox unless marked): direct IPv4 and IPv6 to a public address, each managed resolver address, the metadata endpoint, the proxy egress port without a certificate, the proxy bootstrap port, a DNS query, a build script and `go mod download` with an empty cache; root-before-drop probes (marked): VPC DNS answers nothing, no AWS credential at the metadata endpoint, `resolv.conf` empty; runner-user probes (marked): cannot write `resolv.conf`, cannot gain capabilities, cannot reach the proxy bootstrap with a used code; positive controls: the runner reaches the report host through the proxy, the containment suite passes (`containment.test -test.skip '^TestSource'`, 79 tests, with the codex binary present), and the sandbox can read the Go tree. |
| - |
| -- [ ] **Red:** `TestJudgeUsesTrustedMatrix` (a report claiming "expected" for a failing probe still fails). `TestJudgeNeedsEveryProbe`. `TestJudgeNeedsPositiveControls`. `TestReportRouteLaunchBound` (a report for another launch is refused). `TestSignerRefusesFailingReport`. |
| -- [ ] **Green:** `go test ./internal/hostedcert ./internal/hostedctl -run 'TestJudge|TestReportRoute|TestSigner' -count=1`. |
| -- [ ] **Mutations:** read expected outcomes from the report; skip one positive control. |
| -- [ ] **Commit:** `hostedcert: certification matrix, report route and offline signer`. |
| +- [ ] **Red:** `TestBuildReproducible`. `TestManifestPinsEverything`. `TestImageInputsHaveNoSecrets`. `TestPublishRefusesOtherAccount` (STS answers another account: no further call). `TestPublishRefusesForeignName`. `TestProviderTypesStayInAdapter` updated. |
| +- [ ] **Green:** `go test ./internal/hostedimage ./internal/isolatedjob -run 'TestBuild|TestManifest|TestImageInputs|TestPublish|TestProviderTypes' -count=1`; `make hosted-image-check`. |
| +- [ ] **Mutations:** use file mtimes in the zip; skip the account check. |
| +- [ ] **Commit:** `hostedimage: reproducible image build and a guarded publish tool`. |
| |
| ## Phase D: the hosted runner (spec §5, §8) |
| |
| -### Task 11: Hosted bootstrap, proxy certificate and enrolment in the runner |
| +### Task 11: A shared gate contract and the base-gate flow, out of `thin` |
| |
| -**Files:** Create `internal/runner/hosted/{bootstrap.go,redeem.go,enrol.go,dial.go,hosted_test.go}`. Modify `cmd/equipo-runner/main.go` (subcommands `hosted-run`, `hosted-certify`), `internal/runner/thin/link.go` (token source), `.rastrillo/budgets.txt`. |
| +**Files:** Create `internal/runner/gate/{gate.go,gate_test.go}`, `internal/runner/checkrun/{run.go,run_test.go}`. Modify `internal/runner/thin/worker.go:26` (`GateRunner` becomes `gate.Runner`), `judge.go:240-360` (the base-gate preparation and the run move to `checkrun`), `worker_checks.go`, `run.go:875` (termination kind and record conversion come from the worker setup), `.rastrillo/budgets.txt` (thin shrinks). |
| |
| **Interfaces:** |
| |
| ```go |
| -func ReadBootstrap(path string) (hostedwire.BootstrapV2, string /*vmRef*/, error) // then deletes the file |
| -type Session struct{ /* key, cert, bearer, epoch */ } |
| -func Start(ctx context.Context, b hostedwire.BootstrapV2, vmRef string, state string) (*Session, error) // redeem, then enrol |
| -func (*Session) Dialer() func(ctx context.Context, network, addr string) (net.Conn, error) // CONNECT via a proxy, failover to the second |
| -func (*Session) Token() string // current bearer |
| -// thin.Link gains: TokenSource func() string; Dial func(ctx, network, addr) (net.Conn, error) |
| +// gate (a leaf package; imports wire and checks only) |
| +type Result struct{ Output, Reason string; Code int; Terminated bool; Sandbox string; Evidence *checks.Evidence } |
| +type Runner interface { |
| + Sandbox() string |
| + Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(id string) error) Result |
| + Verify(id string) bool |
| +} |
| +// checkrun |
| +type Inputs struct{ Workspace, BaseSHA, CandidateSHA string; GoRoot, ModuleCache string; Limit time.Duration } |
| +type Outcome struct{ Checks, BaseChecks, Reason, Output string; BaseChecksSHA string; Sandbox string; Evidence *checks.Evidence } |
| +func Run(ctx context.Context, g gate.Runner, repo checks.Repo, in Inputs) Outcome // base gates from BaseSHA, dependency stage, needs_network mapping |
| +// thin |
| +type WorkerKind struct{ Gate gate.Runner; Termination string; Record func(id string) (string, error) } |
| +// Options gains HostedWorker *WorkerKind, set only by cmd/equipo-runner (thin never imports linuxworker) |
| +``` |
| + |
| +- [ ] **Red:** `TestPrimaryChecksUnchanged` (the existing primary checks tests run through `checkrun` with unchanged outputs, including the primary-only `BaseChecks` handling the instance reads at `tasks.go:1831`). `TestMacWorkerUnchanged` (the Mac worker still reports `TerminationProcessGroup`). |
| +- [ ] **Green:** `go test ./internal/runner/gate ./internal/runner/checkrun ./internal/runner/thin -run 'TestPrimaryChecks|TestMacWorker|TestChecks|TestWorker' -count=1`; `make build vet`. |
| +- [ ] **Commit:** `runner: move the gate contract and base-gate checks out of thin`. |
| + |
| +### Task 12: The hosted transport, bootstrap and enrolment in the runner |
| + |
| +**Files:** Create `internal/runner/hosted/{bootstrap.go,redeem.go,enrol.go,transport.go,hosted_test.go}`. Modify `cmd/equipo-runner/main.go` (subcommands `hosted-run`, `hosted-certify`), `internal/runner/thin/link.go:73,652` (token source and HTTP client), `.rastrillo/budgets.txt`. |
| + |
| +**Interfaces:** |
| + |
| +```go |
| +func ReadBootstrap(path string) (hostedwire.BootstrapV2, isolatedjob.Ref, error) // then deletes the file |
| +type Session struct{ /* machine key, proxy key and cert, bearer, epoch, deadline */ } |
| +func Start(ctx context.Context, b hostedwire.BootstrapV2, vm isolatedjob.Ref, state string) (*Session, error) // redeem, then enrol |
| +func (*Session) HTTPClient() *http.Client // Transport: no environment proxy; DialTLSContext opens mTLS to a proxy (failover to the second), sends CONNECT host:443, then TLS with RootCAs = the intercept CA alone (its SPKI must match ProxyCAPin), ServerName = host, NextProtos = ["http/1.1"] |
| +func (*Session) Token() string |
| +// thin.Link gains: TokenSource func() string; HTTPClient *http.Client (passed to websocket.DialOptions) |
| ``` |
| |
| -`Link` reads `TokenSource()` on every dial instead of the copy made at startup (spec §5); a nil `TokenSource` keeps today's behaviour. The runner key is ECDSA P-256 for the proxy CSR and ed25519 for the machine key, both generated in `/run`'s process, never written outside the state directory. |
| +`Link` reads `TokenSource()` on every dial instead of the copy made at startup (spec §5); nil keeps today's behaviour. Keys are generated in the runner process and never leave its state directory. |
| + |
| +- [ ] **Red:** `TestLinkReadsTokenEachDial`. `TestLinkUsesGivenHTTPClient`. `TestReadBootstrapDeletesFile`. `TestTransportFailsOver`. `TestTransportPinsInterceptCA` (a proxy presenting another CA: refused). `TestEnrolSendsVMRefAndKey`. `TestNoDirectDial` (with both proxies down the session never dials the instance directly). `TestRealLinkThroughProxy` (the real `Link` reaches a fake instance's `/api/runner/stream` through Task 6's proxy over TLS; it replaces the harness client in Task 7). |
| +- [ ] **Green:** `go test ./internal/runner/hosted ./internal/runner/thin ./internal/hostedproxy -run 'TestLinkReads|TestLinkUses|TestReadBootstrap|TestTransport|TestEnrolSends|TestNoDirectDial|TestRealLink|TestFronting' -count=1`; `make build vet` (darwin vet included). |
| +- [ ] **Mutations:** copy the token once; trust system roots for the inner TLS. |
| +- [ ] **Commit:** `runner: hosted transport through the proxy, bootstrap and enrolment`. |
| |
| -- [ ] **Red:** `TestLinkReadsTokenEachDial` (rotate the token between two dials; the second handshake carries the new one). `TestReadBootstrapDeletesFile`. `TestDialerFailsOver` (first proxy refuses the TCP connect, second works). `TestEnrolSendsVMRefAndKey`. `TestNoPlainDialInHostedMode` (the session never dials without the proxy). |
| -- [ ] **Green:** `go test ./internal/runner/hosted ./internal/runner/thin -run 'TestLinkReadsToken|TestReadBootstrap|TestDialer|TestEnrolSends|TestNoPlainDial' -count=1`; `make build vet` (darwin vet included). |
| -- [ ] **Mutations:** copy the token once at `Link` construction; dial the instance directly when both proxies fail. |
| -- [ ] **Commit:** `runner: hosted bootstrap, proxy certificate and enrolment`. |
| +### Task 13: Certification run, evidence and offline signing |
| |
| -### Task 12: Token renewal |
| +**Files:** Create `internal/hostedcert/{matrix.go,probe_linux.go,evidence.go,judge.go,matrix_test.go,judge_test.go}`, `internal/hostedctl/ctlcert/{report.go,report_test.go}`, `cmd/equipo-hosted-certify/main.go`. Modify `cmd/equipo-runner/main.go` (`hosted-certify`). |
| + |
| +**Interfaces:** |
| +- Runner (`hosted-certify`, as the runner user): runs the user and sandbox probes, reads `root.json` and `measured.json` from `EQUIPO_HOSTED_RESULTS`, and posts `Report{LaunchID string; Root, User, Sandbox []ProbeResult; Measured map[string]string; Containment ContainmentResult}` to `POST /v1/cert/report` through the proxy (the launch's one service). |
| +- Controller (`ctlcert/report.go`): accepts a report only from a client certificate of a live `certification` launch with that launch ID, once; wraps it in `Evidence{EvidenceID, LaunchID string; Image isolatedjob.ImageDigest; ImageVersion string; ProxyPolicy int; Deployment []string; Report Report; ReceivedNS int64}`, where every field but `Report` comes from the controller's own launch record and config, and signs it with the controller key. `GET /v1/cert/evidence/{launch}` (operator) returns it. Then it stops the VM with proof. |
| +- `equipo-hosted-certify`: `launch` (Task 5's route; waits for the evidence), `judge -evidence e.json -release r.json` (verifies the controller's signature; checks `Measured` equals the release manifest's runner, vm-init and policy digests; runs `Judge(report, Matrix())`; writes `snapshot.json` derived from the evidence alone), `sign -evidence e.json -release r.json -key <file>` (repeats `judge` and signs the derived snapshot; there is no snapshot input to substitute), `verify`, `reload`, `alert-test`. |
| + |
| +Probes, each from its stage. Root, before the drop: VPC DNS answers nothing at each managed resolver address; the metadata endpoint gives no credential; `resolv.conf` is empty. User: cannot write `resolv.conf`; cannot gain a capability; a used proxy code is refused at the bootstrap listener. Sandbox: direct IPv4 and IPv6 to a public address, each managed resolver, the metadata endpoint, the proxy egress port without a certificate, the proxy bootstrap port, a DNS query, a build script and `go mod download` with an empty cache, all failing. Positive controls: the runner reaches the report host through the proxy; the containment suite passes in full (`containment.test -test.skip '^TestSource'`); the sandbox reads the Go tree. Expected outcomes live only in `Matrix()`. |
| + |
| +- [ ] **Red:** `TestJudgeUsesTrustedMatrix` (a report claiming success for a failing probe still fails). `TestJudgeNeedsEveryProbe`. `TestJudgeNeedsPositiveControls`. `TestEvidenceFromLaunchRecord` (a report naming another image or launch cannot change the evidence's image). `TestReportOncePerLaunch`. `TestSignRefusesMeasuredMismatch` (evidence whose measured runner digest differs from the release's: refused). `TestSignHasNoSnapshotInput`. `TestEvidenceSignatureChecked`. |
| +- [ ] **Green:** `go test ./internal/hostedcert ./internal/hostedctl/... ./cmd/equipo-hosted-certify -run 'TestJudge|TestEvidence|TestReportOnce|TestSign' -count=1`. |
| +- [ ] **Mutations:** take the image from the report; skip the measured-digest comparison; skip one positive control. |
| +- [ ] **Commit:** `hostedcert: certification evidence, trusted matrix and offline signer`. |
| + |
| +### Task 14: Token renewal and expiry in the runner |
| |
| **Files:** Create `internal/runner/hosted/{renew.go,renew_test.go}`. |
| |
| -**Interfaces:** `func (*Session) Run(ctx context.Context, clock func() time.Time) error` renews the bearer (1 h) and the proxy certificate (15 min) at half their lifetime, installs each atomically, and on a renewal failure cancels the work context, reports `token_renewal_failed` once if the link is up, and returns `ErrRenewal`; `hosted-run` exits non-zero and the instance stops the VM (Task 18). |
| +**Interfaces:** `func (*Session) Run(ctx context.Context, clock func() time.Time) error` renews the bearer (Task 22's challenge, then renew) and the proxy certificate (`/renew` on the bootstrap listener over the current certificate) at half their lifetime, installs each atomically, never past the job deadline, and on a failure cancels the work context, reports `token_renewal_failed` if the link is up, and returns `ErrRenewal`; `hosted-run` exits non-zero and the instance stops the VM. |
| |
| -- [ ] **Red:** `TestRenewAtHalfLife`. `TestRenewalFailureStopsWork` (no further dial after the failure). `TestStepPastFifteenMinutesAndAnHour` (a fake clock drives a step through four certificate renewals and one bearer renewal; the link never presents an expired credential). |
| -- [ ] **Green:** `go test ./internal/runner/hosted -run 'TestRenew|TestStepPast' -count=1`. |
| -- [ ] **Mutations:** keep working after a failed renewal; renew at expiry. |
| +- [ ] **Red:** `TestRenewAtHalfLife`. `TestRenewalFailureStopsWork`. `TestStepPastFifteenMinutesAndAnHour` (a fake clock drives a step through renewals; the link never presents an expired credential). `TestNoRenewalPastDeadline`. |
| +- [ ] **Green:** `go test ./internal/runner/hosted -run 'TestRenew|TestStepPast|TestNoRenewal' -count=1`. |
| +- [ ] **Mutations:** keep working after a failed renewal; renew past the deadline. |
| - [ ] **Commit:** `runner: renew hosted bearer and proxy certificate at half life`. |
| |
| -### Task 13: The dependency bundle |
| +### Task 15: The hosted pack carries the base and the candidate |
| + |
| +**Files:** Modify `internal/runner/thin/relay.go:494` (`packCommits`), `relay.go:199` (`inboundHeader`), `internal/runner/thin/worker_checks.go`, `internal/equipo/chat/tasks.go` (the send-pack command for hosted steps), `internal/wire/runners.go` (`SendPackCommand`), `.rastrillo/budgets.txt`. Create `internal/runner/thin/hosted_pack_test.go`. |
| |
| -**Files:** Create `internal/runner/depsbundle/{build.go,stage.go,gosum.go,depsbundle_test.go}`. Modify `internal/runner/thin/relay.go` (send the bundle after the pack for hosted steps; budget record). |
| +**Interfaces:** `TransferKindHostedPack`'s header lists `Commits = [BaseSHA, CandidateSHA]`; the primary packs both commits' trees and blobs, no history. The hosted worker indexes it into an empty object store and requires both commits present before checkout; a missing one ends the step `cannot_run` with reason `pack_incomplete`. `inboundHeader` selects by attempt **and kind**; each transfer has its own ID created by the instance. |
| + |
| +- [ ] **Red:** `TestHostedPackHasBaseAndCandidate`. `TestEmptyStoreGetsBothCommits`. `TestMissingBaseRefused`. `TestInboundSelectsByKind` (a `deps` and a `hosted_pack` transfer for one attempt are never confused). |
| +- [ ] **Green:** `go test ./internal/runner/thin ./internal/equipo/chat -run 'TestHostedPack|TestEmptyStore|TestMissingBase|TestInboundSelects' -count=1`. |
| +- [ ] **Mutation:** select the inbound transfer by attempt alone. |
| +- [ ] **Commit:** `runner: hosted checks pack carries the base and the candidate`. |
| + |
| +### Task 16: The dependency bundle |
| + |
| +**Files:** Create `internal/runner/depsbundle/{build.go,stage.go,gosum.go,depsbundle_test.go}`. Modify `internal/runner/thin/relay.go` (send the bundle after the hosted pack). |
| |
| **Interfaces:** |
| |
| ```go |
| -func Build(ctx context.Context, cache string, modules []Module, limit int64) (Bundle, error) // primary side |
| type Module struct{ Path, Version string } |
| +func ModulesFor(base, candidate fs.FS) (want []Module, err error) // primary: every requirement of every go.mod in either tree, vendored modules skipped |
| +func Build(ctx context.Context, cache string, want []Module, limit int64) (Bundle, error) // .zip, .mod, .info from cache/download only |
| type Bundle struct{ Digest string; Size int64; Files []File; Missing []Module } |
| -func ModulesFor(tree fs.FS) ([]Module, error) // every go.mod's requirements and go.sum lines, vendored modules skipped (as GoModuleDirs does) |
| -func Stage(ctx context.Context, b []byte, sums []SumLine, dir string) (Staged, error) // worker side, outside the sandbox |
| +func Pins(base fs.FS) (map[Module]Pin, error) // h1: lines from the BASE tree's go.sum files only |
| +func Conflicts(base, candidate fs.FS) ([]Module, error) // candidate lines that change a base pin |
| +func Stage(ctx context.Context, bundle io.Reader, pins map[Module]Pin, dir string, limits Limits) (Staged, error) |
| +type Limits struct{ Bundle, Expanded int64; Files int } // 256 MiB, 2 GiB, 200000 |
| type Staged struct{ Dir string; Missing []Module } |
| -var ErrHashMismatch, ErrTooLarge error |
| -const DefaultLimit = 512 << 20 |
| +var ErrHashMismatch, ErrTooLarge, ErrUnsafePath error |
| ``` |
| |
| -The bundle holds `cache/download/<module>/@v/<version>.{zip,mod,info}` only. `Stage` verifies each `.zip` and `.mod` against the `h1:` lines from both the base and the candidate trees' `go.sum` (a module listed in neither is not staged), writes into a fresh directory, makes it read-only, and returns what was missing. The check sandbox then mounts it as `/opt/go-mod`. Over the limit, the primary sends nothing and the step ends `cannot_run` `needs_network` with reason `deps_too_large`. |
| +`Stage` runs outside the sandbox: for each module with a base pin it verifies the `.mod` and the `.zip` against the pin, extracts the zip with `golang.org/x/mod/zip.Unzip` (which refuses unsafe paths and symlinks) into `Dir/<module>@<version>`, writes the `cache/download` files, enforces `Limits`, and makes the tree read-only. A module the bundle lacks, or one the base does not pin, goes in `Missing`. The worker ends the step: conflicts give `cannot_run` `deps_conflict`; `Missing` gives `cannot_run` `needs_network` with `deps_new_module` or `deps_missing`; over a limit gives `deps_too_large`. |
| |
| -- [ ] **Red:** `TestBundleRoundTrip`. `TestBundleRefusesHashMismatch` (a tampered zip is not staged; a tampered `.mod` the same). `TestBundleUnlistedModuleDropped`. `TestBundleTooLarge`. `TestStagedReadOnly`. `TestMissingModuleIsNeedsNetwork` (with Task 14's gate: a module absent from the bundle gives `needs_network`, not `failed`). |
| +- [ ] **Red:** `TestBundleRoundTrip`. `TestBasePinWins` (the candidate's `go.sum` changes a base pin; bytes matching the candidate's line: refused as a conflict). `TestNewModuleNotStaged`. `TestBundleRefusesHashMismatch`. `TestUnsafeZipRefused` (a `../` path and a symlink entry). `TestExpandedLimit`. `TestStagedReadOnly`. `TestOfflineBuildFromEmptyCache` (a fixture module with one dependency builds with `GOPROXY=off GOFLAGS=-mod=mod GOMODCACHE=<staged>` and nothing else). |
| - [ ] **Green:** `go test ./internal/runner/depsbundle -count=1`. |
| -- [ ] **Mutations:** skip the hash check; stage a module listed in no `go.sum`. |
| -- [ ] **Commit:** `runner: verified dependency bundle from the primary`. |
| +- [ ] **Mutations:** accept the candidate's pin; write zip entries directly instead of through `Unzip`. |
| +- [ ] **Commit:** `runner: dependency bundle verified against base pins`. |
| |
| -### Task 14: The Linux checks worker |
| +### Task 17: The Linux checks worker |
| |
| -**Files:** Create `internal/runner/linuxworker/{gate.go,checks.go,worker_test.go}`, `internal/runner/checkrun/{run.go,run_test.go}` (the dependency stage, base-gate certification and `needs_network` mapping moved out of `thin.Engineer.checks`, `judge.go:295-360`, so the primary and the hosted worker share one implementation). Modify `internal/runner/thin/run.go` (start `runWorker` on Linux when the credential's role is `worker` and the runner was started by `hosted-run`), `judge.go`, `worker_checks.go`, `.rastrillo/budgets.txt`. |
| +**Files:** Create `internal/runner/linuxworker/{gate.go,worker.go,worker_test.go}`. Modify `cmd/equipo-runner/main.go` (sets `thin.Options.HostedWorker`), `internal/runner/thin/run.go:136-166` (a `worker` credential on Linux runs `runWorker` only with `HostedWorker` set; otherwise it refuses to start), `.rastrillo/budgets.txt`. |
| |
| -**Interfaces:** |
| +**Interfaces:** `func NewGate(m *containment.Manager, goRoot string, staged func(attempt string) (string, error)) gate.Runner` (`Sandbox()` returns `wire.SandboxBubblewrap`); `func Kind(m *containment.Manager, goRoot string, staged func(attempt string) (string, error)) *thin.WorkerKind` with `Termination: wire.TerminationNamespace` and the containment record conversion. The hosted worker's checks path: await the hosted pack and the bundle; index; checkout; `depsbundle.Conflicts` and `Stage`; `checkrun.Run` with base gates from BaseSHA; report `ChecksSandbox = bubblewrap`, `BaseChecks`, and `BaseChecksSHA` only when the base-gate run certified. |
| |
| -```go |
| -// checkrun |
| -type Inputs struct{ Workspace, BaseSHA, CandidateSHA string; GoRoot, ModuleCache string; Gates []provider.Mount; Limit time.Duration } |
| -type Result struct{ Outcome string; Reason string; Output string; Certified bool; Sandbox string; Evidence *checks.Evidence } |
| -func Run(ctx context.Context, m Starter, in Inputs, record func(context.Context, string) error) Result |
| -// linuxworker |
| -func NewGate(m *containment.Manager, goRoot string, staged func(attempt string) (string, error)) thin.GateRunner // Sandbox() returns wire.SandboxBubblewrap |
| -``` |
| - |
| -The hosted worker's `checks` path now runs: await pack and bundle, index, checkout, stage the bundle (Task 13), `checkrun.Run` with base gates read from BaseSHA, `TerminationKind = wire.TerminationNamespace`, `ChecksSandbox = bubblewrap`, `BaseChecksSHA` set only when the base-gate run certified. A Linux runner whose role is `worker` but that was not started by `hosted-run` refuses to start (today it silently runs the primary path; runner survey, `run.go:166`). |
| - |
| -- [ ] **Red:** `TestPrimaryChecksUnchanged` (the existing primary checks tests pass through `checkrun`, unchanged outputs). `TestHostedBaseGatesFromBase` (a candidate that edits `.equipo/gates.json` still runs the base gates; `BaseChecksSHA` set only on a base pass). `TestHostedChecksNamespaceProof` (`TerminationNamespace`, the record ID written before launch). `TestLinuxWorkerRoleRefusedOutsideHosted`. `TestHostedChecksOffline` (inside the sandbox a probe to `127.0.0.1:<proxy port>` and to a public address both fail). |
| -- [ ] **Green:** `go test ./internal/runner/checkrun ./internal/runner/linuxworker ./internal/runner/thin -run 'TestPrimaryChecks|TestHosted|TestLinuxWorker|TestChecks' -count=1`; on docs-t1 `make runner-namespace-test`. |
| +- [ ] **Red:** `TestHostedBaseGatesFromBase` (a candidate that edits `.equipo/gates.json` still runs the base gates; `BaseChecksSHA` set only on a base pass). `TestHostedChecksNamespaceProof` (`TerminationNamespace`; the record ID written before launch). `TestHostedRestartProof` (the runner restarts mid-check: recovery proves the namespace ended before reporting). `TestHostedCancel` (a cancelled step stops the sandbox with proof). `TestLinuxWorkerRefusedOutsideHosted`. `TestHostedChecksOffline` (from inside the sandbox, the proxy port and a public address both fail). |
| +- [ ] **Green:** `go test ./internal/runner/linuxworker ./internal/runner/thin -run 'TestHosted|TestLinuxWorker' -count=1`; on docs-t1 `make runner-namespace-test`. |
| - [ ] **Mutations:** read gates from the candidate tree; set `BaseChecksSHA` on a candidate-gate pass. |
| - [ ] **Commit:** `runner: Linux checks worker on the containment manager`. |
| |
| ## Phase E: the instance (spec §8, §10) |
| |
| -### Task 15: The project setting |
| +Store code lives in `internal/equipo/chat/hosted_*.go`, the dispatcher in `internal/equipo/hostedrun`. The dispatcher reaches the store only through these exported `*chat.Store` methods, each one transaction with the roster check: `HostedPending(ctx) ([]HostedJob, error)`, `HostedLaunched(ctx, attempt string, v hostedwire.JobView) error`, `HostedAdmitted(ctx, attempt string, a hostedwire.AdmissionView, at time.Time) error`, `HostedFailed(ctx, attempt, reason string) error`, `HostedStopped(ctx, attempt string, p hostedwire.StopProof, observed time.Time) error`, `HostedLive(ctx) ([]HostedJob, error)`. |
| + |
| +### Task 18: The project setting |
| |
| **Files:** Create migration `internal/equipo/migrations/01NN_hosted_checks_setting.sql`, `internal/equipo/chat/{hosted_setting.go,hosted_setting_test.go}`, `internal/equipo/hosted_settings.go`, `internal/equipo/templates/hosted_settings.html`. Modify `internal/equipo/app.go`, `settings_hub.go`, `copy.go`. |
| |
| -**Interfaces:** columns `hosted_checks bool`, `hosted_checks_owner`, `hosted_checks_revision` on `chat_projects` (pattern: `SetCopyDelegation`, `copy_store.go:66`). `func (s *Store) SetHostedChecks(ctx context.Context, person, project string, enabled bool, revision int64) error`; `func (t *txn) hostedChecks(project string) (bool, error)`. Owner only, current roster inside the transaction, revision conflict, audit event. Copy keys `hosted.checks`, `hosted.checks_help`, `hosted.title`, `hosted.lede`, pending. The section is hidden unless `EQUIPO_HOSTED_RUNNERS=1`. |
| +**Interfaces:** columns `hosted_checks`, `hosted_checks_owner`, `hosted_checks_revision` on `chat_projects` (the pattern of `SetCopyDelegation`, `copy_store.go:66`). `func (s *Store) SetHostedChecks(ctx context.Context, person, project string, enabled bool, revision int64) error`; `func (t *txn) hostedChecks(project string) (bool, error)`. Owner only, roster inside the transaction, revision conflict, audit event. Copy keys `hosted.checks`, `hosted.checks_help`, `hosted.title`, `hosted.lede`, pending. Hidden unless `EQUIPO_HOSTED_RUNNERS=1`. |
| |
| - [ ] **Red:** `TestHostedSettingOwnerOnly`, `TestHostedSettingRemovedOwnerRefused`, `TestHostedSettingRevisionConflict`, `TestHostedSettingAudited`, `TestHostedSettingHiddenWithoutFlag`. |
| -- [ ] **Green:** `go test ./internal/equipo/... -run 'TestHostedSetting' -count=1`; `python3 scripts/copy-status.py verify` (bounded JSON stdin, AGENTS.md). |
| -- [ ] **Mutation:** skip the roster check (`TestHostedSettingRemovedOwnerRefused`). |
| +- [ ] **Green:** `go test ./internal/equipo/... -run 'TestHostedSetting' -count=1`. |
| +- [ ] **Mutation:** skip the roster check. |
| - [ ] **Commit:** `equipo: owner setting to run a project's checks in a hosted VM`. |
| |
| -### Task 16: Hosted jobs store |
| +### Task 19: Hosted jobs store |
| |
| **Files:** Create migration `01NN_hosted_jobs.sql`, `internal/equipo/chat/{hosted_jobs.go,hosted_jobs_test.go}`. Modify `internal/equipo/chat/models.go`. |
| |
| -**Interfaces:** table `hosted_jobs` (`attempt_id` primary key, `step_id`, `task_id`, `project`, `person`, `size`, `state` one of `pending launching enrolling running stopping ended failed`, `launch_id`, `vm_ref`, `cert_digest`, `code_hash`, `code_expires_at`, `runner_id`, `held_seconds`, `held_micros`, `used_seconds`, `used_micros`, `created_at`, `started_at`, `ended_at`, `stop_reason`, `stop_proof_json`, `retry_of`, `revision`). `func (t *txn) newHostedJob(k *taskRecord, s *stepRecord, person string) (hostedJob, error)`; `func (t *txn) settleHostedJob(attempt string, used time.Duration, proof hostedwire.StopProof) error`; `func (t *txn) hostedJobForRunner(runnerID string) (hostedJob, error)`. |
| +**Interfaces:** table `hosted_jobs`: `attempt_id` primary key; `step_id`, `step_attempt`, `task_id`, `project`, `person`, `size`; `state` one of `pending launching enrolling enrolled stopping ended failed`; `launch_id`, `vm_ref`, `epoch`; `cert_digest`, `cert_valid`, `cert_checked_at`; `code_hash`, `code_expires_at`, `code_used_at`; `runner_id`, `machine_public_key`; `admitted_at`, `enrolled_at`, `ended_at`; `hold_seconds_json`, `hold_micros_json` (per UTC day and month); `used_seconds_json`, `used_micros_json`; `settled_at`; `stop_reason`, `stop_proof_json`; `retry_of`, `retries`; `revision`. Table `hosted_challenges` (`runner_id`, `nonce_hash`, `expires_at`, `used_at`). Transitions: `pending→launching→enrolling→enrolled→stopping→ended`; any live state `→stopping` on a step end or failure; `ended` and `failed` need stop proof, or "never launched" evidence (the controller's `Get` answering not found for an intent it never dispatched). |
| |
| -- [ ] **Red:** `TestHostedJobLifecycle` (only the listed transitions), `TestSettleNeedsProof`, `TestOneLiveJobPerStep`, `TestMigrationAdditive`. |
| -- [ ] **Green:** `go test ./internal/equipo/chat -run 'TestHostedJob|TestSettle|TestOneLiveJob' -count=1`; `make migration-check`. |
| +- [ ] **Red:** `TestHostedJobTransitions` (only the listed ones). `TestEndNeedsProof`. `TestOneLiveJobPerStep`. `TestSettleIdempotent` (settling twice changes nothing). `TestMigrationAdditive`. |
| +- [ ] **Green:** `go test ./internal/equipo/chat -run 'TestHostedJob|TestEndNeedsProof|TestOneLiveJob|TestSettleIdempotent' -count=1`; `make migration-check`. |
| - [ ] **Mutation:** allow `ended` without proof. |
| - [ ] **Commit:** `equipo: hosted jobs table and lifecycle`. |
| |
| -### Task 17: Per-person limits, held and settled (S2-9) |
| +### Task 20: Per-person limits, held and settled (S2-9) |
| |
| **Files:** Create `internal/equipo/chat/{hosted_limits.go,hosted_limits_test.go}`, migration `01NN_hosted_limits.sql`. |
| |
| @@ -357,186 +418,192 @@ The hosted worker's `checks` path now runs: await pack and bundle, index, checko |
| ```go |
| type HostedLimits struct{ Running int; DailySeconds int64; MonthlyMicros int64 } // USD micros |
| var DefaultHostedLimits = HostedLimits{Running: 2, DailySeconds: 8 * 3600, MonthlyMicros: 50_000_000} |
| -const RateSmallMicrosPerHour, RateLargeMicrosPerHour = 155_000, 310_000 // spec §10, eu-west-1 x86_64 |
| -const HostedChecksLifetime = 90 * time.Minute |
| -func (t *txn) hostedAdmit(person string, size isolatedjob.Size, now time.Time) (ok bool, reason string, err error) // reason "running" | "daily" | "monthly" |
| -func (s *Store) SetHostedLimits(ctx context.Context, owner, person string, l HostedLimits, revision int64) error // owner raises or lowers a person's limits |
| +const RateSmallMicrosPerHour, RateLargeMicrosPerHour = 155_000, 310_000 // spec §10, eu-west-1 x86_64 baseline |
| +const BurstHoldFactor = 4 |
| +const HostedChecksLifetime = 90 * time.Minute // per purpose; slice 4 adds its own |
| +func (t *txn) hostedAdmit(person string, size isolatedjob.Size, lifetime time.Duration, now time.Time) (ok bool, reason string, err error) // "running" | "daily" | "monthly" |
| +func Allocate(from, to time.Time) (days map[string]int64, months map[string]int64) // seconds per UTC day and month |
| +func (s *Store) SetHostedLimits(ctx context.Context, owner, person string, l HostedLimits, revision int64) error |
| ``` |
| |
| -Days and months are UTC. A job holds `HostedChecksLifetime` and its cost at that lifetime from admission until it settles; settling replaces the hold with the used time (from the controller's launch-to-stop-proof times) and its cost. Running counts every job not `ended` or `failed`. Any count error denies and keeps the step waiting. |
| +Hold: `Allocate(now, now+lifetime)` seconds against each day, and `lifetime × rate × BurstHoldFactor` against each month the span touches (the whole amount in each, conservatively). Settle (once, with proof): `Allocate(admitted_at, stop proof observed at)` at the baseline rate, replacing the hold. Running counts every job not `ended` or `failed`. A count or read error denies and the step keeps waiting. |
| |
| -- [ ] **Red:** `TestLimitsHoldAndSettle` (a third job waits with `running`; at 7 h 59 min used today a new 90-min hold waits with `daily`; settling a short job frees the difference). `TestLimitsRace` (20 goroutines, one slot: one admitted). `TestLimitCountErrorDenies`. `TestOwnerRaisesLimit` (owner only, audited). `TestMonthBoundaryUTC`. |
| -- [ ] **Green:** `go test ./internal/equipo/chat -run 'TestLimits|TestLimitCount|TestOwnerRaises|TestMonthBoundary' -count=1`. |
| -- [ ] **Mutations:** count only `running` jobs (`TestLimitsHoldAndSettle`); treat a count error as zero. |
| +- [ ] **Red:** `TestLimitsHoldAndSettle`. `TestLimitsRace` (20 goroutines, one slot: one admitted). `TestHoldSpansMidnight` (admission at 23:00 UTC holds against both days; settling at 23:20 frees the second day). `TestHoldSpansMonthEnd`. `TestNoProofKeepsHold`. `TestLimitCountErrorDenies`. `TestOwnerRaisesLimit`. |
| +- [ ] **Green:** `go test ./internal/equipo/chat -run 'TestLimits|TestHoldSpans|TestNoProofKeepsHold|TestLimitCount|TestOwnerRaises' -count=1`. |
| +- [ ] **Mutations:** count only `enrolled` jobs; hold at the baseline rate; treat a count error as zero. |
| - [ ] **Commit:** `equipo: per-person hosted limits, held then settled`. |
| |
| -### Task 18: Placement, the dispatcher and the VM's end |
| +### Task 21: Placement, the dispatcher and the VM's end |
| |
| -**Files:** Create `internal/equipo/hostedrun/{dispatcher.go,dispatcher_test.go,sim_test.go}`. Modify `internal/equipo/chat/runners.go` (`place`, `fits`, `waitingPlacements`, `offline`), `internal/equipo/chat/tasks.go` (`dispatchStep`, step terminal hook), `internal/equipo/app.go` (start the dispatcher only with the flag), `internal/hostedclient/client.go` (package comment), `client_test.go` (delete `TestInstanceDoesNotCallHostedClient`). |
| +**Files:** Create `internal/equipo/hostedrun/{dispatcher.go,dispatcher_test.go,sim_test.go}`. Modify `internal/equipo/chat/runners.go` (`place`, `fits`, `waitingPlacements` at `:1047`, `offline` at `:1112`, `Authorize` at `:931`), `internal/equipo/chat/tasks.go` (`dispatchStep`, the step-terminal hook), `internal/equipo/app.go` (start the dispatcher only with the flag), `internal/hostedclient/client.go` (package comment), `client_test.go` (delete `TestInstanceDoesNotCallHostedClient`; add `TestOnlyHostedrunImportsHostedClient`). |
| |
| -**Interfaces:** |
| +**State machine in `place`, for a checks step of a project with `hostedChecks` on, before the early return at `runners.go:545`:** |
| +1. Needs a hosted VM cannot meet (a Mac, a tag the image lacks): today's path, unchanged. |
| +2. The primary is not online or speaks below `ProtocolHostedChecks`: today's path. |
| +3. The step has a live job: `pending`, `launching`, `enrolling` keep `waiting_hosted` with no new hold; `enrolled` sets `RunnerID` to the job's runner and dispatches. |
| +4. The step's last job `failed`, or `ended` without a report: if `retries < 1` and its stop proof is recorded, admit a new job with `retry_of`; else fail the step with that job's reason. |
| +5. No job: `hostedAdmit`; on success create it `pending` and set `waiting_hosted`; on refusal set `hosted_limit` with the reason. |
| + |
| +Both placements are in `waitingPlacements`. A step with a live hosted job is exempt from offline withdrawal, by job identity. If the primary is offline past `OfflineLimit` while a job waits, the step resolves `runner_offline` and the job is stopped. |
| + |
| +`fits`: a runner bound to a hosted job fits only that job's step; `Authorize` refuses any other step and any other attempt for it in its transaction. |
| |
| -- `place`: for a checks step in a project with `hostedChecks` on, before the early return at `runners.go:545`, check the primary is online and speaks `ProtocolHostedChecks` (else today's path), then `hostedAdmit`: on success create the job and set `Placement = waiting_hosted`, `RunnerID = ""`; on refusal set `Placement = hosted_limit` with the reason. Both are in `waitingPlacements`. Hosted placements are exempt from offline withdrawal like `PlacementSandbox` (`runners.go:1134`). |
| -- `fits`: a runner bound to a hosted job fits only that job's step; `Authorize` (`runners.go:931`) refuses any other step for it inside its transaction. |
| -- `type Dispatcher struct{ Store *chat.Store; Client *hostedclient.Client; Clock func() time.Time }`; `func (*Dispatcher) Pass(ctx context.Context) error`, every 10 s: launch `pending` jobs (outside the transaction; a throttle keeps `pending` with backoff 10 s to 5 min); stop a job not enrolled 2 min after the controller reports it running, retry once as a new attempt with `retry_of`, then fail the step with `hosted_enrol_timeout`; when the step is terminal, or the controller reports the VM gone, call `Stop` until it returns proof, revoke the runner, settle the job; reconcile every live job with `Get` each minute. |
| -- After a VM ends mid-step without a report, the step is retried once on a new job, then fails with `hosted_vm_lost`. |
| +**Dispatcher:** `type Dispatcher struct{ Store *chat.Store; Client *hostedclient.Client; Clock func() time.Time }`; `func (*Dispatcher) Pass(ctx context.Context) error`, every 10 s. At start it asks the controller for the admission of a made-up attempt and logs `hosted_controller_reachable` when the signed not-found answer verifies, or `hosted_controller_unreachable` with the reason. Launch `pending` jobs outside any transaction (`Replaces` set to the predecessor's attempt for a retry; a throttle keeps `pending`, backoff 10 s to 5 min). Refresh `Admission` for every `enrolling` or `enrolled` job each pass and record it (`HostedAdmitted`). Stop a job not enrolled 2 min after the controller reports it running. When the step is terminal, the job failed, or the controller reports the VM gone, call `Stop` until it returns proof, revoke the runner, settle. |
| |
| -- [ ] **Red:** `TestHostedPlacementBeforeEarlyReturn`, `TestHostedNeedsCapablePrimary`, `TestHostedWaitsAtLimit`, `TestBoundRunnerFitsOnlyItsStep`, `TestAuthorizeRefusesOtherStep`, `TestHostedExemptFromWithdrawal`, `TestEnrolTimeoutRetriesOnce`, `TestVMGoneMidStep`, `TestStopUntilProofThenSettle`, `TestThrottleBacksOff`, `TestDispatcherOffWithoutFlag`. `TestDispatcherSimulation` (200 seeds, fake controller with lost replies, throttles, VM deaths and instance restarts; invariants: at most one live VM per step, never more running jobs per person than the limit, every settled job has proof, no step is certified by a VM that was not admitted). |
| -- [ ] **Green:** `go test ./internal/equipo/hostedrun ./internal/equipo/chat ./internal/hostedclient -run 'TestHosted|TestBoundRunner|TestAuthorizeRefuses|TestEnrolTimeout|TestVMGone|TestStopUntil|TestThrottle|TestDispatcher' -count=1`. |
| -- [ ] **Mutations:** place after the early return; let a bound runner fit any step; settle without proof (the simulation fails with its seed). |
| +- [ ] **Red:** `TestHostedPlacementBeforeEarlyReturn`, `TestMacChecksNeverHosted`, `TestHostedNeedsCapablePrimary`, `TestRepeatedPlacementOneJob` (ten placement passes: one job, one hold), `TestEnrolledJobDispatches`, `TestHostedWaitsAtLimit`, `TestBoundRunnerFitsOnlyItsStep`, `TestAuthorizeRefusesOtherStep`, `TestHostedExemptFromWithdrawal`, `TestPrimaryLostDuringEnrolment`, `TestEnrolTimeoutRetriesOnce` (the retry launches only after the first job's proof, with `Replaces`), `TestVMGoneMidStep`, `TestStopUntilProofThenSettle`, `TestThrottleBacksOff`, `TestDispatcherOffWithoutFlag`, `TestReachabilityProbeLogged`, `TestOnlyHostedrunImportsHostedClient`. `TestDispatcherSimulation` (200 seeds; a fake controller with lost replies, throttles, VM deaths, instance restarts and certificate withdrawal; invariants: at most one live VM per step; never more running jobs per person than the limit; holds never exceed limits; every settled job has proof; no step is certified by a VM whose admission was stale or invalid). |
| +- [ ] **Green:** `go test ./internal/equipo/hostedrun ./internal/equipo/chat ./internal/hostedclient -run 'TestHosted|TestMacChecks|TestRepeated|TestEnrolled|TestBoundRunner|TestAuthorizeRefuses|TestPrimaryLost|TestEnrolTimeout|TestVMGone|TestStopUntil|TestThrottle|TestDispatcher|TestOnlyHostedrun' -count=1`. |
| +- [ ] **Mutations:** place after the early return; let a bound runner fit any step; admit a new job on every placement pass; retry without the predecessor's proof (the simulation fails with its seed). |
| - [ ] **Commit:** `equipo: place checks on hosted VMs and see each VM to its end`. |
| |
| -### Task 19: Hosted enrolment and renewal routes |
| +### Task 22: Hosted enrolment, challenge and renewal routes |
| |
| -**Files:** Create `internal/equipo/{hosted_enrol.go,hosted_enrol_test.go}`. Modify `internal/equipo/app.go` (routes beside `:324`), `internal/equipo/personapi/auth.go:101` (public allowlist), `internal/equipo/runners.go` (`mintRunnerCredential` takes a lifetime). |
| +**Files:** Create `internal/equipo/{hosted_enrol.go,hosted_enrol_test.go}`. Modify `internal/equipo/app.go` (beside `:324`), `internal/equipo/personapi/auth.go:101` (public allowlist: `/api/hosted/enrol` only; challenge and renew need the runner bearer), `internal/equipo/runners.go:34` (`mintRunnerCredential` takes a lifetime and a cap). |
| |
| -**Interfaces:** `POST /api/hosted/enrol` takes `wire.HostedEnrolRequest`; `POST /api/hosted/renew` takes `wire.HostedRenewRequest` with the current bearer. Enrol, in one transaction: the code hash matches a job in `enrolling`, unused, unexpired; then outside it `Client.Admission(attempt)`; then a second transaction re-checks the job and requires `AdmissionView` state `running`, `VMRef` equal to the request's, `CertValid`, and the job's person still on the roster; creates the runner row (role `worker`, `hosted_job` bound, no device code) and a 1-hour credential. Renew: signature over the instance's challenge with the machine key, same epoch, job still live. Rate limits as `BeginEnrolment`'s. |
| +**Interfaces:** `POST /api/hosted/enrol` (`wire.HostedEnrolRequest`): transaction 1 matches the code hash to a job in `enrolling`, unused, unexpired (2 min), and marks it used; then outside it `Client.Admission(attempt)`; transaction 2 re-checks the job and the person's roster membership and requires `State` `running`, `VMRef` equal to the request's, `CertValid`, and `Epoch` equal to the job's; creates the runner row (role `worker`, bound to the job, no device code), stores the machine key, records the admission, and issues a credential valid 1 hour and never past the job's deadline. `POST /api/hosted/challenge` (bearer): one nonce, 60 s, stored hashed. `POST /api/hosted/renew` (bearer + `wire.HostedRenewRequest`): the nonce unused and unexpired, the signature valid for the stored machine key, the epoch current, the job live; marks the nonce used and issues the next credential. Rate limits as `BeginEnrolment`'s (`setup/enrolment.go:52`). |
| |
| -- [ ] **Red:** `TestEnrolRefusesReplayAndWrongVM` (second use; right code, wrong `VMRef`; expired code). `TestEnrolNeedsCertifiedAdmission`. `TestEnrolRemovedPersonRefused`. `TestEnrolRouteIsPublicNotCSRF`. `TestRenewOldEpochRefused`. `TestRenewAfterStopRefused`. `TestHostedCredentialIsOneHour`. |
| +- [ ] **Red:** `TestEnrolRefusesReplayAndWrongVM` (second use; right code, wrong `VMRef`; expired code). `TestEnrolNeedsCertifiedAdmission`. `TestEnrolRemovedPersonRefused`. `TestEnrolRouteIsPublicNotCSRF`. `TestRenewNonceSingleUse`. `TestRenewOldEpochRefused`. `TestRenewAfterStopRefused`. `TestHostedCredentialCappedAtDeadline`. |
| - [ ] **Green:** `go test ./internal/equipo -run 'TestEnrol|TestRenew|TestHostedCredential' -count=1`. |
| -- [ ] **Mutations:** skip the `VMRef` comparison; mark the code used outside the transaction. |
| +- [ ] **Mutations:** skip the `VMRef` comparison; accept a used nonce. |
| - [ ] **Commit:** `equipo: hosted enrolment and renewal bound to one job`. |
| |
| -### Task 20: Bundle relay from the primary |
| +### Task 23: Bundle relay from the primary |
| |
| -**Files:** Modify `internal/equipo/chat/tasks.go` (dispatch tells the primary to send the pack and the bundle to the hosted runner), `internal/runner/thin/relay.go` (primary builds with `depsbundle.Build`), `internal/runner/thin/relay_test.go`. |
| +**Files:** Modify `internal/equipo/chat/tasks.go` (the hosted step's send-pack command asks for the bundle), `internal/runner/thin/relay.go` (the primary builds with `depsbundle.Build` and sends `TransferKindDeps` under its own transfer ID), `internal/runner/thin/relay_test.go`, the instance relay's per-transfer storage limit for `deps` and its cleanup when the step ends. |
| |
| -**Interfaces:** `wire.SendPackCommand` gains `Deps bool` (protocol-gated). The primary computes `ModulesFor` over the base and candidate trees and sends the bundle as `TransferKindDeps` after the pack, through the existing relay. |
| +**Interfaces:** `wire.SendPackCommand` gains `Deps bool` (protocol-gated). The instance creates both transfer IDs. |
| |
| -- [ ] **Red:** `TestPrimarySendsBundleForHostedStep`, `TestNoBundleForPersonalWorker`, `TestBundleTooLargeEndsStep`. |
| -- [ ] **Green:** `go test ./internal/runner/thin ./internal/equipo/chat -run 'TestPrimarySendsBundle|TestNoBundle|TestBundleTooLarge' -count=1`. |
| -- [ ] **Mutation:** always send the bundle (`TestNoBundleForPersonalWorker`). |
| +- [ ] **Red:** `TestPrimarySendsBundleForHostedStep`, `TestNoBundleForPersonalWorker`, `TestBundleTooLargeEndsStep`, `TestDepsTransferCleanedUp`. |
| +- [ ] **Green:** `go test ./internal/runner/thin ./internal/equipo/chat -run 'TestPrimarySendsBundle|TestNoBundle|TestBundleTooLarge|TestDepsTransfer' -count=1`. |
| +- [ ] **Mutation:** always send the bundle. |
| - [ ] **Commit:** `runner: primary sends the dependency bundle to hosted checks`. |
| |
| -### Task 21: Certified results from hosted workers (Fable M8) |
| +### Task 24: Certified results from hosted workers (Fable M8) |
| |
| -**Files:** Modify `internal/equipo/chat/tasks.go:1843-1862` (`stepReport`), `internal/equipo/chat/mergeauth.go:1384` (`acceptBaseChecks`), `internal/equipo/chat/runners.go` (`cleanHello`). Create `internal/equipo/chat/hosted_results_test.go`. |
| +**Files:** Modify `internal/equipo/chat/tasks.go:1826-1862` (`stepReport`, including the primary-only `BaseChecks` branch at `:1831`), `internal/equipo/chat/mergeauth.go:1384` (`acceptBaseChecks`), `internal/equipo/chat/runners.go` (`cleanHello`). Create `internal/equipo/chat/hosted_results_test.go`. |
| |
| -**Interfaces:** `func (t *txn) hostedCertified(runnerID string) (bool, error)`: true only when the runner is bound to a hosted job whose admission (recorded at enrolment, Task 19) carried a valid certificate digest and the job is live. In `stepReport`, a worker's checks result keeps `bubblewrap` only when `hostedCertified`; otherwise today's rules. `acceptBaseChecks` accepts `role == worker` only with `hostedCertified`. Hello fields (`Sandbox`, anything about images) are stored for diagnostics and read by none of these decisions. |
| +**Interfaces:** `const AdmissionFresh = 2 * time.Minute`; `func (t *txn) hostedCertified(runnerID, stepID string, stepAttempt int64, now time.Time) (bool, error)`: true only when the runner is bound to a live hosted job for exactly this step and step attempt, the job's last recorded admission has `CertValid`, the same launch, VM, image digest, certificate digest and epoch recorded at enrolment, and `cert_checked_at` within `AdmissionFresh` of `now`. A read error is false. In `stepReport`, a worker's checks result keeps `bubblewrap`, and its `BaseChecks` and `BaseChecksSHA` are read, only when `hostedCertified`; otherwise today's rules. A hosted runner that fails it is not tainted (its result is simply not certified) and the step is retried once. `acceptBaseChecks` accepts `role == worker` only with `hostedCertified`. Hello fields are stored for diagnostics and read by none of these decisions. |
| |
| -- [ ] **Red:** `TestHelloCannotCertify` (an uncertified Linux worker reports `bubblewrap` and a hello claiming a certified image: stored as `none`, runner tainted, no `BaseChecksSHA`). `TestHostedCertifiedResultCounts` (certified worker: `bubblewrap`, base checks accepted, the merge gate's `checked_in_sandbox` and `trusted_base_checks` both pass). `TestCertRevokedAfterEnrolNotCertified`. `TestMacRulesUnchanged`. |
| -- [ ] **Green:** `go test ./internal/equipo/chat ./internal/equipo/mergegate -run 'TestHelloCannotCertify|TestHostedCertified|TestCertRevoked|TestMacRules' -count=1`. |
| -- [ ] **Mutations:** read the hello's sandbox in `hostedCertified`; accept any worker in `acceptBaseChecks`. |
| -- [ ] **Commit:** `equipo: hosted results count only from certified admissions`. |
| +- [ ] **Red:** `TestHelloCannotCertify` (an unbound Linux worker reports `bubblewrap` with a hello claiming a certified image: stored as `none`, runner tainted, no `BaseChecksSHA`). `TestHostedCertifiedResultCounts` (the merge gate's `checked_in_sandbox` and `trusted_base_checks` both pass). `TestStaleAdmissionNotCertified` (last check 2 min 1 s ago). `TestCertWithdrawnNotCertified` (the latest admission says `CertValid` false). `TestWrongStepAttemptNotCertified`. `TestMacRulesUnchanged`. |
| +- [ ] **Green:** `go test ./internal/equipo/chat ./internal/equipo/mergegate -run 'TestHelloCannotCertify|TestHostedCertified|TestStaleAdmission|TestCertWithdrawn|TestWrongStepAttempt|TestMacRules' -count=1`. |
| +- [ ] **Mutations:** read the hello in `hostedCertified`; skip the freshness check; accept any worker in `acceptBaseChecks`. |
| +- [ ] **Commit:** `equipo: hosted results count only from fresh certified admissions`. |
| |
| -### Task 22: What the person sees (cost visibility, only as far as limits need) |
| +### Task 25: What the person sees (cost visibility, only as far as limits need) |
| |
| -**Files:** Modify `internal/equipo/work_pages.go`, `work_views.go`, `copy.go`, the usage page template and handler (`UsageTotals`, `internal/equipo/chat/usage.go:44`). Create `internal/equipo/hosted_views_test.go`. |
| +**Files:** Modify `internal/equipo/work_pages.go`, `work_views.go`, `copy.go`, the usage page (`UsageTotals`, `internal/equipo/chat/usage.go:44`). Create `internal/equipo/hosted_views_test.go`. |
| |
| -**Interfaces:** step chips `work.checks.waiting_hosted` ("Starting a hosted machine"), `work.checks.hosted_limit_running`, `_daily`, `_monthly` (each says which limit and when it frees), failure reasons `work.reason.hosted_enrol_timeout`, `hosted_vm_lost`, `hosted_unavailable`, `deps_too_large`. Usage page: one block, "Hosted machines", with VM-hours today, estimated spend this month and the person's limits. Owners see the per-person limit editor (Task 17). Strings pending; no new page. |
| +**Interfaces:** chips `work.checks.waiting_hosted`, `work.checks.hosted_limit_running`, `_daily`, `_monthly` (each says which limit and when it frees); reasons `work.reason.hosted_enrol_timeout`, `hosted_vm_lost`, `hosted_unavailable`, `deps_conflict`, `deps_new_module`, `deps_too_large`, `pack_incomplete`. Usage page: one block, "Hosted machines", with VM-hours today, estimated spend this month (labelled an estimate) and the person's limits. Owners see the per-person limit editor (Task 20). Strings pending. |
| |
| -- [ ] **Red:** `TestWaitingHostedChip`, `TestLimitChipSaysWhich`, `TestUsageShowsHostedTotals`, `TestUsageUnknownStaysUnknown` (a failed total shows "unknown", not 0). |
| -- [ ] **Green:** `go test ./internal/equipo -run 'TestWaitingHosted|TestLimitChip|TestUsageShowsHosted|TestUsageUnknown' -count=1`; `python3 scripts/copy-status.py verify` (bounded JSON stdin, AGENTS.md). |
| +- [ ] **Red:** `TestWaitingHostedChip`, `TestLimitChipSaysWhich`, `TestUsageShowsHostedTotals`, `TestUsageUnknownStaysUnknown`. |
| +- [ ] **Green:** `go test ./internal/equipo -run 'TestWaitingHosted|TestLimitChip|TestUsageShowsHosted|TestUsageUnknown' -count=1`. |
| - [ ] **Mutation:** render a failed total as 0. |
| - [ ] **Commit:** `equipo: show hosted waits, limits and usage`. |
| |
| ## Phase F: the injection-review fixes that gate hosted work |
| |
| -H3 is closed by Tasks 2 and 4 to 7 (exact hosts, authenticated proxy, fronting matrix), Task 10 (certification probes) and S2-1 (no registry in a VM's egress). M8's digest half is closed by Tasks 3, 19 and 21. Tasks 23 and 24 close what is left of M4 and M8 on main (survey of `27d50e7f`). |
| +H3 is closed by Tasks 2, 4, 6, 7 and 9 (exact hosts, authenticated proxy, fronting and expiry matrix, audited routes), Task 13 (probes in a real VM) and S2-1 (no registry in a VM's egress). M8's certification half is closed by Tasks 3, 13, 22 and 24. Tasks 26 and 27 close what is left of M4 and M8 on main. |
| |
| -### Task 23: M4 residue: Research prompts and old runners |
| +### Task 26: M4 residue: Research prompts, enforced by capability |
| |
| -**Files:** Modify `internal/runner/thin/research.go:664-676`, `internal/equipo/chat/runners.go` (placement), `internal/wire/runners.go:860-866`. Create `internal/runner/thin/research_quote_test.go`, `internal/equipo/chat/protocol_floor_test.go`. |
| +**Files:** Modify `internal/runner/thin/research.go:664-691`, `internal/equipo/chat/runners.go` (placement and `Authorize` at `:931`), `internal/wire/runners.go:860-866`. Create `internal/runner/thin/research_quote_test.go`, `internal/equipo/chat/protocol_floor_test.go`. |
| |
| -**Interfaces:** Research's task title, brief and question enter through `wire.QuotedData` under the labels `Task title`, `Task brief`, `Question`, and each fetched source under `Source <n> (<url>)`; the `<<<`/`>>>` and `=== source` fences go. Placement refuses Engineering, Design and Research on a runner below `wire.ProtocolInjectionDefences` (28), with `PlacementWaiting` and reason `runner_update_needed`, so the folding at `wire/runners.go:860-866` is never used; then the folding is deleted. |
| +**Interfaces:** every untrusted value in Research's prompt enters through `wire.QuotedData` under a label: `Task title`, `Task brief`, `Question`, `Specialist brief`, `Person's words`, and for each source `Source <n> URL`, `Source <n> title`, `Source <n> text`, `Image <n> description`; the `<<<`/`>>>` and `=== source` fences go. `wire.ProtocolHostedChecks` also marks this quoting. Placement and `Authorize` refuse Research on a runner below it, and Engineering, Design and Research below `ProtocolInjectionDefences` (28), with reason `runner_update_needed`; a queued command for such a runner is re-checked at `Authorize`. Then the folding at `wire/runners.go:860-866` is deleted. |
| |
| -- [ ] **Red:** `TestResearchQuotesTitleBriefQuestion` (a title containing `>>>` and a fake `=== source` line stays inside its quoted value). `TestOldRunnerGetsNoModelWork`. `TestNoBriefFolding`. |
| -- [ ] **Green:** `go test ./internal/runner/thin ./internal/equipo/chat ./internal/wire -run 'TestResearchQuotes|TestOldRunner|TestNoBriefFolding' -count=1`. |
| -- [ ] **Mutation:** put the title back unquoted. |
| -- [ ] **Commit:** `research: quote task text; old runners get no model work`. |
| +- [ ] **Red:** `TestResearchQuotesEveryValue` (a title containing `>>>`, a source title containing a fake `=== source` line and a URL containing a quote each stay inside their quoted value). `TestProtocol38RunnerGetsNoResearch`. `TestQueuedResearchRecheckedAtAuthorize`. `TestNoBriefFolding`. |
| +- [ ] **Green:** `go test ./internal/runner/thin ./internal/equipo/chat ./internal/wire -run 'TestResearchQuotes|TestProtocol38|TestQueuedResearch|TestNoBriefFolding' -count=1`. |
| +- [ ] **Mutation:** put the source title back unquoted. |
| +- [ ] **Commit:** `research: quote every untrusted value; older runners get none`. |
| |
| -### Task 24: M8 residue: checkpoint provenance on the instance |
| +### Task 27: M8 residue: checkpoint provenance on the instance |
| |
| -Slice 2 has no checkpoints (S2-6). This task builds the instance's half now so slice 4 only adds the runner's: the acknowledgement that binds a checkpoint, and the only renderer allowed to put checkpoint notes in a prompt. |
| +Slice 2 has no checkpoints (S2-6). This task builds the instance's half so slice 4 adds only the runner's. Content is stored at acknowledgement and rendered only from the acknowledgement's ID, so nothing can be substituted between the two. |
| |
| **Files:** Create migration `01NN_checkpoints.sql`, `internal/equipo/chat/{checkpoint.go,checkpoint_test.go}`, `internal/wire/checkpoint.go`. |
| |
| **Interfaces:** |
| |
| ```go |
| -type Checkpoint struct{ TaskID, Repo, BaseSHA, CandidateSHA, AttemptID, LaunchID string; PackDigest, NotesDigest string; Notes []string } |
| -func (t *txn) AcknowledgeCheckpoint(l Lease, c wire.Checkpoint) (ackID string, err error) // binds digests to the recorded task, repo, base, candidate, attempt, launch |
| -func RenderResume(c Checkpoint, personWords []string) string // task, attempt, checkpoint digest; each note json.Marshal-quoted under "Checkpoint note n"; person words in their own block |
| -var ErrCheckpointMismatch error |
| +// wire |
| +type Checkpoint struct{ TaskID, Repo, BaseSHA, CandidateSHA, AttemptID, LaunchID, PackDigest string; Notes []string } |
| +type PackReceipt struct{ PackDigest, PrimaryRunnerID string; Signature []byte } // the primary's machine-key signature that it holds the pack durably; produced by slice 4 |
| +// chat |
| +func (t *txn) AcknowledgeCheckpoint(l Lease, c wire.Checkpoint, r wire.PackReceipt) (ackID string, err error) |
| +func (t *txn) RenderResume(ackID string, personWords []string) (string, error) |
| +var ErrCheckpointMismatch, ErrNoReceipt error |
| ``` |
| |
| -- [ ] **Red:** `TestCheckpointBindsEverything` (any one field differing from the record: refused). `TestUnacknowledgedCannotResume`. `TestNotesCannotEscape` (a note containing a closing marker, a fake "Person's words:" heading and a JSON fragment stays one quoted string). `TestNotesDigestRecomputed`. |
| -- [ ] **Green:** `go test ./internal/equipo/chat ./internal/wire -run 'TestCheckpoint|TestUnacknowledged|TestNotes' -count=1`. |
| -- [ ] **Mutation:** trust the runner's `NotesDigest` without recomputing it. |
| +`AcknowledgeCheckpoint` binds the checkpoint to the recorded task, repository, base, candidate, attempt and launch; requires a receipt signed by the task's current primary for the same pack digest; recomputes the notes digest from the notes; and stores everything immutably. `RenderResume` loads by ID only and prints the task, attempt and checkpoint digest, each note `json.Marshal`-quoted under `Checkpoint note <n>`, and the person's words in their own block. |
| + |
| +- [ ] **Red:** `TestCheckpointBindsEverything` (any one field differing: refused). `TestCheckpointNeedsPrimaryReceipt` (no receipt, a receipt from a worker, a receipt for another digest: refused). `TestRenderOnlyFromAck` (an unknown ID: error; there is no render from caller-supplied notes). `TestNotesCannotEscape`. `TestAckImmutable`. |
| +- [ ] **Green:** `go test ./internal/equipo/chat ./internal/wire -run 'TestCheckpoint|TestRenderOnly|TestNotes|TestAckImmutable' -count=1`. |
| +- [ ] **Mutation:** trust a caller-supplied notes digest. |
| - [ ] **Commit:** `equipo: checkpoint acknowledgement and quoted resume rendering`. |
| |
| ## Phase G: deployment, end to end, live |
| |
| -### Task 25: OpenTofu for the hosted stack |
| +### Task 28: OpenTofu for the hosted stack |
| |
| -**Files:** Create `infra/hosted/modules/{account,network,controller,proxy,image-store,alerts}/`, `infra/hosted/envs/{dev,prod}/`, `infra/hosted/tests/*.tftest.hcl`, `infra/hosted/README.md`. Modify `.amadan/ci.d/` (a `tofu validate` and `tofu test` lane with mocked providers; no credentials in CI). |
| +**Files:** Create `infra/hosted/modules/{account,network,controller,proxy,config,alerts}/`, `infra/hosted/envs/dev/{network,services}/`, `infra/hosted/envs/prod/{account,network,services}/`, a `tests/` directory in each root, `infra/hosted/scripts/{plan-check.py,plan_check_test.py,phases.json}`, `infra/hosted/README.md`. Modify `.amadan/ci.d/` (a lane running `tofu validate` and `tofu test` with mocked providers in each root, and `plan_check_test.py`; no credentials in CI). |
| |
| -**Shape (S2-4):** |
| -- `account` (prod only): CloudTrail (management events, Lambda MicroVM data events) to its own bucket, account-level S3 public access block, EBS encryption by default, IAM password policy, the alert SNS topic, AWS Budgets with an action (Task 31's plan sets the numbers). |
| -- `network`: VM VPC with `enable_dns_support = false` and `enable_dns_hostnames = false`; one VM subnet per AZ in use, route table with the local route and a route to each proxy's `/32` over the peering only; VM security group allowing egress only to the proxy addresses on 8443 and 8444; NACLs to match. Services VPC with DNS on, two public subnets in two AZs, an internet gateway. The peering, accepted in the same account. |
| -- `controller`: one `t4g.small` with an EIP, a role allowed only `lambda-microvms:*` on this account's MicroVMs and images in `eu-west-1`, `lambda:GetNetworkConnector` on the one connector, `ec2:Describe*` for the audit, `sns:Publish` on the topic, and S3 on the Litestream bucket; security group allowing 443 from anywhere (signed requests, pinned TLS) and metrics on 9100 from nowhere; systemd units running the released controller and Litestream; binaries fetched by digest. |
| -- `proxy` (×2, two AZs): `t4g.micro` with an EIP; no AWS role; listens on 8443 and 8444 on its private address only; egress 443 to anywhere. |
| -- `image-store`: the S3 bucket for image inputs, versioned, public access blocked. |
| -- The connector (`VPC_EGRESS` in the VM subnet) and its operator role with `AWSLambdaNetworkConnectorOperatorPolicy` plus the subnet-scoped `ec2:DeleteNetworkInterface` (Task 17 live fact). |
| +**Shape (S2-4):** as `2026-11-30-hosted-prod-account-plan.md` sections 2 to 4 list them, address by address. `account` (prod only): CloudTrail with Lambda MicroVM data events, account S3 public access block, EBS encryption by default, password policy, the alert topic and email subscription, the monthly budget and its action (a deny policy on the controller role for `RunMicrovm` and `ResumeMicrovm`), the cost anomaly monitor. `network`: VM VPC with DNS support and hostnames off and one VM subnet; services VPC with DNS on, two public subnets in two AZs and an internet gateway; one peering; the VM route table (local plus a `/32` per proxy); the VM security group (egress only to the proxies on 8443 and 8444, no ingress); NACLs; the connector and its operator role (`AWSLambdaNetworkConnectorOperatorPolicy` plus the subnet-scoped `ec2:DeleteNetworkInterface`). `services`: the config, Litestream and image-input buckets; the controller (`t4g.small`, EIP; role: `lambda-microvms` actions on this account's MicroVMs and images in `eu-west-1`, `lambda:GetNetworkConnector` on the one connector, `ec2:Describe*` for the audit, `sns:Publish` on the topic, S3 on its Litestream bucket and on `controller/` and `pins/` in the config bucket; security group 443 from anywhere); two proxies (`t4g.micro`, EIPs, two AZs; role: `s3:GetObject` on `proxy/<name>/` only; listeners on their private addresses only); status-check alarms. `plan-check.py --phase P --account A --region R plan.json` passes only the addresses `phases.json` lists for `P`, only `create` actions (and only `delete` for the `destroy-*` phases), and only ARNs in `A` and `R`. |
| |
| -- [ ] **Red:** `tests/network.tftest.hcl` asserts DNS off on the VM VPC, no route to `0.0.0.0/0` or `::/0` from the VM subnet, the VM security group's egress set equal to the proxies' addresses, and DNS on in the services VPC. `tests/iam.tftest.hcl` asserts the controller role has no `iam:*`, no `*` resource on MicroVM actions outside the account and region, and the proxies have no instance profile. |
| -- [ ] **Green:** `tofu -chdir=infra/hosted/envs/dev init -backend=false && tofu -chdir=infra/hosted/envs/dev validate`; same for `prod`; `tofu -chdir=infra/hosted test` (mocked providers). |
| -- [ ] **Mutations:** add a default route on the VM subnet; give the proxy an instance profile. Each fails its test. |
| +- [ ] **Red:** `envs/prod/network/tests/network.tftest.hcl`: DNS off on the VM VPC; no route to `0.0.0.0/0` or `::/0` from the VM subnet; only `/32` routes over the peering; the VM security group's egress set equals the proxies'; DNS on in the services VPC. `envs/prod/services/tests/iam.tftest.hcl`: the controller role has no `iam:*` and no MicroVM action outside the account and region; the proxy role allows only `s3:GetObject` on its prefix. `plan_check_test.py`: an unlisted address, an `update`, a `replace` and a foreign ARN are each refused. |
| +- [ ] **Green:** for each root `R` in `envs/dev/network envs/dev/services envs/prod/account envs/prod/network envs/prod/services`: `tofu -chdir=infra/hosted/$R init -backend=false && tofu -chdir=infra/hosted/$R validate && tofu -chdir=infra/hosted/$R test`; `python3 -I infra/hosted/scripts/plan_check_test.py`. |
| +- [ ] **Mutations:** add a default route on the VM subnet; widen the proxy role; let `plan-check.py` pass an `update`. Each fails its test. |
| - [ ] **Commit:** `infra: OpenTofu for the hosted stack, dev and prod`. |
| |
| -### Task 26: Release artifacts and host configuration |
| +### Task 29: Release artifacts and host configuration |
| |
| -**Files:** Create `scripts/release-hosted.sh`, `infra/hosted/modules/controller/cloud-init.yaml.tmpl`, `infra/hosted/modules/proxy/cloud-init.yaml.tmpl`, `internal/hostedctl/healthz.go`. Modify `cmd/equipo-hosted-controller/config.go` (read the deployment manifest written by cloud-init), `Makefile`. |
| +**Files:** Create `scripts/release-hosted.sh`, `infra/hosted/modules/controller/cloud-init.yaml.tmpl`, `infra/hosted/modules/proxy/cloud-init.yaml.tmpl`, `internal/hostedctl/healthz.go`. Modify `cmd/equipo-hosted-controller/{main.go,config.go}` (subcommand `keygen -ed25519|-ca -out <prefix>`; read the deployment manifest and the config-bucket files fetched by `ExecStartPre`; write its TLS certificate's SPKI pin to `pins/controller.spki` at first boot), `Makefile`. |
| |
| -**Interfaces:** `release-hosted.sh <version>` builds `equipo-hosted-controller`, `equipo-hosted-proxy`, `equipo-vm-init` and the runner for the image, records SHA-256 sums and publishes them on the forge under the release tag (the same mechanism as `publish-renderer.sh`). Cloud-init downloads by URL and checks the digest before installing; a mismatch leaves the unit off. `GET /healthz` on the metrics listener only. |
| +**Interfaces:** `release-hosted.sh <version>` builds `equipo-hosted-controller`, `equipo-hosted-proxy`, `equipo-vm-init`, `equipo-hosted-image`, `equipo-hosted-certify` and the runner for the image, records SHA-256 sums, and publishes them on the forge under the release tag, as `publish-renderer.sh` does. Cloud-init downloads by URL and checks the digest before installing; a mismatch, or private keys absent from the config bucket after 15 minutes, leaves the unit off. `GET /healthz` on the metrics listener only. |
| |
| -- [ ] **Red:** `TestCloudInitChecksDigest` (template rendering: the unit starts only after `sha256sum -c`). `TestControllerReadsManifest`. |
| -- [ ] **Green:** `go test ./internal/hostedctl ./cmd/equipo-hosted-controller -run 'TestCloudInit|TestControllerReadsManifest|TestHealthz' -count=1`; `scripts/release-hosted.sh --dry-run`. |
| +- [ ] **Red:** `TestCloudInitChecksDigest`, `TestControllerReadsManifest`, `TestKeygenWritesPrivate0600`, `TestPinWrittenOnce`, `TestHealthzOnMetricsOnly`. |
| +- [ ] **Green:** `go test ./internal/hostedctl ./cmd/equipo-hosted-controller -run 'TestCloudInit|TestControllerReads|TestKeygen|TestPinWritten|TestHealthz' -count=1`; `scripts/release-hosted.sh --dry-run`. |
| - [ ] **Commit:** `hosted: release artifacts and host configuration by digest`. |
| |
| -### Task 27: Whole chain on one machine |
| +### Task 30: Whole chain on one machine |
| |
| -**Files:** Create `internal/hostedtest/{chain.go,chain_test.go}` (build tag `hostedchain`, run by its own CI lane on Linux). |
| +**Files:** Create `internal/hostedtest/{chain.go,chain_test.go}` (build tag `hostedchain`, its own CI lane on Linux). |
| |
| -**Interfaces:** one test process starts, on `127.0.0.1`: an instance (`equipotest`), the controller with the in-memory `isolatedjob` fake whose `Launch` starts `equipo-vm-init`'s hook server in-process and calls `/run`, two proxies, and a personal primary (`thintest`). The hosted runner runs real bubblewrap on Linux. |
| +**Interfaces:** one test process starts on `127.0.0.1`: an instance (`equipotest`), the controller with the in-memory `isolatedjob` fake whose `Launch` starts `vminit`'s hook server in-process and posts `/run`, two proxies, and a personal primary (`thintest`). The hosted runner runs real bubblewrap. |
| |
| -- [ ] **Red:** `TestChainHostedCheckPasses` (a project with the setting on: the step goes `waiting_hosted`, the VM enrols, pack and bundle arrive, checks pass in bubblewrap, the result is certified, the VM is stopped with proof, usage is settled). `TestChainFailingCheck`. `TestChainMissingModule` (`needs_network`). Drills: `TestChainKillProxyMidStep` (fails over to the second), `TestChainKillControllerMidStep` (step finishes; the stop waits for the controller), `TestChainStopVMMidStep` (retry once on a new VM), `TestChainOrphanVM` (the controller reaps it). |
| +- [ ] **Red:** `TestChainHostedCheckPasses` (setting on: `waiting_hosted`, enrol, pack and bundle, checks pass in bubblewrap, certified, VM stopped with proof, usage settled). `TestChainFailingCheck`. `TestChainNewModule` (`needs_network` `deps_new_module`). Drills: `TestChainKillProxyMidStep` (fails over), `TestChainKillControllerMidStep` (open sockets close at feed expiry; the step fails `hosted_unavailable` and retries once after the controller returns), `TestChainStopVMMidStep`, `TestChainOrphanVM`, `TestChainCertWithdrawnMidStep` (the result is not certified). |
| - [ ] **Green:** `go test -tags hostedchain ./internal/hostedtest -count=1`. |
| - [ ] **Commit:** `hostedtest: whole-chain hosted checks and failure drills`. |
| |
| -### Task 28: Copy review |
| +### Task 31: Copy review |
| |
| -- [ ] Write every new string from Tasks 15, 17 and 22 into `docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json`; run the copy review. **HUMAN:** Paul or the copy reviewer edits; apply edits verbatim; strings stay pending. |
| +- [ ] Write every new string from Tasks 18, 20 and 25 into `docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json`; run the copy review. **HUMAN:** Paul or the copy reviewer edits; apply edits verbatim. Strings stay pending until accepted through the project's own path (AGENTS.md); `copy-release-check`, and so `make ci`, fails until then, which is correct and blocks merge. |
| - [ ] **Commit:** `copy: hosted checks strings for review`. |
| |
| -### Task 29: Whole-branch review |
| +### Task 32: Whole-branch review |
| |
| -- [ ] `make ci`; one whole-branch Astra review, at most three rounds; fix what is clearly right; record what stays open in the progress file. |
| +- [ ] `make ci` with every target passing except `copy-release-check`, whose only failures must be the pending keys from Task 31; one whole-branch Astra review, at most three rounds; fix what is clearly right; record what stays open. |
| - [ ] **Commit:** `hosted slice 2: review fixes`. |
| |
| -### Task 30: Dev live drill in `kass` (HUMAN GO) |
| +### Task 33: Dev live drill in `kass` (HUMAN GO) |
| |
| -- [ ] Write `docs/superpowers/plans/2026-MM-DD-hosted-2-dev-live-plan.md` in the shape of Task 17 revision 5 and 17b (livectl for Lambda calls, safety-only hard stops, FINDING lines, ledger, systemd user units, teardown verified by type and tag): `tofu apply` of `envs/dev` in `kass` / `eu-west-1`, image build, a certification launch, **HUMAN:** Paul signs the certificate offline, then hosted checks from the staging Equipo instance end to end, the Task 27 drills against real VMs, the egress matrix from inside a real VM, then `tofu destroy` and verification. Astra reviews it, three rounds at most. |
| +- [ ] Write `docs/superpowers/plans/2026-MM-DD-hosted-2-dev-live-plan.md` in the shape of Task 17b (safety-only hard stops, FINDING lines, ledger, systemd user units, teardown verified by type and tag): `tofu apply` of `envs/dev/*` in `kass` / `eu-west-1`, image build and publish, a certification launch, **HUMAN:** Paul signs offline, then hosted checks from the staging Equipo instance end to end, the Task 30 drills against real VMs, the egress matrix from inside a real VM, the connector interface cleanup (still unexercised), then `tofu destroy` and verification. Record `Task 33 PASSED` in the progress file only if every safety check passed. Astra reviews the plan, three rounds at most. |
| - [ ] **HUMAN:** Paul's one GO. The agent runs it, records spend, tears down. |
| |
| -### Task 31: Production bring-up (HUMAN GO) |
| +### Task 34: Production bring-up (HUMAN GO) |
| |
| -- [ ] Run `docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md` (written with this plan) after Task 30 passes and the branch is merged. **HUMAN:** Paul's one GO; Paul signs the production certificate offline; Paul turns the project setting on for the first project. |
| +- [ ] Run `docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md` after Task 33 passes and the branch is merged and released. **HUMAN:** Paul's one GO; Paul signs the production certificate; Paul turns the setting on for the first project. |
| |
| -**Slice 2 is done when** a project with the setting on runs its checks in a hosted VM in `149757027610`, the result is certified through the controller's launch record, limits hold under the simulation and the chain tests, the dev drill and the production bring-up are recorded with nothing left running that the plan did not leave on purpose, and everything is off unless flagged. |
| +**Slice 2 is done when** a project with the setting on runs its checks in a hosted VM in `149757027610`, the result is certified through a fresh controller admission, limits hold under the simulation and the chain tests, the dev drill and the production bring-up are recorded with nothing left running that the plan did not leave on purpose, and everything is off unless flagged. |
| |
| --- |
| |
| ## Decisions owed to Paul |
| |
| -1. **Slice 2 includes the slice 1b foundation** (Phases A to D, Task 25). *Recommendation:* yes; there is no shorter path to a working hosted check. |
| -2. **S2-1, dependencies from the primary instead of a mirror service.** Spec §16 ruling 4 says "the read-only mirror is required before hosted code runs". This plan meets the mirror's properties with a bundle the primary sends and the runner verifies, and defers the importer service until a hosted primary exists. Note: the coordinator's brief quotes the earlier wording of ruling 4 ("the registry leak gap is accepted for a team's own repos in v1"); the spec's later text, written after Fable's H3, says no network for agent code in any project, and this plan follows the spec. *Recommendation:* accept S2-1. |
| -3. **S2-2 and S2-3:** no resolver; no continuation past a 5-minute-old feed. *Recommendation:* accept both. |
| -4. **S2-4:** two VPCs, peered. *Recommendation:* accept; it keeps AWS DNS for the hosts that need it and off for the VMs. |
| -5. **S2-5:** Large VMs for checks, 90-minute lifetime. *Recommendation:* accept. |
| -6. **Who holds the certification key.** The 1b decision says Paul or a named operator, offline. *Recommendation:* Paul, on a machine that is not docs-t1, with the public key in the controller config; each new image needs one signature. |
| +1. **Slice 2 includes the slice 1b foundation** (Phases A to D, Task 28). *Recommendation:* yes; there is no shorter path to a working hosted check. |
| +2. **S2-1, dependencies from the primary, against base pins only, instead of a mirror service.** Spec §16 ruling 4 requires the mirror before hosted code runs; this meets the mirror's properties without the importer, and a candidate that adds a dependency cannot pass hosted checks until a mirror exists. The coordinator's brief quotes the earlier wording of ruling 4 ("the registry leak gap is accepted for a team's own repos in v1"); the spec's later text, written after Fable's H3, says no network for agent code in any project, and this plan follows the spec. *Recommendation:* accept S2-1. |
| +3. **S2-2, S2-3 and S2-10:** no resolver; one expiry rule with no continuation; no mutation-evidence registry in certification. *Recommendation:* accept all three. |
| +4. **S2-4:** two VPCs, peered, with the network audit changed to accept exactly that, and the 1b pinned resolver for proxies dropped. *Recommendation:* accept. |
| +5. **S2-5 and S2-9:** Large VMs, 90-minute lifetime; holds at 4x the baseline rate ($1.86 per job against the $50). *Recommendation:* accept. |
| +6. **Who holds the certification key.** *Recommendation:* Paul, on a machine that is not docs-t1; each new image needs one signature. |
| |
| ## Open questions carried from slice 1a |
| |
| -- The connector's network-interface cleanup permission has never been exercised (Task 17b). Task 30 records it again. |
| -- `internal/hostedctl` already carries a size exception (5,313 / 8,516 lines). Tasks 2 to 4 and 10 add to it; Task 2 splits the store and HTTP layers into `internal/hostedctl/ctlstore` first if the package would pass 6,000 source lines. |
| +- The connector's network-interface cleanup permission has never been exercised (Task 17b). Task 33 exercises it. |