Skip to content
Myr

List projects and a person's credits from D1, fed by every project's outbox, so neither read wakes a project

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

W5 issue 514. `listProjects` and `credits` (already routed through `FrontPage` by 312) now read one D1 query each. - apps/platform/migrations/0004_projects_credits.sql (0002 and 0003 were taken by accounts and identities), mirrored by `ProjectsCreditsDdl` in packages/project/src/projection-d1/tables.ts: `projects (project, posture, open_asks, landed_at)` and `credits (handle_key, project, area, role, count)`. Departures from the issue's interface: the person column is `handle_key`, the handle lowercased (the `sameHandle` rule, as `accounts` and `identities` key handles); no `credits_by_handle` index, since the primary key already indexes the lookup by person and its order; and the file ends by listing every project `cursor` already knows of with its open asks, so a live D1 keeps the project list W4 499's stopgap read from `cursor` (on a fresh D1 it adds nothing). - ProjectionD1.apply: every event first lists its project (open, no landing); AskOpened and AskClosed recount its open asks from `front_page`; Landed stamps `landed_at` and credits each person it names once per role in the landed ask's area (its territory module, read from the ask's `front_page` row, which is still there because an answer's Landed is emitted before its AskClosed); a LedgerAppended PostureChanged sets the posture. All under the same per-event cursor guard, so a replay changes nothing (principle 8). - The area rule mirrors W2 220's `creditsByArea` (no single-landing helper is exported): `sameHandle`'s key, roles deduped per landing, nothing for a landing with no ask, an ask the front page never held, or another project; `assisted` (Assisted-by) never counts. - FrontPageD1: `projects()` reads `projects` by name (landedAt only once landed); `credits(handle)` reads one person's rows by project, area and role, never a score or total; `entries` joins each project's posture (309 #6), `open` when it has no row. - Tests: packages/project/test/projection-d1-credits.test.ts (11; red by assertion before the work: projects without landedAt, credits []): the issue's datekit/burrow check, Assisted-by never credit, replay twice leaves all four tables unchanged, a person with no landings, the file equals its constant, the migration keeps a 0001-only database's projects, case-insensitive handles and per-area counts across landings, a landing with no or an unheld ask, posture moved by the ledger. apps/platform/test/front-page.test.ts: a Node platform world (`platformOn` over the D1 cartridge on sqlite-node with the migration files applied, `ProjectsMemory` feeding it, a counted `Projects`) lands bob's answer, then anonymous /rpc `listProjects` and `credits` return the projected rows with no call to a project (red by assertion against the old projection). packages/project/test/projection-d1.test.ts applies both migration files; its "every project it has heard from" case holds as written. - verify green; platform entry 1,599,445 of 1,665,000. - ASSUMPTION: no event says a project was made, so a project is listed from its first projected event (an ask opened, or a landing such as the generated follow-up after its first push). Left for the integrator in the issue's Comments: migrating 0004 before deploying (deploy does not apply D1 migrations), 399's DoProjects gate, 309 #4.

authored by oscabriel · committed by oscabriel · parent eebd79b · Browse files · 7 files+979 added−60 removed
This commit

State

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

Diff stats

7 files+979 added−60 removed

  • tests:+753 added−23 removed
  • other:+226 added−37 removed

7 files+979 added−60 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+288 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, 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/** The front page's migrations, read from the platform's own folder in order and run statement by statement. */74const migrated = Layer.effectDiscard(75 Effect.gen(function* () {76 const fs = yield* FileSystem.FileSystem;77 const path = yield* Path.Path;78 const sql = yield* SqlClient;7980 for (const file of ["0001_front_page.sql", "0004_projects_credits.sql"]) {81 const text = yield* fs.readFileString(82 yield* path.fromFileUrl(83 new URL(`../migrations/${file}`, import.meta.url)84 )85 );8687 for (const statement of text.split(";")) {88 if (statement.trim().length > 0) {89 yield* sql.unsafe(statement);90 }91 }92 }93 })94).pipe(95 Layer.provide(NodeServices.layer),96 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),97 Layer.orDie98);99100/**101 * An ask's check fails on a commit of main, every time the same way, and102 * every lane passes on an answer's merged tree.103 */104const redOnMainGreenOnAnswers = Layer.succeed(105 CheckRunner,106 CheckRunner.of({107 run: ({ at: where, lanes }) => {108 const passed = CheckAt.guards.Tree(where);109110 return Effect.succeed({111 durationMs: lanes.length,112 evidence: passed113 ? []114 : lanes.map(({ lane }) => ({ lane, signature: `${lane}: red` })),115 heldBack: [],116 lanes: lanes.map(({ command, lane }) => ({117 command,118 durationMs: 1,119 lane,120 result: passed ? ("passed" as const) : ("failed" as const),121 })),122 });123 },124 })125);126127/** At any commit, datekit's policy, holding the asks whose files the commit has. */128const rules = Layer.effect(129 RulesEvaluator,130 Effect.gen(function* () {131 const finishers = yield* Finishers;132 const { policy } = datekit;133134 return RulesEvaluator.of({135 call: () => Effect.succeed(false),136 evaluate: ({ at: landed, facts, modules }) =>137 Effect.succeed({138 ...policy,139 asks: policy.asks.filter(({ file }) => file in modules.modules),140 at: landed,141 judge: finishers.judgeClosure(policy.run, facts.ci),142 } satisfies Policy),143 });144 })145).pipe(Layer.provide(FinishersFromChecks));146147/** The world a front-page test drives. */148interface FrontPageWorld {149 /** Every call the platform made to a project through `Projects`, in order. */150 readonly calls: Effect.Effect<readonly string[]>;151 /** Forgets the calls made so far. */152 readonly forget: Effect.Effect<void>;153 /** A client of the contracts over HTTP at `/rpc`, as anyone. */154 readonly anyone: Client["Service"];155 /** bob's answer to `parse-iso` landed, as his claim, push and submission make it. */156 readonly landAnswer: Effect.Effect<void>;157}158159const frontPageWorld: Effect.Effect<FrontPageWorld, never, Scope.Scope> =160 Effect.gen(function* () {161 // Every port but `Projects`, built once: the Worker's and each project's.162 const base = yield* Layer.build(163 Layer.mergeAll(164 AlarmsMemory,165 AnswerRunsInline,166 EvidenceStoreMemory,167 FrontPageD1,168 MemoryRateLimits(WorkerCaps),169 ProjectionD1,170 rules,171 UpstreamRepoHost172 ).pipe(173 Layer.provideMerge(migrated),174 Layer.provideMerge(LanderIsogit),175 Layer.provideMerge(redOnMainGreenOnAnswers),176 Layer.provideMerge(RepoHostMemory),177 Layer.provideMerge(WorkerFetch)178 )179 );180181 const found = Context.get(182 yield* Layer.build(183 ProjectsMemory.pipe(Layer.provide(Layer.succeedContext(base)))184 ),185 Projects186 );187188 const calls: string[] = [];189190 const counted = Projects.of({191 create: (name) =>192 Effect.suspend(() => {193 calls.push(`create ${name}`);194195 return found.create(name);196 }),197 get: (name) =>198 Effect.suspend(() => {199 calls.push(`get ${name}`);200201 return found.get(name);202 }),203 });204205 const ports = Context.add(base, Projects, counted);206 const config = yield* Effect.orDie(decodeEnv(fakeEnv()));207208 const { dispose, handler } = serve(209 platformOn(config, Layer.succeedContext(ports))210 );211212 yield* Effect.addFinalizer(() => Effect.promise(dispose));213214 const landAnswer = Effect.gen(function* () {215 const answerer = Person.make({ handle: bob });216 const api = yield* counted.get(project);217 const { claim } = yield* api.claim(answerer, parseIso);218 const main = LandedSha.make(claim.base);219220 const { commit } = yield* Context.get(base, Lander).compose({221 files: Array.make({222 content: "export const parse = (s) => ({ year: 2026 });\n",223 path: RepoPath.make("packages/parser/src/parse.ts"),224 }),225 main,226 repo: claim.fork,227 });228229 yield* api.submitAnswer(answerer, {230 ask: parseIso,231 base: main,232 head: commit,233 requestId: RequestId.make("req-parse-iso1"),234 });235 }).pipe(Effect.orDie);236237 yield* seeded(datekit).pipe(Effect.provideContext(ports));238239 return {240 anyone: yield* rpcClient(handler),241 calls: Effect.sync(() => [...calls]),242 forget: Effect.sync(() => {243 calls.length = 0;244 }),245 landAnswer,246 };247 });248249describe("the project list and credits over the platform's /rpc", () => {250 it.effect(251 "after a landing, lists the project and its people's credits from D1 without calling a project",252 () =>253 Effect.gen(function* () {254 yield* advanceTo(noon);255256 const world = yield* frontPageWorld;257258 yield* world.landAnswer;259 yield* world.forget;260261 const listed = yield* world.anyone.listProjects({});262 const bobs = yield* world.anyone.credits({ handle: bob });263 const alices = yield* world.anyone.credits({ handle: alice });264265 expect({266 alices,267 bobs,268 calls: yield* world.calls,269 listed,270 }).toStrictEqual({271 alices: {272 credits: [{ area: "parser", count: 1, project, role: "Asked-by" }],273 },274 bobs: {275 credits: [276 { area: "parser", count: 1, project, role: "Signed-off-by" },277 ],278 },279 calls: [],280 listed: {281 projects: [282 { landedAt: at(noon), openAsks: 1, posture: "open", project },283 ],284 },285 });286 }).pipe(Effect.scoped)287 );288});
modified:packages/project/src/projection-d1/front-page.ts+53 added-30 removed
modified:packages/project/src/projection-d1/projection.ts+80 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";
28 unmodified lines
68/** Each project, with the last event the rows carry for it. */69const lastOf = (events: readonly ProjectedEvent[]) =>70 new Map(events.map(({ event, project }) => [project, event.seq]));7172/**73 * Each person a landing credits, once per role, by the key `sameHandle`74 * compares handles by (the handle lowercased): the rule of75 * `creditsByArea` (`attention/credits.ts`, W2 220) for one landing, whose76 * area the projection reads from D1. Only `credits` counts: `assisted` (the77 * `Assisted-by` trailers) names agents, never people.78 */79const creditedOn = (landing: Pick<LandingView, "credits">) =>80 Array.dedupeWith(81 landing.credits.map(({ handle, role }) => ({82 handleKey: handle.toLowerCase(),83 role,84 })),85 (one, other) => one.handleKey === other.handleKey && one.role === other.role86 );8788export const ProjectionD1: Layer.Layer<Projection, never, SqlClient> =89 Layer.effect(90 Projection,91 Effect.gen(function* () {
10 unmodified lines
102 /** Whether the project's cursor stands just before event `seq`. */103 const isNext = (project: ProjectName, seq: number) =>104 sql`(SELECT COALESCE(MAX(seq), 0) FROM cursor WHERE project = ${project}) = ${seq - 1}`;10577 /** What one event changes on the front page, if anything. */106 /**107 * What one event changes in the read model, if anything: the project's108 * row first, so every event lists its project.109 */110 const writes = ({ event, project }: ProjectedEvent) => {111 const next = isNext(project, event.seq);112113 const listed = sql`INSERT INTO projects (project, posture, open_asks, landed_at)114 SELECT ${project}, 'open', 0, NULL WHERE ${next}115 ON CONFLICT (project) DO NOTHING`;116117 const counted = sql`UPDATE projects SET open_asks =118 (SELECT COUNT(*) FROM front_page WHERE front_page.project = ${project})119 WHERE project = ${project} AND ${next}`;120121 const claims = (ask: AskId, change: number) =>122 sql`UPDATE front_page SET claimed = MAX(claimed + ${change}, 0)123 WHERE project = ${project} AND ask = ${ask} AND ${next}`;124125 /**126 * One more landing for each person `landing` credits, in each role,127 * in its ask's area. A landing that names a project other than the128 * one whose outbox carried it credits nothing: ask ids are unique129 * only within a project (`areaOf` in `attention/record.ts` checks130 * the same).131 */132 const credited = ({ ask, ...landing }: LandingView) =>133 ask === undefined || landing.project !== project134 ? []135 : creditedOn(landing).map(136 ({ handleKey, role }) =>137 sql`INSERT INTO credits (handle_key, project, area, role, count)138 SELECT ${handleKey}, ${project}, page.territory, ${role}, 1139 FROM front_page AS page140 WHERE page.project = ${project} AND page.ask = ${ask} AND ${next}141 ON CONFLICT (handle_key, project, area, role)142 DO UPDATE SET count = credits.count + 1`143 );14485 return ProjectEvent.match(event, {145 const changes = ProjectEvent.match(event, {146 AskClosed: ({ ask }) => [147 sql`DELETE FROM front_page148 WHERE project = ${project} AND ask = ${ask} AND ${next}`,149 counted,150 ],151 AskOpened: ({ ask, at }) => [152 sql`INSERT INTO front_page153 (project, ask, kind, reserve, want, territory, claimed, blocked_by, opened_at)
5 unmodified lines
159 kind = excluded.kind, reserve = excluded.reserve,160 want = excluded.want, territory = excluded.territory,161 claimed = excluded.claimed, blocked_by = excluded.blocked_by,162 opened_at = excluded.opened_at`,163 counted,164 ],165 Claimed: ({ ask }) => [claims(ask, 1)],166 Decided: () => [],167 Judged: () => [],106 Landed: () => [],168 Landed: ({ landing }) => [169 sql`UPDATE projects SET landed_at = ${DateTime.formatIso(landing.landedAt)}170 WHERE project = ${project} AND ${next}`,171 ...credited(landing),172 ],173 Lapsed: ({ ask }) => [claims(ask, -1)],108 LedgerAppended: () => [],174 LedgerAppended: ({ entry }) =>175 LedgerEntry.guards.PostureChanged(entry)176 ? [177 sql`UPDATE projects SET posture = ${entry.to}178 WHERE project = ${project} AND ${next}`,179 ]180 : [],181 ProposalOpened: () => [],182 Pushed: () => [],183 Released: ({ ask }) => [claims(ask, -1)],184 Warned: () => [],185 });186187 return [listed, ...changes];188 };189190 /** Moves the project's cursor on to `seq`, if it stands just before it. */191 const advance = (project: ProjectName, seq: number) =>
71 unmodified lines
modified:packages/project/src/projection-d1/tables.ts+58 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 */17export const FrontPageDdl = `-- The front page: every open ask of every project, projected from each18-- project's outbox by packages/project/src/projection-d1 (its tables.ts19-- holds this text). The projection is the only writer.
18 unmodified lines
38 project TEXT PRIMARY KEY,39 seq INTEGER NOT NULL40);41`;4243/**44 * The project list's and the credits' tables in D1, as the platform's45 * fourth D1 migration (`apps/platform/migrations/0004_projects_credits.sql`)46 * creates them, beside the front page's. The file holds exactly this text,47 * and the projection's credits test applies the file and checks that it48 * does.49 *50 * - `projects`: one row per project the projection has heard from: its51 * posture (`open` until a `PostureChanged` ledger entry), its open asks52 * (counted from `front_page` whenever an ask opens or closes), and when53 * it last landed (null before its first landing).54 * - `credits`: how many landings credit a person (by `handle_key`, the55 * handle lowercased) in one role, in one area of one project.56 *57 * Its last statement lists the projects `cursor` already knows of, with58 * their open asks, so a database the front page's migration made keeps its59 * project list (W4 499's stopgap read it from `cursor`). Their credits and60 * last landings come back only with a rebuild: clear the four tables and61 * replay each project's events from seq 1 (309 #10).62 */63export const ProjectsCreditsDdl = `-- The project list and every person's credits, projected from each64-- project's outbox by packages/project/src/projection-d1 beside the front65-- page (its tables.ts holds this text). The projection is the only writer.6667-- One row per project the projection has heard from: its posture, how many68-- asks it has open, and when the platform last landed on its main (absent69-- before its first landing).70CREATE TABLE projects (71 project TEXT PRIMARY KEY,72 posture TEXT NOT NULL,73 open_asks INTEGER NOT NULL,74 landed_at TEXT75);7677-- How many landings credit a person in one role, in one area of one78-- project: a count by role and area, never a score. \`handle_key\` is the79-- handle lowercased, the rule protocol's \`sameHandle\` compares by. The80-- primary key's index serves the lookup by person.81CREATE TABLE credits (82 handle_key TEXT NOT NULL,83 project TEXT NOT NULL,84 area TEXT NOT NULL,85 role TEXT NOT NULL,86 count INTEGER NOT NULL,87 PRIMARY KEY (handle_key, project, area, role)88);8990-- The projects 0001's tables already know of, each with its open asks, so91-- the list stays whole across this migration. On a fresh database it adds92-- nothing.93INSERT INTO projects (project, posture, open_asks, landed_at)94SELECT cursor.project, 'open',95 (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),96 NULL97FROM cursor;98`;
added:packages/project/test/projection-d1-credits.test.ts+438 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 { NodeServices } from "@effect/platform-node";9import { SqliteClient } from "@effect/sql-sqlite-node";10import { describe, expect, it } from "@effect/vitest";11import type { AskListing } from "@repo/protocol/domain/ask";12import type { Credit } from "@repo/protocol/domain/credit";13import { ProjectEvent } from "@repo/protocol/domain/event";14import { LedgerEntry } from "@repo/protocol/domain/visibility";15import {16 AskId,17 DecisionId,18 Handle,19 KindName,20 LandedSha,21 ProjectName,22} from "@repo/protocol/ids";23import { DateTime, Effect, FileSystem, Layer, Path } from "effect";24import { SqlClient } from "effect/sql/SqlClient";2526import { FrontPage } from "../src/front-page.ts";27import { projectedRows } from "../src/outbox.ts";28import type { OutboxRow } from "../src/project-store/rows.ts";29import { FrontPageD1 } from "../src/projection-d1/front-page.ts";30import { ProjectionD1 } from "../src/projection-d1/projection.ts";31import { ProjectsCreditsDdl } from "../src/projection-d1/tables.ts";32import { Projection } from "../src/projection.ts";3334/** A migration of the platform's D1 database, as its file holds it. */35const migration = (file: string) =>36 Effect.gen(function* () {37 const fs = yield* FileSystem.FileSystem;38 const path = yield* Path.Path;3940 return yield* fs.readFileString(41 yield* path.fromFileUrl(42 new URL(`../../../apps/platform/migrations/${file}`, import.meta.url)43 )44 );45 }).pipe(Effect.provide(NodeServices.layer), Effect.orDie);4647/** Runs a migration's statements in order, as `wrangler d1 migrations apply` does. */48const applied = (file: string) =>49 Effect.gen(function* () {50 const sql = yield* SqlClient;5152 for (const statement of (yield* migration(file)).split(";")) {53 if (statement.trim().length > 0) {54 yield* sql.unsafe(statement);55 }56 }57 }).pipe(Effect.orDie);5859const frontPageMigration = "0001_front_page.sql";6061const projectsMigration = "0004_projects_credits.sql";6263/** A fresh in-memory database each time, with the projection's migrations applied. */64const database = Layer.effectDiscard(65 Effect.andThen(applied(frontPageMigration), applied(projectsMigration))66).pipe(67 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),68 Layer.orDie69);7071const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(72 Layer.provideMerge(database)73);7475/** A database the front page's migration alone made, as W3 and W4 left it. */76const beforeProjects = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(77 Layer.provideMerge(78 Layer.effectDiscard(applied(frontPageMigration)).pipe(79 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),80 Layer.orDie81 )82 )83);8485const datekit = ProjectName.make("datekit");8687const burrow = ProjectName.make("burrow");8889const fix = KindName.make("fix");9091const parseIso = AskId.make("parse-iso");9293const weekStart = AskId.make("week-start");9495const formatTz = AskId.make("format-tz");9697const noAny = AskId.make("no-any");9899const bram = Handle.make("bram");100101const ines = Handle.make("ines-v");102103const okonkwo = Handle.make("okonkwo");104105const landing = LandedSha.make("a".repeat(40));106107const at = (minute: number) =>108 DateTime.makeUnsafe(`2026-10-08T09:${String(minute).padStart(2, "0")}:00Z`);109110const listing = (ask: AskId, territory: string): AskListing => ({111 ask,112 blockedBy: [],113 claimed: false,114 kind: fix,115 territory,116 want: `${ask} works`,117});118119/** One project's events, numbered from `first`, as outbox rows. */120const rows = (121 project: ProjectName,122 first: number,123 events: readonly ((seq: number) => ProjectEvent)[]124) =>125 projectedRows(126 project,127 events.map((event, index) => event(first + index)),128 at(59)129 );130131const opened =132 (ask: AskListing, minute: number) =>133 (seq: number): ProjectEvent =>134 ProjectEvent.cases.AskOpened.make({ ask, at: at(minute), seq });135136const closedBy =137 (ask: AskId) =>138 (seq: number): ProjectEvent =>139 ProjectEvent.cases.AskClosed.make({ ask, at: at(40), landing, seq });140141/** bram's answer to `ask` lands at `minute`, crediting `credits`, written with an agent. */142const landed =143 (ask: AskId, minute: number, credits: readonly Credit[]) =>144 (seq: number): ProjectEvent =>145 ProjectEvent.cases.Landed.make({146 at: at(minute),147 landing: {148 ask,149 assisted: [{ harness: "claude-code", model: "opus", verified: true }],150 author: bram,151 credits,152 landedAt: at(minute),153 parent: LandedSha.make("b".repeat(40)),154 project: datekit,155 sha: landing,156 },157 seq,158 });159160/** The trailers on bram's landing of `parse-iso`. */161const parseIsoCredits: readonly Credit[] = [162 { handle: ines, role: "Asked-by" },163 { handle: bram, role: "Signed-off-by" },164 { handle: okonkwo, role: "Mentored-by" },165];166167const apply = (batch: Effect.Effect<readonly OutboxRow[]>) =>168 Effect.flatMap(batch, (each) =>169 Projection.use((projection) => projection.apply(each))170 );171172/** burrow with one ask opened. */173const burrowRows = rows(burrow, 1, [opened(listing(noAny, "core"), 4)]);174175/** datekit with three asks opened and one landed; burrow with one opened. */176const both = Effect.zipWith(177 rows(datekit, 1, [178 opened(listing(parseIso, "src"), 1),179 opened(listing(weekStart, "src"), 2),180 opened(listing(formatTz, "src"), 3),181 landed(parseIso, 40, parseIsoCredits),182 closedBy(parseIso),183 ]),184 burrowRows,185 (one, other) => [...one, ...other]186);187188/** Every row of the projection's tables, to compare a replay against. */189const tables = Effect.gen(function* () {190 const sql = yield* SqlClient;191192 return {193 credits:194 yield* sql`SELECT * FROM credits ORDER BY handle_key, project, area, role`,195 cursor: yield* sql`SELECT * FROM cursor ORDER BY project`,196 frontPage: yield* sql`SELECT * FROM front_page ORDER BY project, ask`,197 projects: yield* sql`SELECT * FROM projects ORDER BY project`,198 };199});200201describe("the project list and credits in D1", () => {202 it.effect(203 "lists every project with its open asks, posture and last landing",204 () =>205 Effect.gen(function* () {206 yield* apply(both);207208 const front = yield* FrontPage;209210 expect(yield* front.projects()).toStrictEqual([211 { openAsks: 1, posture: "open", project: burrow },212 {213 landedAt: at(40),214 openAsks: 2,215 posture: "open",216 project: datekit,217 },218 ]);219 }).pipe(Effect.provide(world))220 );221222 it.effect(223 "credits each person on a landing once in their role, in the landed ask's area",224 () =>225 Effect.gen(function* () {226 yield* apply(both);227228 const front = yield* FrontPage;229230 expect({231 bram: yield* front.credits(bram),232 ines: yield* front.credits(ines),233 okonkwo: yield* front.credits(okonkwo),234 }).toStrictEqual({235 bram: [236 { area: "src", count: 1, project: datekit, role: "Signed-off-by" },237 ],238 ines: [{ area: "src", count: 1, project: datekit, role: "Asked-by" }],239 okonkwo: [240 { area: "src", count: 1, project: datekit, role: "Mentored-by" },241 ],242 });243 }).pipe(Effect.provide(world))244 );245246 it.effect("never credits the agent an answer was written with", () =>247 Effect.gen(function* () {248 yield* apply(both);249250 const front = yield* FrontPage;251252 expect(yield* front.credits(Handle.make("claude-code"))).toStrictEqual(253 []254 );255 expect(256 (yield* front.credits(bram)).map(({ role }) => role)257 ).toStrictEqual(["Signed-off-by"]);258 }).pipe(Effect.provide(world))259 );260261 it.effect("changes nothing when the same rows come again", () =>262 Effect.gen(function* () {263 yield* apply(both);264265 const before = yield* tables;266267 yield* apply(both);268 yield* apply(both);269270 expect(yield* tables).toStrictEqual(before);271 }).pipe(Effect.provide(world))272 );273274 it.effect("reads no credits for a person with no landings", () =>275 Effect.gen(function* () {276 yield* apply(both);277278 expect(279 yield* FrontPage.use((front) => front.credits(Handle.make("dora")))280 ).toStrictEqual([]);281 }).pipe(Effect.provide(world))282 );283284 it.effect("reads the migration the platform's D1 applies", () =>285 Effect.gen(function* () {286 expect(yield* migration(projectsMigration)).toBe(ProjectsCreditsDdl);287 })288 );289290 it.effect(291 "keeps every project the front page knew of across the migration, with its open asks",292 () =>293 Effect.gen(function* () {294 const sql = yield* SqlClient;295296 // The rows 309's projection wrote before the project list existed.297 yield* sql`INSERT INTO cursor (project, seq) VALUES ('datekit', 4), ('burrow', 2)`;298 yield* sql`INSERT INTO front_page299 (project, ask, kind, reserve, want, territory, claimed, blocked_by, opened_at)300 VALUES301 ('datekit', 'week-start', 'fix', NULL, 'week-start works', 'src', 0, '[]', '2026-10-08T09:02:00.000Z'),302 ('datekit', 'format-tz', 'fix', NULL, 'format-tz works', 'src', 0, '[]', '2026-10-08T09:03:00.000Z')`;303304 yield* applied(projectsMigration);305306 const front = yield* FrontPage;307308 expect(yield* front.projects()).toStrictEqual([309 { openAsks: 0, posture: "open", project: burrow },310 { openAsks: 2, posture: "open", project: datekit },311 ]);312313 yield* apply(rows(burrow, 3, [opened(listing(noAny, "core"), 5)]));314315 expect(yield* front.projects()).toStrictEqual([316 { openAsks: 1, posture: "open", project: burrow },317 { openAsks: 2, posture: "open", project: datekit },318 ]);319 }).pipe(Effect.provide(beforeProjects))320 );321322 it.effect(323 "counts each landing once per person and role, by area, whatever case a trailer spells the handle in",324 () =>325 Effect.gen(function* () {326 yield* apply(327 rows(datekit, 1, [328 opened(listing(parseIso, "src"), 1),329 opened(listing(weekStart, "src"), 2),330 opened(listing(formatTz, "format"), 3),331 landed(parseIso, 40, [332 { handle: bram, role: "Signed-off-by" },333 { handle: Handle.make("Bram"), role: "Signed-off-by" },334 { handle: bram, role: "Finished-by" },335 ]),336 closedBy(parseIso),337 landed(weekStart, 41, [{ handle: bram, role: "Signed-off-by" }]),338 closedBy(weekStart),339 landed(formatTz, 42, [340 { handle: Handle.make("BRAM"), role: "Signed-off-by" },341 ]),342 closedBy(formatTz),343 ])344 );345346 const front = yield* FrontPage;347348 const counted = [349 { area: "format", count: 1, project: datekit, role: "Signed-off-by" },350 { area: "src", count: 1, project: datekit, role: "Finished-by" },351 { area: "src", count: 2, project: datekit, role: "Signed-off-by" },352 ];353354 expect(yield* front.credits(bram)).toStrictEqual(counted);355 expect(yield* front.credits(Handle.make("Bram"))).toStrictEqual(356 counted357 );358 }).pipe(Effect.provide(world))359 );360361 it.effect(362 "credits no area for a landing of no ask, or of an ask the front page never held, yet notes when it landed",363 () =>364 Effect.gen(function* () {365 yield* apply(366 rows(datekit, 1, [367 (seq) =>368 ProjectEvent.cases.Landed.make({369 at: at(20),370 landing: {371 assisted: [],372 author: ines,373 credits: [{ handle: ines, role: "Released-by" }],374 landedAt: at(20),375 project: datekit,376 sha: landing,377 },378 seq,379 }),380 landed(parseIso, 21, parseIsoCredits),381 ])382 );383384 const front = yield* FrontPage;385386 expect(yield* front.projects()).toStrictEqual([387 { landedAt: at(21), openAsks: 0, posture: "open", project: datekit },388 ]);389 expect(yield* front.credits(ines)).toStrictEqual([]);390 expect(yield* front.credits(bram)).toStrictEqual([]);391 }).pipe(Effect.provide(world))392 );393394 it.effect(395 "moves a project's posture when its ledger records a posture change, on its list row and its asks",396 () =>397 Effect.gen(function* () {398 yield* apply(399 rows(datekit, 1, [400 opened(listing(parseIso, "src"), 1),401 (seq) =>402 ProjectEvent.cases.LedgerAppended.make({403 at: at(10),404 entry: LedgerEntry.cases.PostureChanged.make({405 at: at(10),406 decision: DecisionId.make("decision-posture1"),407 from: "open",408 seq: 1,409 to: "openWithSealedEvidence",410 }),411 seq,412 }),413 ])414 );415 yield* apply(burrowRows);416417 const front = yield* FrontPage;418419 expect(yield* front.projects()).toStrictEqual([420 { openAsks: 1, posture: "open", project: burrow },421 {422 openAsks: 1,423 posture: "openWithSealedEvidence",424 project: datekit,425 },426 ]);427 expect(428 (yield* front.entries({})).map(({ posture, project }) => ({429 posture,430 project,431 }))432 ).toStrictEqual([433 { posture: "open", project: burrow },434 { posture: "openWithSealedEvidence", project: datekit },435 ]);436 }).pipe(Effect.provide(world))437 );438});
modified:packages/project/test/projection-d1.test.ts+27 added-23 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";9import { describe, expect, it } from "@effect/vitest";
18 unmodified lines
28import { ProjectionD1 } from "../src/projection-d1/projection.ts";29import { FrontPageDdl } from "../src/projection-d1/tables.ts";30import { Projection, ProjectionFailed } from "../src/projection.ts";3132/** 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;32/** A migration the platform's D1 database applies, as its file holds it. */33const migration = (file: string) =>34 Effect.gen(function* () {35 const fs = yield* FileSystem.FileSystem;36 const path = yield* Path.Path;3737 return yield* fs.readFileString(38 yield* path.fromFileUrl(39 new URL(40 "../../../apps/platform/migrations/0001_front_page.sql",41 import.meta.url38 return yield* fs.readFileString(39 yield* path.fromFileUrl(40 new URL(`../../../apps/platform/migrations/${file}`, import.meta.url)41 )43 )44 );45}).pipe(Effect.provide(NodeServices.layer));42 );43 }).pipe(Effect.provide(NodeServices.layer));4447/** A fresh in-memory database each time, with the migration file applied. */45/**46 * A fresh in-memory database each time, with the projection's migration47 * files applied in order: the front page's, then the project list's and48 * the credits'.49 */50const database = Layer.effectDiscard(51 Effect.gen(function* () {52 const sql = yield* SqlClient;5354 for (const file of ["0001_front_page.sql", "0004_projects_credits.sql"]) {52 for (const statement of (yield* migration).split(";")) {53 if (statement.trim().length > 0) {54 yield* sql.unsafe(statement);55 for (const statement of (yield* migration(file)).split(";")) {56 if (statement.trim().length > 0) {57 yield* sql.unsafe(statement);58 }59 }60 }61 })62).pipe(
344 unmodified lines
407 );408409 it.effect("reads the migration the platform's D1 applies", () =>410 Effect.gen(function* () {407 expect(yield* migration).toBe(FrontPageDdl);411 expect(yield* migration("0001_front_page.sql")).toBe(FrontPageDdl);412 })413 );414411 // 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.415 // A call without a project (`status`, `today`) reaches each project the416 // projection lists, so it lists every project it has applied events of,417 // even one with no ask open.418 it.effect(419 "lists every project it has heard from, with its open asks, and reads no credits",420 () =>421 Effect.gen(function* () {
19 unmodified lines