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
Provenance
- Commit
08b0ff8- Tree
5b53b8e- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
f736a1e- Parent 2
7e05025
8 files changed+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.4+5+-- 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).8+CREATE TABLE projects (9+ project TEXT PRIMARY KEY,10+ posture TEXT NOT NULL,11+ open_asks INTEGER NOT NULL,12+ landed_at TEXT13+);14+15+-- 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.19+CREATE 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+);27+28+-- 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.31+INSERT INTO projects (project, posture, open_asks, landed_at)32+SELECT cursor.project, 'open',33+ (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),34+ NULL35+FROM 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+ */14+import { NodeServices } from "@effect/platform-node";15+import { SqliteClient } from "@effect/sql-sqlite-node";16+import { describe, expect, it } from "@effect/vitest";17+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";18+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";19+import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";20+import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";21+import { AlarmsMemory } from "@repo/project/alarms/memory";22+import { AnswerRunsInline } from "@repo/project/answer-runs/inline";23+import { Lander } from "@repo/project/lander";24+import { LanderIsogit } from "@repo/project/lander/isogit";25+import { FinishersFromChecks } from "@repo/project/project";26+import { FrontPageD1 } from "@repo/project/projection-d1/front-page";27+import { ProjectionD1 } from "@repo/project/projection-d1/projection";28+import { Projects } from "@repo/project/projects";29+import { ProjectsMemory } from "@repo/project/projects/memory";30+import type { Client } from "@repo/protocol/contracts";31+import type { Policy } from "@repo/protocol/domain/policy";32+import {33+ AskId,34+ Handle,35+ LandedSha,36+ RepoPath,37+ RequestId,38+} from "@repo/protocol/ids";39+import { Person } from "@repo/protocol/principal";40+import { Finishers } from "@repo/rules/finish";41+import { RulesEvaluator } from "@repo/rules/rules-evaluator";42+import { advanceTo, at } from "@repo/testkit/clock";43+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";44+import type { Scope } from "effect";45+import { Array, Context, Effect, FileSystem, Layer, Order, Path } from "effect";46+import { SqlClient } from "effect/sql/SqlClient";47+48+import { WorkerFetch } from "../src/adapters/fetch.ts";49+import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";50+import { decodeEnv, platformOn } from "../src/platform.ts";51+import { serve } from "../src/surfaces.ts";52+import { fakeEnv } from "./fake-env.ts";53+import { seeded } from "./handlers.fixtures.ts";54+import { rpcClient } from "./harness.ts";55+56+/** datekit: alice decides and asks; bob is vouched for. */57+const 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+);62+63+const { project } = datekit;64+65+const parseIso = AskId.make("parse-iso");66+67+const bob = Handle.make("bob");68+69+const alice = Handle.make("alice");70+71+const noon = "2026-10-07T12:00:00Z";72+73+/**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+ */79+const migrated = Layer.effectDiscard(80+ Effect.gen(function* () {81+ const fs = yield* FileSystem.FileSystem;82+ const path = yield* Path.Path;83+ const sql = yield* SqlClient;84+85+ const folder = yield* path.fromFileUrl(86+ new URL("../migrations", import.meta.url)87+ );88+89+ const files = Array.sort(90+ (yield* fs.readDirectory(folder)).filter((file) => file.endsWith(".sql")),91+ Order.String92+ );93+94+ for (const file of files) {95+ const text = yield* fs.readFileString(path.join(folder, file));96+97+ const code = text98+ .split("\n")99+ .filter((line) => !line.trimStart().startsWith("--"))100+ .join("\n");101+102+ 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+);114+115+/**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+ */119+const redOnMainGreenOnAnswers = Layer.succeed(120+ CheckRunner,121+ CheckRunner.of({122+ run: ({ at: where, lanes }) => {123+ const passed = CheckAt.guards.Tree(where);124+125+ 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+);141+142+/** At any commit, datekit's policy, holding the asks whose files the commit has. */143+const rules = Layer.effect(144+ RulesEvaluator,145+ Effect.gen(function* () {146+ const finishers = yield* Finishers;147+ const { policy } = datekit;148+149+ 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));161+162+/** The world a front-page test drives. */163+interface 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+}173+174+const 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+ );195+196+ const found = Context.get(197+ yield* Layer.build(198+ ProjectsMemory.pipe(Layer.provide(Layer.succeedContext(base)))199+ ),200+ Projects201+ );202+203+ const calls: string[] = [];204+205+ const counted = Projects.of({206+ create: (name) =>207+ Effect.suspend(() => {208+ calls.push(`create ${name}`);209+210+ return found.create(name);211+ }),212+ get: (name) =>213+ Effect.suspend(() => {214+ calls.push(`get ${name}`);215+216+ return found.get(name);217+ }),218+ });219+220+ const ports = Context.add(base, Projects, counted);221+ const config = yield* Effect.orDie(decodeEnv(fakeEnv()));222+223+ const { dispose, handler } = serve(224+ platformOn(config, Layer.succeedContext(ports))225+ );226+227+ yield* Effect.addFinalizer(() => Effect.promise(dispose));228+229+ 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);234+235+ 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+ });243+244+ 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);251+252+ yield* seeded(datekit).pipe(Effect.provideContext(ports));253+254+ return {255+ anyone: yield* rpcClient(handler),256+ calls: Effect.sync(() => [...calls]),257+ forget: Effect.sync(() => {258+ calls.length = 0;259+ }),260+ landAnswer,261+ };262+ });263+264+describe("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);270+271+ const world = yield* frontPageWorld;272+273+ yield* world.landAnswer;274+ yield* world.forget;275+276+ const listed = yield* world.anyone.listProjects({});277+ const bobs = yield* world.anyone.credits({ handle: bob });278+ const alices = yield* world.anyone.credits({ handle: alice });279+280+ 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
12323456788910111213141591011121314181516171819202122232425262728293031323 unmodified lines3637383940414243444 unmodified lines495051525354555657585960616263646566676869707172737475767778798010 unmodified lines919293947295969798994 unmodified lines104105106107851081091101111121139111411511611711811912012197122123124125126127128104105106129130131132109110111112113114115133134135136119120121122123137138139140141142143144145146147148149/** * `FrontPage` over D1: the open asks of every project in one query, read * from the rows `ProjectionD1` keeps (`tables.ts`), so no project wakes. * `FrontPage` over D1: the open asks of every project, the project list and * a person's credits, each in one query, read from the rows `ProjectionD1` * keeps (`tables.ts`), so no project wakes. * * An entry is what the anonymous viewer sees: an ask is takeable when no * live claim holds it, nothing it waits on is still open, and it is held for * nobody. Its `blockedBy` names only the asks it still waits on: one that * landed has left the front page. Newest asks come first. Every project's * posture reads `open` until visibility (W6) projects a posture change. * Until W5 514 adds its projects and credits tables to this module, * `projects()` lists every project the projection has applied events of * (its `cursor` rows), with its open asks and no landing time, so a call * that names no project (`status`, `today`) still reaches each one; and * `credits()` reads nothing. A failed read is a defect: the port's reads * cannot fail. * landed has left the front page. Newest asks come first, each with its * project's posture. Projects are listed by name, and a person's credits by * project, area and role: counts by role and area, never a score or a total * across roles. A failed read is a defect: the port's reads cannot fail. */import { Reserve } from "@repo/protocol/domain/ask";import type { FrontPageEntry } from "@repo/protocol/domain/front-page";import type { FrontPageEntry, ProjectListing,} from "@repo/protocol/domain/front-page";import { CreditSummary } from "@repo/protocol/domain/record";import { AskId, KindName, ProjectName } from "@repo/protocol/ids";import type { Handle } from "@repo/protocol/ids";import { Posture } from "@repo/protocol/posture";import { Effect, Layer, Schema } from "effect";import { SqlClient } from "effect/sql/SqlClient";
import { FrontPage } from "../front-page.ts";import type { FrontPageFilter } from "../front-page.ts";import { handleKey } from "./tables.ts";
const AskIds = Schema.fromJsonString(Schema.Array(AskId));
/** One row of the front page query. */3 unmodified lines claimed: Schema.Int, kind: KindName, /** The asks it waits on that are still on the front page. */ open_blockers: AskIds, posture: Posture, project: ProjectName, reserve: Schema.NullOr(Reserve), territory: Schema.NonEmptyString, want: Schema.NonEmptyString,4 unmodified linesconst decodeRows = Schema.decodeUnknownEffect(Schema.Array(EntryRow));
/** One row of the projects query. */const ProjectRow = Schema.Struct({ landed_at: Schema.NullOr(Schema.DateTimeUtcFromString), open_asks: Schema.Int, posture: Posture, project: ProjectName,});
type ProjectRow = typeof ProjectRow.Type;
const decodeProjectRows = Schema.decodeUnknownEffect(Schema.Array(ProjectRow));
const decodeCredits = Schema.decodeUnknownEffect(Schema.Array(CreditSummary));
const listingOf = (row: ProjectRow): ProjectListing => { const listing = { openAsks: row.open_asks, posture: row.posture, project: row.project, };
return row.landed_at === null ? listing : { ...listing, landedAt: row.landed_at };};
const entryOf = (row: EntryRow): FrontPageEntry => { const blockedBy = row.blocked_by.filter((ask) => row.open_blockers.includes(ask) );10 unmodified lines };
return { ask: row.reserve === null ? listing : { ...listing, reserve: row.reserve }, posture: "open", posture: row.posture, project: row.project, takeable: !claimed && blockedBy.length === 0 && row.reserve === null, };};4 unmodified lines Effect.gen(function* () { const sql = yield* SqlClient;
const entries = ({ kind, reserved }: FrontPageFilter) => sql`SELECT project, ask, kind, reserve, want, territory, claimed, blocked_by, sql`SELECT page.project, ask, kind, reserve, want, territory, claimed, blocked_by, (SELECT json_group_array(blocker.value) FROM json_each(page.blocked_by) AS blocker WHERE EXISTS ( SELECT 1 FROM front_page AS other WHERE other.project = page.project AND other.ask = blocker.value )) AS open_blockers )) AS open_blockers, COALESCE(listed.posture, 'open') AS posture FROM front_page AS page LEFT JOIN projects AS listed ON listed.project = page.project WHERE ${sql.and([ ...(kind === undefined ? [] : [sql`kind = ${kind}`]), ...(reserved === undefined ? [] : [sql`reserve = ${reserved}`]), ])} ORDER BY opened_at DESC, project, ask`.pipe( ORDER BY opened_at DESC, page.project, ask`.pipe( Effect.flatMap(decodeRows), Effect.map((rows) => rows.map(entryOf)), Effect.orDie );
const projects = () => sql`SELECT project, (SELECT COUNT(*) FROM front_page AS page WHERE page.project = cursor.project) AS open_asks FROM cursor sql`SELECT project, posture, open_asks, landed_at FROM projects ORDER BY project`.pipe( Effect.flatMap(decodeProjectRows), Effect.map((rows) => rows.map(({ open_asks, project }) => ({ openAsks: open_asks, posture: "open" as const, project, })) ), Effect.map((rows) => rows.map(listingOf)), Effect.orDie );
return FrontPage.of({ credits: () => Effect.succeed([]), entries, projects, }); // By the key the projection keeps: the handle as `sameHandle` compares it. const credits = (handle: Handle) => sql`SELECT project, area, role, count FROM credits WHERE handle_key = ${handleKey(handle)} ORDER BY project, area, role`.pipe( Effect.flatMap(decodeCredits), Effect.orDie );
return FrontPage.of({ credits, entries, projects }); }) );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, and9 unmodified lines30 */31 import { TypeId } from "@effect/sql-d1/D1Client";32 import type { D1Client } from "@effect/sql-d1/D1Client";33 import { ProjectEvent } from "@repo/protocol/domain/event";34+import type { LandingView } from "@repo/protocol/domain/landing";35+import { LedgerEntry } from "@repo/protocol/domain/visibility";36 import { ProjectName } from "@repo/protocol/ids";37 import type { AskId } from "@repo/protocol/ids";38 import { Array, DateTime, Effect, Layer, Order, Schema } from "effect";39 import { SqlClient } from "effect/sql/SqlClient";1 unmodified line41 import type { Statement } from "effect/sql/Statement";42 43 import type { OutboxRow } from "../project-store/rows.ts";44 import { Projection, ProjectedEvent, ProjectionFailed } from "../projection.ts";45+import { handleKey } from "./tables.ts";46 47 const decodeProjected = Schema.decodeUnknownEffect(48 Schema.toCodecJson(ProjectedEvent)49 );19 unmodified lines69 /** Each project, with the last event the rows carry for it. */70 const lastOf = (events: readonly ProjectedEvent[]) =>71 new Map(events.map(({ event, project }) => [project, event.seq]));72 73+/**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+ */80+const 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+ );88+89 export const ProjectionD1: Layer.Layer<Projection, never, SqlClient> =90 Layer.effect(91 Projection,92 Effect.gen(function* () {10 unmodified lines103 /** 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}`;106 77- /** 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);113 114+ 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`;117+118+ 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}`;121+122 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}`;125 126+ /**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+ );145+85- 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 lines160 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 });187+188+ return [listed, ...changes];189 };190 191 /** Moves the project's cursor on to `seq`, if it stands just before it. */192 const advance = (project: ProjectName, seq: number) =>71 unmodified linesmodified:packages/project/src/projection-d1/tables.ts+67 added-1 removed
10 unmodified lines11 * - `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 */17+import type { Handle } from "@repo/protocol/ids";18+19+/**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+ */24+export const handleKey = (handle: Handle): string => handle.toLowerCase();25+26 export 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 lines47 project TEXT PRIMARY KEY,48 seq INTEGER NOT NULL49 );50 `;51+52+/**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+ */72+export 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.75+76+-- 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).79+CREATE TABLE projects (80+ project TEXT PRIMARY KEY,81+ posture TEXT NOT NULL,82+ open_asks INTEGER NOT NULL,83+ landed_at TEXT84+);85+86+-- 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.90+CREATE 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+);98+99+-- 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.102+INSERT INTO projects (project, posture, open_asks, landed_at)103+SELECT cursor.project, 'open',104+ (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),105+ NULL106+FROM 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+ */8+import { describe, expect, it } from "@effect/vitest";9+import type { AskListing } from "@repo/protocol/domain/ask";10+import type { Credit } from "@repo/protocol/domain/credit";11+import { ProjectEvent } from "@repo/protocol/domain/event";12+import { LedgerEntry } from "@repo/protocol/domain/visibility";13+import {14+ AskId,15+ DecisionId,16+ Handle,17+ KindName,18+ LandedSha,19+ ProjectName,20+} from "@repo/protocol/ids";21+import { DateTime, Effect, Layer } from "effect";22+import { SqlClient } from "effect/sql/SqlClient";23+24+import { FrontPage } from "../src/front-page.ts";25+import { projectedRows } from "../src/outbox.ts";26+import type { OutboxRow } from "../src/project-store/rows.ts";27+import { FrontPageD1 } from "../src/projection-d1/front-page.ts";28+import { ProjectionD1 } from "../src/projection-d1/projection.ts";29+import { ProjectsCreditsDdl } from "../src/projection-d1/tables.ts";30+import { Projection } from "../src/projection.ts";31+import {32+ applied,33+ frontPageMigration,34+ migrated,35+ migration,36+ projectsMigration,37+} from "./projection-d1.fixtures.ts";38+39+const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(40+ Layer.provideMerge(migrated([frontPageMigration, projectsMigration]))41+);42+43+/** A database the front page's migration alone made, as W3 and W4 left it. */44+const beforeProjects = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(45+ Layer.provideMerge(migrated([frontPageMigration]))46+);47+48+const datekit = ProjectName.make("datekit");49+50+const burrow = ProjectName.make("burrow");51+52+const fix = KindName.make("fix");53+54+const parseIso = AskId.make("parse-iso");55+56+const weekStart = AskId.make("week-start");57+58+const formatTz = AskId.make("format-tz");59+60+const noAny = AskId.make("no-any");61+62+const bram = Handle.make("bram");63+64+const ines = Handle.make("ines-v");65+66+const okonkwo = Handle.make("okonkwo");67+68+const landing = LandedSha.make("a".repeat(40));69+70+const at = (minute: number) =>71+ DateTime.makeUnsafe(`2026-10-08T09:${String(minute).padStart(2, "0")}:00Z`);72+73+const listing = (ask: AskId, territory: string): AskListing => ({74+ ask,75+ blockedBy: [],76+ claimed: false,77+ kind: fix,78+ territory,79+ want: `${ask} works`,80+});81+82+/** One project's events, numbered from `first`, as outbox rows. */83+const 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+ );93+94+const opened =95+ (ask: AskListing, minute: number) =>96+ (seq: number): ProjectEvent =>97+ ProjectEvent.cases.AskOpened.make({ ask, at: at(minute), seq });98+99+const closedBy =100+ (ask: AskId) =>101+ (seq: number): ProjectEvent =>102+ ProjectEvent.cases.AskClosed.make({ ask, at: at(40), landing, seq });103+104+/** bram's answer to `ask` lands at `minute`, crediting `credits`, written with an agent. */105+const 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+ });122+123+/** The trailers on bram's landing of `parse-iso`. */124+const parseIsoCredits: readonly Credit[] = [125+ { handle: ines, role: "Asked-by" },126+ { handle: bram, role: "Signed-off-by" },127+ { handle: okonkwo, role: "Mentored-by" },128+];129+130+const apply = (batch: Effect.Effect<readonly OutboxRow[]>) =>131+ Effect.flatMap(batch, (each) =>132+ Projection.use((projection) => projection.apply(each))133+ );134+135+/** burrow with one ask opened. */136+const burrowRows = rows(burrow, 1, [opened(listing(noAny, "core"), 4)]);137+138+/** datekit with three asks opened and one landed; burrow with one opened. */139+const 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+);150+151+/** Every row of the projection's tables, to compare a replay against. */152+const tables = Effect.gen(function* () {153+ const sql = yield* SqlClient;154+155+ 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+});163+164+describe("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);170+171+ const front = yield* FrontPage;172+173+ 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+ );184+185+ 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);190+191+ const front = yield* FrontPage;192+193+ 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+ );208+209+ it.effect("never credits the agent an answer was written with", () =>210+ Effect.gen(function* () {211+ yield* apply(both);212+213+ const front = yield* FrontPage;214+215+ 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+ );223+224+ it.effect("changes nothing when the same rows come again", () =>225+ Effect.gen(function* () {226+ yield* apply(both);227+228+ const before = yield* tables;229+230+ yield* apply(both);231+ yield* apply(both);232+233+ expect(yield* tables).toStrictEqual(before);234+ }).pipe(Effect.provide(world))235+ );236+237+ it.effect("reads no credits for a person with no landings", () =>238+ Effect.gen(function* () {239+ yield* apply(both);240+241+ expect(242+ yield* FrontPage.use((front) => front.credits(Handle.make("dora")))243+ ).toStrictEqual([]);244+ }).pipe(Effect.provide(world))245+ );246+247+ it.effect("reads the migration the platform's D1 applies", () =>248+ Effect.gen(function* () {249+ expect(yield* migration(projectsMigration)).toBe(ProjectsCreditsDdl);250+ })251+ );252+253+ 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;258+259+ // 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')`;266+267+ yield* applied(projectsMigration);268+269+ const front = yield* FrontPage;270+271+ expect(yield* front.projects()).toStrictEqual([272+ { openAsks: 0, posture: "open", project: burrow },273+ { openAsks: 2, posture: "open", project: datekit },274+ ]);275+276+ yield* apply(rows(burrow, 3, [opened(listing(noAny, "core"), 5)]));277+278+ 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+ );284+285+ 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+ );308+309+ const front = yield* FrontPage;310+311+ 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+ ];316+317+ expect(yield* front.credits(bram)).toStrictEqual(counted);318+ expect(yield* front.credits(Handle.make("Bram"))).toStrictEqual(319+ counted320+ );321+ }).pipe(Effect.provide(world))322+ );323+324+ 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+ );346+347+ const front = yield* FrontPage;348+349+ 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+ );356+357+ 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+ );382+383+ const front = yield* FrontPage;384+385+ expect({386+ bram: yield* front.credits(bram),387+ ines: yield* front.credits(ines),388+ }).toStrictEqual({ bram: [], ines: [] });389+ }).pipe(Effect.provide(world))390+ );391+392+ 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);414+415+ const front = yield* FrontPage;416+417+ 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748/** * The platform's D1 database as the projection's tests make it: migration * files read from `apps/platform/migrations` and run statement by statement * on a fresh sqlite-node database in memory, as `wrangler d1 migrations * apply` runs them in order. */import { NodeServices } from "@effect/platform-node";import { SqliteClient } from "@effect/sql-sqlite-node";import { Effect, FileSystem, Layer, Path } from "effect";import { SqlClient } from "effect/sql/SqlClient";
/** The front page's migration (W3 309; `FrontPageDdl`). */export const frontPageMigration = "0001_front_page.sql";
/** The project list's and the credits' migration (W5 514; `ProjectsCreditsDdl`). */export const projectsMigration = "0004_projects_credits.sql";
/** A migration of the platform's D1 database, as its file holds it. */export const migration = (file: string) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path;
return yield* fs.readFileString( yield* path.fromFileUrl( new URL(`../../../apps/platform/migrations/${file}`, import.meta.url) ) ); }).pipe(Effect.provide(NodeServices.layer), Effect.orDie);
/** Runs a migration's statements in order. */export const applied = (file: string) => Effect.gen(function* () { const sql = yield* SqlClient;
for (const statement of (yield* migration(file)).split(";")) { if (statement.trim().length > 0) { yield* sql.unsafe(statement); } } }).pipe(Effect.orDie);
/** A fresh in-memory database each time, with `files` applied in order. */export const migrated = (files: readonly string[]) => Layer.effectDiscard(Effect.forEach(files, applied, { discard: true })).pipe( Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })), Layer.orDie );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 */7-import { NodeServices } from "@effect/platform-node";8-import { SqliteClient } from "@effect/sql-sqlite-node";7 import { describe, expect, it } from "@effect/vitest";8 import type { AskListing } from "@repo/protocol/domain/ask";9 import { ProjectEvent } from "@repo/protocol/domain/event";10 import type { FrontPageEntry } from "@repo/protocol/domain/front-page";3 unmodified lines14 KindName,15 LandedSha,16 ProjectName,17 } from "@repo/protocol/ids";20-import { DateTime, Effect, FileSystem, Layer, Path } from "effect";18+import { DateTime, Effect, Layer } from "effect";19 import { SqlClient } from "effect/sql/SqlClient";20 21 import { FrontPage } from "../src/front-page.ts";22 import type { FrontPageFilter } from "../src/front-page.ts";2 unmodified lines25 import { FrontPageD1 } from "../src/projection-d1/front-page.ts";26 import { ProjectionD1 } from "../src/projection-d1/projection.ts";27 import { FrontPageDdl } from "../src/projection-d1/tables.ts";28 import { Projection, ProjectionFailed } from "../src/projection.ts";29+import {30+ frontPageMigration,31+ migrated,32+ migration,33+ projectsMigration,34+} from "./projection-d1.fixtures.ts";35 32-/** The migration the platform's D1 database applies, as its file holds it. */33-const 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+ */41+const database = migrated([frontPageMigration, projectsMigration]);42 37- 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));46-47-/** A fresh in-memory database each time, with the migration file applied. */48-const database = Layer.effectDiscard(49- Effect.gen(function* () {50- const sql = yield* SqlClient;51-52- 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-);62-43 const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(44 Layer.provideMerge(database)45 );46 336 unmodified lines383 );384 385 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 );390 411- // 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