gvisor demos: plan fixes from Opus review round 1
Co-Authored-By: Astra (gpt-6-astra) via codex
1 file changed,
+53
−31
docs/superpowers/plans/2026-11-08-gvisor-demos.md+53 −31
CI passed — run details
Intent
diff --git a/docs/superpowers/plans/2026-11-08-gvisor-demos.md b/docs/superpowers/plans/2026-11-08-gvisor-demos.md| index 3aa4bce7f..53eb72ce4 100644 |
| --- a/docs/superpowers/plans/2026-11-08-gvisor-demos.md |
| +++ b/docs/superpowers/plans/2026-11-08-gvisor-demos.md |
| @@ -8,7 +8,7 @@ |
| **Tech Stack:** Go, Linux systemd/cgroup v2, OCI JSON, runsc `release-20261102.0` with systrap, existing release.Store and signed platform releases. Use standard-library typed OCI structs for the small supported subset; add no container daemon or runtime-spec dependency. |
| -**Spec:** `docs/superpowers/specs/2026-11-08-gvisor-demos-design.md`, rev 5, FINAL. Read §§15–18 as dispositions of the older findings, not alternative requirements. |
| +**Spec:** `docs/superpowers/specs/2026-11-08-gvisor-demos-design.md`, rev 5.1 (rev 5 FINAL plus the runsc key inside the store door grant). Read §§15–18 as dispositions of the older findings, not alternative requirements. |
| ## Global Constraints |
| @@ -18,7 +18,7 @@ |
| - BuildWindow and RuntimeMaxSec stay 180 seconds. Build physical memory is 1107296256 bytes, MemoryHigh=996566625, TasksMax=192 (128 + 64); retain build MemorySwapMax=0. Guest GOMEMLIMIT=966367638 bytes, based on the logical 1 GiB build budget. The warm starter witness must finish in less than 60 seconds. |
| - Root reads no launch JSON, source file, database or WAL to construct a run bundle. Preserve validated staged executable preparation, unprivileged launch parsing, agent-read/root-streamed snapshots, and the unchanged advisory exit-record schema. |
| - Bundles: `/run/carlos-control/oci/<id>`; empty rootfs: `/var/lib/carlos/oci-rootfs`, root:root 0755; runtime state: `/run/carlos-runsc`, owned and cleaned by workload units. Root controller never opens or removes runtime state. |
| -- Keep SystemPointer unchanged. Pin both `linux-arm64` and `linux-amd64`; objects are `bootstrap/runsc/<sha256>/runsc-<plat>` (for example suffix `runsc-linux-arm64`). Assets are optional on historical releases and file uploads. |
| +- Keep SystemPointer unchanged. Pin both `linux-arm64` and `linux-amd64`; objects are `bootstrap/router/runsc-<sha256>/runsc-<plat>` (spec §5 rev 5.1; for example suffix `runsc-linux-arm64`), inside the store door's existing read grant, so there is no store-door change. Use this one key in Tasks 1, 3 and 10. Assets are optional on historical releases and file uploads. |
| - Keep all common signatures portable. `unix`, Linux stat fields, cgroup/mount syscalls and privileged runner bodies belong in `_linux.go`; provide matching `!linux` refusal stubs wherever common code calls them. CGO_ENABLED=0 throughout. |
| - This is one implementation branch and one eventual squash merge, not a sequence of separately deployed scaffolding branches. Its first merge includes working status, demo execution and builds. Dev switch-on is this branch's witness; flagship changes wait for the go-live owners. |
| - All implementation commits use the per-task gate below. Full suites run once at the final gate, not during this planning session or in an iteration loop. Do not change shared caches; scratch and logs go under `~/.cache/gvisor-demos/`, with an explicit inventory and cleanup. |
| @@ -73,7 +73,7 @@ Census is not deferred permission to have red commits: when a task changes in-sc |
| Review classes below mean **Opus per-task** for root, security, termination, cache or production-storage changes, and **branch-only** otherwise. No review agent is dispatched by this document-writing task. Implementation reviewer briefs use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`; a Codex-authored root change gets an Opus/Fable reviewer from the other family. Whole-branch review remains required. |
| -Carry this history in every brief: design R1 5 P1/5 P2; R2 3 P1/4 P2 and repeated-family stop; Paul's A–D ruling; R3 2 P1/2 P2; authorized narrow R4 1 P1; Paul's accepted refusal cut closes design rev 5. **There is no fifth design round.** Implementation review concerns conformance and new implementation defects. Stop at the first round with no P1; apply P2s without another round; list P3s as follow-ups. A fourth implementation review round needs Paul's go. Two successive findings against the same invariant trigger the three-way refusal/cut/enforce-once choice; renaming a task or changing reviewers does not reset the count. |
| +Carry this history in every brief: design R1 5 P1/5 P2; R2 3 P1/4 P2 and repeated-family stop; Paul's A–D ruling; R3 2 P1/2 P2; authorized narrow R4 1 P1; Paul's accepted refusal cut closes design rev 5. **There is no fifth design round.** Plan R1 (Opus): READY AFTER FIXES, no P1, 9 P2 and 14 P3; apply all P2s with the controller decisions and nine selected P3 clarifications, retain the other five below. This closes plan R1 without a new review round. Implementation review concerns conformance and new implementation defects. Stop at the first round with no P1; apply P2s without another round; list P3s as follow-ups. A fourth implementation review round needs Paul's go. Two successive findings against the same invariant trigger the three-way refusal/cut/enforce-once choice; renaming a task or changing reviewers does not reset the count. |
| ### Task 1: Define the portable contract and refuse incomplete gVisor starts |
| @@ -90,14 +90,14 @@ Carry this history in every brief: design R1 5 P1/5 P2; R2 3 P1/4 P2 and repeate |
| - Produces `Parse(getenv func(string) string) (Configured, error)`, `Resolve(configured Configured, demoBox bool) Effective`, `const AutoDemoGVisor = false`. A private `resolve(configured Configured, demoBox, autoDemoGVisor bool) Effective` permits tests of the future behavior without changing the shipped constant. |
| - Produces `const GVisorOverhead int64 = 32 << 20`, `const GVisorTaskOverhead int64 = 64`, `Physical(tier cgroup.Limit) cgroup.Limit`, `PhysicalTasks(native int64) int64`, `GuestMemoryLimit(tier cgroup.Limit) int64` (cgroup.HighOf on logical memory: integer division by 10, then multiplication by 9). Physical adds memory only: cgroup.Limit has no task/CPU fields. Callers apply it only for FamilyGVisor, once. |
| - Produces `BundleDir(id string) string`, `ValidID(id string) bool`; IDs match `[A-Za-z0-9][A-Za-z0-9_.-]{0,254}`, never slashes, backslashes, percent, whitespace or traversal. Invalid IDs yield an empty BundleDir and are refused by callers. |
| -- Produces `type RunscLock struct { Release string; Platforms map[string]RunscPin }`, `type RunscPin struct { TarballURL, TarballSHA512, SHA256 string }`, `LoadRunscLock() (RunscLock,error)`, `RunscFor(platform string) (RunscPin,error)`, `RunscPath(pin RunscPin) string`, `RunscObjectKey(platform string, pin RunscPin) string`. JSON keys: `release`, `platforms`, `tarball_url`, `tarball_sha512`, `sha256`. |
| +- Produces `type RunscLock struct { Release string; Platforms map[string]RunscPin }`, `type RunscPin struct { TarballURL, TarballSHA512, SHA256 string }`, `LoadRunscLock() (RunscLock,error)`, `RunscFor(platform string) (RunscPin,error)`, `RunscPath(pin RunscPin) string`, `RunscObjectKey(platform string, pin RunscPin) string` (returns `bootstrap/router/runsc-<sha256>/runsc-<plat>`; a test pins the exact string). JSON keys: `release`, `platforms`, `tarball_url`, `tarball_sha512`, `sha256`. |
| - Produces `type Launch struct { Nested, Demo, ThroughRoot bool; Role, Runtime string; Generation uint64 }`, `AgentLaunchAllowed(effective Effective, launch Launch) error`. Only nested binary demo run, generation 0, ThroughRoot=true is allowed in gVisor; direct calls set ThroughRoot=false. |
| - Produces host `execSandboxConfig(getenv func(string) string) (execsandbox.Configured, execsandbox.Effective, error)` and fixed `Server.SandboxConfigured`, `Server.SandboxEffective`, `Server.SandboxConfigErr`, `Server.SandboxReady func(context.Context) error`. Initial admission only enforces this for gVisor; systemd remains operational. Config errors are enforced independently of that mode check. Missing gVisor readiness callback refuses admission; it never denotes native compatibility. |
| - [ ] **Step 1: Write failing contract tests.** `TestParseExecSandbox`: unset/auto/systemd/gvisor accepted, whitespace/case/unknown refused with `EXEC-SANDBOX-CONFIG`. `TestResolveExecSandbox`: shipped auto returns systemd for either box; private helper with true flips only demo auto. `TestPhysicalLimits`: small→301989888, build→1107296256; logical inputs unchanged; tasks 256→320 and 128→192; shares from small stay 50/50/50. `TestBundleDir`: `run-demo.example` maps to `/run/carlos-control/oci/run-demo.example`; invalid IDs return empty. `TestAgentLaunchAllowed`: table covers every role/layout/rootfs/gen/direct combination with zero allowed direct spawns in gVisor. |
| - [ ] **Step 2: Run** `go test ./internal/execsandbox ./internal/instancectl ./internal/host -run 'Test(ParseExecSandbox|ResolveExecSandbox|PhysicalLimits|BundleDir|AgentLaunchAllowed|SandboxIncompleteAdmission)' -count=1`; expect undefined interfaces or assertion failures. |
| - [ ] **Step 3: Implement the contract and startup refusal.** Resolve root and agent once, retain errors for readiness/status and log the agent configuration error once. Add admission ahead of all process-start dispatches and demo-build admission; a missing SandboxReady in gVisor returns `EXEC-SANDBOX-RUNSC`, never runs a native probe/build/instance. Preserve stop/reset/sweep endpoints. Refactor the existing early fatal demo+host-claims check in RunInstanceControl/runWithClaim so a gVisor CLAIMS refusal serves cleanup without constructing or enabling the claim launch assembly. Invalid config blocks every start, including non-demo boxes. Inject host.env into control on ordinary boxes too; do not rely on claim/demo-only EnvironmentFile rendering. Later tasks fill the callback, not a new operator switch. |
| -- [ ] **Step 4: Freeze the lock from actual artifacts.** Fetch the immutable `release-20261102.0` tarballs and their upstream SHA512 files, mapping linux-arm64→aarch64 and linux-amd64→x86_64, into task scratch. Verify archive SHA512, extract only the regular `runsc` member, calculate binary SHA256, and write literal lowercase digests into the embedded lock. Never invent or leave placeholder digests, use `latest`, or copy a digest from another architecture. `TestRunscLock` rejects duplicate/missing platform keys, non-HTTPS or non-release-scoped URLs, wrong digest lengths, unknown fields and trailing JSON. Record both verified upstream source URLs in the task review evidence. No downloads execute as root. |
| +- [ ] **Step 4: Freeze the lock from actual artifacts.** Fetch the immutable `release-20261102.0` archives (zstd-compressed tar, `gvisor.tar.zstd` per the spike report REPORT.md:91, not gzip; decode with `github.com/klauspost/compress/zstd`, already a direct dependency at go.mod:91) and their upstream SHA512 files, mapping linux-arm64→aarch64 and linux-amd64→x86_64, into task scratch. Verify archive SHA512, extract only the regular `runsc` member, calculate binary SHA256, and write literal lowercase digests into the embedded lock. Never invent or leave placeholder digests, use `latest`, or copy a digest from another architecture. `TestRunscLock` rejects duplicate/missing platform keys, non-HTTPS or non-release-scoped URLs, wrong digest lengths, unknown fields and trailing JSON. Record both verified upstream source URLs in the task review evidence. No downloads execute as root. |
| - [ ] **Step 5: Run the targeted tests and common gate; refresh census and commit.** Stage only this task's files and cumulative census outputs. Subject: `gvisor demos: define sandbox contract and fail-closed admission`. |
| ### Task 2: Run the real trampoline and measure host-unit hardening |
| @@ -108,14 +108,14 @@ Carry this history in every brief: design R1 5 P1/5 P2; R2 3 P1/4 P2 and repeate |
| - Modify: `internal/instanceexec/exec.go:43`, `internal/instanceexec/init_linux.go:60`, `internal/instanceexec/exit.go:29`, `internal/instanceexec/probe.go:116`. |
| - Create: `internal/instanceexec/sandbox.go`, `sandbox_linux.go`, `sandbox_other.go`, tests; `internal/execsandbox/hardening.go` and tests. |
| - Create: `internal/host/gvisor_hardening_rootrunner_linux_test.go`, `internal/host/gvisor_fixture_rootrunner_linux_test.go`. |
| -- Create: `internal/host/units/carlos-instance-gvisor@.service`, `carlos-instance-gvisor-probe.service`, `carlos-demo-build-gvisor@.service`, using the exact skeletons printed in Task 3 and this task's measured hardening block. Bootstrap wiring comes in Task 3. |
| +- Create: `internal/host/units/carlos-instance-gvisor@.service`, `carlos-instance-gvisor-probe.service`, `carlos-demo-build-gvisor@.service`, using the exact skeletons printed in Task 3 and this task's measured hardening block. Embedded units install as soon as they exist (`go:embed units/*.service`, bootstrap.go:38; `unitNames()`, bootstrap.go:702), so this task also updates `expectedUnits` (host_test.go:33-44) for these three; Task 3 does the same for `carlos-runsc.service` and owns the explicit arming/start wiring. |
| - Read: `internal/instancefs/instancefs_linux.go:20`, `internal/host/units/carlos-instance@.service:14`, `internal/host/units/carlos-demo-build@.service:7`. |
| **Interfaces:** |
| - Produces `execCommand.sandbox execsandbox.Effective`, `gvisorInit(argv0 string, argv, env []string) error`; add `--sandbox=gvisor` before positional arguments. Native flag omission keeps scopedInit. GVisor only accepts binary run without a claim reservation or generation suffix. |
| -- Produces `writeExitRecordOwned(runDir string, role instancectl.Role, inst string, env func(string) string, now time.Time, uid, gid int) error`; native wrapper preserves its signature. A gVisor host hook uses safe O_EXCL open, fchown on that descriptor, 0600, then writes unchanged ExitRecord JSON. |
| +- Produces `writeExitRecordOwned(runDir string, role instancectl.Role, inst string, env func(string) string, now time.Time, uid, gid int) error`; native wrapper preserves its signature. A gVisor host hook opens with `instancefs.OpenBeneath` (no symlink in any component; exit.go:111) plus O_EXCL, fchown on that descriptor, 0600, then writes unchanged ExitRecord JSON. |
| - Produces `execsandbox.GVisorHardening() map[string]string` and `GVisorHardeningLines() string`, returning copies of one pinned, deterministic directive set. Verifiers consume this set, with explicit systemctl normalization mappings in tests. |
| -- Produces self-contained runner fixture `newGVisorFixture(t *testing.T) *gvisorFixture` and rootrunner-only applet dispatch to the real instanceexec RunExec/RunExit/RunProbe functions. It uses the running test executable as the platform trampoline; do not require an untransferred local CLI binary on the remote instance. This early fixture constructs OCI JSON locally in the test from fixed paths; it does not consume Task 4 code or claim to verify the production bundle writer. Task 9 replaces that fixture construction with the completed production path. |
| +- Produces self-contained runner fixture `newGVisorFixture(t *testing.T) *gvisorFixture` and rootrunner-only applet dispatch to the real instanceexec RunExec/RunExit/RunProbe functions. It uses the running test executable as the platform trampoline; do not require an untransferred local CLI binary on the remote instance. This early fixture constructs OCI JSON locally in the test from fixed paths; it does not consume Task 4 code or claim to verify the production bundle writer. It must still use the production shape, not the spike's per-bundle writable rootfs: the shared empty `/var/lib/carlos/oci-rootfs` (root-owned 0755, no entries, `readonly: true`), file bind targets (`/opt/carlos/carlos`, `/opt/carlos/app`) that do not exist in that rootfs, the spec's exact runsc argv with no extra `--overlay2` flag, and the candidate `ProtectSystem=strict`. After each case it asserts the rootfs directory is still empty and unchanged. If mountpoint creation on the empty read-only root cannot work, stop at the refusal as Step 4 says. Task 9 replaces that fixture construction with the completed production path. |
| - [ ] **Step 1: Write failing trampoline tests.** `TestGVisorLaunchValidation` preserves all launch/host/executable/openat2 checks and refuses combined rootfs/claim/unsupported roles. `TestGVisorGuestMemoryLimit` supplies hostile duplicate launch GOMEMLIMIT entries and requires one final root-supplied value, 241591905; read the trusted value from the trampoline's initial environment before parsing launch JSON. `TestGVisorExitRecordOwned` asserts carlos uid/gid, 0600, O_EXCL/no symlink following, native-equivalent JSON and advisory failure semantics. No kind field. |
| - [ ] **Step 2: Run** `go test ./internal/instanceexec -run 'TestGVisor(LaunchValidation|GuestMemoryLimit|ExitRecordOwned)' -count=1`; observe failure, then implement the guest mode. Use existing runInit/runInitChecked with a no-op abstract-scope callback only in gVisor; keep subreaper, fork/setsid, signal forwarding and reaping unchanged. Non-Linux execution returns unsupported. The exit hook's new ownership syscall is Linux-specific. |
| @@ -139,7 +139,7 @@ SystemCallArchitectures=native |
| These are measurement candidates, not claimed passing results. Do not copy native `PrivatePIDs`, `PrivateDevices`, `RestrictNamespaces`, empty CapabilityBoundingSet, MemoryDenyWriteExecute, native syscall filters, or `/run`/`/var` tmpfs overlays. The kernel work needed by root runsc is distinct from the guest's zero capabilities. Exact host hardening is this task's measured output, consumed as a block by all three workload templates. |
| -- [ ] **Step 5: Run the two exact root tests through the contract's script.** All runner files begin `//go:build linux && rootrunner`. Use one serial invocation with `--pkg ./internal/host --run '^(TestRootGVisorHardening|TestRootGVisorTrampoline)$'`. The fixture fetches only pinned runsc artifacts as an explicitly declared network exception; hash before execution. It creates exclusive fixture paths/units and refuses pre-existing production paths, cleans only its own users/mounts/units, and never binds an IP listener off loopback. Runner details and scope are under Task 9. |
| +- [ ] **Step 5: Run the two exact root tests through the contract's script.** All runner files begin `//go:build linux && rootrunner`. Use one serial invocation with `--pkg ./internal/host --run '^(TestRootGVisorHardening|TestRootGVisorTrampoline)$'`. The fixture fetches only pinned runsc artifacts as an explicitly declared network exception; hash before execution. It creates exclusive fixture paths/units and refuses pre-existing production paths, cleans only its own users/mounts/units, and never binds an IP listener off loopback. Runner details and scope are under Task 9. Runner budget (ten total, allocated up front): Task 2 at most 3, Task 9 at most 5, at least 2 held back for the merged-SHA rerun; record each run id against its share. |
| - [ ] **Step 6: Run ordinary tests and common gate, review the measured set, refresh census and commit.** Subject: `gvisor demos: establish guest and host hardening contract`. Record runner run ID and results; pending is not a pass. |
| ### Task 3: Install the runtime and enforce the aware recovery baseline |
| @@ -155,13 +155,13 @@ These are measurement candidates, not claimed passing results. Do not copy nativ |
| **Interfaces:** |
| - Consumes Task 1 pin/path/mode functions and Task 2 hardening output. |
| -- Produces `const Protocol = 1`, package-level `ProtocolMarker []byte` containing exactly `CARLOS-EXEC-SANDBOX-PROTOCOL:1\n`; main references it with `runtime.KeepAlive`. Construct the reader prefix from separate pieces so the full marker prefix is not accidentally embedded twice. |
| +- Produces `const Protocol = 1`, package-level `ProtocolMarker []byte` containing exactly `CARLOS-EXEC-SANDBOX-PROTOCOL:1\n`; main references it with `runtime.KeepAlive`. `ProtocolMarker` is the single declaration of the prefix. Build the reader needle at run time from a non-constant value: a package-level `[]byte` copy of `ProtocolMarker[:len(ProtocolMarker)-2]` (dropping the `1\n` tail, leaving the prefix that ends in a colon; a test asserts the exact bytes). Go folds constant concatenation, so never join constants, and never spell the prefix in an error or log string. A source scan in `TestExecSandboxProtocolReleaseBuild` forbids the literal prefix in every non-test Go source file except that one declaration. |
| - Produces `ScanProtocol(r io.Reader,size int64) (int,error)` for bounded byte parsing, `ReadProtocol(path string) (int,error)`, `AllowsBinary(effective Effective,path string) error`, `type RunscVerifier struct` with `Verify(path string,pin RunscPin) error`. Linux implementation uses no-follow open and fstat; other platforms refuse. Protocol cap is 96 MiB (existing systemArtifactLimit), read in 64 KiB chunks with boundary overlap, exactly one prefix occurrence, nonempty decimal protocol terminated by newline, no overflow. Absent marker means protocol 0; malformed/duplicate marker is an error; awareness is protocol >=1. |
| - Produces host `RunSystemRunscEnsure(args []string)`, `ensureRunsc(ctx context.Context, getenv func(string) string, store release.Store, systemctl func(context.Context,...string)(string,error)) error`, `RunSystemExecSandboxAllowsPrev(args []string)`, `checkExecSandboxBaseline(optDir,unitDir string,recovery []byte) error`. |
| - Produces `Server.SandboxBaseline func() error`, wired in host to the exact embedded recovery bytes, and a runsc verification callback. Add host `verifiedSandboxCandidate(src io.Reader,wantSHA string,effective execsandbox.Effective) ([]byte,error)` for the pre-staging check. Keep host's embedded units out of instancectl's import graph. |
| - [ ] **Step 1: Write floor/installer tests.** `TestExecSandboxFloor` requires unaware target/prev rejection in gVisor and allowance in systemd, malformed setting refusal and no staged unit/journal/binary mutation on rejection. `TestExecSandboxBaselinePresence` table-tests journal plus guard executable, census.json and guard/moves as files, directories, symlinks and dangling links; all present/error cases block with `EXEC-SANDBOX-BASELINE` and path. Test installed recovery bytes differing by one byte. `TestRunscEnsure` covers no-op systemd, absent/bad hash/owner/mode/link count, target pin changes, interrupted temp write, same-version retry and refusal without installation on bad download. `TestRunscIdentityCache` tests dev/inode/size/mtime changes and repeated metadata validation even on a cached hash. |
| -- [ ] **Step 2: Run** `go test ./internal/execsandbox ./internal/host -run 'Test(ExecSandbox|Runsc)' -count=1`; expect failure; implement checked opens and installer. Reuse system-update's store opening and bounded fetching, with a 96 MiB runsc binary cap. Existing runsc requires root-owned 0755, single-link regular file and matching SHA256; validate root-owned ancestors, never follow an attacker-created link. Write an exclusive temp in the pin directory, fsync file, chmod 0755, rename, fsync directory. Cache hashes only on verified identity. Retry the oneshot from Ready with 2,4,8,16,30-second capped backoff and no concurrent retries. |
| +- [ ] **Step 2: Run** `go test ./internal/execsandbox ./internal/host -run 'Test(ExecSandbox|Runsc)' -count=1`; expect failure; implement checked opens and installer. Reuse system-update's store opening and bounded fetching, with a 96 MiB runsc binary cap. A box with its own bucket reads with its bucket credentials; a box without one reads through the store door (agent.go:5438-5470), whose grant covers the rev 5.1 key. On a 404 or refusal runsc-ensure logs the store kind and object key. Task evidence (and the runbook) record the pre-release check that the dev demo box can read `bootstrap/router/runsc-<sha256>/runsc-<plat>` by that path; if it cannot, stop and ask, because changing the door ACL is a spec change. Existing runsc requires root-owned 0755, single-link regular file and matching SHA256; validate root-owned ancestors, never follow an attacker-created link. Write an exclusive temp in the pin directory, fsync file, chmod 0755, rename, fsync directory. Cache hashes only on verified identity. Retry the oneshot from Ready with 2,4,8,16,30-second capped backoff and no concurrent retries. |
| - [ ] **Step 3: Integrate floor before mutable staging and every restore.** Read the candidate once into a buffer bounded by systemArtifactLimit, verify its SHA256 against the signed pointer, then ScanProtocol over that same buffer before stageCandidate clears/creates staging or executes `version`; write precisely those verified bytes to staging and recheck the root-owned staged target with ReadProtocol. Do not hash, rewind and rescan a mutable agent cache file. Check `.prev` before rollback/recovery restoreFiles too. Systemd mode does not require awareness. Result is `refused: exec-sandbox floor`. This closes aware updater paths without changing pointers or introducing a native-unit fence. Baseline uses Lstat absence checks on each Ready; journal absence is not cached. Never alter guard-exec: any retained guard/trigger configuration is refused by Paul's cut. |
| - [ ] **Step 4: Install these exact template skeletons, appending Task 2's pinned hardening block to each of the first three.** Empty ExecStart makes an unprepared template unstartable. Root writes the exact command drop-in below before use. No pin placeholders remain in an installed command. |
| @@ -264,7 +264,7 @@ RuntimeDirectoryPreserve=yes |
| ReadWritePaths=/run/carlos-runsc |
| ``` |
| -Build's per-job drop-in adds only its `work/out`, `work/tmp`, `work/home`, and mounted `work/cache` to ReadWritePaths; diagnostics are opened by systemd before the namespace. No `/work` host bind is needed: OCI mounts individual directories. |
| +Build's per-job drop-in adds its `work/out`, `work/tmp`, `work/home`, and mounted `work/cache` to ReadWritePaths, and carries the same lines as the native drop-in (unit.go:189): the `BindsTo=`/`After=` lines for the work and cache mounts (so the overlay cannot be unmounted under a running build), `StandardOutput=truncate:<work>/diagnostics` and `StandardError=inherit`. Systemd opens diagnostics before the namespace, and the worker parses that file; the template's `StandardOutput=null`/`StandardError=null` are only the defaults the drop-in overrides. `assertUnit` checks these lines. No `/work` host bind is needed: OCI mounts individual directories. |
| `carlos-runsc.service` (no extra measured block): |
| @@ -288,7 +288,7 @@ RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 |
| UMask=0077 |
| ``` |
| -The installer itself reopens root-owned host.env with existing host-env parsing; it does not trust inherited values as its authority. No RemainAfterExit and no writable temp directory outside `/opt/carlos/runsc`. |
| +The installer itself reopens root-owned host.env with existing host-env parsing; it does not trust inherited values as its authority. No RemainAfterExit and no writable temp directory outside `/opt/carlos/runsc`. `UMask=0077` would create the pin directory 0700, so the installer explicitly chmods `/opt/carlos/runsc` and each pin directory to 0755; a test asserts the installer and verifier's ancestor check agree. |
| The control dependency edit is two systemd directives (one logical dependency change): add `Wants=carlos-runsc.service` and append `carlos-runsc.service` to its existing mount `After=` line. Wants rather than Requires keeps control reachable for refusals and cleanup if installation fails. Always render `EnvironmentFile=-/etc/carlos/host.env` once in control. |
| @@ -309,7 +309,7 @@ ExecStopPost=-<pinPath> --root=/run/carlos-runsc delete -force <id> |
| Angle-bracket words here are renderer substitutions, never shell expansion. The minus on delete tolerates an already-absent runtime; acceptance checks must still prove state cleanup, and failures cannot make a live ID reusable. Probe uses id `probe`, same command shape, and no instance-exit hook. Build uses id `build-<hex-job>_<attempt>`, same run/delete shape and no instance-exit hook. Assert the locked runtime's systrap default in Task 2, matching the spec's exact argv; do not introduce a configurable platform. |
| -- [ ] **Step 5: Wire installation and awareness tests.** Bootstrap/apply create rootfs 0755 and `/opt/carlos/runsc` root-owned 0755; controller never creates rootfs. Add templates to bootstrap and missing-unit repair, keeping them unarmed until an explicit start. `TestRunscGarbageCollection` removes an old pin only after complete loaded-unit/job/installed-command inventory proves no ExecStart names it; enumeration failure retains it. Never prune a pin still referenced by a prepared drop-in or active sandbox. `TestExecSandboxProtocolReleaseBuild` uses ScanProtocol on actual `make build GOOS=linux GOARCH=arm64` and amd64 outputs with `-s -w`, and the last published release fixture (unaware), plus duplicate/chunk-boundary/oversize cases. Ordinary tests separately cover ReadProtocol's owner/link/symlink refusals; Task 9 exercises successful ReadProtocol on root-owned installed bytes. Non-root local builds are not passed off as root-owned files. Preserve any pre-existing `carlos` output; use task-owned copies and remove only generated outputs. |
| +- [ ] **Step 5: Wire installation and awareness tests.** Bootstrap/apply create rootfs 0755 and `/opt/carlos/runsc` root-owned 0755; controller never creates rootfs. Add templates to bootstrap and missing-unit repair, keeping them unarmed until an explicit start. `TestRunscGarbageCollection` removes an old pin only after complete loaded-unit/job/installed-command inventory proves no ExecStart names it; enumeration failure retains it. Never prune a pin still referenced by a prepared drop-in or active sandbox. `TestExecSandboxProtocolReleaseBuild` is split. The ordinary half runs `go build -ldflags "-s -w"` (the Makefile's LDFLAGS; not `make build`, which writes `./carlos` and needs git) for linux/arm64 and linux/amd64 into `t.TempDir()`, requires protocol 1 from ScanProtocol on each, and skips only the builds under `testing.Short()`; the source scan above and duplicate/chunk-boundary/oversize cases still run in short mode. Use `-short` during targeted iteration, and record both architecture builds once as Task 3 evidence. `TestExecSandboxProtocolPreviousRelease` reads the unaware binary path from `CARLOS_EXEC_SANDBOX_PREVIOUS_RELEASE` and skips when unset. At implementation time, resolve and record the exact tag of the release immediately before this one (do not guess it), fetch its linux binary once, verify it against that release's signed SHA256SUMS, run the half against it (protocol 0) and record tag, hash and run as Task 3 evidence. Spec §7 needs both halves. Ordinary tests separately cover ReadProtocol's owner/link/symlink refusals; Task 9 exercises successful ReadProtocol on root-owned installed bytes. Non-root local builds are not passed off as root-owned files. Remove only generated outputs. |
| - [ ] **Step 6: Run targeted tests/common gate, review, refresh census and commit.** Subject: `gvisor demos: install pinned runtime and guard recovery`. |
| ### Task 4: Derive OCI bundles without tenant-controlled root reads |
| @@ -339,21 +339,21 @@ Angle-bracket words here are renderer substitutions, never shell expansion. The |
| **Files:** |
| - Modify: `internal/instancectl/names.go:645`, `internal/instancectl/client.go:161`, `internal/instancectl/client.go:322`, `internal/instancectl/client.go:419`, `internal/instancectl/server.go:1047`, `internal/instancectl/legacystart.go:74`. |
| - Create: `internal/instancectl/sandboxstop.go`, `sandboxstop_test.go`. |
| -- Modify: `internal/activator/control.go:18`, `internal/activator/backend_exec.go:2092`, `internal/activator/backend_exec.go:2292`, `internal/activator/backend_exec.go:2351`, `internal/activator/backend_exec.go:2823`, `internal/activator/backend_exec.go:2932`, `internal/activator/genbackend.go:274`, `internal/activator/unitproc.go:140`, `internal/activator/unitproc.go:295`, `internal/activator/maintenance.go:415`, `internal/activator/swap.go:393`. |
| +- Modify: `internal/activator/control.go:18`, `internal/activator/backend_exec.go:2092`, `internal/activator/backend_exec.go:2292`, `internal/activator/backend_exec.go:2351`, `internal/activator/backend_exec.go:2823`, `internal/activator/backend_exec.go:2932`, `internal/activator/genbackend.go:274`, `internal/activator/unitproc.go:140`, `internal/activator/unitproc.go:295`, `internal/activator/maintenance.go:415`, `internal/activator/swap.go:393`, `internal/activator/backend_unit.go:146`, `internal/activator/backend_unit.go:475`, `internal/host/rollout.go:169`. |
| - Create: `internal/activator/sandbox_test.go`, `sandbox_spawn_guard_test.go`; update existing control fakes in `backend_legacy_test.go`, `containment_test.go`, `identity_test.go` and all compiler-identified implementers in this commit. |
| **Interfaces:** |
| - Extend `StartResponse` with `Unit string json:"unit,omitempty"`, `Sandbox execsandbox.Effective json:"sandbox,omitempty"`; keep InvocationID. Add Sandbox to ProbeReport and SeedResponse, and fill it in every start response including one-shot/rootfs native responses. Produce portable `execsandbox.State` with `Configured Configured`, `Effective Effective`, `RunscVersion, RunscSHA256 string`, `Ready bool`, `Blocked string`, with snake_case JSON tags; add `ProbeReport.ExecSandbox *execsandbox.State json:"exec_sandbox,omitempty"`. |
| - Change `Client.Start`, `StartExe`, `StartGen`, `StartGenExe`, `StartSidecarExe`, Cmd/CmdExe, TTY/TTYExe and rootfs start methods from `(string,error)` to `(StartResponse,error)` in one atomic migration. Seed keeps SeedResponse with additive Unit/Sandbox. Change corresponding Control/GenControl/StagedExeControl/RootfsControl/TTYControl and test fakes together. No string-return compatibility wrapper that guesses unit identity. |
| - Keep public Ready/ReadyDemo signatures `(context.Context) error`; Client stores immutable expected effective mode and an internal `readyReport(ctx,path,requireDemo) (ProbeReport,error)`. Missing/unequal root mode is `EXEC-SANDBOX-MISMATCH`, retaining the existing build-header comparison. Add `Client.SandboxStatus(ctx context.Context) (execsandbox.State,error)` which preserves a decoded not-ready report on HTTP 503 and supplies the root state to host reporting; transport failure marks it unavailable, never ready. |
| -- Change `newUnitProcFor(..., started instancectl.StartResponse, ...)` in place of `inv string`; retain `unit`, `invocation` and new `sandbox` on unitProc. Add `UnitIdentity() (string,execsandbox.Effective)` to that concrete handle; optional interface access for status. |
| +- Change `newUnitProcFor(..., started instancectl.StartResponse, ...)` in place of `inv string`; retain `unit`, `invocation` and new `sandbox` on unitProc. Add `UnitIdentity() (string,execsandbox.Family)` to that concrete handle, with the family parsed from the retained unit name (a unit's family, not root's Effective mode; `StartResponse.Sandbox` stays `Effective`); optional interface access for status. |
| - Produces `(s *Server) stopRunFamilies(ctx context.Context, host string) error`, invoked **inside** existing fenceLegacyStarts from `/stop`, plus safe bundle cleanup only after proof. `/stop` input stays host/role, never an agent-supplied unit string. |
| - [ ] **Step 1: Write identity/fence tests.** `TestSandboxStartResponseBinding` rejects empty/wrong family/wrong host/malformed unit fields and proves uncertain cleanup invoked before lease release. `TestGVisorStopLostResponse` drops a successful gVisor start response and proves original-run `/stop` finds it. `TestGVisorStopOvertakesAcceptedStart` pauses before beginLegacyStart registration, lets stop capture connSeq watermark, then resumes; require zero submissions. `TestGVisorStopJoinsStart` covers preparation and last-before-submit cancellation; `TestGVisorStopProofFailure` retains bundle/lease if either family is active, has a queued job, ControlPID, nonempty cgroup, or unreadable proof. |
| - [ ] **Step 2: Run** `go test ./internal/instancectl ./internal/activator -run 'Test(SandboxStartResponseBinding|GVisorStop|AgentSandbox|SandboxSpawnGuard)' -count=1`; expect failure, then migrate responses and callers. Server returns the actual selected unit even in native mode. Stops on a retained handle dispatch by its retained identity's parsed kind; original-run cleanup still asks root to fence and stop both siblings. Observation, cgroup reads, exit attribution, reset and finalization use that retained name, never the route to reconstruct its sandbox family. |
| -- [ ] **Step 3: Extend the existing fence, not a second lock.** Under /stop's host fence, cancel/join original-run starts, derive both original unit names, stop every loaded one, prove invocation inactive/no jobs/empty cgroup and completed stop-post, then remove only that host's bundle before releasing the fence. All start bundle work remains an attempt covered by beginLegacyStart. Add a per-host admission bit under legacyMu to reject a second in-flight gVisor original start; retain existing watermark and join semantics. Do not touch markGenStarting for native generations. Discovery and cleanup remain available with invalid config, claims refusal, missing runtime or changed mode. |
| -- [ ] **Step 4: Gate every direct agent launch.** At ExecBackend.Start and direct entries startChildAt, spawnChildFrom, Seed/SeedExe/seedChild, StartGenExe, sidecar, cmd and tty launch paths, build Launch from actual layout/route/role and call AgentLaunchAllowed before spawning. The primitive spawnInCgroupGated/strict.Start/StartChild sites also refuse gVisor direct work. Config errors remain a separate earlier refusal. `TestAgentSandboxNoNativeSpawn` drives each path with fake spawners and requires calls==0. `TestSandboxSpawnGuard` uses Go AST and an explicit call-site inventory to reject any new exec.Cmd Start/Run/Output/CombinedOutput, StartChild*, strict Start or direct spawn wrapper without a gate; include a fixture showing a renamed/aliased new spawn fails the scan. Treat systemctl control subprocesses as explicit reviewed exemptions, not tenant spawns. |
| -- [ ] **Step 5: Force stop-then-start updates.** Route gVisor demo updates through the existing non-overlap update path for every CARLOS_SWAP value. Both agent staged-generation entry and root gen admission refuse. Test `TestGVisorSwapUsesOriginalRun`: stop proof precedes new bundle/start, generation stays zero, retained identity changes only after successful start. Do not call swapOverlap or invent gVisor generations. |
| +- [ ] **Step 3: Extend the existing fence, not a second lock.** Under /stop's host fence, cancel/join original-run starts, derive both original unit names, stop every loaded one, prove invocation inactive/no jobs/empty cgroup and completed stop-post, then remove only that host's bundle before releasing the fence. All start bundle work remains an attempt covered by beginLegacyStart. Add a per-host admission bit under legacyMu to reject a second in-flight gVisor original start; retain existing watermark and join semantics. Do not touch markGenStarting for native generations. When the join times out, the fence-failure branch (server.go:1072-1078; rootfs.go:1153-1160) stops both families, not only the native unit; the answer is still an error and the lease is kept. Discovery and cleanup remain available with invalid config, claims refusal, missing runtime or changed mode. |
| +- [ ] **Step 4: Gate every direct agent launch.** Gate `SplitBackend.Start` and `StartGen` (backend_unit.go:475-500), or each `Backend.Start` including `UnitBackend.Start` (backend_unit.go:146-163, `systemctl start carlos-app@<host>`), so a unit-backed row on an effective-gVisor box cannot run natively. At ExecBackend.Start and direct entries startChildAt, spawnChildFrom, Seed/SeedExe/seedChild, StartGenExe, sidecar, cmd and tty launch paths, build Launch from actual layout/route/role and call AgentLaunchAllowed before spawning. The primitive spawnInCgroupGated/strict.Start/StartChild sites also refuse gVisor direct work. Config errors remain a separate earlier refusal. `TestAgentSandboxNoNativeSpawn` drives each path, including the unit-backed row, with fake spawners and requires calls==0. `TestSandboxSpawnGuard` uses Go AST and an explicit call-site inventory to reject any new exec.Cmd Start/Run/Output/CombinedOutput, StartChild*, strict Start or direct spawn wrapper without a gate; include a fixture showing a renamed/aliased new spawn fails the scan. The guard's systemctl exemption covers only verbs that do not start a tenant (show, stop, reset-failed, daemon-reload); `start`/`restart` of `carlos-app@` must be gated, and the scan fails on any ungated one. |
| +- [ ] **Step 5: Force stop-then-start updates.** The switch that turns generations on is `swapArming` (rollout.go:169-192, used at agent.go:620-622), not swap.go:393. In gVisor mode `swapArming` declines with a published reason code, as it does for host claims (rollout.go:173-178), so generations, containment and `Service.Swap` all stay off for every CARLOS_SWAP value (otherwise `swapOverlap` asks root for `StartGenExe`, which root refuses, and `swapHold` stops the incumbent then pins a wake to a refused generation). Every update then takes today's stop-then-wake paths. Both agent staged-generation entry and root gen admission refuse. Test `TestGVisorSwapUsesOriginalRun` sets `CARLOS_SWAP=overlap` and asserts zero `StartGen*` calls and no generation-pinned hold; stop proof precedes new bundle/start, generation stays zero, retained identity changes only after successful start. Do not call swapOverlap or invent gVisor generations. |
| - [ ] **Step 6: Run targeted tests/common gate, review, refresh census and commit.** Subject: `gvisor demos: retain unit identity and fence both families`. |
| ### Task 6: Select, verify and probe the gVisor run family |
| @@ -367,14 +367,14 @@ Angle-bracket words here are renderer substitutions, never shell expansion. The |
| - Modify: `internal/host/demo_policy.go:33`, `internal/host/claimstop_run.go:23`; test the dispatch inventory below. |
| **Interfaces:** |
| -- Produces `(s *Server) unitFamily(effective execsandbox.Effective, role Role, route *registry.Route) (execsandbox.Family,error)`. Private roles `roleGen`, `roleProbe`, `roleBuild` are root-internal and rejected by ParseRole. All public starts pass the validated registry route; only root probe/build calls permit nil route with DemoBox=true. HostClaims is a fixed Server flag from hostwrite.Enabled. |
| +- Produces `(s *Server) unitFamily(effective execsandbox.Effective, role Role, route *registry.Route) (execsandbox.Family,error)`. It returns only the fixed policy (mode, role, route, claims flag, demo box); readiness (RUNSC, BASELINE, DRAIN, OVERLAP) never flows through it and stays in `gvisorReady` and the per-build proof callback. Private roles `roleGen`, `roleProbe`, `roleBuild` are root-internal and rejected by ParseRole. All public starts pass the validated registry route; only root probe/build calls permit nil route with DemoBox=true. HostClaims is a fixed Server flag from hostwrite.Enabled. |
| - Produces `(s *Server) assertGVisorUnit(ctx context.Context,host,unit string) error`, `(s *Server) gvisorReady(ctx context.Context) error`, `(s *Server) runGVisorProbe(ctx context.Context) ProbeReport`, `(s *Server) assertSandboxDrain(ctx context.Context) error`. |
| - Produces `demoSizeShown(out string,family execsandbox.Family) error`; existing demoCgroup(host,unit) derives family from the validated unit. Add `sliceTierFor(..., logical cgroup.Limit,family execsandbox.Family) error`; retain native sliceTier wrapper for existing claim callers. |
| -- [ ] **Step 1: Write policy/readback tests.** `TestGVisorFamilyPolicy` covers every refusal code: CONFIG, UNSUPPORTED (non-demo box/route), ROOTFS, CLAIMS, ROLE (including gen), RUNSC, BASELINE, DRAIN, OVERLAP and MISMATCH. `TestGVisorUnitMutations` independently mutates every expected property, runsc pin/path/argv, drop-in reload state, bundle byte and parent/kernel limit; each refuses before start. `TestGVisorConcurrentStart` interleaves two starts and a stop around bundle write/readback; at most one submission, no live bundle replacement. `TestGVisorLimits` requires both parent and child physical memory/high/swap/tasks and logical CPU/IO values. |
| +- [ ] **Step 1: Write policy/readback tests.** `TestGVisorFamilyPolicy` covers the fixed-policy refusal codes: CONFIG, UNSUPPORTED (non-demo box/route), ROOTFS, CLAIMS, ROLE (including gen) and MISMATCH; a sibling case through `gvisorReady` covers RUNSC, BASELINE, DRAIN and OVERLAP. `TestGVisorUnitMutations` independently mutates every expected property, runsc pin/path/argv, drop-in reload state, bundle byte and parent/kernel limit; each refuses before start. `TestGVisorConcurrentStart` interleaves two starts and a stop around bundle write/readback; at most one submission, no live bundle replacement. `TestGVisorLimits` requires both parent and child physical memory/high/swap/tasks and logical CPU/IO values. |
| - [ ] **Step 2: Run** `go test ./internal/instancectl ./internal/instanceexec -run 'TestGVisor(Family|Unit|Concurrent|Limits|Probe|Drain|Dispatch)' -count=1`; expect failure, then implement root selection. Build/probe use this same selector via a callback; demobuild never duplicates policy or imports instancectl. In systemd mode preserve each existing native/rootfs dispatch. In gVisor mode assert the baseline and verified pin on every Ready/ReadyDemo request and before any probe or start; refuse unsupported roles before preparing their files. Check no active unit/nonempty cgroup/queued start of either family for the host before bundle preparation. Recheck the attempt context immediately before systemctl submission. |
| -- [ ] **Step 3: Write the run drop-in and verify its effective state.** Use Task 3 command recipe, Task 4 exact BundleDir, physical limits and pinned hardening. Read User=root, Group=root, Type=exec, Slice, KillMode, restart/stop dependencies, stop timeout, ordered pre/start/post commands, pin path, all hardening properties and NeedDaemonReload=no from systemctl; compare structured command arguments, not substrings. Rebuild and compare bundle bytes. Read parent and child memory.max/high/swap.max, pids.max, cpu.max/weight and io.weight. Native demo.conf is never applied to gVisor units. Probe uses the same bundle writer and verifier with its own fixed slice/limits/output contract. |
| -- [ ] **Step 4: Implement the guest probe and root proof.** `TestGVisorProbeChecks` has one failing case per check: numeric carlos uid/gid; CapEff=0; NoNewPrivs=1; locked runsc's gVisor uname/proc-version signature; io_uring_setup=ENOSYS; only loopback; public TCP connect refused; root-created abstract socket unreachable; root fixture outside mounts absent; guest Unix socket created in host-visible run dir and dialled by root. Use a named check token per assertion in ProbeReport. Challenge nonce and socket names are root-derived. Root verifies actual runsc/gofer/Sentry/helper PIDs belong to the unit subtree while running, then waits for stop-post and empty cgroup. `TestGVisorProbePinChange` invalidates a pass when pin/verified identity changes; failed probe blocks starts and records a bounded journal diagnostic. ReadyDemo requires this pass. Do not run native or rootfs probes as a fallback. |
| +- [ ] **Step 3: Write the run drop-in and verify its effective state.** Use Task 3 command recipe, Task 4 exact BundleDir, physical limits and pinned hardening. Read User=root, Group=root, Type=exec, Slice, KillMode, restart/stop dependencies, stop timeout, ordered pre/start/post commands, pin path, all hardening properties and NeedDaemonReload=no from systemctl; compare structured command arguments, not substrings. Rebuild and compare bundle bytes. Read parent and child memory.max/high/swap.max, pids.max, cpu.max/weight and io.weight. Native demo.conf is never applied to gVisor units. Probe uses the same bundle writer and verifier with its own fixed slice/limits/output contract. A start never removes the bundle itself, including on the start-failure paths (`abandonUnit` after `demoCgroup`, server.go:906-909): removal happens only under `/stop`'s fence after proof, or by rewriting at the next proven-idle start. |
| +- [ ] **Step 4: Implement the guest probe and root proof.** `TestGVisorProbeChecks` has one failing case per check: numeric carlos uid/gid; CapEff=0; NoNewPrivs=1; locked runsc's gVisor uname/proc-version signature; io_uring_setup=ENOSYS; only loopback; public TCP connect refused; root-created abstract socket unreachable; root fixture outside mounts absent; guest Unix socket created in host-visible run dir and dialled by root. Use a named check token per assertion in ProbeReport. Challenge nonce and socket names are root-derived. Root verifies actual runsc/gofer/Sentry/helper PIDs belong to the unit subtree while running, then waits for stop-post and empty cgroup. `TestGVisorProbePinChange` invalidates a pass when pin/verified identity changes; failed probe blocks starts and records a bounded journal diagnostic. ReadyDemo requires this pass. Do not run native or rootfs probes as a fallback. The probe id `probe` is reused: rewrite `/run/carlos-control/oci/probe` only after the previous probe invocation is proven inactive with an empty cgroup. |
| - [ ] **Step 5: Make all discovery family-aware.** `TestGVisorDispatchInventory` drives every row below with fake systemctl; no native start/restart in gVisor. `TestGVisorDrain` proves active/opposite-family/nonempty/queued units block Ready and stop endpoints still work; drain succeeds after proven cleanup. Cleanup of stale bundles uses the same original-run fence. Runtime-state cleanup goes through the owning unit's delete hook; controller never traverses `/run/carlos-runsc`. Retained pin-specific drop-ins are kept until cleanup finishes, then removed and daemon-reloaded. |
| | Boundary | Required treatment | |
| @@ -406,14 +406,14 @@ Angle-bracket words here are renderer substitutions, never shell expansion. The |
| **Interfaces:** |
| - Produces `(w *Worker) gvisorBuildBundle(l buildLayout) ([]byte,error)`, using Task 4's OCI structs and shared WriteBundle/ReadBundle; `buildLayout` gains `family execsandbox.Family`, `id string`. Produce `layoutFor(root,dir string,family execsandbox.Family) (buildLayout,error)`; keep existing layout/layoutIn as native wrappers for compatibility, while all Worker execution uses layoutFor with its captured family and recovery explicitly constructs both. |
| -- Add `Worker.family execsandbox.Family`; change `NewWorker(getenv,proof)` to `NewWorker(getenv func(string)string,proof func(context.Context)error,family func()(execsandbox.Family,error)) (*Worker,error)` and all callers together. The supplied root callback invokes Task 6 unitFamily with roleBuild; worker captures its result once. Every build rechecks root proof before dispatch. |
| +- Add `Worker.family execsandbox.Family`; change `NewWorker(getenv,proof)` to `NewWorker(getenv func(string)string,proof func(context.Context)error,family func()(execsandbox.Family,error)) (*Worker,error)` and all callers together. The supplied root callback invokes Task 6 unitFamily with roleBuild, which returns only the fixed policy, so capturing its result once cannot latch a transient refusal. Readiness (RUNSC, BASELINE, DRAIN, OVERLAP) stays in the per-build proof callback, which every build rechecks before dispatch. `NewWorker` never fails on readiness, and sandbox refusals no longer reach the `log.Fatalf` path in `runWithClaim` (server.go:343-358), so a roll with the journal open or runsc not yet installed leaves builds off without restart-looping control. |
| - Produce `SlicePropertiesFor(slots int,family execsandbox.Family) map[string]int64`; keep native SliceProperties wrapper. Add the resolved mode to claimUnitSettings and have claimUnitContent use SlicePropertiesFor for the installed build slice; validate its readback in Worker.assertBudget. Configured concurrency remains 1–4. Family-specific layout uses one existing validated hex-job/attempt key; never trust a supplied unit/bundle path. |
| - Fixed guest build uid/gid = 65534/65534; root unit stays uid 0. No DynamicUser or guest host-passwd lookup for compilation. |
| - [ ] **Step 1: Write `TestGVisorBuildBundle`, `TestGVisorBuildOwnership`, `TestGVisorBuildBudget`, `TestGVisorBuildRecoveryBothFamilies`, `TestGVisorBuildWindow`.** Require only intended guest mounts; directories out/tmp/home 65534:65534 0700; source/toolchain/backing dirs/lower files remain root-owned. Snapshot lower-layer file inode/bytes and upper-layer contents around ownership changes: no cache-file copy-up. For slots 1–4 assert parent MemoryMax=slots*1107296256, TasksMax=slots*192, CPUQuota=slots*50, swap=0. Assert signed deadline, transport, worker and unit all retain 180 seconds. Recovery stops both named families before any mount/bundle removal and retains work on failed proof. |
| - [ ] **Step 2: Run** `go test ./internal/demobuild ./internal/instancectl ./internal/host -run 'TestGVisorBuild|TestDemoBuild' -count=1`; expect failure, then implement family-aware prepareUnit/runUnit/assertUnit/cleanUnit/recover. Write bundle after source extraction and overlay mount. Change ownership on only out/tmp/home and mounted cache **directories** (directory mode 0700 owned by build uid), never recursively chown files or cache backing trees. Individual guest mounts prevent traversal to backing directories. |
| - [ ] **Step 3: Set guest process and mounts.** Argv is `/opt/carlos/demo-toolchain/bin/go build -mod=readonly -trimpath -buildvcs=false -o /work/out/app .`; cwd `/work/src`; environment exactly BuildEnvironment() plus GOMEMLIMIT=966367638. No inherited host env, loader variables or additional Go flags. OCI RLIMIT_FSIZE soft/hard=33554432, umask=0077. Toolchain including module cache and source are ro; `/work/out`, `/work/tmp`, `/work/home`, mounted `/work/cache` rw; guest proc/dev/tmp as Task 4, no host work root or backing dirs. Root-owned source archive parsing remains today's validated extraction, not a new launch-command source. |
| -- [ ] **Step 4: Verify unit/readback and recovery.** Build assertUnit consumes measured hardening and exact Task 3 command recipe; check Type=exec, RemainAfterExit, no DynamicUser, deadlines, limits, slice and byte-identical bundle. Recover enumerates both families for each validated job attempt regardless of current mode, proves both stopped/empty and runtime delete complete, then unmounts overlay/work and removes bundle. Initialization failure keeps the worker closed while cleanup can retry. Build readiness probe uses the selected family and the real warm toolchain cache; never retry a failed gVisor compilation natively. |
| +- [ ] **Step 4: Verify unit/readback and recovery.** Build assertUnit consumes measured hardening and exact Task 3 command recipe; check Type=exec, RemainAfterExit, no DynamicUser, deadlines, limits, slice, byte-identical bundle, the `BindsTo`/`After` work and cache mount lines, and `StandardOutput=truncate:<work>/diagnostics` with `StandardError=inherit`. `TestGVisorBuildBundle` or a runner case asserts a compile error reaches the diagnostics file, with runsc's own stderr lines bounded and not mistaken for compiler output. Recover enumerates both families for each validated job attempt regardless of current mode, proves both stopped/empty and runtime delete complete, then unmounts overlay/work and removes bundle. Initialization failure keeps the worker closed while cleanup can retry. Build readiness probe uses the selected family and the real warm toolchain cache; never retry a failed gVisor compilation natively. |
| - [ ] **Step 5: Run targeted tests/common gate, review, refresh census and commit.** Subject: `gvisor demos: build offline demos in pinned sandboxes`. |
| ### Task 8: Report actual sandbox identity and logical size |
| @@ -427,7 +427,7 @@ Angle-bracket words here are renderer substitutions, never shell expansion. The |
| **Interfaces:** |
| - Add `type ExecSandbox struct { Configured string; Effective string; Runsc *RunscStatus; Ready bool; Blocked string }`, `type RunscStatus struct { Version string; SHA256 string }` in status with snake_case JSON tags. `LayoutReport.ExecSandbox *ExecSandbox json:"exec_sandbox,omitempty"`; `RowLayout.Sandbox string json:"sandbox,omitempty"`. |
| -- Add `Unit string`, `Sandbox execsandbox.Effective` to activator.SizeState, populated from retained unitProc under existing Service locking. Change `readSizeInForce(cgroupRoot,host,unit string,sandbox execsandbox.Effective) (cgroup.Size,bool)`; never reconstruct a gen name. Empty identity means unknown where a live nested unit is expected. |
| +- Add `Unit string`, `Sandbox execsandbox.Family` to activator.SizeState (the unit's family, parsed from the retained unit name; not the Effective mode), populated from retained unitProc under existing Service locking. Change `readSizeInForce(cgroupRoot,host,unit string,sandbox execsandbox.Family) (cgroup.Size,bool)`; never reconstruct a gen name. Empty identity means unknown where a live nested unit is expected. |
| - Add the corresponding fields to console API and CLI structs; no public fleet/private-metrics boundary changes. |
| - [ ] **Step 1: Write `TestExecSandboxStatus`, `TestGVisorSizeInForce`, `TestGVisorExitAttribution`, `TestStatusLayoutSandbox`.** JSON round-trip covers configured/effective/pin/ready/blocked; old payload omits fields and displays unknown. GVisor unit memory.max=301989888 maps to small, native 268435456 maps to small, other/unreadable values remain unknown. Assert observed unit from handle wins over configured mode and route-derived native name. Exit text is exactly `exit status via gVisor`; do not attribute advisory records to app versus runtime. |
| @@ -466,13 +466,25 @@ Angle-bracket words here are renderer substitutions, never shell expansion. The |
| For negative probe checks that the real runtime cannot deliberately produce (for example io_uring support), inject that single observation into the production check function while the remaining observations come from the running guest. Label those subcases check-function fault injection, not proof that gVisor can be reconfigured into that state. Real network/outside-file/abstract/UDS violations use disposable mutated bundles and must never be accepted for tenant starts. |
| - [ ] **Step 2: Compile locally first.** `CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go test -c -tags rootrunner -o "$HOME/.cache/gvisor-demos/gvisor-rootrunner.test" ./internal/host`. Ordinary targeted regression tests and common gate must still pass; no rootrunner dependency leaks into normal CI or non-Linux builds. |
| -- [ ] **Step 3: Run serially, sandbox off, using the existing unmodified script.** Read `~/.cache/tmp/claude-1001/own/after236/root-runner-contract.md` in full before execution. Script: `~/.cache/tmp/claude-1001/own/after236/root-runner.py`. Scope: profile kass, account 640012953448, eu-west-1, throwaway t4g.small, runner's fixed subnet/security-group/SSM instance profile, 30 GiB gp3 deleted on termination. Do not edit runner/contract, create IAM, or use a real demo box. The contract authorizes this sandbox; it does not authorize the dev rollout. At most ten total invocations for this run, counting Task 2; one invocation at a time. Batch the exact names above into one anchored regex, never `TestRoot` or payload helper selectors. |
| +- [ ] **Step 3: Run serially, sandbox off, using the existing unmodified script.** Read `~/.cache/tmp/claude-1001/own/after236/root-runner-contract.md` in full before execution. Script: `~/.cache/tmp/claude-1001/own/after236/root-runner.py`. Scope: profile kass, account 640012953448, eu-west-1, throwaway t4g.small, runner's fixed subnet/security-group/SSM instance profile, 30 GiB gp3 deleted on termination. Do not edit runner/contract, create IAM, or use a real demo box. The contract authorizes this sandbox; it does not authorize the dev rollout. At most ten total invocations for this run, counting Task 2; one invocation at a time. Budget: Task 2 at most 3, Task 9 at most 5, at least 2 held back for the merged-SHA rerun; record each run id against its share. Batch the exact names above into one anchored regex, never `TestRoot` or payload helper selectors. |
| ```sh |
| python3 -u /home/paulca/.cache/tmp/claude-1001/own/after236/root-runner.py --worktree "$PWD" --pkg ./internal/host --run '^(TestRootGVisorHardening|TestRootGVisorTrampoline|TestRootGVisorGracefulStop|TestRootGVisorKillRestart|TestRootGVisorOOM|TestRootGVisorProbe|TestRootGVisorBuild|TestRootGVisorRecoveryUnawarePrev|TestRootGVisorClaimSnapshot|TestRootGVisorModeDrain)$' |
| ``` |
| -Fixture artifact downloads explicitly allow HTTPS reads of pinned runsc and the existing locked demo toolchain; no other external test traffic except IMDS and the bounded refused public-connect probe. Before the runner invocation, obtain the existing operator toolchain archive reference and verify it with demobuild.DefaultLock/CheckBundle; freeze its immutable read-only download URL and SHA256 as test-fixture inputs alongside the runsc pin. This is a fixture prerequisite, not a new toolchain distribution service. Include its prebuilt cache and re-run CheckBundle after remote extraction. Obtain artifacts inside the remote fixture because the runner transfers one test binary only. If that archive is not reachable within the stated read-only network exception, keep acceptance pending; do not widen the runner IAM or upload objects outside its contract. All locally started listeners bind 127.0.0.1 or Unix sockets. Record wall time; a 60-second warm-build failure keeps gVisor builds refused and returns §9 for a decision, never increases BuildWindow. Root recovery applet execution is real; an unaware sentinel fixture only records erroneous execution and does not claim to be an actual released binary. Task 3 separately tests the actual previous release's marker. |
| +Fixture network exceptions: HTTPS reads of the pinned runsc, and one presigned-URL GET of the toolchain bundle below; no other external test traffic except IMDS and the bounded refused public-connect probe. The runner transfers one test binary only, so the fixture fetches both artifacts itself. |
| + |
| +**Toolchain bundle (future implementation gate, built locally before the warm-build invocation).** No published archive with a URL exists and the repo has no bundle builder, so build it: |
| + |
| +1. Re-read root-runner-contract.md. It limits the runner to its throwaway instance and says "never touch anything else in AWS". If it does not explicitly cover uploading a fixture object under `s3://carlos-dev-640012953448/root-runner/gvisor-demos/` with profile kass, **stop and ask before uploading**, stating bucket, key, size, expiry and cleanup. Otherwise cite the covering clause. (Editing this plan needs no ask.) |
| +2. Under task scratch `~/.cache/gvisor-demos/bundle/`, assemble a directory in CheckBundle's MANIFEST format (demobuild bundle.go:23; plan 2026-11-02 line 271): the go.dev Go 1.26.10 linux-arm64 tarball verified against its published SHA256 before extraction; a module cache filled from demobuild's embedded lock (`toolchain.lock.json`), each module's sum checked against the lock, with the private `amadan.net/rastrillo` modules taken from authorized local source at the locked versions (proxy.golang.org cannot serve them); a prebuilt warm cache from a Go 1.26.10 starter build targeting linux/arm64, copying the needed entries from the default build cache into the bundle without changing GOCACHE; and the MANIFEST. Its first lines are `go<TAB>1.26.10` and `modules<TAB><lock.ModulesDigest()>`, then path-sorted file rows (path, four-digit octal mode, decimal size, SHA256), with LF endings and final LF. Include every regular file except MANIFEST once, modes 0444/0555, no links or special files. Validate the manifest bytes and file hashes locally; the real CheckBundle ownership check runs after root-owned extraction on the runner. |
| +3. Tar it, record its SHA256 and size. Ask first if it exceeds a few GB. |
| +4. After the step-1 clearance, upload with `aws --profile kass --region eu-west-1 s3 cp` to `s3://carlos-dev-640012953448/root-runner/gvisor-demos/<sha256>.tar`, and nothing else. |
| +5. Presign a short-lived GET URL and pass it with the SHA256 as fixture inputs, like the test binary (generated untracked input or linker variable; the signed URL is never committed or logged). |
| +6. The remote fixture fetches the URL, rechecks the SHA256, extracts into its root-owned scratch directory, preserves immutable file modes and root-owned non-writable-by-others ancestors, and runs `demobuild.CheckBundle` against `DefaultLock` before the build test. |
| +7. After the final invocation, delete only that own object (`aws s3 rm` on its exact key) and the local scratch, and record both in the report. |
| + |
| +If the upload is not cleared, or the bundle cannot be built, keep `TestRootGVisorBuild` pending; do not widen the runner IAM or touch other objects. All locally started listeners bind 127.0.0.1 or Unix sockets. Record wall time; a 60-second warm-build failure keeps gVisor builds refused and returns §9 for a decision, never increases BuildWindow. Root recovery applet execution is real; an unaware sentinel fixture only records erroneous execution and does not claim to be an actual released binary. Task 3 separately tests the actual previous release's marker. |
| - [ ] **Step 4: Check cleanup after every invocation and the final one.** Use the contract's read-only EC2 list for pending/running `purpose=plan14-root-runner`; terminate only an instance whose Name contains this invocation's printed run ID. Verify termination even after failure and remove only task-owned local scratch. Record failures as **Root-runner acceptance: pending**, with failure lines. Historical spike passes do not count for the current tip. |
| - [ ] **Step 5: Review acceptance evidence, refresh census if fixture bytes are in scope, and commit.** Subject: `gvisor demos: prove sandbox lifecycle on the root runner`. Repeat this exact inventory on the merged SHA before release, within the recorded invocation budget; a budget exhausted before a pass is a stopping point, not permission to invent success. |
| @@ -489,12 +501,12 @@ Fixture artifact downloads explicitly allow HTTPS reads of pinned runsc and the |
| **Interfaces:** |
| - Produces `publicrelease.RunscAssetName(platform string) string`, `Feed.OptionalAsset(ctx context.Context,tag,asset string,limit int64) (data []byte,sha string,present bool,err error)`, `(s *Server) mirrorRunscArtifact(ctx context.Context,platform string,data []byte,sha string) error`. |
| -- Cut helper interface: `go run ./cmd/runsc-assets -out <existing-cut-artifact-directory>`. It reads the embedded lock, verifies tarball SHA512 before extraction and binary SHA256 afterward, then writes only `runsc-linux-arm64` and `runsc-linux-amd64`, mode 0755. Output must be beneath the explicit cut directory; safe bounded extraction never follows archive links. |
| +- Cut helper interface: `go run ./cmd/runsc-assets -out <existing-cut-artifact-directory>`. It reads the embedded lock, verifies the SHA512 of the zstd-compressed upstream archive (`gvisor.tar.zstd`, decoded with the already-direct `github.com/klauspost/compress/zstd`) before extraction and binary SHA256 afterward, then writes only `runsc-linux-arm64` and `runsc-linux-amd64`, mode 0755. Output must be beneath the explicit cut directory; safe bounded extraction never follows archive links. |
| - [ ] **Step 1: Write `TestRunscAssets`, `TestOptionalRunscAsset`, `TestRunscMirror`.** Reject wrong archive/binary hash, duplicate member/link/traversal/oversize archives. Optional absence is only absence from the **verified signed checksum list**; advertised-but-missing, wrong hash, bad signature and transport failure are errors. Test present and absent assets, historical release and --file upload, existing identical object, collision and CAS retry. Mirror uses asset SHA256 from signed sums, not the console's own compiled runsc pin, so an older aware console can mirror a newer target pin. |
| -- [ ] **Step 2: Run** `go test ./cmd/runsc-assets ./internal/publicrelease ./internal/console -run 'Test(RunscAssets|OptionalRunscAsset|RunscMirror)' -count=1`; expect failure, then implement. In runSystemUpdate's release branch, mirror available linux platform runsc assets before promotion. Content-addressed key and bytes must agree. File-upload branch is unchanged. No pointer field, unconditional historical download, or silent corruption skip. |
| +- [ ] **Step 2: Run** `go test ./cmd/runsc-assets ./internal/publicrelease ./internal/console -run 'Test(RunscAssets|OptionalRunscAsset|RunscMirror)' -count=1`; expect failure, then implement. In runSystemUpdate's release branch, mirror available linux platform runsc assets before promotion. Content-addressed key (`bootstrap/router/runsc-<sha256>/runsc-<plat>`) and bytes must agree. File-upload branch is unchanged. No pointer field, unconditional historical download, or silent corruption skip. |
| - [ ] **Step 3: Write the internal runbook through the repository's prose workflow.** State the operator rule prominently: set gvisor only after `carlos status --layout` already displays the exec-sandbox line. State that an unaware binary cannot enforce this setting, and that old-pointer bootstrap/reimage with a retained gvisor setting remains outside this build. Carry a bootstrap-script check as a follow-up on the branch; do not build it here or reopen the closed design. |
| -- [ ] **Step 4: Include the exact release/dev sequence.** Coordinate version/window with manager 8a3d302 and the quoted go; feed cut helper outputs into the existing release cut **before** SHA256SUMS.txt generation/signing and GitHub release attachment. Verify both assets appear in signed sums and match the lock. For a console too old to mirror them, the release agent copies the two verified objects to the dev bucket once within approved scope; document keys and verification, not credentials. Roll aware release with systemd mode first, wait for the apply journal to close and status line to appear, verify guard artifacts absent and recovery unit current, drain, then explicitly set gvisor in root-owned host.env and restart control and agent. Check Ready/probe/pin, box line and instance column, create/build/wake/claim and response version from the newly built release. Keep flagship out of scope. Rollback: set systemd, restart and drain/prove previous family gone, verify systemd status, then roll below the awareness floor if needed. Auto remains systemd; its follow-up change is not part of this release. |
| +- [ ] **Step 4: Include the exact release/dev sequence.** Coordinate version/window with manager 8a3d302 and the quoted go; feed cut helper outputs into the existing release cut **before** SHA256SUMS.txt generation/signing and GitHub release attachment. Verify both assets appear in signed sums and match the lock. For a console too old to mirror them, the release agent copies the two verified objects to the dev bucket once within approved scope, under the `bootstrap/router/runsc-<sha256>/runsc-<plat>` keys; document keys and verification, not credentials. Before the release, confirm the dev demo box can read that key (through the store door or its bucket role); if not, stop and ask, since changing the door is a spec change. Roll aware release with systemd mode first, wait for the apply journal to close and status line to appear, verify guard artifacts absent and recovery unit current, drain, then explicitly set gvisor in root-owned host.env and restart control and agent. Check Ready/probe/pin, box line and instance column, create/build/wake/claim and response version from the newly built release. Keep flagship out of scope. Rollback: set systemd, restart and drain/prove previous family gone, verify systemd status, then roll below the awareness floor if needed. Auto remains systemd; its follow-up change is not part of this release. |
| - [ ] **Step 5: Record the scoped rollout approval requirement.** Before any dev domain/resource/host configuration mutation, present the actual account, region, box/domain, exact host.env/restart/release/object changes, permissions/traffic, duration/cost, cleanup and checks. Reuse any already granted matching scope. Do not confuse the designated runner scope with dev-box authorization. |
| - [ ] **Step 6: Run targeted tests/common gate, review, refresh census and commit.** Subject: `gvisor demos: prepare runtime release assets and dev rollout`. |
| @@ -516,3 +528,13 @@ Fixture artifact downloads explicitly allow HTTPS reads of pinned runsc and the |
| - [ ] **Step 4: Obtain whole-branch and census verdicts.** Stop at the first no-P1 round, apply its P2s, keep P3 follow-ups on the branch. Record the independent census verdict, reviewer and full tip on #280. No fourth review or repeated-family third fix without the required decision. Describe the branch with final behavior, tests, runner run IDs and rollout gates. |
| - [ ] **Step 5: Commit the final census changes with a short subject and real body newlines.** Push only during the authorized implementation session to the amadan remote, check CI green on the exact full tip, then use `amadan branch merge carlos/platform gvisor-demos -squash -expect <full-tip> -message <short-subject-and-body>`. Check main CI after merge; mirror only already-landed main to GitHub if needed. No GitHub PR/merge. This planning session stops at its one local plan commit and does not perform this step. |
| - [ ] **Step 6: Complete the release/dev phase only in its approved window.** Re-run privileged acceptance on the merged SHA, then execute Task 10's authorized release/dev witness and retain the receipt. End this plan's implementation session at merge with an explicit release/dev handoff if the window is later; do not remain running while waiting for it. List actual remaining approval or acceptance work. Clean task-owned scratch/processes; leave no server or EC2 instance running. No automatic flagship switch-on. |
| + |
| +## Follow-ups (P3) |
| + |
| +From plan review round 1; not applied inline, no further round. |
| + |
| +- **P3-7. Build MemoryHigh:** the build template adds `MemoryHigh=996566625`; native builds have none and §9 does not ask for one. Drop it or justify it from measurement (it can slow builds near the cap). |
| +- **P3-8. Guest build uid 65534 (`nobody`)** is shared with any host `nobody` process. Ancestors are root-0700, so no current exposure, but a dedicated unused uid is cleaner. |
| +- **P3-11. Duplicate host.env injection:** Task 1 (claimunit.go:31) and Task 3 Step 4 both add host.env to control. Keep one owner. Injecting all of host.env widens what root reads from the environment (for example `CARLOS_DATA_DIR` via `dataDir()` in claimstop_run.go); reading only `CARLOS_EXEC_SANDBOX` with the existing host-env parser, as runsc-ensure does, is smaller. |
| +- **P3-12. Candidate buffering:** `systemArtifactLimit` (96 MiB) is buffered inside units capped at `MemoryMax=256M` (carlos-system-update.service:63). Note the headroom, or hash and scan the root-owned staged copy before `version` runs. |
| +- **P3-13. `After=carlos-runsc.service` on control:** with the runsc object unreachable, every control (re)start waits up to `TimeoutStartSec=120`, including a socket-activated restart during edge shutdown (T1/DR-4). Consider a shorter fetch bound; design-level, note it in the runbook. |