plan: edge page cache slice 1 (home box)
Twelve tasks: store hooks, the page index and its simulation, the pages switch, marker handling, home serving, clears, resets, arming, copy, the switch door and CLI, and the branch gate.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+766
−0
docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md+766 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md b/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md| new file mode 100644 |
| index 000000000..f66ad0c50 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md |
| @@ -0,0 +1,766 @@ |
| +# Edge page cache, slice 1 (home box) Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** An app marks a response with `Carlos-Page-Cache: on`, and its |
| +home box keeps the page on disk and serves it without waking the app, |
| +until the app clears it or a new release or config arrives. |
| + |
| +**Architecture:** |
| +- **`internal/pageindex`** is the spec's page index (§6.1). It is the |
| + only code that publishes, clears, resets or looks up a page. It |
| + stores bytes in the existing `internal/assetcache` store under keys |
| + whose `Gen` begins `page:`. |
| +- **The edge** looks pages up at today's LRU point. It records marked |
| + responses through the index, and routes both purge channels into it. |
| +- **Opted-in instances** (holding a durable opt-in mark) skip the LRU |
| + entirely. |
| +- **Not in this slice:** far boxes, leases and pushes. |
| + |
| +**Tech Stack:** Go stdlib; existing `internal/assetcache`, |
| +`internal/edge`, `internal/registry`, `internal/provision`, |
| +`internal/console`, CLI in the repo root. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-08-edge-page-cache-design.md` |
| +(rev 4, approved). Slice 1 is spec §11 item 1. The sections it builds |
| +are §4, §5, §6, §8.1 (home side), §8.6 and §10. |
| + |
| +**Branch:** `edge-page-cache-1`, cut from `main` after |
| +`design-edge-page-cache` (spec and this plan) has merged. Stopping |
| +rule 4 forbids building against an unmerged design. |
| + |
| +## Global Constraints |
| + |
| +**The marker and lifetimes:** |
| +- The marker header is exactly `Carlos-Page-Cache`. Value `on`, with an |
| + optional `; ignore-cookies="a,b"` parameter. The edge strips it from |
| + every response on every box, armed or not. |
| +- Lifetime is `s-maxage`, else `max-age`. It must be positive and is |
| + capped at 365 days. `private`, `no-store` and `no-cache` refuse. |
| + |
| +**What is kept:** |
| +- Status 200 only. |
| +- No `Set-Cookie`, as a header or as a trailer. |
| +- `Vary` absent or exactly `Accept-Encoding`. |
| +- No `Content-Range`, no `Cache-Control: no-transform`, and |
| + `Content-Encoding` absent or `identity`. |
| +- Body at most 8 MiB: `pageindex.MaxBody = 8 << 20`. |
| +- Any `Content-Type`. |
| + |
| +**Requests:** |
| +- **Reading the cache:** GET or HEAD; no `Range`; not an upgrade; not a |
| + door call; not `markedRequest(r)`; no `Authorization`; and every |
| + cookie name (if any) is on the hit entry's ignore list. The path must |
| + satisfy `canonicalAssetPath`. |
| +- **Storing:** only a GET with no `Cookie` and no `Authorization`. A |
| + HEAD is never stored. |
| + |
| +**Eligible routes:** |
| +- `Kind == "instance"`, not `IsForward()`, not `HA`, not |
| + `IsSidecar()`, `Status == "ready"`. |
| +- `Gate == ""`, `ImportGate == ""`, `!PagesOff`, no path rows |
| + (`len(up.paths) == 0`). |
| +- The path is not under a declared asset prefix of the host. |
| + |
| +**Keys and scopes:** |
| +- A **scope** is (account, app, instance), where the instance is the |
| + primary `route.Host`. Aliases fold to their primary. |
| +- A **key** is (account, app, host, path, raw query) exactly as sent. |
| + |
| +**Clears and switches:** |
| +- A clear target `all` (bare word) clears every host of the instance. |
| + It works in the `Carlos-Purge` header and the control socket |
| + (`{"path":"all"}`). |
| +- **Clear log bounds:** the last 256 clears or 10 minutes, whichever |
| + holds less. |
| +- **Arming:** `CARLOS_PAGE_CACHE=1` in host.env. It needs the asset |
| + store armed (`CARLOS_ASSET_CACHE=1`). Unarmed boxes treat the marker |
| + as absent. |
| +- **Cache header:** `Carlos-Cache: hit|miss|bypass` on responses of |
| + opted-in instances and on marked responses, with the asset cache's |
| + words. |
| + |
| +**Copy and commits:** |
| +- **Copy:** every new user-facing string goes through the copy deck and |
| + the `copy-review` skill before it is written into code (Task 10). No |
| + em dashes. |
| +- **Tests:** targeted runs only, `go test ./internal/<pkg> -run |
| + '<Name>' -count=1`. Packages that bind unix sockets (`edge`, |
| + `activator`, `host`) run outside the sandbox with `TMPDIR=/tmp/g` |
| + (`mkdir -p /tmp/g` first). CI runs the full suite. |
| +- **Commits:** subjects under 80 characters, prefixed by package |
| + (`pageindex:`, `edge:`, `registry:`, `console:`, `cli:`, `docs:`, |
| + `host:`). |
| + |
| +## Review Focus |
| + |
| +1. **Range, HEAD and `If-None-Match` on a page hit.** A `Range` request |
| + bypasses. HEAD gets headers and no body. A matching |
| + `If-None-Match` gets 304. Tests go in Task 6. |
| +2. **An app that compresses its own response** (`Content-Encoding: |
| + gzip`). It is passed through, not stored, and never compressed |
| + twice. Test in Task 6. |
| +3. **A marked response with no `Content-Length` that grows past 8 MiB.** |
| + The visitor still gets every byte, and nothing is stored or half |
| + stored. Test in Task 6. |
| +4. **A marked response to a cookie-carrying request.** It isn't stored |
| + in either cache, and a later anonymous request still misses. Test in |
| + Task 6. |
| +5. **Clearing through an alias or custom domain.** `Carlos-Purge: *` on |
| + an alias host clears that host's pages. `all` clears the primary and |
| + every alias. Test in Task 7. |
| + |
| +--- |
| + |
| +### Task 1: The store gives the index what it needs |
| + |
| +**Files:** |
| +- Modify: `internal/assetcache/store.go` (add `Delete`). Modify: |
| + `internal/assetcache/key.go` (add `PageGenPrefix`). |
| +- Modify: `internal/edge/assetarm.go:81` (`sweepAssets` keeps page |
| + keys). |
| +- Test: `internal/assetcache/store_test.go`, |
| + `internal/edge/assetarm_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `const PageGenPrefix = "page:"`; |
| + - `func (s *Store) Delete(k Key) bool`: drops the entry and its files, |
| + reporting whether one existed; |
| + - `func IsPageKey(k Key) bool`, which is |
| + `strings.HasPrefix(k.Gen, PageGenPrefix)`. |
| + |
| +- [ ] **Step 1: Write failing tests** |
| + - `TestDeleteDropsEntryAndFiles`: Commit an entry, `Delete` it. |
| + Assert `true`, then that `Get` misses and no `<id>.*` files remain |
| + in the dir. A second `Delete` returns `false`. |
| + - `TestSweepAssetsKeepsPageKeys`: arm a scene, as in |
| + `asset_local_test.go`'s `newLAScene`. Commit one asset key and one |
| + key with `Gen: "page:x:1"`, then make both authorities ready and |
| + let neither name the page key. Assert `sweepAssets` drops only the |
| + asset key. |
| +- [ ] **Step 2: Run them to see them fail:** `go test |
| + ./internal/assetcache -run TestDeleteDropsEntryAndFiles -count=1` |
| + and `TMPDIR=/tmp/g go test ./internal/edge -run |
| + TestSweepAssetsKeepsPageKeys -count=1` fail on the missing symbols. |
| +- [ ] **Step 3: Implement** |
| + - `Delete` wraps the unexported `drop` under the store's lock. |
| + - `sweepAssets`'s keep predicate returns `true` first when |
| + `assetcache.IsPageKey(k)`. |
| +- [ ] **Step 4: Run both to see them pass.** |
| +- [ ] **Step 5: Commit:** `assetcache: Delete and page keys the asset |
| + sweep leaves alone`. |
| + |
| +### Task 2: The page index core (`internal/pageindex`) |
| + |
| +**Files:** |
| +- Create: `internal/pageindex/index.go` (types, Open, Begin, |
| + Clear, Reset, Lookup). |
| +- Create: `internal/pageindex/pending.go` (Reserve, Pending). |
| +- Create: `internal/pageindex/optin.go` (durable marks). |
| +- Test: `internal/pageindex/index_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `assetcache.Store` (`Reserve`, `Fill.Write/Abort/Commit`, |
| + `Get`, `Delete`, `Retain`), plus `assetcache.PageGenPrefix` and |
| + `IsPageKey`. |
| +- Produces: |
| +```go |
| +type Scope struct{ Account, App, Instance string } |
| +type Key struct{ Host, Path, RawQuery string } |
| +type TargetKind int // TargetHost, TargetPath, TargetURL |
| +type Target struct{ Kind TargetKind; Path, RawQuery string } |
| +type Clear struct { |
| + Hosts []string // nil = every host of the scope |
| + Targets []Target // nil = everything on Hosts |
| +} |
| +type Ticket struct{ Scope Scope; Epoch, Seq uint64 } |
| +type Info struct{ ValidAt uint64; Ignore []string } |
| +type Config struct { |
| + Store *assetcache.Store |
| + MarkDir string |
| + Now func() time.Time |
| + LogMax int // 0 means 256 |
| + LogAge time.Duration // 0 means 10 * time.Minute |
| +} |
| +const MaxBody = 8 << 20 |
| +func Open(cfg Config) (*Index, error) |
| +func (x *Index) Begin(s Scope) Ticket |
| +func (x *Index) Reserve(t Ticket, k Key, contentLength int64) (*Pending, error) |
| +func (p *Pending) Write(b []byte) (int, error) |
| +func (p *Pending) Abort() |
| +func (p *Pending) Finish(m assetcache.Meta, info Info) (published bool, err error) |
| +func (x *Index) Clear(s Scope, c Clear) (seq uint64) |
| +func (x *Index) Reset(s Scope) |
| +func (x *Index) Lookup(s Scope, k Key, cookieNames []string) (*assetcache.Entry, bool) |
| +func (x *Index) MarkOptIn(s Scope) error |
| +func (x *Index) ClearOptIn(s Scope) error |
| +func (x *Index) OptedIn(s Scope) bool |
| +func (x *Index) Scopes() []Scope // scopes with entries, a mark, or a live epoch |
| +``` |
| + |
| +**Rules the implementation must keep** (spec §6.1): |
| +- **One `sync.Mutex` per scope.** Clear, Reset, Lookup and the indexing |
| + step of Finish all run under it. |
| +- **The store key** is `assetcache.Key{Account, App, Gen: PageGenPrefix |
| + + Instance + ":" + hex(Epoch), Host, Path, RawQuery}`. |
| +- **The epoch** is a random 64-bit value, drawn the first time a scope |
| + is touched in this process. Reset draws a new one. |
| +- **`Finish`:** |
| + - commits the fill first, outside the scope lock, with |
| + `gzipCopy=true`; |
| + - then takes the lock and indexes the entry only if all of these |
| + hold: |
| + - `t.Epoch` is the scope's epoch; |
| + - `t.Seq` ≤ the scope's sequence; |
| + - the log covers every sequence in (`t.Seq`, current]; |
| + - no clear in that range matches the key; |
| + - otherwise it calls `Store.Delete` and returns `false`; |
| + - `Info.ValidAt` is set to the scope's sequence at indexing. |
| +- **`Clear`:** |
| + - increments the sequence and appends to the log (trimmed to |
| + `LogMax` entries and `LogAge`); |
| + - drops the matching indexed entries with `Store.Delete`; |
| + - returns the new sequence. |
| +- **Matching:** |
| + - `TargetHost` matches every key on the host; |
| + - `TargetPath` matches the path with any query; |
| + - `TargetURL` matches the exact path and raw query; |
| + - `Hosts == nil` means every host; |
| + - `Targets == nil` means everything. |
| +- **`Lookup`** returns the store entry only when all of these hold: |
| + - the key is indexed under the current epoch; |
| + - `Store.Get` still has it (store eviction or expiry removes it from |
| + the index too); |
| + - every name in `cookieNames` is in the entry's `Ignore`. |
| +- **`Open`** runs `Store.Retain(func(k) bool { return |
| + !assetcache.IsPageKey(k) })` once. The pages of an earlier process |
| + are dropped, because their epochs are gone. |
| +- **Opt-in marks:** |
| + - each is one file per scope in `MarkDir`, named by the hex sha256 |
| + of `Account + "\x00" + App + "\x00" + Instance`; |
| + - written to a temp file, fsynced, renamed, then the dir fsynced; |
| + - `Open` loads them; |
| + - `ClearOptIn` removes the file and fsyncs the dir. |
| + |
| +- [ ] **Step 1: Write failing tests** (a temp-dir store, as in |
| + `internal/assetcache` tests): |
| + - `TestPublishThenLookup`: Begin, Reserve, Write, Finish → `true`. |
| + Lookup with no cookies returns the entry, and its body reads back. |
| + - `TestClearRemovesMatching`: publish `/a`, `/a?x=1` and `/b`. |
| + `Clear{Targets: [{TargetPath, "/a"}]}` leaves only `/b`, and |
| + `TargetURL /a?x=1` leaves `/a`. |
| + - `TestClearBetweenBeginAndFinishFences`: Begin, Reserve and Write, |
| + then Clear(TargetPath key), then Finish → `false`. The Lookup |
| + misses and `Store.Get` misses. |
| + - `TestUnrelatedClearDoesNotFence`: same, but clear `/other`. Finish → |
| + `true`. |
| + - `TestLogGapRefuses`: with `LogMax: 2`, Begin, then three clears of |
| + `/other`. Finish → `false`. |
| + - `TestResetDropsAndChangesEpoch`: publish, Reset. The Lookup misses, |
| + and a Ticket from before the Reset gets Finish → `false`. |
| + - `TestIgnoreCookies`: publish with `Info{Ignore: ["consent"]}`. |
| + Lookup with `["consent"]` hits, and with `["consent","sid"]` misses. |
| + - `TestOpenDropsEarlierPages`: publish, close, Open again on the same |
| + store. The Lookup misses and the store has no page keys. |
| + - `TestOptInMarkSurvivesOpen`: MarkOptIn, re-Open → `OptedIn` is |
| + `true`. ClearOptIn, re-Open → `false`. |
| + - `TestTooLargeAborts`: writing more than `MaxBody` returns an error, |
| + and Finish is never reached. Abort leaves no files. |
| +- [ ] **Step 2: Run them to see them fail:** `go test |
| + ./internal/pageindex -count=1` fails to compile. |
| +- [ ] **Step 3: Implement the types and rules above.** |
| +- [ ] **Step 4: Run them to see them pass:** `go test |
| + ./internal/pageindex -count=1 -race`. |
| +- [ ] **Step 5: Commit:** `pageindex: one index owns every page publish, |
| + clear, reset and lookup`. |
| + |
| +### Task 3: The index under a randomized simulation |
| + |
| +**Files:** |
| +- Test: `internal/pageindex/sim_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's API only. |
| + |
| +- [ ] **Step 1: Write `TestSimulationClearsFencePublication`.** |
| + - **The setup:** 8 goroutines run 2000 random operations over 2 |
| + scopes, 3 hosts and 6 paths: Begin + Reserve + Write + (random |
| + sleep 0–2 ms) + Finish, Clear with random targets, Reset, Lookup, |
| + and MarkOptIn/ClearOptIn. |
| + - **The model:** each published body is unique and names its ticket. |
| + The test keeps a model log of clears, with (scope, seq, clear) per |
| + returned seq. |
| + - **It asserts, at every Lookup hit,** that no clear in the model with |
| + seq > the entry's ticket Seq matched its key on the same epoch. |
| + - **Seeding:** a fixed seed from `-seed` (default the time), printed |
| + on failure. `-short` runs 300 operations. |
| +- [ ] **Step 2: Write `TestStoreHoldsNoUnindexedPages`.** After the |
| + simulation and a final `Reset` of every scope, `Store.Retain` with a |
| + counting predicate finds zero page keys. |
| +- [ ] **Step 3: Watch each test fail under its own mutation,** then |
| + restore: |
| + - skip the fence check in `Finish` → the simulation fails; |
| + - skip `Store.Delete` on refusal → the store test fails. |
| +- [ ] **Step 4: Run:** `go test ./internal/pageindex -run Simulation |
| + -count=3 -race` passes. |
| +- [ ] **Step 5: Commit:** `pageindex: randomized simulation of |
| + publishes racing clears`. |
| + |
| +### Task 4: The per-instance switch, `PagesOff` |
| + |
| +**Files:** |
| +- Modify: `internal/provision/provision.go`: |
| + - `Pages *bool` beside `Assets` (:217); |
| + - `func (r Record) PagesOn() bool` beside `AssetsOn` (:569). |
| +- Modify: `internal/provision/reconcile.go`: |
| + - `RouteFor` sets `PagesOff: !rec.PagesOn()` (:586); |
| + - `convergeOwned` calls `reg.SetPages` when it differs (beside |
| + :1005–1016). |
| +- Modify: `internal/registry/registry.go`: |
| + - field `PagesOff bool` beside `AssetsOff` (:120); |
| + - column `{Name: "pages_off", Type: "INTEGER", Default: "0"}` (:747); |
| + - read and scan (:1111–1138), insert (:1708), and the upsert keep rule |
| + as for `assets_off` (:1620); |
| + - `func (r *Registry) SetPages(host string, off bool) error` beside |
| + `SetAssets` (:2520), with `kind <> 'forward'`; |
| + - Fingerprint emits `"\x1fpages_off=1"` only when set (:4060), and |
| + SnapshotFingerprint matches (:4407). |
| +- Modify: `internal/registry/remote_dispatch.go` (request field and |
| + dispatch, as `AssetsOff` :72, :320). |
| +- Modify: `internal/registry/forward.go`: `"PagesOff": "forbidden"` |
| + (:115), the column list (:154), and `!t.PagesOff` in the |
| + forward-inert check (:214). |
| +- Test: `internal/registry/registry_test.go`, |
| + `internal/provision/reconcile_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `Record.Pages *bool`, `Record.PagesOn() bool`, |
| + `Route.PagesOff bool` and `Registry.SetPages(host string, off bool) |
| + error`. |
| + |
| +- [ ] **Step 1: Write failing tests** |
| + - `TestSetPagesRoundTripsAndMovesFingerprint`: upsert a route, record |
| + the fingerprint, `SetPages(host, true)`. Route reads |
| + `PagesOff == true` and the fingerprint changed. `SetPages(host, |
| + false)` restores the original fingerprint. |
| + - `TestConvergeAppliesPagesSwitch`: a record with `Pages: &false` |
| + converges to `PagesOff == true`, and `nil` to `false`. |
| + - `TestForwardRowRefusesPagesOff`: a forward row with `PagesOff` |
| + fails the forward check, as `AssetsOff` does. |
| +- [ ] **Step 2: Run them to see them fail:** `go test |
| + ./internal/registry ./internal/provision -run |
| + 'Pages' -count=1`. |
| +- [ ] **Step 3: Implement, mirroring every `AssetsOff` site listed |
| + above.** |
| +- [ ] **Step 4: Run them to see them pass,** plus `go test |
| + ./internal/registry -run 'Fingerprint|Forward' -count=1`. |
| +- [ ] **Step 5: Commit:** `registry: per-instance pages switch, mirrored |
| + on assets_off`. |
| + |
| +### Task 5: The marker is read once, stripped everywhere, and kept out of the LRU |
| + |
| +**Files:** |
| +- Create: `internal/edge/pagemark.go`. |
| +- Modify: `internal/edge/cookiescope.go:85` (`responseModifier` calls |
| + `takePageMark`). |
| +- Modify: `internal/edge/edge.go` `maybeStore` (:2907). It refuses when |
| + `pageMarkOf(rec.request).Marked`. |
| +- Test: `internal/edge/pagemark_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| +```go |
| +type pageMark struct{ Marked bool; Ignore []string; Bad bool } |
| +func withPageMarkHolder(r *http.Request) *http.Request // attaches an empty *pageMark to the context |
| +func pageMarkOf(r *http.Request) *pageMark // nil when no holder |
| +func takePageMark(resp *http.Response) // parses, strips, fills the holder if any |
| +const pageCacheHeader = "Carlos-Page-Cache" |
| +``` |
| +- **Parsing:** |
| + - `on` gives `Marked`; |
| + - `on; ignore-cookies="a,b"` adds the names; |
| + - anything else sets `Bad` and leaves `Marked` false. |
| +- **Where it applies:** the header is always deleted, on every response |
| + through `responseModifier`, whether or not a holder exists. ServeHTTP |
| + attaches the holder (`withPageMarkHolder`) at the LRU point for every |
| + cacheable or page-eligible request, before the activator or proxy |
| + runs. |
| + |
| +- [ ] **Step 1: Write failing tests** |
| + - `TestPageMarkStrippedOnUnarmedBox`: a `purgeEdge`-style edge with no |
| + page index, where the app sends `Carlos-Page-Cache: on`. The |
| + visitor's response has no such header. |
| + - `TestPageMarkParses`: table over `on`, `on; ignore-cookies="a,b"`, |
| + `On`, `off` and `on; x=1`. Expect `Marked` and `Ignore`, or `Bad`. |
| + - `TestMarkedResponseNeverEntersLRU`: a `cacheProbeEdge` whose app |
| + answers `Cache-Control: public, s-maxage=60` plus the marker, on a |
| + box with no page index. After a GET, `cachedAt` is `false`. |
| + - `TestUnmarkedResponseStillUsesLRU`: same without the marker → |
| + `cachedAt` is `true`, with TTL ≤ 5 minutes. |
| +- [ ] **Step 2: Run them to see them fail:** `TMPDIR=/tmp/g go test |
| + ./internal/edge -run 'PageMark|MarkedResponse|UnmarkedResponse' |
| + -count=1`. |
| +- [ ] **Step 3: Implement as above.** |
| +- [ ] **Step 4: Run them to see them pass.** |
| +- [ ] **Step 5: Commit:** `edge: read and strip Carlos-Page-Cache; marked |
| + responses skip the LRU`. |
| + |
| +### Task 6: Serving and storing pages on the home box |
| + |
| +**Files:** |
| +- Create: `internal/edge/pagecache.go` (state, enable, eligibility, |
| + lookup and serve). |
| +- Create: `internal/edge/pagerecord.go` (the recorder that tees into a |
| + `pageindex.Pending`). |
| +- Modify: `internal/edge/edge.go` at the LRU gate (:2673–2690) and the |
| + proxy calls (:2707–2729). |
| +- Test: `internal/edge/pagecache_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's API, Task 5's `pageMarkOf` and |
| + `withPageMarkHolder`, `serveAssetEntry` (`assetserve.go:37`), |
| + `parseMaxAge` (`edge.go:3110`), `canonicalAssetPath` |
| + (`assetcatch.go:47`), and `e.assets` local `For(host)` for declared |
| + prefixes. |
| +- Produces: |
| +```go |
| +func (e *Edge) EnablePageCache(x *pageindex.Index) |
| +func pageScopeOf(up upstream) pageindex.Scope // Account via release.RouteAccount(up.route), App, Instance = up.route.Host |
| +func (e *Edge) pageRouteEligible(up upstream, host, path string) bool |
| +func pageReadable(r *http.Request) (cookieNames []string, ok bool) |
| +func pageStorable(r *http.Request) bool |
| +func pageAdmit(status int, h http.Header, mark *pageMark) (lifetime time.Duration, ok bool) |
| +func (e *Edge) pagesOptedIn(up upstream) bool |
| +``` |
| +- **State:** `pages atomic.Pointer[pageState]` on `Edge`, holding |
| + `{idx *pageindex.Index}`. |
| + |
| +**At the LRU gate, when `pageRouteEligible` holds:** |
| +1. If `pagesOptedIn(up)`: the LRU is off for this request, so |
| + `cacheable = false`. This is the one place §5.3's rule is checked. |
| +2. If `pageReadable(r)`: `idx.Lookup`. A hit is served with |
| + `serveAssetEntry(w, r, entry, now, "hit")`, and the handler returns. |
| +3. If `pageStorable(r)`: `t := idx.Begin(scope)`, and wrap the writer in |
| + a `pageRecorder`. `withPageMarkHolder` is already attached. |
| +4. **`pageRecorder.WriteHeader`:** |
| + - reads the mark; |
| + - if `pageAdmit` passes and `Content-Length` (when present) is |
| + ≤ `MaxBody`, it reserves a `Pending` and tees; |
| + - sets `Carlos-Cache: miss` when the instance is opted in or the |
| + response is marked; |
| + - an admitted response skips the LRU (Task 5 already refuses marked |
| + ones). |
| +5. **After the proxy returns:** |
| + - a `Set-Cookie` trailer, an error, or an overflow means `Abort`; |
| + - otherwise `idx.MarkOptIn(scope)` (durable, before publishing), |
| + then `Finish(meta, Info{Ignore: mark.Ignore})`; |
| + - meta uses the stored-header filter `assetStoredHeader` |
| + (`assetadmit.go:201`), `Lifetime`, and `Expires = now + lifetime`. |
| +6. **Bypass:** requests that are eligible but neither readable nor |
| + storable get `Carlos-Cache: bypass` when the instance is opted in. |
| + |
| +- [ ] **Step 1: Write failing tests** (a scene like `newLAScene` with an |
| + armed asset store and a page index): |
| + - **The core path:** |
| + - `TestPageMissThenHitWithoutApp`: the app answers marked, with |
| + `s-maxage=31536000`. The first GET is `miss` and the app count is 1. |
| + The second GET is `hit`, the app count is still 1, and the bodies |
| + are equal. |
| + - `TestPageHitOnHibernatingRouteDoesNotWake`: on a hibernate route |
| + with `fakeActivator`, a hit never calls the activator. |
| + - **Responses that must not be stored:** |
| + - `TestPageRefusesSetCookie`, `TestPageRefusesVaryCookie`, |
| + `TestPageRefusesNon200`, `TestPageRefusesPrivate`: each is |
| + passed through and the next GET is a `miss`. |
| + - `TestPageRefusesAppGzip` (Review Focus 2): the app sends |
| + `Content-Encoding: gzip`. It is passed through byte-identical and |
| + never stored. |
| + - `TestPageOverflowStreamsAndStoresNothing` (Review Focus 3): the |
| + app streams 9 MiB with no `Content-Length`. The visitor gets |
| + 9 MiB, the next GET is a `miss`, and the store has no page keys. |
| + - **Requests that bypass:** |
| + - `TestPageCookieRequestNotStoredAnywhere` (Review Focus 4): a GET |
| + with `Cookie: sid=1` gets a marked answer. The next anonymous GET |
| + is a `miss`, and `s.lruLen()` is unchanged. |
| + - `TestPageIgnoredCookieHits`: an entry stored with |
| + `ignore-cookies="consent"` is hit by `Cookie: consent=1`, and |
| + `Cookie: consent=1; sid=2` gets `bypass`. |
| + - `TestPageAuthorizationBypasses`. |
| + - **Hit behaviour** (Review Focus 1): `TestPageHeadRangeConditional`. |
| + - HEAD on a stored page has the headers and an empty body; |
| + - `Range: bytes=0-1` bypasses and reaches the app; |
| + - `If-None-Match` with the stored ETag gets 304. |
| + - **Opt-in and the LRU:** `TestOptedInInstanceSkipsLRU`. Seed the LRU |
| + with an entry for the host (`seed`), then serve one marked page. |
| + The seeded URL now misses the LRU and reaches the app. |
| + - **Ineligible routes:** `TestPageIneligibleRoutes`, a table over HA, |
| + `Gate` set, `ImportGate` set, `PagesOff`, `Kind == "static"`, a |
| + forward row, and a path under a declared asset prefix. None is |
| + stored. |
| +- [ ] **Step 2: Run them to see them fail:** `TMPDIR=/tmp/g go test |
| + ./internal/edge -run 'TestPage|TestOptedIn' -count=1`. |
| +- [ ] **Step 3: Implement as above.** |
| +- [ ] **Step 4: Run them to see them pass,** then run `-run |
| + 'Cache|Asset|Purge'` to see neighbours still pass. |
| +- [ ] **Step 5: Commit:** `edge: home-box page cache at the LRU point`. |
| + |
| +### Task 7: Clears reach the index (header, socket and `all`) |
| + |
| +**Files:** |
| +- Modify: `internal/edge/purge_header.go` (`applyPurgeTargets` :606, the |
| + token loop :643–659). |
| +- Modify: `internal/edge/purge.go` (`ListenControl` :126, the handler |
| + :134–153). |
| +- Modify: `internal/edge/cache.go` (a bridge field set by the edge). |
| +- Test: `internal/edge/pageclear_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `pageindex.Clear` and `Target`, and Task 6's `pageScopeOf`. |
| +- Produces: |
| +```go |
| +type purgeBridge interface { |
| + clearPages(host string, c pageindex.Clear) // maps host to its scope, no-op when unarmed |
| + instanceHosts(host string) []string // the primary and every alias in e.current() |
| +} |
| +func (c *Cache) setBridge(b purgeBridge) // set in EnableCache; the socket handler reads it |
| +``` |
| + |
| +**Header channel.** `applyPurgeTargets` keeps its LRU calls exactly as |
| +today, then: |
| +- for each host, calls `clearPages(host, ...)` with the same targets; |
| +- `*` → `TargetHost`; |
| +- a path → `TargetPath`; |
| +- `path?query` → `TargetURL`; |
| +- the over-limit fallback → `TargetHost`. |
| + |
| +**The new token `all`:** |
| +- it is accepted before `validPurgeTarget`; |
| +- for the LRU, it purges `PurgeHost` on every `instanceHosts(host)`; |
| +- for pages, it sends one `clearPages(host, Clear{})`. |
| + |
| +**Socket channel.** `{"path":"all"}` does the same. The other socket |
| +paths also call `clearPages` after their LRU purge. An activator spawn |
| +still calls only `Cache.PurgeHost`, so a wake never clears pages (spec |
| +§8.6). |
| + |
| +- [ ] **Step 1: Write failing tests** |
| + - `TestPurgeHeaderClearsPage`: store `/post`, then a POST whose |
| + response carries `Carlos-Purge: /post`. The next GET of `/post` is |
| + a `miss`. |
| + - `TestPurgeHeaderOnStoredResponseOrder`: a marked GET response that |
| + itself carries `Carlos-Purge: /post` is applied before that |
| + response is considered (it stays stored if it is `/post`'s own |
| + fresh render). |
| + - `TestPurgeAllClearsAliases` (Review Focus 5): store pages on the |
| + primary and an alias (`upsertAlias`). `Carlos-Purge: all` misses |
| + both, and `Carlos-Purge: *` sent for the alias host misses only the |
| + alias. |
| + - `TestControlSocketClearsPageAndAll`: `dialPurgeSocket`. `{"path": |
| + "/post"}` clears `/post`, and `{"path":"all"}` clears every host. |
| + - `TestSpawnPurgeKeepsPages`: `Cache.PurgeHost(host)` (what an |
| + activator spawn does) leaves the page hit. |
| +- [ ] **Step 2: Run them to see them fail:** `TMPDIR=/tmp/g go test |
| + ./internal/edge -run 'TestPurge.*Page|PurgeAll|ControlSocketClears|SpawnPurgeKeeps' |
| + -count=1`. |
| +- [ ] **Step 3: Implement as above.** |
| +- [ ] **Step 4: Run them to see them pass,** plus `-run 'Purge'` for the |
| + existing purge suite. |
| +- [ ] **Step 5: Commit:** `edge: Carlos-Purge and the control socket |
| + clear pages; add the all target`. |
| + |
| +### Task 8: Authority changes reset or clear the scope |
| + |
| +**Files:** |
| +- Modify: `internal/edge/pagecache.go`: a reload hook registered in |
| + `EnablePageCache` through `OnReload` (`edge.go:1479`). |
| +- Create: |
| + `func (e *Edge) ClearInstancePages(host string, reason string)`. It is |
| + exported for the host wiring in Task 9. |
| +- Test: `internal/edge/pagecache_reload_test.go`. |
| + |
| +**Behaviour.** The hook compares the scopes in `idx.Scopes()` with |
| +`e.current()`: |
| +- **The instance's route is gone, ineligible, or `PagesOff`:** |
| + `Reset(scope)` and `ClearOptIn(scope)`. Ineligible means HA, forward, |
| + a gate, an import gate, a sidecar, or a status that isn't ready. |
| +- **`route.Version` differs from the version last seen for that |
| + scope:** `Clear(scope, Clear{})`. That is spec §8.6, a new release. |
| +- **Versions seen** are kept in the hook's own map, seeded on the first |
| + run without clearing. |
| + |
| +`ClearInstancePages` resolves the host's scope and sends `Clear{}`. |
| + |
| +- [ ] **Step 1: Write failing tests** |
| + - `TestRouteDepartureResetsScope`: store a page, delete the route, |
| + `Reload`. `OptedIn` is `false` and the store has no page keys. |
| + - `TestNewVersionClearsPages`: store, set `Version` on the route, |
| + `Reload`. Miss. |
| + - `TestSameVersionReloadKeepsPages`: an unrelated route change, then |
| + `Reload`. Hit. |
| + - `TestPagesOffResets` and `TestGateAddedResets`: Reload after setting |
| + each. Miss, and not opted in. |
| + - `TestClearInstancePages`: miss after the call. |
| +- [ ] **Step 2: Run them to see them fail:** `TMPDIR=/tmp/g go test |
| + ./internal/edge -run 'TestRouteDeparture|Version.*Pages|PagesOffResets|GateAddedResets|ClearInstancePages' |
| + -count=1`. |
| +- [ ] **Step 3: Implement as above.** |
| +- [ ] **Step 4: Run them to see them pass.** |
| +- [ ] **Step 5: Commit:** `edge: route departure, switch and release |
| + reset or clear an instance's pages`. |
| + |
| +### Task 9: Arming on the host, and config delivery clears |
| + |
| +**Files:** |
| +- Create: `internal/host/pagearm.go`. |
| +- Modify: `internal/host/agent.go`: |
| + - :1290: after `armEdgeAssetCache`, call `armEdgePageCache` with the |
| + returned store; |
| + - the config sync loop (:1796–1875): after a host's config file is |
| + written, call `e.ClearInstancePages(host, "config")`. |
| +- Test: `internal/host/pagearm_test.go`, `internal/host/agent_test.go` |
| + (focused). |
| + |
| +**Interfaces:** |
| +- Consumes: `pageindex.Open` and `edge.(*Edge).EnablePageCache`. |
| +- Produces: |
| +```go |
| +const pageCacheDirName = "page-cache" // marks; bytes stay in asset-cache |
| +func pageCacheArmed(getenv func(string) string) bool // CARLOS_PAGE_CACHE == "1" |
| +func armEdgePageCache(getenv func(string) string, dataDir string, store *assetcache.Store, enable func(*pageindex.Index)) *pageindex.Index |
| +``` |
| +- **When it arms:** it returns nil without enabling when the variable |
| + isn't `"1"` or `store == nil`. With the variable set but no store, it |
| + logs one line ("page cache needs the asset cache"). |
| + |
| +**Config delivery:** |
| +- **Which signal:** read `appconfig.WithHostOutcome` and |
| + `Callbacks.Delivered` (`internal/appconfig/claimsync.go:58`). Hook the |
| + one that fires exactly when a host's config file content changed, |
| + on both the exec path and the rollout path (`rolloutConfigCallbacks`). |
| + Record which one in the commit message. |
| +- **Expected:** a pass that changes nothing must not clear. |
| + |
| +- [ ] **Step 1: Write failing tests** |
| + - `TestArmPageCacheNeedsFlagAndStore`: the table `{unset, store}` → |
| + nil; `{"1", nil}` → nil plus the log line; `{"1", store}` → enabled |
| + once. |
| + - `TestConfigChangeClearsPagesNoChangeKeeps`: a focused agent test |
| + with a fake edge recorder. Changing an instance's config produces |
| + one `ClearInstancePages(host, "config")`; a second identical pass |
| + produces none. |
| +- [ ] **Step 2: Run them to see them fail:** `TMPDIR=/tmp/g go test |
| + ./internal/host -run 'ArmPageCache|ConfigChangeClearsPages' -count=1`. |
| +- [ ] **Step 3: Implement as above.** |
| +- [ ] **Step 4: Run them to see them pass.** |
| +- [ ] **Step 5: Commit:** `host: arm the page cache with |
| + CARLOS_PAGE_CACHE; config changes clear pages`. |
| + |
| +### Task 10: The copy deck, reviewed before any string is written |
| + |
| +**Files:** |
| +- Create: `docs/superpowers/plans/2026-11-08-edge-page-cache-copy.md`. |
| + Rows `EPC-1..n`, in the asset deck's format: id | file | text | |
| + status. |
| +- Create: `docs/superpowers/plans/2026-11-08-edge-page-cache-copy-approved.json` |
| + (written by the review). |
| + |
| +**Rows to draft** (wording is the reviewer's; these are the slots): |
| +- **Console:** |
| + - the PATCH `pages` validation message, on the model of |
| + `apiAssetsOnOff`; |
| + - the "nothing to update" key list, with `pages` added. |
| +- **CLI:** |
| + - `carlos instances set-pages` usage; |
| + - two result lines (on and off), on the model of `printSetAssets`; |
| + - the "console predates" line. |
| +- **Help:** the help lines in `instances_cli.go:230` and `main.go:301`. |
| +- **Docs:** `docs/site/cli.md`: |
| + - a "Caching pages at the edge" section placed after the `carlos |
| + ship` asset paragraph (:285–289). It covers the marker, |
| + lifetimes, the `max-age=0` advice, ignorable cookies, what is never |
| + cached, `Carlos-Cache`, the clear targets including `all`, release |
| + and config clears, and the fact that asset paths win; |
| + - a `### carlos instances set-pages` section; |
| + - the `CARLOS_PURGE` row (:1186), with `all` added; |
| + - `docs/site/rootfs.md:46` if its wording changes. |
| +- **The arming log line** from Task 9 is an operator log line, outside |
| + copy review (Paul's rule: human text only). |
| + |
| +- [ ] **Step 1: Draft the deck,** one row per string, `pending`. |
| +- [ ] **Step 2: Run the `copy-review` skill** on the deck. Wait for |
| + Paul's edits and apply them verbatim. Write the approved JSON. |
| +- [ ] **Step 3: Commit:** `docs: page cache copy deck, approved`. |
| + |
| +### Task 11: The switch door, the CLI, the docs and the copy gate |
| + |
| +**Files:** |
| +- Modify: `internal/console/apiinstances.go`: |
| + - request field `Pages *string \`json:"pages"\`` beside `Assets` |
| + (:2949); |
| + - the nothing-to-update check and message (:2965–2967); |
| + - `pagesSwitch` (:2991); |
| + - `rec.Pages = pages` (:3096); |
| + - audit `"pages"` (:3241). |
| +- Modify: `internal/console/apiassets.go`, or create |
| + `internal/console/apipages.go`, with |
| + `func pagesSwitch(w http.ResponseWriter, v *string) (*bool, bool)` and |
| + the approved message constant. |
| +- Create: `instances_pages.go` (repo root): |
| + - `instancesSetPagesUsage`; |
| + - `func runInstancesSetPages(args []string)`; |
| + - `func printSetPages(w io.Writer, host string, on bool)`. |
| +- Modify: `apimode.go` (`func (s *apiSession) instanceSetPages(ctx, |
| + a apiAcct, app, host string, on bool, messages ...string) |
| + (apiInstanceRecord, error)` beside :5694), `cli.go:615` (case |
| + `"set-pages"`), and the help lines. |
| +- Modify: `docs/site/cli.md`, `docs/site/rootfs.md` as approved. |
| +- Create: `approved_page_cache_copy_test.go` (repo root), on the model |
| + of `approved_asset_cache_copy_test.go`, with `pageCacheCopyBuilt` |
| + listing every built EPC id. |
| +- Test: `internal/console/apiinstances_test.go` (focused), plus a CLI |
| + test beside the `set-assets` tests. |
| + |
| +- [ ] **Step 1: Write failing tests** |
| + - `TestPatchInstancePagesOffAndOn`: the PATCH `{"pages":"off"}` sets |
| + `Record.Pages` to `&false` and is audited. `"on"` sets nil, and |
| + `"maybe"` is a 400 with the approved message. |
| + - `TestSetPagesCLI`: against a fake console, it prints the approved |
| + on and off lines. |
| + - The docs gate (`internal/docsite`) passes with the new heading. |
| + - `TestApprovedPageCacheCopy` fails until each EPC string matches. |
| +- [ ] **Step 2: Run them to see them fail:** `go test |
| + ./internal/console -run 'PatchInstancePages' -count=1`, `go test . |
| + -run 'SetPagesCLI|ApprovedPageCacheCopy' -count=1`, and `go test |
| + ./internal/docsite -count=1`. |
| +- [ ] **Step 3: Implement,** mirroring `assets` at every site listed. |
| +- [ ] **Step 4: Run them to see them pass.** |
| +- [ ] **Step 5: Commit:** `console, cli: carlos instances set-pages; |
| + page cache docs`. |
| + |
| +### Task 12: The whole branch |
| + |
| +- [ ] **Step 1:** `go build ./...`, `go vet ./...`, and `gofmt -l .`, |
| + which must print nothing. `GOOS=darwin go build ./...` and |
| + `GOOS=windows go build ./...` (the cross-compile gate). |
| +- [ ] **Step 2: The census.** Follow AGENTS.md § The census for every |
| + in-scope change: the edge request path, `internal/pageindex` and the |
| + registry column. |
| +- [ ] **Step 3: Push** `edge-page-cache-1`. Then `amadan branch describe |
| + carlos/platform edge-page-cache-1 -body -`, covering what changes, |
| + the spec link and the tests. Wait for CI to go green on the tip. |
| +- [ ] **Step 4: One whole-branch review** by a reviewer from another |
| + model family, under the stopping rules. Fix P2s without reopening |
| + it. |
| +- [ ] **Step 5: Paul's go, then the merge:** `amadan branch merge |
| + carlos/platform edge-page-cache-1 -squash -expect <full sha> |
| + -message ...`. |
| + |
| +**After the merge (not part of this plan; each step needs Paul's go):** |
| +- release, then roll to dev; |
| +- set `CARLOS_PAGE_CACHE=1` on a dev box that already has the asset |
| + cache; |
| +- Patrix sends the marker on its public pages and `Carlos-Purge` on |
| + publish, edit and comment approval; |
| +- check a repeat view is `Carlos-Cache: hit` with no wake, and a |
| + publish clears the homepage. |