carlos / platform Public

plan: edge page cache slice 1 rev 2 after Astra plan round 1

Round 1 findings unedited. Unique physical keys per publish, serving
identity at process start replaces the release and config hooks, the
mark survives temporary ineligibility, marker stripped from 1xx and
trailers, path-routed hosts refused, failed hits fall through.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c006cd41ed172977b4edafda271dadda38eff299 parent 90da7cd
3 files changed, +774 −463
  • docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md +557 −463
  • docs/superpowers/plans/CODEX-FINDINGS-PAGE-CACHE-PLAN1-R1.md +125 −0
  • docs/superpowers/plans/CODEX-REVIEW-BRIEF-PAGE-CACHE-PLAN1-R2.md +92 −0
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
index 1a9eae245..157dad7e0 100644
--- 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
@@ -2,42 +2,63 @@
> **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.
+Plan rev 2, after Astra plan round 1
+(`CODEX-FINDINGS-PAGE-CACHE-PLAN1-R1.md`). Marks like **(P1-3)** point
+at the finding a passage answers.
+
**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.
+until the app clears it or the process answering for the instance
+changes build or config.
**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:`.
+ only code that publishes, clears, resets or looks up a page.
+ - **Bytes** live in the existing `internal/assetcache` store. Each
+ attempt to publish gets its own physical key, whose `Gen` begins
+ `page:`.
+ - **The index** maps each logical page to the one physical object it
+ published.
- **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.
-- **No single-flight in this slice.** The spec's Join (§6.1) arrives
- with far fills in slice 2, so concurrent misses each render, as they
- do today.
+- **Every page carries its serving identity:** the build and config the
+ answering process was started with, recorded at the activator's
+ existing spawn points. A hit needs the current identity, so a new
+ release or config invalidates without a separate clear, while a wake
+ of the same build and config keeps the pages **(P1-3, P1-4)**.
+- **Not in this slice:**
+ - far boxes, leases and pushes;
+ - single-flight: the spec's Join (§6.1) arrives with far fills in
+ slice 2, so concurrent misses each render, as they do today.
**Tech Stack:** Go stdlib; existing `internal/assetcache`,
-`internal/edge`, `internal/registry`, `internal/provision`,
-`internal/console`, CLI in the repo root.
+`internal/edge`, `internal/activator`, `internal/registry`,
+`internal/provision`, `internal/console`, `internal/host`, 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.
+(rev 4, approved).
+- **Coverage:** slice 1 is §11 item 1. The sections it builds are §4,
+ §5, §6, §8.1 (home side), §8.6 and §10.
+- **One change of mechanism:** §8.6's "clear on a new release or config"
+ is implemented as serving-identity tagging. Entries from an earlier
+ identity become unreachable at the moment the new process answers,
+ which is the same guarantee without a hook that could fire early or
+ late. Plan round 1 showed both hooks did.
**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.
+`design-edge-page-cache` (spec and this plan) has merged (stopping rule
+4).
## 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.
+ optional `; ignore-cookies="a,b"` parameter.
+- The edge strips it from every final response, every 1xx response and
+ every trailer, on every box, armed or not **(P1-7)**.
- Lifetime is `s-maxage`, else `max-age`. It must be positive and is
capped at 365 days. `private`, `no-store` and `no-cache` refuse.
@@ -58,60 +79,76 @@ rule 4 forbids building against an unmerged design.
- **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.
+**Eligible requests** (`pageRouteEligible`):
+- **The route:** `Kind == "instance"`, not `IsForward()`, not `HA`, not
+ `IsSidecar()`, `Status == "ready"`, `Gate == ""`, `ImportGate == ""`,
+ `!PagesOff`.
+- **No path rows (P1-6):** neither the requested hostname's own entry in
+ `e.current()` nor its primary has path rows. The request was not
+ dispatched by path to another instance.
+- **Asset prefixes:** the path is not under a prefix the serving build
+ declares, and the declaration is known **(P2-9)**.
+- **Identity:** the instance has a known serving identity.
**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.
+- A **logical key** is (host, path, raw query) exactly as sent.
-**Clears and switches:**
+**Clears:**
- 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.
+
+**The opt-in mark (P1-5):** it is cleared only by the operator switch
+(`PagesOff`) or the route leaving the box. Any other ineligibility
+resets page contents but keeps the mark, so the LRU stays off.
+
+**Arming and visibility:**
- **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.
+ as absent (still stripped; a marked response still never enters the
+ LRU).
+- **`Carlos-Cache: hit|miss|bypass`** goes on every response of an
+ opted-in instance, and on every marked response, whether or not a body
+ was recorded **(P2-10)**:
+ - `hit`: served from the index;
+ - `miss`: the request was storable and the response was considered;
+ - `bypass`: everything else.
**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
+ the `copy-review` skill before it is written into code (Task 11). 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.
+ '<Name>' -count=1`. CI runs the full suite.
+- **Socket packages** (`edge`, `activator`, `host`) need a short temp
+ path. Use task-owned disk scratch, never `/tmp` **(P2-12)**:
+ `export TMPDIR=$(mktemp -d "$HOME/.cache/epc.XXXX")` before the run and
+ `rm -rf "$TMPDIR"` after. Leave `GOCACHE` at its default.
- **Commits:** subjects under 80 characters, prefixed by package
- (`pageindex:`, `edge:`, `registry:`, `console:`, `cli:`, `docs:`,
- `host:`).
+ (`pageindex:`, `assetcache:`, `edge:`, `activator:`, `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.
+ `If-None-Match` gets 304. Tests go in Task 7.
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.
+ twice. Test in Task 7.
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.
+ stored. Test in Task 7.
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.
+ Task 7.
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.
+ every alias. Test in Task 8.
---
@@ -119,7 +156,7 @@ rule 4 forbids building against an unmerged design.
**Files:**
- Modify: `internal/assetcache/store.go` (add `Delete`). Modify:
- `internal/assetcache/key.go` (add `PageGenPrefix`).
+ `internal/assetcache/key.go` (add `PageGenPrefix` and `IsPageKey`).
- Modify: `internal/edge/assetarm.go:81` (`sweepAssets` keeps page
keys).
- Test: `internal/assetcache/store_test.go`,
@@ -128,45 +165,43 @@ rule 4 forbids building against an unmerged design.
**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)`.
+ - `func IsPageKey(k Key) bool`;
+ - `func (s *Store) Delete(k Key) bool`.
- [ ] **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
+ - `TestDeleteDropsEntryAndFiles`: Commit an entry, then `Delete` →
+ `true`. `Get` misses, and no `<id>.*` files remain. A second
+ `Delete` → `false`.
+ - `TestDeleteConcurrentWithGet`: 4 goroutines alternating `Get` and
+ `Delete` on 20 keys finish within 5 s under `-race`. That is the
+ deadlock guard.
+ - `TestSweepAssetsKeepsPageKeys`: in a `newLAScene` store, commit one
+ asset key and one key with `Gen: "page:x:1:a"`, with both
+ authorities ready and naming neither. `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 2: Run them to see them 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
+ - **`Delete` (P1-2):** under `s.mu`, look up the entry pointer and
+ release `s.mu`. Then call `s.drop(e)`, which takes `lockID` itself
+ and keeps its identity check.
+ - **`sweepAssets`'s keep predicate** returns `true` first when
`assetcache.IsPageKey(k)`.
-- [ ] **Step 4: Run both to see them pass.**
+- [ ] **Step 4: Run them to see them pass** (`-race`).
- [ ] **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/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`.
+ `Get`, `Delete`, `Retain`), `PageGenPrefix` and `IsPageKey`.
- Produces:
```go
type Scope struct{ Account, App, Instance string }
@@ -177,53 +212,65 @@ 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 Ticket struct{ Scope Scope; Epoch, Seq uint64; Identity string }
+type Info struct{ ValidAt uint64; Ignore []string; Identity string }
+type Miss int // MissNone (a hit), MissAbsent, MissCookies, MissIdentity
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
+ Store *assetcache.Store
+ MarkDir string
+ Now func() time.Time
+ LogMax int // 0 means 256
+ LogAge time.Duration // 0 means 10 * time.Minute
+ afterCommit func() // test seam: runs between Commit and the scope lock
}
const MaxBody = 8 << 20
func Open(cfg Config) (*Index, error)
-func (x *Index) Begin(s Scope) Ticket
+func (x *Index) Begin(s Scope, identity string) 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 (p *Pending) Finish(m assetcache.Meta, ignore []string) (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) Lookup(s Scope, k Key, identity string, cookieNames []string) (*assetcache.Entry, Miss)
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
+func (x *Index) Scopes() []Scope
```
**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}`.
+ step of Finish run under it.
+- **Physical keys are unique per attempt (P1-1).** `Reserve` draws a
+ random 64-bit attempt id. The store key is `assetcache.Key{Account,
+ App, Gen: PageGenPrefix + Instance + ":" + hex(Epoch) + ":" +
+ hex(attempt), Host, Path, RawQuery}`, so no two attempts share a
+ store object.
+- **The index map** goes from a logical `Key` to the record {physical
+ key, `Info`} under the scope.
- **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:
+ - commits its own physical object first, outside the scope lock,
+ with `gzipCopy=true`;
+ - then calls `afterCommit` (when set) and takes the lock;
+ - 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.
+ - no clear in that range matches the logical key;
+ - **if it indexes:** it replaces the logical key's record. The
+ previous physical object is deleted after the lock is released.
+ `Info.ValidAt` is set to the current sequence, and `Info.Identity`
+ to `t.Identity`;
+ - **if it doesn't:** it deletes only its own physical object and
+ returns `false`.
- **`Clear`:**
- - increments the sequence and appends to the log (trimmed to
- `LogMax` entries and `LogAge`);
- - drops the matching indexed entries with `Store.Delete`;
+ - increments the sequence and appends to the log (trimmed to `LogMax`
+ and `LogAge`);
+ - removes the matching records and deletes their physical objects
+ after the lock is released;
- returns the new sequence.
- **Matching:**
- `TargetHost` matches every key on the host;
@@ -231,14 +278,17 @@ func (x *Index) Scopes() []Scope // scopes with entries, a mark, or a live epoch
- `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`.
+- **`Lookup`:**
+ - finds the logical key's record under the current epoch;
+ - requires `record.Identity == identity`, otherwise returns
+ `MissIdentity`;
+ - requires every cookie name to be in `Ignore`, otherwise
+ `MissCookies`;
+ - then calls `Store.Get(physical key)`. A miss there (evicted or
+ expired) removes the record and returns `MissAbsent`.
- **`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.
+ !assetcache.IsPageKey(k) })` once, because an earlier process's
+ 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`;
@@ -246,94 +296,116 @@ func (x *Index) Scopes() []Scope // scopes with entries, a mark, or a live epoch
- `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 1: Write failing tests** (a temp-dir store):
+ - **Publish and look up:**
+ - `TestPublishThenLookup`: a hit with the same identity, and its
+ body reads back.
+ - `TestLookupNeedsIdentity`: publish under identity `b1`, then
+ Lookup with `b2` → `MissIdentity`.
+ - **Clears:**
+ - `TestClearRemovesMatching`: `/a`, `/a?x=1` and `/b` with path and
+ URL targets, as in rev 1.
+ - `TestClearBetweenBeginAndFinishFences`: the Finish → `false`,
+ Lookup misses, and the store holds no page object for the key.
+ - `TestUnrelatedClearDoesNotFence`.
+ - `TestLogGapRefuses`: with `LogMax: 2`.
+ - **The overwrite race (P1-1):**
+ `TestStaleCommitCannotReplaceFreshPage`:
+ - render A begins, then a Clear of the key lands;
+ - render B begins after the clear, and its Finish → `true`;
+ - A's Finish runs with `afterCommit` blocking on a channel. While
+ A is paused, Lookup returns B's bytes;
+ - release A. A's Finish → `false`, Lookup still returns B's bytes,
+ and B's physical object still exists.
+ - **Replacement:** `TestRepublishDeletesPreviousObject`. Two
+ successful publishes of the same key leave exactly one page object
+ in the store.
+ - **Reset and the store:**
+ - `TestResetDropsAndChangesEpoch`.
+ - `TestIgnoreCookies`: `MissCookies` for an unlisted cookie.
+ - `TestEvictedObjectIsMissAbsent`: `Store.Delete` the physical key
+ behind the index's back, then Lookup → `MissAbsent`, and the
+ record is gone.
+ - `TestOpenDropsEarlierPages`.
+ - **Marks and size:**
+ - `TestOptInMarkSurvivesOpen`.
+ - `TestTooLargeAborts`.
- [ ] **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 4: Run them to see them pass** (`-race`).
- [ ] **Step 5: Commit:** `pageindex: one index owns every page publish,
clear, reset and lookup`.
-### Task 3: The index under a randomized simulation
+### Task 3: The index under simulation, and its guard
**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.
+- Test: `internal/pageindex/sim_test.go`,
+ `internal/pageindex/guard_test.go`.
+
+**Interfaces:** Task 2's API only.
+
+- [ ] **Step 1: Write `TestSimulationInvariants` (P2-11).**
+ - **The setup:** 8 goroutines run 2000 random operations (300 under
+ `-short`) over 3 scopes. The scopes differ in account, app or
+ instance, with 2 hosts each, overlapping host names across scopes,
+ 6 paths and 2 identities.
+ - **The operations:** Begin + Reserve + Write + Finish, where
+ `afterCommit` randomly yields or sleeps 0–2 ms; Clear with random
+ targets; Reset; Lookup; MarkOptIn and ClearOptIn.
+ - **Every body is unique** and encodes (scope, host, path, query,
+ identity, ticket epoch, ticket seq).
+ - **Ordering model:** each Clear records (scope, epoch, seq, clear) in
+ a mutex-guarded model log when it returns. A Lookup snapshots the
+ model log before it calls the index, and checks against that
+ snapshot only.
+ - **At every hit, assert:**
+ - **I1:** no clear in the snapshot on the same scope and epoch, with
+ seq > the body's ticket seq, matches its key;
+ - **I3:** the body's scope, host, path and query equal the Lookup's
+ arguments;
+ - the identity equals the Lookup's identity.
+ - **Seeding:** the seed comes from `-seed` (default the time), and is
+ printed on failure.
- [ ] **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
+ simulation and a final Reset of every scope, the store holds zero page
+ keys.
+- [ ] **Step 3: Write `TestOnlyPageindexBuildsPageKeys`.**
+ - It walks the repo's `.go` files (from `runtime.Caller`, up to the
+ module root).
+ - It fails if any file outside `internal/pageindex/` and
+ `internal/assetcache/` mentions `PageGenPrefix` or the literal
+ `"page:"`.
+ - Test files are excluded, except this guard's own fixtures.
+- [ ] **Step 4: 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`.
+ - skip the fence check → the simulation fails;
+ - drop the attempt id from the physical key → the simulation or
+ Task 2's race test fails;
+ - skip deleting the refused object → the store test fails;
+ - add `"page:"` to a scratch file in `internal/edge` → the guard
+ fails.
+- [ ] **Step 5: Run:** `go test ./internal/pageindex -count=3 -race`
+ passes.
+- [ ] **Step 6: Commit:** `pageindex: randomized invariants and the
+ page-key guard`.
### 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).
+**Files and sites:** every place that carries `AssetsOff` or `Assets`:
+- `internal/provision/provision.go`: `Pages *bool` beside `Assets`
+ (:217), and `PagesOn()` beside `AssetsOn` (:569);
+- `internal/provision/reconcile.go`: `RouteFor` (:586), and
+ `convergeOwned` (:1005–1016) calling `reg.SetPages`;
+- `internal/registry/registry.go`:
+ - the field (:120) and column `pages_off` (:747);
+ - read and scan (:1111–1138), upsert keep (:1620), insert (:1708);
+ - `SetPages(host string, off bool) error` beside `SetAssets` (:2520,
+ `kind <> 'forward'`);
+ - Fingerprint `"\x1fpages_off=1"` (:4060) and SnapshotFingerprint
+ (:4407);
+- `internal/registry/remote_dispatch.go` (:72, :320);
+- `internal/registry/forward.go` (:115, :154, :214).
- Test: `internal/registry/registry_test.go`,
`internal/provision/reconcile_test.go`.
@@ -343,431 +415,453 @@ func (x *Index) Scopes() []Scope // scopes with entries, a mark, or a live epoch
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.
+ - `TestSetPagesRoundTripsAndMovesFingerprint`.
+ - `TestConvergeAppliesPagesSwitch`.
+ - `TestForwardRowRefusesPagesOff`.
- [ ] **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`.
+ ./internal/registry ./internal/provision -run Pages -count=1`.
+- [ ] **Step 3: Implement,** mirroring every site above.
+- [ ] **Step 4: Run them to see them pass,** plus `-run
+ 'Fingerprint|Forward'` in `internal/registry`.
- [ ] **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
+### Task 5: The marker is read once, stripped everywhere, 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`.
+- Modify:
+ - `internal/edge/assetcatch.go:966`: add `pageCacheHeader` to
+ `assetVocabulary`, so `stripAssetResponseHeaders`,
+ `stripAssetTrailers` and `assetInformationalScrub` all remove it;
+ - `internal/edge/cookiescope.go:85`: in `responseModifier`, call
+ `takePageMark(resp)` before `stripAssetResponseHeaders`;
+ - `internal/edge/edge.go`:
+ - wrap the local proxy and activator calls (:2707–2730) in
+ `assetInformationalScrub{w}`, as `edge.go:4285` already does for
+ hops, so a local route's 1xx is scrubbed too;
+ - `maybeStore` (:2907) refuses when `pageMarkOf(rec.request)` is
+ `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
+func withPageMarkHolder(r *http.Request) *http.Request
+func pageMarkOf(r *http.Request) *pageMark // nil when no holder
+func takePageMark(resp *http.Response) // parses the final response's header into the holder; never reads trailers or 1xx
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.
+ - anything else sets `Bad`.
+- **Where the holder goes:** ServeHTTP attaches it at the LRU point for
+ every GET and HEAD it may cache or page-cache, 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`.
+ - `TestPageMarkStrippedFinalHeader`: on an edge with no page index,
+ the app sends the marker, and the visitor's response lacks it.
+ - `TestPageMarkStripped103`: the app writes a `103` carrying the
+ marker, then a 200. The client's informational response lacks it
+ (use `httptrace.ClientTrace.Got1xxResponse`).
+ - `TestPageMarkStrippedTrailers`: the app announces `Trailer:
+ Carlos-Page-Cache` and sets it, and separately sets an unannounced
+ trailer of that name. The client sees neither, and neither marks
+ the page.
+ - `TestPageMarkParses`: a table of values.
+ - `TestMarkedResponseNeverEntersLRU`.
+ - `TestUnmarkedResponseStillUsesLRU`.
+- [ ] **Step 2: Run them to see them fail.**
- [ ] **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`.
+- [ ] **Step 4: Run them to see them pass,** plus `-run
+ 'Asset.*Scrub|Vocabulary|Trailer'` for the neighbours.
+- [ ] **Step 5: Commit:** `edge: read and strip Carlos-Page-Cache
+ everywhere; marked responses skip the LRU`.
-### Task 6: Serving and storing pages on the home box
+### Task 6: The serving identity, recorded where processes start
**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
+- Modify: `internal/edge/cache.go`: add the identity table, beside the
+ existing indexes.
+- Modify: every activator site that calls `b.Cache.PurgeHost` on a
+ process start:
+ - `internal/activator/backend_exec.go:2298, :2573, :2852`;
+ - `internal/activator/rootfs.go:427`;
+ - `internal/activator/genbackend.go:362` (GenSwitched).
+ Each also calls `b.Cache.NoteServing(rt.Host, identity)`.
+- Create: `internal/activator/servingidentity.go`.
+- Test: `internal/activator/servingidentity_test.go`,
+ `internal/edge/cache_test.go`.
+
+**Interfaces:**
+- Produces:
+```go
+func (c *Cache) NoteServing(host, identity string)
+func (c *Cache) ServingIdentity(host string) (string, bool) // false until a start was noted in this agent process
+func servingIdentity(build string, configFiles []string) (string, error) // hex sha256 over the build and each config file's path and bytes, in a stable order
+```
+
+**What goes into the identity:**
+- **The build:** the build that process was started from. At
+ GenSwitched it is the generation's build; at the other sites, the
+ build the spawn launches.
+- **The config files:** every config file the activator hands that
+ process, read at the start.
+
+**Rules:**
+- **Unreadable config:** `NoteServing(host, "")`. An empty identity
+ means "unknown", and pages bypass for that instance.
+- **Wakes:** a wake of the same build and config computes the same
+ identity.
+- **Other starts:** a site that starts a process but doesn't call
+ `PurgeHost` today gets no identity, so its pages bypass. Name any such
+ site in the commit message.
+
+- [ ] **Step 1: Write failing tests**
+ - `TestServingIdentityStableAcrossWake`: the same build and files give
+ the same identity.
+ - `TestServingIdentityChangesWithBuildOrConfig`: each change gives a
+ different identity.
+ - `TestUnreadableConfigGivesEmpty`.
+ - `TestCacheNoteServing`: round-trip, and an unknown host → `false`.
+ - **A focused activator test per start site, through the real
+ backend:**
+ - `TestExecSpawnNotesIdentity`;
+ - `TestGenSwitchNotesNewIdentity`: a staged successor doesn't change
+ the identity until the switch.
+- [ ] **Step 2: Run them to see them fail:** `go test
+ ./internal/activator -run 'ServingIdentity|SpawnNotesIdentity|GenSwitchNotes'
+ -count=1` (with the task-owned `TMPDIR`).
+- [ ] **Step 3: Implement as above.**
+- [ ] **Step 4: Run them to see them pass,** plus `-run 'Purge|Gen'` in
+ `internal/activator`.
+- [ ] **Step 5: Commit:** `activator: record each instance's serving
+ identity at process start`.
+
+### Task 7: Serving and storing pages on the home box
+
+**Files:**
+- Create: `internal/edge/pagecache.go`, `internal/edge/pagerecord.go`.
+- Modify: `internal/edge/edge.go`, at the LRU gate (:2673–2690) and the
proxy calls (:2707–2729).
-- Test: `internal/edge/pagecache_test.go`.
+- Modify: `internal/host/assetpolicy.go`: add `DeclaresPrefix`
+ **(P2-9)**.
+- Modify: `internal/edge/assettypes.go`: an optional interface for it.
+- Test: `internal/edge/pagecache_test.go`,
+ `internal/host/assetpolicy_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.
+- Consumes:
+ - Tasks 2, 5 and 6;
+ - `serveAssetEntry` (`assetserve.go:37`), `parseMaxAge`
+ (`edge.go:3110`), `canonicalAssetPath` (`assetcatch.go:47`);
+ - `lookupUpstreamPath` (`edge.go:1761`).
- 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 (e *Edge) pageRouteEligible(host, path string, up upstream) (identity string, ok 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
+// host side, read through an optional edge interface:
+type assetDeclarations interface{ DeclaresPrefix(host, build, path string) (declared, known bool) }
+func (p *assetPolicy) DeclaresPrefix(host, build, path string) (declared, known bool)
```
-- **State:** `pages atomic.Pointer[pageState]` on `Edge`, holding
- `{idx *pageindex.Index}`.
+
+**Two details:**
+- **`DeclaresPrefix`** reads the release manifest through
+ `p.manifests.paths`, whatever `AssetsOff`, the asset generation or the
+ catch snapshot say. When the manifest hasn't been read, it returns
+ `known=false`, and the page cache bypasses.
+- **`pageRouteEligible`** checks the requested hostname's own
+ `e.current()[host]` entry for path rows, not only the dispatched
+ upstream. It also refuses when that entry's `route.Host` differs from
+ the dispatched `up.route.Host` (a path dispatch) **(P1-6)**.
**At the LRU gate:**
-1. **Whenever `pagesOptedIn(up)` holds,** whatever the path and whether
- or not `pageRouteEligible` holds, the LRU is off for this request:
- `cacheable = false`. This is the one place §5.3's rule is checked.
- The steps below run only when `pageRouteEligible` holds.
-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):
+1. **Whenever `pagesOptedIn(up)` holds,** whatever the path or
+ eligibility, the LRU is off: `cacheable = false`. This is the one
+ place §5.3's rule is checked.
+2. **When `pageRouteEligible` holds and `pageReadable` passes,** call
+ `idx.Lookup(scope, key, identity, cookies)`.
+ - On a hit, `serveAssetEntry(w, r, entry, now, "hit")`. Return only
+ if it returned nil. On an error the writer is untouched, so
+ continue down the miss path **(P1-8)**.
+ - The Miss reason feeds the diagnostic in step 4.
+3. **When it is also `pageStorable`,** `t := idx.Begin(scope,
+ identity)`. A `pageRecorder` reserves at WriteHeader if `pageAdmit`
+ passes and `Content-Length` (when present) ≤ `MaxBody`, then tees.
+ After the proxy returns:
+ - a `Set-Cookie` trailer, an error or an overflow means `Abort`;
+ - otherwise `MarkOptIn` (durable), then `Finish`;
+ - Finish's meta uses `assetStoredHeader`, `Lifetime`, and
+ `Expires = now + lifetime`.
+4. **The diagnostic writer** wraps every response of an eligible route,
+ whatever the method. At WriteHeader it sets `Carlos-Cache` when the
+ instance is opted in or the holder says `Marked`:
+ - `miss` when step 3 ran;
+ - `bypass` otherwise, including a cookie miss, a POST and a HEAD
+ miss.
+ It never sets the header on other apps' responses.
+
+- [ ] **Step 1: Write failing tests** (a `newLAScene`-style scene with
+ an asset store, a page index, and `NoteServing(host, "id1")`):
- **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.
+ - `TestPageMissThenHitWithoutApp`.
+ - `TestPageHitOnHibernatingRouteDoesNotWake`.
- **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.
+ `TestPageRefusesNon200`, `TestPageRefusesPrivate`.
+ - `TestPageRefusesAppGzip` (Review Focus 2).
+ - `TestPageOverflowStreamsAndStoresNothing` (Review Focus 3).
- **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. So does an
- unmarked `s-maxage` response under a declared asset prefix (it is
- not page-eligible, and it is not stored in the LRU).
- - **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`.
+ - `TestPageCookieRequestNotStoredAnywhere` (Review Focus 4).
+ - `TestPageIgnoredCookieHits`, `TestPageAuthorizationBypasses`.
+ - **Hit behaviour:** `TestPageHeadRangeConditional` (Review Focus 1).
+ - **Identity:**
+ - `TestPageNewIdentityMisses`: a hit under `id1`, then
+ `NoteServing(host, "id2")` → `miss` that reaches the app.
+ - `TestPageUnknownIdentityBypasses`: with no `NoteServing`, the
+ response is `bypass` and isn't stored.
+ - **Failed delivery:** `TestPageEvictedBetweenLookupAndOpenFallsThrough`
+ (P1-8). Pause between Lookup and Open with a seam, delete the store
+ object, and the response is the app's 200 with a body.
+ - **Opt-in and the LRU:** `TestOptedInInstanceSkipsLRU`. A seeded LRU
+ entry and an unmarked `s-maxage` path under a declared asset prefix
+ both reach the app after opt-in.
+ - **Path routing:** `TestPagePathRoutedHostRefused` (P1-6). Host A
+ routes `/blog` to instance B, with B's own path map empty, and an
+ alias of A. A marked answer through A or its alias is never stored,
+ under either scope.
+ - **Asset prefixes:**
+ - `TestPageAssetPrefixWinsWhenAssetsOff` (P2-9): an `AssetsOff`
+ route whose release declares `/assets/`. A marked `/assets/x` is
+ not stored.
+ - `TestPageUnknownDeclarationBypasses`.
+ - **Diagnostics:** `TestPageDiagnostics` (P2-10), a table:
+ - hit → `hit`;
+ - stored miss → `miss`;
+ - a cookie-rejected lookup → `bypass`;
+ - a marked POST → `bypass`;
+ - a HEAD miss → `bypass`;
+ - an unrelated app → no header.
+ - **Ineligible routes:** `TestPageIneligibleRoutes`, the table from
+ rev 1.
+ - **Host side:** `TestDeclaresPrefixIgnoresAssetsOff`.
+- [ ] **Step 2: Run them to see them fail:** `go test ./internal/edge
+ -run 'TestPage|TestOptedIn' -count=1` (with the task-owned `TMPDIR`),
+ and `go test ./internal/host -run DeclaresPrefix -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 4: Run them to see them pass,** then `-run
+ 'Cache|Asset|Purge'` for the neighbours.
- [ ] **Step 5: Commit:** `edge: home-box page cache at the LRU point`.
-### Task 7: Clears reach the index (header, socket and `all`)
+### Task 8: 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_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).
+- Modify: `internal/edge/cache.go` (the bridge).
- 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()
+ clearPages(host string, c pageindex.Clear) // host to scope through e.current(); no-op when unarmed
+ instanceHosts(host string) []string // the primary and every alias whose upstream has the same route.Host
}
-func (c *Cache) setBridge(b purgeBridge) // set in EnableCache; the socket handler reads it
+func (c *Cache) setBridge(b purgeBridge) // set in EnableCache
```
**Header channel.** `applyPurgeTargets` keeps its LRU calls exactly as
-today, then:
-- for each host, calls `clearPages(host, ...)` with the same targets;
+today, then calls `clearPages` for each host with the same targets:
- `*` → `TargetHost`;
- a path → `TargetPath`;
- `path?query` → `TargetURL`;
- the over-limit fallback → `TargetHost`.
-**The new token `all`:**
+**The `all` token:**
- it is accepted before `validPurgeTarget`;
- for the LRU, it purges `PurgeHost` on every `instanceHosts(host)`;
-- for pages, it sends one `clearPages(host, Clear{})`.
+- for pages, it sends `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).
+**Socket channel.** `{"path":"all"}` does the same, and every other
+socket path also calls `clearPages`. Activator start sites still call
+only `PurgeHost`, plus Task 6's `NoteServing`. They never clear pages.
- [ ] **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`.
+ - `TestPurgeHeaderClearsPage`.
- `TestPurgeHeaderOnStoredResponseOrder`: a marked GET of `/post`
- whose own response carries `Carlos-Purge: /post` is not stored. Its
- ticket predates the clear, so Finish is fenced. The next GET is a
- `miss` that reaches the app.
- - `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`.
+ whose own response carries `Carlos-Purge: /post` is not stored,
+ because its ticket predates the clear. The next GET is a `miss`.
+ - `TestPurgeAllClearsAliases` (Review Focus 5).
+ - `TestControlSocketClearsPageAndAll`.
+ - `TestSpawnPurgeKeepsPages`.
+- [ ] **Step 2: Run them to see them fail.**
- [ ] **Step 3: Implement as above.**
-- [ ] **Step 4: Run them to see them pass,** plus `-run 'Purge'` for the
- existing purge suite.
+- [ ] **Step 4: Run them to see them pass,** plus `-run Purge`.
- [ ] **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
+### Task 9: Route changes reset a scope; only two things clear the mark
**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
+**Behaviour (P1-5).** The hook compares `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.
+- **The route is gone from this box:** `Reset` and `ClearOptIn`.
+- **`PagesOff` is set:** `Reset` and `ClearOptIn`.
+- **Ineligible for any other reason** (HA, forward, a gate, an import
+ gate, a sidecar, a status that isn't ready): `Reset` only. The mark
+ stays, so the LRU stays off.
-`ClearInstancePages` resolves the host's scope and sends `Clear{}`.
+Releases and config are not handled here: Task 6's identity covers
+them.
- [ ] **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`.
+ - `TestRouteDepartureResetsAndClearsMark`.
+ - `TestPagesOffResetsAndClearsMark`.
+ - `TestGateKeepsMarkAndLRUStaysOff`:
+ - seed an LRU entry before opt-in, then opt in;
+ - add a gate, Reload, pass the gate → the seeded URL reaches the
+ app, not the LRU;
+ - remove the gate → same;
+ - pages miss after the reset.
+ - `TestHAFlipKeepsMark`: the same, with `HA` set and then cleared.
+- [ ] **Step 2: Run them to see them fail.**
- [ ] **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`.
+- [ ] **Step 5: Commit:** `edge: route departure and switch-off reset
+ pages and the mark; other changes keep the mark`.
-### Task 9: Arming on the host, and config delivery clears
+### Task 10: Arming on the host
**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).
+- Modify: `internal/host/agent.go:1290`: after `armEdgeAssetCache`,
+ call `armEdgePageCache` with the returned store.
+- Test: `internal/host/pagearm_test.go`.
**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 pageCacheArmed(getenv func(string) string) bool
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.**
+- **When it arms:** 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").
+- **Declarations:** the asset policy's `DeclaresPrefix` reaches the edge
+ through the same `LocalAssets` value already passed to
+ `EnableAssetCache`.
+
+- [ ] **Step 1: Write a failing test:**
+ `TestArmPageCacheNeedsFlagAndStore`, a table.
+- [ ] **Step 2: Run it to see it fail.**
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run it to see it pass.**
- [ ] **Step 5: Commit:** `host: arm the page cache with
- CARLOS_PAGE_CACHE; config changes clear pages`.
+ CARLOS_PAGE_CACHE`.
-### Task 10: The copy deck, reviewed before any string is written
+### Task 11: 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).
+- Create: `docs/superpowers/plans/2026-11-08-edge-page-cache-copy-approved.json`.
-**Rows to draft** (wording is the reviewer's; these are the slots):
+**Slots to draft** (the wording is the reviewer's):
- **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`.
+ - the on and off result lines, on the model of `printSetAssets`;
+ - the "console predates" line;
+ - the help lines (`instances_cli.go:230`, `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 "Caching pages at the edge" section 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`, that a new
+ release or config stops old pages being served, and 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.
+ - the `CARLOS_PURGE` row (:1186);
+ - `docs/site/rootfs.md:46` if needed.
+- **Operator log lines** are outside copy review (human text only).
+
+- [ ] **Step 1: Draft the deck,** `pending`.
+- [ ] **Step 2: Run the `copy-review` skill,** apply Paul's edits
+ verbatim, and 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
+### Task 12: 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);
+ - `Pages *string \`json:"pages"\`` (:2949);
+ - the empty 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.
+- Create: `internal/console/apipages.go`, with `func pagesSwitch(w
+ http.ResponseWriter, v *string) (*bool, bool)` and the approved
+ message.
+- Create: `instances_pages.go`, with `instancesSetPagesUsage`,
+ `runInstancesSetPages` and `printSetPages`.
+- Modify: `apimode.go` (`instanceSetPages` beside :5694), `cli.go:615`
+ (`"set-pages"`), and the help lines.
+- Modify: `docs/site/cli.md` and `docs/site/rootfs.md` as approved.
+- Create: `approved_page_cache_copy_test.go`, with `pageCacheCopyBuilt`.
+- Test: `internal/console/apiinstances_test.go`, plus a CLI test beside
+ `set-assets`.
- [ ] **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.
+ - `TestPatchInstancePagesOffAndOn`.
+ - `TestSetPagesCLI`.
+ - The `internal/docsite` gate.
+ - `TestApprovedPageCacheCopy`.
+- [ ] **Step 2: Run them to see them fail.**
+- [ ] **Step 3: Implement,** mirroring `assets`.
- [ ] **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.
+### Task 13: The whole branch
+
+- [ ] **Step 1:** `go build ./...`, `go vet ./...`, and `gofmt -l .`
+ (which must print nothing). Then `GOOS=darwin go build ./...` and
+ `GOOS=windows go build ./...`.
+- [ ] **Step 2: The census,** per AGENTS.md § The census.
+- [ ] **Step 3: Push and describe.** Push `edge-page-cache-1`, then run
+ `amadan branch describe`. CI must be 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.
+ model family, under the stopping rules.
- [ ] **Step 5: Paul's go, then the merge:** `amadan branch merge
carlos/platform edge-page-cache-1 -squash -expect <full sha>
-message ...`.
+- [ ] **Step 6:** remove every `$HOME/.cache/epc.*` scratch dir this
+ work created.
**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.
+1. Release, then roll to dev.
+2. Set `CARLOS_PAGE_CACHE=1` on a dev box that already has the asset
+ cache.
+3. Patrix sends the marker and `Carlos-Purge`.
+4. Check a repeat view is `Carlos-Cache: hit` with no wake, and a
+ publish clears the homepage.
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-PAGE-CACHE-PLAN1-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-PAGE-CACHE-PLAN1-R1.md
new file mode 100644
index 000000000..bbaa24b3b
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-PAGE-CACHE-PLAN1-R1.md
@@ -0,0 +1,125 @@
+Reviewed commit `90da7cd5680c644676a9b47f852ddc7500bb17a1`, round 1. No files changed, subagents spawned, or test suites run.
+
+1. **P1 — Task 2: A rejected render can replace a published page before its fence is checked.**
+
+ **Evidence:** The [plan:208–221](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:208) gives concurrent fills the same store key and commits outside the scope lock. [Fill.Commit:432](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/assetcache/fill.go:432) replaces the existing entry; [Store.Get:425](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/assetcache/store.go:425) returns that replacement.
+
+ **Failure:** Render A starts before a clear. After the clear, render B publishes fresh content. A then commits over B’s store key. Before A acquires the scope lock and refuses publication, Lookup finds B’s index record but returns A’s stale bytes. A’s subsequent `Delete` also deletes the replacement at that shared key.
+
+ **Fix:** Give each pending publication a unique physical store key. Under the scope lock, publish the mapping from logical page key to that exact stored object and its cookie metadata. Refusal must delete only its own object. Add a deterministic test pausing A between Commit and the fence check.
+
+ **Boundary:** I1; only successful index publication may make bytes servable.
+
+2. **P1 — Task 1: The prescribed Delete implementation deadlocks.**
+
+ **Evidence:** [Plan:150](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:150) says to wrap `drop` under the store lock. [Store.drop:391](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/assetcache/store.go:391) calls `lockID`, which acquires `s.mu` at [store.go:365](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/assetcache/store.go:365). Its contract explicitly requires calling without `s.mu` held.
+
+ **Failure:** The first deletion hangs, including the proposed Task 1 test and every clear that deletes an entry.
+
+ **Fix:** Find the entry under `s.mu`, release that mutex, then call `drop`, preserving its identity check and lock ordering.
+
+ **Boundary:** Store locking and clear completion.
+
+3. **P1 — Task 8: The Version tracker can miss releases and permit old content to refill after a clear.**
+
+ **Evidence:** [Plan:589–597](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:589) examines existing index scopes and seeds unseen versions without clearing. Separately, [edge.go:1190](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/edge/edge.go:1190) states that registry Version identifies the installed build, not the serving generation. [assetpolicy.go:64](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/host/assetpolicy.go:64) explicitly handles generation switches that change no registry row.
+
+ **Failure:** A scope first caches v1, then its first reload observes v2. The hook seeds v2 and leaves v1 cached. Even with initialization fixed, an installed-version clear can occur while the old generation still serves; a subsequent render caches old content, and the eventual generation switch causes no further Version change.
+
+ **Fix:** Initialize release identity when a scope becomes usable. Define invalidation against the actual serving transition as well as installation for sleeping instances, and prevent old-generation responses from publishing across that transition. Test the first release after opt-in and a delayed generation switch, while preserving same-build wakes.
+
+ **Boundary:** Spec §8.6, automatic release invalidation.
+
+4. **P1 — Task 9: Neither proposed config callback supplies the required complete signal.**
+
+ **Evidence:** [Plan:643–648](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:643) leaves selection between two callbacks to implementation. [WithHostOutcome:840](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/appconfig/syncexec.go:840) reports unchanged files too. `Delivered` is suppressed for unmanaged socket and TCP shapes at [syncexec.go:635](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/appconfig/syncexec.go:635), and runs before restart at [syncexec.go:1490](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/appconfig/syncexec.go:1490). Unit-backed delivery occurs separately in [unitsync.go:318](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/appconfig/unitsync.go:318).
+
+ **Failure:** Using host outcomes clears on unchanged passes. Using `Delivered` misses eligible route shapes and root-side unit delivery. Clearing before a delayed restart also permits the old process to refill the cache under the new sequence.
+
+ **Fix:** Specify the exact change notification, its wiring to the edge across both agent and root delivery, and its relationship to activation before implementation begins. Preserve existing rollout callbacks. Test writes, removals, unchanged passes, delayed/failed restart, and unit-backed delivery through the real wiring.
+
+ **Boundary:** Spec §8.6, delivered-config invalidation without wake clears.
+
+5. **P1 — Task 8: Temporary ineligibility removes the protection against the old LRU.**
+
+ **Evidence:** [Plan:591–593](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:591) clears the opt-in mark for gates, HA and other ineligible states. [Spec:432](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/specs/2026-11-08-edge-page-cache-design.md:432) permits clearing it only for operator switch-off or route departure. The [LRU gate:2673](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/edge/edge.go:2673) does not exclude password-gated routes.
+
+ **Failure:** Adding a gate re-enables LRU entries stored before opt-in. A request passing the gate can receive a previously stored visitor-specific response that the durable mark was meant to make unreachable.
+
+ **Fix:** Separate resetting page contents from clearing opt-in. Preserve the mark through temporary predicate failures. Test a pre-opt-in LRU entry across gate addition/removal and HA changes.
+
+ **Boundary:** I2; an opted-in instance never uses the LRU.
+
+6. **P1 — Task 6: Checking only `up.paths` admits path-routed hosts whose clears cannot reach their entries.**
+
+ **Evidence:** The predicate at [plan:64](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:64) checks `len(up.paths) == 0`. However, [lookupUpstreamPath:1761](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/edge/edge.go:1761) returns the target upstream wholesale. The original hostname’s path map is no longer necessarily present in `up`.
+
+ **Failure:** Host A routes `/blog` to instance B, whose own path map is empty. The page is stored under B’s scope with host A. Task 7’s `clearPages(A, …)` resolves A’s scope, so even an authorized `Carlos-Purge-Host: A` fails to clear B’s stored page.
+
+ **Fix:** Check path rows on the requested hostname and its primary before path dispatch, as the existing [asset predicate:314](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/host/assetpolicy.go:314) does. Add a real path-routing test, including an alias of the front host.
+
+ **Boundary:** I1 and the spec’s exclusion of path-routed hosts.
+
+7. **P1 — Task 5: ModifyResponse alone does not strip the marker everywhere.**
+
+ **Evidence:** [Plan:387–390](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:387) specifies header deletion through `responseModifier`. Informational responses bypass that hook, as documented and handled at [assetcatch.go:1372](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/edge/assetcatch.go:1372). Trailer values arrive later and require separate removal at [assetcatch.go:986](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/edge/assetcatch.go:986).
+
+ **Failure:** An app sends the marker in a 103 response or an announced/unannounced trailer, and the visitor receives it on armed and unarmed boxes.
+
+ **Fix:** Add the marker to informational and trailer stripping, without treating those occurrences as admission signals. Test final headers, 103s, and both trailer forms.
+
+ **Boundary:** The unconditional marker-stripping contract.
+
+8. **P1 — Task 6: A failed hit delivery returns an empty response.**
+
+ **Evidence:** [Plan:447–448](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:447) calls `serveAssetEntry` and returns. Its [documented contract:33](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/edge/assetserve.go:33) returns an error with the writer untouched when eviction or replacement prevents opening the body.
+
+ **Failure:** The shared store evicts a page between Lookup and Open. Following the plan, the handler returns without reaching the app or writing a response body.
+
+ **Fix:** Return only after successful delivery; otherwise continue through the ordinary miss path. Test eviction between lookup and body opening.
+
+ **Boundary:** Store eviction must remain a cache miss, not a broken HTTP response.
+
+9. **P2 — Task 6: `LocalAssets.For` cannot establish that a path has no declared asset prefix.**
+
+ **Evidence:** [Plan:427–428](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:427) uses `For(host)` for this decision. [assetpolicy.go:302](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/host/assetpolicy.go:302) refuses asset opt-outs and missing generations; [For:388](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/internal/host/assetpolicy.go:388) also returns false before initialization and after expiry.
+
+ **Failure:** With assets switched off, a marked response under a release’s declared `/assets/` prefix can enter the page cache.
+
+ **Fix:** Provide declaration knowledge independently of asset-catching eligibility, with an explicit decision for unknown declarations. Test assets-off and unavailable-policy cases.
+
+ **Boundary:** Declared asset prefixes retain exclusive ownership.
+
+10. **P2 — Task 6: The diagnostic header rules omit cookie-rejected lookups and marked unstorable responses.**
+
+ **Evidence:** [Plan:449–466](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:449) installs the header-setting recorder only for storable requests. Its bypass branch requires the request to be neither readable nor storable, while cookie acceptance is decided inside Lookup. [Plan:491–493](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:491) nevertheless expects an unignored cookie to produce `bypass`.
+
+ **Failure:** A cookie-bearing lookup rejected by the entry’s ignore list falls through without either header-setting path. A marked answer to a POST or cookie-bearing request has the same omission.
+
+ **Fix:** Carry the lookup rejection reason and set diagnostics independently of body recording. Test marked POSTs, HEAD misses, and cookie-policy rejection.
+
+ **Boundary:** The promised `Carlos-Cache` visibility.
+
+11. **P2 — Tasks 3 and 6: The verification does not cover all required invariants.**
+
+ **Evidence:** [Task 3:289–307](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:289) asserts clear ordering only. The spec requires I2/I3 assertions at [spec:743–751](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/specs/2026-11-08-edge-page-cache-design.md:743) and a publication-bypass guard at [spec:409–412](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/specs/2026-11-08-edge-page-cache-design.md:409).
+
+ **Failure:** Cross-scope/host lookup defects or a page write outside the index can pass the prescribed checks. Random sleeps also do not guarantee exercising the Commit-to-index window in finding 1.
+
+ **Fix:** Add explicit ownership assertions across account, app, instance and host; exercise cookie/Authorization provenance and opt-in transitions through the edge; add the publication guard and deterministic interleaving barriers. Give the concurrent model a defined ordering for observing clears and lookups.
+
+ **Boundary:** Required evidence for I1, I2, I3 and sole publication authority.
+
+12. **P2 — Global constraints: The test instructions contradict this machine’s scratch-space rules.**
+
+ **Evidence:** [Plan:90–93](/home/paulca/amadan.net/carlos/platform-design-edge-page-cache/docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md:90) mandates `/tmp/g`, repeated throughout the tasks. The supplied AGENTS instructions prohibit task scratch directly under the shared RAM-backed `/tmp`.
+
+ **Failure:** Following the plan puts test scratch on the shared tmpfs.
+
+ **Fix:** Use the configured disk-backed `$TMPDIR` or task-owned disk scratch and remove it afterward; retain the default Go cache.
+
+ **Boundary:** Shared-machine resource rules.
+
+No P3 findings.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-PAGE-CACHE-PLAN1-R2.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-PAGE-CACHE-PLAN1-R2.md
new file mode 100644
index 000000000..76b737631
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-PAGE-CACHE-PLAN1-R2.md
@@ -0,0 +1,92 @@
+# Review brief: edge page cache plan 1 (home box), round 2 of 3
+
+Repo carlos/platform, branch `design-edge-page-cache`, the commit named in
+your prompt.
+Under review: `docs/superpowers/plans/2026-11-08-edge-page-cache-plan-1-home.md`.
+Authorities: the approved spec
+`docs/superpowers/specs/2026-11-08-edge-page-cache-design.md` (rev 4, approved
+by Paul; it merges together with this plan), and the code on this branch
+(`internal/edge`, `internal/assetcache`, `internal/registry`,
+`internal/provision`, `internal/console`, `internal/host`, CLI files in the
+repo root).
+
+You are an independent reviewer and the engineer who will implement each
+task with only the plan and spec in hand. Check every file, line, signature
+and behaviour the plan names against the code.
+
+## Fixed: do not re-argue
+
+- The spec's design, its rulings in §16, and Paul's rule-2 choices:
+ - one page index per box owns every publish, clear, reset and lookup;
+ - an opted-in instance never uses the LRU.
+- The slice boundary: home box only, with no far boxes, leases, pushes or
+ single-flight.
+
+## What to check
+
+1. **Fit with the spec.** Does each task deliver what spec slice 1
+ (§11 item 1) needs, with nothing in the spec's invariants I1 (home
+ side), I2 and I3 left untested? Does any task contradict the spec?
+2. **Fit with the code.**
+ - Are the named sites real, and are the signatures workable? Pay
+ particular attention to:
+ - where `ModifyResponse` runs relative to the recorders (Task 5's
+ context holder);
+ - the LRU gate (Task 6);
+ - `applyPurgeTargets` and `ListenControl` (Task 7);
+ - `OnReload` and the Version signal (Task 8);
+ - the config-delivery hook (Task 9).
+ - Does anything the plan relies on not exist?
+3. **Safety.** Could a task as written:
+ - serve a personalised page;
+ - serve a page after a clear;
+ - leak the marker;
+ - let the asset sweep or store eviction break the index;
+ - or make a wake clear pages?
+4. **Tests.** Does each test fail for the right reason before the change
+ and prove the behaviour after it? Name any missing test for a real
+ failure mode.
+5. **Order and size.** Can each task be built and pass its tests with
+ only the earlier tasks done?
+
+## Round 2
+
+Earlier rounds: `CODEX-FINDINGS-PAGE-CACHE-PLAN1-R1.md` (plan rev 1). First
+give one line per round-1 P1 and P2: resolved, partly, or not. The plan's
+"(P1-n)" marks show where each was answered. Carry unresolved ones forward
+at their severity, then add new findings. The verdict covers everything
+outstanding.
+
+Plan rev 2 replaces spec §8.6's release and config clear hooks with
+serving-identity tagging (Task 6, Task 7). Check that it delivers §8.6's
+guarantee. That means a new build or config is never served from old
+pages, and a same-build wake keeps them. Check also that every process
+start site is covered, including unit-backed instances.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives:
+- the task;
+- the problem;
+- the evidence (file:line, verified);
+- the failure scenario;
+- a concrete fix;
+- the invariant or boundary it breaks.
+
+End with exactly one verdict: **READY**, **READY AFTER FIXES**
+(no P1; the P2s are fixed without another round), or **NOT READY** (P1s
+listed).
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.