Console plans: Astra round 2 fixes across all four plans
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+137
−85
docs/superpowers/plans/2026-10-25-console-perf-1-measure.md+37 −29docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md+39 −29docs/superpowers/plans/2026-10-25-console-ux-nav.md+5 −5docs/superpowers/plans/2026-10-25-operator-pages.md+56 −22
CI failed — 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 80e798ab6..2f0270992 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 |
| @@ -19,10 +19,10 @@ Every task's requirements include this section. |
| - **Targeted local tests; CI runs the full suite.** Run only the touched packages' tests, with `-run`: `go test ./internal/perf/ -count=1`, `go test ./internal/console/ -run 'TestName' -count=1`. Never `make test`, never a whole `internal/console` or root package run. `go build ./...`, `go vet ./...` and `gofmt -l .` stay clean. Prefix go commands with `GOFLAGS=-buildvcs=false` if the sandbox refuses VCS stamping. |
| - **Cross-compiles stay green:** `GOOS=darwin GOARCH=arm64 go build ./...` and `GOOS=windows GOARCH=amd64 go build ./...` before every push. Nothing here needs a Linux-only syscall. |
| - **Go cache:** leave `GOCACHE`, `GOMODCACHE` and `GOTMPDIR` at their defaults (`~/.cache/go-build`). Do not point them at `/tmp` or at a per-task directory, whatever AGENTS.md's sandbox note says. Run go with the sandbox off if the default cache is read-only. |
| -- **Production wiring, not stand-ins.** Every console test here builds the server with `NewServer` through the existing fixture (`newConsoleFixture*`, `internal/console/server_test.go:43-107`), the same constructor `cmd/console` calls (`cmd/console/main.go:520`). The only substitutes are at the seams the spec names for injection: the release store (wrapped, not replaced) and `Config.AppClient`. A pure unit test in `internal/perf` says "not acceptance" in its doc comment. |
| +- **Production wiring, not stand-ins.** Every console test here builds the server with `NewServer` through the existing fixture (`newConsoleFixture*`, `internal/console/server_test.go:43-107`), the same constructor `cmd/console` calls (`cmd/console/main.go:520`). The only substitutes are at the seams the spec names for injection: the object store's far end (a real `release.S3Store` talking to an in-process S3 fake, Task 9) and `Config.AppClient`. A pure unit test in `internal/perf` says "not acceptance" in its doc comment. |
| - **S3 requests cost money.** Nothing in this plan adds an S3 request to any request path, timer or poll. Measuring adds zero requests. |
| - **The budget, verbatim.** A GET or HEAD to a console screen sends its first byte within 150 ms. POST, PUT, DELETE have no budget. A stream or download is judged on when it started answering. No cold-start budget. Groups are route patterns, never paths. Over-budget warnings: at most once a minute per route and 120 a minute overall. Ring: the last 2,048 requests. Skip: `/healthz` (the console serves no static assets: templates are embedded, `internal/console/server.go:64`, and CSS is inline). |
| -- **The CI walk, verbatim.** Ten requests per screen, the first two discarded; the median within 150 ms and no single one over 450 ms. Latency: 25 ms per S3 call, 40 ms per HTTP call to a box or app host. Default allowance: zero remote calls on a warm-cache GET. Fails on timing only when `CI` (or `AMADAN_CI`) is set; locally it prints. Whole test well under 10 s. |
| +- **The CI walk, verbatim.** Ten requests per screen, the first two discarded; the median within 150 ms and no single one over 450 ms. Before them, one cold request per screen within 150 ms (Task 10). Latency: 25 ms per S3 call, 40 ms per HTTP call to a box or app host. Default allowance: zero remote calls on a warm-cache GET. Fails on timing only when `CI` (or `AMADAN_CI`) is set; locally it prints. Whole test well under 10 s. |
| - **Copy goes through a Luna pass before it is written into a template.** Every user-facing string is a row in `docs/superpowers/plans/2026-10-25-console-perf-copy.md` (Task 1), reviewed by Luna (`codex exec -m gpt-5.6-luna`, delegated by Paul for plan copy) before any template carries it. House voice: no em dashes (a full stop and a new sentence, continuing in lower case); human text only (log lines, diagnostics, route patterns and JSON keys are not copy). No tenant names anywhere: code, tests, fixtures and copy use neutral names (`shop`, `example.com`; the existing fixture app `kass` and account `ops` may be reused). |
| - **Console security gate order is unchanged:** session, then CSRF, then owner (byte-identical 404), then `requireFreshAuth`. The perf middleware sits outside the mux and reads nothing from the request but its pattern, method and timing. |
| - **A ResponseWriter wrapper that edits headers needs care** (AGENTS.md, "Rules this repo has paid for"). The perf wrapper adds exactly one header, `Server-Timing`, once, at commit, before the real `WriteHeader`. It keeps `Flush`, `Hijack` and `Unwrap` working. |
| @@ -55,7 +55,8 @@ Every task's requirements include this section. |
| | `internal/console/instances.go` (modify) | box span round `f.client.Do` at `:130`. | |
| | `internal/console/apiversion.go` (modify) | `Versions` caller at `:205`. | |
| | `internal/console/templates/metrics.html` (modify) | the Console speed table. | |
| -| `cmd/console/main.go`, `cmd/console/perfs3.go` (modify, create) | time every S3 request the deployment and seed-data stores make. | |
| +| `cmd/console/main.go` (modify), `internal/console/perfs3.go` (create) | time and count every S3 request the deployment and seed-data stores make. | |
| +| `internal/s3fake/` (create), `internal/release/s3fake_contract_test.go` (create) | an S3 fake for tests that counts at the transport, held to the MinIO contract. | |
| | `docs/superpowers/plans/2026-10-25-console-perf-copy.md` (create) | the copy record, rows `CPF-1` on. | |
| | `approved_console_perf_copy_test.go` (create, repo root) | copy gate, modelled on `approved_asset_cache_copy_test.go`. | |
| | `docs/superpowers/plans/LUNA-COPY-BRIEF-CONSOLE-PERF.md`, `LUNA-COPY-REVIEW-CONSOLE-PERF.md` (create) | the Luna brief and its answer. | |
| @@ -158,7 +159,7 @@ Copy Rastrillo's `Recorder`, `Groups` and `percentile` (nearest rank, `-1` for n |
| - `func SpanContext(ctx context.Context, name string) func()` |
| - `func SpanFor(w http.ResponseWriter, name string) func()`: finds the perf writer by walking `Unwrap() http.ResponseWriter`; a no-op when there is none. |
| - `type Doer interface { Do(*http.Request) (*http.Response, error) }` |
| - - `func TimeDoer(d Doer, name string, c *Recorder) Doer`: each `Do` is one span `name` and one count in `Calls[name]` on the measured request its context belongs to; on a context no measured request owns it counts into `c.countBackground(name)` (a nil `c` drops it). Counting happens at the HTTP boundary, so every page of a paginated listing is one count. A nil `d` uses `http.DefaultClient`. |
| + - `func TimeDoer(d Doer, name string, c *Recorder) Doer`: each `Do` is one span `name` and one count in `Calls[name]` on the measured request its context belongs to; on a context no measured request owns it counts into `c.countBackground(name)` (a nil `c` drops it). Counting happens at the HTTP boundary, so every page of a paginated listing is one count. The span stays open until the response body reaches EOF or is closed (whichever comes first, once), so a prompt header followed by a slow body is charged to `name`; a `Do` that returns an error ends the span at once. A nil `d` uses `http.DefaultClient`. |
| Copy Rastrillo's writer wrapper (`commit`, `WriteHeader` with 1xx passthrough, `Write`, `Flush`/`FlushError` committing first, `Hijack` closing the sample as 101, `Unwrap`, `finish` recording a panic as 500 and re-raising, the lost-route warning, clearing `r2.Pattern` on the copy it passes down, folding unknown methods to `OTHER`). Drop cold start, `Started`, startup and `Label`. `Server-Timing` is `app;dur=%.3f` then each span sorted by name, `, <name>;dur=%.3f`. A GET or HEAD gets `Budget`; other methods get `Budget: 0` and are never over. |
| @@ -167,6 +168,7 @@ Copy Rastrillo's writer wrapper (`commit`, `WriteHeader` with 1xx passthrough, ` |
| - `TestSpanContextReachesTheSample`: the handler passes `r.Context()` to a helper that calls `perf.SpanContext(ctx, "s3")`; the header has `s3;dur=`. |
| - `TestSpanForFindsTheWriterThroughUnwrap`: the handler wraps `w` in a type with `Unwrap()` and calls `perf.SpanFor(wrapped, "render")`; the header has `render;dur=`. |
| - `TestTimeDoerSpansAndCountsEachCall`: an `httptest.Server`; a handler calls `perf.TimeDoer(http.DefaultClient, "box", c).Do(req.WithContext(r.Context()))` twice before writing; the sample's `Spans["box"]` is positive, `Calls["box"] == 2`, and the header has one `box;dur=`. |
| + - `TestTimeDoerSpanCoversASlowBody`: a server that sends its headers and flushes, sleeps 30 ms, then writes the body; the handler reads the body to EOF and closes it before writing; `Spans["box"]` is at least 30. A body closed unread ends the span at the close. |
| - `TestTimeDoerCountsBackgroundCalls`: `Do` on `context.Background()` twice → `c.Background()["box"] == 2` and no sample is recorded. |
| - `TestOverBudgetIsJudgedOnFirstByte`: with `Budget: 20 * time.Millisecond`, a handler that flushes at once then sleeps 50 ms is not over; one that sleeps 50 ms before writing is over; a POST that sleeps 50 ms is not over and has `Budget` 0. |
| - `TestSkipLeavesHealthzUnmeasured`: `GET /healthz` records nothing and has no `Server-Timing`. |
| @@ -214,7 +216,7 @@ Copy Rastrillo's writer wrapper (`commit`, `WriteHeader` with 1xx passthrough, ` |
| ### Task 5: Spans at the seams: S3, app host, console DB, registry |
| **Files:** |
| -- Create: `cmd/console/perfs3.go`; Test: `cmd/console/perfs3_test.go` |
| +- Create: `internal/console/perfs3.go`; Test: `cmd/console/perfs3_test.go` |
| - Modify: `cmd/console/main.go:718-731` (`openStore` takes the recorder), `:365` (its caller), `:389` (seed data store), `:520` (`cfg.Perf`); `cmd/console/member.go:104` (via `optionalStore`, passes nil) |
| - Modify: `internal/console/instances.go:52-81` (fetcher construction and its client field), `:122-131` (`fetch`) |
| - Modify: `internal/console/view.go:552-560` (`Assemble`), `:941-943` (`Versions`) |
| @@ -227,7 +229,7 @@ Copy Rastrillo's writer wrapper (`commit`, `WriteHeader` with 1xx passthrough, ` |
| - Produces: |
| - `func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets) ([]AppView, error)` (the `ctx := context.Background()` at `view.go:553` goes) |
| - `func Versions(ctx context.Context, s release.Store, acct, app string) ([]VersionView, error)` (the `ctx := context.Background()` at `view.go:942` goes) |
| - - `cmd/console`: `func timeS3(s *release.S3Store, rec *perf.Recorder) *release.S3Store` replacing `s.Client` with `awss3.New(s.Client.Options(), func(o *awss3.Options) { o.HTTPClient = perf.TimeDoer(o.HTTPClient, "s3", rec) })`; `func openStore(rec *perf.Recorder) release.Store`. `serve()` makes one `rec := new(perf.Recorder)`, passes it to `openStore`, the seed data store and `cfg.Perf`, so every S3 HTTP request the console makes is counted: in the request that made it, or in `Background()`. |
| + - `internal/console`: `func TimeS3Store(s *release.S3Store, rec *perf.Recorder) *release.S3Store` (exported so `cmd/console` and Task 9's fixture share one wrapper) replacing `s.Client` with `awss3.New(s.Client.Options(), func(o *awss3.Options) { o.HTTPClient = perf.TimeDoer(o.HTTPClient, "s3", rec) })`; `cmd/console`: `func openStore(rec *perf.Recorder) release.Store` calls it. `serve()` makes one `rec := new(perf.Recorder)`, passes it to `openStore`, the seed data store and `cfg.Perf`, so every S3 HTTP request the console makes is counted: in the request that made it, or in `Background()`. |
| Why at these seams and not by wrapping `Config.Releases`: code type-asserts the store for optional interfaces (`release.AppMutationRunner` at `claim_app_mutation.go:30` and `claim_relay.go:29`, `release.ModLister` at `runsweep.go:363`, `release.SizeLister` at `economicspass.go:141`, and `release.VersionCandidates`'s stamp check). A wrapper would change those answers, and for `AppMutationRunner` that is a claim boundary. Timing the S3 client's HTTP doer changes no method set. *(My call.)* |
| @@ -240,7 +242,7 @@ The only HTTP call on a screen path to a box or app host is the instance fetcher |
| - `internal/console` `TestServerTimingNamesDBAndRegistry`: on the fixture, GET the app page; `Server-Timing` contains `db;dur=`. |
| - `internal/console` `TestRunningTabTimesTheAppHost`: on the fixture, replace the fetcher the way `NewServer` builds it, `fx.srv.instances = fx.srv.newInstanceFetcher(client, "http")` with `fx.srv.instances.timeout = 100 * time.Millisecond`, where `client`'s transport answers `200 []` for `/.carlos/instances` (Task 9's `newConsoleFixtureWith` is not there yet); GET `fx.u("/apps/kass/instances")`; `Server-Timing` contains `box;dur=`. |
| - [ ] **Step 2: Run** `go test ./cmd/console/ -run TestOpenStoreTimesS3Requests -count=1` and `go test ./internal/console/ -run 'TestServerTimingNamesDBAndRegistry|TestRunningTabTimesTheAppHost' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement** the signature changes, the callers (every page caller passes `r.Context()`; `apiversion.go:205` passes `r.Context()`; `view_test.go` passes `context.Background()`), `ListTags` at `:3622` with `r.Context()`, the spans, `timeS3` applied in `openStore`'s S3 branch and to the seed data store at `main.go:389`, and `cfg.Perf` set. |
| +- [ ] **Step 3: Implement** the signature changes, the callers (every page caller passes `r.Context()`; `apiversion.go:205` passes `r.Context()`; `view_test.go` passes `context.Background()`), `ListTags` at `:3622` with `r.Context()`, the spans, `TimeS3Store` applied in `openStore`'s S3 branch and to the seed data store at `main.go:389`, and `cfg.Perf` set. |
| - [ ] **Step 4: Run** the Step 2 commands, then the existing view and app-page tests: `go test ./internal/console/ -run 'TestAssemble|TestVersions|TestAppPage|TestReleasesTab|TestInstancesTab' -count=1`. Expected: PASS. Then `go vet ./internal/console/ ./cmd/console/` and both cross-compiles. |
| - [ ] **Step 5: Commit** the touched files, message `console: spans at the seams (s3 doer, app host, gate db reads, registry); Assemble and Versions take the request context`, ending with the Co-Authored-By line. |
| @@ -317,35 +319,39 @@ The file's grammar, one record per line, `#` starts a comment: |
| - [ ] **Step 4: Run** the same command. Expected: PASS. |
| - [ ] **Step 5: Commit**, message `console: perf-budgets.txt grammar and the screen inventory from registerRoute`, ending with the Co-Authored-By line. |
| -### Task 9: Latency injection and call counting at the store and the app host |
| +### Task 9: Latency and request counting at the S3 transport and the app host |
| **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/console/perflatency_test.go` |
| - Modify: `internal/console/server_test.go:49-107` (an options constructor; the three existing constructors call it) |
| **Interfaces:** |
| -- Consumes: `deletableStore` (`view_test.go:20-100`: methods `Put`, `DeleteIfMatch`, `Delete`, `ListMod`, `ListSizes`, plus `Get`, `List`, `ListDirs` from the embedded `release.Store`). |
| -- Produces (test-only): |
| - - `type consoleFixtureOptions struct { WithKey bool; Releases release.Store; WrapReleases func(release.Store) release.Store; AppClient *http.Client }` |
| - - `func newConsoleFixtureWith(t *testing.T, o consoleFixtureOptions) *consoleFixture`: `newConsoleFixtureOn` becomes `newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: withKey, Releases: rel})`. `fx.rel` stays the unwrapped store so seeding pays no latency. |
| - - `type perfLatency struct { S3Delay, HostDelay time.Duration; on atomic.Bool; s3, host atomic.Int64 }` with `func (l *perfLatency) Enable(on bool)`, `func (l *perfLatency) Calls() (s3, host int64)` |
| - - `type latencyStore struct { inner *deletableStore; l *perfLatency }` implementing exactly `Get`, `Put`, `List`, `ListDirs`, `Delete`, `DeleteIfMatch`, `ListMod`, `ListSizes`: each delegates, then counts what production would send over HTTP and sleeps `S3Delay` once per counted request when enabled. A `Get`, `Put` or `Delete` is one request (`DeleteIfMatch` too). A listing is one request per 1,000 keys returned, at least one (`max(1, ceil(n/1000))`), because `S3Store` pages `ListObjectsV2` at 1,000 keys (`release/store.go:1038`, `:1096`, `:1205`). *(My call: the test store cannot see HTTP, so it counts the same requests production's `TimeDoer` counts at the transport, Task 5, including every page of a listing.)* |
| - - `func (l *perfLatency) AppClient() *http.Client`: a transport that counts one host call, sleeps `HostDelay` when enabled, and answers `200` with body `[{"slug":"web-1","status":"ok"}]` for `/.carlos/instances` and `404` otherwise. It never dials. |
| +- Produces: |
| + - package `s3fake`: `func New(store *release.DirStore) *Server`; `type Server struct { … }` is an `http.Handler` speaking the S3 REST subset the console's `release.S3Store` uses, path-style, over the objects `store` holds: `GetObject` (with `If-None-Match`, answering 304), `HeadObject`, `PutObject` (with `If-Match` and `If-None-Match: *`, answering 412 on a lost race), `DeleteObject` (with `If-Match`), and `ListObjectsV2` (`prefix`, `delimiter`, `max-keys` defaulting to 1,000, `start-after`, `continuation-token`; `Contents` with `Key`, `LastModified`, `ETag`, `Size`, and `CommonPrefixes`). A delimiter page counts keys at the level and common prefixes against `max-keys`, as S3 does, so a `ListDirs` over a level with many objects takes as many pages as real S3 would. Authentication headers are accepted unchecked. |
| + - `func (s *Server) SetDelay(d time.Duration)`, `func (s *Server) Requests() int64` (every HTTP request it answered), and `func (s *Server) OnRequest(f func(r *http.Request) (status int, hold <-chan struct{}))`: a hook that may fail a request (non-zero status) or hold its response after the object has been read (plan 2 builds its test switches on it). |
| + - test-only in `internal/console`: |
| + - `type consoleFixtureOptions struct { WithKey bool; Releases release.Store; WrapReleases func(release.Store) release.Store; AppClient *http.Client; S3 *perfLatency }` |
| + - `func newConsoleFixtureWith(t *testing.T, o consoleFixtureOptions) *consoleFixture`: `newConsoleFixtureOn` becomes `newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: withKey, Releases: rel})`. With `S3` set, the fixture seeds its `DirStore` as today (`fx.rel`, so seeding is free and uncounted), starts an `s3fake` over the same `DirStore` under `httptest`, and gives `NewServer` a real `release.S3Store` made by `release.NewDeploymentS3Store` (change index on, as production), with `CARLOS_S3_ENDPOINT` set to the fake's URL and `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION` and `AWS_EC2_METADATA_DISABLED=true` set with `t.Setenv` (so such a test is never parallel), its client wrapped by Task 5's `TimeS3Store` with the server's recorder (`Config.Perf`). |
| + - `type perfLatency struct { S3Delay, HostDelay time.Duration; … }` with `func (l *perfLatency) Enable(on bool)` (delays on or off for both), `func (l *perfLatency) Calls() (s3, host int64)` (`s3` is the fake's `Requests()`), `func (l *perfLatency) Fake() *s3fake.Server`. |
| + - `func (l *perfLatency) AppClient() *http.Client`: a transport that counts one host call, sleeps `HostDelay` when enabled, and answers `200` with body `[{"slug":"web-1","status":"ok"}]` for `/.carlos/instances` and `404` otherwise. It never dials. |
| -The parity rule: `latencyStore` must have the same exported method set as `*deletableStore`, so the console under test sees the same optional interfaces it sees in every other test. *(My call; this is why the store is wrapped with an explicit method list instead of by embedding.)* |
| +Why a fake S3 server and not a counting store wrapper: counting at the HTTP transport is the only count that matches production. It includes every listing page (a `ListDirs` page is consumed by objects at the level as well as by the prefixes returned, `release/store.go:1201-1225`), the change-index `Get` and `Put` after every mutation (`store.go:966`, `changeindex.go:115-140`), and conditional requests. And the console under test runs the production `S3Store`, with every optional interface it really has, instead of a test type whose method set has to be kept in step. *(My call, after Astra round 2 on R1 #14.)* The fake's fidelity is held by the same contract the MinIO job runs. |
| 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:** |
| - - `TestLatencyStoreMethodSetMatches`: the sorted exported method names of `reflect.TypeOf(&latencyStore{})` equal those of `reflect.TypeOf(&deletableStore{})`. |
| - - `TestLatencyStoreCountsAndDelays`: enabled with `S3Delay` 25 ms, one `Get` takes at least 25 ms and `Calls()` reports `(1, 0)`; disabled, a `List` takes under 5 ms and reports `(2, 0)`. |
| - - `TestLatencyStoreCountsListingPages`: a prefix holding 1,001 objects: one `List` counts 2, one `ListMod` counts 2, an empty prefix's `List` counts 1. |
| + - `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. |
| + - `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. |
| - `TestLatencyAppClientAnswersTheContract`: `GET http://shop.example.com/.carlos/instances` answers 200 with one instance and counts `(0, 1)`. |
| - - `TestFixtureWithWrappedStoreServesAppPage`: `newConsoleFixtureWith` with `WrapReleases` set to a `latencyStore` (disabled), signed in, GET `/apps/kass` answers 200 and `Calls()` reports more than zero S3 calls. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLatency|TestFixtureWithWrappedStoreServesAppPage' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement** the options constructor and the two injectors. |
| -- [ ] **Step 4: Run** the same command plus `go test ./internal/console/ -run 'TestConsoleE2E|TestCreateApp' -count=1` (existing fixture users). Expected: PASS. |
| -- [ ] **Step 5: Commit**, message `console tests: fixture options, latency-injecting store and app client that count remote calls`, ending with the Co-Authored-By line. |
| + - `TestFixtureOverTheS3FakeServesAppPage`: `newConsoleFixtureWith` with `S3` set, signed in, GET `/apps/kass` answers 200, `Calls()` reports more than zero S3 requests, and the page's sample in `fx.srv.PerfGroups()` has `Calls["s3"]` equal to the fake's count for that request. |
| +- [ ] **Step 2: Run** `go test ./internal/s3fake/ ./internal/release/ -run 'TestS3' -count=1` and `go test ./internal/console/ -run 'TestLatency|TestFixtureOverTheS3Fake' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** the fake, the contract refactor, the options constructor and the app client. |
| +- [ ] **Step 4: Run** the Step 2 commands plus `go test ./internal/console/ -run 'TestConsoleE2E|TestCreateApp' -count=1` (existing fixture users). Expected: PASS. Both cross-compiles (the fake is plain `net/http`). |
| +- [ ] **Step 5: Commit**, message `tests: an S3 fake that counts at the transport, its contract with the MinIO suite, fixture options and a counting app client`, ending with the Co-Authored-By line. |
| ### Task 10: The walk: every screen, timed and counted |
| @@ -355,14 +361,14 @@ The console makes no direct box HTTP call on a screen path today (Task 5); `Host |
| - Modify: `.amadan/test-weights.tsv` (a row for `TestConsoleScreensMeetTheBudget` with its measured seconds) |
| **Interfaces:** |
| -- Consumes: Tasks 8 and 9 (`perfInventory`, `perfScreenPath`, `loadPerfBudgets`, `perfRecord`, `newConsoleFixtureWith`, `perfLatency`, `latencyStore`), `signInPaul`, `newBrowser`. |
| +- Consumes: Tasks 8 and 9 (`perfInventory`, `perfScreenPath`, `loadPerfBudgets`, `perfRecord`, `newConsoleFixtureWith`, `perfLatency`, `s3fake`), `signInPaul`, `newBrowser`. |
| - Produces (test-only; plan 2 extends `perfTargets` and relies on these names): |
| - `type perfTarget struct { Path string; Expect int; Anonymous bool }` |
| - - `func newPerfFixture(t *testing.T) (*consoleFixture, *perfLatency)`: `newConsoleFixtureWith` with `WithKey: true`, `WrapReleases` to a `latencyStore` (`S3Delay` 25 ms, `HostDelay` 40 ms), `AppClient` from the same `perfLatency`, then the seeds below. |
| + - `func newPerfFixture(t *testing.T) (*consoleFixture, *perfLatency)`: `newConsoleFixtureWith` with `WithKey: true`, `S3` set to a `perfLatency` (`S3Delay` 25 ms, `HostDelay` 40 ms), `AppClient` from the same `perfLatency`, then the seeds below. |
| - `func perfTargets(fx *consoleFixture) map[string][]perfTarget` |
| - `func perfEnforce() bool`: `os.Getenv("CI") != "" || os.Getenv("AMADAN_CI") != ""` |
| - `func TestConsoleScreensMeetTheBudget(t *testing.T)` (not parallel) |
| - - a hook plan 2 fills: `var perfQuiesce = func(fx *consoleFixture) {}`, called after every request before the call count is read. |
| + - hooks plan 2 fills: `var perfQuiesce = func(fx *consoleFixture) {}`, called after every request before the call count is read; and `var perfColdReset = func(fx *consoleFixture) {}`, called before a screen's cold request so that it meets a console that has cached nothing for it. |
| - `func TestPerfSessionS3Requests(t *testing.T)` and `internal/console/testdata/perf-session-s3.txt`: a scripted session's total S3 request count against a recorded ceiling (below). |
| Seeds `newPerfFixture` adds on top of the fixture's own (`kass` with `v1`, `v2`, channels `stable` and `canary/x`, routes `kass.carlosapp.dev`, `docs.kass.carlosapp.dev`): |
| @@ -399,7 +405,8 @@ The walk, per screen in `perfInventory`: |
| 2. A `skip` screen is not requested. |
| 3. An `over` screen: latency disabled; two requests; the call count of the second is printed with its reason as `"%s %s: over (%s): %d S3 and %d host calls warm"`. Never failed. (Measured without latency so the slow screens cost the test milliseconds, not seconds.) |
| 4. Every other screen: latency enabled; ten requests; the first two discarded. Time to first byte is `httptrace`'s `GotFirstResponseByte` as Rastrillo's `perftest` measures it; each response is read to the end. After each request, wait until the handler has returned (an in-flight counter in the `httptest` handler, as `perftest.screens` does), call `perfQuiesce(fx)`, then read the call delta. Status must equal `Expect`, always failed. Calls: the largest delta over the eight measured requests must not exceed the allowance (0, or `n` from a `calls n:` record), always failed, because counts are deterministic. *(My call: the spec says the test fails only when CI is set; that is applied to timing, which is noisy on a laptop, and not to counts, which are not.)* Time: median of the eight within 150 ms and none over 450 ms, failed only when `perfEnforce()`, printed always. A `deferred` screen is timed and printed but exempt from both the 150 ms rule and the count. |
| -5. Print each result with `t.Logf` (`median`, `worst`, `calls`). At the end, print the total elapsed time; when `perfEnforce()` and it exceeds 10 s, fail. |
| +5. Before its warm requests, every screen that is not `skip`, `over` or `deferred` gets one **cold** request: `perfColdReset(fx)`, latency on, one request, its time to first byte held to 150 ms (failed only when `perfEnforce()`, printed always). Then latency goes off until `perfQuiesce` returns, so the background loads that cold request started cost the test milliseconds, and back on for the warm requests. Spec §2.6 asks for the first view after a restart within 150 ms, and a screen that is fast only once cached would pass the warm requests alone. A screen that fails the cold request is recorded `over:` like any other. *(Astra round 2, finding 7.)* |
| +6. Print each result with `t.Logf` (`cold`, `median`, `worst`, `calls`). At the end, print the total elapsed time; when `perfEnforce()` and it exceeds 10 s, fail. |
| Warm-page counts alone cannot show that total S3 use fell: they miss first views, deferred loads and a write's own reads. `TestPerfSessionS3Requests` covers the whole session. On `newPerfFixture`, latency disabled, signed in as Paul, it runs a fixed script and sums every counted S3 request, calling `perfQuiesce` after each step so background loads are included: each of the nine app tab URLs and the settings sections, twice each; the account home, Team, account settings and Trash, twice each; one promote of `v2` to `stable` through the browser form; then Overview and Releases again. The file `testdata/perf-session-s3.txt` holds one line, `<n> <reason>`. The test fails (always, since counts are deterministic) when the total exceeds `n`, and prints the total. This task records today's total as `n`. Plan 2 lowers it. |
| @@ -434,5 +441,6 @@ Not a code task. Spec §2.5 step 1: ship and roll this on its own and read flags |
| ## Self-review |
| - **Spec coverage.** §2.1: budget, methods, streams, no cold start (Tasks 2, 3); API GETs timed in production but not walked (Task 8 inventory). §2.2: middleware on the console mux (Task 4), `Server-Timing` with `app` and spans (Task 3), spans `db`, `s3`, `box`, `render` at the seams (Tasks 4, 5), grouping by pattern (Tasks 3, 4), throttled warning (Tasks 2, 6), the 2,048 ring and Console speed table (Tasks 2, 7), `Skip` `/healthz` (Task 4). §2.3: walk over every `registerRoute` screen including method-less ones (Tasks 8, 10), production constructor (Tasks 9, 10), latency injection 25 ms and 40 ms (Task 9), warm-cache call counts with default zero and `perf-budgets.txt` reasons (Tasks 8, 10), fixtures for every parameter and failure for a missing one (Task 10), deferred parts listed and exempt (Task 8 grammar, Task 10), fails only under `CI` for timing (Task 10), under 10 s (Task 10). §2.5 steps 1 and 2: Tasks 1 to 10 and 12. |
| -- **Calls that cross plans.** Plan 2 uses `perf.SpanContext`, `perf.TimeDoer`, `Config.Perf`, `Server.PerfGroups`, `Server.PerfBackground`, `newPerfFixture`, `newConsoleFixtureWith`, `perfTargets`, `perfTarget`, `perfQuiesce`, `perfLatency` (`Enable`, `Calls`), `latencyStore`, `perfRecord`, `loadPerfBudgets`, `TestPerfSessionS3Requests` with `perf-session-s3.txt`, and the `perf-budgets.txt` grammar by these names. |
| +- **Calls that cross plans.** Plan 2 uses `perf.SpanContext`, `perf.TimeDoer`, `Config.Perf`, `Server.PerfGroups`, `Server.PerfBackground`, `TimeS3Store`, `newPerfFixture`, `newConsoleFixtureWith`, `perfTargets`, `perfTarget`, `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 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 60c4eaa9f..c8dbc4b76 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 |
| @@ -11,7 +11,7 @@ |
| **Spec:** `docs/superpowers/specs/2026-10-25-console-ux-perf-design.md`, §2.4 (A, B, C and the console DB question), §2.5 step 3, §2.6. Read Part 2 whole. Where this plan and the spec disagree, the spec wins and the plan is the bug. |
| **Depends on, and lands after:** |
| -- Plan 1, `2026-10-25-console-perf-1-measure.md`, merged and rolled (its Task 12 recorded the "before" numbers). This plan uses its names exactly: `perf.SpanContext`, `perf.TimeDoer`, `Config.Perf`, `Server.PerfGroups`, `Server.PerfBackground`, `newPerfFixture`, `newConsoleFixtureWith`, `perfTargets`, `perfTarget`, `perfQuiesce`, `perfLatency` (`Enable`, `Calls`), `latencyStore`, `loadPerfBudgets`, `TestPerfSessionS3Requests` and `testdata/perf-session-s3.txt`, the `perf-budgets.txt` grammar, `Assemble(ctx, …)`, `Versions(ctx, …)`, `writeTemplate`. |
| +- Plan 1, `2026-10-25-console-perf-1-measure.md`, merged and rolled (its Task 12 recorded the "before" numbers). This plan uses its names exactly: `perf.SpanContext`, `perf.TimeDoer`, `Config.Perf`, `Server.PerfGroups`, `Server.PerfBackground`, `newPerfFixture`, `newConsoleFixtureWith`, `perfTargets`, `perfTarget`, `perfQuiesce`, `perfColdReset`, `perfLatency` (`Enable`, `Calls`, `Fake`), the S3 fake (`s3fake.Server`, `OnRequest`, `Requests`), `TimeS3Store`, `loadPerfBudgets`, `TestPerfSessionS3Requests` and `testdata/perf-session-s3.txt`, the `perf-budgets.txt` grammar, `Assemble(ctx, …)`, `Versions(ctx, …)`, `writeTemplate`. From the nav plan it uses the Releases pager as it stands: `VersionsPage` (taken here as `VersionsPage(ctx, s, acct, app, page) ([]VersionView, bool, error)`, the nav signature with the request context Astra round 2 finding 2 asks it to carry), `versionsPageParam`, the page fields `VersionsPageNum` and `VersionsMore`, and its acceptance test `TestReleasesOlderVersionsAreReachable`. |
| - The nav plan, `2026-10-25-console-ux-nav.md` (spec Part 1), merged. This plan is written against the code after it: nine one-level tabs; Releases as one page (What's next, pending, Live now from `liveNowTargets(p.Detail, assembleDeploymentTargets(p.Detail, acct.Sqid))`, Versions, then folds for channels and the ladder, canaries and tags; `templates/app_deployments.html` deleted); `GET …/deployments`, `GET …/pipeline` and `…/settings/advanced` are 303s through `appRedirect` (an `accountApp` gate, no remote read); Placement is the settings section `placement` (`populateAppPlacement`, local reads only); the error level and the analytics switch are the settings section `errors-analytics`; Advanced is folded into General. Read the nav plan's Tasks 3, 5 and 7 before Tasks 4, 10, 11 and 13 here. |
| **Branch:** `console-perf-2`, cut from amadan `main` once both have landed. |
| @@ -25,7 +25,7 @@ Every task's requirements include this section. |
| - **Targeted local tests; CI runs the full suite.** `go test ./internal/console/ -run 'TestName' -count=1`; never `make test`, never a whole `internal/console` run. `go build ./...`, `go vet ./...`, `gofmt -l .` clean. `GOFLAGS=-buildvcs=false` if the sandbox refuses VCS stamping. The walk (`TestConsoleScreensMeetTheBudget`) runs with `CI=1` once at the end of each task that deletes `over:` records, not in a loop. `TestClaimConsoleMutationInvariant` runs under `nice -n 19`, once per task that changes routes or doors. |
| - **Cross-compiles stay green:** `GOOS=darwin GOARCH=arm64 go build ./...` and `GOOS=windows GOARCH=amd64 go build ./...` before every push. |
| - **Go cache:** leave `GOCACHE`, `GOMODCACHE` and `GOTMPDIR` at their defaults. Run go with the sandbox off if `~/.cache/go-build` is read-only. |
| -- **Production wiring, not stand-ins.** Console tests build the server with `NewServer` through `newConsoleFixtureWith` or `newPerfFixture`, the constructor `cmd/console` uses. The only injected seams are the wrapped release store and `Config.AppClient`. A test never plants a value in `s.views`: it makes reads happen by viewing pages or parts. Moving the cache's clock (`fx.clock`) is the one direct touch allowed. Unit tests of `viewCache` itself build their own cache. |
| +- **Production wiring, not stand-ins.** Console tests build the server with `NewServer` through `newConsoleFixtureWith` or `newPerfFixture`, the constructor `cmd/console` uses. The only injected seams are the S3 fake behind a real `release.S3Store` (plan 1 Task 9) and `Config.AppClient`. A test never plants a value in `s.views`: it makes reads happen by viewing pages or parts. Moving the cache's clock (`fx.clock`) is the one direct touch allowed. Unit tests of `viewCache` itself build their own cache. |
| - **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. |
| @@ -115,13 +115,13 @@ Spec §2.4 C rows 1 to 3: `ensureAccountManifest` re-reads on every app tab; `Se |
| - `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) 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`: `Keys() []string` (every key or prefix asked for, in order); `ResetKeys()`; `SetFail(match func(key string) bool)` (a matching `Get` or listing returns an error after counting; nil clears it); `HoldNext(match func(key string) bool) (held <-chan struct{}, release func())` (the next matching `Get`, and only that one, performs its read, keeps the result, closes `held` and blocks until `release`, then returns the result it read before blocking); `OnPut(f func(key string))` (runs after each `Put` reaches the store). 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); `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. |
| `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. |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestMemoOnceRunsOncePerRequest`: three `memoOnce(ctx, "k", f)` calls on one memo context run `f` once and return the same value; a second `withPageMemo(context.Background())` runs it again; a context with no memo runs `f` every time. |
| - - `TestSlowManifestReadDoesNotDelayThePage`: on `newPerfFixture`, `HoldNext` on `accounts/<sqid>/account.json`; GET `/apps/kass` answers within 150 ms while the hold is in place; `release()`; after quiesce (wait for `held` closed and the check to finish), a second GET makes no `account.json` read. |
| + - `TestSlowManifestReadDoesNotDelayThePage`: on `newPerfFixture`, `HoldNext("get", …)` on `accounts/<sqid>/account.json`; GET `/apps/kass` answers within 150 ms while the hold is in place; `release()`; after quiesce (wait for `held` closed and the check to finish), a second GET makes no `account.json` read. |
| - `TestAppPageReadsAccountManifestOnce`: across two GETs of `/apps/kass` and a quiesce, `Keys()` holds `accounts/<sqid>/account.json` at most once. |
| - `TestMissingAccountManifestIsStillBackfilled`: delete the manifest from `fx.rel`; GET `/apps/kass`; after the check finishes the manifest exists (the existing `TestAppPageBackfillsAccountManifest`, `server_test.go:1439`, passes after it waits the same way). |
| - `TestNoteLastAccountWritesOnlyOnChange`: `noteLastAccount(a, 1)` is true, again false, `noteLastAccount(a, 2)` true; `fx.st.LastAccount(a)` is 2. |
| @@ -146,7 +146,7 @@ Spec §2.4 C rows 5 to 7, plus two wasted reads the 2026-10-25 inventory found. |
| - 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. |
| - `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` wraps its `ctx` with it. |
| + - `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. |
| - `func ListRecordHosts(ctx context.Context, s release.Store, acct, app string, max int) ([]string, error)` in `internal/provision`: one listing of the records prefix through `recordHosts`, no `Get`. The Logs tab's host picker uses it instead of `ListRecords`, which fetched every record (up to 500) only for its host name. |
| @@ -232,8 +232,9 @@ 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(time.Now, viewCacheMax)`) |
| -- Modify: `internal/console/perfwalk_test.go` (`perfQuiesce = func(fx *consoleFixture) { fx.srv.views.quiesce() }`; `newPerfFixture` sets `fx.clock` and `fx.srv.views.now`) |
| +- 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`. |
| **Interfaces:** |
| - Produces: |
| @@ -244,8 +245,8 @@ Spec §2.4 C rows "Settings, `populateAppSettings`", "`appDeployEmpty`" and "`en |
| - `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 }` (built by Task 8's constructors) |
| - - `func (c *viewCache) wrote(ctx context.Context, e viewEffect) (failed int)`: first, 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. |
| + - `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). |
| - `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). |
| @@ -332,8 +333,10 @@ Every screen converted in Tasks 9 to 14 follows one shape: its template becomes |
| - `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`, `partVersions`, `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`. |
| + - 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. |
| @@ -345,7 +348,9 @@ The effect inventory, as a starting point the implementer completes by reading e |
| | 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, tag, retention | `writesApp(partVersions)`, `writesApp(partTags)`, `writesApp(partRetention, partVersions)` | |
| +| 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)` | |
| @@ -363,7 +368,7 @@ The effect inventory, as a starting point the implementer completes by reading e |
| | 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 | `writesDeployment(partEconomics)` (prefix drop) | |
| +| 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 | |
| @@ -403,22 +408,24 @@ 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, now time.Time) (appCore, error)`: `assembleChannels`, `release.GetProduction` and `release.GetPipeline`, under `ctx`. It holds only what is read remotely. |
| - - `func productionView(flag *release.ProductionFlag, err error, channels []ChannelView, routes []RouteView, now time.Time) ProductionView`: `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.)* |
| + - `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`. |
| + - `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. |
| - `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`: `Versions` (`{sqid, app, partVersions}`, `writtenWindow`, a `versionList` type with `viewClone`), `appResourceMetrics` (`{"", "", partMetrics}`, `liveWindow`, loader `LoadMetrics`, filtered per app after, on the copy), `loadBoxJoin` (`{"", "", partBoxes}`, `liveWindow`, the `boxSnapshot` from Task 5). SQLite reads (events, pending changes) stay direct. |
| + - parts `overview`, `activity`, `account-review` in `appParts`; the Overview's extra reads through `viewGet`: page 1 of the version list (`{sqid, app, versionsPart(1)}`, `writtenWindow`, a `versionPage{Views []VersionView; More bool}` with `viewClone`, loaded by `VersionsPage(ctx, …, 1)`; the same entry as Releases' first page), `appResourceMetrics` (`{"", "", 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. |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestOverviewWarmMakesNoRemoteCalls`: `getAssembled` `/apps/kass` and quiesce; reset counts; GET: zero S3 and zero host calls, 200, shows `v1` on `stable`. |
| - `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. |
| - `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|TestProductionNudge|TestSameAppNameInTwoAccounts|TestConcurrentViews|TestActivityAndAccountReview' -count=1 -race`. Expected: FAIL. |
| +- [ ] **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 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. |
| @@ -433,17 +440,18 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential, |
| **Interfaces:** |
| - Produces: |
| - part `releases`: `fillAppDetail`, then what the nav plan builds on `p.Detail` (`ReleaseSummary`, `PromoteChannels`, pending, `DeploymentTargets` from `liveNowTargets(p.Detail, assembleDeploymentTargets(p.Detail, acct.Sqid))`, the folds), plus `release.ListTags` through `viewGet` (`{sqid, app, partTags}`, `writtenWindow`, a `tagList` with `viewClone`; on the load's context, not `context.Background()`), whose pills decorate the request's copy of the channels. A tags load error degrades to no pills, as today (`server.go:3609-3622`). |
| - - part `releases-versions`, the Versions section alone: `Versions` (Task 9's key), `release.GetRetention` (`{sqid, app, partRetention}`, `writtenWindow`), the tag pills on the request's copy of the versions. On the page, a miss of only these renders the rest of Releases and a placeholder for this section. A Versions load error is a rendered degrade inside the section ("Could not list this app's releases.", today's text) with a 200, never the generic CPF-28 fragment, so Live now survives a failed listing as the nav plan requires. |
| + - part `releases-versions`, the Versions section alone, page-aware: it reads `versionsPageParam(r)` like the page and passes it through (`/apps/<app>/part/releases-versions?page=<n>`); the page's placeholder carries the same `page`. Its reads: that page of the version list (`{sqid, app, versionsPart(n)}`, `writtenWindow`, `versionPage` from `VersionsPage(ctx, s, acct, app, n)`), `release.GetRetention` (`{sqid, app, partRetention}`, `writtenWindow`), the tag pills on the request's copy of the views. It sets `VersionsPageNum` and `VersionsMore` from the cached `versionPage`, so the nav plan's pager (`rel="next"` while `More`, `rel="prev"` above page 1) renders inside the fragment unchanged. On the page, a miss of only these renders the rest of Releases and a placeholder for this section. *(Astra round 2, finding 1.)* A Versions load error is a rendered degrade inside the section ("Could not list this app's releases.", today's text) with a 200, never the generic CPF-28 fragment, so Live now survives a failed listing as the nav plan requires. |
| - `attachHint`'s `instanceDomainFor` through `viewGet` (`{sqid, app, partInstancesManifest}`, `writtenWindow`). |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestReleasesWarmMakesNoRemoteCalls` (same shape as Task 9's). |
| - - `TestReleasesLiveNowRendersWhileVersionsLoad`: Overview warm (so the core is cached) but versions never viewed: the first Releases GET has `id="live-now"` with its Roll back and a `data-part` for `releases-versions`. |
| + - `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. |
| - `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` 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`. |
| + - `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`. |
| - `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|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`, `TestReleasesVersionsCapPointer`, `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 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 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. |
| @@ -482,18 +490,18 @@ Spec §2.4 C row `instances.Report`: HTTP to the app host, 30 s cache, blocks up |
| **Interfaces:** |
| - Produces: |
| - - `func normalizedViewQuery(q url.Values, keep ...string) string`: only the named parameters, sorted, empty ones dropped, each value trimmed and capped at 256 bytes; used in `Part` (`logs?…`, `errors?…`, `availability?…`, `analytics?…`). |
| - - `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, "logs?" + key}`, `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.)* |
| + - `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`). |
| - - 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` (`errors?…`, `availability?…`, `liveWindow`), `analytics.ReadRange` (`analytics?…`, `liveWindow`). |
| + - 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`. |
| - `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`. |
| - - `TestFilteredKeysAreNormalized`: `?since=1h&host=a` and `?host=a&since=1h&junk=x` share one entry. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLogsWarm|TestColdLogsRead|TestLogsFollow|TestErrorsAvailabilityAnalytics|TestFilteredKeys' -count=1`. Expected: FAIL. |
| + - `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 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. |
| @@ -558,7 +566,8 @@ 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`; `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 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) 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. |
| @@ -569,7 +578,7 @@ Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the sha |
| - `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`: save a scenario; the economics page shows it. |
| + - `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. |
| - [ ] **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`. |
| @@ -600,7 +609,7 @@ Spec §2.4 C last row: `SetMaxOpenConns(1)` (`store.go:99`, `store_gate.go:1828` |
| - 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 2: The walk passes with `CI=1`** in under 10 s: `CI=1 go test ./internal/console/ -run TestConsoleScreensMeetTheBudget -count=1 -v`. Update the row in `.amadan/test-weights.tsv`. |
| +- [ ] **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. |
| - [ ] **Step 5: Local gate** (`gofmt -l .`, `go vet ./...`, `go build ./...`, both cross-compiles, `go test ./internal/console/ -run 'TestView|TestPart|TestWrote|TestEveryWriteRoute|TestConcurrentViews|TestLoadInFlight' -race -count=1`, `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`), push, describe, wait for CI, squash, re-run CI, merge with `-expect`. |
| @@ -612,5 +621,6 @@ 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 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-console-ux-nav.md b/docs/superpowers/plans/2026-10-25-console-ux-nav.md| index f4fbee67a..8be691b43 100644 |
| --- a/docs/superpowers/plans/2026-10-25-console-ux-nav.md |
| +++ b/docs/superpowers/plans/2026-10-25-console-ux-nav.md |
| @@ -10,7 +10,7 @@ |
| **Spec:** `docs/superpowers/specs/2026-10-25-console-ux-perf-design.md`, Part 1 (sections 1.1 to 1.4 and 1.6). Section 1.5 is out of scope (see Global Constraints). Part 2 has its own plans. |
| -**Merge order:** this plan lands BEFORE perf plan 2 (`2026-10-25-console-perf-2-fixes.md`). Perf plan 2 is rewritten against the templates and handlers this plan leaves behind, and owns converting this plan's Releases, Running and Settings tests to the page-plus-fragment shape when it defers those parts (coordinator ruling on Astra finding 12, 2026-10-25). Perf plan 1 is independent of this plan. |
| +**Merge order:** this plan lands BEFORE perf plan 2 (`2026-10-25-console-perf-2-fixes.md`). Perf plan 2 is rewritten against the templates and handlers this plan leaves behind, and owns converting this plan's Releases, Running and Settings tests to the page-plus-fragment shape when it defers those parts (coordinator ruling on Astra finding 12, 2026-10-25). Perf plan 1 (`2026-10-25-console-perf-1-measure.md`) lands BEFORE this plan, and this plan is written against its signatures: `Versions(ctx context.Context, s release.Store, acct, app string) ([]VersionView, error)` and `Assemble(ctx, …)` (perf 1 Task 4, `view.go:552,941`), with callers already passing a request context. |
| ## Global Constraints |
| @@ -230,7 +230,7 @@ Open each PNG with the Read tool. Pass: nine tabs in order with Overview (or Log |
| - Produces: `func (s *Server) appRedirect(sub string) http.HandlerFunc` in `appredirect.go`. Calls `s.accountApp(w, r)`; on `ok` answers `http.Redirect(w, r, "/a/"+url.PathEscape(acct.Sqid)+"/apps/"+url.PathEscape(app)+sub, http.StatusSeeOther)`. No flash, query string dropped. Task 7 reuses it. |
| - Produces: `func liveNowTargets(view *AppView, targets []deploymentTarget) []deploymentTarget` in `deployments.go`. For `view.OneChannelPipeline()` it keeps only targets whose `Channel` is declared in `view.Pipeline.Channels`; otherwise it returns `targets` unchanged. |
| - Produces: `func VersionCandidatesPage(ctx context.Context, s Store, acct, app string, offset, max int) (versions []string, more, ranked bool, err error)` in `release/candidates.go`. Same single listing as today (`rankedVersionStamps` on a ModLister, `s.List` otherwise); a ranked answer is `cands[offset:offset+max]` clamped to the slice, `more` true when `len(cands) > offset+max`. An unranked answer returns every version with `more` false (the caller pages after sorting, as today). `VersionCandidates(ctx, s, acct, app, max)` becomes `VersionCandidatesPage(ctx, s, acct, app, 0, max)` minus `more`, so its five callers see no change. |
| -- Produces: `func VersionsPage(s release.Store, acct, app string, page int) (views []VersionView, more bool, err error)` in `view.go`. `page` is 1-based; offset `(page-1)*versionsCap`. Ranked: manifest reads only for the page's at most 20 candidates, then the existing built_at sort within the page. Unranked: fetch and sort all (today's fake-store path), then slice the page and set `more`. `Versions(s, acct, app)` becomes `VersionsPage(s, acct, app, 1)` minus `more`, so Overview and the API keep their exact output. |
| +- Produces: `func VersionsPage(ctx context.Context, s release.Store, acct, app string, page int) (views []VersionView, more bool, err error)` in `view.go`. `ctx` flows into `VersionCandidatesPage` and every `release.GetManifest` read (no `context.Background()`), so perf 1's spans and cancellation cover the new reads. `page` is 1-based; offset `(page-1)*versionsCap`. Ranked: manifest reads only for the page's at most 20 candidates, then the existing built_at sort within the page. Unranked: fetch and sort all (today's fake-store path), then slice the page and set `more`. Perf 1's `Versions(ctx, s, acct, app)` keeps its signature and becomes `VersionsPage(ctx, s, acct, app, 1)` minus `more`, so Overview and the API keep their exact output and their callers do not change. |
| - Produces: `func versionsPageParam(r *http.Request) int` in `deployments.go`: `?page=` parsed as an integer in `[1, maxVersionsPage]` with `const maxVersionsPage = 1000`; anything else (absent, `0`, negative, non-numeric, over the cap) is 1. |
| - Page fields: `VersionsPageNum int`, `VersionsMore bool` on `page` (server.go, beside `Versions`). |
| - **S3 cost per Releases view, unchanged from today on every page:** one listing of `apps/<app>/releases/` (a paginated LIST, as now) plus at most 20 manifest GETs. Page 2 and later cost the same as page 1. For the perf plans: these are the reads perf 2 caches; page 1 is the hot entry, pages 2+ are rare and may stay uncached, but their count is bounded the same way. |
| @@ -253,14 +253,14 @@ Open each PNG with the Read tool. Pass: nine tabs in order with Overview (or Log |
| - `TestReleasesLiveNowSurvivesListingFailure` (replaces `TestDeploymentsDoNotDependOnReleaseListing`, which is deleted): `fx.srv.cfg.Releases = listFailStore{fx.rel}`; GET `/releases` is 200, contains "Could not list this app", `id="live-now"`, and `/apps/kass/instances?channel=stable`. |
| - `TestReleasesOlderVersionsAreReachable`: with the fixture's two versions page 1 has no `rel="next"` link. After `shipVersion` of `v10` through `v30` (21 more, 23 in all): page 1 has exactly 20 `<tr id="version-` rows and a `rel="next"` link whose href ends `/releases?page=2#versions` with text NAV-C30; GET `/releases?page=2` has exactly 3 rows, a `rel="prev"` link (NAV-C35) and no `rel="next"`; the union of the `version-` ids on pages 1 and 2 is all 23 shipped versions, with no id on both pages (so version 21 and beyond are reachable). `?page=3` is 200 with zero rows and NAV-C45. `?page=0`, `?page=-1`, `?page=x` and `?page=1001` render page 1's rows. |
| - `TestVersionCandidatesPage` (`internal/release/versions_test.go`, the `TestVersionCandidatesRanked` setup with `modStamp`): with five stamped versions, `VersionCandidatesPage(ctx, s, "bab", "kass", 0, 2)` gives the two newest and `more == true`; offset 2 gives the next two, `more == true`; offset 4 gives one, `more == false`; offset 10 gives none, `more == false`. Through `plainStore{s}` it returns all five, `more == false`, `ranked == false`. `VersionCandidates` with max 4 still returns `TestVersionCandidatesRanked`'s exact want. |
| - - `TestVersionsPageMatchesVersionsOnPageOne` (console): for the fixture, `Versions(...)` equals the views of `VersionsPage(..., 1)`. |
| + - `TestVersionsPageMatchesVersionsOnPageOne` (console): for the fixture, `Versions(context.Background(), fx.rel, fx.sqid, "kass")` equals the views of `VersionsPage(context.Background(), fx.rel, fx.sqid, "kass", 1)`. |
| - `TestNoLinkPointsAtDeployments`: GET each of the nine tab URLs from Task 2's table; none contains `/deployments"`; `/apps/kass` contains the approved NAV-C01 text inside the Releases tile's `<h2>`. |
| - `TestLiveNowTargetsHidesUndeclaredChannelsOnOneChannelApps` (unit): `AppView{Pipeline: &release.Pipeline{Channels: []release.PipelineChannel{{Name: "edge"}}}}` with targets `edge`, `canary/rc1` keeps only `edge`; a nil pipeline keeps both. |
| - Update `TestReleaseBackTabOnlyAcceptsLocalDestinations`: want `"releases"` for both `"releases"` and `"deployments"`, `""` for the rest. |
| - Rewrite `TestDeploymentRoutesAndHistory` to read `/releases` only: it contains `/apps/kass/releases#version-v1`, `/apps/kass/instances?channel=stable` and `id="version-v1"`. |
| - [ ] **Step 2: Update existing assertions:** `TestReleasesTab`: `"All versions ("` becomes `<h2>` + NAV-C29 text + `</h2>`; keep `<h2>Channels</h2>`, `<h2>Canaries</h2>` and the `back=releases` count of 4. `TestOneChannelAppHidesChannelVocabulary`: `aria-label="Release status"` becomes `id="live-now"`. `TestOneChannelAppKeepsCanariesAndRollback`: add `strings.Count(main, ">Roll back</button>") == 1`. Claim tables: fixture reason `claimRead("redirects to the releases page")`; probe `claimRedirectRead("/a/bab/apps/kass/deployments", http.StatusSeeOther, "/a/bab/apps/kass/releases")`. |
| - [ ] **Step 3: Run** `go test ./internal/console/ -run 'TestReleases|TestDeployment|TestNoLinkPointsAtDeployments|TestLiveNowTargets|TestReleaseBackTab|TestOneChannelApp|TestChannelsTableAndPipelineCardAgreeOnBakeWindow|TestReleaseSummaryStripRenders|TestVersionsPage' -count=1` and `go test ./internal/release/ -run 'TestVersionCandidates' -count=1`. Expected: the new tests FAIL (the release one does not compile until Step 4). |
| -- [ ] **Step 4: Implement** per the Interfaces block. Add `VersionCandidatesPage` and `VersionsPage`; in `handleAppReleases` replace the `Versions` call with `VersionsPage(s.cfg.Releases, acct.Sqid, p.AppName, versionsPageParam(r))` and set `VersionsPageNum`, `VersionsMore`. Delete the `/deployments` branch, set `p.DeploymentTargets = liveNowTargets(p.Detail, assembleDeploymentTargets(p.Detail, acct.Sqid))` and load `p.Pending` exactly as the deleted branch did, before the existing release reads. Register the redirect. Point the activity channel link at `/releases`. Swap `DeploymentsCopy.History` for `.Title` and apply NAV-C36 to C39. Delete `app_deployments.html` and the `solorollback` define. |
| +- [ ] **Step 4: Implement** per the Interfaces block. Add `VersionCandidatesPage` and `VersionsPage`; in `handleAppReleases` replace the `Versions(r.Context(), …)` call with `VersionsPage(r.Context(), s.cfg.Releases, acct.Sqid, p.AppName, versionsPageParam(r))` and set `VersionsPageNum`, `VersionsMore`. Delete the `/deployments` branch, set `p.DeploymentTargets = liveNowTargets(p.Detail, assembleDeploymentTargets(p.Detail, acct.Sqid))` and load `p.Pending` exactly as the deleted branch did, before the existing release reads. Register the redirect. Point the activity channel link at `/releases`. Swap `DeploymentsCopy.History` for `.Title` and apply NAV-C36 to C39. Delete `app_deployments.html` and the `solorollback` define. |
| - [ ] **Step 5: Run** the Step 3 commands plus `go test ./internal/console/ -run 'TestAppTabBarIsOneLevel|TestNavCopyDeck|TestActivity|TestOverview|TestAPIVersion|TestRetention' -count=1` and `go test ./internal/release/ -run 'TestVersionCandidates|TestProgram|TestRootfsShip' -count=1` and `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`. Expected: PASS. Add NAV-C21 to C39 and NAV-C45 to `navCopyBuilt` first. |
| - [ ] **Step 6: Visual check.** Snapshot `releases` at 1280 and 390 (Task 2 Step 7 commands). Pass: callout, Live now, Versions open; three closed folds whose summaries read as headings; one Roll back. |
| - [ ] **Step 7: Commit:** `git commit -m "Console: Releases is one page; /deployments redirects to it"`. |
| @@ -440,7 +440,7 @@ Expected: all clean and PASS. Confirm `navCopyBuilt` holds every deck id. |
| ## Self-review notes |
| - **Spec coverage.** 1.1: Task 2 (tabs, no sub-tabs), Task 9 (390 px header). 1.2: Task 4 (heading, Restart app, toolbar, All count, leftovers), Task 5 (BYO pointer now says Settings, Placement). 1.3: Task 3. 1.4: Tasks 5 and 7; "each section is built on its own" is Part 2's (spec 2.4, `populateAppSettings`), named in the Part 2 seam constraint. 1.5: out of scope by instruction. 1.6: toolbar (Tasks 4, 6; economics excluded), danger style (Tasks 3, 8; store Decline excluded as a `/fleet*` page; app delete and Roll back already use it), page heads (Task 8; operator pages excluded), account settings rows (Task 8), help-text pointers (Tasks 7, 8), Trash per-row delete (Task 8). 1.3's "link to older ones": Task 3's pager. |
| -- **Astra review (e9f42e19) dispositions.** Finding 9: accepted, Task 3 now pages Versions (`VersionsPage`, `?page=`) and tests that version 21 onward is reachable; cost stays one listing plus 20 manifest reads per page. Finding 15: accepted, Task 7 moves both app-level POST handlers' redirects and asserts them. Finding 12: merge order stated in the header; Task 3 lists the Releases data flow for perf 2; perf 2 owns the fragment-test conversion. |
| +- **Astra review (e9f42e19) dispositions.** Finding 9: accepted, Task 3 now pages Versions (`VersionsPage`, `?page=`) and tests that version 21 onward is reachable; cost stays one listing plus 20 manifest reads per page. Finding 15: accepted, Task 7 moves both app-level POST handlers' redirects and asserts them. Round 2 finding 2: accepted, `VersionsPage` and `VersionCandidatesPage` take `ctx` and the plan uses perf 1's `Versions(ctx, …)`. Finding 12: merge order stated in the header; Task 3 lists the Releases data flow for perf 2; perf 2 owns the fragment-test conversion. |
| - **Spec citations re-checked against 0d2e2762.** The Overview pointer is now `app_overview.html:69,71,75` (spec says :62) and the tile heading at :55; the settings pointer is `app_settings.html:563` (spec says :494); `fleet_byo.html:76-77`; `lognav` now holds Availability as a fourth sub-tab; an extra leftover link sits at `app_settings.html:202`; the activity feed links channel targets to `/deployments` at `server.go:3965`. |
| ## Decisions taken as my call |
diff --git a/docs/superpowers/plans/2026-10-25-operator-pages.md b/docs/superpowers/plans/2026-10-25-operator-pages.md| index 13129eb36..dd0c1210a 100644 |
| --- a/docs/superpowers/plans/2026-10-25-operator-pages.md |
| +++ b/docs/superpowers/plans/2026-10-25-operator-pages.md |
| @@ -25,7 +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. |
| -- **Gates unchanged.** `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. |
| +- **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. |
| - **Go cache:** leave `GOCACHE`, `GOMODCACHE` and `GOTMPDIR` at their defaults (`~/.cache/go-build`). Run go with the sandbox off if the default cache is read-only. |
| @@ -67,10 +67,11 @@ Each is marked *(my call)* where it appears in a task. |
| - **Newest people:** Account is the account of the person's earliest live membership (else `none`); Apps counts live apps they created (`apps.created_by`). |
| - **People and accounts:** one page with `seg-tabs` People and Accounts (`?show=accounts`), each with its own search (`q`, literal, at most 100 characters) and numbered pages of 50. Accounts lists live accounts only. |
| - **Activity:** newest first by `audit.id`, 50 per page, keyset paging (`before=<id>`, links Newest and Older) because `OFFSET` over the audit table grows. Kinds: Everything, Deploys (`promote`, `rollback`), Sign-ins (`signin`, `first-signin`), Accounts and invites (`account-created`, `account-deleted`, `invite-sent`, `invite-accepted`), Other changes (everything else). The account filter is `?account=<sqid>`, reached from the Account column's links; an unknown sqid is an empty feed. The What column is the row's stored `Detail`, as the app Activity tab shows it. |
| -- **Account-level audit rows** have `app = ""`. Sign-ins carry `account_id = 0`; invites and account events carry their account. On a host-claim console (`s.store.claimGated()`) they are not written at all: `audit` is a gated table and an insert without an app permit is refused by the gate's triggers (`store_gate.go:552-585`). Task 6 opens an amadan discussion for that follow-up. |
| -- **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 (`Server.seen sync.Map`), `UPDATE users SET last_seen = ? WHERE address = ? AND last_seen < ?`. |
| -- **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)`; passes that return no error mark the run failed with `jobFailed(ctx, err)` at the failure log sites in their own body (one item failing marks the run Failed; the pass carries on as today). A worker that returns without ever reporting a run is not configured here and drops out of the table. Display order is by label. |
| +- **Account-level audit rows** have `app = ""`. Sign-ins carry `account_id = 0`; invites and account events carry their account. They are written on every console, host-claim consoles included. Today the claim gate's `audit` triggers refuse any insert without an app permit (`store_gate.go:535-585`), so Task 6A classifies `audit` with the gate's existing `FreeWhenNoApp` rule, the one `cli_tokens` already uses for its app-less user tokens (`store_gate.go:191`): a row whose `app` is `''` names no app incarnation, so no app permit can cover it, and the rule admits exactly those rows. Rows with any app (including the existing `account` and `(service credentials)` subjects) still need their permit, and moving a row into or out of an app still checks both sides. The change goes through an independent gate review recorded on #280 before merge (Task 6A). *(My call: this is the "or equivalent" to an account permit; it reuses a reviewed gate rule instead of adding a permit mode, which would need a new `CHECK` value, new trigger branches and a new grant constructor.)* |
| +- **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. |
| - **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). |
| --- |
| @@ -94,6 +95,7 @@ Each is marked *(my call)* where it appears in a task. |
| | `internal/console/store.go` (modify `:551`) | `migrate` calls `migrateOperatorPages` | 4 | |
| | `internal/console/lastseen.go`, `lastseen_test.go` (create) | `noteSeen` and its call sites | 5 | |
| | `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 | |
| | 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 | |
| @@ -294,7 +296,8 @@ file LICENSE LICENSE 3f3d9e0024b1921b067d6f7f88deb4a60cbe7a78e76c64e3f1d7fc3b779 |
| - `TestRastrilloCopiesMatchTheTag`: skipped unless `RASTRILLO_REPO` is set; for each line, `git -C $RASTRILLO_REPO show <tag>:<source>` equals the file byte for byte, and `git rev-list -n1 <tag>` equals `Commit`. |
| - `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>/../server.go`, `/static/<hash>/rastrillo/VERSION/x` all answer the mux's missing-route 404 body. |
| + - `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. |
| - `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. |
| @@ -385,15 +388,16 @@ Every method is a read on `s.db` except `TouchLastSeen`, which writes `users`, a |
| **Interfaces:** |
| - Consumes: `Store.TouchLastSeen`. |
| -- Produces: `const lastSeenEvery = time.Hour`; `Server.seen sync.Map` (address → `time.Time` of the last write attempt); `func (s *Server) noteSeen(addr string, now time.Time)`: returns at once when the map holds a time within `lastSeenEvery` of `now`; otherwise stores `now` and calls `TouchLastSeen`, logging a failure (`console: last seen %s: %v`) and keeping the entry, so a failing database is retried an hour later, not on every request. |
| +- Produces: `const lastSeenEvery = time.Hour`; `Server.seenMu sync.Mutex` and `Server.seen map[string]time.Time` (address → when its current hour was reserved; made in `NewServer`); `Server.lastSeenWrites atomic.Int64` (write attempts, read by tests and by nothing else); `func (s *Server) reserveSeen(addr string, now time.Time) bool`: under `seenMu`, false when `seen[addr]` is within `lastSeenEvery` of `now`, otherwise sets `seen[addr] = now` and returns true; `func (s *Server) noteSeen(addr string, now time.Time)`: when `reserveSeen` is true, increments `lastSeenWrites` and calls `TouchLastSeen` outside the lock, logging a failure (`console: last seen %s: %v`) and keeping the reservation, so a failing database is retried an hour later, not on every request. |
| Call sites: `session()` after `SessionAddress` succeeds; `cliRoute` after `CLIPrincipal` succeeds and only when `p.Kind == PrincipalUser`; `cliUser` after `CLITokenAddress` succeeds; `finishSignin` after `CreateSessionMethod` succeeds (with its `now`). Synchronous: one indexed `UPDATE` per person per hour. *(My call: CLI use counts as being active; service credentials do not, since they are not people.)* |
| - [ ] **Step 1: Write the failing tests** on `newConsoleFixture`: |
| - - `TestLastSeenIsWrittenOncePerHour`: Paul signs in (one write: `last_seen` set); ten GETs of `/apps/kass` do not change it (read `last_seen` directly with a test query helper on `fx.st`); after `fx.srv.seen.Store(addr, time.Now().Add(-61*time.Minute))`, one more GET moves it. |
| + - `TestLastSeenIsWrittenOncePerHour`: Paul signs in (`lastSeenWrites` 1, `last_seen` set); ten GETs of `/apps/kass` leave `lastSeenWrites` at 1; after setting `fx.srv.seen[addr]` to `time.Now().Add(-61*time.Minute)` under `seenMu`, one more GET makes it 2 and moves `last_seen`. |
| + - `TestLastSeenReservationIsAtomic`: with the reservation expired as above, 64 concurrent GETs of `/apps/kass` (one `sync.WaitGroup`, a start barrier) raise `lastSeenWrites` by exactly 1; and 64 goroutines calling `fx.srv.noteSeen(addr, now)` directly with one `now` after expiry raise it by exactly 1. Run with `-race`. |
| - `TestLastSeenFromTheCLI`: a request through a CLI door with Paul's CLI token writes it; a service credential's request does not create or move anyone's `last_seen`. |
| - - `TestLastSeenWithNoUserRowIsHarmless`: delete Paul's `users` row through a test query on `fx.st`, clear `fx.srv.seen`, GET `/apps/kass`: the page answers as it does today, no `users` row is created, and the next GET within the hour makes no second attempt (the map holds the address). |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLastSeen' -count=1`. Expected: FAIL. |
| + - `TestLastSeenWithNoUserRowIsHarmless`: delete Paul's `users` row through a test query on `fx.st`, clear `fx.srv.seen` under `seenMu`, GET `/apps/kass`: the page answers as it does today, no `users` row is created, and the next GET within the hour leaves `lastSeenWrites` unchanged. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLastSeen' -count=1 -race`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** Step 2's command and `go test ./internal/console/ -run 'TestConsoleE2E|NonMember|CSRF|TestAuthCLIFamily|TestEveryCLIDoorNamesItsRoles|TestEmailSignin' -count=1`. Expected: PASS. |
| - [ ] **Step 5: Commit**, message `console: remember when each person was last seen, at most once an hour`. |
| @@ -405,10 +409,10 @@ Call sites: `session()` after `SessionAddress` succeeds; `cliRoute` after `CLIPr |
| - Modify: `internal/console/emailsignin.go` (`finishSignin`), `internal/console/server.go:2382-2400` (`mintAccount`), `:2628` (invite sent), `:2836` (invite accepted), `internal/console/ownership.go:168` (account deleted) |
| **Interfaces:** |
| -- Consumes: `Store.RecordActivity`, `Store.claimGated`, approved OPS-131 to OPS-136. |
| +- Consumes: `Store.RecordActivity`, approved OPS-131 to OPS-136. |
| - Produces: |
| - `const ( auditFirstSignin = "first-signin"; auditSignin = "signin"; auditInviteSent = "invite-sent"; auditInviteAccepted = "invite-accepted"; auditAccountCreated = "account-created"; auditAccountDeleted = "account-deleted" )` and `var accountAuditActions = []string{…all six}` (Task 11's kinds read it). |
| - - `func (s *Server) auditAccount(accountID int64, addr string, a Activity)`: returns at once when `s.store.claimGated()`; otherwise `RecordActivity(accountID, "", addr, a, time.Now())`, logging a failure (`console: account audit %s: %v`) and never failing the action. |
| + - `func (s *Server) auditAccount(accountID int64, addr string, a Activity)`: `RecordActivity(accountID, "", addr, a, time.Now())` on every console, logging a failure (`console: account audit %s: %v`) and never failing the action. (`withAutoAppSQL` already calls straight through for `app == ""`, `claim_sql_auto.go:15`; on a host-claim console the insert is admitted by Task 6A's gate rule.) |
| Where each is recorded, after the action has succeeded and before the response: |
| @@ -421,7 +425,7 @@ Where each is recorded, after the action has succeeded and before the response: |
| | `account-created` | after `CreateAccount` succeeds in `mintAccount` (covers the browser, the CLI and first sign-in) | the new id | TargetType `account`, Target the sqid, Detail OPS-135 | |
| | `account-deleted` | after `DeleteAccount` succeeds (`ownership.go:168`) | the account | TargetType `account`, Target the sqid, Detail OPS-136 | |
| -The `app` column is `""`, so these rows never show on any app's Activity tab (`Events` filters by app). *(My call: on a host-claim console these rows are skipped rather than attempted, because the gate's `audit` triggers refuse an insert without an app permit; in Step 5 open `amadan discuss new carlos/platform -title "Account-level activity on a host-claim console" -body -` describing the refusal and two options, a NonApp `people_activity` table or an account permit, without building either.)* |
| +The `app` column is `""`, so these rows never show on any app's Activity tab (`Events` filters by app). Until Task 6A lands (the next commit on this branch), a host-claim console refuses the insert and logs it; nothing else differs. |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestFirstSignInThenSignInAreRecorded`: a new address signs up (`signUp` helper): one `first-signin` row with `app ""` and `account_id 0`; signing out and in again adds one `signin`; and the account minted at landing adds one `account-created` row naming its sqid. |
| @@ -429,11 +433,30 @@ The `app` column is `""`, so these rows never show on any app's Activity tab (`E |
| - `TestAccountDeletedIsRecorded`: delete a second, empty account through its settings door (with its confirmation): one `account-deleted` row. |
| - `TestRefusedActionsRecordNothing`: an invite refused by the rate limit, an `AcceptInvite` of an unknown token, and a delete refused for a non-owner write no row. |
| - `TestAccountActivityNeverShowsOnAnAppTab`: after the rows above, `/apps/kass/activity` shows none of OPS-131 to OPS-136. |
| - - `TestAccountActivitySkippedUnderClaimGate`: on `newClaimCase`, a sign-in succeeds and writes no account-level row. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestFirstSignIn|TestInviteSentAndAccepted|TestAccountDeletedIsRecorded|TestRefusedActionsRecordNothing|TestAccountActivityNever|TestAccountActivitySkipped' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestFirstSignIn|TestInviteSentAndAccepted|TestAccountDeletedIsRecorded|TestRefusedActionsRecordNothing|TestAccountActivityNever' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Implement**; add OPS-131 to OPS-136 to `operatorPagesCopyBuilt`. |
| - [ ] **Step 4: Run** Step 2's command, `go test . -run TestOperatorPagesCopy -count=1`, `go test ./internal/console/ -run 'TestInvite|TestTeam|TestDeleteAccount|TestEmailSignin|TestCallback|TestActivityTab' -count=1`. Expected: PASS. |
| -- [ ] **Step 5: Open the discussion** above and commit, message `console: account-level activity: sign-ins, invites, accounts created and deleted`. |
| +- [ ] **Step 5: Commit**, message `console: account-level activity: sign-ins, invites, accounts created and deleted`. |
| + |
| +### Task 6A: The claim gate admits account-level audit rows, with its gate review |
| + |
| +**Files:** |
| +- Modify: `internal/console/store_gate.go:190` (`"audit": {Account: "account_id", App: "app", FreeWhenNoApp: true}`, with a comment giving the reason: account-level rows name no app incarnation, so no app permit can cover them; the rows are the operator's activity record of sign-ins, invites and accounts) |
| +- Modify: `internal/console/store_gate_test.go` (the tests below), `internal/console/opaudit_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: the gate's `FreeWhenNoApp` (`store_gate.go:141-144`, `:535-541`), `newClaimCase`, Task 6's `auditAccount`. |
| +- Produces: no new type or function. The gate's classification of `audit` changes in one field; every other table, the permit table, the triggers' generation and `withClaimSQL` are untouched. `claimProbeAllSQL` (`claim_probe_all_apps_test.go:57`) already leaves app-less rows of a `FreeWhenNoApp` table out of its digests, so a read probe that signs someone in still sees no app's rows change. |
| + |
| +- [ ] **Step 1: Write the failing tests** (in `store_gate_test.go`, beside `TestClaimSQLUnauthorizedWritesDenied`, on the armed store those tests use): |
| + - `TestClaimSQLAuditAdmitsAppLessRows`: with no permit, `RecordActivity(0, "", addr, Activity{Action: "signin"}, now)` and `RecordActivity(acct, "", …)` succeed. |
| + - `TestClaimSQLAuditStillGatesAppRows`: with no permit, an insert with app `kass`, with app `account` (`accountAuditSubject`) and with app `(service credentials)` are each refused with `claimDenyMessage`, exactly as before the change. |
| + - `TestClaimSQLAuditCannotMoveRowsAcrossTheLine`: with no permit, an `UPDATE audit SET app = 'kass'` of an app-less row is refused (NEW is checked); an `UPDATE audit SET app = ''` of a `kass` row is refused (OLD is checked); a `DELETE` of a `kass` row is refused. |
| + - `TestAccountActivityRecordedUnderClaimGate` (in `opaudit_test.go`, production wiring): on `newClaimCase`, a sign-in succeeds and writes one `first-signin` (or `signin`) row with `app ""`; an invite through the browser door writes `invite-sent`. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestClaimSQLAudit|TestAccountActivityRecordedUnderClaimGate' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement** the one-field change and its comment. |
| +- [ ] **Step 4: Run** Step 2's command, the gate's own suite `go test ./internal/console/ -run 'TestClaimSQL|TestClaimProbe|TestClaimConsoleRouteCensus' -count=1`, and `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`. Expected: PASS. |
| +- [ ] **Step 5: Gate review.** Run `make census-card` and record any unit it names in Task 15's CLAIMS. Give an independent reviewer of the other model family (Astra) the diff of `store_gate.go` and these tests against the task's base, with this brief: does admitting `app = ''` rows of `audit` without a permit let any request, tenant, app or box agent change, hide or forge a row that an app permit, a purge or a restore relies on; can an app-less row be turned into an app row, or the reverse, without a permit; is any existing refusal weakened. Record the verdict on #280 with the reviewer, the tip and the lines read. An escalation goes to Paul as a decision, and Task 6A's commit waits for it (the rest of the plan does not). Then commit, message `claim gate: audit admits account-level rows (app ''), as cli_tokens does; reviewed on #280`. |
| ### Task 7: Background job registry |
| @@ -457,7 +480,9 @@ The `app` column is `""`, so these rows never show on any app's Activity tab (`E |
| Each loop wraps one pass in `s.jobs.Run` with its worker name as a string literal, keeping its existing log line: |
| - returns an error: `if err := s.jobs.Run(ctx, "StartAlertWatcher", s.alertPass); err != nil { log.Printf(…as today…) }` (adapt to each pass's signature with a closure: `economicsPass(ctx, time.Now())`, `mailPushPass(ctx, time.Now)`, `RunClaimRecoveryPass`, `infraPass`, `scanPass`, `relayReconcile` inside the lease branch only, the host report and its put in `runHostReports`, one drain tick in `StartScanDrain`, one attempt of `publishPlansMarkerOnce` (false is a failure: `errors.New("plans marker not published")`), `PublishMovesConsole`). |
| -- returns nothing: `_ = s.jobs.Run(ctx, "StartExpiryPass", func(ctx context.Context) error { s.expiryPass(ctx, time.Now()); return nil })`, and in that pass's own body every existing failure `log.Printf` gains `jobFailed(ctx, err)` beside it: `expiryPass`, `planLimitsPass`, `planGracePass`, `runSweepPass`, `seedsPass`, `resignDoorKeys`, `geoipPass`, `apexSquats`, `logPlacementDiscrepancies`. |
| +- returns nothing: `_ = s.jobs.Run(ctx, "StartExpiryPass", func(ctx context.Context) error { s.expiryPass(ctx, time.Now()); return nil })`. |
| +- in both shapes, every failure the pass logs and steps over gains `jobFailed(ctx, err)` in the same block: the error-returning passes (`alertPass` at `alertwatch.go:121` and `:126`, the stage errors `economicsPass` logs and continues past, `infraPass`, `scanPass`, `relayReconcile`, `mailPushPass` (its prune failure), `RunClaimRecoveryPass`, `runHostReports`, the scan drain tick) and the void ones (`expiryPass`, `planLimitsPass`, `planGracePass`, `runSweepPass`, `seedsPass`, `resignDoorKeys`, `geoipPass`, `apexSquats`, `logPlacementDiscrepancies`). A per-item helper a pass calls that logs and swallows a failure without a `ctx` (`recordAlertSeenFor`, `alertwatch.go:243-270`) takes the pass's `ctx` so it can call `jobFailed` too. |
| +- test-only: `var jobPassFuncs = map[string][]string{"StartAlertWatcher": {"alertPass", "alertRule", "recordAlertSeenFor", "recordAlertSeen"}, "StartEconomicsPass": {"economicsPass"}, …}`: for each worker, the function names whose bodies run inside its `Run` and may log a failure. The implementer completes it by reading each pass; the test below refuses a worker with no entry. |
| `registerClaimWorkers` calls `s.jobs.declare(name)` for every worker; `RunClaimWorker` calls `s.jobs.exited(name)` after `h(ctx)` returns. Sub-loops a pass starts (`relayWriterLoop`, `runCapacityPass`, `startEnrollPass`, the geoip feeder, the scan delivery pool) are not separate jobs. *(My call.)* |
| @@ -465,8 +490,10 @@ Each loop wraps one pass in `s.jobs.Run` with its worker name as a string litera |
| - `TestJobRegistryRecordsRuns` (not acceptance): declare two names; `Snapshot` shows both Not run yet; a `Run` returning nil makes one OK with `LastRan`; a `Run` whose pass calls `jobFailed(ctx, errors.New("a"))` and then `jobFailed(ctx, errors.New("b"))` and returns nil is Failed with `Err "a"`; a later OK run clears it; `exited` on a never-run name drops it. |
| - `TestJobNoteIsTheFirstLineCappedAndEscaped` (Review Focus 3): error `"<b>disk</b> full\nsecond line"` gives note `<b>disk</b> full`; a 500-rune line gives 160 runes ending `…`; rendered through `op_jobs` the body holds `<b>` and still exactly one `<h1>` on the Boxes page (asserted in Task 8). |
| - `TestEveryWorkerReportsItsRuns`: parse every non-test `.go` file in the package with `go/parser`; collect the string-literal second argument of every call whose selector is `.jobs.Run`; that set equals the keys of `fx.srv.claimWorkers` (built by `newConsoleFixture`), and every key has a `jobLabels` entry. |
| + - `TestPassFailureLogsAlsoFailTheJob`: `jobPassFuncs` has a key for every worker; for each listed function (parsed with `go/parser` from the package's non-test files; a name that resolves to no function fails), every `log.Printf` call statement with an argument that is an `error`-named identifier (`err`, `e`, or a name ending `Err`) sits in a block that also contains a `jobFailed(` call, unless the same block returns that error. A deliberately unmarked copy of one site, checked once by hand, makes it fail. |
| + - `TestSwallowedAlertFailureShowsAsFailed` (acceptance, production wiring): on `newConsoleFixture` with Paul an operator, write a corrupt `alerts/boxes/box-1.json` (not JSON) to `fx.rel`; run `fx.srv.RunClaimWorker(ctx, "StartAlertWatcher")` until its first run is recorded, then cancel; `Snapshot` has Alerts `JobFailed` with a note naming the unparsable key; once Task 9 has landed, GET `/fleet` shows OPS-31 for Alerts in the callout and Failed in the jobs table (the test's second half lands with Task 9 and is listed in its Step 1). |
| - `TestWorkerRunsReachTheRegistry` (production wiring): on `newConsoleFixture`, start `fx.srv.RunClaimWorker(ctx, "StartAlertWatcher")` in a goroutine; wait (poll `Snapshot`, 5 s cap) until it has a run; cancel; the worker returns; its row is OK or Failed, never Not run yet. Then `RunClaimWorker(ctx, "StartRelay")` with no relay regions returns at once and `StartRelay` is absent from `Snapshot`. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestJobRegistry|TestJobNote|TestEveryWorkerReports|TestWorkerRunsReach' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestJobRegistry|TestJobNote|TestEveryWorkerReports|TestPassFailureLogs|TestSwallowedAlertFailure|TestWorkerRunsReach' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Implement**; add OPS-32 and OPS-77 to OPS-102 to `operatorPagesCopyBuilt` (OPS-67's file is the dashboard's; Task 9 adds it). |
| - [ ] **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`. |
| @@ -522,6 +549,7 @@ Each loop wraps one pass in `s.jobs.Run` with its worker name as a string litera |
| - [ ] **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). |
| - `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. |
| - `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"`. |
| @@ -589,13 +617,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`); 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), 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. |
| - [ ] **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). |
| - 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`. |
| @@ -616,6 +645,8 @@ 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. |
| + - 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.)* |
| @@ -625,12 +656,14 @@ On a `fleet.json` miss, the dashboard's whole body is the deferred part, because |
| - [ ] **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. |
| - `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`: with plan 2's `Hold` on the `status/boxes/` listing, GET `/fleet` and quiesce everything but the held load (so `fleet.json` and the storage queue are warm and the box entry is still loading); GET `/fleet` again: within 150 ms, the callout and stats render and the Boxes section is `data-part="/fleet/part/dashboard-boxes"`; release the hold; the part answers the five-column table. |
| + - `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`. |
| + - `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. |
| - `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`). |
| - `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|TestEveryFleetPart|TestDashboardAfterAStoreDecision|TestEveryOperatorPage' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestDashboardCold|TestDashboardBoxesCold|TestBoxReadsOncePerWindow|TestEveryFleetPart|TestDashboardAfterAStoreDecision|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`. |
| @@ -672,16 +705,17 @@ ls "$SHOTS"/*.png | wc -l # 44 |
| **Files:** |
| - Create (by the tool): the census overlay and `docs/superpowers/notes/census-proposal-operator-pages.md` |
| -- [ ] **Step 1: Census card.** `make census-card`. For every changed unit write a CLAIMS line (`<file>:<unit><TAB><what changed, and that no read was added or which one was>`): new SQLite reads and one users write, embedded static files, templates, a job registry around existing passes, no new read of root-owned state. `make census-propose NAME=operator-pages CLAIMS=<file>`. A `reads`, `new`, `removed` or `other` class is a decision for Paul on #280, not an approval. |
| +- [ ] **Step 1: Census card.** `make census-card`. For every changed unit write a CLAIMS line (`<file>:<unit><TAB><what changed, and that no read was added or which one was>`): new SQLite reads and one users write, embedded static files, templates, a job registry around existing passes, the `audit` gate classification (Task 6A, reviewed on #280), no new read of root-owned state. `make census-propose NAME=operator-pages CLAIMS=<file>`. A `reads`, `new`, `removed` or `other` class is a decision for Paul on #280, not an approval. |
| - [ ] **Step 2: Independent approval.** Give the card and the branch diff against amadan `main` to a reviewer of the other model family (Astra for this Claude-written branch); record each verdict on #280 with the reviewer and the tip. |
| - [ ] **Step 3: Local gate.** `gofmt -l .` (empty), `go vet ./internal/console/ ./cmd/console/`, `go build ./...`, both cross-compiles, the targeted runs from Tasks 2 to 13, `go test . -run 'TestOperatorPagesCopy|TestConsolePerfCopy' -count=1`, one `nice -n 19` run of `TestClaimConsoleMutationInvariant`, one `go test ./internal/console/ -run 'TestJob|TestLastSeen|TestStatic' -race -count=1`, and the walk with `CI=1`. Update `.amadan/test-weights.tsv` for any new test of a second or more. |
| -- [ ] **Step 4: Push, describe, wait for CI.** `amadan branch describe carlos/platform operator-pages -body -`: what changed, why, the decisions above, the screenshot review notes, the census approval, the follow-up discussion from Task 6. `amadan ci status carlos/platform -branch operator-pages` until exit 0. |
| +- [ ] **Step 4: Push, describe, wait for CI.** `amadan branch describe carlos/platform operator-pages -body -`: what changed, why, the decisions above, the screenshot review notes, the census approval, Task 6A's gate-review verdict on #280. `amadan ci status carlos/platform -branch operator-pages` until exit 0. |
| - [ ] **Step 5: Squash, re-run CI on the squashed tip, merge** with the `-expect <tip>` form. Rolling waits for Paul's go-ahead and follows the house roll order (dev boxes, dev console, check, flagship boxes, flagship console); after the roll, read `/fleet` on flagship and the Console speed table's `GET /fleet` row. |
| --- |
| ## 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). |
| - **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`. |