carlos / platform Public

Console plans: Astra round 3 fixes; read-set invalidation replaces the effect table

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a73f6974c58c0f66735b083a57601fc8b768e3bd parent 4d96309
3 files changed, +185 −150
  • docs/superpowers/plans/2026-10-25-console-perf-1-measure.md +4 −2
  • docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md +116 −124
  • docs/superpowers/plans/2026-10-25-operator-pages.md +65 −24

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 2f0270992..e277f4c4f 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
@@ -323,7 +323,8 @@ The file's grammar, one record per line, `#` starts a comment:
**Files:**
- Create: `internal/s3fake/s3fake.go` (a test helper package: no production code imports it), `internal/s3fake/s3fake_test.go`
-- Create: `internal/release/s3fake_contract_test.go`; Modify: `internal/release/s3_minio_test.go:24` (its body becomes `s3StoreContract(t *testing.T, s *S3Store)`, which both tests call)
+- Create: `internal/release/export_test.go` (package `release`: `func PutRaw(s *S3Store, ctx context.Context, key string, body []byte, ifMatch string) (string, error)` and `func DeleteRaw(s *S3Store, ctx context.Context, key string) error`, thin wrappers over `putRaw` and `deleteRaw` that exist only in test builds), `internal/release/s3contract_test.go` and `internal/release/s3fake_contract_test.go` (both package `release_test`)
+- Modify: `internal/release/s3_minio_test.go` (moves to package `release_test`; its body becomes `s3StoreContract(t *testing.T, s *release.S3Store)` in `s3contract_test.go`, calling `release.PutRaw` and `release.DeleteRaw` where it called `putRaw` and `deleteRaw`, `s3_minio_test.go:78`)
- Create: `internal/console/perflatency_test.go`
- Modify: `internal/console/server_test.go:49-107` (an options constructor; the three existing constructors call it)
@@ -342,7 +343,7 @@ Why a fake S3 server and not a counting store wrapper: counting at the HTTP tran
The console makes no direct box HTTP call on a screen path today (Task 5); `HostDelay` is applied to `AppClient`, the app-host client. A future box client on a screen path must be added here.
- [ ] **Step 1: Write the failing tests:**
- - `internal/release` `TestS3StoreFakeContract`: `s3StoreContract(t, s)` (the body of `TestS3StoreMinioContract`, unchanged) against an `S3Store` pointed at `s3fake.New` over a fresh `DirStore`. It runs in every `go test`, unlike the MinIO job.
+ - `internal/release` (package `release_test`) `TestS3StoreFakeContract`: `s3StoreContract(t, s)` (the body of `TestS3StoreMinioContract`, unchanged but for the two exported raw helpers) against an `S3Store` pointed at `s3fake.New` over a fresh `DirStore`. It runs in every `go test`, unlike the MinIO job. The import graph stays acyclic: `s3fake` imports `release`; only the external test package `release_test` imports `s3fake`, and Go builds external test packages after the package under test. *(Astra round 3, finding 1.)*
- `TestS3FakePagesLikeS3` (in `s3fake`): 1,001 objects under one prefix take two `ListObjectsV2` requests for a `List` and for a `ListMod`; a level holding 1,500 objects and 2 sub-prefixes takes two requests for a `ListDirs`; an empty prefix takes one.
- `TestS3FakeCountsChangeIndexRequests`: one `Put` through `NewDeploymentS3Store` of a key under `apps/<a>/<b>/` counts three requests (the write, then the change index's read and write).
- `TestS3FakeDelayAndHook`: with `SetDelay(25 * time.Millisecond)` a `Get` takes at least 25 ms; an `OnRequest` hook answering 500 for one key makes that `Get` fail; a hold returned by the hook keeps the response until it is closed, after the object was read.
@@ -442,5 +443,6 @@ Not a code task. Spec §2.5 step 1: ship and roll this on its own and read flags
- **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.
+- **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 c8dbc4b76..60c90f567 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,13 +29,14 @@ 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.** A mutation marks its effect after admission (session, CSRF, owner, confirmation, fresh auth, its own validation) and after its write succeeded, before it writes its response. The effect names the entries it changed, across scopes (an app delete also changes the account's Trash). Invalidation bumps each entry's generation, which also covers a load already in flight, so a load that started before the write can never publish. Then only the declared entries are re-read, inside the request. If the re-read fails the mutation still succeeds and the entries stay invalidated: the next GET is a miss. The pre-write value is never served after the user's own write.
+- **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.
- **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.
- **Copy goes through a Luna pass before it is written into a template** (Task 1). House voice: no em dashes (a full stop and a new sentence, continuing in lower case); human text only. No tenant names: neutral names in code, tests and fixtures (`shop`, `example.com`; the existing fixture app `kass`, the claim world's `bab` and `titogo`, and account `ops` may be reused, never newly introduced).
- **`over:` records.** Each task deletes the `over:` records of the screens it makes fast, in the same commit, and the walk passes with `CI=1` before that commit. A screen that needs a remote call on a warm GET gets a `calls <n>: <reason>` record only with a reason a reviewer accepts; the target is none.
-- **Tests that read a converted page see what a browser sees.** A test that asserts on a screen's body after this plan converts it reads it with `getAssembled` (Task 7), which follows the page's deferred parts the way the loader script does. The task that converts a screen converts that screen's tests and claim probes.
+- **Tests that read a converted page see what a browser sees.** The default fixtures (no tracker) read inline, so existing tests keep working unchanged. Tests on a cached server (`newPerfFixture`, the claim world) read bodies with `getAssembled` (Task 7), which follows deferred parts the way the loader script does. The task that converts a screen runs that screen's existing acceptance tests on `newPerfFixture` too: the nav plan's Releases tests at least, as Task 10 lists. Claim probes splice parts.
+- **No script inside a deferred fragment** (Task 7). Page behaviour lives in the frame, as an initializer run on load and on `carlos:part`.
- **Commit per task.** Every commit message ends with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- **Amadan tasks:** one per plan task on the branch, advanced as each closes. **Test weights:** a new top-level `internal/console` test of a second or more gets a row in `.amadan/test-weights.tsv`. **Merge main first** before review and before merging, re-run the census card, wait for CI on that tip, merge with `amadan branch merge carlos/platform console-perf-2 -expect <tip> -message "..."`. Never a bare `amadan branch merge`.
@@ -45,7 +46,7 @@ Every task's requirements include this section.
2. **A refresh, or a first load, that started before the user's write and finishes after it.** It read the pre-write state and must never publish. Test: Task 6, `TestLoadInFlightAtAWriteNeverPublishes` (both a first load and a refresh); Task 10, `TestPromoteDuringABackgroundRefreshShowsTheNewVersion`.
3. **Two people viewing the same app at once.** The cache shares values across requests; one page decorating channels or versions must not leak into another's or race it. Test: Task 9, `TestConcurrentViewsShareNoState` (run with `-race`).
4. **A refresh that hangs.** S3 stalls for a minute while people keep opening the app. They expect the last reading with its "as of" age, not a pile of goroutines, and the next view after the hang ends to try again. Test: Task 6, `TestHungLoadIsBoundedAndRetried`.
-5. **A write whose effect reaches another screen.** Deleting an app changes Trash; an operator's storage approval changes that account's settings page; a CLI promote changes the browser's Releases. A person expects each to show at once. Test: Task 8, `TestWriteEffectsReachOtherScopes`; Task 14, `TestDeletedAppShowsInTrash`; Task 10, `TestCLIPromoteShowsInTheBrowser`.
+5. **A write whose effect reaches another screen.** Deleting an app changes Trash; an operator's storage approval changes that account's settings page; a CLI promote changes the browser's Releases. A person expects each to show at once. Test: Task 8, the coverage check in `TestClaimConsoleMutationInvariant` and the warm-before-write cases; Task 14, `TestDeletedAppShowsInTrash` and `TestStoreDecisionShowsOnTheAccount`; Task 10, `TestCLIPromoteShowsInTheBrowser`.
---
@@ -56,10 +57,11 @@ Every task's requirements include this section.
| `internal/console/pagememo.go` (create) | per-request memo: `withPageMemo`, `memoOnce`. |
| `internal/console/viewcache.go` (create) | the view cache: keys, windows, generations, single-flight loads, `wrote`, eviction, quiesce. |
| `internal/console/viewparts.go` (create) | `viewMode`, `errViewPending`, `viewGet`, the part tables and handlers, `renderView`, `asOfText`. |
-| `internal/console/viewwrites.go` (create) | `viewEffect`, the rule constructors, `viewWrites` (route pattern to effect), `wroteView`. |
+| `internal/console/viewtrack.go` (create), `internal/release/store.go` and the `DirStore` file (modify) | the store observer, `StoreTracker`, write sets and the re-read writer. |
+| `internal/console/bgwork.go` (create) | `bgWork`: every request-triggered goroutine, so tests can wait for all of them. |
| `internal/console/templates/parts.html` (create) | `deferred`, `asof`, `partfailed`, `partloader`, `part_text`. |
| `internal/console/claim_routes.go` (modify `:59-69`) | `registerRoute` installs the request memo. |
-| `internal/console/server.go`, `view.go`, `appsettings.go`, `deployments.go`, `instancepage.go`, `errorsview.go`, `analyticsview.go`, `accountfleet.go`, `fleets.go`, `ownership.go`, `storepage.go`, `archpage.go`, `pipelinepage.go`, `pendinghandlers.go`, `regiondefault.go`, `regioncandidates.go`, `apisystemupdate.go`, `apiinstances.go`, `accountreview.go`, `instances.go`, `apidomains.go`, `appdomains.go`, `controlplane.go`, `appswap.go`, `apitemporary.go`, `apicli.go` and the other write doors (modify) | screens read through the memo and the cache; mutations call `wroteView`. |
+| `internal/console/server.go`, `view.go`, `appsettings.go`, `deployments.go`, `instancepage.go`, `errorsview.go`, `analyticsview.go`, `accountfleet.go`, `fleets.go`, `ownership.go`, `storepage.go`, `archpage.go`, `pipelinepage.go`, `pendinghandlers.go`, `regiondefault.go`, `regioncandidates.go`, `apisystemupdate.go`, `apiinstances.go`, `accountreview.go`, `instances.go`, `apidomains.go`, `appdomains.go`, `controlplane.go`, `appswap.go`, `apitemporary.go`, `apicli.go` and the other write doors (modify) | screens read through the memo and the cache. |
| `internal/console/templates/*.html` (modify) | each converted screen's body wrapped in `{{define "<name>_body"}}`, an `asof` line, a placeholder branch. Operator templates are not touched. |
| `internal/console/store.go` (modify, Task 16 only if the measurement calls for it) | a read-only pool for the gate's reads. |
| `internal/provision/provision.go` (modify) | export `ListRecordHosts` over `recordHosts` (`:2859`). |
@@ -101,6 +103,7 @@ Spec §2.4 C rows 1 to 3: `ensureAccountManifest` re-reads on every app tab; `Se
**Files:**
- Create: `internal/console/pagememo.go`; Test: `internal/console/pagememo_test.go`
+- Create: `internal/console/bgwork.go`: `type bgWork struct{…}` with `Go(f func())` and `Wait()`; `Server.bg bgWork`. Every goroutine a request starts runs through `s.bg.Go`: this task's account-manifest check, Task 3's edge-fold refresh, Task 6's view loads and the inner metrics and economics sweeps, so a test can wait for all of them (Task 6's `waitBackground`).
- Modify: `internal/console/claim_routes.go:59-69` (`registerRoute`)
- Modify: `internal/console/server.go`: `account` (`:2426`), `accountPage` (`:3344`, `:3353`), `memberAccount` (`:2361`), `ensureAccountManifest` (`:4087-4103`), `appPage` (`:3406`, `:3424`)
- Modify: `internal/console/accountreview.go:37`, `:41` (`appAccountReview` gains `ctx context.Context` as its first parameter)
@@ -113,9 +116,9 @@ Spec §2.4 C rows 1 to 3: `ensureAccountManifest` re-reads on every app tab; `Se
- `func memoOnce[T any](ctx context.Context, key string, f func() (T, error)) (T, error)`: the first call per key per request runs `f`; later calls return its result (error included); with no memo in `ctx` it just runs `f`.
- `var pageMemoHits atomic.Int64`: incremented on every memo hit (read by tests).
- `func (s *Server) accountsFor(ctx context.Context, addr string) ([]Account, error)` (memo key `accounts:<addr>`) and the package-level `func memoRoutes(ctx context.Context, regPath string) ([]registry.Route, error)` (memo key `routes:<regPath>`, through `openRegistry`), so `Assemble` and `appAccountReview` share one route read. Every page-path caller of `s.store.AccountsFor` and of `reg.List()` with a request context uses these. Callers copy before sorting or appending.
- - `func (s *Server) ensureAccountManifestLater(acct *Account)`: replaces the synchronous call at `server.go:3406`. It returns at once. When `Server.manifestSeen` (a `sync.Map`, sqid to `struct{}`) does not hold the sqid and no check is running for it, it starts one goroutine that runs today's `ensureAccountManifest` body on `context.WithTimeout(context.Background(), viewLoadTimeout)` and records the sqid on success. The check is still triggered only by a view. *(My call: the backfill is best-effort today; moving it off the response path keeps that and removes the only remote read left in the gates.)*
+ - `func (s *Server) ensureAccountManifestLater(acct *Account)`: replaces the synchronous call at `server.go:3406`. It returns at once. When `Server.manifestSeen` (a `sync.Map`, sqid to `struct{}`) does not hold the sqid and no check is running for it, it starts one goroutine (through `s.bg.Go`, Task 6) that runs today's `ensureAccountManifest` body on `context.WithTimeout(context.Background(), viewLoadTimeout)` and records the sqid on success. The check is still triggered only by a view. *(My call: the backfill is best-effort today; moving it off the response path keeps that and removes the only remote read left in the gates.)*
- `func (s *Server) noteLastAccount(addr string, id int64) (wrote bool)`: writes `SetLastAccount` only when `Server.lastAccount` (a `sync.Map` addr to id, filled on write and by `memberAccount`'s `LastAccount` read) differs from `id`.
- - test-only, on plan 1's `perfLatency`, all built on the S3 fake's `OnRequest` hook so they act on real HTTP requests: `Keys() []string` (the object key of every `GetObject`, `PutObject` and `DeleteObject` and the prefix of every `ListObjectsV2`, in order); `ResetKeys()`; `SetFail(match func(key string) bool)` (a matching request answers 500 after counting; nil clears it); `HoldNext(op string, match func(key string) bool) (held <-chan struct{}, release func())` with `op` `"get"` or `"list"` (the next matching request, and only that one, is read by the fake, then closes `held` and waits for `release` before its response is written, so it returns what was read before the hold); `OnPut(f func(key string))` (runs after each `PutObject` has been stored). Later tasks use these by name.
+ - test-only, on plan 1's `perfLatency`, all built on the S3 fake's `OnRequest` hook so they act on real HTTP requests: `Keys() []string` (the object key of every `GetObject`, `PutObject` and `DeleteObject` and the prefix of every `ListObjectsV2`, in order); `Writes() []string` (the keys of the `PutObject` and `DeleteObject` requests alone, in order: the write oracle Task 8 checks against); `ResetKeys()` (clears both logs); `SetFail(match func(key string) bool)` (a matching request answers 500 after counting; nil clears it); `HoldNext(op string, match func(key string) bool) (held <-chan struct{}, release func())` with `op` `"get"` or `"list"` (the next matching request, and only that one, is read by the fake, then closes `held` and waits for `release` before its response is written, so it returns what was read before the hold); `OnPut(f func(key string))` (runs after each `PutObject` has been stored). Later tasks use these by name.
`registerRoute` wraps every handler with `withPageMemo` inside the mux (the mux has already set the pattern for plan 1's perf middleware) and keeps its existing claim-entry wrapping and order.
@@ -144,7 +147,7 @@ Spec §2.4 C rows 5 to 7, plus two wasted reads the 2026-10-25 inventory found.
**Interfaces:**
- Produces:
- - `foldedEdgeIPs` never waits on a fold: it returns the last fold (or nothing before the first) and, when the fold is older than `edgeFoldTTL` and none is running, starts one in a goroutine. The empty-fold rule (`:1281-1286`) is kept. The fold is still triggered only by a request.
+ - `foldedEdgeIPs` never waits on a fold: it returns the last fold (or nothing before the first) and, when the fold is older than `edgeFoldTTL` and none is running, starts one in a goroutine (through `s.bg.Go`, Task 6). The empty-fold rule (`:1281-1286`) is kept. The fold is still triggered only by a request.
- `AppView.PipelineErr error`: set by `applyPipelineView` when the read fails, so `Pipeline == nil && PipelineErr == nil` means "no pipeline". `func pipelineOf(view *AppView) (*release.Pipeline, error)` replaces the second `GetPipeline` in `pendingPipeline`'s callers (the Overview and the Releases page's pending section) and in `handlePipelineSettingsPage`.
- `var versionsTimeout = instanceStoreTimeout`: `Versions` and the nav plan's `VersionsPage` wrap their `ctx` with it.
- Account settings resolve the account level only: `telemetry.Read(ctx, s.cfg.Releases, telemetry.AccountKey(sqid))` folded with `telemetry.Fold(acct, telemetry.Settings{})`, instead of `telemetry.Resolve(…, "")`, which reads `apps/<sqid>//telemetry.json`, a key nothing writes.
@@ -233,26 +236,29 @@ Spec §2.4 C rows "Settings, `populateAppSettings`", "`appDeployEmpty`" and "`en
**Files:**
- Create: `internal/console/viewcache.go`; Test: `internal/console/viewcache_test.go`
- 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.views.quiesce() }`; `perfColdReset = func(fx *consoleFixture) { fx.srv.resetForColdView() }`; `newPerfFixture` sets `fx.clock` and points `fx.srv.now` at it)
-- Create: `internal/console/viewreset_test.go`: `func (s *Server) resetForColdView()` (test-only) gives the server what a restart would: a fresh `newViewCache(s.now, viewCacheMax)`, an empty `manifestSeen`, an unset edge fold, and empty inner caches in `LoadMetrics` and `LoadEconomics`.
+- 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).
+- Create: `internal/console/viewreset_test.go`: `func (s *Server) waitBackground()` (test-only: `s.bg.Wait()`) and `func (s *Server) resetForColdView()` (test-only), which first waits for background work and then gives the server what a restart would: a fresh `newViewCache(s.now, viewCacheMax)`, an empty `manifestSeen`, an unset edge fold, and empty inner caches in `LoadMetrics` and `LoadEconomics`. `perfQuiesce` is `fx.srv.waitBackground()`, so counts and resets never run while a request-triggered worker is still reading. *(Astra round 3, finding 9.)*
**Interfaces:**
- Produces:
- - `type viewKey struct { Acct, App, Part string }`: `Acct` is the account sqid, `""` for deployment-wide entries; `App` is `""` for account-wide entries; `Part` names the read and, for filtered reads, carries the normalized query (`logs?host=a&since=1h`).
+ - `type viewKey struct { Acct, App, Part string }`: `Acct` is the account sqid, `""` for deployment-wide entries; `App` is `""` for account-wide entries; `Part` names the read and, for filtered reads, carries the filter key (Task 12).
+ - part-name constants used by every later task: `partCore`, `func versionsPart(page int) string` (`versions?page=<n>`), `partTags`, `partRetention`, `partInstancesManifest`, `partAppReport`, `partTelemetry`, `partGates`, `partClaims`, `partCertWarm`, `partCatchall`, `partDeployEmpty`, `partEnvs`, `partStore`, `partMail`, `partFeatures`, `partSwap`, `partRecordHosts`, `partApps`, `func trashPart(app string) string` (one tombstone per entry, see Task 8's second rule), `partEntitlement`, `partAccountTelemetry`, `func fleetBoxesPart(fleet string) string`, `partFleetJSON`, `partBoxes`, `partEdges`, `partMetrics`, `func economicsPart(period string) string`, `partStorePending`, `partStoreUsage`, `partArchitecture`.
- `const (liveWindow = 30 * time.Second; writtenWindow = 5 * time.Minute; viewCacheMax = 4096)` and `var viewLoadTimeout = 15 * time.Second` (a var so a test can shorten it).
- `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`.
- - `type viewEffect struct { Reread []viewKey; Drop func(viewKey) bool; Before []func() }` (built by Task 8's constructors). `Before` runs inside `wrote`, after the generations are bumped and before the re-reads, for a value that also sits in a cache below the view cache (Task 15's economics).
- - `func (c *viewCache) wrote(ctx context.Context, e viewEffect) (failed int)`: first (then `e.Before`), for every entry whose key is in `e.Reread` or matches `e.Drop` (an entry exists 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. Second, for each key in `e.Reread` that has an entry, start a load at the new generation; all run concurrently under `ctx`, and `wrote` waits for them. A success publishes; a failure leaves the entry invalid and counts in `failed`. A key nobody has viewed has no entry and costs nothing.
- - `func (c *viewCache) quiesce()`: waits until no load is running (tests).
+ - 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.
+ - `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 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`.) `wrote`'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 `wrote` 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 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.
- 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.
@@ -262,18 +268,19 @@ The rules the implementation keeps:
- `TestViewPeekStaleServesAndRefreshesOnce`: after `window` passes, three peeks return the old value with `Stale` and the loader runs once more.
- `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 blocks after reading value A; `wrote` with that key in `Reread` and 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.
- - `TestWroteRereadsOnlyDeclaredKeys`: three keys loaded; `wrote` naming one in `Reread` and a second through `Drop`; only the first loader runs again; the second is invalid (next peek misses); the third is untouched.
- - `TestWroteFailureLeavesEntryInvalid`: the re-read fails; `failed == 1`; the next peek is a miss, not the pre-write value.
+ - `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.
+ - `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.
- `TestHungLoadIsBoundedAndRetried`: with `viewLoadTimeout` shortened to 50 ms, a loader that blocks until its context ends; while it runs, peeks start no second goroutine; after it ends, the next peek of the stale entry starts one.
- `TestViewKeysAreAccountScoped`: `{Acct: "a", App: "api"}` and `{Acct: "b", App: "api"}` hold different values.
- `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|TestWrote|TestHungLoad|TestAsOfText' -count=1 -race`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestView|TestLoadInFlight|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, generations that cover in-flight loads, immutable values`, ending with the Co-Authored-By line.
+- [ ] **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.
### Task 7: Deferred parts
@@ -299,7 +306,9 @@ The rules the implementation keeps:
- 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.
-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. No polling and no retry: a part is fetched once per page view. With JavaScript off the `<noscript>` text stands, and a reload is a warm view because the miss started the load.
+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.)*
@@ -310,91 +319,66 @@ Every screen converted in Tasks 9 to 14 follows one shape: its template becomes
- `TestDeferredPartialsCarryTheirCopy`: executing `deferred` with `page{Deferred: "/x"}` gives `data-part="/x"`, CPF-26, and CPF-27 inside `<noscript>`; `asof` with a zero `AsOf` gives nothing and with one three minutes old gives CPF-20 with CPF-23.
- `TestAsOfShowsOnStaleData`: with `fx.clock` moved past `writtenWindow`, the part still answers `one` and now carries CPF-20.
- `TestGetAssembledFollowsParts`: a body holding one `deferred` div for the probe assembles to `one`.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEveryPartGates|TestPartRenders|TestPartFailure|TestDeferredPartials|TestAsOfShows|TestGetAssembled' -count=1`. Expected: FAIL.
+ - `TestNoDeferredFragmentHasAScript`: on `newPerfFixture` with every seed, for every key of `appParts` and `accountParts` (the tables, so later parts are covered without an edit) and every target `perfTargets` gives it, the fragment's body contains no `<script` (case-insensitive). Tasks 9 to 14 keep it passing.
+ - `TestPartLoaderFiresTheEvent`: the rendered `partloader` contains `carlos:part` and dispatches it after the `outerHTML` replacement (a source assertion on the partial; no browser in CI).
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEveryPartGates|TestPartRenders|TestPartFailure|TestDeferredPartials|TestAsOfShows|TestGetAssembled|TestNoDeferredFragmentHasAScript|TestPartLoaderFiresTheEvent' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement**; add CPF-26 to CPF-28 to `consolePerfCopyBuilt`. Add `route GET /a/{sqid}/apps/{app}/part/{part}` and `route GET /a/{sqid}/part/{part}` to `claim-routes.txt` in its sorted place; `claimFixtures` entries `claimRead("deferred part of an app page; the page's own gate")` and `claimRead("deferred part of an account page; the page's own gate")`; `claimReadProbes` entries `claimPageRead(nil, "/a/bab/apps/titogo/part/<a part Task 9 adds>", <its marker>)` and the account equivalent (until Tasks 9 and 14 add parts, point them at an unknown part name and expect the 404, then repoint them in those tasks). Add the two routes to `perfTargets` (one target per key of each table) and record each `deferred: deferred part`.
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestClaimRouteInventory|TestClaimFixture|TestClaimRead' -count=1`, `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`, `go test . -run TestConsolePerfCopy -count=1`, and the walk with `CI=1`. Expected: PASS.
- [ ] **Step 5: Commit**, message `console: deferred parts behind their page's own gate; loader script; route census entries`, ending with the Co-Authored-By line.
-### Task 8: Mutations declare their effect; the cache re-reads it inside the request
+### Task 8: A write invalidates exactly what it touched; the request re-reads it before answering
+
+The design, and why it replaces the declared-effect table. Three review rounds found effects missing from a hand-kept table (R1-2, R2-4, R3-3), each the same class: a write changed a key some cached read depended on, and nobody listed the pair. So the console now records the dependency instead of declaring it. Every cache entry records the keys its load read and the prefixes it listed (its read set). Every successful object-store write reports its key. A write invalidates, at once, every entry whose read set holds that key or a prefix of it. The request that wrote then re-reads those entries before it answers. Correctness then rests on two things a test can check directly, rather than on a list that has to be complete:
+
+1. **Every object-store access is reported.** The two stores the console runs on report every access through one hook. A table test covers every exported method, and fails when a method is added without coverage.
+2. **Two caching rules hold:**
+ - **(a) A cached value holds only facts read from the object store.** Anything joined from local state is joined per request, from the cached facts. That covers registry routes, SQLite rows and the clock. Task 9 does this for bake state and the production nudge. Task 13 does it for the route-derived hosts in `partEnvs`.
+ - **(b) A load whose set of keys comes from local state caches one entry per key.** Trash reads one tombstone per trashed app named in SQLite, so it caches one entry per tombstone (`trashPart(app)`). A newly trashed app is then a miss, never a stale list.
+
+What the read sets cannot see (data the cache does not hold) needs no effect, because the cache holds only object-store reads. Writes made by other processes are still covered by the windows. *(Session lead's request, round 3: "choose the simpler-to-prove design and say why". This is it. The declared table, `wroteView` and its census go.)*
+
+Admission falls out of the design. A refused request (session, CSRF, owner, confirmation page, validation error) writes nothing, so it invalidates nothing and re-reads nothing. A request that writes and then fails invalidates exactly what it wrote, which is correct.
**Files:**
-- Create: `internal/console/viewwrites.go`; Test: `internal/console/viewwrites_test.go`
-- Modify: `internal/console/claim_invariant_test.go` (`runClaimDoor` and its caller at `:312-340`: the mark witness)
-- Modify: every write door's handler (browser POSTs in `server.go`, `appsettings.go`, `appdomains.go`, `errorsview.go`, `analyticsview.go`, `controlplane.go`, `appswap.go`, `apitemporary.go`, `fleets.go`, `pipelinepage.go`, `pendinghandlers.go`, `ownership.go`, `storepage.go`, `economicspass.go`, `archpage.go`; the CLI's write doors in `apicli.go` and the `api*.go` files)
+- Modify: `internal/release/store.go` (`S3Store`: `SetObserver`, a report from each exported method), the `DirStore` file (`DirStore`: the same), `internal/release/changeindex.go` (the index's own raw read and write report too)
+- Create: `internal/release/observer_test.go`
+- Create: `internal/console/viewtrack.go`; Test: `internal/console/viewtrack_test.go`
+- Modify: `internal/console/server.go` (`Config.Track`; `NewServer` binds it), `internal/console/claim_routes.go:59-69` (`registerRoute`: non-GET, non-HEAD requests get a write set and the re-read writer)
+- Modify: `cmd/console/main.go` (`openStore` sets the observer on the store it opens; `serve()` passes the tracker in `Config.Track`); Test: `cmd/console/perfs3_test.go` (extend)
+- Modify: `internal/console/claim_invariant_world_test.go` (`newClaimCaseWith`: when an option sets `Config.Track`, the claim world's `DirStore` gets its observer), `internal/console/claim_invariant_test.go` (`runClaimDoor`: the coverage check)
**Interfaces:**
-- Consumes: `viewCache.wrote`, `viewEffect`, `registerProbePart`.
+- Consumes: `viewCache.touched`, `viewCache.reread`, `viewCache.snapshot`, `withReadSet`, plan 2 Task 2's `perfLatency.Keys`.
- Produces:
- - `type viewRule func(r *http.Request, acct *Account) viewEffect`
- - constructors, combinable with `writes(rules ...viewRule) viewRule`:
- - `writesApp(parts ...string) viewRule`: re-read `{acct.Sqid, r.PathValue("app"), part}` for each part.
- - `writesAppGone() viewRule`: drop every entry of `{acct.Sqid, app}`; re-read the account's `apps` and `trash` (rename, move to another account, delete).
- - `writesAccount(parts ...string) viewRule`: re-read `{acct.Sqid, "", part}`.
- - `writesAccountDrop(part string) viewRule`: drop every entry of the account whose `Part` is `part`, any app (an account-level telemetry change reaches every app's resolved telemetry).
- - `writesAccountOf(param string, parts ...string) viewRule`: re-read `{sqid, "", part}` for the account the path names in `param` (resolved by the same lookup the handler used), for an operator door acting on someone else's account.
- - `writesDeployment(parts ...string) viewRule`: re-read `{"", "", part}`.
- - `writesAppDropPrefix(prefix string) viewRule`: drop every entry of the app whose `Part` starts with `prefix` (every page of the version list).
- - `before(f func()) viewRule`: adds `f` to the effect's `Before`.
- - `type viewWriteDecl struct { Rule viewRule; None string }`: exactly one is set. `func effect(rules ...viewRule) viewWriteDecl` (the rules combined) and `func writesNone(reason string) viewWriteDecl` (the door changes nothing the cache holds; the reason is required) build table entries.
- - part-name constants used by every task: `partCore`, `func versionsPart(page int) string` (`versions?page=<n>`, one entry per Releases page; the Overview reads page 1), `partVersionsPrefix` (`versions?`), `partTags`, `partRetention`, `partInstancesManifest`, `partAppReport`, `partTelemetry`, `partGates`, `partClaims`, `partCertWarm`, `partCatchall`, `partDeployEmpty`, `partEnvs`, `partStore`, `partMail`, `partFeatures`, `partSwap`, `partApps`, `partTrash`, `partEntitlement`, `partAccountTelemetry`, `partFleetBoxes` (`fleet-boxes:<name>`, dropped by prefix), `partFleetJSON`, `partBoxes`, `partEdges`, `partMetrics`, `partEconomics` (`economics:<period>`, dropped by prefix), `partStorePending`, `partStoreUsage`, `partArchitecture`.
- - `var viewWrites map[string]viewWriteDecl`, keyed by the registered pattern (`claimEntry.Pattern`).
- - `func (s *Server) wroteView(r *http.Request, acct *Account)`: looks up `viewWrites[r.Pattern]`, calls `s.onViewMark(r, acct, e)` when that hook is set, and runs `s.views.wrote` with the effect on `context.WithTimeout(context.WithoutCancel(r.Context()), viewLoadTimeout)`. A pattern with no entry, or one declared `writesNone`, panics in tests and logs in production (the census and the witness below keep that from happening).
- - `Server.onViewMark func(r *http.Request, acct *Account, e viewEffect)`: an unexported test hook, nil in production.
-
-Where `wroteView` goes: in each write handler, after every gate and validation has passed and the write has returned success, before the handler writes its response (the redirect, the JSON, the claim-accepted page). Not in `account()`, not on a confirmation page (`handlePromote` renders `confirmPromote` before it writes, `server.go:4595`), not on a refusal or a validation error that redirects with a flash. A door whose success leaves the response to a helper calls it just before that helper. *(My call, per the session lead: marking where the mutation is known to have happened is the only place that can be proved; the table makes each door's effect reviewable in one place.)*
-
-The effect inventory, as a starting point the implementer completes by reading each door (the census test fails on any gap):
-
-| doors (browser and CLI) | rule |
-|---|---|
-| promote, roll back, production flag, fast-track, canary create and retire, pending confirm and reject, pipeline save | `writesApp(partCore)` |
-| ship | `effect(writesAppDropPrefix(partVersionsPrefix), writesApp(versionsPart(1)))` (a new version shifts every page; page 1 is re-read, the rest are misses) |
-| tag | `effect(writesApp(partTags))` |
-| retention | `effect(writesApp(partRetention), writesAppDropPrefix(partVersionsPrefix), writesApp(versionsPart(1)))` |
-| gate, rate limit | `writesApp(partGates)` |
-| domain attach and detach, catch-all | `writesApp(partClaims, partCatchall, partCertWarm)` |
-| swap policy | `writesApp(partSwap)` |
-| control plane set and clear, keep | `writesApp(partCore)` (the flags and lifetime they change are SQLite reads; `partCore` because the Overview header reads production state beside them; drop to `writesNone` if the door changes nothing remote) |
-| app error level, app analytics setting | `writesApp(partTelemetry)` |
-| account error level, account analytics setting | `writes(writesAccount(partAccountTelemetry), writesAccountDrop(partTelemetry))` |
-| store destroy | `writesApp(partStore, partEnvs)` |
-| config, secrets and environment doors | `writesApp(partEnvs)` |
-| mail doors | `writesApp(partMail)` |
-| feature doors | `writesApp(partFeatures)` |
-| place, instance create, delete, move | `writesApp(partInstancesManifest, partGates)` |
-| restart (app and instance), retry, browser updates | `writesNone("instance state is live data, refreshed within liveWindow")` unless the Running tab shows a value the door writes (check `browserrestart.go`; if so, `writesApp` of that part) |
-| rename, delete, move to another account | `writesAppGone()` |
-| new app, trash restore, trash purge | `writesAccount(partApps, partTrash)` |
-| store apply (member) | `writes(writesAccount(partEntitlement), writesDeployment(partStorePending))` |
-| store decision (operator, `POST /fleet/store/{account}/{decision}`) | `writes(writesAccountOf("account", partEntitlement), writesDeployment(partStorePending, partStoreUsage))` |
-| fleet rotate, detach, tags, place | `writesAccount(partFleetBoxes)` (prefix drop plus re-read of the named fleet) |
-| economics scenario, bill and tier saves | `effect(before(s.invalidateEconomics), writesDeployment(partEconomics))` (prefix drop of every period, re-read of the periods that were loaded; Task 15 defines `invalidateEconomics`) |
-| architecture refresh | `writesDeployment(partArchitecture)` |
-| invite, revoke invite, member remove and transfer, services, CLI tokens, sign-in and session doors, SES events | `writesNone(<what it writes: SQLite rows the console reads live>)` |
-| account delete | `effect(writesAccountDrop(""))` with `""` meaning every part of the account |
-
-In the table, rows built from the constructors above are wrapped in `effect(…)`; `writesNone` rows stand alone.
-
-**The witness inside `TestClaimConsoleMutationInvariant`.** That suite already drives every app-scoped write door in `claimFixtures` (each `claimDoor` on its own console, `claim_invariant_test.go:144-160`): a foreign run that must not mutate (`check(…, false)`) and an open run that must (`check(…, true)`). `runClaimDoor` gains the fixture key and, before each run, sets `cx.srv.onViewMark` to record the marks of that run (the pattern is the key without its `route ` prefix). After the runs it reports a problem when:
-- the open run's `check` passed (the mutation happened) and `viewWrites[pattern]` is not `writesNone`, but no mark for `pattern` was recorded: "<pattern> succeeded without declaring its view effect";
-- a run recorded a mark for a pattern other than its own (`r.Pattern`), or whose `Reread` keys differ from `viewWrites[pattern].Rule(r, acct).Reread` for the same request: "<pattern> marked an effect other than its declared one";
-- any foreign run recorded a mark: "<pattern> marked a write that did not happen";
-- the pattern is declared `writesNone` and a mark was recorded.
-
-Non-app doors (`claimNonApp` fixtures: account, operator and session doors) are not driven there; their coverage is the census plus the door tests below. *(Session lead's request: this turns "every door calls `wroteView` on success" from a review item into a test.)*
-
-- [ ] **Step 1: Write the failing tests** on `newPerfFixture`, with the probe part (`{fx.sqid, "kass", "probe"}`, here registered with `Part: partTelemetry` so the app error-level door's rule covers it) warm at `one`, then `two` written straight into `fx.rel` (uncounted):
- - `TestEveryWriteRouteDeclaresItsViewEffect`: every `claimEntry` route whose pattern is not `GET …` (method-less patterns included) has a `viewWrites` entry; no `viewWrites` key names a route that does not exist; every entry has exactly one of `Rule` and `None`, and every `None` is a non-empty reason.
- - The witness in `TestClaimConsoleMutationInvariant`, above. Prove it bites before Step 3 is finished: with `wroteView` deliberately left out of the promote handler, the suite reports `POST /a/{sqid}/apps/{app}/promote succeeded without declaring its view effect`; restore it.
- - `TestAppWriteRereadsItsScope`: Paul POSTs the app error level (`POST /a/<sqid>/apps/kass/errors/level`, with CSRF and a valid level); during the POST `probe.json` is read; after the 303, `ResetKeys()`; GET the probe part: `two` with zero S3 calls.
- - `TestRereadFailureLeavesEntryInvalid`: `SetFail` matching `probe.json` during the POST; clear it after; the next probe GET reads `probe.json` (a miss, not the old value) and answers `two`.
- - `TestRefusedWritesMarkNothing`, one sub-test each, all asserting `probe.json` is not read during the request and Paul's next probe GET makes zero S3 calls and still answers `one`: a CSRF failure; a second signed-in user who is not a member (404); a plain member on the owner-only door (404); a validation error (an unknown level, whatever status the handler answers today); a promote that stops at its confirmation page (`POST …/promote` without the confirm field, with the probe registered as `partCore`).
- - `TestCLIWriteRereadsItsScope`: the same app-level change through its CLI door with a CLI token (an existing `apicli` test shows how to mint one).
- - `TestWriteEffectsReachOtherScopes`: with an account-level probe registered at `{fx.sqid, "", partEntitlement}`, the operator's store decision for `fx.sqid` (with Paul in `Config.StoreOperators`) re-reads it.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEveryWriteRouteDeclares|TestAppWriteRereads|TestRereadFailure|TestRefusedWrites|TestCLIWriteRereads|TestWriteEffectsReach' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement** the constructors, the table and the `wroteView` calls.
-- [ ] **Step 4: Run** Step 2's command, 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 witness reports no problem for any door). Expected: PASS.
-- [ ] **Step 5: Commit**, message `console: every mutation declares its view effect after it succeeds; the cache re-reads it inside the request`, ending with the Co-Authored-By line.
+ - `internal/release`: `type AccessOp int` with `AccessRead`, `AccessList`, `AccessWrite`; `type AccessObserver func(ctx context.Context, op AccessOp, key string)`; `func (s *S3Store) SetObserver(f AccessObserver)` and `func (s *DirStore) SetObserver(f AccessObserver)`. Reads (`Get`, `Open`, `GetIfChanged`) report the key before the request goes out. Listings (`List`, `ListMod`, `ListPage`, `ListDirs` with its trailing `/` added, `ListETags`, `ListSizes`) report the prefix before the request goes out. Writes (`Put`, `PutFrom`, `Delete`, `DeleteIfMatch`, and the change index's own write) report the key after the store has acknowledged the write. A failed write reports nothing. Set it before the store is shared; it is not synchronised.
+ - `internal/console`: `type StoreTracker struct{…}`; `func NewStoreTracker() *StoreTracker`; `func (t *StoreTracker) Observe(ctx context.Context, op release.AccessOp, key string)`; `Config.Track *StoreTracker`.
+ - On a read or a listing, it adds the key or prefix to the read set in `ctx`, if any.
+ - On a write, it calls `views.touched(key)` and adds the invalidated entries to the request's write set in `ctx`, if any.
+ - One mutex orders it with `touched`. A load records a key before it reads, and a write is checked after it lands, so a read that saw the old value is always caught. The only read that can escape the check is one that started after the write, and that read saw the new value.
+ - `NewServer`: with `Config.Track` set, binds it to `s.views` and the cache is on. With it nil, the cache is off: `viewGet` in either mode runs the loader inline on the request's own context, with no entry and no placeholder. *(My call: a store the console cannot observe could not be invalidated, so it is never cached.)* Production always sets it: `cmd/console`'s `openStore` sets the observer on the `S3Store` or `DirStore` it opens.
+ - The default test fixtures build on `deletableStore` and pass no tracker. Their tests therefore run every read inline, exactly as today. That is plan 1's deliberately synchronous seam, and it keeps plan 1's instrumentation tests meaningful (Task 11).
+ - `newPerfFixture` passes one, as does the claim world (this task), so the cached path is tested where it is turned on.
+ - `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.
+ - 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:**
+ - `TestStoreObserverCoversEveryMethod` (`internal/release`): one table row per exported method of `*S3Store` (against the S3 fake) and of `*DirStore`. Each row calls the method and asserts the op and key reported; writes are reported only after success, and a refused conditional `Put` reports nothing. The test compares the table's method names with `reflect` over both types, so a method added without a row fails.
+ - `TestReadRecordedBeforeAWriteIsNeverLost` (`internal/console`, `-race`, 1,000 iterations): a load that records `k` and reads it, racing a write of `k` and its `touched`. The entry never ends valid holding the pre-write value.
+ - `TestUntrackedServerReadsInline`: `newConsoleFixture` (no tracker): the first GET of the Overview has no `data-part` and shows `v1`, and `fx.srv.views.snapshot()` is empty afterwards.
+ - `TestProductionStoreIsObserved` (`cmd/console`): `openStore(rec)` over `CARLOS_DEPLOYMENT_DIR` and over the S3 fake both return a store whose observer feeds the tracker `serve()` passes in `Config.Track` (exercise the wiring helper `serve()` uses).
+ - Warm-before-write acceptance, on `newPerfFixture`. For each case: view the screens, `waitBackground`, `snapshot`; do the write through its real door; `waitBackground`, `snapshot`. Pass both snapshots, with the keys the S3 fake saw written (`Writes()`: the oracle, independent of the tracker), to `assertWriteCoverage`. Then check the screen shows the new state with zero S3 requests on its next view. The cases Astra named, and the earlier ones:
+ - `TestShipRefreshesDeployEmpty`: a new app `shop` with no routes; its General section warm (deploy-empty answers empty); ship `v1` through the CLI ship door; General no longer says the app is empty.
+ - `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.
+ - 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.
### Task 9: App core through the cache: every app tab's shared reads
@@ -409,10 +393,10 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential,
**Interfaces:**
- Produces:
- `type appCore struct { Channels []ChannelView; ProductionFlag *release.ProductionFlag; ProductionErr error; Pipeline *release.Pipeline; PipelineErr error }` with `viewClone` (copies `Channels`; the two pointers are read-only), and `func loadAppCore(ctx context.Context, s release.Store, pub ed25519.PublicKey, acct, app string) (appCore, error)`: `assembleChannels`, `release.GetProduction` and `release.GetPipeline`, under `ctx`. It holds only what is read remotely, and only facts that do not change with the clock: every cached `ChannelView` has a zero `BakedUntil`, and the core keeps `PromotedAt`, `FastTrack` and the channel name from which it is derived. *(Astra round 2, finding 6.)*
- - `assembleChannels` loses its `now` parameter and its bake computation (`view.go:749-753`); `func channelBakes(channels []ChannelView, pipe *release.Pipeline, prod ProductionView, now time.Time)` sets `BakedUntil` on the request's copy: the legacy hold (`release.HoldFor(release.DefaultHolds, name)`) when there is no pipeline, the pipeline's `holdWindow` when there is (what `applyPipelineView` does today, `server.go:3480-3490`), cleared for fast-tracked channels and when production is off (`view.go:615-626`). `Assemble` and `applyPipelineView` call it with `s.now()`; the ladder is rebuilt from its result. Production's turning-off estimate is already derived per request in `productionView`.
+ - `assembleChannels` loses its `now` parameter and its bake computation (`view.go:749-753`); `func channelBakes(channels []ChannelView, pipe *release.Pipeline, prod ProductionView, now time.Time)` sets `BakedUntil` on the request's copy: the legacy hold (`release.HoldFor(release.DefaultHolds, name)`) when there is no pipeline, the pipeline's `holdWindow` when there is (what `applyPipelineView` does today, `server.go:3480-3490`), cleared for fast-tracked channels and when production is off (`view.go:615-626`). `Assemble` calls it with its `now` argument and `applyPipelineView` with `s.now()`; the ladder is rebuilt from its result. Production's turning-off estimate is already derived per request in `productionView`.
- `func productionView(flag *release.ProductionFlag, err error, channels []ChannelView, routes []RouteView, now time.Time) ProductionView` (`now` is `s.now()`): `assembleProduction` minus its read (`view.go:763`), so the route-dependent nudge (`:794-803`) is still computed from the request's routes. *(Astra finding 6: the routes are a local registry read and are never cached.)*
- - `Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets, core func(app string) (appCore, error)) ([]AppView, error)`: routes come from `memoRoutes`; each app's channels, production flag and pipeline from `core`; `productionView`, the channel post-processing at `:615-626` and the ladder run on the request's own copy. An error from `core` is returned (callers map `errViewPending` to the placeholder).
- - `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.
+ - `Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets, now time.Time, core func(app string) (appCore, error)) ([]AppView, error)`: `now` is explicit (screens pass `s.now()`, tests their clock, `storeCore` callers `time.Now()`), so the clock-dependent derivation below has a clock; routes come from `memoRoutes`; each app's channels, production flag and pipeline from `core`; `productionView`, the channel post-processing at `:615-626` and the ladder run on the request's own copy. An error from `core` is returned (callers map `errViewPending` to the placeholder).
+ - `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.
@@ -421,12 +405,13 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential,
- `TestOverviewWarmMakesNoRemoteCalls`: `getAssembled` `/apps/kass` and quiesce; reset counts; GET: zero S3 and zero host calls, 200, shows `v1` on `stable`.
- `TestOverviewColdArrivesWithAPlaceholder`: fresh `newPerfFixture`, latency on: the first GET's time to first byte is under 150 ms and the body has `data-part` for `overview`; `getAssembled` shows `v1`.
- `TestBakeStateFollowsTheClockNotTheCache`: a legacy app (no pipeline) with production on and `stable` promoted 10 minutes ago, warm; the Releases page shows the bake delay and its skip control; move `fx.clock` past the hold's end (the cached core is now stale but still served); the next GET shows no bake delay and no skip control, before any refresh has finished (hold the refresh with `HoldNext("get", …)` on the channel pointer). The same with a pipeline's own window.
+ - `TestDeferredReadsCountAsBackground`: on `newPerfFixture`, a cold Overview: its sample's `Calls["s3"]` is 0 and `fx.srv.PerfBackground()["s3"]` rose by the fake's request count for that load. Plan 1's `TestOverBudgetPageIsLogged` still passes on its untracked fixture, where the Overview's reads run inline on the request (the synchronous seam); if its only slow read was the account manifest, it now sleeps on every `Get`.
- `TestProductionNudgeStillUsesRoutes`: with production off and a stable route present, the Overview shows the production-wiring nudge exactly as before; with no such route it does not.
- `TestSameAppNameInTwoAccountsNeverShares`: a second account owning an app `kass` with a different channel version; each member sees only their own version, warm.
- `TestConcurrentViewsShareNoState` (run with `-race`): warm Overview, Activity and account review (and, as Tasks 10 to 14 land, their screens: the test walks `appParts` and `accountParts`); eight goroutines each `getAssembled` every one five times; every body for one URL is identical to the first.
- `TestActivityAndAccountReviewWarmMakeNoCalls`.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOverview|TestBakeStateFollowsTheClock|TestProductionNudge|TestSameAppNameInTwoAccounts|TestConcurrentViews|TestActivityAndAccountReview' -count=1 -race`. Expected: FAIL.
-- [ ] **Step 3: Implement.** Convert this task's screens' existing tests to `getAssembled` where they assert on the body (start from `grep -n 'apps/kass")\|/activity\|account-review' internal/console/*_test.go`), including `TestOverviewIsALadderNotAnEverythingPage`, `TestRecentActivity`, `TestActivityTab`, `TestAppPageInstances`, `TestAppPageRendersDomains`. Repoint Task 7's app-part probe at `overview`.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOverview|TestBakeStateFollowsTheClock|TestDeferredReadsCountAsBackground|TestOverBudgetPageIsLogged|TestProductionNudge|TestSameAppNameInTwoAccounts|TestConcurrentViews|TestActivityAndAccountReview' -count=1 -race`. Expected: FAIL.
+- [ ] **Step 3: Implement.** The existing tests of these screens run on the untracked fixture and need no change. Run `TestOverviewIsALadderNotAnEverythingPage` and `TestRecentActivity` on `newPerfFixture` as well, through `getAssembled`. Repoint Task 7's app-part probe at `overview`.
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestAssemble|TestAppPage|TestOverviewIsALadder|TestRecentActivity|TestActivityTab|TestAccountReview|TestAppTabBar|TestClaimRead' -count=1`, and the walk with `CI=1`.
- [ ] **Step 5: Delete** the `over:` records for `GET /a/{sqid}/apps/{app}`, `GET /a/{sqid}/apps/{app}/activity` and `GET /a/{sqid}/apps/{app}/account-review`; walk with `CI=1` (PASS); commit, message `console: app core, Overview, Activity and account review read through the view cache`, ending with the Co-Authored-By line.
@@ -446,12 +431,13 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential,
- [ ] **Step 1: Write the failing tests:**
- `TestReleasesWarmMakesNoRemoteCalls` (same shape as Task 9's).
- `TestReleasesLiveNowRendersWhileVersionsLoad`: the core warmed through Activity (which reads no versions; the Overview would warm page 1) and the version list never viewed: the first Releases GET has `id="live-now"` with its Roll back and a `data-part` for `releases-versions`.
- - `TestReleasesPagesAreCachedApart`: with 23 versions (the nav test's setup), warm pages 1 and 2; each warm GET makes zero S3 requests; page 1 has 20 rows and `rel="next"`, page 2 has 3 rows and `rel="prev"`; a ship of one more version makes page 2 a miss (the drop) and page 1 a re-read inside the ship request, after which page 1 starts with the new version.
+ - `TestReleasesPagesAreCachedApart`: with 23 versions (the nav test's setup), warm pages 1 and 2; each warm GET makes zero S3 requests; page 1 has 20 rows and `rel="next"`, page 2 has 3 rows and `rel="prev"`; a ship of one more version writes under the releases prefix both pages listed, so both are invalidated by read set and re-read inside the ship request, after which page 1 starts with the new version and page 2 starts with the version page 1 used to end on.
- `TestPromoteShowsTheNewVersionOnTheNextView`: warm `/apps/kass/releases`; promote `v2` to `stable` through the browser form (with its confirmation step); 303; `ResetKeys()`; `getAssembled` the redirect target: zero S3 calls and `v2` on `stable`.
- `TestPromoteDuringABackgroundRefreshShowsTheNewVersion`: warm; move `fx.clock` past `writtenWindow`; `HoldNext("get", …)` on the `stable` channel pointer key; a GET starts a refresh, which reads `v1` and blocks (wait for `held`); promote `v2` (the promote's own read of the pointer is not held, since `HoldNext` holds one read); `release()`; quiesce; the next GET shows `v2`, never `v1`.
+ - `TestPromoteCoverage`: the promote case through `assertWriteCoverage` (Task 8).
- `TestCLIPromoteShowsInTheBrowser`: the same promote through the CLI door; the next browser GET shows `v2` with zero S3 calls.
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestReleasesWarm|TestReleasesLiveNowRenders|TestReleasesPagesAreCachedApart|TestPromoteShows|TestPromoteDuring|TestCLIPromoteShows' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement.** Convert to `getAssembled`, keeping every assertion: `TestReleasesTab` (`server_test.go:514`), the nav plan's `TestReleasesPageOrder`, `TestReleasesPageHasOneRollBack`, `TestReleasesOlderVersionsAreReachable` (its 23-version page 1 and page 2 assertions, read assembled; it must pass unchanged in substance), `TestVersionsPageMatchesVersionsOnPageOne`, `TestDeploymentRoutesAndHistory`, `TestNoLinkPointsAtDeployments`, `TestOneChannelAppHidesChannelVocabulary`, `TestOneChannelAppKeepsCanariesAndRollback`, `TestChannelsTableAndPipelineCardAgreeOnBakeWindow`, `TestReleaseSummaryStripRenders`, `TestFirstPromoteChannelOptions`. `TestReleasesLiveNowSurvivesListingFailure` (`fx.srv.cfg.Releases = listFailStore{fx.rel}`) keeps its assertions on the assembled page: 200, "Could not list this app", `id="live-now"` and the instances link. Update the claim probe for `GET …/releases` if its marker moved into a part.
+- [ ] **Step 3: Implement.** These keep passing unchanged on the untracked fixture, and each also runs on `newPerfFixture` through `getAssembled` with every assertion kept (a helper `onBothFixtures(t, func(t *testing.T, fx *consoleFixture, get func(path string) string))`): `TestReleasesTab` (`server_test.go:514`), the nav plan's `TestReleasesPageOrder`, `TestReleasesPageHasOneRollBack`, `TestReleasesOlderVersionsAreReachable` (its 23-version page 1 and page 2 assertions, read assembled; it must pass unchanged in substance), `TestVersionsPageMatchesVersionsOnPageOne`, `TestDeploymentRoutesAndHistory`, `TestNoLinkPointsAtDeployments`, `TestOneChannelAppHidesChannelVocabulary`, `TestOneChannelAppKeepsCanariesAndRollback`, `TestChannelsTableAndPipelineCardAgreeOnBakeWindow`, `TestReleaseSummaryStripRenders`, `TestFirstPromoteChannelOptions`. `TestReleasesLiveNowSurvivesListingFailure` keeps its assertions on both: on the untracked fixture as written (`fx.srv.cfg.Releases = listFailStore{fx.rel}`); on `newPerfFixture` with `SetFail` matching listings of the releases prefix. Both must show 200, "Could not list this app", `id="live-now"` and the instances link. Update the claim probe for `GET …/releases` if its marker moved into a part.
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestReleases|TestDeployment|TestNoLinkPointsAtDeployments|TestOneChannelApp|TestChannelsTableAndPipelineCard|TestReleaseSummary|TestFirstPromote|TestPromoteFlow|TestRollbackFlow|TestCanaryFlow|TestRetireCanary|TestClaimRead' -count=1`, and the walk with `CI=1`.
- [ ] **Step 5: Delete** the `over:` record for `/releases`; walk (PASS); commit, message `console: Releases reads through the view cache; Versions loads as its own part`, ending with the Co-Authored-By line.
@@ -476,8 +462,8 @@ Spec §2.4 C row `instances.Report`: HTTP to the app host, 30 s cache, blocks up
- `TestRunningTabNeverWaitsOnTheAppHost`: `HostDelay` 1 s; a cold Running tab answers within 150 ms with the instances table and a `data-part` for `instances-report`; after quiesce the report shows; exactly one host call was made.
- `TestAppReportNeverWakesAHibernatingHost`: with every route `Hibernate`, no host call is ever made (the rule at `instances.go:83-92`).
- `TestInstancePartRefusesAForeignHost`: `/apps/kass/part/instance?host=otherapp.carlosapp.dev` (the fixture's other app's route) is the same 404 the page gives for that host, with no S3 call.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestRunningWarm|TestInstancePageWarm|TestRunningTabNeverWaits|TestAppReportNeverWakes|TestInstancePartRefuses' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement.** Convert this task's screens' tests to `getAssembled` (the nav plan's `TestRunningTabHeadingAndToolbar`, `TestRunningLeftoversNameTheTab`, `TestInstancesTab`, `TestInstancesEmptyStateHintsStable`, `TestInstancesTabRegionLine`, `TestBrowserRestart*`, the instance page tests) and their claim probes.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestRunningWarm|TestInstancePageWarm|TestRunningTabNeverWaits|TestAppReportNeverWakes|TestInstancePartRefuses|TestRunningTabTimesTheAppHost|TestDeferredAppReportCountsAsBackground' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement.** This task's existing tests run unchanged on the untracked fixture. Plan 1's `TestRunningTabTimesTheAppHost` stays meaningful there: the report is fetched inline on the request, so the `box` span is in its `Server-Timing`. Add `TestDeferredAppReportCountsAsBackground`: on `newPerfFixture`, a cold Running tab's sample has no `box` call, `PerfBackground()["box"]` rose by one, and the `instances-report` part's assembled body has the report. Update the claim probes whose markers moved into a part.
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestInstancesTab|TestRunningTab|TestRunningLeftovers|TestInstancePage|TestBrowserRestart|TestBrowserUpdates|TestInstanceReport|TestClaimRead' -count=1`, and the walk with `CI=1`.
- [ ] **Step 5: Delete** the `over:` records for `/instances` and `/instances/{host}`; walk (PASS); commit, message `console: Running and the instance page read through the view cache; the app's self-report is a deferred part`, ending with the Co-Authored-By line.
@@ -492,17 +478,18 @@ Spec §2.4 C row `instances.Report`: HTTP to the app host, 30 s cache, blocks up
- Produces:
- `func viewFilterKey(prefix string, filter any) string`: `prefix + "?" +` the hex SHA-256 of the canonical JSON encoding of the effective filter the loader runs with (`applog.Filter` after `browserLogsFilterFromQuery` and the page's default window; the errors, availability and analytics option structs after their own parsing). It keys on what the read will actually do, losslessly: no trimming, no truncation, no parameter the loader ignores. Two requests share an entry exactly when their loads would read the same thing. *(Astra round 2, finding 5.)* Time-relative filters ("the last hour") are made absolute by the parser; the key then carries the window's start rounded down to `liveWindow`, so a view within the same 30 s shares the entry and a later one does not.
- `func (s *Server) logWindowView(ctx context.Context, p *page, mode viewMode, sqid, app string, f applog.Filter, key string) (logWindow, error)`: the first window of rows for a filter (`applog.ReadWindow`, `{sqid, app, viewFilterKey("logs", f)}`, `liveWindow`, a `logWindow` with `viewClone`), shared by the page and by `/logs/data`. `handleAppLogs` reads it in `viewCached` mode: a miss renders the table empty with `data-load-now` on the form, and the existing script (`app_logs.html:66-196`) calls its fetch of `/logs/data` once at load without starting to follow. `handleAppLogsData` without a `cursor` reads the same entry in `viewBlocking` mode, so it joins the load the page started instead of reading the window again; with a `cursor` (following) it reads as today, uncached. *(Astra finding 10.)*
- - the host picker (`ListRecordHosts`, `{sqid, app, "record-hosts"}`, `liveWindow`).
+ - the host picker (`ListRecordHosts`, `{sqid, app, partRecordHosts}`, `liveWindow`) as its own part `logs-hosts`: the `<select name="host">` element alone, from the template's existing markup with the current `?host=` selected. On a miss, the page renders the picker from the routes it already has (local) and a placeholder for the select. The loader replaces it with the full list; with JavaScript off, a reload shows it. The select keeps its `name`, so the filter form submits it as before, and it holds no script. *(Astra round 3, finding 4.)*
- parts `errors`, `availability`, `analytics`; reads through `viewGet`: `telemetry.Resolve` (`{sqid, app, partTelemetry}`, `writtenWindow`; the error-level and analytics-setting doors re-read it, Task 8), `apperr.ReadWindow` and the platform-stream `applog.ReadWindow` (`viewFilterKey("errors", …)`, `viewFilterKey("availability", …)`, `liveWindow`), `analytics.ReadRange` (`viewFilterKey("analytics", …)`, `liveWindow`).
- [ ] **Step 1: Write the failing tests:**
- `TestLogsWarmMakesNoRemoteCalls`.
+ - `TestColdLogsFillsTheHostPicker`: with a record-only host (an instance record with no route), the cold page's picker lacks it; `getAssembled` of the page has it in the `select`, still `name="host"`; selecting it (`?host=<it>`) is preserved in the assembled select.
- `TestColdLogsReadTheWindowOnce`: fresh fixture; GET `/apps/kass/logs` (cold: `data-load-now`, no rows); GET `/logs/data` with the page's own query and no cursor; across both, the log prefix's listings appear in `Keys()` exactly as many times as one `ReadWindow` makes them; `/logs/data` answers the rows.
- `TestLogsFollowStillReadsLive`: a `/logs/data` with a cursor reads the store each time.
- `TestErrorsAvailabilityAnalyticsWarmMakeNoCalls`.
- `TestFilterKeysAreLossless`: `?since=1h&host=a` and `?host=a&since=1h&junk=x` share one entry (same effective filter); `text=failed` and `text=%20failed` do not; two 300-byte searches that differ only in their last byte do not.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLogsWarm|TestColdLogsRead|TestLogsFollow|TestErrorsAvailabilityAnalytics|TestFilterKeysAreLossless' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement.** Convert this task's screens' tests (the nav plan's `TestLogsToolbar`, `TestTelemetryHintsLinkTheSection`, `TestAppLogs*`, `TestAppErrors*`, `TestAppAvailability*`, `TestAppAnalytics*`) to `getAssembled` and their claim probes.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLogsWarm|TestColdLogsFillsTheHostPicker|TestColdLogsRead|TestLogsFollow|TestErrorsAvailabilityAnalytics|TestFilterKeysAreLossless|TestInstanceCreateRefreshes' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement.** Existing tests run unchanged on the untracked fixture; run the nav plan's `TestLogsToolbar` on `newPerfFixture` too, through `getAssembled`. Remove `TestInstanceCreateRefreshesHostsAndEnvs`' skip (Task 8) once Environments is cached in Task 13, if it is not yet. Update claim probes whose markers moved.
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestAppLogs|TestLogsToolbar|TestAppErrors|TestAppAvailability|TestAppAnalytics|TestErrorLevel|TestAnalyticsSetting|TestTelemetryHints|TestClaimRead' -count=1`, and the walk with `CI=1`.
- [ ] **Step 5: Delete** the `over:` records for `/logs`, `/errors`, `/availability`, `/analytics`; walk (PASS); commit, message `console: Logs, Errors, Availability and Analytics read through the view cache; the first log window is read once`, ending with the Co-Authored-By line.
@@ -516,7 +503,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`), `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 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).
- [ ] **Step 1: Write the failing tests:**
- `TestEverySettingsSectionWarmMakesNoCalls` (one sub-test per key of `appSettingsSections`, with the populated seeds).
@@ -525,7 +512,7 @@ Spec §2.4 C rows `settingsGates` (cache), `aliasReadings`/`LoadBoxes` (cache, o
- `TestPipelineSaveShowsTheNewPipeline`: warm the pipeline section; save a changed pipeline; the redirect target shows it with zero S3 calls.
- `TestRenameFailureRerendersWithoutStaleData`: the existing rename-failure re-render (`renderAppSettingsForm`) still shows its message and the current values.
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEverySettingsSection|TestDomainsArrives|TestDomainAttachShows|TestPipelineSaveShows|TestRenameFailureRerenders' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement.** Convert the settings tests to `getAssembled` (the nav plan's `TestAppSettingsSectionRoutes`, `TestErrorsAndAnalyticsSection`, `TestAppSettingsPlacementSection`, `TestAppSettingsPlacementShowsFleet`, `TestPipelineSettingsCanonicalSectionURL`, and the existing settings, domain, gate, store and control-plane tests that read a section body) and the `settings/{section}` claim probe.
+- [ ] **Step 3: Implement.** Existing settings tests run unchanged on the untracked fixture; run the nav plan's `TestAppSettingsSectionRoutes` and `TestErrorsAndAnalyticsSection` on `newPerfFixture` too. Remove the skips of `TestShipRefreshesDeployEmpty` and `TestInstanceCreateRefreshesHostsAndEnvs` (Task 8). Update the `settings/{section}` claim probe if its marker moved.
- [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestAppSettings|TestBucketless|TestDomain|TestAppGate|TestAppRateLimit|TestStoreDestroy|TestPipeline|TestAppSwap|TestControlPlane|TestErrorsAndAnalyticsSection|TestClaimRead' -count=1`, and the walk with `CI=1`.
- [ ] **Step 5: Delete** the `over:` records for the settings sections and `/settings`; walk (PASS); commit, message `console: settings sections read through the view cache; box readings deferred on Domains`, ending with the Co-Authored-By line.
@@ -537,20 +524,23 @@ 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 (`{sqid, "", partTrash}`, `writtenWindow`), 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`; 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.
+- `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.
- `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|TestAccountPartsKeepOwnerOnly' -count=1`. Expected: FAIL.
-- [ ] **Step 3: Implement.** Convert the account pages' tests to `getAssembled` (the nav plan's `TestPageHeadsOnAccountPages`, `TestTrashDeleteSitsInItsRow`, `TestAccountSettingsFormsUseSettingsRow`, and `TestEmptyStateWelcomesNewUser`, `TestCreateApp`, `TestAccountSettingsPage`, the fleet page and trash tests) and their claim probes; repoint Task 7's account-part probe at `apps`.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAccountPagesWarm|TestAccountHomeShares|TestNewAppAppears|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.
-### Task 15: Operator pages: shared loaders and write effects for Part 3
+### Task 15: Operator pages: shared loaders for Part 3
Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the shape of their handlers. This task changes neither; it provides the loaders Part 3's Task 13 consumes. Order: this task lands (with the rest of plan 2) before Part 3's Task 13, which repoints Part 3's seam functions `opFleetJSON`, `opHostRows` and `opStorePending` (Part 3 Task 8) at `fleetJSONView`, `hostRowsView` and `storePendingView`, adds a `mode viewMode` parameter to each, adds `/fleet/part/{part}` and deletes the operator `over:` records.
@@ -565,24 +555,25 @@ Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the sha
- `func (s *Server) fleetJSONView(ctx context.Context, p *page, mode viewMode) (*status.Fleet, error)` (`{"", "", partFleetJSON}`, `liveWindow`; 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, whose own 60 s cache stays underneath)
- - `func (s *Server) economicsView(ctx context.Context, p *page, mode viewMode, period string) (*EconomicsView, error)` (`economics:<period>`; `LoadEconomics`' own cache, `economicsview.go:283-300`, stays underneath for views)
- - `func (s *Server) invalidateEconomics()`: the `Before` hook of every economics save (Task 8). It empties `LoadEconomics`' inner cache and bumps a generation the inner cache gains, so an inner sweep that started before the save cannot store its result, and the outer re-read that follows sweeps fresh instead of being handed the pre-save value from the inner cache. *(Astra round 2, finding 4.)*
+ - `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`)
- 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.
-- The write effects for operator doors are Task 8's table rows (store decision, economics saves, architecture refresh); this task adds tests for them.
+- 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.
- [ ] **Step 1: Write the failing tests:**
- `TestOperatorPagesWarmMakeNoRemoteCalls` (one sub-test per page, Paul as operator and store operator).
- `TestStoreQueueRefusedOperatorStartsNoLoad`: an operator not in `Config.StoreOperators` GETs `/fleet/store`: the same 404 as today, and `perfLatency.Calls()` is unchanged, no `store-pending` load started.
- `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` so both the outer entry and `LoadEconomics`' inner entry are fresh; save a changed active scenario; follow the redirect: the page shows the new scenario. Again with an inner sweep held in flight (`HoldNext("list", …)` on one of its listings) when the save lands: after release, the page still shows the new scenario.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestStoreQueueRefused|TestStoreDecisionShows|TestEconomicsSaveShows' -count=1`. Expected: FAIL.
+ - `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.
- [ ] **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: Delete** the `over:` records of every operator screen whose reads now go through the loaders (the walk measures warm views). In the second case, the records Part 3 wrote for screens behind its seams (`GET /fleet`, `GET /fleet/boxes`) stay, with Part 3's reason ("until operator-pages Task 13"), and Part 3's Task 13 deletes them. Walk (PASS); commit, message `console: cache-backed loaders and write effects for the operator pages, for Part 3`, ending with the Co-Authored-By line.
+- [ ] **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.)*
### Task 16: The console DB: measure, then decide on a read pool
@@ -608,7 +599,7 @@ Spec §2.4 C last row: `SetMaxOpenConns(1)` (`store.go:99`, `store_gate.go:1828`
- Modify: `internal/console/testdata/perf-budgets.txt`, `internal/console/testdata/perf-session-s3.txt`
- Create (by the tool): the census overlay and `docs/superpowers/notes/census-proposal-console-perf-2.md`
-- [ ] **Step 1: The file holds no `over:` records** apart from operator screens Part 3 recorded "until operator-pages Task 13" (Task 15's second case), which that task deletes, so the file is empty of `over:` lines by the end of the round. `grep ' over:' internal/console/testdata/perf-budgets.txt` prints nothing else. Any record left is a `skip:`, `deferred:` or `calls <n>:` line with a reason; a `calls` record names the call and why no cache can hold it.
+- [ ] **Step 1: The file holds no `over:` records** apart from the operator screens recorded "blocks on a cold view until operator-pages Task 13" (Task 15), which that task deletes, so the file is empty of `over:` lines by the end of the round. `grep ' over:' internal/console/testdata/perf-budgets.txt` prints nothing else. Any record left is a `skip:`, `deferred:` or `calls <n>:` line with a reason; a `calls` record names the call and why no cache can hold it.
- [ ] **Step 2: The walk passes with `CI=1`** in under 10 s, its cold pass included (every screen's first response, from a console reset by `resetForColdView`, within 150 ms), and the nav plan's `TestReleasesOlderVersionsAreReachable` passes: `CI=1 go test ./internal/console/ -run TestConsoleScreensMeetTheBudget -count=1 -v`. Update the row in `.amadan/test-weights.tsv`.
- [ ] **Step 3: Total S3 use went down.** Run `TestPerfSessionS3Requests`; it prints the session's total, which counts cold views, deferred loads, the promote's own re-read and repeat views. It must be below plan 1's recorded ceiling; write the new total into `perf-session-s3.txt` with the reason `after plan 2, <date>` so a later change cannot raise it unnoticed. If it is not below, the cache is costing more than it saves: stop and find the read before going on.
- [ ] **Step 4: Census card**, as plan 1 Task 11 Step 1 (`NAME=console-perf-2`), CLAIMS naming each changed unit: cached reads of the same keys, no read added; `internal/provision` gains `ListRecordHosts`, a listing the unit already made. Approval by a reviewer of the other model family, recorded on #280.
@@ -621,6 +612,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 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).
- **Names used from plan 1:** listed under "Depends on". This plan adds `Keys`, `ResetKeys`, `SetFail`, `HoldNext`, `OnPut` to `perfLatency`, and `Assemble` gains the `core` parameter (Task 9).
diff --git a/docs/superpowers/plans/2026-10-25-operator-pages.md b/docs/superpowers/plans/2026-10-25-operator-pages.md
index dd0c1210a..7cc95f30c 100644
--- a/docs/superpowers/plans/2026-10-25-operator-pages.md
+++ b/docs/superpowers/plans/2026-10-25-operator-pages.md
@@ -12,7 +12,7 @@
**Related plans, consumed by exact name (do not re-plan their work):**
- Plan 1, `2026-10-25-console-perf-1-measure.md` (must be merged before this branch is cut): `internal/perf`, `consolePerfSkip`, `Server.PerfGroups`, `consoleSpeedRows` and the Console speed section of `metrics.html`, `newConsoleFixtureWith`, `newPerfFixture`, `perfTargets`, `perfInventory`, `loadPerfBudgets`, the `perf-budgets.txt` grammar (`over:`, `calls <n>:`, `deferred:`, `skip:`), `TestConsoleScreensMeetTheBudget`, `writeTemplate`.
-- 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`; Task 8's `viewWrites` and `wroteView`; 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.
+- 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.)*
@@ -25,6 +25,7 @@ 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.
+- **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.
- **Targeted local tests.** `go test ./internal/console/ -run 'TestName' -count=1`; never `make test`, never a whole-package run. `TestClaimConsoleMutationInvariant` only under `nice -n 19`, once per task that changes routes. `gofmt -l .` empty, `go vet ./internal/console/ ./cmd/console/`, `GOOS=darwin GOARCH=arm64 go build ./...` and `GOOS=windows GOARCH=amd64 go build ./...` before every push. `GOFLAGS=-buildvcs=false` if the sandbox refuses VCS stamping.
@@ -71,7 +72,8 @@ Each is marked *(my call)* where it appears in a task.
- **Last seen** is written by `session()`, by `cliRoute` for person principals (`PrincipalUser`), by `cliUser`, and by `finishSignin`: at most once an hour per address per process, `UPDATE users SET last_seen = ? WHERE address = ? AND last_seen < ?`. The hour is reserved atomically: one mutex guards the check and the reservation together (`Server.seenMu`, `Server.seen map[string]time.Time`), and the write happens after the lock is released, so concurrent requests after expiry make exactly one write attempt.
- **Job registry:** keyed by the claim worker names (`claim_workers.go`), seeded at `NewServer` as "Not run yet". A pass reports each run with `s.jobs.Run(ctx, "<worker name>", pass)`. Every pass, whether it returns an error or not, also marks the run failed with `jobFailed(ctx, err)` at each site that logs a failure and carries on (a per-item read, parse or write that is stepped over, as `alertPass` does at `alertwatch.go:121-129` before returning nil): one item failing marks the run Failed, and the pass carries on as today. A test walks the listed pass functions and refuses a swallowed failure log without `jobFailed`. A worker that returns without ever reporting a run is not configured here and drops out of the table. Display order is by label.
- **Old `/fleet` content:** `/fleet` keeps answering 200 (now the dashboard), so no HTTP redirect is needed. Every in-console link to that content (`store_approvals.html:3`, tests, claim probes) moves to `/fleet/boxes`, and the dashboard links there. No other URL changes.
-- **Economics scripts survive a deferred body.** A fragment inserted with `outerHTML` runs no `<script>` inside it. So each economics page's script moves out of the body into the page frame as a named, idempotent initializer (`econInit(root)`, `econAccountsInit(root)`), run once at load on the body if it is there, and again on each `carlos:part` event the part loader dispatches after inserting a fragment. The data block (`<script type="application/json" id="econ-data">`) stays in the body: it is read, not run.
+- **Firing alerts are current state, not notification history.** `alert_seen` records what each recipient was told (and geoip's `geoip@N` reason rows), so it cannot say what is firing now. The alert watcher keeps an in-process projection instead (`Server.alertsNow`), replaced box by box on every pass from the published `alerts/boxes/<box>.json` objects it already reads: one entry per firing `(box, rule)`, with `since` from the rule's `FiredAt`. A box whose object failed to read or parse keeps its previous entries; a box whose object is gone is dropped. Before the first pass after a start the projection is "not known yet" and the dashboard lists no alert item. On a console with no keymail sender `alertPass` returns before reading anything (as today, so no new S3 reads); there the projection stays unknown and the Metrics page remains where alerts show. The claim runtime's receipt-database pages (`claim_runtime.go:315`, host-claim only) are not bucket alerts and stay off the dashboard this round. *(My call: in-process like the job registry, because the watcher reruns at start.)*
+- **Economics scripts survive a deferred body.** A fragment inserted with `outerHTML` runs no `<script>` inside it. So each economics page's script moves out of the body into the page frame as a named, idempotent initializer (`econInit(root)`, `econAccountsInit(root)`), run once at load on the body if it is there, and again on each `carlos:part` event the part loader dispatches after inserting a fragment. Following plan 2's rule that a deferred fragment carries no `<script>` at all, the data block (`<script type="application/json" id="econ-data">`) leaves the body too: its JSON moves to a `data-econ` attribute on the body's wrapper (`<div id="econ-body" data-econ="{{.Economics.DataJSON}}">`, escaped by `html/template`), which the initializer parses.
- **Economics:** `/fleet/economics` and `/fleet/economics/accounts` both carry `seg-tabs` Overview and Accounts; the accounts page's search form and position links become one `list-bar` (search plus a filter dropdown); its "Back to the dashboard" link goes (the tabs replace it).
---
@@ -97,6 +99,7 @@ Each is marked *(my call)* where it appears in a task.
| `internal/console/opaudit.go`, `opaudit_test.go` (create) | the six account-level actions | 6 |
| `internal/console/store_gate.go` (modify `:190`), `store_gate_test.go` (modify) | `audit` admits app-less rows under the claim gate | 6A |
| `internal/console/jobs.go`, `jobs_test.go` (create) | the registry, `jobFailed`, labels | 7 |
+| `internal/console/alertnow.go`, `alertnow_test.go` (create); `alertwatch.go` (modify) | what is firing now, kept by the watcher | 7A |
| every `Start*` file listed in Task 7 (modify) | each run reports | 7 |
| `internal/console/opboxes.go`, `templates/ops_boxes.html` (create); `templates/fleet.html` (delete) | Boxes | 8 |
| `internal/console/opdashboard.go`, `opdashboard_test.go`, `templates/ops_dashboard.html` (create) | the dashboard | 9 |
@@ -297,7 +300,7 @@ file LICENSE LICENSE 3f3d9e0024b1921b067d6f7f88deb4a60cbe7a78e76c64e3f1d7fc3b779
- `TestStaticAssetsAreServedWithLongCache` (on `newConsoleFixture`, signed out): GET `assetURL("rastrillo/tokens.css")` answers 200, `text/css; charset=utf-8`, the immutable `Cache-Control`, `nosniff`, and the file's bytes; the same for `shell.js` with `text/javascript; charset=utf-8`; a HEAD answers 200 with no body.
- `TestStaticStaleHashServesCurrentWithoutLongCache`: `/static/000000000000/rastrillo/tokens.css` answers 200, the current bytes, `Cache-Control: no-cache`.
- `TestStaticUnknownFileIs404`: `/static/<hash>/rastrillo/nope.css`, `/static/<hash>/rastrillo/VERSION/x` and `/static/<hash>/server.go` reach `handleStatic` and answer the mux's missing-route 404 body.
- - `TestStaticPathIsCanonicalisedByTheMux`: with the fixture's browser (redirects not followed, `server_test.go:138`), `/static/<hash>/../server.go` answers `301` with `Location: /static/server.go` before `handleStatic` runs (ServeMux cleans the path); a GET of that location is the missing-route 404 (it does not match `GET /static/{hash}/{file...}`). This pins that traversal never reaches the asset lookup, separately from the lookup's own 404.
+ - `TestStaticPathIsCanonicalisedByTheMux`: with the fixture's browser (redirects not followed, `server_test.go:138`), follow the chain one hop at a time: `/static/<hash>/../server.go` answers `301` with `Location: /static/server.go` (ServeMux cleans the path); `/static/server.go` answers `301` with `Location: /static/server.go/` (the mux adds the slash the `{file...}` wildcard needs); `/static/server.go/` reaches `handleStatic` with `{hash}` `server.go` and an empty file and answers the missing-route 404. No hop serves a file. This is separate from `TestStaticUnknownFileIs404`, which covers the lookup's own 404 on paths the mux leaves alone.
- `TestAssetURLPanicsOnUnknownName`.
- `TestStaticIsNotMeasured`: after a GET of an asset, no `fx.srv.PerfGroups()` group names `/static/`, and the response has no `Server-Timing`.
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestRastrillo|TestStatic|TestAssetURL' -count=1`. Expected: FAIL.
@@ -360,7 +363,6 @@ file LICENSE LICENSE 3f3d9e0024b1921b067d6f7f88deb4a60cbe7a78e76c64e3f1d7fc3b779
- `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).
- - `type FiringAlert struct { Box, Rule string }`; `func (s *Store) FiringAlerts() ([]FiringAlert, error)`: `SELECT DISTINCT box, rule FROM alert_seen WHERE firing = 1 ORDER BY box, rule`. Every recipient row counts, the synthetic `''` recipient included (`alertwatch.go:90`): it records a firing nobody could be mailed about, which is still a firing.
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`.)*
@@ -373,9 +375,8 @@ Every method is a read on `s.db` except `TouchLastSeen`, which writes `users`, a
- `TestPeopleAndAccountsSearchIsLiteral` (Review Focus 2): with people `a%b@example.com`, `ab@example.com`, `o'brien@example.com`: `q = "%"` matches only the first; `q = "_"` none; `q = "o'brien"` one; a 2,000-character `q` none and no error. The same for `AccountsPage` with an account named `50% off`.
- `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.
- - `TestFiringAlertsDistinct`: two recipients of one firing rule and one quiet rule → one `FiringAlert`.
- `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|TestFiringAlerts|TestGatedStoreOpens' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestMigrateOperatorPages|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`.
@@ -498,6 +499,35 @@ Each loop wraps one pass in `s.jobs.Run` with its worker name as a string litera
- [ ] **Step 4: Run** Step 2's command; the passes' own tests, `go test ./internal/console/ -run 'TestAlert|TestEconomicsPass|TestInfraPass|TestExpiryPass|TestPlanLimits|TestPlanGrace|TestRunSweep|TestSeedsPass|TestRelay|TestMailPush|TestDoorKey|TestApex|TestPlacementDiscrepanc|TestScanPass|TestScanDrain|TestHostReports|TestPlansMarker|TestGeoip|TestClaimWorker' -count=1`; and `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`. Expected: PASS.
- [ ] **Step 5: Commit**, message `console: every background pass reports its runs to an in-process job registry`.
+### Task 7A: The alert watcher keeps what is firing now
+
+**Files:**
+- Create: `internal/console/alertnow.go`, `internal/console/alertnow_test.go`
+- Modify: `internal/console/alertwatch.go:102-146` (`alertPass` feeds the projection), `internal/console/server.go` (`Server.alertsNow *alertNow`, made in `NewServer`)
+
+**Interfaces:**
+- Produces:
+ - `type FiringAlert struct { Box, Rule string; Since time.Time }`
+ - `type alertNow struct { … }` (a mutex, `known bool`, and per box a map of rule → since); `func newAlertNow() *alertNow`
+ - `func (a *alertNow) setBox(box string, rules map[string]metrics.RuleState, now time.Time)`: replaces that box's entries with its rules whose `Firing` is true; `Since` is `FiredAt`, or, when `FiredAt` is zero, the previous `Since` for a rule already firing, else `now`.
+ - `func (a *alertNow) keepOnly(boxes map[string]bool)`: drops boxes not in the set (their object is gone).
+ - `func (a *alertNow) markKnown()`
+ - `func (a *alertNow) Firing() (alerts []FiringAlert, known bool)`: sorted by box then rule; a copy.
+
+`alertPass`, after its listing succeeds: for each key it reads and parses, `setBox(box, st.Rules, now)` before the mail loop for that box; a key whose read or parse fails adds its box to the kept set without calling `setBox`, so its last entries stand (and Task 7 marks the run Failed); after the loop, `keepOnly(every box listed)` then `markKnown()`. A failed listing leaves the projection as it was. Rule names come from the objects (`disk`, `mem`, `cpu`, `lag`, `geoip`), never from `alert_seen`, so `geoip@N` rows never reach it and one geoip firing is one entry. The projection is updated whatever the recipients are, before and independently of who is mailed.
+
+- [ ] **Step 1: Write the failing tests** (production wiring: `newConsoleFixture`, alert objects written to `fx.rel` with `metrics.AlertKey`, passes run through `fx.srv.alertPass(ctx)`):
+ - `TestAlertsNowFiringThenClearedWithARecipientChange`: Paul is the one operator with a grant; `box-1` publishes `disk` firing; a pass: `Firing()` is `[box-1/disk]` with `Since` the object's `FiredAt`. Then the recipients change: Paul's grant is removed (`SetGrantToken(addr, "")` or the store's revoke) and `ann@example.com` becomes an operator with a grant; `box-1` publishes `disk` cleared; a pass: `Firing()` is empty, while `alert_seen` still holds a `firing = 1` row for `box-1/disk` (Paul's or the synthetic recipient's), which is exactly the history the dashboard must not read.
+ - `TestAlertsNowGeoipIsOneEntry`: `geoip` firing with value 2: `alert_seen` gains `geoip@1` to `geoip@5` rows, and `Firing()` has exactly one entry, `box-1/geoip`.
+ - `TestAlertsNowKeepsABoxWhoseReadFailedAndDropsAGoneBox`: `box-1` firing; its object replaced with invalid JSON; a pass: still `box-1/disk`; the object deleted; a pass: empty.
+ - `TestAlertsNowUnknownBeforeTheFirstPass`: on a fresh server `Firing()` reports `known` false; after one pass over an empty prefix it is true and empty.
+ - `TestAlertsNowWithoutKeymailStaysUnknownAndReadsNothing`: with the sender unset, a pass reads no key (counted with `opProbeStore`, defined in this task, below) and `known` stays false.
+ - Test helper `opProbeStore` (in `alertnow_test.go`; Task 9 reuses it): a `release.Store` wrapper with exactly plan 1's `latencyStore` method list (`Get`, `Put`, `List`, `ListDirs`, `Delete`, `DeleteIfMatch`, `ListMod`, `ListSizes`, delegating to `*deletableStore`), which records every key or prefix it is asked for and fails a `Get` whose key matches a test-set function; `TestOpProbeStoreMethodSetMatches` holds its method set to `*deletableStore`'s, as plan 1's `TestLatencyStoreMethodSetMatches` does.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAlertsNow|TestOpProbeStore' -count=1 -race`. Expected: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** Step 2's command and `go test ./internal/console/ -run 'TestAlert|TestSwallowedAlertFailure|TestPassFailureLogs' -count=1`. Expected: PASS.
+- [ ] **Step 5: Commit**, message `console: the alert watcher keeps a projection of what is firing now`.
+
### Task 8: Boxes at `/fleet/boxes`: today's `/fleet` content, plus background jobs
**Files:**
@@ -535,21 +565,22 @@ Each loop wraps one pass in `s.jobs.Run` with its worker name as a string litera
- Modify: `opshell_test.go` (delete `/fleet` from `opShellPending`); the `route GET /fleet` probe and fixture (`claimRead("operator dashboard: SQLite counts, fleet.json, box snapshots, the storage queue")`, marker `<h1>` + OPS-8 + `</h1>`); `perf-budgets.txt` (`GET /fleet over: reads fleet.json, every box snapshot and, for a store operator, the storage queue until operator-pages Task 13`. Until Task 13 has landed this branch is not rolled to flagship: before it, the dashboard's per-box reads are on the request path. *(My call.)*)
**Interfaces:**
-- Consumes: Task 4's reads, `s.jobs.Snapshot()`, `opFleetJSON`, `opHostRows`, `opStorePending`, `Store.FiringAlerts`, `op_meter`, OPS-8, OPS-20 to OPS-76.
+- Consumes: Task 4's reads, `s.jobs.Snapshot()`, `opFleetJSON`, `opHostRows`, `opStorePending`, `Server.alertsNow.Firing()` (Task 7A), `op_meter`, OPS-8, OPS-20 to OPS-76.
- Produces:
- - `type attentionItem struct { Lead, Code, Tail, Href, Link string }` (`Code` is set for a box, service, rule or job name and renders in `<code>`); `type attentionInput struct { Fleet *status.Fleet; FleetErr error; Now time.Time; Alerts []FiringAlert; StorePending *int; Jobs []JobStatus }`; `func attentionItems(in attentionInput) (items []attentionItem, tone string)`: one item per silent box (OPS-24, link Boxes `#box-<label>`), one for an old summary (OPS-25), one for a read failure (OPS-26), one per down service (OPS-27), one per firing alert (OPS-28, link Metrics), one storage line (OPS-29 or OPS-30, link Storage requests) when `StorePending` is non-nil and positive, one per failed job (OPS-31, link `/fleet/boxes#jobs` labelled OPS-32); tone by the rule in "Decisions".
+ - `type attentionItem struct { Lead, Code, Tail, Href, Link string }` (`Code` is set for a box, service, rule or job name and renders in `<code>`); `type attentionInput struct { Fleet *status.Fleet; FleetErr error; Now time.Time; Alerts []FiringAlert; AlertsKnown bool; StorePending *int; Jobs []JobStatus }`; `func attentionItems(in attentionInput) (items []attentionItem, tone string)`: one item per silent box (OPS-24, link Boxes `#box-<label>`), one for an old summary (OPS-25), one for a read failure (OPS-26), one per down service (OPS-27), one per firing alert when `AlertsKnown` (OPS-28, link Metrics), one storage line (OPS-29 or OPS-30, link Storage requests) when `StorePending` is non-nil and positive, one per failed job (OPS-31, link `/fleet/boxes#jobs` labelled OPS-32); tone by the rule in "Decisions".
- `type dashBar struct { Day time.Time; N, H int }`; `func dashBars(days []DayCount) []dashBar` (the height rule in "Decisions").
- `func dashStats(c OperatorCounts) []opStat`: People (lead; note OPS-34), New people this week (delta OPS-37/38/39 against `NewPeoplePrev7`), New accounts this week (same against `NewAccountsPrev7`), Apps (delta OPS-41 or OPS-42 from `NewApps7`), Deploys today (note OPS-44/45 when `DeploysToday > 0`). Tones per "Decisions"; numbers through `opNumber`.
- `type dashBox struct { Label, Region string; Status opPill; Meter *opMeter; LastSeen time.Time }` (`Meter` nil for a silent box or one with no metrics block, rendered as OPS-76); `func dashBoxes(f *status.Fleet, hosts []HostRow, now time.Time) (rows []dashBox, stale bool)`: one row per `HostRow` in label order, plus a row for any `FleetBox` with no `HostRow` (Silent, no meter, no last report); the status rule in "Decisions"; an empty region is OPS-76.
- `type dashView struct { Attention []attentionItem; Tone string; Stats []opStat; Bars []dashBar; Newest []PersonRow; Activity []FeedRow; Boxes []dashBox; HasFleet bool; Jobs []opJobRow }`
- - `func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request)`: `operatorOnly`; the SQLite reads (`OperatorCounts`, `NewPeoplePerDay(now, 30)`, `NewestPeople(5)`, `ActivityFeed({}, 0, 10)`, `FiringAlerts`) each log and leave their section empty on error (never a 500); `opFleetJSON`, `opHostRows` (a failure logs and the Boxes section shows its existing degrade line, never a 500) and `opStorePending`; render `ops_dashboard`.
+ - `func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request)`: `operatorOnly`; the SQLite reads (`OperatorCounts`, `NewPeoplePerDay(now, 30)`, `NewestPeople(5)`, `ActivityFeed({}, 0, 10)`) each log and leave their section empty on error (never a 500); `opFleetJSON`, `opHostRows` (a failure logs and the Boxes section shows its existing degrade line, never a 500), `opStorePending`, and `s.alertsNow.Firing()` (in-process, no read); render `ops_dashboard`.
`ops_dashboard.html` follows the mockup top to bottom: `op_page_header` (OPS-8, OPS-20 with `.Brand`); the callout (`rst-callout rst-tone="{{.Dash.Tone}}"`, the matching icon `circle-check`, `triangle-alert` or `circle-x`, `aria-hidden`; the title OPS-21, OPS-22 or OPS-23; a `<ul co-attention>` of items, each `{{.Lead}}<code>{{.Code}}</code>{{.Tail}} <a href="{{.Href}}">{{.Link}}</a>`); the `rst-stats rst-card` band of `op_stat`; the chart (`rst-box-head` OPS-46; `<div rst-card>`, `<div co-bars aria-hidden="true">` of `<span co-bar co-h="{{.H}}">`, the axis with the first day as `2 Jan` and OPS-50, then `<table class="rst-sr-only">` with caption OPS-47, headings OPS-48 and OPS-49 and one row per day); Newest people (OPS-51, link OPS-52 to `/fleet/people`, `.co-people` rows: address as `.rst-nm`, account or OPS-56, `ago` joined, apps); Latest activity (OPS-58, link OPS-59, `.co-activity` rows: `ago`, address, `Detail`, app or OPS-56; OPS-64 when empty); Boxes (`{{define "ops_dashboard_boxes"}}` so Task 13 can serve it as its own part: h2 OPS-11, link OPS-65, `.co-boxes` rows of OPS-66 to OPS-70, the label as `.rst-nm` linking `/fleet/boxes#box-<label>`, `op_status`, the region, `op_meter` or OPS-76, `ago` of the last report; OPS-71 when there is no snapshot); `op_jobs`. Empty newest people is OPS-57.
-- [ ] **Step 1: Write the failing tests** in `opdashboard_test.go`. Test helper `opProbeStore` (in `opdashboard_test.go`): a `release.Store` wrapper with exactly plan 1's `latencyStore` method list (`Get`, `Put`, `List`, `ListDirs`, `Delete`, `DeleteIfMatch`, `ListMod`, `ListSizes`, delegating to `*deletableStore`), which records every key or prefix it is asked for and fails a `Get` whose key matches a test-set function; `TestOpProbeStoreMethodSetMatches` holds its method set to `*deletableStore`'s, as plan 1's `TestLatencyStoreMethodSetMatches` does. `seedOperatorWorld(t, fx)` (test-only, shared with Tasks 10, 11 and 14): eight people (`ann@example.com` and others under `example.com`, joined over 30 days with two today and none 10 to 20 days ago), accounts `shop` and `notes` minted through `mintAccount`, apps under them, activity rows (two `promote` today on two apps, a `signin`, an `invite-sent`), `seedHostBoxes` (one fresh box, one dark), a firing `alert_seen` row for `box-1`/`disk`, a failed `StartEconomicsPass` run; Paul is operator and store operator with one pending storage application (as `storepage_test.go` seeds one).
+- [ ] **Step 1: Write the failing tests** in `opdashboard_test.go` (with Task 7A's `opProbeStore`). `seedOperatorWorld(t, fx)` (test-only, shared with Tasks 10, 11 and 14): eight people (`ann@example.com` and others under `example.com`, joined over 30 days with two today and none 10 to 20 days ago), accounts `shop` and `notes` minted through `mintAccount`, apps under them, activity rows (two `promote` today on two apps, a `signin`, an `invite-sent`), `seedHostBoxes` (one fresh box, one dark), `box-1` publishing `disk` firing and one `alertPass` run (so the projection holds it), plus a stale `alert_seen` firing row for a cleared `box-2`/`mem` (history the dashboard must ignore), a failed `StartEconomicsPass` run; Paul is operator and store operator with one pending storage application (as `storepage_test.go` seeds one).
- `TestAttentionItemsEachCondition` (not acceptance, table-driven over `attentionItems`): nothing wrong gives no items and `positive`; a stale box gives OPS-24 with the label and `warning`; `GeneratedAt` older than 15 minutes gives OPS-25; `FleetErr` gives OPS-26; a down service gives OPS-27 and `negative`; an alert gives OPS-28; `StorePending` 1 and 3 give OPS-29 and OPS-30, nil gives none; a failed job gives OPS-31 linking `/fleet/boxes#jobs`.
- `TestDashboardNeedsAttentionFromRealRows`: on the seeded world, the page's callout has `rst-tone="warning"`, OPS-23 with 4 (the dark box, the alert, the storage request, the failed job), and each item's link; an operator who is not a store operator sees 3 and no storage item.
- `TestSwallowedAlertFailureShowsAsFailed`, second half (Task 7's test, extended here): after the failed alert run, GET `/fleet`: the callout lists OPS-31 naming the Alerts label with its link to `/fleet/boxes#jobs`, and the jobs table shows Alerts with OPS-81.
+ - `TestDashboardIgnoresAlertHistory`: on the seeded world, no item names `box-2` or `mem`; with the projection not yet known (a fresh server, no pass), no alert item at all and the page is 200.
- `TestDashboardAllClear`: with no problems seeded, the callout is `positive` with OPS-21 and no list.
- `TestDashboardCountsFromFixtureRows`: the band shows People with the seeded total and OPS-34 with the active count, New people this week with its delta text, Deploys today `2` with OPS-45 for 2 apps.
- `TestDashboardSeriesHasThirtyDaysWithZerosFilled`: 30 `co-bar` spans; the hidden table has 30 rows; the rows for days 10 to 20 ago say 0; the last row is today's and says 2; the tallest bar is `co-h="20"`; no bar of a non-zero day is `co-h="0"`.
@@ -558,7 +589,8 @@ Each loop wraps one pass in `s.jobs.Run` with its worker name as a string litera
- `TestDashboardReadFailuresDegrade`: on `newConsoleFixtureWith` with `WrapReleases` set to an `opProbeStore` failing `status/fleet.json`, the page is 200 with OPS-26 in the callout.
- `TestDashboardBoxesKeepTheMockupColumns`: on the seeded world (`seedHostBoxes`), the Boxes section has the five headings OPS-66 to OPS-70 in order; the fresh box's row has `op_status` Healthy, region `eu-west-1`, `<meter rst-meter-bar` with value 50 and `50%`, and an `ago` last report; the dark box's row is Silent with OPS-76 and a last report about an hour ago.
- `TestDashboardRemoteReadsAreTheDeclaredOnes`: with an `opProbeStore`, GET `/fleet`: every key it was asked for is `status/fleet.json`, the `status/boxes/` listing or a key under it, or the storage queue's. (Task 13 turns these into zero on a warm view.)
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOpProbeStore|TestAttentionItems|TestDashboard|TestEveryOperatorPage' -count=1`. Expected: FAIL.
+ - Walk fixture: `newPerfFixture` (plan 1, `perfwalk_test.go`) gains `seedOperatorScale(t, fx)`, so every operator screen is measured over populated tables: 300 people (joined across 60 days, half with `last_seen`, sessions for a third), 60 accounts each with 2 to 6 members, 1 to 8 apps and a plan row, and 3,000 audit rows spread over the accounts, the six account actions and `promote`/`rollback` (written in one transaction through a test helper so the walk stays well under 10 s). Neutral names (`person-<n>@example.com`, `shop-<n>`).
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAttentionItems|TestDashboard|TestEveryOperatorPage' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement**; add OPS-20 to OPS-31 and OPS-33 to OPS-76 to `operatorPagesCopyBuilt` (OPS-8 and OPS-32 are already there).
- [ ] **Step 4: Run** Step 2's command, `go test . -run TestOperatorPagesCopy -count=1`, `go test ./internal/console/ -run 'TestOperatorGate|TestBoxes' -count=1`, `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`, and the walk without `CI`.
- [ ] **Step 5: Visual check.** Run Task 14's command for `dashboard` only, at 1280 and 390, light and dark; compare with the mockup. Pass: the order and shapes of the mockup; the callout lists four items; at 390 the stats band wraps and the back strip shows. Then commit, message `console: the operator dashboard`.
@@ -571,7 +603,7 @@ Each loop wraps one pass in `s.jobs.Run` with its worker name as a string litera
**Interfaces:**
- Consumes: `PeoplePage`, `AccountsPage`, `OperatorCounts`, `op_seg_tabs`, `op_list_bar`, `op_pagination`, `op_empty`, OPS-9, OPS-33, OPS-103 to OPS-118.
-- Produces: `const peoplePageSize = 50`, `const searchMax = 100`; `type peopleQuery struct { Show, Q string; Page int }`; `func parsePeopleQuery(v url.Values) peopleQuery` (`Show` `people` unless `accounts`; `Q` trimmed and cut at `searchMax` runes; `Page` a positive integer, else 1); `type peopleView struct { Query peopleQuery; Tabs opTabs; Bar opListBar; Pager opPager; People []PersonRow; Accounts []AccountRow; Total int; Active [3]opStat }`; `func (s *Server) handlePeople(w http.ResponseWriter, r *http.Request)`. A page past the last is clamped to the last (one more query with the clamped offset).
+- Produces: `const peoplePageSize = 50`, `const searchMax = 100`; `var peopleShows = []string{"people", "accounts"}`; `type peopleQuery struct { Show, Q string; Page int }`; `func parsePeopleQuery(v url.Values) peopleQuery` (`Show` `people` unless `accounts`; `Q` trimmed and cut at `searchMax` runes; `Page` a positive integer, else 1); `type peopleView struct { Query peopleQuery; Tabs opTabs; Bar opListBar; Pager opPager; People []PersonRow; Accounts []AccountRow; Total int; Active [3]opStat }`; `func (s *Server) handlePeople(w http.ResponseWriter, r *http.Request)`. A page past the last is clamped to the last (one more query with the clamped offset).
The page: `op_page_header` (OPS-9, OPS-103); a small `rst-stats` band of Active today, 7 days, 30 days (OPS-108 to OPS-110); `op_seg_tabs` (OPS-104; OPS-33 `/fleet/people`, OPS-105 `/fleet/people?show=accounts`); an `rst-card` with `op_list_bar` (placeholder OPS-106 or OPS-107, `Hidden` carries `show`, `ClearHref` drops `q` and `page`), then `rst-lrow` rows: people (OPS-53, OPS-55, OPS-111, OPS-112; last seen `ago` or OPS-113) or accounts (OPS-54, OPS-114, OPS-115, OPS-40, OPS-116; the name links to `/fleet/activity?account=<sqid>`; plan `""` is OPS-56); `op_empty` with OPS-117 or OPS-118 for an empty search; `op_pagination` (OPS-19) when there is more than one page.
@@ -579,8 +611,9 @@ The page: `op_page_header` (OPS-9, OPS-103); a small `rst-stats` band of Active
- `TestPeoplePageListsPeopleAndAccounts`: the people view lists every seeded person with joined and last seen; the accounts view lists `shop` and `notes` with created, plan, apps and members, and their links to `/fleet/activity?account=`.
- `TestPeoplePageSearch`: `?q=ann` lists only `ann@example.com`; `?show=accounts&q=sho` only `shop`; an empty result shows OPS-117 / OPS-118; the clear link drops `q`.
- `TestPeoplePagePaging`: with 120 people seeded, page 1 has 50 rows and an `op_pagination` with `aria-current="page"` on 1; `?page=3` has 20.
+ - Walk targets: route enumeration cannot see query-selected views (`claim_routes.go:59` registers patterns), so `perfTargets` (plan 1, `perfwalk_test.go`) gains an explicit entry for `GET /fleet/people`: `{Path: "/fleet/people", Expect: 200}`, `{Path: "/fleet/people?show=accounts", Expect: 200}`, `{Path: "/fleet/people?q=person-1", Expect: 200}`, `{Path: "/fleet/people?show=accounts&q=shop-1", Expect: 200}`, `{Path: "/fleet/people?page=3", Expect: 200}`, all over `seedOperatorScale`'s rows. `TestPerfTargetsCoverOperatorViews` asserts every value of `show` and `kind` this plan defines (`peopleShows`, `feedKinds`) has a target.
- `TestPeoplePageClampsItsParameters` (Review Focus 5): `page=0`, `page=-3` and `page=abc` are page 1; `page=99999` is the last page; `show=nope` is people; a 2,000-character `q` is cut and answers 200.
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPeoplePage|TestEveryOperatorPage|TestOperatorGate' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPeoplePage|TestPerfTargetsCoverOperatorViews|TestEveryOperatorPage|TestOperatorGate' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement**; add OPS-103 to OPS-118 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` (zero remote calls).
- [ ] **Step 5: Commit**, message `console: People and accounts for operators`.
@@ -600,6 +633,7 @@ The page: `op_page_header` (OPS-10, OPS-119); a toolbar (`<div rst-lbar>`) with
- [ ] **Step 1: Write the failing tests** on `seedOperatorWorld` plus 120 extra `RecordEvent` rows:
- `TestActivityPageNewestFirstAndPaged`: the first page has 50 rows newest first and an Older link with the 50th row's id; following it continues; Newest returns to the start.
- `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.
- `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.
@@ -617,14 +651,14 @@ The page: `op_page_header` (OPS-10, OPS-119); a toolbar (`<div rst-lbar>`) with
**Interfaces:**
- Consumes: `opPage`, the `op_*` partials, plan 1's Console speed section (kept whole, moved into an `rst-card`), OPS-12, OPS-14, OPS-15, OPS-139 to OPS-145.
-Each page: `op_top`, `op_page_header` (its rail label and its subhead row), then the existing body with its strings and scripts verbatim, re-dressed: flash and warning `banner`s become `rst-callout` (info or negative tone, `role="alert"` kept off); `tiles`/`tile` become `rst-stats`/`op_stat` (keep each tile's `<h2>` text as the `Label`); tables move into `<div rst-card class="co-table-wrap"><table co-table>`; chips become `op_status`; `small` becomes `<p co-note>`; buttons `rst-btn`, inputs `rst-input`. Economics: `seg-tabs` (OPS-141; OPS-142 `/fleet/economics`, OPS-143 `/fleet/economics/accounts`, each keeping the current `period`) under the header on both pages; the utilization bar at `economics.html:149` becomes `op_meter`; the hidden note at `:528` uses the `hidden` attribute and its script toggles `.hidden` instead of `style.display` (check every script line that reads or sets `style`); each page's one inline script (`economics.html:250-413`, `economics_accounts.html:180-243`) becomes a named initializer placed after the body, outside it: `function econInit(root)` and `function econAccountsInit(root)`, which find every element through `root.querySelector…` instead of `document.…` (the bill checkboxes at `:396` included), read `econ-data` from inside `root`, return at once when `root.dataset.econInit` is set and set it otherwise, and are called once at the end of the script with the body element (`document.getElementById("econ-body")`, a wrapper `<div id="econ-body">` round the body) when it exists. The function bodies are otherwise the existing code, so the existing script-shape tests (`TestEconomicsJSTwinsShape` and its siblings) still find their strings in the page; the accounts page's search form and position links become one `op_list_bar` (search placeholder and submit text moved verbatim from `:66`; `Filter` is a dropdown whose items are All plus each position link, Label the active one, Aria OPS-144) and its "Back to the dashboard" link goes; `js-*` classes and element ids the scripts use stay. Metrics: the alert table and per-box tiles as above; the Console speed section keeps `consoleSpeedRows` and its approved CPF rows. Architecture: content and its refresh form unchanged inside cards.
+Each page: `op_top`, `op_page_header` (its rail label and its subhead row), then the existing body with its strings and scripts verbatim, re-dressed: flash and warning `banner`s become `rst-callout` (info or negative tone, `role="alert"` kept off); `tiles`/`tile` become `rst-stats`/`op_stat` (keep each tile's `<h2>` text as the `Label`); tables move into `<div rst-card class="co-table-wrap"><table co-table>`; chips become `op_status`; `small` becomes `<p co-note>`; buttons `rst-btn`, inputs `rst-input`. Economics: `seg-tabs` (OPS-141; OPS-142 `/fleet/economics`, OPS-143 `/fleet/economics/accounts`, each keeping the current `period`) under the header on both pages; the utilization bar at `economics.html:149` becomes `op_meter`; the hidden note at `:528` uses the `hidden` attribute and its script toggles `.hidden` instead of `style.display` (check every script line that reads or sets `style`); each page's one inline script (`economics.html:250-413`, `economics_accounts.html:180-243`) becomes a named initializer placed after the body, outside it: `function econInit(root)` and `function econAccountsInit(root)`, which find every element through `root.querySelector…` instead of `document.…` (the bill checkboxes at `:396` included), parse the page data from `root.dataset.econ` (the `data-econ` attribute that replaces the `econ-data` script block; the tests that read `econ-data` read the attribute instead), return at once when `root.dataset.econInit` is set and set it otherwise, and are called once at the end of the script with the body element (`document.getElementById("econ-body")`, a wrapper `<div id="econ-body">` round the body) when it exists. The function bodies are otherwise the existing code, so the existing script-shape tests (`TestEconomicsJSTwinsShape` and its siblings) still find their strings in the page; the accounts page's search form and position links become one `op_list_bar` (search placeholder and submit text moved verbatim from `:66`; `Filter` is a dropdown whose items are All plus each position link, Label the active one, Aria OPS-144) and its "Back to the dashboard" link goes; `js-*` classes and element ids the scripts use stay. Metrics: the alert table and per-box tiles as above; the Console speed section keeps `consoleSpeedRows` and its approved CPF rows. Architecture: content and its refresh form unchanged inside cards.
- [ ] **Step 1: Write the failing tests:**
- `TestEveryOperatorPageRendersInTheShell` now covers all pages (`opShellPending` empty; `TestOperatorShellPendingShrinks` asserts it is empty).
- `TestEconomicsTabs`: both pages carry `rst-seg-tabs` with `aria-current="page"` on the right tab and the current period in both links.
- `TestEconomicsAccountsListBar`: the accounts page has one `rst-lbar` with the search and a dropdown holding All and each position; a position filter survives a search (hidden `pos`).
- `TestEconomicsScriptsStillFindTheirElements`: every `getElementById`/`querySelector` argument in the two templates' scripts names an id or class still present in the rendered page.
- - `TestEconomicsInitializerShape`: each page defines its initializer outside `econ-body`, calls it once with `econ-body`, and has no `<script>` other than the `application/json` data block inside `econ-body`; the initializer queries through its `root` argument (no `document.getElementById` or `document.querySelector` inside it).
+ - `TestEconomicsInitializerShape`: each page defines its initializer outside `econ-body`, calls it once with `econ-body`, and has no `<script>` element of any type inside `econ-body` (plan 2's no-script rule for fragments), and `econ-body` carries `data-econ` that parses as the page's data; the initializer queries through its `root` argument (no `document.getElementById` or `document.querySelector` inside it).
- The existing economics, metrics and architecture tests pass with their headings updated.
- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEveryOperatorPage|TestOperatorShellPending|TestEconomics|TestFleetMetrics|TestArchitecture|TestArchPage|TestConsoleSpeed' -count=1`. Expected: the new ones FAIL.
- [ ] **Step 3: Implement**; add OPS-139 to OPS-145 to `operatorPagesCopyBuilt`.
@@ -645,25 +679,30 @@ Each page: `op_top`, `op_page_header` (its rail label and its subhead row), then
- `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".)*
- `var fleetParts map[string]viewPart` with `dashboard`, `dashboard-boxes` (the `ops_dashboard_boxes` section alone), `boxes`, `store`, `metrics`, `economics` and `economics-accounts` (both reading `?period=`; the accounts part also `q`, `pos`, `after`), `architecture`. `Gate` is the page's own (`operatorOnly` through a wrapper returning its `page`; `storePageOperator` for `store`; `handleEconomicsAccounts`' gate for its part); `Fill` the page's fill; `Template` `<name>_body`.
- route `GET /fleet/part/{part}` → `handleFleetPart`, shaped like plan 2's `handleAppPart`: look up the part (unknown is the missing-route 404), run `Gate` first, `Fill(viewCached)` then `Fill(viewBlocking)` bounded by `viewLoadTimeout`, render with `Cache-Control: no-store`, 503 `partfailed` on a failure.
- - **Cross-plan dependency on plan 2 Task 7's `partloader`:** after replacing a placeholder it dispatches `document.dispatchEvent(new CustomEvent("carlos:part", {detail: node}))`, where `node` is the inserted element (built through a `<template>` and `replaceWith`, since `outerHTML` keeps no reference to the new node). If plan 2 has landed without it, Task 13 adds it to `templates/parts.html` (one change, the same for every part) and says so in plan 2's branch discussion. Each economics page's script adds `document.addEventListener("carlos:part", e => { if (e.detail && e.detail.id === "econ-body") econInit(e.detail) })` (and `econAccountsInit` on the accounts page), and its `econ-body` wrapper is the root of the `economics` and `economics-accounts` parts.
+ - **Plan 2's part rules, which these parts follow:** a deferred fragment contains no `<script>` (the economics initializers and their `carlos:part` listeners live in the page frame; the data is an attribute), and plan 2 Task 7's `partloader` fires `carlos:part` with the inserted element after each replacement (its `TestPartLoaderFiresTheEvent`). Each economics page's script adds `document.addEventListener("carlos:part", e => { if (e.detail && e.detail.id === "econ-body") econInit(e.detail) })` (and `econAccountsInit` on the accounts page), and its `econ-body` wrapper is the root of the `economics` and `economics-accounts` parts.
- test-only: plan 2's `HoldNext("list", match)` (plan 2 Task 2, on the S3 fake's real requests) holds the next matching listing request after it has been read; this plan adds no hold helper of its own.
- every operator template follows plan 2's shape with the operator layout: `{{define "<name>"}}{{template "op_top" .}}{{template "op_page_header" …}}{{if .Deferred}}{{template "deferred" .}}{{else}}{{template "<name>_body" .}}{{end}}{{template "op_bottom" .}}{{end}}`, and `{{define "<name>_body"}}{{template "asof" .}}…{{end}}`. The header and rail stay outside the part. People, Activity and the index read only SQLite and get no part.
On a `fleet.json` miss, the dashboard's whole body is the deferred part, because its first section (the callout) depends on it. On a per-box miss alone (`fleet.json` warm), the dashboard renders everything else and the Boxes section is the `dashboard-boxes` placeholder, filled a moment later. *(My call, matching plan 2's rule that the whole body is the part unless a section can render without the missing data.)*
-**S3 cost of the per-box data.** One `List` of `status/boxes/` plus one `Get` per box, at most once per `boxesWindow` (60 s), and only when an operator views the dashboard or Boxes (the two share the entry; single flight, so concurrent viewers make one load). No view, no reads: no timer refreshes it. With 10 boxes and an operator watching continuously that is at most 11 requests a minute; on top, `fleet.json` is one `Get` per `liveWindow` and the storage queue one `List` plus one `Get` per pending account per its window. A warm dashboard GET makes zero S3 reads, within the at-most-one rule.
+**S3 cost of the per-box data.** One `List` of `status/boxes/` plus one `Get` per box, at most once per `boxesWindow` (60 s), and only when an operator views the dashboard or Boxes (the two share the entry; single flight, so concurrent viewers make one load; app pages that read `partBoxes` at their own window share it too). No view, no reads: no timer refreshes it. The cached entry is the raw `boxSnapshot`; `HostRow`s, status words and ages are built per request from it and the clock (rule (a)). With 10 boxes and an operator watching continuously that is at most 11 requests a minute; on top, `fleet.json` is one `Get` per `liveWindow` and the storage queue one `List` plus one `Get` per pending account per its window. A warm dashboard GET makes zero S3 reads, within the at-most-one rule.
- [ ] **Step 1: Write the failing tests:**
- - `TestOperatorPagesWarmMakeNoRemoteCalls`: one sub-test per operator screen on `newPerfFixture` with `seedOperatorWorld`, Paul as operator and store operator: `getAssembled` twice, quiesce, reset counts, GET: zero S3 and zero host calls.
+ - `TestOperatorPagesWarmMakeNoRemoteCalls`: one sub-test per operator screen on `newPerfFixture` with `seedOperatorWorld`, Paul as operator and store operator: `getAssembled` twice, `perfQuiesce(fx)` (plan 2's `waitBackground`), reset counts, GET: zero S3 and zero host calls.
- `TestDashboardColdArrivesWithAPlaceholder`: a fresh fixture with latency on: the first GET of `/fleet` answers within 150 ms (time to first byte) with `data-part="/fleet/part/dashboard"` and the rail; `getAssembled` gives the dashboard with the callout.
- - `TestDashboardBoxesColdAloneIsDeferred`: `held, release := lat.HoldNext("list", func(p string) bool { return p == "status/boxes/" })`; GET `/fleet` (cold: it starts the `fleet.json`, storage-queue and box loads and renders the whole-body placeholder); wait for `held` to close (the box load is inside its listing); then wait for the other two loads by joining them through the production seams in blocking mode, `fx.srv.opFleetJSON(ctx, &page{}, viewBlocking)` and `fx.srv.opStorePending(ctx, &storePage, viewBlocking)` (each joins the load in flight for its key and returns when it publishes; `ctx` has a 5 s deadline; `storePage` is a `page` built by `opPage` for Paul, so the store-operator check passes). Now GET `/fleet` again: within 150 ms, the callout and stats render and the Boxes section is `data-part="/fleet/part/dashboard-boxes"`. `release()`; GET that part: the five-column table. Finally `quiesce`.
+ - `TestDashboardBoxesColdAloneIsDeferred`: `held, release := lat.HoldNext("list", func(p string) bool { return p == "status/boxes/" })`; GET `/fleet` (cold: it starts the `fleet.json`, storage-queue and box loads and renders the whole-body placeholder); wait for `held` to close (the box load is inside its listing); then wait for the other two loads by joining them through the production seams in blocking mode, `fx.srv.opFleetJSON(ctx, &page{}, viewBlocking)` and `fx.srv.opStorePending(ctx, &storePage, viewBlocking)` (each joins the load in flight for its key and returns when it publishes; `ctx` has a 5 s deadline; `storePage` is a `page` built by `opPage` for Paul, so the store-operator check passes). Now GET `/fleet` again: within 150 ms, the callout and stats render and the Boxes section is `data-part="/fleet/part/dashboard-boxes"`. `release()`; GET that part: the five-column table. Finally `fx.srv.waitBackground()`.
- `TestEconomicsEditAndSaveAfterColdLoad` (acceptance; skipped unless `exec.LookPath("chromium")` succeeds, and run locally before the task closes): on a fresh `newPerfFixture` (economics cold), a `127.0.0.1` test server in front of `fx.srv` adds Paul's session cookie and, for `/fleet/economics` only, appends a harness script before `</body>` that waits for `carlos:part` on `econ-body`, sets the first number input inside `#econ-live` to a new value, dispatches `input`, then copies `#scenario-json-field`'s value into a new `<pre id="harness-out">`. `chromium --headless=new --no-sandbox --disable-gpu --virtual-time-budget=15000 --dump-dom <url>` (60 s `exec.CommandContext`, profile under `t.TempDir()`). The dumped DOM's `harness-out` is valid scenario JSON that differs from the server's `scenarioJSON` in exactly that knob. The test then POSTs it to `/fleet/economics/scenarios` with a name and the CSRF token as the form does, follows the redirect, and the economics page lists the saved scenario.
- - `TestEconomicsPartIsInitialisedNotJustPresent` (no browser): the assembled cold economics page has the `carlos:part` listener in the frame and no executable `<script>` inside the part body.
+ - `TestEconomicsPartIsInitialisedNotJustPresent` (no browser): the assembled cold economics page has the `carlos:part` listener in the frame and no `<script>` of any type inside the part body; plan 2's own no-script check over every registered part passes for `economics` and `economics-accounts`.
- `TestBoxReadsOncePerWindowOnlyOnView`: with `fx.clock`: three dashboard GETs and one Boxes GET within 60 s make one `status/boxes/` listing and one `Get` per seeded box in total (counted with plan 2's `Keys()`); moving the clock 61 s and making no request makes no read; the next view serves the old rows and starts exactly one refresh; two concurrent views after the window start one.
- `TestEveryFleetPartGatesLikeItsPage`: for each `fleetParts` key, signed out and a non-operator get the missing-route 404 body and start no load (`perfLatency.Calls()` unchanged); an operator who is not a store operator gets the 404 for `store` and starts no `store-pending` load.
- - `TestDashboardAfterAStoreDecision`: warm `/fleet`; approve the pending application; the redirect's next `/fleet` view shows no storage item, with zero S3 calls (plan 2 Task 8's effect on `partStorePending`).
+ - Operator writes rely on plan 2 Task 8's read-set invalidation; each gets a warm-before-write test (warm every reader, write through the real door, then read without waiting):
+ - `TestDashboardAfterAStoreApproval`: warm `/fleet`, `/fleet/store` and the applicant's account settings (`getAssembled`, `perfQuiesce`); `ResetKeys()`; approve through `POST /fleet/store/{account}/approve`. During the POST, `Writes()` holds the entitlement key and `Keys()` shows the storage queue re-read before the 303. Then `ResetKeys()`: the next `/fleet` shows no storage item, `/fleet/store` no application, the settings page the decision, all with zero S3 requests.
+ - `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.
+ - `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|TestDashboardAfterAStoreDecision|TestEconomicsEditAndSave|TestEconomicsPartIsInitialised|TestEveryOperatorPage' -count=1`. Expected: FAIL.
+- [ ] **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 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`.
@@ -715,7 +754,9 @@ ls "$SHOTS"/*.png | wc -l # 44
## Self-review
-- **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, `HoldNextList` (this plan's addition beside plan 2's `HoldNext`) 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 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).
+- **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`), the four partials, `viewWrites`/`wroteView` (no new write door here, so no new rule), 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`, `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), 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`.