plan: static _headers implementation plan (5 tasks)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+136
−0
docs/superpowers/plans/2026-10-29-static-headers.md+136 −0
Intent
diff --git a/docs/superpowers/plans/2026-10-29-static-headers.md b/docs/superpowers/plans/2026-10-29-static-headers.md| new file mode 100644 |
| index 000000000..daec2eefc |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-29-static-headers.md |
| @@ -0,0 +1,136 @@ |
| +# Static `_headers` 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:** A static site sets `Cache-Control` and a short list of cross-origin headers by path with a `_headers` file at the root of its tree. |
| + |
| +**Architecture:** A new `internal/edge/headers.go` parses `_headers` with the path-pattern parser and matcher factored out of `redirects.go`. `PackDir` refuses a bad file at ship. The edge loads the rules once per version swap into `servedTree`. `serveTree` looks them up on the pre-rewrite path, and `serveFile` applies them through a status-time writer for 200/206/304 only. `Edge.ServeHTTP` takes static routes out of the shared response cache. |
| + |
| +**Tech Stack:** Go 1.26, `net/http`, the existing `internal/edge` test fixtures. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-29-static-headers-design.md` (rev 4, review closed). Read it first; section numbers below are its. |
| + |
| +## Global Constraints |
| + |
| +- File name `_headers`, at the tree root. The edge never serves it (404). |
| +- Allowed headers, v1, exactly: `Cache-Control` (comma-separated `token` or `token=value` directives), `Access-Control-Allow-Origin` (`*` only), `Access-Control-Expose-Headers` (comma-separated header names), `Cross-Origin-Resource-Policy` (`same-origin`, `same-site`, `cross-origin`), `Timing-Allow-Origin` (`*`). Every other name is refused at ship with "not supported yet". |
| +- Limits: 100 path lines, 2,048 characters a line, 256 KiB a file. |
| +- A path pattern is exactly a `_redirects` source: same parser, same matcher, same refusals. |
| +- Match on the cleaned request path and `requestHost(r.Host)` before any `_redirects` rewrite. |
| +- Several matching rules: the last one in the file wins per header. No comma joining. |
| +- Applied at status time, only on 200, 206 and 304 from `serveFile`'s 200 branch. A matching `Cache-Control` replaces `no-cache`. Every other status is header-for-header what it is today. |
| +- The status-time writer owns a private header map (AGENTS.md), syncs down wholesale before forwarding the status, does not implement `io.ReaderFrom`, implements `Flush` (implicit 200 through the hook first) and `Unwrap`. |
| +- `cacheable` in `Edge.ServeHTTP` gains `up.route.Kind != "static"`. |
| +- A tree with no `_headers` file: every response header unchanged. |
| +- Tests locally: only the touched packages, with `-run` (`go test ./internal/edge/ -run 'X|Y' -count=1`). CI runs the full gate. Never `make test` locally. |
| +- Go: leave `GOCACHE` at its default. Scratch under `$TMPDIR`. |
| +- Copy: docs prose goes through the copy-review skill before it lands. No em dashes. Error fragments are out of copy review. |
| +- Commits end with the session's `Co-Authored-By` line. Each task closes its amadan task (983-990 on branch `static-headers`). |
| + |
| +## Review Focus |
| + |
| +1. A `_headers` file saved with CRLF line endings or a BOM (Windows editors). Expected: parsed as LF, as `_redirects` is. Test in Task 1. |
| +2. A header line indented with a tab, an indented `# note` line between header lines, or a trailing `# note` after a value. Expected: tab indents count; the indented comment line is ignored; the trailing `#` is part of the value, so none of the five validators accepts it and ship refuses the line rather than silently cutting it. Test in Task 1. |
| +3. A directory URL: `/1.0.0/` serving `1.0.0/index.html`, and `/1.0.0` without the slash (a 301 to `./1.0.0/`, which must carry no `_headers` headers). Test in Task 2. |
| +4. A `Range` request on an immutable file (`206`), and a `HEAD`. Expected: same headers as the 200. Test in Task 2. |
| +5. A compressed 200 (`Accept-Encoding: gzip`) through the real edge. Expected: the `_headers` values survive the gzip wrapper, and `Vary: Accept-Encoding` is still added. Test in Task 2. |
| + |
| +--- |
| + |
| +### Task 1: `_headers` parser, shared path patterns, and the ship refusal |
| + |
| +**Files:** |
| +- Create: `internal/edge/headers.go`, `internal/edge/headers_test.go` |
| +- Modify: `internal/edge/redirects.go` (factor the source half of `parseRedirectLine` and `redirectRule.match` out), `internal/edge/static.go` (`PackDir`) |
| + |
| +**Interfaces:** |
| +- Produces, in `redirects.go`: |
| + - `type pathPattern struct { host string; segs []string; splat bool }`; `redirectRule` embeds it in place of its own `host`, `segs`, `splat`. |
| + - `func parsePattern(field string) (pathPattern, error)`: the source parsing now inside `parseRedirectLine`, with the same error strings (they quote `field`). `parseRedirectLine` calls it. |
| + - `func (pp *pathPattern) match(host string, reqSegs []string) (map[string]string, bool)`: today's `redirectRule.match` body. |
| + - `func pathSegs(p string) []string`: `nil` for `"/"`, else `strings.Split(p[1:], "/")`; `resolve` and `names` use it. |
| +- Produces, in `headers.go`: |
| + - `const headersFile = "_headers"`; `headersMaxBytes = 256 << 10`, `headersMaxRules = 100`, `headersMaxLine = 2048`. |
| + - `type headerRule struct { line int; pathPattern; set http.Header }` |
| + - `type headerRules struct { rules []headerRule }` |
| + - `func parseHeaders(data []byte) (*headerRules, error)`: usable rules plus an `errors.Join` naming each bad line as `line N: ...`. A bad path line drops its header lines too (spec 3.4). |
| + - `func (hs *headerRules) lookup(host, p string) http.Header`: nil receiver or no match returns nil. Otherwise a fresh map, each matching rule's headers `Set` in file order (last wins). |
| + |
| +- [ ] **Step 1: Write the failing tests** in `headers_test.go`: |
| + - `TestParseHeadersAcceptsTheSupportedForms`: the spec section 2 Fiesta file plus a host-URL path line, a tab-indented header line, a lowercase name (`cache-control: no-store`), CRLF line endings and a leading BOM. Assert 3 rules, `rules[0].set.Get("Cache-Control") == "public, max-age=31536000, immutable"`, and the lowercase name stored as `Cache-Control`. |
| + - `TestParseHeadersRefusesWhatItCannotServe`, table of input → substring of the error: `Set-Cookie: a=b` → `not supported yet`; `X-Carlos-Version: x` → `not supported yet`; `Access-Control-Allow-Origin: https://a.example` → `*`; `Cross-Origin-Resource-Policy: anywhere` → `cross-origin`; `Cache-Control: max-age=1, ,` → `Cache-Control`; a header line before any path line → `before a path`; a path line with no header lines → `no headers`; `/a/*/b` path → `* must be the last segment` (the shared parser's message); `! Cache-Control` → `not supported`; a value with a control byte → `value`; a line with no colon → `Name: value`. |
| + - `TestParseHeadersKeepsTheGoodLinesAroundABadOne`: a bad path line's header lines are not attached to the rule above it (`rules[0].set` has exactly its own header). |
| + - `TestParseHeadersLimits`: 101 path lines → `more than 100`; a 2,049-character line → `longer than 2048`; 256 KiB + 1 → `the limit is`. |
| + - `TestHeaderLookupLastRuleWins`: `/*` with `Access-Control-Allow-Origin: *` and `Cache-Control: no-store`, then `/1.0.0/*` with `Cache-Control: public, max-age=31536000, immutable`. `lookup("h", "/1.0.0/a.css")` has both headers, with the immutable value. `lookup("h", "/x")` has `no-store`. `(*headerRules)(nil).lookup` is nil. |
| + - `TestParseHeadersComments`: an indented ` # note` line between two header lines is ignored (the rule has both headers); ` Cache-Control: max-age=60 # note` is refused with an error naming `Cache-Control`. |
| + - `TestPackDirRefusesABadHeadersFile`: mirrors `TestPackDirRefusesABadRedirectsFile` (`redirects_test.go:111`) with `_headers` holding `Set-Cookie: a=b`; error names `_headers` and `line`. |
| +- [ ] **Step 2: Run them and see them fail.** `go test ./internal/edge/ -run 'ParseHeaders|HeaderLookup|PackDirRefusesABadHeaders' -count=1`. Expected: build failure, `parseHeaders` undefined. |
| +- [ ] **Step 3: Factor `pathPattern` out of `redirects.go`.** No behaviour change. Run `go test ./internal/edge/ -run 'Redirect|SPAFallback|DirectorySlash|StaticWithoutRedirects' -count=1`. Expected: PASS, unchanged. |
| +- [ ] **Step 4: Implement `headers.go`.** Syntax as spec 3.1 (column 0 = path line; leading space or tab = header line split at the first `:`; blank and `#`-first lines skipped). One validator per allowed header, chosen by canonical name; an unknown name is `header %q is not supported yet`. Add the `_headers` branch to `PackDir` beside the `_redirects` one, same wording shape. |
| +- [ ] **Step 5: Run Step 2's command.** Expected: PASS. |
| +- [ ] **Step 6: Commit.** `git add internal/edge/headers.go internal/edge/headers_test.go internal/edge/redirects.go internal/edge/static.go && git commit -m "edge: parse _headers for static sites; ship refuses a bad one (#195, #450)"`. Set amadan task 986 Done. |
| + |
| +### Task 2: The edge serves `_headers` |
| + |
| +**Files:** |
| +- Modify: `internal/edge/static.go` (`staticSite`, `servedTree`, `currentDir`, `served`, `serveTree`, `serveFile`) |
| +- Create: `internal/edge/headerwriter.go`; tests in `internal/edge/static_headers_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: `parseHeaders`, `(*headerRules).lookup`, `headersFile` (Task 1). |
| +- Produces: |
| + - `staticSite.headers *headerRules` and `servedTree.headers *headerRules`, set in `currentDir` beside `redirects` by `func (s *staticSite) loadHeaders(dir, version string) *headerRules`, the same shape as `loadRedirects`. |
| + - `serveFile(fp, p string, fi os.FileInfo, status int, extra http.Header, w http.ResponseWriter, r *http.Request)`: `extra` is the lookup result, nil for none. |
| + - `type headerWriter struct { http.ResponseWriter; hdr, extra http.Header; wroteHdr bool }` and `func newHeaderWriter(w http.ResponseWriter, extra http.Header) *headerWriter` (`hdr` = `w.Header().Clone()`). Methods: `Header()` returns `hdr`; `WriteHeader(status)`: 1xx syncs and forwards without latching; on the first final status, if 200, 206 or 304, `Set` each `extra` key into `hdr`; then sync down wholesale (as `gzipWriter.syncHeader`) and forward. `Write` calls `WriteHeader(200)` first if needed, then forwards. `Flush` does the same implicit 200, then flushes below if it is an `http.Flusher`. `Unwrap() http.ResponseWriter`. No `ReadFrom`. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `static_headers_test.go`. Build the fixture through the real edge, as `TestEdgeServesStaticRouteWhenEnabled` does (`static_test.go:225`: `openReg`, `New`, `EnableStatic`, `Reload`), with `e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))` on. Ship `1.0.0/fiesta.css` (larger than `minCompressSize`, so the compressor takes it), `1.0.0/index.html`, `index.html`, a `_redirects` of `/1/* /1.0.0/:splat 200` and the spec section 2 `_headers`. Name it `headersEdge(t, files map[string]string) (srv *httptest.Server, treeDir string)`, where `treeDir` is the extracted tree: the `cacheDir` given to `EnableStatic`, then `release.RouteAccount(rt)`, the app, and `siteDirOf(t, store, app, version)`. |
| + - `TestStaticHeadersFiestaFile`: `GET /1.0.0/fiesta.css` → 200, `Cache-Control: public, max-age=31536000, immutable`, `Access-Control-Allow-Origin: *`, an `Etag`. `GET /1/fiesta.css` → 200, the same bytes, `Cache-Control: public, max-age=300`. `GET /index.html`'s page `/` → `Cache-Control: no-cache`, no `Access-Control-Allow-Origin`. |
| + - `TestStaticHeadersRideTheRevalidationRangeAndHead`: with the 200's `Etag` as `If-None-Match` → 304 with the immutable `Cache-Control` and `*`. `Range: bytes=0-3` → 206 with both. `HEAD` → both. |
| + - `TestStaticHeadersStayOffErrorsAndRedirects`, each under `/1.0.0/` and each asserting `Cache-Control: no-cache` or absent exactly as on `main` and no `Access-Control-Allow-Origin`: `If-Match: "nope"` → 412; `Range: bytes=999999-` → 416; `/1.0.0/missing.css` → 404; `/1.0.0` → 301; `/1.0.0/index.html` → 301. |
| + - `TestStaticHeadersDirectoryIndex`: `GET /1.0.0/` → 200 from `1.0.0/index.html` with the immutable headers. |
| + - `TestStaticHeadersSurviveCompression`: `GET /1.0.0/fiesta.css` with `Accept-Encoding: gzip` and a body over the compressor's minimum → `Content-Encoding: gzip`, `Vary: Accept-Encoding`, and both `_headers` values. |
| + - `TestStaticHeadersFileIsNotServed`: `GET /_headers` → 404. |
| + - `TestStaticWithoutHeadersIsUnchanged`: the same tree with no `_headers`. For `/1.0.0/fiesta.css` (200, 304, 206, HEAD, 412, 416), `/missing` (404) and `/1.0.0` (301), the full response header set minus `Date` equals a golden captured on `main` before this task's code change. This test lives in its own file, `internal/edge/static_headers_golden_test.go`, with its own fixture (the real edge, no `_headers`) and a `-update-headers-golden` flag, so it compiles before any of this task's code exists. The golden is `internal/edge/testdata/static-headers-golden.json`. |
| + - `TestHeaderWriterKeepsItsOwnMap`: unit test on `newHeaderWriter` over an `httptest.ResponseRecorder`. A `Header().Set` before `WriteHeader` does not appear on the recorder's map until `WriteHeader`. A `Header().Del` of a key the recorder had is gone after `WriteHeader(200)`. `extra` is applied on 200, 206 and 304, not on 412. A `Write` without `WriteHeader` applies `extra`. `Flush` before any write applies `extra`. The writer does not satisfy `io.ReaderFrom`. |
| +- [ ] **Step 2: Capture the golden on the unchanged code.** With only `static_headers_golden_test.go` written (move `static_headers_test.go` aside under `$TMPDIR` for this one run), `go test ./internal/edge/ -run TestStaticWithoutHeadersIsUnchanged -update-headers-golden -count=1`. Put `static_headers_test.go` back, then run the rest and see them fail: `go test ./internal/edge/ -run 'StaticHeaders|HeaderWriter' -count=1`. Expected: build failure or FAIL on the missing headers. |
| +- [ ] **Step 3: Implement `headerwriter.go`.** |
| +- [ ] **Step 4: Wire it in `static.go`.** Load in `currentDir` beside `loadRedirects`. In `serveTree`, compute `extra := tree.headers.lookup(requestHost(r.Host), p)` once, right after `p` is first cleaned and before the loop. Extend `found` to exclude `"/"+headersFile` as it excludes `_redirects`. Pass `extra` to `serveFile`. In `serveFile`, only in the `status == http.StatusOK` branch, after `os.Open` succeeds, `if extra != nil { w = newHeaderWriter(w, extra) }`. The non-200 branch (a `_redirects` 404 page) never gets it. |
| +- [ ] **Step 5: Run Step 2's command and the existing static suites.** `go test ./internal/edge/ -run 'StaticHeaders|HeaderWriter|StaticWithoutHeaders|Static|Redirect|SPAFallback|DirectorySlash|TagCache|PackDir' -count=1`. Expected: PASS. |
| +- [ ] **Step 6: Commit.** `git add internal/edge/headerwriter.go internal/edge/static.go internal/edge/static_headers_test.go internal/edge/static_headers_golden_test.go internal/edge/testdata/static-headers-golden.json && git commit -m "edge: static sites serve _headers on 200/206/304 by request path (#195, #450)"`. Set amadan task 987 Started (Task 3 finishes it). |
| +- [ ] **Step 7: Per-task review.** This task changes cache headers and a response writer, so it gets its own Astra review (AGENTS.md stopping rule 3), briefed from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, round 1 of 3, diff `<Task 1 tip>..HEAD`. |
| + |
| +### Task 3: Static routes leave the shared response cache |
| + |
| +**Files:** |
| +- Modify: `internal/edge/edge.go` (the `cacheable` computation in `ServeHTTP`, and the `maybeStore` doc comment's list of route refusals) |
| +- Test: `internal/edge/static_headers_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: `headersEdge` (Task 2). |
| + |
| +- [ ] **Step 1: Write the failing tests.** |
| + - `TestStaticWithMaxAgeIsNeverStoredInTheSharedCache`: with `headersEdge` and the shared cache on, `GET /1.0.0/fiesta.css` twice; between them, replace `treeDir/1.0.0/fiesta.css` on disk with other bytes (write a new file and rename it over, so the tag cache sees a new file) so a cache hit would return the old bytes. Assert the second answer has the new bytes and a new `Etag`. |
| + - `TestProxiedStaticRouteBypassesTheSharedCache`: a backend `httptest.Server` answering `Cache-Control: public, max-age=300` with a counter in its body; register `registry.Route{Host: "site.example.com", Kind: "static", Addr: <backend host:port>, Status: "ready"}` (it takes the address arm of `Reload`'s switch, ahead of `case t.Kind == "static"`); enable the shared cache; two GETs; assert the backend counted 2. |
| +- [ ] **Step 2: Run them and see them fail.** `go test ./internal/edge/ -run 'NeverStoredInTheSharedCache|ProxiedStaticRoute' -count=1`. Expected: FAIL (one stored hit each). |
| +- [ ] **Step 3: Add `&& up.route.Kind != "static"` to `cacheable`,** with a comment naming spec 4.4's four reasons in one line each, and add static to `maybeStore`'s "One refusal is NOT made here" paragraph. |
| +- [ ] **Step 4: Run Step 2's command and the cache suites.** `go test ./internal/edge/ -run 'NeverStoredInTheSharedCache|ProxiedStaticRoute|Cache' -count=1`. Expected: PASS. |
| +- [ ] **Step 5: Commit.** `git add internal/edge/edge.go internal/edge/static_headers_test.go && git commit -m "edge: static routes never enter the shared response cache (spec 4.4)"`. Set amadan task 987 Done. |
| +- [ ] **Step 6: Per-task review.** Cache change: its own Astra review, round 1 of 3. |
| + |
| +### Task 4: Docs |
| + |
| +**Files:** |
| +- Modify: `docs/site/cli.md` (a `#### Response headers for a static site` section after the "Redirects for a static site" section, which ends before `#### Two builds at once`) |
| + |
| +- [ ] **Step 1: Draft the section** in `$TMPDIR`, not in the file: what the file is for, Fiesta's example from spec section 2 with neutral paths, the five headers and their allowed values, last-rule-wins and why, the request-path rule with the `/1/*` rewrite example, which responses carry them (and that 404s and redirects do not), the limits, that ship refuses a bad file and names the line, and that the edge does not serve `_headers`. Neutral examples only (no tenant names). |
| +- [ ] **Step 2: Copy review.** Invoke the copy-review skill on every human sentence in the draft. Apply Paul's edits verbatim. |
| +- [ ] **Step 3: Write the approved text into `docs/site/cli.md`** and run `go test ./internal/docsite/ -count=1`. Expected: PASS (headings and links resolve). |
| +- [ ] **Step 4: Commit.** `git add docs/site/cli.md && git commit -m "docs: _headers for static sites"`. Set amadan task 988 Done. |
| + |
| +### Task 5: Census, whole-branch review, merge |
| + |
| +- [ ] **Step 1: Push and read CI.** `git push origin static-headers` (sandbox off for the push). Read the amadan run. |
| +- [ ] **Step 2: Census.** If `TestPlan14RootReadCensus` fails: `make census-card`; write `docs/superpowers/notes/census-static-headers-claims.md` (`<file>:<unit><TAB><what changed>` per unit); `make census-propose NAME=static-headers CLAIMS=docs/superpowers/notes/census-static-headers-claims.md`; brief Astra with the card and `git diff origin/main...HEAD` for the named files; record the verdict, reviewer and tip on #280. Decisions or escalations go to Paul; approvals do not. |
| +- [ ] **Step 3: Whole-branch Astra review,** round 1 of 3, diff `origin/main...HEAD`, brief from the template. Stop at the first round with no P1; apply that round's P2s. |
| +- [ ] **Step 4: Merge.** `amadan branch merge carlos/platform static-headers -squash -expect <tip>` with the full commit message (what, reviews, census, "Not released"). Never a bare `amadan branch merge`. Set amadan task 989 Done. |
| +- [ ] **Step 5: Tell the requesters.** Reply on #195 and #450: merged, not released; it reaches sites with the next release roll (dev, then flagship). Task 990 stays Started until the roll. |