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.
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
Provenance
- Commit
6d721f1- Tree
45b8c8e- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
eebd79b
7 files changed+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.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+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+ */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, 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+/** The front page's migrations, read from the platform's own folder in order and run statement by statement. */74+const migrated = Layer.effectDiscard(75+ Effect.gen(function* () {76+ const fs = yield* FileSystem.FileSystem;77+ const path = yield* Path.Path;78+ const sql = yield* SqlClient;79+80+ 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+ );86+87+ 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+);99+100+/**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+ */104+const redOnMainGreenOnAnswers = Layer.succeed(105+ CheckRunner,106+ CheckRunner.of({107+ run: ({ at: where, lanes }) => {108+ const passed = CheckAt.guards.Tree(where);109+110+ 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+);126+127+/** At any commit, datekit's policy, holding the asks whose files the commit has. */128+const rules = Layer.effect(129+ RulesEvaluator,130+ Effect.gen(function* () {131+ const finishers = yield* Finishers;132+ const { policy } = datekit;133+134+ 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));146+147+/** The world a front-page test drives. */148+interface 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+}158+159+const 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+ );180+181+ const found = Context.get(182+ yield* Layer.build(183+ ProjectsMemory.pipe(Layer.provide(Layer.succeedContext(base)))184+ ),185+ Projects186+ );187+188+ const calls: string[] = [];189+190+ const counted = Projects.of({191+ create: (name) =>192+ Effect.suspend(() => {193+ calls.push(`create ${name}`);194+195+ return found.create(name);196+ }),197+ get: (name) =>198+ Effect.suspend(() => {199+ calls.push(`get ${name}`);200+201+ return found.get(name);202+ }),203+ });204+205+ const ports = Context.add(base, Projects, counted);206+ const config = yield* Effect.orDie(decodeEnv(fakeEnv()));207+208+ const { dispose, handler } = serve(209+ platformOn(config, Layer.succeedContext(ports))210+ );211+212+ yield* Effect.addFinalizer(() => Effect.promise(dispose));213+214+ 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);219+220+ 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+ });228+229+ 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);236+237+ yield* seeded(datekit).pipe(Effect.provideContext(ports));238+239+ return {240+ anyone: yield* rpcClient(handler),241+ calls: Effect.sync(() => [...calls]),242+ forget: Effect.sync(() => {243+ calls.length = 0;244+ }),245+ landAnswer,246+ };247+ });248+249+describe("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);255+256+ const world = yield* frontPageWorld;257+258+ yield* world.landAnswer;259+ yield* world.forget;260+261+ const listed = yield* world.anyone.listProjects({});262+ const bobs = yield* world.anyone.credits({ handle: bob });263+ const alices = yield* world.anyone.credits({ handle: alice });264+265+ 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
12323456788910111213141591011121314181516171819202122232425268 unmodified lines3536373839404142434 unmodified lines484950515253545556575859606162636465666768697071727374757677787910 unmodified lines909192937294959697984 unmodified lines103104105106851071081091101111129111311411511611711811912097121122123124125126127104105106128129130131109110111112113114115132133134135119120121122123136137138139140141142143144145146147148/** * `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";8 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 = ${handle.toLowerCase()} 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+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, 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";28 unmodified lines68 /** Each project, with the last event the rows carry for it. */69 const lastOf = (events: readonly ProjectedEvent[]) =>70 new Map(events.map(({ event, project }) => [project, event.seq]));71 72+/**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+ */79+const 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+ );87+88 export const ProjectionD1: Layer.Layer<Projection, never, SqlClient> =89 Layer.effect(90 Projection,91 Effect.gen(function* () {10 unmodified lines102 /** 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}`;105 77- /** 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);112 113+ 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`;116+117+ 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}`;120+121 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}`;124 125+ /**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+ );144+85- 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 lines159 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 });186+187+ return [listed, ...changes];188 };189 190 /** Moves the project's cursor on to `seq`, if it stands just before it. */191 const advance = (project: ProjectName, seq: number) =>71 unmodified linesmodified:packages/project/src/projection-d1/tables.ts+58 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 export 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 lines38 project TEXT PRIMARY KEY,39 seq INTEGER NOT NULL40 );41 `;42+43+/**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+ */63+export 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.66+67+-- 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).70+CREATE TABLE projects (71+ project TEXT PRIMARY KEY,72+ posture TEXT NOT NULL,73+ open_asks INTEGER NOT NULL,74+ landed_at TEXT75+);76+77+-- 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.81+CREATE 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+);89+90+-- 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.93+INSERT INTO projects (project, posture, open_asks, landed_at)94+SELECT cursor.project, 'open',95+ (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),96+ NULL97+FROM 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+ */8+import { NodeServices } from "@effect/platform-node";9+import { SqliteClient } from "@effect/sql-sqlite-node";10+import { describe, expect, it } from "@effect/vitest";11+import type { AskListing } from "@repo/protocol/domain/ask";12+import type { Credit } from "@repo/protocol/domain/credit";13+import { ProjectEvent } from "@repo/protocol/domain/event";14+import { LedgerEntry } from "@repo/protocol/domain/visibility";15+import {16+ AskId,17+ DecisionId,18+ Handle,19+ KindName,20+ LandedSha,21+ ProjectName,22+} from "@repo/protocol/ids";23+import { DateTime, Effect, FileSystem, Layer, Path } from "effect";24+import { SqlClient } from "effect/sql/SqlClient";25+26+import { FrontPage } from "../src/front-page.ts";27+import { projectedRows } from "../src/outbox.ts";28+import type { OutboxRow } from "../src/project-store/rows.ts";29+import { FrontPageD1 } from "../src/projection-d1/front-page.ts";30+import { ProjectionD1 } from "../src/projection-d1/projection.ts";31+import { ProjectsCreditsDdl } from "../src/projection-d1/tables.ts";32+import { Projection } from "../src/projection.ts";33+34+/** A migration of the platform's D1 database, as its file holds it. */35+const migration = (file: string) =>36+ Effect.gen(function* () {37+ const fs = yield* FileSystem.FileSystem;38+ const path = yield* Path.Path;39+40+ 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);46+47+/** Runs a migration's statements in order, as `wrangler d1 migrations apply` does. */48+const applied = (file: string) =>49+ Effect.gen(function* () {50+ const sql = yield* SqlClient;51+52+ 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);58+59+const frontPageMigration = "0001_front_page.sql";60+61+const projectsMigration = "0004_projects_credits.sql";62+63+/** A fresh in-memory database each time, with the projection's migrations applied. */64+const database = Layer.effectDiscard(65+ Effect.andThen(applied(frontPageMigration), applied(projectsMigration))66+).pipe(67+ Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),68+ Layer.orDie69+);70+71+const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(72+ Layer.provideMerge(database)73+);74+75+/** A database the front page's migration alone made, as W3 and W4 left it. */76+const 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+);84+85+const datekit = ProjectName.make("datekit");86+87+const burrow = ProjectName.make("burrow");88+89+const fix = KindName.make("fix");90+91+const parseIso = AskId.make("parse-iso");92+93+const weekStart = AskId.make("week-start");94+95+const formatTz = AskId.make("format-tz");96+97+const noAny = AskId.make("no-any");98+99+const bram = Handle.make("bram");100+101+const ines = Handle.make("ines-v");102+103+const okonkwo = Handle.make("okonkwo");104+105+const landing = LandedSha.make("a".repeat(40));106+107+const at = (minute: number) =>108+ DateTime.makeUnsafe(`2026-10-08T09:${String(minute).padStart(2, "0")}:00Z`);109+110+const listing = (ask: AskId, territory: string): AskListing => ({111+ ask,112+ blockedBy: [],113+ claimed: false,114+ kind: fix,115+ territory,116+ want: `${ask} works`,117+});118+119+/** One project's events, numbered from `first`, as outbox rows. */120+const 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+ );130+131+const opened =132+ (ask: AskListing, minute: number) =>133+ (seq: number): ProjectEvent =>134+ ProjectEvent.cases.AskOpened.make({ ask, at: at(minute), seq });135+136+const closedBy =137+ (ask: AskId) =>138+ (seq: number): ProjectEvent =>139+ ProjectEvent.cases.AskClosed.make({ ask, at: at(40), landing, seq });140+141+/** bram's answer to `ask` lands at `minute`, crediting `credits`, written with an agent. */142+const 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+ });159+160+/** The trailers on bram's landing of `parse-iso`. */161+const parseIsoCredits: readonly Credit[] = [162+ { handle: ines, role: "Asked-by" },163+ { handle: bram, role: "Signed-off-by" },164+ { handle: okonkwo, role: "Mentored-by" },165+];166+167+const apply = (batch: Effect.Effect<readonly OutboxRow[]>) =>168+ Effect.flatMap(batch, (each) =>169+ Projection.use((projection) => projection.apply(each))170+ );171+172+/** burrow with one ask opened. */173+const burrowRows = rows(burrow, 1, [opened(listing(noAny, "core"), 4)]);174+175+/** datekit with three asks opened and one landed; burrow with one opened. */176+const 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+);187+188+/** Every row of the projection's tables, to compare a replay against. */189+const tables = Effect.gen(function* () {190+ const sql = yield* SqlClient;191+192+ 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+});200+201+describe("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);207+208+ const front = yield* FrontPage;209+210+ 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+ );221+222+ 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);227+228+ const front = yield* FrontPage;229+230+ 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+ );245+246+ it.effect("never credits the agent an answer was written with", () =>247+ Effect.gen(function* () {248+ yield* apply(both);249+250+ const front = yield* FrontPage;251+252+ 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+ );260+261+ it.effect("changes nothing when the same rows come again", () =>262+ Effect.gen(function* () {263+ yield* apply(both);264+265+ const before = yield* tables;266+267+ yield* apply(both);268+ yield* apply(both);269+270+ expect(yield* tables).toStrictEqual(before);271+ }).pipe(Effect.provide(world))272+ );273+274+ it.effect("reads no credits for a person with no landings", () =>275+ Effect.gen(function* () {276+ yield* apply(both);277+278+ expect(279+ yield* FrontPage.use((front) => front.credits(Handle.make("dora")))280+ ).toStrictEqual([]);281+ }).pipe(Effect.provide(world))282+ );283+284+ it.effect("reads the migration the platform's D1 applies", () =>285+ Effect.gen(function* () {286+ expect(yield* migration(projectsMigration)).toBe(ProjectsCreditsDdl);287+ })288+ );289+290+ 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;295+296+ // 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')`;303+304+ yield* applied(projectsMigration);305+306+ const front = yield* FrontPage;307+308+ expect(yield* front.projects()).toStrictEqual([309+ { openAsks: 0, posture: "open", project: burrow },310+ { openAsks: 2, posture: "open", project: datekit },311+ ]);312+313+ yield* apply(rows(burrow, 3, [opened(listing(noAny, "core"), 5)]));314+315+ 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+ );321+322+ 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+ );345+346+ const front = yield* FrontPage;347+348+ 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+ ];353+354+ expect(yield* front.credits(bram)).toStrictEqual(counted);355+ expect(yield* front.credits(Handle.make("Bram"))).toStrictEqual(356+ counted357+ );358+ }).pipe(Effect.provide(world))359+ );360+361+ 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+ );383+384+ const front = yield* FrontPage;385+386+ 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+ );393+394+ 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);416+417+ const front = yield* FrontPage;418+419+ 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 */7 import { NodeServices } from "@effect/platform-node";8 import { SqliteClient } from "@effect/sql-sqlite-node";9 import { describe, expect, it } from "@effect/vitest";18 unmodified lines28 import { ProjectionD1 } from "../src/projection-d1/projection.ts";29 import { FrontPageDdl } from "../src/projection-d1/tables.ts";30 import { Projection, ProjectionFailed } from "../src/projection.ts";31 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;32+/** A migration the platform's D1 database applies, as its file holds it. */33+const migration = (file: string) =>34+ Effect.gen(function* () {35+ const fs = yield* FileSystem.FileSystem;36+ const path = yield* Path.Path;37 37- 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));44 47-/** 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+ */50 const database = Layer.effectDiscard(51 Effect.gen(function* () {52 const sql = yield* SqlClient;53 54+ 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 lines407 );408 409 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 );414 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.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