Make commit pages, project lists, whoami and the skills index answer fast
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- A commit's sides are read a window of 8 files at a time in path order, the 2 MiB text budget spent in that order, so the diff is the serial one byte for byte; no window is read once the budget runs out (a tree entry has no size, so a dropped side cannot be known before it is read: ASSUMPTION confirmed in the RepoHost schema). - The finished CommitDiff is kept in the code store under <repo>/commit/v1/<sha> without its landing, decoded with Schema when read and computed again when it no longer decodes; the landing is asked of the project's record on every call. - N7: a StandingPostures port (Context.Reference, default keeps nothing) that withStandingPosture reads first and writes back, with the same signature and requirements. Each entry carries the posture, `until` (the instant an accepted narrowing takes effect, nextMove in visibility/ledger.ts) and `seen` (the project's last event the read saw). - The public ledger carries no decision times, so the posture is read through a platform-only ProjectApi.standing() (on no contract or surface), filled by a new VisibilityPort member whose default answers open; its posture is the ledger's. - A D1 adapter beside the projection over migration 0005 (standing_postures); the projection deletes a project's row in the same batch as Landed, Decided and LedgerAppended, and a put lands only while the projection's cursor stands at or before `seen`, so a read taken before an event is never written back after it. The projection looks for the table until it finds it, so a database without 0005 projects as before; every adapter failure is a logged miss. - whoami: the callback asks status({}) once with the new token and keeps the handle in an HttpOnly __Host-handle cookie bound to the token by its SHA-256, with the session's Max-Age; whoami answers from it with no platform call, an old session asks once, and sign-out and any Unauthenticated expire both cookies. The token string's userId prefix is the provider's internal format, so it was not relied on; no platform route, no Rpc. - The agent-skills index reads each project's landed SHA from its record (head(), refs as before when none) and keeps the skill, or its absence, by that SHA in the code cache and store; no Cache API (a sign-off item, and the docs do not promise it on workers.dev). - smoke probes the web's /llms.txt, a seeded example's llms.txt and ask .md, and the skills index, each by path and content type, timed against a 500 ms budget that warns and never fails. - Tests: concurrent sides and serial-equal truncation, the kept diff (no blob read, landing asked, no landing stored, undecodable recomputed); the port's read-through, until, store failures; the D1 adapter, migration text, per-event clearing, the seen guard, a database before 0005; standing beside the ledger in the cartridge; the platform list's warm read of zero; whoami with no platform call, old sessions, a foreign handle, sign-out and Unauthenticated; the skills index reading files once per landed SHA; smoke's probe table and budget warning. - ASSUMPTION: D1 answers sqlite_master and json_each/json_extract as sqlite does.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
31 files+2366 added−261 removed
- tests:+1332 added−104 removed
- other:+1034 added−157 removed
Provenance
- Commit
cf4c123- Tree
7dd44c1- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
bbace25
31 files changed+2366 added−261 removed
added:apps/platform/migrations/0005_standing_postures.sql+16 added
1+-- Each listed project's standing posture, as a list last read it from the2+-- project's own record, kept by packages/project/src/projection-d1 (its3+-- tables.ts holds this text). A cache: a row lost costs one read. The4+-- projection deletes a project's row in the same write as any event that5+-- can move its posture, and a list writes a row only while the projection6+-- has applied no event of the project later than the one the read saw.7+8+CREATE TABLE standing_postures (9+ project TEXT PRIMARY KEY,10+ posture TEXT NOT NULL,11+ -- when the posture moves by the clock alone (ISO 8601), absent when only12+ -- an event moves it13+ moves_at TEXT,14+ -- the project's last event the read saw15+ seen INTEGER NOT NULL16+);modified:apps/platform/src/adapters/do-projects.ts+1 added
131 unmodified linesExpand all13213313413513613713813914050 unmodified lines131 unmodified linesExpand all setEnv: (caller, input) => assumingMade(on("setEnv", [caller, input])), showAsk: (caller, ask) => assumingMade(on("showAsk", [caller, ask])), showProposal: (caller, proposal) => assumingMade(on("showProposal", [caller, proposal])), standing: () => on("standing", []), status: (caller) => assumingMade(on("status", [caller])), submitAnswer: (caller, input) => assumingMade(on("submitAnswer", [caller, input])), today: (caller) => assumingMade(on("today", [caller])),50 unmodified linesmodified:apps/platform/src/ports.ts+6 added-3 removed
38 unmodified lines39 import { LanderIsogit } from "@repo/project/lander/isogit";40 import { FinishersFromChecks } from "@repo/project/project";41 import type { Projection } from "@repo/project/projection";42 import { FrontPageD1 } from "@repo/project/projection-d1/front-page";43+import { StandingPosturesD1 } from "@repo/project/projection-d1/postures";44 import { ProjectionD1 } from "@repo/project/projection-d1/projection";45 import { ProjectionMemory } from "@repo/project/projection/memory";46 import type { Projects } from "@repo/project/projects";47 import type { RulesEvaluator } from "@repo/rules/rules-evaluator";74 unmodified lines122 const corePorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>123 Layer.mergeAll(124 memoryFrontPage,125 // The D1 cartridge: the front page and its projection in125- // `FRONT_PAGE`, in place of the memory one above. Delete this entry126- // (and its imports) and the platform falls back to the memory front page.127- Layer.merge(FrontPageD1, ProjectionD1).pipe(126+ // `FRONT_PAGE`, in place of the memory one above, and each listed127+ // project's standing posture kept beside them (a `Context.Reference`:128+ // without it every list reads every project). Delete this entry (and129+ // its imports) and the platform falls back to the memory front page.130+ Layer.mergeAll(FrontPageD1, ProjectionD1, StandingPosturesD1).pipe(131 Layer.provide(D1Client.layer({ db: config.FRONT_PAGE })),132 Layer.orDie133 ),134 UpstreamRepoHost,46 unmodified linesmodified:apps/platform/src/project-calls.ts+1 added
137 unmodified lines138 scanForValues: callOf(MethodSchemas.scanForValues),139 setEnv: callOf(MethodSchemas.setEnv),140 showAsk: callOf(MethodSchemas.showAsk),141 showProposal: callOf(MethodSchemas.showProposal),142+ standing: callOf(MethodSchemas.standing),143 status: callOf(MethodSchemas.status),144 submitAnswer: callOf(MethodSchemas.submitAnswer),145 today: callOf(MethodSchemas.today),146 verdict: callOf(MethodSchemas.verdict),66 unmodified linesmodified:apps/platform/src/well-known.ts+125 added-23 removed
8 unmodified lines9 * forwards these paths unchanged, and the index's URLs are path-absolute, so10 * they work on either host.11 *12 * Projects come from the front page (`listProjects` reads the same), each13- * read at its landed SHA: the mirror ref the platform moves after each of14- * its own landings, or `main` for a project whose only landing15- * is its initializer's first push, which writes no mirror.13+ * read at its landed SHA as its own record says it (`ProjectApi.head`: its14+ * last landing, or its initializer's first push); for a project whose15+ * record names none, at its repo's refs: the mirror ref the platform moves16+ * after each of its own landings, or `main`.17+ *18+ * What a landed commit holds never changes, so each project's skill (or19+ * that it has none) is kept by its landed SHA, in the isolate's code cache20+ * and in the code store (`<repo>/skill/v<SKILL_VERSION>/<sha>`): a request21+ * costs one record read per project, and a file read only for a project22+ * whose main moved.23 */24 import { describedIn } from "@repo/agent-kit/generated-file";25 import {26 contributeDescription,1 unmodified line28 contributeSkillPaths,29 } from "@repo/agent-kit/project-skill";30 import { wellKnownSkills } from "@repo/agent-kit/well-known";31 import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";32+import { CodeStore } from "@repo/project/code-store";33+import { CodeCache } from "@repo/project/code/cache";34 import { FrontPage } from "@repo/project/front-page";35 import { landedRef } from "@repo/project/lander";36+import { Projects } from "@repo/project/projects";37 import { ProjectName, RepoName, RepoPath } from "@repo/protocol/ids";38+import type { CommitSha } from "@repo/protocol/ids";39 import type { Layer } from "effect";29-import { Array as Arr, Context, Effect, Option, Order, Schema } from "effect";40+import {41+ Array as Arr,42+ Cause,43+ Context,44+ Effect,45+ Option,46+ Order,47+ Schema,48+} from "effect";49 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";50 51 /** Where the index and the skills are served. */52 const ROOT = "/.well-known/agent-skills";24 unmodified lines77 /** The bytes as text, unless they are not UTF-8. */78 const textOf = (bytes: Uint8Array) =>79 Option.liftThrowable(() => utf8.decode(bytes))();80 81+/** The kept skill's version, in its key: it moves when what is kept changes. */82+const SKILL_VERSION = 1;83+84+/** A project's skill at a landed commit as the store keeps it: its text, or none. */85+const KeptSkill = Schema.fromJsonString(86+ Schema.Struct({ content: Schema.optionalKey(Schema.String) })87+);88+89+const decodeKept = Schema.decodeOption(KeptSkill);90+91+const encodeKept = Schema.encodeEffect(KeptSkill);92+93 /**63- * A project's contribute skill as it landed: none for a project never64- * made, one with no landing, or one whose landed tree has no such file.94+ * Where `project`'s main landed: as its record says, or, for a project whose95+ * record names none (or that the platform never made), at its repo's refs.96 */66-const landedSkill = (97+const landedOf = (98 project: ProjectName68-): Effect.Effect<Option.Option<string>, never, RepoHost> =>99+): Effect.Effect<Option.Option<CommitSha>, never, Projects | RepoHost> =>100 Effect.gen(function* () {70- const host = yield* RepoHost;71- const repo = RepoName.make(project);72- const refs = yield* host.refs(repo);101+ const projects = yield* Projects;102 74- const landed = Option.orElse(75- Option.fromUndefinedOr(refs.get(landedRef)),76- () => Option.fromUndefinedOr(refs.get(mainRef))103+ const recorded = yield* Effect.suspend(() => projects.get(project)).pipe(104+ Effect.flatMap((api) => api.head()),105+ Effect.map(({ landed }) => Option.fromUndefinedOr(landed)),106+ Effect.catchCause((cause) =>107+ Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.succeedNone108+ )109 );110 79- if (Option.isNone(landed)) {80- return Option.none();111+ if (Option.isSome(recorded)) {112+ return Option.some<CommitSha>(recorded.value);113 }114 115+ const host = yield* RepoHost;116+ const refs = yield* host.refs(RepoName.make(project));117+118+ return Option.orElse(Option.fromUndefinedOr(refs.get(landedRef)), () =>119+ Option.fromUndefinedOr(refs.get(mainRef))120+ );121+ }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeedNone));122+123+/** `project`'s skill file at `landed`, read from its repo: none when it has none. */124+const skillAt = (project: ProjectName, landed: CommitSha) =>125+ Effect.gen(function* () {126+ const host = yield* RepoHost;127 const [path] = contributeSkillPaths(project);128 129 const bytes = yield* host.readFile(86- repo,87- Revision.Commit({ sha: landed.value }),130+ RepoName.make(project),131+ Revision.Commit({ sha: landed }),132 RepoPath.make(path)133 );134 135 return Option.flatMap(bytes, textOf);136 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeedNone));137 138+/**139+ * `project`'s skill at `landed`: the isolate's cache first, then the code140+ * store, then its repo, whose answer is kept in both. A store that fails is141+ * a miss.142+ */143+const keptSkillAt = (project: ProjectName, landed: CommitSha) =>144+ Effect.gen(function* () {145+ const cache = yield* CodeCache;146+ const store = yield* CodeStore;147+ const key = `${RepoName.make(project)}/skill/v${SKILL_VERSION}/${landed}`;148+149+ return yield* cache.through(150+ key,151+ Effect.gen(function* () {152+ const kept = Option.flatMap(yield* store.get(key), decodeKept);153+154+ if (Option.isSome(kept)) {155+ return Option.fromUndefinedOr(kept.value.content);156+ }157+158+ const read = yield* skillAt(project, landed);159+160+ yield* encodeKept(161+ Option.match(read, {162+ onNone: () => ({}),163+ onSome: (content) => ({ content }),164+ })165+ ).pipe(166+ Effect.flatMap((text) => store.put(key, text)),167+ Effect.catch((error) =>168+ Effect.logWarning(`${project}'s skill was not kept`, error)169+ )170+ );171+172+ return read;173+ })174+ );175+ });176+177+/**178+ * A project's contribute skill as it landed: none for a project never179+ * made, one with no landing, or one whose landed tree has no such file.180+ */181+const landedSkill = (182+ project: ProjectName183+): Effect.Effect<Option.Option<string>, never, Projects | RepoHost> =>184+ Effect.flatMap(landedOf(project), (landed) =>185+ Option.match(landed, {186+ onNone: () => Effect.succeedNone,187+ onSome: (sha) => keptSkillAt(project, sha),188+ })189+ );190+191 const decodeProject = Schema.decodeUnknownOption(ProjectName);192 193 /** The index: every listed project's landed skill, by name. */194 const index = Effect.gen(function* () {56 unmodified lines251 * the router matched it.252 */253 export const agentSkills = (254 request: Request158-): Effect.Effect<Response, never, FrontPage | RepoHost> => {255+): Effect.Effect<Response, never, FrontPage | Projects | RepoHost> => {256 const { pathname } = new URL(request.url);257 258 if (pathname === INDEX) {259 return index;25 unmodified lines285 286 /**287 * `/.well-known/agent-skills/*` on the platform's router, for anyone: GET288 * and HEAD (the router serves HEAD as GET, without the body) through192- * `agentSkills`, with the front page and the repos taken once when the193- * router is built.289+ * `agentSkills`, with the front page, the projects, the repos and the290+ * code reads' cache and store taken once when the router is built (the291+ * last two are `Context.Reference`s: without them every request reads292+ * every file).293 */294 export const agentSkillRoutes: Layer.Layer<295 never,296 never,198- HttpRouter.HttpRouter | FrontPage | RepoHost297+ HttpRouter.HttpRouter | FrontPage | Projects | RepoHost298 > = HttpRouter.use((router) =>299 Effect.gen(function* () {300 const services = Context.make(FrontPage, yield* FrontPage).pipe(301+ Context.add(Projects, yield* Projects),202- Context.add(RepoHost, yield* RepoHost)302+ Context.add(RepoHost, yield* RepoHost),303+ Context.add(CodeCache, yield* CodeCache),304+ Context.add(CodeStore, yield* CodeStore)305 );306 307 yield* router.add("*", `${ROOT}/*`, (request) =>308 request.method !== "GET" && request.method !== "HEAD"11 unmodified linesmodified:apps/platform/test/do-projects.test.ts+1 added
194 unmodified lines195 showProposal: settled(196 "showProposal",197 api.showProposal(anyone, ProposalId.make("prop-000001"))198 ),199+ standing: settled("standing", api.standing()),200 status: settled("status", api.status(bob)),201 submitAnswer: settled(202 "submitAnswer",203 api.submitAnswer(bob, { ask: parseIso, base: sha, head: sha, requestId })84 unmodified linesmodified:apps/platform/test/front-page.test.ts+10 added-1 removed
22 unmodified lines23 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 { StandingPosturesD1 } from "@repo/project/projection-d1/postures";28 import { ProjectionD1 } from "@repo/project/projection-d1/projection";29 import { Projects } from "@repo/project/projects";30 import { ProjectsMemory } from "@repo/project/projects/memory";31 import type { Client } from "@repo/protocol/contracts";151 unmodified lines183 FrontPageD1,184 MemoryRateLimits(WorkerCaps),185 ProjectionD1,186 rules,187+ StandingPosturesD1,188 UpstreamRepoHost189 ).pipe(190 Layer.provideMerge(migrated),191 Layer.provideMerge(LanderIsogit),72 unmodified lines264 });265 266 describe("the project list and credits over the platform's /rpc", () => {267 it.effect(266- "after a landing, lists the project from D1, asking it only its posture, and its people's credits without calling a project",268+ "after a landing, lists the project from D1, asking it only its posture and only once, and its people's credits without calling a project",269 () =>270 Effect.gen(function* () {271 yield* advanceTo(noon);272 27 unmodified lines300 { landedAt: at(noon), openAsks: 1, posture: "open", project },301 ],302 },303 });304+305+ yield* world.forget;306+307+ // The posture read is kept in D1 beside the projection: the next308+ // list asks no project.309+ expect(yield* world.anyone.listProjects({})).toStrictEqual(listed);310+ expect(yield* world.calls).toStrictEqual([]);311 }).pipe(Effect.scoped)312 );313 });modified:apps/platform/test/home.test.ts+2 added-8 removed
45 unmodified lines46 get: (project) =>47 project === "datekit"48 ? Effect.succeed(49 untouchable<ProjectApi>("ProjectApi", {50- ledger: () =>51- Effect.succeed({52- entries: [],53- layers: [],54- posture: "openWithSealedEvidence",55- postureLabel: "Open with sealed evidence",56- project,57- }),50+ standing: () =>51+ Effect.succeed({ posture: "openWithSealedEvidence", seen: 1 }),52 })53 )54 : Effect.fail(new UnknownProject({ project })),55 })252 unmodified linesmodified:apps/platform/test/posture-listing.test.ts+76 added-36 removed
11 unmodified lines12 import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";13 import { FrontPageMemory } from "@repo/project/front-page/memory";14 import type { ProjectApi } from "@repo/project/project";15 import { Projects } from "@repo/project/projects";16+import { StandingPosturesMemory } from "@repo/project/standing-posture/memory";17 import { Contracts } from "@repo/protocol/contracts";18 import { ProjectName } from "@repo/protocol/ids";19 import {20 Anonymous,1 unmodified line22 CurrentPrincipal,23 } from "@repo/protocol/principal";24 import { UnknownProject } from "@repo/protocol/refusal";25 import { untouchable } from "@repo/testkit/untouchable";25-import { Effect, Layer } from "effect";26+import { Effect, Layer, Ref } from "effect";27 import { RpcTest } from "effect/rpc";28 29 import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";30 import { Handlers } from "../src/handlers.ts";1 unmodified line32 const datekit = ProjectName.make("datekit");33 34 const ghost = ProjectName.make("ghost");35 35-/** datekit's project, whose only answered read is its ledger, standing sealed. */36-const datekitApi = untouchable<ProjectApi>("ProjectApi", {37- ledger: () =>38- Effect.succeed({39- entries: [],40- layers: [],41- posture: "openWithSealedEvidence",42- postureLabel: "Open with sealed evidence",43- project: datekit,44- }),45-});36+/**37+ * datekit's project, whose only answered read is the posture its ledger38+ * shows, standing sealed; each read counted in `reads`.39+ */40+const datekitApi = (reads: Ref.Ref<number>) =>41+ untouchable<ProjectApi>("ProjectApi", {42+ standing: () =>43+ Effect.as(44+ Ref.update(reads, (count) => count + 1),45+ {46+ posture: "openWithSealedEvidence",47+ seen: 1,48+ }49+ ),50+ });51 52+/** The handlers over projects whose datekit counts its reads in `reads`. */53+const platformCounting = (reads: Ref.Ref<number>) =>47-const platform = Handlers.pipe(48- Layer.provide([49- Layer.succeed(50- Projects,51- Projects.of({52- create: () => Effect.die("a listing makes no project"),53- get: (project) =>54- project === datekit55- ? Effect.succeed(datekitApi)56- : Effect.fail(new UnknownProject({ project })),57- })58- ),59- FrontPageMemory.layer({60- credits: [],61- entries: [],62- projects: [63- { openAsks: 3, posture: "open", project: datekit },64- { openAsks: 0, posture: "openCore", project: ghost },65- ],66- }),67- MemoryRateLimits(WorkerCaps),68- EvidenceStoreMemory,69- Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),70- ])54+ Handlers.pipe(55+ Layer.provide([56+ Layer.succeed(57+ Projects,58+ Projects.of({59+ create: () => Effect.die("a listing makes no project"),60+ get: (project) =>61+ project === datekit62+ ? Effect.succeed(datekitApi(reads))63+ : Effect.fail(new UnknownProject({ project })),64+ })65+ ),66+ FrontPageMemory.layer({67+ credits: [],68+ entries: [],69+ projects: [70+ { openAsks: 3, posture: "open", project: datekit },71+ { openAsks: 0, posture: "openCore", project: ghost },72+ ],73+ }),74+ MemoryRateLimits(WorkerCaps),75+ EvidenceStoreMemory,76+ Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),77+ ])78+ );79+80+const platform = Layer.unwrap(81+ Effect.map(Ref.make(0), (reads) => platformCounting(reads))82 );83 84 const anonymous = Layer.succeed(Authenticated, (effect) =>85 Effect.provideService(effect, CurrentPrincipal, Anonymous.make({}))15 unmodified lines101 ],102 });103 }).pipe(Effect.provide(Layer.mergeAll(platform, anonymous)))104 );105+106+ it.effect(107+ "keeps each posture it read where the platform keeps them, so the next list reads none",108+ () =>109+ Effect.gen(function* () {110+ const reads = yield* Ref.make(0);111+112+ const [first, second] = yield* Effect.gen(function* () {113+ const anyone = yield* RpcTest.makeClient(Contracts);114+115+ return [116+ yield* anyone.listProjects({}),117+ yield* anyone.listProjects({}),118+ ] as const;119+ }).pipe(120+ Effect.provide(121+ Layer.mergeAll(122+ platformCounting(reads).pipe(123+ Layer.provide(StandingPosturesMemory)124+ ),125+ anonymous126+ )127+ )128+ );129+130+ expect(second).toStrictEqual(first);131+ expect(yield* Ref.get(reads)).toBe(1);132+ })133+ );134 });modified:apps/platform/test/well-known.test.ts+167 added-4 removed
4 unmodified lines5 * with the SHA-256 of that file's bytes, and each listed URL serves the file6 * as it landed. Anyone may read them, with no credential or a stale one.7 * Through the platform's fetch handler over the Node world, with real git;8 * and `agentSkills` itself over memory adapters, for a `main` that moved9- * past the landed mirror.9+ * past the landed mirror, and for skills kept by each project's landed10+ * commit, so the index reads a file only for a project whose main moved.11 */12 import { describe, expect, it } from "@effect/vitest";13 import { RefName, RepoHost } from "@repo/artifacts/repo-host";14 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";15 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";16+import { CodeStoreMemory } from "@repo/project/code-store/memory";17 import { FrontPageMemory } from "@repo/project/front-page/memory";18 import { landedRef } from "@repo/project/lander";19+import type { ProjectApi } from "@repo/project/project";20+import { Projects } from "@repo/project/projects";17-import { ProjectName, RepoName } from "@repo/protocol/ids";21+import { LandedSha, ProjectName, RepoName } from "@repo/protocol/ids";22+import { UnknownProject } from "@repo/protocol/refusal";23 import { gitClient } from "@repo/testkit/git-client";24+import { untouchable } from "@repo/testkit/untouchable";19-import { Effect, Layer, Option, Schema } from "effect";25+import { Effect, Layer, Option, Ref, Schema } from "effect";26 27 import { agentSkills } from "../src/well-known.ts";28 import { coreLoopWorld } from "./world.ts";29 154 unmodified lines184 agentSkills(new Request(`https://platform.test${path}`)),185 read186 );187 188+/** Projects the platform never made: each skill is read at its repo's refs. */189+const noneMade = Layer.succeed(190+ Projects,191+ Projects.of({192+ create: () => Effect.die("the skills make no project"),193+ get: (project) => Effect.fail(new UnknownProject({ project })),194+ })195+);196+197 describe(agentSkills, () => {198 it.effect(199 "reads each skill at the landed mirror, not at a main that moved past it",200 () =>51 unmodified lines252 credits: [],253 entries: [],254 projects: [listing(datekit)],255 })241- )256+ ).pipe(Layer.merge(noneMade))257 )258 )259 );260 });261+262+/** The memory store, each file read and each refs read counted. */263+const countedHost = (counts: Ref.Ref<{ files: number; refs: number }>) =>264+ Layer.effect(265+ RepoHost,266+ Effect.gen(function* () {267+ const host = yield* RepoHost;268+269+ return RepoHost.of({270+ ...host,271+ readFile: (name, rev, path) =>272+ Ref.update(counts, ({ files, refs }) => ({273+ files: files + 1,274+ refs,275+ })).pipe(Effect.andThen(host.readFile(name, rev, path))),276+ refs: (name) =>277+ Ref.update(counts, ({ files, refs }) => ({278+ files,279+ refs: refs + 1,280+ })).pipe(Effect.andThen(host.refs(name))),281+ });282+ })283+ ).pipe(Layer.provide(RepoHostMemory));284+285+/** Projects whose record says each one's main landed where `landed` holds. */286+const landedWhere = (landed: Ref.Ref<ReadonlyMap<ProjectName, LandedSha>>) =>287+ Layer.succeed(288+ Projects,289+ Projects.of({290+ create: () => Effect.die("the skills make no project"),291+ get: (project) =>292+ Effect.succeed(293+ untouchable<ProjectApi>("ProjectApi", {294+ head: () =>295+ Effect.map(Ref.get(landed), (all) =>296+ Option.match(Option.fromUndefinedOr(all.get(project)), {297+ onNone: () => ({}),298+ onSome: (sha) => ({ landed: sha }),299+ })300+ ),301+ })302+ ),303+ })304+ );305+306+describe("the agent skills index, kept by each project's landed commit", () => {307+ it.effect(308+ "reads each skill once while no main moves, and again only for a project whose main moved",309+ () =>310+ Effect.gen(function* () {311+ const counts = yield* Ref.make({ files: 0, refs: 0 });312+313+ const landed = yield* Ref.make<ReadonlyMap<ProjectName, LandedSha>>(314+ new Map()315+ );316+317+ yield* Effect.gen(function* () {318+ const host = yield* RepoHost;319+ const client = yield* gitClient(memoryFs());320+321+ const first = yield* client.commit("Land", [[skillPath, skill]]);322+323+ const moved = yield* client.commit(324+ "Land again",325+ [[skillPath, skill.replace("Answer one", "Answer any one")]],326+ [first]327+ );328+329+ const bare = yield* client.commit("Start burrow", [330+ ["README.md", "burrow\n"],331+ ]);332+333+ for (const [project, sha] of [334+ [datekit, moved],335+ [burrow, bare],336+ ] as const) {337+ yield* host.create(RepoName.make(project));338+ yield* host.push(RepoName.make(project), client.source, [339+ { from: Option.none(), ref: landedRef, to: sha },340+ ]);341+ }342+343+ yield* Ref.set(344+ landed,345+ new Map([346+ [datekit, LandedSha.make(first)],347+ [burrow, LandedSha.make(bare)],348+ ])349+ );350+351+ const described = Effect.map(352+ Effect.flatMap(353+ at("/.well-known/agent-skills/index.json"),354+ ({ body }) => Schema.decodeEffect(Index)(body)355+ ),356+ ({ skills }) => skills.map(({ description }) => description)357+ );358+359+ /** What one request read: files and refs, since the last. */360+ const reads = Effect.flatMap(361+ Ref.getAndSet(counts, { files: 0, refs: 0 }),362+ Effect.succeed363+ );364+365+ const once = yield* described;366+ const readOnce = yield* reads;367+ const twice = yield* described;368+ const readTwice = yield* reads;369+370+ yield* Ref.update(371+ landed,372+ (all) => new Map([...all, [datekit, LandedSha.make(moved)]])373+ );374+375+ const afterMove = yield* described;376+377+ expect({378+ afterMove,379+ once,380+ readAfterMove: yield* reads,381+ readOnce,382+ readTwice,383+ twice,384+ }).toStrictEqual({385+ afterMove: ["Answer any one of datekit's asks."],386+ once: ["Answer one of datekit's asks."],387+ readAfterMove: { files: 1, refs: 0 },388+ readOnce: { files: 2, refs: 0 },389+ readTwice: { files: 0, refs: 0 },390+ twice: ["Answer one of datekit's asks."],391+ });392+ }).pipe(393+ Effect.provide(394+ Layer.mergeAll(395+ countedHost(counts),396+ CodeStoreMemory,397+ landedWhere(landed),398+ FrontPageMemory.layer({399+ credits: [],400+ entries: [],401+ projects: [listing(burrow), listing(datekit)],402+ })403+ )404+ )405+ );406+ })407+ );408+});modified:apps/web/src/routes/auth/callback.ts+4 added-2 removed
1 import { createFileRoute } from "@tanstack/react-router";2 import { env } from "cloudflare:workers";3 4+import { serverClient } from "../../server/client.ts";5 import { callbackHandler } from "../../server/session.ts";6 7 // The platform sends the browser back here with a code, which becomes the7-// session cookie (src/server/session.ts).8+// session cookie, beside the handle the platform's `status` names for it9+// (src/server/session.ts).10 export const Route = createFileRoute("/auth/callback")({11 server: {12 handlers: {11- GET: callbackHandler(env),13+ GET: callbackHandler(env, (request) => serverClient(env, request)),14 },15 },16 });modified:apps/web/src/server/backend.ts+3 added-3 removed
17 unmodified lines18 import { Effect, Option } from "effect";19 20 import type { Backend } from "./rpc.ts";21 import {22- clearedCookie,22+ clearedCookies,23 credentialFrom,24 settingCookies,25 withCredential,26 } from "./session.ts";4 unmodified lines31 32 return new Request(new URL(`${pathname}${search}`, platformUrl), request);33 };34 35-/** `response` as it came, also expiring the session cookie. */35+/** `response` as it came, also expiring the session cookie and its kept handle. */36 const expiringSession = (response: Response) =>37 new Response(response.body, {38- headers: settingCookies(response.headers, [clearedCookie()]),38+ headers: settingCookies(response.headers, clearedCookies()),39 status: response.status,40 statusText: response.statusText,41 });42 40 unmodified linesmodified:apps/web/src/server/session.ts+134 added-22 removed
11 unmodified lines12 * Every forward to the platform (`backend.ts`) turns that cookie into the13 * HTTP `Authorization` header, the only credential the platform reads,14 * and drops the browser's own cookies and any `authorization` it15 * set: the browser never chooses the credential.16+ *17+ * Who is signed in is kept beside the token, in a second HttpOnly cookie18+ * (`HANDLE_COOKIE`): the callback asks the platform's `status` once, with19+ * the new token, and keeps the handle it names, bound to that token by its20+ * SHA-256, so `/auth/whoami` answers every page from the cookie with no21+ * platform call. The handle only shapes what a page shows: every read and22+ * write still carries the token, and the platform decides who the caller23+ * is. A handle kept for another token is not believed, a session from24+ * before the handle was kept asks `status` once, and sign-out and any25+ * `Unauthenticated` expire both cookies.26 */27 import { Brand } from "@repo/brand";28 import { Client } from "@repo/protocol/contracts";29+import { Handle as HandleSchema } from "@repo/protocol/ids";30 import type { Handle } from "@repo/protocol/ids";31 import { Data, Effect, Option, Redacted, Schema } from "effect";32 import type { Layer } from "effect";33 4 unmodified lines38 * shadow it.39 */40 export const SESSION_COOKIE = "__Host-session";41 42+/** The cookie the signed-in handle is kept in beside the session, for `whoami`. */43+export const HANDLE_COOKIE = "__Host-handle";44+45 /** The cookie a sign-in in progress waits in: its state, PKCE verifier and way back. */46 const SIGN_IN_COOKIE = "__Host-sign-in";47 48 /** How long a sign-in in progress waits for its callback: ten minutes. */82 unmodified lines131 132 /** The `Set-Cookie` value that ends the session now. */133 export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);134 135+/** The `Set-Cookie` values that end the session and forget its handle, now. */136+export const clearedCookies = () => [137+ clearedCookie(),138+ lockedCookie(HANDLE_COOKIE, "", 0),139+];140+141 const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);142 143 /** `headers`, also setting each of `cookies` (each its own `Set-Cookie` line). */144 export const settingCookies = (39 unmodified lines184 verifier,185 };186 });187 188+// --- The handle kept beside the session --------------------------------------189+190+/**191+ * How long a handle `whoami` learned for a session from before handles were192+ * kept is kept: the session's own lifetime is not known there. Bound to its193+ * token, it is never believed past the session.194+ */195+const HANDLE_LEARNED_SECONDS = 24 * 60 * 60;196+197+/** The token's SHA-256, in base64url: what binds a kept handle to its session. */198+const fingerprintOf = (token: string) =>199+ Effect.promise(() =>200+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))201+ ).pipe(202+ Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),203+ Effect.orDie204+ );205+206+/**207+ * The `Set-Cookie` value that keeps `handle` for the session `token`, for208+ * `maxAgeSeconds`: `<fingerprint>.<handle>` (a fingerprint is base64url,209+ * which has no `.`).210+ */211+const handleCookie = (token: string, handle: Handle, maxAgeSeconds: number) =>212+ Effect.map(fingerprintOf(token), (fingerprint) =>213+ lockedCookie(HANDLE_COOKIE, `${fingerprint}.${handle}`, maxAgeSeconds)214+ );215+216+const decodeHandle = Schema.decodeUnknownOption(HandleSchema);217+218+/** The handle kept for the session `token`, if the request carries one kept for it. */219+const keptHandle = (request: Request, token: string) =>220+ Effect.map(fingerprintOf(token), (fingerprint) =>221+ Option.flatMap(cookieValue(request, HANDLE_COOKIE), (value) => {222+ const at = value.indexOf(".");223+224+ return at > 0 && value.slice(0, at) === fingerprint225+ ? decodeHandle(value.slice(at + 1))226+ : Option.none();227+ })228+ );229+230+/** The handle the platform's `status` names for the session `token`, asked through `clientFor`. */231+const handleOf = (232+ clientFor: (request: Request) => Layer.Layer<Client>,233+ origin: string,234+ token: string235+) =>236+ Effect.service(Client).pipe(237+ Effect.flatMap((client) => client.status({})),238+ Effect.map(({ handle }) => handle),239+ Effect.provide(240+ clientFor(241+ new Request(`${origin}/auth/whoami`, {242+ headers: { cookie: `${SESSION_COOKIE}=${encodeURIComponent(token)}` },243+ })244+ )245+ )246+ );247+248 // --- Where the browser goes -------------------------------------------------249 250 /** The web's OAuth client id at `origin`: the URL of its metadata document. */251 const clientIdOf = (origin: string) => `${origin}${AUTH_PATHS.client}`;193 unmodified lines445 /**446 * `GET /auth/callback?code=…&state=…`: the state must be the one this447 * browser's sign-in cookie holds; then the code and its verifier go to the448 * platform's `/token`, and the token comes back only as the session cookie,369- * set to expire before the token does, on a 302 to the way back.449+ * set to expire before the token does, on a 302 to the way back. The450+ * platform's `status`, asked once with the new token through `clientFor`,451+ * names the handle kept beside it for as long; a `status` that fails keeps452+ * none, and the first `whoami` asks again.453 */454 export const callbackHandler =372- (env: Env) =>455+ (env: Env, clientFor: (request: Request) => Layer.Layer<Client>) =>456 ({ request }: Handled): Promise<Response> =>457 Effect.runPromise(458 Effect.gen(function* () {459 const here = new URL(request.url);17 unmodified lines477 origin: here.origin,478 verifier: pending.verifier,479 });480 481+ const token = Redacted.value(answer.access_token);482+ const lives = answer.expires_in - SESSION_MARGIN_SECONDS;483+484+ // Signing in never waits on this: whatever stops it keeps no handle.485+ const handle = yield* handleOf(clientFor, here.origin, token).pipe(486+ Effect.flatMap((named) => handleCookie(token, named, lives)),487+ Effect.map(Option.some),488+ Effect.catchCause(() => Effect.succeedNone)489+ );490+491 return redirect(returnPath(here.origin, pending.return), [399- sessionCookie(400- Redacted.value(answer.access_token),401- answer.expires_in - SESSION_MARGIN_SECONDS402- ),492+ sessionCookie(token, lives),493+ ...Option.toArray(handle),494 clearedSignIn(),495 ]);496 }).pipe(497 Effect.catchTag("SignInStopped", ({ reason, status }) =>3 unmodified lines501 );502 503 // --- Sign-out, who, and the client -------------------------------------------504 414-/** `POST` (or a plain link's `GET`) `/auth/signout`: the session cookie ends, and the browser goes home. */505+/** `POST` (or a plain link's `GET`) `/auth/signout`: the session and its kept handle end, and the browser goes home. */506 export const signOutHandler = (_handled: Handled): Response =>416- redirect("/", [clearedCookie()]);507+ redirect("/", clearedCookies());508 509 /** `/auth/whoami`'s answer: the handle signed in, or nothing (`features/auth/who.ts` reads it). */510 const whoAnswer = (511 who: { readonly handle?: Handle },3 unmodified lines515 headers: settingCookies({ "cache-control": "no-store" }, cookies),516 });517 518 /**428- * `GET /auth/whoami`: `{ handle }` as the platform's `status` names the429- * session's caller, or `{}`. With no session the platform is not asked. A430- * session the platform no longer knows answers `Unauthenticated` (the431- * backend asks again with no credential), so its cookie is expired here.519+ * `GET /auth/whoami`: `{ handle }` for the session, or `{}`, with no520+ * platform call when the handle kept beside the session was kept for its521+ * token. A session without one (from before handles were kept, or whose522+ * kept handle is another token's) asks the platform's `status` once and523+ * keeps the handle it names. With no session the platform is not asked,524+ * and a handle left over is expired. A session the platform no longer525+ * knows answers `Unauthenticated` (the backend asks again with no526+ * credential), so both cookies are expired here.527 */528 export const whoamiHandler =529 (clientFor: (request: Request) => Layer.Layer<Client>) =>530 ({ request }: Handled): Promise<Response> =>531 Effect.runPromise(532 Option.match(credentialFrom(request), {438- onNone: () => Effect.succeed(whoAnswer({})),439- onSome: () =>440- Effect.service(Client).pipe(441- Effect.flatMap((client) => client.status({})),442- Effect.map(({ handle }) => whoAnswer({ handle })),443- Effect.catchTag("Unauthenticated", () =>444- Effect.succeed(whoAnswer({}, [clearedCookie()]))445- ),446- Effect.orElseSucceed(() => whoAnswer({})),447- Effect.provide(clientFor(request))533+ onNone: () =>534+ Effect.succeed(535+ whoAnswer(536+ {},537+ Option.isSome(cookieValue(request, HANDLE_COOKIE))538+ ? [lockedCookie(HANDLE_COOKIE, "", 0)]539+ : []540+ )541 ),542+ onSome: (token) =>543+ Effect.flatMap(keptHandle(request, token), (kept) =>544+ Option.match(kept, {545+ onNone: () =>546+ handleOf(clientFor, new URL(request.url).origin, token).pipe(547+ Effect.flatMap((handle) =>548+ Effect.map(549+ handleCookie(token, handle, HANDLE_LEARNED_SECONDS),550+ (cookie) => whoAnswer({ handle }, [cookie])551+ )552+ ),553+ Effect.catchTag("Unauthenticated", () =>554+ Effect.succeed(whoAnswer({}, clearedCookies()))555+ ),556+ Effect.orElseSucceed(() => whoAnswer({}))557+ ),558+ onSome: (handle) => Effect.succeed(whoAnswer({ handle })),559+ })560+ ),561 })562 );563 564 /**20 unmodified linesmodified:apps/web/test/session.test.ts+187 added-13 removed
22 unmodified lines23 challengeOf,24 clearedCookie,25 clientMetadataHandler,26 credentialFrom,27+ HANDLE_COOKIE,28 pkce,29 SESSION_COOKIE,30 sessionCookie,31 signInHandler,326 unmodified lines358 expect([response.status, yield* textOf(response)]).toStrictEqual([359 200,360 "as anyone",361 ]);361- expect(expiriesOf(response)).toStrictEqual([[SESSION_COOKIE, true]]);362+ expect(expiriesOf(response)).toStrictEqual([363+ [SESSION_COOKIE, true],364+ [HANDLE_COOKIE, true],365+ ]);366 })367 );368 369 it.effect("carries the session on a GET too, at the platform's URL", () =>32 unmodified lines402 403 return { location, response, state };404 });405 402-/** Signs in, then comes back to the callback with `code` and the state sign-in sent, to a platform that answers `/token` with `answer`. */406+/** The protocol client a server route calls the platform with, through the production backend in process. */407+const clientOver = (env: Env) => (request: Request) =>408+ serverClientOver(backend)(env, request);409+410+/** A callback whose platform must not be reached. */411+const unreachableCallback = callbackHandler(412+ unreachable,413+ clientOver(unreachable)414+);415+416+/**417+ * Signs in, then comes back to the callback with `code` and the state sign-in418+ * sent, to a platform that answers `/token` with `answer` and `/rpc` (the419+ * callback's `status`) with `status`.420+ */421 const signInAndBack = (422 path: string,423 code: string,406- answer: () => Response = () => Response.json(TOKEN_ANSWER)424+ answer: () => Response = () => Response.json(TOKEN_ANSWER),425+ status: (request: Request) => Response = statusReply(STATUS_OF_INES)426 ) =>427 Effect.gen(function* () {428 const { location, state } = yield* signIn(path);410- const platform = recorder(answer);429 430+ const platform = recorder((request) =>431+ new URL(request.url).pathname.startsWith("/rpc")432+ ? status(request)433+ : answer()434+ );435+436+ const env = envWith(platform.fetch);437+438 const response = yield* Effect.promise(() =>413- callbackHandler(envWith(platform.fetch))({439+ callbackHandler(440+ env,441+ clientOver(env)442+ )({443 request: get(444 `/auth/callback?code=${code}&state=${location.searchParams.get("state") ?? ""}`,445 { cookie: state?.pair ?? "" }446 ),69 unmodified lines516 517 const [exchange, ...more] = seen;518 const form = new URLSearchParams(exchange?.body);519 491- expect(more).toStrictEqual([]);520+ // Then once, with the new token, `status`: the handle it names is521+ // kept beside the session, so no page asks the platform again.522+ expect(523+ more.map(({ authorization, body, cookie, url }) => [524+ new URL(url).pathname.replace(/\/$/u, ""),525+ authorization,526+ cookie,527+ body.includes('"tag":"status"'),528+ ])529+ ).toStrictEqual([530+ ["/rpc", `Bearer ${TOKEN_ANSWER.access_token}`, null, true],531+ ]);532 expect([533 exchange?.method,534 exchange?.url,535 exchange?.cookie,67 unmodified lines603 Effect.gen(function* () {604 const { state } = yield* signIn("/auth/signin");605 606 const response = yield* Effect.promise(() =>567- callbackHandler(unreachable)({607+ unreachableCallback({608 request: get("/auth/callback?code=c0de&state=forged", {609 cookie: state?.pair ?? "",610 }),611 })8 unmodified lines620 621 it.effect("answers 400 when the browser holds no sign-in in progress", () =>622 Effect.gen(function* () {623 const response = yield* Effect.promise(() =>584- callbackHandler(unreachable)({624+ unreachableCallback({625 request: get("/auth/callback?code=c0de&state=anything"),626 })627 );628 52 unmodified lines681 );682 });683 684 describe("sign-out", () => {645- it("goes home and expires the session cookie, by POST or by a plain link", () => {685+ it("goes home and expires the session and handle cookies, by POST or by a plain link", () => {686 const answers = ["POST", "GET"].map((method) => {687 const response = signOutHandler({688 request: new Request(`${WEB_URL}/auth/signout`, {689 headers: { cookie: `${SESSION_COOKIE}=tok123` },8 unmodified lines698 ];699 });700 701 expect(answers).toStrictEqual([662- [302, "/", [[SESSION_COOKIE, true]]],663- [302, "/", [[SESSION_COOKIE, true]]],702+ [703+ 302,704+ "/",705+ [706+ [SESSION_COOKIE, true],707+ [HANDLE_COOKIE, true],708+ ],709+ ],710+ [711+ 302,712+ "/",713+ [714+ [SESSION_COOKIE, true],715+ [HANDLE_COOKIE, true],716+ ],717+ ],718 ]);719 });720 });721 45 unmodified lines767 },768 ]);769 expect(response.headers.get("cache-control")).toBe("no-store");770 expect(yield* textOf(response)).toBe('{"handle":"ines-v"}');771+772+ // A session from before the handle was kept: asked once, then kept.773+ const kept = cookiesOf(response).filter(774+ ({ name }) => name === HANDLE_COOKIE775+ );776+777+ expect(778+ kept.map(({ attributes }) => lockedDown(attributes))779+ ).toStrictEqual([true]);780+781+ const again = yield* whoami(unreachable, {782+ cookie: [783+ `${SESSION_COOKIE}=tok123`,784+ ...kept.map(({ pair }) => pair),785+ ].join("; "),786+ });787+788+ expect(yield* textOf(again)).toBe('{"handle":"ines-v"}');789 })790 );791 792 it.effect(721- "answers {} and expires the cookie when the platform no longer knows the session",793+ "answers {} and expires both cookies when the platform no longer knows the session",794 () =>795 Effect.gen(function* () {796 const platform = recorder((request) =>797 request.headers.has("authorization")5 unmodified lines803 cookie: `${SESSION_COOKIE}=stale`,804 });805 806 expect(yield* textOf(response)).toBe("{}");735- expect(expiriesOf(response)).toStrictEqual([[SESSION_COOKIE, true]]);807+ expect(expiriesOf(response)).toStrictEqual([808+ [SESSION_COOKIE, true],809+ [HANDLE_COOKIE, true],810+ ]);811 })812 );813 });814 815+/** The `Cookie` header a browser sends back after `response`: each cookie it set and did not expire. */816+const sentBack = (response: Response) =>817+ cookiesOf(response)818+ .filter(({ attributes }) => !attributes.includes("max-age=0"))819+ .map(({ pair }) => pair)820+ .join("; ");821+822+describe("the handle kept beside the session", () => {823+ it.effect(824+ "after a sign-in, answers whoami with no call to the platform",825+ () =>826+ Effect.gen(function* () {827+ const { response } = yield* signInAndBack("/auth/signin", "c0de");828+ const who = yield* whoami(unreachable, { cookie: sentBack(response) });829+830+ expect(yield* textOf(who)).toBe('{"handle":"ines-v"}');831+ expect(who.headers.getSetCookie()).toStrictEqual([]);832+ })833+ );834+835+ it.effect(836+ "is a __Host- cookie the page's JavaScript never reads, living as long as the session",837+ () =>838+ Effect.gen(function* () {839+ const { response } = yield* signInAndBack("/auth/signin", "c0de");840+ const cookies = cookiesOf(response);841+ const session = cookies.find(({ name }) => name === SESSION_COOKIE);842+ const handle = cookies.find(({ name }) => name === HANDLE_COOKIE);843+844+ expect({845+ host: HANDLE_COOKIE.startsWith("__Host-"),846+ lives: maxAgeOf(handle?.attributes ?? []),847+ lockedDown: lockedDown(handle?.attributes),848+ token: handle?.value.includes("tok-from-platform"),849+ }).toStrictEqual({850+ host: true,851+ lives: maxAgeOf(session?.attributes ?? []),852+ lockedDown: true,853+ token: false,854+ });855+ })856+ );857+858+ it.effect(859+ "is not kept when the platform names no one at sign-in, and the session still starts",860+ () =>861+ Effect.gen(function* () {862+ const { response } = yield* signInAndBack(863+ "/auth/signin",864+ "c0de",865+ () => Response.json(TOKEN_ANSWER),866+ () => new Response("down", { status: 503 })867+ );868+869+ expect(870+ cookiesOf(response)871+ .map(({ name }) => name)872+ .filter((name) => name !== "__Host-sign-in")873+ ).toStrictEqual([SESSION_COOKIE]);874+ })875+ );876+877+ it.effect("is not believed for another session: the platform is asked", () =>878+ Effect.gen(function* () {879+ const { response } = yield* signInAndBack("/auth/signin", "c0de");880+881+ const handle = cookiesOf(response).find(882+ ({ name }) => name === HANDLE_COOKIE883+ );884+885+ const platform = recorder(statusReply(STATUS_OF_INES));886+887+ const who = yield* whoami(envWith(platform.fetch), {888+ cookie: `${SESSION_COOKIE}=another-token; ${handle?.pair ?? ""}`,889+ });890+891+ expect(yield* textOf(who)).toBe('{"handle":"ines-v"}');892+ expect(893+ (yield* platform.seen).map(({ authorization }) => authorization)894+ ).toStrictEqual(["Bearer another-token"]);895+ })896+ );897+898+ it.effect("is expired, unread, once no session is left", () =>899+ Effect.gen(function* () {900+ const { response } = yield* signInAndBack("/auth/signin", "c0de");901+902+ const handle = cookiesOf(response).find(903+ ({ name }) => name === HANDLE_COOKIE904+ );905+906+ const who = yield* whoami(unreachable, { cookie: handle?.pair ?? "" });907+908+ expect(yield* textOf(who)).toBe("{}");909+ expect(expiriesOf(who)).toStrictEqual([[HANDLE_COOKIE, true]]);910+ })911+ );912+});913+914 /** A JSON object, read as data. */915 const decodeDocument = Schema.decodeUnknownEffect(916 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))917 );95 unmodified linesmodified:infra/smoke.ts+110 added-15 removed
15 unmodified lines16 * names its MCP endpoint (`/mcp`) and the CLI's `install.sh`;17 * 7. `web-front-page`: the web's `GET /` answers 200 with HTML;18 * 8. `web-llms-txt`: the web's `GET /llms.txt` answers 200 with Markdown,19 * which it builds from the platform's project list, so only a web that20- * reaches the platform through its service binding passes.20+ * reaches the platform through its service binding passes;21+ * 9. `web-project-llms-txt`: a seeded example's `llms.txt` on the web22+ * answers 200 with Markdown;23+ * 10. `web-ask-md`: one of the seeded example's asks as Markdown answers 200;24+ * 11. `web-agent-skills`: the web's `/.well-known/agent-skills/index.json`25+ * answers 200 with JSON.26 *22- * The web's two run when smoke knows where the web lives: bootstrap's23- * workers.dev record, or `--web-url`.27+ * The web's probes run when smoke knows where the web lives: bootstrap's28+ * workers.dev record, or `--web-url`. The agent surfaces among them29+ * (`agentProbes`, 8 to 11) are what an agent reads first, so each is timed30+ * against `AGENT_BUDGET_MS`: one over it is a warning line, never a failure,31+ * since a cold isolate's first answer is slower than the rest.32 *33 * A probe the platform answers with its own failure (a server error, or an34 * RPC defect) asks again for up to `settling`, as a fresh deploy gives35 * those for its first seconds; any other wrong answer fails it at once.33 unmodified lines69 "platform-root",70 ] as const;71 72 /** The web's probes, run after the platform's when smoke has the web's origin. */65-export const webProbes = ["web-front-page", "web-llms-txt"] as const;73+export const webProbes = [74+ "web-front-page",75+ "web-llms-txt",76+ "web-project-llms-txt",77+ "web-ask-md",78+ "web-agent-skills",79+] as const;80 81+/** How long an agent surface may take to answer before smoke warns: 500 ms. */82+export const AGENT_BUDGET_MS = 500;83+84+/** An example every seeded stage holds, and one of its asks. */85+const SEEDED = { ask: "format-ordinal", project: "datekit" } as const;86+87+/** The agent surfaces on the web smoke reads, each by its path and the media type it answers with. */88+export const agentProbes = [89+ { contentType: "text/markdown", path: "/llms.txt", probe: "web-llms-txt" },90+ {91+ contentType: "text/markdown",92+ path: `/${SEEDED.project}/llms.txt`,93+ probe: "web-project-llms-txt",94+ },95+ {96+ contentType: "text/markdown",97+ path: `/${SEEDED.project}/asks/${SEEDED.ask}.md`,98+ probe: "web-ask-md",99+ },100+ {101+ contentType: "application/json",102+ path: "/.well-known/agent-skills/index.json",103+ probe: "web-agent-skills",104+ },105+] as const satisfies readonly {106+ readonly contentType: string;107+ readonly path: string;108+ readonly probe: (typeof webProbes)[number];109+}[];110+111 /** Every probe, in the order smoke runs them. */112 export const probes = [...platformProbes, ...webProbes] as const;113 114 export const Probe = Schema.Literals(probes);33 unmodified lines148 return `${failed} failed at ${this.origin}`;149 }150 }151 108-/** A passing run: the stage `/health` named, and how long each probe took. */152+/**153+ * A passing run: the stage `/health` named, how long each probe took154+ * (against its budget, when it has one), and a line for each probe over it.155+ */156 export interface SmokeReport {157 readonly origin: string;158 readonly stage: string;159 readonly probes: readonly {160 readonly probe: Probe;161 readonly elapsedMs: number;162+ readonly budgetMs?: number;163 }[];164+ readonly warnings: readonly string[];165 }166 167 /**168 * Why one probe failed, in a line a person reads. A transient miss is the270 unmodified lines439 Effect.asVoid440 );441 };442 443+/** An agent surface on the web: 200, with the media type it answers with. */444+const agentSurface = (445+ web: string,446+ { contentType, path }: (typeof agentProbes)[number]447+) => {448+ const label = `GET ${path} on the web`;449+450+ return send(label, HttpClientRequest.get(`${web}${path}`)).pipe(451+ Effect.flatMap(statusIs(label, 200, notServingYet)),452+ Effect.flatMap(typeIs(label, contentType, contentType))453+ );454+};455+456 /**457 * The web's `/llms.txt`: Markdown that opens with its title. The web answers458 * 503 when the platform does not, so a 200 is the service binding working.459 */398-const webLlmsTxt = (web: string) => {460+const webLlmsTxt = (web: string, probe: (typeof agentProbes)[number]) => {461 const label = "GET /llms.txt on the web";462 401- return send(label, HttpClientRequest.get(`${web}/llms.txt`)).pipe(402- Effect.flatMap(statusIs(label, 200, notServingYet)),403- Effect.flatMap(typeIs(label, "text/markdown", "Markdown")),463+ return agentSurface(web, probe).pipe(464 Effect.flatMap(({ text }) =>465 text.startsWith("# ")466 ? Effect.void467 : Effect.fail(52 unmodified lines520 health(origin, Option.fromUndefinedOr(options.stage)),521 settling522 );523 524+ const { web } = options;525+526 const rest = yield* Effect.forEach(527 [528 ["oauth-metadata", oauthMetadata(origin)],529 ["mcp-needs-credential", mcpNeedsCredential(origin)],530 ["anonymous-unknown-project", anonymousUnknownProject(origin)],531 ["missing-repo-404", missingRepo(origin)],532 ["platform-root", platformRoot(origin)],471- ...(options.web === undefined533+ ...(web === undefined534 ? []535 : ([474- ["web-front-page", webFrontPage(options.web)],475- ["web-llms-txt", webLlmsTxt(options.web)],536+ ["web-front-page", webFrontPage(web)],537+ ...agentProbes.map(538+ (agent) =>539+ [540+ agent.probe,541+ agent.probe === "web-llms-txt"542+ ? webLlmsTxt(web, agent)543+ : Effect.asVoid(agentSurface(web, agent)),544+ ] as const545+ ),546 ] as const)),547 ] as const,548 ([probe, run]) => timed(probe, run, settling)549 );14 unmodified lines564 if (Result.isFailure(first.outcome) || failures.length > 0) {565 return yield* new SmokeFailed({ failures, origin });566 }567 568+ const budgeted = new Set<Probe>(agentProbes.map(({ probe }) => probe));569+570+ const timings = runs.map(({ elapsedMs, probe }) =>571+ budgeted.has(probe)572+ ? { budgetMs: AGENT_BUDGET_MS, elapsedMs, probe }573+ : { elapsedMs, probe }574+ );575+576 return {577 origin,500- probes: runs.map(({ elapsedMs, probe }) => ({ elapsedMs, probe })),578+ probes: timings,579 stage: first.outcome.success,580+ warnings: timings.flatMap(({ budgetMs, elapsedMs, probe }) =>581+ budgetMs !== undefined && elapsedMs > budgetMs582+ ? [583+ `${probe} answered in ${elapsedMs} ms, over its ${budgetMs} ms budget`,584+ ]585+ : []586+ ),587 };588 });589 590 /** Neither `--url` nor bootstrap's record says where the stage lives. */73 unmodified lines664 );665 666 yield* Effect.forEach(667 report.probes,583- ({ elapsedMs, probe }) =>584- Console.log(`smoke ${stage}: ${probe} passed in ${elapsedMs} ms`),668+ ({ budgetMs, elapsedMs, probe }) =>669+ Console.log(670+ `smoke ${stage}: ${probe} passed in ${elapsedMs} ms${671+ budgetMs === undefined ? "" : ` (budget ${budgetMs} ms)`672+ }`673+ ),674 { discard: true }675 );676+677+ yield* Effect.forEach(678+ report.warnings,679+ (line) => Console.warn(`smoke ${stage}: warning: ${line}`),680+ { discard: true }681+ );682 }).pipe(Effect.provide(FetchHttpClient.layer));modified:packages/config/test/smoke.test.ts+136 added-13 removed
6 unmodified lines7 HttpServerRequest,8 HttpServerResponse,9 } from "effect/http";10 11+import { AGENT_BUDGET_MS, agentProbes } from "../../../infra/smoke.ts";12 import { NoStage, UnknownStage } from "../../../infra/stages.ts";13 import {14 main,15 NoOrigin,3 unmodified lines19 SmokeFailed,20 webProbes,21 } from "../../../scripts/smoke.ts";22 22-/** What the fake platform answers one request with. */23+/** What the fake platform answers one request with, after `delayMs` when given. */24 interface Reply {25 readonly status: number;26 readonly body?: string;27 readonly contentType?: string;28+ readonly delayMs?: number;29 }30 31 /** A request as the fake platform sees it. */32 interface Seen {109 unmodified lines142 method: request.method,143 path: url.pathname,144 });145 146+ if (reply.delayMs !== undefined) {147+ yield* Effect.sleep(`${reply.delayMs} millis`);148+ }149+150 return reply.body === undefined151 ? HttpServerResponse.empty({ status: reply.status })152 : HttpServerResponse.text(reply.body, {153 contentType: reply.contentType ?? "application/json",155 unmodified lines309 );310 });311 312 /**307- * The web as smoke expects to find it: its front page renders, and308- * its `/llms.txt` answers with the Markdown it builds from the platform's309- * project list, which only a web that reaches the platform can.313+ * The web as smoke expects to find it: its front page renders, its314+ * `/llms.txt` answers with the Markdown it builds from the platform's315+ * project list, which only a web that reaches the platform can, and so do316+ * a seeded example's `llms.txt` and ask, and the agent skills' index.317 */318 const healthyWeb = ({ method, path }: Seen): Reply => {319 if (method === "GET" && path === "/") {320 return {10 unmodified lines331 status: 200,332 };333 }334 335+ if (336+ method === "GET" &&337+ (path === "/datekit/llms.txt" || path === "/datekit/asks/format-ordinal.md")338+ ) {339+ return {340+ body: "# datekit\n",341+ contentType: "text/markdown; charset=utf-8",342+ status: 200,343+ };344+ }345+346+ if (method === "GET" && path === "/.well-known/agent-skills/index.json") {347+ return {348+ body: '{"skills":[]}',349+ contentType: "application/json",350+ status: 200,351+ };352+ }353+354 return { status: 404 };355 };356 357 describe("smoke against a stage's web", () => {7 unmodified lines365 366 expect(report.probes.map(({ probe }) => probe)).toStrictEqual([367 ...probes,368 ]);343- expect(webProbes).toStrictEqual(["web-front-page", "web-llms-txt"]);369+ expect(webProbes).toStrictEqual([370+ "web-front-page",371+ "web-llms-txt",372+ "web-project-llms-txt",373+ "web-ask-md",374+ "web-agent-skills",375+ ]);376+ expect(report.warnings).toStrictEqual([]);377 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))378 );379 380+ it("probes each agent surface by its path and content type, against a 500 ms budget", () => {381+ expect({ agentProbes, budget: AGENT_BUDGET_MS }).toStrictEqual({382+ agentProbes: [383+ {384+ contentType: "text/markdown",385+ path: "/llms.txt",386+ probe: "web-llms-txt",387+ },388+ {389+ contentType: "text/markdown",390+ path: "/datekit/llms.txt",391+ probe: "web-project-llms-txt",392+ },393+ {394+ contentType: "text/markdown",395+ path: "/datekit/asks/format-ordinal.md",396+ probe: "web-ask-md",397+ },398+ {399+ contentType: "application/json",400+ path: "/.well-known/agent-skills/index.json",401+ probe: "web-agent-skills",402+ },403+ ],404+ budget: 500,405+ });406+ });407+408+ it.live(409+ "warns, and still passes, when an agent surface answers past its budget",410+ () =>411+ Effect.gen(function* () {412+ const origin = yield* fakePlatform(healthy);413+414+ const web = yield* fakePlatform((seen) =>415+ seen.path === "/.well-known/agent-skills/index.json"416+ ? { ...healthyWeb(seen), delayMs: AGENT_BUDGET_MS + 100 }417+ : healthyWeb(seen)418+ );419+420+ const report = yield* smoke(origin, { web });421+422+ expect({423+ budgets: report.probes.flatMap(({ budgetMs, probe }) =>424+ budgetMs === undefined ? [] : [[probe, budgetMs]]425+ ),426+ probes: report.probes.map(({ probe }) => probe),427+ warnings: report.warnings.map((line) =>428+ line.replace(/\d+ ms,/u, "N ms,")429+ ),430+ }).toStrictEqual({431+ budgets: [432+ ["web-llms-txt", 500],433+ ["web-project-llms-txt", 500],434+ ["web-ask-md", 500],435+ ["web-agent-skills", 500],436+ ],437+ probes: [...probes],438+ warnings: [439+ "web-agent-skills answered in N ms, over its 500 ms budget",440+ ],441+ });442+ }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))443+ );444+445 // Live on dev-oscabriel: smoke ran 4 s after the web Worker's first446 // deploy, and its new workers.dev hostname answered 404 to both probes; a447 // run seconds later passed both.448 it.live(449 "asks the web again while a first deploy's hostname answers 404, and passes once it settles",450 () =>451 Effect.gen(function* () {452 const origin = yield* fakePlatform(healthy);355- const asked = { front: 0, llms: 0 };453+ const asked = new Map<string, number>();454 455 const web = yield* fakePlatform((seen) => {358- const count =359- seen.path === "/" ? (asked.front += 1) : (asked.llms += 1);456+ const count = (asked.get(seen.path) ?? 0) + 1;457 458+ asked.set(seen.path, count);459+460 return count <= 2 ? { status: 404 } : healthyWeb(seen);461 });462 463 const report = yield* smoke(origin, { settling: "10 seconds", web });464 465 expect({367- asked,466+ asked: Object.fromEntries(asked),467 probes: report.probes.map(({ probe }) => probe),369- }).toStrictEqual({ asked: { front: 3, llms: 3 }, probes: [...probes] });370- }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))468+ }).toStrictEqual({469+ asked: {470+ "/": 3,471+ "/.well-known/agent-skills/index.json": 3,472+ "/datekit/asks/format-ordinal.md": 3,473+ "/datekit/llms.txt": 3,474+ "/llms.txt": 3,475+ },476+ probes: [...probes],477+ });478+ }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)),479+ // Five paths, each asked three times a second apart.480+ 30_000481 );482 483 it.live(484 "fails the web's probes when its front page is not HTML and its /llms.txt cannot reach the platform",25 unmodified lines510 {511 probe: "web-llms-txt",512 reason: "GET /llms.txt on the web answered 503, not 200",513 },514+ {515+ probe: "web-project-llms-txt",516+ reason:517+ "GET /datekit/llms.txt on the web answered application/json, not text/markdown",518+ },519+ {520+ probe: "web-ask-md",521+ reason:522+ "GET /datekit/asks/format-ordinal.md on the web answered application/json, not text/markdown",523+ },524 ]);525 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))526 );527 });118 unmodified lines646 647 it.live("probes the web at --web-url, and only there, beside --url", () =>648 Effect.gen(function* () {649 const origin = yield* fakePlatform(healthy);530- // A web that answers, wrongly: JSON where a page and Markdown belong.650+ // A web that answers, wrongly: JSON where a page and Markdown belong651+ // (only the agent skills' index is JSON).652 const web = yield* fakePlatform(() => ({ body: "{}", status: 200 }));653 654 yield* main(["--stage", "dev-oscabriel", "--url", origin]);655 4 unmodified lines660 expect(661 Schema.is(SmokeFailed)(failed)662 ? failed.failures.map(({ probe }) => probe)663 : []543- ).toStrictEqual([...webProbes]);664+ ).toStrictEqual(665+ webProbes.filter((probe) => probe !== "web-agent-skills")666+ );667 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))668 );669 670 it("says to bootstrap first when neither --url nor bootstrap's record names the origin", () => {10 unmodified linesmodified:packages/project/src/code/commit.ts+154 added-47 removed
2 unmodified lines3 * against the empty tree), through `treeDiff` (`@repo/git/tree-diff`): each4 * file's status, both blob ids, whether it is binary, and its old and new5 * text. At most 300 files and 2 MiB of text in all: past 300 files every6 * file is a path only, and once the text runs past 2 MiB the files after7- * it are; either way the diff says it is `truncated`. The list of changes8- * is kept by the commit's id; the landing is asked for on every call.7+ * it are; either way the diff says it is `truncated`.8+ *9+ * Each file's two sides are read `SIDES_AT_ONCE` files at a time, in path10+ * order, and the budget is spent in that order, so the diff is the one a11+ * read of one file after another gives. A tree entry carries no size, so12+ * a side the budget drops cannot be known before it is read: once the13+ * budget runs out no further window is read, and at most one window's14+ * reads go unused.15+ *16+ * What a commit changed never changes, so the finished diff is kept in the17+ * code store by its repo and id (`commitKey`), without its landing: the18+ * landing is asked of the project's record on every call, so a later19+ * landing shows at once and the store holds none (principle 7). A kept20+ * value that no longer decodes is computed again; the list of changes is21+ * also kept in the isolate's cache by the commit's id.22 */23 import { RepoHost } from "@repo/artifacts/repo-host";24 import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";25 import { treeDiff } from "@repo/git/tree-diff";26 import type { Change } from "@repo/git/tree-diff";27 import type { ChangedFile, CommitDiff } from "@repo/protocol/domain/code";28+import { CommitDiff as CommitDiffSchema } from "@repo/protocol/domain/code";29 import { BlobSha, TreeSha } from "@repo/protocol/ids";30 import type { CommitSha, RepoName } from "@repo/protocol/ids";31 import { UnknownCommit } from "@repo/protocol/refusal";18-import { Array, Effect, Option, Order } from "effect";32+import { Array, Effect, Option, Order, Schema } from "effect";33 34+import { CodeStore } from "../code-store.ts";35 import type { CodeProject } from "../code.ts";36 import { CodeCache } from "./cache.ts";37 import { contentsOf } from "./file.ts";38 import type { Contents } from "./file.ts";24-import { commitViews } from "./log.ts";39+import { commitView } from "./log.ts";40 import { filesUnder, PATHS_CAP } from "./paths.ts";41 import { commitAt } from "./revision.ts";42 import { entriesOf, entryAt } from "./tree.ts";43 2 unmodified lines46 47 /** The most text a commit's diff carries in all: 2 MiB. */48 export const DIFF_TEXT = 2 * 1024 * 1024;49 50+/** The kept commit's version, in its key: it moves when what is kept changes. */51+export const COMMIT_VERSION = 1;52+53+/** Where a commit's diff is kept in the code store: by its repo and its id. */54+export const commitKey = (repo: RepoName, sha: CommitSha) =>55+ `${repo}/commit/v${COMMIT_VERSION}/${sha}`;56+57+/** How many files' sides are read at once: the fan-out the changes are listed with. */58+const SIDES_AT_ONCE = 8;59+60 /** The longest list of changes the cache keeps. */61 const KEPT_CHANGES = 1000;62 63 /** A change, and whether each side is a submodule (whose id names no blob here). */83 unmodified lines147 148 return after === undefined ? file : { ...file, after };149 };150 126-/** Each change with its text while the budget lasts, and whether any went without. */151+/** Both sides of `change`: its old contents and its new, where it has them. */152+const sidesOf = (repo: RepoName, change: Changed) =>153+ Effect.all([154+ sideOf(repo, change.before, change.links.before),155+ sideOf(repo, change.after, change.links.after),156+ ]);157+158+/** The length of a side's text, or 0 when it has none. */159+const lengthOf = (text: Option.Option<string>) =>160+ Option.match(text, { onNone: () => 0, onSome: ({ length }) => length });161+162+/**163+ * Each change with its text while the budget lasts, and whether any went164+ * without: the sides read a window of `SIDES_AT_ONCE` files at a time, the165+ * budget spent in path order, and no window read once it ran out.166+ */167 const withText = (repo: RepoName, changes: readonly Changed[]) =>168 Effect.gen(function* () {169 if (changes.length > DIFF_FILES) {170 return { files: changes.map(pathOnly), truncated: true };2 unmodified lines173 const files: ChangedFile[] = [];174 let budget = DIFF_TEXT;175 let truncated = false;176 137- for (const change of changes) {177+ for (const window of Array.chunksOf(changes, SIDES_AT_ONCE)) {178 if (truncated) {139- files.push(pathOnly(change));179+ files.push(...window.map(pathOnly));180 continue;181 }182 143- const before = yield* sideOf(repo, change.before, change.links.before);144- const after = yield* sideOf(repo, change.after, change.links.after);145- const oldText = Option.flatMap(before, ({ text }) => text);146- const newText = Option.flatMap(after, ({ text }) => text);183+ const sides = yield* Effect.forEach(184+ window,185+ (change) => sidesOf(repo, change),186+ { concurrency: SIDES_AT_ONCE }187+ );188 148- const size =149- Option.getOrElse(150- Option.map(oldText, (text) => text.length),151- () => 0152- ) +153- Option.getOrElse(154- Option.map(newText, (text) => text.length),155- () => 0156- );189+ for (const [index, change] of window.entries()) {190+ const [before, after] = sides[index] ?? [Option.none(), Option.none()];191 158- if (size > budget) {159- truncated = true;160- files.push(pathOnly(change));161- continue;162- }192+ if (truncated) {193+ files.push(pathOnly(change));194+ continue;195+ }196 164- budget -= size;197+ const oldText = Option.flatMap(before, ({ text }) => text);198+ const newText = Option.flatMap(after, ({ text }) => text);199+ const size = lengthOf(oldText) + lengthOf(newText);200 201+ if (size > budget) {202+ truncated = true;203+ files.push(pathOnly(change));204+ continue;205+ }206+207+ budget -= size;208+166- files.push({167- ...pathOnly(change),168- binary:169- Option.exists(before, ({ binary }) => binary) ||170- Option.exists(after, ({ binary }) => binary),171- ...Option.match(oldText, {172- onNone: () => ({}),173- onSome: (text) => ({ oldText: text }),174- }),175- ...Option.match(newText, {176- onNone: () => ({}),177- onSome: (text) => ({ newText: text }),178- }),179- });209+ files.push({210+ ...pathOnly(change),211+ binary:212+ Option.exists(before, ({ binary }) => binary) ||213+ Option.exists(after, ({ binary }) => binary),214+ ...Option.match(oldText, {215+ onNone: () => ({}),216+ onSome: (text) => ({ oldText: text }),217+ }),218+ ...Option.match(newText, {219+ onNone: () => ({}),220+ onSome: (text) => ({ newText: text }),221+ }),222+ });223+ }224 }225 226 return { files, truncated };227 });228 185-/** One commit and the files it changed against its first parent. */186-export const commitDiff = (229+/** A diff as the store keeps it: JSON, by the protocol's own schema. */230+const Kept = Schema.fromJsonString(CommitDiffSchema);231+232+const decodeKept = Schema.decodeUnknownOption(Kept);233+234+const encodeKept = Schema.encodeEffect(Kept);235+236+/** `diff` with its commit's landing, asked of the project's record now. */237+const withLanding = (238 project: CodeProject,239+ diff: CommitDiff240+): Effect.Effect<CommitDiff> =>241+ Effect.map(project.landings([diff.commit.sha]), (landings) =>242+ Option.match(243+ Array.findFirst(landings, ({ sha }) => sha === diff.commit.sha),244+ {245+ onNone: () => diff,246+ onSome: (landing) => ({247+ ...diff,248+ commit: { ...diff.commit, landing },249+ }),250+ }251+ )252+ );253+254+/** The diff kept for `sha` in the code store, if one is and it still decodes. */255+const keptDiff = (repo: RepoName, sha: CommitSha) =>256+ Effect.gen(function* () {257+ const store = yield* CodeStore;258+ const text = yield* store.get(commitKey(repo, sha));259+260+ return Option.filter(261+ Option.flatMap(text, decodeKept),262+ ({ commit }) => commit.sha === sha263+ );264+ });265+266+/** `diff`, which carries no landing, kept for `sha`; a store that fails keeps nothing. */267+const keepDiff = (repo: RepoName, sha: CommitSha, diff: CommitDiff) =>268+ Effect.gen(function* () {269+ const store = yield* CodeStore;270+271+ yield* encodeKept(diff).pipe(272+ Effect.flatMap((text) => store.put(commitKey(repo, sha), text)),273+ Effect.catch((error) =>274+ Effect.logWarning(`${sha}'s diff was not kept`, error)275+ )276+ );277+ });278+279+/** The diff of `sha` against its first parent, computed, with no landing. */280+const computedDiff = (281+ repo: RepoName,282 sha: CommitSha283 ): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>284 Effect.gen(function* () {191- const { repo } = project;285 const cache = yield* CodeCache;286 287 const commit = yield* commitAt(repo, sha).pipe(288 Effect.orDie,29 unmodified lines318 repo,319 Array.sort(changes, byPath)320 ).pipe(Effect.orDie);321 229- const [view] = yield* commitViews(project, [commit]);322+ return { commit: commitView(commit, Option.none()), files, truncated };323+ });324 231- if (view === undefined) {232- return yield* Effect.die(`no view of ${sha}`);325+/** One commit and the files it changed against its first parent. */326+export const commitDiff = (327+ project: CodeProject,328+ sha: CommitSha329+): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>330+ Effect.gen(function* () {331+ const { repo } = project;332+ const kept = yield* keptDiff(repo, sha);333+334+ if (Option.isSome(kept)) {335+ return yield* withLanding(project, kept.value);336 }337 235- return { commit: view, files, truncated };338+ const diff = yield* computedDiff(repo, sha);339+340+ yield* keepDiff(repo, sha, diff);341+342+ return yield* withLanding(project, diff);343 });added:packages/project/src/projection-d1/postures.ts+129 added
1+/**2+ * `StandingPostures` over D1, beside the projection: one row per project in3+ * `standing_postures` (`tables.ts`, migration 0005), each the posture a4+ * list last read from the project's own record, when it moves by the clock5+ * alone, and the project's last event the read saw.6+ *7+ * The projection deletes a project's row in the same write as an event8+ * that can move its posture (`projection.ts`). A read that event came9+ * after could still be written once the event is applied, so a row is10+ * written only while the project's `cursor` stands at or before the event11+ * the read saw, and never over a row from a later read.12+ *13+ * The lists of projects and of rows each go in as one JSON parameter14+ * (`json_each`), so a list of any length is one statement under D1's limit15+ * on bound parameters. Every failure, a database the migration has not16+ * reached among them, is a miss: logged, and never the list's.17+ */18+import { ProjectName } from "@repo/protocol/ids";19+import { Posture } from "@repo/protocol/posture";20+import { Array as Arr, DateTime, Effect, Layer, Result, Schema } from "effect";21+import { SqlClient } from "effect/sql/SqlClient";22+import type { SqlError } from "effect/sql/SqlError";23+24+import { StandingPostures } from "../standing-posture.ts";25+import type {26+ StandingEntry,27+ StandingPosturesApi,28+} from "../standing-posture.ts";29+30+/** A row as `standing_postures` holds it. */31+const Row = Schema.Struct({32+ moves_at: Schema.NullOr(Schema.DateTimeUtcFromString),33+ posture: Posture,34+ project: ProjectName,35+ seen: Schema.Int,36+});37+38+const decodeRow = Schema.decodeUnknownOption(Row);39+40+/** An entry as the row it is written as, one element of the JSON parameter. */41+const rowOf = (project: ProjectName, entry: StandingEntry) => ({42+ moves_at: entry.until === undefined ? null : DateTime.formatIso(entry.until),43+ posture: entry.posture,44+ project,45+ seen: entry.seen,46+});47+48+/** A row read back as an entry; `moves_at` only when it is set. */49+const entryOf = ({50+ moves_at: movesAt,51+ posture,52+ seen,53+}: typeof Row.Type): StandingEntry =>54+ movesAt === null ? { posture, seen } : { posture, seen, until: movesAt };55+56+/** `statement`'s rows, or `missed` and a warning when it fails. */57+const orMissed = <A>(58+ statement: Effect.Effect<A, SqlError>,59+ missed: A,60+ warning: string61+) =>62+ Effect.gen(function* () {63+ const ran = yield* Effect.result(statement);64+65+ if (Result.isSuccess(ran)) {66+ return ran.success;67+ }68+69+ yield* Effect.logWarning(warning, ran.failure);70+71+ return missed;72+ });73+74+export const StandingPosturesD1 = Layer.effect(75+ StandingPostures,76+ Effect.gen(function* () {77+ const sql = yield* SqlClient;78+79+ const store: StandingPosturesApi = {80+ get: (projects) =>81+ projects.length === 082+ ? Effect.succeed(new Map())83+ : Effect.map(84+ orMissed(85+ sql`SELECT project, posture, moves_at, seen FROM standing_postures86+ WHERE project IN (SELECT value FROM json_each(${JSON.stringify(projects)}))`,87+ [],88+ "the kept standing postures were not read"89+ ),90+ (rows) =>91+ new Map(92+ Arr.getSomes(rows.map((row) => decodeRow(row))).map(93+ (row) => [row.project, entryOf(row)] as const94+ )95+ )96+ ),97+ put: (entries) => {98+ const rows = [...entries].map(([project, entry]) =>99+ rowOf(project, entry)100+ );101+102+ return rows.length === 0103+ ? Effect.void104+ : Effect.asVoid(105+ orMissed(106+ sql`INSERT INTO standing_postures (project, posture, moves_at, seen)107+ SELECT json_extract(entry.value, '$.project'),108+ json_extract(entry.value, '$.posture'),109+ json_extract(entry.value, '$.moves_at'),110+ json_extract(entry.value, '$.seen')111+ FROM json_each(${JSON.stringify(rows)}) AS entry112+ WHERE json_extract(entry.value, '$.seen') >= COALESCE(113+ (SELECT seq FROM cursor114+ WHERE cursor.project = json_extract(entry.value, '$.project')),115+ 0)116+ ON CONFLICT (project) DO UPDATE SET117+ posture = excluded.posture, moves_at = excluded.moves_at,118+ seen = excluded.seen119+ WHERE excluded.seen >= standing_postures.seen`,120+ [],121+ "the standing postures read were not kept"122+ )123+ );124+ },125+ };126+127+ return store;128+ })129+);modified:packages/project/src/projection-d1/projection.ts+56 added-7 removed
24 unmodified lines25 * (its project's cursor short of the event before it) is not applied, and26 * `apply` fails with `ProjectionFailed` once the rest is in: the outbox keeps27 * those rows and sends them again after the missing one.28 *29+ * - A list keeps each project's standing posture beside these tables30+ * (`postures.ts`, migration 0005). An event that can move a project's31+ * posture deletes its kept row in the same write: a `Landed` (a config32+ * lands, a narrowing opens its decision), a `Decided` (an accepted33+ * narrowing starts to stand, now or once its notice runs out) and a34+ * `LedgerAppended` (a `PostureChanged` row; any other entry too, which35+ * costs one read). The table is looked for once per isolate until it is36+ * found, so a database the migration has not reached yet projects as37+ * before.38+ *39 * One call is one atomic write: a D1 batch when the `SqlClient` is D1's40 * (D1 has no interactive transactions), and a transaction anywhere else,41 * such as sqlite-node in tests. The client itself says which it is, so the42 * layer needs nothing but the `SqlClient`. A failed write applies nothing.4 unmodified lines47 import type { LandingView } from "@repo/protocol/domain/landing";48 import { LedgerEntry } from "@repo/protocol/domain/visibility";49 import { ProjectName } from "@repo/protocol/ids";50 import type { AskId } from "@repo/protocol/ids";41-import { Array, DateTime, Effect, Layer, Order, Schema } from "effect";51+import { Array, DateTime, Effect, Layer, Order, Ref, Schema } from "effect";52 import { SqlClient } from "effect/sql/SqlClient";53 import type { SqlError } from "effect/sql/SqlError";54 import type { Statement } from "effect/sql/Statement";55 56 unmodified lines112 isD1(sql)113 ? sql.batch(statements)114 : sql.withTransaction(Effect.all(statements));115 116+ const posturesFound = yield* Ref.make(false);117+118+ /**119+ * Whether the kept postures' table is there (migration 0005): looked120+ * for until it is found, and never again after.121+ */122+ const keepsPostures = Effect.gen(function* () {123+ if (yield* Ref.get(posturesFound)) {124+ return true;125+ }126+127+ const tables =128+ yield* sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'standing_postures'`;129+130+ yield* Ref.set(posturesFound, tables.length > 0);131+132+ return tables.length > 0;133+ });134+135 /** Whether the project's cursor stands just before event `seq`. */136 const isNext = (project: ProjectName, seq: number) =>137 sql`(SELECT COALESCE(MAX(seq), 0) FROM cursor WHERE project = ${project}) = ${seq - 1}`;138 139 /**140 * What one event changes in the read model, if anything: the project's141 * row first, so every event lists its project.142 */114- const writes = ({ event, project }: ProjectedEvent) => {143+ const writes = (144+ { event, project }: ProjectedEvent,145+ postures: boolean146+ ) => {147 const next = isNext(project, event.seq);148 149+ /** The project's kept posture, cleared: this event may move it. */150+ const unkept = postures151+ ? [152+ sql`DELETE FROM standing_postures153+ WHERE project = ${project} AND ${next}`,154+ ]155+ : [];156+157 const listed = sql`INSERT INTO projects (project, posture, open_asks, landed_at)158 SELECT ${project}, 'open', 0, NULL WHERE ${next}159 ON CONFLICT (project) DO NOTHING`;160 45 unmodified lines206 opened_at = excluded.opened_at`,207 counted,208 ],209 Claimed: ({ ask }) => [claims(ask, 1)],170- Decided: () => [],210+ Decided: () => unkept,211 Judged: () => [],212 Landed: ({ landing }) => [213 sql`UPDATE projects SET landed_at = ${DateTime.formatIso(landing.landedAt)}214 WHERE project = ${project} AND ${next}`,215 ...credited(landing),216+ ...unkept,217 ],218 Lapsed: ({ ask }) => [claims(ask, -1)],178- LedgerAppended: ({ entry }) =>179- LedgerEntry.guards.PostureChanged(entry)219+ LedgerAppended: ({ entry }) => [220+ ...(LedgerEntry.guards.PostureChanged(entry)221 ? [222 sql`UPDATE projects SET posture = ${entry.to}223 WHERE project = ${project} AND ${next}`,224 ]184- : [],225+ : []),226+ ...unkept,227+ ],228 ProposalDrafted: () => [],229 ProposalOpened: () => [],230 Pushed: () => [],231 Released: ({ ask }) => [claims(ask, -1)],19 unmodified lines251 const deliver = (events: Array.NonEmptyReadonlyArray<ProjectedEvent>) =>252 Effect.gen(function* () {253 const last = lastOf(events);254 255+ const postures = yield* keepsPostures.pipe(256+ Effect.mapError(257+ (failed) => new ProjectionFailed({ reason: failed.message })258+ )259+ );260+261 const results = yield* atomically([262 ...events.flatMap((projected) => [214- ...writes(projected),263+ ...writes(projected, postures),264 advance(projected.project, projected.event.seq),265 ]),266 cursorsOf([...last.keys()]),267 ]).pipe(49 unmodified linesmodified:packages/project/src/projection-d1/tables.ts+35 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: the project list adds15- * its tables in `0004_projects_credits.sql` (`ProjectsCreditsDdl`).15+ * its tables in `0004_projects_credits.sql` (`ProjectsCreditsDdl`), and the16+ * kept standing postures theirs in `0005_standing_postures.sql`17+ * (`StandingPosturesDdl`).18 */19 import type { Handle } from "@repo/protocol/ids";20 21 /**86 unmodified lines108 (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),109 NULL110 FROM cursor;111 `;112+113+/**114+ * The kept standing postures' table in D1, as the platform's fifth D1115+ * migration (`apps/platform/migrations/0005_standing_postures.sql`) creates116+ * it. The file holds exactly this text, and the postures' test applies the117+ * file and checks that it does.118+ *119+ * - `standing_postures`: one row per project a list has read the posture120+ * of (`withStandingPosture`): the posture, when it moves by the clock121+ * alone (`moves_at`, ISO 8601; null when only an event moves it), and122+ * the project's last event the read saw (`seen`). The projection deletes123+ * a project's row with any event that can move its posture; a list124+ * writes one only while `cursor` stands at or before `seen`125+ * (`postures.ts`).126+ */127+export const StandingPosturesDdl = `-- Each listed project's standing posture, as a list last read it from the128+-- project's own record, kept by packages/project/src/projection-d1 (its129+-- tables.ts holds this text). A cache: a row lost costs one read. The130+-- projection deletes a project's row in the same write as any event that131+-- can move its posture, and a list writes a row only while the projection132+-- has applied no event of the project later than the one the read saw.133+134+CREATE TABLE standing_postures (135+ project TEXT PRIMARY KEY,136+ posture TEXT NOT NULL,137+ -- when the posture moves by the clock alone (ISO 8601), absent when only138+ -- an event moves it139+ moves_at TEXT,140+ -- the project's last event the read saw141+ seen INTEGER NOT NULL142+);143+`;added:packages/project/src/standing-posture/memory.ts+41 added
1+/**2+ * The kept standing postures in memory, for tests: a map per layer, kept3+ * whole, with no projection beside it to clear an entry.4+ */5+import type { ProjectName } from "@repo/protocol/ids";6+import { Effect, Layer, Ref } from "effect";7+8+import { StandingPostures } from "../standing-posture.ts";9+import type {10+ StandingEntry,11+ StandingPosturesApi,12+} from "../standing-posture.ts";13+14+/** A fresh, empty store each time the layer is built. */15+export const StandingPosturesMemory = Layer.effect(16+ StandingPostures,17+ Effect.gen(function* () {18+ const kept = yield* Ref.make<ReadonlyMap<ProjectName, StandingEntry>>(19+ new Map()20+ );21+22+ const store: StandingPosturesApi = {23+ get: (projects) =>24+ Effect.map(25+ Ref.get(kept),26+ (all) =>27+ new Map(28+ projects.flatMap((project) => {29+ const entry = all.get(project);30+31+ return entry === undefined ? [] : [[project, entry] as const];32+ })33+ )34+ ),35+ put: (entries) =>36+ Ref.update(kept, (all) => new Map([...all, ...entries])),37+ };38+39+ return store;40+ })41+);modified:packages/project/src/visibility/ledger.ts+28 added
164 unmodified lines165 });166 };167 168 /**169+ * The next instant the posture in effect moves by the clock alone: an170+ * accepted narrowing whose notice still runs at `now`. None when only an171+ * event can move it: no narrowing waits, one waits on its decision (a172+ * `Decided` event settles it), or one took effect already. A later landing173+ * or decision may move it sooner; this is only when time does.174+ */175+export const nextMove = (input: {176+ readonly decisions: readonly Decision[];177+ readonly now: DateTime.Utc;178+ readonly visibility: Option.Option<VisibilityPolicy>;179+}): Option.Option<DateTime.Utc> => {180+ const declared = declaredBy(input.visibility);181+182+ const noticeDays = Option.match(input.visibility, {183+ onNone: () => 0,184+ onSome: ({ notice }) => notice.narrowingDays,185+ });186+187+ return Arr.last(188+ input.decisions.flatMap((decision) => Option.toArray(askedOf(decision)))189+ ).pipe(190+ Option.filter(({ subject }) => subject.to === declared.posture),191+ Option.flatMap(({ decision }) => takesEffect(decision, noticeDays)),192+ Option.filter((at) => DateTime.isGreaterThan(at, input.now))193+ );194+};195+196+/**197 * Whether the config's held-back checks judge answers yet: not while a198 * narrowing from Open waits on its decision (nothing was sealed before).199 */200 export const sealedInEffect = (posture: Standing) =>77 unmodified linesmodified:packages/project/src/visibility/state.ts+11 added
94 unmodified lines95 import {96 appended,97 declaredBy,98 ledgerFor,99+ nextMove,100 nextSeq,101 postureCaughtUp,102 sealedInEffect,103 standing,1061 unmodified lines1165 pinSuite,1166 readableLayers,1167 recordRead,1168 settle,1169+ standing: (snapshot) => {1170+ const now = nowOf();1171+ const visibility = visibilityIn(snapshot);1172+1173+ return {1174+ posture: standing({ decisions: snapshot.decisions, now, visibility })1175+ .posture,1176+ until: nextMove({ decisions: snapshot.decisions, now, visibility }),1177+ };1178+ },1179 };1180 1181 return port;1182 });10 unmodified linesmodified:packages/project/src/project.ts+39 added
131 unmodified lines132 TreeSha,133 sameHandle,134 } from "@repo/protocol/ids";135 import type { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";136+import { Posture } from "@repo/protocol/posture";137 import { Person, Principal } from "@repo/protocol/principal";138 import {139 AskFull,140 DirectPush,223 unmodified lines364 readonly content: string;365 readonly path: RepoPath;366 }367 368+/**369+ * A project's posture as a list keeps it: the posture its ledger shows370+ * now, the next instant it moves by the clock alone, if one is set, and the371+ * project's last event the read saw (`ProjectApi.standing`).372+ */373+export const StandingNow = Schema.Struct({374+ posture: Posture,375+ seen: Schema.Int,376+ until: Schema.optionalKey(Schema.DateTimeUtcFromString),377+});378+379+export type StandingNow = typeof StandingNow.Type;380+381 /** The refusals `submitAnswer` answers with. */382 export type SubmitRefusal =383 | NotClaimed384 | ClaimLapsed44 unmodified lines429 ) => Effect.Effect<readonly LandingView[]>;430 /** Every claim's fork, with its ask, claimant and the claim's state. */431 readonly forks: () => Effect.Effect<readonly ForkRef[]>;432 /**433+ * The posture the ledger shows now, the next instant it moves by the434+ * clock alone (none when only an event moves it), and the project's last435+ * event this read saw. Platform-only, on no surface: what a list keeps436+ * each project's posture by (`standing-posture.ts`).437+ */438+ readonly standing: () => Effect.Effect<StandingNow>;439+ /**440 * The policy at the landed commit as anyone may read it (no layers, no441 * function-valued rules, no asks), once it has evaluated; until then, after442 * the first landing, why it has not (derived at each read, never stored).443 */442 unmodified lines886 args: [Principal, ProposalId],887 error: ShowProposal.errorSchema,888 success: ShowProposal.successSchema,889 },890+ standing: {891+ args: [],892+ error: Schema.Never,893+ success: StandingNow,894+ },895 status: {896 args: [Person],897 error: Status.errorSchema,898 // The contract adds the caller's handle at the platform's edge; a project4913 unmodified lines5812 MethodSchemas.showProposal,5813 [caller, proposal],5814 decided.showProposal(proposal)5815 ),5816+ standing: () =>5817+ checked(5818+ MethodSchemas.standing,5819+ [],5820+ Effect.map(hydrate, (h): StandingNow => {5821+ const { posture, until } = visibility.standing(h.snapshot);5822+5823+ return Option.match(until, {5824+ onNone: () => ({ posture, seen: h.lastSeq }),5825+ onSome: (at) => ({ posture, seen: h.lastSeq, until: at }),5826+ });5827+ })5828+ ),5829 status: (caller) =>5830 checked(MethodSchemas.status, [caller], statusOf(caller)),5831 submitAnswer: (caller, input) =>5832 checked(18 unmodified linesmodified:packages/project/src/standing-posture.ts+130 added-34 removed
2 unmodified lines3 * projection's `posture` moves only on a `PostureChanged` ledger entry, and4 * a project's standing changes without one: its first config stands at5 * once, a widening needs no decision, and an accepted narrowing takes6 * effect when its notice runs out, by the clock. So a list of projects7- * reads each one's ledger, the public read whose `posture` is the standing8- * at now (`visibility/ledger.ts`), and shows that: the badge and the ledger9- * are one value, read at the source, with nothing written to keep them in10- * step.7+ * reads from each one's own record the posture its ledger shows now8+ * (`ProjectApi.standing`, the value the ledger's `posture` is), and shows9+ * that: the badge and the ledger are one value, read at the source.10 *12- * Cost: one ledger read per listed project per list, at most 8 at once,13- * each read whole for its one `posture` field.11+ * What was read is kept (`StandingPostures`) with the next instant the12+ * posture moves by the clock alone (an accepted narrowing's notice running13+ * out) and the project's last event the read saw. A kept posture serves14+ * until that instant; an event that can move it sooner (a landing, a15+ * decision, a ledger entry) clears it where the projection applies that16+ * event (`projection-d1/projection.ts`), and a store that applied a later17+ * event than the read saw keeps nothing from it. A store that fails is a18+ * miss, never the list's failure.19+ *20+ * Cost: one read per listed project whose kept posture is missing or ran21+ * out, at most 8 at once; none for the rest.22 */23 import type { ProjectListing } from "@repo/protocol/domain/front-page";16-import { Anonymous } from "@repo/protocol/principal";17-import { Cause, Effect } from "effect";24+import type { ProjectName } from "@repo/protocol/ids";25+import type { Posture } from "@repo/protocol/posture";26+import { Array as Arr, Cause, Context, DateTime, Effect, Option } from "effect";27 28 import { Projects } from "./projects.ts";29 30+/** A project's standing posture as it is kept between lists. */31+export interface StandingEntry {32+ readonly posture: Posture;33+ /** The instant it moves by the clock alone; none when only an event moves it. */34+ readonly until?: DateTime.Utc;35+ /**36+ * The project's last event the read saw: a store that has applied a37+ * later event of the project keeps nothing from it, since that event may38+ * have moved the posture after the read.39+ */40+ readonly seen: number;41+}42+43+/** Where a list keeps each project's standing posture between lists. */44+export interface StandingPosturesApi {45+ /** What is kept for each of `projects`; a store that fails keeps nothing. */46+ readonly get: (47+ projects: readonly ProjectName[]48+ ) => Effect.Effect<ReadonlyMap<ProjectName, StandingEntry>>;49+ /** Keeps `entries`; a store that fails keeps nothing, silently to the caller. */50+ readonly put: (51+ entries: ReadonlyMap<ProjectName, StandingEntry>52+ ) => Effect.Effect<void>;53+}54+55+/**56+ * The kept standing postures: a `Context.Reference` whose default keeps57+ * nothing, so every list reads each project, as every host did before one58+ * was given; the platform gives one over D1 (`projection-d1/postures.ts`).59+ */60+export const StandingPostures = Context.Reference<StandingPosturesApi>(61+ "project/StandingPostures",62+ {63+ defaultValue: () => ({64+ get: () => Effect.succeed(new Map()),65+ put: () => Effect.void,66+ }),67+ }68+);69+70 /** How many projects a list reads at once (the platform handlers' `FAN_OUT`). */71 const READS_AT_ONCE = 8;72 73+/** `effect`, or `fallback` with a warning if it fails: an interruption stays one. */74+const orWarn = <A, E>(75+ effect: Effect.Effect<A, E>,76+ fallback: A,77+ warning: string78+): Effect.Effect<A> =>79+ Effect.catchCause(effect, (cause) =>80+ Cause.hasInterruptsOnly(cause)81+ ? Effect.interrupt82+ : Effect.as(Effect.logWarning(warning, cause), fallback)83+ );84+85 /**25- * `listed` with each project's posture as its own record says it now (its26- * ledger's standing), read at most 8 at once; a project never made, or one27- * whose read fails, keeps the posture the projection listed.86+ * `listed` with each project's posture as its own record says it now (the87+ * posture its ledger shows): what `StandingPostures` keeps for it while88+ * that has not run out, else read from the project, at most 8 at once, and89+ * kept with the instant it moves by the clock. A project never made, or90+ * one whose read fails, keeps the posture the projection listed and is not91+ * kept; a store that fails is a miss.92 */93 export const withStandingPosture = (94 listed: readonly ProjectListing[]95 ): Effect.Effect<readonly ProjectListing[], never, Projects> =>96 Effect.gen(function* () {97+ if (listed.length === 0) {98+ return listed;99+ }100+101 const projects = yield* Projects;102+ const store = yield* StandingPostures;103+ const now = yield* DateTime.now;104+ const names = Arr.dedupe(listed.map(({ project }) => project));105 35- return yield* Effect.forEach(36- listed,37- (listing) =>38- Effect.suspend(() => projects.get(listing.project)).pipe(39- Effect.flatMap((api) => api.ledger(Anonymous.make({}))),40- Effect.map(({ posture }): ProjectListing => ({41- ...listing,42- posture,43- })),44- // The list answers whatever one project does, a `get` that45- // throws included: an interruption stays one, and anything else46- // keeps the projected posture.47- Effect.catchCause((cause) =>48- Cause.hasInterruptsOnly(cause)49- ? Effect.interrupt50- : Effect.as(51- Effect.logWarning(52- `${listing.project}'s posture is the projection's: its ledger was not read`,53- cause54- ),55- listing56- )57- )106+ const kept = yield* orWarn(107+ Effect.suspend(() => store.get(names)),108+ new Map<ProjectName, StandingEntry>(),109+ "the kept standing postures were not read: every project is read"110+ );111+112+ const fresh = new Map(113+ [...kept].filter(114+ ([, { until }]) =>115+ until === undefined || DateTime.isLessThan(now, until)116+ )117+ );118+119+ const read = yield* Effect.forEach(120+ names.filter((project) => !fresh.has(project)),121+ (project) =>122+ orWarn(123+ Effect.suspend(() => projects.get(project)).pipe(124+ Effect.flatMap((api) => api.standing()),125+ Effect.map(({ posture, seen, until }) =>126+ Option.some([127+ project,128+ until === undefined129+ ? { posture, seen }130+ : { posture, seen, until },131+ ] as const)132+ )133+ ),134+ Option.none(),135+ `${project}'s posture is the projection's: its ledger was not read`136 ),137 { concurrency: READS_AT_ONCE }138 );139+140+ const found = new Map<ProjectName, StandingEntry>(Arr.getSomes(read));141+142+ if (found.size > 0) {143+ yield* orWarn(144+ Effect.suspend(() => store.put(found)),145+ undefined,146+ "the standing postures read were not kept"147+ );148+ }149+150+ return listed.map((listing): ProjectListing => {151+ const entry = found.get(listing.project) ?? fresh.get(listing.project);152+153+ return entry === undefined154+ ? listing155+ : { ...listing, posture: entry.posture };156+ });157 });modified:packages/project/src/visibility-port.ts+11 added
31 unmodified lines32 RepoPath,33 SuiteRoot,34 } from "@repo/protocol/ids";35 import type { AskId, Handle, ProjectName, RequestId } from "@repo/protocol/ids";36+import type { Posture } from "@repo/protocol/posture";37 import type { Principal } from "@repo/protocol/principal";38 import type { AttemptsExhausted, HeldBackFailed } from "@repo/protocol/refusal";39 import { Context, Effect, Layer, Option, Schema } from "effect";40 import type { DateTime } from "effect";220 unmodified lines261 readonly sha: Option.Option<CommitSha>;262 }) => ProjectWrites;263 /** The public ledger. */264 readonly ledger: (project: ProjectName, snapshot: ProjectSnapshot) => Ledger;265+ /**266+ * The posture the ledger shows now, and the next instant it moves by the267+ * clock alone (an accepted narrowing whose notice still runs), if any:268+ * what a list keeps a project's posture by (`standing-posture.ts`).269+ */270+ readonly standing: (snapshot: ProjectSnapshot) => {271+ readonly posture: Posture;272+ readonly until: Option.Option<DateTime.Utc>;273+ };274 /** Runs one effect a plan asked for: true once it is done, false to try again later. */275 readonly settle: (effect: VisibilityEffect) => Effect.Effect<boolean>;276 }277 17 unmodified lines295 pinSuite: () => Option.none(),296 readableLayers: () => new Set(),297 recordRead: () => ({}),298 settle: () => Effect.succeed(true),299+ standing: () => ({ posture: "open", until: Option.none() }),300 };301 302 /**303 * How a host gives the project service typed visibility. The default is30 unmodified linesmodified:packages/project/test/visibility/state.test.ts+34 added-1 removed
20 unmodified lines21 import { Anonymous } from "@repo/protocol/principal";22 import { NotDecider } from "@repo/protocol/refusal";23 import { advanceTo, at } from "@repo/testkit/clock";24 import { areaRoots, suiteRoot } from "@repo/visibility/commitment";25-import { Array, Effect, Option, Order } from "effect";25+import { Array, DateTime, Effect, Option, Order } from "effect";26 27 import { drive } from "../../src/answer-runs/steps.ts";28 import { ProjectStore } from "../../src/project-store.ts";29 import { AdmissionRun, ProjectVisibility } from "../../src/visibility-port.ts";178 unmodified lines208 }).pipe(Effect.provide(visibilityWorld()))209 );210 211 it.effect(212+ "stands, for a list, at the ledger's posture until the instant an accepted narrowing takes effect",213+ () =>214+ Effect.gen(function* () {215+ const { api } = yield* sealedByInes;216+ const [opened] = yield* postureDecisions(api);217+ const decision = Option.getOrThrow(Option.fromUndefinedOr(opened));218+219+ /** What a list keeps, beside the posture the ledger shows. */220+ const both = Effect.gen(function* () {221+ const { posture, until } = yield* api.standing();222+ const ledger = yield* api.ledger(anyone);223+224+ return [posture, ledger.posture, until] as const;225+ });226+227+ const waiting = yield* both;228+229+ yield* advanceTo("2026-10-08T12:00:00Z");230+ yield* api.decide(okonkwo, { choice: "accept", decision: decision.id });231+232+ const accepted = yield* both;233+234+ yield* advanceTo("2026-10-14T12:00:00Z");235+236+ expect([waiting, accepted, yield* both]).toStrictEqual([237+ ["open", "open", undefined],238+ ["open", "open", DateTime.makeUnsafe("2026-10-14T12:00:00Z")],239+ ["openWithSealedEvidence", "openWithSealedEvidence", undefined],240+ ]);241+ }).pipe(Effect.provide(visibilityWorld()))242+ );243+244+ it.effect(245 "keeps the posture when nobody decides: the decision takes its default, decline",246 () =>247 Effect.gen(function* () {248 const { api } = yield* sealedByInes;460 unmodified linesmodified:packages/project/test/code.test.ts+226 added-2 removed
8 unmodified lines9 import { describe, expect, it } from "@effect/vitest";10 import { RepoHost } from "@repo/artifacts/repo-host";11 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12 import { Brand } from "@repo/brand";13+import { CommitDiff } from "@repo/protocol/domain/code";13-import { CommitSha, RepoPath } from "@repo/protocol/ids";14+import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";15 import {16 UnknownCommit,17 UnknownPath,18 UnknownRevision,19 } from "@repo/protocol/refusal";19-import { DateTime, Effect, Exit, Fiber, Layer, Option, Ref } from "effect";20+import {21+ DateTime,22+ Effect,23+ Exit,24+ Fiber,25+ Layer,26+ Option,27+ Ref,28+ Schema,29+} from "effect";30 import { TestClock } from "effect/testing";31 32+import { CodeStore } from "../src/code-store.ts";33+import { CodeStoreMemory } from "../src/code-store/memory.ts";34 import {35 commitOf,36 fileOf,37 logOf,1 unmodified line39 refsOf,40 treeOf,41 } from "../src/code.ts";42 import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";43+import { commitKey, DIFF_TEXT } from "../src/code/commit.ts";44 import { filesUnder } from "../src/code/paths.ts";45 import { compareTags } from "../src/code/refs.ts";46 import { READS_AT_ONCE } from "../src/code/tree.ts";47 import {48 big,49+ Content,50 datekit,51 fork,52 longHistory,53 project,54 overlappingTrees,55 wide,56+ writer,57 } from "./code-fixtures.ts";58 59 const revision = (name: string) => Option.some(name);60 499 unmodified lines560 }).pipe(Effect.provide(RepoHostMemory))561 );562 });563 564+/** 150 KiB of text: fourteen of them run past a diff's 2 MiB of text. */565+const sizable = (name: string) => `${name.padEnd(1023, "y")}\n`.repeat(150);566+567+/**568+ * One commit modifying twenty files, `f00.txt` to `f19.txt`, each from a569+ * line to 150 KiB but `f14.txt`, which stays small: thirteen fit the text570+ * budget, `f13.txt` runs past it, and every file after it is a path only.571+ */572+const twentyFiles = Effect.gen(function* () {573+ const git = yield* writer;574+ const name = RepoName.make("twentykit");575+576+ const paths = Array.from(577+ { length: 20 },578+ (_, at) => `f${String(at).padStart(2, "0")}.txt`579+ );580+581+ const before = yield* git.commit(582+ "Small",583+ paths.map((at) => [at, Content.Text({ text: `${at}\n` })] as const),584+ [],585+ 1586+ );587+588+ const after = yield* git.commit(589+ "Large",590+ paths.map(591+ (at) =>592+ [593+ at,594+ Content.Text({595+ text: at === "f14.txt" ? "small\n" : sizable(at),596+ }),597+ ] as const598+ ),599+ [before],600+ 2601+ );602+603+ yield* git.push(name, [["refs/heads/main", after]]);604+605+ return {606+ after,607+ code: {608+ forks: Effect.succeed([]),609+ head: Effect.succeedNone,610+ landings: () => Effect.succeed([]),611+ project,612+ repo: name,613+ },614+ paths,615+ };616+});617+618+describe("a commit's texts, read live", () => {619+ it.live(620+ "are read several at a time, and cut at the budget in path order as one after another would",621+ () =>622+ Effect.gen(function* () {623+ const reading = yield* Ref.make(false);624+ const peak = yield* Ref.make(0);625+626+ const { diff, paths } = yield* Effect.gen(function* () {627+ const made = yield* twentyFiles;628+629+ yield* Ref.set(reading, true);630+631+ return {632+ diff: yield* commitOf(made.code, made.after),633+ paths: made.paths,634+ };635+ }).pipe(Effect.provide(overlappingTrees(reading, peak, "blob")));636+637+ const most = yield* Ref.get(peak);638+639+ // Thirteen files' texts fit the budget, and a fourteenth does not.640+ expect([641+ 13 * sizable("f00.txt").length <= DIFF_TEXT,642+ 14 * sizable("f00.txt").length > DIFF_TEXT,643+ ]).toStrictEqual([true, true]);644+ expect({645+ files: diff.files.map(({ newText, oldText, path: at, status }) => [646+ at,647+ status,648+ oldText,649+ newText,650+ ]),651+ truncated: diff.truncated,652+ }).toStrictEqual({653+ files: paths.map((at, index) =>654+ index < 13655+ ? [at, "modified", `${at}\n`, sizable(at)]656+ : [at, "modified", undefined, undefined]657+ ),658+ truncated: true,659+ });660+ // Several at once, never past the fan-out of 8.661+ expect([most > 1, most <= 8]).toStrictEqual([true, true]);662+ }),663+ long664+ );665+});666+667+/** The memory store, with each blob `readBlob` is asked for counted in `reads`. */668+const blobsCountedBy = (reads: Ref.Ref<number>) =>669+ Layer.effect(670+ RepoHost,671+ Effect.gen(function* () {672+ const host = yield* RepoHost;673+674+ return RepoHost.of({675+ ...host,676+ readBlob: (name, blob) =>677+ Ref.update(reads, (count) => count + 1).pipe(678+ Effect.andThen(host.readBlob(name, blob))679+ ),680+ });681+ })682+ ).pipe(Layer.provide(RepoHostMemory));683+684+/** What the store keeps under a key, as a diff, if it holds one that decodes. */685+const keptUnder = (key: string) =>686+ Effect.map(687+ Effect.flatMap(Effect.service(CodeStore), (store) => store.get(key)),688+ Option.flatMap(689+ Schema.decodeUnknownOption(Schema.fromJsonString(CommitDiff))690+ )691+ );692+693+describe("a commit kept by its id", () => {694+ it.effect(695+ "is kept without its landing, read again with no blob read, and its landing still asked for",696+ () =>697+ Effect.gen(function* () {698+ const blobs = yield* Ref.make(0);699+ const asked = yield* Ref.make<readonly (readonly CommitSha[])[]>([]);700+701+ yield* Effect.gen(function* () {702+ const { c4, code } = yield* datekit;703+704+ const counted = {705+ ...code,706+ landings: (shas: readonly CommitSha[]) =>707+ Ref.update(asked, (all) => [...all, shas]).pipe(708+ Effect.andThen(code.landings(shas))709+ ),710+ };711+712+ const first = yield* commitOf(counted, c4);713+ const read = yield* Ref.get(blobs);714+715+ expect([first.commit.landing?.sha, read > 0]).toStrictEqual([716+ c4,717+ true,718+ ]);719+720+ const kept = yield* keptUnder(commitKey(code.repo, c4));721+722+ // Kept with no landing: the rest is the diff as it was answered.723+ expect(724+ Option.map(kept, (decoded) => ({725+ kept: decoded.commit.landing,726+ restored: {727+ ...decoded,728+ commit: { ...decoded.commit, landing: first.commit.landing },729+ },730+ }))731+ ).toStrictEqual(Option.some({ kept: undefined, restored: first }));732+733+ const second = yield* commitOf(counted, c4);734+735+ expect({736+ asked: yield* Ref.get(asked),737+ blobs: yield* Ref.get(blobs),738+ second,739+ }).toStrictEqual({ asked: [[c4], [c4]], blobs: read, second: first });740+ }).pipe(741+ Effect.provide(Layer.merge(blobsCountedBy(blobs), CodeStoreMemory))742+ );743+ })744+ );745+746+ it.effect("is computed again when what is kept no longer decodes", () =>747+ Effect.gen(function* () {748+ const blobs = yield* Ref.make(0);749+750+ yield* Effect.gen(function* () {751+ const { c2, code } = yield* datekit;752+ const store = yield* CodeStore;753+ const key = commitKey(code.repo, c2);754+755+ const fresh = yield* commitOf(code, c2).pipe(756+ Effect.provideService(CodeStore, CodeStore.defaultValue())757+ );758+759+ const read = yield* Ref.get(blobs);760+761+ yield* store.put(key, '{"files":"no longer a diff"}');762+763+ expect(yield* commitOf(code, c2)).toStrictEqual(fresh);764+ expect(yield* Ref.get(blobs)).toBe(2 * read);765+ expect(yield* keptUnder(key)).toStrictEqual(Option.some(fresh));766+ }).pipe(767+ Effect.provide(Layer.merge(blobsCountedBy(blobs), CodeStoreMemory))768+ );769+ })770+ );771+});772+773 /** The memory store, with each tree id `readTree` is asked for counted in `reads`. */774 const countedBy = (reads: Ref.Ref<readonly string[]>) =>775 Layer.effect(776 RepoHost,89 unmodified linesmodified:packages/project/test/projection-d1.fixtures.ts+3 added
13 unmodified lines14 15 /** The project list's and the credits' migration (`ProjectsCreditsDdl`). */16 export const projectsMigration = "0004_projects_credits.sql";17 18+/** The kept standing postures' migration (`StandingPosturesDdl`). */19+export const posturesMigration = "0005_standing_postures.sql";20+21 /** A migration of the platform's D1 database, as its file holds it. */22 export const migration = (file: string) =>23 Effect.gen(function* () {24 const fs = yield* FileSystem.FileSystem;27 unmodified linesmodified:packages/project/test/projection-d1.test.ts+190 added-2 removed
6 unmodified lines7 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";11+import { LedgerEntry } from "@repo/protocol/domain/visibility";12 import {13 AskId,14+ DecisionId,15+ EnvKey,16 Handle,17 KindName,18 LandedSha,19 ProjectName,20 } from "@repo/protocol/ids";18-import { DateTime, Effect, Layer } from "effect";21+import { DateTime, Effect, Layer, Logger } from "effect";22 import { SqlClient } from "effect/sql/SqlClient";23 24 import { FrontPage } from "../src/front-page.ts";25 import type { FrontPageFilter } from "../src/front-page.ts";26 import { projectedRows } from "../src/outbox.ts";27 import type { OutboxRow } from "../src/project-store/rows.ts";28 import { FrontPageD1 } from "../src/projection-d1/front-page.ts";29+import { StandingPosturesD1 } from "../src/projection-d1/postures.ts";30 import { ProjectionD1 } from "../src/projection-d1/projection.ts";31+import {32+ FrontPageDdl,33+ StandingPosturesDdl,27-import { FrontPageDdl } from "../src/projection-d1/tables.ts";34+} from "../src/projection-d1/tables.ts";35 import { Projection, ProjectionFailed } from "../src/projection.ts";36+import { StandingPostures } from "../src/standing-posture.ts";37+import type { StandingEntry } from "../src/standing-posture.ts";38 import {39 frontPageMigration,40 migrated,41 migration,42+ posturesMigration,43 projectsMigration,44 } from "./projection-d1.fixtures.ts";45 46 /**376 unmodified lines423 expect(yield* front.credits(Handle.make("bram"))).toStrictEqual([]);424 }).pipe(Effect.provide(world))425 );426 });427+428+/** The projection and the kept postures over a database with every migration. */429+const withPostures = Layer.mergeAll(ProjectionD1, StandingPosturesD1).pipe(430+ Layer.provideMerge(431+ migrated([frontPageMigration, projectsMigration, posturesMigration])432+ )433+);434+435+/** The same over a database the postures' migration has not reached yet. */436+const beforePostures = Layer.mergeAll(ProjectionD1, StandingPosturesD1).pipe(437+ Layer.provideMerge(migrated([frontPageMigration, projectsMigration]))438+);439+440+const sealed: StandingEntry = {441+ posture: "openWithSealedEvidence",442+ seen: 1,443+ until: DateTime.makeUnsafe("2026-10-14T12:00:00Z"),444+};445+446+const open: StandingEntry = { posture: "open", seen: 1 };447+448+const keep = (kept: readonly (readonly [ProjectName, StandingEntry])[]) =>449+ Effect.flatMap(Effect.service(StandingPostures), (store) =>450+ store.put(new Map(kept))451+ );452+453+const keptFor = (projects: readonly ProjectName[]) =>454+ Effect.flatMap(Effect.service(StandingPostures), (store) =>455+ store.get(projects)456+ );457+458+const decided = (seq: number): ProjectEvent =>459+ ProjectEvent.cases.Decided.make({460+ at: at(41),461+ choice: "accept",462+ decision: DecisionId.make("dec-000001"),463+ seq,464+ });465+466+const ledgerAppended = (seq: number): ProjectEvent =>467+ ProjectEvent.cases.LedgerAppended.make({468+ at: at(42),469+ entry: LedgerEntry.cases.ValueSet.make({470+ at: at(42),471+ by: Handle.make("ines-v"),472+ key: EnvKey.make("API_KEY"),473+ seq: 1,474+ }),475+ seq,476+ });477+478+describe("the kept standing postures in D1", () => {479+ it.effect("reads the migration the platform's D1 applies", () =>480+ Effect.gen(function* () {481+ expect(yield* migration(posturesMigration)).toBe(StandingPosturesDdl);482+ })483+ );484+485+ it.effect("keeps each project's posture, when it moves and what it saw", () =>486+ Effect.gen(function* () {487+ yield* keep([488+ [datekit, sealed],489+ [burrow, open],490+ ]);491+492+ expect(493+ yield* keptFor([datekit, burrow, ProjectName.make("ghost")])494+ ).toStrictEqual(495+ new Map([496+ [datekit, sealed],497+ [burrow, open],498+ ])499+ );500+ expect(yield* keptFor([])).toStrictEqual(new Map());501+ }).pipe(Effect.provide(withPostures))502+ );503+504+ it.effect(505+ "clears a project's posture with each event that can move it, and keeps it through the rest",506+ () =>507+ Effect.gen(function* () {508+ const after = (event: (seq: number) => ProjectEvent, seq: number) =>509+ Effect.gen(function* () {510+ yield* keep([511+ [datekit, { ...open, seen: seq - 1 }],512+ [burrow, open],513+ ]);514+ yield* apply(rows(datekit, seq, [event]));515+516+ return [...(yield* keptFor([datekit, burrow])).keys()].toSorted();517+ });518+519+ expect([520+ yield* after(opened(parseIsoAsk, 1), 1),521+ yield* after(claimed(parseIso), 2),522+ yield* after(landed(datekit, parseIso), 3),523+ yield* after(decided, 4),524+ yield* after(ledgerAppended, 5),525+ yield* after(closedBy(parseIso), 6),526+ ]).toStrictEqual([527+ [burrow, datekit],528+ [burrow, datekit],529+ [burrow],530+ [burrow],531+ [burrow],532+ [burrow, datekit],533+ ]);534+ }).pipe(Effect.provide(withPostures))535+ );536+537+ it.effect(538+ "keeps nothing from a read the projection has since moved past, nor an older read over a newer",539+ () =>540+ Effect.gen(function* () {541+ yield* apply(542+ rows(datekit, 1, [opened(parseIsoAsk, 1), claimed(parseIso)])543+ );544+545+ // Read when datekit had one event; the projection has applied two.546+ yield* keep([[datekit, { ...open, seen: 1 }]]);547+548+ const stale = yield* keptFor([datekit]);549+550+ yield* keep([[datekit, { ...sealed, seen: 2 }]]);551+ yield* keep([[datekit, { ...open, seen: 2 }]]);552+ yield* keep([[burrow, { ...open, seen: 3 }]]);553+ yield* keep([[burrow, { ...sealed, seen: 2 }]]);554+555+ expect({556+ kept: yield* keptFor([datekit, burrow]),557+ stale,558+ }).toStrictEqual({559+ kept: new Map([560+ [datekit, { ...open, seen: 2 }],561+ [burrow, { ...open, seen: 3 }],562+ ]),563+ stale: new Map(),564+ });565+ }).pipe(Effect.provide(withPostures))566+ );567+568+ it.effect(569+ "before its migration, projects every event and keeps nothing, with a warning",570+ () =>571+ Effect.gen(function* () {572+ const warnings: string[] = [];573+574+ const keeper = Logger.make(({ logLevel, message }) => {575+ warnings.push(`${logLevel}: ${String(message)}`);576+ });577+578+ yield* Effect.gen(function* () {579+ yield* apply(580+ rows(datekit, 1, [581+ opened(parseIsoAsk, 1),582+ landed(datekit, parseIso),583+ decided,584+ ])585+ );586+ yield* keep([[datekit, { ...open, seen: 3 }]]);587+588+ expect(yield* keptFor([datekit])).toStrictEqual(new Map());589+590+ const cursor = yield* Effect.flatMap(591+ Effect.service(SqlClient),592+ (sql) => sql<{ readonly seq: number }>`SELECT seq FROM cursor`593+ );594+595+ expect(cursor.map(({ seq }) => seq)).toStrictEqual([3]);596+ }).pipe(Effect.provide(Logger.layer([keeper])));597+598+ expect(warnings.map((line) => line.split(":")[0])).toStrictEqual([599+ "Warn",600+ "Warn",601+ ]);602+ }).pipe(Effect.provide(beforePostures))603+ );604+});modified:packages/project/test/standing-posture.test.ts+300 added-24 removed
1 /**2 * A listed project's posture, as its own record says it now: each listing3 * the projection gives is overlaid with the posture its project's ledger4- * stands at, read as anyone reads it, a few projects at once. A project the5- * platform never made, or one whose read breaks, keeps the posture the6- * projection listed, and the list still answers.4+ * stands at, a few projects at once. A project the platform never made, or5+ * one whose read breaks, keeps the posture the projection listed, and the6+ * list still answers. What was read is kept (`StandingPostures`) until the7+ * instant it moves by the clock, so a second list reads only the projects8+ * whose kept posture ran out; a store that fails is a miss.9 */10 import { describe, expect, it } from "@effect/vitest";11+import { ProjectEvent } from "@repo/protocol/domain/event";12 import type { ProjectListing } from "@repo/protocol/domain/front-page";10-import { ProjectName } from "@repo/protocol/ids";13+import { LedgerEntry } from "@repo/protocol/domain/visibility";14+import { DecisionId, Handle, LandedSha, ProjectName } from "@repo/protocol/ids";15 import type { Posture } from "@repo/protocol/posture";12-import { Principal } from "@repo/protocol/principal";16 import { UnknownProject } from "@repo/protocol/refusal";17 import { untouchable } from "@repo/testkit/untouchable";15-import { Array, DateTime, Duration, Effect, Layer, Logger, Ref } from "effect";18+import {19+ Array,20+ DateTime,21+ Duration,22+ Effect,23+ Layer,24+ Logger,25+ Option,26+ Ref,27+} from "effect";28+import { TestClock } from "effect/testing";29 30+import { projectedRows } from "../src/outbox.ts";31 import type { ProjectApi } from "../src/project.ts";32+import { StandingPosturesD1 } from "../src/projection-d1/postures.ts";33+import { ProjectionD1 } from "../src/projection-d1/projection.ts";34+import { Projection } from "../src/projection.ts";35 import { Projects } from "../src/projects.ts";19-import { withStandingPosture } from "../src/standing-posture.ts";36+import {37+ StandingPostures,38+ withStandingPosture,39+} from "../src/standing-posture.ts";40+import { StandingPosturesMemory } from "../src/standing-posture/memory.ts";41+import {42+ frontPageMigration,43+ migrated,44+ posturesMigration,45+ projectsMigration,46+} from "./projection-d1.fixtures.ts";47 48 const datekit = ProjectName.make("datekit");49 50 const ghost = ProjectName.make("ghost");4 unmodified lines55 56 const landedAt = DateTime.makeUnsafe("2026-10-08T12:00:00Z");57 58 /**32- * An api whose only answered read is `ledger`, standing at `posture` for33- * anyone; a person's read is a defect, since a listing is public.59+ * An api whose only answered read is `standing`, at `posture`, having seen60+ * 7 events, moving by the clock at `until` when given.61 */62 const standingAt = (63 project: ProjectName,64 posture: Posture,38- before: Effect.Effect<void> = Effect.void65+ before: Effect.Effect<void> = Effect.void,66+ until: Option.Option<DateTime.Utc> = Option.none()67 ) =>68 untouchable<ProjectApi>("ProjectApi", {41- ledger: (caller) =>42- Principal.match(caller, {43- Anonymous: () =>44- Effect.as(before, {45- entries: [],46- layers: [],47- posture,48- postureLabel: "As its ledger says",49- project,50- }),51- Person: ({ handle }) =>52- Effect.die(`a listing read ${project}'s ledger as ${handle}`),53- }),69+ standing: () =>70+ Effect.as(71+ before,72+ Option.match(until, {73+ onNone: () => ({ posture, seen: 7 }),74+ onSome: (at) => ({ posture, seen: 7, until: at }),75+ })76+ ),77 });78 79 /**80 * The platform's projects: datekit's ledger stands sealed, burrow's open,15 unmodified lines96 97 case broken: {98 return Effect.succeed(99 untouchable<ProjectApi>("ProjectApi", {77- ledger: () => Effect.die("the project's storage is down"),100+ standing: () => Effect.die("the project's storage is down"),101 })102 );103 }104 11 unmodified lines116 { openAsks: 0, posture: "sourceAvailable", project: broken },117 { landedAt, openAsks: 2, posture: "openOnSchedule", project: burrow },118 ];119 120+/** The projects as `listed` stands them, `datekit` sealed and `burrow` open. */121+const standingListed = [122+ {123+ landedAt,124+ openAsks: 3,125+ posture: "openWithSealedEvidence",126+ project: datekit,127+ },128+ { openAsks: 1, posture: "openCore", project: ghost },129+ { openAsks: 0, posture: "sourceAvailable", project: broken },130+ { landedAt, openAsks: 2, posture: "open", project: burrow },131+] satisfies readonly ProjectListing[];132+133+/** One hour past the TestClock's start: when datekit's narrowing takes effect, below. */134+const inAnHour = DateTime.makeUnsafe(Duration.toMillis(Duration.hours(1)));135+136+/**137+ * `platform`, each project's `standing` read counted in `reads`; datekit's138+ * moves by the clock at `datekitUntil`.139+ */140+const counted = (141+ reads: Ref.Ref<readonly ProjectName[]>,142+ datekitUntil: Option.Option<DateTime.Utc> = Option.none()143+) =>144+ Layer.succeed(145+ Projects,146+ Projects.of({147+ create: () => Effect.die("a listing makes no project"),148+ get: (project) => {149+ const read = Ref.update(reads, (all) => [...all, project]);150+151+ switch (project) {152+ case datekit: {153+ return Effect.succeed(154+ standingAt(datekit, "openWithSealedEvidence", read, datekitUntil)155+ );156+ }157+158+ case burrow: {159+ return Effect.succeed(standingAt(burrow, "open", read));160+ }161+162+ case broken: {163+ return Effect.succeed(164+ untouchable<ProjectApi>("ProjectApi", {165+ standing: () =>166+ Effect.andThen(read, Effect.die("the storage is down")),167+ })168+ );169+ }170+171+ default: {172+ return Effect.fail(new UnknownProject({ project }));173+ }174+ }175+ },176+ })177+ );178+179+/** A store whose every read and write dies. */180+const brokenStore = Layer.succeed(StandingPostures, {181+ get: () => Effect.die("D1 is down"),182+ put: () => Effect.die("D1 is down"),183+});184+185 describe("a listing's standing posture", () => {186 it.effect("reads each project's posture from its own ledger", () =>187 Effect.gen(function* () {188 const standing = yield* withStandingPosture(listed);83 unmodified lines272 expect(yield* Ref.get(peak)).toBe(8);273 })274 );275 });276+277+describe("a listing's kept standing posture", () => {278+ it.effect("is read once: a second list reads no project", () =>279+ Effect.gen(function* () {280+ const reads = yield* Ref.make<readonly ProjectName[]>([]);281+282+ const twice = yield* Effect.all([283+ withStandingPosture(listed),284+ withStandingPosture(listed),285+ ]).pipe(286+ Effect.provide(Layer.merge(counted(reads), StandingPosturesMemory))287+ );288+289+ expect(twice).toStrictEqual([standingListed, standingListed]);290+ // ghost was never made and broken's read fails: neither is kept, so291+ // each is asked again; datekit and burrow were kept.292+ expect((yield* Ref.get(reads)).toSorted()).toStrictEqual([293+ broken,294+ broken,295+ burrow,296+ datekit,297+ ]);298+ })299+ );300+301+ it.effect(302+ "keeps what it read, with the instant it moves and the event it saw",303+ () =>304+ Effect.gen(function* () {305+ const reads = yield* Ref.make<readonly ProjectName[]>([]);306+307+ const kept = yield* Effect.gen(function* () {308+ yield* withStandingPosture(listed);309+310+ const store = yield* StandingPostures;311+312+ return yield* store.get([datekit, ghost, broken, burrow]);313+ }).pipe(314+ Effect.provide(315+ Layer.merge(316+ counted(reads, Option.some(inAnHour)),317+ StandingPosturesMemory318+ )319+ )320+ );321+322+ expect(kept).toStrictEqual(323+ new Map([324+ [325+ datekit,326+ { posture: "openWithSealedEvidence", seen: 7, until: inAnHour },327+ ],328+ [burrow, { posture: "open", seen: 7 }],329+ ])330+ );331+ })332+ );333+334+ it.effect(335+ "is read again once the instant it moves by the clock has come",336+ () =>337+ Effect.gen(function* () {338+ const reads = yield* Ref.make<readonly ProjectName[]>([]);339+340+ yield* Effect.gen(function* () {341+ yield* withStandingPosture(listed);342+ yield* TestClock.adjust(Duration.minutes(59));343+ yield* withStandingPosture(listed);344+345+ // The first list read both; the second, inside the hour, neither.346+ expect(347+ (yield* Ref.get(reads)).filter((at) => at !== broken).toSorted()348+ ).toStrictEqual([burrow, datekit]);349+350+ yield* TestClock.adjust(Duration.minutes(1));351+ yield* Ref.set(reads, []);352+ yield* withStandingPosture(listed);353+ }).pipe(354+ Effect.provide(355+ Layer.merge(356+ counted(reads, Option.some(inAnHour)),357+ StandingPosturesMemory358+ )359+ )360+ );361+362+ expect(363+ (yield* Ref.get(reads)).filter((at) => at !== broken)364+ ).toStrictEqual([datekit]);365+ })366+ );367+368+ it.effect(369+ "lists every project with its standing when the store cannot be read or written",370+ () =>371+ Effect.gen(function* () {372+ const reads = yield* Ref.make<readonly ProjectName[]>([]);373+374+ const standing = yield* withStandingPosture(listed).pipe(375+ Effect.provide(Layer.merge(counted(reads), brokenStore))376+ );377+378+ expect(standing).toStrictEqual(standingListed);379+ })380+ );381+});382+383+/** The kept postures and the projection over the platform's D1, in sqlite. */384+const d1 = Layer.mergeAll(StandingPosturesD1, ProjectionD1).pipe(385+ Layer.provideMerge(386+ migrated([frontPageMigration, projectsMigration, posturesMigration])387+ )388+);389+390+/** One event of `project`'s, as the projection is handed it from the outbox. */391+const projected = (project: ProjectName, event: ProjectEvent) =>392+ Effect.flatMap(projectedRows(project, [event], landedAt), (rows) =>393+ Projection.use((projection) => projection.apply(rows))394+ );395+396+describe("a listing's standing posture kept in D1 beside the projection", () => {397+ it.effect(398+ "is read again only for the project whose event the projection applied",399+ () =>400+ Effect.gen(function* () {401+ const reads = yield* Ref.make<readonly ProjectName[]>([]);402+403+ yield* Effect.gen(function* () {404+ /** One list; the projects it read, but broken, whose read always fails. */405+ const list = Effect.gen(function* () {406+ yield* Ref.set(reads, []);407+408+ expect(yield* withStandingPosture(listed)).toStrictEqual(409+ standingListed410+ );411+412+ return (yield* Ref.get(reads))413+ .filter((at) => at !== broken)414+ .toSorted();415+ });416+417+ const first = yield* list;418+ const warm = yield* list;419+420+ yield* projected(421+ datekit,422+ ProjectEvent.cases.Landed.make({423+ at: landedAt,424+ landing: {425+ assisted: [],426+ author: Handle.make("bram"),427+ credits: [],428+ landedAt,429+ parent: LandedSha.make("b".repeat(40)),430+ project: datekit,431+ sha: LandedSha.make("a".repeat(40)),432+ },433+ seq: 1,434+ })435+ );436+437+ const afterLanding = yield* list;438+439+ yield* projected(440+ burrow,441+ ProjectEvent.cases.LedgerAppended.make({442+ at: landedAt,443+ entry: LedgerEntry.cases.PostureChanged.make({444+ at: landedAt,445+ decision: DecisionId.make("dec-000001"),446+ from: "openCore",447+ seq: 1,448+ to: "open",449+ }),450+ seq: 1,451+ })452+ );453+454+ expect([first, warm, afterLanding, yield* list]).toStrictEqual([455+ [burrow, datekit],456+ [],457+ [datekit],458+ [burrow],459+ ]);460+ }).pipe(Effect.provide(Layer.merge(counted(reads), d1)));461+ })462+ );463+});