Merge build/comments-web-rest into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
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
Provenance
- Commit
0eb1248- Tree
ca503d4- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
74bfc72- Parent 2
6c40d07
199 files changed+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- */1 import { expect, test } from "@playwright/test";2 import type { Browser, BrowserContext, Page } from "@playwright/test";3 import { Brand } from "@repo/brand";4 import { Config, Effect, Option } from "effect";18 unmodified lines23 24 const at = (path: string) =>25 `${Option.getOrElse(settings.web, () => "")}${path}`;26 52-/** The decider the dev world signs in. */27 const DECIDER = "ines-v";28 55-/** A page to visit: where, whether a decider must be signed in, what it answers. */29 interface Visit {30 readonly name: string;31 readonly path: string;32 readonly signedIn?: boolean;33 readonly status?: number;34 }35 63-/**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.37 const COMMIT = "<the newest ask opening>";38 70-/** Every page group, over the fixture project's states. */39 const VISITS: readonly Visit[] = [40 { name: "landing", path: "/" },41 { name: "front", path: "/asks" },42 { name: "front, signed in", path: "/asks", signedIn: true },79 unmodified lines122 const SCHEMES = ["light", "dark"] as const;123 124 const WIDTHS = [1440, 390] as const;125 158-/**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.127 const FORBIDDEN =128 /\b(?:review|reviewer|approve|approval|PR|pull request|issue|merge|lease|reputation|inbox|queue|dashboard|explore|trending|nit)\b/iu;129 165-/**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.131 const NOT_OURS =132 "[data-readme], [data-code], [data-diff], [data-said], [data-refusal], [data-term], script, style, noscript";133 175-/** A context for `scheme` at `width`, signed in as the decider when asked. */134 const contextFor = (135 browser: Browser,136 scheme: (typeof SCHEMES)[number],137 width: number,17 unmodified lines155 156 return context;157 });158 201-/** The newest landing's commit page, read from the landings page. */159 const commitPath = (context: BrowserContext) =>160 Effect.gen(function* () {161 const page = yield* Effect.promise(() => context.newPage());162 10 unmodified lines173 174 return href ?? `/${project}/commits/main`;175 });176 220-/** Open `path` and let the browser take the page over. */177 const open = (page: Page, path: string) =>178 Effect.gen(function* () {179 const response = yield* Effect.promise(() =>180 page.goto(at(path), { waitUntil: "load" })181 );182 227- // 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));185 186 return response?.status();187 });188 233-/** The page's own words that the web keeps off its screens. */189 const forbiddenOn = (page: Page) =>190 Effect.promise(() =>191 page.evaluate(192 ({ forbidden, notOurs }) => {101 unmodified lines294 ));295 }296 });297 343-/** What has focus: its tag, its name, and the landmark it sits in. */298 const focused = (page: Page) =>299 Effect.promise(() =>300 page.evaluate(() => {301 // Focus inside a drawing's shadow root (a code box, the file tree) is12 unmodified lines314 315 const style = getComputedStyle(element);316 const after = getComputedStyle(element, "::after");317 364- // 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 lines331 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 );342 392-/**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.344 const tabStops = (page: Page, limit: number, settle = 0) =>345 Effect.gen(function* () {346 const stops: NonNullable<Effect.Success<ReturnType<typeof focused>>>[] = [];347 15 unmodified lines363 364 return stops;365 });366 420-/** A page on its own context, for a keyboard walk. */367 const keyboardPage = (368 browser: Browser,369 path: string,370 width: number,25 unmodified lines396 397 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);401 402 return Effect.runPromise(403 Effect.gen(function* () {54 unmodified lines458 Effect.runPromise(459 Effect.gen(function* () {460 const { context, page } = yield* keyboardPage(browser, "/asks", 1440);461 517- // 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 lines525 yield* Effect.promise(() => page.waitForTimeout(400));526 527 expect(searchOf(page).get(param)).toBe(firstSelected);528 586- // The switch: off, `j` does nothing; `?` still opens the dialog.529 yield* Effect.promise(() => page.keyboard.press("?"));530 531 const dialog = page.getByRole("dialog", { name: "Keys" });532 35 unmodified lines568 );569 570 const ask = searchOf(page).get("ask") ?? "";571 630- // 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 linesmodified: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- */1 import type { Page } from "@playwright/test";2 import { Effect, Schema } from "effect";3 9-/** axe-core, from cdnjs, at the version this check was written against. */4 const AXE = "https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.10.2/axe.min.js";5 12-/** What axe's `run` resolves to, as much of it as this check reads. */6 const AxeRun = Schema.Struct({7 violations: Schema.Array(8 Schema.Struct({9 id: Schema.String,6 unmodified lines16 });17 18 const decodeAxeRun = Schema.decodeUnknownEffect(AxeRun);19 27-/** axe's serious and critical violations on the page, as `rule (n): targets`. */20 export const axeOn = (page: Page) =>21 Effect.gen(function* () {22 yield* Effect.promise(() => page.addScriptTag({ url: AXE }));23 32- // 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 lines37 .join(", ")}`38 );39 });40 50-/** How far the page scrolls sideways, in px; 0 when it does not. */41 export const sideways = (page: Page) =>42 Effect.promise(() =>43 page.evaluate(44 () =>4 unmodified linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import { Config, Effect, Option } from "effect";3 17-/** Where the web lives. */4 const web = Effect.runSync(5 Config.option(Config.NonEmptyString("WEB_URL")).pipe(6 Effect.map(Option.map((url) => url.replace(/\/+$/u, "")))7 )8 );9 24-/** Pages that show command lines to a reader who is not signed in. */10 const PAGES = ["/today", "/home", "/agents"];11 12 const WIDTHS = [390, 1280];13 36 unmodified lines50 );51 52 const word = span.getBoundingClientRect();53 69- // 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 linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import type { Page } from "@playwright/test";3 import { ProjectName } from "@repo/protocol/ids";4 import { Config, Effect, Option } from "effect";5 23-/**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- */6 const examples = {7 burrow: {8 ask: "drop-legacy-fetch",9 file: "packages/kit/src/http.ts",5 unmodified lines15 readme: "Small, dependency-free date helpers",16 },17 } as const;18 41-/** What the check reads of its env: where the web lives, and which ask to look at. */19 const 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 lines45 );46 47 const { ask, file: FILE, project, readme: README_PHRASE } = settings;48 73-/** The root folder `FILE` sits in, which the project's code page lists. */49 const FOLDER = FILE.split("/")[0] ?? FILE;50 76-/** Where each page's screenshot goes: `e2e/out/<shot>.png`. */51 const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);52 79-/** What every page that could not reach the platform says instead of its content. */53 const UNREACHABLE = "The platform did not answer";54 82-/** What a code page said before its view was built; a deployed page never says it. */55 const NOT_BUILT = "not built";56 85-/** `url` on the web. */57 const at = (path: string) =>58 `${Option.getOrElse(settings.web, () => "")}${path}`;59 89-/**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.61 const page = (62 browser: Page,63 path: string,64 shot: string,23 unmodified lines88 browser.screenshot({ fullPage: true, path: `${out}${shot}.png` })89 );90 });91 127-/** A code page: as `page` checks one, and it never says it is not built. */92 const code = (93 browser: Page,94 path: string,95 shot: string,6 unmodified lines102 expect(browser.getByText(NOT_BUILT)).toHaveCount(0)103 );104 });105 142-/**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- */106 const markdown = (107 browser: Page,108 path: string,109 shot: string,36 unmodified lines146 Option.isNone(settings.web),147 "WEB_URL is not set: point it at a deployed web's origin to run this check"148 );149 190- // 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 lines157 Effect.runPromise(158 page(browser, `/${project}`, "project-page", [project, ask])159 ));160 203- // 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 lines211 expect(new URL(browser.url()).hash).toBe("#L3");212 })213 ));214 258- // 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 linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import { Config, Effect, Option, Redacted } from "effect";3 4 const settings = Effect.runSync(12 unmodified lines17 };18 })19 );20 36-/** Where the screenshot goes: `e2e/out/import.png`. */21 const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);22 39-/** An import clones the repo: up to half a minute, and some margin. */23 const IMPORTING = 90_000;24 25 test.describe("a web import", () => {26 test.skip(73 unmodified linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import type { Page } from "@playwright/test";3 import { Brand } from "@repo/brand";4 import { ProjectName } from "@repo/protocol/ids";5 import { Config, Console, Effect, Option, Schema } from "effect";6 29-/** One imported project: where its pages look, and what they must show. */7 interface 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 }15 48-/** The eight imports, in the order the script imports them. */16 const imports: readonly Imported[] = [17 {18 dir: "tests/ui",19 entry: "tests/ui/chained-comparison.rs",34 unmodified lines54 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 lines79 readme: "Fuzzel is a Wayland-native application launcher",80 },81 ];82 117-/** One of the well-known imports: a file at its root of at least five lines, and its README's name. */83 interface Known {84 readonly project: string;85 readonly file: string;86 readonly readme: string;87 }88 124-/** The thirty well-known imports, in the order the script imports them. */89 const 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 lines118 { file: "Gemfile", project: "sinatra", readme: "README.md" },119 { file: "package.json", project: "nvm", readme: "README.md" },120 ];121 158-/** What the check reads of its env: where the web lives, and which imports to visit. */122 const settings = Effect.runSync(123 Effect.gen(function* () {124 return {125 only: yield* Config.option(Config.NonEmptyString("WEB_IMPORTS")),4 unmodified lines130 };131 })132 );133 171-/**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- */134 const nameOf = (spelled: string): ProjectName =>135 Schema.decodeSync(ProjectName)(spelled);136 179-/** `text` as a regular expression matches it, literally. */137 const escaped = (text: string) =>138 text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");139 183-/** A project's address on the web: its full name. */140 const homeOf = (project: string) => `/${nameOf(project)}`;141 186-/**187- * Those of `all` this run visits: `WEB_IMPORTS`' full names188- * (`github.com/pallets/click`), or all of them.189- */142 const visitedOf = <A extends { readonly project: string }>(143 all: readonly A[]144 ): readonly A[] =>145 Option.match(settings.only, {8 unmodified lines154 });155 156 const visited = visitedOf(imports);157 206-/** Where screenshots go: `e2e/out/imports/<project>/<shot>.png`. */158 const out = decodeURIComponent(159 new URL("out/imports/", import.meta.url).pathname160 );161 211-/** What a page says when the platform did not answer it. */162 const UNREACHABLE = "The platform did not answer";163 214-/** What a code page said before its view was built. */164 const NOT_BUILT = "not built";165 217-/** What the router's error boundary says when a page throws. */166 const CRASHED = "Something went wrong";167 220-/** `path` on the web. */168 const at = (path: string) =>169 `${Option.getOrElse(settings.web, () => "")}${path}`;170 171 const awaited = <A>(promise: () => Promise<A>) => Effect.promise(promise);172 226-/** The page says none of the things a broken page says. */173 const whole = (browser: Page) =>174 Effect.forEach(175 [UNREACHABLE, NOT_BUILT, CRASHED],176 (text) => awaited(() => expect(browser.getByText(text)).toHaveCount(0)),7 unmodified lines184 path: `${out}${project}/${shot}.png`,185 })186 );187 242-/**243- * Opens `path`, checks it answered 200, waits for each of `texts` and244- * `selectors`, checks it is whole, and saves the screenshot `shot`.245- */188 const visit = (189 browser: Page,190 project: string,191 path: string,25 unmodified lines217 yield* whole(browser);218 yield* shoot(browser, project, shot);219 });220 279-/**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- */221 const timed = (222 browser: Page,223 project: string,224 path: string,24 unmodified lines249 yield* whole(browser);250 yield* shoot(browser, project, shot);251 });252 316-/** An image on the page has loaded its bytes. */253 const loaded = (browser: Page, selector: string) =>254 awaited(() =>255 expect256 .poll(() =>6 unmodified lines263 )264 .toBeGreaterThan(0)265 );266 331-/** The newest commit's page, as the log links it. */267 const newestCommit = (browser: Page, project: string) =>268 Effect.gen(function* () {269 const response = yield* awaited(() =>270 browser.goto(at(`${homeOf(project)}/commits/main`))13 unmodified lines284 285 return href ?? "";286 });287 353-/**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- */288 const 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 });295 366-/** The pages every import shows. */296 const pages = ({ dir, entry, evaluated, file, project, readme }: Imported) => {297 const timedProject = project === "changesets" || project === "click";298 299 test(`${project}'s home renders its README and the clone box`, ({147 unmodified lines447 ));448 }449 };450 522-/** The pages each well-known import shows. */451 const knownPages = ({ file, project, readme }: Known) => {452 test(`${project}'s home renders its ${readme}`, ({ page: browser }) =>453 Effect.runPromise(454 visit(45 unmodified lines500 })501 ));502 };503 576-/** What each repo was picked to exercise. */504 const 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 lines536 [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 lines559 [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 );570 648- // Scoped tags (`@changesets/cli@…`), on whichever page of 100 holds one.571 let from = 0;572 let found = false;573 574 while (!found && from < 1000) {37 unmodified lines612 [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 lines636 [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 lines656 [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 lines669 [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 );680 763- // 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 linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import { Config, Effect, Option } from "effect";3 4 import { axeOn, sideways } from "./axe.ts";5 18-/** Where the web lives. */6 const web = Effect.runSync(7 Config.option(Config.NonEmptyString("WEB_URL")).pipe(8 Effect.map(Option.map((url) => url.replace(/\/+$/u, "")))9 )10 );11 12 const at = (path: string) => `${Option.getOrElse(web, () => "")}${path}`;13 27-/** The narrowest phone the web is drawn for. */14 const NARROWEST = 360;15 16 test.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 );21 36- // 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 linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import { ProjectName } from "@repo/protocol/ids";3 import { Config, Effect, Option } from "effect";4 14-/** What the check reads of its env: where the web lives, and which project to look at. */5 const 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 lines17 );18 19 const { project } = settings;20 32-/** Where the screenshot goes: `e2e/out/people.png`. */21 const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);22 35-/** What every page that could not reach the platform says instead of its content. */23 const UNREACHABLE = "The platform did not answer";24 25 test.describe("the deployed policy page", () => {26 test.skip(13 unmodified lines40 );41 42 expect(response?.status()).toBe(200);43 57- // 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 linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import { ProjectName } from "@repo/protocol/ids";3 import { Config, Effect, Option } from "effect";4 18-/** What the check reads of its env: where the web lives, and which project to look at. */5 const 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 lines17 );18 19 const { project } = settings;20 36-/** The package whose tags the check follows. */21 const PACKAGE = "@changesets/cli";22 39-/** Where the screenshot goes: `e2e/out/tags.png`. */23 const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);24 42-/** What every page that could not reach the platform says instead of its content. */25 const UNREACHABLE = "The platform did not answer";26 27 const awaited = <A>(promise: () => Promise<A>) => Effect.promise(promise);28 47-/** A tag's release numbers (`@changesets/cli@2.27.1` → 2, 27, 1). */29 const numbersOf = (tag: string) =>30 (tag.slice(tag.lastIndexOf("@") + 1).match(/\d+/gu) ?? [])31 .slice(0, 3)32 .map(Number);33 53-/** `one` is no older than `other` by their first three numbers. */34 const noOlder = (one: readonly number[], other: readonly number[]) => {35 const at = one.findIndex((value, index) => value !== (other[index] ?? 0));36 37 return at === -1 || (one[at] ?? 0) > (other[at] ?? 0);17 unmodified lines55 );56 57 expect(response?.status()).toBe(200);58 79- // The first view: the package list, holding the package.59 const row = browser.locator(`[data-package="${PACKAGE}"]`);60 61 yield* awaited(() => expect(row).toBeVisible());62 4 unmodified lines67 expect(href).toBe(68 `/${project}/refs?package=${encodeURIComponent(PACKAGE)}`69 );70 92- // Its link: that package's tags alone, newest first.71 yield* awaited(() => browser.goto(`${web}${href ?? ""}`));72 73 const tags = browser.locator("[data-tag]");74 22 unmodified lines97 yield* awaited(() =>98 browser.screenshot({ fullPage: true, path: `${out}tags.png` })99 );100 123- // The newest tag's tree opens.101 const tree = yield* awaited(() =>102 tags.first().locator("a").first().getAttribute("href")103 );104 17 unmodified linesmodified: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- */1 import { expect, test } from "@playwright/test";2 import { Brand } from "@repo/brand";3 import { ProjectName } from "@repo/protocol/ids";4 import { Config, Effect, Option } from "effect";5 22-/** What the check reads of its env: where the web lives, and which file to look at. */6 const 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 lines27 );28 29 const { path, project } = settings;30 49-/** Where the screenshot goes: `e2e/out/why.png`. */31 const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);32 52-/** What every page that could not reach the platform says instead of its content. */33 const UNREACHABLE = "The platform did not answer";34 35 test.describe("the deployed why page", () => {36 test.skip(13 unmodified lines50 );51 52 expect(response?.status()).toBe(200);53 74- // 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 linesmodified: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.3 import { resolveConfig } from "vite";4 5 await resolveConfig(6 {5 unmodified linesmodified: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- */1 import type {2 AskId,3 CommitSha,4 LandedSha,2 unmodified lines7 8 import { ContractsClient } from "../surfaces.ts";9 import { keys } from "./keys.ts";10 18-/** The verdict on the ask's latest answer, or on the answer whose head is `head`. */11 export const verdictAtom = (12 project: ProjectName,13 ask: AskId,14 head?: CommitSha3 unmodified lines18 head === undefined ? { ask, project } : { ask, head, project },19 { reactivityKeys: keys.ask(project, ask) }20 );21 30-/** The landing at `sha`, with its credit trailers. */22 export const landingAtom = (project: ProjectName, sha: LandedSha) =>23 ContractsClient.query(24 "landing",25 { project, sha },2 unmodified linesmodified: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- */1 import type { AskId, ProjectName } from "@repo/protocol/ids";2 import { AsyncResult, Atom } from "effect/reactivity";3 4 import { ContractsClient } from "../surfaces.ts";5 import { keys } from "./keys.ts";6 13-/** The ask and its brief. */7 export const askAtom = (project: ProjectName, ask: AskId) =>8 ContractsClient.query(9 "showAsk",10 { ask, project },11 { reactivityKeys: keys.ask(project, ask) }12 );13 21-// What an ask's atom holds: its read, under way, failed or done.14 type AskRead = Atom.Type<ReturnType<typeof askAtom>>;15 24-// No row selected: an ask never read.16 const unselected: Atom.Atom<AskRead> = Atom.make<AskRead>(17 AsyncResult.initial()18 );19 29-// 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.21 export 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- */1 import type { Contract } from "@repo/protocol/contracts";2 import type { CommitView } from "@repo/protocol/domain/code";3 import type { ProjectName, RepoPath } from "@repo/protocol/ids";4 import { Array, Effect, Option } from "effect";2 unmodified lines7 8 import { ContractsClient } from "../surfaces.ts";9 import { keys } from "./keys.ts";10 20-/** What the contract tagged `Tag` takes. */11 type PayloadOf<Tag extends string> = Rpc.Payload<Rpc.ExtractTag<Contract, Tag>>;12 13 const options = (project: ProjectName) => ({14 reactivityKeys: keys.code(project),15 });16 27-/** Main, the tags and the forks. */17 export const refsAtom = Atom.family((project: ProjectName) =>18 Atom.withServerValueInitial(19 ContractsClient.query("listRefs", { project }, options(project))20 )21 );22 34-/** One folder; the root at main when the payload names neither. */23 export const treeAtom = (payload: PayloadOf<"readTree">) =>24 ContractsClient.query("readTree", payload, options(payload.project));25 38-/** Every file path at a revision, for the file tree. */26 export const pathsAtom = (payload: PayloadOf<"listPaths">) =>27 ContractsClient.query("listPaths", payload, options(payload.project));28 42-/** One file at a revision. */29 export const fileAtom = (payload: PayloadOf<"readFile">) =>30 ContractsClient.query("readFile", payload, options(payload.project));31 46-/** A page of the log. */32 export const logAtom = (payload: PayloadOf<"log">) =>33 ContractsClient.query("log", payload, options(payload.project));34 50-/** One commit and what it changed. */35 export const commitAtom = (payload: PayloadOf<"showCommit">) =>36 ContractsClient.query("showCommit", payload, options(payload.project));37 54-/**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- */38 export const projectCodeAtom = Atom.family((project: ProjectName) =>39 Atom.withServerValueInitial(40 ContractsClient.runtime.factory.withReactivity(keys.code(project))(41 ContractsClient.runtime.atom(17 unmodified lines59 )60 )61 );62 87-/** At most this many of a folder's entries have what last changed them read. */63 export const LAST_CHANGES_CAP = 30;64 90-/**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- */65 export const lastChangesAtom = Atom.family(66 (key: {67 readonly at: string;68 readonly paths: readonly RepoPath[];34 unmodified linesmodified: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- */1 import type { Decide } from "@repo/protocol/contracts";2 import { Effect } from "effect";3 import { Reactivity } from "effect/reactivity";4 5 import { ContractsClient } from "../surfaces.ts";6 import { keys } from "./keys.ts";7 18-/** Take one decision: `{ project, decision, choice, note? }`, answered with the decision as it now stands. */8 export const decideAtom = ContractsClient.runtime.fn<9 typeof Decide.payloadSchema.Type10 >()(11 Effect.fnUntraced(function* (input) {10 unmodified linesmodified: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.2 import type { ProjectName } from "@repo/protocol/ids";3 4 import { ContractsClient } from "../surfaces.ts";5 import { keys } from "./keys.ts";7 unmodified linesmodified: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.2 import { ProjectEvent } from "@repo/protocol/domain/event";3 import type { LandingView } from "@repo/protocol/domain/landing";4 import type { ProjectName } from "@repo/protocol/ids";5 import { Effect, Stream } from "effect";17 unmodified lines23 Move,24 Round,25 } from "../features/shared/ask-progress.ts";26 41-/** How many landings a project's page shows. */27 const RECENT = 20;28 44-/**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- */29 export const projectEventsAtom = Atom.family((project: ProjectName) =>30 Atom.withServerValueInitial(31 ContractsClient.runtime.factory.withReactivity(keys.events(project))(32 ContractsClient.runtime.atom(10 unmodified lines43 )44 )45 );46 66-/** The landings among a project's events, newest first, at most twenty. */47 export const recentLandings = (48 events: readonly ProjectEvent[]49 ): readonly LandingView[] =>50 events2 unmodified lines53 )54 .toReversed()55 .slice(0, RECENT);56 77-/** A project's recent landings, from the one replay its page reads. */57 export const recentLandingsAtom = Atom.family((project: ProjectName) =>58 Atom.withServerValueInitial(59 Atom.mapResult(projectEventsAtom(project), recentLandings)60 )1 unmodified linemodified: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.2 import type { Reserve } from "@repo/protocol/domain/ask";3 import type { KindName } from "@repo/protocol/ids";4 import { Atom } from "effect/reactivity";5 6 import { ContractsClient } from "../surfaces.ts";7 import { keys } from "./keys.ts";8 19-/** The open asks `frontPage` returns for `filter`, as the anonymous viewer may take them until sign-in names one. */9 export const frontPageAtom = Atom.family(10 (filter: { readonly kind?: KindName; readonly reserved?: Reserve }) =>11 Atom.withServerValueInitial(12 ContractsClient.query("frontPage", filter, {1 unmodified line14 })15 )16 );17 29-/** Every project the platform lists, with its posture, open asks and last landing. */18 export 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- */1 import type { InitProject } from "@repo/protocol/contracts";2 import type { ProjectName } from "@repo/protocol/ids";3 import { Effect, Option } from "effect";4 import { AsyncResult, Reactivity } from "effect/reactivity";5 6 import { ContractsClient } from "../surfaces.ts";7 import { keys } from "./keys.ts";8 15-/**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.10 export const importMade = (11 result: AsyncResult.AsyncResult<12 typeof InitProject.successSchema.Type,13 unknown2 unmodified lines16 AsyncResult.isSuccess(result) && !result.waiting17 ? Option.some(result.value.project)18 : Option.none();19 30-/** Import a public repo: `initProject`'s payload, answered with the project. */20 export const importAtom = ContractsClient.runtime.fn<21 typeof InitProject.payloadSchema.Type22 >()(23 Effect.fnUntraced(function* (input) {7 unmodified linesmodified: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.2 import type { AskId, ProjectName, ProposalId } from "@repo/protocol/ids";3 4 export 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 linesmodified: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.2 import type { ProjectName } from "@repo/protocol/ids";3 4 import { ContractsClient } from "../surfaces.ts";5 import { keys } from "./keys.ts";7 unmodified linesmodified: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- */1 import type { Handle } from "@repo/protocol/ids";2 import { Atom } from "effect/reactivity";3 4 import { ContractsClient } from "../surfaces.ts";4 unmodified linesmodified: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.2 import type { ProjectName } from "@repo/protocol/ids";3 import { Atom } from "effect/reactivity";4 5 import { ContractsClient } from "../surfaces.ts";9 unmodified linesmodified: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- */1 import type { ProjectEvent } from "@repo/protocol/domain/event";2 import { ProjectName } from "@repo/protocol/ids";3 import { AsyncResult, Atom } from "effect/reactivity";4 13 unmodified lines18 )19 )20 );21 30-/** Projects named in one key, as the atoms below are keyed: "burrow vellum". */22 export const projectsKey = (projects: readonly ProjectName[]) =>23 projects.toSorted().join(" ");24 25 const projectsIn = (key: string): readonly ProjectName[] =>26 key === "" ? [] : key.split(" ").map((name) => ProjectName.make(name));27 37-/**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- */28 export const familyEventsAtom = Atom.family((key: string) =>29 Atom.make(30 (get): ReadonlyMap<ProjectName, readonly ProjectEvent[]> =>31 new Map(5 unmodified lines37 )38 )39 );40 55-/**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- */41 export 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 );48 67-/**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- */49 export const projectLedgerAtom = Atom.family((project: ProjectName) =>50 Atom.withServerValueInitial(ledgerAtom(project))51 );52 76-/**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- */53 export 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- */1 import type { DraftAsk } from "@repo/protocol/contracts";2 import type { ProjectName, ProposalId } from "@repo/protocol/ids";3 import { Effect } from "effect";4 import { Atom, Reactivity } from "effect/reactivity";5 6 import { ContractsClient } from "../surfaces.ts";7 import { keys } from "./keys.ts";8 23-/** One proposal and the files it holds: `proposalAtom(project)(proposal)`. */9 export const proposalAtom = Atom.family((project: ProjectName) =>10 Atom.family((proposal: ProposalId) =>11 Atom.withServerValueInitial(12 ContractsClient.query(4 unmodified lines17 )18 )19 );20 36-/**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- */21 export const projectTodayAtom = Atom.family((project: ProjectName) =>22 Atom.withServerValueInitial(23 ContractsClient.query(24 "today",2 unmodified lines27 )28 )29 );30 51-/**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.32 export const draftAtom = ContractsClient.runtime.fn<33 typeof DraftAsk.payloadSchema.Type34 >()(35 Effect.fnUntraced(function* (input) {11 unmodified linesmodified: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- */1 import type { ProposeAsk } from "@repo/protocol/contracts";2 import { RepoPath } from "@repo/protocol/ids";3 import type { ProjectName, ProposalId } from "@repo/protocol/ids";4 import { Array, Effect, Option, Order, Schema } from "effect";3 unmodified lines8 import { keys } from "./keys.ts";9 10 const decodePath = Schema.decodeUnknownOption(RepoPath);11 20-/** The top folders among `paths`, sorted, without dot folders. */12 export const topFolders = (paths: readonly RepoPath[]): readonly RepoPath[] => {13 const folders = paths.flatMap((path): readonly RepoPath[] => {14 const slash = path.indexOf("/");15 4 unmodified lines20 21 return Array.sort(Array.dedupe(folders), Order.String);22 };23 33-/** The project's top folders at main, each a territory the form offers. */24 export const modulesAtom = Atom.family((project: ProjectName) =>25 Atom.withServerValueInitial(26 ContractsClient.runtime.factory.withReactivity(keys.code(project))(27 ContractsClient.runtime.atom(7 unmodified lines35 )36 )37 );38 49-/**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.40 export 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();46 61-/** Propose an ask: `proposeAsk`'s payload, answered with the proposal. */47 export const proposeAtom = ContractsClient.runtime.fn<48 typeof ProposeAsk.payloadSchema.Type49 >()(50 Effect.fnUntraced(function* (input) {7 unmodified linesmodified: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.3 import { RegistryProvider } from "@effect/atom-react";4 import { AsyncResult, Atom } from "effect/reactivity";5 import { createElement } from "react";6 import type { ReactNode } from "react";7 33-/** An atom and the value it starts from. */8 export type Seed = readonly [Atom.Atom<unknown>, unknown];9 36-/** `atom`, starting from `value`. */10 export const seed = <A>(atom: Atom.Atom<A>, value: A): Seed =>11 Atom.initialValue(atom, value);12 40-/** A read's atom, starting from the success its loader read. */13 export const seedSuccess = <A, E>(14 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,15 value: A16 ): Seed => seed(atom, AsyncResult.success(value));17 46-/**47- * `children` over a registry of their own that starts from `seeds`; a new48- * `id` (another address) makes a new one.49- */18 export const SeededAtoms = ({19 children,20 id,21 seeds,6 unmodified linesmodified: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- */1 import type { ProjectName } from "@repo/protocol/ids";2 import { Atom } from "effect/reactivity";3 4 import { ContractsClient } from "../surfaces.ts";5 import { keys } from "./keys.ts";6 16-/**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- */7 const todayFamily = Atom.family((project: ProjectName | undefined) =>8 Atom.withServerValueInitial(9 ContractsClient.query("today", project === undefined ? {} : { project }, {10 reactivityKeys: keys.today(),5 unmodified linesmodified: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.3 import { ProjectEvent } from "@repo/protocol/domain/event";4 import type { ProjectName } from "@repo/protocol/ids";5 import {6 Array,12 unmodified lines19 import { framedClient, sharedRuntime } from "../surfaces.ts";20 import { lastSeq, projectEventsAtom } from "./events.ts";21 import { keys } from "./keys.ts";22 50-/** How long a page waits before it follows again, or between polls. */23 export const POLL_MS = 5000;24 53-/** Where a page hears its project's events, from a sequence number on. */25 export class ProjectWatch extends Context.Service<26 ProjectWatch,27 {28 readonly follow: (2 unmodified lines31 ) => Stream.Stream<ProjectEvent, unknown>;32 }33 >()("web/ProjectWatch") {}34 64-/** `watch` over the framed `/rpc`. */35 const framedWatch = Layer.effect(36 ProjectWatch,37 Effect.map(framedClient, (client) =>38 ProjectWatch.of({1 unmodified line40 })41 )42 );43 74-/** The runtime `watchAtom` runs on, sharing the page's and the rail's `Reactivity`; a test gives it a stub `ProjectWatch`. */44 export const watchRuntime = sharedRuntime(framedWatch);45 77-/** The keys an event of `project` changes. */46 export 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 lines67 Released: () => keys.project(project),68 Warned: ({ ask }) => keys.ask(project, ask),69 });70 104-/** The keys any of `events` changes, each once. */71 const keysOfAll =72 (project: ProjectName) =>73 (events: readonly ProjectEvent[]): readonly string[] =>74 Array.dedupe(events.flatMap((event) => keysOf(project, event)));75 110-/** `project` followed from the end of its `replay` for as long as it runs: the stream while it works, then the poll. */76 const followed = <E>(77 project: ProjectName,78 replay: Effect.Effect<readonly ProjectEvent[], E>79 ) =>10 unmodified lines90 yield* reactivity.invalidate(91 Option.match(kept, { onNone: () => [], onSome: keysOfAll(project) })92 );93 129- /** 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);96 97 const ended = yield* watch.follow(project, yield* Ref.get(last)).pipe(24 unmodified lines122 .invalidate([...keys.project(project), ...keys.events(project)])123 .pipe(Effect.delay(POLL_MS), Effect.forever);124 });125 162-/**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- */126 export 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 linesmodified: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- */1 import type { Contract } from "@repo/protocol/contracts";2 import type { Rpc } from "effect/rpc";3 4 import { ContractsClient } from "../surfaces.ts";5 import { keys } from "./keys.ts";6 14-/** Why each line of a file at a revision is there. */7 export const whyAtom = (8 payload: Rpc.Payload<Rpc.ExtractTag<Contract, "why">>9 ) =>10 ContractsClient.query("why", payload, {2 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import { CheckSpec } from "@repo/protocol/domain/check";3 import type { Handle } from "@repo/protocol/ids";4 import { AskId, ProjectName, RepoPath, shortNameOf } from "@repo/protocol/ids";92 unmodified lines97 summary: "A connection pool that queues borrowers fairly.",98 }),99 ];100 108-/** `drain-on-shutdown` → `drainOnShutdown`: the export an ask's check looks for. */101 export const exportNameOf = (ask: string) =>102 ask.replaceAll(/-(?<letter>[a-z0-9])/gu, (_match, letter: string) =>103 letter.toUpperCase()104 );105 114-/** A check that fails on main by its assertion: the module exports no function by the ask's name. */106 export const checkOf = (module: string, ask: string, want: string) =>107 [108 'import { expect, test } from "bun:test";',109 "",4 unmodified lines114 "});",115 "",116 ].join("\n");117 127-/** The ask a filler states, as its `policy.json` holds it. */118 const statedOf = (119 project: Filler,120 ask: NonNullable<Filler["ask"]>121 ): StatedAsk => ({61 unmodified lines183 `# The people ${project.project}'s deciders vouch for.\n`,184 ],185 ]);186 197-/**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- */187 export const seedFillers = (minute: number) =>188 Effect.forEach(189 fillers,190 (project, index) =>47 unmodified linesmodified: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- */1 import { creditsByArea } from "@repo/project/attention/credits";2 import { today } from "@repo/project/attention/today";3 import { listingOf } from "@repo/project/events";4 import type { Verdict } from "@repo/protocol/domain/answer";31 unmodified lines36 import { Array, DateTime, Effect, Option, Schema } from "effect";37 38 import { present } from "./story.ts";39 53-/** One proposal and the files it holds. */40 export interface HeldProposal {41 readonly files: readonly ConfigFile[];42 readonly proposal: Proposal;43 }44 59-/** A log a failing lane left, as `evidence` reads it back. */45 export interface KeptLog {46 readonly claimant: Handle;47 readonly lane: Verdict["lanes"][number]["lane"];48 readonly text: string;49 }50 66-/** A fixture project's whole record. */51 export 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 }70 71 const asType = <S extends Schema.Top>(schema: S) =>72 Schema.decodeUnknownEffect(Schema.toType(schema));73 95-/**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- */74 export const decodeRecord = (75 record: FixtureRecord76 ): Effect.Effect<FixtureRecord> =>77 Effect.gen(function* () {23 unmodified lines101 102 return record;103 }).pipe(Effect.orDie);104 130-// ------------------------------------------------------------ reads131-132-/** The open asks, as `listAsks` lists them. */105 export const listedOf = (record: FixtureRecord): readonly AskListing[] =>106 [...record.asks.values()].flatMap((ask) =>107 ask.state === "closed" ? [] : [listingOf(ask)]108 );109 138-/** The verdict on `head`, or the latest; its outcome where the answer stands now. */110 export const verdictIn = (111 record: FixtureRecord,112 ask: AskId,113 head: CommitSha | undefined5 unmodified lines119 (verdict) => head === undefined || verdict.head === head120 );121 };122 152-/** The landing at `sha`, if the record holds one. */123 export const landingIn = (record: FixtureRecord, sha: CommitSha) =>124 Array.findFirst(record.landings, (landing) => landing.sha === sha);125 156-/** How many decisions and finishes `decider` took on the day of `now`. */126 const spentBy = (record: FixtureRecord, decider: Handle, now: DateTime.Utc) => {127 const day = DateTime.formatIsoDateUtc(now);128 129 return record.decisions.filter(3 unmodified lines133 DateTime.formatIsoDateUtc(decided.at) === day134 ).length;135 };136 168-/** `decider`'s Today in the record, as the service computes one; none for anyone who decides nothing in it. */137 export const todayIn = (138 record: FixtureRecord,139 decider: Handle,140 now: DateTime.Utc,17 unmodified lines158 })159 )160 : Option.none();161 194-/** A person's credits in the record, by area and role. */162 export const creditsIn = (163 record: FixtureRecord,164 handle: Handle165 ): readonly CreditSummary[] =>166 creditsByArea({ asks: record.asks, handle, landings: record.landings });167 201-/** The caller's claims still in play, and their answers. */168 export 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 lines176 sameHandle(claimant, who) && (state === "live" || state === "warned")177 ),178 });179 214-/**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- */180 export const decisionTaken = (181 record: FixtureRecord,182 input: {183 readonly choice: Choice;31 unmodified lines215 },216 };217 });218 258-/** The number of the record's last event. */219 export 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- */1 import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";2 import { Brand } from "@repo/brand";3 import { formatLanding } from "@repo/git/trailers";4 import { listingOf } from "@repo/project/events";39 unmodified lines44 import { overlay, personIdentity, platformIdentity, scratch } from "../git.ts";45 import type { Files } from "../git.ts";46 import type { FixtureRecord, HeldProposal, KeptLog } from "./record.ts";47 59-// ------------------------------------------------------------- ids60-61-/** The largest prime below 2^32: each block of eight digits is a hash modulo it. */48 const MODULUS = 4_294_967_291;49 64-/** `count` hex digits made from `label` alone: a polynomial hash, a fresh seed per eight digits. */50 export const hexOf = (label: string, count: number): string => {51 let out = "";52 53 for (let block = 0; out.length < count; block += 1) {8 unmodified lines62 63 return out.slice(0, count);64 };65 81-/** `{ [key]: value }` when there is a value, else nothing: an optional key, spread. */66 export const present = <K extends string, A>(67 key: K,68 value: A | undefined69 ): Partial<Record<K, A>> =>1 unmodified line71 onNone: () => ({}),72 onSome: (held) => Record.singleton(key, held),73 });74 91-/** A commit id made from `label`: an answer's head, which no repo of the world holds. */75 export const headOf = (label: string) => CommitSha.make(hexOf(label, 40));76 94-/** A held-back suite's commitment, made from its area's name. */77 export const suiteOf = (area: string) =>78 SuiteRoot.make(`sha256:${hexOf(`suite:${area}`, 64)}`);79 98-/** An instant of the dev world's calendar (`clock.ts`), from `2026-10-07T10:00`, in UTC. */80 export const instant = (text: string): DateTime.Utc =>81 DateTime.toUtc(DateTime.makeUnsafe(`${text}:00Z`));82 102-// ----------------------------------------------------------- lanes103-104-/** The project's own lanes, by name, with their commands. */83 export type Lanes = Readonly<Record<string, string>>;84 107-/** The lane an ask's own check reports as, and its command. */85 const 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 line90 RedThenGreen: ({ path }) => ["redThenGreen", test.replace("{path}", path)],91 SymbolAbsent: ({ count }) => ["symbolAbsent", count],92 });93 117-// ------------------------------------------------------------ story118-119-/** What one landing carries beside its commit. */94 interface LandingInput {95 readonly assisted?: readonly AgentTrailer[];96 readonly at: DateTime.Utc;97 readonly author: Handle;6 unmodified lines104 readonly requestId: RequestId;105 readonly verdict?: Verdict;106 }107 134-/** One claim as the story keeps it. */108 interface Held {109 readonly at: DateTime.Utc;110 readonly base: LandedSha;111 readonly claimant: Handle;1 unmodified line113 readonly state: ClaimState;114 readonly suite?: SuiteRoot;115 }116 144-/**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- */117 export const storyOf = (input: {118 readonly base: LandedSha;119 readonly files: Files;120 readonly lanes: Lanes;23 unmodified lines144 const firstClaims = new Map<Handle, DateTime.Utc>();145 146 const nextSeq = () => events.length + 1;147 179- /** One event, numbered next. */148 const tell = (made: (seq: number) => ProjectEvent) => {149 events.push(made(nextSeq()));150 };151 27 unmodified lines179 180 claims.set(id, [...all.slice(0, -1), change(last)]);181 };182 215- /** 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 lines239 240 return view;241 });242 276- /** 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 lines294 }295 );296 297 return {332- /** An ask's id, read back; the story names only asks it opened. */298 ask: askOf,299 335- /**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 lines357 358 return landing;359 }),360 401- /** `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 lines379 ProjectEvent.cases.Claimed.make({ ask: id, at, claimant: who, seq })380 );381 },382 424- /** 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 lines391 392 return pushed;393 },394 437- /**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 lines459 460 return verdict;461 },462 509- /**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 lines553 554 return view;555 }),556 609- /**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 lines577 ]);578 }579 },580 638- /** 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 lines599 600 return view;601 }),602 661- /** 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 },607 667- /** 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 },613 674- /** 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 },619 681- /** A decision put to its deciders. */620 decision: (decision: Decision) => {621 decisions.push(decision);622 },623 686- /** 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 lines639 })640 );641 },642 706- /** A ledger entry, numbered next in the ledger, and its event. */643 record: (entry: (seq: number) => LedgerEntry) => {644 const made = entry(ledger.length + 1);645 646 ledger.push(made);5 unmodified lines652 })653 );654 },655 720- /** 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 lines677 );678 }679 },680 746- /** 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 lines688 })689 );690 },691 758- /** A decider accepted the proposal: it is closed, and its ask opens. */692 accepted: (id: ProposalId) => {693 const held = proposals.get(id);694 695 if (held !== undefined) {3 unmodified lines699 });700 }701 },702 770- /** 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 lines714 ])715 );716 }),717 786- /** Main's landed commit now. */718 head: () => head,719 789- /** 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 lines777 },778 };779 });780 851-/** A story under way: its steps, and the record it has written so far. */781 export 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- */1 import { Brand } from "@repo/brand";2 import { childId, deleteChildId } from "@repo/project/migrate";3 import type { HeldBackResult } from "@repo/protocol/domain/answer";4 import type { Ask } from "@repo/protocol/domain/ask";47 unmodified lines52 import type { Story } from "./story.ts";53 54 export const vellum = ProjectName.make("oscabriel/vellum");55 84-/** The calendar's instant the world's clock stands at once the fixtures are told. */56 export const fixturesNow = instant("2026-10-07T10:00");57 87-/** When vellum's first commit was pushed, by its initializer, on the calendar. */58 export const vellumStart = instant("2026-08-24T09:00");59 60 const dir = Brand.configDir;61 7 unmodified lines69 tove: visitors.proposer,70 wren: visitors.regular,71 } as const;72 103-/** vellum's initializer: the operator, in whose namespace it is made. */73 export { operator as vellumInitializer } from "../examples.ts";74 75 const MODULES = [76 "cli",31 unmodified lines108 "sentry.io",109 "ingest.sentry.io",110 ]);111 143-// The areas whose checks the maintainers hold back, and their commitments.112 const EXPORT = AreaName.make("export");113 114 const PARSER = AreaName.make("parser");115 11 unmodified lines127 suite: area === EXPORT ? exportSuite : parserSuite,128 total,129 });130 163-// --------------------------------------------------------------- files164-131 const encodeCheck = Schema.encodeSync(CheckSpec);132 133 const COUNT = Command.make("bun scripts/count-callers.ts oldTokenize --json");134 11 unmodified lines146 null,147 2148 )}\n`;149 184-/** A module's entry, calling the old tokenizer twice. */150 const entryOf = (module: Module, tokenize: string) =>151 [152 `import { ${tokenize} } from "@vellum/parser/tokenize";`,153 "",3 unmodified lines157 `export const marks = (text: string) => ${tokenize}(text).filter((token) => token.kind === "mark");`,158 "",159 ].join("\n");160 196-/** A module's page settings, under the old name or the new. */161 const 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 lines188 "LEGACY_PDF_ENGINE=",189 "",190 ].join("\n");191 228-/** How many decisions a vellum decider takes a day (its `policy.json`'s budget). */192 export const decisionsPerDay = 5;193 231-/** How long a claim goes without a push before it is warned, then lapses. */194 const CLAIMS = { lapseAfter: { hours: 96 }, warnAfter: { hours: 48 } } as const;195 196 const HOUR_MS = 3_600_000;197 60 unmodified lines258 source: "config",259 weakening: { markers: [".skip(", ".only(", ".todo("] },260 });261 300-/** vellum's first push: six packages, its config folder and its env schema. */262 export const vellumFiles: Files = new Map([263 [264 "README.md",265 [96 unmodified lines362 ].join("\n"),363 ],364 ]);365 405-// ---------------------------------------------------------------- asks406-407-/** An ask as the story opens it: everything but where and when it opened. */366 type Stated = Omit<Ask, "openedAt" | "openedIn" | "project">;367 368 const 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 lines403 ),404 };405 };406 450-/** The ask's file as its maintainer writes it, and its check's test. */407 const filesOf = (asks: readonly Stated[]): Files =>408 new Map(409 asks.flatMap((ask) => {410 const stated: StatedAsk = {22 unmodified lines433 return [[file.path, file.content] as const, ...test];434 })435 );436 481-/** A migrate ask split as the service splits one: a child per module, then the delete child. */437 const familyOf = (input: {438 readonly id: string;439 readonly from: string;440 readonly to: string;185 unmodified lines626 want: "A table cell longer than the column wraps instead of widening the table.",627 }),628 } as const;629 675-/** An answer's change: one file in the ask's own module. */630 const answerFiles = (stated: Stated, body: string): Files => {631 const home =632 stated.territory.module === "."633 ? "packages/parser"11 unmodified lines645 646 const allPassed = (askLane: string) =>647 ({ ...passed, [askLane]: "passed" }) as const;648 695-// ----------------------------------------------------------- decisions696-649 const decisionId = (n: number) =>650 DecisionId.make(`dec-${String(n).padStart(6, "0")}`);651 652 const proposalId = (n: number) =>18 unmodified lines671 project: vellum,672 subject: input.subject,673 });674 723-/** The finish's diff: the answer's second round, whose test the first round had narrowed with `.only(`. */675 const 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 lines720 "+// One case per width the renderer supports lives in table.widths.test.ts.",721 "",722 ].join("\n");723 773-// ---------------------------------------------------------------- ledger774-775-/** The ledger's standing parts; its entries are told with the story. */724 const ledger: Ledger = {725 entries: [],726 layers: [727 {12 unmodified lines740 postureLabel: "Open with sealed evidence · sealed checks in export, parser",741 project: vellum,742 };743 796-/**797- * The env shape at `at`: four items, one write-only and set at `setAt`,798- * none with a value or placeholder.799- */744 const envAt = (at: LandedSha, setAt: DateTime.Utc): EnvSchemaView => ({745 at,746 file: RepoPath.make(".env.schema"),747 imports: [],37 unmodified lines785 ],786 project: vellum,787 });788 845-// ------------------------------------------------------------- proposals846-789 const proposal = (input: {790 readonly n: number;791 readonly at: DateTime.Utc;792 readonly proposer: Handle;12 unmodified lines805 want: input.want,806 ...present("draft", input.draft),807 });808 867-/** A drafted ask's three files: its ask file, its check, and the document the check reads. */809 const draftedFiles = (id: string, module: Module, want: string) => {810 const stated = fix({ id, module, want });811 const [askFile, testFile] = [...filesOf([stated])];812 8 unmodified lines821 : [{ content: entry[1], path: RepoPath.make(entry[0]) }]822 );823 };824 884-/** A family child's change: its module's entry on the new tokenizer. */825 const childEntry = (module: Module): Files =>826 new Map([[`packages/${module}/src/index.ts`, entryOf(module, "tokenize")]]);827 888-/** A family child's change: its module's page settings under the new name. */828 const childPage = (module: Module): Files =>829 new Map([[`packages/${module}/src/page.ts`, pageOf(module, "pageFormat")]]);830 892-// ------------------------------------------------------------- the story893-894-/**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- */831 export const tellVellum = (base: LandedSha) =>832 Effect.gen(function* () {833 const { place } = yield* DevClock;834 42 unmodified lines877 ),878 });879 });880 948- // 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 lines917 });918 919 yield* story.tag("v0.8.0", palette.sha);920 989- // 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 lines990 suite: parserSuite,991 })992 );993 1063- // 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 lines1119 at: t("2026-10-04T17:00"),1120 changes: childPage("cli"),1121 });1122 1193- // October 5.1123 story.record((seq) =>1124 LedgerEntry.cases.Admitted.make({1125 area: EXPORT,1126 at: t("2026-10-05T07:00"),249 unmodified lines1376 t("2026-10-05T16:00"),1377 parserSuite1378 );1379 1451- // October 6.1380 story.decision(1381 decision({1382 at: t("2026-10-06T07:00"),1383 deciders: [people.ines, people.lin],390 unmodified lines1774 subject: Subject.cases.OpenProposal.make({ proposal: proposalId(4) }),1775 })1776 );1777 1850- // October 7, this morning.1778 story.claim(1779 ask.exportErrors.id,1780 people.tove,1781 t("2026-10-07T07:00"),113 unmodified lines1895 1896 return { story, told: () => story.told(apart) };1897 });1898 1972-/**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- */1899 export const landLintChild = (story: Story, at: DateTime.Utc) =>1900 Effect.gen(function* () {1901 const child = tokenizer.child("lint");1902 9 unmodified linesmodified: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.3 import type { Backend } from "../server/rpc.ts";4 import { credentialFrom, withCredential } from "../server/session.ts";5 import { fixturesMode } from "./fixtures.ts";6 import { devServer } from "./server.ts";7 23-/**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.9 const time = import.meta.env.MODE === "test" ? "fixed" : "present";10 11 const served = devServer({ fixtures: fixturesMode, time });12 32-/** The development backend: every request answered by the dev world, as the platform is asked; the env unused. */13 export 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- */1 import { CheckAt, CheckRunner } from "@repo/checks/check-runner";2 import type { CheckJob } from "@repo/checks/check-runner";3 import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";4 import type { LaneResult } from "@repo/protocol/domain/answer";5 import { Context, Effect, Layer } from "effect";6 7 import { printedBy } from "./examples.ts";8 19-/** What a lane comes to where it runs: red on a composed commit, green on a merged tree. */9 const scripted = (10 job: CheckJob,11 lane: CheckJob["lanes"][number]12 ): LaneResult => ({42 unmodified linesmodified: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- */1 import { Clock, Context, DateTime, Duration, Effect, Layer } from "effect";2 21-/** The dev world's clock: where its calendar stands, and the way to move it. */3 export 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") {}13 14 const NANOS_PER_MILLI = 1_000_000n;15 42-/** Where the calendar starts: every instant the seed writes is this one or a whole minute after. */16 export const devStart: DateTime.Utc = DateTime.toUtc(17 DateTime.makeUnsafe("2026-10-07T09:00:00Z")18 );19 47-/** The calendar's instant `minutes` whole minutes after its start. */20 export const devMinute = (minutes: number): DateTime.Utc =>21 DateTime.add(devStart, { minutes });22 51-/**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- */23 export const startEndingNow = (24 end: DateTime.Utc25 ): Effect.Effect<DateTime.Utc> =>26 Effect.map(DateTime.now, (now) =>2 unmodified lines29 DateTime.distance(devStart, end)30 )31 );32 66-/**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- */33 export 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);38 39 const place = (at: DateTime.Utc) => DateTime.addDuration(at, offset);40 78- // 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;43 44 const elapsedNanos = () =>52 unmodified linesmodified: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- */2 import { Brand } from "@repo/brand";3 import { cannedDraft } from "@repo/drafting/draft-runs/canned";4 import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";5 import { Command, SymbolName } from "@repo/protocol/domain/common";11 unmodified lines17 const decodeCheck = Schema.decodeSync(CheckSpec);18 19 const encodeMeasure = Schema.encodeSync(RatchetMeasure);20 41-/** What a project's `policy.json` states, as the file holds it. */21 export type Stated = typeof PolicyInput.Encoded;22 44-/** One ask as `policy.json` states it. */23 export type StatedAsk = Stated["asks"][number];24 47-/** A `policy.json` from what its project states, with every default written out. */25 export const policyJson = (stated: Stated) =>26 `${JSON.stringify(27 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),28 null,29 230 )}\n`;31 55-/** One file an ask opens with. */32 export interface AskFile {33 readonly content: string;34 readonly path: RepoPath;35 }36 61-/** The files a decider opens one ask with: its ask file, then its check's file if it has one. */37 export type Opening = Array.NonEmptyReadonlyArray<AskFile>;38 64-/** The args a kind takes for an ask's check, as its ask file passes them (`packages/sdk`'s `kinds`). */39 interface KindArgs {40 readonly command?: string;41 readonly count?: string;42 readonly from?: string;2 unmodified lines45 readonly rule?: string;46 readonly to?: string | undefined;47 }48 75-/** A string, or a list of them, as TypeScript source spells it. */49 const spelled = (value: string | readonly string[]): string =>50 Predicate.isString(value)51 ? JSON.stringify(value)52 : `[${value.map(spelled).join(", ")}]`;53 81-/**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`.55 const 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 line60 RedThenGreen: ({ path }): KindArgs => ({ path }),61 SymbolAbsent: ({ count, symbol }): KindArgs => ({ count, from: symbol }),62 });63 96-/** An ask's territory as its file spells it: the repo-wide builder for `.`, else the data itself. */64 const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>65 module === "."66 ? `territory.paths(${paths.map(spelled).join(", ")})`67 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;68 102-/** An ask's file: the SDK call that states `stated`, as its maintainer writes it. */69 export const askFileOf = (stated: StatedAsk): AskFile => {70 const territory = territoryOf(stated.territory);71 72 const passed = Object.entries({28 unmodified lines101 path: RepoPath.make(stated.file),102 };103 };104 139-// ------------------------------------------------------------- datekit140-141-/**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- */105 export const operator = Handle.make("oscabriel");106 107 export const datekitPeople = {108 contributor: Handle.make("bram"),11 unmodified lines120 requires: ["want", "check", "territory"],121 strength: "assertion",122 } satisfies typeof AskKind.Encoded;123 166-/** One datekit ask: as `policy.json` states it, and the check file it opens with. */124 interface DatekitAsk {125 readonly stated: StatedAsk;126 readonly test: AskFile;127 }128 172-/**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- */129 const datekitAsk = (input: {130 readonly id: string;131 readonly file: string;132 readonly current: string;55 unmodified lines188 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 lines228 want: "diffInDays counts calendar days across a daylight-saving change.",229 }),230 ];231 282-/**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- */232 const draftedAsk: StatedAsk = {233 askedBy: datekitPeople.decider,234 blockedBy: [],235 brief: { current: cannedDraft.current, want: cannedDraft.want },169 unmodified lines405 [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 lines423 message: "Mention time zones in the README",424 },425 } as const;426 484-// -------------------------------------------------------------- burrow485-427 export const burrowPeople = {428 decider: Handle.make("okafor"),429 second: Handle.make("lin-h"),430 } as const;18 unmodified lines449 );450 451 const PARENT = "drop-legacy-fetch";452 512-/**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- */453 const burrowAsks: readonly StatedAsk[] = [454 {455 askedBy: burrowPeople.decider,456 blockedBy: [],146 unmodified lines603 files: monorepo,604 project: ProjectName.make("oscabriel/burrow"),605 } as const;606 672-/** How many times `text` calls `symbol`, as burrow's `scripts/count-callers.ts` counts. */607 const callsIn = (text: string, symbol: string) =>608 text.split(`${symbol}(`).length - 1;609 676-/** What burrow's count command prints on its first commit: each package's calls of `legacyFetch`. */610 const burrowCallers = () => {611 const byModule = Object.fromEntries(612 PACKAGES.map((pkg) => [613 `@burrow/${pkg}`,12 unmodified lines626 total: Number.sumAll(Object.values(byModule)),627 });628 };629 697-/**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- */630 export 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.3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { envSchemaMethod } from "@repo/project/deciders";5 import type { ProjectApi } from "@repo/project/project";6 import { ProjectedEvent } from "@repo/project/projection";51 unmodified lines58 import { DevProjected } from "./projection.ts";59 import { seedDev, startedAt } from "./seed.ts";60 import { devWorldWith } from "./world.ts";61 93-/** Off, on, or on with the live landing. */62 export type FixtureMode = "off" | "on" | "live";63 64 const Switch = Schema.Literals(["1", "on", "live"]);65 98-/** The switch, read once from where Vite puts it. */66 export 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 );73 107-/** Whether the dev world adds the fixtures. */74 export const fixturesOn = fixturesMode !== "off";75 110-/** How long after vellum's `watch` is first answered its lint child lands, in live mode. */76 export const LIVE_AFTER = Duration.seconds(20);77 113-/** vellum's story, and the record it has told so far, decoded. */78 interface Told {79 readonly record: FixtureRecord;80 readonly story: Story;81 readonly told: () => FixtureRecord;82 }83 120-/** The fixtures' state in one world: vellum's story once told, and the live landing's clock. */84 export 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 lines105 });106 })107 );108 149-/** The person calling, when someone signed in is. */109 const callerOf = (principal: Principal) =>110 Principal.match(principal, {111 Anonymous: () => Option.none<Person>(),112 Person: (person) => Option.some(person),113 });114 156-/** Whether `project` is one whose reads the fixtures answer. */115 const isFixture = (project: ProjectName) => project === vellum;116 159-/** The ask as an answerer reads it first, in Markdown. */117 const briefOf = (ask: Ask): string =>118 [119 `# ${ask.brief.want}`,120 "",9 unmodified lines130 : ["", "## Current", "", ask.brief.current]),131 "",132 ].join("\n");133 177-/**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- */134 const overlay: Layer.Layer<135 Projects | DevProjected,136 never,137 Projects | DevProjected | Fixtures | RepoHost | DevClock15 unmodified lines153 Effect.provideService(RepoHost, host),154 Effect.provideService(DevClock, devClock)155 );156 204- /** 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 );163 212- /** 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 lines179 return out;180 })181 );182 232- /**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 lines193 }194 195 const at = yield* Clock.monotonicTimeNanos;196 252- // 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 lines256 .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 lines325 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 lines382 );383 })384 );385 444-/**445- * The fixtures told into a world the default seed has seeded: the fillers,446- * then vellum (made and first pushed through the service, its record told447- * over its repo), and the world's clock left at the record's morning,448- * `fixturesNow`.449- */386 const seedFixtures = Effect.gen(function* () {387 const fixtures = yield* Fixtures;388 389 yield* seedFillers(30);11 unmodified lines401 yield* Ref.set(fixtures.told, Option.some({ record, story, told }));402 yield* (yield* DevClock).set(fixturesNow);403 }).pipe(Effect.orDie);404 469-/**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- */405 export const withFixtures = (406 mode: "on" | "live",407 liveAfter: Duration.Duration = LIVE_AFTER,408 start: DateTime.Utc = devStart15 unmodified linesmodified: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- */1 import { FrontPage } from "@repo/project/front-page";2 import type { FrontPageFilter } from "@repo/project/front-page";3 import type { ProjectedEvent } from "@repo/project/projection";4 import { creditsFor, Projects } from "@repo/project/projects";9 unmodified lines14 import { Array, DateTime, Effect, Layer, Order } from "effect";15 16 import { DevProjected } from "./projection.ts";17 33-/** One open ask on the page, as D1's `front_page` row holds it. */18 interface Row {19 readonly ask: AskListing;20 readonly claims: number;21 readonly openedAt: DateTime.Utc;22 readonly project: ProjectName;23 }24 41-/** A project as D1's `projects` row holds it, but for its open asks, which the page counts. */25 interface Listed {26 readonly landedAt?: DateTime.Utc;27 readonly posture: Posture;28 }29 30 const keyOf = (project: ProjectName, ask: string) => `${project}/${ask}`;31 49-/** Every project's events in its own order. */32 const inOrder = Order.mapInput(33 Order.Tuple([Order.String, Order.Number]),34 ({ event, project }: ProjectedEvent) => [project, event.seq] as const35 );36 55-/** The page's rows with one ask's claim count moved by `change`, if it is on the page. */37 const withClaims = (38 rows: ReadonlyMap<string, Row>,39 key: string,40 change: number7 unmodified lines48 claims: Math.max(row.claims + change, 0),49 });50 };51 71-/** The page's rows after one project's event, as D1's statements change them. */52 const step = (53 rows: ReadonlyMap<string, Row>,54 { event, project }: ProjectedEvent55 ): ReadonlyMap<string, Row> =>24 unmodified lines80 Released: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),81 Warned: () => rows,82 });83 104-/** The project list after one project's event, as D1's statements change it. */84 const listedStep = (85 listed: ReadonlyMap<ProjectName, Listed>,86 { event, project }: ProjectedEvent87 ): ReadonlyMap<ProjectName, Listed> => {19 unmodified lines107 const empty: ReadonlyMap<string, Row> = new Map();108 109 const unlisted: ReadonlyMap<ProjectName, Listed> = new Map();110 132-/** The page's rows after `events`, and every project they came from, by name. */111 const fold = (events: readonly ProjectedEvent[]) => {112 const ordered = Array.sort(events, inOrder);113 114 return {7 unmodified lines122 };123 124 type Folded = ReturnType<typeof fold>;125 148-/** A project's posture as the list holds it: `open` until a ledger entry moves it. */126 const postureOf = (folded: Folded, project: ProjectName): Posture =>127 folded.listed.get(project)?.posture ?? "open";128 152-/** One project as `listProjects` answers it. */129 const listingOf =130 (folded: Folded) =>131 (project: ProjectName): ProjectListing => {132 const listing = {6 unmodified lines139 140 return landedAt === undefined ? listing : { ...listing, landedAt };141 };142 167-/** Newest first, then by project and ask, as D1's query orders them. */143 const 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 ]);148 174-/** A row as the anonymous viewer sees it. */149 const entryOf =150 (folded: Folded) =>151 (row: Row): FrontPageEntry => {152 const onPage = (ask: string) =>18 unmodified lines171 ({ ask }: Row) =>172 (kind === undefined || ask.kind === kind) &&173 (reserved === undefined || ask.reserve === reserved);174 201-/** `FrontPage` over the memory projection's events, and credits from `Projects`. */175 export const DevFrontPage: Layer.Layer<176 FrontPage,177 never,178 Projects | DevProjected25 unmodified linesmodified: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- */1 import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2 import type { PushSource, TreeEntry } from "@repo/artifacts/repo-host";3 import { Brand } from "@repo/brand";4 import { BlobSha, CommitSha } from "@repo/protocol/ids";5 import type { Handle, RepoName } from "@repo/protocol/ids";6 import { Array, DateTime, Effect, Option, Predicate } from "effect";7 20-/** A tree's files, by path, as text: what the world writes. */8 export type Files = ReadonlyMap<string, string>;9 23-/** A file as a commit holds it: its blob's id, and its text. */10 export interface Held {11 readonly blob: BlobSha;12 readonly text: string;13 }14 29-/** A commit's files, by path, as read back. */15 export type Snapshot = ReadonlyMap<string, Held>;16 32-/** The name and email an author or committer line carries. */17 export interface Identity {18 readonly email: string;19 readonly name: string;20 }21 38-/** The platform, which commits every landing. */22 export const platformIdentity: Identity = {23 email: `platform@${Brand.domain}`,24 name: Brand.name,25 };26 44-/** A person, as the author of their own commits and of their landings. */27 export const personIdentity = (handle: Handle): Identity => ({28 email: `${handle}@users.${Brand.domain}`,29 name: handle,30 });31 50-/** A snapshot's text alone. */32 export const textOf = (snapshot: Snapshot): Files =>33 new Map([...snapshot].map(([path, { text }]) => [path, text]));34 54-/** `files` with `changed` written over them. */35 export const overlay = (36 files: Files,37 changed: Iterable<readonly [string, string]>38 ): Files => new Map([...files, ...changed]);39 60-// --------------------------------------------------------------- objects61-40 const encoder = new TextEncoder();41 42 const decoder = new TextDecoder();43 16 unmodified lines60 61 const bytesOfHex = (id: string) =>62 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));63 86-/** git's zlib stream, as a loose object holds it. */64 const deflate = (bytes: Uint8Array) =>65 Effect.promise(() =>66 new Response(67 new Blob([Uint8Array.from(bytes)])1 unmodified line69 .pipeThrough(new CompressionStream("deflate"))70 ).arrayBuffer()71 ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));72 96-/** An object's header and content, and its id: the SHA-1 of both. */73 const framed = (kind: "blob" | "tree" | "commit", content: Uint8Array) => {74 const raw = concat([75 encoder.encode(`${kind} ${content.byteLength}\0`),76 content,32 unmodified lines109 bytesOfHex(entry.sha),110 ])111 );112 137-/**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.115 const messageOf = (message: string) =>116 `${message.replaceAll("\r", "").replace(/^\n+/u, "").replace(/\n+$/u, "")}\n`;117 118 const signature = (who: Identity, at: DateTime.Utc) =>119 `${who.name} <${who.email}> ${Math.floor(DateTime.toEpochMillis(at) / 1000)} +0000`;120 148-/** A commit to write: its tree, parents, people, time and message. */121 export interface CommitInput {122 readonly tree: ObjectId;123 readonly parents: readonly CommitSha[];124 readonly author: Identity;13 unmodified lines138 messageOf(input.message),139 ].join("\n")140 );141 170-// ------------------------------------------------------------ the source171-142 const failure = (code: string, path: string) =>143 Promise.reject(Object.assign(new Error(`${code}: ${path}`), { code }));144 145 const clean = (path: string) =>1 unmodified line147 .split("/")148 .filter((part) => part !== "")149 .join("/")}`;150 181-/** How isomorphic-git asks for a file: as bytes, or as text in "utf8", alone or as `{ encoding }`. */151 type ReadOptions = string | { readonly encoding?: string } | undefined;152 153 const UTF8 = /^utf-?8$/iu;154 1 unmodified line156 Predicate.isString(options)157 ? UTF8.test(options)158 : UTF8.test(options?.encoding ?? "");159 191-/** A write to the scratch directory through the file system: it only reads. */160 const readOnly = (raw: string) => failure("EROFS", clean(raw));161 162 const stats = (kind: "file" | "dir", size: number) => ({163 ctimeMs: 0,8 unmodified lines172 size,173 uid: 1,174 });175 208-/**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- */176 const readOnlyFs = (files: ReadonlyMap<string, Uint8Array>) => {177 const childrenOf = (dir: string) => {178 const prefix = dir === "/" ? "/" : `${dir}/`;179 57 unmodified lines237 },238 };239 };240 278-/** A git directory in memory that a push takes objects from, and how to write into it. */241 export 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 }246 247 const GITDIR = "/scratch.git";248 288-/** A fresh scratch git directory: loose, zlib-deflated objects named by their ids. */249 export const scratch: Effect.Effect<Scratch> = Effect.sync(() => {250 const objects = new Map<string, Uint8Array>();251 252 const write = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>53 unmodified lines306 tree: (files) => folder([...files]),307 };308 });309 350-// ----------------------------------------------------------------- reads351-352-/** One file of a snapshot: its path, its blob's id and its text. */310 const fileOf =311 (path: string, blob: ObjectId) =>312 (bytes: Uint8Array): Snapshot =>313 new Map([314 [path, { blob: BlobSha.make(blob), text: decoder.decode(bytes) }],315 ]);316 360-/** Every file under the tree `tree` of `repo`, by path; none when the repo lacks an object. */317 const snapshotOf = (318 repo: RepoName,319 tree: ObjectId,320 prefix: string23 unmodified lines344 (parts): Snapshot => new Map(parts.flatMap((part) => [...part]))345 );346 });347 392-/** `repo`'s files at `commit`; none when the repo or the commit is not there. */348 export const filesAt = (349 repo: RepoName,350 commit: CommitSha351 ): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>11 unmodified linesmodified: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- */1 import { RepoHost } from "@repo/artifacts/repo-host";2 import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";3 import {4 codeProjectOf,23 unmodified lines28 import type { Layer } from "effect";29 import { HttpServerRequest } from "effect/http";30 import type { Rpc, RpcGroup } from "effect/rpc";31 46-/** How many commits a page of `log` holds when the caller names no limit. */32 const LOG_PAGE = 30;33 49-/** How many events `watch` reads from its project at a time. */34 const EVENT_PAGE = 100;35 52-/** The caller, as the `Authenticated` server side named them. */36 const caller = Effect.service(CurrentPrincipal);37 55-/**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.39 const 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 );46 68-/** Where the caller reached the world: the request's origin. */47 const gateway = Effect.map(48 Effect.serviceOption(HttpServerRequest.HttpServerRequest),49 (request) =>50 Option.getOrElse(3 unmodified lines54 () => "http://localhost"55 )56 );57 80-/** A repo's git URL at the origin the caller came through. */58 const remoteOf = (repo: RepoName | ProjectName) =>59 Effect.map(gateway, (origin) => `${origin}/${repo}.git`);60 84-/** A claim, with its fork's URL at the caller's origin. */61 const atGateway = (claim: ClaimView) =>62 Effect.map(remoteOf(claim.fork), (remote): ClaimView => ({63 ...claim,64 remote,65 }));66 91-/** The caller's claims and answers, each claim at the caller's origin, under their handle. */67 const statusAtGateway = (68 who: Person,69 status: {70 readonly answers: readonly AnswerView[];5 unmodified lines76 claims,77 handle: who.handle,78 }));79 105-/** Decisions across projects: soonest to expire first, then oldest, then by project and id. */80 const 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 ]);86 113-/**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- */87 const acrossProjects = (88 decider: Person,89 pages: readonly Today[]90 ): Effect.Effect<Today, NotDecider> => {22 unmodified lines113 })114 : Effect.fail(new NotDecider({}));115 };116 148-/** Every contract over the dev world. A missing contract is a type error here. */117 export const devHandlers: Layer.Layer<118 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,119 never,120 Projects | FrontPage | EvidenceStore | RepoHost3 unmodified lines124 const frontPage = yield* FrontPage;125 const evidence = yield* EvidenceStore;126 const host = yield* RepoHost;127 160- /** `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);132 166- /** 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 lines139 Effect.provideService(RepoHost, host)140 )141 );142 177- /** `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 lines323 if (project !== undefined) {324 return yield* on(project, (api) => api.today(who));325 }326 362- // 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 linesmodified: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.3 import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";4 import { Brand } from "@repo/brand";5 import { composeRef, Lander, landedRef, Rebuild } from "@repo/project/lander";6 import type { Change, LandJob } from "@repo/project/lander";16 unmodified lines23 const mainRef = RefName.make("refs/heads/main");24 25 const blocked = () => new VerifierBlocked({});26 37-/** A commit's files, or `VerifierBlocked` when the repo doesn't hold it. */27 const read = (repo: RepoName, commit: CommitSha) =>28 filesAt(repo, commit).pipe(29 Effect.flatMap(Effect.fromOption),30 Effect.mapError(blocked)31 );32 44-/** What `head` changed against `base`, path by path, in path order. */33 const changesOf = (base: Snapshot, head: Snapshot): readonly Change[] =>34 Array.dedupe([...base.keys(), ...head.keys()])35 .toSorted()36 .flatMap((path): readonly Change[] => {22 unmodified lines59 },60 ];61 });62 75-/** An answer's head merged onto main: main's files with what the answer changed laid over them. */63 const merged = (input: {64 readonly repo: RepoName;65 readonly main: LandedSha;66 readonly fork: RepoName;21 unmodified lines88 main: input.main,89 });90 }91 105- // Main's files, with each path the answer changed as the answer left it.92 const files = new Map(textOf(main));93 94 for (const { path } of changes) {95 const text = head.get(path)?.text;7 unmodified lines103 104 return { changes, files: files satisfies Files };105 });106 121-/** The files a landing's tree is rebuilt from. */107 const rebuilt = (job: LandJob) =>108 Rebuild.$match(job.rebuild, {109 Compose: ({ files }) =>110 Effect.map(read(job.repo, job.main), (main) =>9 unmodified lines120 ({ files }) => files121 ),122 });123 139-/** The commit an answer's landing was made on: its base; otherwise main. */124 const baseOf = (job: LandJob) =>125 Rebuild.$is("Merge")(job.rebuild) ? job.rebuild.base : job.main;126 143-/** The Lander over the memory repo host, landing at the world's clock. */127 export const DevLander: Layer.Layer<Lander, never, RepoHost> = Layer.effect(128 Lander,129 Effect.gen(function* () {130 const host = yield* RepoHost;67 unmodified lines198 yield* Ref.update(landedBy, (all) =>199 new Map(all).set(job.requestId, sha)200 );201 219- // 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);204 205 yield* host206 .push(job.repo, into.source, [67 unmodified linesmodified: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.3 import { Projection, ProjectedEvent } from "@repo/project/projection";4 import { Context, Effect, Layer, Ref, Schema } from "effect";5 6 const decodeProjected = Schema.decodeUnknownEffect(7 Schema.toCodecJson(ProjectedEvent)8 );9 16-/** Every event the world's projects have projected, in the order they first arrived. */10 export class DevProjected extends Context.Service<11 DevProjected,12 { readonly events: Effect.Effect<readonly ProjectedEvent[]> }13 >()("web/dev/DevProjected") {}14 22-/** A fresh, empty projection, and the reading of it. */15 export const DevProjection: Layer.Layer<Projection | DevProjected> =16 Layer.effectContext(17 Effect.gen(function* () {18 const taken = yield* Ref.make<ReadonlyMap<string, ProjectedEvent>>(31 unmodified linesmodified: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- */1 import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";2 import type { ProjectApi } from "@repo/project/project";3 import { Projects } from "@repo/project/projects";4 import type { HarnessAudit } from "@repo/protocol/audit";17 unmodified lines22 import type { Files } from "./git.ts";23 24 const mainRef = RefName.make("refs/heads/main");25 47-/** People who propose and flag in datekit; nobody vouched for them. */26 export const visitors = {27 flagger: Handle.make("sefa"),28 proposer: Handle.make("tove"),29 regular: Handle.make("wren"),30 } as const;31 54-/** Everyone in the seed: the people a dev token may sign in as. */32 export const devPeople: readonly Handle[] = [33 operator,34 datekitPeople.decider,35 datekitPeople.zones,6 unmodified lines42 ];43 44 const as = (handle: Handle) => Person.make({ handle });45 69-/**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- */46 const bramsHarness = {47 harness: "claude-code",48 model: "haiku",49 } as const satisfies HarnessAudit;50 78-/** A commit of `files` on `parent` (or a first commit), by `author`, at the world's time. */51 const commitOf = (input: {52 readonly author: Handle;53 readonly files: Files;54 readonly message: string;14 unmodified lines69 70 return { commit, source: into.source };71 });72 101-/** A commit pushed to `repo`'s main with a compare-and-swap from `parent`. */73 const 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 lines85 86 return commit;87 });88 118-/** The files of `repo` at `commit`, which the seed itself pushed. */89 const filesOf = (repo: RepoName, commit: CommitSha) =>90 Effect.flatMap(filesAt(repo, commit), Effect.fromOption);91 122-/** Moves the world's clock to the calendar's minute `minute`. */92 const at = (minute: number) =>93 Effect.flatMap(Effect.service(DevClock), (clock) =>94 clock.set(devMinute(minute))95 );96 128-/**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- */97 export const startedAt = (98 project: ProjectName,99 initializer: Handle,100 files: Files,21 unmodified lines122 123 return { api, landed };124 });125 162-/** A project made and adopted at the calendar's minute `minute`. */126 const started = (127 project: ProjectName,128 initializer: Handle,129 files: Files,3 unmodified lines133 startedAt(project, initializer, files, devMinute(minute)),134 ({ api }) => api135 );136 174-/** Each ask opened by `decider` from its files, a minute apart from `minute`. */137 export const opened = (138 api: ProjectApi,139 decider: Handle,140 asks: readonly (readonly [AskId, Opening])[],8 unmodified lines149 ),150 { discard: true }151 );152 191-/**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- */153 const answered = (154 api: ProjectApi,155 answerer: Handle,156 input: {40 unmodified lines197 requestId: RequestId.make(`push-${head}-${answerer}`),198 });199 });200 245-/** The decision that puts proposal `proposal` to `decider`. */201 const decisionOn = (api: ProjectApi, decider: Handle, proposal: ProposalId) =>202 Effect.flatMap(api.today(as(decider)), ({ decisions }) =>203 Effect.fromOption(204 Array.findFirst(4 unmodified lines209 )210 )211 );212 258-/** Proposals from a regular that datekit's decider declines, each on its own minute. */213 const DECLINED = [214 "parseISO accepts two-digit years.",215 "datekit wraps the Temporal API.",216 ];217 264-/** datekit: four asks opened, one answered and landed, one claimed, decisions waiting. */218 const seedDatekit = Effect.gen(function* () {219 const { contributor, decider } = datekitPeople;220 const api = yield* started(datekit.project, operator, datekit.files, 0);221 47 unmodified lines269 270 return api;271 });272 320-/** burrow: the migrate ask opened as its family, six children and a delete child waiting on them. */273 const seedBurrow = Effect.flatMap(274 started(burrow.project, operator, burrow.files, 15),275 (api) => opened(api, burrowPeople.decider, burrow.asks, 17)276 );277 326-/** The seed's last minute: the stray push. */278 const STRAY_MINUTE = 21;279 329-/** The calendar's instant the seed leaves the world's clock at. */280 export const seedEnd = devMinute(STRAY_MINUTE);281 332-/**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- */282 const strayPush = (api: ProjectApi) =>283 Effect.gen(function* () {284 const host = yield* RepoHost;285 const repo = RepoName.make(keyOf(datekit.project));20 unmodified lines306 repo,307 });308 });309 365-/**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- */310 export const seedDev: Effect.Effect<311 void,312 never,313 Projects | RepoHost | DevClock6 unmodified linesmodified: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- */1 import { RepoHost } from "@repo/artifacts/repo-host";2 import { rawFor } from "@repo/project/code/raw";3 import { Projects } from "@repo/project/projects";4 import { Contracts } from "@repo/protocol/contracts";11 unmodified lines16 import { seedDev, seedEnd } from "./seed.ts";17 import { devSessions } from "./sessions.ts";18 import { devWorldAt } from "./world.ts";19 29-/** How a dev world is made: with the fixtures or without, how soon the live landing comes, and when it is. */20 export 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 }25 44-/** The calendar's instant a seed with `fixtures` leaves the clock at. */26 const seedEndOf = (fixtures: FixtureMode) =>27 fixtures === "off" ? seedEnd : fixturesNow;28 48-/** A fresh world whose calendar starts at `start`, seeded; with the fixtures when `fixtures` asks for them. */29 const seededFrom = (start: DateTime.Utc, options: DevWorldOptions) => {30 const { fixtures = "off" } = options;31 32 return fixtures === "off"33 ? Layer.effectDiscard(seedDev).pipe(Layer.provideMerge(devWorldAt(start)))34 : withFixtures(fixtures, options.liveAfter, start);35 };36 57-/** A fresh world, seeded, at the time `options` asks for. */37 const seededWorld = (options: DevWorldOptions) => {38 const { fixtures = "off", time = "fixed" } = options;39 40 return time === "fixed"8 unmodified lines49 };50 51 const decodeProject = Schema.decodeUnknownOption(ProjectName);52 74-/**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- */53 const raw = Layer.unwrap(54 Effect.gen(function* () {55 const services = Context.make(RepoHost, yield* RepoHost).pipe(56 Context.add(Projects, yield* Projects)24 unmodified lines81 );82 })83 );84 111-/**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.86 export const devServer = (options: DevWorldOptions = {}) =>87 HttpRouter.toWebHandler(88 Layer.merge(89 RpcServer.layerHttp({10 unmodified linesmodified: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.3 import { authenticated } from "@repo/protocol/authenticate";4 import type { Handle } from "@repo/protocol/ids";5 import { Person } from "@repo/protocol/principal";6 import type { Authenticated } from "@repo/protocol/principal";1 unmodified line8 import type { Layer } from "effect";9 10 import { devPeople } from "./seed.ts";11 24-/** The dev token that signs in as `handle`. */12 export const devToken = (handle: Handle) => `dev-${handle}`;13 14 const tokens: ReadonlyMap<string, Handle> = new Map(15 devPeople.map((handle) => [devToken(handle), handle])16 );17 31-/** The person a dev token names, if it names one of the seed's people. */18 const personOf = (token: string) =>19 Option.map(Option.fromNullishOr(tokens.get(token)), (handle) =>20 Person.make({ handle })21 );4 unmodified linesmodified: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- */1 import type { RepoHost } from "@repo/artifacts/repo-host";2 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3 import type { EvidenceStore } from "@repo/checks/evidence-store";4 import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";15 unmodified lines20 import { DevFrontPage } from "./front-page.ts";21 import { DevLander } from "./lander.ts";22 import { DevProjection } from "./projection.ts";23 39-/** Every port a project needs but its store, shared by every project in the world. */24 const ports = Layer.mergeAll(25 AlarmsMemory,26 AnswerRunsInline,27 cannedDrafter,3 unmodified lines31 Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)),32 Layer.provideMerge(RepoHostMemory)33 );34 51-/** The project service over every port, before anything reads it. */35 const core = withDraftRunsInline(ProjectsMemory).pipe(36 Layer.provideMerge(ports)37 );38 56-/** What the read side of a world is built over: its projects and their projected events. */39 export type DevCore = Layer.Success<typeof core> | DevClock;40 59-/**60- * A fresh world whose front page and handlers read through `between`,61- * which may stand in for the projects and the projected events it is62- * given (the fixtures do, `fixtures.ts`), with its calendar starting at63- * `start`. Built twice, it is two worlds.64- */41 export const devWorldWith = <Out, E, In extends DevCore>(42 between: Layer.Layer<Out, E, In>,43 start: DateTime.Utc = devStart44 ) =>3 unmodified lines48 Layer.provideMerge(devClockAt(start)),49 Layer.fresh50 );51 76-/**77- * A fresh, empty world: its projects, the front page over them, the lane78- * logs, the repo host the people's git pushes to, and its clock at79- * `start`. Built twice, it is two worlds.80- */52 export 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 lines4 import { backend } from "#backend";5 6 import { forwarded } from "../../../features/agents/forward.ts";7 8-// 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.8 export 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 lines3 4 import { mcpCard } from "../../features/agents/llms.ts";5 import { cardResponse } from "../../features/agents/respond.ts";6 7-// 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.7 export const Route = createFileRoute("/.well-known/mcp.json")({8 server: {9 handlers: {10 GET: () =>4 unmodified linesmodified:apps/web/src/routes/$owner/$project/answers/$ask.tsx+1 added-19 removed
24 unmodified lines25 import { pageHead } from "../../../../features/shared/head.ts";26 import { branchPage } from "../../../../server/cache-headers.ts";27 import { serverClient } from "../../../../server/client.ts";28 29-// 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.32-29 const answerPage = createServerFn({ method: "GET" })30 .validator((address: AnswerAddress) => address)31 .handler(({ data }) =>32 Effect.runPromise(readAnswer(data).pipe(Effect.provide(serverClient(env))))33 );34 39-/** No landing to read: what the page reads while the answer has not landed. */35 const noLanding = Atom.make(Option.none<LandingView>());36 42-/**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.38 const useLanding = (39 read: AnswerPageData,40 sha: LandedSha | undefined41 ): LandingView | undefined => {11 unmodified lines53 sha !== undefined && read.landing?.sha === sha ? read.landing : undefined54 );55 };56 67-/**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- */57 const 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));65 66 const { verdict } = Option.getOrElse(67 AsyncResult.value(64 unmodified lines132 </SeededAtoms>133 );134 };135 152-/** An address with no refusal behind it: a name that can name nothing, or a `?head=` that is no commit id. */136 const 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.";138 139 const AnswerNotFound = ({ data }: { readonly data?: unknown }) => {15 unmodified lines155 : 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 lines10 noAskAt,11 } from "../../../../features/ask/markdown.ts";12 import { serverClient } from "../../../../server/client.ts";13 14-// 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.18-19-/** The path params an ask's routes are handed, not yet decoded. */14 export interface AskParams {15 readonly ask: string;16 readonly project: string;17 }18 25-/** An ask's path, decoded: names the platform could hold. */19 export const AskPath = Schema.Struct({ ask: AskId, project: ProjectName });20 28-/** The protocol client a route calls the platform with, for the request it answers. */21 export type ClientFor = (request: Request) => Layer.Layer<Client>;22 31-/** `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.24 const visibility = Context.get(ShowAsk.annotations, Visibility);25 34-/**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- */26 export const askMarkdownHandler =27 (clientFor: ClientFor) =>28 ({29 params,31 unmodified linesmodified:apps/web/src/routes/$owner/$project/asks/$ask.tsx+1 added-22 removed
28 unmodified lines29 import { serverClient } from "../../../../server/client.ts";30 import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";31 import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";32 33-// 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`).37-38-/**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- */33 export const askPageHandler =34 (clientFor: ClientFor) =>35 <Next,>({36 next,7 unmodified lines44 wantsMarkdown(request)45 ? askMarkdownHandler(clientFor)({ params, request })46 : next();47 58-/**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.49 export const askPageHeaders = ({50 params,51 }: {52 readonly params: AskParams;13 unmodified lines66 );67 68 const root = getRouteApi("__root__");69 84-/**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- */70 const FreshAsk = ({71 platformUrl,72 read,73 viewer,3 unmodified lines77 readonly viewer: Handle | undefined;78 }) => {79 const { project } = read.ask;80 100- // Live: each event the project hears reads again what it changed.81 useAtomMount(watchAtom(project));82 83 const { ask, brief } = Option.getOrElse(84 AsyncResult.value(useAtomValue(askAtom(project, read.ask.id))),78 unmodified lines163 : 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 linesmodified:apps/web/src/routes/$owner/$project/blob/$rev/$.tsx-10 removed
22 unmodified lines23 import { CodeRail } from "../../tree/-code-rail.tsx";24 import { FilesButton } from "../../tree/-files-button.tsx";25 import { softLanding } from "../../tree/-soft-landing.ts";26 27-// 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.34-27 const BlobPageData = Schema.Struct({28 file: FileView,29 last: Schema.optionalKey(CommitView),30 now: Schema.DateTimeUtcFromString,6 unmodified lines37 readonly project: string;38 readonly rev: string;39 }40 49-/** The file for its page, or a not-found carrying the platform's refusal. */41 export 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 lines135 if (import.meta.env.SSR) {136 const plain =137 new URLSearchParams(location.searchStr).get("plain") === "1";138 148- // 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 linesmodified:apps/web/src/routes/$owner/$project/commit/$sha.tsx+2 added-17 removed
20 unmodified lines21 import { CommitRail } from "../tree/-code-rail.tsx";22 import { CommitPageData } from "../tree/-commit-files.ts";23 import { FilesButton } from "../tree/-files-button.tsx";24 25-// 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`.27 28 interface CommitParams {29 readonly project: string;30 readonly sha: string;31 }32 41-/** The commit for its page, or a not-found carrying the platform's refusal. */33 export 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 lines42 UnknownProject: notFoundFor,43 })44 );45 55- // 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);47 48 const territory = Option.isNone(answered)49 ? Option.none()34 unmodified lines84 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;89 102- // 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]);91 92 // The files the server sends highlighted: the same on both sides, since93 // both decide from the diff alone.33 unmodified lines127 },128 [diff.files]129 );130 145- // The layout is the reader's: kept in the address, with no read again.131 const onSplit = (next: boolean) => {132 setChosen(next);133 134 const { hash, pathname } = router.state.location;93 unmodified linesmodified:apps/web/src/routes/$owner/$project/commits/$rev.tsx-7 removed
19 unmodified lines20 import { notFoundFor } from "../../../../features/shared/refusals.ts";21 import { branchPage } from "../../../../server/cache-headers.ts";22 import { serverClient } from "../../../../server/client.ts";23 24-// 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.28-24 const LogPageData = Schema.Struct({25 commits: Schema.Array(CommitView),26 from: Schema.Int,27 next: Schema.UndefinedOr(Schema.Int),2 unmodified lines30 project: ProjectName,31 rev: Schema.String,32 });33 39-/** The kinds of commit a page may be filtered to. */34 const SHOWS: readonly LogShow[] = ["answers", "openings"];35 36 interface LogParams {37 readonly from?: number | undefined;1 unmodified line39 readonly project: string;40 readonly rev: string;41 }42 49-/** The page of the log, or a not-found carrying the platform's refusal. */43 export 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 linesmodified:apps/web/src/routes/$owner/$project/decisions/$decision.tsx+1 added-16 removed
49 unmodified lines50 import { pageHead } from "../../../../features/shared/head.ts";51 import { personalPage } from "../../../../server/cache-headers.ts";52 import { serverClient } from "../../../../server/client.ts";53 54-// `/$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.55 56 const root = getRouteApi("__root__");57 58 interface DecisionParams {8 unmodified lines67 readDecision(data).pipe(Effect.provide(serverClient(env, getRequest())))68 )69 );70 76-/** The decision the page found, when it found one. */71 const foundOf = (read: DecisionRead): Option.Option<FoundDecision> =>72 DecisionRead.guards.Found(read) ? Option.some(read) : Option.none();73 80-/** The finish the page found, when the decision is one. */74 const finishOf = (read: DecisionRead) =>75 Option.flatMap(foundOf(read), (found) =>76 isFinishDecision(found.decision)77 ? Option.some({ decision: found.decision, found })78 : Option.none()79 );80 88-/** The decision as the reader's choice left it, once taken on this page. */81 const takenHere = (82 decided: AsyncResult.AsyncResult<{ readonly decision: Decision }, unknown>,83 decision: Decision84 ) =>6 unmodified lines91 taken.decided !== undefined92 )93 );94 103-/** A finish's page: its files, folds, layout, read marks and keys. */95 const Finish = ({96 busy,97 decision,98 failure,13 unmodified lines112 const { platformUrl } = root.useLoaderData();113 const router = useRouter();114 const { ask, head } = decision.subject;115 125- // 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));118 119 const newerHead =30 unmodified lines150 );151 152 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;155 156 const defaults = useMemo(157 () =>79 unmodified lines237 238 const DecisionPage = () => {239 const loaded = Route.useLoaderData();240 252- // 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 );245 246 const [decided, decide] = useAtom(decideAtom);247 const here = useLocation({ select: hereOf });248 262- // 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 linesmodified:apps/web/src/routes/$owner/$project/proposals/$proposal.tsx-15 removed
26 unmodified lines27 import { notFoundFor, Refusals } from "../../../../features/shared/refusals.ts";28 import { personalPage } from "../../../../server/cache-headers.ts";29 import { serverClient } from "../../../../server/client.ts";30 31-// `/$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.38-31 type Shown = typeof ShowProposal.successSchema.Type;32 41-/** The proposal `name/id` names, encoded for the page; a not-found when there is none. */33 export 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 lines63 )64 )65 );66 76-/** The open decision on `proposal` in the reader's Today, if it is there. */67 const decisionOn = (68 today: AsyncResult.AsyncResult<Today, unknown>,69 proposal: Proposal70 ): Option.Option<DecisionId> =>7 unmodified lines78 subject.proposal === proposal.id79 ).pipe(Option.map(({ id }) => id))80 );81 92-/** Whether `who` is the proposer, or the reader decides in the project (their Today answered). */82 const mayRedraftAs = (83 who: AsyncResult.AsyncResult<Option.Option<Handle>, unknown>,84 today: AsyncResult.AsyncResult<Today, unknown>,85 proposal: Proposal3 unmodified lines89 Option.flatten(AsyncResult.value(who)),90 (handle) => handle.toLowerCase() === proposal.proposer.toLowerCase()91 );92 104-/** The page over the proposal's atom, which starts from what the loader read. */93 const 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));101 102 const { files, proposal } = Option.getOrElse(103 AsyncResult.value(useAtomValue(proposalAtom(project)(read.proposal.id))),53 unmodified lines157 };158 159 const decodeRefusals = Schema.decodeUnknownOption(Refusals);160 174-/** A proposal or a project the platform does not know: its refusal, as git prints it. */161 const 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 lines167 );168 169 export 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 === undefined9 unmodified linesmodified:apps/web/src/routes/$owner/$project/proposals/new.tsx-9 removed
20 unmodified lines21 import { ProposeView } from "../../../../features/propose/propose-view.tsx";22 import type { About } from "../../../../features/propose/propose-view.tsx";23 import { pageHead } from "../../../../features/shared/head.ts";24 25-// `/$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.30-25 const decodeProject = Schema.decodeUnknownOption(ProjectName);26 33-/** The line a why page points at, when the address names all three parts. */27 const AboutParts = Schema.Struct({28 about: RepoPath,29 at: CommitSha,30 line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),4 unmodified lines35 const decodeText = Schema.decodeUnknownOption(Schema.String);36 37 const decodeLine = Schema.decodeUnknownOption(Schema.Int);38 46-/** The address's line, as the form takes it. */39 const aboutOf = (search: {40 readonly about?: string | undefined;41 readonly at?: string | undefined;42 readonly line?: number | undefined;3 unmodified lines46 line,47 path: about,48 }));49 58-/** The form for `project`, once the browser knows who is signed in. */50 const Propose = ({ project }: { readonly project: ProjectName }) => {51 const navigate = useNavigate();52 const search = Route.useSearch();53 const here = useLocation({ select: hereOf });72 unmodified linesmodified:apps/web/src/routes/$owner/$project/raw/$rev/$.ts+1 added-4 removed
3 unmodified lines4 import { backend } from "#backend";5 6 import { forwarded } from "../../../../../features/agents/forward.ts";7 8-// 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.9 export 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 lines24 import { branchPage } from "../../../../../server/cache-headers.ts";25 import { serverClient } from "../../../../../server/client.ts";26 import { readFolderWithReadme } from "../../../../../server/folder.ts";27 28-// 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.33-28 const TreePageData = Schema.Struct({29 listing: TreeListing,30 now: Schema.DateTimeUtcFromString,31 project: ProjectName,6 unmodified lines38 readonly project: string;39 readonly rev: string;40 }41 48-/** The folder for its page, or a not-found carrying the platform's refusal. */42 export 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 linesmodified: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.3 import { ClientOnly } from "@tanstack/react-router";4 import { lazy, Suspense } from "react";5 6 import { RailSlot } from "../../../../features/shared/shell/rail-slot.tsx";1 unmodified line8 const Body = import.meta.env.SSR9 ? undefined10 : lazy(() => import("./-rail-body.tsx"));11 21-/** The ref line's place, the height the switcher will take. */12 const Placeholder = () => (13 <div aria-hidden="true" className="border-rule h-12 shrink-0 border-b" />14 );15 26-/** The rail's body, once the browser has it. */16 const Later = ({ commit }: { readonly commit: boolean }) =>17 Body === undefined ? (18 <Placeholder />19 ) : (3 unmodified lines23 </Suspense>24 </ClientOnly>25 );26 38-/** The rail's slot on a folder's, a file's and a why page. */27 export const CodeRail = () => (28 <RailSlot label="Files">29 <Later commit={false} />30 </RailSlot>31 );32 45-/** The rail's slot on a commit's page. */33 export const CommitRail = () => (34 <RailSlot label="Changed files">35 <Later commit />36 </RailSlot>1 unmodified linemodified: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- */1 import { CommitDiff } from "@repo/protocol/domain/code";2 import { ProjectName } from "@repo/protocol/ids";3 import { Schema } from "effect";4 5 export 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- */1 import { FolderTree } from "lucide-react";2 import { lazy, Suspense, useState } from "react";3 4 import { Button } from "@/components/ui/button";33 unmodified linesmodified: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- */1 import { useLocation } from "@tanstack/react-router";2 import { useEffect, useRef } from "react";3 4 import { Sheet, SheetContent } from "@/components/ui/sheet";17 unmodified lines22 });23 24 const opened = useRef(href);25 33- // 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 linesmodified: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- */1 import { useAtomValue } from "@effect/atom-react";2 import type { ChangedFile } from "@repo/protocol/domain/code";3 import { ProjectName } from "@repo/protocol/ids";4 import {27 unmodified lines32 const decode = Schema.decodeUnknownOption(CommitPageData);33 34 const NONE: readonly ChangedFile[] = [];35 47-/** The files the commit on the page changed; none while its data is not there. */36 const useCommitFiles = (): readonly ChangedFile[] => {37 const data: unknown = useMatch({38 from: "/$owner/$project/commit/$sha",39 select: (match) => match.loaderData,40 shouldThrow: false,41 });42 55- // Decoded once per read, not on every move between files.43 return useMemo(44 () =>45 Option.match(decode(data), {46 onNone: () => NONE,2 unmodified lines49 [data]50 );51 };52 66-/** Which page of a file the address is: its folder, its code, or why. */53 type Kind = "blob" | "tree" | "why";54 69-/** Where the reader is in the code: the project, the revision and the path, and which page. */55 const useCodeAddress = () => {56 const params = useParams({ strict: false });57 58 const kind = useLocation({14 unmodified lines73 74 return { kind, path, project, rev };75 };76 92-/** The page of `kind` for `path` at `rev`. */77 const hrefFor = (78 project: ProjectName,79 kind: Kind,80 rev: string,5 unmodified lines86 87 return (kind === "why" ? whyHref : blobHref)(project, rev, path);88 };89 106-/** The ref line: the revision, and the switcher to the same page at another. */90 const RefLine = ({91 kind,92 path,93 project,16 unmodified lines110 </div>111 );112 };113 131-/** The tree of every path at the revision, and the keys between its files. */114 const ProjectTree = ({115 kind,116 path,117 project,3 unmodified lines121 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 lines153 />154 ) : null;155 };156 176-/** A folder's, a file's or a why page's files: the ref line, then the tree. */157 export const CodeFiles = ({158 always = false,159 }: {160 readonly always?: boolean;18 unmodified lines179 </div>180 );181 };182 203-/** A commit's changed files, marked by how, and the keys between them. */183 export const CommitFiles = ({184 always = false,185 }: {186 readonly always?: boolean;42 unmodified lines229 </div>230 ) : null;231 };232 254-/** The rail's body: a commit's changed files, or the project's. */233 const RailBody = ({ commit }: { readonly commit: boolean }) =>234 commit ? <CommitFiles /> : <CodeFiles />;235 236 // `React.lazy` takes a module's default export.1 unmodified linemodified: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- */1 import { Client } from "@repo/protocol/contracts";2 import type { TreeListing } from "@repo/protocol/domain/code";3 import { RepoPath } from "@repo/protocol/ids";4 import type { ProjectName } from "@repo/protocol/ids";4 unmodified lines9 import { ancestorsOf } from "../../../../features/code/paths.ts";10 import { SoftLanding } from "../../../../features/code/soft-landing.ts";11 import { notFoundFor } from "../../../../features/shared/refusals.ts";12 22-/** Each folder above `path`, nearest first, then the root (none). */13 const above = (path: string): readonly Option.Option<RepoPath>[] => [14 ...ancestorsOf(path)15 .toReversed()16 .map((folder) => Option.some(RepoPath.make(folder))),17 Option.none(),18 ];19 30-/** A 404 for `refusal` that lands on the nearest folder above its path at its commit. */20 export const softLanding = (21 refusal: UnknownPath,22 project: ProjectName,23 rev: string40 unmodified linesmodified:apps/web/src/routes/$owner/$project/why/$rev/$.tsx-10 removed
24 unmodified lines25 import { CodeRail } from "../../tree/-code-rail.tsx";26 import { FilesButton } from "../../tree/-files-button.tsx";27 import { softLanding } from "../../tree/-soft-landing.ts";28 29-// 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.37-29 const WhyPageData = Schema.Struct({30 file: FileView,31 last: Schema.optionalKey(CommitView),32 now: Schema.DateTimeUtcFromString,8 unmodified lines41 readonly project: string;42 readonly rev: string;43 }44 54-/** The view and the file's text, or a not-found carrying the platform's refusal. */45 export 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 linesmodified:apps/web/src/routes/$owner/$project/env.tsx+1 added-19 removed
19 unmodified lines20 import { useProjectList } from "../../../features/shared/shell/context.ts";21 import { branchPage } from "../../../server/cache-headers.ts";22 import { serverClient } from "../../../server/client.ts";23 24-// 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.29-30-/**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- */24 const EnvPageData = Schema.Struct({25 now: Schema.DateTimeUtcFromString,26 project: ProjectName,27 schema: Schema.UndefinedOr(EnvSchemaView),28 });29 30 type EnvPageData = typeof EnvPageData.Type;31 42-/**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.33 export const readEnv = (name: string) =>34 Effect.gen(function* () {35 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(36 Effect.mapError(() => notFound())23 unmodified lines60 .handler(({ data }) =>61 Effect.runPromise(readEnv(data).pipe(Effect.provide(serverClient(env))))62 );63 79-/** The page over the env shape's atom, which starts from what the loader read and reads again when the env shape changes. */64 const FreshEnv = ({65 atom,66 now,67 read,1 unmodified line69 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));74 75 const schema = Option.getOrElse(76 AsyncResult.value(useAtomValue(atom)),36 unmodified lines113 };114 115 export 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 linesmodified:apps/web/src/routes/$owner/$project/index.tsx+2 added-31 removed
53 unmodified lines54 projectPageHandler,55 readProjectPage,56 } from "../../../server/project-page.ts";57 58-// 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`.68-58 const 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 );65 77-/** Where a project's Markdown is; none for a name that can name no project. */66 const markdownOf = (name: string) =>67 Option.map(decodeName(name), (project) => `/${project}/llms.txt`);68 81-/**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- */70 export const projectPageHeaders = ({71 params,72 }: {73 readonly params: { readonly project: string };6 unmodified lines80 vary: "Accept",81 }),82 });83 100-/** The page's head: its name, its README's first sentence, and its Markdown. */84 export const projectPageHead = ({85 loaderData,86 params,87 }: {19 unmodified lines107 };108 109 const root = getRouteApi("__root__");110 128-/**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.112 const WithFull = ({113 children,114 pick,115 }: {8 unmodified lines124 };125 126 const decodeAsk = Schema.decodeUnknownOption(AskId);127 149-/** An atom's value once it has one, else what the loader read. */128 const 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);134 157-/** The page over its atoms, each section as its read arrives, all kept live. */135 const LiveProject = ({136 data,137 platformUrl,138 selected,6 unmodified lines145 }) => {146 const { project } = data;147 const hydrated = useHydrated();148 172- // Live: each event the project commits makes these reads fetch again.149 useAtomMount(watchAtom(project));150 151 const asksRead = useAtomValue(asksAtom(project));152 const asks = valueOr(asksRead, data.asks, ({ asks: listed }) => listed);115 unmodified lines268 </SeededAtoms>269 );270 };271 296-/** The import offer for `project`, wired. */272 const Offer = ({ project }: { readonly project: ProjectName }) => {273 const importer = useImporter(project);274 275 return <ImportOffer importer={importer} project={project} />;276 };277 303-/**304- * No project at this address: at a source namespace's305- * (`/github.com/pallets/click`) the import offer, else the not-found.306- */278 const Unknown = () => {279 const { project } = Route.useParams();280 281 return Option.match(offerFor(project), {24 unmodified linesmodified:apps/web/src/routes/$owner/$project/ledger.tsx-10 removed
18 unmodified lines19 import { pageHead } from "../../../features/shared/head.ts";20 import { branchPage } from "../../../server/cache-headers.ts";21 import { serverClient } from "../../../server/client.ts";22 23-// 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.27-28-/** What the page's loader carries from the server, encoded: the ledger, and when it was read. */23 const LedgerPageData = Schema.Struct({24 ledger: Ledger,25 now: Schema.DateTimeUtcFromString,26 });27 28 type LedgerPageData = typeof LedgerPageData.Type;29 36-/** The ledger of the project `name`, or a not-found when there is no such project (a 404). */30 export const readLedger = (name: string) =>31 Effect.gen(function* () {32 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(33 Effect.mapError(() => notFound())16 unmodified lines50 .handler(({ data }) =>51 Effect.runPromise(readLedger(data).pipe(Effect.provide(serverClient(env))))52 );53 61-/** The page over the ledger's atom, which starts from what the loader read and reads again when the ledger changes. */54 const 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));62 63 const ledger = Option.getOrElse(64 AsyncResult.value(useAtomValue(atom)),26 unmodified lines91 };92 93 export 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 linesmodified:apps/web/src/routes/$owner/$project/llms[.]txt.ts-1 removed
2 unmodified lines3 4 import { serverClient } from "../../../server/client.ts";5 import { projectLlmsHandler } from "../../../server/llms.ts";6 7-// `/<project>/llms.txt`: one project for an agent (`server/llms.ts`).7 export const Route = createFileRoute("/$owner/$project/llms.txt")({8 server: {9 handlers: {10 GET: projectLlmsHandler(6 unmodified linesmodified:apps/web/src/routes/$owner/$project/people.tsx+1 added-15 removed
20 unmodified lines21 import { pageHead } from "../../../features/shared/head.ts";22 import { branchPage } from "../../../server/cache-headers.ts";23 import { serverClient } from "../../../server/client.ts";24 25-// 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.26 32-/**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- */27 const PeoplePageData = Schema.Struct({28 ledger: Ledger,29 policy: Schema.optionalKey(PublicPolicy),30 unevaluated: Schema.optionalKey(PolicyPending),31 });32 33 type PeoplePageData = typeof PeoplePageData.Type;34 45-/** The policy and ledger of the project `name`, or a not-found when there is no such project (a 404). */35 export const readPeople = (name: string) =>36 Effect.gen(function* () {37 const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(38 Effect.mapError(() => notFound())14 unmodified lines53 .handler(({ data }) =>54 Effect.runPromise(readPeople(data).pipe(Effect.provide(serverClient(env))))55 );56 68-/** The page over the two atoms, which start from what the loader read and read again as the project changes. */57 const 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));65 66 const { policy, unevaluated } = Option.getOrElse(67 AsyncResult.value(useAtomValue(policyAtom(project))),45 unmodified lines113 };114 115 export 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 linesmodified:apps/web/src/routes/$owner/$project/refs.tsx-7 removed
12 unmodified lines13 import { notFoundFor } from "../../../features/shared/refusals.ts";14 import { branchPage } from "../../../server/cache-headers.ts";15 import { serverClient } from "../../../server/client.ts";16 17-// 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.20-21-/** The refs for their page, or a not-found carrying the platform's refusal. */17 export const readRefsPage = (name: string) =>18 Effect.gen(function* () {19 const project = yield* Effect.fromOption(projectOf(name));20 const client = yield* Client;9 unmodified lines30 .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 lines63 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 linesmodified:apps/web/src/routes/$owner/$project/route.tsx+2 added-9 removed
1 import { createFileRoute, Outlet } from "@tanstack/react-router";2 3 import { projectParams } from "../../../server/addresses.ts";4 5-// 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.7 export 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 lines3 import { Effect, Option, Schema } from "effect";4 5 import { personPath } from "../../features/shared/paths.ts";6 7-// `/<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.8 9 const decodeHandle = Schema.decodeOption(Handle);10 11 const isReserved = (owner: string) =>12 reservedProjectNames.some((reserved) => reserved === owner.toLowerCase());13 18-/**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.15 export const ownerLoader = ({16 params,17 }: {18 readonly params: { readonly owner: string };17 unmodified linesmodified: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.2 import { Handle } from "@repo/protocol/ids";3 import { Option, Schema } from "effect";4 5 import type { Handled } from "../../server/session.ts";6 import { redirect, returnPath, sessionCookie } from "../../server/session.ts";7 17-/** How long a dev session lasts: a working day. */8 const DEV_SESSION_SECONDS = 8 * 60 * 60;9 10 const decodeHandle = Schema.decodeUnknownOption(Handle);11 15 unmodified linesmodified:apps/web/src/routes/auth/$.ts+2 added-8 removed
1 unmodified line2 import { Effect } from "effect";3 4 import type { Handled } from "../../server/session.ts";5 6-/**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.8 const devRoute = import.meta.env.DEV9 ? () => Effect.promise(() => import("./-dev.ts"))10 : undefined;11 23 unmodified linesmodified:apps/web/src/routes/auth/callback.ts-3 removed
2 unmodified lines3 4 import { serverClient } from "../../server/client.ts";5 import { callbackHandler } from "../../server/session.ts";6 7-// 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).7 export const Route = createFileRoute("/auth/callback")({8 server: {9 handlers: {10 GET: callbackHandler(env, (request) => serverClient(env, request)),3 unmodified linesmodified:apps/web/src/routes/auth/client.ts-2 removed
1 import { createFileRoute } from "@tanstack/react-router";2 3 import { clientMetadataHandler } from "../../server/session.ts";4 5-// The web's OAuth client, as a Client ID Metadata Document: its URL is the6-// client id the platform's /authorize reads.5 export const Route = createFileRoute("/auth/client")({6 server: {7 handlers: {8 GET: clientMetadataHandler,3 unmodified linesmodified:apps/web/src/routes/auth/signin.ts-2 removed
1 unmodified line2 import { env } from "cloudflare:workers";3 4 import { signInHandler } from "../../server/session.ts";5 6-// Sign-in starts here: to the platform's /authorize with PKCE7-// (src/server/session.ts).6 export const Route = createFileRoute("/auth/signin")({7 server: {8 handlers: {9 GET: signInHandler(env),3 unmodified linesmodified:apps/web/src/routes/auth/signout.ts-2 removed
1 import { createFileRoute } from "@tanstack/react-router";2 3 import { signOutHandler } from "../../server/session.ts";4 5-// Sign-out ends the session cookie: the header's form posts here, and a6-// plain link works too.5 export const Route = createFileRoute("/auth/signout")({6 server: {7 handlers: {8 GET: signOutHandler,4 unmodified linesmodified:apps/web/src/routes/auth/whoami.ts-2 removed
2 unmodified lines3 4 import { serverClient } from "../../server/client.ts";5 import { whoamiHandler } from "../../server/session.ts";6 7-// Who is signed in, as the platform's `status` names the session's caller,8-// asked in process through `#backend`.7 export const Route = createFileRoute("/auth/whoami")({8 server: {9 handlers: {10 GET: whoamiHandler((request) => serverClient(env, request)),3 unmodified linesmodified:apps/web/src/routes/docs/{$page}[.]md.ts-5 removed
4 unmodified lines5 6 import { commands } from "../../features/agents/catalog.ts";7 import { markdown } from "../../features/agents/respond.ts";8 9-// `/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.12-13-/** The route's handler as a function of the platform's URL, which its test hands in. */9 export const docsMarkdownHandler =10 (platformUrl: string) =>11 ({12 params,29 unmodified linesmodified:apps/web/src/routes/docs/$page.tsx-6 removed
12 unmodified lines13 import { docsHead, docsMarkdownPath } from "../../features/docs/head.ts";14 import { markdownLink } from "../../features/front/markdown.ts";15 import { branchPage } from "../../server/cache-headers.ts";16 17-// `/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.21-17 const root = getRouteApi("__root__");18 19 const DocsPage = () => {20 const { page: slug } = Route.useParams();7 unmodified lines28 });29 };30 31 export 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.void13 unmodified linesmodified:apps/web/src/routes/docs/index.tsx-4 removed
8 unmodified lines9 import { DocsIndexView } from "../../features/docs/docs-view.tsx";10 import { docsIndexHead } from "../../features/docs/head.ts";11 import { branchPage } from "../../server/cache-headers.ts";12 13-// `/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.16-13 const root = getRouteApi("__root__");14 15 const DocsIndex = () => {16 const { platformUrl } = root.useLoaderData();14 unmodified linesmodified:apps/web/src/routes/people/$handle.tsx-6 removed
11 unmodified lines12 import { pageHead } from "../../features/shared/head.ts";13 import { Reading, Unreachable } from "../../features/shared/pending.tsx";14 import { branchPage } from "../../server/cache-headers.ts";15 16-// A person's page: the roles they hold in each project's landings, by area,17-// read once by the browser. An address whose last part cannot be a handle18-// is a 404.19-16 const decodeHandle = Schema.decodeUnknownOption(Handle);17 18 const Credits = ({ handle }: { readonly handle: Handle }) =>19 AsyncResult.matchWithError(useAtomValue(creditsAtom(handle)), {15 unmodified lines35 };36 37 export 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 linesmodified:apps/web/src/routes/releases/$.ts-3 removed
3 unmodified lines4 import { backend } from "#backend";5 6 import { forwarded } from "../../features/agents/forward.ts";7 8-// 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.8 export const Route = createFileRoute("/releases/$")({9 server: { handlers: forwarded(backend, env) },10 });modified:apps/web/src/routes/__root.tsx+6 added-39 removed
23 unmodified lines24 import { themeColors } from "../features/shared/theme.ts";25 26 import styles from "../styles.css?url";27 28-// 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.29 34-/**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- */30 const siteFacts = createServerFn({ method: "GET" }).handler(() => ({31 platformUrl: env.PUBLIC_PLATFORM_URL,32 }));33 43-/**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.36 export const ThemeColors = () => (37 <>38 <meta39 content={themeColors.light}20 unmodified lines60 </body>61 </html>62 );63 76-/** The decider's Today, read in the browser for the rail's count. */64 const railToday = todayAtom();65 66 const TodayWaiting = () => {67 const today = useAtomValue(railToday);8 unmodified lines76 <RailCount count={waiting} of="decisions waiting" />77 );78 };79 93-/**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- */80 const TodayCount = () => {81 const hydrated = useHydrated();82 const signedIn = useSignedIn();83 84 return hydrated && signedIn ? <TodayWaiting /> : null;85 };86 87 const Root = () => {106- // Read in the browser after the page is up; the rail draws without it first.88 const listed = useAtomValue(projectsAtom);89 90 return (91 <TooltipProvider>8 unmodified lines100 </TooltipProvider>101 );102 };103 123-/**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- */104 export 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.";106 130-/** The site's icon, drawn to scale (`public/icons/icon.svg`). */107 const ICON_PATH = "/icons/icon.svg";108 133-/**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.111 const fontPreload = (href: string) =>112 ({113 as: "font",114 crossOrigin: "anonymous",1 unmodified line116 rel: "preload",117 type: "font/woff2",118 }) as const;119 147-/**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.121 export const rootHead = () => ({122 links: [123 { href: styles, rel: "stylesheet" },124 fontPreload(sansFont),26 unmodified linesmodified:apps/web/src/routes/agents.tsx-7 removed
7 unmodified lines8 import { AgentsView } from "../features/agents/setup-page.tsx";9 import { pageHead } from "../features/shared/head.ts";10 import { branchPage } from "../server/cache-headers.ts";11 12-// `/agents`: the reference an agent and the person running it read, drawn13-// from `@repo/agent-kit` for this stage's platform and the web's own origin14-// (the router's: the request's on the server, the page's in the browser),15-// so the server's render and the browser's agree. `/agents.md` is the same16-// text as Markdown.17-12 const root = getRouteApi("__root__");13 14 const AgentsPage = () => {15 const { platformUrl } = root.useLoaderData();5 unmodified lines21 };22 23 export 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 linesmodified:apps/web/src/routes/agents[.]md.ts-5 removed
3 unmodified lines4 5 import { commands } from "../features/agents/catalog.ts";6 import { markdown } from "../features/agents/respond.ts";7 8-// `/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.11-12-/** The route's handler as a function of the platform's URL, which its test hands in. */8 export const agentsMarkdownHandler =9 (platformUrl: string) =>10 ({ request }: { readonly request: Request }): Promise<Response> =>11 Promise.resolve(16 unmodified linesmodified:apps/web/src/routes/asks.tsx+1 added-19 removed
44 unmodified lines45 frontPageHandler,46 readFrontPage,47 } from "../server/front-page.ts";48 49-// `/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`.55-49 const TITLE = "Open asks";50 58-/** Where the page's Markdown is. */51 const MARKDOWN = "/llms.txt";52 53 const frontPageData = createServerFn({ method: "GET" }).handler(() =>54 Effect.runPromise(readFrontPage.pipe(Effect.provide(serverClient(env))))55 );56 65-/** The page's headers: kept briefly, varied by `Accept`, its Markdown named. */57 export const frontPageHeaders = () => ({58 ...branchPage,59 link: markdownLink(MARKDOWN),60 vary: "Accept",61 });62 72-/** The page's head: its title, its one sentence, and its Markdown. */63 export const frontPageHead = () => ({64 ...pageHead({ description: EXPLAINER, title: TITLE }),65 links: [markdownAlternateLink(MARKDOWN)],66 });67 78-/** The open asks, unfiltered: the page narrows them, so its filter can offer every kind. */68 const everyAsk = frontPageAtom({});69 70 const root = getRouteApi("__root__");71 83-/**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.73 const WithFull = ({74 children,75 pick,76 }: {8 unmodified lines85 };86 87 const decodeAsk = Schema.decodeUnknownOption(AskId);88 104-/** The page over its atoms, which start from what the loader read and stay live. */89 const LiveFront = ({90 data,91 filter,92 platformUrl,13 unmodified lines106 const hydrated = useHydrated();107 const key = projectsKey(data.events.map(({ project }) => project));108 const refresh = useAtomRefresh(everyAsk);109 126- // Live: each family's project, followed while the page is open.110 useAtomMount(followedAtom(key));111 112 // The loader read as anyone; once someone is signed in, read who may take what for them.113 useEffect(() => {78 unmodified lines192 </SeededAtoms>193 );194 };195 213-/** The filter, and the selected ask, from the address. */196 const readSearch = (search: {197 readonly ask?: unknown;198 readonly kind?: unknown;199 readonly project?: unknown;27 unmodified linesmodified:apps/web/src/routes/home.tsx-6 removed
9 unmodified lines10 import { reloadOnEnter } from "../features/shared/shell/selection.ts";11 import { personalPage } from "../server/cache-headers.ts";12 import { serverClient } from "../server/client.ts";13 14-// `/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.18-19-/** A page about its reader, kept by no cache. */14 export const homeHeaders = () => personalPage;15 16 const homePage = createServerFn({ method: "GET" }).handler(() =>17 Effect.runPromise(17 unmodified linesmodified:apps/web/src/routes/import.tsx-8 removed
5 unmodified lines6 import { useImporter } from "../features/import/use-importer.tsx";7 import { pageHead } from "../features/shared/head.ts";8 import { personalPage } from "../server/cache-headers.ts";9 10-// `/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.15-16-/** A page about its reader, kept by no cache. */10 export const importHeaders = () => personalPage;11 12 const ImportPage = () => {13 const { url } = Route.useSearch();2 unmodified lines16 17 return <ImportView {...importer} here={here} url={url} />;18 };19 27-/** The address's search: the URL to fill the form with, when it is text. */20 export const importSearch = ({21 url,22 }: {23 readonly url?: unknown;8 unmodified linesmodified:apps/web/src/routes/index.tsx+1 added-18 removed
21 unmodified lines22 import { branchPage } from "../server/cache-headers.ts";23 import { serverClient } from "../server/client.ts";24 import { landingHandler } from "../server/front-page.ts";25 26-// `/`, 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.33-26 const root = getRouteApi("__root__");27 36-/** Where the page's Markdown is. */28 const MARKDOWN = "/llms.txt";29 39-/**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.31 const landingData = createServerFn({ method: "GET" }).handler(() =>32 Effect.runPromise(33 readLandingProjects.pipe(34 Effect.flatMap(Schema.encodeEffect(LandingProjects)),1 unmodified line36 )37 )38 );39 54-/** The landing's headers: kept briefly, varied by `Accept`, its Markdown named. */40 export const landingHeaders = () => ({41 ...branchPage,42 link: markdownLink(MARKDOWN),43 vary: "Accept",44 });45 61-/** The landing's head: its title, its own sentence to unfurl with, and its Markdown. */46 export const landingHead = () => ({47 ...pageHead({48 description: LEDE,49 title: "A git platform with a typed gate",50 }),51 links: [markdownAlternateLink(MARKDOWN)],52 });53 70-/** A signed-in reader who came by a link goes on to their home. */54 const useHomeOnceSignedIn = () => {55 const signedIn = useSignedIn();56 const router = useRouter();57 42 unmodified linesmodified:apps/web/src/routes/install[.]sh.ts-3 removed
3 unmodified lines4 import { backend } from "#backend";5 6 import { forwarded } from "../features/agents/forward.ts";7 8-// 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.8 export 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 lines8 import { commands } from "../features/agents/catalog.ts";9 import { markdown, unavailable } from "../features/agents/respond.ts";10 import { serverClient } from "../server/client.ts";11 12-/**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- */18-19-/** The route's handler as a function of its client and the platform's URL, which its test hands in. */12 export const llmsFullHandler =13 (clientFor: (request: Request) => Layer.Layer<Client>, platformUrl: string) =>14 ({ request }: { readonly request: Request }): Promise<Response> =>15 Effect.runPromise(29 unmodified linesmodified:apps/web/src/routes/llms[.]txt.ts-1 removed
2 unmodified lines3 4 import { serverClient } from "../server/client.ts";5 import { frontLlmsHandler } from "../server/llms.ts";6 7-// `/llms.txt`: the platform for an agent (`server/llms.ts`).7 export const Route = createFileRoute("/llms.txt")({8 server: {9 handlers: {10 GET: frontLlmsHandler(6 unmodified linesmodified:apps/web/src/routes/rpc.ts-2 removed
3 unmodified lines4 import { backend } from "#backend";5 6 import { rpcHandler } from "../server/rpc.ts";7 8-// The browser's contracts: every call posts here, and the backend carries it9-// to the platform (src/server/rpc.ts).8 export const Route = createFileRoute("/rpc")({9 server: {10 handlers: {11 POST: rpcHandler(backend, env),3 unmodified linesmodified:apps/web/src/routes/today.tsx-10 removed
24 unmodified lines25 import { TodayView } from "../features/today/today-page.tsx";26 import { personalPage } from "../server/cache-headers.ts";27 import { serverClient } from "../server/client.ts";28 29-// `/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.34-35-/** What the address may name: a project to narrow to, and the decision selected. */29 const TodaySearch = Schema.Struct({30 decision: Schema.optionalKey(Schema.String),31 project: Schema.optionalKey(ProjectName),32 });1 unmodified line34 type TodaySearch = typeof TodaySearch.Type;35 36 const searchOf = Schema.decodeUnknownOption(TodaySearch);37 45-/** A page about its reader, kept by no cache. */38 export const todayHeaders = () => personalPage;39 48-/** What the atom holds now, or the loader's read until it has read. */40 const readFrom = (41 result: AsyncResult.AsyncResult<Today, unknown>,42 loaded: TodayRead43 ): TodayRead => {11 unmodified lines55 readToday(data).pipe(Effect.provide(serverClient(env, getRequest())))56 )57 );58 68-/** Today over its atom, which starts from what the loader read and reads again after a choice. */59 const LiveToday = ({60 data,61 project,62 }: {53 unmodified linesmodified: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.3 import {4 ProjectName,5 projectAddressOf,6 reservedProjectNames,9 unmodified lines16 17 const isReserved = (segment: string) =>18 reservedProjectNames.some((reserved) => reserved === segment.toLowerCase());19 35-/** `/github.com/pallets/…` as the route tree reads it: the owner in one segment. */20 const intoTree = (pathname: string) => {21 const [, host, account, ...rest] = pathname.split("/");22 23 return host !== undefined && account !== undefined && isSourceHost(host)24 ? ["", `${host}%2F${account}`, ...rest].join("/")25 : pathname;26 };27 44-/** The route tree's one-segment owner as the address spells it. */28 const outOfTree = (pathname: string) => {29 const [, owner, ...rest] = pathname.split("/");30 const slash = owner?.toUpperCase().indexOf("%2F") ?? -1;31 5 unmodified lines37 "/"38 );39 };40 58-/** The router's rewrite pair: a source path in, the real address out. */41 export const addressRewrite: LocationRewrite = {42 input: ({ url }) => {43 url.pathname = intoTree(url.pathname);44 5 unmodified lines50 return url;51 },52 };53 72-/**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`.55 interface ProjectParams {56 readonly owner: string;57 readonly project: string;58 }59 82-/**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- */60 export const projectParams = {61 parse: ({ owner, project }: ProjectParams): ProjectParams => ({62 owner,63 project: `${owner}/${project}`,8 unmodified lines72 };73 74 const decodeName = Schema.decodeOption(ProjectName);75 103-/**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.77 const movedTo = (location: string) =>78 new Response(null, {79 headers: { "cache-control": "public, max-age=86400", location },80 status: 301,81 });82 113-/**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- */83 const withoutGit = (spelled: string) => spelled.replace(/\.git$/iu, "");84 120-/**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- */85 export const canonicalAddress = (request: Request): Option.Option<Response> => {86 if (request.method !== "GET" && request.method !== "HEAD") {87 return Option.none();88 }22 unmodified lines111 )112 );113 };114 160-/** A Worker's `fetch`, as TanStack Start's server entry gives it. */115 interface Entry<Rest extends readonly unknown[]> {116 readonly fetch: (117 request: Request,118 ...rest: Rest119 ) => Promise<Response> | Response;120 }121 168-/** `entry`, answering first with the 301 a request's address needs. */122 export const addressedEntry = <Rest extends readonly unknown[]>(123 entry: Entry<Rest>124 ): Entry<Rest> => ({125 fetch: (request, ...rest) =>4 unmodified linesmodified: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.4 import { Effect, Option } from "effect";5 6 import type { Backend } from "./rpc.ts";7 import {2 unmodified lines10 settingCookies,11 withCredential,12 } from "./session.ts";13 28-/** `request` as the platform's own: the same path and query on its origin. */14 const onPlatform = (request: Request, platformUrl: string) => {15 const { pathname, search } = new URL(request.url);16 17 return new Request(new URL(`${pathname}${search}`, platformUrl), request);18 };19 35-/** `response` as it came, also expiring the session cookie and its kept handle. */20 const expiringSession = (response: Response) =>21 new Response(response.body, {22 headers: settingCookies(response.headers, clearedCookies()),23 status: response.status,2 unmodified lines26 27 const send = (env: Env, request: Request) =>28 Effect.promise(() => env.PLATFORM.fetch(request));29 46-/** The request's body read whole, so the call can be asked twice; none for a GET or HEAD. */30 const bodyOf = (request: Request) =>31 request.method === "GET" || request.method === "HEAD"32 ? Effect.succeed(null)33 : Effect.promise(() => request.arrayBuffer());32 unmodified linesmodified: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.3 4 export const branchPage = {5 "Cache-Control": "public, max-age=30, stale-while-revalidate=300",6 } as const satisfies Readonly<Record<string, string>>;4 unmodified linesmodified: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- */1 import { Client, Contracts } from "@repo/protocol/contracts";2 import { Layer } from "effect";3 import { FetchHttpClient } from "effect/http";4 import { RpcClient, RpcSerialization } from "effect/rpc";1 unmodified line6 import { backend } from "#backend";7 8 import type { Backend } from "./rpc.ts";9 16-/**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- */10 const inProcess =11 (over: Backend, env: Env, caller: Request | undefined): typeof fetch =>12 (input, init) => {13 const request = new Request(input, init);5 unmodified lines19 20 return over(request, env);21 };22 34-/** `serverClient` over any backend: the seam its test drives. */23 export const serverClientOver =24 (over: Backend) =>25 (env: Env, request?: Request): Layer.Layer<Client> =>26 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(7 unmodified lines34 Layer.succeed(FetchHttpClient.Fetch)(inProcess(over, env, request))35 )36 );37 50-/** The contracts as a server route calls them, through `#backend`. */38 export 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.4 import { Effect } from "effect";5 26-/** The `Cache-Control` of an answer kept by nobody: no shared cache, no browser. */6 export const KEPT_NOWHERE = "private, no-store";7 29-/** Headers that would decide what the edge keeps over `Cache-Control`. */8 const EDGE_OVERRIDES = ["cdn-cache-control", "cloudflare-cdn-cache-control"];9 32-/** The directives of a `Cache-Control` value, each as `name` or `name=value`, lower-cased. */10 const directivesOf = (cacheControl: string) =>11 cacheControl12 .split(",")13 .map((directive) => directive.trim().toLowerCase())14 .filter((directive) => directive !== "");15 39-/** Whether the request says who is reading it: any cookie, or an `Authorization`. */16 const speaksForSomeone = (request: Request) =>17 request.headers.has("cookie") || request.headers.has("authorization");18 43-/**44- * Whether `cacheControl` must be replaced by `KEPT_NOWHERE`: it is missing,45- * or it names a field (`private="set-cookie"`, `no-cache="…"`), the form46- * that lets the cache store the answer with that field stripped.47- */19+// A field-naming directive (`private="set-cookie"`) lets the cache store the answer with that field stripped.20 const unsafeFor = (cacheControl: string | null) =>21 cacheControl === null ||22 directivesOf(cacheControl).some(23 (directive) =>24 directive.startsWith("private=") || directive.startsWith("no-cache=")25 );26 55-/** Whether the cache bypasses an answer under `cacheControl`. */27 const keptNowhere = (cacheControl: string) =>28 directivesOf(cacheControl).some(29 (directive) => directive === "private" || directive === "no-store"30 );31 61-/** `vary` with `Cookie` among its headers. */32 const varyingByCookie = (vary: string | null) => {33 const names = (vary ?? "")34 .split(",")35 .map((name) => name.trim())3 unmodified lines39 ? names.join(", ")40 : [...names, "Cookie"].join(", ");41 };42 73-/** `response`'s headers as the edge may see them, for `request`. */43 const edgeHeaders = (request: Request, response: Response) => {44 const headers = new Headers(response.headers);45 46 for (const name of EDGE_OVERRIDES) {18 unmodified lines65 66 return headers;67 };68 100-/**101- * `response` as the edge may keep it, for `request`: the same status and102- * body (a stream stays a stream), under the two rules above.103- */69 export 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 });75 111-/** A Worker's `fetch`, as TanStack Start's server entry gives it. */76 interface Entry<Rest extends readonly unknown[]> {77 readonly fetch: (78 request: Request,79 ...rest: Rest80 ) => Promise<Response> | Response;81 }82 119-/** The Worker's `fetch` once every answer passes through `forTheEdge`. */83 interface EdgeEntry<Rest extends readonly unknown[]> {84 readonly fetch: (request: Request, ...rest: Rest) => Promise<Response>;85 }86 124-/**125- * `entry` with every answer it gives passed through `forTheEdge`; its other126- * arguments (the Worker's env and context) go on to it untouched.127- */87 export const edgeEntry = <Rest extends readonly unknown[]>(88 entry: Entry<Rest>89 ): EdgeEntry<Rest> => ({90 fetch: (request, ...rest) =>7 unmodified linesmodified: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- */1 import { Client } from "@repo/protocol/contracts";2 import type { FileView, Rev, TreeListing } from "@repo/protocol/domain/code";3 import type { ProjectName } from "@repo/protocol/ids";4 import { RepoPath } from "@repo/protocol/ids";5 unmodified lines10 } from "@repo/protocol/refusal";11 import { Effect, Option } from "effect";12 import type { RpcClientError } from "effect/rpc";13 21-/** The name most folders give their README, read beside the folder rather than after it. */14 const GUESS = "README.md";15 24-/**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).18 export const readFolderWithReadme = (input: {19 readonly path: Option.Option<RepoPath>;20 readonly project: ProjectName;21 readonly rev: Rev;54 unmodified linesmodified: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- */1 import { Client } from "@repo/protocol/contracts";2 import { Ask } from "@repo/protocol/domain/ask";3 import { ProjectEvent } from "@repo/protocol/domain/event";4 import { FrontPageEntry } from "@repo/protocol/domain/front-page";8 unmodified lines13 import { frontLlmsHandler } from "./llms.ts";14 import type { ClientFor } from "./llms.ts";15 import { credentialFrom } from "./session.ts";16 24-/** What the loader carries from the server: the asks, the families' parents in full, and their projects' events. */17 export const FrontPageData = Schema.Struct({18 entries: Schema.Array(FrontPageEntry),19 events: Schema.Array(20 Schema.Struct({ events: Schema.Array(ProjectEvent), project: ProjectName })3 unmodified lines24 });25 26 export type FrontPageData = typeof FrontPageData.Type;27 36-/** Four reads at once: a page holds a few families, each read once. */28 const AT_ONCE = 4;29 39-/** Each family on the page, by its project: `[project, parent]`. */30 const 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 );36 47-/**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.38 export const readFrontPage = Effect.gen(function* () {39 const client = yield* Client;40 const { entries } = yield* client.frontPage({});41 const families = familiesOf(entries);25 unmodified lines67 parents: Arr.getSomes(parents),68 });69 });70 88-/**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- */71 export const frontPageHandler =72 (clientFor: ClientFor, platformUrl: string) =>73 <Next>({74 next,12 unmodified lines87 )88 )89 : next();90 113-/** The answer that sends a signed-in reader from the landing to their home. */91 const toHome = () =>92 new Response(null, {93 headers: { "cache-control": KEPT_NOWHERE, location: HOME_PATH },94 status: 302,95 });96 120-/**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- */97 export const landingHandler =98 (clientFor: ClientFor, platformUrl: string) =>99 <Next>({100 next,13 unmodified linesmodified: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- */1 import { Client } from "@repo/protocol/contracts";2 import { ProjectName } from "@repo/protocol/ids";3 import { Array as Arr, Effect, Option, Schema } from "effect";4 import type { Layer } from "effect";6 unmodified lines11 } from "../features/agents/llms.ts";12 import { markdown, unavailable } from "../features/agents/respond.ts";13 import { stillWaiting } from "../features/front/families.ts";14 22-/** A route's client, for the request it answers. */15 export type ClientFor = (request: Request) => Layer.Layer<Client>;16 25-/**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- */17 export const frontLlmsHandler =18 (clientFor: ClientFor, platformUrl: string) =>19 ({ request }: { readonly request: Request }): Promise<Response> =>20 Effect.runPromise(16 unmodified lines37 );38 39 const decodeProject = Schema.decodeUnknownOption(ProjectName);40 53-/**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- */41 export const projectLlmsHandler =42 (clientFor: ClientFor, platformUrl: string) =>43 ({44 params,53 unmodified linesmodified: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.3 import { Effect } from "effect";4 import { normalizeTheme } from "shiki/core";5 import type {6 ThemeRegistrationAny,7 ThemeRegistrationResolved,8 } from "shiki/core";9 17-/** A theme as a collection holds it: its name, and its loader. */10 interface Descriptor {11 readonly name: string;12 readonly load: () => Promise<ThemeRegistrationResolved>;13 }14 23-/** A collection with no themes in it. */15 const empty = {16 getTheme: (_name: string): Descriptor | undefined => undefined,17 getThemes: (): readonly Descriptor[] => [],18 };3 unmodified lines22 export const shikiThemes = empty;23 24 export const themes = empty;25 35-/** A module's theme, whether it is the module or its default export. */26 const unwrap = (27 loaded: ThemeRegistrationAny | { default: ThemeRegistrationAny }28 ) => ("default" in loaded ? loaded.default : loaded);29 40-/** A named theme whose loader hands it over normalized, as Shiki draws with it. */30 export const createTheme = ({31 load,32 name,33 }: {13 unmodified linesmodified: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- */1 import { Client, PolicyOf } from "@repo/protocol/contracts";2 import { Ask, AskListing } from "@repo/protocol/domain/ask";3 import { FileView, TreeListing } from "@repo/protocol/domain/code";4 import { ProjectEvent } from "@repo/protocol/domain/event";19 unmodified lines24 import type { ClientFor } from "./llms.ts";25 26 export const decodeName = Schema.decodeUnknownOption(ProjectName);27 34-/** What the loader carries from the server, each read there when the platform gave it. */28 export const ProjectPageData = Schema.Struct({29 asks: Schema.optionalKey(Schema.Array(AskListing)),30 code: Schema.optionalKey(31 Schema.Struct({4 unmodified lines36 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 });43 44 export type ProjectPageData = typeof ProjectPageData.Type;45 46 const isUnknownProject = Schema.is(UnknownProject);47 56-/**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- */48 const optional = <A, E, R>(read: Effect.Effect<A, E, R>) =>49 read.pipe(50 Effect.asSome,51 Effect.catchCause((cause) =>2 unmodified lines54 : Effect.succeed(Option.none<A>())55 )56 );57 71-/** Four reads at once: a project holds a few families, each read once. */58 const AT_ONCE = 4;59 74-/**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- */60 export const readProjectPage = (name: string) =>61 Effect.gen(function* () {62 const project = yield* Effect.fromOption(decodeName(name));63 const client = yield* Client;60 unmodified lines124 project,125 }).pipe(Effect.orDie);126 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));127 146-/**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- */128 export const projectPageHandler =129 (clientFor: ClientFor, platformUrl: string) =>130 <Next>({131 next,17 unmodified linesmodified: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- */5-6-/**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.2 export type Backend = (request: Request, env: Env) => Promise<Response>;3 13-/** The `/rpc` route's handler: the request goes to `backend`, with the Worker's env. */4 export 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.4 import { Brand } from "@repo/brand";5 import { Client } from "@repo/protocol/contracts";6 import { Handle as HandleSchema } from "@repo/protocol/ids";7 import type { Handle } from "@repo/protocol/ids";8 import { Data, Effect, Option, Redacted, Schema } from "effect";9 import type { Layer } from "effect";10 34-/**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.12 export const SESSION_COOKIE = "__Host-session";13 42-/** The cookie the signed-in handle is kept in beside the session, for `whoami`. */14 export const HANDLE_COOKIE = "__Host-handle";15 45-/** The cookie a sign-in in progress waits in: its state, PKCE verifier and way back. */16 const SIGN_IN_COOKIE = "__Host-sign-in";17 48-/** How long a sign-in in progress waits for its callback: ten minutes. */18 const SIGN_IN_SECONDS = 600;19 20 /**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 */24 const SESSION_MARGIN_SECONDS = 60;25 57-/** The web's own sign-in paths that this module names in what it answers. */26 const AUTH_PATHS = {27 callback: "/auth/callback",28 client: "/auth/client",29 signIn: "/auth/signin",30 } as const;31 64-/** What a route's server handler is handed, of what it uses. */32 export interface Handled {33 readonly request: Request;34 }35 69-// --- The cookie -------------------------------------------------------------70-71-/**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.37 const Token = Schema.NonEmptyString.check(Schema.isPattern(/^[^\s",;\\]+$/u));38 39 const isToken = Schema.is(Token);40 81-/** A cookie value as it was set, if it decodes. */41 const decodedValue = Option.liftThrowable(decodeURIComponent);42 84-/** The value of the cookie `name` the request carries, if it carries one. */43 const cookieValue = (request: Request, name: string) =>44 Option.fromNullishOr(request.headers.get("cookie")).pipe(45 Option.flatMap((header) =>46 Option.fromUndefinedOr(6 unmodified lines53 Option.map((pair) => pair.slice(name.length + 1)),54 Option.flatMap(decodedValue)55 );56 99-/** The session cookie's value: the platform token this browser signed in with. */57 export const credentialFrom = (request: Request): Option.Option<string> =>58 cookieValue(request, SESSION_COOKIE).pipe(Option.filter(isToken));59 103-/**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- */60 export const withCredential = (61 request: Request,62 token: Option.Option<string>63 ): Request => {8 unmodified lines72 73 return new Request(request, { headers });74 };75 124-/** A cookie only this origin's HTTP requests carry, never the page's JavaScript. */76 const lockedCookie = (name: string, value: string, maxAgeSeconds: number) =>77 `${name}=${encodeURIComponent(value)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`;78 128-/** The `Set-Cookie` value that holds `token` for `maxAgeSeconds`. */79 export const sessionCookie = (token: string, maxAgeSeconds: number) =>80 lockedCookie(SESSION_COOKIE, token, maxAgeSeconds);81 132-/** The `Set-Cookie` value that ends the session now. */82 export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);83 135-/** The `Set-Cookie` values that end the session and forget its handle, now. */84 export const clearedCookies = () => [85 clearedCookie(),86 lockedCookie(HANDLE_COOKIE, "", 0),87 ];88 89 const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);90 143-/** `headers`, also setting each of `cookies` (each its own `Set-Cookie` line). */91 export const settingCookies = (92 headers: HeadersInit,93 cookies: readonly string[]94 ) => {5 unmodified lines100 101 return all;102 };103 157-// --- PKCE -------------------------------------------------------------------158-104 const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);105 161-/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */106 const randomText = (size: number) =>107 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(108 Effect.flatMap(encodeBase64Url),109 Effect.orDie110 );111 168-/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */112 export 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 );119 177-/** A fresh PKCE verifier and its challenge, and a fresh state, each 32 random bytes. */120 export const pkce = Effect.gen(function* () {121 const verifier = yield* randomText(32);122 123 return {2 unmodified lines126 verifier,127 };128 });129 188-// --- The handle kept beside the session --------------------------------------189-190-/**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- */130 const HANDLE_LEARNED_SECONDS = 24 * 60 * 60;131 197-/** The token's SHA-256, in base64url: what binds a kept handle to its session. */132 const 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 );139 206-/**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 `.`.141 const handleCookie = (token: string, handle: Handle, maxAgeSeconds: number) =>142 Effect.map(fingerprintOf(token), (fingerprint) =>143 lockedCookie(HANDLE_COOKIE, `${fingerprint}.${handle}`, maxAgeSeconds)144 );145 146 const decodeHandle = Schema.decodeUnknownOption(HandleSchema);147 218-/** The handle kept for the session `token`, if the request carries one kept for it. */148 const 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 lines155 : Option.none();156 })157 );158 230-/** The handle the platform's `status` names for the session `token`, asked through `clientFor`. */159 const handleOf = (160 clientFor: (request: Request) => Layer.Layer<Client>,161 origin: string,162 token: string9 unmodified lines172 )173 )174 );175 248-// --- Where the browser goes -------------------------------------------------249-250-/** The web's OAuth client id at `origin`: the URL of its metadata document. */176 const clientIdOf = (origin: string) => `${origin}${AUTH_PATHS.client}`;177 253-/** Where the platform sends the browser back to, at `origin`. */178 const redirectUriOf = (origin: string) => `${origin}${AUTH_PATHS.callback}`;179 256-/**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.181 export 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 lines187 Option.filter((path) => !path.startsWith("/auth/")),188 Option.getOrElse(() => "/")189 );190 272-/** A 302 to `location` that sets `cookies` and is never cached. */191 export const redirect = (location: string, cookies: readonly string[]) =>192 new Response(null, {193 headers: settingCookies(194 {5 unmodified lines200 ),201 status: 302,202 });203 286-/** A short page that says why signing in stopped, and how to start again. */204 const stoppedPage = (205 status: number,206 reason: string,207 cookies: readonly string[]11 unmodified lines219 { headers, status }220 );221 };222 306-// --- Sign-in ----------------------------------------------------------------307-308-/** A sign-in in progress, as its cookie holds it. */223 const PendingSignIn = Schema.Struct({224 return: Schema.String,225 state: Schema.String,226 verifier: Schema.String,6 unmodified lines233 const encodePending = Schema.encodeEffect(PendingCookie);234 235 const decodePending = Schema.decodeOption(PendingCookie);236 323-/**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- */237 export const signInHandler =238 (env: Env) =>239 ({ request }: Handled): Promise<Response> =>240 Effect.runPromise(23 unmodified lines264 ]);265 })266 );267 359-// --- The callback -----------------------------------------------------------360-361-/** Signing in stopped before a session: a 400 the person reads, or a 502 when the platform could not be asked. */268 class SignInStopped extends Data.TaggedError("SignInStopped")<{269 readonly reason: string;270 readonly status: 400 | 502;271 }> {}13 unmodified lines285 reason: "The platform could not be reached to complete this sign-in.",286 status: 502,287 });288 383-/** What the platform's `/token` answers a good code with, of what the web keeps. */289 const 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 lines295 const decodeTokenAnswer = Schema.decodeEffect(296 Schema.fromJsonString(TokenAnswer)297 );298 394-/** Trades `code` for an access token at the platform's `/token`, over `PLATFORM`. */299 const exchange = (300 env: Env,301 input: {302 readonly code: string;42 unmodified lines345 346 return answer;347 });348 445-/**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- */349 export const callbackHandler =350 (env: Env, clientFor: (request: Request) => Layer.Layer<Client>) =>351 ({ request }: Handled): Promise<Response> =>352 Effect.runPromise(41 unmodified lines394 )395 )396 );397 503-// --- Sign-out, who, and the client -------------------------------------------504-505-/** `POST` (or a plain link's `GET`) `/auth/signout`: the session and its kept handle end, and the browser goes home. */398 export const signOutHandler = (_handled: Handled): Response =>399 redirect("/", clearedCookies());400 509-/** `/auth/whoami`'s answer: the handle signed in, or nothing (`features/auth/who.ts` reads it). */401 const whoAnswer = (402 who: { readonly handle?: Handle },403 cookies: readonly string[] = []404 ) =>405 Response.json(who, {406 headers: settingCookies({ "cache-control": "no-store" }, cookies),407 });408 518-/**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- */409 export const whoamiHandler =410 (clientFor: (request: Request) => Layer.Layer<Client>) =>411 ({ request }: Handled): Promise<Response> =>412 Effect.runPromise(28 unmodified lines441 ),442 })443 );444 564-/**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- */445 export const webClientMetadata = (origin: string) => ({446 client_id: clientIdOf(origin),447 client_name: `${Brand.name} web`,448 client_uri: origin,2 unmodified lines451 response_types: ["code"],452 token_endpoint_auth_method: "none",453 });454 580-/** `GET /auth/client`: the web's Client ID Metadata Document. */455 export 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.3 import {4 createBundledHighlighter,5 createSingletonShorthands,6 guessEmbeddedLanguages,8 unmodified lines15 export * from "shiki/core";16 17 export { createJavaScriptRegexEngine } from "shiki/engine/javascript";18 30-/** No grammar is bundled by name; each is attached where it is used. */19 export const bundledLanguages: Record<20 string,21 DynamicImportLanguageRegistration22 > = {};23 36-/** No theme is bundled by name; the token theme is attached where it is used. */24 export const bundledThemes: Record<string, DynamicImportThemeRegistration> = {};25 26 /** Oniguruma compiles WebAssembly, which a Worker may not: never on the server. */27 export const createOnigurumaEngine = (): Promise<RegexEngine> =>19 unmodified linesmodified:apps/web/src/router.tsx-18 removed
6 unmodified lines7 } from "./features/shared/pending.tsx";8 import { routeTree } from "./routeTree.gen.ts";9 import { addressRewrite } from "./server/addresses.ts";10 11-/**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- */11 export const getRouter = () =>12 createRouter({13 defaultErrorComponent: RouteError,14 defaultNotFoundComponent: NotFoundPage,17 unmodified linesmodified: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- */1 import handler from "@tanstack/react-start/server-entry";2 3 import { addressedEntry } from "./server/addresses.ts";4 import { edgeEntry } from "./server/edge-cache.ts";2 unmodified linesmodified: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- */1 import { surfaced } from "@repo/protocol/contracts";2 import { Effect, Layer } from "effect";3 import { FetchHttpClient } from "effect/http";4 import { Atom, AtomRpc } from "effect/reactivity";5 import { RpcClient, RpcSerialization } from "effect/rpc";6 26-/** The contracts whose `Surfaces` annotation includes `web`. */7 export const webContracts = surfaced("web");8 29-/**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.11 export const sharedRuntime = Atom.context({12 memoMap: Layer.makeMemoMapUnsafe(),13 });14 41-/** The web's contracts as atoms: `ContractsClient.query(tag, payload, options)` and `ContractsClient.mutation(tag)`. */15 export 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 ) {}25 54-/**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.27 export const framedClient = RpcClient.make(webContracts).pipe(28 Effect.provide(29 RpcClient.layerProtocolHttp({ url: "/rpc" }).pipe(30 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerNdjson])3 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import {3 agentEndpoints,4 agentLimits,14 unmodified lines19 const webUrl = "https://web-test.example.workers.dev";20 21 const channels = agentSetup({ commands, platformUrl, webUrl });22 29-/** The entities React writes for text, and what each reads as. */23 const ENTITIES: ReadonlyMap<string, string> = new Map([24 ["'", "'"],25 ["&", "&"],26 [">", ">"],6 unmodified lines33 /&(?:#x27|amp|gt|lt|quot);/gu,34 (entity) => ENTITIES.get(entity) ?? entity35 );36 44-/** What a reader sees: the markup without its tags, entities decoded. */37 const textOf = (html: string) => decoded(html.replaceAll(/<[^>]+>/gu, ""));38 47-/** The text of every `<code>` in `html`, in order. */39 const codeOf = (html: string) =>40 [...html.matchAll(/<code\b[^>]*>(?<body>.*?)<\/code>/gsu)].map(41 ({ groups: found }) => textOf(found?.body ?? "")42 );43 53-/** The page at `/agents`, inside a router. */44 const page = renderAt(45 "/agents",46 <AgentsView commands={commands} platformUrl={platformUrl} webUrl={webUrl} />47 );48 59-/** The section whose id is `id`: its markup, from its tag to its close. */49 const sectionOf = (html: string, id: string) => {50 const start = html.indexOf(`<section aria-labelledby="${id}"`);51 const end = html.indexOf("</section>", start);52 215 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import type { Verdict } from "@repo/protocol/domain/answer";54 unmodified lines59 const refused = verdictOf(60 Outcome.cases.Refused.make({ refusals: [checksFailed, heldBackFailed] })61 );62 72-/** Each element that names a stage, as `[stage, state]`. */63 const 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;67 68 return stage === undefined || state === undefined ? [] : [[stage, state]];69 });70 81-/** Each lane, in page order, as `[lane, result]`. */71 const 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 lines77 return lane === undefined || result === undefined ? [] : [[lane, result]];78 }79 );80 92-/** Each link to a commit page, in page order, as `[href, text]`. */81 const commitLinksOf = (markup: string) =>82 [83 ...markup.matchAll(84 /<a\b[^>]*href="(?<href>[^"]*\/commit\/[^"]*)"[^>]*>(?<inner>.*?)<\/a>/gu3 unmodified lines88 ? []89 : [[groups.href, plainText(groups.inner).trim()]]90 );91 104-/** The hero, and the run after it. */92 const heroOf = (markup: string) =>93 /<section aria-label="Outcome"[^>]*>(?<inner>.*?)<\/section>/su.exec(markup)94 ?.groups?.inner ?? "";95 96 const runOf = (markup: string) =>97 markup.slice(markup.indexOf('id="answer-gate"'), markup.indexOf("</main>"));98 112-/** The page's main pane, without the inspector. */99 const mainOf = (markup: string) =>100 /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";101 116-/** The inspector. */102 const asideOf = (markup: string) =>103 /<aside\b[^>]*>(?<inner>.*)<\/aside>/su.exec(markup)?.groups?.inner ?? "";104 105 const page = (423 unmodified lines529 ]);530 });531 });532 548-/** What the stub platform was asked: verdicts, landings, asks and replays. */533 interface Asked {534 readonly asks: number;535 readonly landings: number;536 readonly replays: number;537 readonly verdicts: number;538 }539 556-/** Events in datekit: bram claimed the ask and pushed, and another ask was claimed too. */540 const replay = [541 claimedEvent(1, "bram"),542 claimedEvent(2, "okafor", AskId.make("format-week")),543 judgedEvent(3, refused.outcome),1 unmodified line545 546 const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>547 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));548 566-/**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- */549 const platformAt = (550 asked: Ref.Ref<Asked>,551 outcome: Outcome,552 landingKnown = true,192 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import type { Verdict } from "@repo/protocol/domain/answer";3 import type { Ask } from "@repo/protocol/domain/ask";4 import { CheckSpec } from "@repo/protocol/domain/check";23 unmodified lines28 export const project = ProjectName.make("oscabriel/datekit");29 30 export const askId = AskId.make("parse-iso-week");31 38-/** The moment every view test renders at. */32 export const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");33 34 export const ask: Ask = {35 askedBy: Handle.make("ines-v"),22 unmodified lines58 paths: [Glob.make("packages/parse/**")],59 },60 };61 69-/** The brief as the platform renders it for `showAsk`; the web serves it untouched. */62 export const brief = `# Parse ISO week dates like 2026-W41-363 64 Ask \`parse-iso-week\` in datekit, a \`fix\` ask from ines-v.65 13 unmodified lines79 export const landedSha = LandedSha.make(80 "9b1c3e5d7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c"81 );82 91-/** A verdict on the ask's latest answer: lint passed, unit failed, one held-back area 6 of 7. */83 export 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 lines124 project,125 sha: landedSha,126 };127 137-/** The landing as a decider's finish made it: decided, and judged by held-back checks. */128 export const decidedLanding: LandingView = {129 ...landing,130 credits: [131 ...landing.credits,132 { handle: Handle.make("ines-v"), role: "Decided-by" },133 ],134 };135 146-/** The landing as one that needed neither a decider nor held-back checks makes it. */136 export const plainLanding: LandingView = {137 ask: askId,138 assisted: [],139 author: Handle.make("bram"),6 unmodified lines146 project,147 sha: landedSha,148 };149 161-/** When the events below happened. */150 const eventAt = DateTime.makeUnsafe("2026-10-07T11:30:00Z");151 164-/** `claimant` claimed `on`, as event `seq`. */152 export 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 });159 173-/** An answer at `head` to `on` was judged `outcome`, as event `seq`. */160 export 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 });167 182-/** An answer to `on` was pushed at `head`, as event `seq`. */168 export const pushedEvent = (169 seq: number,170 head = CommitSha.make(sha("b")),171 on = askId172 ) => ProjectEvent.cases.Pushed.make({ ask: on, at: eventAt, head, seq });173 189-/** `on` closed by a landing, as event `seq`. */174 export const closedEvent = (seq: number, on = askId) =>175 ProjectEvent.cases.AskClosed.make({176 ask: on,177 at: eventAt,8 unmodified lines186 );187 188 const familyDelete = AskId.make("retire-old-week-delete");189 206-/** One member of the family below: blocked by `blockedBy`, its parent named. */190 const member = (id: AskId, blockedBy: readonly AskId[]): Ask => ({191 ...ask,192 blockedBy,193 brief: { want: `Step ${id} of retiring oldWeek` },1 unmodified line195 kind: KindName.make("migrate"),196 parent: familyParent,197 });198 216-/** A migrate family in datekit: a parent, three children, and the delete child that waits on them. */199 export 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 lines214 kind: KindName.make("migrate"),215 } satisfies Ask,216 };217 237-/** The entities React writes for text, and what each reads as. */218 const ENTITIES: ReadonlyMap<string, string> = new Map([219 ["'", "'"],220 ["&", "&"],221 [">", ">"],3 unmodified lines225 226 export const markupOf = (element: ReactElement) =>227 renderToStaticMarkup(element);228 249-/** What a reader sees of `markup`: the text without its tags, entities decoded. */229 export const plainText = (markup: string) =>230 markup231 .replaceAll(/<[^>]+>/gu, " ")232 .replaceAll(1 unmodified line234 (entity) => ENTITIES.get(entity) ?? entity235 )236 .replaceAll(/\s+/gu, " ");237 259-/** What a reader sees of `element`, rendered. */238 export const textOf = (element: ReactElement) => plainText(markupOf(element));239 262-/** Whether each of `parts` appears in `text`, each after the one before. */240 export const inOrder = (text: string, parts: readonly string[]) => {241 let from = 0;242 243 for (const part of parts) {11 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import { AskId, ProjectName } from "@repo/protocol/ids";17 unmodified lines22 import { ask, askId, brief, project } from "./ask-fixtures.ts";23 24 const WEB = "https://web-test.example.workers.dev";25 34-/** Where the web's indexes are for datekit's asks, as the routes find them. */26 const index = { project, webUrl: WEB };27 37-/** An ask's Markdown as served: the brief's title, the banner naming the indexes, then the rest of the brief unchanged. */28 const [title = "", ...rest] = brief.split("\n");29 30 const served = [title, "", indexBanner(index), ...rest].join("\n");31 1 unmodified line33 34 const BROWSER =35 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";36 47-/**48- * A platform that knows datekit and its one ask, counting `showAsk` calls,49- * as a route's client.50- */37 const platformOf = (calls: Ref.Ref<number>) => () =>38 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(39 Layer.provide([40 Layer.mergeAll(17 unmodified lines58 asTester,59 ])60 );61 76-/** A platform that cannot be reached: every call dies on the way. */62 const unreachable = () =>63 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(64 Layer.provide([unanswered, asTester])65 );7 unmodified lines73 ask: askName,74 project: projectName,75 });76 92-/** What a response says, read whole. */77 const read = (response: Response) =>78 Effect.map(79 Effect.promise(() => response.text()),80 (body) => ({4 unmodified lines85 vary: response.headers.get("vary"),86 })87 );88 105-/** The page's own render, which a Markdown request must never reach. */89 const PAGE = new Response("<!doctype html><title>the page</title>");90 91 describe("an ask's URL with Accept: text/markdown", () => {92 it.effect(286 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import type { Ask } from "@repo/protocol/domain/ask";43 unmodified lines48 import { textIn } from "./markup.ts";49 50 const platformUrl = "https://platform-test.example.workers.dev";51 58-/** The markup inside the first `<pre>`. */52 const inPre = (markup: string) =>53 /<pre\b[^>]*>(?<inner>.*?)<\/pre>/su.exec(markup)?.groups?.inner;54 62-/** The page's main pane, without the inspector. */55 const mainOf = (markup: string) =>56 /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";57 66-/** The inspector. */58 const asideOf = (markup: string) =>59 /<aside\b[^>]*>(?<inner>.*)<\/aside>/su.exec(markup)?.groups?.inner ?? "";60 70-/** The context bar's trail. */61 const trailOf = (markup: string) =>62 /<nav aria-label="Breadcrumb"[^>]*>(?<inner>.*?)<\/nav>/su.exec(markup)63 ?.groups?.inner ?? "";64 8 unmodified lines73 {...more}74 />75 );76 87-/** The check's source, as the platform reads it. */77 const checkSource = (lines: number) => ({78 path: RepoPath.make("test/parse-week.test.ts"),79 sha: "f".repeat(40),80 text: Array.from(400 unmodified lines481 ).toContain("No answer is at this head.");482 });483 });484 496-/** What the stub platform was asked. */485 interface Asked {486 readonly asks: number;487 readonly files: number;488 readonly replays: number;4 unmodified lines493 494 const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>495 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));496 509-/** Events in datekit: tamsin claimed the ask, and another ask was claimed too. */497 const replay = [498 claimedEvent(1, "tamsin"),499 claimedEvent(2, "okafor", AskId.make("format-week")),500 ];501 515-/**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- */502 const platformOf = (503 asked: Ref.Ref<Asked>,504 {505 readable = true,158 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 3 import * as CacheHeaders from "../src/server/cache-headers.ts";4 import { branchPage, personalPage } from "../src/server/cache-headers.ts";22 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { AskId } from "@repo/protocol/ids";3 import { UnknownAsk } from "@repo/protocol/refusal";4 import { Effect, Exit, Option, Schema } from "effect";29 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Effect, Exit } from "effect";3 4 import { keys } from "../src/client/keys.ts";51 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { ProjectName } from "@repo/protocol/ids";3 import { Effect, Exit } from "effect";4 77 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { env } from "cloudflare:workers";3 import { Effect } from "effect";4 25 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { DecisionSubject } from "@repo/protocol/domain/decision";3 import { Unauthenticated } from "@repo/protocol/principal";4 import { Array, DateTime, Effect, Exit, Option, Schema } from "effect";94 unmodified lines99 ? decided.value.decision.decided100 : undefined;101 102 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");106 114- /** 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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { FileTree } from "@pierre/trees";3 import { ChangedFile } from "@repo/protocol/domain/code";4 import { Schema } from "effect";53 unmodified lines58 });59 60 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 );64 65 expect(markup).toContain("<file-tree-container");66 });67 });68 89-/** A tree over `PATHS` showing `current`, and the files it asked the page to open. */69 const treeAt = (current: string) => {70 const opened: string[] = [];71 const tree = new FileTree(treeOptionsFor({ current, paths: PATHS }));72 71 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { ChangedFile } from "@repo/protocol/domain/code";3 import { Option, Schema } from "effect";4 12 unmodified lines17 import { stepFrom } from "../src/features/code/file-keys.ts";18 19 const decode = Schema.decodeSync(ChangedFile);20 28-/** Lines `from` to `to`, as a file's text. */21 const lines = (from: number, to: number) =>22 `${Array.from(23 { length: to - from + 1 },24 (_, index) => `line ${from + index}`199 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { ChangedFile, CommitDiff, FileView } from "@repo/protocol/domain/code";3 import { ProjectName } from "@repo/protocol/ids";4 import { DateTime, Effect, Schema } from "effect";24 unmodified lines29 const decodeFile = Schema.decodeSync(FileView);30 31 const decodeFiles = Schema.decodeSync(Schema.Array(ChangedFile));32 44-/** A highlighted token, as Pierre draws one in the token theme. */33 const TOKEN = /--diffs-token-light:var\(--diffs-token-[a-z-]+/gu;34 47-/** How many highlighted tokens `markup` holds. */35 const tokensIn = (markup: string) => [...markup.matchAll(TOKEN)].length;36 50-/** How many server drawings `markup` holds. */37 const shadowRootsIn = (markup: string) =>38 [...markup.matchAll(/<template shadowrootmode="open">/gu)].length;39 40 const TYPESCRIPT = [3 unmodified lines44 "export const parse = (text: string): Date => fromIso(text);",45 "",46 ].join("\n");47 62-/** `count` lines of TypeScript. */48 const linesOf = (count: number) =>49 Array.from(50 { length: count },51 (_, index) => `export const n${index} = ${index};`52 ).join("\n");53 54 let blobs = 0;55 71-/** A file at `path`, with a blob id of its own, so no drawing is shared. */56 const fileAt = (path: string, text: string) => {57 blobs += 1;58 59 return decodeFile({6 unmodified lines66 truncated: false,67 });68 };69 86-/** The blob page's markup for `file`, as the server renders it once its loader has drawn the file. */70 const blobPage = (file: FileView) =>71 Effect.gen(function* () {72 yield* Effect.promise(() => drawFileAhead(file));73 24 unmodified lines98 email: "lin@example.com",99 name: "Lin",100 };101 119-/** A commit changing `files`, imported (no landing). */102 const commitOf = (files: readonly (typeof ChangedFile.Encoded)[]) =>103 Schema.decodeSync(CommitDiff)({104 commit: {105 author: signature,8 unmodified lines114 files,115 truncated: false,116 });117 136-/** The commit page's markup, as the server renders it once its loader has drawn the first files. */118 const commitPage = (diff: CommitDiff) =>119 Effect.gen(function* () {120 const drawn = drawnFiles(diff.files);121 21 unmodified lines143 />144 );145 });146 166-/** The markup of one file's section of a diff. */147 const sectionOf = (markup: string, path: string) =>148 new RegExp(149 `<section aria-label="${path.replaceAll(".", "\\.")}"[\\s\\S]*?</section>`,150 "u"151 ).exec(markup)?.[0] ?? "";152 173-/** An added file at `path`, `lines` long, with a blob id of its own. */153 const added = (path: string, lines: number) => {154 blobs += 1;155 156 return {192 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Client, Contracts } from "@repo/protocol/contracts";3 import type { Contract } from "@repo/protocol/contracts";4 import {51 unmodified lines56 import { reachingTransport } from "./transport.ts";57 58 const markupOf = (element: ReactElement) => renderToStaticMarkup(element);59 71-/** What a reader sees: the markup without its tags, entities decoded. */60 const textOf = (element: ReactElement) =>61 markupOf(element)62 .replaceAll(/<[^>]+>/gu, " ")63 .replaceAll("'", "'")2 unmodified lines66 .replaceAll(">", ">")67 .replaceAll("&", "&")68 .replaceAll(/\s+/gu, " ");69 82-/** Every `href` in `markup`, in order, entities decoded. */70 const hrefsOf = (markup: string) =>71 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map((match) =>72 (match.groups?.href ?? "").replaceAll("&", "&")73 );74 88-/** The markup from the element marked `marker` to the next element marked the same way. */75 const 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 line80 ? ""81 : markup.slice(start, next === -1 ? undefined : next);82 };83 98-/** The `<nav>` marked `attribute` (`data-slot="breadcrumb"`), whole. */84 const navOf = (markup: string, attribute: string) =>85 new RegExp(`<nav\\b[^>]*${attribute}[^>]*>[\\s\\S]*?</nav>`, "u").exec(86 markup87 )?.[0] ?? "";52 unmodified lines140 ],141 path: "src/format/locale",142 });143 159-/** A tag with a slash and an at sign: one URL-encoded segment. */144 const TAG = "@datekit/core@1.0.0";145 146 const TAG_SEGMENT = "%40datekit%2Fcore%401.0.0";147 142 unmodified lines290 ],291 truncated: false,292 });293 310-/** The markup of `<main>` alone: the page, without its inspector. */294 const mainOf = (markup: string) =>295 /<main\b[\s\S]*?<\/main>/u.exec(markup)?.[0] ?? "";296 314-/** The markup of the inspector alone. */297 const inspectorOf = (markup: string) =>298 /<aside\b[^>]*data-facts="inspector"[\s\S]*?<\/aside>/u.exec(markup)?.[0] ??299 "";300 319-/** How many times `part` appears in `text`. */301 const countIn = (text: string, part: string) => text.split(part).length - 1;302 322-/** The `<a …>` that reads `label`, in `markup`. */303 const anchorOf = (markup: string, label: string) =>304 new RegExp(`<a\\b[^>]*>${label}</a>`, "u").exec(markup)?.[0];305 306 describe(TreeView, () => {95 unmodified lines402 })403 );404 });405 426-/** Where a file's facts link their permalink, on the page of `mode`. */406 const permalink = (mode: "code" | "why") =>407 /href="(?<href>[^"]*)"[^>]*>Permalink</u.exec(408 markupOf(409 <FileFacts91 unmodified lines501 502 it("names the path once in the page, in its file header", () => {503 const main = mainOf(markupOf(page));504 526- // 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 lines894 ]);895 });896 });897 920-/** Lines `1` to `count`, as a file's text. */898 const linesUpTo = (count: number) =>899 `${Array.from({ length: count }, (_, index) => `line ${index + 1}`).join(900 "\n"901 )}\n`;902 926-/** `diff`, with an added file of 120 lines: long enough to start folded. */903 const long = decodeDiff({904 ...Schema.encodeSync(CommitDiff)(diff),905 files: [906 ...Schema.encodeSync(CommitDiff)(diff).files,223 unmodified lines1130 expect(textOf(page)).not.toContain("too large to show whole");1131 });1132 });1133 1158-/** A payload the platform was sent: one of the contracts'. */1134 type Sent = Rpc.Payload<Contract>;1135 1161-/** Datekit, or the refusal for any other project. */1136 const knownProject = (name: ProjectName) =>1137 name === datekit1138 ? Effect.void1139 : Effect.fail(new UnknownProject({ project: name }));1140 1167-/** Main, or its commit `AT`, or the refusal for any other revision. */1141 const knownRevision = (at: string | undefined) =>1142 at === undefined || at === "main" || at === AT1143 ? Effect.void1144 : Effect.fail(new UnknownRevision({ rev: at }));1145 1173-/** Datekit's refs with main landed and no tags or forks. */1146 const landedOnly = Schema.decodeSync(Refs)({1147 forks: [],1148 landed: LANDED,1149 project: "datekit",1150 tags: [],1151 });1152 1181-/** The refusal for a path datekit lacks at `AT`. */1153 const noPath = (path: RepoPath) =>1154 new UnknownPath({ commit: CommitSha.make(AT), path });1155 1185-/**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- */1156 const platformOf = (calls: Ref.Ref<readonly Sent[]>) => {1157 const sent = (payload: Sent) => Ref.update(calls, (all) => [...all, payload]);1158 1159 return Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(64 unmodified lines1224 ])1225 );1226 };1227 1262-/** What a page's read that ended in a not-found asked and carried. */1228 interface 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 }1232 1270-/** Runs a page's read against `platformOf`, which must end in a not-found. */1233 const refusedBy = <A, E>(1234 read: Effect.Effect<A, E, Client>1235 ): Effect.Effect<Refused> =>1236 Effect.gen(function* () {6 unmodified lines1243 expect(isNotFound(failed)).toBeTruthy();1244 1245 const data: unknown = isNotFound(failed) ? failed.data : undefined;1246 1285- // 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 lines1405 })1406 );1407 });1408 1448-/** The soft landing a page's read ended in. */1409 const landingOf = <A, E>(read: Effect.Effect<A, E, Client>) =>1410 Effect.gen(function* () {1411 const calls = yield* Ref.make<readonly Sent[]>([]);1412 118 unmodified lines1531 expect(hrefsOf(markupOf(element))).toContain("/asks");1532 });1533 });1534 1575-/** The line every code page's route answers its headers with. */1535 const HEADERS_LINE = "headers: () => branchPage";1536 1537 describe("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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Handle } from "@repo/protocol/ids";3 import { Schema } from "effect";4 112 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Contracts } from "@repo/protocol/contracts";4 import { RefNameText } from "@repo/protocol/domain/common";45 unmodified lines50 import { ContractsClient, webContracts } from "../src/surfaces.ts";51 52 const markupOf = (element: ReactElement) => renderToStaticMarkup(element);53 65-/** What a reader sees of `markup`: the text without its tags. */54 const plainTextOf = (markup: string) =>55 markup56 .replaceAll(/<[^>]+>/gu, " ")57 .replaceAll("'", "'")58 .replaceAll(""", '"')59 .replaceAll("&", "&")60 .replaceAll(/\s+/gu, " ");61 74-/** Today as the page reads it from the atom: listed, or why not. */62 const readOf = (result: AsyncResult.AsyncResult<Today, unknown>): TodayRead => {63 if (AsyncResult.isSuccess(result)) {64 return TodayRead.cases.Read.make({ today: result.value });65 }33 unmodified lines99 overflow: 0,100 unattended: [],101 });102 116-/** What the platform was asked, call by call. */103 interface Asked {104 readonly decide: readonly unknown[];105 readonly listAsks: number;106 readonly today: number;5 unmodified lines112 { readonly decision: Decision },113 DecisionClosed | UnknownDecision114 >;115 130-/**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- */116 const contracts = (asked: Ref.Ref<Asked>, answer: Decide) => {117 const decided = Ref.makeUnsafe(false);118 119 const handlers = Layer.mergeAll(27 unmodified lines147 Layer.provideMerge(Reactivity.layer)148 );149 };150 170-/** A registry whose atoms reach `contracts` instead of `/rpc`. */151 const registryOver = (152 layer: Layer.Layer<ContractsClient | Reactivity.Reactivity>153 ) =>154 Effect.acquireRelease(15 unmodified lines170 { project: datekit },171 { reactivityKeys: keys.project(datekit) }172 );173 194-/** Today and a read of the project, both on screen, read once; then `input` decided. */174 const decideOnce = (175 answer: Decide,176 input: {177 readonly choice: Choice;126 unmodified lines304 })305 );306 });307 329-/** The Accept button's opening tag. */308 const acceptOf = (markup: string) =>309 /<button[^>]*data-choice="accept"[^>]*>/u.exec(markup)?.[0] ?? "";310 311 describe("DecisionCard for an OpenProposal", () => {28 unmodified lines340 onDecide={() => {}}341 />342 );343 366- /** `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 lines358 proposal: draft === undefined ? wanted : { ...wanted, draft },359 };360 };361 385- /** 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 lines494 });495 496 const vellum = ProjectName.make("oscabriel/vellum");497 522-/** A waiver on the answer to escape-attribute-quotes, carrying the answer's diff of the marker's file. */498 const waiver: Decision = {499 deciders: [okonkwo],500 default: "decline",501 evidence: [170 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { ProjectName } from "@repo/protocol/ids";3 import { Effect } from "effect";4 import { renderToStaticMarkup } from "react-dom/server";7 unmodified lines12 import { wordTone } from "../src/features/shared/row.tsx";13 import { Workspace } from "../src/features/shared/shell/workspace.tsx";14 import { renderAt } from "./render.tsx";15 23-/** A `spacing` token's value in DESIGN.md's frontmatter. */16 const spacing = (name: string) =>17 new RegExp(`^ {2}${name}: "(?<value>[^"]+)"$`, "mu").exec(design)?.groups18 ?.value;19 28-/** The inspector's class list, as a page with facts draws it. */20 const inspectorClasses = (code: boolean) => {21 const markup = renderToStaticMarkup(22 <Workspace23 crumbs={[{ label: "Ledger" }]}78 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import { ProjectEvent } from "@repo/protocol/domain/event";23 unmodified lines28 const decider = devToken(Handle.make("ines-v"));29 30 const contributor = devToken(Handle.make("bram"));31 38-/**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- */32 const inFreshWorld = <A, E>(33 read: (34 as: (token?: string) => Layer.Layer<Client>35 ) => Effect.Effect<A, E, Scope.Scope>27 unmodified lines63 return yield* read(as);64 })65 );66 77-/** The client a layer from `as(token)` makes, for as long as the world lives. */67 const clientOf = (layer: Layer.Layer<Client>) =>68 Effect.map(Layer.build(layer), Context.get(Client));69 81-/** The front page and the project list, as anyone reads them. */70 const pages = inFreshWorld((as) =>71 Effect.gen(function* () {72 const anyone = yield* clientOf(as());73 const { entries } = yield* anyone.frontPage({});2 unmodified lines76 return { entries, projects };77 })78 );79 92-/** Every instant a reader of the seeded world can see. */80 const instants = inFreshWorld((as) =>81 Effect.gen(function* () {82 const anyone = yield* clientOf(as());83 const ines = yield* clientOf(as(decider));28 unmodified lines112 ];113 })114 );115 129-/** datekit's landed answer, as Today samples it and as `landing` reads it. */116 const landedAnswer = inFreshWorld((as) =>117 Effect.gen(function* () {118 const anyone = yield* clientOf(as());119 const ines = yield* clientOf(as(decider));12 unmodified lines132 return { landing, sampled };133 })134 );135 150-/** The project list beside datekit's landed answer, as anyone reads them. */136 const listedWithLanding = inFreshWorld((as) =>137 Effect.gen(function* () {138 const anyone = yield* clientOf(as());139 const ines = yield* clientOf(as(decider));18 unmodified lines158 };159 })160 );161 177-/** The project list beside each project's ledger, as anyone reads them. */162 const listedWithLedgers = inFreshWorld((as) =>163 Effect.gen(function* () {164 const anyone = yield* clientOf(as());165 const { projects } = yield* anyone.listProjects({});5 unmodified lines171 return { ledgers, projects };172 })173 );174 191-/**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.176 const seededWorlds = { timeout: 30_000 };177 178 describe("the dev seed", seededWorlds, () => {179 it.live("gives two fresh worlds equal front pages and project lists", () =>111 unmodified lines291 })292 );293 });294 315-/** Each of `paths` on a fresh world's own handler: its status, headers and body. */295 const fetched = (paths: readonly string[]) =>296 Effect.scoped(297 Effect.gen(function* () {298 const { dispose, handler } = devServer();39 unmodified lines338 })339 );340 });341 363-/**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- */342 const drafted = inFreshWorld((as) =>343 Effect.gen(function* () {344 const anyone = yield* clientOf(as());345 const ines = yield* clientOf(as(decider));52 unmodified linesmodified: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.3 import { ProjectName } from "@repo/protocol/ids";4 import { env } from "cloudflare:workers";5 import { Effect, Layer } from "effect";6 import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";9 unmodified lines16 export const WEB_URL = "http://localhost:3000";17 18 export const datekit = ProjectName.make("oscabriel/datekit");19 29-/** The decider of datekit in the dev world, and the token that signs them in. */20 export const DECIDER = "dev-ines-v";21 32-/**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- */22 const browser = (token?: string) =>23 Layer.effect(24 ContractsClient,25 RpcClient.make(webContracts, { flatten: true })20 unmodified lines46 ),47 Layer.provideMerge(Reactivity.layer)48 );49 65-/** A registry whose `ContractsClient` is `browser(token)`'s. */50 export const registryAs = (token?: string) =>51 AtomRegistry.make({52 initialValues: [53 Atom.initialValue(ContractsClient.runtime.layer, browser(token)),54 ],55 });56 73-/** An atom's value once it has one, past any refetch under way. */57 export 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 );64 82-/**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.66 export 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- */1 import { Client, Contracts } from "@repo/protocol/contracts";2 import { Handle } from "@repo/protocol/ids";3 import { Effect, Layer } from "effect";4 import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";35 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Client, Contracts } from "@repo/protocol/contracts";3 import { DecisionSubject } from "@repo/protocol/domain/decision";4 import type { Decision } from "@repo/protocol/domain/decision";25 unmodified lines30 const ask = (id: string) => AskId.make(id);31 32 const signedIn = (handle: string) => devToken(Handle.make(handle));33 39-/** A client of `handler`'s `/rpc`, whose calls carry `token` as their bearer when there is one. */34 const connect = (35 handler: (request: Request) => Promise<Response>,36 token?: string37 ) =>22 unmodified lines60 );61 62 type Reader = Effect.Success<ReturnType<typeof connect>>;63 70-/** A fresh world with `options`, served, and `read` run against it. */64 const inWorld = <A, E>(65 options: DevWorldOptions,66 read: (67 as: (token?: string) => Effect.Effect<Reader, never, Scope.Scope>10 unmodified lines78 );79 80 const withFixtures: DevWorldOptions = { fixtures: "on" };81 89-/** vellum's events, as `watch` replays them from the first. */82 const eventsOf = (client: Reader) =>83 Effect.map(84 Stream.runCollect(client.watch({ project: vellum })),85 (events): readonly ProjectEvent[] => events86 );87 96-/** The `AskClosed` events among `events`. */88 const closedIn = (events: readonly ProjectEvent[]) =>89 events.filter(ProjectEvent.guards.AskClosed);90 100-/** The tag of each answer state's verdict outcome, by ask. */91 const ANSWERS = {92 "carry-footnotes-to-epub": "Landed",93 "cli-version-flag": "Landed",94 "escape-attribute-quotes": "AwaitingDecision",38 unmodified lines133 };134 })135 );136 147-/** Each refusal of a refused outcome, as its tag and the place it points at. */137 const refusalsOf = (outcome: Outcome | undefined) =>138 outcome !== undefined && Outcome.guards.Refused(outcome)139 ? outcome.refusals140 : [];141 153-/**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- */142 const hunksOf = (patch: string) => {143 const hunks: { declared: string; counted: string }[] = [];144 let old = 0;145 let fresh = 0;27 unmodified lines173 174 return hunks;175 };176 193-/**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.178 const seededWorlds = { timeout: 30_000 };179 180 describe("the dev world's fixtures", seededWorlds, () => {181 it.live(527 unmodified lines709 )710 );711 });712 732-/** `at`'s distance from `from`, in milliseconds. */713 const millisFrom = (from: DateTime.DateTime, at: DateTime.DateTime) =>714 Duration.toMillis(DateTime.distance(from, at));715 736-/**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- */716 const timesIn = (options: DevWorldOptions) =>717 inWorld(options, (as) =>718 Effect.gen(function* () {719 const ines = yield* as(signedIn("ines-v"));19 unmodified lines739 return { decisions, first, overflow, second };740 })741 );742 767-/** A decision, keyed as the platform counts it: its id within its project. */743 const keyOf = ({ id, project }: Decision) => `${project}/${id}`;744 770-/**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.747 const placedAtThePresent = (fixtures: FixtureMode, end: DateTime.Utc) =>748 Effect.gen(function* () {749 const fixed = yield* timesIn({ fixtures });750 98 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { docPage, docPages } from "@repo/agent-kit/docs/index";3 import { Effect, Option } from "effect";4 104 unmodified lines109 });110 });111 });112 119-/** What `/docs/<page>.md` answers. */113 const served = (page: string) =>114 Effect.gen(function* () {115 const response = yield* Effect.promise(() =>116 docsMarkdownHandler(input.platformUrl)({29 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Client, Contracts } from "@repo/protocol/contracts";3 import { ProjectName } from "@repo/protocol/ids";4 import { asTester, unanswered } from "@repo/protocol/testing";17 unmodified lines22 const WEB_URL = "https://web-test.example.workers.dev";23 24 const PLATFORM_URL = "https://platform-test.example.workers.dev";25 36-/** A signed-in reader's cookie, as the browser sends it. */26 const SIGNED_IN = `${SESSION_COOKIE}=dev-ada`;27 39-/** A GET for `path` on the web host, with `headers`. */28 const get = (path: string, headers: HeadersInit = {}) =>29 new Request(`${WEB_URL}${path}`, { headers });30 43-/** What the edge sees of an answer: how long it may be kept, and what it varies by. */31 const kept = (response: Response) => ({32 cacheControl: response.headers.get("cache-control"),33 vary: response.headers.get("vary"),34 });35 49-/** An answer under `headers`, with a body. */36 const answer = (headers: HeadersInit, status = 200) =>37 new Response("the page", { headers, status });38 53-/** Every `Cache-Control` the web gives or passes on, and none. */39 const 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 lines227 ]);228 });229 });230 246-// --- The routes that read the reader's credential ----------------------------247-248-/** A platform that lists datekit and no asks, and answers nothing else. */231 const listingDatekit = () =>232 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(233 Layer.provide([234 Layer.mergeAll(14 unmodified lines249 asTester,250 ])251 );252 271-/** An env whose PLATFORM answers every request with a long-lived public answer. */253 const platformEnv: Env = {254 PLATFORM: untouchable<Fetcher>("PLATFORM", {255 fetch: () =>256 Promise.resolve(2 unmodified lines259 }),260 PUBLIC_PLATFORM_URL: PLATFORM_URL,261 };262 282-/**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.264 const CREDENTIAL_ROUTES: readonly (readonly [265 string,266 (request: Request) => Promise<Response>,267 ])[] = [48 unmodified lines316 )({ request: new Request(request, { body: "{}", method: "POST" }) }),317 ],318 ];319 344-/** A signed-in agent's request for `path`, as Markdown. */320 const signedInAt = (path: string) =>321 get(path, { accept: "text/markdown", cookie: SIGNED_IN });322 323 describe("a route that hands the reader's cookie on", () => {29 unmodified lines353 })354 );355 });356 382-/** The landing's GET, falling through to a page the edge may keep. */357 const landing = (request: Request) =>358 Promise.resolve(359 landingHandler(360 listingDatekit,52 unmodified lines413 })414 );415 });416 443-// --- The pages ---------------------------------------------------------------444-417 const routeSources: Readonly<Record<string, string>> = import.meta.glob(418 "../src/routes/**/*.{ts,tsx}",419 { eager: true, import: "default", query: "?raw" }420 );2 unmodified lines423 "../src/**/*.{ts,tsx}",424 { eager: true, import: "default", query: "?raw" }425 );426 455-/**456- * Where a page's loader or server function reaches the request it answers457- * (its cookie, its headers): TanStack Start's server helpers.458- */427 const readsTheRequest = /from "@tanstack\/react-start\/server"/u;428 429 describe("a page", () => {430 it("reads the reader's request only where it is kept nowhere", () => {35 unmodified linesmodified: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.3 import { describe, expectTypeOf, it } from "vitest";4 5 describe("the web Worker's Env", () => {6 it("reaches the platform through the PLATFORM service binding", () => {14 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Client, Contracts, EnvSchemaOf } from "@repo/protocol/contracts";4 import { EnvSchemaView } from "@repo/protocol/domain/env";16 unmodified lines21 const now = DateTime.makeUnsafe("2026-10-12T12:00:00Z");22 23 const decodeView = Schema.decodeSync(EnvSchemaView);24 33-/** datekit's items, encoded, as its `.env.schema` declares them. */25 const items: readonly (typeof EnvItem.Encoded)[] = [26 {27 key: "APP_ENV",28 required: true,28 unmodified lines57 tags: [],58 },59 ];60 70-/** datekit's env shape at its landed SHA, as `envShape` returns it. */61 const datekit = decodeView({62 at: "9b1c3e5d7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c",63 currentEnvKey: "APP_ENV",64 file: ".env.schema",6 unmodified lines71 const scriptAddress = ["javascript", "alert(1)"].join(":");72 73 const page = <EnvView now={now} schema={datekit} />;74 85-/** The markup of the item `key`: from its row to the next item's. */75 const 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 line80 ? ""81 : markup.slice(start, next === -1 ? undefined : next);82 };83 95-/** Each item's key, in the order the page lists them. */84 const keysOf = (markup: string) =>85 [...mainOf(markup).matchAll(/data-env-key="(?<key>[^"]*)"/gu)].map(86 (found) => found.groups?.key87 );239 unmodified lines327 );328 });329 });330 343-/** What the stub platform was asked: env shapes and ask lists. */331 interface Asked {332 readonly asks: number;333 readonly schemas: number;334 }335 336 const nothingAsked: Asked = { asks: 0, schemas: 0 };337 351-/**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- */338 const platformWhere = (339 asked: Ref.Ref<Asked>,340 { known, landed }: { readonly known: boolean; readonly landed: boolean }341 ) =>106 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import type { Ask } from "@repo/protocol/domain/ask";3 import { ProjectEvent } from "@repo/protocol/domain/event";4 import { LandingView } from "@repo/protocol/domain/landing";200 unmodified lines205 }).toStrictEqual({ claimed: "answerer", open: "none" });206 });207 });208 217-/** A child of `drop-legacy-fetch`, one per module. */209 const child = (module: string) => AskId.make(`drop-legacy-fetch-${module}`);210 211 describe(familyMarks, () => {212 const modules = [106 unmodified lines319 }).toStrictEqual({ none: 0, some: 9 });320 });321 });322 332-/** The 40-hex sha of the `n`th landing. */323 const shaOf = (n: number) => LandedSha.make(n.toString(16).padStart(40, "0"));324 325 describe(recentLandings, () => {326 const one = Schema.decodeSync(LandingView)({43 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Glob } from "@repo/protocol/domain/common";4 import { Outcome } from "@repo/protocol/domain/outcome";278 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import type { Ask } from "@repo/protocol/domain/ask";4 import { ProjectEvent } from "@repo/protocol/domain/event";101 unmodified lines106 states={states}107 />108 );109 118-/** The `<li>`s of the list named `label`, each as its text. */110 const itemsOf = (markup: string, label: string) => {111 const start = markup.indexOf(`aria-label="${label}"`);112 const end = markup.indexOf("</ol>", start);113 241 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import type { Verdict } from "@repo/protocol/domain/answer";4 import type { Ask } from "@repo/protocol/domain/ask";35 unmodified lines40 readMarks,41 writeMark,42 } from "../src/features/finish/read-marks.ts";43 55-/** The entities React writes for text, and what each reads as. */44 const ENTITIES: ReadonlyMap<string, string> = new Map([45 ["'", "'"],46 ["&", "&"],47 [">", ">"],2 unmodified lines50 ]);51 52 const markupOf = (element: ReactElement) => renderToStaticMarkup(element);53 66-/** What a reader sees of `markup`: the text without its tags, entities decoded. */54 const textIn = (markup: string) =>55 markup56 .replaceAll(/<[^>]+>/gu, " ")57 .replaceAll(1 unmodified line59 (entity) => ENTITIES.get(entity) ?? entity60 )61 .replaceAll(/\s+/gu, " ");62 76-/** What a reader sees of `element`. */63 const textOf = (element: ReactElement) => textIn(markupOf(element));64 65 const PLATFORM_URL = "https://platform-test.example.workers.dev";66 6 unmodified lines73 const base = CommitSha.make("1".repeat(40));74 75 const okonkwo = Handle.make("okonkwo");76 91-/** Two files changed, one added, one removed, one renamed. */77 const PATCH = [78 "diff --git a/src/parse.ts b/src/parse.ts",79 "index 1111111..2222222 100644",80 "--- a/src/parse.ts",119 unmodified lines200 {...extra}201 />202 );203 219-/** The files the server's diff draws, in its order. */204 const drawnFilesOf = (markup: string) =>205 [...markup.matchAll(/<section aria-label="(?<file>[^"]+)" data-file=/gu)].map(206 (match) => match.groups?.file207 );208 225-/** A refusal from the answer's first round, at line 2 of its test. */209 const placed: PlacedRefusal = {210 line: 2,211 path: "test/parse.test.ts",212 refusal: new Weakened({144 unmodified lines357 );358 });359 });360 378-/** A browser storage over a map, as `localStorage` behaves. */361 const storageOver = (kept: Map<string, string>): Storage => ({362 clear: () => {363 kept.clear();364 },9 unmodified lines374 kept.set(key, value);375 },376 });377 396-/** A storage that refuses every read and write, as a private window's may. */378 const refusing: Storage = {379 clear: () => {380 throw new Error("refused");381 },117 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Client, Contracts } from "@repo/protocol/contracts";3 import type { FileView, TreeListing } from "@repo/protocol/domain/code";4 import { BlobSha, CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";20 unmodified lines25 text: `# ${path}`,26 truncated: false,27 });28 36-/** A folder at the landed commit holding nothing but its README, when `readme` names one. */29 const folder = (readme?: string, path?: string): TreeListing => {30 const listing: Types.Mutable<TreeListing> = {31 at: landed,32 entries: [],12 unmodified lines45 46 return listing;47 };48 57-/**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- */49 const platform = (input: {50 readonly asked: Ref.Ref<readonly string[]>;51 readonly files: ReadonlyMap<string, FileView>;52 readonly listing: TreeListing;24 unmodified lines77 asTester,78 ])79 );80 95-/** The folder at `path` (the root when none) at main, with the paths of its README and the files asked for. */81 const readWith = (82 input: Omit<Parameters<typeof platform>[0], "asked">,83 path?: string84 ) =>98 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { untouchable } from "@repo/testkit/untouchable";4 import { Effect } from "effect";7 unmodified lines12 const PLATFORM_URL = "https://platform-test.example.workers.dev";13 14 const WEB_URL = "https://web-test.example.workers.dev";15 25-/** A PLATFORM binding that keeps each request it is handed and answers `answer`. */16 const platform = (answer: (request: Request) => Response) => {17 const handed: Request[] = [];18 19 const env: Env = {11 unmodified lines31 32 return { env, handed };33 };34 45-/** The production routes' handlers, over a fake PLATFORM. */35 const served = (answer: (request: Request) => Response) => {36 const binding = platform(answer);37 38 return { ...binding, handlers: forwarded(backend, binding.env) };77 unmodified lines116 })117 );118 });119 131-/** What a route says of its server handlers. */120 interface ServerRoute {121 readonly options: { readonly server?: { readonly handlers?: object } };122 }123 19 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { deleteChildId, splitFamily } from "@repo/project/migrate";4 import { Client, Contracts } from "@repo/protocol/contracts";28 unmodified lines33 import { reachingTransport } from "./transport.ts";34 35 const kind = Schema.decodeSync(KindName);36 45-/** The markup of the row for `ask`: from its `<li>` to the next row or group. */37 const rowOf = (markup: string, ask: string) => {38 const start = markup.indexOf(`data-ask="${ask}"`);39 40 const ends = ["data-ask=", "<section", "</main>"].flatMap((end) => {4 unmodified lines45 46 return start === -1 ? "" : markup.slice(start, Math.min(...ends));47 };48 58-/** The ask ids of the rows on the page, top to bottom. */49 const rowsIn = (markup: string) =>50 [...markup.matchAll(/<li\b[^>]*data-ask="(?<ask>[^"]+)"/gu)].map(51 (row) => row.groups?.ask52 );53 64-/** The markup of each project group's sticky header, by its project. */54 const 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);60 72-/** The list itself: from the toolbar to the end of main, the facts left out. */61 const listIn = (markup: string) =>62 markup.slice(markup.indexOf("data-toolbar"), markup.indexOf("</main>"));63 64 const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");57 unmodified lines122 123 const asksOf = (shown: readonly FrontPageEntry[]) =>124 shown.map(({ ask }) => ask.ask);125 138-/** The page's props, with nothing the loader read beyond `entries`. */126 const props = (127 filter: FrontFilter,128 more: Partial<FrontPageProps> = {}129 ): FrontPageProps => ({78 unmodified lines208 ).toStrictEqual({});209 });210 });211 225-/** A listing as the contracts return one. */212 const listing = (id: string, blockedBy: readonly string[] = []) =>213 Schema.decodeSync(AskListing)({214 ask: id,215 blockedBy,363 unmodified lines579 })580 );581 });582 597-/** The contracts over HTTP, each request answered by `answer`. */583 const 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 lines590 )591 )592 );593 609-/** The contracts over a fresh dev world; the world ends with the scope. */594 const devWorld = Layer.unwrap(595 Effect.gen(function* () {596 const { dispose, handler } = devServer();597 2 unmodified lines600 return clientOver(handler);601 })602 );603 620-/** A platform that answers the front page and never answers the list of projects. */604 const projectsNeverAnswer = Layer.effect(605 Client,606 RpcTest.makeClient(Contracts)607 ).pipe(11 unmodified lines619 620 /** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */621 const seededWorld = { timeout: 30_000 };622 640-/** The page as the route renders it from what its loader read. */623 const sentFrom = (data: FrontPageData, filter: FrontFilter = {}) =>624 renderAt(625 "/asks",626 <FrontPageView81 unmodified linesmodified: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.2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 5 import { pageHead } from "../src/features/shared/head.ts";6 import { rootHead } from "../src/routes/__root.tsx";7 14-/** Each meta's key as the router dedupes it: its `name`, else its `property`. */8 const keyOf = (meta: Readonly<Record<string, string>>) =>9 meta.name ?? meta.property ?? (meta.title === undefined ? "" : "title");10 18-/** The metas of `head` as `key: content` pairs (the title as `title`). */11 const metasOf = (head: {12 readonly meta: readonly Readonly<Record<string, string>>[];13 }) =>14 Object.fromEntries(43 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import type { AnswerView } from "@repo/protocol/domain/answer";4 import { ClaimView } from "@repo/protocol/domain/claim";26 unmodified lines31 import { renderAt } from "./render.tsx";32 33 const NOW = "2026-10-07T12:00:00.000Z";34 44-/** The page as the route renders it from what the loader sent. */35 const pageFrom = (encoded: typeof HomePageData.Encoded) =>36 Effect.gen(function* () {37 const data = yield* Schema.decodeEffect(HomePageData)(encoded);38 2 unmodified lines41 <HomeView now={data.now} read={data.read} />42 );43 });44 55-/** The page drawn from a signed-in read made here. */45 const pageOf = (read: Partial<typeof HomeRead.cases.Read.Type>) =>46 renderAt(47 "/home",48 <HomeView9 unmodified lines58 })}59 />60 );61 73-/** The sections' names, in order. */62 const sectionsOf = (markup: string) =>63 [...markup.matchAll(/<section\b[^>]*aria-label="(?<name>[^"]+)"/gu)].map(64 (found) => found.groups?.name65 );66 79-/** The commands a reader can copy: each in the DOM as text. */67 const commandsOf = (markup: string) =>68 [...markup.matchAll(/<code\b[^>]*>(?<command>.*?)<\/code>/gsu)].map((found) =>69 textIn(found.groups?.command ?? "").trim()70 );13 unmodified lines84 warnsAt: "2026-10-08T06:00:00.000Z",85 ...fields,86 });87 101-/** An answer refused because its claim lapsed, which a new claim can mend. */88 const 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 linesmodified: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- */1 import { RegistryContext } from "@effect/atom-react";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import { Contracts, InitProject } from "@repo/protocol/contracts";34 unmodified lines39 40 const signedIn = (url = CLICK) =>41 markupOf(<ImportView handle={oscabriel} here="/import" url={url} />);42 52-/** An input's opening tag, by its `name`. */43 const inputNamed = (markup: string, name: string) =>44 new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";45 56-/** Where a sign-in link in `markup` comes back to. */46 const returnOf = (markup: string) => {47 const href = /href="(?<href>\/auth\/signin[^"]*)"/u48 .exec(markup)49 ?.groups?.href?.replaceAll("&", "&");178 unmodified lines228 );229 });230 });231 243-/** `initProject`'s answer: the project made. */232 const made = (project: string) =>233 Schema.decodeSync(InitProject.successSchema)({234 project,235 remote: `https://platform.test/${project}.git`,65 unmodified lines301 expect(markup).toContain("<form");302 });303 });304 317-/**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.306 const Page = ({307 seen,308 }: {309 readonly seen?: ((importer: Importer) => void) | undefined;24 unmodified lines334 <Page seen={seen} />335 </RegistryContext.Provider>336 );337 356-/**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- */338 const browserWith = (339 sent: ImportPayload[],340 answer: (341 payload: ImportPayload26 unmodified lines368 ),369 ],370 });371 394-/** The form's fields as the page drew them: what pressing Import sends. */372 const fieldsIn = (markup: string) => {373 const value = (name: string) =>374 /value="(?<value>[^"]*)"/u375 .exec(inputNamed(markup, name))6 unmodified lines382 url: value("url"),383 };384 };385 409-/** Presses Import on the page drawn over `registry`, and waits for the answer. */386 const pressImport = (registry: AtomRegistry.AtomRegistry) =>387 Effect.gen(function* () {388 const importers: Importer[] = [];389 81 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { renderToStaticMarkup } from "react-dom/server";3 4 import {2 unmodified lines7 readShortcuts,8 writeShortcuts,9 } from "../src/features/shared/keys.tsx";10 17-/** A press of `key` outside any text field, with no modifier held. */11 const press = (key: string, inField = false) => ({12 altKey: false,13 ctrlKey: false,14 inField,15 key,16 metaKey: false,17 });18 26-/** A `Storage` whose every read and write throws, as a blocked one does. */19 const refusing: Storage = {20 clear: () => {21 throw new Error("blocked");22 },13 unmodified lines36 throw new Error("blocked");37 },38 };39 48-/** A `Storage` held in a map, as a browser's is. */40 const kept = (): Storage => {41 const items = new Map<string, string>();42 43 return {157 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 3 const routeSources: Readonly<Record<string, string>> = import.meta.glob(4 "../src/routes/**/*.{ts,tsx}",12 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Contracts } from "@repo/protocol/contracts";4 import { ProjectListing } from "@repo/protocol/domain/front-page";29 unmodified lines34 "/",35 <LandingView platformUrl={PLATFORM} projects={projects} webUrl={WEB} />36 );37 47-/** Every link's address, in the page's order. */38 const hrefsOf = (markup: string) =>39 [...markup.matchAll(/<a\b[^>]*href="(?<href>[^"]+)"/gu)].map(40 (found) => found.groups?.href41 );107 unmodified lines149 Effect.gen(function* () {150 const markup = yield* pageWith(listed);151 const text = textIn(markup).toLowerCase();152 163- // 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 lines180 })181 );182 });183 196-/** A platform that lists `projects`, and answers nothing else. */184 const listing = (projects: readonly ProjectListing[]) =>185 platformWith(186 Contracts.toLayerHandler("listProjects", () => Effect.succeed({ projects }))187 );29 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import type { LandingView } from "@repo/protocol/domain/landing";3 import { AskId, LandedSha } from "@repo/protocol/ids";4 import { Struct } from "effect";5 6 import { LandingList } from "../src/features/project/landings.tsx";7 import { landing, markupOf, now, plainText } from "./ask-fixtures.ts";8 15-/** Every `href` in `markup`, in order. */9 const hrefsOf = (markup: string) =>10 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map(11 (match) => match.groups?.href ?? ""12 );13 21-/** The markup of the list item for the landing `sha`. */14 const itemOf = (markup: string, sha: string) =>15 new RegExp(`<li\\b[^>]*data-landing="${sha}"[^>]*>[\\s\\S]*?</li>`, "u").exec(16 markup17 )?.[0] ?? "";18 27-/** `landing` without the ask it answers: a decider's own landing. */19 const unasked: LandingView = {20 ...Struct.omit(landing, ["ask"]),21 sha: LandedSha.make("e".repeat(40)),22 };23 33-/** An ask's opening: it opened `format-ordinal` and answers nothing. */24 const opening: LandingView = {25 ...unasked,26 opened: AskId.make("format-ordinal"),27 sha: LandedSha.make("f".repeat(40)),42 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import { ProjectListing } from "@repo/protocol/domain/front-page";37 unmodified lines42 const maintainers = LayerName.make("maintainers");43 44 const decodeLedger = Schema.decodeSync(Ledger);45 53-/** The ledger's own fields, decoded from the wire as `ledger` returns them. */46 const datekitRead = decodeLedger({47 entries: [],48 layers: [49 {12 unmodified lines62 postureLabel: "Open with sealed evidence",63 project: "datekit",64 });65 74-/** Its entries, each made (and checked) by the protocol's own constructors. */66 const entries: readonly LedgerEntry[] = [67 LedgerEntry.cases.LayerDeclared.make({68 at: DateTime.makeUnsafe("2026-10-09T10:00:00.000Z"),69 disclose: "sealed",58 unmodified lines128 const parserArea = AreaName.make("parser");129 130 const parserRoot = SuiteRoot.make(`sha256:7fbe4b${"2c3d".repeat(14)}a1`);131 141-/** The `parser` suite's commitment, published as the release landed. */132 const parserCommitment = LedgerEntry.cases.CommitmentPublished.make({133 area: parserArea,134 at: DateTime.makeUnsafe("2026-10-12T08:00:00.000Z"),135 authors: 3,1 unmodified line137 seq: 9,138 suite: parserRoot,139 });140 151-/** datekit's ledger once its maintainers layer holds the `export` and `parser` suites. */141 const datekit: Ledger = {142 ...datekitRead,143 entries: [...entries, parserCommitment],144 };145 157-/** A project with no visibility config: the platform's neutral ledger. */146 const open = decodeLedger({147 entries: [],148 layers: [],149 posture: "open",2 unmodified lines152 });153 154 const page = <LedgerView ledger={datekit} now={now} />;155 168-/** The entries' sequence numbers, in the order the page lists them. */156 const seqsOf = (markup: string) =>157 [...markup.matchAll(/data-seq="(?<seq>\d+)"/gu)].map((found) =>158 Number(found.groups?.seq)159 );160 174-/** The words of the first `<time>` after `marker` in `markup`. */161 const whenOf = (markup: string, marker: string) =>162 /<time\b[^>]*>(?<when>[^<]*)<\/time>/u.exec(163 markup.slice(markup.indexOf(marker))164 )?.groups?.when;165 180-/** Each history row's markup, in the order the page lists them. */166 const historyRowsOf = (markup: string) =>167 [168 ...mainOf(markup).matchAll(/<li\b[^>]*data-entry="[^"]*"[\s\S]*?<\/li>/gu),169 ].map(([row]) => row);170 186-/** Each history row's typed word, in order. */171 const wordsOf = (markup: string) =>172 historyRowsOf(markup).map((row) =>173 plainText(elementWith(row, "data-entry-word")).trim()174 );175 192-/** Whether a history row's word is drawn in the sealed role or in ink. */176 const toneOf = (row: string) =>177 /text-sealed/u.test(elementWith(row, "data-entry-word")) ? "sealed" : "ink";178 179 describe("a project's ledger", () => {302 unmodified lines482 expect(areaSummaries(open)).toStrictEqual([]);483 });484 });485 503-/** A platform that knows only datekit, counting the ledgers it is asked for. */486 const platformHandlers = (asked: Ref.Ref<number>) =>487 Layer.mergeAll(488 unanswered,489 Contracts.toLayerHandler("ledger", ({ project }) =>9 unmodified lines499 ),500 asTester501 );502 521-/** That platform, as the page's loader reaches it on the server. */503 const platformOf = (asked: Ref.Ref<number>) =>504 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(505 Layer.provide(platformHandlers(asked))506 );45 unmodified lines552 })553 );554 });555 575-/** Lets the atoms' fibers run until `done` holds, or long enough that it would have. */556 const runUntil = (done: Effect.Effect<boolean>) =>557 Effect.yieldNow.pipe(558 Effect.andThen(done),559 Effect.repeat({ times: 200, until: (held) => held })101 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Effect, Option } from "effect";3 4 import { addressedEntry, canonicalAddress } from "../src/server/addresses.ts";5 import { forTheEdge, KEPT_NOWHERE } from "../src/server/edge-cache.ts";6 7 const WEB_URL = "https://web-test.example.workers.dev";8 16-/** A request for `path` on the web host, by `method`. */9 const request = (path: string, method = "GET") =>10 new Request(`${WEB_URL}${path}`, { method });11 20-/** Where the 301 for `path` leads, if there is one. */12 const movedTo = (path: string) =>13 Option.map(canonicalAddress(request(path)), (response) => [14 response.status,15 response.headers.get("location"),16 ]);17 27-/** An entry that answers every request it is handed with the page. */18 const pages = {19 fetch: (_request: Request) => new Response("the page", { status: 200 }),20 };21 96 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Option } from "effect";3 4 import {96 unmodified linesmodified: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- */1 import { ProjectListing } from "@repo/protocol/domain/front-page";2 import { Schema } from "effect";3 4 export const TEN_LISTED = Schema.decodeSync(Schema.Array(ProjectListing))([8 unmodified lines13 { openAsks: 3, posture: "open", project: "oscabriel/hearth" },14 { openAsks: 7, posture: "open", project: "oscabriel/ember" },15 ]);16 22-/** The eight of `TEN_LISTED` that lead, in order. */17 export const EIGHT_LEADING = [18 "oscabriel/burrow",19 "oscabriel/ember",20 "github.com/pallets/click",6 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import type { CommandDoc } from "@repo/agent-kit/command-doc";3 import { fullLlms } from "@repo/agent-kit/full-llms";4 import { Brand } from "@repo/brand";37 unmodified lines42 const datekit = ProjectName.make("oscabriel/datekit");43 44 const burrow = ProjectName.make("oscabriel/burrow");45 53-/** A command row as `@repo/agent-kit`'s command list holds it. */46 const row = (47 path: readonly [string, ...string[]],48 summary: string,49 more: Partial<CommandDoc> = {}276 unmodified lines326 327 const words = catalog.map(({ path }) => path.join(" "));328 329 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 lines337 ).toStrictEqual([]);338 });339 });340 350-/** A platform that lists `listed` as its projects, and answers nothing else. */341 const listing = (listed: readonly ProjectListing[]) => () =>342 platformWith(343 Contracts.toLayerHandler("listProjects", () =>344 Effect.succeed({ projects: listed })345 )346 );347 358-/** A platform that cannot be reached: every call dies on the way. */348 const unreachable = () => unreachablePlatform;349 350 const getFull = () => new Request(`${webUrl}/llms-full.txt`);351 363-/** A fork's gateway address: its project's name, then the fork's parts. */352 const addressed = (repo: RepoName) =>353 Option.getOrElse(addressOfRepo(repo), () => repo);354 355 const read = (response: Response) =>38 unmodified lines394 const text = fullLlms({ commands: catalog, platformUrl, projects, webUrl });395 const parseIso = AskId.make("parse-iso");396 const ada = Handle.make("Ada");397 410- /** 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());403 417- /** 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 lines435 });436 });437 });438 453-/** A platform that lists `listed` as its projects and `listedAsks` as datekit's asks. */439 const listingWithAsks =440 (listed: readonly ProjectListing[], listedAsks: readonly AskListing[]) =>441 () =>442 platformWith(4 unmodified lines447 Effect.succeed({ asks: listedAsks })448 )449 );450 466-/** A request for `path` on the web host, accepting `accept`. */451 const getAt = (path: string, accept: string) =>452 new Request(`${webUrl}${path}`, { headers: { accept } });453 454 const BROWSER =455 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";456 473-/** What a handler answered: a response, or the page it fell through to. */457 const answered = (result: Promise<Response> | "the page") =>458 result === "the page"459 ? Effect.void460 : Effect.flatMap(4 unmodified lines465 vary: response.headers.get("vary"),466 }))467 );468 486-/** The head's link naming `href` as a page's Markdown. */469 const alternate = (href: string) => ({470 href,471 rel: "alternate",472 type: "text/markdown",117 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { CommitSha, ProjectName } from "@repo/protocol/ids";3 4 import { resolveRepoUrl } from "../src/features/markdown/resolve.ts";69 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { CommitSha, ProjectName } from "@repo/protocol/ids";3 import {4 RouterContextProvider,15 unmodified lines20 const sha = CommitSha.make("0123456789abcdef0123456789abcdef01234567");21 22 const project = ProjectName.make("oscabriel/p");23 30-/** The file `<dir>/README.md` at `sha`, rendered with no router around it, as a view's test renders it. */24 const rendered = (source: string, dir = "") =>25 renderToString(26 <RepoMarkdown at={sha} dir={dir} project={project} source={source} />27 );28 36-/** The same, inside a router at `location`, as the app renders it. */29 const routed = (element: ReactElement, location = "/p") =>30 renderToString(31 <RouterContextProvider32 router={createRouter({4 unmodified lines37 {element}38 </RouterContextProvider>39 );40 49-/** Each `<a …>` opening tag in `markup`. */41 const anchorsOf = (markup: string) => markup.match(/<a\b[^>]*>/gu) ?? [];42 43 describe("what a README cannot carry", () => {44 it("drops a script and what it says", () => {47 unmodified lines92 expect(markup).toMatch(/(?:id|name)="user-content-top"/u);93 });94 });95 105-/** `docs/README.md`, rendered. */96 const readme = (source: string) => rendered(source, "docs");97 98 describe("links and images in docs/README.md", () => {99 it("loads a relative image raw from the README's folder, at the SHA", () => {135 unmodified lines235 236 describe("a footnote", () => {237 const markup = rendered("Text[^1]\n\n[^1]: Note.");238 249- /** 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;243 255- /** 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 lines298 expect(rendered("hi")).toMatch(/class="[^"]*\bprose\b[^"]*"/u);299 });300 });301 314-/** The classes on the prose wrapper of a README with code and a title. */302 const proseClasses = () => {303 const markup = rendered(304 "# datekit\n\nCall `format()` first.\n\n```ts\nconst a = () => 1;\n```"305 );64 unmodified linesmodified: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- */1 import type { ReactElement } from "react";2 import { renderToStaticMarkup } from "react-dom/server";3 9-/** The entities React writes for text, and what each reads as. */4 const ENTITIES: ReadonlyMap<string, string> = new Map([5 ["'", "'"],6 ["&", "&"],7 [">", ">"],3 unmodified lines11 12 export const markupOf = (element: ReactElement) =>13 renderToStaticMarkup(element);14 21-/** What a reader sees of `markup`: the text without its tags, entities decoded. */15 export const textIn = (markup: string) =>16 markup17 .replaceAll(/<[^>]+>/gu, "")18 .replaceAll(19 /&(?:#x27|amp|gt|lt|quot);/gu,20 (entity) => ENTITIES.get(entity) ?? entity21 );22 30-/** What a reader sees of `element`, rendered. */23 export const textOf = (element: ReactElement) => textIn(markupOf(element));24 33-/** Where each of `parts` starts in `text`, each searched after the one before; -1 once one is missing. */25 export const positionsInOrder = (text: string, parts: readonly string[]) => {26 const positions: number[] = [];27 let from = 0;28 6 unmodified lines35 36 return positions;37 };38 48-/** Whether every one of `parts` is in `text`, each after the one before. */39 export const allInOrder = (text: string, parts: readonly string[]) =>40 positionsInOrder(text, parts).every((at) => at >= 0);41 52-/** Each opening tag in `markup` that carries `attribute`, as the tag's text. */42 export const tagsWith = (markup: string, attribute: string) =>43 [...markup.matchAll(/<[a-z][^>]*>/gu)].flatMap(([tag]) =>44 tag.includes(`${attribute}=`) ? [tag] : []45 );46 58-/** The value of `attribute` in one opening `tag`. */47 export 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- */1 import { describe, expect, it } from "@effect/vitest";2 import { ProjectName } from "@repo/protocol/ids";3 import { Effect } from "effect";4 import { renderToStaticMarkup } from "react-dom/server";2 unmodified lines7 import { renderAt } from "./render.tsx";8 9 const datekit = ProjectName.make("oscabriel/datekit");10 18-/** Each link in `markup`: its text, its href, and whether it is current. */11 const 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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Outcome } from "@repo/protocol/domain/outcome";4 import type { StageName } from "@repo/protocol/domain/outcome";16 unmodified lines21 } from "../src/features/shared/outcome.tsx";22 import { RefusalView } from "../src/features/shared/refusal.tsx";23 import { allInOrder, markupOf, textOf } from "./markup.ts";24 31-/** Each `<li>` that names a stage, as `[stage, state]`. */25 const 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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { reservedProjectNames } from "@repo/protocol/ids";3 import { isNotFound, isRedirect } from "@tanstack/react-router";4 import { Effect } from "effect";4 unmodified lines9 Route as OwnerRoute,10 } from "../src/routes/$owner/index.tsx";11 import { Route as ImportRoute } from "../src/routes/import.tsx";12 21-/** What the loader's load came to for `owner`: a redirect, a 404, or neither. */13 interface Outcome {14 readonly location?: string | null;15 readonly notFound: boolean;16 readonly status?: number;17 }18 28-/** What the route's loader rejects with for `owner`, as an outcome. */19 const outcomeFor = (owner: string) =>20 Effect.tryPromise({21 catch: (thrown): Outcome =>22 isRedirect(thrown)5 unmodified lines28 : { notFound: isNotFound(thrown) },29 try: () => ownerLoader({ params: { owner } }),30 }).pipe(Effect.flip);31 42-/** The route the app's own tree finds for `pathname`. */32 const routeAt = (pathname: string) => getRouter().getMatchedRoutes(pathname)[2];33 34 describe("an owner's address alone", () => {35 it.effect(42 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { CreditSummary } from "@repo/protocol/domain/record";3 import { Handle } from "@repo/protocol/ids";4 import { Effect, Schema } from "effect";19 unmodified lines24 25 const markupOf = (element: ReactElement) =>26 renderAt(`/people/${handle}`, element);27 34-/** What a reader sees: the markup without its tags, entities decoded. */28 const textOf = (html: string) =>29 html30 .replaceAll(/<[^>]+>/gu, "")31 .replaceAll("'", "'")32 .replaceAll("&", "&");33 41-/** The credits: every project's group, from the first to the last. */34 const creditsOf = (html: string) => {35 const start = html.indexOf('data-credits=""');36 const end = html.indexOf("</main>", start);37 126 unmodified linesmodified: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- */1 import { describe, expect, it, vi } from "@effect/vitest";2 import { DEFAULT_TOKENIZE_MAX_LENGTH, resolveTheme } from "@pierre/diffs";3 import { Effect } from "effect";4 3 unmodified lines8 registerCodeTheme,9 treesOptions,10 } from "../src/features/code/pierre.ts";11 19-/** A drawn code box, wider than its pane when it `scrolls`. */12 const box = (scrolls: boolean) => ({13 clientHeight: 400,14 clientWidth: 600,15 scrollHeight: 400,99 unmodified linesmodified: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- */1 import { Client, Contracts } from "@repo/protocol/contracts";2 import { asTester, unanswered } from "@repo/protocol/testing";3 import { Layer } from "effect";4 import { RpcTest } from "effect/rpc";5 10-/** A platform that answers only the contracts in `handlers`, each a `Contracts.toLayerHandler` layer. */6 export 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 );12 18-/** A platform that cannot be reached: every call dies on the way. */13 export 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.3 import { NodeServices } from "@effect/platform-node";4 import { expect, layer } from "@effect/vitest";5 import { Brand } from "@repo/brand";6 import {7 unmodified lines14 Stream,15 } from "effect";16 import { ChildProcess, ChildProcessSpawner } from "effect/process";17 40-/** A production build takes a few seconds; a cold one on a busy machine, longer. */18 const BUILD = 180_000;19 43-/** Text only the dev world, the test kit or the memory adapters' engine carry. */20 const DEV_STRINGS = [21 "src/dev/",22 "devWorld",23 "seedDev",4 unmodified lines28 "@repo/testkit",29 "isomorphic-git",30 ] as const;31 56-/** The memory adapters the dev world runs on, as module folders. */32 const DEV_MODULES = [33 "packages/project/src/project-store/memory",34 "packages/artifacts/src/repo-host/memory",35 ] as const;36 62-/**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.39 const ROOT_PRELOADS_GZIP = 268_000;40 74-/** A Shiki grammar module, by its name. */41 const GRAMMAR = /node_modules\/@shikijs\/langs\/dist\/(?<name>[\w-]+)\.mjs$/u;42 77-/**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- */44 const SERVER_GRAMMARS = [45 "css",46 "html",47 "javascript",6 unmodified lines54 "typescript",55 "yaml",56 ];57 95-/** Whether a file's modules hold the server's highlighting. */58 const drawing = (held: readonly string[]) =>59 held.some((module) => module.endsWith("features/code/prerender-server.ts"));60 99-/** Files whose bytes are not text: fonts and images. */61 const BINARY = /\.(?:ico|png|woff2)$/u;62 63 const decodeSourceMap = Schema.decodeUnknownEffect(64 Schema.fromJsonString(Schema.Struct({ sources: Schema.Array(Schema.String) }))9 unmodified lines74 })75 )76 );77 117-/** What one build wrote. */78 interface 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 }84 85 const where = Effect.gen(function* () {2 unmodified lines88 89 return { repo: path.resolve(web, "../.."), web };90 });91 136-/** Puts the Cloudflare plugin's deploy redirect back as it was when the scope ends. */92 const keepDeployRedirect = (web: string) =>93 Effect.gen(function* () {94 const fs = yield* FileSystem.FileSystem;95 const path = yield* Path.Path;7 unmodified lines103 }).pipe(Effect.orDie)104 );105 });106 152-/** The modules a source map at `map` names, from the repo root. */107 const 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 lines116 )117 );118 });119 166-/** Reads every file under `out`: the source maps as modules, the rest as text. */120 const readOutput = (out: string, repo: string) =>121 Effect.gen(function* () {122 const fs = yield* FileSystem.FileSystem;123 const path = yield* Path.Path;27 unmodified lines151 152 return { holding, modules, paths, texts } satisfies Output;153 });154 202-/** The web's production build, into a folder of its own, read back whole. */155 const productionBuild = Effect.gen(function* () {156 const fs = yield* FileSystem.FileSystem;157 const path = yield* Path.Path;158 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;26 unmodified lines185 186 return yield* readOutput(out, repo);187 }).pipe(Effect.scoped, Effect.orDie, Effect.provide(NodeServices.layer));188 237-/** The one production build every test here reads. */189 class Built extends Context.Service<Built, Output>()("test/Built") {}190 240-/** The files under `folder` of the output, as text. */191 const textsUnder = (output: Output, folder: "client" | "server") =>192 [...output.texts].filter(([at]) => at.startsWith(`${folder}/`));193 244-/** Whether some file under `folder` holds `pattern`. */194 const holds = (output: Output, folder: "client" | "server", pattern: RegExp) =>195 textsUnder(output, folder).some(([, text]) => pattern.test(text));196 248-/** A route's path, as the route tree spells it in a quoted string. */197 const routePath = (path: string) =>198 new RegExp(199 `(?<quote>["'\`])${path.replaceAll(/[$.]/gu, "\\$&")}\\k<quote>`,200 "u"201 );202 255-/**256- * The chunks every page preloads: the root route's, as Start's manifest in257- * the server output names them (`/assets/…`).258- */203 const rootPreloads = (output: Output) => {204 const manifest = textsUnder(output, "server").find(([at]) =>205 at.includes("tanstack-start-manifest")206 )?.[1];11 unmodified lines218 ([chunk]) => chunk219 );220 };221 278-/** `text`'s size gzipped, in bytes. */222 const gzipped = (text: string) =>223 Stream.fromReadableStream({224 evaluate: () =>225 new Blob([text]).stream().pipeThrough(new CompressionStream("gzip")),52 unmodified lines278 ).toStrictEqual([]);279 })280 );281 339- // 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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { commandDocs } from "@repo/agent-kit/command-doc";3 import { Brand } from "@repo/brand";4 import { Client, Contracts } from "@repo/protocol/contracts";20 unmodified lines25 const decodePolicy = Schema.decodeSync(PublicPolicy);26 27 const decodeLedger = Schema.decodeSync(Ledger);28 37-/** What every policy below shares: the parts the page doesn't show. */29 const unshown = {30 judge: { paths: [`${Brand.configDir}/**`], pointers: [] },31 kinds: [],32 modules: [],1 unmodified line34 run: { checks: { unit: "bun test" }, test: "bun test {path}" },35 weakening: { markers: [] },36 };37 47-/** datekit's evaluated config folder at `sha`, as `projectPolicy` returns it. */38 const datekitPolicy = decodePolicy({39 ...unshown,40 agents: "trailer",41 at: sha,14 unmodified lines56 { denounced: true, handle: "spam-bot", note: "opened 40 proposals" },57 ],58 });59 70-/** datekit's ledger: one maintainers layer. */60 const datekitLedger = decodeLedger({61 entries: [],62 layers: [63 {12 unmodified lines76 postureLabel: "Open with sealed evidence",77 project: "datekit",78 });79 91-/** An imported repo with no `project.ts` in its config folder: the platform's defaults, its initializer deciding. */80 const burrowPolicy = decodePolicy({81 ...unshown,82 agents: "trailer",83 at: sha,6 unmodified lines90 vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },91 vouches: [],92 });93 106-/** Why an import with no config folder, whose defaults found no test command, has no policy at `sha`. */94 const noConfig = Schema.decodeSync(PolicyPending)({95 at: sha,96 reason: "noConfig",97 });14 unmodified lines112 unevaluated={Option.none()}113 />114 );115 129-/** The markup of the section whose heading has the id `id`. */116 const sectionOf = (markup: string, id: string) => {117 const heading = markup.indexOf(`id="${id}"`);118 119 return heading === -1120 ? ""121 : elementWith(markup.slice(markup.lastIndexOf("<section", heading)), "");122 };123 138-/**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- */124 const 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 );130 149-/** The CLI command a line runs: the longest command path it starts with. */131 const 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);136 156-/** Each deciders row's text, in order. */137 const decidersOf = (markup: string) =>138 elementsWith(mainOf(markup), "data-paths=").map((row) =>139 plainText(row).trim()140 );385 unmodified lines526 expect(textOf(view)).toContain("Open: nothing is held back");527 });528 });529 550-/** A platform that knows only datekit, counting the reads it is asked for. */530 const platformOf = (531 asked: Ref.Ref<number>,532 read: {533 readonly policy?: PublicPolicy;131 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import { AskListing } from "@repo/protocol/domain/ask";54 unmodified lines59 import { markupOf, textIn, textOf } from "./markup.ts";60 import { renderAt } from "./render.tsx";61 import { reachingTransport } from "./transport.ts";62 72-/** The markup of the row for `ask`: from its `<li>` to the next row or the list's end. */63 const rowOf = (markup: string, ask: string) => {64 const start = markup.indexOf(`data-ask="${ask}"`);65 66 const ends = ['data-ask="', "</ul></section>", "</main>"].flatMap((end) => {4 unmodified lines71 72 return start === -1 ? "" : markup.slice(start, Math.min(...ends));73 };74 85-/** Which of `parts` `text` does not hold. */75 const missingFrom = (text: string, parts: readonly string[]) =>76 parts.filter((part) => !text.includes(part));77 89-/** Which of `parts` `text` holds. */78 const foundIn = (text: string, parts: readonly string[]) =>79 parts.filter((part) => text.includes(part));80 93-/** The page's main pane, the inline facts left in (they sit after its head). */81 const mainOf = (markup: string) =>82 markup.slice(markup.indexOf("<main"), markup.indexOf("</main>"));83 97-/** The inspector, as the shell's width shows it. */84 const inspectorOf = (markup: string) =>85 markup.slice(markup.indexOf('data-facts="inspector"'));86 87 const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");74 unmodified lines162 id: AskId.make("drop-legacy-parse"),163 kind: KindName.make("migrate"),164 };165 180-/** A landing of `ask` (or an opening of it), credited to `answerer`. */166 const landingOf = (167 sha: string,168 more: { readonly ask?: string; readonly opened?: string },169 answerer?: string419 unmodified lines589 expect(ledeOf("# title\n\n| a | b |\n| - | - |\n")).toBeUndefined();590 });591 });592 608-/** The contracts over HTTP, each request answered by `answer`. */593 const 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 lines600 )601 )602 );603 620-/**621- * `handler`, but with the list of projects failing when `listed` counts its622- * calls.623- */604 const failingProjects =605 (606 handler: (request: Request) => Promise<Response>,607 listed: Ref.Ref<number> | undefined12 unmodified lines620 return yield* Effect.promise(() => handler(request));621 })622 );623 644-/**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- */624 const devWorldWith = (options: DevWorldOptions, listed?: Ref.Ref<number>) =>625 Layer.unwrap(626 Effect.gen(function* () {627 const { dispose, handler } = devServer(options);5 unmodified lines633 );634 635 const devWorld = devWorldWith({});636 662-/** A platform that does not answer: every call comes back a 503. */637 const unanswering = clientOver(() =>638 Promise.resolve(new Response("", { status: 503 }))639 );640 667-/** A platform that knows every project and has landed nothing on any. */641 const nothingLanded = Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(642 Layer.provide([643 Layer.mergeAll(644 unanswered,7 unmodified lines652 );653 654 const decodePage = Schema.decodeEffect(ProjectPageData);655 683-/** An input's opening tag, by its `name`. */656 const inputNamed = (markup: string, name: string) =>657 new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";658 659 /** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */660 const seededWorld = { timeout: 30_000 };661 690-/** The page as the route draws it from what its loader read. */662 const sentFrom = (663 data: ProjectPageData,664 more: Partial<ProjectViewProps> = {}665 ) => {342 unmodified linesmodified: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
1 import { defineConfig, devices } from "@playwright/test";2 3-/**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- */3 export default defineConfig({4 forbidOnly: true,5 outputDir: "e2e/out/results",6 projects: [16 unmodified linesmodified: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.