Skip to content
Myr

Merge build/502-web-dev-backend: the web runs locally over a seeded in-process world

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

authored by oscabriel · committed by oscabriel · parents eebd79b, e11b9ce · Browse files · 15 files+2986 added−7 removed
This commit

State

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

Diff stats

15 files+2986 added−7 removed

  • tests:+460 added−0 removed
  • other:+2526 added−7 removed

15 files+2986 added−7 removed

modified:apps/web/src/dev/backend.ts+17 added-7 removed
added:apps/web/src/dev/checker.ts+54 added
added:apps/web/src/dev/clock.ts+59 added
added:apps/web/src/dev/examples.ts+669 added
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.6 *7 * `datekit` is a small date library (the people of `examples/datekit`,8 * issue 507): `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`, issue 508), 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.20 */21import { Brand } from "@repo/brand";22import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";23import { Command, SymbolName } from "@repo/protocol/domain/common";24import type { AskKind } from "@repo/protocol/domain/kind";25import { PolicyInput } from "@repo/protocol/domain/policy";26import { AskId, Handle, ProjectName, RepoPath } from "@repo/protocol/ids";27import { Array, Predicate, Schema } from "effect";2829import type { Files } from "./git.ts";3031const dir = Brand.configDir;3233const encodeCheck = Schema.encodeSync(CheckSpec);3435const decodeCheck = Schema.decodeSync(CheckSpec);3637const encodeMeasure = Schema.encodeSync(RatchetMeasure);3839/** What a project's `policy.json` states, as the file holds it. */40type Stated = typeof PolicyInput.Encoded;4142/** One ask as `policy.json` states it. */43type StatedAsk = Stated["asks"][number];4445/** A `policy.json` from what its project states, with every default written out. */46const policyJson = (stated: Stated) =>47 `${JSON.stringify(48 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),49 null,50 251 )}\n`;5253/** One file an ask opens with. */54interface AskFile {55 readonly content: string;56 readonly path: RepoPath;57}5859/** The files a decider opens one ask with: its ask file, then its check's file if it has one. */60export type Opening = Array.NonEmptyReadonlyArray<AskFile>;6162/** The args a kind takes for an ask's check, as its ask file passes them (`packages/sdk`'s `kinds`). */63interface KindArgs {64 readonly command?: string;65 readonly count?: string;66 readonly from?: string;67 readonly path?: string;68 readonly ratchet?: string;69 readonly rule?: string;70 readonly to?: string | undefined;71}7273/** A string, or a list of them, as TypeScript source spells it. */74const spelled = (value: string | readonly string[]): string =>75 Predicate.isString(value)76 ? JSON.stringify(value)77 : `[${value.map(spelled).join(", ")}]`;7879/**80 * The args an ask's kind takes for its check, as the ask file spells them.81 * No SDK call states a `SymbolAbsent` check (a migrate's split opens its82 * delete step, issue 506), so that file spells the nearest one: a migrate83 * with no `to`, every use gone.84 */85const checkArgs = (check: StatedAsk["check"]) =>86 CheckSpec.match(decodeCheck(check), {87 LintToZero: ({ command, rule }): KindArgs => ({ command, rule }),88 Migrate: ({ count, from, to }): KindArgs => ({ count, from, to }),89 Ratchet: ({ ratchet }): KindArgs => ({ ratchet }),90 RedThenGreen: ({ path }): KindArgs => ({ path }),91 SymbolAbsent: ({ count, symbol }): KindArgs => ({ count, from: symbol }),92 });9394/** An ask's territory as its file spells it: the repo-wide builder for `.`, else the data itself. */95const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>96 module === "."97 ? `territory.paths(${paths.map(spelled).join(", ")})`98 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;99100/** An ask's file: the SDK call that states `stated`, as its maintainer writes it. */101const askFileOf = (stated: StatedAsk): AskFile => {102 const territory = territoryOf(stated.territory);103104 const passed = Object.entries({105 ...checkArgs(stated.check),106 blockedBy: Array.isReadonlyArrayNonEmpty(stated.blockedBy)107 ? stated.blockedBy108 : undefined,109 current: stated.brief.current,110 mentor: stated.mentor,111 parent: stated.parent,112 reserve: stated.reserve,113 want: stated.brief.want,114 }).flatMap(([key, value]) =>115 value === undefined ? [] : [`${key}: ${spelled(value)}`]116 );117118 const args = [...passed, `territory: ${territory}`].toSorted();119120 const builders = territory.startsWith("territory.")121 ? "kinds, territory"122 : "kinds";123124 return {125 content: [126 `import { ${builders} } from "${Brand.cliPackage}/rules";`,127 "",128 `export default kinds.${stated.kind}.ask({`,129 ...args.map((arg) => ` ${arg},`),130 "});",131 "",132 ].join("\n"),133 path: RepoPath.make(stated.file),134 };135};136137// ------------------------------------------------------------- datekit138139export const datekitPeople = {140 contributor: Handle.make("bram"),141 decider: Handle.make("ines-v"),142 zones: Handle.make("okonkwo"),143} as const;144145const fix = {146 checkKind: "redThenGreen",147 claimers: "vouched",148 finish: "optional",149 name: "fix",150 oneWay: false,151 race: 1,152 requires: ["want", "check", "territory"],153 strength: "assertion",154} satisfies typeof AskKind.Encoded;155156/** One datekit ask: as `policy.json` states it, and the check file it opens with. */157interface DatekitAsk {158 readonly stated: StatedAsk;159 readonly test: AskFile;160}161162/**163 * One datekit ask, from its id, the module file it fixes, its brief and its164 * check's one test (red on main, by an assertion). One held for a newcomer165 * names the maintainer who mentors them. datekit is one package, so every166 * territory is in the repo-wide module, `.`.167 */168const datekitAsk = (input: {169 readonly id: string;170 readonly file: string;171 readonly current: string;172 readonly want: string;173 readonly mentor?: Handle;174 readonly test: {175 readonly imports: readonly string[];176 readonly name: string;177 readonly assertion: string;178 };179}): DatekitAsk => {180 const path = RepoPath.make(`test/asks/${input.id}.test.ts`);181182 const stated: StatedAsk = {183 askedBy: datekitPeople.decider,184 blockedBy: [],185 brief: { current: input.current, want: input.want },186 check: encodeCheck(CheckSpec.cases.RedThenGreen.make({ path })),187 file: `${dir}/asks/${input.id}.ask.ts`,188 id: input.id,189 kind: "fix",190 territory: { module: ".", paths: [`src/${input.file}.ts`] },191 };192193 return {194 stated:195 input.mentor === undefined196 ? stated197 : { ...stated, mentor: input.mentor, reserve: "newcomers" },198 test: {199 content: [200 'import { expect, test } from "bun:test";',201 "",202 ...input.test.imports,203 "",204 `test(${spelled(input.test.name)}, () => {`,205 ` ${input.test.assertion}`,206 "});",207 "",208 ].join("\n"),209 path,210 },211 };212};213214const datekitAsks: readonly DatekitAsk[] = [215 datekitAsk({216 current: "parseISO returns an invalid date for a week date.",217 file: "parse",218 id: "parse-iso-week",219 test: {220 assertion:221 'expect(parseISO("2026-W41-3").toISOString()).toBe("2026-10-07T00:00:00.000Z");',222 imports: ['import { parseISO } from "../../src/parse.ts";'],223 name: "parses an ISO week date",224 },225 want: "parseISO accepts ISO week dates such as 2026-W41-3.",226 }),227 datekitAsk({228 current: 'format prints "11st", "12nd" and "13rd".',229 file: "format",230 id: "format-ordinal",231 // Held for a newcomer, whom its asker mentors.232 mentor: datekitPeople.decider,233 test: {234 assertion: 'expect(format(parseISO("2026-10-11"), "Do")).toBe("11th");',235 imports: [236 'import { format } from "../../src/format.ts";',237 'import { parseISO } from "../../src/parse.ts";',238 ],239 name: "prints the teens as th",240 },241 want: 'format(date, "Do") prints 1st, 2nd, 3rd, 11th, 12th, 13th and 21st.',242 }),243 datekitAsk({244 current: "addMonths(January 31, 1) overflows into March.",245 file: "add",246 id: "add-months-clamp",247 test: {248 assertion:249 'expect(addMonths(parseISO("2026-01-31"), 1).toISOString()).toBe("2026-02-28T00:00:00.000Z");',250 imports: [251 'import { addMonths } from "../../src/add.ts";',252 'import { parseISO } from "../../src/parse.ts";',253 ],254 name: "clamps to the end of February",255 },256 want: "addMonths(January 31, 1) is the last day of February, in leap and common years.",257 }),258 datekitAsk({259 current: "diffInDays counts a day short across the spring change.",260 file: "diff",261 id: "diff-in-days-dst",262 test: {263 assertion:264 'expect(diffInDays(new Date("2026-03-30T00:00:00+02:00"), new Date("2026-03-29T00:00:00+01:00"))).toBe(1);',265 imports: ['import { diffInDays } from "../../src/diff.ts";'],266 name: "counts the spring change as one day",267 },268 want: "diffInDays counts calendar days across a daylight-saving change.",269 }),270];271272const library: Files = new Map([273 [274 "README.md",275 [276 "# datekit",277 "",278 "Small, dependency-free date helpers: parse, format, add and diff.",279 "",280 "A fictional project: it and its people are invented.",281 "",282 ].join("\n"),283 ],284 [285 "package.json",286 `${JSON.stringify(287 {288 license: "MIT",289 name: "datekit",290 scripts: { test: "bun test", typecheck: "tsc --noEmit" },291 type: "module",292 version: "0.4.2",293 },294 null,295 2296 )}\n`,297 ],298 [299 "src/index.ts",300 [301 'export { addMonths } from "./add.ts";',302 'export { diffInDays } from "./diff.ts";',303 'export { format } from "./format.ts";',304 'export { parseISO } from "./parse.ts";',305 'export { inZone } from "./tz.ts";',306 "",307 ].join("\n"),308 ],309 [310 "src/parse.ts",311 [312 "/** An ISO 8601 date (`2026-10-07`) or date-time, read as UTC. */",313 "export const parseISO = (text: string): Date =>",314 ' new Date(text.length === 10 ? text + "T00:00:00Z" : text);',315 "",316 ].join("\n"),317 ],318 [319 "src/format.ts",320 [321 'const pad = (n: number) => String(n).padStart(2, "0");',322 "",323 'const ordinal = (n: number) => String(n) + (["th", "st", "nd", "rd"][n % 10] ?? "th");',324 "",325 "/** `date` in `pattern`: YYYY, MM, DD and Do (the day as an ordinal). */",326 "export const format = (date: Date, pattern: string): string =>",327 " pattern",328 ' .replaceAll("YYYY", String(date.getUTCFullYear()))',329 ' .replaceAll("MM", pad(date.getUTCMonth() + 1))',330 ' .replaceAll("Do", ordinal(date.getUTCDate()))',331 ' .replaceAll("DD", pad(date.getUTCDate()));',332 "",333 ].join("\n"),334 ],335 [336 "src/add.ts",337 [338 "/** `date` moved by whole months. */",339 "export const addMonths = (date: Date, months: number): Date => {",340 " const next = new Date(date);",341 "",342 " next.setUTCMonth(next.getUTCMonth() + months);",343 "",344 " return next;",345 "};",346 "",347 ].join("\n"),348 ],349 [350 "src/diff.ts",351 [352 "const DAY = 86_400_000;",353 "",354 "/** Whole days from `earlier` to `later`. */",355 "export const diffInDays = (later: Date, earlier: Date): number =>",356 " Math.floor((later.getTime() - earlier.getTime()) / DAY);",357 "",358 ].join("\n"),359 ],360 [361 "src/tz.ts",362 [363 "/** `date` as wall-clock parts in an IANA time zone. */",364 "export const inZone = (date: Date, zone: string) =>",365 ' new Intl.DateTimeFormat("en-CA", { dateStyle: "short", timeStyle: "short", timeZone: zone }).format(date);',366 "",367 ].join("\n"),368 ],369 [370 "test/format.test.ts",371 [372 'import { expect, test } from "bun:test";',373 "",374 'import { format } from "../src/format.ts";',375 'import { parseISO } from "../src/parse.ts";',376 "",377 'test("formats a date", () => {',378 ' expect(format(parseISO("2026-10-07"), "YYYY-MM-DD")).toBe("2026-10-07");',379 "});",380 "",381 ].join("\n"),382 ],383 [384 `${dir}/policy.json`,385 policyJson({386 asks: datekitAsks.map(({ stated }) => stated),387 deciders: [388 { handles: [datekitPeople.decider], paths: "**" },389 { handles: [datekitPeople.zones], paths: "src/tz.ts" },390 ],391 functions: { admit: false, opensAlone: false },392 kinds: [fix],393 ratchets: [],394 run: {395 checks: { types: "bun run typecheck" },396 test: "bun test {path}",397 },398 source: "config",399 weakening: { markers: [".skip(", ".only(", ".todo("] },400 }),401 ],402 [403 `${dir}/vouched.td`,404 [405 "# The people datekit's deciders vouch for.",406 datekitPeople.contributor,407 "",408 ].join("\n"),409 ],410]);411412export const datekit = {413 answer: {414 ask: AskId.make("diff-in-days-dst"),415 files: new Map([416 [417 "src/diff.ts",418 [419 "const DAY = 86_400_000;",420 "",421 "/** Whole calendar days from `earlier` to `later`, across any daylight-saving change. */",422 "export const diffInDays = (later: Date, earlier: Date): number =>",423 " Math.round((later.getTime() - earlier.getTime()) / DAY);",424 "",425 ].join("\n"),426 ],427 ]) satisfies Files,428 message: "Count calendar days across a daylight-saving change",429 },430 asks: datekitAsks.map(431 ({ stated, test }) =>432 [AskId.make(stated.id), [askFileOf(stated), test]] as const433 ),434 files: library,435 project: ProjectName.make("datekit"),436 /** A commit someone pushed straight to main, past the platform. */437 stray: {438 files: new Map([439 [440 "README.md",441 [442 "# datekit",443 "",444 "Small, dependency-free date helpers: parse, format, add, diff and time zones.",445 "",446 "A fictional project: it and its people are invented.",447 "",448 ].join("\n"),449 ],450 ]) satisfies Files,451 message: "Mention time zones in the README",452 },453} as const;454455// -------------------------------------------------------------- burrow456457export const burrowPeople = {458 decider: Handle.make("okafor"),459 second: Handle.make("lin-h"),460} as const;461462const PACKAGES = [463 "kit",464 "auth",465 "billing",466 "catalog",467 "notify",468 "search",469] as const;470471const COUNT = "bun scripts/count-callers.ts legacyFetch --json";472473const migrateCheck = encodeCheck(474 CheckSpec.cases.Migrate.make({475 count: Command.make(COUNT),476 from: SymbolName.make("legacyFetch"),477 to: SymbolName.make("http.get"),478 })479);480481const PARENT = "drop-legacy-fetch";482483/** One step of the migrate family: moving one package off `legacyFetch`. */484const child = (pkg: string): StatedAsk => ({485 askedBy: burrowPeople.decider,486 blockedBy: [],487 brief: {488 want: `@burrow/${pkg} calls http.get wherever it called legacyFetch.`,489 },490 check: migrateCheck,491 file: `${dir}/asks/${PARENT}-${pkg}.ask.ts`,492 id: `${PARENT}-${pkg}`,493 kind: "migrate",494 parent: PARENT,495 territory: { module: `@burrow/${pkg}`, paths: [`packages/${pkg}/**`] },496});497498const CHILDREN = ["auth", "billing"];499500const burrowAsks: readonly StatedAsk[] = [501 {502 askedBy: burrowPeople.decider,503 blockedBy: [],504 brief: {505 want: "Replace every call to legacyFetch with http.get, then delete legacyFetch.",506 },507 check: migrateCheck,508 file: `${dir}/asks/${PARENT}.ask.ts`,509 id: PARENT,510 kind: "migrate",511 territory: {512 module: ".",513 paths: Array.map(PACKAGES, (pkg) => `packages/${pkg}/**`),514 },515 },516 ...CHILDREN.map(child),517 {518 askedBy: burrowPeople.decider,519 blockedBy: CHILDREN.map((pkg) => `${PARENT}-${pkg}`),520 brief: { want: "Delete legacyFetch: nothing calls it any more." },521 check: encodeCheck(522 CheckSpec.cases.SymbolAbsent.make({523 count: Command.make(COUNT),524 symbol: SymbolName.make("legacyFetch"),525 })526 ),527 file: `${dir}/asks/${PARENT}-delete.ask.ts`,528 id: `${PARENT}-delete`,529 kind: "migrate",530 parent: PARENT,531 territory: { module: "@burrow/kit", paths: ["packages/kit/**"] },532 },533];534535const packageFiles = (pkg: string): readonly (readonly [string, string])[] => [536 [537 `packages/${pkg}/package.json`,538 `${JSON.stringify(539 {540 exports: { ".": "./src/index.ts" },541 name: `@burrow/${pkg}`,542 type: "module",543 },544 null,545 2546 )}\n`,547 ],548 [549 `packages/${pkg}/src/index.ts`,550 pkg === "kit"551 ? [552 "/** The old way to fetch: kept until nothing calls it. */",553 "export const legacyFetch = (url: string) => fetch(url).then((response) => response.json());",554 "",555 "export const http = { get: (url: string) => fetch(url).then((response) => response.json()) };",556 "",557 "let calls = 0;",558 "",559 'export const ping = () => legacyFetch("/kit/ping?n=" + String((calls += 1)));',560 "",561 ].join("\n")562 : [563 'import { legacyFetch } from "@burrow/kit";',564 "",565 "let cache: unknown;",566 "",567 `export const load = async () => (cache ??= await legacyFetch("/${pkg}"));`,568 "",569 ].join("\n"),570 ],571];572573const monorepo: Files = new Map([574 [575 "README.md",576 [577 "# burrow",578 "",579 "Six packages that share a kit, a lint setup and a debt counter.",580 "",581 "A fictional project: it and its people are invented.",582 "",583 ].join("\n"),584 ],585 [586 "package.json",587 `${JSON.stringify(588 {589 name: "burrow",590 private: true,591 scripts: { lint: "oxlint", test: "bun test" },592 workspaces: ["packages/*"],593 },594 null,595 2596 )}\n`,597 ],598 [599 "scripts/count-callers.ts",600 [601 "// Prints how many times each package calls a symbol, as JSON.",602 'import { Glob } from "bun";',603 "",604 "const [symbol] = Bun.argv.slice(2);",605 "const byModule: Record<string, number> = {};",606 "",607 'for await (const path of new Glob("packages/*/src/**/*.ts").scan()) {',608 ' const name = "@burrow/" + path.split("/")[1];',609 " const text = await Bun.file(path).text();",610 "",611 ' byModule[name] = (byModule[name] ?? 0) + (text.split(symbol + "(").length - 1);',612 "}",613 "",614 "const total = Object.values(byModule).reduce((sum, n) => sum + n, 0);",615 "",616 "console.log(JSON.stringify({ byModule, total }));",617 "",618 ].join("\n"),619 ],620 ...PACKAGES.flatMap(packageFiles),621 [622 `${dir}/policy.json`,623 policyJson({624 asks: burrowAsks,625 deciders: [626 {627 handles: [burrowPeople.decider, burrowPeople.second],628 paths: "**",629 },630 ],631 functions: { admit: false, opensAlone: false },632 kinds: [633 {634 checkKind: "migrate",635 claimers: "vouched",636 finish: "never",637 name: "migrate",638 oneWay: false,639 race: 1,640 requires: ["want", "check", "territory"],641 strength: "assertion",642 },643 ],644 ratchets: [645 {646 measure: encodeMeasure(647 RatchetMeasure.cases.Count.make({648 command: Command.make("bun run lint --format json"),649 rule: "burrow/no-module-level-mutable-state",650 })651 ),652 name: "mutable-state",653 },654 ],655 run: { checks: { lint: "bun run lint" }, test: "bun test {path}" },656 source: "config",657 weakening: { markers: [".skip(", ".only(", ".todo("] },658 }),659 ],660 [`${dir}/vouched.td`, "# The people burrow's deciders vouch for.\n"],661]);662663export const burrow = {664 asks: burrowAsks.map(665 (stated) => [AskId.make(stated.id), [askFileOf(stated)]] as const666 ),667 files: monorepo,668 project: ProjectName.make("burrow"),669} as const;
added:apps/web/src/dev/front-page.ts+172 added
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 * Every posture reads `open`, as D1's does until W6. A person's credits are10 * each project's own count, joined (`creditsFor`).11 */12import { FrontPage } from "@repo/project/front-page";13import type { FrontPageFilter } from "@repo/project/front-page";14import type { ProjectedEvent } from "@repo/project/projection";15import { creditsFor, Projects } from "@repo/project/projects";16import type { AskListing } from "@repo/protocol/domain/ask";17import { ProjectEvent } from "@repo/protocol/domain/event";18import type {19 FrontPageEntry,20 ProjectListing,21} from "@repo/protocol/domain/front-page";22import type { ProjectName } from "@repo/protocol/ids";23import { Array, DateTime, Effect, Layer, Order } from "effect";2425import { DevProjected } from "./projection.ts";2627/** One open ask on the page, as D1's `front_page` row holds it. */28interface Row {29 readonly ask: AskListing;30 readonly claims: number;31 readonly openedAt: DateTime.Utc;32 readonly project: ProjectName;33}3435const keyOf = (project: ProjectName, ask: string) => `${project}/${ask}`;3637/** Every project's events in its own order. */38const inOrder = Order.mapInput(39 Order.Tuple([Order.String, Order.Number]),40 ({ event, project }: ProjectedEvent) => [project, event.seq] as const41);4243/** The page's rows with one ask's claim count moved by `change`, if it is on the page. */44const withClaims = (45 rows: ReadonlyMap<string, Row>,46 key: string,47 change: number48): ReadonlyMap<string, Row> => {49 const row = rows.get(key);5051 return row === undefined52 ? rows53 : new Map(rows).set(key, {54 ...row,55 claims: Math.max(row.claims + change, 0),56 });57};5859/** The page's rows after one project's event, as D1's statements change them. */60const step = (61 rows: ReadonlyMap<string, Row>,62 { event, project }: ProjectedEvent63): ReadonlyMap<string, Row> =>64 ProjectEvent.match(event, {65 AskClosed: ({ ask }) => {66 const next = new Map(rows);6768 next.delete(keyOf(project, ask));6970 return next;71 },72 AskOpened: ({ ask, at }) =>73 new Map(rows).set(keyOf(project, ask.ask), {74 ask,75 claims: ask.claimed ? 1 : 0,76 openedAt: at,77 project,78 }),79 Claimed: ({ ask }) => withClaims(rows, keyOf(project, ask), 1),80 Decided: () => rows,81 Judged: () => rows,82 Landed: () => rows,83 Lapsed: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),84 LedgerAppended: () => rows,85 ProposalOpened: () => rows,86 Pushed: () => rows,87 Released: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),88 Warned: () => rows,89 });9091const empty: ReadonlyMap<string, Row> = new Map();9293/** The page's rows after `events`, and every project they came from. */94const fold = (events: readonly ProjectedEvent[]) => ({95 projects: Array.sort(96 Array.dedupe(events.map(({ project }) => project)),97 Order.String98 ),99 rows: [...Array.reduce(Array.sort(events, inOrder), empty, step).values()],100});101102/** Newest first, then by project and ask, as D1's query orders them. */103const newestFirst = Order.combineAll([104 Order.flip(Order.mapInput(DateTime.Order, ({ openedAt }: Row) => openedAt)),105 Order.mapInput(Order.String, ({ project }: Row) => project),106 Order.mapInput(Order.String, ({ ask }: Row) => ask.ask),107]);108109/** A row as the anonymous viewer sees it. */110const entryOf =111 (rows: readonly Row[]) =>112 (row: Row): FrontPageEntry => {113 const onPage = (ask: string) =>114 rows.some(115 (other) => other.project === row.project && other.ask.ask === ask116 );117118 const blockedBy = row.ask.blockedBy.filter(onPage);119 const claimed = row.claims > 0;120121 return {122 ask: { ...row.ask, blockedBy, claimed },123 posture: "open",124 project: row.project,125 takeable:126 !claimed && blockedBy.length === 0 && row.ask.reserve === undefined,127 };128 };129130const matches =131 ({ kind, reserved }: FrontPageFilter) =>132 ({ ask }: Row) =>133 (kind === undefined || ask.kind === kind) &&134 (reserved === undefined || ask.reserve === reserved);135136/** `FrontPage` over the memory projection's events, and credits from `Projects`. */137export const DevFrontPage: Layer.Layer<138 FrontPage,139 never,140 Projects | DevProjected141> = Layer.effect(142 FrontPage,143 Effect.gen(function* () {144 const projected = yield* DevProjected;145 const projects = yield* Projects;146 const page = Effect.map(projected.events, fold);147148 return FrontPage.of({149 credits: (handle) =>150 Effect.flatMap(page, (folded) =>151 creditsFor(handle, folded.projects).pipe(152 Effect.provideService(Projects, projects)153 )154 ),155 entries: (filter) =>156 Effect.map(page, ({ rows }) =>157 Array.sort(rows.filter(matches(filter)), newestFirst).map(158 entryOf(rows)159 )160 ),161 projects: () =>162 Effect.map(page, (folded) =>163 folded.projects.map((project): ProjectListing => ({164 openAsks: folded.rows.filter((row) => row.project === project)165 .length,166 posture: "open",167 project,168 }))169 ),170 });171 })172);
added:apps/web/src/dev/git.ts+407 added
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 */13import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";14import type { PushSource, TreeEntry } from "@repo/artifacts/repo-host";15import { Brand } from "@repo/brand";16import { BlobSha, CommitSha } from "@repo/protocol/ids";17import type { Handle, RepoName } from "@repo/protocol/ids";18import { Array, DateTime, Effect, Option, Predicate } from "effect";1920/** A tree's files, by path, as text: what the world writes. */21export type Files = ReadonlyMap<string, string>;2223/** A file as a commit holds it: its blob's id, and its text. */24export interface Held {25 readonly blob: BlobSha;26 readonly text: string;27}2829/** A commit's files, by path, as read back. */30export type Snapshot = ReadonlyMap<string, Held>;3132/** The name and email an author or committer line carries. */33export interface Identity {34 readonly email: string;35 readonly name: string;36}3738/** The platform, which commits every landing. */39export const platformIdentity: Identity = {40 email: `platform@${Brand.domain}`,41 name: Brand.name,42};4344/** A person, as the author of their own commits and of their landings. */45export const personIdentity = (handle: Handle): Identity => ({46 email: `${handle}@users.${Brand.domain}`,47 name: handle,48});4950/** A snapshot's text alone. */51export const textOf = (snapshot: Snapshot): Files =>52 new Map([...snapshot].map(([path, { text }]) => [path, text]));5354/** `files` with `changed` written over them. */55export const overlay = (56 files: Files,57 changed: Iterable<readonly [string, string]>58): Files => new Map([...files, ...changed]);5960// --------------------------------------------------------------- objects6162const encoder = new TextEncoder();6364const decoder = new TextDecoder();6566const concat = (parts: readonly Uint8Array[]) => {67 const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));68 let at = 0;6970 for (const part of parts) {71 all.set(part, at);72 at += part.byteLength;73 }7475 return all;76};7778const hex = (bytes: ArrayBuffer) =>79 [...new Uint8Array(bytes)]80 .map((byte) => byte.toString(16).padStart(2, "0"))81 .join("");8283const bytesOfHex = (id: string) =>84 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));8586/** git's zlib stream, as a loose object holds it. */87const deflate = (bytes: Uint8Array) =>88 Effect.promise(() =>89 new Response(90 new Blob([Uint8Array.from(bytes)])91 .stream()92 .pipeThrough(new CompressionStream("deflate"))93 ).arrayBuffer()94 ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));9596/** An object's header and content, and its id: the SHA-1 of both. */97const framed = (kind: "blob" | "tree" | "commit", content: Uint8Array) => {98 const raw = concat([99 encoder.encode(`${kind} ${content.byteLength}\0`),100 content,101 ]);102103 return Effect.map(104 Effect.promise(() => crypto.subtle.digest("SHA-1", raw)),105 (digest) => ({ id: hex(digest), raw })106 );107};108109const sortKey = (entry: TreeEntry) =>110 encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);111112// git sorts a tree's entries by name, a subtree's name as if it ended in "/".113const treeOrder = (one: TreeEntry, other: TreeEntry) => {114 const left = sortKey(one);115 const right = sortKey(other);116117 for (let at = 0; at < Math.min(left.length, right.length); at += 1) {118 const diff = (left[at] ?? 0) - (right[at] ?? 0);119120 if (diff !== 0) {121 return diff;122 }123 }124125 return left.length - right.length;126};127128const treeBytes = (entries: readonly TreeEntry[]) =>129 concat(130 entries.toSorted(treeOrder).flatMap((entry) => [131 // A tree object spells a subtree's mode without its leading zero.132 encoder.encode(`${entry.mode.replace(/^0/u, "")} ${entry.name}\0`),133 bytesOfHex(entry.sha),134 ])135 );136137/**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 */142const messageOf = (message: string) =>143 `${message.replaceAll("\r", "").replace(/^\n+/u, "").replace(/\n+$/u, "")}\n`;144145const signature = (who: Identity, at: DateTime.Utc) =>146 `${who.name} <${who.email}> ${Math.floor(DateTime.toEpochMillis(at) / 1000)} +0000`;147148/** A commit to write: its tree, parents, people, time and message. */149export interface CommitInput {150 readonly tree: ObjectId;151 readonly parents: readonly CommitSha[];152 readonly author: Identity;153 readonly committer: Identity;154 readonly at: DateTime.Utc;155 readonly message: string;156}157158const commitBytes = (input: CommitInput) =>159 encoder.encode(160 [161 `tree ${input.tree}`,162 ...input.parents.map((parent) => `parent ${parent}`),163 `author ${signature(input.author, input.at)}`,164 `committer ${signature(input.committer, input.at)}`,165 "",166 messageOf(input.message),167 ].join("\n")168 );169170// ------------------------------------------------------------ the source171172const failure = (code: string, path: string) =>173 Promise.reject(Object.assign(new Error(`${code}: ${path}`), { code }));174175const clean = (path: string) =>176 `/${path177 .split("/")178 .filter((part) => part !== "")179 .join("/")}`;180181/** How isomorphic-git asks for a file: as bytes, or as text in "utf8", alone or as `{ encoding }`. */182type ReadOptions = string | { readonly encoding?: string } | undefined;183184const UTF8 = /^utf-?8$/iu;185186const wantsText = (options: ReadOptions) =>187 Predicate.isString(options)188 ? UTF8.test(options)189 : UTF8.test(options?.encoding ?? "");190191/** A write to the scratch directory through the file system: it only reads. */192const readOnly = (raw: string) => failure("EROFS", clean(raw));193194const stats = (kind: "file" | "dir", size: number) => ({195 ctimeMs: 0,196 dev: 1,197 gid: 1,198 ino: 0,199 isDirectory: () => kind === "dir",200 isFile: () => kind === "file",201 isSymbolicLink: () => false,202 mode: kind === "dir" ? 0o4_0000 : 0o10_0644,203 mtimeMs: 0,204 size,205 uid: 1,206});207208/**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 */213const readOnlyFs = (files: ReadonlyMap<string, Uint8Array>) => {214 const childrenOf = (dir: string) => {215 const prefix = dir === "/" ? "/" : `${dir}/`;216217 return Array.dedupe(218 [...files.keys()].flatMap((path) =>219 path.startsWith(prefix)220 ? [path.slice(prefix.length).split("/")[0] ?? ""]221 : []222 )223 );224 };225226 const stat = (raw: string) => {227 const path = clean(raw);228 const file = files.get(path);229230 if (file !== undefined) {231 return Promise.resolve(stats("file", file.byteLength));232 }233234 return childrenOf(path).length > 0235 ? Promise.resolve(stats("dir", 0))236 : failure("ENOENT", path);237 };238239 return {240 promises: {241 lstat: stat,242 mkdir: readOnly,243 // isomorphic-git may call it with no path to learn whether this fs244 // returns promises, so that call answers with a rejected promise.245 readFile: (raw?: string, options?: ReadOptions) => {246 const path = clean(raw ?? "");247 const file = files.get(path);248249 if (file === undefined) {250 return failure(251 childrenOf(path).length > 0 ? "EISDIR" : "ENOENT",252 path253 );254 }255256 return Promise.resolve(257 wantsText(options) ? decoder.decode(file) : file258 );259 },260 readdir: (raw: string) => {261 const path = clean(raw);262 const children = childrenOf(path);263264 return children.length > 0265 ? Promise.resolve(children)266 : failure("ENOENT", path);267 },268 readlink: (raw: string) => failure("EINVAL", clean(raw)),269 rmdir: readOnly,270 stat,271 symlink: (_target: string, raw: string) => failure("ENOSYS", clean(raw)),272 unlink: readOnly,273 writeFile: readOnly,274 },275 };276};277278/** A git directory in memory that a push takes objects from, and how to write into it. */279export interface Scratch {280 readonly source: PushSource;281 /** Every blob and tree of `files`, and the root tree's id. */282 readonly tree: (files: Files) => Effect.Effect<ObjectId>;283 readonly commit: (input: CommitInput) => Effect.Effect<CommitSha>;284}285286const GITDIR = "/scratch.git";287288/** A fresh scratch git directory: loose, zlib-deflated objects named by their ids. */289export const scratch: Effect.Effect<Scratch> = Effect.sync(() => {290 const objects = new Map<string, Uint8Array>();291292 const write = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>293 Effect.gen(function* () {294 const { id, raw } = yield* framed(kind, content);295 const path = `${GITDIR}/objects/${id.slice(0, 2)}/${id.slice(2)}`;296297 if (!objects.has(path)) {298 objects.set(path, yield* deflate(raw));299 }300301 return ObjectId.make(id);302 });303304 const folder = (305 files: readonly (readonly [string, string])[]306 ): Effect.Effect<ObjectId> =>307 Effect.gen(function* () {308 const blobs = files.filter(([path]) => !path.includes("/"));309310 const nested = Array.groupBy(311 files.filter(([path]) => path.includes("/")),312 ([path]) => path.slice(0, path.indexOf("/"))313 );314315 const blobEntries = yield* Effect.forEach(blobs, ([name, text]) =>316 Effect.map(write("blob", encoder.encode(text)), (sha): TreeEntry => ({317 mode: "100644",318 name,319 sha,320 type: "blob",321 }))322 );323324 const treeEntries = yield* Effect.forEach(325 Object.entries(nested),326 ([name, inside]) =>327 Effect.map(328 folder(329 inside.map(330 ([path, text]) => [path.slice(name.length + 1), text] as const331 )332 ),333 (sha): TreeEntry => ({ mode: "040000", name, sha, type: "tree" })334 )335 );336337 return yield* write("tree", treeBytes([...blobEntries, ...treeEntries]));338 });339340 return {341 commit: (input) =>342 Effect.map(write("commit", commitBytes(input)), (id) =>343 CommitSha.make(id)344 ),345 source: { fs: readOnlyFs(objects), gitdir: GITDIR },346 tree: (files) => folder([...files]),347 };348});349350// ----------------------------------------------------------------- reads351352/** One file of a snapshot: its path, its blob's id and its text. */353const fileOf =354 (path: string, blob: ObjectId) =>355 (bytes: Uint8Array): Snapshot =>356 new Map([357 [path, { blob: BlobSha.make(blob), text: decoder.decode(bytes) }],358 ]);359360/** Every file under the tree `tree` of `repo`, by path; none when the repo lacks an object. */361const snapshotOf = (362 repo: RepoName,363 tree: ObjectId,364 prefix: string365): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>366 Effect.gen(function* () {367 const host = yield* RepoHost;368 const entries = yield* host.readTree(repo, tree).pipe(Effect.orDie);369370 if (Option.isNone(entries)) {371 return Option.none();372 }373374 const each = yield* Effect.forEach(entries.value, (entry) => {375 const path = `${prefix}${entry.name}`;376377 if (entry.type === "tree") {378 return snapshotOf(repo, entry.sha, `${path}/`);379 }380381 return host382 .readBlob(repo, entry.sha)383 .pipe(Effect.orDie, Effect.map(Option.map(fileOf(path, entry.sha))));384 });385386 return Option.map(387 Option.all(each),388 (parts): Snapshot => new Map(parts.flatMap((part) => [...part]))389 );390 });391392/** `repo`'s files at `commit`; none when the repo or the commit is not there. */393export const filesAt = (394 repo: RepoName,395 commit: CommitSha396): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>397 Effect.gen(function* () {398 const host = yield* RepoHost;399400 const found = yield* host401 .readCommit(repo, commit)402 .pipe(Effect.orElseSucceed(() => Option.none()));403404 return Option.isNone(found)405 ? Option.none()406 : yield* snapshotOf(repo, found.value.tree, "");407 });
added:apps/web/src/dev/handlers.ts+332 added
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.12 */13import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";14import { FrontPage } from "@repo/project/front-page";15import type { ProjectApi } from "@repo/project/project";16import { Projects } from "@repo/project/projects";17import { Contracts, EnvSchemaOf } from "@repo/protocol/contracts";18import type { AnswerView } from "@repo/protocol/domain/answer";19import type { ClaimView } from "@repo/protocol/domain/claim";20import type { Decision, Today } from "@repo/protocol/domain/decision";21import { sameHandle } from "@repo/protocol/ids";22import type { ProjectName, RepoName } from "@repo/protocol/ids";23import { CurrentPrincipal, Principal } from "@repo/protocol/principal";24import type { Person } from "@repo/protocol/principal";25import { NotDecider } from "@repo/protocol/refusal";26import { Array, DateTime, Effect, Number, Option, Order, Stream } from "effect";27import type { Layer } from "effect";28import { HttpServerRequest } from "effect/http";29import type { Rpc, RpcGroup } from "effect/rpc";3031/** How many events `watch` reads from its project at a time. */32const EVENT_PAGE = 100;3334/** The caller, as the `Authenticated` server side named them. */35const caller = Effect.service(CurrentPrincipal);3637/**38 * The caller of a contract only a person may call. `Authenticated` lets an39 * anonymous call reach only a `public` contract, so anyone else here is a40 * defect in the server side, never a caller to serve.41 */42const person = Effect.flatMap(caller, (principal) =>43 Principal.match(principal, {44 Anonymous: () =>45 Effect.die("a contract for signed-in people was called anonymously"),46 Person: (named) => Effect.succeed<Person>(named),47 })48);4950/** Where the caller reached the world: the request's origin. */51const gateway = Effect.map(52 Effect.serviceOption(HttpServerRequest.HttpServerRequest),53 (request) =>54 Option.getOrElse(55 Option.flatMap(request, (incoming) =>56 Option.map(HttpServerRequest.toURL(incoming), ({ origin }) => origin)57 ),58 () => "http://localhost"59 )60);6162/** A repo's git URL at the origin the caller came through. */63const remoteOf = (repo: RepoName | ProjectName) =>64 Effect.map(gateway, (origin) => `${origin}/${repo}.git`);6566/** A claim, with its fork's URL at the caller's origin. */67const atGateway = (claim: ClaimView) =>68 Effect.map(remoteOf(claim.fork), (remote): ClaimView => ({69 ...claim,70 remote,71 }));7273/** The caller's claims and answers, each claim at the caller's origin, under their handle. */74const statusAtGateway = (75 who: Person,76 status: {77 readonly answers: readonly AnswerView[];78 readonly claims: readonly ClaimView[];79 }80) =>81 Effect.map(Effect.forEach(status.claims, atGateway), (claims) => ({82 answers: status.answers,83 claims,84 handle: who.handle,85 }));8687/** Decisions across projects: soonest to expire first, then oldest, then by project and id. */88const byExpiry: Order.Order<Decision> = Order.combineAll([89 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),90 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),91 Order.mapInput(Order.String, ({ project }: Decision) => project),92 Order.mapInput(Order.String, ({ id }: Decision) => id),93]);9495/**96 * One decider's Today across the projects they decide in, as the platform97 * merges it: budgets added up, decisions in one order of expiry, the rest98 * side by side. A person who decides in none has no Today.99 */100const acrossProjects = (101 decider: Person,102 pages: readonly Today[]103): Effect.Effect<Today, NotDecider> => {104 const sumOf = (pick: (page: Today) => number) =>105 Number.sumAll(pages.map(pick));106107 return Array.isReadonlyArrayNonEmpty(pages)108 ? Effect.succeed({109 budget: {110 finishes: sumOf(({ budget }) => budget.finishes),111 total: sumOf(({ budget }) => budget.total),112 used: sumOf(({ budget }) => budget.used),113 },114 decider: decider.handle,115 decisions: Array.sort(116 pages.flatMap(({ decisions }) => decisions),117 byExpiry118 ),119 expiringSoon: pages.flatMap(({ expiringSoon }) => expiringSoon),120 newcomers: Array.dedupeWith(121 pages.flatMap(({ newcomers }) => newcomers),122 sameHandle123 ),124 overflow: sumOf(({ overflow }) => overflow),125 unattended: pages.flatMap(({ unattended }) => unattended),126 })127 : Effect.fail(new NotDecider({}));128};129130/** Every contract over the dev world. A missing contract is a type error here. */131export const devHandlers: Layer.Layer<132 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,133 never,134 Projects | FrontPage | EvidenceStore135> = Contracts.toLayer(136 Effect.gen(function* () {137 const projects = yield* Projects;138 const frontPage = yield* FrontPage;139 const evidence = yield* EvidenceStore;140141 /** `call` on the project named `project`; one never made is `UnknownProject`. */142 const on = <A, E>(143 project: ProjectName,144 call: (api: ProjectApi) => Effect.Effect<A, E>145 ) => Effect.flatMap(projects.get(project), call);146147 /** `call` on every project the front page lists, in name order, keeping what each finds. */148 const everywhere = <A, E>(149 call: (api: ProjectApi) => Effect.Effect<Option.Option<A>, E>150 ) =>151 Effect.gen(function* () {152 const listed = yield* frontPage.projects();153154 const each = yield* Effect.forEach(155 Array.sort(156 Array.dedupe(listed.map(({ project }) => project)),157 Order.String158 ),159 (project) =>160 Effect.flatMap(161 Effect.option(projects.get(project)),162 Option.match({ onNone: () => Effect.succeedNone, onSome: call })163 )164 );165166 return Array.getSomes(each);167 });168169 return {170 claim: ({ ask, project }) =>171 Effect.gen(function* () {172 const who = yield* person;173 const { claim } = yield* on(project, (api) => api.claim(who, ask));174175 return { claim: yield* atGateway(claim) };176 }),177 credits: ({ handle }) =>178 Effect.map(frontPage.credits(handle), (credits) => ({ credits })),179 decide: ({ project, ...input }) =>180 Effect.flatMap(person, (who) =>181 on(project, (api) => api.decide(who, input))182 ),183 evidence: ({ project, ref }) =>184 Effect.flatMap(person, (who) =>185 on(project, (api) =>186 api187 .evidence(who, LogRef.make(ref))188 .pipe(Effect.provideService(EvidenceStore, evidence))189 )190 ),191 // Keyed by the class: lint keeps "shape" out of code names.192 [EnvSchemaOf._tag]: ({ project }) =>193 Effect.flatMap(caller, (who) =>194 on(project, (api) => api[EnvSchemaOf._tag](who))195 ),196 finish: ({ project, ...input }) =>197 Effect.flatMap(person, (who) =>198 on(project, (api) => api.finish(who, input))199 ),200 flagAsk: ({ project, ...input }) =>201 Effect.flatMap(person, (who) =>202 on(project, (api) => api.flagAsk(who, input))203 ),204 fork: ({ project }) =>205 Effect.gen(function* () {206 const who = yield* person;207 const { fork } = yield* on(project, (api) => api.fork(who));208209 return { fork, remote: yield* remoteOf(fork) };210 }),211 frontPage: (filter) =>212 Effect.map(frontPage.entries(filter), (entries) => ({ entries })),213 initProject: ({ project, ...input }) =>214 Effect.gen(function* () {215 const who = yield* person;216217 // A project an earlier call made but could not start is this218 // call's to start; one already started refuses it itself.219 const api = yield* projects220 .create(project)221 .pipe(222 Effect.catchTag("ProjectExists", () =>223 Effect.orDie(projects.get(project))224 )225 );226227 const made = yield* api.initProject(who, input);228229 return { ...made, remote: yield* remoteOf(made.project) };230 }),231 land: ({ project, ...input }) =>232 Effect.flatMap(person, (who) =>233 on(project, (api) => api.land(who, input))234 ),235 landing: ({ project, sha }) =>236 Effect.flatMap(caller, (who) =>237 on(project, (api) => api.landing(who, sha))238 ),239 ledger: ({ project }) =>240 Effect.flatMap(caller, (who) => on(project, (api) => api.ledger(who))),241 listAsks: ({ project }) =>242 Effect.flatMap(caller, (who) =>243 on(project, (api) => api.listAsks(who))244 ),245 listProjects: () =>246 Effect.map(frontPage.projects(), (listed) => ({ projects: listed })),247 openAsk: ({ project, ...input }) =>248 Effect.flatMap(person, (who) =>249 on(project, (api) => api.openAsk(who, input))250 ),251 proposeAsk: ({ project, ...input }) =>252 Effect.flatMap(person, (who) =>253 on(project, (api) => api.proposeAsk(who, input))254 ),255 release: ({ ask, project }) =>256 Effect.flatMap(person, (who) =>257 on(project, (api) => api.release(who, ask))258 ),259 setEnv: ({ project, ...input }) =>260 Effect.flatMap(person, (who) =>261 on(project, (api) => api.setEnv(who, input))262 ),263 showAsk: ({ ask, project }) =>264 Effect.flatMap(caller, (who) =>265 on(project, (api) => api.showAsk(who, ask))266 ),267 status: ({ project }) =>268 Effect.gen(function* () {269 const who = yield* person;270271 if (project !== undefined) {272 return yield* statusAtGateway(273 who,274 yield* on(project, (api) => api.status(who))275 );276 }277278 const each = yield* everywhere((api) =>279 Effect.asSome(api.status(who))280 );281282 return yield* statusAtGateway(who, {283 answers: each.flatMap(({ answers }) => answers),284 claims: each.flatMap(({ claims }) => claims),285 });286 }),287 submitAnswer: ({ project, ...input }) =>288 Effect.flatMap(person, (who) =>289 on(project, (api) => api.submitAnswer(who, input))290 ),291 today: ({ project }) =>292 Effect.gen(function* () {293 const who = yield* person;294295 if (project !== undefined) {296 return yield* on(project, (api) => api.today(who));297 }298299 // A project the caller decides nothing in has no page for them.300 const pages = yield* everywhere((api) =>301 api.today(who).pipe(302 Effect.asSome,303 Effect.catchTag("NotDecider", () => Effect.succeedNone)304 )305 );306307 return yield* acrossProjects(who, pages);308 }),309 verdict: ({ project, ...input }) =>310 Effect.flatMap(caller, (who) =>311 on(project, (api) => api.verdict(who, input))312 ),313 vouch: ({ project, ...input }) =>314 Effect.flatMap(person, (who) =>315 on(project, (api) => api.vouch(who, input))316 ),317 watch: ({ project, since = 0 }) =>318 Stream.unwrap(319 Effect.map(projects.get(project), (api) =>320 Stream.paginate(since, (after) =>321 Effect.map(api.events(after, EVENT_PAGE), (rows) => [322 rows.map(({ event }) => event),323 rows.length < EVENT_PAGE324 ? Option.none()325 : Option.fromUndefinedOr(rows.at(-1)?.seq),326 ])327 )328 )329 ),330 };331 })332);
added:apps/web/src/dev/lander.ts+290 added
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 */13import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";14import { Brand } from "@repo/brand";15import { composeRef, Lander, landedRef, Rebuild } from "@repo/project/lander";16import type { Change, LandJob } from "@repo/project/lander";17import type { CommitSha, RepoName } from "@repo/protocol/ids";18import { LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";19import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";20import { sdkVersion } from "@repo/rules/rules-evaluator";21import { Array, DateTime, Effect, Layer, Option, Ref } from "effect";2223import {24 filesAt,25 overlay,26 personIdentity,27 platformIdentity,28 scratch,29 textOf,30} from "./git.ts";31import type { Files, Snapshot } from "./git.ts";3233const mainRef = RefName.make("refs/heads/main");3435const blocked = () => new VerifierBlocked({});3637/** A commit's files, or `VerifierBlocked` when the repo doesn't hold it. */38const read = (repo: RepoName, commit: CommitSha) =>39 filesAt(repo, commit).pipe(40 Effect.flatMap(Effect.fromOption),41 Effect.mapError(blocked)42 );4344/** What `head` changed against `base`, path by path, in path order. */45const changesOf = (base: Snapshot, head: Snapshot): readonly Change[] =>46 Array.dedupe([...base.keys(), ...head.keys()])47 .toSorted()48 .flatMap((path): readonly Change[] => {49 const before = base.get(path);50 const after = head.get(path);51 const at = RepoPath.make(path);5253 if (before === undefined) {54 return after === undefined55 ? []56 : [{ after: after.blob, path: at, status: "added" }];57 }5859 if (after === undefined) {60 return [{ before: before.blob, path: at, status: "deleted" }];61 }6263 return before.blob === after.blob64 ? []65 : [66 {67 after: after.blob,68 before: before.blob,69 path: at,70 status: "modified",71 },72 ];73 });7475/** An answer's head merged onto main: main's files with what the answer changed laid over them. */76const merged = (input: {77 readonly repo: RepoName;78 readonly main: LandedSha;79 readonly fork: RepoName;80 readonly base: CommitSha;81 readonly head: CommitSha;82}) =>83 Effect.gen(function* () {84 const base = yield* read(input.fork, input.base);85 const head = yield* read(input.fork, input.head);86 const main = yield* read(input.repo, input.main);87 const changes = changesOf(base, head);8889 // Main moved this path since the answer's base, to something else.90 const conflicts = changes.flatMap(({ path }) =>91 main.get(path)?.blob !== base.get(path)?.blob &&92 main.get(path)?.blob !== head.get(path)?.blob93 ? [path]94 : []95 );9697 if (Array.isReadonlyArrayNonEmpty(conflicts)) {98 return yield* new StaleBase({99 base: input.base,100 conflicts,101 main: input.main,102 });103 }104105 // Main's files, with each path the answer changed as the answer left it.106 const files = new Map(textOf(main));107108 for (const { path } of changes) {109 const text = head.get(path)?.text;110111 if (text === undefined) {112 files.delete(path);113 } else {114 files.set(path, text);115 }116 }117118 return { changes, files: files satisfies Files };119 });120121/** The files a landing's tree is rebuilt from. */122const rebuilt = (job: LandJob) =>123 Rebuild.$match(job.rebuild, {124 Compose: ({ files }) =>125 Effect.map(read(job.repo, job.main), (main) =>126 overlay(127 textOf(main),128 files.map(({ content, path }) => [path, content] as const)129 )130 ),131 Existing: ({ commit }) => Effect.map(read(job.repo, commit), textOf),132 Merge: ({ base, fork, head }) =>133 Effect.map(134 merged({ base, fork, head, main: job.main, repo: job.repo }),135 ({ files }) => files136 ),137 });138139/** The commit an answer's landing was made on: its base; otherwise main. */140const baseOf = (job: LandJob) =>141 Rebuild.$is("Merge")(job.rebuild) ? job.rebuild.base : job.main;142143/** The Lander over the memory repo host, landing at the world's clock. */144export const DevLander: Layer.Layer<Lander, never, RepoHost> = Layer.effect(145 Lander,146 Effect.gen(function* () {147 const host = yield* RepoHost;148 const provided = Effect.provideService(RepoHost, host);149150 // A request landed before: its commit, so a second land returns it.151 const landedBy = yield* Ref.make<ReadonlyMap<string, LandedSha>>(new Map());152153 const tipOf = (repo: RepoName, ref: RefName) =>154 host.refs(repo).pipe(155 Effect.map((refs) => Option.fromNullishOr(refs.get(ref))),156 Effect.mapError(blocked)157 );158159 const land = (job: LandJob) =>160 Effect.gen(function* () {161 const before = (yield* Ref.get(landedBy)).get(job.requestId);162163 if (before !== undefined) {164 return { pending: [], sha: before };165 }166167 const tip = yield* tipOf(job.repo, mainRef);168169 if (!Option.contains(tip, job.main)) {170 return yield* new StaleBase({171 base: baseOf(job),172 conflicts: [],173 main: Option.getOrElse(tip, () => job.main),174 });175 }176177 const into = yield* scratch;178 const tree = yield* into.tree(yield* rebuilt(job));179180 if (TreeSha.make(tree) !== job.tree) {181 return yield* blocked();182 }183184 const commit = yield* into.commit({185 at: yield* DateTime.now,186 author: personIdentity(job.author),187 committer: platformIdentity,188 message: job.message,189 parents: [job.main],190 tree,191 });192193 // Never forced: if main moved since `job.main`, the push is refused.194 const [outcome] = yield* host195 .push(job.repo, into.source, [196 { from: Option.some(job.main), ref: mainRef, to: commit },197 ])198 .pipe(199 Effect.catchTags({200 HostBusy: () => Effect.fail(new RepoBusy({})),201 RepoNotFound: () => Effect.fail(blocked()),202 })203 );204205 if (outcome === undefined || !RefOutcome.$is("Updated")(outcome)) {206 return yield* new StaleBase({207 base: baseOf(job),208 conflicts: [],209 main: job.main,210 });211 }212213 const sha = LandedSha.make(commit);214215 yield* Ref.update(landedBy, (all) =>216 new Map(all).set(job.requestId, sha)217 );218219 // The mirror follows main in a push of its own (ADR 0005).220 const mirror = yield* tipOf(job.repo, landedRef);221222 yield* host223 .push(job.repo, into.source, [224 { from: mirror, ref: landedRef, to: commit },225 ])226 .pipe(Effect.ignore);227228 return { pending: [], sha };229 });230231 return Lander.of({232 bundleRules: ({ at, repo }) =>233 provided(234 Effect.map(read(repo, at), (files) => ({235 entry: `${Brand.configDir}/project.ts`,236 modules: Object.fromEntries(237 [...textOf(files)].filter(([path]) =>238 path.startsWith(`${Brand.configDir}/`)239 )240 ),241 sdkVersion,242 }))243 ),244 compose: ({ files, main, repo }) =>245 provided(246 Effect.gen(function* () {247 const onMain = yield* read(repo, main);248 const into = yield* scratch;249250 const tree = yield* into.tree(251 overlay(252 textOf(onMain),253 files.map(({ content, path }) => [path, content] as const)254 )255 );256257 const commit = yield* into.commit({258 at: yield* DateTime.now,259 author: platformIdentity,260 committer: platformIdentity,261 message: "Compose files onto main for a check",262 parents: [main],263 tree,264 });265266 const ref = composeRef(TreeSha.make(tree));267 const existing = yield* tipOf(repo, ref);268269 if (!Option.contains(existing, commit)) {270 yield* host271 .push(repo, into.source, [{ from: existing, ref, to: commit }])272 .pipe(Effect.mapError(blocked));273 }274275 return { commit, tree: TreeSha.make(tree) };276 })277 ),278 land: (job) => provided(land(job)),279 merge: (job) =>280 provided(281 Effect.gen(function* () {282 const { changes, files } = yield* merged(job);283 const into = yield* scratch;284285 return { changes, tree: TreeSha.make(yield* into.tree(files)) };286 })287 ),288 });289 })290);
added:apps/web/src/dev/projection.ts+57 added
added:apps/web/src/dev/seed.ts+335 added
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 and offering it as custody does8 * (it lands, through the answer's run, in the same call), people proposing9 * and flagging, the decider declining two, and someone pushing straight to10 * `main`, reported as the push event would be.11 *12 * Each step happens at its own whole minute after the world's start13 * (`devMinute`), so every time the world holds comes from one fixed instant14 * and two seeds give the same world. The world then serves at the last15 * step's minute.16 *17 * What the service can't be brought to through its methods is left out18 * (502's `## Comments`): a `Finish` decision (nothing opens one yet), an19 * answer refused `OutOfScope` (a refused answer is never recorded) and an20 * `Assisted-by:` trailer (no answer carries one yet, 515).21 */22import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";23import type { ProjectApi } from "@repo/project/project";24import { Projects } from "@repo/project/projects";25import { DecisionSubject } from "@repo/protocol/domain/decision";26import type { Decision } from "@repo/protocol/domain/decision";27import { AskId, Handle, RepoName, RequestId } from "@repo/protocol/ids";28import type { CommitSha, ProjectName, ProposalId } from "@repo/protocol/ids";29import { Anonymous, Person } from "@repo/protocol/principal";30import { Array, DateTime, Effect, Option } from "effect";3132import { DevClock, devMinute } from "./clock.ts";33import { burrow, burrowPeople, datekit, datekitPeople } from "./examples.ts";34import type { Opening } from "./examples.ts";35import { filesAt, overlay, personIdentity, scratch, textOf } from "./git.ts";36import type { Files } from "./git.ts";3738const mainRef = RefName.make("refs/heads/main");3940/** People who propose and flag in datekit; nobody vouched for them. */41const visitors = {42 flagger: Handle.make("sefa"),43 proposer: Handle.make("tove"),44 regular: Handle.make("wren"),45} as const;4647/** Everyone in the seed: the people a dev token may sign in as. */48export const devPeople: readonly Handle[] = [49 datekitPeople.decider,50 datekitPeople.zones,51 datekitPeople.contributor,52 visitors.proposer,53 visitors.flagger,54 visitors.regular,55 burrowPeople.decider,56 burrowPeople.second,57];5859const as = (handle: Handle) => Person.make({ handle });6061/** A commit of `files` on `parent` (or a first commit), by `author`, at the world's time. */62const commitOf = (input: {63 readonly author: Handle;64 readonly files: Files;65 readonly message: string;66 readonly parent: Option.Option<CommitSha>;67}) =>68 Effect.gen(function* () {69 const into = yield* scratch;70 const who = personIdentity(input.author);7172 const commit = yield* into.commit({73 at: yield* DateTime.now,74 author: who,75 committer: who,76 message: input.message,77 parents: Option.toArray(input.parent),78 tree: yield* into.tree(input.files),79 });8081 return { commit, source: into.source };82 });8384/** A commit pushed to `repo`'s main with a compare-and-swap from `parent`. */85const pushed = (repo: RepoName, input: Parameters<typeof commitOf>[0]) =>86 Effect.gen(function* () {87 const host = yield* RepoHost;88 const { commit, source } = yield* commitOf(input);8990 const outcomes = yield* host.push(repo, source, [91 { from: input.parent, ref: mainRef, to: commit },92 ]);9394 if (!outcomes.every(RefOutcome.$is("Updated"))) {95 return yield* Effect.die(`${repo}'s main moved under the seed`);96 }9798 return commit;99 });100101/** The files of `repo` at `commit`, which the seed itself pushed. */102const filesOf = (repo: RepoName, commit: CommitSha) =>103 Effect.flatMap(filesAt(repo, commit), Effect.fromOption);104105/** Moves the world's clock to `minute` minutes after its start. */106const at = (minute: number) =>107 Effect.flatMap(Effect.service(DevClock), (clock) =>108 clock.set(devMinute(minute))109 );110111/**112 * A project made and adopted: its initializer creates it, pushes its first113 * commit, and the gateway reports the push.114 */115const started = (116 project: ProjectName,117 initializer: Handle,118 files: Files,119 minute: number120) =>121 Effect.gen(function* () {122 const projects = yield* Projects;123124 yield* at(minute);125126 const api = yield* projects.create(project);127128 yield* api.initProject(as(initializer), {});129 yield* at(minute + 1);130131 const first = yield* pushed(RepoName.make(project), {132 author: initializer,133 files,134 message: "First commit",135 parent: Option.none(),136 });137138 yield* api.recordFirstPush(as(initializer), first);139140 return api;141 });142143/** Each ask opened by `decider` from its files, a minute apart from `minute`. */144const opened = (145 api: ProjectApi,146 decider: Handle,147 asks: readonly (readonly [AskId, Opening])[],148 minute: number149) =>150 Effect.forEach(151 asks,152 ([ask, files], index) =>153 Effect.andThen(154 at(minute + index),155 api.openAsk(as(decider), { ask, files })156 ),157 { discard: true }158 );159160/**161 * An answer to `ask` from `answerer`, who holds its claim: a commit of162 * `files` on the claim's base, pushed to the claim's fork, reported as the163 * gateway's custody reports it, then offered as the answer.164 */165const answered = (166 api: ProjectApi,167 answerer: Handle,168 input: {169 readonly ask: AskId;170 readonly files: Files;171 readonly message: string;172 }173) =>174 Effect.gen(function* () {175 const { claims } = yield* api.status(as(answerer));176177 const claim = yield* Effect.fromOption(178 Array.findFirst(claims, ({ ask }) => ask === input.ask)179 );180181 const base = yield* filesOf(claim.fork, claim.base);182183 const head = yield* pushed(claim.fork, {184 author: answerer,185 files: overlay(textOf(base), input.files),186 message: input.message,187 parent: Option.some(claim.base),188 });189190 const refusals = yield* api.recordPush({191 after: head,192 before: Option.some(claim.base),193 eventId: `${claim.fork}@${head}`,194 pusher: as(answerer),195 ref: mainRef,196 repo: claim.fork,197 });198199 if (Array.isReadonlyArrayNonEmpty(refusals)) {200 return yield* Effect.die(refusals);201 }202203 return yield* api.submitAnswer(as(answerer), {204 ask: input.ask,205 base: claim.base,206 head,207 requestId: RequestId.make(`push-${head}-${answerer}`),208 });209 });210211/** The decision that puts proposal `proposal` to `decider`. */212const decisionOn = (api: ProjectApi, decider: Handle, proposal: ProposalId) =>213 Effect.flatMap(api.today(as(decider)), ({ decisions }) =>214 Effect.fromOption(215 Array.findFirst(216 decisions,217 ({ subject }: Decision) =>218 DecisionSubject.guards.OpenProposal(subject) &&219 subject.proposal === proposal220 )221 )222 );223224/** Proposals from a regular that datekit's decider declines, each on its own minute. */225const DECLINED = [226 "parseISO accepts two-digit years.",227 "datekit wraps the Temporal API.",228];229230/** datekit: four asks opened, one answered and landed, one claimed, decisions waiting. */231const seedDatekit = Effect.gen(function* () {232 const { contributor, decider } = datekitPeople;233 const api = yield* started(datekit.project, decider, datekit.files, 0);234235 yield* opened(api, decider, datekit.asks, 2);236237 yield* at(6);238 yield* api.claim(as(contributor), datekit.answer.ask);239240 yield* at(7);241 yield* answered(api, contributor, datekit.answer);242243 yield* at(8);244 yield* api.claim(as(contributor), AskId.make("parse-iso-week"));245246 yield* at(9);247 yield* api.proposeAsk(as(visitors.proposer), {248 want: 'format(date, "Qo") prints the quarter as an ordinal.',249 });250251 yield* at(10);252 yield* api.flagAsk(as(visitors.flagger), {253 ask: AskId.make("add-months-clamp"),254 reason: "Its check pins a common year only; leap years need a case too.",255 });256257 yield* Effect.forEach(258 DECLINED,259 (want, index) =>260 Effect.gen(function* () {261 yield* at(11 + index * 2);262263 const { proposal } = yield* api.proposeAsk(as(visitors.regular), {264 want,265 });266267 yield* at(12 + index * 2);268269 const decision = yield* decisionOn(api, decider, proposal.id);270271 yield* api.decide(as(decider), {272 choice: "decline",273 decision: decision.id,274 note: "Out of scope for a small library.",275 });276 }),277 { discard: true }278 );279280 return api;281});282283/** burrow: the migrate family opened, its delete step waiting on the other two. */284const seedBurrow = Effect.flatMap(285 started(burrow.project, burrowPeople.decider, burrow.files, 15),286 (api) => opened(api, burrowPeople.decider, burrow.asks, 17)287);288289/**290 * Someone with access to datekit's storage pushes to `main` past the291 * platform, and the push event reports it: a `StrayPush` decision whose292 * default is to revert.293 */294const strayPush = (api: ProjectApi) =>295 Effect.gen(function* () {296 const host = yield* RepoHost;297 const repo = RepoName.make(datekit.project);298299 yield* at(21);300301 const tip = yield* Effect.fromOption(302 Option.fromNullishOr((yield* host.refs(repo)).get(mainRef))303 );304305 const after = yield* pushed(repo, {306 author: datekitPeople.zones,307 files: overlay(textOf(yield* filesOf(repo, tip)), datekit.stray.files),308 message: datekit.stray.message,309 parent: Option.some(tip),310 });311312 yield* api.recordPush({313 after,314 before: Option.some(tip),315 eventId: `${repo}@${after}`,316 pusher: Anonymous.make({}),317 ref: mainRef,318 repo,319 });320 });321322/**323 * Both projects, seeded; the world's clock left at the last step. Any324 * refusal on the way is a defect of the seed's, never a state to serve.325 */326export const seedDev: Effect.Effect<327 void,328 never,329 Projects | RepoHost | DevClock330> = Effect.gen(function* () {331 const datekitApi = yield* seedDatekit;332333 yield* seedBurrow;334 yield* strayPush(datekitApi);335}).pipe(Effect.orDie);
added:apps/web/src/dev/server.ts+40 added
added:apps/web/src/dev/sessions.ts+39 added
added:apps/web/src/dev/world.ts+55 added
added:apps/web/test/client.test.ts+272 added
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 HTTP `Authorization`, or none.7 * Every test reads the one world the module's `backend` seeds, in order;8 * only the last changes it.9 */10import { describe, expect, it } from "@effect/vitest";11import { DecisionSubject } from "@repo/protocol/domain/decision";12import { AskId, ProjectName } from "@repo/protocol/ids";13import { Unauthenticated } from "@repo/protocol/principal";14import { UnknownAsk } from "@repo/protocol/refusal";15import { env } from "cloudflare:workers";16import { Array, DateTime, Effect, Exit, Layer, Option, Schema } from "effect";17import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";18import { Atom, AtomRegistry, Reactivity } from "effect/reactivity";19import type { AsyncResult } from "effect/reactivity";20import { RpcClient, RpcSerialization } from "effect/rpc";2122import { backend } from "#backend";2324import { keys } from "../src/client/keys.ts";25import { ContractsClient, webContracts } from "../src/surfaces.ts";2627const WEB_URL = "http://localhost:3000";2829const datekit = ProjectName.make("datekit");3031/** The decider of datekit in the dev world, and the token that signs them in. */32const DECIDER = "dev-ines-v";3334/**35 * `ContractsClient` as one browser runs it: its HTTP protocol posts to the36 * web's `/rpc`, which hands the request to `backend` in process, with37 * `token` as the request's bearer when there is one.38 */39const browser = (token?: string) =>40 Layer.effect(41 ContractsClient,42 RpcClient.make(webContracts, { flatten: true })43 ).pipe(44 Layer.provide(45 RpcClient.layerProtocolHttp({46 transformClient: HttpClient.mapRequest((request) =>47 token === undefined48 ? request49 : HttpClientRequest.bearerToken(request, token)50 ),51 url: `${WEB_URL}/rpc`,52 })53 ),54 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),55 Layer.provide(56 Layer.succeed(FetchHttpClient.Fetch, (input, init) =>57 backend(new Request(input, init), env)58 )59 ),60 Layer.provideMerge(Reactivity.layer)61 );6263/** A registry whose `ContractsClient` is `browser(token)`'s. */64const registryAs = (token?: string) =>65 AtomRegistry.make({66 initialValues: [67 Atom.initialValue(ContractsClient.runtime.layer, browser(token)),68 ],69 });7071/** An atom's value once it has one, past any refetch under way. */72const settled = <A, E>(73 registry: AtomRegistry.AtomRegistry,74 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>75) =>76 Effect.exit(77 AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true })78 );7980const todayAtom = ContractsClient.query(81 "today",82 {},83 { reactivityKeys: keys.today() }84);8586describe("the dev world, through the web's atoms", () => {87 it.live(88 "lists every open ask of both projects on the front page, the newcomers' one untakeable",89 () =>90 Effect.gen(function* () {91 const registry = registryAs();9293 const page = yield* settled(94 registry,95 ContractsClient.query(96 "frontPage",97 {},98 { reactivityKeys: keys.front() }99 )100 );101102 expect(Exit.isSuccess(page)).toBeTruthy();103104 const entries = Exit.isSuccess(page) ? page.value.entries : [];105106 expect(107 entries108 .map(109 ({ ask, project, takeable }) =>110 `${project}/${ask.ask} ${takeable}`111 )112 .toSorted()113 ).toStrictEqual([114 "burrow/drop-legacy-fetch true",115 "burrow/drop-legacy-fetch-auth true",116 "burrow/drop-legacy-fetch-billing true",117 "burrow/drop-legacy-fetch-delete false",118 "datekit/add-months-clamp true",119 "datekit/format-ordinal false",120 "datekit/parse-iso-week false",121 ]);122123 const reserved = entries.find(({ ask }) => ask.reserve !== undefined);124125 expect(reserved?.ask.ask).toBe("format-ordinal");126 expect(reserved?.ask.reserve).toBe("newcomers");127 expect(reserved?.ask.claimed).toBeFalsy();128 })129 );130131 it.live(132 "lists a project's asks, and an ask it never opened is UnknownAsk",133 () =>134 Effect.gen(function* () {135 const registry = registryAs();136137 const listed = yield* settled(138 registry,139 ContractsClient.query(140 "listAsks",141 { project: datekit },142 { reactivityKeys: keys.project(datekit) }143 )144 );145146 expect(147 Exit.isSuccess(listed)148 ? listed.value.asks.map(({ ask }) => ask).toSorted()149 : []150 ).toStrictEqual([151 "add-months-clamp",152 "format-ordinal",153 "parse-iso-week",154 ]);155156 const unknown = AskId.make("no-such-ask");157158 const shown = yield* settled(159 registry,160 ContractsClient.query(161 "showAsk",162 { ask: unknown, project: datekit },163 { reactivityKeys: keys.ask(datekit, unknown) }164 )165 );166167 const error = Exit.isFailure(shown)168 ? Option.getOrUndefined(Exit.findErrorOption(shown))169 : undefined;170171 expect(Schema.is(UnknownAsk)(error)).toBeTruthy();172 })173 );174175 it.live("keeps Today from an anonymous browser", () =>176 Effect.gen(function* () {177 const anonymous = yield* settled(registryAs(), todayAtom);178179 const refused = Exit.isFailure(anonymous)180 ? Option.getOrUndefined(Exit.findErrorOption(anonymous))181 : undefined;182183 expect(Schema.is(Unauthenticated)(refused)).toBeTruthy();184 })185 );186187 it.live("shows the decider their Today, with the seed's decisions", () =>188 Effect.gen(function* () {189 const today = yield* settled(registryAs(DECIDER), todayAtom);190191 expect(192 Exit.isSuccess(today)193 ? {194 budget: today.value.budget,195 decider: today.value.decider,196 newcomers: today.value.newcomers,197 projects: Array.dedupe(198 today.value.decisions.map(({ project }) => project)199 ),200 subjects: today.value.decisions201 .map(({ subject }) => subject._tag)202 .toSorted(),203 unattended: today.value.unattended.map(({ ask }) => ask),204 }205 : undefined206 ).toStrictEqual({207 budget: { finishes: 0, total: 5, used: 2 },208 decider: "ines-v",209 newcomers: ["bram"],210 projects: ["datekit"],211 subjects: ["OpenProposal", "OpenProposal", "StrayPush"],212 unattended: ["diff-in-days-dst"],213 });214 })215 );216217 it.live(218 "closes a decision the decider declines, and Today refetches without it",219 () =>220 Effect.gen(function* () {221 const registry = registryAs(DECIDER);222 const unmount = registry.mount(todayAtom);223 const before = yield* settled(registry, todayAtom);224225 const proposal = Exit.isSuccess(before)226 ? before.value.decisions.find(({ subject }) =>227 DecisionSubject.guards.OpenProposal(subject)228 )229 : undefined;230231 expect(proposal).toBeDefined();232233 if (proposal === undefined) {234 return;235 }236237 const decide = ContractsClient.mutation("decide");238239 registry.set(decide, {240 payload: {241 choice: "decline",242 decision: proposal.id,243 project: proposal.project,244 },245 reactivityKeys: [...keys.today(), ...keys.project(proposal.project)],246 });247248 const decided = yield* settled(registry, decide);249250 const taken = Exit.isSuccess(decided)251 ? decided.value.decision.decided252 : undefined;253254 expect(taken?.choice).toBe("decline");255 // The world serves at the instant its seed left the clock.256 expect(257 taken === undefined ? undefined : DateTime.formatIso(taken.at)258 ).toBe("2026-10-07T09:21:00.000Z");259260 const after = yield* settled(registry, todayAtom);261262 expect(263 Exit.isSuccess(after)264 ? after.value.decisions.map(({ id }) => id).includes(proposal.id)265 : true266 ).toBeFalsy();267 expect(Exit.isSuccess(after) ? after.value.budget.used : 0).toBe(3);268269 unmount();270 })271 );272});
added:apps/web/test/dev-backend.test.ts+188 added
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 */7import { describe, expect, it } from "@effect/vitest";8import { Client, Contracts } from "@repo/protocol/contracts";9import { ProjectEvent } from "@repo/protocol/domain/event";10import { Handle, ProjectName } from "@repo/protocol/ids";11import {12 Context,13 DateTime,14 Duration,15 Effect,16 Equal,17 Layer,18 Stream,19} from "effect";20import type { Scope } from "effect";21import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";22import { RpcClient, RpcSerialization } from "effect/rpc";2324import { devStart } from "../src/dev/clock.ts";25import { devServer } from "../src/dev/server.ts";26import { devToken } from "../src/dev/sessions.ts";2728const PROJECTS = [ProjectName.make("burrow"), ProjectName.make("datekit")];2930const decider = devToken(Handle.make("ines-v"));3132const contributor = devToken(Handle.make("bram"));3334/**35 * A fresh world, seeded and served, and `read` run against it: each36 * `as(token)` is a client whose requests carry that bearer, or none.37 */38const inFreshWorld = <A, E>(39 read: (40 as: (token?: string) => Layer.Layer<Client>41 ) => Effect.Effect<A, E, Scope.Scope>42) =>43 Effect.scoped(44 Effect.gen(function* () {45 const { dispose, handler } = devServer();4647 yield* Effect.addFinalizer(() => Effect.promise(dispose));4849 const as = (token?: string) =>50 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(51 Layer.provide(52 RpcClient.layerProtocolHttp({53 transformClient: HttpClient.mapRequest((request) =>54 token === undefined55 ? request56 : HttpClientRequest.bearerToken(request, token)57 ),58 url: "http://localhost/rpc",59 })60 ),61 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),62 Layer.provide(63 Layer.succeed(FetchHttpClient.Fetch, (input, init) =>64 handler(new Request(input, init))65 )66 )67 );6869 return yield* read(as);70 })71 );7273/** The client a layer from `as(token)` makes, for as long as the world lives. */74const clientOf = (layer: Layer.Layer<Client>) =>75 Effect.map(Layer.build(layer), Context.get(Client));7677/** The front page and the project list, as anyone reads them. */78const pages = inFreshWorld((as) =>79 Effect.gen(function* () {80 const anyone = yield* clientOf(as());81 const { entries } = yield* anyone.frontPage({});82 const { projects } = yield* anyone.listProjects({});8384 return { entries, projects };85 })86);8788/** Every instant a reader of the seeded world can see. */89const instants = inFreshWorld((as) =>90 Effect.gen(function* () {91 const anyone = yield* clientOf(as());92 const ines = yield* clientOf(as(decider));93 const bram = yield* clientOf(as(contributor));9495 const events = yield* Effect.forEach(PROJECTS, (project) =>96 Stream.runCollect(anyone.watch({ project }))97 );9899 const today = yield* ines.today({});100 const { claims } = yield* bram.status({});101102 return [103 ...events104 .flat()105 .flatMap((event) => [106 event.at,107 ...(ProjectEvent.guards.Landed(event)108 ? [event.landing.landedAt]109 : []),110 ]),111 ...today.decisions.flatMap(({ expiresAt, openedAt }) => [112 openedAt,113 expiresAt,114 ]),115 ...today.unattended.map(({ landedAt }) => landedAt),116 ...claims.flatMap(({ lapsesAt, openedAt, warnsAt }) => [117 openedAt,118 warnsAt,119 lapsesAt,120 ]),121 ];122 })123);124125/** datekit's landed answer, as Today samples it and as `landing` reads it. */126const landedAnswer = inFreshWorld((as) =>127 Effect.gen(function* () {128 const anyone = yield* clientOf(as());129 const ines = yield* clientOf(as(decider));130 const { unattended } = yield* ines.today({});131 const [sampled] = unattended;132133 if (sampled === undefined) {134 return yield* Effect.die("datekit has no landed answer");135 }136137 const { landing } = yield* anyone.landing({138 project: sampled.project,139 sha: sampled.sha,140 });141142 return { landing, sampled };143 })144);145146describe("the dev seed", () => {147 it.live("gives two fresh worlds equal front pages and project lists", () =>148 Effect.gen(function* () {149 const first = yield* pages;150 const second = yield* pages;151152 expect(first.entries).toHaveLength(7);153 expect(first.projects.map(({ project }) => project)).toStrictEqual(154 PROJECTS155 );156 expect(Equal.equals(first, second)).toBeTruthy();157 })158 );159160 it.live("counts every time it holds in whole minutes from one start", () =>161 Effect.gen(function* () {162 const seen = yield* instants;163 const minute = Duration.toMillis(Duration.minutes(1));164165 expect(seen.length).toBeGreaterThan(20);166167 for (const instant of seen) {168 const since = Duration.toMillis(DateTime.distance(devStart, instant));169170 expect(since).toBeGreaterThanOrEqual(0);171 expect(since % minute).toBe(0);172 }173 })174 );175176 it.live("lands bram's answer to datekit with its credit trailers", () =>177 Effect.gen(function* () {178 const { landing, sampled } = yield* landedAnswer;179180 expect(landing).toStrictEqual(sampled);181 expect(landing.ask).toBe("diff-in-days-dst");182 expect(landing.author).toBe("bram");183 expect(184 landing.credits.map(({ handle, role }) => `${role}: ${handle}`)185 ).toStrictEqual(["Asked-by: ines-v", "Signed-off-by: bram"]);186 })187 );188});