Merge main into perf/ssr-highlight
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 6a8da5d, 3c4c931 · Browse files · 20 files·+988 added−72 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
20 files+988 added−72 removed
- tests:+569 added−0 removed
- other:+419 added−72 removed
Provenance
- Commit
51a1ca5- Tree
febfd43- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
6a8da5d- Parent 2
3c4c931
20 files changed+988 added−72 removed
modified:apps/web/src/dev/fixtures/story.ts+1 added-1 removed
91 unmodified lines92 /** A held-back suite's commitment, made from its area's name. */93 export const suiteOf = (area: string) =>94 SuiteRoot.make(`sha256:${hexOf(`suite:${area}`, 64)}`);95 96-/** An instant, from `2026-10-07T10:00`, in UTC. */96+/** An instant of the dev world's calendar (`clock.ts`), from `2026-10-07T10:00`, in UTC. */97 export const instant = (text: string): DateTime.Utc =>98 DateTime.toUtc(DateTime.makeUnsafe(`${text}:00Z`));99 100 // ----------------------------------------------------------- lanes750 unmodified linesmodified:apps/web/src/dev/fixtures/vellum.ts+17 added-8 removed
62 unmodified lines63 Weakened,64 } from "@repo/protocol/refusal";65 import { Array, DateTime, Effect, Schema } from "effect";66 67+import { DevClock } from "../clock.ts";68 import {69 askFileOf,70 burrowPeople,71 datekitPeople,7 unmodified lines79 import type { Story } from "./story.ts";80 81 export const vellum = ProjectName.make("vellum");82 82-/** Where the world's clock stands once the fixtures are told. */83+/** The calendar's instant the world's clock stands at once the fixtures are told. */84 export const fixturesNow = instant("2026-10-07T10:00");85 85-/** When vellum's first commit was pushed, by its initializer. */86+/** When vellum's first commit was pushed, by its initializer, on the calendar. */87 export const vellumStart = instant("2026-08-24T09:00");88 89 const dir = Brand.configDir;90 700 unmodified lines791 postureLabel: "Open with sealed evidence · sealed checks in export, parser",792 project: vellum,793 };794 794-/** The env shape at `at`: four items, one write-only and set, none with a value or placeholder. */795-const envAt = (at: LandedSha): EnvSchemaView => ({795+/**796+ * The env shape at `at`: four items, one write-only and set at `setAt`,797+ * none with a value or placeholder.798+ */799+const envAt = (at: LandedSha, setAt: DateTime.Utc): EnvSchemaView => ({800 at,801 file: RepoPath.make(".env.schema"),802 imports: [],803 items: [6 unmodified lines810 required: true,811 sensitive: true,812 tags: ["export", "errors"],813 type: 'string(startsWith="sntrys_")',810- value: { setAt: instant("2026-10-06T16:30"), setBy: people.ines },814+ value: { setAt, setBy: people.ines },815 },816 {817 description: "Where error reports go; public.",818 key: EnvKey.make("SENTRY_DSN"),70 unmodified lines889 new Map([[`packages/${module}/src/page.ts`, pageOf(module, "pageFormat")]]);890 891 // ------------------------------------------------------------- the story892 889-/** The record vellum's story writes, over its canonical repo standing at `base`. */893+/**894+ * The record vellum's story writes, over its canonical repo standing at895+ * `base`: each instant written on the calendar, placed in this world.896+ */897 export const tellVellum = (base: LandedSha) =>898 Effect.gen(function* () {892- const t = instant;899+ const { place } = yield* DevClock;900 901+ const t = (text: string) => place(instant(text));902+903 const story = yield* storyOf({904 base,905 files: vellumFiles,906 lanes: LANES,1052 unmodified lines1959 }),1960 });1961 1962 const apart = {1954- env: envAt(story.head()),1963+ env: envAt(story.head(), t("2026-10-06T16:30")),1964 ledger,1965 working: [people.ines, people.okonkwo],1966 };1967 20 unmodified linesmodified:apps/web/src/dev/backend.ts+13 added-3 removed
7 unmodified lines89101112131213141516171819202122202324252627282930313233347 unmodified lines * sets signs a browser in to the dev world as that person. * * One world per isolate (`server.ts`): it is made and seeded when this * module loads, since `toWebHandler` builds at once, and kept for the * isolate's life. Nothing outside `src/dev/` imports this file, and the * production build carries none of it (`test/production-bundle.test.ts`). * isolate's life. Under `vite dev` its seed ends at the minute it loads, * and its clock runs on from there (`clock.ts`), so a page reads each * deadline as the seed meant it on whatever day the server starts. Nothing * outside `src/dev/` imports this file, and the production build carries * none of it (`test/production-bundle.test.ts`). */import type { Backend } from "../server/rpc.ts";import { credentialFrom, withCredential } from "../server/session.ts";import { fixturesMode } from "./fixtures.ts";import { devServer } from "./server.ts";
const served = devServer({ fixtures: fixturesMode });/** * `vite dev` places the world at the present; vitest, whose `MODE` is * `test`, keeps the calendar as written, so a test reads the same instants * on every run. */const time = import.meta.env.MODE === "test" ? "fixed" : "present";
const served = devServer({ fixtures: fixturesMode, time });
/** The development backend: every request answered by the dev world, as the platform is asked; the env unused. */export const backend: Backend = (request) => served.handler(withCredential(request, credentialFrom(request)));modified:apps/web/src/dev/clock.ts+92 added-16 removed
123456734567891011121314151617189192011212223142425262728293031323334353637383940411942434445462447484950285152535455565758596061626364656667686970717273337475357677787980818283848586878889909192939495969798991003839101102103104105106107108109110111112113114115116117511181191201211221231241251261271281291301311323 unmodified lines/** * The dev world's time: one clock that every part of the world reads, as a * test's TestClock is, standing still at the instant it was last set. The * seed sets it step by step from one fixed start (`seed.ts`), and the world * then serves at the instant the seed left it, so a decision opened by the * seed never expires under a developer and every timestamp is the same on * every run. Sleeping, which nothing in the world does, waits in real time. * test's TestClock is. The seed and the fixtures are written against one * fixed calendar, which starts at `devStart`: each step names its instant * on it (`devMinute`, or a fixture's date), and the seed sets the clock * there step by step. A world places that calendar on time by one offset, * the distance from `devStart` to where the world starts, so every instant * it holds is the calendar's moved by the same amount and the gaps between * them are as written. * * A world built for a test starts at `devStart` and its clock stands still * where the seed left it, so every timestamp is the same on every run. The * running dev server (`backend.ts`) starts its world so that the seed's * last instant is the minute it starts in (`startEndingNow`), and its clock * runs on from there in real time (`run`), so a page in a browser reads a * deadline as the seed meant it and sees it come. Elapsed time and sleeping, * which nothing in the world does, are always real. */import { Clock, Context, DateTime, Effect, Layer } from "effect";import { Clock, Context, DateTime, Duration, Effect, Layer } from "effect";
/** Moves the dev world's clock to an instant. *//** The dev world's clock: where its calendar stands, and the way to move it. */export class DevClock extends Context.Service< DevClock, { readonly set: (at: DateTime.Utc) => Effect.Effect<void> } { /** The calendar's instant `at`, as it stands in this world. */ readonly place: (at: DateTime.Utc) => DateTime.Utc; /** Stands the clock at the calendar's instant `at`; a running clock runs on from there. */ readonly set: (at: DateTime.Utc) => Effect.Effect<void>; /** From the instant it stands at, the clock moves in real time. */ readonly run: Effect.Effect<void>; /** * When something that happens now happens: on a running clock, the * present; on one standing still, a minute after where it stands, which * it then stands at, so the thing reads as after all before it. */ readonly step: Effect.Effect<DateTime.Utc>; }>()("web/dev/DevClock") {}
const NANOS_PER_MILLI = 1_000_000n;
/** Where the world's time starts: every instant the seed writes is this one or a whole minute after. *//** Where the calendar starts: every instant the seed writes is this one or a whole minute after. */export const devStart: DateTime.Utc = DateTime.toUtc( DateTime.makeUnsafe("2026-10-07T09:00:00Z"));
/** The instant `minutes` whole minutes after the world's start. *//** The calendar's instant `minutes` whole minutes after its start. */export const devMinute = (minutes: number): DateTime.Utc => DateTime.add(devStart, { minutes });
/** A clock standing at `start` until it is set elsewhere, and the way to set it. *//** * Where a world starts whose calendar instant `end` is the present minute: * the clock read once, rounded down to its minute, less the calendar's * distance from its start to `end`. */export const startEndingNow = ( end: DateTime.Utc): Effect.Effect<DateTime.Utc> => Effect.map(DateTime.now, (now) => DateTime.subtractDuration( DateTime.startOf(now, "minute"), DateTime.distance(devStart, end) ) );
/** * A world's clock, whose calendar starts at `start`: standing at `start` * until it is set or run, and the way to do either. */export const devClockAt = (start: DateTime.Utc): Layer.Layer<DevClock> => Layer.effectContext( Effect.gen(function* () { const real = yield* Clock.Clock; let millis = DateTime.toEpochMillis(start); const offset = DateTime.distance(devStart, start);
const nanos = () => BigInt(millis) * NANOS_PER_MILLI; const place = (at: DateTime.Utc) => DateTime.addDuration(at, offset);
// The instant the clock was last stood at, and, once it runs, the // monotonic reading it has run from since. let stood = DateTime.toEpochMillis(start); let runningSince: bigint | undefined;
const elapsedNanos = () => runningSince === undefined ? 0n : real.monotonicTimeNanosUnsafe() - runningSince;
const nanos = () => BigInt(stood) * NANOS_PER_MILLI + elapsedNanos();
const millis = () => Number(nanos() / NANOS_PER_MILLI);
const standAt = (at: number) => { stood = at;
if (runningSince !== undefined) { runningSince = real.monotonicTimeNanosUnsafe(); } };
const clock: Clock.Clock = { currentTimeMillis: Effect.sync(() => millis), currentTimeMillisUnsafe: () => millis, currentTimeMillis: Effect.sync(millis), currentTimeMillisUnsafe: millis, currentTimeNanos: Effect.sync(nanos), currentTimeNanosUnsafe: nanos, // Elapsed time is measured, never seeded. monotonicTimeNanos: real.monotonicTimeNanos, monotonicTimeNanosUnsafe: () => real.monotonicTimeNanosUnsafe(), sleep: (duration) => real.sleep(duration), };
const devClock = DevClock.of({ place, run: Effect.sync(() => { runningSince ??= real.monotonicTimeNanosUnsafe(); }), set: (at) => Effect.sync(() => { millis = DateTime.toEpochMillis(at); standAt(DateTime.toEpochMillis(place(at))); }), step: Effect.sync(() => { if (runningSince !== undefined) { return DateTime.toUtc(DateTime.makeUnsafe(millis())); }
standAt(millis() + Duration.toMillis(Duration.minutes(1)));
return DateTime.toUtc(DateTime.makeUnsafe(stood)); }), });
return Context.make(DevClock, devClock).pipe( Context.add(Clock.Clock, clock)3 unmodified linesmodified:apps/web/src/dev/fixtures.ts+13 added-14 removed
59 unmodified lines60 Schema,61 Semaphore,62 } from "effect";63 64-import { DevClock } from "./clock.ts";64+import { DevClock, devStart } from "./clock.ts";65 import { seedFillers } from "./fixtures/fillers.ts";66 import {67 creditsIn,68 decisionTaken,203 unmodified lines272 return;273 }274 275 yield* write((story) =>276- Effect.gen(function* () {277- const landedAt = DateTime.add(yield* now, { minutes: 1 });278-279- yield* devClock.set(landedAt);280-281- return yield* landLintChild(story, landedAt);282- })276+ Effect.flatMap(devClock.step, (landedAt) =>277+ landLintChild(story, landedAt)278+ )279 );280 }).pipe(Effect.provideService(Clock.Clock, clock)),281 });282 160 unmodified lines443 444 /**445 * The fixtures told into a world the default seed has seeded: the fillers,446 * then vellum (made and first pushed through the service, its record told451- * over its repo), and the world's clock left at the record's morning.447+ * over its repo), and the world's clock left at the record's morning,448+ * `fixturesNow`.449 */450 const seedFixtures = Effect.gen(function* () {451 const fixtures = yield* Fixtures;452 13 unmodified lines466 yield* (yield* DevClock).set(fixturesNow);467 }).pipe(Effect.orDie);468 469 /**473- * A fresh world with the fixtures, seeded: the default seed, then the474- * fixtures. In `live` mode the lint child lands `liveAfter` after vellum's475- * `watch` is first answered.470+ * A fresh world with the fixtures, seeded, its calendar starting at471+ * `start`: the default seed, then the fixtures. In `live` mode the lint472+ * child lands `liveAfter` after vellum's `watch` is first answered.473 */474 export const withFixtures = (475 mode: "on" | "live",479- liveAfter: Duration.Duration = LIVE_AFTER476+ liveAfter: Duration.Duration = LIVE_AFTER,477+ start: DateTime.Utc = devStart478 ) =>479 Layer.effectDiscard(Effect.andThen(seedDev, seedFixtures)).pipe(480 Layer.provideMerge(481 devWorldWith(2 unmodified lines484 fixturesLayer(485 mode === "live" ? Option.some(liveAfter) : Option.none()486 )487 )490- )488+ ),489+ start490 )491 )492 );modified:apps/web/src/dev/seed.ts+16 added-9 removed
8 unmodified lines9 * with the harness disclosed as `Assisted-by:`), people proposing10 * and flagging, the decider declining two, and someone pushing straight to11 * `main`, reported as the push event would be.12 *13- * Each step happens at its own whole minute after the world's start14- * (`devMinute`), so every time the world holds comes from one fixed instant15- * and two seeds give the same world. The world then serves at the last16- * step's minute.13+ * Each step happens at its own whole minute of the world's calendar14+ * (`devMinute`), so every time the world holds comes from one start and15+ * two seeds on the same start give the same world. The world then serves16+ * from the last step's minute, `seedEnd`.17 *18 * What the service can't be brought to through its methods is left out:19 * a `Finish` decision (nothing opens one yet) and an20 * answer refused `OutOfScope` (a refused answer is never recorded).90 unmodified lines111 /** The files of `repo` at `commit`, which the seed itself pushed. */112 const filesOf = (repo: RepoName, commit: CommitSha) =>113 Effect.flatMap(filesAt(repo, commit), Effect.fromOption);114 115-/** Moves the world's clock to `minute` minutes after its start. */115+/** Moves the world's clock to the calendar's minute `minute`. */116 const at = (minute: number) =>117 Effect.flatMap(Effect.service(DevClock), (clock) =>118 clock.set(devMinute(minute))119 );120 121 /**122- * A project made and adopted at `when`: its initializer creates it, pushes123- * its first commit a minute later, and the gateway reports the push.122+ * A project made and adopted at the calendar's instant `when`: its123+ * initializer creates it, pushes its first commit a minute later, and the124+ * gateway reports the push.125 */126 export const startedAt = (127 project: ProjectName,128 initializer: Handle,22 unmodified lines151 152 return { api, landed };153 });154 154-/** A project made and adopted at `minute` minutes after the world's start. */155+/** A project made and adopted at the calendar's minute `minute`. */156 const started = (157 project: ProjectName,158 initializer: Handle,159 files: Files,155 unmodified lines315 started(burrow.project, burrowPeople.decider, burrow.files, 15),316 (api) => opened(api, burrowPeople.decider, burrow.asks, 17)317 );318 319+/** The seed's last minute: the stray push. */320+const STRAY_MINUTE = 21;321+322+/** The calendar's instant the seed leaves the world's clock at. */323+export const seedEnd = devMinute(STRAY_MINUTE);324+325 /**326 * Someone with access to datekit's storage pushes to `main` past the327 * platform, and the push event reports it: a `StrayPush` decision whose328 * default is to revert.2 unmodified lines331 Effect.gen(function* () {332 const host = yield* RepoHost;333 const repo = RepoName.make(datekit.project);334 328- yield* at(21);335+ yield* at(STRAY_MINUTE);336 337 const tip = yield* Effect.fromOption(338 Option.fromNullishOr((yield* host.refs(repo)).get(mainRef))339 );32 unmodified linesmodified:apps/web/src/dev/server.ts+37 added-8 removed
11 unmodified lines12 import { Projects } from "@repo/project/projects";13 import { Contracts } from "@repo/protocol/contracts";14 import { ProjectName } from "@repo/protocol/ids";15 import { Context, Effect, Layer, Option, Schema } from "effect";16-import type { Duration } from "effect";16+import type { DateTime, Duration } from "effect";17 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";18 import { RpcSerialization, RpcServer } from "effect/rpc";19 20+import { DevClock, devStart, startEndingNow } from "./clock.ts";21 import { withFixtures } from "./fixtures.ts";22 import type { FixtureMode } from "./fixtures.ts";23+import { fixturesNow } from "./fixtures/vellum.ts";24 import { devHandlers } from "./handlers.ts";23-import { seedDev } from "./seed.ts";25+import { seedDev, seedEnd } from "./seed.ts";26 import { devSessions } from "./sessions.ts";25-import { devWorld } from "./world.ts";27+import { devWorldAt } from "./world.ts";28 27-/** How a dev world is made: with the fixtures or without, and how soon the live landing comes. */29+/** How a dev world is made: with the fixtures or without, how soon the live landing comes, and when it is. */30 export interface DevWorldOptions {31 readonly fixtures?: FixtureMode;32 /** In `live` mode, how long after vellum's `watch` is first answered its lint child lands. */33 readonly liveAfter?: Duration.Duration;34+ /**35+ * Where the world's time stands. `"fixed"`, as a test builds it: the36+ * calendar as written, from `devStart`, and the clock standing where the37+ * seed left it. `"present"`, as the running dev server builds it: the38+ * calendar moved so the seed's last instant is the minute the world is39+ * built in, and the clock running on from there in real time.40+ */41+ readonly time?: "fixed" | "present";42 }43 34-/** A fresh world, seeded; with the fixtures when `options` asks for them. */35-const seededWorld = (options: DevWorldOptions) => {44+/** The calendar's instant a seed with `fixtures` leaves the clock at. */45+const seedEndOf = (fixtures: FixtureMode) =>46+ fixtures === "off" ? seedEnd : fixturesNow;47+48+/** A fresh world whose calendar starts at `start`, seeded; with the fixtures when `fixtures` asks for them. */49+const seededFrom = (start: DateTime.Utc, options: DevWorldOptions) => {50 const { fixtures = "off" } = options;51 52 return fixtures === "off"39- ? Layer.effectDiscard(seedDev).pipe(Layer.provideMerge(devWorld))40- : withFixtures(fixtures, options.liveAfter);53+ ? Layer.effectDiscard(seedDev).pipe(Layer.provideMerge(devWorldAt(start)))54+ : withFixtures(fixtures, options.liveAfter, start);55 };56 57+/** A fresh world, seeded, at the time `options` asks for. */58+const seededWorld = (options: DevWorldOptions) => {59+ const { fixtures = "off", time = "fixed" } = options;60+61+ return time === "fixed"62+ ? seededFrom(devStart, options)63+ : Layer.unwrap(64+ Effect.map(startEndingNow(seedEndOf(fixtures)), (start) =>65+ Layer.effectDiscard(66+ Effect.flatMap(Effect.service(DevClock), (clock) => clock.run)67+ ).pipe(Layer.provideMerge(seededFrom(start, options)))68+ )69+ );70+};71+72 const decodeProject = Schema.decodeUnknownOption(ProjectName);73 74 /** `/<project>/raw/<rev>/<path…>`: a project's raw files, as the platform serves them. */75 const raw = Layer.unwrap(46 unmodified linesmodified:apps/web/src/dev/world.ts+13 added-8 removed
8 unmodified lines9 * rows (`front-page.ts`); lane logs are kept in memory. A proposal made10 * with a draft is drafted in process as it is made, by the memory drafter11 * scripted with the canned draft (`@repo/drafting/draft-runs/canned`),12 * and goes red first on the scripted Checker. One clock, set by the seed,13- * is the world's time (`clock.ts`).13+ * is the world's time, its calendar starting where the world is told to14+ * (`clock.ts`).15 */16 import type { RepoHost } from "@repo/artifacts/repo-host";17 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";18 import type { EvidenceStore } from "@repo/checks/evidence-store";7 unmodified lines26 import type { Projects } from "@repo/project/projects";27 import { ProjectsMemory } from "@repo/project/projects/memory";28 import { RulesEvaluatorJson } from "@repo/rules/rules-evaluator/json";29 import { Layer } from "effect";30+import type { DateTime } from "effect";31 32 import { DevChecker } from "./checker.ts";33 import { devClockAt, devStart } from "./clock.ts";34 import type { DevClock } from "./clock.ts";23 unmodified lines58 59 /**60 * A fresh world whose front page and handlers read through `between`,61 * which may stand in for the projects and the projected events it is60- * given (the fixtures do, `fixtures.ts`). Built twice, it is two worlds.62+ * given (the fixtures do, `fixtures.ts`), with its calendar starting at63+ * `start`. Built twice, it is two worlds.64 */65 export const devWorldWith = <Out, E, In extends DevCore>(63- between: Layer.Layer<Out, E, In>66+ between: Layer.Layer<Out, E, In>,67+ start: DateTime.Utc = devStart68 ) =>69 Layer.mergeAll(DevFrontPage, EvidenceStoreMemory).pipe(70 Layer.provideMerge(between),71 Layer.provideMerge(core),68- Layer.provideMerge(devClockAt(devStart)),72+ Layer.provideMerge(devClockAt(start)),73 Layer.fresh74 );75 76 /**77 * A fresh, empty world: its projects, the front page over them, the lane78 * logs, the repo host the people's git pushes to, and its clock at75- * `devStart`. Built twice, it is two worlds.79+ * `start`. Built twice, it is two worlds.80 */77-export const devWorld: Layer.Layer<78- Projects | FrontPage | EvidenceStore | RepoHost | DevClock79-> = devWorldWith(Layer.empty);81+export const devWorldAt = (82+ start: DateTime.Utc83+): Layer.Layer<Projects | FrontPage | EvidenceStore | RepoHost | DevClock> =>84+ devWorldWith(Layer.empty, start);modified:apps/web/src/routes/people/$handle.tsx+3 added
9 unmodified lines10 PersonView,11 } from "../../features/people/person-page.tsx";12 import { pageHead } from "../../features/shared/head.ts";13 import { Reading, Unreachable } from "../../features/shared/pending.tsx";14+import { branchPage } from "../../server/cache-headers.ts";15 16 // A person's page: the roles they hold in each project's landings, by area,17 // read once by the browser. An address whose last part cannot be a handle18 // is a 404.20 unmodified lines39 };40 41 export const Route = createFileRoute("/people/$handle")({42 component: PersonPage,43+ // The same for every reader: the credits are read in the browser.44+ headers: () => branchPage,45 head: ({ params }) =>46 pageHead({47 description: `What ${params.handle} is credited for, by project and area.`,48 title: params.handle,12 unmodified linesmodified:apps/web/src/routes/agents.tsx+3 added
5 unmodified lines6 7 import { commands } from "../features/agents/catalog.ts";8 import { AgentsView } from "../features/agents/setup-page.tsx";9 import { pageHead } from "../features/shared/head.ts";10+import { branchPage } from "../server/cache-headers.ts";11 12 // `/agents`: the reference an agent and the person running it read, drawn13 // from `@repo/agent-kit` for this stage's platform and the web's own origin14 // (the router's: the request's on the server, the page's in the browser),12 unmodified lines27 };28 29 export const Route = createFileRoute("/agents")({30 component: AgentsPage,31+ // The same for every reader, and it changes only with a deploy.32+ headers: () => branchPage,33 head: () =>34 pageHead({35 description:36 "How an agent reaches the platform: the CLI's commands, the ways to connect, the endpoints, the limits and the refusals.",3 unmodified linesmodified:apps/web/src/server/cache-headers.ts+9 added
11 unmodified lines12 * finds none), and times reckoned from when it was read. What does not13 * change is kept below the page, by object id (ADR 0019, ADR 0020).14 * - A page about the person reading it (Today, a decision, a proposal) is15 * kept nowhere.16+ *17+ * Workers Cache keeps these at the edge too, shared by every reader, keyed18+ * by path and query and never by cookie (ADR 0026). So a page that gives19+ * `branchPage` reads as nobody: its loader never reaches the reader's20+ * request, and its markup is the same for everyone. The Worker's entry21+ * (`edge-cache.ts`) has the last word on every answer: one to a request22+ * that carries a cookie is kept nowhere whatever its route says, and one23+ * the edge may keep varies by `Cookie`, so it reaches only a reader with24+ * none (`test/edge-cache.test.ts`).25 */26 27 export const branchPage = {28 "Cache-Control": "public, max-age=30, stale-while-revalidate=300",5 unmodified linesadded:apps/web/src/server/edge-cache.ts+138 added
1+/**2+ * What the edge may keep of the web's answers (ADR 0026). Workers Cache3+ * stands in front of the deployed web Worker and keys an answer by its path4+ * and query string alone: not by the host, and not by the `Cookie` or the5+ * `Authorization` a request carries. A request with a cookie is served what6+ * the cache holds for its path, unless the stored answer varies by7+ * `Cookie`; an answer without `Cache-Control` is kept by a heuristic (two8+ * hours for a 200). Every answer the Worker gives passes through9+ * `forTheEdge` (`src/server.ts`), which holds two rules:10+ *11+ * - An answer to a request that carries any cookie or an `Authorization`,12+ * an answer that sets a cookie, and an answer that says nothing of how13+ * long it may be kept, is kept nowhere: `private, no-store`, which the14+ * cache bypasses. So nothing read with a reader's credential is ever15+ * stored, and a route that forgets its headers keeps nothing.16+ * - Any other answer the cache may store varies by `Cookie`: it was made for17+ * a request with no cookie, and is served only to one, so a signed-in18+ * reader is never handed a page kept from a signed-out one.19+ *20+ * `CDN-Cache-Control` and `Cloudflare-CDN-Cache-Control` would outrank21+ * `Cache-Control` at the edge; the web sets neither, and drops any an22+ * answer it passes on carries.23+ */24+import { Effect } from "effect";25+26+/** The `Cache-Control` of an answer kept by nobody: no shared cache, no browser. */27+export const KEPT_NOWHERE = "private, no-store";28+29+/** Headers that would decide what the edge keeps over `Cache-Control`. */30+const EDGE_OVERRIDES = ["cdn-cache-control", "cloudflare-cdn-cache-control"];31+32+/** The directives of a `Cache-Control` value, each as `name` or `name=value`, lower-cased. */33+const directivesOf = (cacheControl: string) =>34+ cacheControl35+ .split(",")36+ .map((directive) => directive.trim().toLowerCase())37+ .filter((directive) => directive !== "");38+39+/** Whether the request says who is reading it: any cookie, or an `Authorization`. */40+const speaksForSomeone = (request: Request) =>41+ request.headers.has("cookie") || request.headers.has("authorization");42+43+/**44+ * Whether `cacheControl` must be replaced by `KEPT_NOWHERE`: it is missing,45+ * or it names a field (`private="set-cookie"`, `no-cache="…"`), the form46+ * that lets the cache store the answer with that field stripped.47+ */48+const unsafeFor = (cacheControl: string | null) =>49+ cacheControl === null ||50+ directivesOf(cacheControl).some(51+ (directive) =>52+ directive.startsWith("private=") || directive.startsWith("no-cache=")53+ );54+55+/** Whether the cache bypasses an answer under `cacheControl`. */56+const keptNowhere = (cacheControl: string) =>57+ directivesOf(cacheControl).some(58+ (directive) => directive === "private" || directive === "no-store"59+ );60+61+/** `vary` with `Cookie` among its headers. */62+const varyingByCookie = (vary: string | null) => {63+ const names = (vary ?? "")64+ .split(",")65+ .map((name) => name.trim())66+ .filter((name) => name !== "");67+68+ return names.some((name) => name.toLowerCase() === "cookie")69+ ? names.join(", ")70+ : [...names, "Cookie"].join(", ");71+};72+73+/** `response`'s headers as the edge may see them, for `request`. */74+const edgeHeaders = (request: Request, response: Response) => {75+ const headers = new Headers(response.headers);76+77+ for (const name of EDGE_OVERRIDES) {78+ headers.delete(name);79+ }80+81+ const cacheControl = headers.get("cache-control");82+83+ if (84+ speaksForSomeone(request) ||85+ headers.has("set-cookie") ||86+ unsafeFor(cacheControl)87+ ) {88+ headers.set("cache-control", KEPT_NOWHERE);89+90+ return headers;91+ }92+93+ if (cacheControl !== null && !keptNowhere(cacheControl)) {94+ headers.set("vary", varyingByCookie(headers.get("vary")));95+ }96+97+ return headers;98+};99+100+/**101+ * `response` as the edge may keep it, for `request`: the same status and102+ * body (a stream stays a stream), under the two rules above.103+ */104+export const forTheEdge = (request: Request, response: Response): Response =>105+ new Response(response.body, {106+ headers: edgeHeaders(request, response),107+ status: response.status,108+ statusText: response.statusText,109+ });110+111+/** A Worker's `fetch`, as TanStack Start's server entry gives it. */112+interface Entry<Rest extends readonly unknown[]> {113+ readonly fetch: (114+ request: Request,115+ ...rest: Rest116+ ) => Promise<Response> | Response;117+}118+119+/** The Worker's `fetch` once every answer passes through `forTheEdge`. */120+interface EdgeEntry<Rest extends readonly unknown[]> {121+ readonly fetch: (request: Request, ...rest: Rest) => Promise<Response>;122+}123+124+/**125+ * `entry` with every answer it gives passed through `forTheEdge`; its other126+ * arguments (the Worker's env and context) go on to it untouched.127+ */128+export const edgeEntry = <Rest extends readonly unknown[]>(129+ entry: Entry<Rest>130+): EdgeEntry<Rest> => ({131+ fetch: (request, ...rest) =>132+ Effect.runPromise(133+ Effect.map(134+ Effect.promise(() => Promise.resolve(entry.fetch(request, ...rest))),135+ (response) => forTheEdge(request, response)136+ )137+ ),138+});added:apps/web/src/server.ts+11 added
1+/**2+ * The web Worker's entry (`wrangler.jsonc`'s `main`): TanStack Start's own3+ * server entry, with every answer it gives passed through `forTheEdge`, so4+ * what the edge's cache may keep is decided in one place for pages, server5+ * functions, server routes, redirects and errors alike (ADR 0026).6+ */7+import handler from "@tanstack/react-start/server-entry";8+9+import { edgeEntry } from "./server/edge-cache.ts";10+11+export default edgeEntry(handler);modified:apps/web/test/dev-fixtures.test.ts+130 added
20 unmodified lines21 import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";22 import { RpcClient, RpcSerialization } from "effect/rpc";23 24 import { askStates, familyMarks } from "../src/client/events.ts";25+import type { FixtureMode } from "../src/dev/fixtures.ts";26+import { fixturesNow } from "../src/dev/fixtures/vellum.ts";27+import { seedEnd } from "../src/dev/seed.ts";28 import type { DevWorldOptions } from "../src/dev/server.ts";29 import { devServer } from "../src/dev/server.ts";30 import { devToken } from "../src/dev/sessions.ts";31 691 unmodified lines723 })724 )725 );726 });727+728+/** `at`'s distance from `from`, in milliseconds. */729+const millisFrom = (from: DateTime.DateTime, at: DateTime.DateTime) =>730+ Duration.toMillis(DateTime.distance(from, at));731+732+/**733+ * The open decisions ines-v takes across her projects, and two instants734+ * the world stamps on what it makes, a little apart: its present then.735+ */736+const timesIn = (options: DevWorldOptions) =>737+ inWorld(options, (as) =>738+ Effect.gen(function* () {739+ const ines = yield* as(signedIn("ines-v"));740+ const { decisions } = yield* ines.today({});741+742+ const proposedAt = (handle: string, want: string) =>743+ Effect.flatMap(as(signedIn(handle)), (client) =>744+ Effect.map(745+ client.proposeAsk({ project: ProjectName.make("datekit"), want }),746+ ({ proposal }) => proposal.openedAt747+ )748+ );749+750+ const first = yield* proposedAt("tove", "datekit prints ISO weeks.");751+752+ yield* Effect.sleep(Duration.millis(20));753+754+ const second = yield* proposedAt("sefa", "datekit reads RFC 2822 dates.");755+756+ return { decisions, first, second };757+ })758+ );759+760+/**761+ * A fixed world stands at the calendar's `end` once seeded; a world at762+ * the present has every instant moved by one whole number of minutes, so763+ * `end` is the minute it was built in, and its clock runs on from there,764+ * with every decision still to come.765+ */766+const placedAtThePresent = (fixtures: FixtureMode, end: DateTime.Utc) =>767+ Effect.gen(function* () {768+ const fixed = yield* timesIn({ fixtures });769+770+ expect([fixed.first, fixed.second]).toStrictEqual([end, end]);771+772+ const before = DateTime.startOf(yield* DateTime.now, "minute");773+ const present = yield* timesIn({ fixtures, time: "present" });774+ const after = yield* DateTime.now;775+776+ const shift = millisFrom(777+ fixed.decisions[0]?.openedAt ?? end,778+ present.decisions[0]?.openedAt ?? end779+ );780+781+ const unshifted = (at: DateTime.Utc) =>782+ DateTime.subtractDuration(at, Duration.millis(shift));783+784+ expect(present.decisions.length).toBeGreaterThan(0);785+ expect(786+ present.decisions.map(({ expiresAt, id, openedAt }) => [787+ id,788+ unshifted(openedAt),789+ unshifted(expiresAt),790+ ])791+ ).toStrictEqual(792+ fixed.decisions.map(({ expiresAt, id, openedAt }) => [793+ id,794+ openedAt,795+ expiresAt,796+ ])797+ );798+ expect(shift % Duration.toMillis(Duration.minutes(1))).toBe(0);799+800+ const anchor = DateTime.addDuration(end, Duration.millis(shift));801+802+ expect([803+ millisFrom(before, anchor) >= 0,804+ millisFrom(anchor, DateTime.startOf(after, "minute")) >= 0,805+ millisFrom(anchor, present.first) >= 0,806+ millisFrom(present.first, present.second) > 0,807+ millisFrom(present.second, after) >= 0,808+ present.decisions.every(809+ ({ expiresAt }) => millisFrom(present.second, expiresAt) > 0810+ ),811+ ]).toStrictEqual([true, true, true, true, true, true]);812+ });813+814+describe("the dev world's time", seededWorlds, () => {815+ it.live(816+ "ends the default seed at the present minute and runs on from it",817+ () => placedAtThePresent("off", seedEnd)818+ );819+820+ it.live(821+ "ends the fixtures' story at the present minute and runs on from it",822+ () => placedAtThePresent("on", fixturesNow)823+ );824+825+ it.live("lands the live child at the present on a running clock", () =>826+ Effect.gen(function* () {827+ const before = yield* DateTime.now;828+829+ const landed = yield* inWorld(830+ { fixtures: "live", liveAfter: Duration.zero, time: "present" },831+ (as) =>832+ Effect.gen(function* () {833+ const anyone = yield* as();834+835+ yield* eventsOf(anyone);836+837+ return closedIn(yield* eventsOf(anyone)).find(838+ (event) => event.ask === "retire-old-tokenizer-vellum-lint"839+ );840+ })841+ );842+843+ const after = yield* DateTime.now;844+845+ expect(landed).toBeDefined();846+ expect([847+ millisFrom(DateTime.startOf(before, "minute"), landed?.at ?? before) >=848+ 0,849+ millisFrom(landed?.at ?? after, after) >= 0,850+ ]).toStrictEqual([true, true]);851+ })852+ );853+});added:apps/web/test/edge-cache.test.ts+415 added
1+/**2+ * What the edge's cache may keep of the web's answers (ADR 0026). Workers3+ * Cache keys an answer by its path and query alone, never by the cookie a4+ * request carries, so the Worker's entry decides for every answer: one to a5+ * request that carries a cookie or an `Authorization`, one that sets a6+ * cookie, and one that says nothing of how long it may be kept, is kept7+ * nowhere; any other the cache may store varies by `Cookie`, so it is served8+ * only to a request with none. And no page the cache may keep reads who is9+ * reading it: only a page kept nowhere reaches the reader's request.10+ */11+import { describe, expect, it } from "@effect/vitest";12+import { Client, Contracts } from "@repo/protocol/contracts";13+import { ProjectName } from "@repo/protocol/ids";14+import { asTester, unanswered } from "@repo/protocol/testing";15+import { untouchable } from "@repo/testkit/untouchable";16+import { Effect, Layer } from "effect";17+import { RpcTest } from "effect/rpc";18+19+import { forwarded } from "../src/features/agents/forward.ts";20+import { backend } from "../src/server/backend.ts";21+import { branchPage, personalPage } from "../src/server/cache-headers.ts";22+import {23+ edgeEntry,24+ forTheEdge,25+ KEPT_NOWHERE,26+} from "../src/server/edge-cache.ts";27+import { frontPageHandler } from "../src/server/front-page.ts";28+import { frontLlmsHandler, projectLlmsHandler } from "../src/server/llms.ts";29+import { rpcHandler } from "../src/server/rpc.ts";30+import { SESSION_COOKIE } from "../src/server/session.ts";31+32+const WEB_URL = "https://web-test.example.workers.dev";33+34+const PLATFORM_URL = "https://platform-test.example.workers.dev";35+36+/** A signed-in reader's cookie, as the browser sends it. */37+const SIGNED_IN = `${SESSION_COOKIE}=dev-ada`;38+39+/** A GET for `path` on the web host, with `headers`. */40+const get = (path: string, headers: HeadersInit = {}) =>41+ new Request(`${WEB_URL}${path}`, { headers });42+43+/** What the edge sees of an answer: how long it may be kept, and what it varies by. */44+const kept = (response: Response) => ({45+ cacheControl: response.headers.get("cache-control"),46+ vary: response.headers.get("vary"),47+});48+49+/** An answer under `headers`, with a body. */50+const answer = (headers: HeadersInit, status = 200) =>51+ new Response("the page", { headers, status });52+53+/** Every `Cache-Control` the web gives or passes on, and none. */54+const ANSWERS: readonly (readonly [string, HeadersInit])[] = [55+ ["a page at main", branchPage],56+ ["a page about its reader", personalPage],57+ ["an agent's document", { "cache-control": "public, max-age=60" }],58+ [59+ "a raw file at a commit",60+ { "cache-control": "public, max-age=31536000, immutable" },61+ ],62+ ["a sign-in redirect", { "cache-control": "no-store" }],63+ ["an answer with no Cache-Control", {}],64+];65+66+describe("an answer to a request that says who is reading", () => {67+ it.each(ANSWERS)(68+ "is kept nowhere, given a session cookie: %s",69+ (_, headers) => {70+ expect(71+ kept(72+ forTheEdge(get("/datekit", { cookie: SIGNED_IN }), answer(headers))73+ ).cacheControl74+ ).toBe(KEPT_NOWHERE);75+ }76+ );77+78+ it.each(ANSWERS)("is kept nowhere, given any cookie: %s", (_, headers) => {79+ expect(80+ kept(81+ forTheEdge(get("/datekit", { cookie: "theme=dark" }), answer(headers))82+ ).cacheControl83+ ).toBe(KEPT_NOWHERE);84+ });85+86+ it.each(ANSWERS)(87+ "is kept nowhere, given an Authorization: %s",88+ (_, headers) => {89+ expect(90+ kept(91+ forTheEdge(92+ get("/datekit", { authorization: "Bearer dev-ada" }),93+ answer(headers)94+ )95+ ).cacheControl96+ ).toBe(KEPT_NOWHERE);97+ }98+ );99+});100+101+describe("an answer to a request with no cookie", () => {102+ it("is kept nowhere when it sets a cookie", () => {103+ expect(104+ kept(105+ forTheEdge(106+ get("/auth/whoami"),107+ answer({108+ ...branchPage,109+ "set-cookie": `${SESSION_COOKIE}=; Max-Age=0`,110+ })111+ )112+ ).cacheControl113+ ).toBe(KEPT_NOWHERE);114+ });115+116+ it("is kept nowhere when it says nothing of how long it may be kept", () => {117+ // Without it, the cache would keep a 200 for two hours by its heuristic.118+ expect(kept(forTheEdge(get("/_serverFn/x"), answer({})))).toStrictEqual({119+ cacheControl: KEPT_NOWHERE,120+ vary: null,121+ });122+ });123+124+ it.each([`private="set-cookie"`, `public, no-cache="set-cookie"`])(125+ "is kept nowhere when its Cache-Control names a field to strip: %s",126+ (cacheControl) => {127+ expect(128+ kept(forTheEdge(get("/"), answer({ "cache-control": cacheControl })))129+ .cacheControl130+ ).toBe(KEPT_NOWHERE);131+ }132+ );133+134+ it("keeps a page at main as the route says, varied by Cookie", () => {135+ expect(136+ kept(forTheEdge(get("/datekit/tree/main"), answer(branchPage)))137+ ).toStrictEqual({138+ cacheControl: branchPage["Cache-Control"],139+ vary: "Cookie",140+ });141+ });142+143+ it("adds Cookie to what an answer already varies by, once", () => {144+ expect(145+ [146+ { ...branchPage, vary: "Accept" },147+ { ...branchPage, vary: "Accept, cookie" },148+ ].map((headers) => kept(forTheEdge(get("/"), answer(headers))).vary)149+ ).toStrictEqual(["Accept, Cookie", "Accept, cookie"]);150+ });151+152+ it("keeps a page about its reader nowhere, as the route says", () => {153+ expect(kept(forTheEdge(get("/today"), answer(personalPage)))).toStrictEqual(154+ {155+ cacheControl: personalPage["Cache-Control"],156+ vary: null,157+ }158+ );159+ });160+161+ it("drops the headers that would outrank Cache-Control at the edge", () => {162+ const response = forTheEdge(163+ get("/releases/manifest.json"),164+ answer({165+ ...branchPage,166+ "cdn-cache-control": "public, max-age=86400",167+ "cloudflare-cdn-cache-control": "public, max-age=86400",168+ })169+ );170+171+ expect([172+ response.headers.get("cdn-cache-control"),173+ response.headers.get("cloudflare-cdn-cache-control"),174+ ]).toStrictEqual([null, null]);175+ });176+177+ it.effect("comes back with its status, its other headers and its body", () =>178+ Effect.gen(function* () {179+ const response = forTheEdge(180+ get("/nowhere"),181+ answer({ ...branchPage, "content-type": "text/html" }, 404)182+ );183+184+ expect({185+ body: yield* Effect.promise(() => response.text()),186+ contentType: response.headers.get("content-type"),187+ status: response.status,188+ }).toStrictEqual({189+ body: "the page",190+ contentType: "text/html",191+ status: 404,192+ });193+ })194+ );195+});196+197+describe("the Worker's entry", () => {198+ it.effect(199+ "hands the request and the Worker's env and context to Start, and its answer to the edge's rule",200+ () =>201+ Effect.gen(function* () {202+ const handed: unknown[] = [];203+204+ const entry = edgeEntry({205+ fetch: (request: Request, env: string, context: string) => {206+ handed.push(request.url, env, context);207+208+ return Promise.resolve(answer(branchPage));209+ },210+ });211+212+ const response = yield* Effect.promise(() =>213+ entry.fetch(get("/", { cookie: SIGNED_IN }), "env", "context")214+ );215+216+ expect(handed).toStrictEqual([`${WEB_URL}/`, "env", "context"]);217+ expect(kept(response).cacheControl).toBe(KEPT_NOWHERE);218+ })219+ );220+221+ it("is Start's server entry wrapped by edgeEntry, and nothing else", () => {222+ const sources: Readonly<Record<string, string>> = import.meta.glob(223+ "../src/server.ts",224+ { eager: true, import: "default", query: "?raw" }225+ );226+227+ const code = (sources["../src/server.ts"] ?? "")228+ .replaceAll(/\/\*\*[\s\S]*?\*\//gu, "")229+ .trim();230+231+ expect(code.split(/\n+/u)).toStrictEqual([232+ 'import handler from "@tanstack/react-start/server-entry";',233+ 'import { edgeEntry } from "./server/edge-cache.ts";',234+ "export default edgeEntry(handler);",235+ ]);236+ });237+});238+239+// --- The routes that read the reader's credential ----------------------------240+241+/** A platform that lists datekit and no asks, and answers nothing else. */242+const listingDatekit = () =>243+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(244+ Layer.provide([245+ Layer.mergeAll(246+ unanswered,247+ Contracts.toLayerHandler("listProjects", () =>248+ Effect.succeed({249+ projects: [250+ {251+ openAsks: 0,252+ posture: "open" as const,253+ project: ProjectName.make("datekit"),254+ },255+ ],256+ })257+ ),258+ Contracts.toLayerHandler("listAsks", () => Effect.succeed({ asks: [] }))259+ ),260+ asTester,261+ ])262+ );263+264+/** An env whose PLATFORM answers every request with a long-lived public answer. */265+const platformEnv: Env = {266+ PLATFORM: untouchable<Fetcher>("PLATFORM", {267+ fetch: () =>268+ Promise.resolve(269+ answer({ "cache-control": "public, max-age=31536000, immutable" })270+ ),271+ }),272+ PUBLIC_PLATFORM_URL: PLATFORM_URL,273+};274+275+/**276+ * Each server route that hands the reader's cookie on (to the platform, as277+ * its credential), by the request it answers. Each answers a public278+ * `Cache-Control` of its own; the entry is what keeps a reader's answer279+ * from the edge.280+ */281+const CREDENTIAL_ROUTES: readonly (readonly [282+ string,283+ (request: Request) => Promise<Response>,284+])[] = [285+ [286+ "/llms.txt",287+ (request) => frontLlmsHandler(listingDatekit, PLATFORM_URL)({ request }),288+ ],289+ [290+ "/datekit/llms.txt",291+ (request) =>292+ projectLlmsHandler(293+ listingDatekit,294+ PLATFORM_URL295+ )({ params: { project: "datekit" }, request }),296+ ],297+ [298+ "/",299+ (request) =>300+ Promise.resolve(301+ frontPageHandler(302+ listingDatekit,303+ PLATFORM_URL304+ )({305+ next: () => answer(branchPage),306+ request,307+ })308+ ),309+ ],310+ [311+ "/datekit/raw/main/README.md",312+ (request) => forwarded(backend, platformEnv).GET({ request }),313+ ],314+ [315+ "/rpc",316+ (request) =>317+ rpcHandler(318+ backend,319+ platformEnv320+ )({ request: new Request(request, { body: "{}", method: "POST" }) }),321+ ],322+];323+324+/** A signed-in agent's request for `path`, as Markdown. */325+const signedInAt = (path: string) =>326+ get(path, { accept: "text/markdown", cookie: SIGNED_IN });327+328+describe("a route that hands the reader's cookie on", () => {329+ it.effect.each(CREDENTIAL_ROUTES)(330+ "%s is kept nowhere when a session cookie comes with it",331+ ([path, handle]) =>332+ Effect.gen(function* () {333+ const own = yield* Effect.promise(() => handle(signedInAt(path)));334+335+ // The route alone would let a shared cache keep it.336+ expect(own.headers.get("cache-control")).toMatch(/^public\b/u);337+338+ const served = yield* Effect.promise(() =>339+ edgeEntry({ fetch: handle }).fetch(signedInAt(path))340+ );341+342+ expect(kept(served).cacheControl).toBe(KEPT_NOWHERE);343+ })344+ );345+346+ it.effect.each(CREDENTIAL_ROUTES)(347+ "%s, with no cookie, is kept as it says and varied by Cookie",348+ ([path, handle]) =>349+ Effect.gen(function* () {350+ const served = yield* Effect.promise(() =>351+ edgeEntry({ fetch: handle }).fetch(352+ get(path, { accept: "text/markdown" })353+ )354+ );355+356+ expect(kept(served).cacheControl).toMatch(/^public\b/u);357+ expect(kept(served).vary).toMatch(/\bCookie$/u);358+ })359+ );360+});361+362+// --- The pages ---------------------------------------------------------------363+364+const routeSources: Readonly<Record<string, string>> = import.meta.glob(365+ "../src/routes/**/*.{ts,tsx}",366+ { eager: true, import: "default", query: "?raw" }367+);368+369+const allSources: Readonly<Record<string, string>> = import.meta.glob(370+ "../src/**/*.{ts,tsx}",371+ { eager: true, import: "default", query: "?raw" }372+);373+374+/**375+ * Where a page's loader or server function reaches the request it answers376+ * (its cookie, its headers): TanStack Start's server helpers.377+ */378+const readsTheRequest = /from "@tanstack\/react-start\/server"/u;379+380+describe("a page", () => {381+ it("reads the reader's request only where it is kept nowhere", () => {382+ const reading = Object.entries(allSources).flatMap(([path, source]) =>383+ readsTheRequest.test(source) ? [path] : []384+ );385+386+ expect(reading.toSorted()).toStrictEqual([387+ "../src/routes/$project/decisions/$decision.tsx",388+ "../src/routes/today.tsx",389+ ]);390+391+ for (const path of reading) {392+ const source = routeSources[path] ?? "";393+394+ expect(source, `${path} is kept nowhere`).toContain("personalPage");395+ expect(source, `${path} is never kept at main`).not.toContain(396+ "branchPage"397+ );398+ }399+ });400+401+ it("that the edge may keep reads as nobody, so its markup is the same for every reader", () => {402+ const keepable = Object.entries(routeSources).filter(([, source]) =>403+ source.includes("branchPage")404+ );405+406+ expect(keepable.length).toBeGreaterThan(10);407+408+ for (const [path, source] of keepable) {409+ expect(source, `${path} reaches no request`).not.toMatch(readsTheRequest);410+ expect(source, `${path} reads no cookie`).not.toMatch(411+ /credentialFrom|SESSION_COOKIE|HANDLE_COOKIE/u412+ );413+ }414+ });415+});modified:apps/web/worker-configuration.d.ts+4 added-1 removed
1 /* eslint-disable */2-// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: da1857314b335dfd1203e75276309d10)2+// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: aa7c6db610447e5e6e68b0fe0dbbcb47)3 interface __BaseEnv_Env {4 PUBLIC_PLATFORM_URL: string;5 PLATFORM: Fetcher /* platform-dev-oscabriel */ | Fetcher /* platform-demo */ | Fetcher /* platform */;6 }7 declare namespace Cloudflare {8+ interface GlobalProps {9+ mainModule: typeof import("./src/server");10+ }11 interface DevOscabrielEnv {12 PUBLIC_PLATFORM_URL: string;13 PLATFORM: Fetcher /* platform-dev-oscabriel */;14 }13 unmodified linesmodified:apps/web/wrangler.jsonc+11 added-3 removed
8 unmodified lines9 //10 // The top level is stage `local`: `vite dev` and the type generation read11 // it, and it is never deployed. Each stage under `env` repeats the binding12 // and the vars, since wrangler does not inherit them into an environment.13+ //14+ // Workers Cache is on in each deployed stage, and off at the top, so `vite15+ // dev` keeps nothing (ADR 0026). It keys by the Worker's version, so each16+ // deploy starts cold and a kept page never names another version's hashed17+ // assets: `cross_version_cache` stays off.18 "$schema": "node_modules/wrangler/config-schema.json",19 "name": "web",15- // TanStack Start's own server entry (the Cloudflare framework guide); the16- // Cloudflare Vite plugin builds it.17- "main": "@tanstack/react-start/server-entry",20+ // TanStack Start's own server entry, wrapped so every answer passes21+ // through what the edge may keep (src/server/edge-cache.ts; the Cloudflare22+ // framework guide's custom entrypoint). The Cloudflare Vite plugin builds it.23+ "main": "src/server.ts",24 "compatibility_date": "2026-10-05",25 "compatibility_flags": ["nodejs_compat"],26 "workers_dev": true,27 "preview_urls": false,8 unmodified lines36 "PUBLIC_PLATFORM_URL": "http://localhost:8787",37 },38 "env": {39 "dev-oscabriel": {40+ "cache": { "enabled": true },41 "services": [42 { "binding": "PLATFORM", "service": "platform-dev-oscabriel" },43 ],44 "vars": {45 "PUBLIC_PLATFORM_URL": "https://platform-dev-oscabriel.oscargabriel.workers.dev",46 },47 },48 "demo": {49+ "cache": { "enabled": true },50 "services": [{ "binding": "PLATFORM", "service": "platform-demo" }],51 "vars": {52 "PUBLIC_PLATFORM_URL": "https://platform-demo.oscargabriel.workers.dev",53 },3 unmodified linesadded:docs/adr/0026-the-edge-keeps-the-webs-anonymous-answers.md+37 added
1+---2+status: accepted3+---4+5+# The edge keeps the web's anonymous answers, and nothing read for a reader6+7+The web Worker runs behind Workers Cache in each deployed stage (`"cache": { "enabled": true }` in `apps/web/wrangler.jsonc`'s `dev-oscabriel` and `demo` blocks; the top-level `local` stage, which `vite dev` reads, has none). A page the cache holds comes back from the edge without running the Worker, at the `Cache-Control` the page already gives: `branchPage` (`public, max-age=30, stale-while-revalidate=300`) for the pages at `main`, a tag or a commit, `public, max-age=60` for the agents' documents, and the platform's own headers on what the web passes on (raw files, releases, the install script).8+9+Workers Cache keys an answer by the Worker's entrypoint, path, query string and version, and by none of the host, the `Cookie` or the `Authorization` (<https://developers.cloudflare.com/workers/cache/cache-keys/>). It bypasses a request with an `Authorization`, an answer with `Set-Cookie`, and an answer marked `private` or `no-store`. It does not bypass a request that carries a cookie, it honours `Vary` by storing one variant per verbatim value of each named request header, and an answer with no `Cache-Control` is kept by a heuristic: two hours for a 200, three minutes for a 404 (<https://developers.cloudflare.com/workers/cache/configuration/>). So a page whose markup depended on its reader would be handed to everyone, and a route that forgot its headers would be kept for hours.10+11+The web holds that off in one place. `wrangler.jsonc`'s `main` is `apps/web/src/server.ts`: TanStack Start's own server entry, with every answer it gives (pages, server functions, server routes, redirects and errors) passed through `forTheEdge` (`apps/web/src/server/edge-cache.ts`):12+13+- An answer to a request that carries any cookie or an `Authorization`, an answer that sets a cookie, an answer with no `Cache-Control`, and one whose `private` or `no-cache` names a field to strip, is `private, no-store`, which the cache bypasses. Nothing read with a reader's credential is stored.14+- Any other answer the cache may store varies by `Cookie`. It was made for a request with no cookie, and the cache serves it only to a request with none, so a signed-in reader never receives a page kept from a signed-out one, and the browser's own cache drops it when a session begins or ends.15+- `CDN-Cache-Control` and `Cloudflare-CDN-Cache-Control`, which outrank `Cache-Control` at the edge, are dropped.16+17+The pages keep a rule their loaders already followed (`apps/web/src/server/front-page.ts` reads "as the anonymous viewer reads it"): a page the edge may keep reads as nobody. Its loader calls `serverClient(env)` without the request, and only the pages kept nowhere (Today and a decision, `personalPage`) reach the reader's request through Start's server helpers. The rail's signed-in state and Today's count are read in the browser after hydration. So the markup of a `branchPage` page is the same for every reader, and the `Vary` above is a second wall, not the only one.18+19+`apps/web/test/edge-cache.test.ts` holds it: the rule for every kind of answer the web gives, the entry as Start's handler wrapped and nothing else, each server route that hands the reader's cookie on (`/llms.txt`, a project's `llms.txt`, `/` as Markdown, a raw file, `/rpc`) kept nowhere when a session cookie comes with it, and the pages that read the request being exactly the `personalPage` ones. `packages/config/test/web-wiring.test.ts` holds the config: the entry, the cache on in each stage and off at the top, and no `cross_version_cache`.20+21+## Considered Options22+23+- **No Workers Cache.** Nothing to hold, but every page view runs the Worker and its platform reads; a page at a commit, which never changes, costs as much as one at `main`.24+- **A cookie-reading gateway entrypoint with the cache off, forwarding cookie-less requests to a cached inner entrypoint over `ctx.exports`** (Cloudflare's own pattern for authenticated traffic, <https://developers.cloudflare.com/workers/cache/examples/>). Every request would run the gateway, and it needs a second entrypoint in a Worker that TanStack Start's build owns. The `Vary: Cookie` rule gives the same separation inside one entrypoint.25+- **Bypassing only on the session cookie.** More hits for a reader who carries some other cookie, but every cookie the web sets would have to be weighed; the web's readers carry none until they sign in.26+- **`private` with the page's own `max-age` for a signed-in reader**, so their browser could still keep a page. Kept simple instead: `private, no-store` is what the cookie fence checks.27+- **`cross_version_cache`.** Pages would survive a deploy, but a kept page names the hashed assets of the version that drew it.28+29+## Consequences30+31+- Cost: with caching on, every request to the web Worker is billed at the standard request rate, including the static asset requests (`/assets/*`, icons, fonts) and the service-binding calls that are free without it (<https://developers.cloudflare.com/workers/cache/>). A hit runs no CPU.32+- Cost: an answer is held to the Free plan's cacheable size, whatever the account's plan, while that launch limit lasts, and purges run at the Free tier's rate (<https://developers.cloudflare.com/workers/cache/limitations/>).33+- A signed-in reader, and anyone who carries a cookie, always runs the Worker and keeps nothing in the browser; the edge serves signed-out readers and agents.34+- A page at `main` may be served by the edge up to 30 seconds old, and up to five minutes more while one request refreshes it in the background, now to every reader rather than one browser. Purging on a landing would have to run inside the web Worker (`ctx.cache.purge`), since a purge belongs to the entrypoint that owns the answer; nothing purges yet.35+- Each deploy starts the cache cold, since the version is in the key.36+- The host is not in the key: an answer that names its own origin (the agents' documents' `webUrl`) is kept for whichever host asked first. Each stage's web answers on one `workers.dev` host today; a custom domain beside it would share one cache.37+- After a deploy, `curl -sI <web>/<project>/tree/main` twice shows `cf-cache-status: MISS` then `HIT` and `vary: Cookie`; the same request with `-H 'cookie: a=b'` shows `cache-control: private, no-store` and no `HIT`.modified:packages/config/test/web-wiring.test.ts+24 added
158 unmodified lines159 );160 }161 })162 );163+164+ // ADR 0026: the edge keeps the web's answers only behind its entry, which165+ // decides what may be kept; `vite dev` keeps nothing; and a kept page166+ // never outlives its Worker version, whose hashed assets it names.167+ it.effect(168+ "enters through src/server.ts, and turns Workers Cache on in each stage alone, per version",169+ () =>170+ Effect.gen(function* () {171+ const config = yield* presentJson("apps/web/wrangler.jsonc", Wrangler);172+ const top = yield* presentJson("apps/web/wrangler.jsonc", Block);173+174+ expect(top.main).toBe("src/server.ts");175+ expect("cache" in top, "the local stage keeps nothing").toBeFalsy();176+177+ for (const stage of stages) {178+ expect(179+ config.env[stage]?.cache,180+ `${stage} keeps answers`181+ ).toStrictEqual({182+ enabled: true,183+ });184+ }185+ })186+ );187 });188 189 describe("the web Worker's generated Env", () => {190 it.effect("has PLATFORM as a Fetcher and nothing named ARTIFACTS…", () =>91 unmodified linesmodified:README.md+1 added-1 removed
81 unmodified lines82 ```sh83 bun run --cwd apps/web dev84 ```85 86-`vite dev` resolves the web's `#backend` import to `apps/web/src/dev/backend.ts`: every contract served in process over memory adapters, seeded with the two fictional example projects, `examples/datekit/` and `examples/burrow/`. It answers on `http://127.0.0.1:3032`, pinned in `apps/web/vite.config.ts`; a `CADDY_DEV_HOST` in a gitignored `.env.development.local` beside it (not `.env`, which Wrangler would load as a Worker secret) also lets a reverse proxy serve it under that name, with hot reload over `wss`. `/auth/dev?handle=ines-v` signs you in as datekit's fictional decider.86+`vite dev` resolves the web's `#backend` import to `apps/web/src/dev/backend.ts`: every contract served in process over memory adapters, seeded with the two fictional example projects, `examples/datekit/` and `examples/burrow/`. It answers on `http://127.0.0.1:3032`, pinned in `apps/web/vite.config.ts`; a `CADDY_DEV_HOST` in a gitignored `.env.development.local` beside it (not `.env`, which Wrangler would load as a Worker secret) also lets a reverse proxy serve it under that name, with hot reload over `wss`. `/auth/dev?handle=ines-v` signs you in as datekit's fictional decider. The seed is written on a fixed calendar; the dev server moves it so the seed's last step is the minute it starts, then lets its clock run in real time, so deadlines read as the seed meant them on any day (tests keep the calendar as written, with the clock standing still).87 88 To see every state a page can draw (each outcome, a family's fan mid-way, every kind of decision, a sealed ledger, a set env value, drafted proposals), add the dev fixtures: a fictional project, `vellum`, told as a story through the same service, and six small projects beside it. `live` also lands one family child about 20 s after a vellum page first reads it, so a page open on it shows the landing as it happens:89 90 ```sh303 unmodified lines