Skip to content
Myr

Merge build/514-projection-d1-projects-credits

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

authored by oscabriel · committed by oscabriel · parents f736a1e, 7e05025 · Browse files · 8 files+1044 added−77 removed
This commit

State

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

Diff stats

8 files+1044 added−77 removed

  • tests:+807 added−40 removed
  • other:+237 added−37 removed

8 files+1044 added−77 removed

added:apps/platform/migrations/0004_projects_credits.sql+35 added
1-- The project list and every person's credits, projected from each2-- project's outbox by packages/project/src/projection-d1 beside the front3-- page (its tables.ts holds this text). The projection is the only writer.45-- One row per project the projection has heard from: its posture, how many6-- asks it has open, and when the platform last landed on its main (absent7-- before its first landing).8CREATE TABLE projects (9 project TEXT PRIMARY KEY,10 posture TEXT NOT NULL,11 open_asks INTEGER NOT NULL,12 landed_at TEXT13);1415-- How many landings credit a person in one role, in one area of one16-- project: a count by role and area, never a score. `handle_key` is the17-- handle lowercased, the rule protocol's `sameHandle` compares by. The18-- primary key's index serves the lookup by person.19CREATE TABLE credits (20 handle_key TEXT NOT NULL,21 project TEXT NOT NULL,22 area TEXT NOT NULL,23 role TEXT NOT NULL,24 count INTEGER NOT NULL,25 PRIMARY KEY (handle_key, project, area, role)26);2728-- The projects 0001's tables already know of, each with its open asks, so29-- the list stays whole across this migration. On a fresh database it adds30-- nothing.31INSERT INTO projects (project, posture, open_asks, landed_at)32SELECT cursor.project, 'open',33 (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),34 NULL35FROM cursor;
added:apps/platform/test/front-page.test.ts+303 added
1/**2 * The project list and a person's credits as the platform serves them, over3 * a Node platform world: the platform's fetch handler composed as the4 * Worker composes it (`platformOn`), on the ports `workerPorts` gives it,5 * each a Node adapter. The front page and its projection are the D16 * cartridge (`FrontPageD1`, `ProjectionD1`) over sqlite-node with the7 * platform's D1 migrations applied from their files; each project is a8 * project service in memory (`ProjectsMemory`) whose outbox feeds that9 * projection; the Lander is W2's `/isogit` over `RepoHostMemory`; and the10 * Checker fails every lane on a commit of main (an ask's check, red first)11 * and passes every lane on an answer's merged tree. The world's `Projects`12 * counts every call, so a test shows which reads never reach a project.13 */14import { NodeServices } from "@effect/platform-node";15import { SqliteClient } from "@effect/sql-sqlite-node";16import { describe, expect, it } from "@effect/vitest";17import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";18import { CheckAt, CheckRunner } from "@repo/checks/check-runner";19import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";20import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";21import { AlarmsMemory } from "@repo/project/alarms/memory";22import { AnswerRunsInline } from "@repo/project/answer-runs/inline";23import { Lander } from "@repo/project/lander";24import { LanderIsogit } from "@repo/project/lander/isogit";25import { FinishersFromChecks } from "@repo/project/project";26import { FrontPageD1 } from "@repo/project/projection-d1/front-page";27import { ProjectionD1 } from "@repo/project/projection-d1/projection";28import { Projects } from "@repo/project/projects";29import { ProjectsMemory } from "@repo/project/projects/memory";30import type { Client } from "@repo/protocol/contracts";31import type { Policy } from "@repo/protocol/domain/policy";32import {33 AskId,34 Handle,35 LandedSha,36 RepoPath,37 RequestId,38} from "@repo/protocol/ids";39import { Person } from "@repo/protocol/principal";40import { Finishers } from "@repo/rules/finish";41import { RulesEvaluator } from "@repo/rules/rules-evaluator";42import { advanceTo, at } from "@repo/testkit/clock";43import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";44import type { Scope } from "effect";45import { Array, Context, Effect, FileSystem, Layer, Order, Path } from "effect";46import { SqlClient } from "effect/sql/SqlClient";4748import { WorkerFetch } from "../src/adapters/fetch.ts";49import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";50import { decodeEnv, platformOn } from "../src/platform.ts";51import { serve } from "../src/surfaces.ts";52import { fakeEnv } from "./fake-env.ts";53import { seeded } from "./handlers.fixtures.ts";54import { rpcClient } from "./harness.ts";5556/** datekit: alice decides and asks; bob is vouched for. */57const datekit = aProject({ people: ["bob"] }).pipe(58 withVouches(["bob"]),59 withAsk({ id: "parse-iso", territory: "packages/parser" }),60 withAsk({ id: "trim-input", territory: "packages/trim" })61);6263const { project } = datekit;6465const parseIso = AskId.make("parse-iso");6667const bob = Handle.make("bob");6869const alice = Handle.make("alice");7071const noon = "2026-10-07T12:00:00Z";7273/**74 * The platform's D1 database: every migration in its own folder, in75 * file-name order as `wrangler d1 migrations apply` runs them, statement by76 * statement. Comment lines go before the split: a comment may hold a `;`77 * (`0002_accounts.sql`'s does).78 */79const migrated = Layer.effectDiscard(80 Effect.gen(function* () {81 const fs = yield* FileSystem.FileSystem;82 const path = yield* Path.Path;83 const sql = yield* SqlClient;8485 const folder = yield* path.fromFileUrl(86 new URL("../migrations", import.meta.url)87 );8889 const files = Array.sort(90 (yield* fs.readDirectory(folder)).filter((file) => file.endsWith(".sql")),91 Order.String92 );9394 for (const file of files) {95 const text = yield* fs.readFileString(path.join(folder, file));9697 const code = text98 .split("\n")99 .filter((line) => !line.trimStart().startsWith("--"))100 .join("\n");101102 for (const statement of code.split(";")) {103 if (statement.trim().length > 0) {104 yield* sql.unsafe(statement);105 }106 }107 }108 })109).pipe(110 Layer.provide(NodeServices.layer),111 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),112 Layer.orDie113);114115/**116 * An ask's check fails on a commit of main, every time the same way, and117 * every lane passes on an answer's merged tree.118 */119const redOnMainGreenOnAnswers = Layer.succeed(120 CheckRunner,121 CheckRunner.of({122 run: ({ at: where, lanes }) => {123 const passed = CheckAt.guards.Tree(where);124125 return Effect.succeed({126 durationMs: lanes.length,127 evidence: passed128 ? []129 : lanes.map(({ lane }) => ({ lane, signature: `${lane}: red` })),130 heldBack: [],131 lanes: lanes.map(({ command, lane }) => ({132 command,133 durationMs: 1,134 lane,135 result: passed ? ("passed" as const) : ("failed" as const),136 })),137 });138 },139 })140);141142/** At any commit, datekit's policy, holding the asks whose files the commit has. */143const rules = Layer.effect(144 RulesEvaluator,145 Effect.gen(function* () {146 const finishers = yield* Finishers;147 const { policy } = datekit;148149 return RulesEvaluator.of({150 call: () => Effect.succeed(false),151 evaluate: ({ at: landed, facts, modules }) =>152 Effect.succeed({153 ...policy,154 asks: policy.asks.filter(({ file }) => file in modules.modules),155 at: landed,156 judge: finishers.judgeClosure(policy.run, facts.ci),157 } satisfies Policy),158 });159 })160).pipe(Layer.provide(FinishersFromChecks));161162/** The world a front-page test drives. */163interface FrontPageWorld {164 /** Every call the platform made to a project through `Projects`, in order. */165 readonly calls: Effect.Effect<readonly string[]>;166 /** Forgets the calls made so far. */167 readonly forget: Effect.Effect<void>;168 /** A client of the contracts over HTTP at `/rpc`, as anyone. */169 readonly anyone: Client["Service"];170 /** bob's answer to `parse-iso` landed, as his claim, push and submission make it. */171 readonly landAnswer: Effect.Effect<void>;172}173174const frontPageWorld: Effect.Effect<FrontPageWorld, never, Scope.Scope> =175 Effect.gen(function* () {176 // Every port but `Projects`, built once: the Worker's and each project's.177 const base = yield* Layer.build(178 Layer.mergeAll(179 AlarmsMemory,180 AnswerRunsInline,181 EvidenceStoreMemory,182 FrontPageD1,183 MemoryRateLimits(WorkerCaps),184 ProjectionD1,185 rules,186 UpstreamRepoHost187 ).pipe(188 Layer.provideMerge(migrated),189 Layer.provideMerge(LanderIsogit),190 Layer.provideMerge(redOnMainGreenOnAnswers),191 Layer.provideMerge(RepoHostMemory),192 Layer.provideMerge(WorkerFetch)193 )194 );195196 const found = Context.get(197 yield* Layer.build(198 ProjectsMemory.pipe(Layer.provide(Layer.succeedContext(base)))199 ),200 Projects201 );202203 const calls: string[] = [];204205 const counted = Projects.of({206 create: (name) =>207 Effect.suspend(() => {208 calls.push(`create ${name}`);209210 return found.create(name);211 }),212 get: (name) =>213 Effect.suspend(() => {214 calls.push(`get ${name}`);215216 return found.get(name);217 }),218 });219220 const ports = Context.add(base, Projects, counted);221 const config = yield* Effect.orDie(decodeEnv(fakeEnv()));222223 const { dispose, handler } = serve(224 platformOn(config, Layer.succeedContext(ports))225 );226227 yield* Effect.addFinalizer(() => Effect.promise(dispose));228229 const landAnswer = Effect.gen(function* () {230 const answerer = Person.make({ handle: bob });231 const api = yield* counted.get(project);232 const { claim } = yield* api.claim(answerer, parseIso);233 const main = LandedSha.make(claim.base);234235 const { commit } = yield* Context.get(base, Lander).compose({236 files: Array.make({237 content: "export const parse = (s) => ({ year: 2026 });\n",238 path: RepoPath.make("packages/parser/src/parse.ts"),239 }),240 main,241 repo: claim.fork,242 });243244 yield* api.submitAnswer(answerer, {245 ask: parseIso,246 base: main,247 head: commit,248 requestId: RequestId.make("req-parse-iso1"),249 });250 }).pipe(Effect.orDie);251252 yield* seeded(datekit).pipe(Effect.provideContext(ports));253254 return {255 anyone: yield* rpcClient(handler),256 calls: Effect.sync(() => [...calls]),257 forget: Effect.sync(() => {258 calls.length = 0;259 }),260 landAnswer,261 };262 });263264describe("the project list and credits over the platform's /rpc", () => {265 it.effect(266 "after a landing, lists the project and its people's credits from D1 without calling a project",267 () =>268 Effect.gen(function* () {269 yield* advanceTo(noon);270271 const world = yield* frontPageWorld;272273 yield* world.landAnswer;274 yield* world.forget;275276 const listed = yield* world.anyone.listProjects({});277 const bobs = yield* world.anyone.credits({ handle: bob });278 const alices = yield* world.anyone.credits({ handle: alice });279280 expect({281 alices,282 bobs,283 calls: yield* world.calls,284 listed,285 }).toStrictEqual({286 alices: {287 credits: [{ area: "parser", count: 1, project, role: "Asked-by" }],288 },289 bobs: {290 credits: [291 { area: "parser", count: 1, project, role: "Signed-off-by" },292 ],293 },294 calls: [],295 listed: {296 projects: [297 { landedAt: at(noon), openAsks: 1, posture: "open", project },298 ],299 },300 });301 }).pipe(Effect.scoped)302 );303});
modified:packages/project/src/projection-d1/front-page.ts+54 added-30 removed
modified:packages/project/src/projection-d1/projection.ts+81 added-6 removed
1/**2 * `Projection` over D1: each project's outbox rows become the front page's3 * rows (`tables.ts`). The Project DO stays the system of record; this is a4 * read model it feeds through its outbox, and nothing else writes it.3 * rows, the project list's and every person's credits (`tables.ts`). The4 * Project DO stays the system of record; this is a read model it feeds5 * through its outbox, and nothing else writes it.6 *7 * - A project is listed from its first event on (no event says a project8 * was made), `open` until a `PostureChanged` ledger entry moves it. Its9 * open asks are counted again from the front page whenever an ask opens10 * or closes, and a landing stamps when it last landed.11 * - A landing credits each person it names once per role, in its ask's12 * area: the module of the ask's territory, read from the ask's front13 * page row, which is still there when its `Landed` applies (its14 * `AskClosed` comes after). A landing with no ask, or whose ask the front15 * page never held, credits no area. `Assisted-by` is never credit.16 *17 * Events apply in their project's order, once each. Every statement is18 * guarded by the project's cursor: it runs only if the cursor stands just19 * before its event, and the event's last statement moves the cursor on. So a20 * row seen again, or an older row after a newer one, changes nothing, and
9 unmodified lines
30 */31import { TypeId } from "@effect/sql-d1/D1Client";32import type { D1Client } from "@effect/sql-d1/D1Client";33import { ProjectEvent } from "@repo/protocol/domain/event";34import type { LandingView } from "@repo/protocol/domain/landing";35import { LedgerEntry } from "@repo/protocol/domain/visibility";36import { ProjectName } from "@repo/protocol/ids";37import type { AskId } from "@repo/protocol/ids";38import { Array, DateTime, Effect, Layer, Order, Schema } from "effect";39import { SqlClient } from "effect/sql/SqlClient";
1 unmodified line
41import type { Statement } from "effect/sql/Statement";4243import type { OutboxRow } from "../project-store/rows.ts";44import { Projection, ProjectedEvent, ProjectionFailed } from "../projection.ts";45import { handleKey } from "./tables.ts";4647const decodeProjected = Schema.decodeUnknownEffect(48 Schema.toCodecJson(ProjectedEvent)49);
19 unmodified lines
69/** Each project, with the last event the rows carry for it. */70const lastOf = (events: readonly ProjectedEvent[]) =>71 new Map(events.map(({ event, project }) => [project, event.seq]));7273/**74 * Each person a landing credits, once per role, by the key `sameHandle`75 * compares handles by (`handleKey`): the rule of76 * `creditsByArea` (`attention/credits.ts`, W2 220) for one landing, whose77 * area the projection reads from D1. Only `credits` counts: `assisted` (the78 * `Assisted-by` trailers) names agents, never people.79 */80const creditedOn = (landing: Pick<LandingView, "credits">) =>81 Array.dedupeWith(82 landing.credits.map(({ handle, role }) => ({83 person: handleKey(handle),84 role,85 })),86 (one, other) => one.person === other.person && one.role === other.role87 );8889export const ProjectionD1: Layer.Layer<Projection, never, SqlClient> =90 Layer.effect(91 Projection,92 Effect.gen(function* () {
10 unmodified lines
103 /** Whether the project's cursor stands just before event `seq`. */104 const isNext = (project: ProjectName, seq: number) =>105 sql`(SELECT COALESCE(MAX(seq), 0) FROM cursor WHERE project = ${project}) = ${seq - 1}`;10677 /** What one event changes on the front page, if anything. */107 /**108 * What one event changes in the read model, if anything: the project's109 * row first, so every event lists its project.110 */111 const writes = ({ event, project }: ProjectedEvent) => {112 const next = isNext(project, event.seq);113114 const listed = sql`INSERT INTO projects (project, posture, open_asks, landed_at)115 SELECT ${project}, 'open', 0, NULL WHERE ${next}116 ON CONFLICT (project) DO NOTHING`;117118 const counted = sql`UPDATE projects SET open_asks =119 (SELECT COUNT(*) FROM front_page WHERE front_page.project = ${project})120 WHERE project = ${project} AND ${next}`;121122 const claims = (ask: AskId, change: number) =>123 sql`UPDATE front_page SET claimed = MAX(claimed + ${change}, 0)124 WHERE project = ${project} AND ask = ${ask} AND ${next}`;125126 /**127 * One more landing for each person `landing` credits, in each role,128 * in its ask's area. A landing that names a project other than the129 * one whose outbox carried it credits nothing: ask ids are unique130 * only within a project (`areaOf` in `attention/record.ts` checks131 * the same).132 */133 const credited = ({ ask, ...landing }: LandingView) =>134 ask === undefined || landing.project !== project135 ? []136 : creditedOn(landing).map(137 ({ person, role }) =>138 sql`INSERT INTO credits (handle_key, project, area, role, count)139 SELECT ${person}, ${project}, page.territory, ${role}, 1140 FROM front_page AS page141 WHERE page.project = ${project} AND page.ask = ${ask} AND ${next}142 ON CONFLICT (handle_key, project, area, role)143 DO UPDATE SET count = credits.count + 1`144 );14585 return ProjectEvent.match(event, {146 const changes = ProjectEvent.match(event, {147 AskClosed: ({ ask }) => [148 sql`DELETE FROM front_page149 WHERE project = ${project} AND ask = ${ask} AND ${next}`,150 counted,151 ],152 AskOpened: ({ ask, at }) => [153 sql`INSERT INTO front_page154 (project, ask, kind, reserve, want, territory, claimed, blocked_by, opened_at)
5 unmodified lines
160 kind = excluded.kind, reserve = excluded.reserve,161 want = excluded.want, territory = excluded.territory,162 claimed = excluded.claimed, blocked_by = excluded.blocked_by,163 opened_at = excluded.opened_at`,164 counted,165 ],166 Claimed: ({ ask }) => [claims(ask, 1)],167 Decided: () => [],168 Judged: () => [],106 Landed: () => [],169 Landed: ({ landing }) => [170 sql`UPDATE projects SET landed_at = ${DateTime.formatIso(landing.landedAt)}171 WHERE project = ${project} AND ${next}`,172 ...credited(landing),173 ],174 Lapsed: ({ ask }) => [claims(ask, -1)],108 LedgerAppended: () => [],175 LedgerAppended: ({ entry }) =>176 LedgerEntry.guards.PostureChanged(entry)177 ? [178 sql`UPDATE projects SET posture = ${entry.to}179 WHERE project = ${project} AND ${next}`,180 ]181 : [],182 ProposalOpened: () => [],183 Pushed: () => [],184 Released: ({ ask }) => [claims(ask, -1)],185 Warned: () => [],186 });187188 return [listed, ...changes];189 };190191 /** Moves the project's cursor on to `seq`, if it stands just before it. */192 const advance = (project: ProjectName, seq: number) =>
71 unmodified lines
modified:packages/project/src/projection-d1/tables.ts+67 added-1 removed
10 unmodified lines
11 * - `cursor`: the last event applied per project. Events apply in their12 * project's order, once each, so a replayed or late row changes nothing.13 *14 * A migration is never edited once it has run anywhere: W5 514 adds its15 * tables in `0002_projects_credits.sql`.15 * tables in `0004_projects_credits.sql` (`ProjectsCreditsDdl`).16 */17import type { Handle } from "@repo/protocol/ids";1819/**20 * The key `credits.handle_key` holds a person by: the handle lowercased,21 * the rule protocol's `sameHandle` compares by. The projection writes it and22 * the credits query reads by it, so both take it from here.23 */24export const handleKey = (handle: Handle): string => handle.toLowerCase();2526export const FrontPageDdl = `-- The front page: every open ask of every project, projected from each27-- project's outbox by packages/project/src/projection-d1 (its tables.ts28-- holds this text). The projection is the only writer.29
17 unmodified lines
47 project TEXT PRIMARY KEY,48 seq INTEGER NOT NULL49);50`;5152/**53 * The project list's and the credits' tables in D1, as the platform's54 * fourth D1 migration (`apps/platform/migrations/0004_projects_credits.sql`)55 * creates them, beside the front page's. The file holds exactly this text,56 * and the projection's credits test applies the file and checks that it57 * does.58 *59 * - `projects`: one row per project the projection has heard from: its60 * posture (`open` until a `PostureChanged` ledger entry), its open asks61 * (counted from `front_page` whenever an ask opens or closes), and when62 * it last landed (null before its first landing).63 * - `credits`: how many landings credit a person (by `handle_key`, the64 * handle lowercased: `handleKey`) in one role, in one area of one project.65 *66 * Its last statement lists the projects `cursor` already knows of, with67 * their open asks, so a database the front page's migration made keeps its68 * project list (W4 499's stopgap read it from `cursor`). Their credits and69 * last landings come back only with a rebuild: clear the four tables and70 * replay each project's events from seq 1 (309 #10).71 */72export const ProjectsCreditsDdl = `-- The project list and every person's credits, projected from each73-- project's outbox by packages/project/src/projection-d1 beside the front74-- page (its tables.ts holds this text). The projection is the only writer.7576-- One row per project the projection has heard from: its posture, how many77-- asks it has open, and when the platform last landed on its main (absent78-- before its first landing).79CREATE TABLE projects (80 project TEXT PRIMARY KEY,81 posture TEXT NOT NULL,82 open_asks INTEGER NOT NULL,83 landed_at TEXT84);8586-- How many landings credit a person in one role, in one area of one87-- project: a count by role and area, never a score. \`handle_key\` is the88-- handle lowercased, the rule protocol's \`sameHandle\` compares by. The89-- primary key's index serves the lookup by person.90CREATE TABLE credits (91 handle_key TEXT NOT NULL,92 project TEXT NOT NULL,93 area TEXT NOT NULL,94 role TEXT NOT NULL,95 count INTEGER NOT NULL,96 PRIMARY KEY (handle_key, project, area, role)97);9899-- The projects 0001's tables already know of, each with its open asks, so100-- the list stays whole across this migration. On a fresh database it adds101-- nothing.102INSERT INTO projects (project, posture, open_asks, landed_at)103SELECT cursor.project, 'open',104 (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),105 NULL106FROM cursor;107`;
added:packages/project/test/projection-d1-credits.test.ts+436 added
1/**2 * The project list and a person's credits over D1, on sqlite-node with the3 * platform's D1 migrations applied from their files: projects' outbox rows4 * go in through `ProjectionD1`, and `FrontPageD1` reads every project, and5 * one person's credits by project, area and role, back out in one query6 * each.7 */8import { describe, expect, it } from "@effect/vitest";9import type { AskListing } from "@repo/protocol/domain/ask";10import type { Credit } from "@repo/protocol/domain/credit";11import { ProjectEvent } from "@repo/protocol/domain/event";12import { LedgerEntry } from "@repo/protocol/domain/visibility";13import {14 AskId,15 DecisionId,16 Handle,17 KindName,18 LandedSha,19 ProjectName,20} from "@repo/protocol/ids";21import { DateTime, Effect, Layer } from "effect";22import { SqlClient } from "effect/sql/SqlClient";2324import { FrontPage } from "../src/front-page.ts";25import { projectedRows } from "../src/outbox.ts";26import type { OutboxRow } from "../src/project-store/rows.ts";27import { FrontPageD1 } from "../src/projection-d1/front-page.ts";28import { ProjectionD1 } from "../src/projection-d1/projection.ts";29import { ProjectsCreditsDdl } from "../src/projection-d1/tables.ts";30import { Projection } from "../src/projection.ts";31import {32 applied,33 frontPageMigration,34 migrated,35 migration,36 projectsMigration,37} from "./projection-d1.fixtures.ts";3839const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(40 Layer.provideMerge(migrated([frontPageMigration, projectsMigration]))41);4243/** A database the front page's migration alone made, as W3 and W4 left it. */44const beforeProjects = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(45 Layer.provideMerge(migrated([frontPageMigration]))46);4748const datekit = ProjectName.make("datekit");4950const burrow = ProjectName.make("burrow");5152const fix = KindName.make("fix");5354const parseIso = AskId.make("parse-iso");5556const weekStart = AskId.make("week-start");5758const formatTz = AskId.make("format-tz");5960const noAny = AskId.make("no-any");6162const bram = Handle.make("bram");6364const ines = Handle.make("ines-v");6566const okonkwo = Handle.make("okonkwo");6768const landing = LandedSha.make("a".repeat(40));6970const at = (minute: number) =>71 DateTime.makeUnsafe(`2026-10-08T09:${String(minute).padStart(2, "0")}:00Z`);7273const listing = (ask: AskId, territory: string): AskListing => ({74 ask,75 blockedBy: [],76 claimed: false,77 kind: fix,78 territory,79 want: `${ask} works`,80});8182/** One project's events, numbered from `first`, as outbox rows. */83const rows = (84 project: ProjectName,85 first: number,86 events: readonly ((seq: number) => ProjectEvent)[]87) =>88 projectedRows(89 project,90 events.map((event, index) => event(first + index)),91 at(59)92 );9394const opened =95 (ask: AskListing, minute: number) =>96 (seq: number): ProjectEvent =>97 ProjectEvent.cases.AskOpened.make({ ask, at: at(minute), seq });9899const closedBy =100 (ask: AskId) =>101 (seq: number): ProjectEvent =>102 ProjectEvent.cases.AskClosed.make({ ask, at: at(40), landing, seq });103104/** bram's answer to `ask` lands at `minute`, crediting `credits`, written with an agent. */105const landed =106 (ask: AskId, minute: number, credits: readonly Credit[]) =>107 (seq: number): ProjectEvent =>108 ProjectEvent.cases.Landed.make({109 at: at(minute),110 landing: {111 ask,112 assisted: [{ harness: "claude-code", model: "opus", verified: true }],113 author: bram,114 credits,115 landedAt: at(minute),116 parent: LandedSha.make("b".repeat(40)),117 project: datekit,118 sha: landing,119 },120 seq,121 });122123/** The trailers on bram's landing of `parse-iso`. */124const parseIsoCredits: readonly Credit[] = [125 { handle: ines, role: "Asked-by" },126 { handle: bram, role: "Signed-off-by" },127 { handle: okonkwo, role: "Mentored-by" },128];129130const apply = (batch: Effect.Effect<readonly OutboxRow[]>) =>131 Effect.flatMap(batch, (each) =>132 Projection.use((projection) => projection.apply(each))133 );134135/** burrow with one ask opened. */136const burrowRows = rows(burrow, 1, [opened(listing(noAny, "core"), 4)]);137138/** datekit with three asks opened and one landed; burrow with one opened. */139const both = Effect.zipWith(140 rows(datekit, 1, [141 opened(listing(parseIso, "src"), 1),142 opened(listing(weekStart, "src"), 2),143 opened(listing(formatTz, "src"), 3),144 landed(parseIso, 40, parseIsoCredits),145 closedBy(parseIso),146 ]),147 burrowRows,148 (one, other) => [...one, ...other]149);150151/** Every row of the projection's tables, to compare a replay against. */152const tables = Effect.gen(function* () {153 const sql = yield* SqlClient;154155 return {156 credits:157 yield* sql`SELECT * FROM credits ORDER BY handle_key, project, area, role`,158 cursor: yield* sql`SELECT * FROM cursor ORDER BY project`,159 frontPage: yield* sql`SELECT * FROM front_page ORDER BY project, ask`,160 projects: yield* sql`SELECT * FROM projects ORDER BY project`,161 };162});163164describe("the project list and credits in D1", () => {165 it.effect(166 "lists every project with its open asks, posture and last landing",167 () =>168 Effect.gen(function* () {169 yield* apply(both);170171 const front = yield* FrontPage;172173 expect(yield* front.projects()).toStrictEqual([174 { openAsks: 1, posture: "open", project: burrow },175 {176 landedAt: at(40),177 openAsks: 2,178 posture: "open",179 project: datekit,180 },181 ]);182 }).pipe(Effect.provide(world))183 );184185 it.effect(186 "credits each person on a landing once in their role, in the landed ask's area",187 () =>188 Effect.gen(function* () {189 yield* apply(both);190191 const front = yield* FrontPage;192193 expect({194 bram: yield* front.credits(bram),195 ines: yield* front.credits(ines),196 okonkwo: yield* front.credits(okonkwo),197 }).toStrictEqual({198 bram: [199 { area: "src", count: 1, project: datekit, role: "Signed-off-by" },200 ],201 ines: [{ area: "src", count: 1, project: datekit, role: "Asked-by" }],202 okonkwo: [203 { area: "src", count: 1, project: datekit, role: "Mentored-by" },204 ],205 });206 }).pipe(Effect.provide(world))207 );208209 it.effect("never credits the agent an answer was written with", () =>210 Effect.gen(function* () {211 yield* apply(both);212213 const front = yield* FrontPage;214215 expect(yield* front.credits(Handle.make("claude-code"))).toStrictEqual(216 []217 );218 expect(219 (yield* front.credits(bram)).map(({ role }) => role)220 ).toStrictEqual(["Signed-off-by"]);221 }).pipe(Effect.provide(world))222 );223224 it.effect("changes nothing when the same rows come again", () =>225 Effect.gen(function* () {226 yield* apply(both);227228 const before = yield* tables;229230 yield* apply(both);231 yield* apply(both);232233 expect(yield* tables).toStrictEqual(before);234 }).pipe(Effect.provide(world))235 );236237 it.effect("reads no credits for a person with no landings", () =>238 Effect.gen(function* () {239 yield* apply(both);240241 expect(242 yield* FrontPage.use((front) => front.credits(Handle.make("dora")))243 ).toStrictEqual([]);244 }).pipe(Effect.provide(world))245 );246247 it.effect("reads the migration the platform's D1 applies", () =>248 Effect.gen(function* () {249 expect(yield* migration(projectsMigration)).toBe(ProjectsCreditsDdl);250 })251 );252253 it.effect(254 "keeps every project the front page knew of across the migration, with its open asks",255 () =>256 Effect.gen(function* () {257 const sql = yield* SqlClient;258259 // The rows 309's projection wrote before the project list existed.260 yield* sql`INSERT INTO cursor (project, seq) VALUES ('datekit', 4), ('burrow', 2)`;261 yield* sql`INSERT INTO front_page262 (project, ask, kind, reserve, want, territory, claimed, blocked_by, opened_at)263 VALUES264 ('datekit', 'week-start', 'fix', NULL, 'week-start works', 'src', 0, '[]', '2026-10-08T09:02:00.000Z'),265 ('datekit', 'format-tz', 'fix', NULL, 'format-tz works', 'src', 0, '[]', '2026-10-08T09:03:00.000Z')`;266267 yield* applied(projectsMigration);268269 const front = yield* FrontPage;270271 expect(yield* front.projects()).toStrictEqual([272 { openAsks: 0, posture: "open", project: burrow },273 { openAsks: 2, posture: "open", project: datekit },274 ]);275276 yield* apply(rows(burrow, 3, [opened(listing(noAny, "core"), 5)]));277278 expect(yield* front.projects()).toStrictEqual([279 { openAsks: 1, posture: "open", project: burrow },280 { openAsks: 2, posture: "open", project: datekit },281 ]);282 }).pipe(Effect.provide(beforeProjects))283 );284285 it.effect(286 "counts each landing once per person and role, by area, whatever case a trailer spells the handle in",287 () =>288 Effect.gen(function* () {289 yield* apply(290 rows(datekit, 1, [291 opened(listing(parseIso, "src"), 1),292 opened(listing(weekStart, "src"), 2),293 opened(listing(formatTz, "format"), 3),294 landed(parseIso, 40, [295 { handle: bram, role: "Signed-off-by" },296 { handle: Handle.make("Bram"), role: "Signed-off-by" },297 { handle: bram, role: "Finished-by" },298 ]),299 closedBy(parseIso),300 landed(weekStart, 41, [{ handle: bram, role: "Signed-off-by" }]),301 closedBy(weekStart),302 landed(formatTz, 42, [303 { handle: Handle.make("BRAM"), role: "Signed-off-by" },304 ]),305 closedBy(formatTz),306 ])307 );308309 const front = yield* FrontPage;310311 const counted = [312 { area: "format", count: 1, project: datekit, role: "Signed-off-by" },313 { area: "src", count: 1, project: datekit, role: "Finished-by" },314 { area: "src", count: 2, project: datekit, role: "Signed-off-by" },315 ];316317 expect(yield* front.credits(bram)).toStrictEqual(counted);318 expect(yield* front.credits(Handle.make("Bram"))).toStrictEqual(319 counted320 );321 }).pipe(Effect.provide(world))322 );323324 it.effect(325 "credits no area for a landing of no ask, or of an ask the front page never held, yet notes when it landed",326 () =>327 Effect.gen(function* () {328 yield* apply(329 rows(datekit, 1, [330 (seq) =>331 ProjectEvent.cases.Landed.make({332 at: at(20),333 landing: {334 assisted: [],335 author: ines,336 credits: [{ handle: ines, role: "Released-by" }],337 landedAt: at(20),338 project: datekit,339 sha: landing,340 },341 seq,342 }),343 landed(parseIso, 21, parseIsoCredits),344 ])345 );346347 const front = yield* FrontPage;348349 expect(yield* front.projects()).toStrictEqual([350 { landedAt: at(21), openAsks: 0, posture: "open", project: datekit },351 ]);352 expect(yield* front.credits(ines)).toStrictEqual([]);353 expect(yield* front.credits(bram)).toStrictEqual([]);354 }).pipe(Effect.provide(world))355 );356357 it.effect(358 "credits nothing for a landing that names another project than the one whose outbox carried it",359 () =>360 Effect.gen(function* () {361 // Ask ids are unique only within a project: datekit's `parse-iso`362 // is no area of burrow's.363 yield* apply(364 rows(datekit, 1, [365 opened(listing(parseIso, "src"), 1),366 (seq) =>367 ProjectEvent.cases.Landed.make({368 at: at(30),369 landing: {370 ask: parseIso,371 assisted: [],372 author: bram,373 credits: parseIsoCredits,374 landedAt: at(30),375 project: burrow,376 sha: landing,377 },378 seq,379 }),380 ])381 );382383 const front = yield* FrontPage;384385 expect({386 bram: yield* front.credits(bram),387 ines: yield* front.credits(ines),388 }).toStrictEqual({ bram: [], ines: [] });389 }).pipe(Effect.provide(world))390 );391392 it.effect(393 "moves a project's posture when its ledger records a posture change, on its list row and its asks",394 () =>395 Effect.gen(function* () {396 yield* apply(397 rows(datekit, 1, [398 opened(listing(parseIso, "src"), 1),399 (seq) =>400 ProjectEvent.cases.LedgerAppended.make({401 at: at(10),402 entry: LedgerEntry.cases.PostureChanged.make({403 at: at(10),404 decision: DecisionId.make("decision-posture1"),405 from: "open",406 seq: 1,407 to: "openWithSealedEvidence",408 }),409 seq,410 }),411 ])412 );413 yield* apply(burrowRows);414415 const front = yield* FrontPage;416417 expect(yield* front.projects()).toStrictEqual([418 { openAsks: 1, posture: "open", project: burrow },419 {420 openAsks: 1,421 posture: "openWithSealedEvidence",422 project: datekit,423 },424 ]);425 expect(426 (yield* front.entries({})).map(({ posture, project }) => ({427 posture,428 project,429 }))430 ).toStrictEqual([431 { posture: "open", project: burrow },432 { posture: "openWithSealedEvidence", project: datekit },433 ]);434 }).pipe(Effect.provide(world))435 );436});
added:packages/project/test/projection-d1.fixtures.ts+48 added
modified:packages/project/test/projection-d1.test.ts+20 added-40 removed
1/**2 * The front page's D1 projection over sqlite-node, with the platform's D13 * migration applied from its file: projects' outbox rows go in through4 * `ProjectionD1`, and `FrontPageD1` reads every open ask back out, as the5 * anonymous viewer may take it.3 * migrations for it applied from their files: projects' outbox rows go in4 * through `ProjectionD1`, and `FrontPageD1` reads every open ask back out,5 * as the anonymous viewer may take it.6 */7import { NodeServices } from "@effect/platform-node";8import { SqliteClient } from "@effect/sql-sqlite-node";7import { describe, expect, it } from "@effect/vitest";8import type { AskListing } from "@repo/protocol/domain/ask";9import { ProjectEvent } from "@repo/protocol/domain/event";10import type { FrontPageEntry } from "@repo/protocol/domain/front-page";
3 unmodified lines
14 KindName,15 LandedSha,16 ProjectName,17} from "@repo/protocol/ids";20import { DateTime, Effect, FileSystem, Layer, Path } from "effect";18import { DateTime, Effect, Layer } from "effect";19import { SqlClient } from "effect/sql/SqlClient";2021import { FrontPage } from "../src/front-page.ts";22import type { FrontPageFilter } from "../src/front-page.ts";
2 unmodified lines
25import { FrontPageD1 } from "../src/projection-d1/front-page.ts";26import { ProjectionD1 } from "../src/projection-d1/projection.ts";27import { FrontPageDdl } from "../src/projection-d1/tables.ts";28import { Projection, ProjectionFailed } from "../src/projection.ts";29import {30 frontPageMigration,31 migrated,32 migration,33 projectsMigration,34} from "./projection-d1.fixtures.ts";3532/** The migration the platform's D1 database applies, as its file holds it. */33const migration = Effect.gen(function* () {34 const fs = yield* FileSystem.FileSystem;35 const path = yield* Path.Path;36/**37 * A fresh in-memory database each time, with the projection's migration38 * files applied in order: the front page's, then the project list's and39 * the credits'.40 */41const database = migrated([frontPageMigration, projectsMigration]);4237 return yield* fs.readFileString(38 yield* path.fromFileUrl(39 new URL(40 "../../../apps/platform/migrations/0001_front_page.sql",41 import.meta.url42 )43 )44 );45}).pipe(Effect.provide(NodeServices.layer));4647/** A fresh in-memory database each time, with the migration file applied. */48const database = Layer.effectDiscard(49 Effect.gen(function* () {50 const sql = yield* SqlClient;5152 for (const statement of (yield* migration).split(";")) {53 if (statement.trim().length > 0) {54 yield* sql.unsafe(statement);55 }56 }57 })58).pipe(59 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),60 Layer.orDie61);6243const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(44 Layer.provideMerge(database)45);46
336 unmodified lines
383 );384385 it.effect("reads the migration the platform's D1 applies", () =>386 Effect.gen(function* () {407 expect(yield* migration).toBe(FrontPageDdl);387 expect(yield* migration(frontPageMigration)).toBe(FrontPageDdl);388 })389 );390411 // Until W5 514's projects table, the projects are those the projection412 // has applied events of, so a call without a project (`status`, `today`)413 // reaches each of them.391 // A call without a project (`status`, `today`) reaches each project the392 // projection lists, so it lists every project it has applied events of,393 // even one with no ask open.394 it.effect(395 "lists every project it has heard from, with its open asks, and reads no credits",396 () =>397 Effect.gen(function* () {
19 unmodified lines