carlos / platform Public

Console plans: Astra round 4 fixes; cached loaders restricted to the object store

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 2fb56393f62802477a8295fffbcc8533bbe3501c parent 001cc83
3 files changed, +76 −45
  • docs/superpowers/plans/2026-10-25-console-perf-1-measure.md +5 −3
  • docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md +36 −24
  • docs/superpowers/plans/2026-10-25-operator-pages.md +35 −18

CI passed — run details

diff --git a/docs/superpowers/plans/2026-10-25-console-perf-1-measure.md b/docs/superpowers/plans/2026-10-25-console-perf-1-measure.md
index e277f4c4f..9987839aa 100644
--- a/docs/superpowers/plans/2026-10-25-console-perf-1-measure.md
+++ b/docs/superpowers/plans/2026-10-25-console-perf-1-measure.md
@@ -367,6 +367,7 @@ The console makes no direct box HTTP call on a screen path today (Task 5); `Host
- `type perfTarget struct { Path string; Expect int; Anonymous bool }`
- `func newPerfFixture(t *testing.T) (*consoleFixture, *perfLatency)`: `newConsoleFixtureWith` with `WithKey: true`, `S3` set to a `perfLatency` (`S3Delay` 25 ms, `HostDelay` 40 ms), `AppClient` from the same `perfLatency`, then the seeds below.
- `func perfTargets(fx *consoleFixture) map[string][]perfTarget`
+ - `type perfScreenTarget struct { Screen string; Target perfTarget; Record *perfRecord }` and `func perfWalkTargets(fx *consoleFixture) []perfScreenTarget`: every screen in `perfInventory`, with `perfTargets`' entries or the default target for a parameter-less screen, and its budgets record; `skip` screens left out. The walk iterates it, and so do plan 2's coverage checks, so nothing walked can escape them.
- `func perfEnforce() bool`: `os.Getenv("CI") != "" || os.Getenv("AMADAN_CI") != ""`
- `func TestConsoleScreensMeetTheBudget(t *testing.T)` (not parallel)
- hooks plan 2 fills: `var perfQuiesce = func(fx *consoleFixture) {}`, called after every request before the call count is read; and `var perfColdReset = func(fx *consoleFixture) {}`, called before a screen's cold request so that it meets a console that has cached nothing for it.
@@ -404,9 +405,9 @@ The walk, per screen in `perfInventory`:
1. Structural checks, which fail always (not only under CI), all reported before anything is measured: a screen with a path parameter and no `perfTargets` entry; a `perfTargets` key or a budgets record naming no screen in the inventory ("stale: delete it"); a `skip` record on a screen that also has targets.
2. A `skip` screen is not requested.
-3. An `over` screen: latency disabled; two requests; the call count of the second is printed with its reason as `"%s %s: over (%s): %d S3 and %d host calls warm"`. Never failed. (Measured without latency so the slow screens cost the test milliseconds, not seconds.)
+3. An `over` screen: latency disabled; two requests; the call count of the second is printed with its reason as `"%s %s: over (%s): %d S3 and %d host calls warm"`. Its status must still equal `Expect` on both, failed always: `over` exempts a screen from the latency and call thresholds only, never from answering correctly. (Measured without latency so the slow screens cost the test milliseconds, not seconds; Astra round 4, finding 8.)
4. Every other screen: latency enabled; ten requests; the first two discarded. Time to first byte is `httptrace`'s `GotFirstResponseByte` as Rastrillo's `perftest` measures it; each response is read to the end. After each request, wait until the handler has returned (an in-flight counter in the `httptest` handler, as `perftest.screens` does), call `perfQuiesce(fx)`, then read the call delta. Status must equal `Expect`, always failed. Calls: the largest delta over the eight measured requests must not exceed the allowance (0, or `n` from a `calls n:` record), always failed, because counts are deterministic. *(My call: the spec says the test fails only when CI is set; that is applied to timing, which is noisy on a laptop, and not to counts, which are not.)* Time: median of the eight within 150 ms and none over 450 ms, failed only when `perfEnforce()`, printed always. A `deferred` screen is timed and printed but exempt from both the 150 ms rule and the count.
-5. Before its warm requests, every screen that is not `skip`, `over` or `deferred` gets one **cold** request: `perfColdReset(fx)`, latency on, one request, its time to first byte held to 150 ms (failed only when `perfEnforce()`, printed always). Then latency goes off until `perfQuiesce` returns, so the background loads that cold request started cost the test milliseconds, and back on for the warm requests. Spec §2.6 asks for the first view after a restart within 150 ms, and a screen that is fast only once cached would pass the warm requests alone. A screen that fails the cold request is recorded `over:` like any other. *(Astra round 2, finding 7.)*
+5. Every request the walk makes, cold or warm, of any kind of screen, has its status checked against `Expect`. Before its warm requests, every screen that is not `skip`, `over` or `deferred` gets one **cold** request: `perfColdReset(fx)`, latency on, one request, its time to first byte held to 150 ms (failed only when `perfEnforce()`, printed always). Then latency goes off until `perfQuiesce` returns, so the background loads that cold request started cost the test milliseconds, and back on for the warm requests. Spec §2.6 asks for the first view after a restart within 150 ms, and a screen that is fast only once cached would pass the warm requests alone. A screen that fails the cold request is recorded `over:` like any other. *(Astra round 2, finding 7.)*
6. Print each result with `t.Logf` (`cold`, `median`, `worst`, `calls`). At the end, print the total elapsed time; when `perfEnforce()` and it exceeds 10 s, fail.
Warm-page counts alone cannot show that total S3 use fell: they miss first views, deferred loads and a write's own reads. `TestPerfSessionS3Requests` covers the whole session. On `newPerfFixture`, latency disabled, signed in as Paul, it runs a fixed script and sums every counted S3 request, calling `perfQuiesce` after each step so background loads are included: each of the nine app tab URLs and the settings sections, twice each; the account home, Team, account settings and Trash, twice each; one promote of `v2` to `stable` through the browser form; then Overview and Releases again. The file `testdata/perf-session-s3.txt` holds one line, `<n> <reason>`. The test fails (always, since counts are deterministic) when the total exceeds `n`, and prints the total. This task records today's total as `n`. Plan 2 lowers it.
@@ -442,7 +443,8 @@ Not a code task. Spec §2.5 step 1: ship and roll this on its own and read flags
## Self-review
- **Spec coverage.** §2.1: budget, methods, streams, no cold start (Tasks 2, 3); API GETs timed in production but not walked (Task 8 inventory). §2.2: middleware on the console mux (Task 4), `Server-Timing` with `app` and spans (Task 3), spans `db`, `s3`, `box`, `render` at the seams (Tasks 4, 5), grouping by pattern (Tasks 3, 4), throttled warning (Tasks 2, 6), the 2,048 ring and Console speed table (Tasks 2, 7), `Skip` `/healthz` (Task 4). §2.3: walk over every `registerRoute` screen including method-less ones (Tasks 8, 10), production constructor (Tasks 9, 10), latency injection 25 ms and 40 ms (Task 9), warm-cache call counts with default zero and `perf-budgets.txt` reasons (Tasks 8, 10), fixtures for every parameter and failure for a missing one (Task 10), deferred parts listed and exempt (Task 8 grammar, Task 10), fails only under `CI` for timing (Task 10), under 10 s (Task 10). §2.5 steps 1 and 2: Tasks 1 to 10 and 12.
-- **Calls that cross plans.** Plan 2 uses `perf.SpanContext`, `perf.TimeDoer`, `Config.Perf`, `Server.PerfGroups`, `Server.PerfBackground`, `TimeS3Store`, `newPerfFixture`, `newConsoleFixtureWith`, `perfTargets`, `perfTarget`, `perfQuiesce`, `perfColdReset`, `perfLatency` (`Enable`, `Calls`, `Fake`), `s3fake.Server` (`OnRequest`, `Requests`), `perfRecord`, `loadPerfBudgets`, `TestPerfSessionS3Requests` with `perf-session-s3.txt`, and the `perf-budgets.txt` grammar by these names.
+- **Calls that cross plans.** Plan 2 uses `perf.SpanContext`, `perf.TimeDoer`, `Config.Perf`, `Server.PerfGroups`, `Server.PerfBackground`, `TimeS3Store`, `newPerfFixture`, `newConsoleFixtureWith`, `perfTargets`, `perfTarget`, `perfWalkTargets`, `perfQuiesce`, `perfColdReset`, `perfLatency` (`Enable`, `Calls`, `Fake`), `s3fake.Server` (`OnRequest`, `Requests`), `perfRecord`, `loadPerfBudgets`, `TestPerfSessionS3Requests` with `perf-session-s3.txt`, and the `perf-budgets.txt` grammar by these names.
+- **Review round 4 (Astra, `CODEX-FINDINGS-CONSOLE-PLANS-R4.md`).** Finding 8: every request's status is checked, `over` included; `over` exempts only latency and call counts (Task 10). Finding 6 (plan 2): `perfWalkTargets` is the one expanded target list (Task 10).
- **Review round 3 (Astra, `CODEX-FINDINGS-CONSOLE-PLANS-R3.md`).** Finding 1: the contract runs from `release_test` with the raw helpers exported only in test builds, so `release → s3fake → release` never forms (Task 9). Finding 6 (plan 2's seam): this plan's `TestRunningTabTimesTheAppHost` and `TestOverBudgetPageIsLogged` run on untracked fixtures, which plan 2 reads inline, so they keep testing request-path instrumentation.
- **Review round 2 (Astra, `CODEX-FINDINGS-CONSOLE-PLANS-R2.md`).** R1 #14: requests are now counted at the HTTP transport against an S3 fake running the production `S3Store` (listing pages including objects a delimiter page skips, change-index requests on writes), Task 9. Finding 7: a cold first request per screen, enforced, Task 10. Finding 8: `TimeDoer`'s span stays open to body EOF or close, Task 3.
- **Review round 1 (Astra, at `e9f42e19`).** Finding 8 (span test ended its spans after the write: Task 3 now ends them first), 14 (listings counted per 1,000-key page and at the HTTP boundary in production; populated sections and paginated box listings seeded; a whole-session S3 ceiling, Tasks 2, 3, 5, 7, 9, 10), 16 (`renderCLI` shares the buffered seam, Task 4).
diff --git a/docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md b/docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md
index 60c90f567..9af2dda2a 100644
--- a/docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md
+++ b/docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md
@@ -29,7 +29,7 @@ Every task's requirements include this section.
- **S3 requests cost money.** Total S3 requests go down, not just warm-page counts: `TestPerfSessionS3Requests`' ceiling falls (Task 17) and the Console speed table's per-route and background counts fall on flagship. Refresh happens only when someone views the screen (a page GET, a part fetch) or inside a mutation's own request. No timers, no tickers, no per-app or per-box polling, no warm-up at start. A background load is one goroutine per key, started by a view, ended within `viewLoadTimeout`.
- **Freshness, verbatim from the spec.** About 30 s for live data (instance health, observed versions, box snapshots, edges, app self-reports, logs, errors and analytics windows): `liveWindow = 30 * time.Second`. About 5 min for data only console writes change (manifests, channels, pipeline, account manifest, settings records): `writtenWindow = 5 * time.Minute`.
- **Cached values are immutable.** `viewGet` hands every caller its own copy (`viewClone`). No consumer can change what the next request sees. Pointer fields inside a cached value are never written through.
-- **Read your own writes, by read set** (Task 8). Every cache entry records the object keys its load read and the prefixes it listed. Every acknowledged object-store write invalidates, at once, every entry whose read set covers its key, bumping its generation, which also covers a load already in flight; such a load can never publish. The writing request re-reads those entries before it answers. If the re-read fails, the write still stands and the entries stay invalidated: the next GET is a miss. A refused request writes nothing and so touches nothing. The pre-write value is never served after the user's own write. Two rules keep read sets complete: a cached value holds only object-store facts (routes, SQLite rows and the clock are joined per request), and a load whose key set comes from local state caches one entry per key. A server with no store tracker caches nothing.
+- **Read your own writes, by read set** (Task 8). Every cache entry records the object keys its load read and the prefixes it listed. Every acknowledged object-store write invalidates, at once, every entry whose read set covers its key, bumping its generation, which also covers a load already in flight; such a load can never publish. The writing request re-reads those entries before it answers. If the re-read fails, the write still stands and the entries stay invalidated: the next GET is a miss. A refused request writes nothing and so touches nothing. The pre-write value is never served after the user's own write. Two rules keep read sets complete: a cached value holds only object-store facts (routes, SQLite rows and the clock are joined per request), and a load whose key set comes from local state caches one entry per key. The first is structural: loaders are package-level functions given only `viewLoadEnv` (the observed store, the release key, a read time, DNS), checked by the compiler and by `TestViewLoadersAreRestricted` (Task 6). A server with no store tracker caches nothing.
- **Deferred parts.** The page arrives within 150 ms. A part the cache does not hold renders as a placeholder that a `fetch()` fills, following the Logs tab's pattern (`templates/app_logs.html:66-196`: inline script, an `AbortController` with a 20 s timeout, an `Accept` header). Parts are HTML fragments rendered by the same templates as the page. No new JS framework. With JavaScript off the page is still usable minus that part, and its placeholder says how to see it. A part endpoint runs its page's own full authorization before it touches the cache. Independent reads that remain on a request path run concurrently; removing them is the goal.
- **Console security gate order is unchanged:** session, then CSRF, then owner (byte-identical 404), then `requireFreshAuth`. A request the gate refuses starts no load and makes no remote call.
- **New routes pass the existing route gates.** Every registration this plan adds gets its line in `internal/console/testdata/claim-routes.txt`, a classification in `claimFixtures` (`claim_invariant_fixtures_test.go:722`) and a probe in `claimReadProbes` (`claim_invariant_probes_read_test.go:112`), in the task that adds it.
@@ -235,6 +235,7 @@ Spec §2.4 C rows "Settings, `populateAppSettings`", "`appDeployEmpty`" and "`en
**Files:**
- Create: `internal/console/viewcache.go`; Test: `internal/console/viewcache_test.go`
+- Create: `internal/console/viewloaders.go` (every loader lives here; empty but for the probe's in this task); Test: `internal/console/viewloaders_test.go` (`TestViewLoadersAreRestricted`)
- Modify: `internal/console/server.go` (`Server.views *viewCache`, set in `NewServer` to `newViewCache(s.now, viewCacheMax)`; `Server.now func() time.Time`, `time.Now` by default, the clock every request-time derivation in Tasks 9 to 14 reads)
- Modify: `internal/console/perfwalk_test.go` (`perfQuiesce = func(fx *consoleFixture) { fx.srv.waitBackground() }`; `perfColdReset = func(fx *consoleFixture) { fx.srv.resetForColdView() }`; `newPerfFixture` sets `fx.clock` and points `fx.srv.now` at it)
- Modify: `internal/console/metricsview.go:361`, `internal/console/economicsview.go:288-300` (their own background sweeps run through `s.bg.Go`, Task 2's `bgWork`, as view loads do from this task on).
@@ -248,17 +249,22 @@ Spec §2.4 C rows "Settings, `populateAppSettings`", "`appDeployEmpty`" and "`en
- `type viewCloner[T any] interface { viewClone() T }`: every cached type implements it, copying every slice and map it holds (pointer fields are shared and read-only).
- `type viewResult[T any] struct { Val T; At time.Time; Stale bool }`
- `func newViewCache(now func() time.Time, max int) *viewCache`
- - `func viewPeek[T viewCloner[T]](c *viewCache, key viewKey, window time.Duration, load func(context.Context) (T, error)) (viewResult[T], bool)`: never blocks. A valid entry returns a clone and `true`, with `Stale` when older than `window`, in which case a refresh is started unless one is running at the entry's current generation. A missing or invalid entry returns `false` and starts a load unless one is running at the current generation.
- - `func viewWait[T viewCloner[T]](ctx context.Context, c *viewCache, key viewKey, window time.Duration, load func(context.Context) (T, error)) (viewResult[T], error)`: a valid entry returns a clone at once; otherwise joins the load running at the current generation or starts one, and waits for it or for `ctx`.
- - read sets: every entry carries `type readSet struct { keys map[string]bool; prefixes []string }`, the object keys its load read and the prefixes it listed, filled while the load runs by Task 8's tracker through the load's context (`withReadSet(ctx, *readSet) context.Context`). A new load of an entry starts with an empty set.
- - `func (c *viewCache) touched(key string) []viewKey`: for every entry whose read set holds `key` or a prefix of it (an entry exists, with its set, from the moment its first load starts), bump its generation and mark it invalid; a load that started at an older generation, first load or refresh, then discards its result. Returns the entries it invalidated.
+ - **The restricted loader** (rule (a), made structural; Astra round 4, findings 2 to 4):
+ - `type viewLoadEnv struct { Ctx context.Context; Store release.Store; Pub ed25519.PublicKey; ReadAt time.Time; LookupTXT func(ctx context.Context, name string) ([]string, error) }`, built by the cache for each load. It holds the observed object store, the release key, the time the load started (only for library calls that need a read time, such as the box listing's 24-hour horizon; nothing derived from it is shown), and DNS as one explicit, named dependency. It holds no `*Server`, no console `Store`, no registry and no clock.
+ - `type viewLoader[A, T any] func(env viewLoadEnv, key viewKey, arg A) (T, error)`. Every loader is a package-level function in `internal/console/viewloaders.go`, so it can reach neither a `*Server` nor the console `Store`: it is given neither, and that is checked by the compiler. `arg` carries the load's inputs as plain data (a page number, a filter, a period's dates).
+ - `TestViewLoadersAreRestricted` (`viewloaders_test.go`, built on `go/parser`) closes the remaining doors, which are package-level globals. (1) At every call of `viewPeek`, `viewWait` and `viewGet`, the loader argument is an identifier naming a function declared in `viewloaders.go`: no function literal, no method value, nothing that could capture state. (2) No function in `viewloaders.go`, nor any package-level function of package `console` they call, transitively by name, mentions `openRegistry`, `memoRoutes`, `registry.`, `database/sql`, `time.Now`, `time.Since`, `time.Until`, `context.Background` or `context.TODO` (a store call off `env.Ctx` would escape the read set), or has a receiver. (3) Every `A` and `T` named in `var viewLoaderTypes` (one entry per loader, kept complete by (1)'s scan) is, by `reflect`, plain data, with no pointer to anything mutable outside the value, no func, chan or interface field. The two read-only pointers `appCore` holds (`*release.Pipeline`, `*release.ProductionFlag`) are listed by name as allowed.
+ - Everything that needs local state, the registry or the clock is joined per request, in the screen's fill, from the cached facts. Each later task names, per loader, what is cached and what is joined.
+ - `func viewPeek[A any, T viewCloner[T]](c *viewCache, key viewKey, window time.Duration, load viewLoader[A, T], arg A) (viewResult[T], bool)`: never blocks. A valid entry returns a clone and `true`, with `Stale` when older than `window`, in which case a refresh is started unless one is running at the entry's current generation. A missing or invalid entry returns `false` and starts a load unless one is running at the current generation.
+ - `func viewWait[A any, T viewCloner[T]](ctx context.Context, c *viewCache, key viewKey, window time.Duration, load viewLoader[A, T], arg A) (viewResult[T], error)`: a valid entry returns a clone at once; otherwise joins the load running at the current generation or starts one, and waits for it or for `ctx`.
+ - read sets: every entry carries `type readSet struct { keys map[string]bool; prefixes []string }`, the object keys its load read and the prefixes it listed, filled while the load runs by Task 8's tracker through the load's context (`withReadSet(ctx, *readSet) context.Context`). An entry keeps two: the **published** set, of the value it is serving, and the **in-flight** set, of the load running now. A load starts with an empty in-flight set. Only a successful publish replaces the published set with the in-flight one. A failed or discarded load drops its in-flight set and leaves the published set alone. *(Astra round 4, finding 1: a refresh that has not yet reached a key must not hide that the value being served depends on it.)*
+ - `func (c *viewCache) touched(key string) []viewKey`: for every entry whose published or in-flight read set holds `key` or a prefix of it (an entry exists, with its set, from the moment its first load starts), bump its generation and mark it invalid; a load that started at an older generation, first load or refresh, then discards its result. Returns the entries it invalidated.
- `func (c *viewCache) reread(ctx context.Context, keys []viewKey) (failed int)`: for each key that has an entry, start a load at its current generation; all run concurrently under `ctx`, and `reread` waits for them. A success publishes; a failure leaves the entry invalid and counts in `failed`.
- `func (c *viewCache) snapshot() []viewEntryInfo` (test-only: key, generation, valid, read set), for Task 8's coverage check.
- `func asOfText(now, at time.Time) string`: CPF-20 with CPF-21 to CPF-25 (under a minute, 1 minute, n minutes, 1 hour, n hours).
The rules the implementation keeps:
- A load runs in its own goroutine (through `s.bg.Go`) on `context.WithTimeout(context.Background(), viewLoadTimeout)`, never on a request's context, so a closed tab does not cancel a load other viewers share and no span lands on a finished request. (Its S3 requests are counted in `Server.PerfBackground()` by plan 1's `TimeDoer`.) `reread`'s loads run on the mutation's own context, bounded the same way.
-- Each entry stores its loader (as `func(context.Context) (any, error)`) so `reread` can re-run it, plus its value, `At`, generation and the generation of the load in flight, if any. Single flight is per key and generation.
+- Each entry stores its loader and argument (bound as `func(viewLoadEnv) (any, error)`) so `reread` can re-run it, plus its value, `At`, generation and the generation of the load in flight, if any. Single flight is per key and generation.
- A refresh that fails leaves the previous valid value in place (the next view retries once the window has passed again) but never makes an invalid entry valid.
- Over `max` entries, the least recently used entries with no load in flight are dropped.
- Nothing runs on a timer, and no goroutine outlives its load.
@@ -269,6 +275,8 @@ The rules the implementation keeps:
- `TestViewWaitJoinsTheRunningLoad`: a peek starts a blocked load; `viewWait` waits; releasing the loader returns its value to both, with one run.
- `TestViewWaitHonoursItsContext`: a blocked loader and a 20 ms `ctx`: `viewWait` returns `ctx.Err()`.
- `TestLoadInFlightAtAWriteNeverPublishes`: two sub-tests. *First load:* a peek on a miss starts a load that records key `k` in its read set, reads value A and blocks; `touched("k")` then `reread` with a loader now answering B; release the first load; the entry holds B, never A, at any point a peek can see. *Refresh:* the same with a warm stale entry whose refresh reads A.
+ - `TestWriteToADependencyTheRefreshHasNotReachedInvalidates`: a warm entry whose published set holds `a` and `b`; a refresh starts, reads `a` and blocks before `b`; `touched("b")` invalidates the entry (from the published set), and the refresh, released, discards its result.
+ - `TestWriteAfterAFailedRefreshStillInvalidates`: a warm entry whose published set holds `b`; a refresh that fails after reading only `a`; the entry still serves its old value (stale) with its published set intact; `touched("b")` invalidates it.
- `TestTouchedCoversExactKeysAndListedPrefixes`: three entries, one that read `a/x`, one that listed `a/`, one that read `b/y`; `touched("a/x")` invalidates the first two and not the third; `touched("a/z")` invalidates only the lister.
- `TestRereadFailureLeavesEntryInvalid`: the re-read fails; `failed == 1`; the next peek is a miss, not the pre-write value.
- `TestBackgroundWaitCoversEveryWorker`: a view load, a `bg.Go` worker and a held loader; `waitBackground` returns only after all three end.
@@ -277,7 +285,7 @@ The rules the implementation keeps:
- `TestViewCacheEvictsLeastRecentlyUsed`: `max` 3; four keys loaded; the least recently peeked is gone; an entry mid-load is not evicted.
- `TestViewValuesAreCopies`: changing a slice element of a peeked value does not change the next peek's value.
- `TestAsOfText`: 20 s → CPF-20 with CPF-21; 60 s → CPF-22; 150 s → CPF-23 with 2; 1 h → CPF-24; 3 h → CPF-25 with 3 (approved text verbatim).
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestView|TestLoadInFlight|TestTouched|TestRereadFailure|TestBackgroundWait|TestHungLoad|TestAsOfText' -count=1 -race`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestView|TestLoadInFlight|TestWriteToADependency|TestWriteAfterAFailedRefresh|TestTouched|TestRereadFailure|TestBackgroundWait|TestHungLoad|TestAsOfText' -count=1 -race`. Expected: FAIL.
- [ ] **Step 3: Implement**; add CPF-20 to CPF-25 to `consolePerfCopyBuilt`; set `perfQuiesce` and the fixture clock.
- [ ] **Step 4: Run** Step 2's command and `go test . -run TestConsolePerfCopy -count=1`. Expected: PASS.
- [ ] **Step 5: Commit**, message `console: in-process view cache: view-triggered single-flight refresh, read sets, generations that cover in-flight loads, immutable values`, ending with the Co-Authored-By line.
@@ -297,20 +305,20 @@ The rules the implementation keeps:
- Produces:
- `type viewMode int; const (viewCached viewMode = iota; viewBlocking)`
- `var errViewPending = errors.New("console: part not loaded yet")`
- - `func viewGet[T viewCloner[T]](ctx context.Context, s *Server, p *page, mode viewMode, key viewKey, window time.Duration, load func(context.Context) (T, error)) (T, error)`: `viewCached` peeks and returns `errViewPending` on a miss; `viewBlocking` waits under `ctx`. A stale result sets `p.AsOf` to the oldest stale `At` seen on this page.
+ - `func viewGet[A any, T viewCloner[T]](ctx context.Context, s *Server, p *page, mode viewMode, key viewKey, window time.Duration, load viewLoader[A, T], arg A) (T, error)`: `viewCached` peeks and returns `errViewPending` on a miss; `viewBlocking` waits under `ctx`. A stale result sets `p.AsOf` to the oldest stale `At` seen on this page.
- `type viewPart struct { Gate func(s *Server, w http.ResponseWriter, r *http.Request) (page, *Account, bool); Fill func(s *Server, r *http.Request, p *page, acct *Account, mode viewMode) error; Template string }`. `Gate` is the very function the part's page calls first (for app parts, `appPage`'s gates, which the tab handlers already share; for an account page, the gate that page calls, including any role or owner check and any check on a query parameter that the page does on its path, such as the instance page's host or the fleet page's `resolveOwnedFleet`). `Fill` is the page's own fill. A part is never registered without its page's gate.
- `var appParts, accountParts map[string]viewPart` (empty in this task; Tasks 9 to 14 add entries)
- routes `GET /a/{sqid}/apps/{app}/part/{part}` → `handleAppPart` and `GET /a/{sqid}/part/{part}` → `handleAccountPart`. Each looks up the part first (unknown is `http.NotFound`), runs its `Gate` before anything else, then `Fill(viewCached)` (which starts every missing load at once, so independent reads run concurrently) and `Fill(viewBlocking)` under `r.Context()` bounded by `viewLoadTimeout`; renders `Template` with `Cache-Control: no-store`; on an error that is not a rendered degrade answers 503 with the `partfailed` partial (CPF-28). Query parameters pass through to `Fill` (filters, `host`, `section`, `fleet`). There are no operator part routes (Part 3 owns those pages).
- `func (s *Server) renderView(w http.ResponseWriter, r *http.Request, p page, name, partURL string, fill error)`: `errViewPending` sets `p.Deferred = partURL` and renders `name` (whose body branch shows the placeholder); any other error is the screen's existing error handling; nil renders normally.
- partials in `parts.html`: `deferred` (`<div class="deferred" data-part="{{.Deferred}}">` with CPF-26 and a `<noscript>` CPF-27), `asof` (CPF-20 in small text when `.AsOf` is set), `partfailed` (CPF-28), `partloader` (the inline script), `part_text` (`{{template "asof" .}}<p>{{.Msg}}</p>`, the fragment the tests' probe part renders).
- test-only: `func getAssembled(t *testing.T, c *http.Client, u string) (status int, body string)`: GET `u`; then, up to five rounds, replace each `<div class="deferred" data-part="X">…</div>` with the body of a GET of `X` on the same client, as the loader script does. `claimPageRead` uses the same splice, so claim probes assert on the assembled page.
- - test-only: `func registerProbePart(t *testing.T, key viewKey, objectKey string)`: adds an app part `probe` (gate: `appPage`'s) whose `Fill` reads `objectKey` from `s.cfg.Releases` through `viewGet` (`writtenWindow`) into `p.Msg` and renders `part_text`; removed in `t.Cleanup`. Tests that use it are not parallel.
+ - test-only: `func registerProbePart(t *testing.T, key viewKey, objectKey string)`: adds an app part `probe` (gate: `appPage`'s) whose `Fill` reads `objectKey` through `viewGet` with the loader `loadProbeObject` (in `viewloaders.go`: one `env.Store.Get` of its `arg`) into `p.Msg` and renders `part_text`; removed in `t.Cleanup`. Tests that use it are not parallel.
The loader script, in the Logs tab's style: for each `[data-part]` element, `fetch(el.dataset.part, {headers: {Accept: "text/html"}, signal})` with an `AbortController` aborting after 20 s; on `ok` replace the element's `outerHTML` with the response text; otherwise (or on abort) replace it with the response text when there is one, else with CPF-28. After each replacement it dispatches `document.dispatchEvent(new CustomEvent("carlos:part", {detail: {part: <the part URL>, root: <the inserted element>}}))`. This plan owns that event; the operator-pages plan uses the same one. No polling and no retry: a part is fetched once per page view.
**No script inside a deferred fragment.** A fragment inserted with `outerHTML` does not run its `<script>` elements, so a template rendered as a part never contains one. A page's behaviour lives in its frame as an initializer that runs once on `DOMContentLoaded` over the whole document and again on every `carlos:part` over `event.detail.root`, finds its elements by id or attribute inside the root it is given, and never uses `document.currentScript`. *(Astra round 3, finding 5.)* With JavaScript off the `<noscript>` text stands, and a reload is a warm view because the miss started the load.
-Every screen converted in Tasks 9 to 14 follows one shape: its template becomes `{{define "<name>"}}{{template "top" .}}…chrome (flash, appnav, banners, page head)…{{if .Deferred}}{{template "deferred" .}}{{else}}{{template "<name>_body" .}}{{end}}{{template "bottom" .}}{{end}}` and `{{define "<name>_body"}}{{template "asof" .}}…the existing body…{{end}}`; its handler becomes the gate, `Fill(viewCached)`, `renderView`; its part entry reuses the same `Gate`, `Fill` and `<name>_body`. *(My call: on a miss the whole body is the deferred part, except where a section can render without the missing data, which Tasks 10, 11 and 13 make parts of their own: Releases' Versions, Running's app self-report and Domains' box readings. The change to each template stays at its first and last lines.)*
+Every screen converted in Tasks 9 to 14 follows one shape: its template becomes `{{define "<name>"}}{{template "top" .}}…chrome (flash, appnav, banners, page head)…{{if .Deferred}}{{template "deferred" .}}{{else}}{{template "<name>_body" .}}{{end}}{{template "bottom" .}}{{end}}` and `{{define "<name>_body"}}{{template "asof" .}}…the existing body…{{end}}`; its handler becomes the gate, `Fill(viewCached)`, `renderView`; its part entry reuses the same `Gate`, `Fill` and `<name>_body`. Each cached read named in Tasks 9 to 15 becomes a loader in `viewloaders.go`, named `load<Read>` (for example `loadTags`, `loadRetention`, `loadRecordHosts`, `loadEnvFacts`), returning only what it read. The fill joins anything local afterwards. Where a task names no loader, that is the rule. *(My call: on a miss the whole body is the deferred part, except where a section can render without the missing data, which Tasks 10, 11 and 13 make parts of their own: Releases' Versions, Running's app self-report and Domains' box readings. The change to each template stays at its first and last lines.)*
- [ ] **Step 1: Write the failing tests** (the probe part stores `"one"` at `apps/<sqid>/kass/probe.json` in `fx.rel`):
- `TestEveryPartGatesLikeItsPage`: for each registered part (the probe here; Tasks 9 to 14 add theirs, and this test walks both tables, so each new part is covered without an edit): signed out gives the same 302 to `/` the pages give; a signed-in non-member gives a 404 whose body equals that user's 404 for `/a/<sqid>/apps/kass` (app parts) or `/a/<sqid>/` (account parts); for all, `perfLatency.Calls()` is unchanged. An unknown part name is a 404 with no call. Parts with an extra check get their own refusal test in the task that adds them (Tasks 11, 13, 14).
@@ -361,6 +369,7 @@ Admission falls out of the design. A refused request (session, CSRF, owner, conf
- `func withWriteSet(ctx context.Context) (context.Context, *writeSet)` and `type viewRereadWriter struct { http.ResponseWriter; … }` (`WriteHeader`, `Write`, `Flush`, `Hijack`, `Unwrap`; it edits no header). `registerRoute` installs both on every request that is not GET or HEAD.
- On the first `WriteHeader`, or a `Write` without one, it re-reads the write set's entries through `s.views.reread`, on `context.WithTimeout(context.WithoutCancel(r.Context()), viewLoadTimeout)`, and then passes the call down.
- An empty write set does nothing. A write made after the response has started, or by a background pass, invalidates and is not re-read.
+ - **Primers**, for an entry that a write creates rather than changes (Astra round 4, finding 5): `type viewPrimer struct { Match func(key string) (viewKey, bool); Load any }` (the loader and its `arg` derived from the key), `var viewPrimers []viewPrimer`. When a write's key matches a primer, the tracker adds the primer's entry to the request's write set even though no entry exists yet. The re-read writer then loads it, a real read through the observed store, before the response goes out. One primer exists: an app tombstone's key primes `{sqid, "", trashPart(app)}` (Task 14). A primed entry is a validated read, never a value written from the request's own state.
- test-only: `func assertWriteCoverage(t *testing.T, before []viewEntryInfo, after []viewEntryInfo, written []string)`. Every entry in `before` that was valid and whose read set holds a written key, or a prefix of one, must have a newer generation in `after`; anything else fails, naming the entry and the key.
- [ ] **Step 1: Write the failing tests:**
@@ -373,12 +382,12 @@ Admission falls out of the design. A refused request (session, CSRF, owner, conf
- `TestInstanceCreateRefreshesHostsAndEnvs`: Logs' host picker (`partRecordHosts`) and Environments (`partEnvs`) warm; create an instance through the CLI door; the picker lists the new host and Environments shows it (its host join is per request, rule (a)).
- `TestScenarioActivationRefreshesArchitecture`: Architecture warm; activate a scenario through the economics door; Architecture's rate card is the new scenario's.
- `TestRefusedWritesInvalidateNothing`: a CSRF failure, a non-member, a plain member on an owner door, a validation error, and a promote stopped at its confirmation page. For each, the fake saw no write and every entry's generation is unchanged.
- - `TestReadSetsCoverEveryRead`: on `newPerfFixture`, for each screen in `perfTargets`: `resetForColdView`, `ResetKeys`, `getAssembled`, `waitBackground`. Every `GetObject` key and `ListObjectsV2` prefix the fake saw is held by some entry's read set, or is on a short allowlist of reads the cache does not hold: the account-manifest check, the change index, and reads that plan 1's warm walk already allows by a `calls` record.
+ - `TestReadSetsCoverEveryRead`: on `newPerfFixture`, for each target plan 1's `perfWalkTargets(fx)` gives (every screen in `perfInventory` with its defaults expanded exactly as the walk expands them, `skip` records excluded; Astra round 4, finding 6): `resetForColdView`, `ResetKeys`, `getAssembled`, `waitBackground`. Every `GetObject` key and `ListObjectsV2` prefix the fake saw is held by some entry's read set, or is on a short allowlist of reads the cache does not hold: the account-manifest check, the change index, and reads that plan 1's warm walk already allows by a `calls` record.
- The coverage check inside `TestClaimConsoleMutationInvariant`. The suite builds its door consoles with `newClaimCaseWith(t, func(c *Config) { c.Track = NewStoreTracker() })`; `newClaimCaseWith`, seeing `Track` set after the options run, calls `dir.SetObserver(cfg.Track.Observe)` on the claim world's `DirStore` (`claim_invariant_world_test.go:464`). Every other `newClaimCase` user stays untracked and reads inline, unchanged. In each door's `setup`, outside every measured window, `runClaimDoor` assembles every app tab, settings section and account page of the door's account and app, then calls `waitBackground` and `snapshot`. After each run, it calls `waitBackground` and `snapshot` and runs `assertWriteCoverage` with that run's written keys from the suite's own raw-store recorder (`claimRawStore`'s events: an oracle the tracker does not feed). For a foreign run (`check(…, false)`), which writes nothing, no generation may move.
- [ ] **Step 2: Run** `go test ./internal/release/ -run 'TestStoreObserver' -count=1`, `go test ./internal/console/ -run 'TestReadRecordedBefore|TestUntrackedServer|TestShipRefreshes|TestInstanceCreateRefreshes|TestScenarioActivation|TestRefusedWrites|TestReadSetsCoverEveryRead' -count=1 -race`, `go test ./cmd/console/ -run TestProductionStoreIsObserved -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.** Some of these tests need screens converted later (Logs in Task 12, Architecture in Task 15). Write them now with `t.Skip("cached in Task N")` and remove the skip in that task. Every other case runs here, with the probe part standing in for a cached screen.
- [ ] **Step 4: Run** Step 2's commands, the gate-order tests `go test ./internal/console/ -run 'NonMember|CSRF|StepUp|FreshAuth|TestEveryCLIDoorNamesItsRoles|TestAuthCLIFamily|TestPromoteFlow|TestRollbackFlow' -count=1`, and `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`. The claim run's background reads happen in setup, outside measured windows. A door's own re-reads are reads inside its window. If the suite's recorder treats them as anything but the door's reads, record them as the door's reads; never silence the check. Expected: PASS.
-- [ ] **Step 5: Prove the check bites.** Make one loader read a key without recording it (a raw `s.cfg.Releases` call through a context with no read set). `TestReadSetsCoverEveryRead` must name that key, and the matching warm-before-write case must fail. Restore, then commit with message `console: writes invalidate what they touched, by read set; the writing request re-reads it before answering`, ending with the Co-Authored-By line.
+- [ ] **Step 5: Prove the check bites.** Make one loader read a key without recording it (an `env.Store` call on `context.Background()` instead of `env.Ctx`, with the AST rule against it temporarily disabled). `TestReadSetsCoverEveryRead` must name that key, and the matching warm-before-write case must fail. Restore, then commit with message `console: writes invalidate what they touched, by read set; the writing request re-reads it before answering`, ending with the Co-Authored-By line.
### Task 9: App core through the cache: every app tab's shared reads
@@ -399,7 +408,7 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential,
- `func storeCore(ctx context.Context, s release.Store, pub ed25519.PublicKey, acct string) func(app string) (appCore, error)`: `loadAppCore` with no cache, for callers that are not screens and for `view_test.go`'s existing `Assemble` calls (which pass `time.Now()` as `now`).
- `func (s *Server) appCoreView(ctx context.Context, p *page, mode viewMode, sqid, app string) (appCore, error)`: `viewGet` with key `{sqid, app, partCore}`, `writtenWindow`.
- `appPage` keeps the gates and chrome and no longer assembles. `func (s *Server) fillAppDetail(r *http.Request, p *page, acct *Account, mode viewMode) error` sets `p.Detail` (`Assemble` with `appCoreView`), the account review and `applyPipelineView` (from the core, no read). Every tab's `Fill` calls it first; anything that reads `p.Detail` (the nav plan's `liveNowTargets`, `assembleDeploymentTargets`, the ladder, `hasPublishedChannel`) runs after it.
- - parts `overview`, `activity`, `account-review` in `appParts`; the Overview's extra reads through `viewGet`: page 1 of the version list (`{sqid, app, versionsPart(1)}`, `writtenWindow`, a `versionPage{Views []VersionView; More bool}` with `viewClone`, loaded by `VersionsPage(ctx, …, 1)`; the same entry as Releases' first page), `appResourceMetrics` (`{"", "", partMetrics}`, `liveWindow`, loader `LoadMetrics`, filtered per app after, on the copy), `loadBoxJoin` (`{"", "", partBoxes}`, `liveWindow`, the `boxSnapshot` from Task 5). SQLite reads (events, pending changes) stay direct.
+ - parts `overview`, `activity`, `account-review` in `appParts`; the Overview's extra reads through `viewGet`: page 1 of the version list (`{sqid, app, versionsPart(1)}`, `writtenWindow`, a `versionPage{Views []VersionView; More bool}` with `viewClone`, loaded by `VersionsPage(ctx, …, 1)`; the same entry as Releases' first page), `appResourceMetrics` through the one metrics entry, `{"", "", partMetrics}`, defined here for every consumer: loader `loadMetricsFacts` (the uncached sweep `LoadMetrics` runs on a miss, `metricsview.go:257-410`; never `LoadMetrics` itself, whose inner-cache hit would read nothing and record nothing), result `metricsFacts` (the raw hourly samples and alert records per box), window `metricsWindow = 60 * time.Second` (the inner cache's own freshness, so S3 use does not rise). Per request, the app's rows (filtered to the app's own hosts by the account check at `server.go:3509-3531`), the staleness verdicts and the sparklines are built from the facts with `s.now()`. Task 15's operator metrics read the same entry, loader, type and window. *(Astra round 4, finding 3.)* `loadBoxJoin` (`{"", "", partBoxes}`, `liveWindow`, loader `loadBoxSnapshot` returning the `boxSnapshot` from Task 5; staleness and the join are computed per request). `loadAppCore` becomes the loader `loadAppCore(env viewLoadEnv, key viewKey, _ struct{}) (appCore, error)`; `VersionsPage` is wrapped as `loadVersionPage(env, key, page int)`. SQLite reads (events, pending changes) stay direct.
- [ ] **Step 1: Write the failing tests:**
- `TestOverviewWarmMakesNoRemoteCalls`: `getAssembled` `/apps/kass` and quiesce; reset counts; GET: zero S3 and zero host calls, 200, shows `v1` on `stable`.
@@ -503,7 +512,7 @@ Spec §2.4 C rows `settingsGates` (cache), `aliasReadings`/`LoadBoxes` (cache, o
- Test: `internal/console/viewscreens_test.go` (extend)
**Interfaces:**
-- Produces: parts `settings` (its `Gate` reads `?section=` and refuses one not in `appSettingsSections`, as the page refuses the path) and `domain-readings` (the box readings on Domains alone, deferred on a miss of `partBoxes` while the rest of Domains renders). Reads through `viewGet`, keyed `{sqid, app, …}` with `writtenWindow` unless marked live: `settingsGates`' records (`partGates`), the claims listing (`partClaims`; `ClaimCache` stays underneath), `warmRecords` (`partCertWarm`, live), catch-all views including their DNS TXT lookup (`partCatchall`), `appDeployEmpty` (`partDeployEmpty`), `envCards` (`partEnvs`: the config bundles and store records only; the route-derived host list each card shows is joined per request from `p.Detail.Routes`, rule (a)), `storeCard` and `storeEnvCards` (`partStore`), `mailCard` (`partMail`), `featuresCard` (`partFeatures`), `telemetry.Resolve` on `errors-analytics` (Task 12's key), `loadSwapPolicy` (`partSwap`); `aliasReadings` reads the shared `partBoxes` entry. Placement is local and stays direct. The pipeline section reads the core's pipeline (Task 9).
+- Produces: parts `settings` (its `Gate` reads `?section=` and refuses one not in `appSettingsSections`, as the page refuses the path) and `domain-readings` (the box readings on Domains alone, deferred on a miss of `partBoxes` while the rest of Domains renders). Reads through `viewGet`, keyed `{sqid, app, …}` with `writtenWindow` unless marked live: `settingsGates`' records (`partGates`; the plan limits shown beside them, `EffectiveLimits`, are SQLite and joined per request), the claims listing (`partClaims`; `ClaimCache` stays underneath), `warmRecords` (`partCertWarm`, live), catch-all facts, not views (Astra round 4, finding 4): the release manifest each catch-all claim derives from (`{sqid, app, partCatchall}`, `writtenWindow`, loader `loadCatchallManifests`), and each proof TXT answer (`{"", "", "dns:" + name}`, `liveWindow`, loader `loadCatchallTXT` through `env.LookupTXT`: DNS is outside the object store, so its entry has no read set and is refreshed by its window alone, which is the same freshness the live check has today). The catch-all rows (`domaincatchall.go:279-320`) are built per request from those facts, the current `partBoxes` readings, the certificate records and `s.now()`, `appDeployEmpty` (`partDeployEmpty`), `envCards` (`partEnvs`: the config bundles and store records only; the route-derived host list each card shows is joined per request from `p.Detail.Routes`, rule (a)), `storeCard` and `storeEnvCards` (`partStore`), `mailCard` (`partMail`), `featuresCard` (`partFeatures`), `telemetry.Resolve` on `errors-analytics` (Task 12's key), `loadSwapPolicy` (`partSwap`); `aliasReadings` reads the shared `partBoxes` entry. Placement is local and stays direct. The pipeline section reads the core's pipeline (Task 9).
- [ ] **Step 1: Write the failing tests:**
- `TestEverySettingsSectionWarmMakesNoCalls` (one sub-test per key of `appSettingsSections`, with the populated seeds).
@@ -524,18 +533,19 @@ Spec §2.4 C rows `settingsGates` (cache), `aliasReadings`/`LoadBoxes` (cache, o
- Test: `internal/console/viewscreens_test.go` (extend)
**Interfaces:**
-- Produces: parts in `accountParts`: `apps` (the account home's app list; each app's channels through Task 9's per-app `partCore` entries, so the home page and the app tabs share them), `settings` (its `Fill` keeps the owner-only panes behind the role check the page uses), `fleet`, `fleets` (its `Gate` reads `?fleet=` and runs `resolveOwnedFleet` as the page does), `trash` (the delete form for owners only, as the page), `new-app`. Reads through `viewGet`: `fleet.json` (`{"", "", partFleetJSON}`, `liveWindow`), each owned fleet's boxes (Task 11's key), the store entitlement (`{sqid, "", partEntitlement}`, `writtenWindow`), the account telemetry (`{sqid, "", partAccountTelemetry}`, `writtenWindow`), tombstones, one entry per trashed app (`{sqid, "", trashPart(app)}`, `writtenWindow`; the list of trashed apps is SQLite, read per request, rule (b)), the region picker's edges snapshot and boxes (the shared `partEdges` and `partBoxes`). Minting a first account (`server.go:2382`) is a write, unchanged.
+- Produces: parts in `accountParts`: `apps` (the account home's app list; each app's channels through Task 9's per-app `partCore` entries, so the home page and the app tabs share them), `settings` (its `Fill` keeps the owner-only panes behind the role check the page uses), `fleet`, `fleets` (its `Gate` reads `?fleet=` and runs `resolveOwnedFleet` as the page does), `trash` (the delete form for owners only, as the page), `new-app`. Reads through `viewGet`: `fleet.json` (`{"", "", partFleetJSON}`, `liveWindow`), each owned fleet's boxes (Task 11's key), the store entitlement (`{sqid, "", partEntitlement}`, `writtenWindow`), the account telemetry (`{sqid, "", partAccountTelemetry}`, `writtenWindow`), tombstones, one entry per trashed app (`{sqid, "", trashPart(app)}`, `writtenWindow`, loader `loadTombstone`; the list of trashed apps is SQLite, read per request, rule (b); a delete's tombstone write primes the new app's entry through Task 8's one primer, so the redirect's Trash view makes no read), the region picker's edges snapshot and boxes (the shared `partEdges` and `partBoxes`). Minting a first account (`server.go:2382`) is a write, unchanged.
- `app_new.html`'s region and timezone initializer (today an inline script in the body using `document.currentScript`, `templates/app_new.html:22`) moves into the frame. It runs once on `DOMContentLoaded` and again on `carlos:part` for the `new-app` part, and finds the hidden timezone input and the automatic-region label by id inside the root it is given. The fragment carries no script. *(Astra round 3, finding 5.)*
- [ ] **Step 1: Write the failing tests:**
- `TestAccountPagesWarmMakeNoRemoteCalls` (one sub-test each for `/a/{sqid}/`, `/settings`, `/fleet`, `/fleets/fleet-a`, `/trash`, `/apps/new`).
- `TestAccountHomeSharesAppCoreWithAppTabs`: `getAssembled` `/apps/kass` and quiesce; the account home then makes zero channel reads for `kass`.
- `TestNewAppAppearsOnHomeAfterCreate`: create `shop`; the redirect target lists it.
+ - `TestTombstonePrimerReadsThroughTheStore`: the primed entry's read set holds the tombstone key and the S3 fake saw its `GetObject` inside the delete request.
- `TestDeletedAppShowsInTrash`: warm `/trash`; delete `kass` through its settings door (with its confirmation); `getAssembled` `/trash` lists `kass` with zero S3 calls.
- `TestNewAppInitializerSurvivesAColdLoad`: on `newPerfFixture` with `CONSOLE_APP_REGIONS` on, a cold `/apps/new`: the frame holds the initializer (it listens for `carlos:part` and `DOMContentLoaded`, and does not use `document.currentScript`). The part's fragment has no `<script`. The assembled page holds every id the initializer looks up. When `chromium` is on `PATH` (skipped otherwise, as the nav plan's snapshots are), a headless load of the cold page served by the test server ends with the hidden timezone input non-empty.
- `TestStoreDecisionShowsOnTheAccount`: the account's settings warm (its entitlement entry); the operator approves its storage application; the warm-before-write check (Task 8) passes and the account's next settings view shows the approval with zero S3 calls.
- `TestAccountPartsKeepOwnerOnlyContent`: a plain member's assembled `/settings` and `/trash` have no owner-only form, exactly as the pages today.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAccountPagesWarm|TestAccountHomeShares|TestNewAppAppears|TestDeletedAppShowsInTrash|TestNewAppInitializerSurvives|TestStoreDecisionShowsOnTheAccount|TestAccountPartsKeepOwnerOnly' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAccountPagesWarm|TestAccountHomeShares|TestNewAppAppears|TestTombstonePrimer|TestDeletedAppShowsInTrash|TestNewAppInitializerSurvives|TestStoreDecisionShowsOnTheAccount|TestAccountPartsKeepOwnerOnly' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.** Existing tests run unchanged on the untracked fixture; run the nav plan's `TestPageHeadsOnAccountPages` and `TestTrashDeleteSitsInItsRow` on `newPerfFixture` too. Update claim probes whose markers moved; repoint Task 7's account-part probe at `apps`.
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestEmptyStateWelcomesNewUser|TestCreateApp|TestAccountSettings|TestAccountFleet|TestFleetPage|TestTrash|TestRegionPicker|TestPageHeads|TestClaimRead' -count=1`, and the walk with `CI=1`.
- [ ] **Step 5: Delete** the account pages' `over:` records; walk (PASS); commit, message `console: account pages read through the view cache`, ending with the Co-Authored-By line.
@@ -552,14 +562,14 @@ Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the sha
**Interfaces:**
- Produces, the exact signatures Part 3's plan names (`(ctx context.Context, p *page, mode viewMode) (T, error)`), with `T` the type Part 3's seam returns so its Task 13 is a one-line swap:
- - `func (s *Server) fleetJSONView(ctx context.Context, p *page, mode viewMode) (*status.Fleet, error)` (`{"", "", partFleetJSON}`, `liveWindow`; the read `opFleetJSON` makes, `FleetView`)
+ - `func (s *Server) fleetJSONView(ctx context.Context, p *page, mode viewMode) (*status.Fleet, error)` (`{"", "", partFleetJSON}`, `liveWindow`; loader `loadFleetJSON`; the read `opFleetJSON` makes, `FleetView`)
- `func (s *Server) hostRowsView(ctx context.Context, p *page, mode viewMode) ([]HostRow, error)` (rows built per request from the shared `partBoxes` `boxSnapshot`, as `HostRows` builds them; what `opHostRows` returns)
- - `func (s *Server) storePendingView(ctx context.Context, p *page, mode viewMode) (storePendingList, error)` (`partStorePending`; `storePendingList` is the slice `pendingStoreApplications` returns, with `viewClone`; `opStorePending` takes its length and keeps its own store-operator and no-bucket checks)
- - `func (s *Server) metricsView(ctx context.Context, p *page, mode viewMode) (metricsResult, error)` (`partMetrics`; `metricsResult` holds what `LoadMetrics` returns)
- - `func (s *Server) economicsView(ctx context.Context, p *page, mode viewMode, period string) (*EconomicsView, error)` (`economicsPart(period)`)
- - Both loaders call the sweep their inner cache runs on a miss (`LoadMetrics`' and `LoadEconomics`' uncached sweep, `metricsview.go:257-410`, `economicsview.go:283-300`), never the inner caches. Their read sets are then complete, and Task 8's invalidation reaches them directly: a scenario save invalidates every entry that read the scenario keys, Architecture's rate card included. This also makes round 2's `invalidateEconomics` unnecessary. Their window is `operatorWindow = 60 * time.Second`, the inner caches' own freshness, so S3 use does not rise. The inner caches stay for the callers that use them today (the CLI's economics door, `OwnerAppMetrics` outside views).
- - `func (s *Server) storeUsageView(ctx context.Context, p *page, mode viewMode) (storeUsage, error)` (`partStoreUsage`; what `storeBucketCount` returns)
- - `func (s *Server) architectureView(ctx context.Context, p *page, mode viewMode) (architectureData, error)` (`partArchitecture`, `writtenWindow`; the inventory, `fleet.json` and scenario `handleArchitecture` reads, boxes from `partBoxes`)
+ - `func (s *Server) storePendingView(ctx context.Context, p *page, mode viewMode) (storePendingList, error)` (`partStorePending`; loader `loadStorePending` (object-store reads only; the per-account SQLite lookup is joined per request); `storePendingList` is the slice `pendingStoreApplications` returns, with `viewClone`; `opStorePending` takes its length and keeps its own store-operator and no-bucket checks)
+ - `func (s *Server) metricsView(ctx context.Context, p *page, mode viewMode) (metricsResult, error)`: Task 9's `partMetrics` entry, loader `loadMetricsFacts`, `metricsWindow`, unchanged; `metricsResult` (what `LoadMetrics` returns today) is built per request from `metricsFacts` and `s.now()`.
+ - `func (s *Server) economicsView(ctx context.Context, p *page, mode viewMode, period string) (*EconomicsView, error)`: the period's dates are computed per request from `s.now()`. The remote facts are cached: one entry per day of usage (`{"", "", economicsPart(day)}`, loader `loadEconomicsDay`: the day's metrics, edge and storage objects that `sweepUsage` and `foldStorageAndCensus` read, `economicspass.go:318`, `:486`; `liveWindow` for today, `writtenWindow` for earlier days), the active scenario and scenario names (`economics-scenarios`, `writtenWindow`), the recent bills (`economics-bills`, `writtenWindow`) and the fleet meter objects (`economics-fleet-meters`, `liveWindow`). Then `buildEconomicsView` (`economicsview.go:401`) runs per request over those facts. The account names and tiers (`Accounts`, `AccountTiers`, SQLite), the registry attribution (`loadRoutesForEconomics`, `:729`, and `ListFleets`/`ListFleetBoxes`) and the period arithmetic are read and computed per request, never cached. *(Astra round 4, finding 2.)*
+ - Both screens use their loaders, never `LoadMetrics`' or `LoadEconomics`' inner caches, whose hits record no reads. The inner caches stay for the callers that use them today (the CLI's economics door, `OwnerAppMetrics` outside views).
+ - `func (s *Server) storeUsageView(ctx context.Context, p *page, mode viewMode) (storeUsage, error)` (`partStoreUsage`; loader `loadStoreUsage`; what `storeBucketCount` returns)
+ - `func (s *Server) architectureView(ctx context.Context, p *page, mode viewMode) (architectureData, error)`: cached facts are the inventory object and the active scenario (`partArchitecture`, `writtenWindow`, loader `loadArchitectureFacts`), `fleet.json` (`partFleetJSON`) and the boxes (`partBoxes`); the registry route list and the rate card's arithmetic are joined per request.
- A loader assumes its caller already ran the page's full gate: `operatorOnly` for all of them, and `storePageOperator` (`storepage.go:119`, `operatorOnly` plus `storeOperator`'s check of `Config.StoreOperators`, `apistore.go:645`) for the two store loaders. Each loader's doc comment names the gate. Part 3, if it adds deferred parts for these pages, gives each part its page's gate (Task 7's `viewPart.Gate` rule); this task adds no operator part route.
- Writes from operator doors (store decision, economics saves, architecture refresh) invalidate these entries by read set (Task 8); this task's tests check the redirect targets.
- In `viewBlocking` mode a stale entry is served at once with a background refresh, and only a miss waits, so an operator page is warm-fast now and pays one read on its first view per window, as today. The placeholder for that first view is Part 3's, with its templates.
@@ -570,7 +580,8 @@ Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the sha
- `TestStoreDecisionShowsOnRedirect`: warm `/fleet/store` and the applicant account's settings; approve; both redirect targets show the decision with zero S3 calls.
- `TestEconomicsSaveShowsOnRedirect`: warm `/fleet/economics` (and, with it, `LoadEconomics`' inner cache through the CLI economics door); save a changed active scenario; follow the redirect: the page shows the new scenario. Again with the view's sweep held in flight (`HoldNext("list", …)` on one of its listings) when the save lands: after release, the page still shows the new scenario.
- Remove `TestScenarioActivationRefreshesArchitecture`'s skip (Task 8).
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestStoreQueueRefused|TestStoreDecisionShows|TestEconomicsSaveShows|TestScenarioActivationRefreshesArchitecture' -count=1`. Expected: FAIL.
+ - `TestTierSaveShowsOnRedirect`: warm `/fleet/economics/accounts` (and `/fleet/economics`); save a new tier for an account through `/fleet/economics/tier`; follow the redirect: the account's tier and its revenue line are the new ones. The tier is SQLite, joined per request, so no invalidation is involved, and the test pins that.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestStoreQueueRefused|TestStoreDecisionShows|TestEconomicsSaveShows|TestScenarioActivationRefreshesArchitecture|TestTierSaveShowsOnRedirect|TestViewLoadersAreRestricted' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestFleet|TestStoreApprovals|TestEconomics|TestArchitecture|TestArchPage|TestClaimRead' -count=1`, and the walk with `CI=1`.
- [ ] **Step 5: Keep every operator screen's `over:` record**, in both cases. In `viewBlocking` mode each of them still waits for its remote reads on the walk's cold request (plan 1 Task 10), and only Part 3's Task 13, which adds their placeholders, makes the cold request fast. Each record's reason becomes "blocks on a cold view until operator-pages Task 13"; that task deletes them. Walk (PASS: warm views have zero remote calls and are fast; the recorded screens are exempt from the cold check). Commit, message `console: cache-backed loaders for the operator pages, for Part 3`, ending with the Co-Authored-By line. *(Astra round 3, finding 2.)*
@@ -612,6 +623,7 @@ Spec §2.4 C last row: `SetMaxOpenConns(1)` (`store.go:99`, `store_gate.go:1828`
- **Spec coverage.** §2.4 C, row by row: account manifest (Task 2, now off the response path), `SetLastAccount` (Task 2), `AccountsFor` and `registry.List` once (Task 2), `assembleChannels` (Task 9), `dnsTargets` fold (Task 3), Overview `Versions` bounded and cached (Tasks 3, 9), pipeline once (Task 3), `instances.Report` (Task 11), `populateAppSettings` (Task 4), `appDeployEmpty` (Task 4), `settingsGates` (Task 13), `aliasReadings` (Task 13), `envCards` + `storeEnvCards` (Task 4), console DB (Task 16). Concurrency as a fallback: part endpoints start every missing load before waiting (Task 7). §2.4 A: serve cached, background refresh single flight (Task 6), miss renders a placeholder (Tasks 7, 9 to 14), read your own writes declared at the mutation, generations covering in-flight loads, re-read in the request, invalidated on failure (Tasks 6, 8; end to end in Tasks 10, 13, 14, 15), refresh only on view (Global Constraints, Task 6), windows (Task 6), "as of" (Tasks 6, 7). §2.4 B: fetch parts following the Logs pattern, HTML fragments from the same templates, no framework, usable without JavaScript, gated like their page (Task 7; Logs through its own data endpoint in Task 12). §2.5 step 3 order: C (Tasks 2 to 5), then A and B (Tasks 6 to 15). §2.6: Task 17. Every task that makes a screen fast deletes its `over:` records; Task 17 ends with none and with a lower whole-session S3 total.
- **Review round 1 (Astra, at `e9f42e19`), findings that applied here:** 1 parts run their page's own gate, no operator part routes, refused store operator tested (Tasks 7, 15); 2 effects declared per door with cross-scope rules (Task 8; Tasks 14, 15 tests); 3 generations cover first loads and refreshes in flight (Task 6); 4 marking at the mutation after admission and success, refusals tested (Task 8); 5 immutable values with `viewClone` and a concurrent `-race` render test (Tasks 6, 9); 6 the production flag cached, the route-dependent view derived per request (Task 9); 7 claim route, fixture and probe entries (Task 7); 8 `HoldNext` keeps the read's result and holds one read only (Tasks 2, 10); 10 page and `/logs/data` share the first window (Task 12); 11 the manifest check off the response path, tested with a held read (Task 2); 12 written against the nav plan's code, test conversion owned here, Live now survives a failed listing (Branch notes, Tasks 9, 10); 13 `boxSnapshot` keeps completeness (Task 5); 14 whole-session S3 ceiling (Task 17, with plan 1 Task 10).
+- **Astra round 4 (`CODEX-FINDINGS-CONSOLE-PLANS-R4.md`):** rule (a) made structural, `viewLoadEnv` and `TestViewLoadersAreRestricted` (Task 6); 1 published and in-flight read sets, published replaced only on success (Task 6); 2 economics caches per-day usage, scenario, bill and fleet-meter facts, with tiers, accounts, registry and period derived per request, plus a tier-save witness (Task 15); 3 one metrics entry, loader, type and window (Task 9, consumed by Task 15); 4 catch-all caches manifest and TXT facts, rows per request (Task 13); 5 a tombstone primer (Tasks 8, 14); 6 the coverage oracle walks `perfWalkTargets` (Task 8).
- **Astra round 3 (`CODEX-FINDINGS-CONSOLE-PLANS-R3.md`):** the class behind R1-2, R2-4 and R3-3 is fixed by invalidating by read set (Task 8), checked by the coverage oracle in `TestClaimConsoleMutationInvariant` and the warm-before-write cases (deploy-empty on ship, record hosts and environments on instance create, Architecture on scenario activation); the scripts class (R2-3, R3-5) by the no-script-in-fragments rule, the `carlos:part` event and `app_new.html`'s initializer (Tasks 7, 14); 2 operator records kept until operator-pages Task 13 in both orders (Task 15); 4 the host picker is its own part (Task 12); 6 untracked fixtures read inline, so plan 1's instrumentation tests keep their meaning, and background attribution is asserted (Tasks 8, 9, 11); 9 `bgWork` and `waitBackground` cover every request-triggered worker (Task 6); R2-6 `Assemble` takes `now` (Task 9).
- **Astra round 2 (`CODEX-FINDINGS-CONSOLE-PLANS-R2.md`):** 1 the pager kept, one cache entry and fragment per page (Tasks 8, 10); 4 economics saves empty and generation-guard `LoadEconomics`' inner cache before re-reading (Tasks 8, 15); 5 filter keys are a hash of the whole effective filter (Task 12); 6 only clock-independent facts are cached and bake state is derived per request from `s.now()` (Tasks 6, 9); 7 the cold pass reset is `resetForColdView` (Task 6; plan 1 Task 10 runs it); 8 is plan 1's; 12a the cold Versions test warms the core through Activity (Task 10); R1 #14 counts come from the S3 fake at the transport (plan 1 Task 9), so `Keys`, `SetFail` and `HoldNext` act on real requests and `HoldNext` can hold a listing (Task 2).
- **Round 2 (session lead):** the success-path gap is closed by the witness in `TestClaimConsoleMutationInvariant` (Task 8); Task 15's loaders carry the signatures and seams `2026-10-25-operator-pages.md` names (its Task 8 seams, its Task 13 after this plan).
diff --git a/docs/superpowers/plans/2026-10-25-operator-pages.md b/docs/superpowers/plans/2026-10-25-operator-pages.md
index 7cc95f30c..5d0d3c701 100644
--- a/docs/superpowers/plans/2026-10-25-operator-pages.md
+++ b/docs/superpowers/plans/2026-10-25-operator-pages.md
@@ -15,7 +15,7 @@
- Plan 2, `2026-10-25-console-perf-2-fixes.md`: Task 7's `viewMode` (`viewCached`, `viewBlocking`), `errViewPending`, `viewGet`, `viewPart{Gate, Fill, Template}`, `renderView`, the `deferred`, `asof`, `partfailed` and `partloader` partials, `getAssembled`, `s.bg.Go` and the test-only `waitBackground` (Tasks 2 and 6); Task 8's invalidation by read set (every cache entry records the keys and prefixes its load read; an acknowledged object-store write invalidates every entry that covers its key and the writing request re-reads them before it answers), which needs no per-door declaration from this plan; Task 15's loaders `fleetJSONView`, `hostRowsView`, `metricsView`, `economicsView(ctx, p, mode, period)`, `storePendingView`, `storeUsageView`, `architectureView`, each `(ctx context.Context, p *page, mode viewMode) (T, error)`. **Only this plan's Task 13 depends on plan 2**, and it runs once plan 2 Task 15 is on `main`. Plan 2 Task 15 says it wires its loaders into "Part 3's handlers if Part 3 has landed": here that means into this plan's seam functions (`opFleetJSON`, `opHostRows`, `opStorePending`, Task 8), not into templates. Plan 2 adds no operator part route and no operator template; this plan's Task 13 adds both. Plan 2 Task 15 is therefore not superseded: it must precede Task 13, and Task 13 consumes its loaders.
- The nav plan, `2026-10-25-console-ux-nav.md`, keeps `fleet.html`, `store_approvals.html`, `metrics.html`, `economics.html`, `economics_accounts.html`, `architecture.html` and `fleetdetail.html` byte-identical. This plan rewrites the first six and does not touch `fleetdetail.html` or `layout.html`. No conflict.
-**Branch:** `operator-pages`, cut from amadan `main` after plan 1 has merged. Tasks 1 to 12 and 14 run alongside plan 2 and Part 1. If plan 2 Task 15 is not on `main` when Tasks 1 to 12 are done, those land as one merge with `over:` records for the operator screens that still read S3, and Task 13 follows on a second branch `operator-pages-cache` cut after plan 2 merges. *(My call.)*
+**Branch:** `operator-pages`, cut from amadan `main` after plan 1 has merged. Tasks 1 to 12 and 14 run alongside plan 2 and Part 1. If plan 2 Task 15 is not on `main` when Tasks 1 to 12 are done, those land as one merge with `over:` records for the operator screens that still read S3, and Task 13 follows on a second branch `operator-pages-cache` cut after plan 2 merges. *(My call.)* Each landing branch has its own census proposal: `NAME=operator-pages` for the first (overlay `testdata/plan14-root-reads-operator-pages.tsv`, card `docs/superpowers/notes/census-proposal-operator-pages.md`, rows `rev3=census-ruling-operator-pages`), and `NAME=operator-pages-cache` for the second (its own overlay, card and `rev3=census-ruling-operator-pages-cache`, appended after whatever plan 2 added, never replacing the first). Each gets its own approval on #280. When everything lands as one branch, only `operator-pages` exists.
## Global Constraints
@@ -25,6 +25,15 @@ Every task's requirements include this section.
- **House voice.** No em dashes in a new or changed string: a full stop and a new sentence, continuing in lower case. Human text only: log lines, diagnostics, route patterns, rule and job identifiers, JSON keys and data values (box labels, load words from `fleet.json`) are not copy. Strings that move unchanged from today's operator templates are not rows and are carried verbatim (count each one at the base commit with `git grep -n` before touching it).
- **No tenant names** in code, tests, fixtures or copy. Neutral names only: `shop`, `notes`, `example.com`, `fleet-a`, `box-1`. The existing fixtures (`kass`, `ops`/`bab`, `paul@keymail.dev`, the `ada-stargazing` and `grace-kayaking` box labels) may be reused, never newly introduced. The brand in copy is `<brand>` (`page.Brand`), never a literal product name.
- **The budget.** Every operator GET answers within 150 ms with at most one S3 read on a warm cache. No new polling, no timers. The dashboard's remote reads are `status/fleet.json`, the per-box snapshots behind `HostRows`, and, for a store operator, the storage queue, all through plan 2's view cache from Task 13 on: refreshed only when someone views, single flight, never on the request path of a warm view. The per-box cost is stated in Task 13 (one `List` of `status/boxes/` plus one `Get` per box, at most once per 60 s window, only when an operator views the dashboard or Boxes, which share the entry). S3 requests must not go up. Every new screen is in plan 1's walk (`TestConsoleScreensMeetTheBudget`); a screen that still reads S3 before Task 13 carries an `over:` record naming Task 13, and Task 13 deletes it.
+- **Cached loaders see the object store only.** Every cached load is a plan 2 `viewLoader[A, T] func(env viewLoadEnv, key viewKey, arg A) (T, error)`: a package-level function in `internal/console/viewloaders.go`, passed to `viewGet` by name. No cached loader in this plan is a closure or a method value (`TestViewLoadersAreRestricted` refuses one), and this plan defines none of its own: all seven operator reads use plan 2 Task 15's loaders and views, and their per-request builders. What each caches (raw object-store facts) and what is derived per request:
+ - `fleet.json`: `loadFleetJSON` (`{"", "", partFleetJSON}`, the parsed `*status.Fleet`), behind `fleetJSONView`; box status words, the summary-age test and attention items are per request (`s.now()`).
+ - box snapshots: `loadBoxSnapshot` (`partBoxes`, the raw `boxSnapshot`), behind `hostRowsView`, which builds `HostRow`s per request; the dashboard's box rows, staleness, `Dark` and the memory meter are per request.
+ - storage queue: `loadStorePending` (`partStorePending`, the entitlement objects listed and read under `store/entitlements/`), behind `storePendingView`; the account-existence filter `pendingStoreApplications` applies today (`AccountBySqid`, `apistore_entitlement.go:235`) and the count are per request.
+ - store usage: `loadStoreUsage` (`partStoreUsage`, the sweep record `storeBucketCount` reads), behind `storeUsageView`.
+ - metrics: plan 2's one `partMetrics` entry, `loadMetricsFacts` returning `metricsFacts` (60 s), behind `metricsView`, which builds what `LoadMetrics` returns per request from `metricsFacts` and `s.now()`. This plan reads only `metricsView` and defines no metrics type.
+ - economics: plan 2's per-day `loadEconomicsDay` entries and its scenario, bill and fleet-meter entries, behind `economicsView(ctx, p, mode, period)`, which runs `buildEconomicsView` per request with account names, tiers, registry attribution and the period's dates from SQLite, the registry and `s.now()`. This plan defines no economics loader or builder.
+ - architecture: `loadArchitectureFacts` (`partArchitecture`) plus the `fleet.json` and box entries above, behind `architectureView`; the route list and rate-card arithmetic are per request.
+ - `loadFleetJSON`, `loadStorePending` and `loadStoreUsage` are the names this plan expects for the three loaders plan 2 Task 15 describes without naming yet; they are plan 2's to define, in `viewloaders.go`, with this signature. If plan 2 lands them under other names, Task 13 uses those and this list is the bug. Task 13 adds `TestOperatorPagesJoinLocalStatePerRequest` for the joins it can see.
- **What the view cache holds (plan 2's two rules).** Only object-store loads go through it, and only these: `fleet.json`, the box snapshots behind `HostRows`, the storage queue, metrics, economics, store usage and architecture (plan 2 Task 15's loaders). (a) A cached value holds only object-store facts; SQLite rows, registry routes and the clock are joined per request: the dashboard's counts, series, newest people and latest activity, People and accounts, Activity, the job registry and the alert projection are read per request (indexed SQLite or in-process memory), never cached, and the box status words, the "is the summary old" test and the storage count are computed per request from the cached facts. (b) A load whose key set comes from local state caches one entry per key; no operator load here does (each key set comes from a bucket listing). No deferred fragment contains a `<script>`; page behaviour initializes on load and on `carlos:part`. Background work a request starts goes through `s.bg.Go`; this plan starts none of its own.
- **Gates unchanged.** The claim SQL gate changes in one place only, Task 6A's `audit` classification, and only after its own review. `operatorOnly` (`server.go:3082`) is the first call of every operator page handler; `storePageOperator` (`storepage.go:119`) stays the gate of `/fleet/store`; `handleEconomicsAccounts`' own copy of the gate stays as it is. Every refusal is the byte-identical missing-route 404. The console's security gate order (session, CSRF, owner, `requireFreshAuth`) is unchanged. No new POST door.
- **Production wiring.** Console tests build the server with `NewServer` through `newConsoleFixture`/`newConsoleFixtureWith` (the constructor `cmd/console` calls, `cmd/console/main.go:520`) and sign in through `signInPaul`. Store tests open the database with `Open` (the flag-off constructor `openConsoleDB` uses) and, for the claim gate, `newClaimCase` (the `OpenGated` path). A pure unit test says "not acceptance" in its doc comment.
@@ -122,7 +131,7 @@ Each is marked *(my call)* where it appears in a task.
- Create: `docs/superpowers/plans/LUNA-COPY-BRIEF-OPERATOR-PAGES.md`, `docs/superpowers/plans/LUNA-COPY-REVIEW-OPERATOR-PAGES.md`
**Interfaces:**
-- Produces: rows `OPS-1` to `OPS-147`, all `approved`; `var operatorPagesCopyBuilt = []string{}` in the gate (later tasks append the ids they write). Placeholders are `<name>` in the record, and the gate checks the fixed text between them, as the moves gate does.
+- Produces: rows `OPS-1` to `OPS-148`, all `approved`; `var operatorPagesCopyBuilt = []string{}` in the gate (later tasks append the ids they write). Placeholders are `<name>` in the record, and the gate checks the fixed text between them, as the moves gate does.
The record uses the moves record's format (one table per heading; columns id, file, text, status), and the gate reuses `parseCopyTable`, `checkMovesNoEmDash`, `checkRunBuilt` and `checkRunApplied` exactly as `approved_asset_cache_copy_test.go` does; name the helpers `operatorPagesBuiltRows`, `checkOperatorPagesBuilt`, `mustParseOperatorPagesCopyRecord`, with id pattern `^OPS-[0-9]+$`. A page's `<h1>` uses its rail row (OPS-8 to OPS-15), so h1s are not separate rows.
@@ -230,11 +239,12 @@ Draft rows (Luna may change any text; ids and files are fixed):
| OPS-145 | `templates/architecture.html` | The deployment's parts and how they connect. |
| OPS-146 | `templates/ops_boxes.html` | Memory (the Hosts table's meter column) |
| OPS-147 | same | Last report |
+| OPS-148 | `templates/ops_activity.html` | <account> (deleted) (the Activity filter line's name for a deleted account) |
A row's file is where the gate looks for its text; a later page that shows the same words carries them too, unchecked.
- [ ] **Step 1: Write the record** with the rows above as `pending`, one row per id (expand the grouped rows), a placeholder note (`<n>` a whole number of 2 or more where a singular row exists; `<age>` a `humanAge` value; `<brand>` the console's name), and the house rules section copied from `2026-10-24-edge-asset-cache-copy.md`. Header text: where each string shows (an operator-only console; the rail on every page; the dashboard's sections), that strings moved unchanged are not rows, and that OPS-131 to OPS-136 are stored in audit rows at write time.
-- [ ] **Step 2: Write the gate** `approved_operator_pages_copy_test.go` with `TestOperatorPagesCopyInventory` (every row parses, ids unique, no em dash in any text, 147 rows) and `TestOperatorPagesCopyBuiltRowsAreApprovedAndPresent` (every id in `operatorPagesCopyBuilt` is `approved` and its fixed text is in its file).
+- [ ] **Step 2: Write the gate** `approved_operator_pages_copy_test.go` with `TestOperatorPagesCopyInventory` (every row parses, ids unique, no em dash in any text, 148 rows) and `TestOperatorPagesCopyBuiltRowsAreApprovedAndPresent` (every id in `operatorPagesCopyBuilt` is `approved` and its fixed text is in its file).
- [ ] **Step 3: Run** `go test . -run 'TestOperatorPagesCopy' -count=1`. Expected: PASS (nothing built).
- [ ] **Step 4: Write the brief** `LUNA-COPY-BRIEF-OPERATOR-PAGES.md`: Paul delegated plan copy; read the record, spec §3.2 to §3.5 and the mockup; house rules (no em dashes, full stop and a lower-case continuation; plain words; neutral names; keep every `<placeholder>`; rail and tab labels stay short nouns; status words stay one word; facts unchanged); flag anything not human text. Output: a table `id | current | new | why`, a flags list, one count line. Commit the record, gate and brief so Luna reviews a fixed commit.
- [ ] **Step 5: Run Luna** from a script file under a scratch dir, with the sandbox off (codex writes under `~/.codex`):
@@ -355,11 +365,13 @@ file LICENSE LICENSE 3f3d9e0024b1921b067d6f7f88deb4a60cbe7a78e76c64e3f1d7fc3b779
**Interfaces:**
- Produces:
- - `func (s *Store) migrateOperatorPages() error`: `ALTER TABLE users ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0;` (a "duplicate column" error is swallowed, as the ALTER list does), `CREATE INDEX IF NOT EXISTS audit_by_time ON audit (created_at);`, `CREATE INDEX IF NOT EXISTS audit_by_account ON audit (account_id, id);`.
+ - `func (s *Store) migrateOperatorPages() error`: `ALTER TABLE users ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0;` (a "duplicate column" error is swallowed, as the ALTER list does), `CREATE INDEX IF NOT EXISTS audit_by_time ON audit (created_at);`, `CREATE INDEX IF NOT EXISTS audit_by_account ON audit (account_id, id);`, `CREATE INDEX IF NOT EXISTS sessions_by_time ON sessions (created_at, address);`, `CREATE INDEX IF NOT EXISTS users_by_created ON users (created_at);`, `CREATE INDEX IF NOT EXISTS users_by_last_seen ON users (last_seen);`, `CREATE INDEX IF NOT EXISTS memberships_by_address ON memberships (address, added_at);`, `CREATE INDEX IF NOT EXISTS apps_by_creator ON apps (created_by);`.
+ - `type OperatorAccount struct { ID int64; Sqid, Name string; Deleted bool }`; `func (s *Store) OperatorAccountBySqid(sqid string) (*OperatorAccount, error)`: the account row whatever its `deleted_at` (nil when there is no row). Operator pages only: its doc comment says it must never back a member-facing lookup, which keeps using `AccountBySqid` and its tombstone exclusion (`store.go:1068`).
- `func (s *Store) TouchLastSeen(address string, now time.Time) error`: `UPDATE users SET last_seen = ? WHERE address = ? AND last_seen < ?` (never moves backwards; no row, no insert).
- - `type OperatorCounts struct { People, Active30, Active7, ActiveToday, NewPeople7, NewPeoplePrev7, NewAccounts7, NewAccountsPrev7, Apps, NewApps7, DeploysToday, DeployApps int }`; `func (s *Store) OperatorCounts(now time.Time) (OperatorCounts, error)` with the windows from "Decisions" (active: `last_seen >= cutoff OR EXISTS (SELECT 1 FROM sessions WHERE sessions.address = users.address AND sessions.created_at >= cutoff)`; deploys: `audit.created_at >= <UTC midnight> AND action IN deployActions`, `DeployApps` = distinct `(account_id, app)` among them).
+ - `type OperatorCounts struct { People, Active30, Active7, ActiveToday, NewPeople7, NewPeoplePrev7, NewAccounts7, NewAccountsPrev7, Apps, NewApps7, DeploysToday, DeployApps int }`; `func (s *Store) OperatorCounts(now time.Time) (OperatorCounts, error)` with the windows from "Decisions" (active, set-based, never a correlated subquery: `SELECT COUNT(*) FROM (SELECT address FROM users WHERE last_seen >= ?1 UNION SELECT address FROM sessions WHERE created_at >= ?1)`, served by `users_by_last_seen` and the covering `sessions_by_time`; deploys: `audit.created_at >= <UTC midnight> AND action IN deployActions`, `DeployApps` = distinct `(account_id, app)` among them).
- `var deployActions = []string{"promote", "rollback"}` (check both strings against the `Action:` values in `server.go` and `apicli.go` before writing them).
- `type DayCount struct { Day time.Time; N int }`; `func (s *Store) NewPeoplePerDay(now time.Time, days int) ([]DayCount, error)`: `days` entries, oldest first, the last one today (UTC), zero-filled; rows created after `now` are not counted.
+ - Every statement these methods run is a package-level constant (`opSQLActive`, `opSQLNewPeople`, `opSQLNewAccounts`, `opSQLApps`, `opSQLDeploys`, `opSQLPerDay`, `opSQLNewestPeople`, `opSQLPeoplePage`, `opSQLAccountsPage`, `opSQLFeed…` for each filter shape) so the plan witness below can `EXPLAIN QUERY PLAN` exactly what runs. The per-person columns of `NewestPeople` and `PeoplePage` (accounts, first account, apps) are computed only for the page's rows: the `LIMIT`/`OFFSET` is applied in an inner query over `users`, and the outer query looks each row up through `memberships_by_address` and `apps_by_creator`.
- `type PersonRow struct { Address string; Joined, LastSeen time.Time; Accounts int; FirstAccount string; Apps int }` (`LastSeen` zero when never seen; `FirstAccount` `""` when none); `func (s *Store) NewestPeople(limit int) ([]PersonRow, error)` (newest `created_at` first, ties by address); `func (s *Store) PeoplePage(q string, offset, limit int) ([]PersonRow, int, error)` (filtered by address `LIKE` with `ESCAPE '\'`, `%`, `_` and `\` escaped; newest first; returns the filtered total).
- `type AccountRow struct { ID int64; Sqid, Name, Plan string; Created time.Time; Apps, Members int }`; `func (s *Store) AccountsPage(q string, offset, limit int) ([]AccountRow, int, error)` (live accounts, `name` or `sqid` matching literally, newest first; `Plan` from `account_plans.plan`, `""` when none).
- `type ActivityFilter struct { AccountID int64; Actions, Exclude []string }` (`AccountID` 0 means every account, and `-1` means "an account matched nothing", which answers no rows without a query); `type FeedRow struct { ID int64; At time.Time; Address, AccountName, AccountSqid, App, Action, Detail string }`; `func (s *Store) ActivityFeed(f ActivityFilter, beforeID int64, limit int) ([]FeedRow, error)` (`ORDER BY audit.id DESC`, `id < beforeID` when `beforeID > 0`, `LEFT JOIN accounts` for name and sqid, deleted accounts included).
@@ -367,7 +379,9 @@ file LICENSE LICENSE 3f3d9e0024b1921b067d6f7f88deb4a60cbe7a78e76c64e3f1d7fc3b779
Every method is a read on `s.db` except `TouchLastSeen`, which writes `users`, a NonApp table (`store_gate.go:204`), so it needs no claim SQL adapter and passes the gate on a host-claim console. No method reaches a raw handle, so `TestClaimSQLSeamCallers` is unaffected. *(My call: new reads go in their own file with their own migration, "for the same reason" the other features' tables do, `store.go:524-551`.)*
- [ ] **Step 1: Write the failing tests** in `opstore_test.go`, each on a store from `Open(filepath.Join(t.TempDir(), "console.db"))` with rows written through the existing methods at fixed times (`now := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)`): `EnsureUser`, `CreateSessionMethod`, `CreateAccount`, `AddMember`, `DeleteAccount`, `RecordActivity`, `RecordEvent`, `SetAlertSeen` (or whatever writes `alert_seen`, `store.go:2277`), and the app-claim method the fixtures use.
- - `TestMigrateOperatorPagesIsIdempotent`: `Open` twice on one path; `PRAGMA index_list(audit)` names both indexes; `users` has `last_seen`.
+ - `TestMigrateOperatorPagesIsIdempotent`: `Open` twice on one path; `PRAGMA index_list` names all seven new indexes on their tables; `users` has `last_seen`.
+ - `TestOperatorQueryPlans` (the witness): on a store migrated by `Open`, `EXPLAIN QUERY PLAN` of every `opSQL…` constant with representative arguments. No plan line contains `CORRELATED`. `sessions`, `audit` and `users` appear only as `SEARCH … USING INDEX` or `… USING COVERING INDEX`, with two named exceptions where a scan is the query: `users` in `opSQLPeoplePage` with a non-empty search (a `LIKE '%q%'` cannot use an index) and `audit` in the `other` kind's `NOT IN` feed, which walks `audit` by primary key newest first and stops at its `LIMIT` (asserted as `SCAN audit` with no `USE TEMP B-TREE`). `accounts`, `apps`, `memberships` and `account_plans` may be scanned only in `opSQLApps` and `opSQLAccountsPage`, bounded by the number of accounts and apps. Removing `sessions_by_time` (by hand, once) makes it fail with the old `CORRELATED SCALAR SUBQUERY` shape.
+ - `TestOperatorCountsAtScale`: a store with 20,000 users, 60,000 sessions over 30 days, 2,000 accounts, 8,000 apps and 200,000 audit rows (inserted in one transaction through a test helper); `OperatorCounts`, `NewPeoplePerDay`, `NewestPeople`, the first `PeoplePage` and each feed kind's first page are timed; each is printed, and under `CI` each must finish within 20 ms. Not parallel; listed in `.amadan/test-weights.tsv` if it takes a second or more.
- `TestTouchLastSeenNeverMovesBack`: touch at `now`, then at `now-1h`: `last_seen` stays `now`; a touch for an unknown address inserts nothing.
- `TestOperatorCountsWindows`: users created at `now-1h`, `now-6d`, `now-8d`, `now-13d`, `now-20d`; accounts at `now-2d`, `now-10d`; apps (one deleted); audit `promote` rows today for two apps and one yesterday; `last_seen` for two people and a session at `now-3d` for a third → `People 5`, `NewPeople7 2`, `NewPeoplePrev7 2`, `NewAccounts7 1`, `NewAccountsPrev7 1`, `Active30 3`, `DeploysToday 2`, `DeployApps 2`, `Apps` excludes the deleted one.
- `TestNewPeoplePerDayFillsZeroDaysAndIgnoresFuture`: three users today, one 29 days ago, none between, one at `now+1h`: 30 entries, `[0].N == 1`, `[29].N == 3`, every other `N == 0`, `[29].Day` is 2026-10-25 UTC midnight.
@@ -376,7 +390,7 @@ Every method is a read on `s.db` except `TouchLastSeen`, which writes `users`, a
- `TestOperatorReadsSurviveMissingAndDeletedAccounts` (Review Focus 4): a person with no membership (`Accounts 0`, `FirstAccount ""`); a person whose only account is deleted (`FirstAccount ""`, still counted in `People`); an audit row with `account_id 0` and one of a deleted account both appear in `ActivityFeed` with `AccountName` `""` and the deleted name respectively.
- `TestActivityFeedFiltersAndPages`: 120 rows across two accounts and three actions; `ActivityFeed({}, 0, 50)` is ids 120 to 71; `beforeID 71` continues at 70; `{AccountID: a}` only `a`'s; `{Actions: deployActions}` only those; `{Exclude: …}` none of them; `{AccountID: -1}` none.
- `TestGatedStoreOpensWithTheNewSchema`: `newClaimCase(t)` opens; `cx.st.TouchLastSeen(claimFxOwner, time.Now())` succeeds.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestMigrateOperatorPages|TestTouchLastSeen|TestOperatorCounts|TestNewPeoplePerDay|TestNewestPeople|TestPeopleAndAccountsSearch|TestOperatorReadsSurvive|TestActivityFeed|TestGatedStoreOpens' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestMigrateOperatorPages|TestOperatorQueryPlans|TestOperatorCountsAtScale|TestTouchLastSeen|TestOperatorCounts|TestNewPeoplePerDay|TestNewestPeople|TestPeopleAndAccountsSearch|TestOperatorReadsSurvive|TestActivityFeed|TestGatedStoreOpens' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement** `opstore.go` and the one-line `migrate` change.
- [ ] **Step 4: Run** Step 2's command and the store's own guards: `go test ./internal/console/ -run 'TestClaimSQL|TestStore|TestMigrate|Census' -count=1`. Expected: PASS.
- [ ] **Step 5: Commit**, message `console store: users.last_seen, audit indexes, and the operator pages' reads`.
@@ -625,8 +639,8 @@ The page: `op_page_header` (OPS-9, OPS-103); a small `rst-stats` band of Active
- Modify: `internal/console/server.go` (register `GET /fleet/activity` → `handleActivity`; `page` gains `Feed *feedView`); claim census, fixture (`claimRead("operator activity feed; SQLite only")`), probe (`claimPageRead(nil, "/fleet/activity", "<h1>" + OPS-10 + "</h1>")`)
**Interfaces:**
-- Consumes: `ActivityFeed`, `AccountBySqid`, `deployActions`, `accountAuditActions`, `op_dropdown`, `op_pagination`, OPS-10, OPS-119 to OPS-130.
-- Produces: `const feedPageSize = 50`; `type feedKind struct { Key, Label string; Actions []string; Exclude bool }`; `var feedKinds = []feedKind{{"all", OPS-121}, {"deploys", OPS-122, deployActions}, {"signins", OPS-123, []string{auditSignin, auditFirstSignin}}, {"accounts", OPS-124, the four account and invite actions}, {"other", OPS-125, every action above, Exclude: true}}`; `type feedQuery struct { Kind, Account string; Before int64 }`; `func parseFeedQuery(v url.Values) feedQuery` (an unknown kind is `all`; `before` a positive integer, else 0; `account` kept as text and resolved by the handler); `type feedView struct { Query feedQuery; Kind opDropdown; AccountName string; Rows []FeedRow; Pager opPager }`; `func (s *Server) handleActivity(w http.ResponseWriter, r *http.Request)`: fetches `feedPageSize + 1` rows to know whether Older exists; an `account` that `AccountBySqid` does not find filters with `AccountID: -1`.
+- Consumes: `ActivityFeed`, `OperatorAccountBySqid`, `deployActions`, `accountAuditActions`, `op_dropdown`, `op_pagination`, OPS-10, OPS-119 to OPS-130, OPS-148.
+- Produces: `const feedPageSize = 50`; `type feedKind struct { Key, Label string; Actions []string; Exclude bool }`; `var feedKinds = []feedKind{{"all", OPS-121}, {"deploys", OPS-122, deployActions}, {"signins", OPS-123, []string{auditSignin, auditFirstSignin}}, {"accounts", OPS-124, the four account and invite actions}, {"other", OPS-125, every action above, Exclude: true}}`; `type feedQuery struct { Kind, Account string; Before int64 }`; `func parseFeedQuery(v url.Values) feedQuery` (an unknown kind is `all`; `before` a positive integer, else 0; `account` kept as text and resolved by the handler); `type feedView struct { Query feedQuery; Kind opDropdown; AccountName string; Rows []FeedRow; Pager opPager }`; `func (s *Server) handleActivity(w http.ResponseWriter, r *http.Request)`: fetches `feedPageSize + 1` rows to know whether Older exists; the `account` parameter is resolved with `OperatorAccountBySqid` (after `operatorOnly`), so a deleted account's history stays reachable from its links; a sqid with no row at all filters with `AccountID: -1`. The filter line reads OPS-126 with the name, or with OPS-148 for a deleted account.
The page: `op_page_header` (OPS-10, OPS-119); a toolbar (`<div rst-lbar>`) with the kind `op_dropdown` (Label the current kind, Aria OPS-120); when an account filter is on, a line OPS-126 with a link OPS-127 that drops `account`; an `rst-card class="co-feed"` of rows: When (`ago`, with `fmtTime` as the `title`), Who, Account (the name linking to `?account=<sqid>`, or OPS-56), What (`Detail`), App (or OPS-56); OPS-130 when empty; `op_pagination` with Newest (when `Before > 0`, the URL without `before`) and Older (`before=<last row id>`, when there is one more row). The column template `.co-feed` goes in `ops.css`.
@@ -635,9 +649,10 @@ The page: `op_page_header` (OPS-10, OPS-119); a toolbar (`<div rst-lbar>`) with
- `TestActivityPageFiltersByKindAndAccount`: `?kind=deploys` shows only the promote rows; `?kind=signins` the sign-in; `?kind=other` none of the named actions; `?account=<shop sqid>` only shop's rows, with OPS-126 naming `shop` and the clear link.
- Walk targets: `perfTargets` gains `GET /fleet/activity` with `{Path: "/fleet/activity"}`, one target per `feedKinds` key (`?kind=deploys` and the rest, `other` included because its `NOT IN` is the likeliest slow query), `{Path: "/fleet/activity?account=<a seeded shop sqid>"}`, and `{Path: "/fleet/activity?before=<an id 2,000 rows back>"}`, all `Expect: 200`; `TestPerfTargetsCoverOperatorViews` (Task 10) now covers `feedKinds`.
- `TestActivityPageClampsItsParameters` (Review Focus 5): `before=-1`, `before=abc` are the first page; `kind=nope` is everything; `account=zzzz` is OPS-130, 200.
+ - `TestActivityFollowsADeletedAccountsLink`: delete `notes` through its settings door; on `/fleet/activity` its `account-deleted` row links `?account=<notes sqid>`; following that link shows `notes`'s rows, the deletion included, with OPS-148 naming `notes` in the filter line; a member-facing lookup of the same sqid (`AccountBySqid`) still answers nil.
- `TestActivityShowsAccountLevelRows`: the seeded `signin` row shows its Detail with OPS-56 for account and app.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestActivityPage|TestActivityShows|TestEveryOperatorPage|TestOperatorGate' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement**; add OPS-119 to OPS-130 to `operatorPagesCopyBuilt`.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestActivityPage|TestActivityShows|TestActivityFollowsADeleted|TestEveryOperatorPage|TestOperatorGate' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement**; add OPS-119 to OPS-130 and OPS-148 to `operatorPagesCopyBuilt`.
- [ ] **Step 4: Run** Step 2's command, `go test . -run TestOperatorPagesCopy -count=1`, `go test ./internal/console/ -run 'TestClaimConsoleRouteCensus' -count=1`, `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`, and the walk without `CI`.
- [ ] **Step 5: Commit**, message `console: platform-wide Activity for operators`.
@@ -673,7 +688,7 @@ Each page: `op_top`, `op_page_header` (its rail label and its subhead row), then
- Modify: claim census, fixture (`claimRead("deferred part of an operator page; the page's own gate")`) and probe for `GET /fleet/part/{part}`; `perfTargets` (one target per `fleetParts` key); `perf-budgets.txt` (`GET /fleet/part/{part} deferred: deferred part`; delete the `over:` records of `GET /fleet` and `GET /fleet/boxes`, and any other operator `over:` left)
**Interfaces:**
-- Consumes: plan 2's `viewGet`, `viewMode`, `errViewPending`, `viewPart`, `renderView`, `getAssembled`, the `deferred`/`asof`/`partfailed`/`partloader` partials, and Task 15's `fleetJSONView`, `hostRowsView`, `storePendingView`, `metricsView`, `economicsView`, `architectureView`.
+- Consumes: plan 2's `viewGet`, `viewMode`, `errViewPending`, `viewPart`, `renderView`, `getAssembled`, the `deferred`/`asof`/`partfailed`/`partloader` partials, and Task 15's `fleetJSONView`, `hostRowsView`, `storePendingView`, `storeUsageView`, `metricsView`, `economicsView`, `architectureView` over the package-level loaders in `viewloaders.go` (`loadFleetJSON`, `loadBoxSnapshot`, `loadStorePending`, `loadStoreUsage`, `loadMetricsFacts`, `loadEconomicsDay` and its siblings, `loadArchitectureFacts`), with `metricsFacts` and `buildEconomicsView` per request. Task 13 passes no closure or method value as a loader.
- Produces:
- the seams now read through the loaders: `opFleetJSON` → `fleetJSONView(ctx, p, mode)`, `opHostRows` → `hostRowsView`, `opStorePending` → `storePendingView` (still only for a store operator); each seam gains a `mode viewMode` parameter.
- `const boxesWindow = 60 * time.Second`: the window the per-box entry (`{"", "", partBoxes}`, plan 2's key) is read with. If plan 2 Task 15's `hostRowsView` uses `liveWindow` (30 s), Task 13 gives it a window parameter and passes `boxesWindow` from both the dashboard and Boxes, so they share one entry. *(My call on the exact value, from the coordinator's "~60 s".)*
@@ -700,12 +715,13 @@ On a `fleet.json` miss, the dashboard's whole body is the deferred part, because
- `TestDashboardAfterAStoreDecline`: the same through `/decline` with a reason.
- `TestEconomicsScenarioSaveWarmBeforeWrite`: warm `/fleet/economics`, `/fleet/economics/accounts` and `/fleet/architecture`; save a changed active scenario through `POST /fleet/economics/scenarios`; the next view of each shows the new scenario with zero S3 requests. Again with the economics view's refresh held in flight (`HoldNext("list", …)` on one of its listings, after moving `fx.clock` past the window) when the save lands: after `release()` and `waitBackground`, every page still shows the new scenario, never the old.
- `TestArchitectureRefreshWarmBeforeWrite`: warm `/fleet/architecture`; `POST /fleet/architecture/refresh`; the redirect target shows the refreshed inventory with zero S3 requests.
+ - `TestOperatorPagesJoinLocalStatePerRequest`: warm `/fleet`, `/fleet/store` and `/fleet/economics/accounts`; then, with no object-store write: rename an account in SQLite (the economics accounts table shows the new name at once), delete the account whose storage application is pending (the store page and the dashboard's storage item drop it at once), and move `fx.clock` 16 minutes (the dashboard says the fleet summary is old and the boxes read Stale at once); every one with zero S3 requests.
- `TestDashboardCountsAreNeverCached`: warm `/fleet`; create a user and an audit row through the store (no object-store write); the next GET's counts and Latest activity include them at once, with zero S3 requests (rule (a)).
- `TestEveryOperatorPageRendersInTheShell` and the page tests from Tasks 3 to 12 read assembled pages (`getAssembled`) and still pass.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestDashboardCold|TestDashboardBoxesCold|TestBoxReadsOncePerWindow|TestEveryFleetPart|TestDashboardAfterAStore|TestEconomicsScenarioSaveWarm|TestArchitectureRefreshWarm|TestDashboardCountsAreNeverCached|TestEconomicsEditAndSave|TestEconomicsPartIsInitialised|TestEveryOperatorPage' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestDashboardCold|TestDashboardBoxesCold|TestBoxReadsOncePerWindow|TestEveryFleetPart|TestDashboardAfterAStore|TestEconomicsScenarioSaveWarm|TestArchitectureRefreshWarm|TestDashboardCountsAreNeverCached|TestOperatorPagesJoinLocalState|TestEconomicsEditAndSave|TestEconomicsPartIsInitialised|TestEveryOperatorPage' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** Step 2's command, the page tests of Tasks 3 to 12 (`-run 'TestDashboard|TestBoxes|TestPeoplePage|TestActivityPage|TestEconomics|TestFleetMetrics|TestArchitecture|TestStoreQueue|TestOperatorGate'`), `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`, and the walk with `CI=1`: every operator screen within 150 ms with zero remote calls warm, and `grep -c '/fleet.* over:' internal/console/testdata/perf-budgets.txt` prints `0`.
-- [ ] **Step 5: Commit**, message `console: operator pages read through the view cache; deferred parts behind each page's own gate`.
+- [ ] **Step 5: Commit**, message `console: operator pages read through the view cache; deferred parts behind each page's own gate`. If this task lands on `operator-pages-cache`, run Task 15 on that branch with `NAME=operator-pages-cache`.
### Task 14: Screenshots at 1280 and 390 px, light and dark
@@ -742,10 +758,10 @@ ls "$SHOTS"/*.png | wc -l # 44
### Task 15: Census, full gate, review, merge
**Files:**
-- Create (by the tool): the census overlay and `docs/superpowers/notes/census-proposal-operator-pages.md`
+- Create (by the tool): the census overlay and `docs/superpowers/notes/census-proposal-<NAME>.md`, where `NAME` is the landing branch (`operator-pages`, or `operator-pages-cache` for a second landing, as "Branch" says)
-- [ ] **Step 1: Census card.** `make census-card`. For every changed unit write a CLAIMS line (`<file>:<unit><TAB><what changed, and that no read was added or which one was>`): new SQLite reads and one users write, embedded static files, templates, a job registry around existing passes, the `audit` gate classification (Task 6A, reviewed on #280), no new read of root-owned state. `make census-propose NAME=operator-pages CLAIMS=<file>`. A `reads`, `new`, `removed` or `other` class is a decision for Paul on #280, not an approval.
-- [ ] **Step 2: Independent approval.** Give the card and the branch diff against amadan `main` to a reviewer of the other model family (Astra for this Claude-written branch); record each verdict on #280 with the reviewer and the tip.
+- [ ] **Step 1: Census card.** `make census-card`. For every changed unit write a CLAIMS line (`<file>:<unit><TAB><what changed, and that no read was added or which one was>`): new SQLite reads and one users write, embedded static files, templates, a job registry around existing passes, the `audit` gate classification (Task 6A, reviewed on #280), no new read of root-owned state. `make census-propose NAME=<landing branch> CLAIMS=<file>`: `operator-pages` for the branch holding Tasks 1 to 12 and 14 (and 13, if it lands together), `operator-pages-cache` for a separate Task 13 landing. The second run is a new proposal with its own CLAIMS (only Task 13's units), card and ruling, not a rerun of the first: the tool replaces only its own overlay while it is the chain's last line, and plan 2's overlay sits between them. A `reads`, `new`, `removed` or `other` class is a decision for Paul on #280, not an approval.
+- [ ] **Step 2: Independent approval.** Give the card and the branch diff against amadan `main` to a reviewer of the other model family (Astra for this Claude-written branch); record each verdict on #280 with the reviewer, the proposal NAME and the tip.
- [ ] **Step 3: Local gate.** `gofmt -l .` (empty), `go vet ./internal/console/ ./cmd/console/`, `go build ./...`, both cross-compiles, the targeted runs from Tasks 2 to 13, `go test . -run 'TestOperatorPagesCopy|TestConsolePerfCopy' -count=1`, one `nice -n 19` run of `TestClaimConsoleMutationInvariant`, one `go test ./internal/console/ -run 'TestJob|TestLastSeen|TestStatic' -race -count=1`, and the walk with `CI=1`. Update `.amadan/test-weights.tsv` for any new test of a second or more.
- [ ] **Step 4: Push, describe, wait for CI.** `amadan branch describe carlos/platform operator-pages -body -`: what changed, why, the decisions above, the screenshot review notes, the census approval, Task 6A's gate-review verdict on #280. `amadan ci status carlos/platform -branch operator-pages` until exit 0.
- [ ] **Step 5: Squash, re-run CI on the squashed tip, merge** with the `-expect <tip>` form. Rolling waits for Paul's go-ahead and follows the house roll order (dev boxes, dev console, check, flagship boxes, flagship console); after the roll, read `/fleet` on flagship and the Console speed table's `GET /fleet` row.
@@ -756,7 +772,8 @@ ls "$SHOTS"/*.png | wc -l # 44
- **Astra round 2 (`d9e0277a`), findings that applied here:** 3, economics initializers run after fragment insertion, with an edit-and-save test after a cold load (Tasks 12, 13); 9, the six account actions are recorded on claim-gated consoles through the gate's `FreeWhenNoApp` rule, with its own gate review (Task 6A; the follow-up discussion is gone); 10, the last-seen hour is reserved under one mutex and write attempts are counted under concurrency (Task 5); 11, swallowed per-item failures mark the run Failed in every pass, with an AST check and an injected alert failure seen on the dashboard (Tasks 7, 9); 12b, plan 2's `HoldNext("list", …)` (no hold helper of this plan's own) and joining in-flight loads through the seams in blocking mode (Task 13); 12c, mux canonicalisation tested apart from the unknown-asset 404 (Task 2).
- **Astra round 3 (`4d963091`), findings that applied here:** 7, the dashboard reads an in-process projection of what is firing now, kept by the watcher from the published objects, one entry per rule, with firing-then-cleared across a recipient change tested (Task 7A, Task 9); 8, explicit walk targets for every query-selected view (`?show=accounts`, searches, pages, every activity kind, an account filter, a deep `before`) over a populated fixture, with a test that each `show` and `kind` has one (Tasks 9, 10, 11); R2-12c, the traversal test follows each hop of the mux's redirect chain to the final 404, apart from the unknown-asset 404 (Task 2). Economics initializers follow plan 2's no-script rule for fragments (the data moves to an attribute) and its `carlos:part` event (Tasks 12, 13).
+- **Astra round 4, findings that applied here:** 7, active counts are set-based over new covering indexes, with an `EXPLAIN QUERY PLAN` witness over every statement and a scale run (Task 4); 9, each landing branch has its own census NAME, card, overlay and ruling (Branch, Tasks 13, 15); 10, the Activity filter resolves accounts with an operator-only, tombstone-inclusive lookup, and following a deleted account's link is tested (Tasks 4, 11). Plan 2's restricted load environment: every operator load caches only object-store facts, with per-request builders for the rest (Global Constraints, Task 13).
- **Plan 2's read-set redesign (coordinator, 2026-10-25).** This plan no longer leans on a per-door effect table. Only the seven object-store loads above are cached; every SQLite count and list, the job registry and the alert projection are read per request; status words and ages are joined per request; the operator writes (store approve and decline, economics scenario save, architecture refresh) are covered by read-set invalidation with warm-before-write tests (Task 13).
- **Coordinator change (2026-10-25).** The dashboard's Boxes table keeps the mockup's columns from `HostRows` through the view cache (Decisions, Tasks 9 and 13); the spec's "`HostRows`' per-box reads stay off the dashboard" is met by keeping them off the request path of a warm view, with the per-window cost stated in Task 13.
- **Spec coverage.** §3.1: copy in (Task 2), `go:embed`, own origin, long cache, content hash (Task 2), `VERSION` and hash test (Task 2), MPL notice (Task 2, via `LICENSE` since the files carry no header), no `light.js` (not copied), fetches nothing (Task 3's shell test). §3.2: one layout ported from `console.html` (Task 3), brand and account menu with Customer console and Sign out (Task 3), rail order and labels (Tasks 1, 3), below 800 px index and page (Task 3's `/fleet/index`, Task 14), light and dark through the theme (Tasks 2, 14), `operatorOnly` unchanged (Task 3's gate test, every page task). §3.3: dashboard, page header, needs attention with all five conditions, the stats band, the 30-day bars with screen-reader numbers, newest people, latest activity, boxes, background jobs (Task 9); old `/fleet` content to Boxes (Task 8); errors and edge failures out of scope (not built). §3.4: `last_seen` with the hourly throttle (Tasks 4, 5), account-level audit rows and the feed newest-first with an index for time-window counts (Tasks 4, 6, 11), job registry, in-process, Not run yet after restart (Task 7), counts from SQLite and `fleet.json` through the view cache, per-box rows from `HostRows` through the cache too, never on a warm view's request path (Tasks 4, 9, 13), 150 ms and one S3 read (Tasks 9, 13). §3.5: People and accounts (Task 10), Activity (Task 11), Boxes plus jobs (Task 8), Metrics with Console speed, Storage requests, Economics with seg-tabs and a list-bar, Architecture (Tasks 3, 12), old URLs keep working (all registrations kept; `/fleet` stays 200). §3.6: one `<h1>`, rail `aria-current`, no inline style (Task 3, every page), screenshots (Task 14), every page in the walk (Tasks 2 to 13), Luna copy pass (Task 1). §3.7: lands after plan 1, alongside plan 2 and Part 1, Task 13 after plan 2 Task 15.
-- **Names that cross plans.** From plan 1: `consolePerfSkip`, `PerfGroups`, `consoleSpeedRows`, `newConsoleFixtureWith`, `newPerfFixture`, `perfInventory`, `perfTargets`, `loadPerfBudgets`, `TestConsoleScreensMeetTheBudget`, the budgets grammar. From plan 2: `viewGet`, `viewMode`, `viewCached`, `viewBlocking`, `errViewPending`, `viewPart`, `renderView`, `getAssembled`, `perfLatency` (`Calls`, `SetFail`, `Keys`, `Writes`, `ResetKeys`, `HoldNext`), `perfQuiesce`/`waitBackground`, `s.bg.Go`, the four partials, Task 8's read-set invalidation (no per-door declaration), and Task 15's seven loaders. This plan's names used across its own tasks: `assetURL`, `opShell`, `opRail`, `opPage`, `op_top`/`op_bottom`, the `op_*` partials and their data types, `opPages`, `opNumber`, `signInOperator`, `operatorScreens`, `opShellPending`, `assertOpShell`, `deployActions`, `accountAuditActions`, `OperatorCounts`, `DayCount`, `PersonRow`, `AccountRow`, `ActivityFilter`, `FeedRow`, `FiringAlert`, `TouchLastSeen`, `noteSeen`, `alertNow`, `alertsNow`, `seedOperatorScale`, `peopleShows`, `auditAccount`, `jobRegistry`, `jobFailed`, `JobStatus`, `opJobRows`, `opFleetJSON`, `opHostRows`, `opStorePending`, `seedOperatorWorld`, `fleetParts`, `handleFleetPart`.
+- **Names that cross plans.** From plan 1: `consolePerfSkip`, `PerfGroups`, `consoleSpeedRows`, `newConsoleFixtureWith`, `newPerfFixture`, `perfInventory`, `perfTargets`, `loadPerfBudgets`, `TestConsoleScreensMeetTheBudget`, the budgets grammar. From plan 2: `viewGet`, `viewMode`, `viewCached`, `viewBlocking`, `errViewPending`, `viewPart`, `renderView`, `getAssembled`, `perfLatency` (`Calls`, `SetFail`, `Keys`, `Writes`, `ResetKeys`, `HoldNext`), `perfQuiesce`/`waitBackground`, `s.bg.Go`, the four partials, Task 8's read-set invalidation (no per-door declaration), `viewLoader`, `viewLoadEnv`, `viewloaders.go` and its `load…` functions (`loadFleetJSON`, `loadBoxSnapshot`, `loadStorePending`, `loadStoreUsage`, `loadMetricsFacts`, `loadEconomicsDay`, `loadArchitectureFacts`), `metricsFacts`, `buildEconomicsView`, and Task 15's seven views. This plan's names used across its own tasks: `assetURL`, `opShell`, `opRail`, `opPage`, `op_top`/`op_bottom`, the `op_*` partials and their data types, `opPages`, `opNumber`, `signInOperator`, `operatorScreens`, `opShellPending`, `assertOpShell`, `deployActions`, `accountAuditActions`, `OperatorCounts`, `DayCount`, `PersonRow`, `AccountRow`, `ActivityFilter`, `FeedRow`, `FiringAlert`, `TouchLastSeen`, `OperatorAccountBySqid`, `OperatorAccount`, the `opSQL…` constants, `noteSeen`, `alertNow`, `alertsNow`, `seedOperatorScale`, `peopleShows`, `auditAccount`, `jobRegistry`, `jobFailed`, `JobStatus`, `opJobRows`, `opFleetJSON`, `opHostRows`, `opStorePending`, `seedOperatorWorld`, `fleetParts`, `handleFleetPart`.