Console plans: Astra round 5 fixes (perf-2, operator-pages)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+47
−29
docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md+19 −12docs/superpowers/plans/2026-10-25-operator-pages.md+28 −17
CI passed — run details
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 9af2dda2a..9198765b9 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 |
| @@ -218,8 +218,8 @@ Spec §2.4 C rows "Settings, `populateAppSettings`", "`appDeployEmpty`" and "`en |
| **Interfaces:** |
| - Produces: |
| - - `type boxSnapshot struct { Boxes []status.Box; Complete bool; Err error }`: what `status.LoadBoxesComplete` (`status/fleet.go:224`) returns, kept whole so a reader that must fail closed on partial evidence still can. |
| - - `func (s *Server) platformBoxes(ctx context.Context) boxSnapshot` (memo key `boxes:platform`), read once per request. Strict readers (`loadBoxJoinComplete`, automatic placement) use `Complete` and `Err` exactly as they use `LoadBoxesComplete`'s results today; lenient readers (`loadBoxJoin`, `systemBoxes`, `geoipInventory`, `aliasReadings`) take `Boxes` and treat `Err` as they treat `LoadBoxes`' error today. |
| + - `type boxSnapshot struct { Boxes []status.Box; Complete bool; ErrText string }`: what `status.LoadBoxesComplete` (`status/fleet.go:224`) returns, kept whole so a reader that must fail closed on partial evidence still can. The error is kept as plain data (its text, empty for none), because the snapshot is cached from Task 9 on and cached types hold no interface fields (Task 6). `func (b boxSnapshot) Err() error` gives it back as an `error` (nil when `ErrText` is empty) for the callers below. `Complete == false && ErrText == ""` keeps meaning "partial, no error", exactly as `LoadBoxesComplete`'s `complete == false, err == nil` does today. *(Astra round 5, finding 4.)* |
| + - `func (s *Server) platformBoxes(ctx context.Context) boxSnapshot` (memo key `boxes:platform`), read once per request. Strict readers (`loadBoxJoinComplete`, automatic placement) use `Complete` and `Err()` exactly as they use `LoadBoxesComplete`'s results today; lenient readers (`loadBoxJoin`, `systemBoxes`, `geoipInventory`, `aliasReadings`) take `Boxes` and treat `Err()` as they treat `LoadBoxes`' error today. |
| - `liveEdges` behind the memo (key `edges`); `instanceDomainFor` and `appPolicy`'s instance-manifest read behind the memo (key `instances-manifest:<sqid>/<app>`). |
| - [ ] **Step 1: Write the failing tests:** |
| @@ -250,9 +250,9 @@ Spec §2.4 C rows "Settings, `populateAppSettings`", "`appDeployEmpty`" and "`en |
| - `type viewResult[T any] struct { Val T; At time.Time; Stale bool }` |
| - `func newViewCache(now func() time.Time, max int) *viewCache` |
| - **The restricted loader** (rule (a), made structural; Astra round 4, findings 2 to 4): |
| - - `type viewLoadEnv struct { Ctx context.Context; Store release.Store; Pub ed25519.PublicKey; ReadAt time.Time; LookupTXT func(ctx context.Context, name string) ([]string, error) }`, built by the cache for each load. It holds the observed object store, the release key, the time the load started (only for library calls that need a read time, such as the box listing's 24-hour horizon; nothing derived from it is shown), and DNS as one explicit, named dependency. It holds no `*Server`, no console `Store`, no registry and no clock. |
| + - `type viewLoadEnv struct { Ctx context.Context; Store release.Store; Pub ed25519.PublicKey; ReadAt time.Time; LookupTXT func(ctx context.Context, name string) ([]string, error); AppHost func(ctx context.Context, host string) InstanceReport }`, built by the cache for each load. It holds the observed object store, the release key, the time the load started (only for library calls that need a read time, such as the box listing's 24-hour horizon; nothing derived from it is shown), and two explicit, named outside dependencies. DNS is one. The other is the app-host capability: `AppHost` is the instance fetcher's `fetch` (`instances.go:122-158`), bound to the configured `Config.AppClient` as plan 1 wraps it (`perf.TimeDoer`, so the walk's counting transport still sees every call), with its scheme, timeout and size caps. Neither has a read set; each is refreshed by its window only (Astra round 5, finding 3). It holds no `*Server`, no console `Store`, no registry and no clock. |
| - `type viewLoader[A, T any] func(env viewLoadEnv, key viewKey, arg A) (T, error)`. Every loader is a package-level function in `internal/console/viewloaders.go`, so it can reach neither a `*Server` nor the console `Store`: it is given neither, and that is checked by the compiler. `arg` carries the load's inputs as plain data (a page number, a filter, a period's dates). |
| - - `TestViewLoadersAreRestricted` (`viewloaders_test.go`, built on `go/parser`) closes the remaining doors, which are package-level globals. (1) At every call of `viewPeek`, `viewWait` and `viewGet`, the loader argument is an identifier naming a function declared in `viewloaders.go`: no function literal, no method value, nothing that could capture state. (2) No function in `viewloaders.go`, nor any package-level function of package `console` they call, transitively by name, mentions `openRegistry`, `memoRoutes`, `registry.`, `database/sql`, `time.Now`, `time.Since`, `time.Until`, `context.Background` or `context.TODO` (a store call off `env.Ctx` would escape the read set), or has a receiver. (3) Every `A` and `T` named in `var viewLoaderTypes` (one entry per loader, kept complete by (1)'s scan) is, by `reflect`, plain data, with no pointer to anything mutable outside the value, no func, chan or interface field. The two read-only pointers `appCore` holds (`*release.Pipeline`, `*release.ProductionFlag`) are listed by name as allowed. |
| + - `TestViewLoadersAreRestricted` (`viewloaders_test.go`, built on `go/parser`) closes the remaining doors, which are package-level globals. (1) At every call of `viewPeek`, `viewWait` and `viewGet`, the loader argument is an identifier naming a function declared in `viewloaders.go`: no function literal, no method value, nothing that could capture state. (2) No function in `viewloaders.go`, nor any package-level function of package `console` they call, transitively by name, mentions `openRegistry`, `memoRoutes`, `registry.`, `database/sql`, `time.Now`, `time.Since`, `time.Until`, `context.Background` or `context.TODO` (a store call off `env.Ctx` would escape the read set), or has a receiver. (3) Every `A` and `T` named in `var viewLoaderTypes` (one entry per loader, kept complete by (1)'s scan) is, by `reflect`, plain data, with no pointer to anything mutable outside the value, and no func, chan or interface field: errors included, which cached types keep as text (`ErrText`, `ProductionErrText`, `PipelineErrText`). The two read-only pointers `appCore` holds (`*release.Pipeline`, `*release.ProductionFlag`) are listed by name as allowed. (4) Every call from `viewloaders.go` to another package names a function on `var viewLoaderCallees`, a reviewed list of read-only functions that return what they read (for example `release.Channel`, `release.GetProduction`, `release.GetPipeline`, `release.ListTags`, `release.GetRetention`, `status.LoadBoxesComplete`, `telemetry.Read`, `applog.ReadWindow`, `apperr.ReadWindow`, `analytics.ReadRange`, `provision.ListRecordHosts`). Each entry carries a comment saying what it reads and that it derives nothing from local state or the clock beyond choosing what to read. A function that derives liveness, freshness or an expected set (such as `edgesfile.ReadSnapshot`'s freshness, `edgesfile/snapshot.go:152`, or the GeoIP inventory's registry join) cannot be on it; its read half is split out and listed instead. Adding a callee is a reviewed change to the list, and that is how cross-package derivation stays visible. *(Astra round 5, finding 2.)* |
| - Everything that needs local state, the registry or the clock is joined per request, in the screen's fill, from the cached facts. Each later task names, per loader, what is cached and what is joined. |
| - `func viewPeek[A any, T viewCloner[T]](c *viewCache, key viewKey, window time.Duration, load viewLoader[A, T], arg A) (viewResult[T], bool)`: never blocks. A valid entry returns a clone and `true`, with `Stale` when older than `window`, in which case a refresh is started unless one is running at the entry's current generation. A missing or invalid entry returns `false` and starts a load unless one is running at the current generation. |
| - `func viewWait[A any, T viewCloner[T]](ctx context.Context, c *viewCache, key viewKey, window time.Duration, load viewLoader[A, T], arg A) (viewResult[T], error)`: a valid entry returns a clone at once; otherwise joins the load running at the current generation or starts one, and waits for it or for `ctx`. |
| @@ -314,7 +314,7 @@ 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` through `viewGet` with the loader `loadProbeObject` (in `viewloaders.go`: one `env.Store.Get` of its `arg`) into `p.Msg` and renders `part_text`; removed in `t.Cleanup`. Tests that use it are not parallel. |
| -The loader script, in the Logs tab's style: for each `[data-part]` element, `fetch(el.dataset.part, {headers: {Accept: "text/html"}, signal})` with an `AbortController` aborting after 20 s; on `ok` replace the element's `outerHTML` with the response text; otherwise (or on abort) replace it with the response text when there is one, else with CPF-28. After each replacement it dispatches `document.dispatchEvent(new CustomEvent("carlos:part", {detail: {part: <the part URL>, root: <the inserted element>}}))`. This plan owns that event; the operator-pages plan uses the same one. No polling and no retry: a part is fetched once per page view. |
| +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>}}))`. **That payload is the contract**, owned by this plan: `detail.part` is the part URL that was fetched (a string, as in `data-part`), and `detail.root` is the element now in the page (the inserted fragment's root). There are no other fields. A listener chooses by `detail.part` or by what it finds under `detail.root`, and initializes inside `detail.root`. The operator-pages plan consumes it as stated (Astra round 5, finding 5). 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. |
| @@ -328,7 +328,7 @@ Every screen converted in Tasks 9 to 14 follows one shape: its template becomes |
| - `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`. |
| - `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). |
| + - `TestPartLoaderFiresTheEvent`: the rendered `partloader` contains `carlos:part` and dispatches it after the `outerHTML` replacement with exactly the `detail` keys `part` and `root` (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. |
| @@ -401,7 +401,7 @@ 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.)* |
| + - `type appCore struct { Channels []ChannelView; ProductionFlag *release.ProductionFlag; ProductionErrText string; Pipeline *release.Pipeline; PipelineErrText string }` with `viewClone` (copies `Channels`; the two pointers are read-only). The two read errors are kept as their text, empty for none (Astra round 5, finding 4): `productionView` takes `ProductionErrText` where it took the error (the existing "fail toward baking" branch, `view.go:765-768`, runs when it is non-empty and puts the same text in `ProductionView.Err`). `applyPipelineView` sets the per-request `AppView.PipelineErr` (Task 3, not cached) to `errors.New(PipelineErrText)` when it is non-empty, so the pipeline page still tells a failed read from an absent pipeline. A failed channel read already degrades to `ChannelView.Err`, a string. 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` 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, 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). |
| @@ -463,15 +463,18 @@ Spec §2.4 C row `instances.Report`: HTTP to the app host, 30 s cache, blocks up |
| **Interfaces:** |
| - Produces: |
| - parts `instances`, `instance` (its `Gate` checks `?host=` against the app's own routes exactly as the page checks `{host}`, else 404), and `instances-report` (the self-report section alone). |
| - - `instances.Report` (its only caller is the Running tab) through `viewGet` with `{sqid, app, partAppReport}`, `liveWindow`. A miss of the report alone renders the rest of the tab and a placeholder for `instances-report` only (the part the spec names). |
| - - Reads through `viewGet`: `appResourceMetrics` (Task 9's key), `liveEdges` (`{"", "", partEdges}`, `liveWindow`), `platformBoxes` (Task 9's `partBoxes`, the whole `boxSnapshot`), the instance manifest (Task 10's key), the instance page's fleet boxes (`{sqid, "", "fleet-boxes:<fleet>"}`, `liveWindow`, a `boxSnapshot` each), `updatesPage`'s record and manifest (`{sqid, app, "updates:<host>"}`, `liveWindow`), the geoip inventory (`{"", "", "geoip-inventory"}`, `liveWindow`). The region line's reads go through the same entries. Registry and SQLite reads stay direct. |
| + - The app's self-report: the host is chosen per request by `instances.Report`'s existing rule (first ready, non-static, non-sidecar, non-hibernating route, `instances.go:83-101`, over the request's routes), and becomes part of the key, `{sqid, app, partAppReport + ":" + host}`, `liveWindow`, loader `loadAppReport(env, key, host string)` calling `env.AppHost`. A different eligible host (one went to sleep) is a different entry; no eligible host is no read at all, as today. `instanceFetcher` keeps host choice and its client; its cache map goes. A miss of the report alone renders the rest of the tab and a placeholder for `instances-report` only (the part the spec names). |
| + - Reads through `viewGet`: `appResourceMetrics` (Task 9's key), the edge files as raw facts (`{"", "", partEdges}`, `liveWindow`, loader `loadEdgeFiles`: the read half of `edgesfile.ReadSnapshot`, `control/edges/` listed and each file read, split out and put on `viewLoaderCallees`); `liveEdges`' freshness and its clock-dependent box completeness (`edgesfile/snapshot.go:152`) are computed per request from those facts, the `partBoxes` snapshot and `s.now()` by the split's pure half, `platformBoxes` (Task 9's `partBoxes`, the whole `boxSnapshot`), the instance manifest (Task 10's key), the instance page's fleet boxes (`{sqid, "", "fleet-boxes:<fleet>"}`, `liveWindow`, a `boxSnapshot` each), `updatesPage`'s record and manifest (`{sqid, app, "updates:<host>"}`, `liveWindow`), the GeoIP inventory as facts only: the platform boxes (`partBoxes`) and one heartbeat snapshot per fleet (`{"", "", fleetBoxesPart(fleet)}`, the same entries as the instance page's fleet boxes). The expected inventory (which fleets and boxes exist, `ListFleets`/`ListFleetBoxes`, `apisystemgeoip.go:281`) is read from the registry per request, and selects which fleet entries the request needs. A fleet registered since is then a miss for its own entry, never absent from a stale aggregate. The region line's reads go through the same entries. Registry and SQLite reads stay direct. |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestRunningWarmMakesNoRemoteCalls` and `TestInstancePageWarmMakesNoRemoteCalls`. |
| - `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`). |
| + - `TestEdgeFreshnessCrossesItsBoundaryWithoutARefresh`: warm Running with fresh edge files; move `fx.clock` past the edges' freshness bound with no store change (the cached facts are now stale but served); the region line's freshness-dependent text changes on that very view, while a refresh is held with `HoldNext("list", …)`. |
| + - `TestFleetAddedOrRemovedReachesGeoipInventory`: warm the instance page's update section; register a new fleet and box in the registry (no object-store write); the next view lists it (its own entry loads); remove it from the registry; the next view drops it, with no store write either way. |
| + - `TestAppReportIsKeyedByHost`: two eligible routes; the report is fetched from the first; mark it hibernating; the next view fetches from the second (a new entry) and never polls the hibernating one. |
| - `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|TestRunningTabTimesTheAppHost|TestDeferredAppReportCountsAsBackground' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestRunningWarm|TestInstancePageWarm|TestRunningTabNeverWaits|TestAppReportNeverWakes|TestEdgeFreshnessCrosses|TestFleetAddedOrRemoved|TestAppReportIsKeyedByHost|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. |
| @@ -566,7 +569,7 @@ Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the sha |
| - `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`; loader `loadStorePending` (object-store reads only; the per-account SQLite lookup is joined per request); `storePendingList` is the slice `pendingStoreApplications` returns, with `viewClone`; `opStorePending` takes its length and keeps its own store-operator and no-bucket checks) |
| - `func (s *Server) metricsView(ctx context.Context, p *page, mode viewMode) (metricsResult, error)`: Task 9's `partMetrics` entry, loader `loadMetricsFacts`, `metricsWindow`, unchanged; `metricsResult` (what `LoadMetrics` returns today) is built per request from `metricsFacts` and `s.now()`. |
| - - `func (s *Server) economicsView(ctx context.Context, p *page, mode viewMode, period string) (*EconomicsView, error)`: the period's dates are computed per request from `s.now()`. The remote facts are cached: one entry per day of usage (`{"", "", economicsPart(day)}`, loader `loadEconomicsDay`: the day's metrics, edge and storage objects that `sweepUsage` and `foldStorageAndCensus` read, `economicspass.go:318`, `:486`; `liveWindow` for today, `writtenWindow` for earlier days), the active scenario and scenario names (`economics-scenarios`, `writtenWindow`), the recent bills (`economics-bills`, `writtenWindow`) and the fleet meter objects (`economics-fleet-meters`, `liveWindow`). Then `buildEconomicsView` (`economicsview.go:401`) runs per request over those facts. The account names and tiers (`Accounts`, `AccountTiers`, SQLite), the registry attribution (`loadRoutesForEconomics`, `:729`, and `ListFleets`/`ListFleetBoxes`) and the period arithmetic are read and computed per request, never cached. *(Astra round 4, finding 2.)* |
| + - `func (s *Server) economicsView(ctx context.Context, p *page, mode viewMode, period string) (*EconomicsView, error)`: the period's dates are computed per request from `s.now()`. The remote facts are cached: one entry per day of usage (`{"", "", economicsPart(day)}`, loader `loadEconomicsDay`: the day's metrics, edge and storage objects that `sweepUsage` and `foldStorageAndCensus` read, `economicspass.go:318`, `:486`; `liveWindow` for today, `writtenWindow` for earlier days), the active scenario and scenario names (`economics-scenarios`, `writtenWindow`), the bills, one entry per month (`{"", "", economicsBillPart(month)}`, `writtenWindow`, loader `loadEconomicsBill`; the request picks the months `loadRecentBills` reads today, `economicsview.go:801`, from `s.now()`), and the fleet meters, one entry per fleet, box and day (`{"", "", economicsFleetMeterPart(fleet, box, day)}`, `liveWindow` for today, `writtenWindow` before; the request picks the triples from the registry's `ListFleets`/`ListFleetBoxes` and the period's dates, as `fleetMeters` picks objects today, `economicspass.go:667-700`). A key never stands for a set of objects chosen by local state or the clock; it names the objects it reads. *(Astra round 5, finding 1.)* Then `buildEconomicsView` (`economicsview.go:401`) runs per request over those facts. The account names and tiers (`Accounts`, `AccountTiers`, SQLite), the registry attribution (`loadRoutesForEconomics`, `:729`, and `ListFleets`/`ListFleetBoxes`) and the period arithmetic are read and computed per request, never cached. *(Astra round 4, finding 2.)* |
| - Both screens use their loaders, never `LoadMetrics`' or `LoadEconomics`' inner caches, whose hits record no reads. The inner caches stay for the callers that use them today (the CLI's economics door, `OwnerAppMetrics` outside views). |
| - `func (s *Server) storeUsageView(ctx context.Context, p *page, mode viewMode) (storeUsage, error)` (`partStoreUsage`; loader `loadStoreUsage`; what `storeBucketCount` returns) |
| - `func (s *Server) architectureView(ctx context.Context, p *page, mode viewMode) (architectureData, error)`: cached facts are the inventory object and the active scenario (`partArchitecture`, `writtenWindow`, loader `loadArchitectureFacts`), `fleet.json` (`partFleetJSON`) and the boxes (`partBoxes`); the registry route list and the rate card's arithmetic are joined per request. |
| @@ -580,8 +583,11 @@ Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the sha |
| - `TestStoreDecisionShowsOnRedirect`: warm `/fleet/store` and the applicant account's settings; approve; both redirect targets show the decision with zero S3 calls. |
| - `TestEconomicsSaveShowsOnRedirect`: warm `/fleet/economics` (and, with it, `LoadEconomics`' inner cache through the CLI economics door); save a changed active scenario; follow the redirect: the page shows the new scenario. Again with the view's sweep held in flight (`HoldNext("list", …)` on one of its listings) when the save lands: after release, the page still shows the new scenario. |
| - Remove `TestScenarioActivationRefreshesArchitecture`'s skip (Task 8). |
| + - `TestBillSaveAcrossMonthRolloverShows`: `fx.clock` at 23:59 on 31 October; warm `/fleet/economics` (October's and September's bill entries); move the clock to 00:01 on 1 November; save November's bill; the redirect shows it (November's entry is primed by the save's re-read or loads as a miss; never October's set reused). |
| + - `TestEconomicsPeriodSwitchReadsItsOwnDays`: warm `mtd`; switch to `7d` and to `last`: each view's totals equal an uncached `LoadEconomics` for that period over the same store, and the entries used are exactly that period's days. |
| + - `TestNewFleetShowsInEconomics`: register a fleet with one box in the registry (no store write) with a meter object for today; the next economics view counts it. |
| - `TestTierSaveShowsOnRedirect`: warm `/fleet/economics/accounts` (and `/fleet/economics`); save a new tier for an account through `/fleet/economics/tier`; follow the redirect: the account's tier and its revenue line are the new ones. The tier is SQLite, joined per request, so no invalidation is involved, and the test pins that. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestStoreQueueRefused|TestStoreDecisionShows|TestEconomicsSaveShows|TestScenarioActivationRefreshesArchitecture|TestTierSaveShowsOnRedirect|TestViewLoadersAreRestricted' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestStoreQueueRefused|TestStoreDecisionShows|TestEconomicsSaveShows|TestScenarioActivationRefreshesArchitecture|TestTierSaveShowsOnRedirect|TestBillSaveAcrossMonthRollover|TestEconomicsPeriodSwitch|TestNewFleetShowsInEconomics|TestViewLoadersAreRestricted' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestFleet|TestStoreApprovals|TestEconomics|TestArchitecture|TestArchPage|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| - [ ] **Step 5: Keep every operator screen's `over:` record**, in both cases. In `viewBlocking` mode each of them still waits for its remote reads on the walk's cold request (plan 1 Task 10), and only Part 3's Task 13, which adds their placeholders, makes the cold request fast. Each record's reason becomes "blocks on a cold view until operator-pages Task 13"; that task deletes them. Walk (PASS: warm views have zero remote calls and are fast; the recorded screens are exempt from the cold check). Commit, message `console: cache-backed loaders for the operator pages, for Part 3`, ending with the Co-Authored-By line. *(Astra round 3, finding 2.)* |
| @@ -623,6 +629,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 5 (`CODEX-FINDINGS-CONSOLE-PLANS-R5.md`):** 1 bills per month and fleet meters per fleet, box and day, selected per request, with rollover and period-switch witnesses (Task 15); 2 edge files and per-fleet snapshots cached as raw facts, liveness and the expected inventory derived per request, and a reviewed callee list for cross-package calls (Tasks 6, 11); 3 the app-host capability `env.AppHost`, host chosen per request and keyed (Tasks 6, 11); 4 errors cached as text (Tasks 5, 6, 9); 5 the `carlos:part` payload stated as the contract (Task 7). |
| - **Astra round 4 (`CODEX-FINDINGS-CONSOLE-PLANS-R4.md`):** rule (a) made structural, `viewLoadEnv` and `TestViewLoadersAreRestricted` (Task 6); 1 published and in-flight read sets, published replaced only on success (Task 6); 2 economics caches per-day usage, scenario, bill and fleet-meter facts, with tiers, accounts, registry and period derived per request, plus a tier-save witness (Task 15); 3 one metrics entry, loader, type and window (Task 9, consumed by Task 15); 4 catch-all caches manifest and TXT facts, rows per request (Task 13); 5 a tombstone primer (Tasks 8, 14); 6 the coverage oracle walks `perfWalkTargets` (Task 8). |
| - **Astra round 3 (`CODEX-FINDINGS-CONSOLE-PLANS-R3.md`):** the class behind R1-2, R2-4 and R3-3 is fixed by invalidating by read set (Task 8), checked by the coverage oracle in `TestClaimConsoleMutationInvariant` and the warm-before-write cases (deploy-empty on ship, record hosts and environments on instance create, Architecture on scenario activation); the scripts class (R2-3, R3-5) by the no-script-in-fragments rule, the `carlos:part` event and `app_new.html`'s initializer (Tasks 7, 14); 2 operator records kept until operator-pages Task 13 in both orders (Task 15); 4 the host picker is its own part (Task 12); 6 untracked fixtures read inline, so plan 1's instrumentation tests keep their meaning, and background attribution is asserted (Tasks 8, 9, 11); 9 `bgWork` and `waitBackground` cover every request-triggered worker (Task 6); R2-6 `Assemble` takes `now` (Task 9). |
| - **Astra round 2 (`CODEX-FINDINGS-CONSOLE-PLANS-R2.md`):** 1 the pager kept, one cache entry and fragment per page (Tasks 8, 10); 4 economics saves empty and generation-guard `LoadEconomics`' inner cache before re-reading (Tasks 8, 15); 5 filter keys are a hash of the whole effective filter (Task 12); 6 only clock-independent facts are cached and bake state is derived per request from `s.now()` (Tasks 6, 9); 7 the cold pass reset is `resetForColdView` (Task 6; plan 1 Task 10 runs it); 8 is plan 1's; 12a the cold Versions test warms the core through Activity (Task 10); R1 #14 counts come from the S3 fake at the transport (plan 1 Task 9), so `Keys`, `SetFail` and `HoldNext` act on real requests and `HoldNext` can hold a listing (Task 2). |
diff --git a/docs/superpowers/plans/2026-10-25-operator-pages.md b/docs/superpowers/plans/2026-10-25-operator-pages.md| index 5d0d3c701..940d65740 100644 |
| --- a/docs/superpowers/plans/2026-10-25-operator-pages.md |
| +++ b/docs/superpowers/plans/2026-10-25-operator-pages.md |
| @@ -365,23 +365,31 @@ file LICENSE LICENSE 3f3d9e0024b1921b067d6f7f88deb4a60cbe7a78e76c64e3f1d7fc3b779 |
| **Interfaces:** |
| - Produces: |
| - - `func (s *Store) migrateOperatorPages() error`: `ALTER TABLE users ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0;` (a "duplicate column" error is swallowed, as the ALTER list does), `CREATE INDEX IF NOT EXISTS audit_by_time ON audit (created_at);`, `CREATE INDEX IF NOT EXISTS audit_by_account ON audit (account_id, id);`, `CREATE INDEX IF NOT EXISTS sessions_by_time ON sessions (created_at, address);`, `CREATE INDEX IF NOT EXISTS users_by_created ON users (created_at);`, `CREATE INDEX IF NOT EXISTS users_by_last_seen ON users (last_seen);`, `CREATE INDEX IF NOT EXISTS memberships_by_address ON memberships (address, added_at);`, `CREATE INDEX IF NOT EXISTS apps_by_creator ON apps (created_by);`. |
| + - `func (s *Store) migrateOperatorPages() error`: `ALTER TABLE users ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0;` (a "duplicate column" error is swallowed, as the ALTER list does), `CREATE INDEX IF NOT EXISTS audit_by_time ON audit (created_at);`, `CREATE INDEX IF NOT EXISTS audit_by_account ON audit (account_id, id);`, `CREATE INDEX IF NOT EXISTS sessions_by_time ON sessions (created_at, address);`, `CREATE INDEX IF NOT EXISTS users_by_created ON users (created_at);`, `CREATE INDEX IF NOT EXISTS users_by_last_seen ON users (last_seen);`, `CREATE INDEX IF NOT EXISTS memberships_by_address ON memberships (address, added_at);`, `CREATE INDEX IF NOT EXISTS apps_by_creator ON apps (created_by);`, `CREATE INDEX IF NOT EXISTS audit_by_action ON audit (action, id);`. |
| - `type OperatorAccount struct { ID int64; Sqid, Name string; Deleted bool }`; `func (s *Store) OperatorAccountBySqid(sqid string) (*OperatorAccount, error)`: the account row whatever its `deleted_at` (nil when there is no row). Operator pages only: its doc comment says it must never back a member-facing lookup, which keeps using `AccountBySqid` and its tombstone exclusion (`store.go:1068`). |
| - `func (s *Store) TouchLastSeen(address string, now time.Time) error`: `UPDATE users SET last_seen = ? WHERE address = ? AND last_seen < ?` (never moves backwards; no row, no insert). |
| - `type OperatorCounts struct { People, Active30, Active7, ActiveToday, NewPeople7, NewPeoplePrev7, NewAccounts7, NewAccountsPrev7, Apps, NewApps7, DeploysToday, DeployApps int }`; `func (s *Store) OperatorCounts(now time.Time) (OperatorCounts, error)` with the windows from "Decisions" (active, set-based, never a correlated subquery: `SELECT COUNT(*) FROM (SELECT address FROM users WHERE last_seen >= ?1 UNION SELECT address FROM sessions WHERE created_at >= ?1)`, served by `users_by_last_seen` and the covering `sessions_by_time`; deploys: `audit.created_at >= <UTC midnight> AND action IN deployActions`, `DeployApps` = distinct `(account_id, app)` among them). |
| - `var deployActions = []string{"promote", "rollback"}` (check both strings against the `Action:` values in `server.go` and `apicli.go` before writing them). |
| - `type DayCount struct { Day time.Time; N int }`; `func (s *Store) NewPeoplePerDay(now time.Time, days int) ([]DayCount, error)`: `days` entries, oldest first, the last one today (UTC), zero-filled; rows created after `now` are not counted. |
| - - Every statement these methods run is a package-level constant (`opSQLActive`, `opSQLNewPeople`, `opSQLNewAccounts`, `opSQLApps`, `opSQLDeploys`, `opSQLPerDay`, `opSQLNewestPeople`, `opSQLPeoplePage`, `opSQLAccountsPage`, `opSQLFeed…` for each filter shape) so the plan witness below can `EXPLAIN QUERY PLAN` exactly what runs. The per-person columns of `NewestPeople` and `PeoplePage` (accounts, first account, apps) are computed only for the page's rows: the `LIMIT`/`OFFSET` is applied in an inner query over `users`, and the outer query looks each row up through `memberships_by_address` and `apps_by_creator`. |
| + - Every statement these methods run is a package-level constant (`opSQLPeopleTotal`, `opSQLActive`, `opSQLNewPeople`, `opSQLNewAccounts`, `opSQLApps`, `opSQLDeploys`, `opSQLPerDay`, `opSQLNewestPeople`, `opSQLPeoplePage`, `opSQLAccountsPage`, `opSQLFeed…` for each filter shape) so the plan witness below can `EXPLAIN QUERY PLAN` exactly what runs. The per-person columns of `NewestPeople` and `PeoplePage` (accounts, first account, apps) are computed only for the page's rows: the `LIMIT`/`OFFSET` is applied in an inner query over `users`, and the outer query looks each row up through `memberships_by_address` and `apps_by_creator`. |
| - `type PersonRow struct { Address string; Joined, LastSeen time.Time; Accounts int; FirstAccount string; Apps int }` (`LastSeen` zero when never seen; `FirstAccount` `""` when none); `func (s *Store) NewestPeople(limit int) ([]PersonRow, error)` (newest `created_at` first, ties by address); `func (s *Store) PeoplePage(q string, offset, limit int) ([]PersonRow, int, error)` (filtered by address `LIKE` with `ESCAPE '\'`, `%`, `_` and `\` escaped; newest first; returns the filtered total). |
| - `type AccountRow struct { ID int64; Sqid, Name, Plan string; Created time.Time; Apps, Members int }`; `func (s *Store) AccountsPage(q string, offset, limit int) ([]AccountRow, int, error)` (live accounts, `name` or `sqid` matching literally, newest first; `Plan` from `account_plans.plan`, `""` when none). |
| - - `type ActivityFilter struct { AccountID int64; Actions, Exclude []string }` (`AccountID` 0 means every account, and `-1` means "an account matched nothing", which answers no rows without a query); `type FeedRow struct { ID int64; At time.Time; Address, AccountName, AccountSqid, App, Action, Detail string }`; `func (s *Store) ActivityFeed(f ActivityFilter, beforeID int64, limit int) ([]FeedRow, error)` (`ORDER BY audit.id DESC`, `id < beforeID` when `beforeID > 0`, `LEFT JOIN accounts` for name and sqid, deleted accounts included). |
| + - `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). Its shapes, each a constant: no filter walks `audit` by primary key newest first and stops at `limit`; `AccountID` alone walks `audit_by_account`; `Actions` runs one `WHERE action = ? AND id < ? ORDER BY id DESC LIMIT ?` per action through `audit_by_action` and merges the at most `limit × len(Actions)` rows in Go, newest first, cut to `limit` (so a rare kind never walks the whole table and no query sorts); `Actions` with `AccountID` runs the per-account walk with the action test in the row; `Exclude` (the `other` kind, most rows) walks by primary key with the exclusion in the row. |
| Every method is a read on `s.db` except `TouchLastSeen`, which writes `users`, a NonApp table (`store_gate.go:204`), so it needs no claim SQL adapter and passes the gate on a host-claim console. No method reaches a raw handle, so `TestClaimSQLSeamCallers` is unaffected. *(My call: new reads go in their own file with their own migration, "for the same reason" the other features' tables do, `store.go:524-551`.)* |
| - [ ] **Step 1: Write the failing tests** in `opstore_test.go`, each on a store from `Open(filepath.Join(t.TempDir(), "console.db"))` with rows written through the existing methods at fixed times (`now := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)`): `EnsureUser`, `CreateSessionMethod`, `CreateAccount`, `AddMember`, `DeleteAccount`, `RecordActivity`, `RecordEvent`, `SetAlertSeen` (or whatever writes `alert_seen`, `store.go:2277`), and the app-claim method the fixtures use. |
| - - `TestMigrateOperatorPagesIsIdempotent`: `Open` twice on one path; `PRAGMA index_list` names all seven new indexes on their tables; `users` has `last_seen`. |
| - - `TestOperatorQueryPlans` (the witness): on a store migrated by `Open`, `EXPLAIN QUERY PLAN` of every `opSQL…` constant with representative arguments. No plan line contains `CORRELATED`. `sessions`, `audit` and `users` appear only as `SEARCH … USING INDEX` or `… USING COVERING INDEX`, with two named exceptions where a scan is the query: `users` in `opSQLPeoplePage` with a non-empty search (a `LIKE '%q%'` cannot use an index) and `audit` in the `other` kind's `NOT IN` feed, which walks `audit` by primary key newest first and stops at its `LIMIT` (asserted as `SCAN audit` with no `USE TEMP B-TREE`). `accounts`, `apps`, `memberships` and `account_plans` may be scanned only in `opSQLApps` and `opSQLAccountsPage`, bounded by the number of accounts and apps. Removing `sessions_by_time` (by hand, once) makes it fail with the old `CORRELATED SCALAR SUBQUERY` shape. |
| - - `TestOperatorCountsAtScale`: a store with 20,000 users, 60,000 sessions over 30 days, 2,000 accounts, 8,000 apps and 200,000 audit rows (inserted in one transaction through a test helper); `OperatorCounts`, `NewPeoplePerDay`, `NewestPeople`, the first `PeoplePage` and each feed kind's first page are timed; each is printed, and under `CI` each must finish within 20 ms. Not parallel; listed in `.amadan/test-weights.tsv` if it takes a second or more. |
| + - `TestMigrateOperatorPagesIsIdempotent`: `Open` twice on one path; `PRAGMA index_list` names all eight new indexes on their tables; `users` has `last_seen`. |
| + - `TestOperatorQueryPlans` (the witness): on a store migrated by `Open`, `EXPLAIN QUERY PLAN` of every `opSQL…` constant with representative arguments, checked against that query's own intended access pattern, written as a table `opQueryPlans` (`name`, the constant, its args, the plan lines that must appear, the lines that must not). Every query forbids `CORRELATED` and `USE TEMP B-TREE FOR ORDER BY`; beyond that each states its pattern: |
| + - `opSQLPeopleTotal` (`COUNT(*) FROM users`): a total-count scan, `SCAN users USING COVERING INDEX …`. |
| + - `opSQLActive`: `SEARCH users USING … INDEX users_by_last_seen` and `SEARCH sessions USING COVERING INDEX sessions_by_time`, combined by the `UNION` (its `USE TEMP B-TREE FOR UNION` is allowed: it holds only addresses in the window). |
| + - `opSQLNewPeople`, `opSQLPerDay`: `SEARCH users USING COVERING INDEX users_by_created`. |
| + - `opSQLNewestPeople` and `opSQLPeoplePage` with no search: a bounded ordered scan, `SCAN users USING INDEX users_by_created` stopped by `LIMIT`/`OFFSET`, with the per-row `SEARCH memberships USING INDEX memberships_by_address` and `SEARCH apps USING INDEX apps_by_creator`; with a search, `SCAN users` (a `LIKE '%q%'` cannot use an index). |
| + - `opSQLDeploys`: `SEARCH audit USING INDEX audit_by_time`. |
| + - `opSQLFeedAll`: a bounded ordered scan, `SCAN audit` (by primary key, newest first, stopped by `LIMIT`); `opSQLFeedBefore`: `SEARCH audit USING INTEGER PRIMARY KEY (rowid<?)`; `opSQLFeedAccount`: `SEARCH audit USING INDEX audit_by_account`; `opSQLFeedAction`: `SEARCH audit USING INDEX audit_by_action (action=? AND rowid<?)`; `opSQLFeedOther`: `SCAN audit` as for all. |
| + - `opSQLApps`, `opSQLAccountsPage`: scans of `accounts`, `apps`, `memberships` and `account_plans` are allowed, bounded by the number of accounts and apps. |
| + The pattern check is shown to bite twice, by hand, once each: dropping `sessions_by_time` turns `opSQLActive`'s sessions line into `SCAN sessions` and fails; rewriting `opSQLActive` in the earlier per-user `EXISTS` form fails on `CORRELATED SCALAR SUBQUERY`. |
| + - `TestOperatorCountsAtScale`: a store with 20,000 users, 60,000 sessions over 30 days, 2,000 accounts, 8,000 apps and 200,000 audit rows (inserted in one transaction through a test helper); `OperatorCounts`, `NewPeoplePerDay`, `NewestPeople`, the first `PeoplePage` and each feed kind's first page (with and without an account filter, and with a rare kind of 50 rows among the 200,000) are timed; each is printed, and under `CI` each must finish within 20 ms. Not parallel; listed in `.amadan/test-weights.tsv` if it takes a second or more. |
| - `TestTouchLastSeenNeverMovesBack`: touch at `now`, then at `now-1h`: `last_seen` stays `now`; a touch for an unknown address inserts nothing. |
| - `TestOperatorCountsWindows`: users created at `now-1h`, `now-6d`, `now-8d`, `now-13d`, `now-20d`; accounts at `now-2d`, `now-10d`; apps (one deleted); audit `promote` rows today for two apps and one yesterday; `last_seen` for two people and a session at `now-3d` for a third → `People 5`, `NewPeople7 2`, `NewPeoplePrev7 2`, `NewAccounts7 1`, `NewAccountsPrev7 1`, `Active30 3`, `DeploysToday 2`, `DeployApps 2`, `Apps` excludes the deleted one. |
| - `TestNewPeoplePerDayFillsZeroDaysAndIgnoresFuture`: three users today, one 29 days ago, none between, one at `now+1h`: 30 entries, `[0].N == 1`, `[29].N == 3`, every other `N == 0`, `[29].Day` is 2026-10-25 UTC midnight. |
| @@ -581,30 +589,31 @@ Each loop wraps one pass in `s.jobs.Run` with its worker name as a string litera |
| **Interfaces:** |
| - 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; 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 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; Boxes []dashBox; Now time.Time; Alerts []FiringAlert; AlertsKnown bool; StorePending *int; Jobs []JobStatus }`, where `Boxes` is the very slice the Boxes table renders, built once per request by `dashBoxes` from `HostRows` (staleness judged at request time, `status.BoxStale` against `now`), `fleet.json` and `now`; `func attentionItems(in attentionInput) (items []attentionItem, tone string)`: one item per row of `Boxes` whose status is Silent (OPS-24, link Boxes `#box-<label>`), which covers a box only `HostRows` lists, and never reads `FleetBox.Stale`, 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)`) 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. |
| +`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"}}`, a partial of the dashboard body: 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` (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`. |
| + - `TestAttentionItemsEachCondition` (not acceptance, table-driven over `attentionItems`): nothing wrong gives no items and `positive`; a `Boxes` row with status Silent gives OPS-24 with the label and `warning`, and a `FleetBox.Stale` with no Silent row gives nothing (the callout reads only `Boxes`); `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"`. |
| + - `TestAttentionAndBoxesAgreeAcrossTheFifteenMinuteLine`: a box heartbeat at `now − 14 min` and a `fleet.json` built at `now − 2 min` with that box not stale; warm `/fleet` (Healthy row, no box item). Move `fx.clock` 2 minutes (the heartbeat is now 16 minutes old; the summary is 4 minutes old, so not itself stale) and GET again with no new reads: the row is Silent and the callout lists OPS-24 for that box with `warning`. A second box present only in `HostRows` (absent from `fleet.json`) and dark is listed in both too. The same holds on the assembled page after a cold load in which the box entry arrived late (the whole-body part, Task 13), checked there. |
| - `TestDashboardBoxStatuses` (not acceptance, over `dashBoxes`): comfortable is Healthy, busy is Busy (warning), critical is Busy (negative), a stale `HostRow` is Silent with no meter, a summary older than 15 minutes makes every row Stale, a `FleetBox` with no `HostRow` is Silent; an empty region is OPS-76. |
| - `TestDashboardLatestActivityAndNewestPeople`: newest 10 activity rows, newest first, with `none` for the sign-in's app; the newest five people with their first account. |
| - `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.) |
| - 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 2: Run** `go test ./internal/console/ -run 'TestAttentionItems|TestAttentionAndBoxesAgree|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`. |
| @@ -692,21 +701,22 @@ Each page: `op_top`, `op_page_header` (its rail label and its subhead row), then |
| - Produces: |
| - the seams now read through the loaders: `opFleetJSON` → `fleetJSONView(ctx, p, mode)`, `opHostRows` → `hostRowsView`, `opStorePending` → `storePendingView` (still only for a store operator); each seam gains a `mode viewMode` parameter. |
| - `const boxesWindow = 60 * time.Second`: the window the per-box entry (`{"", "", partBoxes}`, plan 2's key) is read with. If plan 2 Task 15's `hostRowsView` uses `liveWindow` (30 s), Task 13 gives it a window parameter and passes `boxesWindow` from both the dashboard and Boxes, so they share one entry. *(My call on the exact value, from the coordinator's "~60 s".)* |
| - - `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`. |
| + - `var fleetParts map[string]viewPart` with `dashboard`, `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. |
| - - **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. |
| + - **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`). The event's payload is plan 2's `detail: {part, root}` (`part` the part name, `root` the inserted element). Each economics page's script adds `document.addEventListener("carlos:part", e => { if (e.detail && e.detail.part === "economics") econInit(e.detail.root) })`, and the accounts page the same with `"economics-accounts"` and `econAccountsInit`; each initializer finds `#econ-body` inside `root` (the part's root is that wrapper or contains it) before it binds anything. |
| - 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.)* |
| +On a miss of either `fleet.json` or the box entry, the dashboard's whole body is the deferred part: the callout and the Boxes table must come from the same box evidence (Task 9's `attentionInput.Boxes`), so neither renders without it. A stale entry is served at once, so this costs only the first view after a start or an invalidation. *(My call; replaces the earlier separate `dashboard-boxes` part, which could show a callout built without the box rows beside them.)* |
| **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, `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 `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. |
| + - `TestDashboardWaitsForBoxEvidenceAsAWhole`: `held, release := lat.HoldNext("list", func(p string) bool { return p == "status/boxes/" })`; GET `/fleet` (cold): within 150 ms, the whole-body placeholder `data-part="/fleet/part/dashboard"` and no callout; wait for `held`, then join the `fleet.json` and storage-queue loads through the seams in blocking mode (`fx.srv.opFleetJSON(ctx, &page{}, viewBlocking)`, `fx.srv.opStorePending(ctx, &storePage, viewBlocking)`, 5 s deadline); GET `/fleet` again: still the whole-body placeholder, never a callout without box rows. `release()`; the assembled page's callout and Boxes table agree (the dark seeded box is Silent in the table and listed as OPS-24 in the callout). Then advance `fx.clock` across the fifteen-minute line for the fresh box as in Task 9's test: the next assembled view, served from the cache, marks it Silent in both places. 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 the `carlos:part` event plan 2's real `partloader` dispatches (no synthetic event; the harness only listens, checking `e.detail.part === "economics"`), then, after the page's own listener has run, 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. |
| + - `TestEconomicsListenerMatchesThePartLoaderPayload` (no browser): the rendered `partloader` (plan 2's partial, from the real template set) dispatches `carlos:part` with a `detail` carrying `part` and `root`; each economics frame's listener reads `e.detail.part` and `e.detail.root` and nothing else from `detail`, compares `part` with a name that is a `fleetParts` key (`economics`, `economics-accounts`), and passes `root` to its initializer. A listener that read `e.detail.id` or passed `e.detail` itself fails it. |
| - `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. |
| @@ -718,7 +728,7 @@ On a `fleet.json` miss, the dashboard's whole body is the deferred part, because |
| - `TestOperatorPagesJoinLocalStatePerRequest`: warm `/fleet`, `/fleet/store` and `/fleet/economics/accounts`; then, with no object-store write: rename an account in SQLite (the economics accounts table shows the new name at once), delete the account whose storage application is pending (the store page and the dashboard's storage item drop it at once), and move `fx.clock` 16 minutes (the dashboard says the fleet summary is old and the boxes read Stale at once); every one with zero S3 requests. |
| - `TestDashboardCountsAreNeverCached`: warm `/fleet`; create a user and an audit row through the store (no object-store write); the next GET's counts and Latest activity include them at once, with zero S3 requests (rule (a)). |
| - `TestEveryOperatorPageRendersInTheShell` and the page tests from Tasks 3 to 12 read assembled pages (`getAssembled`) and still pass. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestDashboardCold|TestDashboardBoxesCold|TestBoxReadsOncePerWindow|TestEveryFleetPart|TestDashboardAfterAStore|TestEconomicsScenarioSaveWarm|TestArchitectureRefreshWarm|TestDashboardCountsAreNeverCached|TestOperatorPagesJoinLocalState|TestEconomicsEditAndSave|TestEconomicsPartIsInitialised|TestEveryOperatorPage' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestDashboardCold|TestDashboardWaitsForBoxEvidence|TestBoxReadsOncePerWindow|TestEveryFleetPart|TestDashboardAfterAStore|TestEconomicsScenarioSaveWarm|TestArchitectureRefreshWarm|TestDashboardCountsAreNeverCached|TestOperatorPagesJoinLocalState|TestEconomicsEditAndSave|TestEconomicsListenerMatches|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`. If this task lands on `operator-pages-cache`, run Task 15 on that branch with `NAME=operator-pages-cache`. |
| @@ -772,8 +782,9 @@ ls "$SHOTS"/*.png | wc -l # 44 |
| - **Astra round 2 (`d9e0277a`), findings that applied here:** 3, economics initializers run after fragment insertion, with an edit-and-save test after a cold load (Tasks 12, 13); 9, the six account actions are recorded on claim-gated consoles through the gate's `FreeWhenNoApp` rule, with its own gate review (Task 6A; the follow-up discussion is gone); 10, the last-seen hour is reserved under one mutex and write attempts are counted under concurrency (Task 5); 11, swallowed per-item failures mark the run Failed in every pass, with an AST check and an injected alert failure seen on the dashboard (Tasks 7, 9); 12b, plan 2's `HoldNext("list", …)` (no hold helper of this plan's own) and joining in-flight loads through the seams in blocking mode (Task 13); 12c, mux canonicalisation tested apart from the unknown-asset 404 (Task 2). |
| - **Astra round 3 (`4d963091`), findings that applied here:** 7, the dashboard reads an in-process projection of what is firing now, kept by the watcher from the published objects, one entry per rule, with firing-then-cleared across a recipient change tested (Task 7A, Task 9); 8, explicit walk targets for every query-selected view (`?show=accounts`, searches, pages, every activity kind, an account filter, a deep `before`) over a populated fixture, with a test that each `show` and `kind` has one (Tasks 9, 10, 11); R2-12c, the traversal test follows each hop of the mux's redirect chain to the final 404, apart from the unknown-asset 404 (Task 2). Economics initializers follow plan 2's no-script rule for fragments (the data moves to an attribute) and its `carlos:part` event (Tasks 12, 13). |
| +- **Astra round 5, findings that applied here:** 5, the economics listeners read plan 2's `{part, root}` payload and are tested against the real `partloader` (Task 13); 6, the callout and the Boxes table come from one per-request `dashBoxes` slice built from `HostRows` at request time, the separate box part is gone, and the 14-to-16-minute case is tested on the page and after a cold load (Tasks 9, 13); 7, the query-plan witness checks each query's own access pattern, allowing total-count and bounded ordered scans, kind filters go through `audit_by_action` one action at a time, the bite checks are stated correctly, and the scale witness stays (Task 4). |
| - **Astra round 4, findings that applied here:** 7, active counts are set-based over new covering indexes, with an `EXPLAIN QUERY PLAN` witness over every statement and a scale run (Task 4); 9, each landing branch has its own census NAME, card, overlay and ruling (Branch, Tasks 13, 15); 10, the Activity filter resolves accounts with an operator-only, tombstone-inclusive lookup, and following a deleted account's link is tested (Tasks 4, 11). Plan 2's restricted load environment: every operator load caches only object-store facts, with per-request builders for the rest (Global Constraints, Task 13). |
| - **Plan 2's read-set redesign (coordinator, 2026-10-25).** This plan no longer leans on a per-door effect table. Only the seven object-store loads above are cached; every SQLite count and list, the job registry and the alert projection are read per request; status words and ages are joined per request; the operator writes (store approve and decline, economics scenario save, architecture refresh) are covered by read-set invalidation with warm-before-write tests (Task 13). |
| - **Coordinator change (2026-10-25).** The dashboard's Boxes table keeps the mockup's columns from `HostRows` through the view cache (Decisions, Tasks 9 and 13); the spec's "`HostRows`' per-box reads stay off the dashboard" is met by keeping them off the request path of a warm view, with the per-window cost stated in Task 13. |
| - **Spec coverage.** §3.1: copy in (Task 2), `go:embed`, own origin, long cache, content hash (Task 2), `VERSION` and hash test (Task 2), MPL notice (Task 2, via `LICENSE` since the files carry no header), no `light.js` (not copied), fetches nothing (Task 3's shell test). §3.2: one layout ported from `console.html` (Task 3), brand and account menu with Customer console and Sign out (Task 3), rail order and labels (Tasks 1, 3), below 800 px index and page (Task 3's `/fleet/index`, Task 14), light and dark through the theme (Tasks 2, 14), `operatorOnly` unchanged (Task 3's gate test, every page task). §3.3: dashboard, page header, needs attention with all five conditions, the stats band, the 30-day bars with screen-reader numbers, newest people, latest activity, boxes, background jobs (Task 9); old `/fleet` content to Boxes (Task 8); errors and edge failures out of scope (not built). §3.4: `last_seen` with the hourly throttle (Tasks 4, 5), account-level audit rows and the feed newest-first with an index for time-window counts (Tasks 4, 6, 11), job registry, in-process, Not run yet after restart (Task 7), counts from SQLite and `fleet.json` through the view cache, per-box rows from `HostRows` through the cache too, never on a warm view's request path (Tasks 4, 9, 13), 150 ms and one S3 read (Tasks 9, 13). §3.5: People and accounts (Task 10), Activity (Task 11), Boxes plus jobs (Task 8), Metrics with Console speed, Storage requests, Economics with seg-tabs and a list-bar, Architecture (Tasks 3, 12), old URLs keep working (all registrations kept; `/fleet` stays 200). §3.6: one `<h1>`, rail `aria-current`, no inline style (Task 3, every page), screenshots (Task 14), every page in the walk (Tasks 2 to 13), Luna copy pass (Task 1). §3.7: lands after plan 1, alongside plan 2 and Part 1, Task 13 after plan 2 Task 15. |
| -- **Names that cross plans.** From plan 1: `consolePerfSkip`, `PerfGroups`, `consoleSpeedRows`, `newConsoleFixtureWith`, `newPerfFixture`, `perfInventory`, `perfTargets`, `loadPerfBudgets`, `TestConsoleScreensMeetTheBudget`, the budgets grammar. From plan 2: `viewGet`, `viewMode`, `viewCached`, `viewBlocking`, `errViewPending`, `viewPart`, `renderView`, `getAssembled`, `perfLatency` (`Calls`, `SetFail`, `Keys`, `Writes`, `ResetKeys`, `HoldNext`), `perfQuiesce`/`waitBackground`, `s.bg.Go`, the four partials, Task 8's read-set invalidation (no per-door declaration), `viewLoader`, `viewLoadEnv`, `viewloaders.go` and its `load…` functions (`loadFleetJSON`, `loadBoxSnapshot`, `loadStorePending`, `loadStoreUsage`, `loadMetricsFacts`, `loadEconomicsDay`, `loadArchitectureFacts`), `metricsFacts`, `buildEconomicsView`, and Task 15's seven views. This plan's names used across its own tasks: `assetURL`, `opShell`, `opRail`, `opPage`, `op_top`/`op_bottom`, the `op_*` partials and their data types, `opPages`, `opNumber`, `signInOperator`, `operatorScreens`, `opShellPending`, `assertOpShell`, `deployActions`, `accountAuditActions`, `OperatorCounts`, `DayCount`, `PersonRow`, `AccountRow`, `ActivityFilter`, `FeedRow`, `FiringAlert`, `TouchLastSeen`, `OperatorAccountBySqid`, `OperatorAccount`, the `opSQL…` constants, `noteSeen`, `alertNow`, `alertsNow`, `seedOperatorScale`, `peopleShows`, `auditAccount`, `jobRegistry`, `jobFailed`, `JobStatus`, `opJobRows`, `opFleetJSON`, `opHostRows`, `opStorePending`, `seedOperatorWorld`, `fleetParts`, `handleFleetPart`. |
| +- **Names that cross plans.** From plan 1: `consolePerfSkip`, `PerfGroups`, `consoleSpeedRows`, `newConsoleFixtureWith`, `newPerfFixture`, `perfInventory`, `perfTargets`, `loadPerfBudgets`, `TestConsoleScreensMeetTheBudget`, the budgets grammar. From plan 2: `viewGet`, `viewMode`, `viewCached`, `viewBlocking`, `errViewPending`, `viewPart`, `renderView`, `getAssembled`, `perfLatency` (`Calls`, `SetFail`, `Keys`, `Writes`, `ResetKeys`, `HoldNext`), `perfQuiesce`/`waitBackground`, `s.bg.Go`, the four partials, Task 8's read-set invalidation (no per-door declaration), `viewLoader`, `viewLoadEnv`, `viewloaders.go` and its `load…` functions (`loadFleetJSON`, `loadBoxSnapshot`, `loadStorePending`, `loadStoreUsage`, `loadMetricsFacts`, `loadEconomicsDay`, `loadArchitectureFacts`), `metricsFacts`, `buildEconomicsView`, and Task 15's seven views. This plan's names used across its own tasks: `assetURL`, `opShell`, `opRail`, `opPage`, `op_top`/`op_bottom`, the `op_*` partials and their data types, `opPages`, `opNumber`, `signInOperator`, `operatorScreens`, `opShellPending`, `assertOpShell`, `deployActions`, `accountAuditActions`, `OperatorCounts`, `DayCount`, `PersonRow`, `AccountRow`, `ActivityFilter`, `FeedRow`, `FiringAlert`, `TouchLastSeen`, `OperatorAccountBySqid`, `opQueryPlans`, `OperatorAccount`, the `opSQL…` constants, `noteSeen`, `alertNow`, `alertsNow`, `seedOperatorScale`, `peopleShows`, `auditAccount`, `jobRegistry`, `jobFailed`, `JobStatus`, `opJobRows`, `opFleetJSON`, `opHostRows`, `opStorePending`, `seedOperatorWorld`, `fleetParts`, `handleFleetPart`. |