carlos / platform Public

caps, host: reserve the carlos- runtime-dir prefix; root's console fleet step; plan rev 2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev db6dee85c028c0138dffa513cff94b911688331a parent 90fcfec
14 files changed, +1,427 −47
  • docs/superpowers/plans/2026-11-24-hub-console-socket.md +84 −33
  • docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R1.md +85 −0
  • docs/superpowers/plans/CODEX-REVIEW-BRIEF-hub-console-socket-plan-R2.md +89 −0
  • internal/caps/caps.go +16 −1
  • internal/caps/converge.go +37 −0
  • internal/caps/runtimedir_guard_test.go +279 −0
  • internal/caps/runtimedir_reserved_test.go +99 −0
  • internal/consolefleet/consolefleet.go +119 −0
  • internal/consolefleet/consolefleet_test.go +61 −0
  • internal/edge/edge.go +2 −1
  • internal/edge/replicaconsole.go +0 −12
  • internal/host/agent.go +7 −0
  • internal/host/consolefleet.go +319 −0
  • internal/host/consolefleet_test.go +230 −0
diff --git a/docs/superpowers/plans/2026-11-24-hub-console-socket.md b/docs/superpowers/plans/2026-11-24-hub-console-socket.md
index 758bbcc5a..d0fddf0d9 100644
--- a/docs/superpowers/plans/2026-11-24-hub-console-socket.md
+++ b/docs/superpowers/plans/2026-11-24-hub-console-socket.md
@@ -27,12 +27,14 @@ Read it first. One slice, one branch: `console-addr-from-install`.
the console share it.
- Outcomes, exactly: `installed`, `unchanged`, `removed`, `absent`,
`failed`.
-- Edge sources, exactly: `env`, `socket`, `route-scan`. Results: `ok`, or
- the HTTP status the edge answered (`502`, `503`).
+- Edge sources, exactly: `env`, `socket`, `route-scan`. Result: `ok` for a
+ 2xx the edge answered, otherwise that status code as a string (`401`,
+ `500`, `502`, `503`, …), whether the edge or the console produced it.
- Nothing here reads a route record or the registry to decide the socket.
- Tests first in every task. Linux-only tests run in Docker:
`docker run --rm -v <worktree>:/src -v $HOME/go/pkg/mod:/go/pkg/mod -w /src golang:1.26.10 go test ...`.
- On the Mac, `GOCACHE=/tmp/g3/gocache`.
+ Leave `GOCACHE` at its default (AGENTS.md, Build & test); a session's
+ own environment may point it elsewhere for local runs.
- Every Go change: `gofmt`, `go vet`, `make code-health` before pushing.
## Tasks
@@ -40,7 +42,8 @@ Read it first. One slice, one branch: `console-addr-from-install`.
### Task 1: the reserved prefix (security gate, own Codex review)
Files: `internal/caps/caps.go`, `internal/caps/converge.go`, new
-`internal/caps/runtimedir_guard_test.go`, `internal/caps/caps_test.go`.
+`internal/caps/runtimedir_reserved_test.go` and
+`internal/caps/runtimedir_guard_test.go`.
- Add `ReservedRuntimeDir(name string) bool`: true for the existing map,
the `systemd-` prefix and the `carlos-` prefix. `ValidCapabilities`
@@ -48,24 +51,40 @@ Files: `internal/caps/caps.go`, `internal/caps/converge.go`, new
(`cli.go:2818`), adopt (`release.go:485`), converge (`converge.go:228`)
and render (`render.go:152`) all go through `ValidCapabilities`, so all
refuse.
-- Add `RuntimeDirClaimant(etcDir, name string) (host string, ok bool)`
- over the existing `scanClaims` (`converge.go:775`) with no excepted host.
- An unreadable `etcDir` returns `ok=true` with host `"?"` (fail closed:
- root cannot show the name is free); `scanClaims` keeps its current
- behaviour for its existing caller.
-- Guard test `TestRuntimeDirectoryRenderSites`: parse every non-test `.go`
- file in the module (`go/parser`), collect string literals containing
- `RuntimeDirectory`, and every file under `internal/host/units` and
- `infra/` containing it. The set of files must equal an allowlist:
- `internal/caps/render.go`, `internal/consolefleet/consolefleet.go`,
- `internal/demobuild/gvisor.go`, the three `carlos-runsc` units and
- `infra/devbox/carlos-devbox.service` (`carlos-devbox`). Each
- allowlisted literal outside caps names a `carlos-` directory. A new site
- fails the test, naming the file, and needs a reviewed allowlist edit.
-- Tests: `carlos-console`, `carlos-x` and `carlos-` refused by
- `ValidCapabilities` and by `RenderService`; `carlosx` (no hyphen) still
- allowed; `RuntimeDirClaimant` finds a claim in a fake etc dir, and fails
- closed on an unreadable one.
+- Add `RuntimeDirClaimant(etcDir, name string) (host string, claimed bool)`,
+ its own scan of the generated service drop-ins (the paths `scanClaims`
+ reads, no host excepted), failing closed on every error that is not
+ absence: an unreadable `etcDir`, or any candidate drop-in that exists but
+ cannot be read, answers `claimed` with host `"?"` (plan review R1 P1-2).
+ `scanClaims` and its caller are unchanged.
+- Guard `TestRuntimeDirectoryRenderSites`, over the module's non-test Go
+ files (`go/parser`; skipping hidden directories, `testdata`, `vendor`,
+ `docs`) and every file under `internal/host/units` and `infra/`:
+ - a *site* is a string literal containing `RuntimeDirectory`, a `+`
+ chain of string literals whose folded value contains it (a split
+ spelling), or a composite-literal key `"RuntimeDirectory"` (its value
+ literal recorded); in a unit file, each `RuntimeDirectory=` line;
+ - an allowlist names every file with its *kind* (`writer` or `reader`)
+ and its exact site count: writers `internal/caps/render.go` (app
+ names, behind `ValidCapabilities`), `internal/consolefleet/consolefleet.go`,
+ `internal/demobuild/gvisor.go`, the three `carlos-runsc` units and
+ `infra/devbox/carlos-devbox.service`; readers
+ `internal/caps/converge.go` and `internal/instancectl/gvisorunit.go`;
+ - a file not listed, or a listed file whose count changed, fails, naming
+ the file: a second writer inside an allowlisted file fails too (plan
+ review R1 P2-3);
+ - every value a writer outside `internal/caps` assigns (a
+ `RuntimeDirectory=` line or a key's value) starts `carlos-`;
+ - the scanner is a function with its own fixture tests: a split
+ spelling, a second writer in a listed file and a property map are each
+ found. Its residual (a spelling assembled from named constants or at
+ run time) is stated in the test's comment: the authority is
+ `ValidCapabilities` and root's exclusivity check, the guard a tripwire.
+- Tests: `carlos-console`, `carlos-x` refused by `ValidCapabilities`,
+ `RenderService` and `Converge` (nothing written, no systemctl call);
+ `carlosx` (no hyphen) still allowed; `RuntimeDirClaimant` finds a
+ pre-existing claim, answers claimed for an unreadable `etcDir` and for a
+ readable directory holding an unreadable drop-in.
### Task 2: the shared package
@@ -125,13 +144,24 @@ Files: `internal/edge/replicaconsole.go`, new
recording wrapper; exported `(*Edge).LastReplicaConsoleCall()`.
- Production record read: `rootstate.OpenTrustedFile` +
`rootstate.CheckPublicConfig` + `consolefleet.DecodeRecord`.
+- Production record read: `rootstate.Open(consolefleet.StatusDir, false,
+ true)` and `Read(StatusFile)` (the store checks the chain and the file:
+ root-owned, not group- or other-writable, regular), then
+ `consolefleet.DecodeRecord`.
- Tests (real unix listener in `t.TempDir()`): env wins over a ready
socket; record missing, malformed, `exclusive:false` each fall to the
route scan; dir symlink, dir 0777, socket a regular file each fall to
the route scan; ready socket forwards with the hub's version header and
the box's token; a route row naming another upstream changes nothing
- while the socket is used; listener closed after the check answers 502;
- last-call source, result and time for each path; "no call yet" is nil.
+ while the socket is used; the selected socket's listener closed after
+ the check answers 502 with no version header **and** a live competing
+ route upstream receives nothing; last call recorded for `ok`, `401`,
+ `500`, `502` and the route scan's `503`, with source and time; "no call
+ yet" is nil; an env call that succeeds while the record says
+ `exclusive:false` records source `env`, result `ok`.
+- A Linux-only test of the production reader, run as root in Docker:
+ a record owned by another uid, and one with mode 0666, are refused, so
+ the edge falls to the route scan (plan review R1 P2-5).
### Task 5: the console's listener
@@ -147,9 +177,11 @@ Files: `cmd/console/main.go` (serve), `cmd/console/stop.go`, new
`consolefleet.BoxDoor` gets 404.
- `consoleStop.serve` serves the extra listener on the same `http.Server`
(one `Shutdown` closes both); an error from the fleet listener is logged,
- never fatal.
+ never fatal, and only the TCP listener's `Serve` error stops the console.
- Tests: the wrapper's 404 and pass-through; the directory checks (owner,
- mode, symlink); a request over the socket reaches the box-door handler.
+ mode, symlink); a request over the socket reaches the box-door handler;
+ a fleet listener that fails leaves TCP serving; a stop closes both
+ listeners and drains a request in flight on each (plan review R1 P2-6).
### Task 6: visibility (UX pass, then copy, then build)
@@ -159,12 +191,20 @@ Files: `internal/status/snapshot.go`, `internal/host/agent.go` (probe),
1. **UX pass** first, recorded in
`docs/superpowers/notes/copy/hub-console-socket.md`: the suffix on a
- box's `carlos system status` line, leading with state: `console: socket
- · ok 2m ago`, `console: env · ok 2m ago`, `console: route scan · 503 1m
- ago`, `console: no call yet`, and, when root's record is not exclusive,
- `console: socket unused (<reason>)`. Colour carries ok, warn and bad.
+ box's `carlos system status` line always shows the observed call
+ (source, result, age) and, separately, the socket's eligibility when it
+ is not in use: `console: socket · ok 2m ago`, `console: env · ok 2m
+ ago · socket not ready`, `console: route scan · 503 1m ago · socket not
+ ready`, `console: no call yet`. The reason for "socket not ready" is
+ not on the line (it can be long); it prints on one indented line under
+ the box. No new flag. Colour carries ok, warn and bad; no colour
+ still reads. The pass renders real `printSystemStatus` output for a
+ healthy, a failed, a no-call and a socket-not-ready box at 80 and 160
+ columns, with and without colour, and fixes what wraps or reads badly
+ before copy review (plan review R1 P2-7).
2. **Copy review** of those strings and any new log lines by a Luna pass
- (`codex exec -s read-only`), recorded in the same note.
+ (`codex exec -s read-only`), in that rendered layout, recorded in the
+ same note.
3. Build: `status.ConsoleFleet{Record *consolefleet.Record; Source,
Result string; At time.Time}` on `Probes` and `BoxMetrics`
(`console_fleet`, omitempty, private like `named_units`); the agent
@@ -196,8 +236,19 @@ Files: `internal/status/snapshot.go`, `internal/host/agent.go` (probe),
6. Push, describe the branch, wait for green CI, then
`amadan branch merge carlos/platform console-addr-from-install -squash
-expect <tip> -message …`.
+7. After the merge: read `main`'s CI run (`amadan ci status
+ carlos/platform -branch main`), and fast-forward the GitHub mirror from
+ amadan if it is behind (AGENTS.md, Build & test).
## Review sizing (AGENTS.md stopping rule 3)
-Own reviews: Task 1 (security gate), Task 3 (root), Task 4 (gate). Tasks
-2, 5, 6 and 7 are covered by the whole-branch review.
+Own reviews: Task 1 (security gate), Task 3 (root), Task 4 (gate) and
+Task 5 (it changes how the console stops: termination). Tasks 2, 6 and 7
+are covered by the whole-branch review.
+
+## Plan review history
+
+Round 1 (`CODEX-FINDINGS-hub-console-socket-plan-R1.md`): NOT READY, P1-1
+(the guard's allowlist omitted existing sites) and P1-2 (claimant not fail
+closed on a drop-in read error), with P2-3 to P2-8. All applied above;
+P2-8's cache line now follows AGENTS.md.
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R1.md
new file mode 100644
index 000000000..5b601d552
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R1.md
@@ -0,0 +1,85 @@
+Reviewed commit `38f8af18aa9c82eff491522aaff1338f4959924b`. No files edited, subagents spawned, or test suites run.
+
+1. **P1 — Task 1: the specified guard fails on existing code.**
+
+ **Evidence:** The allowlist at [plan:56](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:56) excludes `internal/caps/converge.go`, which contains matching literals at lines 752 and 804, and `internal/instancectl/gvisorunit.go`, which contains them at line 54. Furthermore, the allowlisted `internal/demobuild/gvisor.go:146` has separate `"RuntimeDirectory"` and `"carlos-runsc"` literals: the matching literal does not itself name a reserved directory.
+
+ **Failure scenario:** Implementing the stated file-set equality and per-literal assertion produces a failing guard before any new unsafe writer exists.
+
+ **Fix:** Inventory readers and writers separately; include the existing instancectl site. Validate directive/value associations and rendered assignments, rather than requiring each matching literal to contain its value.
+
+ **Fault family:** Runtime-directory writer inventory correctness.
+
+2. **P1 — Task 1/3: `RuntimeDirClaimant` does not fail closed on an incomplete scan.**
+
+ **Evidence:** [plan:51](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:51) handles an unreadable top-level directory but delegates to `scanClaims`. [converge.go:791](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/internal/caps/converge.go:791) silently skips individual drop-in read errors. Its return type cannot distinguish “no claim” from “could not inspect a claim.”
+
+ **Failure scenario:** Systemd has already loaded a legacy app’s `carlos-console` claim, but reading that drop-in now fails, for example with an I/O error. The new wrapper reports no claimant. With the console active and the other checks satisfied, root can publish `exclusive:true` without establishing exclusivity, enabling the socket destination despite an unresolved competing claim.
+
+ **Fix:** Give the authority-facing scan an error result and refuse exclusivity on every non-absence read or traversal error. Preserve the existing caller’s behavior through a separate wrapper if necessary. Add a test where the parent directory is readable but a candidate drop-in read fails.
+
+ **Fault family:** Unknown claim state must never become socket authority.
+
+3. **P2 — Task 1: file-level literal scanning does not enforce the promised new-site guard.**
+
+ **Evidence:** [plan:56–64](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:56) compares filenames. Another writer added inside an allowlisted file does not change that set. `"Runtime" + "Directory="` also spells the directive without either literal matching the search.
+
+ **Failure scenario:** A new rendering path bypasses capability validation while the guard remains green.
+
+ **Fix:** Track reviewed sites or enclosing units, evaluate constant string expressions, and add mutation fixtures proving that a split spelling and an additional writer in an already-allowlisted file fail. Keep reader exemptions distinct from writer approval.
+
+ **Fault family:** Runtime-directory writer inventory completeness.
+
+4. **P2 — Global constraints/Task 6: visibility loses required call outcomes.**
+
+ **Evidence:** [plan:30](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:30) restricts results to `ok`, `502`, and `503`, whereas [spec:233](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md:233) requires the status actually answered. The reverse proxy passes upstream responses through; `ModifyResponse` only sets the version header (`internal/edge/replicaconsole.go:78`). Task 6 also supplies `socket unused (<reason>)` without specifying how the actual env/route-scan call remains visible.
+
+ **Failure scenario:** A console authentication refusal or application error cannot be represented faithfully. A working env override can be obscured by a socket-exclusivity warning.
+
+ **Fix:** Preserve every unsuccessful HTTP status and define which successful responses map to `ok`. Always retain actual source, result, and age; append socket eligibility separately. Test 401, 500, and `exclusive:false` with a successful env call.
+
+ **Fault family:** Report observed delivery independently of socket eligibility.
+
+5. **P2 — Task 4: the test list omits required authority-check coverage.**
+
+ **Evidence:** [plan:128](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:128) tests decoded record failures but not a record rejected for ownership or permissions. [Spec:270](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md:270) requires every §7 case. The production reader’s ownership/mode check is `internal/rootstate/file_linux.go:137`.
+
+ **Failure scenario:** Replacing the trusted production reader with an ordinary file read could leave the proposed selection tests green. Likewise, checking only a 502 does not prove that no fallback destination received the token.
+
+ **Fix:** Exercise the production record reader with rejected ownership/mode fixtures. For the selected-socket dial failure, install a live competing route and assert zero requests there, alongside 502 and no version header.
+
+ **Fault family:** Fleet-token destination authority regression coverage.
+
+6. **P2 — Tasks 5/8: termination changes lack lifecycle tests and corresponding review scope.**
+
+ **Evidence:** [plan:148](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:148) changes `consoleStop.serve`, but its tests cover only request handling and directory checks. Today [stop.go:133](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/cmd/console/stop.go:133) treats its sole Serve error as fatal. Task 8 classifies Task 5 as ordinary whole-branch coverage despite its termination behavior.
+
+ **Failure scenario:** An implementation can pass every listed test while a fleet-listener failure stops TCP service, or shutdown mishandles one listener’s Serve completion.
+
+ **Fix:** Add tests for nonfatal fleet-listener failure, continued TCP service, and shutdown closing and draining both listeners. Include Task 5’s termination changes explicitly in the appropriately scoped review.
+
+ **Fault family:** Console service lifetime and shutdown.
+
+7. **P2 — Task 6: the UX step records strings but omits the required layout pass.**
+
+ **Evidence:** [plan:160](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:160) specifies a note and strings. `AGENTS.md:422–427` requires viewing the layout at 390 px and desktop, light and dark, before copy review.
+
+ **Failure scenario:** Copy is approved without seeing how the suffix and potentially long refusal reason fit the existing box-status row.
+
+ **Fix:** Add the prescribed rendered UX pass before the Luna copy review, including healthy, failed, no-call, and socket-unused examples.
+
+ **Fault family:** Review copy in its actual presentation.
+
+8. **P2 — Global constraints/Task 8: execution instructions contradict or omit repository requirements.**
+
+ **Evidence:** [plan:35](/Users/paulcampbell/github.com/carlosframework/platform-console-addr/docs/superpowers/plans/2026-11-24-hub-console-socket.md:35) sets `GOCACHE=/tmp/g3/gocache`; `AGENTS.md:343–347` explicitly prohibits that override. Task 8 ends at merge, omitting the required main-CI check and conditional GitHub mirror fast-forward (`AGENTS.md:274–282`).
+
+ **Failure scenario:** Following the plan invokes a prohibited cache configuration and declares completion without checking the merged result.
+
+ **Fix:** Retain the default cache and applicable Go environment settings. Add post-merge main-CI verification and mirror synchronization when needed.
+
+ **Fault family:** Repository execution and completion contract.
+
+The shared validation gate does cover ship, adopt, converge, and render at the cited call sites. The proposed adopt insertion point covers full and config-only passes. The shared-server approach and Unix `LocalAddrContextKey` discrimination are sound. Also, `systemctl -p` explicitly includes empty requested properties; no missing-`--all` finding applies. [systemd source](https://github.com/systemd/systemd/blob/main/src/systemctl/systemctl.c)
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-hub-console-socket-plan-R2.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-hub-console-socket-plan-R2.md
new file mode 100644
index 000000000..ca3420c14
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-hub-console-socket-plan-R2.md
@@ -0,0 +1,89 @@
+# Review brief: hub console socket (implementation plan), round 2 of 3
+
+Repo carlos/platform, branch `console-addr-from-install`, commit 38f8af18aa9c82eff491522aaff1338f4959924b.
+Under review: `docs/superpowers/plans/2026-11-24-hub-console-socket.md`.
+Authorities: `docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md`
+rev 3 on this branch, whose design review is CLOSED (Paul's decisions of
+2026-11-24 are its §12, §14 and §15; its findings files sit beside it), and
+the code on `main` (this branch is main plus docs). Do not review against
+other unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the plan, then the spec, then the code
+it names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- The design (spec rev 3) and Paul's decisions: the `carlos-` runtime
+ directory prefix reserved in `internal/caps` with a guard test; a
+ root-written drop-in plus a console-owned socket is "the console install
+ writes it"; the route scan stays one release, then goes. Report only plan
+ steps that fail to implement the spec, or that would not work.
+- Round 1 P1-2 of the design review (version-path provenance) is declined;
+ the design review agreed in round 2.
+
+## What to check
+
+1. Does every task implement its spec section exactly, and does the plan
+ miss anything the spec requires (§4, §4a, §5, §6, §7, §8, §10)?
+2. Task 1: does routing everything through `ValidCapabilities` really
+ cover ship, adopt, converge and render? Is the guard test's scan sound
+ (what could spell the directive and escape it)? Is `RuntimeDirClaimant`'s
+ fail-closed behaviour right?
+3. Task 3: the `systemctl show` properties and their output format, the
+ marker ordering, `hostfloor.Durable` and `rootstate` store semantics,
+ placement in `runAdoptUnderRootRelease` (`internal/host/agent.go`).
+4. Task 4: the edge's selection, the unix proxy, the last-call record, and
+ whether the tests would catch a regression in the trust rule at
+ `internal/edge/replicaconsole.go:16-26`.
+5. Task 5: serving a second listener through `consoleStop`
+ (`cmd/console/stop.go`) and its shutdown; `http.LocalAddrContextKey`
+ for a unix listener.
+6. Task 6: the heartbeat to API to CLI path, the UX pass and copy steps
+ in the order AGENTS.md requires.
+7. Task 8 and the review sizing: census scope, the guard tests named, the
+ merge steps.
+
+## Round 2
+
+Earlier rounds: `docs/superpowers/plans/CODEX-FINDINGS-hub-console-socket-plan-R1.md`.
+The round number counts every earlier review of this plan.
+
+First give one line per P1 and P2 from round 1: resolved, partly, or not.
+Carry every unresolved or partly resolved finding forward at its current
+severity, then add new findings. The verdict covers everything outstanding,
+earlier rounds included. Tasks 1-3 have code on the branch already
+(`internal/caps`, `internal/consolefleet`, `internal/host/consolefleet.go`);
+you may read it to check the plan, but this round reviews the plan.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/internal/caps/caps.go b/internal/caps/caps.go
index 3ddc7c7ce..e12ea49ef 100644
--- a/internal/caps/caps.go
+++ b/internal/caps/caps.go
@@ -94,6 +94,21 @@ var reservedRuntimeDir = map[string]bool{
"initctl": true,
}
+// ReservedRuntimeDir is the one decision on which /run directory names no
+// app may own: the reservedRuntimeDir list, systemd's systemd- prefix, and
+// the platform's carlos- prefix (Paul, 2026-11-24; the hub console spec
+// §4a). The platform's own directories live under carlos-: carlos-runsc for
+// gVisor, and carlos-console, where the console binds the socket the edge
+// hands fleet boxes' bearer tokens to. An app holding /run/carlos-console
+// while the console is down could bind that socket itself, so the prefix
+// is closed to every runtime_dir. ValidCapabilities calls this, and ship,
+// adopt, converge and render all go through ValidCapabilities;
+// TestRuntimeDirectoryRenderSites fails if RuntimeDirectory= is spelled
+// anywhere that does not.
+func ReservedRuntimeDir(name string) bool {
+ return reservedRuntimeDir[name] || strings.HasPrefix(name, "systemd-") || strings.HasPrefix(name, "carlos-")
+}
+
// reservedPort is bound absolutely and is never grantable, typo or not
// (spec §7): the edge's own ports and the box's SSH.
var reservedPort = map[int]bool{22: true, 80: true, 443: true}
@@ -352,7 +367,7 @@ func ValidCapabilities(app string, s *Set) error {
if !tokenRe.MatchString(s.RuntimeDir) {
return fmt.Errorf("capabilities: runtime_dir %q must match ^[a-z][a-z0-9-]{0,31}$", s.RuntimeDir)
}
- if reservedRuntimeDir[s.RuntimeDir] || strings.HasPrefix(s.RuntimeDir, "systemd-") {
+ if ReservedRuntimeDir(s.RuntimeDir) {
return fmt.Errorf("capabilities: runtime_dir %q is a reserved name", s.RuntimeDir)
}
}
diff --git a/internal/caps/converge.go b/internal/caps/converge.go
index d8305eb72..39fe614c1 100644
--- a/internal/caps/converge.go
+++ b/internal/caps/converge.go
@@ -810,6 +810,43 @@ func scanClaims(etcDir, exceptHost string) (map[int]string, map[string]string) {
return ports, dirs
}
+// RuntimeDirClaimant reports whether a capability drop-in on this box
+// claims /run/<name>, and whose: root's console step asks it about
+// carlos-console, which ValidCapabilities now refuses but a drop-in
+// written before the refusal could still hold (converge leaves a refused
+// manifest's drop-ins as they are). It reads the same generated paths
+// scanClaims does, with no host excepted, but fails closed where
+// scanClaims skips: a systemd directory or a drop-in it cannot read is
+// answered as claimed (host "?"), since root cannot show the name is free.
+func RuntimeDirClaimant(etcDir, name string) (host string, ok bool) {
+ ents, err := os.ReadDir(etcDir)
+ if err != nil {
+ return "?", true
+ }
+ for _, e := range ents {
+ if !e.IsDir() {
+ continue
+ }
+ h, kind, isUnit := parseUnitDir(e.Name())
+ if !isUnit || kind != "service" {
+ continue
+ }
+ b, exists, _, err := readDropIn(filepath.Join(etcDir, e.Name(), DropInName))
+ if err != nil {
+ return "?", true
+ }
+ if !exists {
+ continue
+ }
+ for _, line := range strings.Split(string(b), "\n") {
+ if v, found := strings.CutPrefix(line, "RuntimeDirectory="); found && v == name {
+ return h, true
+ }
+ }
+ }
+ return "", false
+}
+
// listenStreamPort reads the port out of a ListenStream= value. This package
// only ever WRITES the bare-number form, but the claim scan also reads files
// this package did not write, and systemd accepts several spellings of the
diff --git a/internal/caps/runtimedir_guard_test.go b/internal/caps/runtimedir_guard_test.go
new file mode 100644
index 000000000..2e7fa41ff
--- /dev/null
+++ b/internal/caps/runtimedir_guard_test.go
@@ -0,0 +1,279 @@
+package caps
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// runtimeDirectorySite is one file allowed to spell systemd's
+// RuntimeDirectory, with how many times and why.
+type runtimeDirectorySite struct {
+ kind string // "writer" hands out a /run directory; "reader" only reads the property back
+ count int // exact number of sites (runtimeDirectorySites) in the file
+ why string
+}
+
+// runtimeDirectorySites is every reviewed place RuntimeDirectory is spelled.
+// ReservedRuntimeDir is the one gate on which /run directory an app may own,
+// and it only holds if apps reach RuntimeDirectory= through RenderService
+// alone (ValidCapabilities). Every other writer names a platform directory
+// under the reserved carlos- prefix. A new file, or a new site in a listed
+// file, is a possible new way to hand out a /run directory, so it fails
+// TestRuntimeDirectoryRenderSites until it is reviewed and the count here
+// changed (hub console spec §4a).
+//
+// The guard is a tripwire, not the authority: a spelling assembled from
+// named constants or at run time escapes it. The authority is
+// ValidCapabilities at ship, adopt, converge and render, and root's
+// exclusivity check over the box's capability drop-ins
+// (internal/host/consolefleet.go).
+var runtimeDirectorySites = map[string]runtimeDirectorySite{
+ "internal/caps/render.go": {"writer", 1, "app runtime_dir, behind ValidCapabilities"},
+ "internal/consolefleet/consolefleet.go": {"writer", 1, "root's console drop-in, carlos-console"},
+ "internal/demobuild/gvisor.go": {"writer", 1, "transient demo build unit, carlos-runsc"},
+ "internal/host/units/carlos-instance-gvisor@.service": {"writer", 1, "carlos-runsc"},
+ "internal/host/units/carlos-instance-gvisor-probe.service": {"writer", 1, "carlos-runsc"},
+ "internal/host/units/carlos-demo-build-gvisor@.service": {"writer", 1, "carlos-runsc"},
+ "infra/devbox/carlos-devbox.service": {"writer", 1, "carlos-devbox"},
+ "internal/caps/converge.go": {"reader", 3, "scanClaims, dropInHas and RuntimeDirClaimant read claims back"},
+ "internal/host/consolefleet.go": {"reader", 3, "root's console step reads console.service's property and names it in reasons"},
+ "internal/instancectl/gvisorunit.go": {"reader", 1, "checks the gVisor unit's properties"},
+}
+
+// runtimeDirSite is one spelling found in a file, and the directory it
+// assigns when the site carries one ("" when built from a variable).
+type runtimeDirSite struct{ value string }
+
+// goRuntimeDirSites finds every site in Go source: a string literal
+// containing RuntimeDirectory (outside a + chain), a + chain of string
+// literals whose folded value contains it (a split spelling counts once),
+// and a composite-literal key "RuntimeDirectory" with its value literal.
+// The key of a property map is itself a string literal, so it is counted
+// as the key site only. RuntimeDirectoryMode and RuntimeDirectoryPreserve
+// are not sites: they hand out nothing.
+func goRuntimeDirSites(src []byte) ([]runtimeDirSite, error) {
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "src.go", src, parser.SkipObjectResolution)
+ if err != nil {
+ return nil, err
+ }
+ var sites []runtimeDirSite
+ inChain := map[*ast.BasicLit]bool{}
+ isKey := map[*ast.BasicLit]bool{}
+ ast.Inspect(f, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.KeyValueExpr:
+ k, ok := n.Key.(*ast.BasicLit)
+ if !ok || k.Kind != token.STRING {
+ return true
+ }
+ if key, _ := strconv.Unquote(k.Value); key == "RuntimeDirectory" {
+ isKey[k] = true
+ value := ""
+ if v, ok := n.Value.(*ast.BasicLit); ok && v.Kind == token.STRING {
+ value, _ = strconv.Unquote(v.Value)
+ }
+ sites = append(sites, runtimeDirSite{value})
+ }
+ case *ast.BinaryExpr:
+ if n.Op != token.ADD {
+ return true
+ }
+ lits, folded, ok := foldStringChain(n)
+ if !ok {
+ // A chain with a variable in it: its literals still count
+ // one by one below.
+ return true
+ }
+ for _, l := range lits {
+ inChain[l] = true
+ }
+ if hasRuntimeDirectory(folded) {
+ sites = append(sites, runtimeDirectoryAssignments(folded)...)
+ }
+ return false
+ case *ast.BasicLit:
+ if n.Kind != token.STRING || inChain[n] || isKey[n] {
+ return true
+ }
+ if v, err := strconv.Unquote(n.Value); err == nil && hasRuntimeDirectory(v) {
+ sites = append(sites, runtimeDirectoryAssignments(v)...)
+ }
+ }
+ return true
+ })
+ return sites, nil
+}
+
+// foldStringChain folds a + chain made only of string literals.
+func foldStringChain(e ast.Expr) (lits []*ast.BasicLit, folded string, ok bool) {
+ switch e := e.(type) {
+ case *ast.BasicLit:
+ if e.Kind != token.STRING {
+ return nil, "", false
+ }
+ v, err := strconv.Unquote(e.Value)
+ return []*ast.BasicLit{e}, v, err == nil
+ case *ast.ParenExpr:
+ return foldStringChain(e.X)
+ case *ast.BinaryExpr:
+ if e.Op != token.ADD {
+ return nil, "", false
+ }
+ l, lv, lok := foldStringChain(e.X)
+ r, rv, rok := foldStringChain(e.Y)
+ return append(l, r...), lv + rv, lok && rok
+ }
+ return nil, "", false
+}
+
+// hasRuntimeDirectory: the property itself, not Mode or Preserve.
+func hasRuntimeDirectory(s string) bool {
+ for rest := s; ; {
+ i := strings.Index(rest, "RuntimeDirectory")
+ if i < 0 {
+ return false
+ }
+ rest = rest[i+len("RuntimeDirectory"):]
+ if !strings.HasPrefix(rest, "Mode") && !strings.HasPrefix(rest, "Preserve") {
+ return true
+ }
+ }
+}
+
+// runtimeDirectoryAssignments is one site per RuntimeDirectory= line in s
+// with its value, or one valueless site when s spells the name without
+// assigning on a line (a prefix a variable completes, or a key name).
+func runtimeDirectoryAssignments(s string) []runtimeDirSite {
+ var out []runtimeDirSite
+ for _, line := range strings.Split(s, "\n") {
+ if v, ok := strings.CutPrefix(strings.TrimSpace(line), "RuntimeDirectory="); ok {
+ out = append(out, runtimeDirSite{strings.TrimSpace(v)})
+ }
+ }
+ if len(out) == 0 {
+ out = append(out, runtimeDirSite{})
+ }
+ return out
+}
+
+// unitRuntimeDirSites is one site per RuntimeDirectory= line of a unit file.
+func unitRuntimeDirSites(raw []byte) []runtimeDirSite {
+ var out []runtimeDirSite
+ for _, line := range strings.Split(string(raw), "\n") {
+ if v, ok := strings.CutPrefix(strings.TrimSpace(line), "RuntimeDirectory="); ok {
+ out = append(out, runtimeDirSite{strings.TrimSpace(v)})
+ }
+ }
+ return out
+}
+
+func TestRuntimeDirectoryRenderSites(t *testing.T) {
+ root, err := filepath.Abs(filepath.Join("..", ".."))
+ if err != nil {
+ t.Fatal(err)
+ }
+ found := map[string][]runtimeDirSite{}
+ err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ rel, _ := filepath.Rel(root, path)
+ rel = filepath.ToSlash(rel)
+ if d.IsDir() {
+ name := d.Name()
+ if path != root && (strings.HasPrefix(name, ".") || name == "testdata" || name == "vendor" || name == "node_modules" || rel == "docs") {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ var sites []runtimeDirSite
+ switch {
+ case strings.HasSuffix(rel, ".go") && !strings.HasSuffix(rel, "_test.go"):
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ if sites, err = goRuntimeDirSites(raw); err != nil {
+ return err
+ }
+ case strings.HasPrefix(rel, "internal/host/units/") || strings.HasPrefix(rel, "infra/"):
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ sites = unitRuntimeDirSites(raw)
+ }
+ if len(sites) > 0 {
+ found[rel] = sites
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ files := make([]string, 0, len(found))
+ for file := range found {
+ files = append(files, file)
+ }
+ sort.Strings(files)
+ for _, file := range files {
+ sites := found[file]
+ want, ok := runtimeDirectorySites[file]
+ if !ok {
+ t.Errorf("%s spells RuntimeDirectory (%d sites) and is not a reviewed site; an app's /run directory must come through caps.RenderService (ValidCapabilities), so review it and add it to runtimeDirectorySites", file, len(sites))
+ continue
+ }
+ if len(sites) != want.count {
+ t.Errorf("%s spells RuntimeDirectory %d times, reviewed for %d; review the new site and change the count", file, len(sites), want.count)
+ }
+ if want.kind != "writer" || strings.HasPrefix(file, "internal/caps/") {
+ continue
+ }
+ for _, s := range sites {
+ if s.value != "" && !strings.HasPrefix(s.value, "carlos-") {
+ t.Errorf("%s assigns RuntimeDirectory %q, outside the platform's carlos- prefix", file, s.value)
+ }
+ }
+ }
+ for file := range runtimeDirectorySites {
+ if _, ok := found[file]; !ok {
+ t.Errorf("%s is listed in runtimeDirectorySites but no longer spells RuntimeDirectory; remove it", file)
+ }
+ }
+}
+
+// TestRuntimeDirSitesScanner: the scanner finds what the guard depends on.
+func TestRuntimeDirSitesScanner(t *testing.T) {
+ for name, tc := range map[string]struct {
+ src string
+ values []string
+ }{
+ "split spelling": {`package p; const s = "Runtime" + "Directory=evil\n"`, []string{"evil"}},
+ "second writer": {"package p\nconst a = \"RuntimeDirectory=carlos-a\\n\"\nconst b = \"RuntimeDirectory=evil\\n\"\n", []string{"carlos-a", "evil"}},
+ "property map": {`package p; var m = map[string]string{"RuntimeDirectory": "evil", "RuntimeDirectoryMode": "0700"}`, []string{"evil"}},
+ "prefix and a variable": {`package p; func f(x string) string { return "RuntimeDirectory=" + x }`, []string{""}},
+ "constant concatenation": {`package p; const n = "carlos-console"; const b = "[Service]\nRuntimeDirectory=" + n + "\n"`, []string{""}},
+ "mode only": {`package p; const s = "RuntimeDirectoryMode=0700"`, nil},
+ } {
+ sites, err := goRuntimeDirSites([]byte(tc.src))
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ var values []string
+ for _, s := range sites {
+ values = append(values, s.value)
+ }
+ if strings.Join(values, "|") != strings.Join(tc.values, "|") || len(values) != len(tc.values) {
+ t.Errorf("%s: sites %q, want %q", name, values, tc.values)
+ }
+ }
+}
diff --git a/internal/caps/runtimedir_reserved_test.go b/internal/caps/runtimedir_reserved_test.go
new file mode 100644
index 000000000..d2c8439f9
--- /dev/null
+++ b/internal/caps/runtimedir_reserved_test.go
@@ -0,0 +1,99 @@
+package caps
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// TestCarlosRuntimeDirPrefixIsReserved: the platform owns every /run
+// directory whose name starts carlos- (Paul, 2026-11-24; the hub console
+// spec §4a). An app holding /run/carlos-console could bind the console's
+// fleet socket while the console is down and receive fleet bearer tokens,
+// so ValidCapabilities refuses the whole prefix, and RenderService with
+// it. A name that only starts "carlos" without the hyphen is an app's.
+func TestCarlosRuntimeDirPrefixIsReserved(t *testing.T) {
+ for _, name := range []string{"carlos-console", "carlos-runsc", "carlos-x", "carlos-devbox"} {
+ if !ReservedRuntimeDir(name) {
+ t.Errorf("ReservedRuntimeDir(%q) = false", name)
+ }
+ s := &Set{V: 1, RuntimeDir: name}
+ if err := ValidCapabilities("keymail", s); err == nil {
+ t.Errorf("ValidCapabilities accepted runtime_dir %q", name)
+ }
+ if out, err := RenderService("keymail", s, Grants{}); err == nil {
+ t.Errorf("RenderService rendered runtime_dir %q:\n%s", name, out)
+ }
+ }
+ for _, name := range []string{"carlosx", "keymail", "console"} {
+ if ReservedRuntimeDir(name) {
+ t.Errorf("ReservedRuntimeDir(%q) = true", name)
+ }
+ if err := ValidCapabilities("keymail", &Set{V: 1, RuntimeDir: name}); err != nil {
+ t.Errorf("runtime_dir %q refused: %v", name, err)
+ }
+ }
+ // The existing reservations still hold through the one function.
+ for _, name := range []string{"carlos", "systemd", "systemd-foo", "shm"} {
+ if !ReservedRuntimeDir(name) {
+ t.Errorf("ReservedRuntimeDir(%q) = false", name)
+ }
+ }
+}
+
+// TestConvergeRefusesAReservedRuntimeDir: a staged manifest naming a
+// carlos- directory writes nothing at converge, through the same gate.
+func TestConvergeRefusesAReservedRuntimeDir(t *testing.T) {
+ o, f, _, _ := testOps(t)
+ var s Set
+ if err := s.UnmarshalJSON([]byte(`{"v":1,"command":"serve","runtime_dir":"carlos-console"}`)); err != nil {
+ t.Fatal(err)
+ }
+ p := Plan{Host: "claim.example.com", App: "claim", Set: &s}
+ if _, err := Converge(o, p); err == nil {
+ t.Fatal("converge accepted runtime_dir carlos-console")
+ }
+ if len(f.calls) != 0 {
+ t.Fatalf("systemctl calls on a refusal: %v", f.calls)
+ }
+ svcPath, _ := DropInPaths(o.EtcDir, p.Host)
+ mustNotExist(t, svcPath)
+}
+
+// TestRuntimeDirClaimant: root's console step asks whether any capability
+// drop-in on the box claims a directory, including one installed before the
+// prefix was reserved. An unreadable systemd directory cannot show the name
+// is free, so it answers claimed.
+func TestRuntimeDirClaimant(t *testing.T) {
+ etc := t.TempDir()
+ if host, ok := RuntimeDirClaimant(etc, "carlos-console"); ok {
+ t.Fatalf("empty etc: claimed by %q", host)
+ }
+ svcPath, _ := DropInPaths(etc, "old.example.com")
+ if err := os.MkdirAll(filepath.Dir(svcPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(svcPath, []byte("[Service]\nRuntimeDirectory=carlos-console\nRuntimeDirectoryMode=0700\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if host, ok := RuntimeDirClaimant(etc, "carlos-console"); !ok || host != "old.example.com" {
+ t.Fatalf("pre-existing claim: %q %v", host, ok)
+ }
+ if host, ok := RuntimeDirClaimant(etc, "keymail"); ok {
+ t.Fatalf("keymail: claimed by %q", host)
+ }
+ if host, ok := RuntimeDirClaimant(filepath.Join(etc, "missing"), "carlos-console"); !ok || host == "" {
+ t.Fatalf("unreadable etc: %q %v, want claimed", host, ok)
+ }
+ // A readable directory holding a drop-in that cannot be read (here a
+ // directory where the file should be, unreadable even to root): the
+ // claim it might hold is unknown, so claimed.
+ etc2 := t.TempDir()
+ bad, _ := DropInPaths(etc2, "broken.example.com")
+ if err := os.MkdirAll(bad, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if host, ok := RuntimeDirClaimant(etc2, "carlos-console"); !ok || host != "?" {
+ t.Fatalf("unreadable drop-in: %q %v, want claimed by ?", host, ok)
+ }
+}
diff --git a/internal/consolefleet/consolefleet.go b/internal/consolefleet/consolefleet.go
new file mode 100644
index 000000000..e37ca9c01
--- /dev/null
+++ b/internal/consolefleet/consolefleet.go
@@ -0,0 +1,119 @@
+// Package consolefleet is the one place the names behind the console's
+// fleet socket live, shared by root's console step (internal/host), the
+// edge that forwards fleet boxes' console calls (internal/edge) and the
+// console that answers them (cmd/console), so none of the three can drift.
+//
+// The design: root gives console.service a runtime directory with one
+// drop-in (DropInPath, DropInBody); systemd creates Dir when the console
+// starts, owned by the console's user, and removes it when the console
+// stops; the console binds Socket in it, serving only the box doors
+// (BoxDoor); the edge forwards to Socket while root's record (Record)
+// says the console holds the directory alone. Nothing here is read from a
+// route record: records are not a tenancy boundary (a legacy direct-S3
+// fleet box can write them), and Dir is under /run, which only root can
+// create entries in. docs/superpowers/specs/
+// 2026-11-24-hub-console-address-from-install-design.md has the argument.
+package consolefleet
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "path"
+ "strings"
+ "time"
+)
+
+const (
+ // RuntimeDirName is the runtime directory root gives console.service.
+ // The carlos- prefix is the platform's: internal/caps refuses it to
+ // every app's runtime_dir (caps.ReservedRuntimeDir).
+ RuntimeDirName = "carlos-console"
+ // Dir is where systemd creates it.
+ Dir = "/run/" + RuntimeDirName
+ // Socket is the console's fleet listener, in Dir.
+ Socket = Dir + "/fleet.sock"
+
+ // Unit is the one unit root gives the directory to.
+ Unit = "console.service"
+ // DropInPath is root's drop-in on Unit.
+ DropInPath = "/etc/systemd/system/" + Unit + ".d/70-carlos-fleet-socket.conf"
+ // DropInBody sets no mode and no preservation, so a runtime directory
+ // the unit already has keeps its own settings: the default mode 0755
+ // and no preservation are what root checks for (Record.Exclusive).
+ DropInBody = "[Service]\nRuntimeDirectory=" + RuntimeDirName + "\n"
+
+ // StatusDir is root's public store for its record and its
+ // reload-pending marker.
+ StatusDir = "/var/lib/carlos-console-fleet"
+ // StatusFile is the record's name in StatusDir.
+ StatusFile = "status.json"
+ // ReloadPending is the marker root writes before it changes the
+ // drop-in and removes after a daemon-reload succeeds.
+ ReloadPending = "reload-pending"
+
+ // MaxRecord caps a record read.
+ MaxRecord = 4096
+)
+
+// Outcomes of root's console step.
+const (
+ OutcomeInstalled = "installed"
+ OutcomeUnchanged = "unchanged"
+ OutcomeRemoved = "removed"
+ OutcomeAbsent = "absent"
+ OutcomeFailed = "failed"
+)
+
+// Record is root's last console step. Exclusive is the only field the edge
+// acts on: true when root saw the drop-in applied, the unit's runtime
+// directory settings as the design needs them, and no other claim on Dir.
+type Record struct {
+ Schema int `json:"schema"`
+ Outcome string `json:"outcome"`
+ Reason string `json:"reason,omitempty"`
+ Exclusive bool `json:"exclusive"`
+ At time.Time `json:"at"`
+}
+
+// DecodeRecord is the strict reading the edge and the agent share: at most
+// MaxRecord bytes, one JSON document, no unknown field, schema 1, a known
+// outcome.
+func DecodeRecord(raw []byte) (Record, error) {
+ if len(raw) > MaxRecord {
+ return Record{}, fmt.Errorf("console fleet record: %d bytes, the limit is %d", len(raw), MaxRecord)
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.DisallowUnknownFields()
+ var r Record
+ if err := dec.Decode(&r); err != nil {
+ return Record{}, fmt.Errorf("console fleet record: %w", err)
+ }
+ if dec.Decode(new(any)) != io.EOF {
+ return Record{}, errors.New("console fleet record: more than one JSON document")
+ }
+ if r.Schema != 1 {
+ return Record{}, fmt.Errorf("console fleet record: schema %d, want 1", r.Schema)
+ }
+ switch r.Outcome {
+ case OutcomeInstalled, OutcomeUnchanged, OutcomeRemoved, OutcomeAbsent, OutcomeFailed:
+ default:
+ return Record{}, fmt.Errorf("console fleet record: unknown outcome %q", r.Outcome)
+ }
+ return r, nil
+}
+
+// BoxDoor reports whether r is one of the box doors the hub hands to the
+// local console, and the only requests the console's fleet socket answers:
+// POST, a clean path, no raw path, under /api/fleet/replicas/ or
+// /api/fleet/seeds/ (a box's placed and failed reports).
+func BoxDoor(r *http.Request) bool {
+ p := r.URL.Path
+ if r.Method != http.MethodPost || r.URL.RawPath != "" || path.Clean(p) != p {
+ return false
+ }
+ return strings.HasPrefix(p, "/api/fleet/replicas/") || strings.HasPrefix(p, "/api/fleet/seeds/")
+}
diff --git a/internal/consolefleet/consolefleet_test.go b/internal/consolefleet/consolefleet_test.go
new file mode 100644
index 000000000..9d83b87f6
--- /dev/null
+++ b/internal/consolefleet/consolefleet_test.go
@@ -0,0 +1,61 @@
+package consolefleet
+
+import (
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestDecodeRecord(t *testing.T) {
+ good := `{"schema":1,"outcome":"unchanged","exclusive":true,"at":"2026-11-24T10:00:00Z"}`
+ r, err := DecodeRecord([]byte(good))
+ if err != nil || !r.Exclusive || r.Outcome != OutcomeUnchanged {
+ t.Fatalf("good record: %+v %v", r, err)
+ }
+ for name, raw := range map[string]string{
+ "oversize": `{"schema":1,"outcome":"unchanged","reason":"` + strings.Repeat("x", MaxRecord) + `"}`,
+ "two documents": good + good,
+ "unknown field": `{"schema":1,"outcome":"unchanged","exclusive":true,"addr":"127.0.0.1:1"}`,
+ "schema 0": `{"outcome":"unchanged","exclusive":true}`,
+ "schema 2": `{"schema":2,"outcome":"unchanged","exclusive":true}`,
+ "unknown outcome": `{"schema":1,"outcome":"maybe","exclusive":true}`,
+ "not json": `exclusive`,
+ "empty": ``,
+ } {
+ if _, err := DecodeRecord([]byte(raw)); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
+
+// TestBoxDoor keeps every case the edge's boxConsolePath had: only POSTs on
+// a clean path under the two doors.
+func TestBoxDoor(t *testing.T) {
+ for _, tc := range []struct {
+ method, path string
+ want bool
+ }{
+ {"POST", "/api/fleet/replicas/a/app/h/coordinator", true},
+ {"POST", "/api/fleet/seeds/fleet/box/placed", true},
+ {"GET", "/api/fleet/replicas/a/app/h/coordinator", false},
+ {"POST", "/api/fleet/replicas", false},
+ {"POST", "/api/fleet/replicas-other/a", false},
+ {"POST", "/api/accounts", false},
+ {"POST", "/api%2Ffleet%2Freplicas%2Fx", false},
+ {"POST", "/api/fleet/replicas/../../cli/apps/x", false},
+ {"POST", "//api/fleet/replicas/x", false},
+ {"POST", "/api/fleet/replicas/%2e%2e/x", false},
+ {"POST", "/api/fleet/replicas/a%2Fb/app/h/coordinator", false},
+ } {
+ r := httptest.NewRequest(tc.method, "https://tunnel.test"+tc.path, nil)
+ if got := BoxDoor(r); got != tc.want {
+ t.Errorf("%s %s: %v, want %v", tc.method, tc.path, got, tc.want)
+ }
+ }
+}
+
+func TestDropInNamesTheDirectory(t *testing.T) {
+ if DropInBody != "[Service]\nRuntimeDirectory=carlos-console\n" || Socket != "/run/carlos-console/fleet.sock" {
+ t.Fatalf("drop-in %q socket %q", DropInBody, Socket)
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 52501ce1c..155290879 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -48,6 +48,7 @@ import (
"github.com/carlosframework/platform/internal/apperr"
"github.com/carlosframework/platform/internal/cliflag"
+ "github.com/carlosframework/platform/internal/consolefleet"
"github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/democlaim"
"github.com/carlosframework/platform/internal/edgeguard"
@@ -2252,7 +2253,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.door.ServeHTTP(w, r)
return
}
- if boxConsolePath(r) {
+ if consolefleet.BoxDoor(r) {
e.serveReplicaConsole(w, r)
return
}
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go
index 7629be368..f69d88821 100644
--- a/internal/edge/replicaconsole.go
+++ b/internal/edge/replicaconsole.go
@@ -6,7 +6,6 @@ import (
"net/http"
"net/http/httputil"
"net/netip"
- "path"
"strconv"
"strings"
"time"
@@ -130,14 +129,3 @@ func (e *Edge) serveReplicaConsole(w http.ResponseWriter, r *http.Request) {
}
console.ServeHTTP(w, e.withForwardKey(r))
}
-
-// boxConsolePath: the box doors the hub hands to the local console, POST
-// only, with a clean path and no raw path: /api/fleet/replicas/ and
-// /api/fleet/seeds/ (the seeds door, a box's placed and failed reports).
-func boxConsolePath(r *http.Request) bool {
- p := r.URL.Path
- if r.Method != http.MethodPost || r.URL.RawPath != "" || path.Clean(p) != p {
- return false
- }
- return strings.HasPrefix(p, "/api/fleet/replicas/") || strings.HasPrefix(p, "/api/fleet/seeds/")
-}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index e9a823c91..b4e8f7942 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -6179,6 +6179,13 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni
// before the release key parse, which can end the pass, so an install
// is never left unreported. Never fatal.
namedUnits := runNamedUnitsStep(ctx)
+ // The console step (hub console spec §4): give console.service the
+ // runtime directory its fleet socket lives in, and record whether the
+ // console holds it alone, the one fact the edge's socket selection reads.
+ // Here for the same reasons as the named-units step: full and
+ // config-only passes alike, before the release key parse can end the
+ // pass. Never fatal.
+ adoptConsoleFleetStep(ctx)
// Parsed here, before config sync, exactly as the full pass always has
// (a box with an unusable release key must die before it converges
// anything), but SKIPPED entirely for -config-only: that mode never
diff --git a/internal/host/consolefleet.go b/internal/host/consolefleet.go
new file mode 100644
index 000000000..3d950d74d
--- /dev/null
+++ b/internal/host/consolefleet.go
@@ -0,0 +1,319 @@
+// Root's console step (hub console spec §4,
+// docs/superpowers/specs/2026-11-24-hub-console-address-from-install-design.md):
+// give console.service the runtime directory the console binds its fleet
+// socket in, and record whether the console holds that directory alone. The
+// edge forwards fleet boxes' console calls, with their bearer tokens, to the
+// socket only while that record says so.
+package host
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "log"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/caps"
+ "github.com/carlosframework/platform/internal/consolefleet"
+ "github.com/carlosframework/platform/internal/hostfloor"
+ "github.com/carlosframework/platform/internal/rootstate"
+ "github.com/carlosframework/platform/internal/systemd"
+)
+
+// consoleUnitProps is what the step reads of console.service.
+type consoleUnitProps struct {
+ LoadState string
+ ActiveState string
+ RuntimeDirectory []string
+ Mode string
+ Preserve string
+}
+
+func (p consoleUnitProps) hasRuntimeDir(name string) bool {
+ return slices.Contains(p.RuntimeDirectory, name)
+}
+
+// consoleUnitShowKeys is the one systemctl show query the step makes.
+var consoleUnitShowKeys = []string{"Id", "LoadState", "ActiveState", "RuntimeDirectory", "RuntimeDirectoryMode", "RuntimeDirectoryPreserve"}
+
+// parseConsoleUnitProps reads `systemctl show console.service -p <keys>`
+// strictly: one block, every asked key exactly once, the unit's own Id.
+// Anything else is an error and the step changes nothing.
+func parseConsoleUnitProps(out []byte) (consoleUnitProps, error) {
+ body := strings.TrimSpace(string(out))
+ if strings.Contains(body, "\n\n") {
+ return consoleUnitProps{}, errors.New("systemctl show answered more than one unit")
+ }
+ got := map[string]string{}
+ for _, line := range strings.Split(body, "\n") {
+ k, v, ok := strings.Cut(line, "=")
+ if !ok {
+ return consoleUnitProps{}, fmt.Errorf("systemctl show: unreadable line %q", line)
+ }
+ if _, dup := got[k]; dup {
+ return consoleUnitProps{}, fmt.Errorf("systemctl show: %s twice", k)
+ }
+ got[k] = v
+ }
+ for _, k := range consoleUnitShowKeys {
+ if _, ok := got[k]; !ok {
+ return consoleUnitProps{}, fmt.Errorf("systemctl show: no %s", k)
+ }
+ }
+ if got["Id"] != consolefleet.Unit {
+ return consoleUnitProps{}, fmt.Errorf("systemctl show answered for %q, not %s", got["Id"], consolefleet.Unit)
+ }
+ return consoleUnitProps{
+ LoadState: got["LoadState"],
+ ActiveState: got["ActiveState"],
+ RuntimeDirectory: strings.Fields(got["RuntimeDirectory"]),
+ Mode: got["RuntimeDirectoryMode"],
+ Preserve: got["RuntimeDirectoryPreserve"],
+ }, nil
+}
+
+// consoleFleetStep is the step with every effect behind a seam;
+// productionConsoleFleetStep holds the real ones.
+type consoleFleetStep struct {
+ show func() (consoleUnitProps, error)
+ reload func() error
+ readDropIn func() (body []byte, exists bool, err error)
+ writeDropIn func([]byte) error
+ removeDropIn func() error
+ markerPresent func() (bool, error)
+ setMarker func() error
+ clearMarker func() error
+ claimant func() (host string, claimed bool)
+ runDirExists func() (bool, error)
+ readRecord func() ([]byte, error)
+ writeRecord func([]byte) error
+ now func() time.Time
+}
+
+// run is spec §4 steps 1-5. It never fails the pass: every refusal is a
+// record with Exclusive false and the reason.
+func (s consoleFleetStep) run() consolefleet.Record {
+ rec := consolefleet.Record{Schema: 1, At: s.now()}
+ fail := func(format string, args ...any) consolefleet.Record {
+ rec.Outcome, rec.Reason, rec.Exclusive = consolefleet.OutcomeFailed, fmt.Sprintf(format, args...), false
+ return rec
+ }
+ // A reload owed by an earlier pass comes first, whatever the bytes are
+ // now: a drop-in changed on disk and never reloaded is not in effect.
+ pending, err := s.markerPresent()
+ if err != nil {
+ return fail("reading the reload marker: %v", err)
+ }
+ if pending {
+ if err := s.reload(); err != nil {
+ return fail("daemon-reload owed by an earlier pass failed: %v", err)
+ }
+ if err := s.clearMarker(); err != nil {
+ return fail("clearing the reload marker: %v", err)
+ }
+ }
+ props, err := s.show()
+ if err != nil {
+ return fail("reading %s: %v", consolefleet.Unit, err)
+ }
+ cur, exists, err := s.readDropIn()
+ if err != nil {
+ return fail("reading %s: %v", consolefleet.DropInPath, err)
+ }
+ switch props.LoadState {
+ case "loaded":
+ rec.Outcome = consolefleet.OutcomeUnchanged
+ if !exists || !bytes.Equal(cur, []byte(consolefleet.DropInBody)) {
+ if reason := s.change(func() error { return s.writeDropIn([]byte(consolefleet.DropInBody)) }); reason != "" {
+ return fail("%s", reason)
+ }
+ if props, err = s.show(); err != nil {
+ return fail("reading %s after daemon-reload: %v", consolefleet.Unit, err)
+ }
+ rec.Outcome = consolefleet.OutcomeInstalled
+ }
+ rec.Exclusive, rec.Reason = s.exclusive(props)
+ case "not-found":
+ rec.Outcome, rec.Reason = consolefleet.OutcomeAbsent, "no "+consolefleet.Unit+" on this box"
+ if exists {
+ if reason := s.change(s.removeDropIn); reason != "" {
+ return fail("%s", reason)
+ }
+ rec.Outcome = consolefleet.OutcomeRemoved
+ }
+ default:
+ return fail("%s is %s; nothing changed", consolefleet.Unit, props.LoadState)
+ }
+ return rec
+}
+
+// change makes one change to the drop-in under the reload marker: the
+// marker is durable before the change and goes only after daemon-reload
+// succeeds, so a failure anywhere leaves a reload the next pass owes
+// (round 2, P2-2). It returns "" or the reason it stopped.
+func (s consoleFleetStep) change(edit func() error) string {
+ if err := s.setMarker(); err != nil {
+ return fmt.Sprintf("cannot record a pending reload, so nothing was changed: %v", err)
+ }
+ if err := edit(); err != nil {
+ return fmt.Sprintf("changing %s: %v; the next pass reloads", consolefleet.DropInPath, err)
+ }
+ if err := s.reload(); err != nil {
+ return fmt.Sprintf("daemon-reload after changing %s: %v; the next pass retries", consolefleet.DropInPath, err)
+ }
+ if err := s.clearMarker(); err != nil {
+ return fmt.Sprintf("clearing the reload marker: %v", err)
+ }
+ return ""
+}
+
+// exclusive is spec §4 step 5: the console holds /run/carlos-console alone,
+// with the lifetime and mode the design needs.
+func (s consoleFleetStep) exclusive(p consoleUnitProps) (bool, string) {
+ if !p.hasRuntimeDir(consolefleet.RuntimeDirName) {
+ return false, fmt.Sprintf("the drop-in is not in effect: %s has no RuntimeDirectory=%s", consolefleet.Unit, consolefleet.RuntimeDirName)
+ }
+ if p.Preserve != "no" {
+ return false, fmt.Sprintf("%s sets RuntimeDirectoryPreserve=%s, so %s would outlive the console", consolefleet.Unit, p.Preserve, consolefleet.Dir)
+ }
+ if p.Mode != "0755" {
+ return false, fmt.Sprintf("%s's RuntimeDirectoryMode is %s, not 0755", consolefleet.Unit, p.Mode)
+ }
+ if host, claimed := s.claimant(); claimed {
+ return false, fmt.Sprintf("a capability drop-in for %s also claims %s", host, consolefleet.Dir)
+ }
+ switch p.ActiveState {
+ case "active", "activating", "reloading", "deactivating":
+ default:
+ found, err := s.runDirExists()
+ if err != nil {
+ return false, fmt.Sprintf("checking %s: %v", consolefleet.Dir, err)
+ }
+ if found {
+ return false, fmt.Sprintf("%s exists while %s is %s, so something else made it", consolefleet.Dir, consolefleet.Unit, p.ActiveState)
+ }
+ }
+ return true, ""
+}
+
+// persist writes rec unless the stored record differs only in its time, so
+// an idle hourly pass does not churn the file; At is when this state began.
+func (s consoleFleetStep) persist(rec consolefleet.Record) {
+ if raw, err := s.readRecord(); err == nil {
+ if old, err := consolefleet.DecodeRecord(raw); err == nil && old.Outcome == rec.Outcome && old.Reason == rec.Reason && old.Exclusive == rec.Exclusive {
+ return
+ }
+ }
+ raw, err := json.Marshal(rec)
+ if err == nil {
+ err = s.writeRecord(raw)
+ }
+ if err != nil {
+ log.Printf("adopt: console fleet record: %v", err)
+ }
+}
+
+// productionConsoleFleetStep is the step as root runs it.
+func productionConsoleFleetStep(ctx context.Context) consoleFleetStep {
+ store := func() (rootstate.Store, error) { return rootstate.Open(consolefleet.StatusDir, true, true) }
+ withStore := func(f func(rootstate.Store) error) error {
+ st, err := store()
+ if err != nil {
+ return err
+ }
+ defer st.Close()
+ return f(st)
+ }
+ return consoleFleetStep{
+ show: func() (consoleUnitProps, error) {
+ out, err := systemd.Command(systemd.Systemctl, "show", consolefleet.Unit, "-p", strings.Join(consoleUnitShowKeys, ",")).Output(ctx)
+ if err != nil {
+ return consoleUnitProps{}, err
+ }
+ return parseConsoleUnitProps(out)
+ },
+ reload: daemonReload,
+ readDropIn: func() ([]byte, bool, error) {
+ b, err := os.ReadFile(consolefleet.DropInPath)
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil, false, nil
+ }
+ return b, err == nil, err
+ },
+ writeDropIn: func(b []byte) error {
+ if err := os.MkdirAll(filepath.Dir(consolefleet.DropInPath), 0o755); err != nil {
+ return err
+ }
+ return hostfloor.Durable(consolefleet.DropInPath, b, 0o644)
+ },
+ removeDropIn: func() error {
+ if err := os.Remove(consolefleet.DropInPath); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ return syncDir(filepath.Dir(consolefleet.DropInPath))
+ },
+ markerPresent: func() (bool, error) {
+ found := false
+ err := withStore(func(st rootstate.Store) error {
+ _, err := st.Read(consolefleet.ReloadPending)
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ found = err == nil
+ return err
+ })
+ return found, err
+ },
+ setMarker: func() error {
+ return withStore(func(st rootstate.Store) error { return st.Write(consolefleet.ReloadPending, []byte("1\n")) })
+ },
+ clearMarker: func() error {
+ return withStore(func(st rootstate.Store) error { return st.Remove(consolefleet.ReloadPending) })
+ },
+ claimant: func() (string, bool) { return caps.RuntimeDirClaimant(dropInRoot, consolefleet.RuntimeDirName) },
+ runDirExists: func() (bool, error) {
+ _, err := os.Lstat(consolefleet.Dir)
+ if errors.Is(err, fs.ErrNotExist) {
+ return false, nil
+ }
+ return err == nil, err
+ },
+ readRecord: func() ([]byte, error) {
+ var raw []byte
+ err := withStore(func(st rootstate.Store) error {
+ var err error
+ raw, err = st.Read(consolefleet.StatusFile)
+ return err
+ })
+ return raw, err
+ },
+ writeRecord: func(b []byte) error {
+ return withStore(func(st rootstate.Store) error { return st.Write(consolefleet.StatusFile, b) })
+ },
+ now: time.Now,
+ }
+}
+
+// adoptConsoleFleetStep is the step runAdoptUnderRootRelease runs; a
+// variable so a test can drive the real pass with the step injected.
+var adoptConsoleFleetStep = func(ctx context.Context) {
+ s := productionConsoleFleetStep(ctx)
+ rec := s.run()
+ log.Print(consoleFleetLogLine(rec))
+ s.persist(rec)
+}
+
+func consoleFleetLogLine(rec consolefleet.Record) string {
+ line := fmt.Sprintf("console fleet: %s, exclusive=%t", rec.Outcome, rec.Exclusive)
+ if rec.Reason != "" {
+ line += ": " + rec.Reason
+ }
+ return line
+}
diff --git a/internal/host/consolefleet_test.go b/internal/host/consolefleet_test.go
new file mode 100644
index 000000000..065602488
--- /dev/null
+++ b/internal/host/consolefleet_test.go
@@ -0,0 +1,230 @@
+package host
+
+import (
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/consolefleet"
+)
+
+// fakeConsoleFleet is every seam of consoleFleetStep, in memory.
+type fakeConsoleFleet struct {
+ props consoleUnitProps
+ showErr error
+ dropIn []byte // nil = absent
+ readErr error
+ writeErr error
+ removeErr error
+ reloadErr error
+ reloads int
+ writes int
+ removes int
+ marker bool
+ markerErr error
+ claimant string
+ claimed bool
+ runDirFound bool
+ record []byte
+ recordErr error
+}
+
+func (f *fakeConsoleFleet) step() consoleFleetStep {
+ return consoleFleetStep{
+ show: func() (consoleUnitProps, error) { return f.props, f.showErr },
+ reload: func() error { f.reloads++; return f.reloadErr },
+ readDropIn: func() ([]byte, bool, error) {
+ if f.readErr != nil {
+ return nil, false, f.readErr
+ }
+ return f.dropIn, f.dropIn != nil, nil
+ },
+ writeDropIn: func(b []byte) error {
+ f.writes++
+ if f.writeErr != nil {
+ return f.writeErr
+ }
+ f.dropIn = append([]byte(nil), b...)
+ return nil
+ },
+ removeDropIn: func() error {
+ f.removes++
+ if f.removeErr != nil {
+ return f.removeErr
+ }
+ f.dropIn = nil
+ return nil
+ },
+ markerPresent: func() (bool, error) { return f.marker, f.markerErr },
+ setMarker: func() error { f.marker = true; return f.markerErr },
+ clearMarker: func() error { f.marker = false; return f.markerErr },
+ claimant: func() (string, bool) { return f.claimant, f.claimed },
+ runDirExists: func() (bool, error) { return f.runDirFound, nil },
+ readRecord: func() ([]byte, error) { return f.record, f.recordErr },
+ writeRecord: func(b []byte) error { f.record = append([]byte(nil), b...); return nil },
+ now: func() time.Time { return time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC) },
+ }
+}
+
+func loadedConsole() consoleUnitProps {
+ return consoleUnitProps{LoadState: "loaded", ActiveState: "active", RuntimeDirectory: []string{consolefleet.RuntimeDirName}, Mode: "0755", Preserve: "no"}
+}
+
+func TestConsoleFleetInstallsOnceAndReloadsOnce(t *testing.T) {
+ f := &fakeConsoleFleet{props: loadedConsole()}
+ rec := f.step().run()
+ if rec.Outcome != consolefleet.OutcomeInstalled || !rec.Exclusive || string(f.dropIn) != consolefleet.DropInBody || f.reloads != 1 || f.marker {
+ t.Fatalf("first pass: %+v drop-in %q reloads %d marker %v", rec, f.dropIn, f.reloads, f.marker)
+ }
+ rec = f.step().run()
+ if rec.Outcome != consolefleet.OutcomeUnchanged || !rec.Exclusive || f.writes != 1 || f.reloads != 1 {
+ t.Fatalf("second pass: %+v writes %d reloads %d", rec, f.writes, f.reloads)
+ }
+}
+
+// A reload that fails after the drop-in changed leaves the marker, so the
+// next pass reloads although the bytes now match (round 2, P2-2), and the
+// record is not exclusive until it does.
+func TestConsoleFleetFailedReloadIsRetriedWithUnchangedBytes(t *testing.T) {
+ f := &fakeConsoleFleet{props: loadedConsole(), reloadErr: errors.New("bus timeout")}
+ rec := f.step().run()
+ if rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || !f.marker || string(f.dropIn) != consolefleet.DropInBody {
+ t.Fatalf("failed reload: %+v marker %v drop-in %q", rec, f.marker, f.dropIn)
+ }
+ rec = f.step().run()
+ if rec.Outcome != consolefleet.OutcomeFailed || f.reloads != 2 || !f.marker || f.writes != 1 {
+ t.Fatalf("still failing: %+v reloads %d writes %d", rec, f.reloads, f.writes)
+ }
+ f.reloadErr = nil
+ rec = f.step().run()
+ if rec.Outcome != consolefleet.OutcomeUnchanged || !rec.Exclusive || f.reloads != 3 || f.marker || f.writes != 1 {
+ t.Fatalf("recovered: %+v reloads %d marker %v writes %d", rec, f.reloads, f.marker, f.writes)
+ }
+}
+
+// A failed write leaves the marker too: whatever reached the disk is
+// reloaded next pass.
+func TestConsoleFleetFailedWriteKeepsTheMarker(t *testing.T) {
+ f := &fakeConsoleFleet{props: loadedConsole(), writeErr: errors.New("disk full")}
+ rec := f.step().run()
+ if rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || !f.marker || f.reloads != 0 {
+ t.Fatalf("failed write: %+v marker %v reloads %d", rec, f.marker, f.reloads)
+ }
+ if !strings.Contains(rec.Reason, "disk full") {
+ t.Fatalf("reason %q", rec.Reason)
+ }
+}
+
+// No marker can be written: nothing is changed.
+func TestConsoleFleetNoMarkerNoChange(t *testing.T) {
+ f := &fakeConsoleFleet{props: loadedConsole(), markerErr: errors.New("read-only")}
+ rec := f.step().run()
+ if rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || f.writes != 0 || f.reloads != 0 {
+ t.Fatalf("%+v writes %d reloads %d", rec, f.writes, f.reloads)
+ }
+}
+
+func TestConsoleFleetRemovesWhenTheConsoleIsGone(t *testing.T) {
+ f := &fakeConsoleFleet{props: consoleUnitProps{LoadState: "not-found"}, dropIn: []byte(consolefleet.DropInBody)}
+ rec := f.step().run()
+ if rec.Outcome != consolefleet.OutcomeRemoved || rec.Exclusive || f.dropIn != nil || f.reloads != 1 || f.marker {
+ t.Fatalf("%+v drop-in %q reloads %d marker %v", rec, f.dropIn, f.reloads, f.marker)
+ }
+ rec = f.step().run()
+ if rec.Outcome != consolefleet.OutcomeAbsent || rec.Exclusive || f.removes != 1 || f.reloads != 1 {
+ t.Fatalf("second pass: %+v removes %d reloads %d", rec, f.removes, f.reloads)
+ }
+}
+
+func TestConsoleFleetNotExclusive(t *testing.T) {
+ for name, tc := range map[string]struct {
+ mutate func(*fakeConsoleFleet)
+ reason string
+ }{
+ "preserved": {func(f *fakeConsoleFleet) { f.props.Preserve = "restart" }, "RuntimeDirectoryPreserve"},
+ "mode": {func(f *fakeConsoleFleet) { f.props.Mode = "0700" }, "RuntimeDirectoryMode"},
+ "not applied": {func(f *fakeConsoleFleet) {
+ f.props.RuntimeDirectory = nil
+ }, "not in effect"},
+ "app claim": {func(f *fakeConsoleFleet) { f.claimant, f.claimed = "old.example.com", true }, "old.example.com"},
+ "directory while stopped": {func(f *fakeConsoleFleet) {
+ f.props.ActiveState = "inactive"
+ f.runDirFound = true
+ }, consolefleet.Dir},
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := &fakeConsoleFleet{props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
+ tc.mutate(f)
+ rec := f.step().run()
+ if rec.Exclusive || !strings.Contains(rec.Reason, tc.reason) {
+ t.Fatalf("%+v, want not exclusive naming %q", rec, tc.reason)
+ }
+ })
+ }
+ // Stopped with no directory left behind is still exclusive.
+ f := &fakeConsoleFleet{props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
+ f.props.ActiveState = "inactive"
+ if rec := f.step().run(); !rec.Exclusive {
+ t.Fatalf("stopped console, no directory: %+v", rec)
+ }
+}
+
+func TestConsoleFleetShowFailureChangesNothing(t *testing.T) {
+ f := &fakeConsoleFleet{showErr: errors.New("no bus"), dropIn: []byte(consolefleet.DropInBody)}
+ rec := f.step().run()
+ if rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || f.writes+f.removes+f.reloads != 0 {
+ t.Fatalf("%+v", rec)
+ }
+ f = &fakeConsoleFleet{props: consoleUnitProps{LoadState: "masked"}}
+ if rec := f.step().run(); rec.Outcome != consolefleet.OutcomeFailed || rec.Exclusive || f.writes+f.removes != 0 {
+ t.Fatalf("masked: %+v", rec)
+ }
+}
+
+// The record is rewritten only when something but its time changed, so an
+// idle hourly pass leaves the file alone.
+func TestConsoleFleetRecordWrittenOnlyOnChange(t *testing.T) {
+ f := &fakeConsoleFleet{props: loadedConsole(), dropIn: []byte(consolefleet.DropInBody)}
+ s := f.step()
+ s.persist(s.run())
+ first := string(f.record)
+ s.now = func() time.Time { return time.Date(2026, 11, 24, 11, 0, 0, 0, time.UTC) }
+ s.persist(s.run())
+ if string(f.record) != first {
+ t.Fatalf("idle pass rewrote the record:\n%s\n%s", first, f.record)
+ }
+ f.props.Preserve = "yes"
+ s.persist(s.run())
+ var rec consolefleet.Record
+ if err := json.Unmarshal(f.record, &rec); err != nil || rec.Exclusive {
+ t.Fatalf("changed record not written: %s %v", f.record, err)
+ }
+ if _, err := consolefleet.DecodeRecord(f.record); err != nil {
+ t.Fatalf("root's record does not decode: %v", err)
+ }
+}
+
+func TestParseConsoleUnitProps(t *testing.T) {
+ good := "Id=console.service\nLoadState=loaded\nActiveState=active\nRuntimeDirectory=console carlos-console\nRuntimeDirectoryMode=0755\nRuntimeDirectoryPreserve=no\n"
+ p, err := parseConsoleUnitProps([]byte(good))
+ if err != nil || p.LoadState != "loaded" || len(p.RuntimeDirectory) != 2 || !p.hasRuntimeDir(consolefleet.RuntimeDirName) {
+ t.Fatalf("%+v %v", p, err)
+ }
+ notFound := "Id=console.service\nLoadState=not-found\nActiveState=inactive\nRuntimeDirectory=\nRuntimeDirectoryMode=0755\nRuntimeDirectoryPreserve=no\n"
+ if p, err := parseConsoleUnitProps([]byte(notFound)); err != nil || p.LoadState != "not-found" || len(p.RuntimeDirectory) != 0 {
+ t.Fatalf("not-found: %+v %v", p, err)
+ }
+ for name, raw := range map[string]string{
+ "missing key": "Id=console.service\nLoadState=loaded\n",
+ "wrong unit": strings.Replace(good, "Id=console.service", "Id=other.service", 1),
+ "two blocks": good + "\n" + good,
+ "repeated key": good + "LoadState=loaded\n",
+ "no equals": good + "junk\n",
+ } {
+ if _, err := parseConsoleUnitProps([]byte(raw)); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}