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
Provenance
- Commit
4aeb23e- Tree
9fdf413- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
eebd79b- Parent 2
e11b9ce
15 files changed+2986 added−7 removed
modified:apps/web/src/dev/backend.ts+17 added-7 removed
123456723456789101112913141516171819/** * `#backend` under the `development` condition (`vite dev`, vitest). For now * it forwards like the production target; issue 502 replaces it with the * project service in process over memory adapters and a seeded world, so UI * work needs no live platform. Nothing outside `src/dev/` imports this file: * only the `#backend` condition reaches it, and the production build carries * none of it (505's production-bundle test). * `#backend` under the `development` condition (`vite dev`, vitest): the * contracts served in process by the dev world, so the web runs with no * platform, no Artifacts and no network. The browser reaches it through * the same `/rpc` route, the same `Contracts` group and the same atoms as * production; only this target differs. * * One world per isolate (`server.ts`): it is made and seeded when this * module loads, since `toWebHandler` builds at once, and kept for the * isolate's life. Nothing outside `src/dev/` imports this file, and the * production build carries none of it (505's production-bundle test). */export { backend } from "../server/backend.ts";import type { Backend } from "../server/rpc.ts";import { devServer } from "./server.ts";
const served = devServer();
/** The development backend: every request answered by the dev world, the env unused. */export const backend: Backend = (request) => served.handler(request);added:apps/web/src/dev/checker.ts+54 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/** * The dev world's Checker: the scripted `/memory` adapter, with a script it * writes as it goes, by one rule. A commit is checked only when a decider's * ask files are composed onto main, where the ask's check is red first, so * every lane fails there, the same way each time; a tree is checked only * when an answer is merged, and every lane passes there. No check runs: * the world shows the platform's flow, not a project's tests. */import { CheckAt, CheckRunner } from "@repo/checks/check-runner";import type { CheckJob } from "@repo/checks/check-runner";import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";import type { LaneResult } from "@repo/protocol/domain/answer";import { Context, Effect, Layer } from "effect";
/** What a lane comes to where it runs: red on a composed commit, green on a merged tree. */const scripted = ( job: CheckJob, lane: CheckJob["lanes"][number]): LaneResult => ({ command: lane.command, durationMs: 1, lane: lane.lane, result: CheckAt.match(job.at, { Commit: () => "failed" as const, Tree: () => "passed" as const, }),});
export const DevChecker: Layer.Layer<CheckRunner> = Layer.effect( CheckRunner, Effect.gen(function* () { const script = new Map<string, readonly LaneResult[]>();
const memory = Context.get( yield* Layer.build(CheckRunnerMemory.layer(script)), CheckRunner );
return CheckRunner.of({ run: (job) => Effect.suspend(() => { for (const lane of job.lanes) { const key = scriptKey(job.at, lane.lane);
if (!script.has(key)) { script.set(key, [scripted(job, lane)]); } }
return memory.run(job); }), }); }));added:apps/web/src/dev/clock.ts+59 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859/** * The dev world's time: one clock that every part of the world reads, as a * test's TestClock is, standing still at the instant it was last set. The * seed sets it step by step from one fixed start (`seed.ts`), and the world * then serves at the instant the seed left it, so a decision opened by the * seed never expires under a developer and every timestamp is the same on * every run. Sleeping, which nothing in the world does, waits in real time. */import { Clock, Context, DateTime, Effect, Layer } from "effect";
/** Moves the dev world's clock to an instant. */export class DevClock extends Context.Service< DevClock, { readonly set: (at: DateTime.Utc) => Effect.Effect<void> }>()("web/dev/DevClock") {}
const NANOS_PER_MILLI = 1_000_000n;
/** Where the world's time starts: every instant the seed writes is this one or a whole minute after. */export const devStart: DateTime.Utc = DateTime.toUtc( DateTime.makeUnsafe("2026-10-07T09:00:00Z"));
/** The instant `minutes` whole minutes after the world's start. */export const devMinute = (minutes: number): DateTime.Utc => DateTime.add(devStart, { minutes });
/** A clock standing at `start` until it is set elsewhere, and the way to set it. */export const devClockAt = (start: DateTime.Utc): Layer.Layer<DevClock> => Layer.effectContext( Effect.gen(function* () { const real = yield* Clock.Clock; let millis = DateTime.toEpochMillis(start);
const nanos = () => BigInt(millis) * NANOS_PER_MILLI;
const clock: Clock.Clock = { currentTimeMillis: Effect.sync(() => millis), currentTimeMillisUnsafe: () => millis, currentTimeNanos: Effect.sync(nanos), currentTimeNanosUnsafe: nanos, // Elapsed time is measured, never seeded. monotonicTimeNanos: real.monotonicTimeNanos, monotonicTimeNanosUnsafe: () => real.monotonicTimeNanosUnsafe(), sleep: (duration) => real.sleep(duration), };
const devClock = DevClock.of({ set: (at) => Effect.sync(() => { millis = DateTime.toEpochMillis(at); }), });
return Context.make(DevClock, devClock).pipe( Context.add(Clock.Clock, clock) ); }) );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+ */21+import { Brand } from "@repo/brand";22+import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";23+import { Command, SymbolName } from "@repo/protocol/domain/common";24+import type { AskKind } from "@repo/protocol/domain/kind";25+import { PolicyInput } from "@repo/protocol/domain/policy";26+import { AskId, Handle, ProjectName, RepoPath } from "@repo/protocol/ids";27+import { Array, Predicate, Schema } from "effect";28+29+import type { Files } from "./git.ts";30+31+const dir = Brand.configDir;32+33+const encodeCheck = Schema.encodeSync(CheckSpec);34+35+const decodeCheck = Schema.decodeSync(CheckSpec);36+37+const encodeMeasure = Schema.encodeSync(RatchetMeasure);38+39+/** What a project's `policy.json` states, as the file holds it. */40+type Stated = typeof PolicyInput.Encoded;41+42+/** One ask as `policy.json` states it. */43+type StatedAsk = Stated["asks"][number];44+45+/** A `policy.json` from what its project states, with every default written out. */46+const policyJson = (stated: Stated) =>47+ `${JSON.stringify(48+ Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),49+ null,50+ 251+ )}\n`;52+53+/** One file an ask opens with. */54+interface AskFile {55+ readonly content: string;56+ readonly path: RepoPath;57+}58+59+/** The files a decider opens one ask with: its ask file, then its check's file if it has one. */60+export type Opening = Array.NonEmptyReadonlyArray<AskFile>;61+62+/** The args a kind takes for an ask's check, as its ask file passes them (`packages/sdk`'s `kinds`). */63+interface 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+}72+73+/** A string, or a list of them, as TypeScript source spells it. */74+const spelled = (value: string | readonly string[]): string =>75+ Predicate.isString(value)76+ ? JSON.stringify(value)77+ : `[${value.map(spelled).join(", ")}]`;78+79+/**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+ */85+const 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+ });93+94+/** An ask's territory as its file spells it: the repo-wide builder for `.`, else the data itself. */95+const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>96+ module === "."97+ ? `territory.paths(${paths.map(spelled).join(", ")})`98+ : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;99+100+/** An ask's file: the SDK call that states `stated`, as its maintainer writes it. */101+const askFileOf = (stated: StatedAsk): AskFile => {102+ const territory = territoryOf(stated.territory);103+104+ 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+ );117+118+ const args = [...passed, `territory: ${territory}`].toSorted();119+120+ const builders = territory.startsWith("territory.")121+ ? "kinds, territory"122+ : "kinds";123+124+ 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+};136+137+// ------------------------------------------------------------- datekit138+139+export const datekitPeople = {140+ contributor: Handle.make("bram"),141+ decider: Handle.make("ines-v"),142+ zones: Handle.make("okonkwo"),143+} as const;144+145+const 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;155+156+/** One datekit ask: as `policy.json` states it, and the check file it opens with. */157+interface DatekitAsk {158+ readonly stated: StatedAsk;159+ readonly test: AskFile;160+}161+162+/**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+ */168+const 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`);181+182+ 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+ };192+193+ 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+};213+214+const 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+];271+272+const 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+]);411+412+export 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;454+455+// -------------------------------------------------------------- burrow456+457+export const burrowPeople = {458+ decider: Handle.make("okafor"),459+ second: Handle.make("lin-h"),460+} as const;461+462+const PACKAGES = [463+ "kit",464+ "auth",465+ "billing",466+ "catalog",467+ "notify",468+ "search",469+] as const;470+471+const COUNT = "bun scripts/count-callers.ts legacyFetch --json";472+473+const 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+);480+481+const PARENT = "drop-legacy-fetch";482+483+/** One step of the migrate family: moving one package off `legacyFetch`. */484+const 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+});497+498+const CHILDREN = ["auth", "billing"];499+500+const 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+];534+535+const 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+];572+573+const 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+]);662+663+export 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+ */12+import { FrontPage } from "@repo/project/front-page";13+import type { FrontPageFilter } from "@repo/project/front-page";14+import type { ProjectedEvent } from "@repo/project/projection";15+import { creditsFor, Projects } from "@repo/project/projects";16+import type { AskListing } from "@repo/protocol/domain/ask";17+import { ProjectEvent } from "@repo/protocol/domain/event";18+import type {19+ FrontPageEntry,20+ ProjectListing,21+} from "@repo/protocol/domain/front-page";22+import type { ProjectName } from "@repo/protocol/ids";23+import { Array, DateTime, Effect, Layer, Order } from "effect";24+25+import { DevProjected } from "./projection.ts";26+27+/** One open ask on the page, as D1's `front_page` row holds it. */28+interface Row {29+ readonly ask: AskListing;30+ readonly claims: number;31+ readonly openedAt: DateTime.Utc;32+ readonly project: ProjectName;33+}34+35+const keyOf = (project: ProjectName, ask: string) => `${project}/${ask}`;36+37+/** Every project's events in its own order. */38+const inOrder = Order.mapInput(39+ Order.Tuple([Order.String, Order.Number]),40+ ({ event, project }: ProjectedEvent) => [project, event.seq] as const41+);42+43+/** The page's rows with one ask's claim count moved by `change`, if it is on the page. */44+const withClaims = (45+ rows: ReadonlyMap<string, Row>,46+ key: string,47+ change: number48+): ReadonlyMap<string, Row> => {49+ const row = rows.get(key);50+51+ return row === undefined52+ ? rows53+ : new Map(rows).set(key, {54+ ...row,55+ claims: Math.max(row.claims + change, 0),56+ });57+};58+59+/** The page's rows after one project's event, as D1's statements change them. */60+const 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);67+68+ next.delete(keyOf(project, ask));69+70+ 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+ });90+91+const empty: ReadonlyMap<string, Row> = new Map();92+93+/** The page's rows after `events`, and every project they came from. */94+const 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+});101+102+/** Newest first, then by project and ask, as D1's query orders them. */103+const 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+]);108+109+/** A row as the anonymous viewer sees it. */110+const 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+ );117+118+ const blockedBy = row.ask.blockedBy.filter(onPage);119+ const claimed = row.claims > 0;120+121+ 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+ };129+130+const matches =131+ ({ kind, reserved }: FrontPageFilter) =>132+ ({ ask }: Row) =>133+ (kind === undefined || ask.kind === kind) &&134+ (reserved === undefined || ask.reserve === reserved);135+136+/** `FrontPage` over the memory projection's events, and credits from `Projects`. */137+export 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);147+148+ 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+ */13+import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";14+import type { PushSource, TreeEntry } from "@repo/artifacts/repo-host";15+import { Brand } from "@repo/brand";16+import { BlobSha, CommitSha } from "@repo/protocol/ids";17+import type { Handle, RepoName } from "@repo/protocol/ids";18+import { Array, DateTime, Effect, Option, Predicate } from "effect";19+20+/** A tree's files, by path, as text: what the world writes. */21+export type Files = ReadonlyMap<string, string>;22+23+/** A file as a commit holds it: its blob's id, and its text. */24+export interface Held {25+ readonly blob: BlobSha;26+ readonly text: string;27+}28+29+/** A commit's files, by path, as read back. */30+export type Snapshot = ReadonlyMap<string, Held>;31+32+/** The name and email an author or committer line carries. */33+export interface Identity {34+ readonly email: string;35+ readonly name: string;36+}37+38+/** The platform, which commits every landing. */39+export const platformIdentity: Identity = {40+ email: `platform@${Brand.domain}`,41+ name: Brand.name,42+};43+44+/** A person, as the author of their own commits and of their landings. */45+export const personIdentity = (handle: Handle): Identity => ({46+ email: `${handle}@users.${Brand.domain}`,47+ name: handle,48+});49+50+/** A snapshot's text alone. */51+export const textOf = (snapshot: Snapshot): Files =>52+ new Map([...snapshot].map(([path, { text }]) => [path, text]));53+54+/** `files` with `changed` written over them. */55+export const overlay = (56+ files: Files,57+ changed: Iterable<readonly [string, string]>58+): Files => new Map([...files, ...changed]);59+60+// --------------------------------------------------------------- objects61+62+const encoder = new TextEncoder();63+64+const decoder = new TextDecoder();65+66+const concat = (parts: readonly Uint8Array[]) => {67+ const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));68+ let at = 0;69+70+ for (const part of parts) {71+ all.set(part, at);72+ at += part.byteLength;73+ }74+75+ return all;76+};77+78+const hex = (bytes: ArrayBuffer) =>79+ [...new Uint8Array(bytes)]80+ .map((byte) => byte.toString(16).padStart(2, "0"))81+ .join("");82+83+const bytesOfHex = (id: string) =>84+ Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));85+86+/** git's zlib stream, as a loose object holds it. */87+const 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)));95+96+/** An object's header and content, and its id: the SHA-1 of both. */97+const framed = (kind: "blob" | "tree" | "commit", content: Uint8Array) => {98+ const raw = concat([99+ encoder.encode(`${kind} ${content.byteLength}\0`),100+ content,101+ ]);102+103+ return Effect.map(104+ Effect.promise(() => crypto.subtle.digest("SHA-1", raw)),105+ (digest) => ({ id: hex(digest), raw })106+ );107+};108+109+const sortKey = (entry: TreeEntry) =>110+ encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);111+112+// git sorts a tree's entries by name, a subtree's name as if it ended in "/".113+const treeOrder = (one: TreeEntry, other: TreeEntry) => {114+ const left = sortKey(one);115+ const right = sortKey(other);116+117+ for (let at = 0; at < Math.min(left.length, right.length); at += 1) {118+ const diff = (left[at] ?? 0) - (right[at] ?? 0);119+120+ if (diff !== 0) {121+ return diff;122+ }123+ }124+125+ return left.length - right.length;126+};127+128+const 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+ );136+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+ */142+const messageOf = (message: string) =>143+ `${message.replaceAll("\r", "").replace(/^\n+/u, "").replace(/\n+$/u, "")}\n`;144+145+const signature = (who: Identity, at: DateTime.Utc) =>146+ `${who.name} <${who.email}> ${Math.floor(DateTime.toEpochMillis(at) / 1000)} +0000`;147+148+/** A commit to write: its tree, parents, people, time and message. */149+export 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+}157+158+const 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+ );169+170+// ------------------------------------------------------------ the source171+172+const failure = (code: string, path: string) =>173+ Promise.reject(Object.assign(new Error(`${code}: ${path}`), { code }));174+175+const clean = (path: string) =>176+ `/${path177+ .split("/")178+ .filter((part) => part !== "")179+ .join("/")}`;180+181+/** How isomorphic-git asks for a file: as bytes, or as text in "utf8", alone or as `{ encoding }`. */182+type ReadOptions = string | { readonly encoding?: string } | undefined;183+184+const UTF8 = /^utf-?8$/iu;185+186+const wantsText = (options: ReadOptions) =>187+ Predicate.isString(options)188+ ? UTF8.test(options)189+ : UTF8.test(options?.encoding ?? "");190+191+/** A write to the scratch directory through the file system: it only reads. */192+const readOnly = (raw: string) => failure("EROFS", clean(raw));193+194+const 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+});207+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+ */213+const readOnlyFs = (files: ReadonlyMap<string, Uint8Array>) => {214+ const childrenOf = (dir: string) => {215+ const prefix = dir === "/" ? "/" : `${dir}/`;216+217+ return Array.dedupe(218+ [...files.keys()].flatMap((path) =>219+ path.startsWith(prefix)220+ ? [path.slice(prefix.length).split("/")[0] ?? ""]221+ : []222+ )223+ );224+ };225+226+ const stat = (raw: string) => {227+ const path = clean(raw);228+ const file = files.get(path);229+230+ if (file !== undefined) {231+ return Promise.resolve(stats("file", file.byteLength));232+ }233+234+ return childrenOf(path).length > 0235+ ? Promise.resolve(stats("dir", 0))236+ : failure("ENOENT", path);237+ };238+239+ 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);248+249+ if (file === undefined) {250+ return failure(251+ childrenOf(path).length > 0 ? "EISDIR" : "ENOENT",252+ path253+ );254+ }255+256+ 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);263+264+ 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+};277+278+/** A git directory in memory that a push takes objects from, and how to write into it. */279+export 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+}285+286+const GITDIR = "/scratch.git";287+288+/** A fresh scratch git directory: loose, zlib-deflated objects named by their ids. */289+export const scratch: Effect.Effect<Scratch> = Effect.sync(() => {290+ const objects = new Map<string, Uint8Array>();291+292+ 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)}`;296+297+ if (!objects.has(path)) {298+ objects.set(path, yield* deflate(raw));299+ }300+301+ return ObjectId.make(id);302+ });303+304+ const folder = (305+ files: readonly (readonly [string, string])[]306+ ): Effect.Effect<ObjectId> =>307+ Effect.gen(function* () {308+ const blobs = files.filter(([path]) => !path.includes("/"));309+310+ const nested = Array.groupBy(311+ files.filter(([path]) => path.includes("/")),312+ ([path]) => path.slice(0, path.indexOf("/"))313+ );314+315+ 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+ );323+324+ 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+ );336+337+ return yield* write("tree", treeBytes([...blobEntries, ...treeEntries]));338+ });339+340+ 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+});349+350+// ----------------------------------------------------------------- reads351+352+/** One file of a snapshot: its path, its blob's id and its text. */353+const fileOf =354+ (path: string, blob: ObjectId) =>355+ (bytes: Uint8Array): Snapshot =>356+ new Map([357+ [path, { blob: BlobSha.make(blob), text: decoder.decode(bytes) }],358+ ]);359+360+/** Every file under the tree `tree` of `repo`, by path; none when the repo lacks an object. */361+const 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);369+370+ if (Option.isNone(entries)) {371+ return Option.none();372+ }373+374+ const each = yield* Effect.forEach(entries.value, (entry) => {375+ const path = `${prefix}${entry.name}`;376+377+ if (entry.type === "tree") {378+ return snapshotOf(repo, entry.sha, `${path}/`);379+ }380+381+ return host382+ .readBlob(repo, entry.sha)383+ .pipe(Effect.orDie, Effect.map(Option.map(fileOf(path, entry.sha))));384+ });385+386+ return Option.map(387+ Option.all(each),388+ (parts): Snapshot => new Map(parts.flatMap((part) => [...part]))389+ );390+ });391+392+/** `repo`'s files at `commit`; none when the repo or the commit is not there. */393+export const filesAt = (394+ repo: RepoName,395+ commit: CommitSha396+): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>397+ Effect.gen(function* () {398+ const host = yield* RepoHost;399+400+ const found = yield* host401+ .readCommit(repo, commit)402+ .pipe(Effect.orElseSucceed(() => Option.none()));403+404+ 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+ */13+import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";14+import { FrontPage } from "@repo/project/front-page";15+import type { ProjectApi } from "@repo/project/project";16+import { Projects } from "@repo/project/projects";17+import { Contracts, EnvSchemaOf } from "@repo/protocol/contracts";18+import type { AnswerView } from "@repo/protocol/domain/answer";19+import type { ClaimView } from "@repo/protocol/domain/claim";20+import type { Decision, Today } from "@repo/protocol/domain/decision";21+import { sameHandle } from "@repo/protocol/ids";22+import type { ProjectName, RepoName } from "@repo/protocol/ids";23+import { CurrentPrincipal, Principal } from "@repo/protocol/principal";24+import type { Person } from "@repo/protocol/principal";25+import { NotDecider } from "@repo/protocol/refusal";26+import { Array, DateTime, Effect, Number, Option, Order, Stream } from "effect";27+import type { Layer } from "effect";28+import { HttpServerRequest } from "effect/http";29+import type { Rpc, RpcGroup } from "effect/rpc";30+31+/** How many events `watch` reads from its project at a time. */32+const EVENT_PAGE = 100;33+34+/** The caller, as the `Authenticated` server side named them. */35+const caller = Effect.service(CurrentPrincipal);36+37+/**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+ */42+const 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+);49+50+/** Where the caller reached the world: the request's origin. */51+const 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+);61+62+/** A repo's git URL at the origin the caller came through. */63+const remoteOf = (repo: RepoName | ProjectName) =>64+ Effect.map(gateway, (origin) => `${origin}/${repo}.git`);65+66+/** A claim, with its fork's URL at the caller's origin. */67+const atGateway = (claim: ClaimView) =>68+ Effect.map(remoteOf(claim.fork), (remote): ClaimView => ({69+ ...claim,70+ remote,71+ }));72+73+/** The caller's claims and answers, each claim at the caller's origin, under their handle. */74+const 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+ }));86+87+/** Decisions across projects: soonest to expire first, then oldest, then by project and id. */88+const 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+]);94+95+/**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+ */100+const 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));106+107+ 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+};129+130+/** Every contract over the dev world. A missing contract is a type error here. */131+export 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;140+141+ /** `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);146+147+ /** `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();153+154+ 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+ );165+166+ return Array.getSomes(each);167+ });168+169+ 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));174+175+ 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));208+209+ 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;216+217+ // 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+ );226+227+ const made = yield* api.initProject(who, input);228+229+ 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;270+271+ if (project !== undefined) {272+ return yield* statusAtGateway(273+ who,274+ yield* on(project, (api) => api.status(who))275+ );276+ }277+278+ const each = yield* everywhere((api) =>279+ Effect.asSome(api.status(who))280+ );281+282+ 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;294+295+ if (project !== undefined) {296+ return yield* on(project, (api) => api.today(who));297+ }298+299+ // 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+ );306+307+ 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+ */13+import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";14+import { Brand } from "@repo/brand";15+import { composeRef, Lander, landedRef, Rebuild } from "@repo/project/lander";16+import type { Change, LandJob } from "@repo/project/lander";17+import type { CommitSha, RepoName } from "@repo/protocol/ids";18+import { LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";19+import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";20+import { sdkVersion } from "@repo/rules/rules-evaluator";21+import { Array, DateTime, Effect, Layer, Option, Ref } from "effect";22+23+import {24+ filesAt,25+ overlay,26+ personIdentity,27+ platformIdentity,28+ scratch,29+ textOf,30+} from "./git.ts";31+import type { Files, Snapshot } from "./git.ts";32+33+const mainRef = RefName.make("refs/heads/main");34+35+const blocked = () => new VerifierBlocked({});36+37+/** A commit's files, or `VerifierBlocked` when the repo doesn't hold it. */38+const read = (repo: RepoName, commit: CommitSha) =>39+ filesAt(repo, commit).pipe(40+ Effect.flatMap(Effect.fromOption),41+ Effect.mapError(blocked)42+ );43+44+/** What `head` changed against `base`, path by path, in path order. */45+const 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);52+53+ if (before === undefined) {54+ return after === undefined55+ ? []56+ : [{ after: after.blob, path: at, status: "added" }];57+ }58+59+ if (after === undefined) {60+ return [{ before: before.blob, path: at, status: "deleted" }];61+ }62+63+ return before.blob === after.blob64+ ? []65+ : [66+ {67+ after: after.blob,68+ before: before.blob,69+ path: at,70+ status: "modified",71+ },72+ ];73+ });74+75+/** An answer's head merged onto main: main's files with what the answer changed laid over them. */76+const 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);88+89+ // 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+ );96+97+ if (Array.isReadonlyArrayNonEmpty(conflicts)) {98+ return yield* new StaleBase({99+ base: input.base,100+ conflicts,101+ main: input.main,102+ });103+ }104+105+ // Main's files, with each path the answer changed as the answer left it.106+ const files = new Map(textOf(main));107+108+ for (const { path } of changes) {109+ const text = head.get(path)?.text;110+111+ if (text === undefined) {112+ files.delete(path);113+ } else {114+ files.set(path, text);115+ }116+ }117+118+ return { changes, files: files satisfies Files };119+ });120+121+/** The files a landing's tree is rebuilt from. */122+const 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+ });138+139+/** The commit an answer's landing was made on: its base; otherwise main. */140+const baseOf = (job: LandJob) =>141+ Rebuild.$is("Merge")(job.rebuild) ? job.rebuild.base : job.main;142+143+/** The Lander over the memory repo host, landing at the world's clock. */144+export 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);149+150+ // A request landed before: its commit, so a second land returns it.151+ const landedBy = yield* Ref.make<ReadonlyMap<string, LandedSha>>(new Map());152+153+ 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+ );158+159+ const land = (job: LandJob) =>160+ Effect.gen(function* () {161+ const before = (yield* Ref.get(landedBy)).get(job.requestId);162+163+ if (before !== undefined) {164+ return { pending: [], sha: before };165+ }166+167+ const tip = yield* tipOf(job.repo, mainRef);168+169+ 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+ }176+177+ const into = yield* scratch;178+ const tree = yield* into.tree(yield* rebuilt(job));179+180+ if (TreeSha.make(tree) !== job.tree) {181+ return yield* blocked();182+ }183+184+ 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+ });192+193+ // 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+ );204+205+ if (outcome === undefined || !RefOutcome.$is("Updated")(outcome)) {206+ return yield* new StaleBase({207+ base: baseOf(job),208+ conflicts: [],209+ main: job.main,210+ });211+ }212+213+ const sha = LandedSha.make(commit);214+215+ yield* Ref.update(landedBy, (all) =>216+ new Map(all).set(job.requestId, sha)217+ );218+219+ // The mirror follows main in a push of its own (ADR 0005).220+ const mirror = yield* tipOf(job.repo, landedRef);221+222+ yield* host223+ .push(job.repo, into.source, [224+ { from: mirror, ref: landedRef, to: commit },225+ ])226+ .pipe(Effect.ignore);227+228+ return { pending: [], sha };229+ });230+231+ 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;249+250+ const tree = yield* into.tree(251+ overlay(252+ textOf(onMain),253+ files.map(({ content, path }) => [path, content] as const)254+ )255+ );256+257+ 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+ });265+266+ const ref = composeRef(TreeSha.make(tree));267+ const existing = yield* tipOf(repo, ref);268+269+ if (!Option.contains(existing, commit)) {270+ yield* host271+ .push(repo, into.source, [{ from: existing, ref, to: commit }])272+ .pipe(Effect.mapError(blocked));273+ }274+275+ 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;284+285+ return { changes, tree: TreeSha.make(yield* into.tree(files)) };286+ })287+ ),288+ });289+ })290+);added:apps/web/src/dev/projection.ts+57 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657/** * Where the dev world's projects send their events for the read models: * the `Projection` port in memory, keyed as the D1 projection keys its rows, * by project and event number, so one world holds every project's events * and a row delivered twice is kept once. (`@repo/project`'s own memory * projection keys rows by their outbox id, `projected:<seq>`, which two * projects share: it suits a test of one project, not a world of two.) */import { Projection, ProjectedEvent } from "@repo/project/projection";import { Context, Effect, Layer, Ref, Schema } from "effect";
const decodeProjected = Schema.decodeUnknownEffect( Schema.toCodecJson(ProjectedEvent));
/** Every event the world's projects have projected, in the order they first arrived. */export class DevProjected extends Context.Service< DevProjected, { readonly events: Effect.Effect<readonly ProjectedEvent[]> }>()("web/dev/DevProjected") {}
/** A fresh, empty projection, and the reading of it. */export const DevProjection: Layer.Layer<Projection | DevProjected> = Layer.effectContext( Effect.gen(function* () { const taken = yield* Ref.make<ReadonlyMap<string, ProjectedEvent>>( new Map() );
const projection = Projection.of({ apply: (rows) => Effect.flatMap( Effect.forEach(rows, (row) => Effect.orDie(decodeProjected(row.body)) ), (events) => Ref.update(taken, (kept) => { const next = new Map(kept);
for (const projected of events) { const key = `${projected.project}:${projected.event.seq}`;
next.set(key, next.get(key) ?? projected); }
return next; }) ), });
return Context.make(Projection, projection).pipe( Context.add(DevProjected, { events: Effect.map(Ref.get(taken), (kept) => [...kept.values()]), }) ); }) );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+ */22+import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";23+import type { ProjectApi } from "@repo/project/project";24+import { Projects } from "@repo/project/projects";25+import { DecisionSubject } from "@repo/protocol/domain/decision";26+import type { Decision } from "@repo/protocol/domain/decision";27+import { AskId, Handle, RepoName, RequestId } from "@repo/protocol/ids";28+import type { CommitSha, ProjectName, ProposalId } from "@repo/protocol/ids";29+import { Anonymous, Person } from "@repo/protocol/principal";30+import { Array, DateTime, Effect, Option } from "effect";31+32+import { DevClock, devMinute } from "./clock.ts";33+import { burrow, burrowPeople, datekit, datekitPeople } from "./examples.ts";34+import type { Opening } from "./examples.ts";35+import { filesAt, overlay, personIdentity, scratch, textOf } from "./git.ts";36+import type { Files } from "./git.ts";37+38+const mainRef = RefName.make("refs/heads/main");39+40+/** People who propose and flag in datekit; nobody vouched for them. */41+const visitors = {42+ flagger: Handle.make("sefa"),43+ proposer: Handle.make("tove"),44+ regular: Handle.make("wren"),45+} as const;46+47+/** Everyone in the seed: the people a dev token may sign in as. */48+export 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+];58+59+const as = (handle: Handle) => Person.make({ handle });60+61+/** A commit of `files` on `parent` (or a first commit), by `author`, at the world's time. */62+const 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);71+72+ 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+ });80+81+ return { commit, source: into.source };82+ });83+84+/** A commit pushed to `repo`'s main with a compare-and-swap from `parent`. */85+const pushed = (repo: RepoName, input: Parameters<typeof commitOf>[0]) =>86+ Effect.gen(function* () {87+ const host = yield* RepoHost;88+ const { commit, source } = yield* commitOf(input);89+90+ const outcomes = yield* host.push(repo, source, [91+ { from: input.parent, ref: mainRef, to: commit },92+ ]);93+94+ if (!outcomes.every(RefOutcome.$is("Updated"))) {95+ return yield* Effect.die(`${repo}'s main moved under the seed`);96+ }97+98+ return commit;99+ });100+101+/** The files of `repo` at `commit`, which the seed itself pushed. */102+const filesOf = (repo: RepoName, commit: CommitSha) =>103+ Effect.flatMap(filesAt(repo, commit), Effect.fromOption);104+105+/** Moves the world's clock to `minute` minutes after its start. */106+const at = (minute: number) =>107+ Effect.flatMap(Effect.service(DevClock), (clock) =>108+ clock.set(devMinute(minute))109+ );110+111+/**112+ * A project made and adopted: its initializer creates it, pushes its first113+ * commit, and the gateway reports the push.114+ */115+const started = (116+ project: ProjectName,117+ initializer: Handle,118+ files: Files,119+ minute: number120+) =>121+ Effect.gen(function* () {122+ const projects = yield* Projects;123+124+ yield* at(minute);125+126+ const api = yield* projects.create(project);127+128+ yield* api.initProject(as(initializer), {});129+ yield* at(minute + 1);130+131+ const first = yield* pushed(RepoName.make(project), {132+ author: initializer,133+ files,134+ message: "First commit",135+ parent: Option.none(),136+ });137+138+ yield* api.recordFirstPush(as(initializer), first);139+140+ return api;141+ });142+143+/** Each ask opened by `decider` from its files, a minute apart from `minute`. */144+const 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+ );159+160+/**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+ */165+const 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));176+177+ const claim = yield* Effect.fromOption(178+ Array.findFirst(claims, ({ ask }) => ask === input.ask)179+ );180+181+ const base = yield* filesOf(claim.fork, claim.base);182+183+ 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+ });189+190+ 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+ });198+199+ if (Array.isReadonlyArrayNonEmpty(refusals)) {200+ return yield* Effect.die(refusals);201+ }202+203+ 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+ });210+211+/** The decision that puts proposal `proposal` to `decider`. */212+const 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+ );223+224+/** Proposals from a regular that datekit's decider declines, each on its own minute. */225+const DECLINED = [226+ "parseISO accepts two-digit years.",227+ "datekit wraps the Temporal API.",228+];229+230+/** datekit: four asks opened, one answered and landed, one claimed, decisions waiting. */231+const seedDatekit = Effect.gen(function* () {232+ const { contributor, decider } = datekitPeople;233+ const api = yield* started(datekit.project, decider, datekit.files, 0);234+235+ yield* opened(api, decider, datekit.asks, 2);236+237+ yield* at(6);238+ yield* api.claim(as(contributor), datekit.answer.ask);239+240+ yield* at(7);241+ yield* answered(api, contributor, datekit.answer);242+243+ yield* at(8);244+ yield* api.claim(as(contributor), AskId.make("parse-iso-week"));245+246+ yield* at(9);247+ yield* api.proposeAsk(as(visitors.proposer), {248+ want: 'format(date, "Qo") prints the quarter as an ordinal.',249+ });250+251+ 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+ });256+257+ yield* Effect.forEach(258+ DECLINED,259+ (want, index) =>260+ Effect.gen(function* () {261+ yield* at(11 + index * 2);262+263+ const { proposal } = yield* api.proposeAsk(as(visitors.regular), {264+ want,265+ });266+267+ yield* at(12 + index * 2);268+269+ const decision = yield* decisionOn(api, decider, proposal.id);270+271+ 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+ );279+280+ return api;281+});282+283+/** burrow: the migrate family opened, its delete step waiting on the other two. */284+const seedBurrow = Effect.flatMap(285+ started(burrow.project, burrowPeople.decider, burrow.files, 15),286+ (api) => opened(api, burrowPeople.decider, burrow.asks, 17)287+);288+289+/**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+ */294+const strayPush = (api: ProjectApi) =>295+ Effect.gen(function* () {296+ const host = yield* RepoHost;297+ const repo = RepoName.make(datekit.project);298+299+ yield* at(21);300+301+ const tip = yield* Effect.fromOption(302+ Option.fromNullishOr((yield* host.refs(repo)).get(mainRef))303+ );304+305+ 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+ });311+312+ 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+ });321+322+/**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+ */326+export const seedDev: Effect.Effect<327+ void,328+ never,329+ Projects | RepoHost | DevClock330+> = Effect.gen(function* () {331+ const datekitApi = yield* seedDatekit;332+333+ yield* seedBurrow;334+ yield* strayPush(datekitApi);335+}).pipe(Effect.orDie);added:apps/web/src/dev/server.ts+40 added
12345678910111213141516171819202122232425262728293031323334353637383940/** * The dev world as a fetch handler: `POST /rpc` is an `RpcServer` over * `Contracts` with the dev handlers, protocol's `Authenticated` server side * over dev tokens (`sessions.ts`) and JSON, as the platform's `/rpc` serves * it, over a fresh world the seed has brought to its state. `backend.ts` * makes the one an isolate serves; a test makes its own. */import { Contracts } from "@repo/protocol/contracts";import { Layer } from "effect";import { HttpRouter } from "effect/http";import { RpcSerialization, RpcServer } from "effect/rpc";
import { devHandlers } from "./handlers.ts";import { seedDev } from "./seed.ts";import { devSessions } from "./sessions.ts";import { devWorld } from "./world.ts";
/** A fresh world, seeded. */const seededWorld = Layer.effectDiscard(seedDev).pipe( Layer.provideMerge(devWorld));
/** * The contracts at `/rpc` over a fresh, seeded world. `toWebHandler` builds * its layer as soon as it is called, so the world is made and seeded from * that moment, and a request that arrives before the seed is done waits for * it. `dispose` ends the world. */export const devServer = () => HttpRouter.toWebHandler( RpcServer.layerHttp({ group: Contracts, path: "/rpc", protocol: "http", }).pipe( Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson]), Layer.provide(seededWorld) ), { disableLogger: true } );added:apps/web/src/dev/sessions.ts+39 added
123456789101112131415161718192021222324252627282930313233343536373839/** * Who calls the dev world: protocol's own `Authenticated` server side * (`authenticated`), the rule the platform serves by, over a table of dev * tokens. `dev-<handle>` names that person of the seed's fictional people; * any other credential names nobody, so the call is `Unauthenticated`; a * call with none is anyone, for a `public` contract only. The tokens are * literal and exist only under the `development` condition, which the * production build never resolves (505). * * The world reads the credential from the call's headers, which the RPC * server fills from the HTTP request's own, so a browser's `Authorization` * reaches it as it reaches the platform. (The platform also refuses one an * RPC message adds to its own headers; the dev world does not check.) */import { authenticated } from "@repo/protocol/authenticate";import type { Handle } from "@repo/protocol/ids";import { Person } from "@repo/protocol/principal";import type { Authenticated } from "@repo/protocol/principal";import { Effect, Option } from "effect";import type { Layer } from "effect";
import { devPeople } from "./seed.ts";
/** The dev token that signs in as `handle`. */export const devToken = (handle: Handle) => `dev-${handle}`;
const tokens: ReadonlyMap<string, Handle> = new Map( devPeople.map((handle) => [devToken(handle), handle]));
/** The person a dev token names, if it names one of the seed's people. */const personOf = (token: string) => Option.map(Option.fromNullishOr(tokens.get(token)), (handle) => Person.make({ handle }) );
export const devSessions: Layer.Layer<Authenticated> = authenticated((token) => Effect.succeed(personOf(token)));added:apps/web/src/dev/world.ts+55 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455/** * The dev world: the project service over memory adapters, every project * in one isolate, as `@repo/project`'s own scenario test runs it. Repos live * in the memory repo host and move only by real git objects (`git.ts`); the * Lander does the trusted Lander's work over them (`lander.ts`); the * Checker is scripted (`checker.ts`); rules are read from each project's * committed `policy.json` (`/json`); answers run in process; alarms are * recorded and never fire; the front page is folded from the projection's * rows (`front-page.ts`); lane logs are kept in memory. One clock, set by * the seed, is the world's time (`clock.ts`). */import type { RepoHost } from "@repo/artifacts/repo-host";import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";import type { EvidenceStore } from "@repo/checks/evidence-store";import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";import { AlarmsMemory } from "@repo/project/alarms/memory";import { AnswerRunsInline } from "@repo/project/answer-runs/inline";import type { FrontPage } from "@repo/project/front-page";import { FinishersFromChecks } from "@repo/project/project";import type { Projects } from "@repo/project/projects";import { ProjectsMemory } from "@repo/project/projects/memory";import { RulesEvaluatorJson } from "@repo/rules/rules-evaluator/json";import { Layer } from "effect";
import { DevChecker } from "./checker.ts";import { devClockAt, devStart } from "./clock.ts";import type { DevClock } from "./clock.ts";import { DevFrontPage } from "./front-page.ts";import { DevLander } from "./lander.ts";import { DevProjection } from "./projection.ts";
/** Every port a project needs but its store, shared by every project in the world. */const ports = Layer.mergeAll( AlarmsMemory, AnswerRunsInline, DevProjection, RulesEvaluatorJson.pipe(Layer.provide(FinishersFromChecks))).pipe( Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)), Layer.provideMerge(RepoHostMemory));
/** * A fresh, empty world: its projects, the front page over them, the lane * logs, the repo host the people's git pushes to, and its clock at * `devStart`. Built twice, it is two worlds. */export const devWorld: Layer.Layer< Projects | FrontPage | EvidenceStore | RepoHost | DevClock> = Layer.mergeAll(DevFrontPage, EvidenceStoreMemory).pipe( Layer.provideMerge(ProjectsMemory), Layer.provideMerge(ports), Layer.provideMerge(devClockAt(devStart)), Layer.fresh);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+ */10+import { describe, expect, it } from "@effect/vitest";11+import { DecisionSubject } from "@repo/protocol/domain/decision";12+import { AskId, ProjectName } from "@repo/protocol/ids";13+import { Unauthenticated } from "@repo/protocol/principal";14+import { UnknownAsk } from "@repo/protocol/refusal";15+import { env } from "cloudflare:workers";16+import { Array, DateTime, Effect, Exit, Layer, Option, Schema } from "effect";17+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";18+import { Atom, AtomRegistry, Reactivity } from "effect/reactivity";19+import type { AsyncResult } from "effect/reactivity";20+import { RpcClient, RpcSerialization } from "effect/rpc";21+22+import { backend } from "#backend";23+24+import { keys } from "../src/client/keys.ts";25+import { ContractsClient, webContracts } from "../src/surfaces.ts";26+27+const WEB_URL = "http://localhost:3000";28+29+const datekit = ProjectName.make("datekit");30+31+/** The decider of datekit in the dev world, and the token that signs them in. */32+const DECIDER = "dev-ines-v";33+34+/**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+ */39+const 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+ );62+63+/** A registry whose `ContractsClient` is `browser(token)`'s. */64+const registryAs = (token?: string) =>65+ AtomRegistry.make({66+ initialValues: [67+ Atom.initialValue(ContractsClient.runtime.layer, browser(token)),68+ ],69+ });70+71+/** An atom's value once it has one, past any refetch under way. */72+const 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+ );79+80+const todayAtom = ContractsClient.query(81+ "today",82+ {},83+ { reactivityKeys: keys.today() }84+);85+86+describe("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();92+93+ const page = yield* settled(94+ registry,95+ ContractsClient.query(96+ "frontPage",97+ {},98+ { reactivityKeys: keys.front() }99+ )100+ );101+102+ expect(Exit.isSuccess(page)).toBeTruthy();103+104+ const entries = Exit.isSuccess(page) ? page.value.entries : [];105+106+ 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+ ]);122+123+ const reserved = entries.find(({ ask }) => ask.reserve !== undefined);124+125+ expect(reserved?.ask.ask).toBe("format-ordinal");126+ expect(reserved?.ask.reserve).toBe("newcomers");127+ expect(reserved?.ask.claimed).toBeFalsy();128+ })129+ );130+131+ 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();136+137+ const listed = yield* settled(138+ registry,139+ ContractsClient.query(140+ "listAsks",141+ { project: datekit },142+ { reactivityKeys: keys.project(datekit) }143+ )144+ );145+146+ 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+ ]);155+156+ const unknown = AskId.make("no-such-ask");157+158+ const shown = yield* settled(159+ registry,160+ ContractsClient.query(161+ "showAsk",162+ { ask: unknown, project: datekit },163+ { reactivityKeys: keys.ask(datekit, unknown) }164+ )165+ );166+167+ const error = Exit.isFailure(shown)168+ ? Option.getOrUndefined(Exit.findErrorOption(shown))169+ : undefined;170+171+ expect(Schema.is(UnknownAsk)(error)).toBeTruthy();172+ })173+ );174+175+ it.live("keeps Today from an anonymous browser", () =>176+ Effect.gen(function* () {177+ const anonymous = yield* settled(registryAs(), todayAtom);178+179+ const refused = Exit.isFailure(anonymous)180+ ? Option.getOrUndefined(Exit.findErrorOption(anonymous))181+ : undefined;182+183+ expect(Schema.is(Unauthenticated)(refused)).toBeTruthy();184+ })185+ );186+187+ it.live("shows the decider their Today, with the seed's decisions", () =>188+ Effect.gen(function* () {189+ const today = yield* settled(registryAs(DECIDER), todayAtom);190+191+ 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+ );216+217+ 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);224+225+ const proposal = Exit.isSuccess(before)226+ ? before.value.decisions.find(({ subject }) =>227+ DecisionSubject.guards.OpenProposal(subject)228+ )229+ : undefined;230+231+ expect(proposal).toBeDefined();232+233+ if (proposal === undefined) {234+ return;235+ }236+237+ const decide = ContractsClient.mutation("decide");238+239+ 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+ });247+248+ const decided = yield* settled(registry, decide);249+250+ const taken = Exit.isSuccess(decided)251+ ? decided.value.decision.decided252+ : undefined;253+254+ 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");259+260+ const after = yield* settled(registry, todayAtom);261+262+ 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);268+269+ 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+ */7+import { describe, expect, it } from "@effect/vitest";8+import { Client, Contracts } from "@repo/protocol/contracts";9+import { ProjectEvent } from "@repo/protocol/domain/event";10+import { Handle, ProjectName } from "@repo/protocol/ids";11+import {12+ Context,13+ DateTime,14+ Duration,15+ Effect,16+ Equal,17+ Layer,18+ Stream,19+} from "effect";20+import type { Scope } from "effect";21+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";22+import { RpcClient, RpcSerialization } from "effect/rpc";23+24+import { devStart } from "../src/dev/clock.ts";25+import { devServer } from "../src/dev/server.ts";26+import { devToken } from "../src/dev/sessions.ts";27+28+const PROJECTS = [ProjectName.make("burrow"), ProjectName.make("datekit")];29+30+const decider = devToken(Handle.make("ines-v"));31+32+const contributor = devToken(Handle.make("bram"));33+34+/**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+ */38+const 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();46+47+ yield* Effect.addFinalizer(() => Effect.promise(dispose));48+49+ 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+ );68+69+ return yield* read(as);70+ })71+ );72+73+/** The client a layer from `as(token)` makes, for as long as the world lives. */74+const clientOf = (layer: Layer.Layer<Client>) =>75+ Effect.map(Layer.build(layer), Context.get(Client));76+77+/** The front page and the project list, as anyone reads them. */78+const 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({});83+84+ return { entries, projects };85+ })86+);87+88+/** Every instant a reader of the seeded world can see. */89+const 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));94+95+ const events = yield* Effect.forEach(PROJECTS, (project) =>96+ Stream.runCollect(anyone.watch({ project }))97+ );98+99+ const today = yield* ines.today({});100+ const { claims } = yield* bram.status({});101+102+ 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+);124+125+/** datekit's landed answer, as Today samples it and as `landing` reads it. */126+const 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;132+133+ if (sampled === undefined) {134+ return yield* Effect.die("datekit has no landed answer");135+ }136+137+ const { landing } = yield* anyone.landing({138+ project: sampled.project,139+ sha: sampled.sha,140+ });141+142+ return { landing, sampled };143+ })144+);145+146+describe("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;151+152+ expect(first.entries).toHaveLength(7);153+ expect(first.projects.map(({ project }) => project)).toStrictEqual(154+ PROJECTS155+ );156+ expect(Equal.equals(first, second)).toBeTruthy();157+ })158+ );159+160+ 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));164+165+ expect(seen.length).toBeGreaterThan(20);166+167+ for (const instant of seen) {168+ const since = Duration.toMillis(DateTime.distance(devStart, instant));169+170+ expect(since).toBeGreaterThanOrEqual(0);171+ expect(since % minute).toBe(0);172+ }173+ })174+ );175+176+ it.live("lands bram's answer to datekit with its credit trailers", () =>177+ Effect.gen(function* () {178+ const { landing, sampled } = yield* landedAnswer;179+180+ 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+});