Skip to content
Myr

Merge build/comments-web-rest into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 74bfc72, 6c40d07 · Browse files · 199 files+128 added−3188 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

199 files+128 added−3188 removed

  • tests:+22 added−845 removed
  • other:+106 added−2343 removed

199 files+128 added−3188 removed

This commit is too large to show whole: its files are listed by path, without their changes.

modified:apps/web/e2e/a11y.e2e.ts+5 added-64 removed
1/**2 * Every page of the web, as a browser and a keyboard reach it, in both3 * colour schemes at 1440 and 390 px wide:4 *5 * - axe-core finds no serious or critical violation (it is loaded from6 * cdnjs into the page at run time, so no package is added for it);7 * - no page scrolls sideways at 390 or 360;8 * - no word the web keeps off its screens (review, approve, merge, queue,9 * …) appears in its own chrome; text that comes from a repository or a10 * person (a README, code, a diff, a want, a brief, a commit message, a11 * note, a refusal's own text) is left out by the marker its view sets;12 * - the keyboard: the skip link is the first stop and lands on main; focus13 * shows on every stop; the rail, the toolbar's filters, a row's copy14 * button and the inspector's commands come in that order; `?` opens the15 * keys dialog, whose switch turns `j`/`k` off; `j`/`k` move the16 * selection on the front page and Today; `J`/`K` move between files on a17 * commit and a finish; `1` copies the inspector's first command; every18 * sheet keeps focus inside it and gives it back to its button on Escape.19 *20 * It runs only against `WEB_URL`, the web's dev world with its fixtures21 * (`VITE_DEV_FIXTURES=1 bun run dev -- --port <port>`): the pages it visits22 * are the fixture project's, and it signs in through the dev world's own23 * `/auth/dev`. `A11Y_PROJECT` names the fixture project by its full name24 * (`oscabriel/vellum` unless given). It only reads, but for the keys switch, kept in this browser.25 */1import { expect, test } from "@playwright/test";2import type { Browser, BrowserContext, Page } from "@playwright/test";3import { Brand } from "@repo/brand";4import { Config, Effect, Option } from "effect";
18 unmodified lines
2324const at = (path: string) =>25 `${Option.getOrElse(settings.web, () => "")}${path}`;2652/** The decider the dev world signs in. */27const DECIDER = "ines-v";2855/** A page to visit: where, whether a decider must be signed in, what it answers. */29interface Visit {30 readonly name: string;31 readonly path: string;32 readonly signedIn?: boolean;33 readonly status?: number;34}3563/**64 * The commit page's address comes from the landings page (its SHA is the65 * dev world's), so it is visited by name and found at run time: the newest66 * ask opening, which changes two files or more (the ask and its check).67 */36// Its SHA is the dev world's, so it is found at run time from the landings page.37const COMMIT = "<the newest ask opening>";3870/** Every page group, over the fixture project's states. */39const VISITS: readonly Visit[] = [40 { name: "landing", path: "/" },41 { name: "front", path: "/asks" },42 { name: "front, signed in", path: "/asks", signedIn: true },
79 unmodified lines
122const SCHEMES = ["light", "dark"] as const;123124const WIDTHS = [1440, 390] as const;125158/**159 * Words the web keeps off its screens, matched whole and in any case160 * ("merged tree" passes; "merge" does not).161 */126// Matched whole and in any case: "merged tree" passes, "merge" does not.127const FORBIDDEN =128 /\b(?:review|reviewer|approve|approval|PR|pull request|issue|merge|lease|reputation|inbox|queue|dashboard|explore|trending|nit)\b/iu;129165/**166 * Text a repository or a person wrote, which the web shows as given: the167 * views mark each such block (`data-said` for a want, a brief, a commit's168 * subject or body, a note). A refusal's own text comes from the one169 * renderer every surface shares (`data-refusal`), and the gate's own names170 * for its stages ("Merge") are the protocol's (`data-term`).171 */130// Text a repository or a person wrote, which its view marks; the forbidden words are not looked for there.131const NOT_OURS =132 "[data-readme], [data-code], [data-diff], [data-said], [data-refusal], [data-term], script, style, noscript";133175/** A context for `scheme` at `width`, signed in as the decider when asked. */134const contextFor = (135 browser: Browser,136 scheme: (typeof SCHEMES)[number],137 width: number,
17 unmodified lines
155156 return context;157 });158201/** The newest landing's commit page, read from the landings page. */159const commitPath = (context: BrowserContext) =>160 Effect.gen(function* () {161 const page = yield* Effect.promise(() => context.newPage());162
10 unmodified lines
173174 return href ?? `/${project}/commits/main`;175 });176220/** Open `path` and let the browser take the page over. */177const open = (page: Page, path: string) =>178 Effect.gen(function* () {179 const response = yield* Effect.promise(() =>180 page.goto(at(path), { waitUntil: "load" })181 );182227 // The page hydrates, then its client reads settle (lists, the tree).183 // The page hydrates, then its client reads settle.184 yield* Effect.promise(() => page.waitForTimeout(1500));185186 return response?.status();187 });188233/** The page's own words that the web keeps off its screens. */189const forbiddenOn = (page: Page) =>190 Effect.promise(() =>191 page.evaluate(192 ({ forbidden, notOurs }) => {
101 unmodified lines
294 ));295 }296});297343/** What has focus: its tag, its name, and the landmark it sits in. */298const focused = (page: Page) =>299 Effect.promise(() =>300 page.evaluate(() => {301 // Focus inside a drawing's shadow root (a code box, the file tree) is
12 unmodified lines
314315 const style = getComputedStyle(element);316 const after = getComputedStyle(element, "::after");317364 // Where the stop sits, first match wins.318 const places = [319 ["[role=dialog]", "dialog"],320 ["nav[aria-label=Site]", "rail"],321 ["[data-toolbar]", "toolbar"],
9 unmodified lines
331 label: (element.getAttribute("aria-label") ?? element.textContent ?? "")332 .trim()333 .slice(0, 60),334 tag: element.tagName.toLowerCase(),382 // The ring: an outline, a row link's outline drawn on its ::after,383 // or the kit's box-shadow ring.335 visible:336 (style.outlineStyle !== "none" && style.outlineWidth !== "0px") ||337 (after.outlineStyle !== "none" && after.outlineWidth !== "0px") ||338 style.boxShadow !== "none",339 };340 })341 );342392/**393 * Tab through the page, up to `limit` stops, and what each stop was;394 * `settle` waits after each press (a sheet's trap moves focus in the next395 * frame).396 */343// `settle` waits after each press: a sheet's focus trap moves focus in the next frame.344const tabStops = (page: Page, limit: number, settle = 0) =>345 Effect.gen(function* () {346 const stops: NonNullable<Effect.Success<ReturnType<typeof focused>>>[] = [];347
15 unmodified lines
363364 return stops;365 });366420/** A page on its own context, for a keyboard walk. */367const keyboardPage = (368 browser: Browser,369 path: string,370 width: number,
25 unmodified lines
396397 test("the skip link comes first, lands on main, and every stop shows its focus", ({398 browser,399 }) => {454 // Every page, each tabbed through: far longer than one page's check.400 test.setTimeout(VISITS.length * 30_000);401402 return Effect.runPromise(403 Effect.gen(function* () {
54 unmodified lines
458 Effect.runPromise(459 Effect.gen(function* () {460 const { context, page } = yield* keyboardPage(browser, "/asks", 1440);461517 // A row selected, so the inspector holds its commands; then the518 // same address again, tabbed from its start.462 yield* Effect.promise(() => page.keyboard.press("j"));463 yield* Effect.promise(() => page.waitForTimeout(500));464 yield* open(465 page,
59 unmodified lines
525 yield* Effect.promise(() => page.waitForTimeout(400));526527 expect(searchOf(page).get(param)).toBe(firstSelected);528586 // The switch: off, `j` does nothing; `?` still opens the dialog.529 yield* Effect.promise(() => page.keyboard.press("?"));530531 const dialog = page.getByRole("dialog", { name: "Keys" });532
35 unmodified lines
568 );569570 const ask = searchOf(page).get("ask") ?? "";571630 // The selected row's own claim command, as its copy button holds it.572 const command = yield* Effect.promise(() =>573 page574 .locator(`li[data-ask="${ask}"] button code`)575 .first()
108 unmodified lines
modified:apps/web/e2e/axe.ts-10 removed
1/**2 * What the browser checks share: axe's serious and critical violations on a3 * page, and how far a page scrolls sideways. `a11y.e2e.ts` runs them over4 * every page; `landing.e2e.ts` adds the landing at 360 px.5 */1import type { Page } from "@playwright/test";2import { Effect, Schema } from "effect";39/** axe-core, from cdnjs, at the version this check was written against. */4const AXE = "https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.10.2/axe.min.js";512/** What axe's `run` resolves to, as much of it as this check reads. */6const AxeRun = Schema.Struct({7 violations: Schema.Array(8 Schema.Struct({9 id: Schema.String,
6 unmodified lines
16});1718const decodeAxeRun = Schema.decodeUnknownEffect(AxeRun);1927/** axe's serious and critical violations on the page, as `rule (n): targets`. */20export const axeOn = (page: Page) =>21 Effect.gen(function* () {22 yield* Effect.promise(() => page.addScriptTag({ url: AXE }));2332 // axe's results come from the page: decoded here, as any outside input.24 const raw: unknown = yield* Effect.promise(() =>25 page.evaluate("axe.run()")26 );27
9 unmodified lines
37 .join(", ")}`38 );39 });4050/** How far the page scrolls sideways, in px; 0 when it does not. */41export const sideways = (page: Page) =>42 Effect.promise(() =>43 page.evaluate(44 () =>
4 unmodified lines
modified:apps/web/e2e/command-line.e2e.ts-16 removed
1/**2 * The command line's layout, as a browser lays it out: a word never breaks3 * while its row has room for it, on a phone or a desk. A line's first row4 * has the box's whole width; a row the column breaks off hangs, and has the5 * box's width less the hang (a URL longer than that still breaks,6 * anywhere). A short command once broke its own words (`<cli> today` read7 * "tod" / "<cli> ay"): its box hugged the line, and the 6ch hang left its8 * last word too little room.9 *10 * It runs only against `WEB_URL` (a stage's web origin, or a `vite dev`11 * with the dev fixtures) and is skipped without it. It only reads, signed12 * out.13 */1import { expect, test } from "@playwright/test";2import { Config, Effect, Option } from "effect";317/** Where the web lives. */4const web = Effect.runSync(5 Config.option(Config.NonEmptyString("WEB_URL")).pipe(6 Effect.map(Option.map((url) => url.replace(/\/+$/u, "")))7 )8);924/** Pages that show command lines to a reader who is not signed in. */10const PAGES = ["/today", "/home", "/agents"];1112const WIDTHS = [390, 1280];13
36 unmodified lines
50 );5152 const word = span.getBoundingClientRect();5369 // Its own width on one row: set it so, read it, set it back.54 span.style.whiteSpace = "pre";55 span.style.maxWidth = "none";56 const natural = span.getBoundingClientRect().width;57 span.style.whiteSpace = "";
31 unmodified lines
modified:apps/web/e2e/deployed.e2e.ts+3 added-48 removed
1/**2 * The deployed web, as a browser shows it: the front page, a3 * project's page, an ask's page and the same ask as Markdown,4 * `/llms.txt`, and the project's code (a folder, a file at a line, the5 * log, a commit and the refs), each asserted on its key text, each saved6 * as one screenshot in `e2e/out/` for the shot list.7 *8 * It runs only against `WEB_URL` (a stage's web origin) and is skipped9 * without it. `WEB_PROJECT` picks the project (datekit unless given) and10 * `WEB_ASK` the ask, `WEB_FILE` the file opened at line 3 (its first folder11 * is the one the code page must list) and `WEB_README_PHRASE` a phrase of12 * the project's README, which its page must carry as the server sends it.13 * Each defaults to the seeded example's own (`examples`: datekit's14 * format-ordinal, `src/add.ts` and opening words; burrow's15 * drop-legacy-fetch, `packages/kit/src/http.ts` and "six small TypeScript16 * packages"), so `WEB_PROJECT=burrow` alone checks burrow. It only reads.17 */1import { expect, test } from "@playwright/test";2import type { Page } from "@playwright/test";3import { ProjectName } from "@repo/protocol/ids";4import { Config, Effect, Option } from "effect";523/**24 * What the check looks at in each seeded example unless told otherwise: an25 * ask the seed opens, a file whose first folder the code page lists, and a26 * phrase of its README.27 */6const examples = {7 burrow: {8 ask: "drop-legacy-fetch",9 file: "packages/kit/src/http.ts",
5 unmodified lines
15 readme: "Small, dependency-free date helpers",16 },17} as const;1841/** What the check reads of its env: where the web lives, and which ask to look at. */19const settings = Effect.runSync(20 Effect.gen(function* () {44 // Read by the one parser: `burrow` and `oscabriel/burrow` alike.21 const project = yield* Config.schema(ProjectName, "WEB_PROJECT").pipe(22 Config.withDefault(ProjectName.make("oscabriel/datekit"))23 );24
20 unmodified lines
45);4647const { ask, file: FILE, project, readme: README_PHRASE } = settings;4873/** The root folder `FILE` sits in, which the project's code page lists. */49const FOLDER = FILE.split("/")[0] ?? FILE;5076/** Where each page's screenshot goes: `e2e/out/<shot>.png`. */51const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);5279/** What every page that could not reach the platform says instead of its content. */53const UNREACHABLE = "The platform did not answer";5482/** What a code page said before its view was built; a deployed page never says it. */55const NOT_BUILT = "not built";5685/** `url` on the web. */57const at = (path: string) =>58 `${Option.getOrElse(settings.web, () => "")}${path}`;5989/**90 * Opens `path` as a page, waits for each of `texts` on screen, checks the91 * platform answered it, and saves the screenshot `shot`. A text may also sit92 * in markup a width hides (the facts render once as the inspector and once93 * inline, and a folded family keeps its children's rows), so each text is94 * found among the visible matches.95 */60// A text may also sit in markup a width hides, so each is found among the visible matches.61const page = (62 browser: Page,63 path: string,64 shot: string,
23 unmodified lines
88 browser.screenshot({ fullPage: true, path: `${out}${shot}.png` })89 );90 });91127/** A code page: as `page` checks one, and it never says it is not built. */92const code = (93 browser: Page,94 path: string,95 shot: string,
6 unmodified lines
102 expect(browser.getByText(NOT_BUILT)).toHaveCount(0)103 );104 });105142/**143 * Fetches `path` as Markdown, checks it opens with a title and holds each144 * of `texts`, and saves a screenshot of it, shown as plain text.145 */106const markdown = (107 browser: Page,108 path: string,109 shot: string,
36 unmodified lines
146 Option.isNone(settings.web),147 "WEB_URL is not set: point it at a deployed web's origin to run this check"148 );149190 // The heading renders before the platform answers, so each list page also191 // waits for a row only the platform's answer holds: until then the page192 // shows placeholders, and "did not answer" can't have appeared yet.150 // The heading renders before the platform answers, so each list page also waits for a row only the answer holds.151 test("the front page lists the open asks", ({ page: browser }) =>152 Effect.runPromise(153 page(browser, "/", "front-page", ["Open asks", project])154 ));
2 unmodified lines
157 Effect.runPromise(158 page(browser, `/${project}`, "project-page", [project, ask])159 ));160203 // A request, not a page: no browser script runs, so this is the HTML the204 // server sent, as a crawler or `curl` reads it.161 // A request, not a page: this is the HTML the server sent, as a crawler reads it.162 test(`${project}'s page arrives with its README rendered by the server`, ({163 page: browser,164 }) =>165 Effect.runPromise(
45 unmodified lines
211 expect(new URL(browser.url()).hash).toBe("#L3");212 })213 ));214258 // The landings are grouped under one heading per day, each naming its259 // date in words ("October 7, 2026") over that day's commits.215 test(`${project}'s log groups its commits by day`, ({ page: browser }) =>216 Effect.runPromise(217 Effect.gen(function* () {218 yield* code(browser, `/${project}/commits/main`, "code-log", [
41 unmodified lines
modified:apps/web/e2e/import.e2e.ts-17 removed
1/**2 * A web import, as a browser does it: signed in, `/import?url=<repo>`3 * fills the form (owner and name from the URL), Import runs it, the page4 * says "Importing…" while the platform clones, and lands on the project's5 * page, which names where it was imported from. Saved as6 * `e2e/out/import.png`.7 *8 * It runs only when `WEB_IMPORT_URL` names a tiny public repo to import9 * (an HTTPS clone URL) and `WEB_URL` a web's origin, and is skipped10 * otherwise. It signs in with `WEB_SESSION`, a session token for the11 * stage, or, without one, through the dev world's own `/auth/dev` as12 * `WEB_IMPORT_AS` (oscabriel unless given). `WEB_IMPORT_NAME` names the13 * project instead of the URL's last segment, so a second run does not meet14 * `ProjectExists`. It writes: each run makes a project.15 */1import { expect, test } from "@playwright/test";2import { Config, Effect, Option, Redacted } from "effect";34const settings = Effect.runSync(
12 unmodified lines
17 };18 })19);2036/** Where the screenshot goes: `e2e/out/import.png`. */21const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);2239/** An import clones the repo: up to half a minute, and some margin. */23const IMPORTING = 90_000;2425test.describe("a web import", () => {26 test.skip(
73 unmodified lines
modified:apps/web/e2e/imports.e2e.ts-83 removed
1/**2 * The open-source repos imported onto a dev stage (`scripts/import-examples.ts`),3 * as a browser shows them: for each project its home page (README rendered,4 * clone box), a nested folder, a file at line 5, the log, the newest5 * commit, the refs, the people and why each line of that file is there,6 * each asserted on its key text and saved as one screenshot under7 * `e2e/out/imports/<project>/`. Then what each repo was picked to8 * exercise: ky's lowercase `readme.md` and its SVG logo through raw,9 * awesome's relative links, changesets' deep tree and scoped tags, stb's10 * 730 KB header and a PNG, fuzzel's submodule, click's second log page and11 * anyhow's annotated tags. The first view of `tree`, `why` and12 * `commits?path=` on changesets and click is timed and printed. The thirty13 * well-known imports after them each show their home with its README, the14 * root folder, a file at line 5, the log, and why that file's lines are15 * there.16 *17 * It runs only against `WEB_URL` (a dev stage's web origin) and is skipped18 * without it. `WEB_IMPORTS` narrows it to some projects, a comma list of19 * full names (`github.com/pallets/click`), for a run while the imports go20 * in one at a time. Every address it visits or expects is the project's21 * full name (ADR 0032). It only reads.22 */1import { expect, test } from "@playwright/test";2import type { Page } from "@playwright/test";3import { Brand } from "@repo/brand";4import { ProjectName } from "@repo/protocol/ids";5import { Config, Console, Effect, Option, Schema } from "effect";629/** One imported project: where its pages look, and what they must show. */7interface Imported {8 readonly project: string;32 /** A phrase of its README, as the home page renders it. */9 readonly readme: string;34 /** A folder at least two levels down. */10 readonly dir: string;36 /** An entry of `dir`, listed on its page. */11 readonly entry: string;38 /** A text file of at least five lines. */12 readonly file: string;40 /**41 * Whether its policy evaluated: an import with no config folder takes the42 * defaults, and its run block from its CI; where the finder finds no test43 * command there, the policy never evaluates and the people page says so.44 */13 readonly evaluated: boolean;14}1548/** The eight imports, in the order the script imports them. */16const imports: readonly Imported[] = [17 {18 dir: "tests/ui",19 entry: "tests/ui/chained-comparison.rs",
34 unmodified lines
54 project: "awesome",55 readme: "Programming Languages",56 },57 {91 // Six folders down; its file is the seventh level.58 dir: "packages/cli/src/commands/status/__tests__",59 entry: "packages/cli/src/commands/status/__tests__/status.test.ts",60 evaluated: true,61 file: "packages/cli/src/index.ts",
17 unmodified lines
79 readme: "Fuzzel is a Wayland-native application launcher",80 },81];82117/** One of the well-known imports: a file at its root of at least five lines, and its README's name. */83interface Known {84 readonly project: string;85 readonly file: string;86 readonly readme: string;87}88124/** The thirty well-known imports, in the order the script imports them. */89const known: readonly Known[] = [90 { file: "package.json", project: "hono", readme: "README.md" },91 { file: "package.json", project: "express", readme: "Readme.md" },92 { file: "package.json", project: "fastify", readme: "README.md" },
25 unmodified lines
118 { file: "Gemfile", project: "sinatra", readme: "README.md" },119 { file: "package.json", project: "nvm", readme: "README.md" },120];121158/** What the check reads of its env: where the web lives, and which imports to visit. */122const settings = Effect.runSync(123 Effect.gen(function* () {124 return {125 only: yield* Config.option(Config.NonEmptyString("WEB_IMPORTS")),
4 unmodified lines
130 };131 })132);133171/**172 * A project's full name, read by the one parser (ADR 0032): an import's173 * key from before owners (`click`) reads as its source path174 * (`github.com/pallets/click`), and a full name as itself.175 */134const nameOf = (spelled: string): ProjectName =>135 Schema.decodeSync(ProjectName)(spelled);136179/** `text` as a regular expression matches it, literally. */137const escaped = (text: string) =>138 text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");139183/** A project's address on the web: its full name. */140const homeOf = (project: string) => `/${nameOf(project)}`;141186/**187 * Those of `all` this run visits: `WEB_IMPORTS`' full names188 * (`github.com/pallets/click`), or all of them.189 */142const visitedOf = <A extends { readonly project: string }>(143 all: readonly A[]144): readonly A[] =>145 Option.match(settings.only, {
8 unmodified lines
154 });155156const visited = visitedOf(imports);157206/** Where screenshots go: `e2e/out/imports/<project>/<shot>.png`. */158const out = decodeURIComponent(159 new URL("out/imports/", import.meta.url).pathname160);161211/** What a page says when the platform did not answer it. */162const UNREACHABLE = "The platform did not answer";163214/** What a code page said before its view was built. */164const NOT_BUILT = "not built";165217/** What the router's error boundary says when a page throws. */166const CRASHED = "Something went wrong";167220/** `path` on the web. */168const at = (path: string) =>169 `${Option.getOrElse(settings.web, () => "")}${path}`;170171const awaited = <A>(promise: () => Promise<A>) => Effect.promise(promise);172226/** The page says none of the things a broken page says. */173const whole = (browser: Page) =>174 Effect.forEach(175 [UNREACHABLE, NOT_BUILT, CRASHED],176 (text) => awaited(() => expect(browser.getByText(text)).toHaveCount(0)),
7 unmodified lines
184 path: `${out}${project}/${shot}.png`,185 })186 );187242/**243 * Opens `path`, checks it answered 200, waits for each of `texts` and244 * `selectors`, checks it is whole, and saves the screenshot `shot`.245 */188const visit = (189 browser: Page,190 project: string,191 path: string,
25 unmodified lines
217 yield* whole(browser);218 yield* shoot(browser, project, shot);219 });220279/**280 * The first view of `path`, timed from the request until the network is281 * quiet (the browser's own reads, the file tree's included) and `selector`282 * shows; printed and kept as an annotation.283 */221const timed = (222 browser: Page,223 project: string,224 path: string,
24 unmodified lines
249 yield* whole(browser);250 yield* shoot(browser, project, shot);251 });252316/** An image on the page has loaded its bytes. */253const loaded = (browser: Page, selector: string) =>254 awaited(() =>255 expect256 .poll(() =>
6 unmodified lines
263 )264 .toBeGreaterThan(0)265 );266331/** The newest commit's page, as the log links it. */267const newestCommit = (browser: Page, project: string) =>268 Effect.gen(function* () {269 const response = yield* awaited(() =>270 browser.goto(at(`${homeOf(project)}/commits/main`))
13 unmodified lines
284285 return href ?? "";286 });287353/**354 * A project's home: its README rendered, and the facts' Take part steps,355 * which clone it with plain git. The facts render inline and in the356 * inspector, one of them hidden at each width, so the visible one is asked.357 */288const homeWanted = (project: string, readme: string) => ({289 selectors: [290 "[data-readme]",291 `section[aria-label="Take part"]:visible:has-text("${homeOf(project)}.git")`,292 ],293 texts: [readme],294});295366/** The pages every import shows. */296const pages = ({ dir, entry, evaluated, file, project, readme }: Imported) => {297 const timedProject = project === "changesets" || project === "click";298299 test(`${project}'s home renders its README and the clone box`, ({
147 unmodified lines
447 ));448 }449};450522/** The pages each well-known import shows. */451const knownPages = ({ file, project, readme }: Known) => {452 test(`${project}'s home renders its ${readme}`, ({ page: browser }) =>453 Effect.runPromise(454 visit(
45 unmodified lines
500 })501 ));502};503576/** What each repo was picked to exercise. */504const specifics = new Map<string, (browser: Page) => Effect.Effect<void>>([505 [506 "anyhow",507 (browser) =>508 Effect.gen(function* () {582 // Annotated tags, listed peeled to their commits: a tag's tree opens.583 // The newest come first, a hundred a page: 1.0.0 is on the second.509 yield* visit(510 browser,511 "anyhow",512 `${homeOf("anyhow")}/refs?from=100`,
23 unmodified lines
536 [537 "awesome",538 (browser) =>539 Effect.gen(function* () {615 // The 78 KB README renders, its relative links pinned to a commit.540 yield* visit(browser, "awesome", homeOf("awesome"), "readme-links", {541 texts: ["Contribution guide", "Front-End Development"],542 });543
15 unmodified lines
559 [560 "changesets",561 (browser) =>562 Effect.gen(function* () {639 // Seven levels down: the deepest folder's file opens.563 yield* visit(564 browser,565 "changesets",566 `${homeOf("changesets")}/blob/main/packages/cli/src/commands/status/__tests__/status.test.ts`,567 "deep-file",568 { texts: ["Permalink"] }569 );570648 // Scoped tags (`@changesets/cli@…`), on whichever page of 100 holds one.571 let from = 0;572 let found = false;573574 while (!found && from < 1000) {
37 unmodified lines
612 [613 "click",614 (browser) =>615 Effect.gen(function* () {694 // Past the first 30 commits, by Older.616 yield* visit(617 browser,618 "click",619 `${homeOf("click")}/commits/main`,
16 unmodified lines
636 [637 "fuzzel",638 (browser) =>639 Effect.gen(function* () {719 // A gitlink lists as a submodule, with no page of its own.640 yield* visit(641 browser,642 "fuzzel",643 `${homeOf("fuzzel")}/tree/main/external`,
12 unmodified lines
656 [657 "ky",658 (browser) =>659 Effect.gen(function* () {740 // Lowercase `readme.md`, and its SVG logo shown through raw.660 yield* visit(browser, "ky", homeOf("ky"), "readme-logo", {661 selectors: ['[data-readme="readme.md"]'],662 });663
5 unmodified lines
669 [670 "stb",671 (browser) =>672 Effect.gen(function* () {754 // A 730 KB header opens, cut or drawn, never a crash.673 yield* visit(674 browser,675 "stb",676 `${homeOf("stb")}/blob/main/tests/caveview/glext.h`,677 "large-file",678 { texts: ["glext.h"] }679 );680763 // A PNG shows as an image.681 yield* visit(682 browser,683 "stb",684 `${homeOf("stb")}/blob/main/data/easy_font_raw.png`,
41 unmodified lines
modified:apps/web/e2e/landing.e2e.ts+1 added-16 removed
1/**2 * The landing as a first-time reader meets it in a browser: the page as3 * sent names its projects, so a reader with no script sees them; its first4 * action takes them to the open asks; and on the narrowest phone it scrolls5 * nothing sideways and axe finds no serious or critical violation, in6 * either scheme.7 * `a11y.e2e.ts` checks it with every other page at 1440 and 390 px.8 *9 * It runs only against `WEB_URL` (a stage's web origin, or a `vite dev`10 * with the dev fixtures) and is skipped without it. It only reads, signed11 * out.12 */1import { expect, test } from "@playwright/test";2import { Config, Effect, Option } from "effect";34import { axeOn, sideways } from "./axe.ts";518/** Where the web lives. */6const web = Effect.runSync(7 Config.option(Config.NonEmptyString("WEB_URL")).pipe(8 Effect.map(Option.map((url) => url.replace(/\/+$/u, "")))9 )10);1112const at = (path: string) => `${Option.getOrElse(web, () => "")}${path}`;1327/** The narrowest phone the web is drawn for. */14const NARROWEST = 360;1516test.describe("the landing", () => {17 test.skip(18 Option.isNone(web),19 "WEB_URL is not set: point it at a web's origin to run this check"20 );2136 // A seeded stage, or the dev world: a platform with no project yet sends37 // an empty list, which is a page of its own and not this check's.22 // A platform with no project yet sends an empty list, which is a page of its own.23 test("names its projects in the page as sent, before any script runs", ({24 page,25 }) =>26 Effect.runPromise(
51 unmodified lines
modified:apps/web/e2e/people.e2e.ts-15 removed
1/**2 * The deployed Policy page (`/<project>/people`), as a browser shows it: who decides which paths3 * and the commit the config is read at, saved as `e2e/out/people.png` for4 * the shot list.5 *6 * It runs only against `WEB_URL` (a stage's web origin) and is skipped7 * without it. `WEB_PROJECT` picks the project (datekit, which the seed puts8 * on every stage, unless given). It only reads.9 */1import { expect, test } from "@playwright/test";2import { ProjectName } from "@repo/protocol/ids";3import { Config, Effect, Option } from "effect";414/** What the check reads of its env: where the web lives, and which project to look at. */5const settings = Effect.runSync(6 Effect.gen(function* () {7 return {18 // Read by the one parser: `datekit` and `oscabriel/datekit` alike.8 project: yield* Config.schema(ProjectName, "WEB_PROJECT").pipe(9 Config.withDefault(ProjectName.make("oscabriel/datekit"))10 ),11 web: Option.map(
5 unmodified lines
17);1819const { project } = settings;2032/** Where the screenshot goes: `e2e/out/people.png`. */21const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);2235/** What every page that could not reach the platform says instead of its content. */23const UNREACHABLE = "The platform did not answer";2425test.describe("the deployed policy page", () => {26 test.skip(
13 unmodified lines
40 );4142 expect(response?.status()).toBe(200);4357 // The page reads Policy, and its deciders: their heading and at58 // least the whole-repo glob's row.44 yield* Effect.promise(() =>45 expect(46 browser.getByRole("heading", { level: 1, name: "Policy" })47 ).toBeVisible()
26 unmodified lines
modified:apps/web/e2e/tags.e2e.ts-23 removed
1/**2 * A monorepo's tags on a deployed web, as a browser shows them: the refs3 * page's first view lists the packages the tags version, `@changesets/cli`4 * among them; its link lists that package's tags alone, newest first; and5 * the first one's tree opens. The package's page is saved as6 * `e2e/out/tags.png` for the shot list.7 *8 * It runs only against `WEB_URL` (a stage's web origin) and is skipped9 * without it. `WEB_TAGS_PROJECT` picks the project by its full name10 * (`github.com/changesets/changesets`, which `scripts/import-examples.ts`11 * puts on a dev stage, unless given). It only12 * reads.13 */1import { expect, test } from "@playwright/test";2import { ProjectName } from "@repo/protocol/ids";3import { Config, Effect, Option } from "effect";418/** What the check reads of its env: where the web lives, and which project to look at. */5const settings = Effect.runSync(6 Effect.gen(function* () {7 return {22 // Read by the one parser: `changesets` and its full name alike.8 project: yield* Config.schema(ProjectName, "WEB_TAGS_PROJECT").pipe(9 Config.withDefault(ProjectName.make("github.com/changesets/changesets"))10 ),11 web: Option.map(
5 unmodified lines
17);1819const { project } = settings;2036/** The package whose tags the check follows. */21const PACKAGE = "@changesets/cli";2239/** Where the screenshot goes: `e2e/out/tags.png`. */23const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);2442/** What every page that could not reach the platform says instead of its content. */25const UNREACHABLE = "The platform did not answer";2627const awaited = <A>(promise: () => Promise<A>) => Effect.promise(promise);2847/** A tag's release numbers (`@changesets/cli@2.27.1` → 2, 27, 1). */29const numbersOf = (tag: string) =>30 (tag.slice(tag.lastIndexOf("@") + 1).match(/\d+/gu) ?? [])31 .slice(0, 3)32 .map(Number);3353/** `one` is no older than `other` by their first three numbers. */34const noOlder = (one: readonly number[], other: readonly number[]) => {35 const at = one.findIndex((value, index) => value !== (other[index] ?? 0));3637 return at === -1 || (one[at] ?? 0) > (other[at] ?? 0);
17 unmodified lines
55 );5657 expect(response?.status()).toBe(200);5879 // The first view: the package list, holding the package.59 const row = browser.locator(`[data-package="${PACKAGE}"]`);6061 yield* awaited(() => expect(row).toBeVisible());62
4 unmodified lines
67 expect(href).toBe(68 `/${project}/refs?package=${encodeURIComponent(PACKAGE)}`69 );7092 // Its link: that package's tags alone, newest first.71 yield* awaited(() => browser.goto(`${web}${href ?? ""}`));7273 const tags = browser.locator("[data-tag]");74
22 unmodified lines
97 yield* awaited(() =>98 browser.screenshot({ fullPage: true, path: `${out}tags.png` })99 );100123 // The newest tag's tree opens.101 const tree = yield* awaited(() =>102 tags.first().locator("a").first().getAttribute("href")103 );104
17 unmodified lines
modified:apps/web/e2e/why.e2e.ts-22 removed
1/**2 * The deployed "why" page, as a browser shows it: a file a landing changed,3 * with at least one row linking an ask, saved as `e2e/out/why.png` for the4 * shot list. The ask a landing answers counts, and so does the ask an5 * opening opened ("Open ask <id>"), so a project whose landings are only6 * openings (burrow, or demo's datekit, where nothing is answered) passes on7 * an opening's file.8 *9 * It runs only against `WEB_URL` (a stage's web origin) and is skipped10 * without it. `WEB_PROJECT` picks the project (datekit, which the seed puts11 * on every stage, unless given) and `WEB_WHY_PATH` the file: datekit's12 * `src/format.ts` unless given, and burrow's own opening's file, the config13 * folder's `asks/drop-legacy-fetch.ask.ts`, for `WEB_PROJECT=burrow` (per14 * stage, an opening's file such as datekit's `asks/format-ordinal.ask.ts`15 * where nothing was answered). It only reads.16 */1import { expect, test } from "@playwright/test";2import { Brand } from "@repo/brand";3import { ProjectName } from "@repo/protocol/ids";4import { Config, Effect, Option } from "effect";522/** What the check reads of its env: where the web lives, and which file to look at. */6const settings = Effect.runSync(7 Effect.gen(function* () {25 // Read by the one parser: `burrow` and `oscabriel/burrow` alike.8 const project = yield* Config.schema(ProjectName, "WEB_PROJECT").pipe(9 Config.withDefault(ProjectName.make("oscabriel/datekit"))10 );11
15 unmodified lines
27);2829const { path, project } = settings;3049/** Where the screenshot goes: `e2e/out/why.png`. */31const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);3252/** What every page that could not reach the platform says instead of its content. */33const UNREACHABLE = "The platform did not answer";3435test.describe("the deployed why page", () => {36 test.skip(
13 unmodified lines
50 );5152 expect(response?.status()).toBe(200);5374 // A group's band, among the server's lines or above the drawn75 // ones, linking the ask its landing answered or opened.54 yield* Effect.promise(() =>55 expect(56 browser.locator(`[data-range] a[href^="/${project}/asks/"]`).first()57 ).toBeVisible()
12 unmodified lines
modified:apps/web/scripts/route-tree.ts+2 added-10 removed
1/**2 * Writes `src/routeTree.gen.ts`, TanStack Router's generated route tree,3 * without a build: resolving the Vite config runs the TanStack Start plugin's4 * generator (its `configResolved` hook), and writes nothing else.5 *6 * The tree is never committed (the route issues run in parallel and would7 * conflict on it), so whatever reads the app's types generates it first:8 * this package's `typecheck`, and the root's `check` and `fix`, whose lint is9 * type-aware.10 */1// Writes `src/routeTree.gen.ts` without a build: resolving the Vite config runs the TanStack Start plugin's generator.2// The tree is not committed, so typecheck, check and fix run this first.3import { resolveConfig } from "vite";45await resolveConfig(6 {
5 unmodified lines
modified:apps/web/src/client/answer.ts-9 removed
1/**2 * An answer's atoms (the data pattern in `src/surfaces.ts`): the verdict on3 * an ask's latest answer (or the one at `head`), and the landing a landed4 * answer made. A judged or landed answer changes its ask's keys, so both5 * refetch then. The answer page seeds them with the data its loader read6 * on the server.7 */1import type {2 AskId,3 CommitSha,4 LandedSha,
2 unmodified lines
78import { ContractsClient } from "../surfaces.ts";9import { keys } from "./keys.ts";1018/** The verdict on the ask's latest answer, or on the answer whose head is `head`. */11export const verdictAtom = (12 project: ProjectName,13 ask: AskId,14 head?: CommitSha
3 unmodified lines
18 head === undefined ? { ask, project } : { ask, head, project },19 { reactivityKeys: keys.ask(project, ask) }20 );2130/** The landing at `sha`, with its credit trailers. */22export const landingAtom = (project: ProjectName, sha: LandedSha) =>23 ContractsClient.query(24 "landing",25 { project, sha },
2 unmodified lines
modified:apps/web/src/client/ask.ts+1 added-12 removed
1/**2 * An ask's atoms (the data pattern in `src/surfaces.ts`): `showAsk` over the3 * browser's `/rpc`, keyed so that a write that changes the ask (a claim, a4 * landing) refetches it. The ask page seeds this atom with the data its5 * loader read on the server, so it fetches only when its keys change.6 */1import type { AskId, ProjectName } from "@repo/protocol/ids";2import { AsyncResult, Atom } from "effect/reactivity";34import { ContractsClient } from "../surfaces.ts";5import { keys } from "./keys.ts";613/** The ask and its brief. */7export const askAtom = (project: ProjectName, ask: AskId) =>8 ContractsClient.query(9 "showAsk",10 { ask, project },11 { reactivityKeys: keys.ask(project, ask) }12 );1321// What an ask's atom holds: its read, under way, failed or done.14type AskRead = Atom.Type<ReturnType<typeof askAtom>>;1524// No row selected: an ask never read.16const unselected: Atom.Atom<AskRead> = Atom.make<AskRead>(17 AsyncResult.initial()18);1929// The selected ask in full, or nothing while no row is: one atom either30// way, so a list that reads it keeps its rows (and the row the keys rest31// on) when the selection moves.20// One atom either way, so a list that reads it keeps its rows when the selection moves.21export const selectedAskAtom = (22 pick: { readonly ask: AskId; readonly project: ProjectName } | undefined23): Atom.Atom<AskRead> =>24 pick === undefined ? unselected : askAtom(pick.project, pick.ask);
modified:apps/web/src/client/code.ts-32 removed
1/**2 * The code browser's reads (the data pattern in `src/surfaces.ts`): one3 * atom per code contract over the browser's `/rpc`, each taking the4 * contract's own payload and keyed by the project's code (`keys.code`),5 * which a landing changes. The code pages read on the server first (their6 * loaders), so the browser calls only the reads a page draws there (every7 * path for the file tree, `pathsAtom`) or keeps live: the project page's8 * root folder and README (`projectCodeAtom`), which its loader also read.9 */1import type { Contract } from "@repo/protocol/contracts";2import type { CommitView } from "@repo/protocol/domain/code";3import type { ProjectName, RepoPath } from "@repo/protocol/ids";4import { Array, Effect, Option } from "effect";
2 unmodified lines
78import { ContractsClient } from "../surfaces.ts";9import { keys } from "./keys.ts";1020/** What the contract tagged `Tag` takes. */11type PayloadOf<Tag extends string> = Rpc.Payload<Rpc.ExtractTag<Contract, Tag>>;1213const options = (project: ProjectName) => ({14 reactivityKeys: keys.code(project),15});1627/** Main, the tags and the forks. */17export const refsAtom = Atom.family((project: ProjectName) =>18 Atom.withServerValueInitial(19 ContractsClient.query("listRefs", { project }, options(project))20 )21);2234/** One folder; the root at main when the payload names neither. */23export const treeAtom = (payload: PayloadOf<"readTree">) =>24 ContractsClient.query("readTree", payload, options(payload.project));2538/** Every file path at a revision, for the file tree. */26export const pathsAtom = (payload: PayloadOf<"listPaths">) =>27 ContractsClient.query("listPaths", payload, options(payload.project));2842/** One file at a revision. */29export const fileAtom = (payload: PayloadOf<"readFile">) =>30 ContractsClient.query("readFile", payload, options(payload.project));3146/** A page of the log. */32export const logAtom = (payload: PayloadOf<"log">) =>33 ContractsClient.query("log", payload, options(payload.project));3450/** One commit and what it changed. */35export const commitAtom = (payload: PayloadOf<"showCommit">) =>36 ContractsClient.query("showCommit", payload, options(payload.project));3754/**55 * The project page's code: the root folder at main and, when it has one,56 * its README, read after it. A project with nothing landed yet refuses57 * the read, and its page shows no code. It renders as waiting on the58 * server, where the page draws its loader's read of the same code59 * (`server/folder.ts`); in the browser it takes over once it has a value,60 * and reads again on each landing.61 */38export const projectCodeAtom = Atom.family((project: ProjectName) =>39 Atom.withServerValueInitial(40 ContractsClient.runtime.factory.withReactivity(keys.code(project))(41 ContractsClient.runtime.atom(
17 unmodified lines
59 )60 )61);6287/** At most this many of a folder's entries have what last changed them read. */63export const LAST_CHANGES_CAP = 30;6490/**91 * What last changed each of a folder's entries at a commit, by path: one92 * `log` of one commit per entry (the platform keeps a path's history once93 * walked), three at a time, read after the page and only in the browser.94 * An entry whose read fails is left out; a folder of more than95 * `LAST_CHANGES_CAP` entries reads none, to spare the platform the walks.96 */65export const lastChangesAtom = Atom.family(66 (key: {67 readonly at: string;68 readonly paths: readonly RepoPath[];
34 unmodified lines
modified:apps/web/src/client/decide.ts-11 removed
1/**2 * A decider's choice on one decision, as a mutation atom over the `decide`3 * contract (the browser's `/rpc` call carries the session cookie).4 * A choice taken changes Today and the decision's project, so on5 * success both read again (`keys.today()`, `keys.project(project)`) and the6 * decision leaves Today. A choice that comes too late (`DecisionClosed`:7 * someone decided first, or it expired to its default) or names a decision8 * Today no longer has (`UnknownDecision`) fails with that refusal, and Today9 * reads again so the stale decision leaves the list.10 */1import type { Decide } from "@repo/protocol/contracts";2import { Effect } from "effect";3import { Reactivity } from "effect/reactivity";45import { ContractsClient } from "../surfaces.ts";6import { keys } from "./keys.ts";718/** Take one decision: `{ project, decision, choice, note? }`, answered with the decision as it now stands. */8export const decideAtom = ContractsClient.runtime.fn<9 typeof Decide.payloadSchema.Type10>()(11 Effect.fnUntraced(function* (input) {
10 unmodified lines
modified:apps/web/src/client/env.ts+1 added-8 removed
1/**2 * A project's env shape (the data pattern in `src/surfaces.ts`): `envShape`3 * over the browser's `/rpc`. It changes when a value is set (a ledger4 * entry, `ValueSet`) and when a landing changes the `.env.schema` (the5 * project's key), so both keys make it read again. The env page seeds it6 * with what its loader read on the server. (Lint keeps "shape" out of code7 * names, so the atom is named for the schema it reads.)8 */1// Lint keeps "shape" out of code names, so the atom is named for the schema it reads.2import type { ProjectName } from "@repo/protocol/ids";34import { ContractsClient } from "../surfaces.ts";5import { keys } from "./keys.ts";
7 unmodified lines
modified:apps/web/src/client/events.ts+1 added-22 removed
1/**2 * A project's events, read once per page and folded: the `watch` replay3 * from the first event, which every page that needs who holds an ask, its4 * rounds, a family's progress or the recent landings reads the same way.5 * No contract of its own: the fold reads only what `watch` already sends.6 *7 * - `projectEventsAtom(project)` holds the replay. Over JSON the platform8 * replays the kept events in one response and ends (only the framed9 * `/rpc` keeps the stream open), and the page's live view (`watch.ts`)10 * reads it again on each event, so it stays current.11 * - The derivations are pure and live with the views that draw them12 * (`features/shared/ask-progress.ts`): `askStates` (per ask), `whoseMove`,13 * `familyMarks`, `stampsFrom` (when a landing that happened while the page14 * was open earns its stamp); `recentLandings` is here, beside its atom.15 */1// Over JSON the platform replays the kept events in one response and ends; only the framed `/rpc` keeps the stream open.2import { ProjectEvent } from "@repo/protocol/domain/event";3import type { LandingView } from "@repo/protocol/domain/landing";4import type { ProjectName } from "@repo/protocol/ids";5import { Effect, Stream } from "effect";
17 unmodified lines
23 Move,24 Round,25} from "../features/shared/ask-progress.ts";2641/** How many landings a project's page shows. */27const RECENT = 20;2844/**45 * The project's events, replayed from the first; read again on each event46 * the page's live view hears, and on each of its polls (`keys.events`).47 */29export const projectEventsAtom = Atom.family((project: ProjectName) =>30 Atom.withServerValueInitial(31 ContractsClient.runtime.factory.withReactivity(keys.events(project))(32 ContractsClient.runtime.atom(
10 unmodified lines
43 )44 )45);4666/** The landings among a project's events, newest first, at most twenty. */47export const recentLandings = (48 events: readonly ProjectEvent[]49): readonly LandingView[] =>50 events
2 unmodified lines
53 )54 .toReversed()55 .slice(0, RECENT);5677/** A project's recent landings, from the one replay its page reads. */57export const recentLandingsAtom = Atom.family((project: ProjectName) =>58 Atom.withServerValueInitial(59 Atom.mapResult(projectEventsAtom(project), recentLandings)60 )
1 unmodified line
modified:apps/web/src/client/front.ts+1 added-13 removed
1/**2 * The front page's reads: the open asks across every project, and the list3 * of projects (which the shell's rail also reads, for each posture). The4 * page's loader reads the asks on the server and seeds their atom5 * (`seeded.ts`); the events of the projects whose families it draws are6 * `project.ts`'s.7 *8 * Each atom renders as waiting on the server unless a loader seeded it9 * (`withServerValueInitial`): a server render never fetches into the10 * registry that every request on the Worker shares.11 */1// Each atom waits on the server unless a loader seeded it: a server render never fetches into the registry every request shares.2import type { Reserve } from "@repo/protocol/domain/ask";3import type { KindName } from "@repo/protocol/ids";4import { Atom } from "effect/reactivity";56import { ContractsClient } from "../surfaces.ts";7import { keys } from "./keys.ts";819/** The open asks `frontPage` returns for `filter`, as the anonymous viewer may take them until sign-in names one. */9export const frontPageAtom = Atom.family(10 (filter: { readonly kind?: KindName; readonly reserved?: Reserve }) =>11 Atom.withServerValueInitial(12 ContractsClient.query("frontPage", filter, {
1 unmodified line
14 })15 )16);1729/** Every project the platform lists, with its posture, open asks and last landing. */18export const projectsAtom = Atom.withServerValueInitial(19 ContractsClient.query("listProjects", {}, { reactivityKeys: keys.front() })20);
modified:apps/web/src/client/import.ts+1 added-12 removed
1/**2 * The import form's write. `importAtom` sends `initProject` with `import`:3 * the platform clones the public repo and makes the project, with the4 * caller as its decider, which takes up to half a minute. The list of5 * projects changes, and so does the project's own key, so both read again.6 */1import type { InitProject } from "@repo/protocol/contracts";2import type { ProjectName } from "@repo/protocol/ids";3import { Effect, Option } from "effect";4import { AsyncResult, Reactivity } from "effect/reactivity";56import { ContractsClient } from "../surfaces.ts";7import { keys } from "./keys.ts";815/**16 * The project the last import made, once it answered. While a later17 * import is on its way, or after it was refused, the atom still holds an18 * earlier one's project, which names none here: the form never moves to it.19 */9// While a later import is on its way, or was refused, the atom still holds an earlier project; that names none here.10export const importMade = (11 result: AsyncResult.AsyncResult<12 typeof InitProject.successSchema.Type,13 unknown
2 unmodified lines
16 AsyncResult.isSuccess(result) && !result.waiting17 ? Option.some(result.value.project)18 : Option.none();1930/** Import a public repo: `initProject`'s payload, answered with the project. */20export const importAtom = ContractsClient.runtime.fn<21 typeof InitProject.payloadSchema.Type22>()(23 Effect.fnUntraced(function* (input) {
7 unmodified lines
modified:apps/web/src/client/keys.ts+2 added-17 removed
1/**2 * Reactivity keys: a query names the keys it reads, and a mutation names the3 * keys it changes, so each write refetches exactly the reads it affects.4 *5 * Each key is one string: `Reactivity` treats every element of a key list6 * as a key of its own, so a bare `"project"` would match every project. An7 * ask's keys include its project's, so a write that changes the ask (a8 * claim, a landing) also refetches the project's ask list.9 */1// Each key is one string: Reactivity treats every element of a key list as a key of its own.2import type { AskId, ProjectName, ProposalId } from "@repo/protocol/ids";34export const keys = {5 ask: (project: ProjectName, ask: AskId): readonly string[] => [6 `ask:${project}/${ask}`,7 `project:${project}`,8 ],17 /** The project's code reads (refs, trees, files, log, commits, why): a landing changes them. */9 code: (project: ProjectName): readonly string[] => [`code:${project}`],19 /**20 * The project's replayed events (`events.ts`): every event changes them.21 * Not the project's key, so a page's reads can be read again without22 * replaying every event once more.23 */10 // Not the project's key, so a page's reads can refetch without replaying every event.11 events: (project: ProjectName): readonly string[] => [`events:${project}`],12 front: (): readonly string[] => ["front"],13 ledger: (project: ProjectName): readonly string[] => [`ledger:${project}`],27 /** The project's evaluated policy (the people page): a landing may change it. */14 policy: (project: ProjectName): readonly string[] => [`policy:${project}`],15 project: (project: ProjectName): readonly string[] => [`project:${project}`],30 /** One proposal (its draft state and files); includes its project's, as an ask's does. */16 proposal: (project: ProjectName, proposal: ProposalId): readonly string[] => [17 `proposal:${project}/${proposal}`,18 `project:${project}`,19 ],
2 unmodified lines
modified:apps/web/src/client/ledger.ts+1 added-9 removed
1/**2 * A project's ledger (the data pattern in `src/surfaces.ts`): `ledger` over3 * the browser's `/rpc`, keyed by the project's ledger, so each entry the4 * platform appends (`LedgerAppended`, which `watch.ts` turns into5 * `keys.ledger`) makes it read again. It is keyed by the project too: when6 * the watch's stream fails at connect, its poll changes only the project's7 * keys, and the ledger must read again then as well. The ledger page seeds8 * it with what its loader read on the server.9 */1// Keyed by the project too: when the watch's stream fails at connect, its poll changes only the project's keys.2import type { ProjectName } from "@repo/protocol/ids";34import { ContractsClient } from "../surfaces.ts";5import { keys } from "./keys.ts";
7 unmodified lines
modified:apps/web/src/client/people.ts-5 removed
1/**2 * A person's page's read: their credit by project, area and3 * role. Read once per page; it renders as waiting on the server, and the4 * browser calls `/rpc` (see `front.ts`).5 */1import type { Handle } from "@repo/protocol/ids";2import { Atom } from "effect/reactivity";34import { ContractsClient } from "../surfaces.ts";
4 unmodified lines
modified:apps/web/src/client/policy.ts+1 added-8 removed
1/**2 * A project's evaluated policy (the people page's read, the data pattern in3 * `src/surfaces.ts`): `projectPolicy` over the browser's `/rpc`, keyed by4 * the project's policy, so a landing (`Landed`, which `watch.ts` turns into5 * `keys.policy`) makes it read again. It is keyed by the project too: when6 * the watch's stream fails at connect, its poll changes only the project's7 * keys. The people page seeds it with what its loader read on the server.8 */1// Keyed by the project too: when the watch's stream fails at connect, its poll changes only the project's keys.2import type { ProjectName } from "@repo/protocol/ids";3import { Atom } from "effect/reactivity";45import { ContractsClient } from "../surfaces.ts";
9 unmodified lines
modified:apps/web/src/client/project.ts-28 removed
1/**2 * A project page's reads: its open asks (`listAsks`), and the events of one3 * or more projects (`events.ts`) with their live views (`watch.ts`), as the4 * project's home and the front page's families read them. Each reads again5 * when its key is invalidated, which the page's live view does on each6 * event. Each renders as waiting on the server unless the page's loader7 * seeded it (`seeded.ts`); the browser calls `/rpc` (see `front.ts`).8 */1import type { ProjectEvent } from "@repo/protocol/domain/event";2import { ProjectName } from "@repo/protocol/ids";3import { AsyncResult, Atom } from "effect/reactivity";4
13 unmodified lines
18 )19 )20);2130/** Projects named in one key, as the atoms below are keyed: "burrow vellum". */22export const projectsKey = (projects: readonly ProjectName[]) =>23 projects.toSorted().join(" ");2425const projectsIn = (key: string): readonly ProjectName[] =>26 key === "" ? [] : key.split(" ").map((name) => ProjectName.make(name));2737/**38 * The events of each project in `key`, as far as each has been read; a39 * project whose replay has not arrived is left out. A new value each time40 * a replay is read again.41 */28export const familyEventsAtom = Atom.family((key: string) =>29 Atom.make(30 (get): ReadonlyMap<ProjectName, readonly ProjectEvent[]> =>31 new Map(
5 unmodified lines
37 )38 )39);4055/**56 * The live view of each project in `key` (`watch.ts`): mounted by the57 * page in the browser, it reads each project's events again as they come.58 */41export const followedAtom = Atom.family((key: string) =>42 Atom.make((get) => {43 for (const project of projectsIn(key)) {44 get.mount(watchAtom(project));45 }46 })47);4867/**68 * The project's ledger, which its home reads for its posture and what it69 * holds back; read again when the ledger or the project changes. Waiting on70 * the server, where the page draws what its loader read.71 */49export const projectLedgerAtom = Atom.family((project: ProjectName) =>50 Atom.withServerValueInitial(ledgerAtom(project))51);5276/**77 * The project's policy, which its home reads for who decides; read again78 * when a landing changes it. Waiting on the server, where the page draws79 * what its loader read.80 */53export const projectPolicyAtom = Atom.family((project: ProjectName) =>54 Atom.withServerValueInitial(policyAtom(project))55);
modified:apps/web/src/client/proposal.ts+1 added-26 removed
1/**2 * A proposal's reads and its one write. `proposalAtom` reads `showProposal`3 * (its draft's state and the files it holds), keyed by `keys.proposal`,4 * which a `ProposalDrafted` event invalidates (`watch.ts`), so the page5 * follows a draft from Drafting to Ready or Failed. `draftAtom` is the6 * proposer's or a decider's "Draft again" over `draftAsk`.7 *8 * The decider's Today in one project lives here too, as the proposal page9 * reads it: it holds the open decision on the proposal (within the day's10 * budget), and it answers only a decider (`NotDecider` otherwise); it reads11 * again when the project's keys change, as a settled draft changes them. Each read12 * renders as waiting on the server, so the Worker reads none of them for a13 * page that draws them in the browser.14 */1import type { DraftAsk } from "@repo/protocol/contracts";2import type { ProjectName, ProposalId } from "@repo/protocol/ids";3import { Effect } from "effect";4import { Atom, Reactivity } from "effect/reactivity";56import { ContractsClient } from "../surfaces.ts";7import { keys } from "./keys.ts";823/** One proposal and the files it holds: `proposalAtom(project)(proposal)`. */9export const proposalAtom = Atom.family((project: ProjectName) =>10 Atom.family((proposal: ProposalId) =>11 Atom.withServerValueInitial(12 ContractsClient.query(
4 unmodified lines
17 )18 )19);2036/**37 * The reader's Today in `project`, when they decide there. A draft that38 * settles puts its decision up, so the project's keys (which a39 * `ProposalDrafted` changes, through `keys.proposal`) read it again too.40 */21export const projectTodayAtom = Atom.family((project: ProjectName) =>22 Atom.withServerValueInitial(23 ContractsClient.query(24 "today",
2 unmodified lines
27 )28 )29);3051/**52 * Draft a proposal's ask again: `{ project, proposal, note? }`, answered53 * with the proposal as it now stands (Drafting). The proposal reads again54 * on success, and on `DraftInProgress` or `ProposalClosed` too, since then55 * the page shows a stale state.56 */31// Reads again on `DraftInProgress` or `ProposalClosed` too, since then the page shows a stale state.32export const draftAtom = ContractsClient.runtime.fn<33 typeof DraftAsk.payloadSchema.Type34>()(35 Effect.fnUntraced(function* (input) {
11 unmodified lines
modified:apps/web/src/client/propose.ts+1 added-16 removed
1/**2 * The propose form's read and write. `modulesAtom` lists the territories3 * the form offers: the project's top folders at main, from `listPaths`4 * (dot folders, the config folder among them, are no territory). A project5 * with nothing landed yet refuses the read, and the form offers none.6 * `proposeAtom` sends `proposeAsk`; the project's proposals change, so its7 * key reads again.8 */1import type { ProposeAsk } from "@repo/protocol/contracts";2import { RepoPath } from "@repo/protocol/ids";3import type { ProjectName, ProposalId } from "@repo/protocol/ids";4import { Array, Effect, Option, Order, Schema } from "effect";
3 unmodified lines
8import { keys } from "./keys.ts";910const decodePath = Schema.decodeUnknownOption(RepoPath);1120/** The top folders among `paths`, sorted, without dot folders. */12export const topFolders = (paths: readonly RepoPath[]): readonly RepoPath[] => {13 const folders = paths.flatMap((path): readonly RepoPath[] => {14 const slash = path.indexOf("/");15
4 unmodified lines
2021 return Array.sort(Array.dedupe(folders), Order.String);22};2333/** The project's top folders at main, each a territory the form offers. */24export const modulesAtom = Atom.family((project: ProjectName) =>25 Atom.withServerValueInitial(26 ContractsClient.runtime.factory.withReactivity(keys.code(project))(27 ContractsClient.runtime.atom(
7 unmodified lines
35 )36 )37);3849/**50 * The proposal the last send made, once it answered. While a later send is51 * on its way, or after it was refused, the atom still holds an earlier52 * send's proposal, which names none here: the form never moves to it.53 */39// While a later send is on its way, or was refused, the atom still holds an earlier proposal; that names none here.40export const proposalMade = (41 result: AsyncResult.AsyncResult<typeof ProposeAsk.successSchema.Type, unknown>42): Option.Option<ProposalId> =>43 AsyncResult.isSuccess(result) && !result.waiting44 ? Option.some(result.value.proposal.id)45 : Option.none();4661/** Propose an ask: `proposeAsk`'s payload, answered with the proposal. */47export const proposeAtom = ContractsClient.runtime.fn<48 typeof ProposeAsk.payloadSchema.Type49>()(50 Effect.fnUntraced(function* (input) {
7 unmodified lines
modified:apps/web/src/client/seeded.ts+2 added-34 removed
1/**2 * A page's atoms, rendered from what its loader read on the server.3 *4 * A route's loader reads on the server, so the page arrives with its data;5 * its atoms then start from that read and keep it live in the browser (a6 * key invalidated by `watch` reads again). The seeds go into a registry of7 * the page's own, made for each render: the registry `@effect/atom-react`8 * gives by default lives for the Worker's whole life and every request on9 * it shares it, so a server render must never write a value there (the10 * reason the client's atoms render as waiting on the server,11 * `withServerValueInitial`).12 *13 * Everything under `SeededAtoms` reads and writes its own registry: put the14 * page's whole body under it, so its reads, its live view (`watchAtom`)15 * and its writes share one, and give each address its own `id`, so moving16 * to another address makes a new registry from that address's seeds. The17 * registries share one `Reactivity` (`sharedRuntime`, `surfaces.ts`), so a18 * write on the page also refetches what the root reads (the rail's counts).19 *20 * ```tsx21 * const read = Route.useLoaderData();22 *23 * <SeededAtoms id={`${read.project}/${read.ask}`} seeds={[seedSuccess(verdictAtom(read.project, read.ask), { verdict: read.verdict })]}>24 * <FreshAnswer read={read} />25 * </SeededAtoms>26 * ```27 */1// The seeds go into a registry of the page's own: @effect/atom-react's default registry lives for the Worker's2// whole life and every request shares it, so a server render must never write a value there.3import { RegistryProvider } from "@effect/atom-react";4import { AsyncResult, Atom } from "effect/reactivity";5import { createElement } from "react";6import type { ReactNode } from "react";733/** An atom and the value it starts from. */8export type Seed = readonly [Atom.Atom<unknown>, unknown];936/** `atom`, starting from `value`. */10export const seed = <A>(atom: Atom.Atom<A>, value: A): Seed =>11 Atom.initialValue(atom, value);1240/** A read's atom, starting from the success its loader read. */13export const seedSuccess = <A, E>(14 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,15 value: A16): Seed => seed(atom, AsyncResult.success(value));1746/**47 * `children` over a registry of their own that starts from `seeds`; a new48 * `id` (another address) makes a new one.49 */18export const SeededAtoms = ({19 children,20 id,21 seeds,
6 unmodified lines
modified:apps/web/src/client/today.ts-14 removed
1/**2 * The signed-in decider's Today, as an atom over the `today` contract: every3 * project they decide in, or the one `project` names. The browser's `/rpc`4 * call carries the session cookie; the platform decides who is5 * asking, and answers a person who decides nothing with `NotDecider`.6 *7 * A write that changes Today (a decision taken, here or by a teammate's8 * `decide`) invalidates `keys.today()`, and this atom reads again.9 */1import type { ProjectName } from "@repo/protocol/ids";2import { Atom } from "effect/reactivity";34import { ContractsClient } from "../surfaces.ts";5import { keys } from "./keys.ts";616/**17 * The caller's Today, across their projects or narrowed to one. A server18 * render never reads it (the page's loader does, with the reader's19 * session, and seeds it); unseeded, it renders as waiting there.20 */7const todayFamily = Atom.family((project: ProjectName | undefined) =>8 Atom.withServerValueInitial(9 ContractsClient.query("today", project === undefined ? {} : { project }, {10 reactivityKeys: keys.today(),
5 unmodified lines
modified:apps/web/src/client/watch.ts+2 added-42 removed
1/**2 * A page's live view: `watchAtom(project)` follows3 * the project's `watch` stream over the framed `/rpc` and invalidates the4 * keys each event changes (`keysOf`), so the page's own reads (`listAsks`,5 * `verdict`, the landings) fetch again. It keeps nothing but the last6 * number it heard.7 *8 * - A stream that ends, or fails after it heard something, is followed9 * again `POLL_MS` later, from the last number heard: nothing is missed10 * and nothing is heard twice.11 * - A stream that fails before it hears anything (no framed `/rpc`, as in12 * the dev world, or a platform that cannot stream) turns the page to13 * polling: every `POLL_MS` the project's keys are invalidated, and since14 * an ask's keys include its project's (`keys.ts`), the answer page's15 * verdict fetches again too.16 *17 * Every page that shows a project live mounts it (`useAtomMount`), so it18 * runs only in the browser, from the page's mount to its unmount. It follows from the19 * last number of the project's replay (`projectEventsAtom`), not from the20 * first event, so a new watcher hears none of the kept events again and21 * never replays them twice. The page's own reads may be older than that22 * replay (a loader read them on the server, or they were read beside it),23 * so once the replay is in, the keys its events change are invalidated24 * once: whatever happened between the page's first read and the replay is25 * read then, and whatever happened after comes first on the stream. The26 * replay has a key of its own (`keys.events`), so that read leaves it be;27 * each event the stream brings, and each poll, reads it again. A replay28 * that cannot be read starts the follow from the first event, as before.29 */1// Follows from the replay's last number, so a new watcher never hears a kept event twice. A stream that fails2// before it hears anything (no framed `/rpc`, as in the dev world) turns the page to polling the project's keys.3import { ProjectEvent } from "@repo/protocol/domain/event";4import type { ProjectName } from "@repo/protocol/ids";5import {6 Array,
12 unmodified lines
19import { framedClient, sharedRuntime } from "../surfaces.ts";20import { lastSeq, projectEventsAtom } from "./events.ts";21import { keys } from "./keys.ts";2250/** How long a page waits before it follows again, or between polls. */23export const POLL_MS = 5000;2453/** Where a page hears its project's events, from a sequence number on. */25export class ProjectWatch extends Context.Service<26 ProjectWatch,27 {28 readonly follow: (
2 unmodified lines
31 ) => Stream.Stream<ProjectEvent, unknown>;32 }33>()("web/ProjectWatch") {}3464/** `watch` over the framed `/rpc`. */35const framedWatch = Layer.effect(36 ProjectWatch,37 Effect.map(framedClient, (client) =>38 ProjectWatch.of({
1 unmodified line
40 })41 )42);4374/** The runtime `watchAtom` runs on, sharing the page's and the rail's `Reactivity`; a test gives it a stub `ProjectWatch`. */44export const watchRuntime = sharedRuntime(framedWatch);4577/** The keys an event of `project` changes. */46export const keysOf = (47 project: ProjectName,48 event: ProjectEvent49): readonly string[] =>50 ProjectEvent.match(event, {83 // The project list's open asks and last landing (the rail's) too.51 AskClosed: () => [...keys.project(project), ...keys.front()],52 AskOpened: () => [...keys.project(project), ...keys.front()],53 Claimed: () => keys.project(project),54 Decided: () => keys.project(project),
12 unmodified lines
67 Released: () => keys.project(project),68 Warned: ({ ask }) => keys.ask(project, ask),69 });70104/** The keys any of `events` changes, each once. */71const keysOfAll =72 (project: ProjectName) =>73 (events: readonly ProjectEvent[]): readonly string[] =>74 Array.dedupe(events.flatMap((event) => keysOf(project, event)));75110/** `project` followed from the end of its `replay` for as long as it runs: the stream while it works, then the poll. */76const followed = <E>(77 project: ProjectName,78 replay: Effect.Effect<readonly ProjectEvent[], E>79) =>
10 unmodified lines
90 yield* reactivity.invalidate(91 Option.match(kept, { onNone: () => [], onSome: keysOfAll(project) })92 );93129 /** One stream from the last number heard, to its end: whether it failed before it heard anything. */94 const once = Effect.gen(function* () {95 const heard = yield* Ref.make(false);9697 const ended = yield* watch.follow(project, yield* Ref.get(last)).pipe(
24 unmodified lines
122 .invalidate([...keys.project(project), ...keys.events(project)])123 .pipe(Effect.delay(POLL_MS), Effect.forever);124 });125162/**163 * A page's live view of `project`: mounted, it follows the project's164 * events and invalidates the keys they change. Its value says nothing.165 */126export const watchAtom = Atom.family((project: ProjectName) =>127 Atom.map(128 watchRuntime.atom((get) =>129 // Read once, not followed: a new replay must not start the stream over.
5 unmodified lines
modified:apps/web/src/client/why.ts-8 removed
1/**2 * The "why" read (the data pattern in `src/surfaces.ts`): an atom over the3 * browser's `/rpc`, taking the contract's own payload and keyed by the4 * project's code (`keys.code`), which a landing changes. The page reads on5 * the server first (its loader); this atom is for a drawing that asks6 * again in the browser.7 */1import type { Contract } from "@repo/protocol/contracts";2import type { Rpc } from "effect/rpc";34import { ContractsClient } from "../surfaces.ts";5import { keys } from "./keys.ts";614/** Why each line of a file at a revision is there. */7export const whyAtom = (8 payload: Rpc.Payload<Rpc.ExtractTag<Contract, "why">>9) =>10 ContractsClient.query("why", payload, {
2 unmodified lines
modified:apps/web/src/dev/fixtures/fillers.ts-15 removed
1/**2 * Six small fictional projects beside the others, so a list of projects3 * runs past what fits beside it, each made through the project service as4 * datekit is, in its decider's namespace (`okafor/amberlog`): created, its5 * first commit pushed, one ask opened by its decider. `mossgate` opens none: a visitor's proposal is all it holds, so6 * it lists with no open asks.7 */1import { Brand } from "@repo/brand";2import { CheckSpec } from "@repo/protocol/domain/check";3import type { Handle } from "@repo/protocol/ids";4import { AskId, ProjectName, RepoPath, shortNameOf } from "@repo/protocol/ids";
92 unmodified lines
97 summary: "A connection pool that queues borrowers fairly.",98 }),99];100108/** `drain-on-shutdown` → `drainOnShutdown`: the export an ask's check looks for. */101export const exportNameOf = (ask: string) =>102 ask.replaceAll(/-(?<letter>[a-z0-9])/gu, (_match, letter: string) =>103 letter.toUpperCase()104 );105114/** A check that fails on main by its assertion: the module exports no function by the ask's name. */106export const checkOf = (module: string, ask: string, want: string) =>107 [108 'import { expect, test } from "bun:test";',109 "",
4 unmodified lines
114 "});",115 "",116 ].join("\n");117127/** The ask a filler states, as its `policy.json` holds it. */118const statedOf = (119 project: Filler,120 ask: NonNullable<Filler["ask"]>121): StatedAsk => ({
61 unmodified lines
183 `# The people ${project.project}'s deciders vouch for.\n`,184 ],185 ]);186197/**198 * Every filler made and adopted, one every three minutes from `minute`,199 * each one's ask (or, in mossgate, a visitor's proposal) a minute after its200 * first push.201 */187export const seedFillers = (minute: number) =>188 Effect.forEach(189 fillers,190 (project, index) =>
47 unmodified lines
modified:apps/web/src/dev/fixtures/record.ts-40 removed
1/**2 * A fixture project's record: everything its reads answer with, held as3 * one value so every contract reads the same story (the asks, the events4 * `watch` replays, the verdicts, the landings, the decisions, the ledger,5 * the env shape, the proposals and the claims). Every part is decoded6 * through the protocol's own schema before the world serves it7 * (`decodeRecord`), so a fixture cannot drift from the wire.8 *9 * The reads a record answers are derived here by the service's own pure10 * functions where it has them: Today by `today` (budget, overflow, what11 * expires within the day, newcomers, what landed without anyone), credits12 * by `creditsByArea`, a listing by `listingOf`.13 */1import { creditsByArea } from "@repo/project/attention/credits";2import { today } from "@repo/project/attention/today";3import { listingOf } from "@repo/project/events";4import type { Verdict } from "@repo/protocol/domain/answer";
31 unmodified lines
36import { Array, DateTime, Effect, Option, Schema } from "effect";3738import { present } from "./story.ts";3953/** One proposal and the files it holds. */40export interface HeldProposal {41 readonly files: readonly ConfigFile[];42 readonly proposal: Proposal;43}4459/** A log a failing lane left, as `evidence` reads it back. */45export interface KeptLog {46 readonly claimant: Handle;47 readonly lane: Verdict["lanes"][number]["lane"];48 readonly text: string;49}5066/** A fixture project's whole record. */51export interface FixtureRecord {68 /** Every claim's answers: one per round, oldest first. */52 readonly answers: readonly AnswerView[];53 readonly asks: ReadonlyMap<AskId, Ask>;71 /** Every claim, as its claimant's `status` shows it. */54 readonly claims: readonly ClaimView[];55 readonly decisions: readonly Decision[];56 readonly env: EnvSchemaView;57 readonly events: readonly ProjectEvent[];76 /** Each person's first claim, older history included. */58 readonly firstClaims: readonly {59 readonly at: DateTime.Utc;60 readonly handle: Handle;61 }[];62 readonly forks: readonly ForkRef[];82 /** Main's landed commit. */63 readonly head: LandedSha;64 readonly landings: readonly LandingView[];65 readonly ledger: Ledger;66 readonly logs: ReadonlyMap<string, KeptLog>;67 readonly proposals: ReadonlyMap<ProposalId, HeldProposal>;88 /** Each answered ask's verdicts, one per round, oldest first. */68 readonly verdicts: ReadonlyMap<AskId, readonly Verdict[]>;69}7071const asType = <S extends Schema.Top>(schema: S) =>72 Schema.decodeUnknownEffect(Schema.toType(schema));7395/**96 * `record` decoded part by part through the protocol's schemas: a value97 * that fails is a defect of the fixture's, found when the world is built.98 */74export const decodeRecord = (75 record: FixtureRecord76): Effect.Effect<FixtureRecord> =>77 Effect.gen(function* () {
23 unmodified lines
101102 return record;103 }).pipe(Effect.orDie);104130// ------------------------------------------------------------ reads131132/** The open asks, as `listAsks` lists them. */105export const listedOf = (record: FixtureRecord): readonly AskListing[] =>106 [...record.asks.values()].flatMap((ask) =>107 ask.state === "closed" ? [] : [listingOf(ask)]108 );109138/** The verdict on `head`, or the latest; its outcome where the answer stands now. */110export const verdictIn = (111 record: FixtureRecord,112 ask: AskId,113 head: CommitSha | undefined
5 unmodified lines
119 (verdict) => head === undefined || verdict.head === head120 );121};122152/** The landing at `sha`, if the record holds one. */123export const landingIn = (record: FixtureRecord, sha: CommitSha) =>124 Array.findFirst(record.landings, (landing) => landing.sha === sha);125156/** How many decisions and finishes `decider` took on the day of `now`. */126const spentBy = (record: FixtureRecord, decider: Handle, now: DateTime.Utc) => {127 const day = DateTime.formatIsoDateUtc(now);128129 return record.decisions.filter(
3 unmodified lines
133 DateTime.formatIsoDateUtc(decided.at) === day134 ).length;135};136168/** `decider`'s Today in the record, as the service computes one; none for anyone who decides nothing in it. */137export const todayIn = (138 record: FixtureRecord,139 decider: Handle,140 now: DateTime.Utc,
17 unmodified lines
158 })159 )160 : Option.none();161194/** A person's credits in the record, by area and role. */162export const creditsIn = (163 record: FixtureRecord,164 handle: Handle165): readonly CreditSummary[] =>166 creditsByArea({ asks: record.asks, handle, landings: record.landings });167201/** The caller's claims still in play, and their answers. */168export const statusIn = (record: FixtureRecord, who: Handle) => ({169 answers: record.answers.filter(({ ask }) =>170 record.claims.some(171 (claim) => claim.ask === ask && sameHandle(claim.claimant, who)
4 unmodified lines
176 sameHandle(claimant, who) && (state === "live" || state === "warned")177 ),178});179214/**215 * The decision `who` takes when they choose `choice` on `id` at `now`, with216 * its record (by, choice, when, note); or why they may not: no such217 * decision, one already taken or expired, or one they do not decide.218 */180export const decisionTaken = (181 record: FixtureRecord,182 input: {183 readonly choice: Choice;
31 unmodified lines
215 },216 };217 });218258/** The number of the record's last event. */219export const lastSeqOf = (record: FixtureRecord): number =>220 Math.max(0, ...record.events.map(({ seq }) => seq));
modified:apps/web/src/dev/fixtures/story.ts-71 removed
1/**2 * How a fixture project's record is written: a story told in the order3 * things happened, each step writing what the service would have written4 * for it (the events `watch` replays, numbered in order, the asks, each5 * round's verdict, the claims and the landings). A landing is a real6 * commit on the project's canonical `main` in the world's repo host,7 * committed by the platform with its credit trailers, so the code pages,8 * the log and every landing link read real git. An answer's head names no9 * commit the world holds (its fork is never made): it is a stable id made10 * from the step's name, as are merged trees, patch ids and suite roots.11 */1import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";2import { Brand } from "@repo/brand";3import { formatLanding } from "@repo/git/trailers";4import { listingOf } from "@repo/project/events";
39 unmodified lines
44import { overlay, personIdentity, platformIdentity, scratch } from "../git.ts";45import type { Files } from "../git.ts";46import type { FixtureRecord, HeldProposal, KeptLog } from "./record.ts";4759// ------------------------------------------------------------- ids6061/** The largest prime below 2^32: each block of eight digits is a hash modulo it. */48const MODULUS = 4_294_967_291;4964/** `count` hex digits made from `label` alone: a polynomial hash, a fresh seed per eight digits. */50export const hexOf = (label: string, count: number): string => {51 let out = "";5253 for (let block = 0; out.length < count; block += 1) {
8 unmodified lines
6263 return out.slice(0, count);64};6581/** `{ [key]: value }` when there is a value, else nothing: an optional key, spread. */66export const present = <K extends string, A>(67 key: K,68 value: A | undefined69): Partial<Record<K, A>> =>
1 unmodified line
71 onNone: () => ({}),72 onSome: (held) => Record.singleton(key, held),73 });7491/** A commit id made from `label`: an answer's head, which no repo of the world holds. */75export const headOf = (label: string) => CommitSha.make(hexOf(label, 40));7694/** A held-back suite's commitment, made from its area's name. */77export const suiteOf = (area: string) =>78 SuiteRoot.make(`sha256:${hexOf(`suite:${area}`, 64)}`);7998/** An instant of the dev world's calendar (`clock.ts`), from `2026-10-07T10:00`, in UTC. */80export const instant = (text: string): DateTime.Utc =>81 DateTime.toUtc(DateTime.makeUnsafe(`${text}:00Z`));82102// ----------------------------------------------------------- lanes103104/** The project's own lanes, by name, with their commands. */83export type Lanes = Readonly<Record<string, string>>;84107/** The lane an ask's own check reports as, and its command. */85const askLane = (ask: Ask, test: string): readonly [string, string] =>86 CheckSpec.match(ask.check, {87 LintToZero: ({ command }) => ["lintToZero", command],88 Migrate: ({ count }) => ["migrate", count],
1 unmodified line
90 RedThenGreen: ({ path }) => ["redThenGreen", test.replace("{path}", path)],91 SymbolAbsent: ({ count }) => ["symbolAbsent", count],92 });93117// ------------------------------------------------------------ story118119/** What one landing carries beside its commit. */94interface LandingInput {95 readonly assisted?: readonly AgentTrailer[];96 readonly at: DateTime.Utc;97 readonly author: Handle;
6 unmodified lines
104 readonly requestId: RequestId;105 readonly verdict?: Verdict;106}107134/** One claim as the story keeps it. */108interface Held {109 readonly at: DateTime.Utc;110 readonly base: LandedSha;111 readonly claimant: Handle;
1 unmodified line
113 readonly state: ClaimState;114 readonly suite?: SuiteRoot;115}116144/**145 * A story over `project`'s canonical repo, whose `main` stands at `base`146 * with `files`: each step writes what the service would, in order.147 */117export const storyOf = (input: {118 readonly base: LandedSha;119 readonly files: Files;120 readonly lanes: Lanes;
23 unmodified lines
144 const firstClaims = new Map<Handle, DateTime.Utc>();145146 const nextSeq = () => events.length + 1;147179 /** One event, numbered next. */148 const tell = (made: (seq: number) => ProjectEvent) => {149 events.push(made(nextSeq()));150 };151
27 unmodified lines
179180 claims.set(id, [...all.slice(0, -1), change(last)]);181 };182215 /** A commit of `changes` on main, by the platform for `author`, at `at`. */183 const commit = (landing: LandingInput) =>184 Effect.gen(function* () {185 const into = yield* scratch;186 const next = overlay(files, landing.changes);
52 unmodified lines
239240 return view;241 });242276 /** The child of a family that waits on the rest opens once they have all closed. */243 const familyMoves = (landed: Ask, at: DateTime.Utc) => {244 if (landed.parent === undefined) {245 return;246 }
47 unmodified lines
294 }295 );296297 return {332 /** An ask's id, read back; the story names only asks it opened. */298 ask: askOf,299335 /**336 * The asks a decider opens in one landing: their files on main, an337 * `AskOpened` for each that opens now (a child waiting on the rest338 * opens later), and the landing, which names the first as opened.339 */300 open: (step: {301 readonly asks: Array.NonEmptyReadonlyArray<302 Omit<Ask, "openedAt" | "openedIn" | "project">303 >;
53 unmodified lines
357358 return landing;359 }),360401 /** `who` claims `id`; an answer to it is judged by `suite` when its claim pins one. */361 claim: (id: AskId, who: Handle, at: DateTime.Utc, suite?: SuiteRoot) => {362 claims.set(id, [363 ...(claims.get(id) ?? []),364 {
14 unmodified lines
379 ProjectEvent.cases.Claimed.make({ ask: id, at, claimant: who, seq })380 );381 },382424 /** The claimant pushes to the claim's fork: its head, named for `round`. */383 push: (id: AskId, at: DateTime.Utc, round = 1) => {384 const claimed = claimOf(id);385 const pushed = headOf(`${project}/${id}/${claimed.claimant}/${round}`);386
4 unmodified lines
391392 return pushed;393 },394437 /**438 * The answer at `pushed` checked: its verdict, kept as a round of the439 * ask, and a `Judged` event with where it stands.440 */395 judge: (396 id: AskId,397 pushed: CommitSha,398 step: {
60 unmodified lines
459460 return verdict;461 },462509 /**510 * The ask's last judged answer lands: a platform commit of `changes`511 * crediting the asker, the answerer and anyone who decided on it,512 * then `Landed` and `AskClosed`, and the family's next step opens513 * once every sibling has landed.514 */463 land: (464 id: AskId,465 step: {466 readonly assisted?: readonly AgentTrailer[];
86 unmodified lines
553554 return view;555 }),556609 /**610 * The checks still running on the ask's last answer finish with611 * `lanes`, and it passes every stage: its verdict, kept, stands at the612 * last stage until it lands.613 */557 finishChecks: (558 id: AskId,559 lanes: Readonly<Record<string, LaneOutcome>>560 ) => {
16 unmodified lines
577 ]);578 }579 },580638 /** A landing that answers no ask: a release from a layer, a decider's own change. */581 landOwn: (step: {582 readonly at: DateTime.Utc;583 readonly author: Handle;584 readonly changes: Files;
14 unmodified lines
599600 return view;601 }),602661 /** The claim is warned: no push for a while. */603 warn: (id: AskId, at: DateTime.Utc) => {604 moveClaim(id, (held) => ({ ...held, state: "warned" }));605 tell((seq) => ProjectEvent.cases.Warned.make({ ask: id, at, seq }));606 },607667 /** The claim lapsed, and the ask is open again. */608 lapse: (id: AskId, at: DateTime.Utc) => {609 moveClaim(id, (held) => ({ ...held, state: "lapsed" }));610 setAsk({ ...askOf(id), state: "open" });611 tell((seq) => ProjectEvent.cases.Lapsed.make({ ask: id, at, seq }));612 },613674 /** The claimant let the ask go, and it is open again. */614 release: (id: AskId, at: DateTime.Utc) => {615 moveClaim(id, (held) => ({ ...held, state: "released" }));616 setAsk({ ...askOf(id), state: "open" });617 tell((seq) => ProjectEvent.cases.Released.make({ ask: id, at, seq }));618 },619681 /** A decision put to its deciders. */620 decision: (decision: Decision) => {621 decisions.push(decision);622 },623686 /** A decider takes a decision put earlier. */624 decide: (id: Decision["id"], taken: NonNullable<Decision["decided"]>) => {625 const index = decisions.findIndex((each) => each.id === id);626 const found = decisions[index];627
11 unmodified lines
639 })640 );641 },642706 /** A ledger entry, numbered next in the ledger, and its event. */643 record: (entry: (seq: number) => LedgerEntry) => {644 const made = entry(ledger.length + 1);645646 ledger.push(made);
5 unmodified lines
652 })653 );654 },655720 /** A proposal opened, as anyone reads it now, and its events. */656 propose: (657 held: HeldProposal,658 settled?: { readonly at: DateTime.Utc; readonly ready: boolean }659 ) => {
17 unmodified lines
677 );678 }679 },680746 /** A later round of a proposal's draft settled. */681 drafted: (id: ProposalId, at: DateTime.Utc, ready: boolean) => {682 tell((seq) =>683 ProjectEvent.cases.ProposalDrafted.make({684 at,
3 unmodified lines
688 })689 );690 },691758 /** A decider accepted the proposal: it is closed, and its ask opens. */692 accepted: (id: ProposalId) => {693 const held = proposals.get(id);694695 if (held !== undefined) {
3 unmodified lines
699 });700 }701 },702770 /** A tag on `sha`, as a release names it. */703 tag: (name: string, sha: LandedSha) =>704 Effect.gen(function* () {705 const into = yield* scratch;706
7 unmodified lines
714 ])715 );716 }),717786 /** Main's landed commit now. */718 head: () => head,719789 /** The record the story wrote, with what it keeps apart from the story. */720 told: (721 apart: Pick<FixtureRecord, "env" | "ledger"> & {722 readonly working: readonly Handle[];723 }
53 unmodified lines
777 },778 };779 });780851/** A story under way: its steps, and the record it has written so far. */781export type Story = Effect.Success<ReturnType<typeof storyOf>>;
modified:apps/web/src/dev/fixtures/vellum.ts-77 removed
1/**2 * vellum: the fixture project, a six-package library that reads and3 * writes a small document format, with its held-back checks in two areas4 * (export and parser) and a write-only token for its error reports. Its5 * record is told as a story (`story.ts`) from its first asks in September6 * to the morning the world stands at, so each state a page draws is there7 * once, reached the way the service would reach it:8 *9 * - answers: checking, waiting on a decision, waiting for a finish,10 * waiting on another ask, refused at Shape, at the held-back stage and at11 * the checks, landed with a decision and held-back results, landed with12 * neither, and one in its third round;13 * - asks: open, held for newcomers, claimed with and without a push, a14 * released claim, a lapsed one, and a want too long for a title;15 * - two families: one with a child in every mark and its delete child16 * waiting, one whose children all landed and whose delete child opened;17 * - a decision of every kind, two taken this morning, one due within the18 * day; proposals drafting, ready and failed;19 * - a ledger with a layer, two committed areas and history of every kind,20 * an env shape with a write-only item someone set, and a policy that21 * names deciders by path and one denounced person.22 *23 * Its people are the examples' own (`examples.ts`, `seed.ts`): `ines-v`24 * decides, `okonkwo` decides the export package, the env schema and the25 * vouch file, `lin-h` decides the config folder with her; `bram`,26 * `okafor` and `lin-h` have answered here for weeks; `tove` and `sefa`27 * are new; `wren` is denounced.28 */1import { Brand } from "@repo/brand";2import { childId, deleteChildId } from "@repo/project/migrate";3import type { HeldBackResult } from "@repo/protocol/domain/answer";4import type { Ask } from "@repo/protocol/domain/ask";
47 unmodified lines
52import type { Story } from "./story.ts";5354export const vellum = ProjectName.make("oscabriel/vellum");5584/** The calendar's instant the world's clock stands at once the fixtures are told. */56export const fixturesNow = instant("2026-10-07T10:00");5787/** When vellum's first commit was pushed, by its initializer, on the calendar. */58export const vellumStart = instant("2026-08-24T09:00");5960const dir = Brand.configDir;61
7 unmodified lines
69 tove: visitors.proposer,70 wren: visitors.regular,71} as const;72103/** vellum's initializer: the operator, in whose namespace it is made. */73export { operator as vellumInitializer } from "../examples.ts";7475const MODULES = [76 "cli",
31 unmodified lines
108 "sentry.io",109 "ingest.sentry.io",110]);111143// The areas whose checks the maintainers hold back, and their commitments.112const EXPORT = AreaName.make("export");113114const PARSER = AreaName.make("parser");115
11 unmodified lines
127 suite: area === EXPORT ? exportSuite : parserSuite,128 total,129});130163// --------------------------------------------------------------- files164131const encodeCheck = Schema.encodeSync(CheckSpec);132133const COUNT = Command.make("bun scripts/count-callers.ts oldTokenize --json");134
11 unmodified lines
146 null,147 2148 )}\n`;149184/** A module's entry, calling the old tokenizer twice. */150const entryOf = (module: Module, tokenize: string) =>151 [152 `import { ${tokenize} } from "@vellum/parser/tokenize";`,153 "",
3 unmodified lines
157 `export const marks = (text: string) => ${tokenize}(text).filter((token) => token.kind === "mark");`,158 "",159 ].join("\n");160196/** A module's page settings, under the old name or the new. */161const pageOf = (module: Module, name: string) =>162 [163 `/** ${moduleName(module)}'s page: A4 unless a theme says otherwise. */`,164 `export const ${name} = { height: 297, width: 210 } as const;`,
23 unmodified lines
188 "LEGACY_PDF_ENGINE=",189 "",190].join("\n");191228/** How many decisions a vellum decider takes a day (its `policy.json`'s budget). */192export const decisionsPerDay = 5;193231/** How long a claim goes without a push before it is warned, then lapses. */194const CLAIMS = { lapseAfter: { hours: 96 }, warnAfter: { hours: 48 } } as const;195196const HOUR_MS = 3_600_000;197
60 unmodified lines
258 source: "config",259 weakening: { markers: [".skip(", ".only(", ".todo("] },260});261300/** vellum's first push: six packages, its config folder and its env schema. */262export const vellumFiles: Files = new Map([263 [264 "README.md",265 [
96 unmodified lines
362 ].join("\n"),363 ],364]);365405// ---------------------------------------------------------------- asks406407/** An ask as the story opens it: everything but where and when it opened. */366type Stated = Omit<Ask, "openedAt" | "openedIn" | "project">;367368const fix = (input: {369 readonly id: string;370 readonly module: Module;413 /** A territory other than the module's own. */371 readonly territory?: Territory;372 readonly want: string;373 readonly current?: string;374 readonly askedBy?: Handle;
28 unmodified lines
403 ),404 };405};406450/** The ask's file as its maintainer writes it, and its check's test. */407const filesOf = (asks: readonly Stated[]): Files =>408 new Map(409 asks.flatMap((ask) => {410 const stated: StatedAsk = {
22 unmodified lines
433 return [[file.path, file.content] as const, ...test];434 })435 );436481/** A migrate ask split as the service splits one: a child per module, then the delete child. */437const familyOf = (input: {438 readonly id: string;439 readonly from: string;440 readonly to: string;
185 unmodified lines
626 want: "A table cell longer than the column wraps instead of widening the table.",627 }),628} as const;629675/** An answer's change: one file in the ask's own module. */630const answerFiles = (stated: Stated, body: string): Files => {631 const home =632 stated.territory.module === "."633 ? "packages/parser"
11 unmodified lines
645646const allPassed = (askLane: string) =>647 ({ ...passed, [askLane]: "passed" }) as const;648695// ----------------------------------------------------------- decisions696649const decisionId = (n: number) =>650 DecisionId.make(`dec-${String(n).padStart(6, "0")}`);651652const proposalId = (n: number) =>
18 unmodified lines
671 project: vellum,672 subject: input.subject,673});674723/** The finish's diff: the answer's second round, whose test the first round had narrowed with `.only(`. */675const WRAP_PATCH = [676 "diff --git a/packages/render/src/table.ts b/packages/render/src/table.ts",677 "index 5d1c0e2..a8f4b71 100644",678 "--- a/packages/render/src/table.ts",
41 unmodified lines
720 "+// One case per width the renderer supports lives in table.widths.test.ts.",721 "",722].join("\n");723773// ---------------------------------------------------------------- ledger774775/** The ledger's standing parts; its entries are told with the story. */724const ledger: Ledger = {725 entries: [],726 layers: [727 {
12 unmodified lines
740 postureLabel: "Open with sealed evidence · sealed checks in export, parser",741 project: vellum,742};743796/**797 * The env shape at `at`: four items, one write-only and set at `setAt`,798 * none with a value or placeholder.799 */744const envAt = (at: LandedSha, setAt: DateTime.Utc): EnvSchemaView => ({745 at,746 file: RepoPath.make(".env.schema"),747 imports: [],
37 unmodified lines
785 ],786 project: vellum,787});788845// ------------------------------------------------------------- proposals846789const proposal = (input: {790 readonly n: number;791 readonly at: DateTime.Utc;792 readonly proposer: Handle;
12 unmodified lines
805 want: input.want,806 ...present("draft", input.draft),807});808867/** A drafted ask's three files: its ask file, its check, and the document the check reads. */809const draftedFiles = (id: string, module: Module, want: string) => {810 const stated = fix({ id, module, want });811 const [askFile, testFile] = [...filesOf([stated])];812
8 unmodified lines
821 : [{ content: entry[1], path: RepoPath.make(entry[0]) }]822 );823};824884/** A family child's change: its module's entry on the new tokenizer. */825const childEntry = (module: Module): Files =>826 new Map([[`packages/${module}/src/index.ts`, entryOf(module, "tokenize")]]);827888/** A family child's change: its module's page settings under the new name. */828const childPage = (module: Module): Files =>829 new Map([[`packages/${module}/src/page.ts`, pageOf(module, "pageFormat")]]);830892// ------------------------------------------------------------- the story893894/**895 * The record vellum's story writes, over its canonical repo standing at896 * `base`: each instant written on the calendar, placed in this world.897 */831export const tellVellum = (base: LandedSha) =>832 Effect.gen(function* () {833 const { place } = yield* DevClock;834
42 unmodified lines
877 ),878 });879 });880948 // September: the first asks, answered by the people who have been here longest.881 yield* story.open({882 asks: [ask.quotes],883 at: t("2026-09-01T10:00"),884 by: people.ines,
32 unmodified lines
917 });918919 yield* story.tag("v0.8.0", palette.sha);920989 // The maintainers' layer, and the posture change that seals its checks.921 story.decision(922 decision({923 at: t("2026-09-28T09:00"),924 deciders: [people.ines, people.lin],
65 unmodified lines
990 suite: parserSuite,991 })992 );9931063 // October 4: the second family opens, and the standalone asks.994 yield* story.open({995 asks: pageSize.asks,996 at: t("2026-10-04T09:30"),997 by: people.ines,
121 unmodified lines
1119 at: t("2026-10-04T17:00"),1120 changes: childPage("cli"),1121 });11221193 // October 5.1123 story.record((seq) =>1124 LedgerEntry.cases.Admitted.make({1125 area: EXPORT,1126 at: t("2026-10-05T07:00"),
249 unmodified lines
1376 t("2026-10-05T16:00"),1377 parserSuite1378 );13791451 // October 6.1380 story.decision(1381 decision({1382 at: t("2026-10-06T07:00"),1383 deciders: [people.ines, people.lin],
390 unmodified lines
1774 subject: Subject.cases.OpenProposal.make({ proposal: proposalId(4) }),1775 })1776 );17771850 // October 7, this morning.1778 story.claim(1779 ask.exportErrors.id,1780 people.tove,1781 t("2026-10-07T07:00"),
113 unmodified lines
18951896 return { story, told: () => story.told(apart) };1897 });18981972/**1973 * The live landing: the first family's lint child, checking since this1974 * morning, passes its last lanes and lands at `at`, one more of six.1975 */1899export const landLintChild = (story: Story, at: DateTime.Utc) =>1900 Effect.gen(function* () {1901 const child = tokenizer.child("lint");1902
9 unmodified lines
modified:apps/web/src/dev/backend.ts+3 added-23 removed
1/**2 * `#backend` under the `development` condition (`vite dev`, vitest): the3 * contracts served in process by the dev world, so the web runs with no4 * platform, no Artifacts and no network. The browser reaches it through5 * the same `/rpc` route, the same `Contracts` group and the same atoms as6 * production; only this target differs. The session cookie becomes the7 * bearer here too (`withCredential`), so the cookie `/auth/dev`8 * sets signs a browser in to the dev world as that person.9 *10 * One world per isolate (`server.ts`): it is made and seeded when this11 * module loads, since `toWebHandler` builds at once, and kept for the12 * isolate's life. Under `vite dev` its seed ends at the minute it loads,13 * and its clock runs on from there (`clock.ts`), so a page reads each14 * deadline as the seed meant it on whatever day the server starts. Nothing15 * outside `src/dev/` imports this file, and the production build carries16 * none of it (`test/production-bundle.test.ts`).17 */1// One world per isolate, made and seeded when this module loads, since `toWebHandler` builds at once.2// Nothing outside `src/dev/` imports this file, so the production build carries none of it.3import type { Backend } from "../server/rpc.ts";4import { credentialFrom, withCredential } from "../server/session.ts";5import { fixturesMode } from "./fixtures.ts";6import { devServer } from "./server.ts";723/**24 * `vite dev` places the world at the present; vitest, whose `MODE` is25 * `test`, keeps the calendar as written, so a test reads the same instants26 * on every run.27 */8// vitest (`MODE` is `test`) keeps the calendar as written, so a test reads the same instants on every run.9const time = import.meta.env.MODE === "test" ? "fixed" : "present";1011const served = devServer({ fixtures: fixturesMode, time });1232/** The development backend: every request answered by the dev world, as the platform is asked; the env unused. */13export const backend: Backend = (request) =>14 served.handler(withCredential(request, credentialFrom(request)));
modified:apps/web/src/dev/checker.ts-11 removed
1/**2 * The dev world's Checker: the scripted `/memory` adapter, with a script it3 * writes as it goes, by one rule. A commit is checked only when a decider's4 * ask files are composed onto main, where the ask's check is red first, so5 * every lane fails there, the same way each time; a tree is checked only6 * when an answer is merged, and every lane passes there. A count lane (a7 * migrate ask's callers) prints what the examples state its command prints8 * on the project's first commit (`printedBy`), wherever it runs. No check9 * runs: the world shows the platform's flow, not a project's tests.10 */1import { CheckAt, CheckRunner } from "@repo/checks/check-runner";2import type { CheckJob } from "@repo/checks/check-runner";3import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";4import type { LaneResult } from "@repo/protocol/domain/answer";5import { Context, Effect, Layer } from "effect";67import { printedBy } from "./examples.ts";819/** What a lane comes to where it runs: red on a composed commit, green on a merged tree. */9const scripted = (10 job: CheckJob,11 lane: CheckJob["lanes"][number]12): LaneResult => ({
42 unmodified lines
modified:apps/web/src/dev/clock.ts+1 added-40 removed
1/**2 * The dev world's time: one clock that every part of the world reads, as a3 * test's TestClock is. The seed and the fixtures are written against one4 * fixed calendar, which starts at `devStart`: each step names its instant5 * on it (`devMinute`, or a fixture's date), and the seed sets the clock6 * there step by step. A world places that calendar on time by one offset,7 * the distance from `devStart` to where the world starts, so every instant8 * it holds is the calendar's moved by the same amount and the gaps between9 * them are as written.10 *11 * A world built for a test starts at `devStart` and its clock stands still12 * where the seed left it, so every timestamp is the same on every run. The13 * running dev server (`backend.ts`) starts its world so that the seed's14 * last instant is the minute it starts in (`startEndingNow`), and its clock15 * runs on from there in real time (`run`), so a page in a browser reads a16 * deadline as the seed meant it and sees it come. Elapsed time and sleeping,17 * which nothing in the world does, are always real.18 */1import { Clock, Context, DateTime, Duration, Effect, Layer } from "effect";221/** The dev world's clock: where its calendar stands, and the way to move it. */3export class DevClock extends Context.Service<4 DevClock,5 {25 /** The calendar's instant `at`, as it stands in this world. */6 readonly place: (at: DateTime.Utc) => DateTime.Utc;27 /** Stands the clock at the calendar's instant `at`; a running clock runs on from there. */7 readonly set: (at: DateTime.Utc) => Effect.Effect<void>;29 /** From the instant it stands at, the clock moves in real time. */8 readonly run: Effect.Effect<void>;31 /**32 * When something that happens now happens: on a running clock, the33 * present; on one standing still, a minute after where it stands, which34 * it then stands at, so the thing reads as after all before it.35 */9 /** On a running clock, the present; on one standing still, a minute after where it stands, so each thing reads as after all before it. */10 readonly step: Effect.Effect<DateTime.Utc>;11 }12>()("web/dev/DevClock") {}1314const NANOS_PER_MILLI = 1_000_000n;1542/** Where the calendar starts: every instant the seed writes is this one or a whole minute after. */16export const devStart: DateTime.Utc = DateTime.toUtc(17 DateTime.makeUnsafe("2026-10-07T09:00:00Z")18);1947/** The calendar's instant `minutes` whole minutes after its start. */20export const devMinute = (minutes: number): DateTime.Utc =>21 DateTime.add(devStart, { minutes });2251/**52 * Where a world starts whose calendar instant `end` is the present minute:53 * the clock read once, rounded down to its minute, less the calendar's54 * distance from its start to `end`.55 */23export const startEndingNow = (24 end: DateTime.Utc25): Effect.Effect<DateTime.Utc> =>26 Effect.map(DateTime.now, (now) =>
2 unmodified lines
29 DateTime.distance(devStart, end)30 )31 );3266/**67 * A world's clock, whose calendar starts at `start`: standing at `start`68 * until it is set or run, and the way to do either.69 */33export const devClockAt = (start: DateTime.Utc): Layer.Layer<DevClock> =>34 Layer.effectContext(35 Effect.gen(function* () {36 const real = yield* Clock.Clock;37 const offset = DateTime.distance(devStart, start);3839 const place = (at: DateTime.Utc) => DateTime.addDuration(at, offset);4078 // The instant the clock was last stood at, and, once it runs, the79 // monotonic reading it has run from since.41 let stood = DateTime.toEpochMillis(start);42 let runningSince: bigint | undefined;4344 const elapsedNanos = () =>
52 unmodified lines
modified:apps/web/src/dev/examples.ts+2 added-73 removed
1/**2 * The dev world's two fictional projects, as files: each one's first push,3 * the files a decider opens each ask with (its ask file, and its check when4 * the check is a file), and the commits its people push. The projects and5 * their people are invented; any likeness to a real one is not meant.1// The projects and their people are invented; any likeness to a real one is not meant.6 *7 * `datekit` is a small date library (the people of8 * `examples/datekit`): `ines-v` decides everything, `okonkwo` the time zones, and9 * `bram` is a vouched contributor. `burrow` is a six-package monorepo with10 * a legacy helper to migrate away from and a lint count to ratchet down11 * (`examples/burrow`), decided by `okafor` and `lin-h`. These are12 * cut-down copies: just enough for every page of the web to have something13 * real to show.14 *15 * A project's rules are its committed `policy.json`, the config folder the16 * `/json` rules evaluator reads, with every ask it will open stated there;17 * an ask opens when a decider lands its files. Each ask file is written18 * from the ask `policy.json` states, as the SDK call a maintainer writes,19 * so the two never disagree. datekit's `policy.json` also states the ask20 * the dev world's drafter drafts, which only an accepted draft opens.21 */2import { Brand } from "@repo/brand";3import { cannedDraft } from "@repo/drafting/draft-runs/canned";4import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";5import { Command, SymbolName } from "@repo/protocol/domain/common";
11 unmodified lines
17const decodeCheck = Schema.decodeSync(CheckSpec);1819const encodeMeasure = Schema.encodeSync(RatchetMeasure);2041/** What a project's `policy.json` states, as the file holds it. */21export type Stated = typeof PolicyInput.Encoded;2244/** One ask as `policy.json` states it. */23export type StatedAsk = Stated["asks"][number];2447/** A `policy.json` from what its project states, with every default written out. */25export const policyJson = (stated: Stated) =>26 `${JSON.stringify(27 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),28 null,29 230 )}\n`;3155/** One file an ask opens with. */32export interface AskFile {33 readonly content: string;34 readonly path: RepoPath;35}3661/** The files a decider opens one ask with: its ask file, then its check's file if it has one. */37export type Opening = Array.NonEmptyReadonlyArray<AskFile>;3864/** The args a kind takes for an ask's check, as its ask file passes them (`packages/sdk`'s `kinds`). */39interface KindArgs {40 readonly command?: string;41 readonly count?: string;42 readonly from?: string;
2 unmodified lines
45 readonly rule?: string;46 readonly to?: string | undefined;47}4875/** A string, or a list of them, as TypeScript source spells it. */49const spelled = (value: string | readonly string[]): string =>50 Predicate.isString(value)51 ? JSON.stringify(value)52 : `[${value.map(spelled).join(", ")}]`;5381/**82 * The args an ask's kind takes for its check, as the ask file spells them.83 * No SDK call states a `SymbolAbsent` check (a migrate's split opens its84 * delete step), so that file spells the nearest one: a migrate85 * with no `to`, every use gone.86 */54// No SDK call states a `SymbolAbsent` check, so the file spells the nearest one: a migrate with no `to`.55const checkArgs = (check: StatedAsk["check"]) =>56 CheckSpec.match(decodeCheck(check), {57 LintToZero: ({ command, rule }): KindArgs => ({ command, rule }),58 Migrate: ({ count, from, to }): KindArgs => ({ count, from, to }),
1 unmodified line
60 RedThenGreen: ({ path }): KindArgs => ({ path }),61 SymbolAbsent: ({ count, symbol }): KindArgs => ({ count, from: symbol }),62 });6396/** An ask's territory as its file spells it: the repo-wide builder for `.`, else the data itself. */64const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>65 module === "."66 ? `territory.paths(${paths.map(spelled).join(", ")})`67 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;68102/** An ask's file: the SDK call that states `stated`, as its maintainer writes it. */69export const askFileOf = (stated: StatedAsk): AskFile => {70 const territory = territoryOf(stated.territory);7172 const passed = Object.entries({
28 unmodified lines
101 path: RepoPath.make(stated.file),102 };103};104139// ------------------------------------------------------------- datekit140141/**142 * The operator, who makes the dev world's examples in their namespace as143 * the stages' were made, so `oscabriel/datekit` is theirs and the legacy144 * address `/datekit` leads to it. They decide nothing: each project's145 * config folder names its deciders.146 */105export const operator = Handle.make("oscabriel");106107export const datekitPeople = {108 contributor: Handle.make("bram"),
11 unmodified lines
120 requires: ["want", "check", "territory"],121 strength: "assertion",122} satisfies typeof AskKind.Encoded;123166/** One datekit ask: as `policy.json` states it, and the check file it opens with. */124interface DatekitAsk {125 readonly stated: StatedAsk;126 readonly test: AskFile;127}128172/**173 * One datekit ask, from its id, the module file it fixes, its brief and its174 * check's one test (red on main, by an assertion). One held for a newcomer175 * names the maintainer who mentors them. datekit is one package, so every176 * territory is in the repo-wide module, `.`.177 */129const datekitAsk = (input: {130 readonly id: string;131 readonly file: string;132 readonly current: string;
55 unmodified lines
188 datekitAsk({189 current: 'format prints "11st", "12nd" and "13rd".',190 file: "format",191 id: "format-ordinal",241 // Held for a newcomer, whom its asker mentors.192 mentor: datekitPeople.decider,193 test: {194 assertion: 'expect(format(parseISO("2026-10-11"), "Do")).toBe("11th");',195 imports: [
32 unmodified lines
228 want: "diffInDays counts calendar days across a daylight-saving change.",229 }),230];231282/**283 * The ask the dev world's drafter drafts for any want (`cannedDraft`),284 * stated beside datekit's own so the `/json` rules evaluator finds it once285 * a draft's files are composed; nobody opens it in the seed. A decider who286 * accepts the draft opens it.287 */232const draftedAsk: StatedAsk = {233 askedBy: datekitPeople.decider,234 blockedBy: [],235 brief: { current: cannedDraft.current, want: cannedDraft.want },
169 unmodified lines
405 [AskId.make(stated.id), [askFileOf(stated), test]] as const406 ),407 files: library,408 project: ProjectName.make("oscabriel/datekit"),465 /** A commit someone pushed straight to main, past the platform. */409 stray: {410 files: new Map([411 [412 "README.md",
10 unmodified lines
423 message: "Mention time zones in the README",424 },425} as const;426484// -------------------------------------------------------------- burrow485427export const burrowPeople = {428 decider: Handle.make("okafor"),429 second: Handle.make("lin-h"),430} as const;
18 unmodified lines
449);450451const PARENT = "drop-legacy-fetch";452512/**513 * The one ask burrow's decider opens: the migrate. Its callers sit in all514 * six packages, so the platform opens it as a family: a child515 * per package and a delete child waiting on the six, their files written516 * beside the parent's in the same landing.517 */453const burrowAsks: readonly StatedAsk[] = [454 {455 askedBy: burrowPeople.decider,456 blockedBy: [],
146 unmodified lines
603 files: monorepo,604 project: ProjectName.make("oscabriel/burrow"),605} as const;606672/** How many times `text` calls `symbol`, as burrow's `scripts/count-callers.ts` counts. */607const callsIn = (text: string, symbol: string) =>608 text.split(`${symbol}(`).length - 1;609676/** What burrow's count command prints on its first commit: each package's calls of `legacyFetch`. */610const burrowCallers = () => {611 const byModule = Object.fromEntries(612 PACKAGES.map((pkg) => [613 `@burrow/${pkg}`,
12 unmodified lines
626 total: Number.sumAll(Object.values(byModule)),627 });628};629697/**698 * What each count command of the examples prints, by the command: the dev699 * Checker runs none, so a count lane prints this wherever it runs.700 */630export const printedBy: ReadonlyMap<string, string> = new Map([631 [COUNT, burrowCallers()],632]);
modified:apps/web/src/dev/fixtures.ts+4 added-73 removed
1/**2 * The dev world's fixtures: the states a page draws that the default world3 * never reaches, served through the same contracts, beside datekit and4 * burrow. Off unless the dev server is started with the switch:5 *6 * VITE_DEV_FIXTURES=1 bun run --cwd apps/web dev # the fixtures7 * VITE_DEV_FIXTURES=live bun run --cwd apps/web dev # and the live landing8 *9 * The switch is a `VITE_` variable because the dev world runs in the10 * Worker's runtime, which sees no other variable of the shell that started11 * Vite; Vite writes `VITE_` ones into the modules it serves.12 *13 * With the switch on the world holds, beside the default two:14 *15 * - six small projects made through the project service, as the seed makes16 * datekit (`fixtures/fillers.ts`), so the project list runs past eight,17 * one of them with no open asks;18 * - `vellum`, whose record is told as a story (`fixtures/vellum.ts`). Its19 * repo and policy are real: the service made the project and took its20 * first push, and every landing is a commit on its `main`. What the21 * service cannot reach in a world with no visibility cartridge (a ledger22 * with layers, sealed areas, an env item someone set, a refusal at Shape23 * kept as a verdict, a finish put to a decider) is in the record, which24 * answers vellum's reads in place of the service's own: its asks,25 * events, verdicts, landings, decisions and Today, ledger, env shape,26 * proposals, claims and forks. Writes other than a decision reach the27 * service underneath, which holds none of the record's asks.28 *29 * In live mode the lint child of vellum's first family, checking since the30 * morning, lands `LIVE_AFTER` after the world first answers vellum's31 * `watch`: on the first read of vellum after that, as the dev world's pages32 * poll, so a page left open sees one more landing arrive.33 */1// The switch is a `VITE_` variable because the dev world runs in the Worker's runtime,2// which sees no other variable of the shell that started Vite.3import { RepoHost } from "@repo/artifacts/repo-host";4import { envSchemaMethod } from "@repo/project/deciders";5import type { ProjectApi } from "@repo/project/project";6import { ProjectedEvent } from "@repo/project/projection";
51 unmodified lines
58import { DevProjected } from "./projection.ts";59import { seedDev, startedAt } from "./seed.ts";60import { devWorldWith } from "./world.ts";6193/** Off, on, or on with the live landing. */62export type FixtureMode = "off" | "on" | "live";6364const Switch = Schema.Literals(["1", "on", "live"]);6598/** The switch, read once from where Vite puts it. */66export const fixturesMode: FixtureMode = Option.match(67 Schema.decodeUnknownOption(Switch)(import.meta.env.VITE_DEV_FIXTURES),68 {69 onNone: (): FixtureMode => "off",70 onSome: (on): FixtureMode => (on === "live" ? "live" : "on"),71 }72);73107/** Whether the dev world adds the fixtures. */74export const fixturesOn = fixturesMode !== "off";75110/** How long after vellum's `watch` is first answered its lint child lands, in live mode. */76export const LIVE_AFTER = Duration.seconds(20);77113/** vellum's story, and the record it has told so far, decoded. */78interface Told {79 readonly record: FixtureRecord;80 readonly story: Story;81 readonly told: () => FixtureRecord;82}83120/** The fixtures' state in one world: vellum's story once told, and the live landing's clock. */84export class Fixtures extends Context.Service<85 Fixtures,86 {87 readonly told: Ref.Ref<Option.Option<Told>>;125 /** How long after the first `watch` the live landing waits; none, no live landing. */88 readonly liveAfter: Option.Option<Duration.Duration>;127 /** When vellum's `watch` was first answered, by the monotonic clock. */89 readonly armedAt: Ref.Ref<Option.Option<bigint>>;90 readonly landed: Ref.Ref<boolean>;130 /** One write to the story at a time. */91 readonly lock: Semaphore.Semaphore;92 }93>()("web/dev/Fixtures") {}94
10 unmodified lines
105 });106 })107 );108149/** The person calling, when someone signed in is. */109const callerOf = (principal: Principal) =>110 Principal.match(principal, {111 Anonymous: () => Option.none<Person>(),112 Person: (person) => Option.some(person),113 });114156/** Whether `project` is one whose reads the fixtures answer. */115const isFixture = (project: ProjectName) => project === vellum;116159/** The ask as an answerer reads it first, in Markdown. */117const briefOf = (ask: Ask): string =>118 [119 `# ${ask.brief.want}`,120 "",
9 unmodified lines
130 : ["", "## Current", "", ask.brief.current]),131 "",132 ].join("\n");133177/**178 * vellum's reads answered from its record, everything else by the service179 * underneath; and the projection's events with vellum's from the record.180 */134const overlay: Layer.Layer<135 Projects | DevProjected,136 never,137 Projects | DevProjected | Fixtures | RepoHost | DevClock
15 unmodified lines
153 Effect.provideService(RepoHost, host),154 Effect.provideService(DevClock, devClock)155 );156204 /** The record's latest, once told. */157 const current = Effect.flatMap(Ref.get(fixtures.told), (told) =>158 Option.match(told, {159 onNone: () => Effect.die("vellum's story is not told yet"),160 onSome: ({ record }) => Effect.succeed(record),161 })162 );163212 /** A write to the story, under the lock, and the record told again. */164 const write = <A, E>(165 step: (story: Story) => Effect.Effect<A, E, RepoHost | DevClock>166 ) =>167 fixtures.lock.withPermits(1)(
11 unmodified lines
179 return out;180 })181 );182232 /**233 * vellum's `watch` was read from `since`: the first read arms the live234 * landing, and a read once it is due lands the lint child first. Only a235 * read's start counts (from the first event, or from the last one, as a236 * page that follows the stream asks); a later page of the same replay237 * never lands it in the middle of the replay.238 */183 // Only a read's start counts, so a later page of the same replay never lands it mid-replay.184 const heard = (since: number) =>185 Option.match(fixtures.liveAfter, {186 onNone: () => Effect.void,187 onSome: (after) =>
5 unmodified lines
193 }194195 const at = yield* Clock.monotonicTimeNanos;196252 // The read before this one armed it, or this read arms it.197 const armed = yield* Ref.modify(198 fixtures.armedAt,199 (was): readonly [Option.Option<bigint>, Option.Option<bigint>] =>200 Option.isSome(was)
55 unmodified lines
256 .slice(0, limit)257 .map((event) => ({ event, seq: event.seq }))258 )259 ),316 // As the service answers: a decider here or the log's claimant may317 // read; anyone else hears `NotDecider` whether or not a log is kept,260 // Anyone but a decider or the log's claimant hears `NotDecider` whether or not a log is kept,261 // so the reply tells no one which logs exist.262 evidence: (caller, ref) =>263 Effect.gen(function* () {264 const record = yield* current;
60 unmodified lines
325 Effect.fromOption(Option.fromUndefinedOr(proposals.get(id))).pipe(326 Effect.mapError(() => new UnknownProposal({ proposal: id }))327 )328 ),386 // The posture vellum's record's ledger shows, which no clock moves.329 standing: () =>330 Effect.map(current, (record) => ({331 posture: record.ledger.posture,332 seen: lastSeqOf(record),
49 unmodified lines
382 );383 })384);385444/**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 told447 * over its repo), and the world's clock left at the record's morning,448 * `fixturesNow`.449 */386const seedFixtures = Effect.gen(function* () {387 const fixtures = yield* Fixtures;388389 yield* seedFillers(30);
11 unmodified lines
401 yield* Ref.set(fixtures.told, Option.some({ record, story, told }));402 yield* (yield* DevClock).set(fixturesNow);403}).pipe(Effect.orDie);404469/**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 */405export const withFixtures = (406 mode: "on" | "live",407 liveAfter: Duration.Duration = LIVE_AFTER,408 start: DateTime.Utc = devStart
15 unmodified lines
modified:apps/web/src/dev/front-page.ts-27 removed
1/**2 * The dev world's front page: the read model the platform keeps in D13 * (`@repo/project/projection-d1`), folded the same way from the same rows,4 * which here are the events every project's outbox hands the world's5 * projection (`projection.ts`). An ask opened goes on the page and one closed comes off; a6 * claim marks it claimed until it lapses or is released. An entry is what7 * the anonymous viewer sees: takeable when no live claim holds it, nothing8 * it waits on is still on the page, and it is held for nobody; newest first.9 * A project is listed from its first event, `open` until a `PostureChanged`10 * ledger entry moves it, with when it last landed (the `projects` table);11 * `listProjects` reads each one's standing posture from its own ledger12 * (`withStandingPosture`) and keeps this one only as the fallback. A13 * person's credits are each project's own count, joined (`creditsFor`): the14 * rule D1's `credits` table is fed by, read at the source.15 */1import { FrontPage } from "@repo/project/front-page";2import type { FrontPageFilter } from "@repo/project/front-page";3import type { ProjectedEvent } from "@repo/project/projection";4import { creditsFor, Projects } from "@repo/project/projects";
9 unmodified lines
14import { Array, DateTime, Effect, Layer, Order } from "effect";1516import { DevProjected } from "./projection.ts";1733/** One open ask on the page, as D1's `front_page` row holds it. */18interface Row {19 readonly ask: AskListing;20 readonly claims: number;21 readonly openedAt: DateTime.Utc;22 readonly project: ProjectName;23}2441/** A project as D1's `projects` row holds it, but for its open asks, which the page counts. */25interface Listed {26 readonly landedAt?: DateTime.Utc;27 readonly posture: Posture;28}2930const keyOf = (project: ProjectName, ask: string) => `${project}/${ask}`;3149/** Every project's events in its own order. */32const inOrder = Order.mapInput(33 Order.Tuple([Order.String, Order.Number]),34 ({ event, project }: ProjectedEvent) => [project, event.seq] as const35);3655/** The page's rows with one ask's claim count moved by `change`, if it is on the page. */37const withClaims = (38 rows: ReadonlyMap<string, Row>,39 key: string,40 change: number
7 unmodified lines
48 claims: Math.max(row.claims + change, 0),49 });50};5171/** The page's rows after one project's event, as D1's statements change them. */52const step = (53 rows: ReadonlyMap<string, Row>,54 { event, project }: ProjectedEvent55): ReadonlyMap<string, Row> =>
24 unmodified lines
80 Released: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),81 Warned: () => rows,82 });83104/** The project list after one project's event, as D1's statements change it. */84const listedStep = (85 listed: ReadonlyMap<ProjectName, Listed>,86 { event, project }: ProjectedEvent87): ReadonlyMap<ProjectName, Listed> => {
19 unmodified lines
107const empty: ReadonlyMap<string, Row> = new Map();108109const unlisted: ReadonlyMap<ProjectName, Listed> = new Map();110132/** The page's rows after `events`, and every project they came from, by name. */111const fold = (events: readonly ProjectedEvent[]) => {112 const ordered = Array.sort(events, inOrder);113114 return {
7 unmodified lines
122};123124type Folded = ReturnType<typeof fold>;125148/** A project's posture as the list holds it: `open` until a ledger entry moves it. */126const postureOf = (folded: Folded, project: ProjectName): Posture =>127 folded.listed.get(project)?.posture ?? "open";128152/** One project as `listProjects` answers it. */129const listingOf =130 (folded: Folded) =>131 (project: ProjectName): ProjectListing => {132 const listing = {
6 unmodified lines
139140 return landedAt === undefined ? listing : { ...listing, landedAt };141 };142167/** Newest first, then by project and ask, as D1's query orders them. */143const newestFirst = Order.combineAll([144 Order.flip(Order.mapInput(DateTime.Order, ({ openedAt }: Row) => openedAt)),145 Order.mapInput(Order.String, ({ project }: Row) => project),146 Order.mapInput(Order.String, ({ ask }: Row) => ask.ask),147]);148174/** A row as the anonymous viewer sees it. */149const entryOf =150 (folded: Folded) =>151 (row: Row): FrontPageEntry => {152 const onPage = (ask: string) =>
18 unmodified lines
171 ({ ask }: Row) =>172 (kind === undefined || ask.kind === kind) &&173 (reserved === undefined || ask.reserve === reserved);174201/** `FrontPage` over the memory projection's events, and credits from `Projects`. */175export const DevFrontPage: Layer.Layer<176 FrontPage,177 never,178 Projects | DevProjected
25 unmodified lines
modified:apps/web/src/dev/git.ts+2 added-47 removed
1/**2 * Git for the dev world: commits written the way git writes them, so the3 * memory repo host takes them by a push like any other, and files read back4 * through `RepoHost`.5 *6 * The world writes three kinds of commit: each example project's first7 * push, an answerer's commit on their claim's fork, and what the dev Lander8 * composes and lands. Each is written whole, every blob and tree of its9 * files, as loose objects in a scratch git directory in memory; a push10 * copies only what the repo lacks. Text files only: the examples hold11 * nothing else.12 */1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { PushSource, TreeEntry } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { BlobSha, CommitSha } from "@repo/protocol/ids";5import type { Handle, RepoName } from "@repo/protocol/ids";6import { Array, DateTime, Effect, Option, Predicate } from "effect";720/** A tree's files, by path, as text: what the world writes. */8export type Files = ReadonlyMap<string, string>;923/** A file as a commit holds it: its blob's id, and its text. */10export interface Held {11 readonly blob: BlobSha;12 readonly text: string;13}1429/** A commit's files, by path, as read back. */15export type Snapshot = ReadonlyMap<string, Held>;1632/** The name and email an author or committer line carries. */17export interface Identity {18 readonly email: string;19 readonly name: string;20}2138/** The platform, which commits every landing. */22export const platformIdentity: Identity = {23 email: `platform@${Brand.domain}`,24 name: Brand.name,25};2644/** A person, as the author of their own commits and of their landings. */27export const personIdentity = (handle: Handle): Identity => ({28 email: `${handle}@users.${Brand.domain}`,29 name: handle,30});3150/** A snapshot's text alone. */32export const textOf = (snapshot: Snapshot): Files =>33 new Map([...snapshot].map(([path, { text }]) => [path, text]));3454/** `files` with `changed` written over them. */35export const overlay = (36 files: Files,37 changed: Iterable<readonly [string, string]>38): Files => new Map([...files, ...changed]);3960// --------------------------------------------------------------- objects6140const encoder = new TextEncoder();4142const decoder = new TextDecoder();43
16 unmodified lines
6061const bytesOfHex = (id: string) =>62 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));6386/** git's zlib stream, as a loose object holds it. */64const deflate = (bytes: Uint8Array) =>65 Effect.promise(() =>66 new Response(67 new Blob([Uint8Array.from(bytes)])
1 unmodified line
69 .pipeThrough(new CompressionStream("deflate"))70 ).arrayBuffer()71 ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));7296/** An object's header and content, and its id: the SHA-1 of both. */73const framed = (kind: "blob" | "tree" | "commit", content: Uint8Array) => {74 const raw = concat([75 encoder.encode(`${kind} ${content.byteLength}\0`),76 content,
32 unmodified lines
109 bytesOfHex(entry.sha),110 ])111 );112137/**138 * A commit message as git keeps it: no carriage returns, no blank lines139 * first, and one newline last (isomorphic-git writes it back so when the140 * memory host copies the commit, and the id must not change).141 */113// No carriage returns, no leading blank lines, one trailing newline: isomorphic-git writes it back so when the114// memory host copies the commit, and the id must not change.115const messageOf = (message: string) =>116 `${message.replaceAll("\r", "").replace(/^\n+/u, "").replace(/\n+$/u, "")}\n`;117118const signature = (who: Identity, at: DateTime.Utc) =>119 `${who.name} <${who.email}> ${Math.floor(DateTime.toEpochMillis(at) / 1000)} +0000`;120148/** A commit to write: its tree, parents, people, time and message. */121export interface CommitInput {122 readonly tree: ObjectId;123 readonly parents: readonly CommitSha[];124 readonly author: Identity;
13 unmodified lines
138 messageOf(input.message),139 ].join("\n")140 );141170// ------------------------------------------------------------ the source171142const failure = (code: string, path: string) =>143 Promise.reject(Object.assign(new Error(`${code}: ${path}`), { code }));144145const clean = (path: string) =>
1 unmodified line
147 .split("/")148 .filter((part) => part !== "")149 .join("/")}`;150181/** How isomorphic-git asks for a file: as bytes, or as text in "utf8", alone or as `{ encoding }`. */151type ReadOptions = string | { readonly encoding?: string } | undefined;152153const UTF8 = /^utf-?8$/iu;154
1 unmodified line
156 Predicate.isString(options)157 ? UTF8.test(options)158 : UTF8.test(options?.encoding ?? "");159191/** A write to the scratch directory through the file system: it only reads. */160const readOnly = (raw: string) => failure("EROFS", clean(raw));161162const stats = (kind: "file" | "dir", size: number) => ({163 ctimeMs: 0,
8 unmodified lines
172 size,173 uid: 1,174});175208/**209 * The part of `fs.promises` isomorphic-git calls when a push reads its210 * source (`docs/fs.md` there), over loose objects kept by path. It only211 * reads: the scratch directory is written by `scratch`, never through it.212 */176const readOnlyFs = (files: ReadonlyMap<string, Uint8Array>) => {177 const childrenOf = (dir: string) => {178 const prefix = dir === "/" ? "/" : `${dir}/`;179
57 unmodified lines
237 },238 };239};240278/** A git directory in memory that a push takes objects from, and how to write into it. */241export interface Scratch {242 readonly source: PushSource;281 /** Every blob and tree of `files`, and the root tree's id. */243 readonly tree: (files: Files) => Effect.Effect<ObjectId>;244 readonly commit: (input: CommitInput) => Effect.Effect<CommitSha>;245}246247const GITDIR = "/scratch.git";248288/** A fresh scratch git directory: loose, zlib-deflated objects named by their ids. */249export const scratch: Effect.Effect<Scratch> = Effect.sync(() => {250 const objects = new Map<string, Uint8Array>();251252 const write = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>
53 unmodified lines
306 tree: (files) => folder([...files]),307 };308});309350// ----------------------------------------------------------------- reads351352/** One file of a snapshot: its path, its blob's id and its text. */310const fileOf =311 (path: string, blob: ObjectId) =>312 (bytes: Uint8Array): Snapshot =>313 new Map([314 [path, { blob: BlobSha.make(blob), text: decoder.decode(bytes) }],315 ]);316360/** Every file under the tree `tree` of `repo`, by path; none when the repo lacks an object. */317const snapshotOf = (318 repo: RepoName,319 tree: ObjectId,320 prefix: string
23 unmodified lines
344 (parts): Snapshot => new Map(parts.flatMap((part) => [...part]))345 );346 });347392/** `repo`'s files at `commit`; none when the repo or the commit is not there. */348export const filesAt = (349 repo: RepoName,350 commit: CommitSha351): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>
11 unmodified lines
modified:apps/web/src/dev/handlers.ts+1 added-37 removed
1/**2 * Every contract, served by the dev world the way the platform serves it3 * (`apps/platform/src/handlers.ts`, which an app may not import): a4 * contract that names a project calls that project's service as the caller5 * `Authenticated` named; the cross-project reads (`listProjects`,6 * `frontPage`, `credits`) come from the front page folded over the world's7 * projects; `status` and `today` without a project ask every project it8 * lists and merge what each says; `evidence` reads the world's lane logs.9 * Unlike the platform, nothing spends a rate limit: the world has one10 * browser at a time. Every `remote` names the origin the caller reached the11 * world by, as the platform's do. The code reads run the same12 * `@repo/project/code` functions the platform's do, over the world's13 * `RepoHost`.14 */1import { RepoHost } from "@repo/artifacts/repo-host";2import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";3import {4 codeProjectOf,
23 unmodified lines
28import type { Layer } from "effect";29import { HttpServerRequest } from "effect/http";30import type { Rpc, RpcGroup } from "effect/rpc";3146/** How many commits a page of `log` holds when the caller names no limit. */32const LOG_PAGE = 30;3349/** How many events `watch` reads from its project at a time. */34const EVENT_PAGE = 100;3552/** The caller, as the `Authenticated` server side named them. */36const caller = Effect.service(CurrentPrincipal);3755/**56 * The caller of a contract only a person may call. `Authenticated` lets an57 * anonymous call reach only a `public` contract, so anyone else here is a58 * defect in the server side, never a caller to serve.59 */38// `Authenticated` lets an anonymous call reach only a `public` contract, so anyone else here is a defect.39const person = Effect.flatMap(caller, (principal) =>40 Principal.match(principal, {41 Anonymous: () =>42 Effect.die("a contract for signed-in people was called anonymously"),43 Person: (named) => Effect.succeed<Person>(named),44 })45);4668/** Where the caller reached the world: the request's origin. */47const gateway = Effect.map(48 Effect.serviceOption(HttpServerRequest.HttpServerRequest),49 (request) =>50 Option.getOrElse(
3 unmodified lines
54 () => "http://localhost"55 )56);5780/** A repo's git URL at the origin the caller came through. */58const remoteOf = (repo: RepoName | ProjectName) =>59 Effect.map(gateway, (origin) => `${origin}/${repo}.git`);6084/** A claim, with its fork's URL at the caller's origin. */61const atGateway = (claim: ClaimView) =>62 Effect.map(remoteOf(claim.fork), (remote): ClaimView => ({63 ...claim,64 remote,65 }));6691/** The caller's claims and answers, each claim at the caller's origin, under their handle. */67const statusAtGateway = (68 who: Person,69 status: {70 readonly answers: readonly AnswerView[];
5 unmodified lines
76 claims,77 handle: who.handle,78 }));79105/** Decisions across projects: soonest to expire first, then oldest, then by project and id. */80const byExpiry: Order.Order<Decision> = Order.combineAll([81 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),82 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),83 Order.mapInput(Order.String, ({ project }: Decision) => project),84 Order.mapInput(Order.String, ({ id }: Decision) => id),85]);86113/**114 * One decider's Today across the projects they decide in, as the platform115 * merges it: budgets added up, decisions in one order of expiry, the rest116 * side by side. A person who decides in none has no Today.117 */87const acrossProjects = (88 decider: Person,89 pages: readonly Today[]90): Effect.Effect<Today, NotDecider> => {
22 unmodified lines
113 })114 : Effect.fail(new NotDecider({}));115};116148/** Every contract over the dev world. A missing contract is a type error here. */117export const devHandlers: Layer.Layer<118 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,119 never,120 Projects | FrontPage | EvidenceStore | RepoHost
3 unmodified lines
124 const frontPage = yield* FrontPage;125 const evidence = yield* EvidenceStore;126 const host = yield* RepoHost;127160 /** `call` on the project named `project`; one never made is `UnknownProject`. */128 const on = <A, E>(129 project: ProjectName,130 call: (api: ProjectApi) => Effect.Effect<A, E>131 ) => Effect.flatMap(projects.get(project), call);132166 /** A code read of `project`'s canonical repo, over the world's `RepoHost`. */133 const code = <A, E>(134 project: ProjectName,135 read: (of: CodeProject) => Effect.Effect<A, E, RepoHost>136 ) =>
2 unmodified lines
139 Effect.provideService(RepoHost, host)140 )141 );142177 /** `call` on every project the front page lists, in name order, keeping what each finds. */143 const everywhere = <A, E>(144 call: (api: ProjectApi) => Effect.Effect<Option.Option<A>, E>145 ) =>146 Effect.gen(function* () {
176 unmodified lines
323 if (project !== undefined) {324 return yield* on(project, (api) => api.today(who));325 }326362 // A project the caller decides nothing in has no page for them.327 const pages = yield* everywhere((api) =>328 api.today(who).pipe(329 Effect.asSome,330 Effect.catchTag("NotDecider", () => Effect.succeedNone)
31 unmodified lines
modified:apps/web/src/dev/lander.ts+3 added-20 removed
1/**2 * The dev world's Lander: what the trusted Lander does, over the memory3 * repo host, in a few lines a developer can read. It composes a decider's4 * files onto main for a check, merges an answer by laying the files it5 * changed over main (a path both main and the answer changed since the6 * answer's base is a conflict), lands a tree on main as the platform's7 * commit with a compare-and-swap push and then the mirror ref, and reads the8 * config folder at a commit. It writes no verdict notes: nothing in the9 * world reads them. The scripted `/memory` Lander answers in a fixed order,10 * which a world people click through can't follow, so this one does the11 * work, as `/isogit` does, through `git.ts`.12 */1// The scripted `/memory` Lander answers in a fixed order, which a world people click through can't follow,2// so this one does the work over the memory repo host.3import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";4import { Brand } from "@repo/brand";5import { composeRef, Lander, landedRef, Rebuild } from "@repo/project/lander";6import type { Change, LandJob } from "@repo/project/lander";
16 unmodified lines
23const mainRef = RefName.make("refs/heads/main");2425const blocked = () => new VerifierBlocked({});2637/** A commit's files, or `VerifierBlocked` when the repo doesn't hold it. */27const read = (repo: RepoName, commit: CommitSha) =>28 filesAt(repo, commit).pipe(29 Effect.flatMap(Effect.fromOption),30 Effect.mapError(blocked)31 );3244/** What `head` changed against `base`, path by path, in path order. */33const changesOf = (base: Snapshot, head: Snapshot): readonly Change[] =>34 Array.dedupe([...base.keys(), ...head.keys()])35 .toSorted()36 .flatMap((path): readonly Change[] => {
22 unmodified lines
59 },60 ];61 });6275/** An answer's head merged onto main: main's files with what the answer changed laid over them. */63const merged = (input: {64 readonly repo: RepoName;65 readonly main: LandedSha;66 readonly fork: RepoName;
21 unmodified lines
88 main: input.main,89 });90 }91105 // Main's files, with each path the answer changed as the answer left it.92 const files = new Map(textOf(main));9394 for (const { path } of changes) {95 const text = head.get(path)?.text;
7 unmodified lines
103104 return { changes, files: files satisfies Files };105 });106121/** The files a landing's tree is rebuilt from. */107const rebuilt = (job: LandJob) =>108 Rebuild.$match(job.rebuild, {109 Compose: ({ files }) =>110 Effect.map(read(job.repo, job.main), (main) =>
9 unmodified lines
120 ({ files }) => files121 ),122 });123139/** The commit an answer's landing was made on: its base; otherwise main. */124const baseOf = (job: LandJob) =>125 Rebuild.$is("Merge")(job.rebuild) ? job.rebuild.base : job.main;126143/** The Lander over the memory repo host, landing at the world's clock. */127export const DevLander: Layer.Layer<Lander, never, RepoHost> = Layer.effect(128 Lander,129 Effect.gen(function* () {130 const host = yield* RepoHost;
67 unmodified lines
198 yield* Ref.update(landedBy, (all) =>199 new Map(all).set(job.requestId, sha)200 );201219 // The mirror follows main in a push of its own (ADR 0005).202 // The mirror follows main in a push of its own.203 const mirror = yield* tipOf(job.repo, landedRef);204205 yield* host206 .push(job.repo, into.source, [
67 unmodified lines
modified:apps/web/src/dev/projection.ts+2 added-10 removed
1/**2 * Where the dev world's projects send their events for the read models:3 * the `Projection` port in memory, keyed as the D1 projection keys its rows,4 * by project and event number, so one world holds every project's events5 * and a row delivered twice is kept once. (`@repo/project`'s own memory6 * projection keys rows by their outbox id, `projected:<seq>`, which two7 * projects share: it suits a test of one project, not a world of two.)8 */1// Keyed by project and event number: `@repo/project`'s memory projection keys rows by outbox id,2// which two projects share.3import { Projection, ProjectedEvent } from "@repo/project/projection";4import { Context, Effect, Layer, Ref, Schema } from "effect";56const decodeProjected = Schema.decodeUnknownEffect(7 Schema.toCodecJson(ProjectedEvent)8);916/** Every event the world's projects have projected, in the order they first arrived. */10export class DevProjected extends Context.Service<11 DevProjected,12 { readonly events: Effect.Effect<readonly ProjectedEvent[]> }13>()("web/dev/DevProjected") {}1422/** A fresh, empty projection, and the reading of it. */15export const DevProjection: Layer.Layer<Projection | DevProjected> =16 Layer.effectContext(17 Effect.gen(function* () {18 const taken = yield* Ref.make<ReadonlyMap<string, ProjectedEvent>>(
31 unmodified lines
modified:apps/web/src/dev/seed.ts-59 removed
1/**2 * The dev world's seed: both fictional projects (`examples.ts`) brought to3 * a state where every page has something to show, by the project service's4 * own methods, in the order people would act. The seed plays the people and5 * the platform's other parts: the initializer's first push and the gateway6 * that reports it, a decider opening asks, a contributor claiming one,7 * pushing an answer to the claim's fork through a harness and offering it8 * as custody does (it lands, through the answer's run, in the same call,9 * 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 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).21 */1import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";2import type { ProjectApi } from "@repo/project/project";3import { Projects } from "@repo/project/projects";4import type { HarnessAudit } from "@repo/protocol/audit";
17 unmodified lines
22import type { Files } from "./git.ts";2324const mainRef = RefName.make("refs/heads/main");2547/** People who propose and flag in datekit; nobody vouched for them. */26export const visitors = {27 flagger: Handle.make("sefa"),28 proposer: Handle.make("tove"),29 regular: Handle.make("wren"),30} as const;3154/** Everyone in the seed: the people a dev token may sign in as. */32export const devPeople: readonly Handle[] = [33 operator,34 datekitPeople.decider,35 datekitPeople.zones,
6 unmodified lines
42];4344const as = (handle: Handle) => Person.make({ handle });4569/**70 * The harness bram answers through, as the CLI's credential helper names it71 * to the gateway and custody reports it: audit metadata, never a credit.72 */46const bramsHarness = {47 harness: "claude-code",48 model: "haiku",49} as const satisfies HarnessAudit;5078/** A commit of `files` on `parent` (or a first commit), by `author`, at the world's time. */51const commitOf = (input: {52 readonly author: Handle;53 readonly files: Files;54 readonly message: string;
14 unmodified lines
6970 return { commit, source: into.source };71 });72101/** A commit pushed to `repo`'s main with a compare-and-swap from `parent`. */73const pushed = (repo: RepoName, input: Parameters<typeof commitOf>[0]) =>74 Effect.gen(function* () {75 const host = yield* RepoHost;76 const { commit, source } = yield* commitOf(input);
8 unmodified lines
8586 return commit;87 });88118/** The files of `repo` at `commit`, which the seed itself pushed. */89const filesOf = (repo: RepoName, commit: CommitSha) =>90 Effect.flatMap(filesAt(repo, commit), Effect.fromOption);91122/** Moves the world's clock to the calendar's minute `minute`. */92const at = (minute: number) =>93 Effect.flatMap(Effect.service(DevClock), (clock) =>94 clock.set(devMinute(minute))95 );96128/**129 * A project made and adopted at the calendar's instant `when`: its130 * initializer creates it, pushes its first commit a minute later, and the131 * gateway reports the push.132 */97export const startedAt = (98 project: ProjectName,99 initializer: Handle,100 files: Files,
21 unmodified lines
122123 return { api, landed };124 });125162/** A project made and adopted at the calendar's minute `minute`. */126const started = (127 project: ProjectName,128 initializer: Handle,129 files: Files,
3 unmodified lines
133 startedAt(project, initializer, files, devMinute(minute)),134 ({ api }) => api135 );136174/** Each ask opened by `decider` from its files, a minute apart from `minute`. */137export const opened = (138 api: ProjectApi,139 decider: Handle,140 asks: readonly (readonly [AskId, Opening])[],
8 unmodified lines
149 ),150 { discard: true }151 );152191/**192 * An answer to `ask` from `answerer`, who holds its claim: a commit of193 * `files` on the claim's base, pushed to the claim's fork through `audit`'s194 * harness, reported as the gateway's custody reports it, then offered as195 * the answer.196 */153const answered = (154 api: ProjectApi,155 answerer: Handle,156 input: {
40 unmodified lines
197 requestId: RequestId.make(`push-${head}-${answerer}`),198 });199 });200245/** The decision that puts proposal `proposal` to `decider`. */201const decisionOn = (api: ProjectApi, decider: Handle, proposal: ProposalId) =>202 Effect.flatMap(api.today(as(decider)), ({ decisions }) =>203 Effect.fromOption(204 Array.findFirst(
4 unmodified lines
209 )210 )211 );212258/** Proposals from a regular that datekit's decider declines, each on its own minute. */213const DECLINED = [214 "parseISO accepts two-digit years.",215 "datekit wraps the Temporal API.",216];217264/** datekit: four asks opened, one answered and landed, one claimed, decisions waiting. */218const seedDatekit = Effect.gen(function* () {219 const { contributor, decider } = datekitPeople;220 const api = yield* started(datekit.project, operator, datekit.files, 0);221
47 unmodified lines
269270 return api;271});272320/** burrow: the migrate ask opened as its family, six children and a delete child waiting on them. */273const seedBurrow = Effect.flatMap(274 started(burrow.project, operator, burrow.files, 15),275 (api) => opened(api, burrowPeople.decider, burrow.asks, 17)276);277326/** The seed's last minute: the stray push. */278const STRAY_MINUTE = 21;279329/** The calendar's instant the seed leaves the world's clock at. */280export const seedEnd = devMinute(STRAY_MINUTE);281332/**333 * Someone with access to datekit's storage pushes to `main` past the334 * platform, and the push event reports it: a `StrayPush` decision whose335 * default is to revert.336 */282const strayPush = (api: ProjectApi) =>283 Effect.gen(function* () {284 const host = yield* RepoHost;285 const repo = RepoName.make(keyOf(datekit.project));
20 unmodified lines
306 repo,307 });308 });309365/**366 * Both projects, seeded; the world's clock left at the last step. Any367 * refusal on the way is a defect of the seed's, never a state to serve.368 */310export const seedDev: Effect.Effect<311 void,312 never,313 Projects | RepoHost | DevClock
6 unmodified lines
modified:apps/web/src/dev/server.ts+1 added-32 removed
1/**2 * The dev world as a fetch handler: `POST /rpc` is an `RpcServer` over3 * `Contracts` with the dev handlers, protocol's `Authenticated` server side4 * over dev tokens (`sessions.ts`) and JSON, as the platform's `/rpc` serves5 * it, over a fresh world the seed has brought to its state; and6 * `GET /<project>/raw/<rev>/<path…>` answers a project's raw files with7 * the response the platform's `raw.ts` gives (`@repo/project/code/raw`).8 * `backend.ts` makes the one an isolate serves; a test makes its own.9 */1import { RepoHost } from "@repo/artifacts/repo-host";2import { rawFor } from "@repo/project/code/raw";3import { Projects } from "@repo/project/projects";4import { Contracts } from "@repo/protocol/contracts";
11 unmodified lines
16import { seedDev, seedEnd } from "./seed.ts";17import { devSessions } from "./sessions.ts";18import { devWorldAt } from "./world.ts";1929/** How a dev world is made: with the fixtures or without, how soon the live landing comes, and when it is. */20export interface DevWorldOptions {21 readonly fixtures?: FixtureMode;32 /** In `live` mode, how long after vellum's `watch` is first answered its lint child lands. */22 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 */23 readonly time?: "fixed" | "present";24}2544/** The calendar's instant a seed with `fixtures` leaves the clock at. */26const seedEndOf = (fixtures: FixtureMode) =>27 fixtures === "off" ? seedEnd : fixturesNow;2848/** A fresh world whose calendar starts at `start`, seeded; with the fixtures when `fixtures` asks for them. */29const seededFrom = (start: DateTime.Utc, options: DevWorldOptions) => {30 const { fixtures = "off" } = options;3132 return fixtures === "off"33 ? Layer.effectDiscard(seedDev).pipe(Layer.provideMerge(devWorldAt(start)))34 : withFixtures(fixtures, options.liveAfter, start);35};3657/** A fresh world, seeded, at the time `options` asks for. */37const seededWorld = (options: DevWorldOptions) => {38 const { fixtures = "off", time = "fixed" } = options;3940 return time === "fixed"
8 unmodified lines
49};5051const decodeProject = Schema.decodeUnknownOption(ProjectName);5274/**75 * `/<project>/raw/<rev>/<path…>`: a project's raw files, as the platform76 * serves them, at each spelling of a name: `oscabriel/datekit`,77 * `github.com/pallets/click`, and a key from before owners, `datekit`.78 */53const raw = Layer.unwrap(54 Effect.gen(function* () {55 const services = Context.make(RepoHost, yield* RepoHost).pipe(56 Context.add(Projects, yield* Projects)
24 unmodified lines
81 );82 })83);84111/**112 * The contracts at `/rpc` and the raw files over a fresh, seeded world. `toWebHandler` builds113 * its layer as soon as it is called, so the world is made and seeded from114 * that moment, and a request that arrives before the seed is done waits for115 * it. `dispose` ends the world.116 */85// `toWebHandler` builds its layer as soon as it is called; a request that arrives before the seed is done waits for it.86export const devServer = (options: DevWorldOptions = {}) =>87 HttpRouter.toWebHandler(88 Layer.merge(89 RpcServer.layerHttp({
10 unmodified lines
modified:apps/web/src/dev/sessions.ts+2 added-16 removed
1/**2 * Who calls the dev world: protocol's own `Authenticated` server side3 * (`authenticated`), the rule the platform serves by, over a table of dev4 * tokens. `dev-<handle>` names that person of the seed's fictional people;5 * any other credential names nobody, so the call is `Unauthenticated`; a6 * call with none is anyone, for a `public` contract only. The tokens are7 * literal and exist only under the `development` condition, which the8 * production build never resolves.9 *10 * The world reads the credential from the call's headers, which the RPC11 * server fills from the HTTP request's own, so a browser's `Authorization`12 * reaches it as it reaches the platform. (The platform also refuses one an13 * RPC message adds to its own headers; the dev world does not check.)14 */1// The tokens are literal and exist only under the `development` condition, which the production build never resolves.2// Unlike the platform, the dev world does not refuse a credential an RPC message adds to its own headers.3import { authenticated } from "@repo/protocol/authenticate";4import type { Handle } from "@repo/protocol/ids";5import { Person } from "@repo/protocol/principal";6import type { Authenticated } from "@repo/protocol/principal";
1 unmodified line
8import type { Layer } from "effect";910import { devPeople } from "./seed.ts";1124/** The dev token that signs in as `handle`. */12export const devToken = (handle: Handle) => `dev-${handle}`;1314const tokens: ReadonlyMap<string, Handle> = new Map(15 devPeople.map((handle) => [devToken(handle), handle])16);1731/** The person a dev token names, if it names one of the seed's people. */18const personOf = (token: string) =>19 Option.map(Option.fromNullishOr(tokens.get(token)), (handle) =>20 Person.make({ handle })21 );
4 unmodified lines
modified:apps/web/src/dev/world.ts-29 removed
1/**2 * The dev world: the project service over memory adapters, every project3 * in one isolate, as `@repo/project`'s own scenario test runs it. Repos live4 * in the memory repo host and move only by real git objects (`git.ts`); the5 * Lander does the trusted Lander's work over them (`lander.ts`); the6 * Checker is scripted (`checker.ts`); rules are read from each project's7 * committed `policy.json` (`/json`); answers run in process; alarms are8 * recorded and never fire; the front page is folded from the projection's9 * 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, its calendar starting where the world is told to14 * (`clock.ts`).15 */1import type { RepoHost } from "@repo/artifacts/repo-host";2import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3import type { EvidenceStore } from "@repo/checks/evidence-store";4import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";
15 unmodified lines
20import { DevFrontPage } from "./front-page.ts";21import { DevLander } from "./lander.ts";22import { DevProjection } from "./projection.ts";2339/** Every port a project needs but its store, shared by every project in the world. */24const ports = Layer.mergeAll(25 AlarmsMemory,26 AnswerRunsInline,27 cannedDrafter,
3 unmodified lines
31 Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)),32 Layer.provideMerge(RepoHostMemory)33);3451/** The project service over every port, before anything reads it. */35const core = withDraftRunsInline(ProjectsMemory).pipe(36 Layer.provideMerge(ports)37);3856/** What the read side of a world is built over: its projects and their projected events. */39export type DevCore = Layer.Success<typeof core> | DevClock;4059/**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 is62 * given (the fixtures do, `fixtures.ts`), with its calendar starting at63 * `start`. Built twice, it is two worlds.64 */41export const devWorldWith = <Out, E, In extends DevCore>(42 between: Layer.Layer<Out, E, In>,43 start: DateTime.Utc = devStart44) =>
3 unmodified lines
48 Layer.provideMerge(devClockAt(start)),49 Layer.fresh50 );5176/**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 at79 * `start`. Built twice, it is two worlds.80 */52export const devWorldAt = (53 start: DateTime.Utc54): Layer.Layer<Projects | FrontPage | EvidenceStore | RepoHost | DevClock> =>55 devWorldWith(Layer.empty, start);
modified:apps/web/src/routes/[.]well-known/agent-skills/$.ts-2 removed
3 unmodified lines
4import { backend } from "#backend";56import { forwarded } from "../../../features/agents/forward.ts";78// The projects' contribute skills and their index: the platform serves9// them from each project's landed tree; the web host passes GET and HEAD on.8export const Route = createFileRoute("/.well-known/agent-skills/$")({9 server: { handlers: forwarded(backend, env) },10});
modified:apps/web/src/routes/[.]well-known/mcp[.]json.ts-2 removed
2 unmodified lines
34import { mcpCard } from "../../features/agents/llms.ts";5import { cardResponse } from "../../features/agents/respond.ts";67// The platform's MCP endpoint, described for a client that starts from the8// web host: where it is, how it speaks, and where to learn to sign in.7export const Route = createFileRoute("/.well-known/mcp.json")({8 server: {9 handlers: {10 GET: () =>
4 unmodified lines
modified:apps/web/src/routes/$owner/$project/answers/$ask.tsx+1 added-19 removed
24 unmodified lines
25import { pageHead } from "../../../../features/shared/head.ts";26import { branchPage } from "../../../../server/cache-headers.ts";27import { serverClient } from "../../../../server/client.ts";2829// The answer page: where the latest answer to an ask stands, stage by30// stage, or with `?head=<sha>` an earlier answer. It updates live while31// open, from the project's events.3229const answerPage = createServerFn({ method: "GET" })30 .validator((address: AnswerAddress) => address)31 .handler(({ data }) =>32 Effect.runPromise(readAnswer(data).pipe(Effect.provide(serverClient(env))))33 );3439/** No landing to read: what the page reads while the answer has not landed. */35const noLanding = Atom.make(Option.none<LandingView>());3642/**43 * The landing at `sha`, from its atom (seeded when the loader read it), or44 * as the loader read it. One hook whether or not the answer landed, so the45 * page keeps its place in the tree when the answer lands while it is open46 * (its outcome settles in rather than the page drawing anew).47 */37// One hook whether or not the answer landed, so the page keeps its place in the tree when it lands while open.38const useLanding = (39 read: AnswerPageData,40 sha: LandedSha | undefined41): LandingView | undefined => {
11 unmodified lines
53 sha !== undefined && read.landing?.sha === sha ? read.landing : undefined54 );55};5667/**68 * The page over its atoms, which start from what the loader read and read69 * again as the project's events arrive: the verdict, the ask, its landing,70 * and the events the fold reads.71 */57const FreshAnswer = ({58 read,59 viewer,60}: {61 readonly read: AnswerPageData;62 readonly viewer: Handle | undefined;63}) => {79 // Live: each event the project hears reads again what it changed.64 useAtomMount(watchAtom(read.project));6566 const { verdict } = Option.getOrElse(67 AsyncResult.value(
64 unmodified lines
132 </SeededAtoms>133 );134};135152/** An address with no refusal behind it: a name that can name nothing, or a `?head=` that is no commit id. */136const NOTHING =137 "Nothing is at this address: a project's and an ask's names are lowercase words joined by single dashes, and ?head= takes an answer's whole commit id, 40 hex digits.";138139const AnswerNotFound = ({ data }: { readonly data?: unknown }) => {
15 unmodified lines
155 : pageHead({156 description: loaderData.askRead.brief.want,157 title: `Answer to ${params.ask} · ${params.project}`,158 }),176 // An answer moves with each push and verdict: kept briefly, asked again.159 headers: () => branchPage,160 component: AnswerPage,161 notFoundComponent: AnswerNotFound,162});
modified:apps/web/src/routes/$owner/$project/asks/{$ask}[.]md.ts+1 added-15 removed
9 unmodified lines
10 noAskAt,11} from "../../../../features/ask/markdown.ts";12import { serverClient } from "../../../../server/client.ts";1314// An ask as Markdown, always: `/<project>/asks/<ask>.md` (a literal `.` is15// `[.]` in a route file's name; `{$ask}` keeps the param apart from it). The16// ask page's own URL answers the same with `Accept: text/markdown`17// (`$ask.tsx`), so a harness reads an ask with one plain fetch.1819/** The path params an ask's routes are handed, not yet decoded. */14export interface AskParams {15 readonly ask: string;16 readonly project: string;17}1825/** An ask's path, decoded: names the platform could hold. */19export const AskPath = Schema.Struct({ ask: AskId, project: ProjectName });2028/** The protocol client a route calls the platform with, for the request it answers. */21export type ClientFor = (request: Request) => Layer.Layer<Client>;2231/** `showAsk` is public, so its Markdown may be cached; the annotation says so, not this file. */23// `showAsk` is public, so its Markdown may be cached; the annotation says so.24const visibility = Context.get(ShowAsk.annotations, Visibility);2534/**35 * The `.md` route's handler as a function of its client, which its test36 * drives with a stub platform: the brief `showAsk` gives, with the banner37 * naming this host's indexes under its title, a refusal as a 404, or a 404 without asking38 * when the path can name no ask.39 */26export const askMarkdownHandler =27 (clientFor: ClientFor) =>28 ({29 params,
31 unmodified lines
modified:apps/web/src/routes/$owner/$project/asks/$ask.tsx+1 added-22 removed
28 unmodified lines
29import { serverClient } from "../../../../server/client.ts";30import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";31import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";3233// The ask page: where the ask stands, its brief, its check and its answers,34// and the lines that take it; live while open. The same35// URL answers `Accept: text/markdown` with the brief as Markdown (the GET36// handler below), and its `.md` twin always does (`{$ask}[.]md.ts`).3738/**39 * The ask page's GET, as a function of its client: a request that asks for40 * Markdown gets the ask's Markdown, as at its `.md` URL; any other falls41 * through to the page.42 */33export const askPageHandler =34 (clientFor: ClientFor) =>35 <Next,>({36 next,
7 unmodified lines
44 wantsMarkdown(request)45 ? askMarkdownHandler(clientFor)({ params, request })46 : next();4758/**59 * The page's headers: that the URL answers by `Accept`, and, for a path that60 * can name an ask, its Markdown as an alternate. A path that cannot (a 404)61 * names none, so no raw path text reaches a header.62 */48// A path that cannot name an ask names no Markdown, so no raw path text reaches a header.49export const askPageHeaders = ({50 params,51}: {52 readonly params: AskParams;
13 unmodified lines
66 );6768const root = getRouteApi("__root__");6984/**85 * The page over its atoms, which start from what the loader read and read86 * again as the project's events arrive: the ask, its latest verdict, and87 * the events the fold reads.88 */70const FreshAsk = ({71 platformUrl,72 read,73 viewer,
3 unmodified lines
77 readonly viewer: Handle | undefined;78}) => {79 const { project } = read.ask;80100 // Live: each event the project hears reads again what it changed.81 useAtomMount(watchAtom(project));8283 const { ask, brief } = Option.getOrElse(84 AsyncResult.value(useAtomValue(askAtom(project, read.ask.id))),
78 unmodified lines
163 : pageHead({164 description: loaderData.ask.brief.want,165 title: `${params.ask} · ${params.project}`,166 }),187 // An ask moves with each claim and landing: kept briefly, asked again.167 headers: (context) => ({ ...branchPage, ...askPageHeaders(context) }),168 component: AskPage,169 notFoundComponent: AskNotFound,170 server: {
5 unmodified lines
modified:apps/web/src/routes/$owner/$project/blob/$rev/$.tsx-10 removed
22 unmodified lines
23import { CodeRail } from "../../tree/-code-rail.tsx";24import { FilesButton } from "../../tree/-files-button.tsx";25import { softLanding } from "../../tree/-soft-landing.ts";2627// A file at a revision, read on the server with the commit that last28// changed it: its text arrives highlighted when the server highlights its29// language and size (`features/code/prerender.ts`), else as numbered,30// anchored lines, and the browser's drawing then takes its place, the31// `#L10-L20` selection kept in the address. `?plain=1` shows a Markdown file's source. A path missing at a32// revision that exists lands on the nearest folder above it; any other33// address naming nothing is a 404 showing the platform's refusal.3427const BlobPageData = Schema.Struct({28 file: FileView,29 last: Schema.optionalKey(CommitView),30 now: Schema.DateTimeUtcFromString,
6 unmodified lines
37 readonly project: string;38 readonly rev: string;39}4049/** The file for its page, or a not-found carrying the platform's refusal. */41export const readBlobPage = (params: BlobParams) =>42 Effect.gen(function* () {43 const project = yield* Effect.fromOption(projectOf(params.project));44 const rev = yield* Effect.fromOption(revisionOf(params.rev));
90 unmodified lines
135 if (import.meta.env.SSR) {136 const plain =137 new URLSearchParams(location.searchStr).get("plain") === "1";138148 // A failed read rejects as it would have (the router's not-found).139 return Effect.runPromise(140 Effect.gen(function* () {141 const data = yield* Effect.promise(() => page);142
38 unmodified lines
modified:apps/web/src/routes/$owner/$project/commit/$sha.tsx+2 added-17 removed
20 unmodified lines
21import { CommitRail } from "../tree/-code-rail.tsx";22import { CommitPageData } from "../tree/-commit-files.ts";23import { FilesButton } from "../tree/-files-button.tsx";2425// One commit and what it changed, read on the server, with the territory26// of the ask it answered (the diff's stats split by it): the page arrives27// with the landing and the diff, its first files highlighted where the28// server highlights them (`features/code/prerender.ts`) and the rest as29// plain text, and the browser's drawing then takes its place, the changed30// files as a tree in the rail. A commit never31// changes, but its page carries its landing, which the project records32// after main has moved, and times reckoned from the read: a browser keeps33// it briefly, as a page at `main`. Within a visit the router keeps what it34// read, so a change of layout never reads the diff again.25// A commit never changes, but its page carries its landing, which the project records after main has moved,26// and times reckoned from the read: a browser keeps it briefly, as a page at `main`.2728interface CommitParams {29 readonly project: string;30 readonly sha: string;31}3241/** The commit for its page, or a not-found carrying the platform's refusal. */33export const readCommitPage = (params: CommitParams) =>34 Effect.gen(function* () {35 const project = yield* Effect.fromOption(projectOf(params.project));36 const sha = yield* Effect.fromOption(commitOf(params.sha));
5 unmodified lines
42 UnknownProject: notFoundFor,43 })44 );4555 // The ask the landing answered, for its territory; a page without it56 // splits its stats into tests and the rest.46 const answered = Option.fromUndefinedOr(diff.commit.landing?.ask);4748 const territory = Option.isNone(answered)49 ? Option.none()
34 unmodified lines
84 const router = useRouter();85 const asked = Route.useSearch().style === "split";86 const [chosen, setChosen] = useState(asked);87 const roomy = useMedia(SPLIT_QUERY);99 // Split only where the screen has room for two sides.88 const split = chosen && roomy;89102 // Each file parsed once for the page: the head's stats, the plain text103 // and the folds all read this.90 const drawn = useMemo(() => drawnFiles(diff.files), [diff.files]);9192 // The files the server sends highlighted: the same on both sides, since93 // both decide from the diff alone.
33 unmodified lines
127 },128 [diff.files]129 );130145 // The layout is the reader's: kept in the address, with no read again.131 const onSplit = (next: boolean) => {132 setChosen(next);133134 const { hash, pathname } = router.state.location;
93 unmodified lines
modified:apps/web/src/routes/$owner/$project/commits/$rev.tsx-7 removed
19 unmodified lines
20import { notFoundFor } from "../../../../features/shared/refusals.ts";21import { branchPage } from "../../../../server/cache-headers.ts";22import { serverClient } from "../../../../server/client.ts";2324// The landings: the log from a revision, a page at a time (`?from=` is25// where the page starts), only the commits that changed `?path=` when26// given, filtered to the answers or the asks' openings by `?show=`; read27// on the server, so the page arrives whole.2824const LogPageData = Schema.Struct({25 commits: Schema.Array(CommitView),26 from: Schema.Int,27 next: Schema.UndefinedOr(Schema.Int),
2 unmodified lines
30 project: ProjectName,31 rev: Schema.String,32});3339/** The kinds of commit a page may be filtered to. */34const SHOWS: readonly LogShow[] = ["answers", "openings"];3536interface LogParams {37 readonly from?: number | undefined;
1 unmodified line
39 readonly project: string;40 readonly rev: string;41}4249/** The page of the log, or a not-found carrying the platform's refusal. */43export const readLogPage = (params: LogParams) =>44 Effect.gen(function* () {45 const project = yield* Effect.fromOption(projectOf(params.project));46 const rev = yield* Effect.fromOption(revisionOf(params.rev));
71 unmodified lines
modified:apps/web/src/routes/$owner/$project/decisions/$decision.tsx+1 added-16 removed
49 unmodified lines
50import { pageHead } from "../../../../features/shared/head.ts";51import { personalPage } from "../../../../server/cache-headers.ts";52import { serverClient } from "../../../../server/client.ts";5354// `/$project/decisions/$decision`: one decision from the reader's Today in55// that project, read on the server with their own session; for a finish,56// the answer's diff, its ask and verdict, and where an earlier round was57// refused. The decision comes from `today` alone: someone who decides58// nothing there sees what a decision is and no evidence. A page about its59// reader is kept by no cache.54// The decision comes from `today` alone: someone who decides nothing there sees no evidence.5556const root = getRouteApi("__root__");5758interface DecisionParams {
8 unmodified lines
67 readDecision(data).pipe(Effect.provide(serverClient(env, getRequest())))68 )69 );7076/** The decision the page found, when it found one. */71const foundOf = (read: DecisionRead): Option.Option<FoundDecision> =>72 DecisionRead.guards.Found(read) ? Option.some(read) : Option.none();7380/** The finish the page found, when the decision is one. */74const finishOf = (read: DecisionRead) =>75 Option.flatMap(foundOf(read), (found) =>76 isFinishDecision(found.decision)77 ? Option.some({ decision: found.decision, found })78 : Option.none()79 );8088/** The decision as the reader's choice left it, once taken on this page. */81const takenHere = (82 decided: AsyncResult.AsyncResult<{ readonly decision: Decision }, unknown>,83 decision: Decision84) =>
6 unmodified lines
91 taken.decided !== undefined92 )93 );94103/** A finish's page: its files, folds, layout, read marks and keys. */95const Finish = ({96 busy,97 decision,98 failure,
13 unmodified lines
112 const { platformUrl } = root.useLoaderData();113 const router = useRouter();114 const { ask, head } = decision.subject;115125 // Live: a push to the answer while the page is open says so.116 useAtomMount(watchAtom(decision.project));117 const events = useAtomValue(projectEventsAtom(decision.project));118119 const newerHead =
30 unmodified lines
150 );151152 const [chosen, setChosen] = useState(false);153 const roomy = useMedia(SPLIT_QUERY);164 // Split only where the screen has room for two sides.154 const split = chosen && roomy;155156 const defaults = useMemo(157 () =>
79 unmodified lines
237238const DecisionPage = () => {239 const loaded = Route.useLoaderData();240252 // Decoded once per read, so what is built from it (the diff's parsed253 // files above all) is built once too.241 const data = useMemo(242 () => Schema.decodeSync(DecisionPageData)(loaded),243 [loaded]244 );245246 const [decided, decide] = useAtom(decideAtom);247 const here = useLocation({ select: hereOf });248262 // A choice that failed says why where the choices are: its refusal, the263 // way to sign in, or that the platform did not answer.249 const failure = AsyncResult.isFailure(decided) ? (250 <ProposalFailure251 cause={decided.cause}252 doing="take this decision"
57 unmodified lines
modified:apps/web/src/routes/$owner/$project/proposals/$proposal.tsx-15 removed
26 unmodified lines
27import { notFoundFor, Refusals } from "../../../../features/shared/refusals.ts";28import { personalPage } from "../../../../server/cache-headers.ts";29import { serverClient } from "../../../../server/client.ts";3031// `/$project/proposals/$proposal`: one proposal and the platform's draft of32// its ask. The loader reads `showProposal` on the server, so the page33// arrives whole and an address naming no project or proposal is a 404; in34// the browser it reads again on each `ProposalDrafted` (the project's35// watch), so a draft moves from Drafting to Ready or Failed on screen.36// Who is signed in and the reader's Today (a decider's: it holds the open37// decision on the proposal) are read in the browser only.3831type Shown = typeof ShowProposal.successSchema.Type;3241/** The proposal `name/id` names, encoded for the page; a not-found when there is none. */33export const readProposal = (name: string, id: string) =>34 Effect.gen(function* () {35 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(36 Effect.mapError(() => notFound())
26 unmodified lines
63 )64 )65 );6676/** The open decision on `proposal` in the reader's Today, if it is there. */67const decisionOn = (68 today: AsyncResult.AsyncResult<Today, unknown>,69 proposal: Proposal70): Option.Option<DecisionId> =>
7 unmodified lines
78 subject.proposal === proposal.id79 ).pipe(Option.map(({ id }) => id))80 );8192/** Whether `who` is the proposer, or the reader decides in the project (their Today answered). */82const mayRedraftAs = (83 who: AsyncResult.AsyncResult<Option.Option<Handle>, unknown>,84 today: AsyncResult.AsyncResult<Today, unknown>,85 proposal: Proposal
3 unmodified lines
89 Option.flatten(AsyncResult.value(who)),90 (handle) => handle.toLowerCase() === proposal.proposer.toLowerCase()91 );92104/** The page over the proposal's atom, which starts from what the loader read. */93const FreshProposal = ({94 project,95 read,96}: {97 readonly project: ProjectName;98 readonly read: Shown;99}) => {112 // Live: a `ProposalDrafted` re-reads the proposal.100 useAtomMount(watchAtom(project));101102 const { files, proposal } = Option.getOrElse(103 AsyncResult.value(useAtomValue(proposalAtom(project)(read.proposal.id))),
53 unmodified lines
157};158159const decodeRefusals = Schema.decodeUnknownOption(Refusals);160174/** A proposal or a project the platform does not know: its refusal, as git prints it. */161const Unknown = ({ data }: { readonly data?: unknown }) => (162 <NotFoundView163 nothing="Nothing is at this address: a project's name is lowercase words joined by single dashes, and a proposal's id reads prop- and six digits."164 refusals={Option.getOrUndefined(decodeRefusals(data))}
2 unmodified lines
167);168169export const Route = createFileRoute("/$owner/$project/proposals/$proposal")({170 loader: ({ params }) => proposalPage({ data: params }),185 // Who may draft it again and the decision on it are the reader's own.171 headers: () => personalPage,172 head: ({ loaderData, params: { project, proposal } }) =>173 pageHead(174 loaderData === undefined
9 unmodified lines
modified:apps/web/src/routes/$owner/$project/proposals/new.tsx-9 removed
20 unmodified lines
21import { ProposeView } from "../../../../features/propose/propose-view.tsx";22import type { About } from "../../../../features/propose/propose-view.tsx";23import { pageHead } from "../../../../features/shared/head.ts";2425// `/$project/proposals/new`: the propose form. Who is signed in and the26// project's top folders are read in the browser (the server paints the27// page while it checks); a proposal made goes to its own page, a refusal28// shows under the form. `?about=<path>&line=<n>&at=<sha>` (the why page's29// "Propose an ask about this line") starts the want at that line.3025const decodeProject = Schema.decodeUnknownOption(ProjectName);2633/** The line a why page points at, when the address names all three parts. */27const AboutParts = Schema.Struct({28 about: RepoPath,29 at: CommitSha,30 line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
4 unmodified lines
35const decodeText = Schema.decodeUnknownOption(Schema.String);3637const decodeLine = Schema.decodeUnknownOption(Schema.Int);3846/** The address's line, as the form takes it. */39const aboutOf = (search: {40 readonly about?: string | undefined;41 readonly at?: string | undefined;42 readonly line?: number | undefined;
3 unmodified lines
46 line,47 path: about,48 }));4958/** The form for `project`, once the browser knows who is signed in. */50const Propose = ({ project }: { readonly project: ProjectName }) => {51 const navigate = useNavigate();52 const search = Route.useSearch();53 const here = useLocation({ select: hereOf });
72 unmodified lines
modified:apps/web/src/routes/$owner/$project/raw/$rev/$.ts+1 added-4 removed
3 unmodified lines
4import { backend } from "#backend";56import { forwarded } from "../../../../../features/agents/forward.ts";78// A file's bytes at a revision: the platform serves them, under its9// sandboxing headers and content types, at the same path; the web10// passes GET and HEAD on and hands the answer back untouched, headers and11// all, as `routes/releases/$.ts` does.8// The platform serves the bytes under its sandboxing headers; the web passes GET and HEAD on and hands the answer back untouched.9export const Route = createFileRoute("/$owner/$project/raw/$rev/$")({10 server: { handlers: forwarded(backend, env) },11});
modified:apps/web/src/routes/$owner/$project/tree/$rev/$.tsx-7 removed
23 unmodified lines
24import { branchPage } from "../../../../../server/cache-headers.ts";25import { serverClient } from "../../../../../server/client.ts";26import { readFolderWithReadme } from "../../../../../server/folder.ts";2728// A folder at a revision: its entries and its README, read on the server,29// so the page arrives whole; the tree in the rail and what last changed30// each entry are the browser's. A path missing at a revision that exists31// lands on the nearest folder above it, the refusal as its notice; any32// other address naming nothing is a 404 showing the platform's refusal.3328const TreePageData = Schema.Struct({29 listing: TreeListing,30 now: Schema.DateTimeUtcFromString,31 project: ProjectName,
6 unmodified lines
38 readonly project: string;39 readonly rev: string;40}4148/** The folder for its page, or a not-found carrying the platform's refusal. */42export const readTreePage = (params: TreeParams) =>43 Effect.gen(function* () {44 const project = yield* Effect.fromOption(projectOf(params.project));45 const rev = yield* Effect.fromOption(revisionOf(params.rev));
79 unmodified lines
modified:apps/web/src/routes/$owner/$project/tree/-code-rail.tsx+2 added-15 removed
1/**2 * The code pages' files: in the rail's slot from the shell's width, and in3 * a sheet behind the Files button below it. A folder's, a file's and a why4 * page name the same `CodeRail`, so one tree stays mounted while the5 * reader moves between them; a commit's page names `CommitRail`.6 *7 * A route's `staticData` loads with every page, so this module stays8 * light: the server draws the ref line's place, and the browser loads the9 * tree, the switcher and the keys (`-rail-body.tsx`) once the page is up.10 * Not a route: the `-` prefix keeps the router from reading it as one.11 */1// A route's `staticData` loads with every page, so this module stays light: the browser loads the rail's body2// (`-rail-body.tsx`) once the page is up.3import { ClientOnly } from "@tanstack/react-router";4import { lazy, Suspense } from "react";56import { RailSlot } from "../../../../features/shared/shell/rail-slot.tsx";
1 unmodified line
8const Body = import.meta.env.SSR9 ? undefined10 : lazy(() => import("./-rail-body.tsx"));1121/** The ref line's place, the height the switcher will take. */12const Placeholder = () => (13 <div aria-hidden="true" className="border-rule h-12 shrink-0 border-b" />14);1526/** The rail's body, once the browser has it. */16const Later = ({ commit }: { readonly commit: boolean }) =>17 Body === undefined ? (18 <Placeholder />19 ) : (
3 unmodified lines
23 </Suspense>24 </ClientOnly>25 );2638/** The rail's slot on a folder's, a file's and a why page. */27export const CodeRail = () => (28 <RailSlot label="Files">29 <Later commit={false} />30 </RailSlot>31);3245/** The rail's slot on a commit's page. */33export const CommitRail = () => (34 <RailSlot label="Changed files">35 <Later commit />36 </RailSlot>
1 unmodified line
modified:apps/web/src/routes/$owner/$project/tree/-commit-files.ts-7 removed
1/**2 * A commit page's data, as its loader sends it: the rail reads the files3 * it changed from the page's match (`-rail-body.tsx`), so the rail's tree4 * and the page's diff come from one read. Not a route: the `-` prefix5 * keeps the router from reading it as one.6 */1import { CommitDiff } from "@repo/protocol/domain/code";2import { ProjectName } from "@repo/protocol/ids";3import { Schema } from "effect";45export const CommitPageData = Schema.Struct({6 diff: CommitDiff,7 now: Schema.DateTimeUtcFromString,8 project: ProjectName,15 /** The territory of the ask the commit answered, when it answered one. */9 territory: Schema.optionalKey(Schema.Array(Schema.String)),10});
modified:apps/web/src/routes/$owner/$project/tree/-files-button.tsx-6 removed
1/**2 * The Files button on the code pages below the shell's width, where the3 * rail is not drawn: it opens the files as a sheet from the left (the4 * whole screen on a phone), loaded on the first press. Not a route: the5 * `-` prefix keeps the router from reading it as one.6 */1import { FolderTree } from "lucide-react";2import { lazy, Suspense, useState } from "react";34import { Button } from "@/components/ui/button";
33 unmodified lines
modified:apps/web/src/routes/$owner/$project/tree/-files-sheet.tsx-8 removed
1/**2 * The code pages' files below the shell's width: a sheet from the left on3 * a tablet, the whole screen on a phone, holding the ref line and the4 * tree (or a commit's changed files). Choosing a file moves the page, and5 * the sheet closes. Loaded on the first press of Files. Not a route: the6 * `-` prefix keeps the router from reading it as one.7 */1import { useLocation } from "@tanstack/react-router";2import { useEffect, useRef } from "react";34import { Sheet, SheetContent } from "@/components/ui/sheet";
17 unmodified lines
22 });2324 const opened = useRef(href);2533 // The reader chose a file: the page moved, so the sheet has done its work.26 useEffect(() => {27 if (href !== opened.current) {28 onOpenChange(false);29 }
17 unmodified lines
modified:apps/web/src/routes/$owner/$project/tree/-rail-body.tsx-22 removed
1/**2 * What the code pages' rail and Files sheet hold, loaded in the browser3 * only (`-code-rail.tsx`): the ref line (main, a tag or a commit, as a4 * switcher), then the tree with its filter, filling the rest; choosing a5 * file moves the page with the router, never reloading the document. On6 * a commit's page, the files it changed, open, marked A, M or D with their7 * `+n −m`; choosing one scrolls the diff to it.8 *9 * `J` and `K` move to the next or previous file, in the tree's order.10 * Not a route: the `-` prefix keeps the router from reading it as one.11 */1import { useAtomValue } from "@effect/atom-react";2import type { ChangedFile } from "@repo/protocol/domain/code";3import { ProjectName } from "@repo/protocol/ids";4import {
27 unmodified lines
32const decode = Schema.decodeUnknownOption(CommitPageData);3334const NONE: readonly ChangedFile[] = [];3547/** The files the commit on the page changed; none while its data is not there. */36const useCommitFiles = (): readonly ChangedFile[] => {37 const data: unknown = useMatch({38 from: "/$owner/$project/commit/$sha",39 select: (match) => match.loaderData,40 shouldThrow: false,41 });4255 // Decoded once per read, not on every move between files.43 return useMemo(44 () =>45 Option.match(decode(data), {46 onNone: () => NONE,
2 unmodified lines
49 [data]50 );51};5266/** Which page of a file the address is: its folder, its code, or why. */53type Kind = "blob" | "tree" | "why";5469/** Where the reader is in the code: the project, the revision and the path, and which page. */55const useCodeAddress = () => {56 const params = useParams({ strict: false });5758 const kind = useLocation({
14 unmodified lines
7374 return { kind, path, project, rev };75};7692/** The page of `kind` for `path` at `rev`. */77const hrefFor = (78 project: ProjectName,79 kind: Kind,80 rev: string,
5 unmodified lines
8687 return (kind === "why" ? whyHref : blobHref)(project, rev, path);88};89106/** The ref line: the revision, and the switcher to the same page at another. */90const RefLine = ({91 kind,92 path,93 project,
16 unmodified lines
110 </div>111 );112};113131/** The tree of every path at the revision, and the keys between its files. */114const ProjectTree = ({115 kind,116 path,117 project,
3 unmodified lines
121 readonly kind: Kind;122 readonly path: string | undefined;123 readonly project: ProjectName;124 readonly rev: string;143 /** Whether the tree is on screen here (the rail is not below the shell's width). */125 readonly shown: boolean;126}) => {127 const router = useRouter();128 const read = useAtomValue(pathsAtom({ at: rev, project }));
24 unmodified lines
153 />154 ) : null;155};156176/** A folder's, a file's or a why page's files: the ref line, then the tree. */157export const CodeFiles = ({158 always = false,159}: {160 readonly always?: boolean;
18 unmodified lines
179 </div>180 );181};182203/** A commit's changed files, marked by how, and the keys between them. */183export const CommitFiles = ({184 always = false,185}: {186 readonly always?: boolean;
42 unmodified lines
229 </div>230 ) : null;231};232254/** The rail's body: a commit's changed files, or the project's. */233const RailBody = ({ commit }: { readonly commit: boolean }) =>234 commit ? <CommitFiles /> : <CodeFiles />;235236// `React.lazy` takes a module's default export.
1 unmodified line
modified:apps/web/src/routes/$owner/$project/tree/-soft-landing.ts-11 removed
1/**2 * The soft landing for a missing path (the nearest folder, with the3 * refusal above it): when a code page's path is not at a revision4 * that exists, the folders above it are read, nearest first, and the5 * first that exists travels in the 404 with the platform's `UnknownPath`,6 * so the page shows that folder with the refusal's own words as its7 * notice. The root always exists where the revision does. Not a route:8 * the `-` prefix keeps the router from reading it as one.9 */1import { Client } from "@repo/protocol/contracts";2import type { TreeListing } from "@repo/protocol/domain/code";3import { RepoPath } from "@repo/protocol/ids";4import type { ProjectName } from "@repo/protocol/ids";
4 unmodified lines
9import { ancestorsOf } from "../../../../features/code/paths.ts";10import { SoftLanding } from "../../../../features/code/soft-landing.ts";11import { notFoundFor } from "../../../../features/shared/refusals.ts";1222/** Each folder above `path`, nearest first, then the root (none). */13const above = (path: string): readonly Option.Option<RepoPath>[] => [14 ...ancestorsOf(path)15 .toReversed()16 .map((folder) => Option.some(RepoPath.make(folder))),17 Option.none(),18];1930/** A 404 for `refusal` that lands on the nearest folder above its path at its commit. */20export const softLanding = (21 refusal: UnknownPath,22 project: ProjectName,23 rev: string
40 unmodified lines
modified:apps/web/src/routes/$owner/$project/why/$rev/$.tsx-10 removed
24 unmodified lines
25import { CodeRail } from "../../tree/-code-rail.tsx";26import { FilesButton } from "../../tree/-files-button.tsx";27import { softLanding } from "../../tree/-soft-landing.ts";2829// Why each line of a file at a revision is there, read on the server: the30// blame's ranges with their commits and landings, the file at the commit31// the blame resolved, so the two always agree (all asked for at once, the32// file again only if the revision moved between them), and the commit33// that last changed it. The browser then draws the file with a band above34// each group of lines. A path missing at a revision that exists lands on35// the nearest folder above it; any other address naming nothing is a 40436// showing the platform's refusal.3729const WhyPageData = Schema.Struct({30 file: FileView,31 last: Schema.optionalKey(CommitView),32 now: Schema.DateTimeUtcFromString,
8 unmodified lines
41 readonly project: string;42 readonly rev: string;43}4454/** The view and the file's text, or a not-found carrying the platform's refusal. */45export const readWhyPage = (params: WhyParams) =>46 Effect.gen(function* () {47 const project = yield* Effect.fromOption(projectOf(params.project));48 const rev = yield* Effect.fromOption(revisionOf(params.rev));
102 unmodified lines
modified:apps/web/src/routes/$owner/$project/env.tsx+1 added-19 removed
19 unmodified lines
20import { useProjectList } from "../../../features/shared/shell/context.ts";21import { branchPage } from "../../../server/cache-headers.ts";22import { serverClient } from "../../../server/client.ts";2324// A project's env shape, as anyone may read it: never a value, and no form25// (a value is set from a terminal only). The loader reads it on the server,26// so the page arrives whole and an address naming no project is a 40427// showing the platform's `UnknownProject` refusal; in the browser it reads28// again when a value is set or a landing changes the schema.2930/**31 * What the page's loader carries from the server, encoded: the project, its32 * env shape (absent before its main first lands), and when it was read.33 */24const EnvPageData = Schema.Struct({25 now: Schema.DateTimeUtcFromString,26 project: ProjectName,27 schema: Schema.UndefinedOr(EnvSchemaView),28});2930type EnvPageData = typeof EnvPageData.Type;3142/**43 * The env shape of the project `name`; none when nothing has landed there44 * yet; or a not-found when there is no such project (a 404). Before a45 * project's first landing `envShape` has no commit to read and names no46 * project, so whether the project exists is `listAsks`' to say.47 */32// Before a project's first landing `envShape` names no project, so whether it exists is `listAsks`' to say.33export const readEnv = (name: string) =>34 Effect.gen(function* () {35 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(36 Effect.mapError(() => notFound())
23 unmodified lines
60 .handler(({ data }) =>61 Effect.runPromise(readEnv(data).pipe(Effect.provide(serverClient(env))))62 );6379/** The page over the env shape's atom, which starts from what the loader read and reads again when the env shape changes. */64const FreshEnv = ({65 atom,66 now,67 read,
1 unmodified line
69 readonly atom: ReturnType<typeof envSchemaAtom>;70 readonly now: DateTime.Utc;71 readonly read: EnvSchemaView;72}) => {89 // Live: a value set, or a landing, makes the env shape read again.73 useAtomMount(watchAtom(read.project));7475 const schema = Option.getOrElse(76 AsyncResult.value(useAtomValue(atom)),
36 unmodified lines
113};114115export const Route = createFileRoute("/$owner/$project/env")({116 loader: ({ params }) => envPage({ data: params.project }),134 // The env shape moves with the next landing or value set: kept briefly, read again behind.117 headers: () => branchPage,118 head: ({ params: { project } }) =>119 pageHead({120 title: `Env shape · ${project}`,
5 unmodified lines
modified:apps/web/src/routes/$owner/$project/index.tsx+2 added-31 removed
53 unmodified lines
54 projectPageHandler,55 readProjectPage,56} from "../../../server/project-page.ts";5758// A project's home, which is its list of asks. The loader reads, on the59// server and at once, the project's asks, its own ledger (its posture), its60// events (each ask's progress, a family's marks, its landings), its policy61// (who decides) and its root folder with its README, then each family's62// parent in full; so the page, and an agent fetching it, arrive with the63// asks and the README. A read the platform cannot give now leaves its64// section to the browser; an address naming no project is a 404 that shows65// the platform's `UnknownProject` refusal. The list of projects is never66// read here. The same URL answers `Accept: text/markdown` with the67// project's `llms.txt`.6858const projectPage = createServerFn({ method: "GET" })59 .validator((name: string) => name)60 .handler(({ data }) =>61 Effect.runPromise(62 readProjectPage(data).pipe(Effect.provide(serverClient(env)))63 )64 );6577/** Where a project's Markdown is; none for a name that can name no project. */66const markdownOf = (name: string) =>67 Option.map(decodeName(name), (project) => `/${project}/llms.txt`);6881/**82 * The page's headers: varied by `Accept`; for a name that can be a83 * project's, kept briefly with its Markdown named. A path that cannot names84 * nothing, so no raw path text reaches a header.69// A path that cannot name a project names nothing, so no raw path text reaches a header.85 */70export const projectPageHeaders = ({71 params,72}: {73 readonly params: { readonly project: string };
6 unmodified lines
80 vary: "Accept",81 }),82 });83100/** The page's head: its name, its README's first sentence, and its Markdown. */84export const projectPageHead = ({85 loaderData,86 params,87}: {
19 unmodified lines
107};108109const root = getRouteApi("__root__");110128/**129 * The selected ask in full, read in the browser once it is selected. It130 * wraps the page whether or not a row is selected, so selecting one never131 * remounts the list (and loses the row the keys rest on).132 */111// Wraps the page whether or not a row is selected, so selecting one never remounts the list.112const WithFull = ({113 children,114 pick,115}: {
8 unmodified lines
124};125126const decodeAsk = Schema.decodeUnknownOption(AskId);127149/** An atom's value once it has one, else what the loader read. */128const valueOr = <A, E, B>(129 read: AsyncResult.AsyncResult<A, E>,130 seeded: B | undefined,131 pick: (value: A) => B132): B | undefined =>133 Option.getOrElse(Option.map(AsyncResult.value(read), pick), () => seeded);134157/** The page over its atoms, each section as its read arrives, all kept live. */135const LiveProject = ({136 data,137 platformUrl,138 selected,
6 unmodified lines
145}) => {146 const { project } = data;147 const hydrated = useHydrated();148172 // Live: each event the project commits makes these reads fetch again.149 useAtomMount(watchAtom(project));150151 const asksRead = useAtomValue(asksAtom(project));152 const asks = valueOr(asksRead, data.asks, ({ asks: listed }) => listed);
115 unmodified lines
268 </SeededAtoms>269 );270};271296/** The import offer for `project`, wired. */272const Offer = ({ project }: { readonly project: ProjectName }) => {273 const importer = useImporter(project);274275 return <ImportOffer importer={importer} project={project} />;276};277303/**304 * No project at this address: at a source namespace's305 * (`/github.com/pallets/click`) the import offer, else the not-found.306 */278const Unknown = () => {279 const { project } = Route.useParams();280281 return Option.match(offerFor(project), {
24 unmodified lines
modified:apps/web/src/routes/$owner/$project/ledger.tsx-10 removed
18 unmodified lines
19import { pageHead } from "../../../features/shared/head.ts";20import { branchPage } from "../../../server/cache-headers.ts";21import { serverClient } from "../../../server/client.ts";2223// A project's ledger, as anyone may read it. The loader reads it on the24// server, so the page arrives whole and an address naming no project is a25// 404 showing the platform's `UnknownProject` refusal; in the browser the26// ledger reads again as the platform appends entries.2728/** What the page's loader carries from the server, encoded: the ledger, and when it was read. */23const LedgerPageData = Schema.Struct({24 ledger: Ledger,25 now: Schema.DateTimeUtcFromString,26});2728type LedgerPageData = typeof LedgerPageData.Type;2936/** The ledger of the project `name`, or a not-found when there is no such project (a 404). */30export const readLedger = (name: string) =>31 Effect.gen(function* () {32 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(33 Effect.mapError(() => notFound())
16 unmodified lines
50 .handler(({ data }) =>51 Effect.runPromise(readLedger(data).pipe(Effect.provide(serverClient(env))))52 );5361/** The page over the ledger's atom, which starts from what the loader read and reads again when the ledger changes. */54const FreshLedger = ({55 atom,56 read,57}: {58 readonly atom: ReturnType<typeof ledgerAtom>;59 readonly read: LedgerPageData;60}) => {69 // Live: each entry the platform appends makes the ledger read again.61 useAtomMount(watchAtom(read.ledger.project));6263 const ledger = Option.getOrElse(64 AsyncResult.value(useAtomValue(atom)),
26 unmodified lines
91};9293export const Route = createFileRoute("/$owner/$project/ledger")({94 loader: ({ params }) => ledgerPage({ data: params.project }),104 // A ledger moves with the project's next entry: kept briefly, read again behind.95 headers: () => branchPage,96 head: ({ params: { project } }) =>97 pageHead({98 title: `Ledger · ${project}`,
5 unmodified lines
modified:apps/web/src/routes/$owner/$project/llms[.]txt.ts-1 removed
2 unmodified lines
34import { serverClient } from "../../../server/client.ts";5import { projectLlmsHandler } from "../../../server/llms.ts";67// `/<project>/llms.txt`: one project for an agent (`server/llms.ts`).7export const Route = createFileRoute("/$owner/$project/llms.txt")({8 server: {9 handlers: {10 GET: projectLlmsHandler(
6 unmodified lines
modified:apps/web/src/routes/$owner/$project/people.tsx+1 added-15 removed
20 unmodified lines
21import { pageHead } from "../../../features/shared/head.ts";22import { branchPage } from "../../../server/cache-headers.ts";23import { serverClient } from "../../../server/client.ts";2425// A project's policy (its section reads "Policy" at the address it has26// always had): who decides what, who is vouched for, its limits, and its27// layers in a line, from the evaluated policy at the landed commit beside28// the ledger. The loader reads both on the server, so the page arrives whole29// and an address naming no project is a 404; in the browser each reads30// again as the platform lands changes and appends entries.25// The project's policy page, at the address it has always had.2632/**33 * What the page's loader carries from the server, encoded: the policy34 * (absent until evaluated), why it has not evaluated (absent before the35 * first landing and once it has), and the ledger.36 */27const PeoplePageData = Schema.Struct({28 ledger: Ledger,29 policy: Schema.optionalKey(PublicPolicy),30 unevaluated: Schema.optionalKey(PolicyPending),31});3233type PeoplePageData = typeof PeoplePageData.Type;3445/** The policy and ledger of the project `name`, or a not-found when there is no such project (a 404). */35export const readPeople = (name: string) =>36 Effect.gen(function* () {37 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(38 Effect.mapError(() => notFound())
14 unmodified lines
53 .handler(({ data }) =>54 Effect.runPromise(readPeople(data).pipe(Effect.provide(serverClient(env))))55 );5668/** The page over the two atoms, which start from what the loader read and read again as the project changes. */57const FreshPeople = ({58 project,59 read,60}: {61 readonly project: ProjectName;62 readonly read: PeoplePageData;63}) => {76 // Live: a landing re-reads the policy, a ledger entry the layers.64 useAtomMount(watchAtom(project));6566 const { policy, unevaluated } = Option.getOrElse(67 AsyncResult.value(useAtomValue(policyAtom(project))),
45 unmodified lines
113};114115export const Route = createFileRoute("/$owner/$project/people")({116 loader: ({ params }) => peoplePage({ data: params.project }),130 // The policy moves with the next landing: kept briefly, read again behind.117 headers: () => branchPage,118 head: ({ params: { project } }) =>119 pageHead({120 title: `Policy · ${project}`,
5 unmodified lines
modified:apps/web/src/routes/$owner/$project/refs.tsx-7 removed
12 unmodified lines
13import { notFoundFor } from "../../../features/shared/refusals.ts";14import { branchPage } from "../../../server/cache-headers.ts";15import { serverClient } from "../../../server/client.ts";1617// Main, the tags and the forks, read on the server; `?from=` pages the18// tags, and `?package=` lists one package's tags alone. Where the project19// is cloned from comes with them.2021/** The refs for their page, or a not-found carrying the platform's refusal. */17export const readRefsPage = (name: string) =>18 Effect.gen(function* () {19 const project = yield* Effect.fromOption(projectOf(name));20 const client = yield* Client;
9 unmodified lines
30 .validator((name: string) => name)31 .handler(({ data }) =>32 Effect.runPromise(33 readRefsPage(data).pipe(39 // Where the project is cloned from rides with its refs.34 Effect.map((refs) => ({ platformUrl: env.PUBLIC_PLATFORM_URL, refs })),35 Effect.provide(serverClient(env))36 )37 )
25 unmodified lines
63 from: Option.getOrUndefined(offsetOf(search.from)),64 package: Option.getOrUndefined(packageParamOf(search.package)),65 }),66 loader: ({ params }) => refsPage({ data: params.project }),73 // Refs move with the next landing or claim: kept briefly, read again behind.67 headers: () => branchPage,68 head: ({ params: { project } }) =>69 pageHead({70 title: `Refs · ${project}`,
5 unmodified lines
modified:apps/web/src/routes/$owner/$project/route.tsx+2 added-9 removed
1import { createFileRoute, Outlet } from "@tanstack/react-router";23import { projectParams } from "../../../server/addresses.ts";45// Every page of a project sits under this route. It reads nothing, so no6// page waits on it: the shell finds the project here (`useCurrentProject`,7// which reads this route's match) and draws the project's part of the rail8// from the name in the address at once, its posture arriving later with the9// list of projects without moving anything. A name no project could take10// is left to the page, which says so. The rail itself is the root's, so11// what a project's pages put in its slot (`staticData.rail`) stays mounted12// as the reader moves between them. Its params give every page below the13// project's full name as `project` (`oscabriel/datekit`).5// Reads nothing, so no page waits on it. The rail is the root's, so what a project's pages put in its slot6// (`staticData.rail`) stays mounted as the reader moves between them.7export const Route = createFileRoute("/$owner/$project")({8 component: Outlet,9 params: projectParams,10});
modified:apps/web/src/routes/$owner/index.tsx+2 added-10 removed
2 unmodified lines
3import { Effect, Option, Schema } from "effect";45import { personPath } from "../../features/shared/paths.ts";67// `/<owner>` alone: a handle leads to the person's page,8// `/people/<handle>` in lowercase (handles compare without case), by a9// 302, since the address may yet hold a page of its own. An owner that is10// no handle (a source host, `/github.com`) and a word the web keeps for11// itself (`/icons`) are not found.7// A 302, since the address may yet hold a page of its own.89const decodeHandle = Schema.decodeOption(Handle);1011const isReserved = (owner: string) =>12 reservedProjectNames.some((reserved) => reserved === owner.toLowerCase());1318/**19 * The redirect to the person's page, or a 404, as the loader's rejection:20 * the router reads either from a failed load (the lint keeps a bare21 * `throw` for `Error`s, which neither is).22 */14// The loader rejects with the redirect or the 404: the lint keeps a bare `throw` for `Error`s, which neither is.15export const ownerLoader = ({16 params,17}: {18 readonly params: { readonly owner: string };
17 unmodified lines
modified:apps/web/src/routes/auth/-dev.ts+1 added-11 removed
1/**2 * The dev sign-in, for `vite dev` and tests only: `GET /auth/dev?handle=<h>`3 * sets the session cookie to `dev-<h>`, the token the dev backend (`#backend`4 * under the `development` condition) knows as that fictional5 * person, so Today and decide can be tried with no platform.6 *7 * The leading `-` keeps this module out of the route tree; `$.ts` reaches8 * it through an `import()` that only a development build keeps, so the9 * production bundle carries none of it (`test/production-bundle.test.ts`).10 */1// Development only: the leading `-` keeps this module out of the route tree, and only a development build imports it.2import { Handle } from "@repo/protocol/ids";3import { Option, Schema } from "effect";45import type { Handled } from "../../server/session.ts";6import { redirect, returnPath, sessionCookie } from "../../server/session.ts";717/** How long a dev session lasts: a working day. */8const DEV_SESSION_SECONDS = 8 * 60 * 60;910const decodeHandle = Schema.decodeUnknownOption(Handle);11
15 unmodified lines
modified:apps/web/src/routes/auth/$.ts+2 added-8 removed
1 unmodified line
2import { Effect } from "effect";34import type { Handled } from "../../server/session.ts";56/**7 * Any other `/auth/<name>`. A development build serves the dev sign-in8 * (`-dev.ts`) at `dev`; Vite writes `import.meta.env.DEV` as `false` in a9 * production build, so the `import()` below is dead code there and the dev10 * module never enters the bundle (`test/production-bundle.test.ts`). It is11 * reached this way, not as a route of its own, so the route tree names no12 * dev path.13 */6// Vite writes `import.meta.env.DEV` as `false` in a production build, so this `import()` is dead code there7// and the dev module never enters the bundle. Reached this way so the route tree names no dev path.8const devRoute = import.meta.env.DEV9 ? () => Effect.promise(() => import("./-dev.ts"))10 : undefined;11
23 unmodified lines
modified:apps/web/src/routes/auth/callback.ts-3 removed
2 unmodified lines
34import { serverClient } from "../../server/client.ts";5import { callbackHandler } from "../../server/session.ts";67// The platform sends the browser back here with a code, which becomes the8// session cookie, beside the handle the platform's `status` names for it9// (src/server/session.ts).7export const Route = createFileRoute("/auth/callback")({8 server: {9 handlers: {10 GET: callbackHandler(env, (request) => serverClient(env, request)),
3 unmodified lines
modified:apps/web/src/routes/auth/client.ts-2 removed
1import { createFileRoute } from "@tanstack/react-router";23import { clientMetadataHandler } from "../../server/session.ts";45// The web's OAuth client, as a Client ID Metadata Document: its URL is the6// client id the platform's /authorize reads.5export const Route = createFileRoute("/auth/client")({6 server: {7 handlers: {8 GET: clientMetadataHandler,
3 unmodified lines
modified:apps/web/src/routes/auth/signin.ts-2 removed
1 unmodified line
2import { env } from "cloudflare:workers";34import { signInHandler } from "../../server/session.ts";56// Sign-in starts here: to the platform's /authorize with PKCE7// (src/server/session.ts).6export const Route = createFileRoute("/auth/signin")({7 server: {8 handlers: {9 GET: signInHandler(env),
3 unmodified lines
modified:apps/web/src/routes/auth/signout.ts-2 removed
1import { createFileRoute } from "@tanstack/react-router";23import { signOutHandler } from "../../server/session.ts";45// Sign-out ends the session cookie: the header's form posts here, and a6// plain link works too.5export const Route = createFileRoute("/auth/signout")({6 server: {7 handlers: {8 GET: signOutHandler,
4 unmodified lines
modified:apps/web/src/routes/auth/whoami.ts-2 removed
2 unmodified lines
34import { serverClient } from "../../server/client.ts";5import { whoamiHandler } from "../../server/session.ts";67// Who is signed in, as the platform's `status` names the session's caller,8// asked in process through `#backend`.7export const Route = createFileRoute("/auth/whoami")({8 server: {9 handlers: {10 GET: whoamiHandler((request) => serverClient(env, request)),
3 unmodified lines
modified:apps/web/src/routes/docs/{$page}[.]md.ts-5 removed
4 unmodified lines
56import { commands } from "../../features/agents/catalog.ts";7import { markdown } from "../../features/agents/respond.ts";89// `/docs/<page>.md`: a page of the docs as Markdown (a literal `.` is `[.]`10// in a route file's name; `{$page}` keeps the param apart from it), the11// same text the page draws, for the web's own origin.1213/** The route's handler as a function of the platform's URL, which its test hands in. */9export const docsMarkdownHandler =10 (platformUrl: string) =>11 ({12 params,
29 unmodified lines
modified:apps/web/src/routes/docs/$page.tsx-6 removed
12 unmodified lines
13import { docsHead, docsMarkdownPath } from "../../features/docs/head.ts";14import { markdownLink } from "../../features/front/markdown.ts";15import { branchPage } from "../../server/cache-headers.ts";1617// `/docs/<page>`: one guide or reference page, written for this stage's18// platform and the web's own origin, with its Markdown at19// `/docs/<page>.md`. The same for every reader, and it changes only with a20// deploy.2117const root = getRouteApi("__root__");1819const DocsPage = () => {20 const { page: slug } = Route.useParams();
7 unmodified lines
28 });29};3031export const Route = createFileRoute("/docs/$page")({37 // A page the docs don't have is the router's not-found.32 loader: ({ params }) =>33 Effect.runPromise(34 Option.isSome(docEntry(params.page))35 ? Effect.void
13 unmodified lines
modified:apps/web/src/routes/docs/index.tsx-4 removed
8 unmodified lines
9import { DocsIndexView } from "../../features/docs/docs-view.tsx";10import { docsIndexHead } from "../../features/docs/head.ts";11import { branchPage } from "../../server/cache-headers.ts";1213// `/docs`: the guides and the reference, each page with its summary,14// written for this stage's platform and the web's own origin. The same for15// every reader, and it changes only with a deploy.1613const root = getRouteApi("__root__");1415const DocsIndex = () => {16 const { platformUrl } = root.useLoaderData();
14 unmodified lines
modified:apps/web/src/routes/people/$handle.tsx-6 removed
11 unmodified lines
12import { pageHead } from "../../features/shared/head.ts";13import { Reading, Unreachable } from "../../features/shared/pending.tsx";14import { branchPage } from "../../server/cache-headers.ts";1516// 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.1916const decodeHandle = Schema.decodeUnknownOption(Handle);1718const Credits = ({ handle }: { readonly handle: Handle }) =>19 AsyncResult.matchWithError(useAtomValue(creditsAtom(handle)), {
15 unmodified lines
35};3637export const Route = createFileRoute("/people/$handle")({38 component: PersonPage,43 // The same for every reader: the credits are read in the browser.39 headers: () => branchPage,40 head: ({ params }) =>41 pageHead({42 description: `What ${params.handle} is credited for, by project and area.`,43 title: params.handle,44 }),50 // A 404 for an address that names no handle.45 loader: ({ params }) =>46 Effect.runPromise(47 Effect.asVoid(48 Effect.mapError(Schema.decodeEffect(Handle)(params.handle), () =>
6 unmodified lines
modified:apps/web/src/routes/releases/$.ts-3 removed
3 unmodified lines
4import { backend } from "#backend";56import { forwarded } from "../../features/agents/forward.ts";78// The CLI's releases (the manifest, each version's binaries and checksums,9// and `latest`'s redirects, which are path-absolute and so stay on this10// host): the platform serves them; the web passes GET and HEAD on.8export const Route = createFileRoute("/releases/$")({9 server: { handlers: forwarded(backend, env) },10});
modified:apps/web/src/routes/__root.tsx+6 added-39 removed
23 unmodified lines
24import { themeColors } from "../features/shared/theme.ts";2526import styles from "../styles.css?url";2728// The document every page shares, and the shell inside it: the rail, the29// bars, and each page's own panes (its `Workspace`). The document is the30// route's shell component, so a failure in this route's own read still31// draws inside a whole document. Pages read the site's facts from this32// route's loader data (`getRouteApi("__root__").useLoaderData()`).28// The document is the route's shell component, so a failure in this route's own read still draws inside a whole document.2934/**35 * What every page may need from the Worker's env: where a browser reaches36 * the platform (its git remotes and the CLI's install line). Read on the37 * server; the loader's data rides into the page with the first render.38 */30const siteFacts = createServerFn({ method: "GET" }).handler(() => ({31 platformUrl: env.PUBLIC_PLATFORM_URL,32}));3343/**44 * The browser's chrome colour for each scheme. Rendered into the head45 * directly, not through `rootHead`: both metas are named `theme-color`, and46 * TanStack's `HeadContent` keeps one meta per name.47 */34// Rendered into the head directly, not through `rootHead`: both metas are named `theme-color`,35// and TanStack's `HeadContent` keeps one meta per name.36export const ThemeColors = () => (37 <>38 <meta39 content={themeColors.light}
20 unmodified lines
60 </body>61 </html>62);6376/** The decider's Today, read in the browser for the rail's count. */64const railToday = todayAtom();6566const TodayWaiting = () => {67 const today = useAtomValue(railToday);
8 unmodified lines
76 <RailCount count={waiting} of="decisions waiting" />77 );78};7993/**94 * How many decisions wait on the signed-in decider, beside Today in the95 * rail: read once the page is up and only for someone signed in, never on96 * the server, so it never holds a page back.97 */80const TodayCount = () => {81 const hydrated = useHydrated();82 const signedIn = useSignedIn();8384 return hydrated && signedIn ? <TodayWaiting /> : null;85};8687const Root = () => {106 // Read in the browser after the page is up; the rail draws without it first.88 const listed = useAtomValue(projectsAtom);8990 return (91 <TooltipProvider>
8 unmodified lines
100 </TooltipProvider>101 );102};103123/**124 * What a shared link to any page unfurls with until the page gives its own125 * (`pageHead`): what the platform is, in a sentence.126 */104export const SITE_DESCRIPTION =105 "A git platform where a project says what it wants as asks, anyone may answer, and a change lands on main only by passing a typed gate, with credit for every person involved.";106130/** The site's icon, drawn to scale (`public/icons/icon.svg`). */107const ICON_PATH = "/icons/icon.svg";108133/**134 * A font every page draws with, fetched with the page rather than once the135 * stylesheet names it. Fonts are fetched without credentials whatever their136 * origin, so the preload says so too, or the browser fetches the file twice.137 */109// Fonts are fetched without credentials whatever their origin, so the preload says so too,110// or the browser fetches the file twice.111const fontPreload = (href: string) =>112 ({113 as: "font",114 crossOrigin: "anonymous",
1 unmodified line
116 rel: "preload",117 type: "font/woff2",118 }) as const;119147/**148 * The document's head on every page: the stylesheet, the latin fonts (the149 * latin-ext files load only when a page needs them), the manifest, the icon150 * and the metas. TanStack keeps one meta per `name` (the last a route gives),151 * so each meta here must have a name of its own; the two theme colours are152 * `ThemeColors`, in the document itself.153 */120// TanStack keeps one meta per `name` (the last a route gives), so each meta here must have a name of its own.121export const rootHead = () => ({122 links: [123 { href: styles, rel: "stylesheet" },124 fontPreload(sansFont),
26 unmodified lines
modified:apps/web/src/routes/agents.tsx-7 removed
7 unmodified lines
8import { AgentsView } from "../features/agents/setup-page.tsx";9import { pageHead } from "../features/shared/head.ts";10import { branchPage } from "../server/cache-headers.ts";1112// `/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),15// so the server's render and the browser's agree. `/agents.md` is the same16// text as Markdown.1712const root = getRouteApi("__root__");1314const AgentsPage = () => {15 const { platformUrl } = root.useLoaderData();
5 unmodified lines
21};2223export const Route = createFileRoute("/agents")({24 component: AgentsPage,31 // The same for every reader, and it changes only with a deploy.25 headers: () => branchPage,26 head: () =>27 pageHead({28 description:
4 unmodified lines
modified:apps/web/src/routes/agents[.]md.ts-5 removed
3 unmodified lines
45import { commands } from "../features/agents/catalog.ts";6import { markdown } from "../features/agents/respond.ts";78// `/agents.md`: the Agents page as Markdown (a literal `.` is `[.]` in a9// route file's name), from the same `agentSetup` the page draws, for the10// web's own origin.1112/** The route's handler as a function of the platform's URL, which its test hands in. */8export const agentsMarkdownHandler =9 (platformUrl: string) =>10 ({ request }: { readonly request: Request }): Promise<Response> =>11 Promise.resolve(
16 unmodified lines
modified:apps/web/src/routes/asks.tsx+1 added-19 removed
44 unmodified lines
45 frontPageHandler,46 readFrontPage,47} from "../server/front-page.ts";4849// `/asks`, the front page: every open ask, read on the server by the loader, so the50// page (and an agent fetching it) arrives with its asks; narrowed here by51// the address's search. The whole list is read, so the filter offers every52// kind. The list of projects (each group's posture) is the browser's read,53// never the loader's: it may arrive after the rows, and moves none of them.54// The same URL answers `Accept: text/markdown` with `llms.txt`.5549const TITLE = "Open asks";5058/** Where the page's Markdown is. */51const MARKDOWN = "/llms.txt";5253const frontPageData = createServerFn({ method: "GET" }).handler(() =>54 Effect.runPromise(readFrontPage.pipe(Effect.provide(serverClient(env))))55);5665/** The page's headers: kept briefly, varied by `Accept`, its Markdown named. */57export const frontPageHeaders = () => ({58 ...branchPage,59 link: markdownLink(MARKDOWN),60 vary: "Accept",61});6272/** The page's head: its title, its one sentence, and its Markdown. */63export const frontPageHead = () => ({64 ...pageHead({ description: EXPLAINER, title: TITLE }),65 links: [markdownAlternateLink(MARKDOWN)],66});6778/** The open asks, unfiltered: the page narrows them, so its filter can offer every kind. */68const everyAsk = frontPageAtom({});6970const root = getRouteApi("__root__");7183/**84 * The selected ask in full, read in the browser once it is selected. It85 * wraps the page whether or not a row is selected, so selecting one never86 * remounts the list (and loses the row the keys rest on).87 */72// Wraps the page whether or not a row is selected, so selecting one never remounts the list.73const WithFull = ({74 children,75 pick,76}: {
8 unmodified lines
85};8687const decodeAsk = Schema.decodeUnknownOption(AskId);88104/** The page over its atoms, which start from what the loader read and stay live. */89const LiveFront = ({90 data,91 filter,92 platformUrl,
13 unmodified lines
106 const hydrated = useHydrated();107 const key = projectsKey(data.events.map(({ project }) => project));108 const refresh = useAtomRefresh(everyAsk);109126 // Live: each family's project, followed while the page is open.110 useAtomMount(followedAtom(key));111112 // The loader read as anyone; once someone is signed in, read who may take what for them.113 useEffect(() => {
78 unmodified lines
192 </SeededAtoms>193 );194};195213/** The filter, and the selected ask, from the address. */196const readSearch = (search: {197 readonly ask?: unknown;198 readonly kind?: unknown;199 readonly project?: unknown;
27 unmodified lines
modified:apps/web/src/routes/home.tsx-6 removed
9 unmodified lines
10import { reloadOnEnter } from "../features/shared/shell/selection.ts";11import { personalPage } from "../server/cache-headers.ts";12import { serverClient } from "../server/client.ts";1314// `/home`: the signed-in reader's own page, where the landing sends them.15// The loader reads it on the server with the reader's own session (their16// cookie goes with the call), so the page arrives with its rows. A page17// about its reader is kept by no cache.1819/** A page about its reader, kept by no cache. */14export const homeHeaders = () => personalPage;1516const homePage = createServerFn({ method: "GET" }).handler(() =>17 Effect.runPromise(
17 unmodified lines
modified:apps/web/src/routes/import.tsx-8 removed
5 unmodified lines
6import { useImporter } from "../features/import/use-importer.tsx";7import { pageHead } from "../features/shared/head.ts";8import { personalPage } from "../server/cache-headers.ts";910// `/import`: import a public repo as a project. Who is signed in is read11// in the browser (the server paints the page while it checks); an import12// made goes to the project's page, a refusal shows under the form.13// `?url=<https URL>` fills the form; nothing is imported until Import is14// pressed. A page about its reader, kept by no cache.1516/** A page about its reader, kept by no cache. */10export const importHeaders = () => personalPage;1112const ImportPage = () => {13 const { url } = Route.useSearch();
2 unmodified lines
1617 return <ImportView {...importer} here={here} url={url} />;18};1927/** The address's search: the URL to fill the form with, when it is text. */20export const importSearch = ({21 url,22}: {23 readonly url?: unknown;
8 unmodified lines
modified:apps/web/src/routes/index.tsx+1 added-18 removed
21 unmodified lines
22import { branchPage } from "../server/cache-headers.ts";23import { serverClient } from "../server/client.ts";24import { landingHandler } from "../server/front-page.ts";2526// `/`, the landing: the one page drawn outside the shell. It is the same27// page for every reader, so the edge may keep it; its server GET sends a28// reader who carries a session to `/home` before the page is drawn, and29// gives an agent `llms.txt`. A signed-in reader who reaches it by a link30// is moved on once the browser knows who they are. Its projects are read31// on the server as nobody, so every reader, script or not, is sent the32// same page with its projects in.3326const root = getRouteApi("__root__");2736/** Where the page's Markdown is. */28const MARKDOWN = "/llms.txt";2939/**40 * The projects to read, as nobody (the client without the request, so no41 * cookie reaches the platform), encoded for the loader to carry. The list42 * ignores the caller, so nobody's read is everyone's, and the page stays43 * one the edge may keep.44 */30// Read as nobody (no cookie reaches the platform): the list ignores the caller, so the page stays one the edge may keep.31const landingData = createServerFn({ method: "GET" }).handler(() =>32 Effect.runPromise(33 readLandingProjects.pipe(34 Effect.flatMap(Schema.encodeEffect(LandingProjects)),
1 unmodified line
36 )37 )38);3954/** The landing's headers: kept briefly, varied by `Accept`, its Markdown named. */40export const landingHeaders = () => ({41 ...branchPage,42 link: markdownLink(MARKDOWN),43 vary: "Accept",44});4561/** The landing's head: its title, its own sentence to unfurl with, and its Markdown. */46export const landingHead = () => ({47 ...pageHead({48 description: LEDE,49 title: "A git platform with a typed gate",50 }),51 links: [markdownAlternateLink(MARKDOWN)],52});5370/** A signed-in reader who came by a link goes on to their home. */54const useHomeOnceSignedIn = () => {55 const signedIn = useSignedIn();56 const router = useRouter();57
42 unmodified lines
modified:apps/web/src/routes/install[.]sh.ts-3 removed
3 unmodified lines
4import { backend } from "#backend";56import { forwarded } from "../features/agents/forward.ts";78// The CLI's install script, so `curl -fsSL <web>/install.sh | sh` works9// from the web host: the platform serves it; the web passes GET10// and HEAD on.8export const Route = createFileRoute("/install.sh")({9 server: { handlers: forwarded(backend, env) },10});
modified:apps/web/src/routes/llms-full[.]txt.ts-8 removed
7 unmodified lines
8import { commands } from "../features/agents/catalog.ts";9import { markdown, unavailable } from "../features/agents/respond.ts";10import { serverClient } from "../server/client.ts";1112/**13 * `/llms-full.txt`: the index, then every refusal, how git meets the14 * platform, how a landing happens, the events and the guides, with the15 * projects the platform lists now. The web alone serves it: the platform's16 * `/` stays the index (`apps/platform/test/home.test.ts`).17 */1819/** The route's handler as a function of its client and the platform's URL, which its test hands in. */12export const llmsFullHandler =13 (clientFor: (request: Request) => Layer.Layer<Client>, platformUrl: string) =>14 ({ request }: { readonly request: Request }): Promise<Response> =>15 Effect.runPromise(
29 unmodified lines
modified:apps/web/src/routes/llms[.]txt.ts-1 removed
2 unmodified lines
34import { serverClient } from "../server/client.ts";5import { frontLlmsHandler } from "../server/llms.ts";67// `/llms.txt`: the platform for an agent (`server/llms.ts`).7export const Route = createFileRoute("/llms.txt")({8 server: {9 handlers: {10 GET: frontLlmsHandler(
6 unmodified lines
modified:apps/web/src/routes/rpc.ts-2 removed
3 unmodified lines
4import { backend } from "#backend";56import { rpcHandler } from "../server/rpc.ts";78// The browser's contracts: every call posts here, and the backend carries it9// to the platform (src/server/rpc.ts).8export const Route = createFileRoute("/rpc")({9 server: {10 handlers: {11 POST: rpcHandler(backend, env),
3 unmodified lines
modified:apps/web/src/routes/today.tsx-10 removed
24 unmodified lines
25import { TodayView } from "../features/today/today-page.tsx";26import { personalPage } from "../server/cache-headers.ts";27import { serverClient } from "../server/client.ts";2829// `/today`: the signed-in decider's decisions across their projects, or in30// the one `?project=` names. The loader reads it on the server with the31// reader's own session (their cookie goes with the call), so the page32// arrives with its rows; in the browser the same read stays live, and a33// choice reads it again. A page about its reader is kept by no cache.3435/** What the address may name: a project to narrow to, and the decision selected. */29const TodaySearch = Schema.Struct({30 decision: Schema.optionalKey(Schema.String),31 project: Schema.optionalKey(ProjectName),32});
1 unmodified line
34type TodaySearch = typeof TodaySearch.Type;3536const searchOf = Schema.decodeUnknownOption(TodaySearch);3745/** A page about its reader, kept by no cache. */38export const todayHeaders = () => personalPage;3948/** What the atom holds now, or the loader's read until it has read. */40const readFrom = (41 result: AsyncResult.AsyncResult<Today, unknown>,42 loaded: TodayRead43): TodayRead => {
11 unmodified lines
55 readToday(data).pipe(Effect.provide(serverClient(env, getRequest())))56 )57 );5868/** Today over its atom, which starts from what the loader read and reads again after a choice. */59const LiveToday = ({60 data,61 project,62}: {
53 unmodified lines
modified:apps/web/src/server/addresses.ts+4 added-51 removed
1/**2 * A project's address on the web (ADR 0032): `/<owner>/<name>/…`, and for3 * a project at its source path `/<host>/<account>/<name>/…`. One route tree4 * serves both, `routes/$owner/$project/**`:5 *6 * - `addressRewrite` carries a source path into that tree and back. On the7 * way in `/github.com/pallets/click/…` reads as8 * `/github.com%2Fpallets/click/…`, so `$owner` is `github.com/pallets`;9 * on the way out every link the router prints is the real address again.10 * - `projectParams` gives the project's pages its full name as `project`11 * (`oscabriel/datekit`), the name every read takes, and splits it again12 * when the router prints a link.13 * - `canonicalAddress` answers, before any page, a key a project kept from14 * before owners (`/datekit/…`), a name spelled in another case15 * (`/OscaBriel/datekit/…`) and one ending in `.git` with a 301 to the name's address, the rest of16 * the path and the query kept.17 */1// A project at its source path is carried into the one route tree by `addressRewrite`: `/github.com/pallets/click/…`2// reads as `/github.com%2Fpallets/click/…`, so `$owner` is `github.com/pallets`, and every printed link is the real address.3import {4 ProjectName,5 projectAddressOf,6 reservedProjectNames,
9 unmodified lines
1617const isReserved = (segment: string) =>18 reservedProjectNames.some((reserved) => reserved === segment.toLowerCase());1935/** `/github.com/pallets/…` as the route tree reads it: the owner in one segment. */20const intoTree = (pathname: string) => {21 const [, host, account, ...rest] = pathname.split("/");2223 return host !== undefined && account !== undefined && isSourceHost(host)24 ? ["", `${host}%2F${account}`, ...rest].join("/")25 : pathname;26};2744/** The route tree's one-segment owner as the address spells it. */28const outOfTree = (pathname: string) => {29 const [, owner, ...rest] = pathname.split("/");30 const slash = owner?.toUpperCase().indexOf("%2F") ?? -1;31
5 unmodified lines
37 "/"38 );39};4058/** The router's rewrite pair: a source path in, the real address out. */41export const addressRewrite: LocationRewrite = {42 input: ({ url }) => {43 url.pathname = intoTree(url.pathname);44
5 unmodified lines
50 return url;51 },52};5372/**73 * What the `$owner/$project` route reads from its two segments. Start runs74 * `parse` for a server handler too, so a handler reads the full name as75 * `project` (`test/server-params.test.ts`).76 */54// Start runs `parse` for a server handler too, so a handler reads the full name as `project`.55interface ProjectParams {56 readonly owner: string;57 readonly project: string;58}5982/**83 * The `$owner/$project` route's params: `project` is the full name its84 * pages read (`oscabriel/datekit`), and a link that names the full name85 * prints its owner and short name as two params.86 */60export const projectParams = {61 parse: ({ owner, project }: ProjectParams): ProjectParams => ({62 owner,63 project: `${owner}/${project}`,
8 unmodified lines
72};7374const decodeName = Schema.decodeOption(ProjectName);75103/**104 * A permanent redirect to `location`. It reads as nobody and changes only105 * when the forty are keyed again, so a browser and the edge keep it a day.106 */76// It reads as nobody and changes only when the projects are keyed again, so a browser and the edge keep it a day.77const movedTo = (location: string) =>78 new Response(null, {79 headers: { "cache-control": "public, max-age=86400", location },80 status: 301,81 });82113/**114 * A name as spelled without a trailing `.git` on its last segment: an115 * address copied from a clone URL (`/github.com/pallets/click.git`) names116 * the project.117 */83const withoutGit = (spelled: string) => spelled.replace(/\.git$/iu, "");84120/**121 * The 301 a request needs to reach its project's address, if any: a key a122 * project kept from before owners (`/datekit/tree/main?x=1` to123 * `/oscabriel/datekit/tree/main?x=1`) and a name in another case124 * (`/OscaBriel/datekit` to `/oscabriel/datekit`), and a name with a125 * trailing `.git` (`/github.com/pallets/click.git` to126 * `/github.com/pallets/click`). None for the web's own127 * pages and files, for an address already canonical, and for a name no128 * project could have, which its page says is unknown.129 */85export const canonicalAddress = (request: Request): Option.Option<Response> => {86 if (request.method !== "GET" && request.method !== "HEAD") {87 return Option.none();88 }
22 unmodified lines
111 )112 );113};114160/** A Worker's `fetch`, as TanStack Start's server entry gives it. */115interface Entry<Rest extends readonly unknown[]> {116 readonly fetch: (117 request: Request,118 ...rest: Rest119 ) => Promise<Response> | Response;120}121168/** `entry`, answering first with the 301 a request's address needs. */122export const addressedEntry = <Rest extends readonly unknown[]>(123 entry: Entry<Rest>124): Entry<Rest> => ({125 fetch: (request, ...rest) =>
4 unmodified lines
modified:apps/web/src/server/backend.ts+3 added-20 removed
1/**2 * `#backend`'s production target: the request goes to the platform over the3 * `PLATFORM` service binding, with no network hop and no CORS.4 *5 * It travels at the platform's own URL (`PUBLIC_PLATFORM_URL`), never the6 * web's: the platform names a project's and a claim's git remote from the7 * origin of the request it is handed, and a remote on the web's8 * host would lead nowhere. Method and body are kept; the browser's session9 * cookie becomes the HTTP `Authorization` header, the only credential the10 * platform reads, and the browser's own cookies and any11 * `authorization` it set never leave the web (`session.ts`).12 *13 * A session the platform no longer knows (it answers 401 to a credential14 * it cannot verify, and only then) is not a refusal of the call: the call is15 * asked again with no credential, so a public read still answers and a16 * signed-in one says `Unauthenticated`, and the answer expires the cookie.17 */1// The request travels at the platform's own URL, never the web's: the platform names git remotes from the origin it is handed.2// The session cookie becomes `Authorization`; the browser's own cookies and any `authorization` it set never leave the web.3// A 401 (a credential the platform cannot verify) is asked again with no credential, and the answer expires the cookie.4import { Effect, Option } from "effect";56import type { Backend } from "./rpc.ts";7import {
2 unmodified lines
10 settingCookies,11 withCredential,12} from "./session.ts";1328/** `request` as the platform's own: the same path and query on its origin. */14const onPlatform = (request: Request, platformUrl: string) => {15 const { pathname, search } = new URL(request.url);1617 return new Request(new URL(`${pathname}${search}`, platformUrl), request);18};1935/** `response` as it came, also expiring the session cookie and its kept handle. */20const expiringSession = (response: Response) =>21 new Response(response.body, {22 headers: settingCookies(response.headers, clearedCookies()),23 status: response.status,
2 unmodified lines
2627const send = (env: Env, request: Request) =>28 Effect.promise(() => env.PLATFORM.fetch(request));2946/** The request's body read whole, so the call can be asked twice; none for a GET or HEAD. */30const bodyOf = (request: Request) =>31 request.method === "GET" || request.method === "HEAD"32 ? Effect.succeed(null)33 : Effect.promise(() => request.arrayBuffer());
32 unmodified lines
modified:apps/web/src/server/cache-headers.ts+2 added-25 removed
1/**2 * The `Cache-Control` a page's route gives (its `headers`), by what the3 * page is addressed by. Only a document's own response carries these:4 * the hashed assets get theirs from `public/_headers`.5 *6 * - A page at `main` or a tag changes with the next landing: a browser7 * keeps it for 30 seconds and may show it for five minutes more while it8 * asks again. No `s-maxage`: a shared cache that honours it stops serving9 * stale while it asks. A code page at a full commit id is kept the same10 * way: the commit never changes, but the page also carries its landing,11 * which the project records after main has moved (a read between the two12 * 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 */1// No `s-maxage`: a shared cache that honours it stops serving stale while it asks.2// Workers Cache keys by path and query, never by cookie, so a page that gives `branchPage` must read as nobody.34export const branchPage = {5 "Cache-Control": "public, max-age=30, stale-while-revalidate=300",6} as const satisfies Readonly<Record<string, string>>;
4 unmodified lines
modified:apps/web/src/server/client.ts-13 removed
1/**2 * The contracts for server routes that answer agents (`llms.txt`, an ask as3 * Markdown): a protocol `Client` whose calls go to `/rpc` through the same4 * backend the browser's do, in process, so a server route needs no network5 * hop and meets the same credential rule.6 */1import { Client, Contracts } from "@repo/protocol/contracts";2import { Layer } from "effect";3import { FetchHttpClient } from "effect/http";4import { RpcClient, RpcSerialization } from "effect/rpc";
1 unmodified line
6import { backend } from "#backend";78import type { Backend } from "./rpc.ts";916/**17 * A `fetch` that hands each request to `backend` with `env`, carrying the18 * caller's cookie when there is a caller, so `backend` treats the call as19 * the browser's own.20 */10const inProcess =11 (over: Backend, env: Env, caller: Request | undefined): typeof fetch =>12 (input, init) => {13 const request = new Request(input, init);
5 unmodified lines
1920 return over(request, env);21 };2234/** `serverClient` over any backend: the seam its test drives. */23export const serverClientOver =24 (over: Backend) =>25 (env: Env, request?: Request): Layer.Layer<Client> =>26 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(
7 unmodified lines
34 Layer.succeed(FetchHttpClient.Fetch)(inProcess(over, env, request))35 )36 );3750/** The contracts as a server route calls them, through `#backend`. */38export const serverClient: (39 env: Env,40 request?: Request41) => Layer.Layer<Client> = serverClientOver(backend);
modified:apps/web/src/server/edge-cache.ts+4 added-45 removed
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 */1// Workers Cache keys an answer by path and query alone, not by host, `Cookie` or `Authorization`.2// An answer to a request with a credential, one that sets a cookie, or one with no `Cache-Control` is kept nowhere;3// any other varies by `Cookie`, so a signed-in reader is never handed a page kept from a signed-out one.4import { Effect } from "effect";526/** The `Cache-Control` of an answer kept by nobody: no shared cache, no browser. */6export const KEPT_NOWHERE = "private, no-store";729/** Headers that would decide what the edge keeps over `Cache-Control`. */8const EDGE_OVERRIDES = ["cdn-cache-control", "cloudflare-cdn-cache-control"];932/** The directives of a `Cache-Control` value, each as `name` or `name=value`, lower-cased. */10const directivesOf = (cacheControl: string) =>11 cacheControl12 .split(",")13 .map((directive) => directive.trim().toLowerCase())14 .filter((directive) => directive !== "");1539/** Whether the request says who is reading it: any cookie, or an `Authorization`. */16const speaksForSomeone = (request: Request) =>17 request.headers.has("cookie") || request.headers.has("authorization");1843/**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 */19// A field-naming directive (`private="set-cookie"`) lets the cache store the answer with that field stripped.20const unsafeFor = (cacheControl: string | null) =>21 cacheControl === null ||22 directivesOf(cacheControl).some(23 (directive) =>24 directive.startsWith("private=") || directive.startsWith("no-cache=")25 );2655/** Whether the cache bypasses an answer under `cacheControl`. */27const keptNowhere = (cacheControl: string) =>28 directivesOf(cacheControl).some(29 (directive) => directive === "private" || directive === "no-store"30 );3161/** `vary` with `Cookie` among its headers. */32const varyingByCookie = (vary: string | null) => {33 const names = (vary ?? "")34 .split(",")35 .map((name) => name.trim())
3 unmodified lines
39 ? names.join(", ")40 : [...names, "Cookie"].join(", ");41};4273/** `response`'s headers as the edge may see them, for `request`. */43const edgeHeaders = (request: Request, response: Response) => {44 const headers = new Headers(response.headers);4546 for (const name of EDGE_OVERRIDES) {
18 unmodified lines
6566 return headers;67};68100/**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 */69export const forTheEdge = (request: Request, response: Response): Response =>70 new Response(response.body, {71 headers: edgeHeaders(request, response),72 status: response.status,73 statusText: response.statusText,74 });75111/** A Worker's `fetch`, as TanStack Start's server entry gives it. */76interface Entry<Rest extends readonly unknown[]> {77 readonly fetch: (78 request: Request,79 ...rest: Rest80 ) => Promise<Response> | Response;81}82119/** The Worker's `fetch` once every answer passes through `forTheEdge`. */83interface EdgeEntry<Rest extends readonly unknown[]> {84 readonly fetch: (request: Request, ...rest: Rest) => Promise<Response>;85}86124/**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 */87export const edgeEntry = <Rest extends readonly unknown[]>(88 entry: Entry<Rest>89): EdgeEntry<Rest> => ({90 fetch: (request, ...rest) =>
7 unmodified lines
modified:apps/web/src/server/folder.ts+2 added-20 removed
1/**2 * A folder and its README, read on the server: the read both the project's3 * page (its root at main) and a folder's page (`/$project/tree/$rev/$`)4 * render from, so either arrives whole, README included, before the5 * browser runs anything. It lives here, not in `features/code/`, because6 * it calls the contracts and the views there import no transport.7 */1import { Client } from "@repo/protocol/contracts";2import type { FileView, Rev, TreeListing } from "@repo/protocol/domain/code";3import type { ProjectName } from "@repo/protocol/ids";4import { RepoPath } from "@repo/protocol/ids";
5 unmodified lines
10} from "@repo/protocol/refusal";11import { Effect, Option } from "effect";12import type { RpcClientError } from "effect/rpc";1321/** The name most folders give their README, read beside the folder rather than after it. */14const GUESS = "README.md";1524/**25 * The folder `path` (the root when none) of `project` at `rev`, and its26 * README; a README that cannot be read leaves the folder without it, while27 * a folder that cannot be read is the platform's refusal (or the call's28 * own failure: the platform did not answer, or turned the credential29 * away).30 *31 * The folder and a `README.md` in it are read at once, saving a round trip32 * on most pages. The guess stands only when it is the README the folder33 * names, read at the folder's commit (`main` may move between the two34 * reads); otherwise the folder's own README is read at its commit.35 */16// The folder and a `README.md` in it are read at once. The guess stands only when it is the README the folder17// names at the folder's commit (`main` may move between the two reads).18export const readFolderWithReadme = (input: {19 readonly path: Option.Option<RepoPath>;20 readonly project: ProjectName;21 readonly rev: Rev;
54 unmodified lines
modified:apps/web/src/server/front-page.ts+1 added-30 removed
1/**2 * The front page's reads on the server, and its answer to an agent: what3 * its loader reads (the open asks, each family's parent in full, and the4 * events of each project that holds a family), and its GET, which gives a5 * request for Markdown `llms.txt`. The landing at `/` answers an agent the6 * same way, and sends a reader who carries a session to their home.7 */1import { Client } from "@repo/protocol/contracts";2import { Ask } from "@repo/protocol/domain/ask";3import { ProjectEvent } from "@repo/protocol/domain/event";4import { FrontPageEntry } from "@repo/protocol/domain/front-page";
8 unmodified lines
13import { frontLlmsHandler } from "./llms.ts";14import type { ClientFor } from "./llms.ts";15import { credentialFrom } from "./session.ts";1624/** What the loader carries from the server: the asks, the families' parents in full, and their projects' events. */17export const FrontPageData = Schema.Struct({18 entries: Schema.Array(FrontPageEntry),19 events: Schema.Array(20 Schema.Struct({ events: Schema.Array(ProjectEvent), project: ProjectName })
3 unmodified lines
24});2526export type FrontPageData = typeof FrontPageData.Type;2736/** Four reads at once: a page holds a few families, each read once. */28const AT_ONCE = 4;2939/** Each family on the page, by its project: `[project, parent]`. */30const familiesOf = (entries: readonly FrontPageEntry[]) =>31 Arr.dedupe(entries.map(({ project }) => project)).flatMap((project) =>32 familiesIn(33 entries.flatMap((entry) => (entry.project === project ? [entry.ask] : []))34 ).map(({ parent }) => [project, parent] as const)35 );3647/**48 * The front page's data, as the anonymous viewer reads it (so the page may49 * be kept by a cache; the browser reads again once someone signs in): the50 * open asks; each family's parent in full, which counts its children; and51 * the events of each project that holds a family, which mark them. A52 * parent or a replay the platform cannot give now leaves its family drawn53 * as plain rows. The list of projects is never read here.54 */37// As the anonymous viewer reads it, so the page may be kept by a cache; the browser reads again once someone signs in.38export const readFrontPage = Effect.gen(function* () {39 const client = yield* Client;40 const { entries } = yield* client.frontPage({});41 const families = familiesOf(entries);
25 unmodified lines
67 parents: Arr.getSomes(parents),68 });69});7088/**89 * The page's GET, as a function of its client: a request that asks for90 * Markdown gets `llms.txt`, varied by `Accept`; any other falls through to91 * the page.92 */71export const frontPageHandler =72 (clientFor: ClientFor, platformUrl: string) =>73 <Next>({74 next,
12 unmodified lines
87 )88 )89 : next();90113/** The answer that sends a signed-in reader from the landing to their home. */91const toHome = () =>92 new Response(null, {93 headers: { "cache-control": KEPT_NOWHERE, location: HOME_PATH },94 status: 302,95 });96120/**121 * The landing's GET: a request for Markdown gets `llms.txt`, as the front122 * page's does; a reader who carries a session goes to `/home`, an answer123 * kept nowhere (the edge never stores an answer to a request with a124 * cookie); anyone else gets the landing, the same page for every reader.125 */97export const landingHandler =98 (clientFor: ClientFor, platformUrl: string) =>99 <Next>({100 next,
13 unmodified lines
modified:apps/web/src/server/llms.ts-16 removed
1/**2 * The agents' indexes as handlers of a request, each a function of its3 * client and the platform's URL: `/llms.txt` for the platform and4 * `/<owner>/<name>/llms.txt` for one project. Their routes serve them, and the5 * front page and a project's page answer a request for Markdown with them,6 * so the text is written once.7 */1import { Client } from "@repo/protocol/contracts";2import { ProjectName } from "@repo/protocol/ids";3import { Array as Arr, Effect, Option, Schema } from "effect";4import type { Layer } from "effect";
6 unmodified lines
11} from "../features/agents/llms.ts";12import { markdown, unavailable } from "../features/agents/respond.ts";13import { stillWaiting } from "../features/front/families.ts";1422/** A route's client, for the request it answers. */15export type ClientFor = (request: Request) => Layer.Layer<Client>;1625/**26 * `/llms.txt`: the platform for an agent, with the projects it lists now,27 * read through the same backend the browser's calls take.28 */17export const frontLlmsHandler =18 (clientFor: ClientFor, platformUrl: string) =>19 ({ request }: { readonly request: Request }): Promise<Response> =>20 Effect.runPromise(
16 unmodified lines
37 );3839const decodeProject = Schema.decodeUnknownOption(ProjectName);4053/**54 * `/<owner>/<name>/llms.txt`: one project for an agent, as the platform lists55 * it, with its open asks. A name the platform does not list is not found.56 */41export const projectLlmsHandler =42 (clientFor: ClientFor, platformUrl: string) =>43 ({44 params,
53 unmodified lines
modified:apps/web/src/server/pierre-themes.ts+2 added-13 removed
1/**2 * `@pierre/theming/themes` as the web Worker bundles it (`vite.config.ts`3 * resolves it here for the Worker): no theme collection. The package's4 * collections map every Pierre and Shiki theme to a dynamic import, about5 * 1.7 MB the Worker's build would carry; the server draws in the token6 * theme alone, which `features/code/prerender-server.ts` attaches itself.7 * So the collections here hold nothing, and `createTheme` normalizes a8 * theme as the package's does.9 */1// `@pierre/theming/themes` for the Worker: its collections map every theme to a dynamic import, about 1.7 MB,2// and the server draws in the token theme alone, so these collections hold nothing.3import { Effect } from "effect";4import { normalizeTheme } from "shiki/core";5import type {6 ThemeRegistrationAny,7 ThemeRegistrationResolved,8} from "shiki/core";917/** A theme as a collection holds it: its name, and its loader. */10interface Descriptor {11 readonly name: string;12 readonly load: () => Promise<ThemeRegistrationResolved>;13}1423/** A collection with no themes in it. */15const empty = {16 getTheme: (_name: string): Descriptor | undefined => undefined,17 getThemes: (): readonly Descriptor[] => [],18};
3 unmodified lines
22export const shikiThemes = empty;2324export const themes = empty;2535/** A module's theme, whether it is the module or its default export. */26const unwrap = (27 loaded: ThemeRegistrationAny | { default: ThemeRegistrationAny }28) => ("default" in loaded ? loaded.default : loaded);2940/** A named theme whose loader hands it over normalized, as Shiki draws with it. */30export const createTheme = ({31 load,32 name,33}: {
13 unmodified lines
modified:apps/web/src/server/project-page.ts-23 removed
1/**2 * A project's home's reads on the server, and its answer to an agent: what3 * its loader reads (its asks, its own ledger, its events, its policy, its4 * root folder and README, then each family's parent in full), and its GET,5 * which gives a request for Markdown the project's `llms.txt`.6 */1import { Client, PolicyOf } from "@repo/protocol/contracts";2import { Ask, AskListing } from "@repo/protocol/domain/ask";3import { FileView, TreeListing } from "@repo/protocol/domain/code";4import { ProjectEvent } from "@repo/protocol/domain/event";
19 unmodified lines
24import type { ClientFor } from "./llms.ts";2526export const decodeName = Schema.decodeUnknownOption(ProjectName);2734/** What the loader carries from the server, each read there when the platform gave it. */28export const ProjectPageData = Schema.Struct({29 asks: Schema.optionalKey(Schema.Array(AskListing)),30 code: Schema.optionalKey(31 Schema.Struct({
4 unmodified lines
36 events: Schema.optionalKey(Schema.Array(ProjectEvent)),37 ledger: Schema.optionalKey(Ledger),38 now: Schema.DateTimeUtcFromString,39 parents: Schema.Array(Ask),47 /** The project's policy, and where it was imported from, as `projectPolicy` gives them. */40 policy: Schema.optionalKey(PolicyOf.successSchema),41 project: ProjectName,42});4344export type ProjectPageData = typeof ProjectPageData.Type;4546const isUnknownProject = Schema.is(UnknownProject);4756/**57 * A read the page can do without: its value, or none when the platform58 * cannot give it now (whatever went wrong on the way); a project it does59 * not know is a 404.60 */48const optional = <A, E, R>(read: Effect.Effect<A, E, R>) =>49 read.pipe(50 Effect.asSome,51 Effect.catchCause((cause) =>
2 unmodified lines
54 : Effect.succeed(Option.none<A>())55 )56 );5771/** Four reads at once: a project holds a few families, each read once. */58const AT_ONCE = 4;5974/**75 * The project's home, read over `Client`, or a not-found for a name that is76 * none or a project the platform does not know.77 */60export const readProjectPage = (name: string) =>61 Effect.gen(function* () {62 const project = yield* Effect.fromOption(decodeName(name));63 const client = yield* Client;
60 unmodified lines
124 project,125 }).pipe(Effect.orDie);126 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));127146/**147 * The page's GET, as a function of its client: a request that asks for148 * Markdown gets the project's `llms.txt`, varied by `Accept`; any other149 * falls through to the page.150 */128export const projectPageHandler =129 (clientFor: ClientFor, platformUrl: string) =>130 <Next>({131 next,
17 unmodified lines
modified:apps/web/src/server/rpc.ts+1 added-11 removed
1/**2 * The web's `/rpc` route, as a function of its backend: what the route file3 * (`src/routes/rpc.ts`) wires, and what its test drives with a stub.4 */56/**7 * How the web reaches the platform. `#backend` picks one: under the8 * `development` condition an in-process world (`src/dev/backend.ts`),9 * otherwise the `PLATFORM` service binding (`src/server/backend.ts`).10 */1// `#backend` picks one: under the `development` condition an in-process world, otherwise the `PLATFORM` binding.2export type Backend = (request: Request, env: Env) => Promise<Response>;313/** The `/rpc` route's handler: the request goes to `backend`, with the Worker's env. */4export const rpcHandler =5 (backend: Backend, env: Env) =>6 ({ request }: { readonly request: Request }) =>7 backend(request, env);
modified:apps/web/src/server/session.ts+7 added-133 removed
1/**2 * A decider's session on the web. The platform is the OAuth3 * authorization server; the web is one of its public clients, and4 * signs a person in with PKCE: `/auth/signin` sends the browser to the5 * platform's `/authorize`, `/auth/callback` trades the code at the6 * platform's `/token` over `PLATFORM`, and the access token goes into one7 * HttpOnly cookie on the web's origin. The page's JavaScript never sees it,8 * no URL, log line or response body carries it, and the web holds no9 * secret: PKCE needs none, and the web's client is a Client ID Metadata10 * Document the web serves itself (`/auth/client`).11 *12 * Every forward to the platform (`backend.ts`) turns that cookie into the13 * HTTP `Authorization` header, the only credential the platform reads,14 * and drops the browser's own cookies and any `authorization` it15 * set: the browser never chooses the credential.16 *17 * Who is signed in is kept beside the token, in a second HttpOnly cookie18 * (`HANDLE_COOKIE`): the callback asks the platform's `status` once, with19 * the new token, and keeps the handle it names, bound to that token by its20 * SHA-256, so `/auth/whoami` answers every page from the cookie with no21 * platform call. The handle only shapes what a page shows: every read and22 * write still carries the token, and the platform decides who the caller23 * is. A handle kept for another token is not believed, a session from24 * before the handle was kept asks `status` once, and sign-out and any25 * `Unauthenticated` expire both cookies.26 */1// The access token lives only in an HttpOnly cookie: no URL, log line or response body carries it, and the web2// holds no secret (PKCE, and a Client ID Metadata Document it serves itself). The handle cookie beside it only3// shapes what a page shows; every call carries the token, and the platform decides who the caller is.4import { Brand } from "@repo/brand";5import { Client } from "@repo/protocol/contracts";6import { Handle as HandleSchema } from "@repo/protocol/ids";7import type { Handle } from "@repo/protocol/ids";8import { Data, Effect, Option, Redacted, Schema } from "effect";9import type { Layer } from "effect";1034/**35 * The session cookie: the platform's access token. `__Host-` keeps it to36 * this exact origin over HTTPS, so no sibling host under the same site37 * (another Worker on the account's `workers.dev` subdomain) can set or38 * shadow it.39 */11// `__Host-` keeps it to this exact origin over HTTPS, so no sibling host on the same `workers.dev` subdomain can set or shadow it.12export const SESSION_COOKIE = "__Host-session";1342/** The cookie the signed-in handle is kept in beside the session, for `whoami`. */14export const HANDLE_COOKIE = "__Host-handle";1545/** The cookie a sign-in in progress waits in: its state, PKCE verifier and way back. */16const SIGN_IN_COOKIE = "__Host-sign-in";1748/** How long a sign-in in progress waits for its callback: ten minutes. */18const SIGN_IN_SECONDS = 600;1920/**21 * How much sooner than its token the session cookie expires, so a cookie22 * never carries a token the platform has just let go.23 */24const SESSION_MARGIN_SECONDS = 60;2557/** The web's own sign-in paths that this module names in what it answers. */26const AUTH_PATHS = {27 callback: "/auth/callback",28 client: "/auth/client",29 signIn: "/auth/signin",30} as const;3164/** What a route's server handler is handed, of what it uses. */32export interface Handled {33 readonly request: Request;34}3569// --- The cookie -------------------------------------------------------------7071/**72 * A platform token as the session cookie carries it: no space, quote,73 * comma, semicolon or backslash. The callback keeps only such a token and74 * `credentialFrom` reads back only such a token, so a cookie is never set75 * that no later request could be signed in with.76 */36// Only such a token is kept and read back, so a cookie is never set that no later request could sign in with.37const Token = Schema.NonEmptyString.check(Schema.isPattern(/^[^\s",;\\]+$/u));3839const isToken = Schema.is(Token);4081/** A cookie value as it was set, if it decodes. */41const decodedValue = Option.liftThrowable(decodeURIComponent);4284/** The value of the cookie `name` the request carries, if it carries one. */43const cookieValue = (request: Request, name: string) =>44 Option.fromNullishOr(request.headers.get("cookie")).pipe(45 Option.flatMap((header) =>46 Option.fromUndefinedOr(
6 unmodified lines
53 Option.map((pair) => pair.slice(name.length + 1)),54 Option.flatMap(decodedValue)55 );5699/** The session cookie's value: the platform token this browser signed in with. */57export const credentialFrom = (request: Request): Option.Option<string> =>58 cookieValue(request, SESSION_COOKIE).pipe(Option.filter(isToken));59103/**104 * `request` as the platform should see it: without the browser's cookies105 * and without any `authorization` the browser set, and with `Authorization:106 * Bearer <token>` when there is a session.107 */60export const withCredential = (61 request: Request,62 token: Option.Option<string>63): Request => {
8 unmodified lines
7273 return new Request(request, { headers });74};75124/** A cookie only this origin's HTTP requests carry, never the page's JavaScript. */76const lockedCookie = (name: string, value: string, maxAgeSeconds: number) =>77 `${name}=${encodeURIComponent(value)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`;78128/** The `Set-Cookie` value that holds `token` for `maxAgeSeconds`. */79export const sessionCookie = (token: string, maxAgeSeconds: number) =>80 lockedCookie(SESSION_COOKIE, token, maxAgeSeconds);81132/** The `Set-Cookie` value that ends the session now. */82export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);83135/** The `Set-Cookie` values that end the session and forget its handle, now. */84export const clearedCookies = () => [85 clearedCookie(),86 lockedCookie(HANDLE_COOKIE, "", 0),87];8889const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);90143/** `headers`, also setting each of `cookies` (each its own `Set-Cookie` line). */91export const settingCookies = (92 headers: HeadersInit,93 cookies: readonly string[]94) => {
5 unmodified lines
100101 return all;102};103157// --- PKCE -------------------------------------------------------------------158104const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);105161/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */106const randomText = (size: number) =>107 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(108 Effect.flatMap(encodeBase64Url),109 Effect.orDie110 );111168/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */112export const challengeOf = (verifier: string) =>113 Effect.promise(() =>114 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))115 ).pipe(116 Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),117 Effect.orDie118 );119177/** A fresh PKCE verifier and its challenge, and a fresh state, each 32 random bytes. */120export const pkce = Effect.gen(function* () {121 const verifier = yield* randomText(32);122123 return {
2 unmodified lines
126 verifier,127 };128});129188// --- The handle kept beside the session --------------------------------------189190/**191 * How long a handle `whoami` learned for a session from before handles were192 * kept is kept: the session's own lifetime is not known there. Bound to its193 * token, it is never believed past the session.194 */130const HANDLE_LEARNED_SECONDS = 24 * 60 * 60;131197/** The token's SHA-256, in base64url: what binds a kept handle to its session. */132const fingerprintOf = (token: string) =>133 Effect.promise(() =>134 crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))135 ).pipe(136 Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),137 Effect.orDie138 );139206/**207 * The `Set-Cookie` value that keeps `handle` for the session `token`, for208 * `maxAgeSeconds`: `<fingerprint>.<handle>` (a fingerprint is base64url,209 * which has no `.`).210 */140// `<fingerprint>.<handle>`: a fingerprint is base64url, which has no `.`.141const handleCookie = (token: string, handle: Handle, maxAgeSeconds: number) =>142 Effect.map(fingerprintOf(token), (fingerprint) =>143 lockedCookie(HANDLE_COOKIE, `${fingerprint}.${handle}`, maxAgeSeconds)144 );145146const decodeHandle = Schema.decodeUnknownOption(HandleSchema);147218/** The handle kept for the session `token`, if the request carries one kept for it. */148const keptHandle = (request: Request, token: string) =>149 Effect.map(fingerprintOf(token), (fingerprint) =>150 Option.flatMap(cookieValue(request, HANDLE_COOKIE), (value) => {151 const at = value.indexOf(".");
3 unmodified lines
155 : Option.none();156 })157 );158230/** The handle the platform's `status` names for the session `token`, asked through `clientFor`. */159const handleOf = (160 clientFor: (request: Request) => Layer.Layer<Client>,161 origin: string,162 token: string
9 unmodified lines
172 )173 )174 );175248// --- Where the browser goes -------------------------------------------------249250/** The web's OAuth client id at `origin`: the URL of its metadata document. */176const clientIdOf = (origin: string) => `${origin}${AUTH_PATHS.client}`;177253/** Where the platform sends the browser back to, at `origin`. */178const redirectUriOf = (origin: string) => `${origin}${AUTH_PATHS.callback}`;179256/**257 * Where to go after signing in or out: `wanted` when it is a path on this258 * web (resolved against its origin, so `//host`, `/\host` and a full URL259 * elsewhere all fall back) and not a sign-in path itself; the front page260 * otherwise.261 */180// Resolved against the origin, so `//host`, `/\host` and a full URL elsewhere all fall back to the front page.181export const returnPath = (origin: string, wanted: string | null) =>182 Option.fromNullishOr(wanted).pipe(183 Option.filter((path) => path.startsWith("/")),184 Option.flatMap((path) => Option.fromNullishOr(URL.parse(path, origin))),
2 unmodified lines
187 Option.filter((path) => !path.startsWith("/auth/")),188 Option.getOrElse(() => "/")189 );190272/** A 302 to `location` that sets `cookies` and is never cached. */191export const redirect = (location: string, cookies: readonly string[]) =>192 new Response(null, {193 headers: settingCookies(194 {
5 unmodified lines
200 ),201 status: 302,202 });203286/** A short page that says why signing in stopped, and how to start again. */204const stoppedPage = (205 status: number,206 reason: string,207 cookies: readonly string[]
11 unmodified lines
219 { headers, status }220 );221};222306// --- Sign-in ----------------------------------------------------------------307308/** A sign-in in progress, as its cookie holds it. */223const PendingSignIn = Schema.Struct({224 return: Schema.String,225 state: Schema.String,226 verifier: Schema.String,
6 unmodified lines
233const encodePending = Schema.encodeEffect(PendingCookie);234235const decodePending = Schema.decodeOption(PendingCookie);236323/**324 * `GET /auth/signin[?return=<path>]`: to the platform's `/authorize` with a325 * fresh PKCE challenge and state; the verifier, the state and the way back326 * wait in a short-lived HttpOnly cookie for the callback.327 */237export const signInHandler =238 (env: Env) =>239 ({ request }: Handled): Promise<Response> =>240 Effect.runPromise(
23 unmodified lines
264 ]);265 })266 );267359// --- The callback -----------------------------------------------------------360361/** Signing in stopped before a session: a 400 the person reads, or a 502 when the platform could not be asked. */268class SignInStopped extends Data.TaggedError("SignInStopped")<{269 readonly reason: string;270 readonly status: 400 | 502;271}> {}
13 unmodified lines
285 reason: "The platform could not be reached to complete this sign-in.",286 status: 502,287});288383/** What the platform's `/token` answers a good code with, of what the web keeps. */289const TokenAnswer = Schema.Struct({290 access_token: Schema.RedactedFromValue(Token),291 expires_in: Schema.Int.check(Schema.isGreaterThan(0)),292 token_type: Schema.String,
2 unmodified lines
295const decodeTokenAnswer = Schema.decodeEffect(296 Schema.fromJsonString(TokenAnswer)297);298394/** Trades `code` for an access token at the platform's `/token`, over `PLATFORM`. */299const exchange = (300 env: Env,301 input: {302 readonly code: string;
42 unmodified lines
345346 return answer;347 });348445/**446 * `GET /auth/callback?code=…&state=…`: the state must be the one this447 * browser's sign-in cookie holds; then the code and its verifier go to the448 * platform's `/token`, and the token comes back only as the session cookie,449 * set to expire before the token does, on a 302 to the way back. The450 * platform's `status`, asked once with the new token through `clientFor`,451 * names the handle kept beside it for as long; a `status` that fails keeps452 * none, and the first `whoami` asks again.453 */349export const callbackHandler =350 (env: Env, clientFor: (request: Request) => Layer.Layer<Client>) =>351 ({ request }: Handled): Promise<Response> =>352 Effect.runPromise(
41 unmodified lines
394 )395 )396 );397503// --- Sign-out, who, and the client -------------------------------------------504505/** `POST` (or a plain link's `GET`) `/auth/signout`: the session and its kept handle end, and the browser goes home. */398export const signOutHandler = (_handled: Handled): Response =>399 redirect("/", clearedCookies());400509/** `/auth/whoami`'s answer: the handle signed in, or nothing (`features/auth/who.ts` reads it). */401const whoAnswer = (402 who: { readonly handle?: Handle },403 cookies: readonly string[] = []404) =>405 Response.json(who, {406 headers: settingCookies({ "cache-control": "no-store" }, cookies),407 });408518/**519 * `GET /auth/whoami`: `{ handle }` for the session, or `{}`, with no520 * platform call when the handle kept beside the session was kept for its521 * token. A session without one (from before handles were kept, or whose522 * kept handle is another token's) asks the platform's `status` once and523 * keeps the handle it names. With no session the platform is not asked,524 * and a handle left over is expired. A session the platform no longer525 * knows answers `Unauthenticated` (the backend asks again with no526 * credential), so both cookies are expired here.527 */409export const whoamiHandler =410 (clientFor: (request: Request) => Layer.Layer<Client>) =>411 ({ request }: Handled): Promise<Response> =>412 Effect.runPromise(
28 unmodified lines
441 ),442 })443 );444564/**565 * The web's OAuth client at `origin`, as a Client ID Metadata Document: a566 * public client (PKCE, no secret) whose id is this document's URL and whose567 * one redirect is the web's callback. The platform reads it when the568 * browser arrives at `/authorize`, so nothing is registered there.569 */445export const webClientMetadata = (origin: string) => ({446 client_id: clientIdOf(origin),447 client_name: `${Brand.name} web`,448 client_uri: origin,
2 unmodified lines
451 response_types: ["code"],452 token_endpoint_auth_method: "none",453});454580/** `GET /auth/client`: the web's Client ID Metadata Document. */455export const clientMetadataHandler = ({ request }: Handled): Response =>456 Response.json(webClientMetadata(new URL(request.url).origin), {457 headers: { "cache-control": "public, max-age=300" },458 });
modified:apps/web/src/server/shiki.ts+2 added-15 removed
1/**2 * `shiki` as the web Worker bundles it (`vite.config.ts` resolves the3 * Worker's `shiki` here): Shiki's core and its JavaScript regex engine,4 * with no bundled grammar or theme and no WebAssembly.5 *6 * The package's own entry maps every grammar and theme to a dynamic7 * import, about 10 MB the Worker's build would carry, and its Oniguruma8 * engine compiles WebAssembly, which a Worker may not. `@pierre/diffs`9 * imports both from `shiki`; it reaches neither on the server, where the10 * few grammars the server highlights in are loaded and attached by11 * `features/code/prerender-server.ts`. So here the bundled maps are empty,12 * and asking for Oniguruma fails.13 */1// `shiki` for the Worker: the package's entry maps every grammar and theme to a dynamic import (about 10 MB),2// and its Oniguruma engine compiles WebAssembly, which a Worker may not. The server attaches its few grammars itself.3import {4 createBundledHighlighter,5 createSingletonShorthands,6 guessEmbeddedLanguages,
8 unmodified lines
15export * from "shiki/core";1617export { createJavaScriptRegexEngine } from "shiki/engine/javascript";1830/** No grammar is bundled by name; each is attached where it is used. */19export const bundledLanguages: Record<20 string,21 DynamicImportLanguageRegistration22> = {};2336/** No theme is bundled by name; the token theme is attached where it is used. */24export const bundledThemes: Record<string, DynamicImportThemeRegistration> = {};2526/** Oniguruma compiles WebAssembly, which a Worker may not: never on the server. */27export const createOnigurumaEngine = (): Promise<RegexEngine> =>
19 unmodified lines
modified:apps/web/src/router.tsx-18 removed
6 unmodified lines
7} from "./features/shared/pending.tsx";8import { routeTree } from "./routeTree.gen.ts";9import { addressRewrite } from "./server/addresses.ts";1011/**12 * TanStack Start's router, over the route tree the Vite plugin generates.13 *14 * - A link (`AppLink`) fetches its page's code and loader data once a15 * pointer rests on it for 50 ms (the router's own delay, stated) or it16 * takes focus, and what it read stays fresh for 30 s, so a click soon17 * after reads nothing again. A page left and come back to within 10 s is18 * drawn from what it read; later, it is drawn so and read again behind19 * it. A page's own reads stay live through its atoms either way.20 * - A page that takes longer than 300 ms to load shows `PendingPage` in the21 * shell; a quicker one never flashes it.22 * - A failed read draws `RouteError` and an address no page serves draws23 * `NotFoundPage`, both inside the shell, never the router's own.24 * - Each new page's main pane (and its inspector) starts at its top; going25 * back returns each to where it was.26 * - A project at its source path (`/github.com/pallets/click`) is read by27 * the same pages as `/oscabriel/datekit` (`addressRewrite`).28 */11export const getRouter = () =>12 createRouter({13 defaultErrorComponent: RouteError,14 defaultNotFoundComponent: NotFoundPage,
17 unmodified lines
modified:apps/web/src/server.ts-8 removed
1/**2 * The web Worker's entry (`wrangler.jsonc`'s `main`): TanStack Start's own3 * server entry, behind the 301s that bring an old or miscased project4 * address to its name's (`canonicalAddress`), with every answer passed5 * through `forTheEdge`, so what the edge's cache may keep is decided in one6 * place for pages, server functions, server routes, redirects and errors7 * alike (ADR 0026).8 */1import handler from "@tanstack/react-start/server-entry";23import { addressedEntry } from "./server/addresses.ts";4import { edgeEntry } from "./server/edge-cache.ts";
2 unmodified lines
modified:apps/web/src/surfaces.ts+3 added-35 removed
1/**2 * The web's projection of the contracts (AGENTS.md principle 4): the only3 * place the web builds one.4 *5 * The data pattern every view follows:6 *7 * - `src/features/<name>/` holds views only: props in, markup out, and no8 * transport import.9 * - `src/client/<name>.ts` holds that feature's atoms over `ContractsClient`,10 * with reactivity keys from `src/client/keys.ts`, so a mutation refetches11 * the reads it changes. Views never import `ContractsClient`.12 * - Route files wire atoms to views.13 * - Server routes that answer agents (Markdown, `llms.txt`) call contracts14 * through `serverClient` (`src/server/client.ts`), never through atoms.15 *16 * The atoms run in the browser, against the same-origin `/rpc`, which17 * `#backend` carries to the platform. A stream the page follows as it18 * happens (`watch`) goes over the framed `/rpc` instead (`framedClient`).19 */1import { surfaced } from "@repo/protocol/contracts";2import { Effect, Layer } from "effect";3import { FetchHttpClient } from "effect/http";4import { Atom, AtomRpc } from "effect/reactivity";5import { RpcClient, RpcSerialization } from "effect/rpc";626/** The contracts whose `Surfaces` annotation includes `web`. */7export const webContracts = surfaced("web");829/**30 * The runtimes the web's atoms run on, over one memo map for every31 * registry, so they share one `Reactivity`: a page's atoms live in a32 * registry of the page's own (`client/seeded.ts`) and the rail's in the33 * root's, and a write or an event heard on the page must refetch the34 * rail's counts too. A layer built for several registries is released35 * when the last of them lets it go.36 */9// One memo map for every registry, so they share one `Reactivity`: a write on a page's own registry10// must refetch the rail's counts in the root's too.11export const sharedRuntime = Atom.context({12 memoMap: Layer.makeMemoMapUnsafe(),13});1441/** The web's contracts as atoms: `ContractsClient.query(tag, payload, options)` and `ContractsClient.mutation(tag)`. */15export class ContractsClient extends AtomRpc.Service<ContractsClient>()(16 "web/ContractsClient",17 {18 group: webContracts,19 runtime: sharedRuntime,47 // JSON, as the platform's `/rpc` serves it.20 protocol: RpcClient.layerProtocolHttp({ url: "/rpc" }).pipe(21 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])22 ),23 }24) {}2554/**55 * The web's contracts over the framed `/rpc` (NDJSON), which the platform56 * answers message by message, so a stream stays open for as long as the57 * page reads it: how a page follows `watch` (`client/watch.ts`).58 */26// NDJSON, which the platform answers message by message, so a stream stays open while the page reads it.27export const framedClient = RpcClient.make(webContracts).pipe(28 Effect.provide(29 RpcClient.layerProtocolHttp({ url: "/rpc" }).pipe(30 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerNdjson])
3 unmodified lines
modified:apps/web/test/agents.test.tsx-11 removed
1/**2 * The For agents page: a reference in five sections (Synopsis, Connect,3 * Endpoints, Limits, Refusals), every word of it from `@repo/agent-kit`,4 * so the page has no text of its own for a snippet, a command or an5 * endpoint (principle 4); `/agents.md` is the same reference as Markdown.6 */1import { describe, expect, it } from "@effect/vitest";2import {3 agentEndpoints,4 agentLimits,
14 unmodified lines
19const webUrl = "https://web-test.example.workers.dev";2021const channels = agentSetup({ commands, platformUrl, webUrl });2229/** The entities React writes for text, and what each reads as. */23const ENTITIES: ReadonlyMap<string, string> = new Map([24 ["&#x27;", "'"],25 ["&amp;", "&"],26 ["&gt;", ">"],
6 unmodified lines
33 /&(?:#x27|amp|gt|lt|quot);/gu,34 (entity) => ENTITIES.get(entity) ?? entity35 );3644/** What a reader sees: the markup without its tags, entities decoded. */37const textOf = (html: string) => decoded(html.replaceAll(/<[^>]+>/gu, ""));3847/** The text of every `<code>` in `html`, in order. */39const codeOf = (html: string) =>40 [...html.matchAll(/<code\b[^>]*>(?<body>.*?)<\/code>/gsu)].map(41 ({ groups: found }) => textOf(found?.body ?? "")42 );4353/** The page at `/agents`, inside a router. */44const page = renderAt(45 "/agents",46 <AgentsView commands={commands} platformUrl={platformUrl} webUrl={webUrl} />47);4859/** The section whose id is `id`: its markup, from its tag to its close. */49const sectionOf = (html: string, id: string) => {50 const start = html.indexOf(`<section aria-labelledby="${id}"`);51 const end = html.indexOf("</section>", start);52
215 unmodified lines
modified:apps/web/test/answer.test.tsx-22 removed
1/**2 * The answer page: the latest verdict on an ask's answer, stage by stage.3 * The gate's stages in a strip, each lane's result and time, held-back4 * checks only as one line per area (its counts and suite root, nothing5 * more), the outcome, and a refusal as `git push` printed it. A landed6 * answer shows its landing's credit trailers and the commit. The base and7 * the landing link their commit pages; the head and the merged tree, which8 * live in the claim's fork, do not.9 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import type { Verdict } from "@repo/protocol/domain/answer";
54 unmodified lines
59const refused = verdictOf(60 Outcome.cases.Refused.make({ refusals: [checksFailed, heldBackFailed] })61);6272/** Each element that names a stage, as `[stage, state]`. */63const stagesOf = (markup: string) =>64 [...markup.matchAll(/<li\b[^>]*>/gu)].flatMap(([tag]) => {65 const stage = /data-stage="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;66 const state = /data-state="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;6768 return stage === undefined || state === undefined ? [] : [[stage, state]];69 });7081/** Each lane, in page order, as `[lane, result]`. */71const lanesOf = (markup: string) =>72 [...markup.matchAll(/<[a-z]+\b[^>]*data-lane="[^"]*"[^>]*>/gu)].flatMap(73 ([tag]) => {74 const lane = /data-lane="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;
2 unmodified lines
77 return lane === undefined || result === undefined ? [] : [[lane, result]];78 }79 );8092/** Each link to a commit page, in page order, as `[href, text]`. */81const commitLinksOf = (markup: string) =>82 [83 ...markup.matchAll(84 /<a\b[^>]*href="(?<href>[^"]*\/commit\/[^"]*)"[^>]*>(?<inner>.*?)<\/a>/gu
3 unmodified lines
88 ? []89 : [[groups.href, plainText(groups.inner).trim()]]90 );91104/** The hero, and the run after it. */92const heroOf = (markup: string) =>93 /<section aria-label="Outcome"[^>]*>(?<inner>.*?)<\/section>/su.exec(markup)94 ?.groups?.inner ?? "";9596const runOf = (markup: string) =>97 markup.slice(markup.indexOf('id="answer-gate"'), markup.indexOf("</main>"));98112/** The page's main pane, without the inspector. */99const mainOf = (markup: string) =>100 /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";101116/** The inspector. */102const asideOf = (markup: string) =>103 /<aside\b[^>]*>(?<inner>.*)<\/aside>/su.exec(markup)?.groups?.inner ?? "";104105const page = (
423 unmodified lines
529 ]);530 });531});532548/** What the stub platform was asked: verdicts, landings, asks and replays. */533interface Asked {534 readonly asks: number;535 readonly landings: number;536 readonly replays: number;537 readonly verdicts: number;538}539556/** Events in datekit: bram claimed the ask and pushed, and another ask was claimed too. */540const replay = [541 claimedEvent(1, "bram"),542 claimedEvent(2, "okafor", AskId.make("format-week")),543 judgedEvent(3, refused.outcome),
1 unmodified line
545546const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>547 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));548566/**567 * A platform whose datekit ask's latest answer ended in `outcome`, as the568 * answer page's loader calls it; `landingKnown` says whether it still finds569 * the landing a landed verdict names.570 */549const platformAt = (550 asked: Ref.Ref<Asked>,551 outcome: Outcome,552 landingKnown = true,
192 unmodified lines
modified:apps/web/test/ask-fixtures.ts-23 removed
1/**2 * datekit's `parse-iso-week` (a fictional ask in a fictional project), and3 * the answers to it, as the platform's contracts return them: the ask and4 * its brief (`showAsk`), a verdict (`verdict`) and a landing (`landing`).5 * Also how the view tests read rendered markup.6 */1import { Brand } from "@repo/brand";2import type { Verdict } from "@repo/protocol/domain/answer";3import type { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec } from "@repo/protocol/domain/check";
23 unmodified lines
28export const project = ProjectName.make("oscabriel/datekit");2930export const askId = AskId.make("parse-iso-week");3138/** The moment every view test renders at. */32export const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");3334export const ask: Ask = {35 askedBy: Handle.make("ines-v"),
22 unmodified lines
58 paths: [Glob.make("packages/parse/**")],59 },60};6169/** The brief as the platform renders it for `showAsk`; the web serves it untouched. */62export const brief = `# Parse ISO week dates like 2026-W41-36364Ask \`parse-iso-week\` in datekit, a \`fix\` ask from ines-v.65
13 unmodified lines
79export const landedSha = LandedSha.make(80 "9b1c3e5d7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c"81);8291/** A verdict on the ask's latest answer: lint passed, unit failed, one held-back area 6 of 7. */83export const verdictOf = (outcome: Outcome): Verdict => ({84 ask: askId,85 at: DateTime.makeUnsafe("2026-10-07T11:40:00Z"),86 base: CommitSha.make(sha("a")),
37 unmodified lines
124 project,125 sha: landedSha,126};127137/** The landing as a decider's finish made it: decided, and judged by held-back checks. */128export const decidedLanding: LandingView = {129 ...landing,130 credits: [131 ...landing.credits,132 { handle: Handle.make("ines-v"), role: "Decided-by" },133 ],134};135146/** The landing as one that needed neither a decider nor held-back checks makes it. */136export const plainLanding: LandingView = {137 ask: askId,138 assisted: [],139 author: Handle.make("bram"),
6 unmodified lines
146 project,147 sha: landedSha,148};149161/** When the events below happened. */150const eventAt = DateTime.makeUnsafe("2026-10-07T11:30:00Z");151164/** `claimant` claimed `on`, as event `seq`. */152export const claimedEvent = (seq: number, claimant: string, on = askId) =>153 ProjectEvent.cases.Claimed.make({154 ask: on,155 at: eventAt,156 claimant: Handle.make(claimant),157 seq,158 });159173/** An answer at `head` to `on` was judged `outcome`, as event `seq`. */160export const judgedEvent = (161 seq: number,162 outcome: Outcome,163 head = CommitSha.make(sha("b")),164 on = askId165) =>166 ProjectEvent.cases.Judged.make({ ask: on, at: eventAt, head, outcome, seq });167182/** An answer to `on` was pushed at `head`, as event `seq`. */168export const pushedEvent = (169 seq: number,170 head = CommitSha.make(sha("b")),171 on = askId172) => ProjectEvent.cases.Pushed.make({ ask: on, at: eventAt, head, seq });173189/** `on` closed by a landing, as event `seq`. */174export const closedEvent = (seq: number, on = askId) =>175 ProjectEvent.cases.AskClosed.make({176 ask: on,177 at: eventAt,
8 unmodified lines
186);187188const familyDelete = AskId.make("retire-old-week-delete");189206/** One member of the family below: blocked by `blockedBy`, its parent named. */190const member = (id: AskId, blockedBy: readonly AskId[]): Ask => ({191 ...ask,192 blockedBy,193 brief: { want: `Step ${id} of retiring oldWeek` },
1 unmodified line
195 kind: KindName.make("migrate"),196 parent: familyParent,197});198216/** A migrate family in datekit: a parent, three children, and the delete child that waits on them. */199export const family = {218 /** The child at `index`, which waits on nothing. */200 child: (index: number) =>201 member(familyChildren[index] ?? AskId.make("retire-old-week-format"), []),202 children: familyChildren,203 deleteChild: {
10 unmodified lines
214 kind: KindName.make("migrate"),215 } satisfies Ask,216};217237/** The entities React writes for text, and what each reads as. */218const ENTITIES: ReadonlyMap<string, string> = new Map([219 ["&#x27;", "'"],220 ["&amp;", "&"],221 ["&gt;", ">"],
3 unmodified lines
225226export const markupOf = (element: ReactElement) =>227 renderToStaticMarkup(element);228249/** What a reader sees of `markup`: the text without its tags, entities decoded. */229export const plainText = (markup: string) =>230 markup231 .replaceAll(/<[^>]+>/gu, " ")232 .replaceAll(
1 unmodified line
234 (entity) => ENTITIES.get(entity) ?? entity235 )236 .replaceAll(/\s+/gu, " ");237259/** What a reader sees of `element`, rendered. */238export const textOf = (element: ReactElement) => plainText(markupOf(element));239262/** Whether each of `parts` appears in `text`, each after the one before. */240export const inOrder = (text: string, parts: readonly string[]) => {241 let from = 0;242243 for (const part of parts) {
11 unmodified lines
modified:apps/web/test/ask-markdown.test.ts-17 removed
1/**2 * An ask answers as Markdown, so a harness reads it with one plain fetch:3 * the ask's URL with `Accept: text/markdown`, or the same URL with `.md`.4 * The body is the brief the platform rendered (`showAsk`), with the banner5 * naming the web's indexes under its title; an unknown ask is a 404 whose6 * body is the refusal, as git would print it.7 * A browser asking for HTML gets the page.8 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import { AskId, ProjectName } from "@repo/protocol/ids";
17 unmodified lines
22import { ask, askId, brief, project } from "./ask-fixtures.ts";2324const WEB = "https://web-test.example.workers.dev";2534/** Where the web's indexes are for datekit's asks, as the routes find them. */26const index = { project, webUrl: WEB };2737/** An ask's Markdown as served: the brief's title, the banner naming the indexes, then the rest of the brief unchanged. */28const [title = "", ...rest] = brief.split("\n");2930const served = [title, "", indexBanner(index), ...rest].join("\n");31
1 unmodified line
3334const BROWSER =35 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";3647/**48 * A platform that knows datekit and its one ask, counting `showAsk` calls,49 * as a route's client.50 */37const platformOf = (calls: Ref.Ref<number>) => () =>38 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(39 Layer.provide([40 Layer.mergeAll(
17 unmodified lines
58 asTester,59 ])60 );6176/** A platform that cannot be reached: every call dies on the way. */62const unreachable = () =>63 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(64 Layer.provide([unanswered, asTester])65 );
7 unmodified lines
73 ask: askName,74 project: projectName,75});7692/** What a response says, read whole. */77const read = (response: Response) =>78 Effect.map(79 Effect.promise(() => response.text()),80 (body) => ({
4 unmodified lines
85 vary: response.headers.get("vary"),86 })87 );88105/** The page's own render, which a Markdown request must never reach. */89const PAGE = new Response("<!doctype html><title>the page</title>");9091describe("an ask's URL with Accept: text/markdown", () => {92 it.effect(
286 unmodified lines
modified:apps/web/test/ask.test.tsx-18 removed
1/**2 * The ask page, as a person reads it: the brief (want, current behaviour,3 * out of scope, terms, context), its kind, territory, check and state, who4 * asked, its parent and blockers, and the exact lines that clone, claim and5 * check it. Rendered to HTML with `react-dom/server`.6 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import type { Ask } from "@repo/protocol/domain/ask";
43 unmodified lines
48import { textIn } from "./markup.ts";4950const platformUrl = "https://platform-test.example.workers.dev";5158/** The markup inside the first `<pre>`. */52const inPre = (markup: string) =>53 /<pre\b[^>]*>(?<inner>.*?)<\/pre>/su.exec(markup)?.groups?.inner;5462/** The page's main pane, without the inspector. */55const mainOf = (markup: string) =>56 /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";5766/** The inspector. */58const asideOf = (markup: string) =>59 /<aside\b[^>]*>(?<inner>.*)<\/aside>/su.exec(markup)?.groups?.inner ?? "";6070/** The context bar's trail. */61const trailOf = (markup: string) =>62 /<nav aria-label="Breadcrumb"[^>]*>(?<inner>.*?)<\/nav>/su.exec(markup)63 ?.groups?.inner ?? "";64
8 unmodified lines
73 {...more}74 />75);7687/** The check's source, as the platform reads it. */77const checkSource = (lines: number) => ({78 path: RepoPath.make("test/parse-week.test.ts"),79 sha: "f".repeat(40),80 text: Array.from(
400 unmodified lines
481 ).toContain("No answer is at this head.");482 });483});484496/** What the stub platform was asked. */485interface Asked {486 readonly asks: number;487 readonly files: number;488 readonly replays: number;
4 unmodified lines
493494const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>495 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));496509/** Events in datekit: tamsin claimed the ask, and another ask was claimed too. */497const replay = [498 claimedEvent(1, "tamsin"),499 claimedEvent(2, "okafor", AskId.make("format-week")),500];501515/**516 * A platform that knows datekit's ask (`shown`, under its id) and the517 * family parent, its events, no verdict yet, and the check's file when518 * `readable`.519 */502const platformOf = (503 asked: Ref.Ref<Asked>,504 {505 readable = true,
158 unmodified lines
modified:apps/web/test/cache-headers.test.ts-6 removed
1/**2 * How long a browser may keep a page, by what the page is addressed by: a3 * page at `main`, a tag or a commit changes with the next landing (a4 * commit's page carries its landing), and a page about the person reading5 * it is theirs alone. A route gives one of these as its `headers`.6 */1import { describe, expect, it } from "@effect/vitest";23import * as CacheHeaders from "../src/server/cache-headers.ts";4import { branchPage, personalPage } from "../src/server/cache-headers.ts";
22 unmodified lines
modified:apps/web/test/client-ask.test.ts-4 removed
1/**2 * An ask's reads, as the web's atoms make them.3 * Over the dev world in process (`dev-browser.ts`).4 */1import { describe, expect, it } from "@effect/vitest";2import { AskId } from "@repo/protocol/ids";3import { UnknownAsk } from "@repo/protocol/refusal";4import { Effect, Exit, Option, Schema } from "effect";
29 unmodified lines
modified:apps/web/test/client-front.test.ts-5 removed
1/**2 * The front page's reads, as the web's atoms make them: every open ask3 * of every project.4 * Over the dev world in process (`dev-browser.ts`).5 */1import { describe, expect, it } from "@effect/vitest";2import { Effect, Exit } from "effect";34import { keys } from "../src/client/keys.ts";
51 unmodified lines
modified:apps/web/test/client-project.test.ts-5 removed
1/**2 * A project page's reads, as the web's atoms make them: its open asks,3 * and its events, replayed and folded.4 * Over the dev world in process (`dev-browser.ts`).5 */1import { describe, expect, it } from "@effect/vitest";2import { ProjectName } from "@repo/protocol/ids";3import { Effect, Exit } from "effect";4
77 unmodified lines
modified:apps/web/test/client-session.test.ts-5 removed
1/**2 * Who a browser is: the session cookie `/auth/dev` sets names the person3 * whoami answers with.4 * Over the dev world in process (`dev-browser.ts`).5 */1import { describe, expect, it } from "@effect/vitest";2import { env } from "cloudflare:workers";3import { Effect } from "effect";4
25 unmodified lines
modified:apps/web/test/client-today.test.ts-8 removed
1/**2 * Today's reads and a decider's writes, as the web's atoms make them: kept3 * from an anonymous browser, a decider's own, and refetched once a decision4 * is taken.5 * Over the dev world in process (`dev-browser.ts`).6 */1import { describe, expect, it } from "@effect/vitest";2import { DecisionSubject } from "@repo/protocol/domain/decision";3import { Unauthenticated } from "@repo/protocol/principal";4import { Array, DateTime, Effect, Exit, Option, Schema } from "effect";
94 unmodified lines
99 ? decided.value.decision.decided100 : undefined;101102 expect(taken?.choice).toBe("decline");109 // The world serves at the instant its seed left the clock.103 expect(104 taken === undefined ? undefined : DateTime.formatIso(taken.at)105 ).toBe("2026-10-07T09:21:00.000Z");106114 /** Whether Today, in `where`, still holds the decision, and the budget it has used. */107 const todayIn = (where: typeof registry) =>108 Effect.map(settled(where, todayAtom), (today) =>109 Exit.isSuccess(today)110 ? {
21 unmodified lines
modified:apps/web/test/code-client.test.tsx+1 added-22 removed
1/**2 * The code browser's client-only drawings, rendered directly (as3 * `finish.test.tsx` renders `patch-diff.tsx`): a file is drawn by4 * `@pierre/diffs` (`<diffs-container>`), a commit's diff by its `CodeView`5 * (which draws nothing until it mounts, so its server markup is its6 * marked host alone; `code.test.tsx` holds the plain text it replaces), and7 * the repo's file tree by `@pierre/trees` (`<file-tree-container>`). The8 * pages import these only through a dynamic import the Worker's build9 * drops, so the Worker never bundles them (the server's own highlighting10 * is `code-prerender.test.tsx`'s).11 *12 * The tree moves the page through the router: choosing a file calls the13 * page's own `onOpen`, never `location.assign`, so the document stays.14 */1import { describe, expect, it } from "@effect/vitest";2import { FileTree } from "@pierre/trees";3import { ChangedFile } from "@repo/protocol/domain/code";4import { Schema } from "effect";
53 unmodified lines
58 });5960 it("draw the repo's file tree with @pierre/trees", () => {61 const markup = renderToStaticMarkup(76 <RepoTree77 current="src/parse.ts"78 onOpen={() => {79 // Nothing is chosen in a server render.80 }}81 paths={PATHS}82 />62 <RepoTree current="src/parse.ts" onOpen={() => {}} paths={PATHS} />63 );6465 expect(markup).toContain("<file-tree-container");66 });67});6889/** A tree over `PATHS` showing `current`, and the files it asked the page to open. */69const treeAt = (current: string) => {70 const opened: string[] = [];71 const tree = new FileTree(treeOptionsFor({ current, paths: PATHS }));72
71 unmodified lines
modified:apps/web/test/code-diff.test.ts-8 removed
1/**2 * A commit's diff as the server sends it and the browser draws it: both3 * parse a file's two texts with the drawing's own parser, so the plain4 * text holds the drawing's hunks line for line; a file's counts, which5 * files start folded, the order a tree lists paths in, the stats split by6 * the ask's territory, and the keys that move between files.7 */1import { describe, expect, it } from "@effect/vitest";2import { ChangedFile } from "@repo/protocol/domain/code";3import { Option, Schema } from "effect";4
12 unmodified lines
17import { stepFrom } from "../src/features/code/file-keys.ts";1819const decode = Schema.decodeSync(ChangedFile);2028/** Lines `from` to `to`, as a file's text. */21const lines = (from: number, to: number) =>22 `${Array.from(23 { length: to - from + 1 },24 (_, index) => `line ${from + index}`
199 unmodified lines
modified:apps/web/test/code-prerender.test.tsx-21 removed
1/**2 * Code the server sends highlighted (ADR 0027): a blob page's file and a3 * commit page's first files, drawn by `@pierre/diffs/ssr` into a4 * declarative shadow root, in a fixed set of languages and within the5 * server's own limit; anything else is sent as plain text, as before.6 *7 * Each page is rendered as its route renders it on the server: the loader8 * draws the code ahead (`drawFileAhead`, `drawDiffAhead`), then the page9 * renders with the browser's drawing (`ClientFile`, `ClientDiffs`) holding10 * the server's fallback, which is all a server render shows.11 */1import { describe, expect, it } from "@effect/vitest";2import { ChangedFile, CommitDiff, FileView } from "@repo/protocol/domain/code";3import { ProjectName } from "@repo/protocol/ids";4import { DateTime, Effect, Schema } from "effect";
24 unmodified lines
29const decodeFile = Schema.decodeSync(FileView);3031const decodeFiles = Schema.decodeSync(Schema.Array(ChangedFile));3244/** A highlighted token, as Pierre draws one in the token theme. */33const TOKEN = /--diffs-token-light:var\(--diffs-token-[a-z-]+/gu;3447/** How many highlighted tokens `markup` holds. */35const tokensIn = (markup: string) => [...markup.matchAll(TOKEN)].length;3650/** How many server drawings `markup` holds. */37const shadowRootsIn = (markup: string) =>38 [...markup.matchAll(/<template shadowrootmode="open">/gu)].length;3940const TYPESCRIPT = [
3 unmodified lines
44 "export const parse = (text: string): Date => fromIso(text);",45 "",46].join("\n");4762/** `count` lines of TypeScript. */48const linesOf = (count: number) =>49 Array.from(50 { length: count },51 (_, index) => `export const n${index} = ${index};`52 ).join("\n");5354let blobs = 0;5571/** A file at `path`, with a blob id of its own, so no drawing is shared. */56const fileAt = (path: string, text: string) => {57 blobs += 1;5859 return decodeFile({
6 unmodified lines
66 truncated: false,67 });68};6986/** The blob page's markup for `file`, as the server renders it once its loader has drawn the file. */70const blobPage = (file: FileView) =>71 Effect.gen(function* () {72 yield* Effect.promise(() => drawFileAhead(file));73
24 unmodified lines
98 email: "lin@example.com",99 name: "Lin",100};101119/** A commit changing `files`, imported (no landing). */102const commitOf = (files: readonly (typeof ChangedFile.Encoded)[]) =>103 Schema.decodeSync(CommitDiff)({104 commit: {105 author: signature,
8 unmodified lines
114 files,115 truncated: false,116 });117136/** The commit page's markup, as the server renders it once its loader has drawn the first files. */118const commitPage = (diff: CommitDiff) =>119 Effect.gen(function* () {120 const drawn = drawnFiles(diff.files);121
21 unmodified lines
143 />144 );145 });146166/** The markup of one file's section of a diff. */147const sectionOf = (markup: string, path: string) =>148 new RegExp(149 `<section aria-label="${path.replaceAll(".", "\\.")}"[\\s\\S]*?</section>`,150 "u"151 ).exec(markup)?.[0] ?? "";152173/** An added file at `path`, `lines` long, with a blob id of its own. */153const added = (path: string, lines: number) => {154 blobs += 1;155156 return {
192 unmodified lines
modified:apps/web/test/code.test.tsx+2 added-46 removed
1/**2 * The code browser's pages, rendered to HTML with `react-dom/server` from3 * fixtures decoded with the protocol's own schemas: a folder (`TreeView`), a4 * file (`BlobView`), the landings (`LogView`), one commit (`CommitView`), a5 * missing path's soft landing; the refs page has its own test6 * (`refs.test.tsx`). Each is what the server sends before the browser7 * loads Pierre: the tree and the8 * highlighted code are client-only, so none of these pages carries a9 * `<file-tree-container` or a `<diffs-container`; a commit's diff arrives as10 * plain text at the drawing's measures.11 */1import { describe, expect, it } from "@effect/vitest";2import { Client, Contracts } from "@repo/protocol/contracts";3import type { Contract } from "@repo/protocol/contracts";4import {
51 unmodified lines
56import { reachingTransport } from "./transport.ts";5758const markupOf = (element: ReactElement) => renderToStaticMarkup(element);5971/** What a reader sees: the markup without its tags, entities decoded. */60const textOf = (element: ReactElement) =>61 markupOf(element)62 .replaceAll(/<[^>]+>/gu, " ")63 .replaceAll("&#x27;", "'")
2 unmodified lines
66 .replaceAll("&gt;", ">")67 .replaceAll("&amp;", "&")68 .replaceAll(/\s+/gu, " ");6982/** Every `href` in `markup`, in order, entities decoded. */70const hrefsOf = (markup: string) =>71 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map((match) =>72 (match.groups?.href ?? "").replaceAll("&amp;", "&")73 );7488/** The markup from the element marked `marker` to the next element marked the same way. */75const slice = (markup: string, marker: string, value: string) => {76 const start = markup.indexOf(`${marker}="${value}"`);77 const next = markup.indexOf(`${marker}="`, start + 1);78
1 unmodified line
80 ? ""81 : markup.slice(start, next === -1 ? undefined : next);82};8398/** The `<nav>` marked `attribute` (`data-slot="breadcrumb"`), whole. */84const navOf = (markup: string, attribute: string) =>85 new RegExp(`<nav\\b[^>]*${attribute}[^>]*>[\\s\\S]*?</nav>`, "u").exec(86 markup87 )?.[0] ?? "";
52 unmodified lines
140 ],141 path: "src/format/locale",142});143159/** A tag with a slash and an at sign: one URL-encoded segment. */144const TAG = "@datekit/core@1.0.0";145146const TAG_SEGMENT = "%40datekit%2Fcore%401.0.0";147
142 unmodified lines
290 ],291 truncated: false,292});293310/** The markup of `<main>` alone: the page, without its inspector. */294const mainOf = (markup: string) =>295 /<main\b[\s\S]*?<\/main>/u.exec(markup)?.[0] ?? "";296314/** The markup of the inspector alone. */297const inspectorOf = (markup: string) =>298 /<aside\b[^>]*data-facts="inspector"[\s\S]*?<\/aside>/u.exec(markup)?.[0] ??299 "";300319/** How many times `part` appears in `text`. */301const countIn = (text: string, part: string) => text.split(part).length - 1;302322/** The `<a …>` that reads `label`, in `markup`. */303const anchorOf = (markup: string, label: string) =>304 new RegExp(`<a\\b[^>]*>${label}</a>`, "u").exec(markup)?.[0];305306describe(TreeView, () => {
95 unmodified lines
402 })403 );404});405426/** Where a file's facts link their permalink, on the page of `mode`. */406const permalink = (mode: "code" | "why") =>407 /href="(?<href>[^"]*)"[^>]*>Permalink</u.exec(408 markupOf(409 <FileFacts
91 unmodified lines
501502 it("names the path once in the page, in its file header", () => {503 const main = mainOf(markupOf(page));504526 // The trail's segments, read as text, spell the path: once.505 expect(506 countIn(main.replaceAll(/<[^>]+>/gu, ""), "src/format/parse.ts")507 ).toBe(1);508 expect(countIn(main, 'title="src/format/parse.ts"')).toBe(1);
385 unmodified lines
894 ]);895 });896});897920/** Lines `1` to `count`, as a file's text. */898const linesUpTo = (count: number) =>899 `${Array.from({ length: count }, (_, index) => `line ${index + 1}`).join(900 "\n"901 )}\n`;902926/** `diff`, with an added file of 120 lines: long enough to start folded. */903const long = decodeDiff({904 ...Schema.encodeSync(CommitDiff)(diff),905 files: [906 ...Schema.encodeSync(CommitDiff)(diff).files,
223 unmodified lines
1130 expect(textOf(page)).not.toContain("too large to show whole");1131 });1132});11331158/** A payload the platform was sent: one of the contracts'. */1134type Sent = Rpc.Payload<Contract>;11351161/** Datekit, or the refusal for any other project. */1136const knownProject = (name: ProjectName) =>1137 name === datekit1138 ? Effect.void1139 : Effect.fail(new UnknownProject({ project: name }));11401167/** Main, or its commit `AT`, or the refusal for any other revision. */1141const knownRevision = (at: string | undefined) =>1142 at === undefined || at === "main" || at === AT1143 ? Effect.void1144 : Effect.fail(new UnknownRevision({ rev: at }));11451173/** Datekit's refs with main landed and no tags or forks. */1146const landedOnly = Schema.decodeSync(Refs)({1147 forks: [],1148 landed: LANDED,1149 project: "datekit",1150 tags: [],1151});11521181/** The refusal for a path datekit lacks at `AT`. */1153const noPath = (path: RepoPath) =>1154 new UnknownPath({ commit: CommitSha.make(AT), path });11551185/**1186 * A platform that holds datekit at main (commit `AT`): its root (with a1187 * README), the folder `src/format/locale`, the README, a page of the log1188 * and one commit. Every payload it is sent is kept, in order.1189 */1156const platformOf = (calls: Ref.Ref<readonly Sent[]>) => {1157 const sent = (payload: Sent) => Ref.update(calls, (all) => [...all, payload]);11581159 return Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(
64 unmodified lines
1224 ])1225 );1226};12271262/** What a page's read that ended in a not-found asked and carried. */1228interface Refused {1264 /** Every payload it sent the platform. */1229 readonly calls: readonly Sent[];1266 /** The refusals its not-found carried, as `git` prints them; none when it carried none. */1230 readonly refused: Option.Option<readonly string[]>;1231}12321270/** Runs a page's read against `platformOf`, which must end in a not-found. */1233const refusedBy = <A, E>(1234 read: Effect.Effect<A, E, Client>1235): Effect.Effect<Refused> =>1236 Effect.gen(function* () {
6 unmodified lines
1243 expect(isNotFound(failed)).toBeTruthy();12441245 const data: unknown = isNotFound(failed) ? failed.data : undefined;12461285 // A missing path lands on its nearest folder, its refusal beside it.1247 const carried = Option.orElse(1248 Schema.decodeUnknownOption(Refusals)(data),1249 () =>1250 Option.map(
154 unmodified lines
1405 })1406 );1407});14081448/** The soft landing a page's read ended in. */1409const landingOf = <A, E>(read: Effect.Effect<A, E, Client>) =>1410 Effect.gen(function* () {1411 const calls = yield* Ref.make<readonly Sent[]>([]);1412
118 unmodified lines
1531 expect(hrefsOf(markupOf(element))).toContain("/asks");1532 });1533});15341575/** The line every code page's route answers its headers with. */1535const HEADERS_LINE = "headers: () => branchPage";15361537describe("a code page's caching", () => {1579 // A commit never changes, but its page is more than the commit: it1580 // carries the commit's landing, which the project records only after1581 // main has moved (a read between the two finds none), and words such as1582 // "2 minutes ago", reckoned from when it was read. Kept for good, such a1583 // page would never show the landing, and its times would never move.1538 // A commit's page carries its landing, recorded after main has moved, and times reckoned from the read,1539 // so it is never kept for good.1540 const routes: Readonly<Record<string, string>> = import.meta.glob(1541 "../src/routes/$owner/$project/{tree,blob,why}/$rev/$.tsx",1542 { eager: true, import: "default", query: "?raw" }1543 );
32 unmodified lines
modified:apps/web/test/credits.test.tsx-6 removed
1/**2 * A landing's credit, as the commit carries it: the trailers in the order3 * of their roles, each person linked, the held-back commitment on its own4 * line and the agents apart; and its one-line form for a row, which names5 * the people by role and never the agents.6 */1import { describe, expect, it } from "@effect/vitest";2import { Handle } from "@repo/protocol/ids";3import { Schema } from "effect";4
112 unmodified lines
modified:apps/web/test/decision.test.tsx-25 removed
1/**2 * Deciding from Today: the `decide` atom sends the decider's choice as the3 * contract's payload, and on success reads Today and the project again, so4 * the decision leaves the list and the project shows what it changed. A5 * decision someone else closed first comes back as the `DecisionClosed`6 * refusal, shown as such, and Today reads again without it.7 *8 * The atoms run in an `AtomRegistry` whose `ContractsClient` is the protocol's9 * own client over in-process handlers that record each call (`RpcTest`); no10 * HTTP and no platform.11 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Contracts } from "@repo/protocol/contracts";4import { RefNameText } from "@repo/protocol/domain/common";
45 unmodified lines
50import { ContractsClient, webContracts } from "../src/surfaces.ts";5152const markupOf = (element: ReactElement) => renderToStaticMarkup(element);5365/** What a reader sees of `markup`: the text without its tags. */54const plainTextOf = (markup: string) =>55 markup56 .replaceAll(/<[^>]+>/gu, " ")57 .replaceAll("&#x27;", "'")58 .replaceAll("&quot;", '"')59 .replaceAll("&amp;", "&")60 .replaceAll(/\s+/gu, " ");6174/** Today as the page reads it from the atom: listed, or why not. */62const readOf = (result: AsyncResult.AsyncResult<Today, unknown>): TodayRead => {63 if (AsyncResult.isSuccess(result)) {64 return TodayRead.cases.Read.make({ today: result.value });65 }
33 unmodified lines
99 overflow: 0,100 unattended: [],101});102116/** What the platform was asked, call by call. */103interface Asked {104 readonly decide: readonly unknown[];105 readonly listAsks: number;106 readonly today: number;
5 unmodified lines
112 { readonly decision: Decision },113 DecisionClosed | UnknownDecision114>;115130/**131 * The web's `ContractsClient`, answered in process: `today` answers the132 * stray push until a decision is taken and nothing after, `listAsks` answers133 * an empty list, and `decide` answers `answer`. Each call is recorded.134 */116const contracts = (asked: Ref.Ref<Asked>, answer: Decide) => {117 const decided = Ref.makeUnsafe(false);118119 const handlers = Layer.mergeAll(
27 unmodified lines
147 Layer.provideMerge(Reactivity.layer)148 );149};150170/** A registry whose atoms reach `contracts` instead of `/rpc`. */151const registryOver = (152 layer: Layer.Layer<ContractsClient | Reactivity.Reactivity>153) =>154 Effect.acquireRelease(
15 unmodified lines
170 { project: datekit },171 { reactivityKeys: keys.project(datekit) }172);173194/** Today and a read of the project, both on screen, read once; then `input` decided. */174const decideOnce = (175 answer: Decide,176 input: {177 readonly choice: Choice;
126 unmodified lines
304 })305 );306});307329/** The Accept button's opening tag. */308const acceptOf = (markup: string) =>309 /<button[^>]*data-choice="accept"[^>]*>/u.exec(markup)?.[0] ?? "";310311describe("DecisionCard for an OpenProposal", () => {
28 unmodified lines
340 onDecide={() => {}}341 />342 );343366 /** `showProposal`'s answer for the proposal, its draft at `draft`. */344 const shown = (draft?: DraftState) => {345 const wanted = {346 expiresAt: opening.expiresAt,347 files: [],
10 unmodified lines
358 proposal: draft === undefined ? wanted : { ...wanted, draft },359 };360 };361385 /** The card once the browser's read of the proposal answered with `draft`. */362 const cardRead = (draft?: DraftState) =>363 markupOf(364 <DecisionCard365 decision={opening}
128 unmodified lines
494});495496const vellum = ProjectName.make("oscabriel/vellum");497522/** A waiver on the answer to escape-attribute-quotes, carrying the answer's diff of the marker's file. */498const waiver: Decision = {499 deciders: [okonkwo],500 default: "decline",501 evidence: [
170 unmodified lines
modified:apps/web/test/design-rules.test.tsx-9 removed
1/**2 * DESIGN.md's named values, held against the components that draw them:3 * the inspector's widths (its `spacing` tokens) and the row's state word4 * (the Mark Carries Rule), and a path's file name read before its5 * folders. A change to either side without the other6 * fails here, so the document and the web never drift apart.7 */1import { describe, expect, it } from "@effect/vitest";2import { ProjectName } from "@repo/protocol/ids";3import { Effect } from "effect";4import { renderToStaticMarkup } from "react-dom/server";
7 unmodified lines
12import { wordTone } from "../src/features/shared/row.tsx";13import { Workspace } from "../src/features/shared/shell/workspace.tsx";14import { renderAt } from "./render.tsx";1523/** A `spacing` token's value in DESIGN.md's frontmatter. */16const spacing = (name: string) =>17 new RegExp(`^ {2}${name}: "(?<value>[^"]+)"$`, "mu").exec(design)?.groups18 ?.value;1928/** The inspector's class list, as a page with facts draws it. */20const inspectorClasses = (code: boolean) => {21 const markup = renderToStaticMarkup(22 <Workspace23 crumbs={[{ label: "Ledger" }]}
78 unmodified lines
modified:apps/web/test/dev-backend.test.ts+1 added-26 removed
1/**2 * The dev world's seed, read back through the contracts a fresh world3 * serves: the same world every time, every time it holds counted in whole4 * minutes from one fixed start (so a page looks the same on every machine5 * and every run), and an answer that landed with its credit.6 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import { ProjectEvent } from "@repo/protocol/domain/event";
23 unmodified lines
28const decider = devToken(Handle.make("ines-v"));2930const contributor = devToken(Handle.make("bram"));3138/**39 * A fresh world, seeded and served, and `read` run against it: each40 * `as(token)` is a client whose requests carry that bearer, or none.41 */32const inFreshWorld = <A, E>(33 read: (34 as: (token?: string) => Layer.Layer<Client>35 ) => Effect.Effect<A, E, Scope.Scope>
27 unmodified lines
63 return yield* read(as);64 })65 );6677/** The client a layer from `as(token)` makes, for as long as the world lives. */67const clientOf = (layer: Layer.Layer<Client>) =>68 Effect.map(Layer.build(layer), Context.get(Client));6981/** The front page and the project list, as anyone reads them. */70const pages = inFreshWorld((as) =>71 Effect.gen(function* () {72 const anyone = yield* clientOf(as());73 const { entries } = yield* anyone.frontPage({});
2 unmodified lines
76 return { entries, projects };77 })78);7992/** Every instant a reader of the seeded world can see. */80const instants = inFreshWorld((as) =>81 Effect.gen(function* () {82 const anyone = yield* clientOf(as());83 const ines = yield* clientOf(as(decider));
28 unmodified lines
112 ];113 })114);115129/** datekit's landed answer, as Today samples it and as `landing` reads it. */116const landedAnswer = inFreshWorld((as) =>117 Effect.gen(function* () {118 const anyone = yield* clientOf(as());119 const ines = yield* clientOf(as(decider));
12 unmodified lines
132 return { landing, sampled };133 })134);135150/** The project list beside datekit's landed answer, as anyone reads them. */136const listedWithLanding = inFreshWorld((as) =>137 Effect.gen(function* () {138 const anyone = yield* clientOf(as());139 const ines = yield* clientOf(as(decider));
18 unmodified lines
158 };159 })160);161177/** The project list beside each project's ledger, as anyone reads them. */162const listedWithLedgers = inFreshWorld((as) =>163 Effect.gen(function* () {164 const anyone = yield* clientOf(as());165 const { projects } = yield* anyone.listProjects({});
5 unmodified lines
171 return { ledgers, projects };172 })173);174191/**192 * Each test seeds whole worlds, the first one cold, while turbo runs every193 * package's tests at once: about 0.5 s alone, near vitest's 5 s default194 * under that load once burrow's migrate opens as a family of eight asks.195 */175// Each test seeds whole worlds while turbo runs every package's tests at once: near vitest's 5 s default.176const seededWorlds = { timeout: 30_000 };177178describe("the dev seed", seededWorlds, () => {179 it.live("gives two fresh worlds equal front pages and project lists", () =>
111 unmodified lines
291 })292 );293});294315/** Each of `paths` on a fresh world's own handler: its status, headers and body. */295const fetched = (paths: readonly string[]) =>296 Effect.scoped(297 Effect.gen(function* () {298 const { dispose, handler } = devServer();
39 unmodified lines
338 })339 );340});341363/**364 * bram proposes a want for datekit with a draft, and what follows: the365 * proposal as anyone reads it, and ines-v's Today before and after.366 */342const drafted = inFreshWorld((as) =>343 Effect.gen(function* () {344 const anyone = yield* clientOf(as());345 const ines = yield* clientOf(as(decider));
52 unmodified lines
modified:apps/web/test/dev-browser.ts+3 added-23 removed
1/**2 * The web's contracts as its atoms read them, with `#backend` under the3 * `development` condition: the same `ContractsClient` group, the same4 * reactivity keys and the same `/rpc` path, answered by the dev world in5 * process instead of a platform. Each registry stands for one browser: its6 * client's requests carry that browser's session cookie, or none, which7 * the backend turns into the bearer the dev world reads.8 *9 * Each `client-*.test.ts` file reads the one world its module's `backend`10 * seeds, in order; within a file, only the last test changes it.11 */1// Each `client-*.test.ts` file reads the one world its module's `backend` seeds, in order;2// within a file, only the last test changes it.3import { ProjectName } from "@repo/protocol/ids";4import { env } from "cloudflare:workers";5import { Effect, Layer } from "effect";6import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
9 unmodified lines
16export const WEB_URL = "http://localhost:3000";1718export const datekit = ProjectName.make("oscabriel/datekit");1929/** The decider of datekit in the dev world, and the token that signs them in. */20export const DECIDER = "dev-ines-v";2132/**33 * `ContractsClient` as one browser runs it: its HTTP protocol posts to the34 * web's `/rpc`, which hands the request to `backend` in process, with35 * `token` in the session cookie when there is one.36 */22const browser = (token?: string) =>23 Layer.effect(24 ContractsClient,25 RpcClient.make(webContracts, { flatten: true })
20 unmodified lines
46 ),47 Layer.provideMerge(Reactivity.layer)48 );4965/** A registry whose `ContractsClient` is `browser(token)`'s. */50export const registryAs = (token?: string) =>51 AtomRegistry.make({52 initialValues: [53 Atom.initialValue(ContractsClient.runtime.layer, browser(token)),54 ],55 });5673/** An atom's value once it has one, past any refetch under way. */57export const settled = <A, E>(58 registry: AtomRegistry.AtomRegistry,59 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>60) =>61 Effect.exit(62 AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true })63 );6482/**83 * The first test of a file waits for its world to be seeded, cold, while84 * turbo runs every package's tests at once (near vitest's 5 s default).85 */65// Cold seeding while turbo runs every package's tests at once comes near vitest's 5 s default.66export const seededWorld = { timeout: 30_000 };
modified:apps/web/test/dev-client.ts-4 removed
1/**2 * A `Client` of a fresh dev world with its fixtures, as a route's loader3 * calls the platform on the server: signed in as `handle`, or as nobody.4 */1import { Client, Contracts } from "@repo/protocol/contracts";2import { Handle } from "@repo/protocol/ids";3import { Effect, Layer } from "effect";4import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
35 unmodified lines
modified:apps/web/test/dev-fixtures.test.ts+3 added-38 removed
1/**2 * The dev world with its fixtures switched on: every state a page draws,3 * served through the contracts the pages call, beside datekit and burrow.4 * Each case reads a fresh world the way a browser would, over `/rpc`.5 */1import { describe, expect, it } from "@effect/vitest";2import { Client, Contracts } from "@repo/protocol/contracts";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import type { Decision } from "@repo/protocol/domain/decision";
25 unmodified lines
30const ask = (id: string) => AskId.make(id);3132const signedIn = (handle: string) => devToken(Handle.make(handle));3339/** A client of `handler`'s `/rpc`, whose calls carry `token` as their bearer when there is one. */34const connect = (35 handler: (request: Request) => Promise<Response>,36 token?: string37) =>
22 unmodified lines
60 );6162type Reader = Effect.Success<ReturnType<typeof connect>>;6370/** A fresh world with `options`, served, and `read` run against it. */64const inWorld = <A, E>(65 options: DevWorldOptions,66 read: (67 as: (token?: string) => Effect.Effect<Reader, never, Scope.Scope>
10 unmodified lines
78 );7980const withFixtures: DevWorldOptions = { fixtures: "on" };8189/** vellum's events, as `watch` replays them from the first. */82const eventsOf = (client: Reader) =>83 Effect.map(84 Stream.runCollect(client.watch({ project: vellum })),85 (events): readonly ProjectEvent[] => events86 );8796/** The `AskClosed` events among `events`. */88const closedIn = (events: readonly ProjectEvent[]) =>89 events.filter(ProjectEvent.guards.AskClosed);90100/** The tag of each answer state's verdict outcome, by ask. */91const ANSWERS = {92 "carry-footnotes-to-epub": "Landed",93 "cli-version-flag": "Landed",94 "escape-attribute-quotes": "AwaitingDecision",
38 unmodified lines
133 };134 })135);136147/** Each refusal of a refused outcome, as its tag and the place it points at. */137const refusalsOf = (outcome: Outcome | undefined) =>138 outcome !== undefined && Outcome.guards.Refused(outcome)139 ? outcome.refusals140 : [];141153/**154 * Each hunk of a unified diff, as its header declares its old and new155 * lengths and as its lines count them, so a patch a diff view cannot parse156 * shows as a mismatch.157 */142const hunksOf = (patch: string) => {143 const hunks: { declared: string; counted: string }[] = [];144 let old = 0;145 let fresh = 0;
27 unmodified lines
173174 return hunks;175};176193/**194 * Each test seeds a whole world with its fixtures while turbo runs every195 * package's tests at once, as `dev-backend.test.ts` does.196 */177// Each test seeds a whole world while turbo runs every package's tests at once.178const seededWorlds = { timeout: 30_000 };179180describe("the dev world's fixtures", seededWorlds, () => {181 it.live(
527 unmodified lines
709 )710 );711});712732/** `at`'s distance from `from`, in milliseconds. */713const millisFrom = (from: DateTime.DateTime, at: DateTime.DateTime) =>714 Duration.toMillis(DateTime.distance(from, at));715736/**737 * The open decisions ines-v takes across her projects, and two instants738 * the world stamps on what it makes, a little apart: its present then.739 */716const timesIn = (options: DevWorldOptions) =>717 inWorld(options, (as) =>718 Effect.gen(function* () {719 const ines = yield* as(signedIn("ines-v"));
19 unmodified lines
739 return { decisions, first, overflow, second };740 })741 );742767/** A decision, keyed as the platform counts it: its id within its project. */743const keyOf = ({ id, project }: Decision) => `${project}/${id}`;744770/**771 * A fixed world stands at the calendar's `end` once seeded; a world at772 * the present has every instant moved by one whole number of minutes, so773 * `end` is the minute it was built in, and its clock runs on from there,774 * with every decision still to come.775 *776 * Today lists as many decisions as the day's budget allows, and the budget777 * counts a UTC day: which of the story's taken decisions fall on the778 * present day moves with the time of day the world is built at. So the779 * two worlds are held to the same open count, listed and overflowing780 * together, and the decisions both list are held to the one shift.781 */745// Today's budget counts a UTC day, so which taken decisions fall on the present day moves with the time of day746// the world is built at: the two worlds are held to the same open count, and shared decisions to one shift.747const placedAtThePresent = (fixtures: FixtureMode, end: DateTime.Utc) =>748 Effect.gen(function* () {749 const fixed = yield* timesIn({ fixtures });750
98 unmodified lines
modified:apps/web/test/docs.test.tsx-7 removed
1/**2 * The docs on the web: `/docs` lists every page, guides then reference,3 * each linking its page with its summary; a page draws its Markdown under4 * its title, with the list of pages beside it; `/docs/<page>.md` serves the5 * text, and a page that does not exist is a 404.6 */1import { describe, expect, it } from "@effect/vitest";2import { docPage, docPages } from "@repo/agent-kit/docs/index";3import { Effect, Option } from "effect";4
104 unmodified lines
109 });110 });111});112119/** What `/docs/<page>.md` answers. */113const served = (page: string) =>114 Effect.gen(function* () {115 const response = yield* Effect.promise(() =>116 docsMarkdownHandler(input.platformUrl)({
29 unmodified lines
modified:apps/web/test/edge-cache.test.ts+1 added-33 removed
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 */1import { describe, expect, it } from "@effect/vitest";2import { Client, Contracts } from "@repo/protocol/contracts";3import { ProjectName } from "@repo/protocol/ids";4import { asTester, unanswered } from "@repo/protocol/testing";
17 unmodified lines
22const WEB_URL = "https://web-test.example.workers.dev";2324const PLATFORM_URL = "https://platform-test.example.workers.dev";2536/** A signed-in reader's cookie, as the browser sends it. */26const SIGNED_IN = `${SESSION_COOKIE}=dev-ada`;2739/** A GET for `path` on the web host, with `headers`. */28const get = (path: string, headers: HeadersInit = {}) =>29 new Request(`${WEB_URL}${path}`, { headers });3043/** What the edge sees of an answer: how long it may be kept, and what it varies by. */31const kept = (response: Response) => ({32 cacheControl: response.headers.get("cache-control"),33 vary: response.headers.get("vary"),34});3549/** An answer under `headers`, with a body. */36const answer = (headers: HeadersInit, status = 200) =>37 new Response("the page", { headers, status });3853/** Every `Cache-Control` the web gives or passes on, and none. */39const ANSWERS: readonly (readonly [string, HeadersInit])[] = [40 ["a page at main", branchPage],41 ["a page about its reader", personalPage],42 ["an agent's document", { "cache-control": "public, max-age=60" }],
184 unmodified lines
227 ]);228 });229});230246// --- The routes that read the reader's credential ----------------------------247248/** A platform that lists datekit and no asks, and answers nothing else. */231const listingDatekit = () =>232 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(233 Layer.provide([234 Layer.mergeAll(
14 unmodified lines
249 asTester,250 ])251 );252271/** An env whose PLATFORM answers every request with a long-lived public answer. */253const platformEnv: Env = {254 PLATFORM: untouchable<Fetcher>("PLATFORM", {255 fetch: () =>256 Promise.resolve(
2 unmodified lines
259 }),260 PUBLIC_PLATFORM_URL: PLATFORM_URL,261};262282/**283 * Each server route that hands the reader's cookie on (to the platform, as284 * its credential), by the request it answers. Each answers a public285 * `Cache-Control` of its own; the entry is what keeps a reader's answer286 * from the edge.287 */263// Each answers a public `Cache-Control` of its own; the entry is what keeps a reader's answer from the edge.264const CREDENTIAL_ROUTES: readonly (readonly [265 string,266 (request: Request) => Promise<Response>,267])[] = [
48 unmodified lines
316 )({ request: new Request(request, { body: "{}", method: "POST" }) }),317 ],318];319344/** A signed-in agent's request for `path`, as Markdown. */320const signedInAt = (path: string) =>321 get(path, { accept: "text/markdown", cookie: SIGNED_IN });322323describe("a route that hands the reader's cookie on", () => {
29 unmodified lines
353 })354 );355});356382/** The landing's GET, falling through to a page the edge may keep. */357const landing = (request: Request) =>358 Promise.resolve(359 landingHandler(360 listingDatekit,
52 unmodified lines
413 })414 );415});416443// --- The pages ---------------------------------------------------------------444417const routeSources: Readonly<Record<string, string>> = import.meta.glob(418 "../src/routes/**/*.{ts,tsx}",419 { eager: true, import: "default", query: "?raw" }420);
2 unmodified lines
423 "../src/**/*.{ts,tsx}",424 { eager: true, import: "default", query: "?raw" }425);426455/**456 * Where a page's loader or server function reaches the request it answers457 * (its cookie, its headers): TanStack Start's server helpers.458 */427const readsTheRequest = /from "@tanstack\/react-start\/server"/u;428429describe("a page", () => {430 it("reads the reader's request only where it is kept nowhere", () => {
35 unmodified lines
modified:apps/web/test/env.test-d.ts+2 added-6 removed
1/**2 * Principle 7's type fence: the web Worker's generated `Env` (from3 * `wrangler.jsonc`, by `bun run types`) reaches the platform only through4 * `PLATFORM`, and holds no Artifacts binding, public or private, so no code5 * in a public page can reach a repo.6 */1// The web Worker's `Env` reaches the platform only through `PLATFORM` and holds no Artifacts binding,2// so no code in a public page can reach a repo.3import { describe, expectTypeOf, it } from "vitest";45describe("the web Worker's Env", () => {6 it("reaches the platform through the PLATFORM service binding", () => {
14 unmodified lines
modified:apps/web/test/env.test.tsx-18 removed
1/**2 * A project's env shape, rendered to HTML with `react-dom/server` from3 * datekit's `.env.schema` as `envShape` returns it: each item's name,4 * description, type, whether it is required, whether it is sensitive, its5 * `@proxy` hosts, docs and deprecation; for a sensitive item who set its6 * value and when, never the value, and no control that would take or show7 * one. A caption credits the format to varlock.8 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts, EnvSchemaOf } from "@repo/protocol/contracts";4import { EnvSchemaView } from "@repo/protocol/domain/env";
16 unmodified lines
21const now = DateTime.makeUnsafe("2026-10-12T12:00:00Z");2223const decodeView = Schema.decodeSync(EnvSchemaView);2433/** datekit's items, encoded, as its `.env.schema` declares them. */25const items: readonly (typeof EnvItem.Encoded)[] = [26 {27 key: "APP_ENV",28 required: true,
28 unmodified lines
57 tags: [],58 },59];6070/** datekit's env shape at its landed SHA, as `envShape` returns it. */61const datekit = decodeView({62 at: "9b1c3e5d7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c",63 currentEnvKey: "APP_ENV",64 file: ".env.schema",
6 unmodified lines
71const scriptAddress = ["javascript", "alert(1)"].join(":");7273const page = <EnvView now={now} schema={datekit} />;7485/** The markup of the item `key`: from its row to the next item's. */75const itemOf = (markup: string, key: string) => {76 const start = markup.indexOf(`data-env-key="${key}"`);77 const next = markup.indexOf("data-env-key=", start + 1);78
1 unmodified line
80 ? ""81 : markup.slice(start, next === -1 ? undefined : next);82};8395/** Each item's key, in the order the page lists them. */84const keysOf = (markup: string) =>85 [...mainOf(markup).matchAll(/data-env-key="(?<key>[^"]*)"/gu)].map(86 (found) => found.groups?.key87 );
239 unmodified lines
327 );328 });329});330343/** What the stub platform was asked: env shapes and ask lists. */331interface Asked {332 readonly asks: number;333 readonly schemas: number;334}335336const nothingAsked: Asked = { asks: 0, schemas: 0 };337351/**352 * A platform as the env page's loader calls it: `known` says whether it353 * knows datekit at all, `landed` whether datekit's main has landed (before354 * that, `envShape` has no commit to read and answers `UnknownProject`).355 */338const platformWhere = (339 asked: Ref.Ref<Asked>,340 { known, landed }: { readonly known: boolean; readonly landed: boolean }341) =>
106 unmodified lines
modified:apps/web/test/events.test.ts-10 removed
1/**2 * One fold over a project's `watch` replay, which every page reads the same3 * way: who holds each ask, its rounds and latest outcome, whether it landed;4 * whose move an outcome leaves; a family's marks counted against the5 * parent's stored children; and which landings a page that is open should6 * stamp, on the stream and on the poll alike. Events are built with their7 * cases, never a literal tag.8 */1import { describe, expect, it } from "@effect/vitest";2import type { Ask } from "@repo/protocol/domain/ask";3import { ProjectEvent } from "@repo/protocol/domain/event";4import { LandingView } from "@repo/protocol/domain/landing";
200 unmodified lines
205 }).toStrictEqual({ claimed: "answerer", open: "none" });206 });207});208217/** A child of `drop-legacy-fetch`, one per module. */209const child = (module: string) => AskId.make(`drop-legacy-fetch-${module}`);210211describe(familyMarks, () => {212 const modules = [
106 unmodified lines
319 }).toStrictEqual({ none: 0, some: 9 });320 });321});322332/** The 40-hex sha of the `n`th landing. */323const shaOf = (n: number) => LandedSha.make(n.toString(16).padStart(40, "0"));324325describe(recentLandings, () => {326 const one = Schema.decodeSync(LandingView)({
43 unmodified lines
modified:apps/web/test/facts.test.tsx-7 removed
1/**2 * The inspector's fact blocks: typed facts under a label, never prose the3 * page already says. A claim never shows a deadline (no read carries one),4 * agents sit below the line that says they are not credit, long hashes are5 * shortened with the whole value kept, and the gate marks where an answer6 * stands.7 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Glob } from "@repo/protocol/domain/common";4import { Outcome } from "@repo/protocol/domain/outcome";
278 unmodified lines
modified:apps/web/test/family.test.tsx-9 removed
1/**2 * A family drawn as a fan: one node per child the parent stores, each its3 * mark and its short name, an arrow to the delete child that waits on4 * them, and "n of N landed" counted against the stored children, never the5 * listing's remaining ones. A child that landed while the page was open6 * settles with the stamp, once. Its states come from the event fold, built7 * here from hand-made events.8 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import type { Ask } from "@repo/protocol/domain/ask";4import { ProjectEvent } from "@repo/protocol/domain/event";
101 unmodified lines
106 states={states}107 />108 );109118/** The `<li>`s of the list named `label`, each as its text. */110const itemsOf = (markup: string, label: string) => {111 const start = markup.indexOf(`aria-label="${label}"`);112 const end = markup.indexOf("</ol>", start);113
241 unmodified lines
modified:apps/web/test/finish.test.tsx-19 removed
1/**2 * Finishing an answer from its diff: a `Finish` decision's page lays the3 * answer's diff out as the code browser does. The server sends it as plain4 * text (the browser draws it over in place), its files with the ask's5 * territory first, then tests, then the rest; a refusal from an earlier6 * round sits under the line it pointed at; each file can be marked read in7 * this browser alone; a newer head says so above the diff; and the three8 * lines that fetch the head and finish it are numbered. The diff comes only9 * from the decision's own `patch` evidence; without one the page shows the10 * lines and no diff. Rendered with `react-dom/server`.11 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import type { Verdict } from "@repo/protocol/domain/answer";4import type { Ask } from "@repo/protocol/domain/ask";
35 unmodified lines
40 readMarks,41 writeMark,42} from "../src/features/finish/read-marks.ts";4355/** The entities React writes for text, and what each reads as. */44const ENTITIES: ReadonlyMap<string, string> = new Map([45 ["&#x27;", "'"],46 ["&amp;", "&"],47 ["&gt;", ">"],
2 unmodified lines
50]);5152const markupOf = (element: ReactElement) => renderToStaticMarkup(element);5366/** What a reader sees of `markup`: the text without its tags, entities decoded. */54const textIn = (markup: string) =>55 markup56 .replaceAll(/<[^>]+>/gu, " ")57 .replaceAll(
1 unmodified line
59 (entity) => ENTITIES.get(entity) ?? entity60 )61 .replaceAll(/\s+/gu, " ");6276/** What a reader sees of `element`. */63const textOf = (element: ReactElement) => textIn(markupOf(element));6465const PLATFORM_URL = "https://platform-test.example.workers.dev";66
6 unmodified lines
73const base = CommitSha.make("1".repeat(40));7475const okonkwo = Handle.make("okonkwo");7691/** Two files changed, one added, one removed, one renamed. */77const PATCH = [78 "diff --git a/src/parse.ts b/src/parse.ts",79 "index 1111111..2222222 100644",80 "--- a/src/parse.ts",
119 unmodified lines
200 {...extra}201 />202);203219/** The files the server's diff draws, in its order. */204const drawnFilesOf = (markup: string) =>205 [...markup.matchAll(/<section aria-label="(?<file>[^"]+)" data-file=/gu)].map(206 (match) => match.groups?.file207 );208225/** A refusal from the answer's first round, at line 2 of its test. */209const placed: PlacedRefusal = {210 line: 2,211 path: "test/parse.test.ts",212 refusal: new Weakened({
144 unmodified lines
357 );358 });359});360378/** A browser storage over a map, as `localStorage` behaves. */361const storageOver = (kept: Map<string, string>): Storage => ({362 clear: () => {363 kept.clear();364 },
9 unmodified lines
374 kept.set(key, value);375 },376});377396/** A storage that refuses every read and write, as a private window's may. */378const refusing: Storage = {379 clear: () => {380 throw new Error("refused");381 },
117 unmodified lines
modified:apps/web/test/folder.test.ts-15 removed
1/**2 * A folder and its README, read on the server for the project's page and a3 * folder's page: the README is asked for beside the folder, not after it,4 * as `README.md`, the name most folders give it, and the folder's own5 * README is read when it names another (or the guess was read at another6 * commit). Over a stub platform that answers `readTree` and `readFile`.7 */1import { describe, expect, it } from "@effect/vitest";2import { Client, Contracts } from "@repo/protocol/contracts";3import type { FileView, TreeListing } from "@repo/protocol/domain/code";4import { BlobSha, CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";
20 unmodified lines
25 text: `# ${path}`,26 truncated: false,27});2836/** A folder at the landed commit holding nothing but its README, when `readme` names one. */29const folder = (readme?: string, path?: string): TreeListing => {30 const listing: Types.Mutable<TreeListing> = {31 at: landed,32 entries: [],
12 unmodified lines
4546 return listing;47};4857/**58 * A platform whose `readTree` answers `listing` once `treeWaits` lets it,59 * and whose `readFile` answers each path in `files` with the file kept60 * there (at its own commit), refusing any other; every path `readFile` is61 * asked for is kept in `asked`, and the first ask lets `readStarted` go.62 */49const platform = (input: {50 readonly asked: Ref.Ref<readonly string[]>;51 readonly files: ReadonlyMap<string, FileView>;52 readonly listing: TreeListing;
24 unmodified lines
77 asTester,78 ])79 );8095/** The folder at `path` (the root when none) at main, with the paths of its README and the files asked for. */81const readWith = (82 input: Omit<Parameters<typeof platform>[0], "asked">,83 path?: string84) =>
98 unmodified lines
modified:apps/web/test/forward.test.ts-12 removed
1/**2 * The paths the platform serves and the web host only passes on:3 * the projects' skills under `/.well-known/agent-skills/`, the CLI's4 * `/install.sh` and its `/releases/`. Each route hands GET and HEAD to the5 * backend; the production backend forwards over `PLATFORM` at the6 * platform's URL with the path, query, method and headers as they came,7 * and the platform's answer comes back as it is, a redirect's path-absolute8 * `Location` included, so the next request stays on the web host.9 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { untouchable } from "@repo/testkit/untouchable";4import { Effect } from "effect";
7 unmodified lines
12const PLATFORM_URL = "https://platform-test.example.workers.dev";1314const WEB_URL = "https://web-test.example.workers.dev";1525/** A PLATFORM binding that keeps each request it is handed and answers `answer`. */16const platform = (answer: (request: Request) => Response) => {17 const handed: Request[] = [];1819 const env: Env = {
11 unmodified lines
3132 return { env, handed };33};3445/** The production routes' handlers, over a fake PLATFORM. */35const served = (answer: (request: Request) => Response) => {36 const binding = platform(answer);3738 return { ...binding, handlers: forwarded(backend, binding.env) };
77 unmodified lines
116 })117 );118});119131/** What a route says of its server handlers. */120interface ServerRoute {121 readonly options: { readonly server?: { readonly handlers?: object } };122}123
19 unmodified lines
modified:apps/web/test/front.test.tsx-18 removed
1/**2 * The front page: the open asks of every project, read on the server by the3 * route's loader and rendered inside the router, grouped by project with4 * each project's posture said once on its group's header, a family drawn5 * as one fan row, each ask the viewer may take with its claim command as6 * text, narrowed by kind, by whether it is open to take or held for7 * newcomers, and by project.8 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { deleteChildId, splitFamily } from "@repo/project/migrate";4import { Client, Contracts } from "@repo/protocol/contracts";
28 unmodified lines
33import { reachingTransport } from "./transport.ts";3435const kind = Schema.decodeSync(KindName);3645/** The markup of the row for `ask`: from its `<li>` to the next row or group. */37const rowOf = (markup: string, ask: string) => {38 const start = markup.indexOf(`data-ask="${ask}"`);3940 const ends = ["data-ask=", "<section", "</main>"].flatMap((end) => {
4 unmodified lines
4546 return start === -1 ? "" : markup.slice(start, Math.min(...ends));47};4858/** The ask ids of the rows on the page, top to bottom. */49const rowsIn = (markup: string) =>50 [...markup.matchAll(/<li\b[^>]*data-ask="(?<ask>[^"]+)"/gu)].map(51 (row) => row.groups?.ask52 );5364/** The markup of each project group's sticky header, by its project. */54const headersIn = (markup: string) =>55 [56 ...markup.matchAll(57 /<section aria-label="(?<project>[^"]+)"[^>]*>(?<header><div\b[\s\S]*?<\/div><\/div>)/gu58 ),59 ].map((match) => [match.groups?.project, match.groups?.header] as const);6072/** The list itself: from the toolbar to the end of main, the facts left out. */61const listIn = (markup: string) =>62 markup.slice(markup.indexOf("data-toolbar"), markup.indexOf("</main>"));6364const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");
57 unmodified lines
122123const asksOf = (shown: readonly FrontPageEntry[]) =>124 shown.map(({ ask }) => ask.ask);125138/** The page's props, with nothing the loader read beyond `entries`. */126const props = (127 filter: FrontFilter,128 more: Partial<FrontPageProps> = {}129): FrontPageProps => ({
78 unmodified lines
208 ).toStrictEqual({});209 });210});211225/** A listing as the contracts return one. */212const listing = (id: string, blockedBy: readonly string[] = []) =>213 Schema.decodeSync(AskListing)({214 ask: id,215 blockedBy,
363 unmodified lines
579 })580 );581});582597/** The contracts over HTTP, each request answered by `answer`. */583const clientOver = (answer: (request: Request) => Promise<Response>) =>584 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(585 Layer.provide(RpcClient.layerProtocolHttp({ url: "http://localhost/rpc" })),586 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),
3 unmodified lines
590 )591 )592 );593609/** The contracts over a fresh dev world; the world ends with the scope. */594const devWorld = Layer.unwrap(595 Effect.gen(function* () {596 const { dispose, handler } = devServer();597
2 unmodified lines
600 return clientOver(handler);601 })602);603620/** A platform that answers the front page and never answers the list of projects. */604const projectsNeverAnswer = Layer.effect(605 Client,606 RpcTest.makeClient(Contracts)607).pipe(
11 unmodified lines
619620/** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */621const seededWorld = { timeout: 30_000 };622640/** The page as the route renders it from what its loader read. */623const sentFrom = (data: FrontPageData, filter: FrontFilter = {}) =>624 renderAt(625 "/asks",626 <FrontPageView
81 unmodified lines
modified:apps/web/test/head.test.ts+1 added-9 removed
1/**2 * What a page puts in the document's head: its title, and the description3 * a shared link unfurls with (`description` and the Open Graph trio). The4 * router keeps one meta per name (or Open Graph property), the last a route5 * gives, so each one here has a name of its own and a page's replace the6 * root's.7 */1// The router keeps one meta per name (or Open Graph property), the last a route gives, so a page's replace the root's.2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";45import { pageHead } from "../src/features/shared/head.ts";6import { rootHead } from "../src/routes/__root.tsx";714/** Each meta's key as the router dedupes it: its `name`, else its `property`. */8const keyOf = (meta: Readonly<Record<string, string>>) =>9 meta.name ?? meta.property ?? (meta.title === undefined ? "" : "title");1018/** The metas of `head` as `key: content` pairs (the title as `title`). */11const metasOf = (head: {12 readonly meta: readonly Readonly<Record<string, string>>[];13}) =>14 Object.fromEntries(
43 unmodified lines
modified:apps/web/test/home.test.tsx-14 removed
1/**2 * `/home`, a signed-in reader's own page: their work (each claim, its ask's3 * want, where its answer stands and the command that runs next), the4 * decisions waiting when they decide somewhere, the asks they may take, and5 * their record; each block says what to do when it is empty or did not6 * come. Read on the server with the reader's session from the dev world and7 * its fixtures, and drawn from reads made here. Signed out, it says what8 * the page is and how to sign in. A page about its reader, kept by no cache.9 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import type { AnswerView } from "@repo/protocol/domain/answer";4import { ClaimView } from "@repo/protocol/domain/claim";
26 unmodified lines
31import { renderAt } from "./render.tsx";3233const NOW = "2026-10-07T12:00:00.000Z";3444/** The page as the route renders it from what the loader sent. */35const pageFrom = (encoded: typeof HomePageData.Encoded) =>36 Effect.gen(function* () {37 const data = yield* Schema.decodeEffect(HomePageData)(encoded);38
2 unmodified lines
41 <HomeView now={data.now} read={data.read} />42 );43 });4455/** The page drawn from a signed-in read made here. */45const pageOf = (read: Partial<typeof HomeRead.cases.Read.Type>) =>46 renderAt(47 "/home",48 <HomeView
9 unmodified lines
58 })}59 />60 );6173/** The sections' names, in order. */62const sectionsOf = (markup: string) =>63 [...markup.matchAll(/<section\b[^>]*aria-label="(?<name>[^"]+)"/gu)].map(64 (found) => found.groups?.name65 );6679/** The commands a reader can copy: each in the DOM as text. */67const commandsOf = (markup: string) =>68 [...markup.matchAll(/<code\b[^>]*>(?<command>.*?)<\/code>/gsu)].map((found) =>69 textIn(found.groups?.command ?? "").trim()70 );
13 unmodified lines
84 warnsAt: "2026-10-08T06:00:00.000Z",85 ...fields,86 });87101/** An answer refused because its claim lapsed, which a new claim can mend. */88const refused = (ask: string): AnswerView => ({89 ask: AskId.make(ask),90 at: DateTime.makeUnsafe("2026-10-07T11:00:00Z"),91 head: CommitSha.make("b".repeat(40)),
298 unmodified lines
modified:apps/web/test/import.test.tsx+1 added-25 removed
1/**2 * The import page, `/import`, rendered to HTML with `react-dom/server`: a3 * signed-in person pastes a public repo's HTTPS URL, may name a branch,4 * picks the owner (their handle, or the URL's source namespace when its5 * host is one the platform knows, which is the default then) and the name,6 * prefilled from the URL, and imports it through `initProject`. Signed out,7 * the page links to sign-in, coming back to it. A refusal reads as the8 * platform gave it. The page is about its reader, so no cache keeps it.9 */1import { RegistryContext } from "@effect/atom-react";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Contracts, InitProject } from "@repo/protocol/contracts";
34 unmodified lines
3940const signedIn = (url = CLICK) =>41 markupOf(<ImportView handle={oscabriel} here="/import" url={url} />);4252/** An input's opening tag, by its `name`. */43const inputNamed = (markup: string, name: string) =>44 new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";4556/** Where a sign-in link in `markup` comes back to. */46const returnOf = (markup: string) => {47 const href = /href="(?<href>\/auth\/signin[^"]*)"/u48 .exec(markup)49 ?.groups?.href?.replaceAll("&amp;", "&");
178 unmodified lines
228 );229 });230});231243/** `initProject`'s answer: the project made. */232const made = (project: string) =>233 Schema.decodeSync(InitProject.successSchema)({234 project,235 remote: `https://platform.test/${project}.git`,
65 unmodified lines
301 expect(markup).toContain("<form");302 });303});304317/**318 * The page as its route draws it, the hook's importer over `registry`,319 * handing each render's importer to `seen`, as the press would reach it.320 * A server's render always reads who is signed in as not yet known (the321 * page's first paint, `whoAtom`), so this one says, as the browser would322 * once it knows, that oscabriel is.323 */305// A server's render always reads who is signed in as not yet known, so this one says, as the browser would, that oscabriel is.306const Page = ({307 seen,308}: {309 readonly seen?: ((importer: Importer) => void) | undefined;
24 unmodified lines
334 <Page seen={seen} />335 </RegistryContext.Provider>336);337356/**357 * A browser signed in as oscabriel, over a platform whose `initProject`358 * answers with `answer`, every payload it is sent kept in `sent`.359 */338const browserWith = (339 sent: ImportPayload[],340 answer: (341 payload: ImportPayload
26 unmodified lines
368 ),369 ],370 });371394/** The form's fields as the page drew them: what pressing Import sends. */372const fieldsIn = (markup: string) => {373 const value = (name: string) =>374 /value="(?<value>[^"]*)"/u375 .exec(inputNamed(markup, name))
6 unmodified lines
382 url: value("url"),383 };384};385409/** Presses Import on the page drawn over `registry`, and waits for the answer. */386const pressImport = (registry: AtomRegistry.AtomRegistry) =>387 Effect.gen(function* () {388 const importers: Importer[] = [];389
81 unmodified lines
modified:apps/web/test/keys.test.tsx-9 removed
1/**2 * The keyboard's single keys: what each press does, when none acts (focus in3 * a text field, the switch off), and the switch itself, kept in the4 * browser's storage as a per-viewer convenience that must survive a5 * storage that refuses to read or write.6 */1import { describe, expect, it } from "@effect/vitest";2import { renderToStaticMarkup } from "react-dom/server";34import {
2 unmodified lines
7 readShortcuts,8 writeShortcuts,9} from "../src/features/shared/keys.tsx";1017/** A press of `key` outside any text field, with no modifier held. */11const press = (key: string, inField = false) => ({12 altKey: false,13 ctrlKey: false,14 inField,15 key,16 metaKey: false,17});1826/** A `Storage` whose every read and write throws, as a blocked one does. */19const refusing: Storage = {20 clear: () => {21 throw new Error("blocked");22 },
13 unmodified lines
36 throw new Error("blocked");37 },38};3948/** A `Storage` held in a map, as a browser's is. */40const kept = (): Storage => {41 const items = new Map<string, string>();4243 return {
157 unmodified lines
modified:apps/web/test/landing-route.test.ts-4 removed
1/**2 * The landing is the one page drawn outside the shell: its route alone3 * names `shell: "bare"`, so no other page loses the rail by accident.4 */1import { describe, expect, it } from "@effect/vitest";23const routeSources: Readonly<Record<string, string>> = import.meta.glob(4 "../src/routes/**/*.{ts,tsx}",
12 unmodified lines
modified:apps/web/test/landing.test.tsx+1 added-14 removed
1/**2 * The landing, as a first-time reader meets it: what the platform is, the3 * way to the open asks before anything else, the install line to copy, the4 * screen `git push` prints when the gate refuses (from the one renderer),5 * the four nouns, the loop, and the projects to read, each with its6 * posture. Drawn in the house style: no banned word, and no rounded,7 * shadowed or gradient surface. Its projects are read on the server as8 * nobody, so the page is the same for everyone, script or not.9 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Contracts } from "@repo/protocol/contracts";4import { ProjectListing } from "@repo/protocol/domain/front-page";
29 unmodified lines
34 "/",35 <LandingView platformUrl={PLATFORM} projects={projects} webUrl={WEB} />36 );3747/** Every link's address, in the page's order. */38const hrefsOf = (markup: string) =>39 [...markup.matchAll(/<a\b[^>]*href="(?<href>[^"]+)"/gu)].map(40 (found) => found.groups?.href41 );
107 unmodified lines
149 Effect.gen(function* () {150 const markup = yield* pageWith(listed);151 const text = textIn(markup).toLowerCase();152163 // DESIGN.md's list, and the glossary's words to avoid. "Merge" is164 // banned for a landing, and the page never says it of one ("merges165 // onto main" is the gate's step, in the README's words).153 // DESIGN.md's list, and the glossary's words to avoid. "Merge" is banned for a landing.154 expect(155 [156 "review",157 "approve",
22 unmodified lines
180 })181 );182});183196/** A platform that lists `projects`, and answers nothing else. */184const listing = (projects: readonly ProjectListing[]) =>185 platformWith(186 Contracts.toLayerHandler("listProjects", () => Effect.succeed({ projects }))187 );
29 unmodified lines
modified:apps/web/test/landings.test.tsx-10 removed
1/**2 * A project's landings list, rendered to HTML: each landing's subject says3 * what it is and links the ask it answers or the ask it opened; one that4 * did neither reads as what it is. Its credit is one line of roles, never5 * the trailers again.6 */1import { describe, expect, it } from "@effect/vitest";2import type { LandingView } from "@repo/protocol/domain/landing";3import { AskId, LandedSha } from "@repo/protocol/ids";4import { Struct } from "effect";56import { LandingList } from "../src/features/project/landings.tsx";7import { landing, markupOf, now, plainText } from "./ask-fixtures.ts";815/** Every `href` in `markup`, in order. */9const hrefsOf = (markup: string) =>10 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map(11 (match) => match.groups?.href ?? ""12 );1321/** The markup of the list item for the landing `sha`. */14const itemOf = (markup: string, sha: string) =>15 new RegExp(`<li\\b[^>]*data-landing="${sha}"[^>]*>[\\s\\S]*?</li>`, "u").exec(16 markup17 )?.[0] ?? "";1827/** `landing` without the ask it answers: a decider's own landing. */19const unasked: LandingView = {20 ...Struct.omit(landing, ["ask"]),21 sha: LandedSha.make("e".repeat(40)),22};2333/** An ask's opening: it opened `format-ordinal` and answers nothing. */24const opening: LandingView = {25 ...unasked,26 opened: AskId.make("format-ordinal"),27 sha: LandedSha.make("f".repeat(40)),
42 unmodified lines
modified:apps/web/test/ledger.test.tsx-20 removed
1/**2 * A project's ledger, rendered to HTML with `react-dom/server` from fixtures3 * decoded with the protocol's own schemas: the posture label, each declared4 * layer, each sealed area folded from the entries (count, authors, root,5 * admission), and the entries newest first. The ledger carries no path, no6 * check name and no file name, and the view adds none.7 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import { ProjectListing } from "@repo/protocol/domain/front-page";
37 unmodified lines
42const maintainers = LayerName.make("maintainers");4344const decodeLedger = Schema.decodeSync(Ledger);4553/** The ledger's own fields, decoded from the wire as `ledger` returns them. */46const datekitRead = decodeLedger({47 entries: [],48 layers: [49 {
12 unmodified lines
62 postureLabel: "Open with sealed evidence",63 project: "datekit",64});6574/** Its entries, each made (and checked) by the protocol's own constructors. */66const entries: readonly LedgerEntry[] = [67 LedgerEntry.cases.LayerDeclared.make({68 at: DateTime.makeUnsafe("2026-10-09T10:00:00.000Z"),69 disclose: "sealed",
58 unmodified lines
128const parserArea = AreaName.make("parser");129130const parserRoot = SuiteRoot.make(`sha256:7fbe4b${"2c3d".repeat(14)}a1`);131141/** The `parser` suite's commitment, published as the release landed. */132const parserCommitment = LedgerEntry.cases.CommitmentPublished.make({133 area: parserArea,134 at: DateTime.makeUnsafe("2026-10-12T08:00:00.000Z"),135 authors: 3,
1 unmodified line
137 seq: 9,138 suite: parserRoot,139});140151/** datekit's ledger once its maintainers layer holds the `export` and `parser` suites. */141const datekit: Ledger = {142 ...datekitRead,143 entries: [...entries, parserCommitment],144};145157/** A project with no visibility config: the platform's neutral ledger. */146const open = decodeLedger({147 entries: [],148 layers: [],149 posture: "open",
2 unmodified lines
152});153154const page = <LedgerView ledger={datekit} now={now} />;155168/** The entries' sequence numbers, in the order the page lists them. */156const seqsOf = (markup: string) =>157 [...markup.matchAll(/data-seq="(?<seq>\d+)"/gu)].map((found) =>158 Number(found.groups?.seq)159 );160174/** The words of the first `<time>` after `marker` in `markup`. */161const whenOf = (markup: string, marker: string) =>162 /<time\b[^>]*>(?<when>[^<]*)<\/time>/u.exec(163 markup.slice(markup.indexOf(marker))164 )?.groups?.when;165180/** Each history row's markup, in the order the page lists them. */166const historyRowsOf = (markup: string) =>167 [168 ...mainOf(markup).matchAll(/<li\b[^>]*data-entry="[^"]*"[\s\S]*?<\/li>/gu),169 ].map(([row]) => row);170186/** Each history row's typed word, in order. */171const wordsOf = (markup: string) =>172 historyRowsOf(markup).map((row) =>173 plainText(elementWith(row, "data-entry-word")).trim()174 );175192/** Whether a history row's word is drawn in the sealed role or in ink. */176const toneOf = (row: string) =>177 /text-sealed/u.test(elementWith(row, "data-entry-word")) ? "sealed" : "ink";178179describe("a project's ledger", () => {
302 unmodified lines
482 expect(areaSummaries(open)).toStrictEqual([]);483 });484});485503/** A platform that knows only datekit, counting the ledgers it is asked for. */486const platformHandlers = (asked: Ref.Ref<number>) =>487 Layer.mergeAll(488 unanswered,489 Contracts.toLayerHandler("ledger", ({ project }) =>
9 unmodified lines
499 ),500 asTester501 );502521/** That platform, as the page's loader reaches it on the server. */503const platformOf = (asked: Ref.Ref<number>) =>504 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(505 Layer.provide(platformHandlers(asked))506 );
45 unmodified lines
552 })553 );554});555575/** Lets the atoms' fibers run until `done` holds, or long enough that it would have. */556const runUntil = (done: Effect.Effect<boolean>) =>557 Effect.yieldNow.pipe(558 Effect.andThen(done),559 Effect.repeat({ times: 200, until: (held) => held })
101 unmodified lines
modified:apps/web/test/legacy-redirect.test.ts-10 removed
1/**2 * A project's address on the web (ADR 0032): a key a project kept from3 * before owners, and a name in another case, are a 301 to the name's4 * address with the rest of the path and the query kept, which the edge may5 * keep as any page; everything else goes on to the pages. The router reads6 * a source path as the same project pages, its owner in one param.7 */1import { describe, expect, it } from "@effect/vitest";2import { Effect, Option } from "effect";34import { addressedEntry, canonicalAddress } from "../src/server/addresses.ts";5import { forTheEdge, KEPT_NOWHERE } from "../src/server/edge-cache.ts";67const WEB_URL = "https://web-test.example.workers.dev";816/** A request for `path` on the web host, by `method`. */9const request = (path: string, method = "GET") =>10 new Request(`${WEB_URL}${path}`, { method });1120/** Where the 301 for `path` leads, if there is one. */12const movedTo = (path: string) =>13 Option.map(canonicalAddress(request(path)), (response) => [14 response.status,15 response.headers.get("location"),16 ]);1727/** An entry that answers every request it is handed with the page. */18const pages = {19 fetch: (_request: Request) => new Response("the page", { status: 200 }),20};21
96 unmodified lines
modified:apps/web/test/line-hash.test.ts-5 removed
1/**2 * A line anchor, as a file page's address carries it: `#L10` names one3 * line and `#L10-L20` a range, whichever end comes first. Anything else4 * names no line. One pure parser, read by the file, why and propose pages.5 */1import { describe, expect, it } from "@effect/vitest";2import { Option } from "effect";34import {
96 unmodified lines
modified:apps/web/test/listings.ts-6 removed
1/**2 * Ten listed projects, as the platform lists them (in no order the page3 * keeps), two pairs tied on open asks, and the eight that lead: the most4 * open asks first, a tie by name.5 */1import { ProjectListing } from "@repo/protocol/domain/front-page";2import { Schema } from "effect";34export const TEN_LISTED = Schema.decodeSync(Schema.Array(ProjectListing))([
8 unmodified lines
13 { openAsks: 3, posture: "open", project: "oscabriel/hearth" },14 { openAsks: 7, posture: "open", project: "oscabriel/ember" },15]);1622/** The eight of `TEN_LISTED` that lead, in order. */17export const EIGHT_LEADING = [18 "oscabriel/burrow",19 "oscabriel/ember",20 "github.com/pallets/click",
6 unmodified lines
modified:apps/web/test/llms.test.ts-18 removed
1/**2 * What an agent reads first on the web host: `/llms.txt` for3 * the platform and `/<project>/llms.txt` for one project, as Markdown, and4 * the MCP card at `/.well-known/mcp.json`. Each is a pure function of what5 * the platform lists and of the CLI's commands (`@repo/agent-kit`'s one6 * list); every name in them comes from `Brand`.7 */1import { describe, expect, it } from "@effect/vitest";2import type { CommandDoc } from "@repo/agent-kit/command-doc";3import { fullLlms } from "@repo/agent-kit/full-llms";4import { Brand } from "@repo/brand";
37 unmodified lines
42const datekit = ProjectName.make("oscabriel/datekit");4344const burrow = ProjectName.make("oscabriel/burrow");4553/** A command row as `@repo/agent-kit`'s command list holds it. */46const row = (47 path: readonly [string, ...string[]],48 summary: string,49 more: Partial<CommandDoc> = {}
276 unmodified lines
326327 const words = catalog.map(({ path }) => path.join(" "));328329 expect(catalog.length).toBeGreaterThan(20);338 // A contract the CLI projects, and commands written by hand in it.330 expect(words).toContain("asks");331 expect(words).toContain("env set");332 expect(words).toContain("login");333 expect(
3 unmodified lines
337 ).toStrictEqual([]);338 });339});340350/** A platform that lists `listed` as its projects, and answers nothing else. */341const listing = (listed: readonly ProjectListing[]) => () =>342 platformWith(343 Contracts.toLayerHandler("listProjects", () =>344 Effect.succeed({ projects: listed })345 )346 );347358/** A platform that cannot be reached: every call dies on the way. */348const unreachable = () => unreachablePlatform;349350const getFull = () => new Request(`${webUrl}/llms-full.txt`);351363/** A fork's gateway address: its project's name, then the fork's parts. */352const addressed = (repo: RepoName) =>353 Option.getOrElse(addressOfRepo(repo), () => repo);354355const read = (response: Response) =>
38 unmodified lines
394 const text = fullLlms({ commands: catalog, platformUrl, projects, webUrl });395 const parseIso = AskId.make("parse-iso");396 const ada = Handle.make("Ada");397410 /** A name pattern the doc states, with its placeholders filled in. */398 const filled = (pattern: string) =>399 pattern400 .replaceAll("<owner>/<name>", datekit)401 .replaceAll("<ask>", parseIso)402 .replaceAll("<handle>", ada.toLowerCase());403417 /** The patterns in the doc's code spans that name a fork. */404 const patterns = [405 ...text.matchAll(/`(?<name><owner>\/<name>--[^`]+)`/gu),406 ].map((match) => match.groups?.name ?? "");407
27 unmodified lines
435 });436 });437});438453/** A platform that lists `listed` as its projects and `listedAsks` as datekit's asks. */439const listingWithAsks =440 (listed: readonly ProjectListing[], listedAsks: readonly AskListing[]) =>441 () =>442 platformWith(
4 unmodified lines
447 Effect.succeed({ asks: listedAsks })448 )449 );450466/** A request for `path` on the web host, accepting `accept`. */451const getAt = (path: string, accept: string) =>452 new Request(`${webUrl}${path}`, { headers: { accept } });453454const BROWSER =455 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";456473/** What a handler answered: a response, or the page it fell through to. */457const answered = (result: Promise<Response> | "the page") =>458 result === "the page"459 ? Effect.void460 : Effect.flatMap(
4 unmodified lines
465 vary: response.headers.get("vary"),466 }))467 );468486/** The head's link naming `href` as a page's Markdown. */469const alternate = (href: string) => ({470 href,471 rel: "alternate",472 type: "text/markdown",
117 unmodified lines
modified:apps/web/test/markdown-resolve.test.ts-7 removed
1/**2 * A Markdown file's link or image, resolved into the project at the commit3 * it was read at: a fragment and anything with a scheme stay as written,4 * `/x` starts at the repo root, anything else starts at the file's5 * directory, `..` stops at the root, and a query and a fragment survive.6 * Links open the file's page, media its raw bytes, always at the SHA.7 */1import { describe, expect, it } from "@effect/vitest";2import { CommitSha, ProjectName } from "@repo/protocol/ids";34import { resolveRepoUrl } from "../src/features/markdown/resolve.ts";
69 unmodified lines
modified:apps/web/test/markdown.test.tsx-13 removed
1/**2 * A project's Markdown file, rendered to HTML with `react-dom/server`, as3 * the Worker renders it: GitHub-flavoured Markdown and the README's own4 * HTML, its links and images pointing into the project at the commit it5 * was read at, and nothing that could run script or post a form.6 */1import { describe, expect, it } from "@effect/vitest";2import { CommitSha, ProjectName } from "@repo/protocol/ids";3import {4 RouterContextProvider,
15 unmodified lines
20const sha = CommitSha.make("0123456789abcdef0123456789abcdef01234567");2122const project = ProjectName.make("oscabriel/p");2330/** The file `<dir>/README.md` at `sha`, rendered with no router around it, as a view's test renders it. */24const rendered = (source: string, dir = "") =>25 renderToString(26 <RepoMarkdown at={sha} dir={dir} project={project} source={source} />27 );2836/** The same, inside a router at `location`, as the app renders it. */29const routed = (element: ReactElement, location = "/p") =>30 renderToString(31 <RouterContextProvider32 router={createRouter({
4 unmodified lines
37 {element}38 </RouterContextProvider>39 );4049/** Each `<a …>` opening tag in `markup`. */41const anchorsOf = (markup: string) => markup.match(/<a\b[^>]*>/gu) ?? [];4243describe("what a README cannot carry", () => {44 it("drops a script and what it says", () => {
47 unmodified lines
92 expect(markup).toMatch(/(?:id|name)="user-content-top"/u);93 });94});95105/** `docs/README.md`, rendered. */96const readme = (source: string) => rendered(source, "docs");9798describe("links and images in docs/README.md", () => {99 it("loads a relative image raw from the README's folder, at the SHA", () => {
135 unmodified lines
235236 describe("a footnote", () => {237 const markup = rendered("Text[^1]\n\n[^1]: Note.");238249 /** The `href` of the anchor carrying `attribute`, without its `#`. */239 const targetOf = (attribute: string) =>240 anchorsOf(markup)241 .find((anchor) => anchor.includes(attribute))242 ?.match(/href="#(?<id>[^"]+)"/u)?.groups?.id;243255 /** The `id` of the element whose opening tag carries `attribute`. */244 const idOf = (attribute: string) =>245 new RegExp(`<[a-z]+\\b[^>]*${attribute}[^>]*>`, "u")246 .exec(markup)?.[0]247 .match(/\bid="(?<id>[^"]+)"/u)?.groups?.id;
50 unmodified lines
298 expect(rendered("hi")).toMatch(/class="[^"]*\bprose\b[^"]*"/u);299 });300});301314/** The classes on the prose wrapper of a README with code and a title. */302const proseClasses = () => {303 const markup = rendered(304 "# datekit\n\nCall `format()` first.\n\n```ts\nconst a = () => 1;\n```"305 );
64 unmodified lines
modified:apps/web/test/markup.ts-12 removed
1/**2 * How the shared parts' tests read rendered markup: the markup itself, the3 * text a reader sees (tags dropped, entities decoded), and whether parts4 * of that text come in order.5 */1import type { ReactElement } from "react";2import { renderToStaticMarkup } from "react-dom/server";39/** The entities React writes for text, and what each reads as. */4const ENTITIES: ReadonlyMap<string, string> = new Map([5 ["&#x27;", "'"],6 ["&amp;", "&"],7 ["&gt;", ">"],
3 unmodified lines
1112export const markupOf = (element: ReactElement) =>13 renderToStaticMarkup(element);1421/** What a reader sees of `markup`: the text without its tags, entities decoded. */15export const textIn = (markup: string) =>16 markup17 .replaceAll(/<[^>]+>/gu, "")18 .replaceAll(19 /&(?:#x27|amp|gt|lt|quot);/gu,20 (entity) => ENTITIES.get(entity) ?? entity21 );2230/** What a reader sees of `element`, rendered. */23export const textOf = (element: ReactElement) => textIn(markupOf(element));2433/** Where each of `parts` starts in `text`, each searched after the one before; -1 once one is missing. */25export const positionsInOrder = (text: string, parts: readonly string[]) => {26 const positions: number[] = [];27 let from = 0;28
6 unmodified lines
3536 return positions;37};3848/** Whether every one of `parts` is in `text`, each after the one before. */39export const allInOrder = (text: string, parts: readonly string[]) =>40 positionsInOrder(text, parts).every((at) => at >= 0);4152/** Each opening tag in `markup` that carries `attribute`, as the tag's text. */42export const tagsWith = (markup: string, attribute: string) =>43 [...markup.matchAll(/<[a-z][^>]*>/gu)].flatMap(([tag]) =>44 tag.includes(`${attribute}=`) ? [tag] : []45 );4658/** The value of `attribute` in one opening `tag`. */47export const attributeOf = (tag: string, attribute: string) =>48 new RegExp(`\\b${attribute}="(?<value>[^"]*)"`, "u").exec(tag)?.groups?.value;
modified:apps/web/test/nav.test.tsx-8 removed
1/**2 * A project's section row, rendered to HTML: the seven sections every3 * project page shares, in one line under the page's head where the rail is4 * not drawn, each linking to its page, and only the page being read marked5 * as the current one. Inside the router it draws the router's links; a view6 * rendered alone draws the same addresses as plain links.7 */1import { describe, expect, it } from "@effect/vitest";2import { ProjectName } from "@repo/protocol/ids";3import { Effect } from "effect";4import { renderToStaticMarkup } from "react-dom/server";
2 unmodified lines
7import { renderAt } from "./render.tsx";89const datekit = ProjectName.make("oscabriel/datekit");1018/** Each link in `markup`: its text, its href, and whether it is current. */11const linksOf = (markup: string) =>12 [...markup.matchAll(/<a\b(?<attributes>[^>]*)>(?<text>.*?)<\/a>/gu)].map(13 ({ groups }) => ({14 current: /aria-current="page"/u.test(groups?.attributes ?? ""),
70 unmodified lines
modified:apps/web/test/outcome.test.tsx-7 removed
1/**2 * Where an answer stands, as every page that shows one reads it: a refusal3 * as `git push` printed it, an outcome as one sentence (waiting is never a4 * refusal), and the gate's stages as a results row that says which stages5 * ran, which refused and which the answer never needed.6 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { StageName } from "@repo/protocol/domain/outcome";
16 unmodified lines
21} from "../src/features/shared/outcome.tsx";22import { RefusalView } from "../src/features/shared/refusal.tsx";23import { allInOrder, markupOf, textOf } from "./markup.ts";2431/** Each `<li>` that names a stage, as `[stage, state]`. */25const stagesOf = (element: ReactElement) =>26 [...markupOf(element).matchAll(/<li\b[^>]*>/gu)].flatMap(([tag]) => {27 const stage = /data-stage="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;28 const state = /data-state="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;
255 unmodified lines
modified:apps/web/test/owner-route.test.ts-11 removed
1/**2 * An owner's address alone: `/<handle>` leads to the person's page,3 * `/people/<handle>` in lowercase (handles compare without case), by a 3024 * (a handle may yet become a page of its own); an owner that is no handle,5 * a source host among them, and a word the web keeps for itself are not6 * found. The app's own router reaches the route for `/<handle>` and still7 * reaches its own pages by their words.8 */1import { describe, expect, it } from "@effect/vitest";2import { reservedProjectNames } from "@repo/protocol/ids";3import { isNotFound, isRedirect } from "@tanstack/react-router";4import { Effect } from "effect";
4 unmodified lines
9 Route as OwnerRoute,10} from "../src/routes/$owner/index.tsx";11import { Route as ImportRoute } from "../src/routes/import.tsx";1221/** What the loader's load came to for `owner`: a redirect, a 404, or neither. */13interface Outcome {14 readonly location?: string | null;15 readonly notFound: boolean;16 readonly status?: number;17}1828/** What the route's loader rejects with for `owner`, as an outcome. */19const outcomeFor = (owner: string) =>20 Effect.tryPromise({21 catch: (thrown): Outcome =>22 isRedirect(thrown)
5 unmodified lines
28 : { notFound: isNotFound(thrown) },29 try: () => ownerLoader({ params: { owner } }),30 }).pipe(Effect.flip);3142/** The route the app's own tree finds for `pathname`. */32const routeAt = (pathname: string) => getRouter().getMatchedRoutes(pathname)[2];3334describe("an owner's address alone", () => {35 it.effect(
42 unmodified lines
modified:apps/web/test/people.test.tsx-8 removed
1/**2 * A person's page, rendered inside a router from fixtures decoded with the3 * protocol's own schemas: their credit by project and area, each area one4 * sentence of the roles they hold there, and no number anywhere (the No5 * Score Rule): the counts the read carries are never drawn.6 */1import { describe, expect, it } from "@effect/vitest";2import { CreditSummary } from "@repo/protocol/domain/record";3import { Handle } from "@repo/protocol/ids";4import { Effect, Schema } from "effect";
19 unmodified lines
2425const markupOf = (element: ReactElement) =>26 renderAt(`/people/${handle}`, element);2734/** What a reader sees: the markup without its tags, entities decoded. */28const textOf = (html: string) =>29 html30 .replaceAll(/<[^>]+>/gu, "")31 .replaceAll("&#x27;", "'")32 .replaceAll("&amp;", "&");3341/** The credits: every project's group, from the first to the last. */34const creditsOf = (html: string) => {35 const start = html.indexOf('data-credits=""');36 const end = html.indexOf("</main>", start);37
126 unmodified lines
modified:apps/web/test/pierre.test.ts-8 removed
1/**2 * Every drawing of code takes its options from one module: the theme that3 * reads the web's tokens (so code sits on the paper and follows the scheme4 * with the page), the highlighter, and the limits past which a minified5 * file or a lockfile is drawn as plain text instead of stalling the page.6 * The module touches no DOM and no React, so it loads here, in Node.7 */1import { describe, expect, it, vi } from "@effect/vitest";2import { DEFAULT_TOKENIZE_MAX_LENGTH, resolveTheme } from "@pierre/diffs";3import { Effect } from "effect";4
3 unmodified lines
8 registerCodeTheme,9 treesOptions,10} from "../src/features/code/pierre.ts";1119/** A drawn code box, wider than its pane when it `scrolls`. */12const box = (scrolls: boolean) => ({13 clientHeight: 400,14 clientWidth: 600,15 scrollHeight: 400,
99 unmodified lines
modified:apps/web/test/platform.ts-6 removed
1/**2 * A platform for a test to read from: the contracts it sets up answer, and3 * every other dies on the way (`unanswered`), as the tester.4 */1import { Client, Contracts } from "@repo/protocol/contracts";2import { asTester, unanswered } from "@repo/protocol/testing";3import { Layer } from "effect";4import { RpcTest } from "effect/rpc";510/** A platform that answers only the contracts in `handlers`, each a `Contracts.toLayerHandler` layer. */6export const platformWith = (7 ...handlers: readonly Layer.Layer<never>[]8): Layer.Layer<Client> =>9 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(10 Layer.provide([Layer.mergeAll(unanswered, ...handlers), asTester])11 );1218/** A platform that cannot be reached: every call dies on the way. */13export const unreachablePlatform: Layer.Layer<Client> = platformWith();
modified:apps/web/test/production-bundle.test.ts+6 added-65 removed
1/**2 * The web as it deploys (AGENTS.md principle 6): the production3 * `vite build`, run as `infra/deploy.ts` and bytes:check run it4 * (`NODE_ENV=production`), into a folder of its own, once for every test5 * here. Its client output carries the web app manifest and every icon the6 * manifest names; its server output serves `llms.txt` (the platform's and7 * each project's) and the MCP card, and passes the skills, the install8 * script and the releases on; `#backend` resolves to the forward to9 * `PLATFORM`; and nothing in it comes from the dev world: no `src/dev/`10 * module, no memory adapter, no seed, no dev sign-in and no test kit.11 *12 * Its root route, whose chunks every page preloads, carries no Markdown13 * renderer, no grammar and nothing of the server's highlighting, and stays14 * under a size ceiling, and the hashed assets it serves are kept by15 * browsers for good (`public/_headers`). The Worker bundles the grammars16 * it highlights in and no others, none on its entry, and no theme17 * collection or WebAssembly (ADR 0027).18 *19 * Modules are read from the build's source maps (each map's `sources`),20 * strings from every other file it wrote. The Cloudflare plugin rewrites21 * `.wrangler/deploy/config.json` at each build to point at its output; the22 * redirect is put back as it was, so a deploy never follows it into a23 * folder this test removed.24 */1// The Cloudflare plugin rewrites `.wrangler/deploy/config.json` at each build to point at its output;2// the redirect is put back as it was, so a deploy never follows it into a folder this test removed.3import { NodeServices } from "@effect/platform-node";4import { expect, layer } from "@effect/vitest";5import { Brand } from "@repo/brand";6import {
7 unmodified lines
14 Stream,15} from "effect";16import { ChildProcess, ChildProcessSpawner } from "effect/process";1740/** A production build takes a few seconds; a cold one on a busy machine, longer. */18const BUILD = 180_000;1943/** Text only the dev world, the test kit or the memory adapters' engine carry. */20const DEV_STRINGS = [21 "src/dev/",22 "devWorld",23 "seedDev",
4 unmodified lines
28 "@repo/testkit",29 "isomorphic-git",30] as const;3156/** The memory adapters the dev world runs on, as module folders. */32const DEV_MODULES = [33 "packages/project/src/project-store/memory",34 "packages/artifacts/src/repo-host/memory",35] as const;3662/**63 * The most the chunks every page preloads (the root route's) may weigh,64 * gzipped: about 10% above what they weighed (244,172 bytes in 47 chunks)65 * once the landing read its projects on the server (243,991 before; 222,16966 * in 19 chunks when the Markdown renderer left them, 322,049 in 31 before67 * that). Raised on the user's sign-off, 2026-10-10. A route's `head`,68 * `loader` and server functions ride in the route tree every page loads,69 * so what they import counts here; its view does not, and the landing's70 * must not: the next case holds it out.71 */37// About 10% above what the root's preloads weighed once the landing read its projects on the server.38// A route's `head`, `loader` and server functions ride in the route tree every page loads, so what they import counts here.39const ROOT_PRELOADS_GZIP = 268_000;4074/** A Shiki grammar module, by its name. */41const GRAMMAR = /node_modules\/@shikijs\/langs\/dist\/(?<name>[\w-]+)\.mjs$/u;4277/**78 * The grammars the Worker highlights in (`features/code/prerender-server.ts`,79 * ADR 0027), by Shiki's module names: HTML brings JavaScript and CSS with it.43// By Shiki's module names: HTML brings JavaScript and CSS with it.80 */44const SERVER_GRAMMARS = [45 "css",46 "html",47 "javascript",
6 unmodified lines
54 "typescript",55 "yaml",56];5795/** Whether a file's modules hold the server's highlighting. */58const drawing = (held: readonly string[]) =>59 held.some((module) => module.endsWith("features/code/prerender-server.ts"));6099/** Files whose bytes are not text: fonts and images. */61const BINARY = /\.(?:ico|png|woff2)$/u;6263const decodeSourceMap = Schema.decodeUnknownEffect(64 Schema.fromJsonString(Schema.Struct({ sources: Schema.Array(Schema.String) }))
9 unmodified lines
74 })75 )76);77117/** What one build wrote. */78interface Output {119 /** Every file but the source maps, by its path under the output folder, as text. */79 readonly texts: ReadonlyMap<string, string>;121 /** Every path the build wrote, under the output folder. */80 readonly paths: ReadonlySet<string>;123 /** Every module it bundled, by its path from the repo root, without a query. */81 readonly modules: ReadonlySet<string>;125 /** The modules each file holds, by the file's path under the output folder. */82 readonly holding: ReadonlyMap<string, readonly string[]>;83}8485const where = Effect.gen(function* () {
2 unmodified lines
8889 return { repo: path.resolve(web, "../.."), web };90});91136/** Puts the Cloudflare plugin's deploy redirect back as it was when the scope ends. */92const keepDeployRedirect = (web: string) =>93 Effect.gen(function* () {94 const fs = yield* FileSystem.FileSystem;95 const path = yield* Path.Path;
7 unmodified lines
103 }).pipe(Effect.orDie)104 );105 });106152/** The modules a source map at `map` names, from the repo root. */107const modulesIn = (map: string, text: string, repo: string) =>108 Effect.gen(function* () {109 const path = yield* Path.Path;110 const { sources } = yield* decodeSourceMap(text);
5 unmodified lines
116 )117 );118 });119166/** Reads every file under `out`: the source maps as modules, the rest as text. */120const readOutput = (out: string, repo: string) =>121 Effect.gen(function* () {122 const fs = yield* FileSystem.FileSystem;123 const path = yield* Path.Path;
27 unmodified lines
151152 return { holding, modules, paths, texts } satisfies Output;153 });154202/** The web's production build, into a folder of its own, read back whole. */155const productionBuild = Effect.gen(function* () {156 const fs = yield* FileSystem.FileSystem;157 const path = yield* Path.Path;158 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
26 unmodified lines
185186 return yield* readOutput(out, repo);187}).pipe(Effect.scoped, Effect.orDie, Effect.provide(NodeServices.layer));188237/** The one production build every test here reads. */189class Built extends Context.Service<Built, Output>()("test/Built") {}190240/** The files under `folder` of the output, as text. */191const textsUnder = (output: Output, folder: "client" | "server") =>192 [...output.texts].filter(([at]) => at.startsWith(`${folder}/`));193244/** Whether some file under `folder` holds `pattern`. */194const holds = (output: Output, folder: "client" | "server", pattern: RegExp) =>195 textsUnder(output, folder).some(([, text]) => pattern.test(text));196248/** A route's path, as the route tree spells it in a quoted string. */197const routePath = (path: string) =>198 new RegExp(199 `(?<quote>["'\`])${path.replaceAll(/[$.]/gu, "\\$&")}\\k<quote>`,200 "u"201 );202255/**256 * The chunks every page preloads: the root route's, as Start's manifest in257 * the server output names them (`/assets/…`).258 */203const rootPreloads = (output: Output) => {204 const manifest = textsUnder(output, "server").find(([at]) =>205 at.includes("tanstack-start-manifest")206 )?.[1];
11 unmodified lines
218 ([chunk]) => chunk219 );220};221278/** `text`'s size gzipped, in bytes. */222const gzipped = (text: string) =>223 Stream.fromReadableStream({224 evaluate: () =>225 new Blob([text]).stream().pipeThrough(new CompressionStream("gzip")),
52 unmodified lines
278 ).toStrictEqual([]);279 })280 );281339 // A build that resolves `#backend` to `src/dev/backend.ts` fails here340 // (`devBackend`) and in the next case (the dev world's modules): checked341 // by a planted fault, once the dev world had its code.282 // A build that resolves `#backend` to `src/dev/backend.ts` fails here and in the next case.283 it.effect("resolves #backend to the forward to PLATFORM", () =>284 Effect.gen(function* () {285 const output = yield* Built;286
150 unmodified lines
modified:apps/web/test/project-people.test.tsx-21 removed
1/**2 * A project's policy page (its route is `/$project/people`), rendered to HTML with `react-dom/server` from3 * fixtures decoded with the protocol's own schemas (`PublicPolicy` from4 * `projectPolicy`, `Ledger` from `ledger`): who decides which paths, who is5 * vouched for and denounced, each layer's readers and writers, the caps,6 * budget and timings, and where each comes from at the landed commit. The7 * page is read-only, and it shows nothing the two contracts don't carry.8 */1import { describe, expect, it } from "@effect/vitest";2import { commandDocs } from "@repo/agent-kit/command-doc";3import { Brand } from "@repo/brand";4import { Client, Contracts } from "@repo/protocol/contracts";
20 unmodified lines
25const decodePolicy = Schema.decodeSync(PublicPolicy);2627const decodeLedger = Schema.decodeSync(Ledger);2837/** What every policy below shares: the parts the page doesn't show. */29const unshown = {30 judge: { paths: [`${Brand.configDir}/**`], pointers: [] },31 kinds: [],32 modules: [],
1 unmodified line
34 run: { checks: { unit: "bun test" }, test: "bun test {path}" },35 weakening: { markers: [] },36};3747/** datekit's evaluated config folder at `sha`, as `projectPolicy` returns it. */38const datekitPolicy = decodePolicy({39 ...unshown,40 agents: "trailer",41 at: sha,
14 unmodified lines
56 { denounced: true, handle: "spam-bot", note: "opened 40 proposals" },57 ],58});5970/** datekit's ledger: one maintainers layer. */60const datekitLedger = decodeLedger({61 entries: [],62 layers: [63 {
12 unmodified lines
76 postureLabel: "Open with sealed evidence",77 project: "datekit",78});7991/** An imported repo with no `project.ts` in its config folder: the platform's defaults, its initializer deciding. */80const burrowPolicy = decodePolicy({81 ...unshown,82 agents: "trailer",83 at: sha,
6 unmodified lines
90 vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },91 vouches: [],92});93106/** Why an import with no config folder, whose defaults found no test command, has no policy at `sha`. */94const noConfig = Schema.decodeSync(PolicyPending)({95 at: sha,96 reason: "noConfig",97});
14 unmodified lines
112 unevaluated={Option.none()}113 />114);115129/** The markup of the section whose heading has the id `id`. */116const sectionOf = (markup: string, id: string) => {117 const heading = markup.indexOf(`id="${id}"`);118119 return heading === -1120 ? ""121 : elementWith(markup.slice(markup.lastIndexOf("<section", heading)), "");122};123138/**139 * Each shell line the page offers to copy, as typed: one command, its140 * continuation lines (` \` then a new line) joined back into one.141 */124const commandsOf = (markup: string) =>125 [126 ...markup.matchAll(/<code\b[^>]*select-all[^>]*>(?<line>.*?)<\/code>/gsu),127 ].map((found) =>128 plainText((found.groups?.line ?? "").replaceAll(/ \\\n\s*/gu, " ")).trim()129 );130149/** The CLI command a line runs: the longest command path it starts with. */131const commandOf = (line: string) =>132 commandDocs(Contracts)133 .filter(({ path }) => line.startsWith(`${Brand.cli} ${path.join(" ")} `))134 .toSorted((one, other) => other.path.length - one.path.length)135 .at(0);136156/** Each deciders row's text, in order. */137const decidersOf = (markup: string) =>138 elementsWith(mainOf(markup), "data-paths=").map((row) =>139 plainText(row).trim()140 );
385 unmodified lines
526 expect(textOf(view)).toContain("Open: nothing is held back");527 });528});529550/** A platform that knows only datekit, counting the reads it is asked for. */530const platformOf = (531 asked: Ref.Ref<number>,532 read: {533 readonly policy?: PublicPolicy;
131 unmodified lines
modified:apps/web/test/project.test.tsx-29 removed
1/**2 * A project's home, which is its list of asks: read on the server by the3 * route's loader (its asks, its own ledger, its events, its policy, its4 * README) and rendered inside the router. Its asks come first, a family5 * expanded as a fan with its children listed; then its README; beside them,6 * how a change lands here, with the commands that take part and the last7 * landings as one-line credits. A child that lands while the page is open8 * stamps its node once.9 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import { AskListing } from "@repo/protocol/domain/ask";
54 unmodified lines
59import { markupOf, textIn, textOf } from "./markup.ts";60import { renderAt } from "./render.tsx";61import { reachingTransport } from "./transport.ts";6272/** The markup of the row for `ask`: from its `<li>` to the next row or the list's end. */63const rowOf = (markup: string, ask: string) => {64 const start = markup.indexOf(`data-ask="${ask}"`);6566 const ends = ['data-ask="', "</ul></section>", "</main>"].flatMap((end) => {
4 unmodified lines
7172 return start === -1 ? "" : markup.slice(start, Math.min(...ends));73};7485/** Which of `parts` `text` does not hold. */75const missingFrom = (text: string, parts: readonly string[]) =>76 parts.filter((part) => !text.includes(part));7789/** Which of `parts` `text` holds. */78const foundIn = (text: string, parts: readonly string[]) =>79 parts.filter((part) => text.includes(part));8093/** The page's main pane, the inline facts left in (they sit after its head). */81const mainOf = (markup: string) =>82 markup.slice(markup.indexOf("<main"), markup.indexOf("</main>"));8397/** The inspector, as the shell's width shows it. */84const inspectorOf = (markup: string) =>85 markup.slice(markup.indexOf('data-facts="inspector"'));8687const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");
74 unmodified lines
162 id: AskId.make("drop-legacy-parse"),163 kind: KindName.make("migrate"),164};165180/** A landing of `ask` (or an opening of it), credited to `answerer`. */166const landingOf = (167 sha: string,168 more: { readonly ask?: string; readonly opened?: string },169 answerer?: string
419 unmodified lines
589 expect(ledeOf("# title\n\n| a | b |\n| - | - |\n")).toBeUndefined();590 });591});592608/** The contracts over HTTP, each request answered by `answer`. */593const clientOver = (answer: (request: Request) => Promise<Response>) =>594 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(595 Layer.provide(RpcClient.layerProtocolHttp({ url: "http://localhost/rpc" })),596 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),
3 unmodified lines
600 )601 )602 );603620/**621 * `handler`, but with the list of projects failing when `listed` counts its622 * calls.623 */604const failingProjects =605 (606 handler: (request: Request) => Promise<Response>,607 listed: Ref.Ref<number> | undefined
12 unmodified lines
620 return yield* Effect.promise(() => handler(request));621 })622 );623644/**645 * A fresh dev world with `options`, served; with `listed`, its list of646 * projects fails and each call to it is counted. The world ends with the647 * scope.648 */624const devWorldWith = (options: DevWorldOptions, listed?: Ref.Ref<number>) =>625 Layer.unwrap(626 Effect.gen(function* () {627 const { dispose, handler } = devServer(options);
5 unmodified lines
633 );634635const devWorld = devWorldWith({});636662/** A platform that does not answer: every call comes back a 503. */637const unanswering = clientOver(() =>638 Promise.resolve(new Response("", { status: 503 }))639);640667/** A platform that knows every project and has landed nothing on any. */641const nothingLanded = Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(642 Layer.provide([643 Layer.mergeAll(644 unanswered,
7 unmodified lines
652);653654const decodePage = Schema.decodeEffect(ProjectPageData);655683/** An input's opening tag, by its `name`. */656const inputNamed = (markup: string, name: string) =>657 new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";658659/** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */660const seededWorld = { timeout: 30_000 };661690/** The page as the route draws it from what its loader read. */662const sentFrom = (663 data: ProjectPageData,664 more: Partial<ProjectViewProps> = {}665) => {
342 unmodified lines
modified:apps/web/test/proposal.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/propose.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/records.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/refs.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/render.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/rev.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/root.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/routes.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/row.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/rpc-route.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/seeded.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/server-params.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/session.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/shared.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/shell.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/status-line.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/today.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/tokens.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/transport.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/type-floor.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/watch.test.tsnot shown

Its text is not shown, modified.

modified:apps/web/test/why.test.tsxnot shown

Its text is not shown, modified.

modified:apps/web/test/workers-shim.tsnot shown

Its text is not shown, modified.

modified:apps/web/playwright.config.ts-11 removed
1import { defineConfig, devices } from "@playwright/test";23/**4 * The Playwright check of a deployed web, never part of verify:5 * vitest runs only `test/`, and this runs only `e2e/*.e2e.ts`, against the stage6 * `WEB_URL` names (the spec skips itself without one). From `apps/web`:7 *8 * bunx playwright install chromium9 * WEB_URL=https://web-dev-oscabriel.oscargabriel.workers.dev bun run e2e10 *11 * Each page's screenshot lands in `e2e/out/` (gitignored), for the shot12 * list; Playwright's own traces and failures go to `e2e/out/results/`.13 */3export default defineConfig({4 forbidOnly: true,5 outputDir: "e2e/out/results",6 projects: [
16 unmodified lines
modified:apps/web/vite.config.tsnot shown

Its text is not shown, modified.

modified:apps/web/vitest.config.tsnot shown

Its text is not shown, modified.