Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent bbace25 · Browse files · 31 files+2366 added−261 removed
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

31 files+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.78CREATE 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
modified:apps/platform/src/ports.ts+6 added-3 removed
38 unmodified lines
39import { LanderIsogit } from "@repo/project/lander/isogit";40import { FinishersFromChecks } from "@repo/project/project";41import type { Projection } from "@repo/project/projection";42import { FrontPageD1 } from "@repo/project/projection-d1/front-page";43import { StandingPosturesD1 } from "@repo/project/projection-d1/postures";44import { ProjectionD1 } from "@repo/project/projection-d1/projection";45import { ProjectionMemory } from "@repo/project/projection/memory";46import type { Projects } from "@repo/project/projects";47import type { RulesEvaluator } from "@repo/rules/rules-evaluator";
74 unmodified lines
122const 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 lines
modified:apps/platform/src/project-calls.ts+1 added
137 unmodified lines
138 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 lines
modified:apps/platform/src/well-known.ts+125 added-23 removed
8 unmodified lines
9 * 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 */24import { describedIn } from "@repo/agent-kit/generated-file";25import {26 contributeDescription,
1 unmodified line
28 contributeSkillPaths,29} from "@repo/agent-kit/project-skill";30import { wellKnownSkills } from "@repo/agent-kit/well-known";31import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";32import { CodeStore } from "@repo/project/code-store";33import { CodeCache } from "@repo/project/code/cache";34import { FrontPage } from "@repo/project/front-page";35import { landedRef } from "@repo/project/lander";36import { Projects } from "@repo/project/projects";37import { ProjectName, RepoName, RepoPath } from "@repo/protocol/ids";38import type { CommitSha } from "@repo/protocol/ids";39import type { Layer } from "effect";29import { Array as Arr, Context, Effect, Option, Order, Schema } from "effect";40import {41 Array as Arr,42 Cause,43 Context,44 Effect,45 Option,46 Order,47 Schema,48} from "effect";49import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";5051/** Where the index and the skills are served. */52const ROOT = "/.well-known/agent-skills";
24 unmodified lines
77/** The bytes as text, unless they are not UTF-8. */78const textOf = (bytes: Uint8Array) =>79 Option.liftThrowable(() => utf8.decode(bytes))();8081/** The kept skill's version, in its key: it moves when what is kept changes. */82const SKILL_VERSION = 1;8384/** A project's skill at a landed commit as the store keeps it: its text, or none. */85const KeptSkill = Schema.fromJsonString(86 Schema.Struct({ content: Schema.optionalKey(Schema.String) })87);8889const decodeKept = Schema.decodeOption(KeptSkill);9091const encodeKept = Schema.encodeEffect(KeptSkill);9293/**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 */66const landedSkill = (97const 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;10274 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 );11079 if (Option.isNone(landed)) {80 return Option.none();111 if (Option.isSome(recorded)) {112 return Option.some<CommitSha>(recorded.value);113 }114115 const host = yield* RepoHost;116 const refs = yield* host.refs(RepoName.make(project));117118 return Option.orElse(Option.fromUndefinedOr(refs.get(landedRef)), () =>119 Option.fromUndefinedOr(refs.get(mainRef))120 );121 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeedNone));122123/** `project`'s skill file at `landed`, read from its repo: none when it has none. */124const skillAt = (project: ProjectName, landed: CommitSha) =>125 Effect.gen(function* () {126 const host = yield* RepoHost;127 const [path] = contributeSkillPaths(project);128129 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 );134135 return Option.flatMap(bytes, textOf);136 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeedNone));137138/**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 */143const 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}`;148149 return yield* cache.through(150 key,151 Effect.gen(function* () {152 const kept = Option.flatMap(yield* store.get(key), decodeKept);153154 if (Option.isSome(kept)) {155 return Option.fromUndefinedOr(kept.value.content);156 }157158 const read = yield* skillAt(project, landed);159160 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 );171172 return read;173 })174 );175 });176177/**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 */181const 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 );190191const decodeProject = Schema.decodeUnknownOption(ProjectName);192193/** The index: every listed project's landed skill, by name. */194const index = Effect.gen(function* () {
56 unmodified lines
251 * the router matched it.252 */253export 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);257258 if (pathname === INDEX) {259 return index;
25 unmodified lines
285286/**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 */294export 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 );306307 yield* router.add("*", `${ROOT}/*`, (request) =>308 request.method !== "GET" && request.method !== "HEAD"
11 unmodified lines
modified:apps/platform/test/do-projects.test.ts+1 added
194 unmodified lines
195 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 lines
modified:apps/platform/test/front-page.test.ts+10 added-1 removed
22 unmodified lines
23import { Lander } from "@repo/project/lander";24import { LanderIsogit } from "@repo/project/lander/isogit";25import { FinishersFromChecks } from "@repo/project/project";26import { FrontPageD1 } from "@repo/project/projection-d1/front-page";27import { StandingPosturesD1 } from "@repo/project/projection-d1/postures";28import { ProjectionD1 } from "@repo/project/projection-d1/projection";29import { Projects } from "@repo/project/projects";30import { ProjectsMemory } from "@repo/project/projects/memory";31import type { Client } from "@repo/protocol/contracts";
151 unmodified lines
183 FrontPageD1,184 MemoryRateLimits(WorkerCaps),185 ProjectionD1,186 rules,187 StandingPosturesD1,188 UpstreamRepoHost189 ).pipe(190 Layer.provideMerge(migrated),191 Layer.provideMerge(LanderIsogit),
72 unmodified lines
264 });265266describe("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 lines
300 { landedAt: at(noon), openAsks: 1, posture: "open", project },301 ],302 },303 });304305 yield* world.forget;306307 // 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 lines
46 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 lines
modified:apps/platform/test/posture-listing.test.ts+76 added-36 removed
11 unmodified lines
12import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";13import { FrontPageMemory } from "@repo/project/front-page/memory";14import type { ProjectApi } from "@repo/project/project";15import { Projects } from "@repo/project/projects";16import { StandingPosturesMemory } from "@repo/project/standing-posture/memory";17import { Contracts } from "@repo/protocol/contracts";18import { ProjectName } from "@repo/protocol/ids";19import {20 Anonymous,
1 unmodified line
22 CurrentPrincipal,23} from "@repo/protocol/principal";24import { UnknownProject } from "@repo/protocol/refusal";25import { untouchable } from "@repo/testkit/untouchable";25import { Effect, Layer } from "effect";26import { Effect, Layer, Ref } from "effect";27import { RpcTest } from "effect/rpc";2829import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";30import { Handlers } from "../src/handlers.ts";
1 unmodified line
32const datekit = ProjectName.make("datekit");3334const ghost = ProjectName.make("ghost");3535/** datekit's project, whose only answered read is its ledger, standing sealed. */36const 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 */40const 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 });5152/** The handlers over projects whose datekit counts its reads in `reads`. */53const platformCounting = (reads: Ref.Ref<number>) =>47const 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 );7980const platform = Layer.unwrap(81 Effect.map(Ref.make(0), (reads) => platformCounting(reads))82);8384const anonymous = Layer.succeed(Authenticated, (effect) =>85 Effect.provideService(effect, CurrentPrincipal, Anonymous.make({}))
15 unmodified lines
101 ],102 });103 }).pipe(Effect.provide(Layer.mergeAll(platform, anonymous)))104 );105106 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);111112 const [first, second] = yield* Effect.gen(function* () {113 const anyone = yield* RpcTest.makeClient(Contracts);114115 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 );129130 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 lines
5 * 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 */12import { describe, expect, it } from "@effect/vitest";13import { RefName, RepoHost } from "@repo/artifacts/repo-host";14import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";15import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";16import { CodeStoreMemory } from "@repo/project/code-store/memory";17import { FrontPageMemory } from "@repo/project/front-page/memory";18import { landedRef } from "@repo/project/lander";19import type { ProjectApi } from "@repo/project/project";20import { Projects } from "@repo/project/projects";17import { ProjectName, RepoName } from "@repo/protocol/ids";21import { LandedSha, ProjectName, RepoName } from "@repo/protocol/ids";22import { UnknownProject } from "@repo/protocol/refusal";23import { gitClient } from "@repo/testkit/git-client";24import { untouchable } from "@repo/testkit/untouchable";19import { Effect, Layer, Option, Schema } from "effect";25import { Effect, Layer, Option, Ref, Schema } from "effect";2627import { agentSkills } from "../src/well-known.ts";28import { coreLoopWorld } from "./world.ts";29
154 unmodified lines
184 agentSkills(new Request(`https://platform.test${path}`)),185 read186 );187188/** Projects the platform never made: each skill is read at its repo's refs. */189const 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);196197describe(agentSkills, () => {198 it.effect(199 "reads each skill at the landed mirror, not at a main that moved past it",200 () =>
51 unmodified lines
252 credits: [],253 entries: [],254 projects: [listing(datekit)],255 })241 )256 ).pipe(Layer.merge(noneMade))257 )258 )259 );260});261262/** The memory store, each file read and each refs read counted. */263const countedHost = (counts: Ref.Ref<{ files: number; refs: number }>) =>264 Layer.effect(265 RepoHost,266 Effect.gen(function* () {267 const host = yield* RepoHost;268269 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));284285/** Projects whose record says each one's main landed where `landed` holds. */286const 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 );305306describe("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 });312313 const landed = yield* Ref.make<ReadonlyMap<ProjectName, LandedSha>>(314 new Map()315 );316317 yield* Effect.gen(function* () {318 const host = yield* RepoHost;319 const client = yield* gitClient(memoryFs());320321 const first = yield* client.commit("Land", [[skillPath, skill]]);322323 const moved = yield* client.commit(324 "Land again",325 [[skillPath, skill.replace("Answer one", "Answer any one")]],326 [first]327 );328329 const bare = yield* client.commit("Start burrow", [330 ["README.md", "burrow\n"],331 ]);332333 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 }342343 yield* Ref.set(344 landed,345 new Map([346 [datekit, LandedSha.make(first)],347 [burrow, LandedSha.make(bare)],348 ])349 );350351 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 );358359 /** 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 );364365 const once = yield* described;366 const readOnce = yield* reads;367 const twice = yield* described;368 const readTwice = yield* reads;369370 yield* Ref.update(371 landed,372 (all) => new Map([...all, [datekit, LandedSha.make(moved)]])373 );374375 const afterMove = yield* described;376377 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
1import { createFileRoute } from "@tanstack/react-router";2import { env } from "cloudflare:workers";34import { serverClient } from "../../server/client.ts";5import { callbackHandler } from "../../server/session.ts";67// 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).10export 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 lines
18import { Effect, Option } from "effect";1920import type { Backend } from "./rpc.ts";21import {22 clearedCookie,22 clearedCookies,23 credentialFrom,24 settingCookies,25 withCredential,26} from "./session.ts";
4 unmodified lines
3132 return new Request(new URL(`${pathname}${search}`, platformUrl), request);33};3435/** `response` as it came, also expiring the session cookie. */35/** `response` as it came, also expiring the session cookie and its kept handle. */36const 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 lines
modified:apps/web/src/server/session.ts+134 added-22 removed
11 unmodified lines
12 * 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 */27import { Brand } from "@repo/brand";28import { Client } from "@repo/protocol/contracts";29import { Handle as HandleSchema } from "@repo/protocol/ids";30import type { Handle } from "@repo/protocol/ids";31import { Data, Effect, Option, Redacted, Schema } from "effect";32import type { Layer } from "effect";33
4 unmodified lines
38 * shadow it.39 */40export const SESSION_COOKIE = "__Host-session";4142/** The cookie the signed-in handle is kept in beside the session, for `whoami`. */43export const HANDLE_COOKIE = "__Host-handle";4445/** The cookie a sign-in in progress waits in: its state, PKCE verifier and way back. */46const SIGN_IN_COOKIE = "__Host-sign-in";4748/** How long a sign-in in progress waits for its callback: ten minutes. */
82 unmodified lines
131132/** The `Set-Cookie` value that ends the session now. */133export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);134135/** The `Set-Cookie` values that end the session and forget its handle, now. */136export const clearedCookies = () => [137 clearedCookie(),138 lockedCookie(HANDLE_COOKIE, "", 0),139];140141const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);142143/** `headers`, also setting each of `cookies` (each its own `Set-Cookie` line). */144export const settingCookies = (
39 unmodified lines
184 verifier,185 };186});187188// --- The handle kept beside the session --------------------------------------189190/**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 */195const HANDLE_LEARNED_SECONDS = 24 * 60 * 60;196197/** The token's SHA-256, in base64url: what binds a kept handle to its session. */198const 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 );205206/**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 */211const handleCookie = (token: string, handle: Handle, maxAgeSeconds: number) =>212 Effect.map(fingerprintOf(token), (fingerprint) =>213 lockedCookie(HANDLE_COOKIE, `${fingerprint}.${handle}`, maxAgeSeconds)214 );215216const decodeHandle = Schema.decodeUnknownOption(HandleSchema);217218/** The handle kept for the session `token`, if the request carries one kept for it. */219const keptHandle = (request: Request, token: string) =>220 Effect.map(fingerprintOf(token), (fingerprint) =>221 Option.flatMap(cookieValue(request, HANDLE_COOKIE), (value) => {222 const at = value.indexOf(".");223224 return at > 0 && value.slice(0, at) === fingerprint225 ? decodeHandle(value.slice(at + 1))226 : Option.none();227 })228 );229230/** The handle the platform's `status` names for the session `token`, asked through `clientFor`. */231const 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 );247248// --- Where the browser goes -------------------------------------------------249250/** The web's OAuth client id at `origin`: the URL of its metadata document. */251const clientIdOf = (origin: string) => `${origin}${AUTH_PATHS.client}`;
193 unmodified lines
445/**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 */454export 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 lines
477 origin: here.origin,478 verifier: pending.verifier,479 });480481 const token = Redacted.value(answer.access_token);482 const lives = answer.expires_in - SESSION_MARGIN_SECONDS;483484 // 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 );490491 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 lines
501 );502503// --- Sign-out, who, and the client -------------------------------------------504414/** `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. */506export const signOutHandler = (_handled: Handled): Response =>416 redirect("/", [clearedCookie()]);507 redirect("/", clearedCookies());508509/** `/auth/whoami`'s answer: the handle signed in, or nothing (`features/auth/who.ts` reads it). */510const whoAnswer = (511 who: { readonly handle?: Handle },
3 unmodified lines
515 headers: settingCookies({ "cache-control": "no-store" }, cookies),516 });517518/**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 */528export 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 );563564/**
20 unmodified lines
modified:apps/web/test/session.test.ts+187 added-13 removed
22 unmodified lines
23 challengeOf,24 clearedCookie,25 clientMetadataHandler,26 credentialFrom,27 HANDLE_COOKIE,28 pkce,29 SESSION_COOKIE,30 sessionCookie,31 signInHandler,
326 unmodified lines
358 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 );368369 it.effect("carries the session on a GET too, at the platform's URL", () =>
32 unmodified lines
402403 return { location, response, state };404 });405402/** 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. */407const clientOver = (env: Env) => (request: Request) =>408 serverClientOver(backend)(env, request);409410/** A callback whose platform must not be reached. */411const unreachableCallback = callbackHandler(412 unreachable,413 clientOver(unreachable)414);415416/**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 */421const 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);429430 const platform = recorder((request) =>431 new URL(request.url).pathname.startsWith("/rpc")432 ? status(request)433 : answer()434 );435436 const env = envWith(platform.fetch);437438 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 lines
516517 const [exchange, ...more] = seen;518 const form = new URLSearchParams(exchange?.body);519491 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 lines
603 Effect.gen(function* () {604 const { state } = yield* signIn("/auth/signin");605606 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 lines
620621 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 lines
681 );682});683684describe("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 lines
698 ];699 });700701 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 lines
767 },768 ]);769 expect(response.headers.get("cache-control")).toBe("no-store");770 expect(yield* textOf(response)).toBe('{"handle":"ines-v"}');771772 // A session from before the handle was kept: asked once, then kept.773 const kept = cookiesOf(response).filter(774 ({ name }) => name === HANDLE_COOKIE775 );776777 expect(778 kept.map(({ attributes }) => lockedDown(attributes))779 ).toStrictEqual([true]);780781 const again = yield* whoami(unreachable, {782 cookie: [783 `${SESSION_COOKIE}=tok123`,784 ...kept.map(({ pair }) => pair),785 ].join("; "),786 });787788 expect(yield* textOf(again)).toBe('{"handle":"ines-v"}');789 })790 );791792 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 lines
803 cookie: `${SESSION_COOKIE}=stale`,804 });805806 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});814815/** The `Cookie` header a browser sends back after `response`: each cookie it set and did not expire. */816const sentBack = (response: Response) =>817 cookiesOf(response)818 .filter(({ attributes }) => !attributes.includes("max-age=0"))819 .map(({ pair }) => pair)820 .join("; ");821822describe("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) });829830 expect(yield* textOf(who)).toBe('{"handle":"ines-v"}');831 expect(who.headers.getSetCookie()).toStrictEqual([]);832 })833 );834835 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);843844 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 );857858 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 );868869 expect(870 cookiesOf(response)871 .map(({ name }) => name)872 .filter((name) => name !== "__Host-sign-in")873 ).toStrictEqual([SESSION_COOKIE]);874 })875 );876877 it.effect("is not believed for another session: the platform is asked", () =>878 Effect.gen(function* () {879 const { response } = yield* signInAndBack("/auth/signin", "c0de");880881 const handle = cookiesOf(response).find(882 ({ name }) => name === HANDLE_COOKIE883 );884885 const platform = recorder(statusReply(STATUS_OF_INES));886887 const who = yield* whoami(envWith(platform.fetch), {888 cookie: `${SESSION_COOKIE}=another-token; ${handle?.pair ?? ""}`,889 });890891 expect(yield* textOf(who)).toBe('{"handle":"ines-v"}');892 expect(893 (yield* platform.seen).map(({ authorization }) => authorization)894 ).toStrictEqual(["Bearer another-token"]);895 })896 );897898 it.effect("is expired, unread, once no session is left", () =>899 Effect.gen(function* () {900 const { response } = yield* signInAndBack("/auth/signin", "c0de");901902 const handle = cookiesOf(response).find(903 ({ name }) => name === HANDLE_COOKIE904 );905906 const who = yield* whoami(unreachable, { cookie: handle?.pair ?? "" });907908 expect(yield* textOf(who)).toBe("{}");909 expect(expiriesOf(who)).toStrictEqual([[HANDLE_COOKIE, true]]);910 })911 );912});913914/** A JSON object, read as data. */915const decodeDocument = Schema.decodeUnknownEffect(916 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))917);
95 unmodified lines
modified:infra/smoke.ts+110 added-15 removed
15 unmodified lines
16 * 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 lines
69 "platform-root",70] as const;7172/** The web's probes, run after the platform's when smoke has the web's origin. */65export const webProbes = ["web-front-page", "web-llms-txt"] as const;73export 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;8081/** How long an agent surface may take to answer before smoke warns: 500 ms. */82export const AGENT_BUDGET_MS = 500;8384/** An example every seeded stage holds, and one of its asks. */85const SEEDED = { ask: "format-ordinal", project: "datekit" } as const;8687/** The agent surfaces on the web smoke reads, each by its path and the media type it answers with. */88export 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}[];110111/** Every probe, in the order smoke runs them. */112export const probes = [...platformProbes, ...webProbes] as const;113114export const Probe = Schema.Literals(probes);
33 unmodified lines
148 return `${failed} failed at ${this.origin}`;149 }150}151108/** 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 */156export 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}166167/**168 * Why one probe failed, in a line a person reads. A transient miss is the
270 unmodified lines
439 Effect.asVoid440 );441};442443/** An agent surface on the web: 200, with the media type it answers with. */444const agentSurface = (445 web: string,446 { contentType, path }: (typeof agentProbes)[number]447) => {448 const label = `GET ${path} on the web`;449450 return send(label, HttpClientRequest.get(`${web}${path}`)).pipe(451 Effect.flatMap(statusIs(label, 200, notServingYet)),452 Effect.flatMap(typeIs(label, contentType, contentType))453 );454};455456/**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 */398const webLlmsTxt = (web: string) => {460const webLlmsTxt = (web: string, probe: (typeof agentProbes)[number]) => {461 const label = "GET /llms.txt on the web";462401 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 lines
520 health(origin, Option.fromUndefinedOr(options.stage)),521 settling522 );523524 const { web } = options;525526 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 lines
564 if (Result.isFailure(first.outcome) || failures.length > 0) {565 return yield* new SmokeFailed({ failures, origin });566 }567568 const budgeted = new Set<Probe>(agentProbes.map(({ probe }) => probe));569570 const timings = runs.map(({ elapsedMs, probe }) =>571 budgeted.has(probe)572 ? { budgetMs: AGENT_BUDGET_MS, elapsedMs, probe }573 : { elapsedMs, probe }574 );575576 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 });589590/** Neither `--url` nor bootstrap's record says where the stage lives. */
73 unmodified lines
664 );665666 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 );676677 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 lines
7 HttpServerRequest,8 HttpServerResponse,9} from "effect/http";1011import { AGENT_BUDGET_MS, agentProbes } from "../../../infra/smoke.ts";12import { NoStage, UnknownStage } from "../../../infra/stages.ts";13import {14 main,15 NoOrigin,
3 unmodified lines
19 SmokeFailed,20 webProbes,21} from "../../../scripts/smoke.ts";2222/** What the fake platform answers one request with. */23/** What the fake platform answers one request with, after `delayMs` when given. */24interface Reply {25 readonly status: number;26 readonly body?: string;27 readonly contentType?: string;28 readonly delayMs?: number;29}3031/** A request as the fake platform sees it. */32interface Seen {
109 unmodified lines
142 method: request.method,143 path: url.pathname,144 });145146 if (reply.delayMs !== undefined) {147 yield* Effect.sleep(`${reply.delayMs} millis`);148 }149150 return reply.body === undefined151 ? HttpServerResponse.empty({ status: reply.status })152 : HttpServerResponse.text(reply.body, {153 contentType: reply.contentType ?? "application/json",
155 unmodified lines
309 );310});311312/**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 */318const healthyWeb = ({ method, path }: Seen): Reply => {319 if (method === "GET" && path === "/") {320 return {
10 unmodified lines
331 status: 200,332 };333 }334335 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 }345346 if (method === "GET" && path === "/.well-known/agent-skills/index.json") {347 return {348 body: '{"skills":[]}',349 contentType: "application/json",350 status: 200,351 };352 }353354 return { status: 404 };355};356357describe("smoke against a stage's web", () => {
7 unmodified lines
365366 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 );379380 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 });407408 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);413414 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 );419420 const report = yield* smoke(origin, { web });421422 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 );444445 // 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>();454455 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;457458 asked.set(seen.path, count);459460 return count <= 2 ? { status: 404 } : healthyWeb(seen);461 });462463 const report = yield* smoke(origin, { settling: "10 seconds", web });464465 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 );482483 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 lines
510 {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 lines
646647 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 }));653654 yield* main(["--stage", "dev-oscabriel", "--url", origin]);655
4 unmodified lines
660 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 );669670 it("says to bootstrap first when neither --url nor bootstrap's record names the origin", () => {
10 unmodified lines
modified:packages/project/src/code/commit.ts+154 added-47 removed
2 unmodified lines
3 * 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 */23import { RepoHost } from "@repo/artifacts/repo-host";24import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";25import { treeDiff } from "@repo/git/tree-diff";26import type { Change } from "@repo/git/tree-diff";27import type { ChangedFile, CommitDiff } from "@repo/protocol/domain/code";28import { CommitDiff as CommitDiffSchema } from "@repo/protocol/domain/code";29import { BlobSha, TreeSha } from "@repo/protocol/ids";30import type { CommitSha, RepoName } from "@repo/protocol/ids";31import { UnknownCommit } from "@repo/protocol/refusal";18import { Array, Effect, Option, Order } from "effect";32import { Array, Effect, Option, Order, Schema } from "effect";3334import { CodeStore } from "../code-store.ts";35import type { CodeProject } from "../code.ts";36import { CodeCache } from "./cache.ts";37import { contentsOf } from "./file.ts";38import type { Contents } from "./file.ts";24import { commitViews } from "./log.ts";39import { commitView } from "./log.ts";40import { filesUnder, PATHS_CAP } from "./paths.ts";41import { commitAt } from "./revision.ts";42import { entriesOf, entryAt } from "./tree.ts";43
2 unmodified lines
4647/** The most text a commit's diff carries in all: 2 MiB. */48export const DIFF_TEXT = 2 * 1024 * 1024;4950/** The kept commit's version, in its key: it moves when what is kept changes. */51export const COMMIT_VERSION = 1;5253/** Where a commit's diff is kept in the code store: by its repo and its id. */54export const commitKey = (repo: RepoName, sha: CommitSha) =>55 `${repo}/commit/v${COMMIT_VERSION}/${sha}`;5657/** How many files' sides are read at once: the fan-out the changes are listed with. */58const SIDES_AT_ONCE = 8;5960/** The longest list of changes the cache keeps. */61const KEPT_CHANGES = 1000;6263/** A change, and whether each side is a submodule (whose id names no blob here). */
83 unmodified lines
147148 return after === undefined ? file : { ...file, after };149};150126/** 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. */152const 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 ]);157158/** The length of a side's text, or 0 when it has none. */159const lengthOf = (text: Option.Option<string>) =>160 Option.match(text, { onNone: () => 0, onSome: ({ length }) => length });161162/**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 */167const 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 lines
173 const files: ChangedFile[] = [];174 let budget = DIFF_TEXT;175 let truncated = false;176137 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 }182143 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 );188148 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()];191158 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 }196164 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);200201 if (size > budget) {202 truncated = true;203 files.push(pathOnly(change));204 continue;205 }206207 budget -= size;208166 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 }225226 return { files, truncated };227 });228185/** One commit and the files it changed against its first parent. */186export const commitDiff = (229/** A diff as the store keeps it: JSON, by the protocol's own schema. */230const Kept = Schema.fromJsonString(CommitDiffSchema);231232const decodeKept = Schema.decodeUnknownOption(Kept);233234const encodeKept = Schema.encodeEffect(Kept);235236/** `diff` with its commit's landing, asked of the project's record now. */237const 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 );253254/** The diff kept for `sha` in the code store, if one is and it still decodes. */255const keptDiff = (repo: RepoName, sha: CommitSha) =>256 Effect.gen(function* () {257 const store = yield* CodeStore;258 const text = yield* store.get(commitKey(repo, sha));259260 return Option.filter(261 Option.flatMap(text, decodeKept),262 ({ commit }) => commit.sha === sha263 );264 });265266/** `diff`, which carries no landing, kept for `sha`; a store that fails keeps nothing. */267const keepDiff = (repo: RepoName, sha: CommitSha, diff: CommitDiff) =>268 Effect.gen(function* () {269 const store = yield* CodeStore;270271 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 });278279/** The diff of `sha` against its first parent, computed, with no landing. */280const 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;286287 const commit = yield* commitAt(repo, sha).pipe(288 Effect.orDie,
29 unmodified lines
318 repo,319 Array.sort(changes, byPath)320 ).pipe(Effect.orDie);321229 const [view] = yield* commitViews(project, [commit]);322 return { commit: commitView(commit, Option.none()), files, truncated };323 });324231 if (view === undefined) {232 return yield* Effect.die(`no view of ${sha}`);325/** One commit and the files it changed against its first parent. */326export 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);333334 if (Option.isSome(kept)) {335 return yield* withLanding(project, kept.value);336 }337235 return { commit: view, files, truncated };338 const diff = yield* computedDiff(repo, sha);339340 yield* keepDiff(repo, sha, diff);341342 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 */18import { ProjectName } from "@repo/protocol/ids";19import { Posture } from "@repo/protocol/posture";20import { Array as Arr, DateTime, Effect, Layer, Result, Schema } from "effect";21import { SqlClient } from "effect/sql/SqlClient";22import type { SqlError } from "effect/sql/SqlError";2324import { StandingPostures } from "../standing-posture.ts";25import type {26 StandingEntry,27 StandingPosturesApi,28} from "../standing-posture.ts";2930/** A row as `standing_postures` holds it. */31const Row = Schema.Struct({32 moves_at: Schema.NullOr(Schema.DateTimeUtcFromString),33 posture: Posture,34 project: ProjectName,35 seen: Schema.Int,36});3738const decodeRow = Schema.decodeUnknownOption(Row);3940/** An entry as the row it is written as, one element of the JSON parameter. */41const 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});4748/** A row read back as an entry; `moves_at` only when it is set. */49const entryOf = ({50 moves_at: movesAt,51 posture,52 seen,53}: typeof Row.Type): StandingEntry =>54 movesAt === null ? { posture, seen } : { posture, seen, until: movesAt };5556/** `statement`'s rows, or `missed` and a warning when it fails. */57const 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);6465 if (Result.isSuccess(ran)) {66 return ran.success;67 }6869 yield* Effect.logWarning(warning, ran.failure);7071 return missed;72 });7374export const StandingPosturesD1 = Layer.effect(75 StandingPostures,76 Effect.gen(function* () {77 const sql = yield* SqlClient;7879 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 );101102 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 };126127 return store;128 })129);
modified:packages/project/src/projection-d1/projection.ts+56 added-7 removed
24 unmodified lines
25 * (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 lines
47import type { LandingView } from "@repo/protocol/domain/landing";48import { LedgerEntry } from "@repo/protocol/domain/visibility";49import { ProjectName } from "@repo/protocol/ids";50import type { AskId } from "@repo/protocol/ids";41import { Array, DateTime, Effect, Layer, Order, Schema } from "effect";51import { Array, DateTime, Effect, Layer, Order, Ref, Schema } from "effect";52import { SqlClient } from "effect/sql/SqlClient";53import type { SqlError } from "effect/sql/SqlError";54import type { Statement } from "effect/sql/Statement";55
56 unmodified lines
112 isD1(sql)113 ? sql.batch(statements)114 : sql.withTransaction(Effect.all(statements));115116 const posturesFound = yield* Ref.make(false);117118 /**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 }126127 const tables =128 yield* sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'standing_postures'`;129130 yield* Ref.set(posturesFound, tables.length > 0);131132 return tables.length > 0;133 });134135 /** 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}`;138139 /**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);148149 /** 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 : [];156157 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 lines
206 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 lines
251 const deliver = (events: Array.NonEmptyReadonlyArray<ProjectedEvent>) =>252 Effect.gen(function* () {253 const last = lastOf(events);254255 const postures = yield* keepsPostures.pipe(256 Effect.mapError(257 (failed) => new ProjectionFailed({ reason: failed.message })258 )259 );260261 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 lines
modified:packages/project/src/projection-d1/tables.ts+35 added-1 removed
10 unmodified lines
11 * - `cursor`: the last event applied per project. Events apply in their12 * project's order, once each, so a replayed or late row changes nothing.13 *14 * A migration is never edited once it has run anywhere: 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 */19import type { Handle } from "@repo/protocol/ids";2021/**
86 unmodified lines
108 (SELECT COUNT(*) FROM front_page WHERE front_page.project = cursor.project),109 NULL110FROM cursor;111`;112113/**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 */127export 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.133134CREATE 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 */5import type { ProjectName } from "@repo/protocol/ids";6import { Effect, Layer, Ref } from "effect";78import { StandingPostures } from "../standing-posture.ts";9import type {10 StandingEntry,11 StandingPosturesApi,12} from "../standing-posture.ts";1314/** A fresh, empty store each time the layer is built. */15export const StandingPosturesMemory = Layer.effect(16 StandingPostures,17 Effect.gen(function* () {18 const kept = yield* Ref.make<ReadonlyMap<ProjectName, StandingEntry>>(19 new Map()20 );2122 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);3031 return entry === undefined ? [] : [[project, entry] as const];32 })33 )34 ),35 put: (entries) =>36 Ref.update(kept, (all) => new Map([...all, ...entries])),37 };3839 return store;40 })41);
modified:packages/project/src/visibility/ledger.ts+28 added
164 unmodified lines
165 });166};167168/**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 */175export 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);181182 const noticeDays = Option.match(input.visibility, {183 onNone: () => 0,184 onSome: ({ notice }) => notice.narrowingDays,185 });186187 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};195196/**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 */200export const sealedInEffect = (posture: Standing) =>
77 unmodified lines
modified:packages/project/src/visibility/state.ts+11 added
94 unmodified lines
95import {96 appended,97 declaredBy,98 ledgerFor,99 nextMove,100 nextSeq,101 postureCaughtUp,102 sealedInEffect,103 standing,
1061 unmodified lines
1165 pinSuite,1166 readableLayers,1167 recordRead,1168 settle,1169 standing: (snapshot) => {1170 const now = nowOf();1171 const visibility = visibilityIn(snapshot);11721173 return {1174 posture: standing({ decisions: snapshot.decisions, now, visibility })1175 .posture,1176 until: nextMove({ decisions: snapshot.decisions, now, visibility }),1177 };1178 },1179 };11801181 return port;1182});
10 unmodified lines
modified:packages/project/src/project.ts+39 added
131 unmodified lines
132 TreeSha,133 sameHandle,134} from "@repo/protocol/ids";135import type { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";136import { Posture } from "@repo/protocol/posture";137import { Person, Principal } from "@repo/protocol/principal";138import {139 AskFull,140 DirectPush,
223 unmodified lines
364 readonly content: string;365 readonly path: RepoPath;366}367368/**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 */373export const StandingNow = Schema.Struct({374 posture: Posture,375 seen: Schema.Int,376 until: Schema.optionalKey(Schema.DateTimeUtcFromString),377});378379export type StandingNow = typeof StandingNow.Type;380381/** The refusals `submitAnswer` answers with. */382export type SubmitRefusal =383 | NotClaimed384 | ClaimLapsed
44 unmodified lines
429 ) => 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 lines
886 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 project
4913 unmodified lines
5812 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);58225823 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 lines
modified:packages/project/src/standing-posture.ts+130 added-34 removed
2 unmodified lines
3 * 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 */23import type { ProjectListing } from "@repo/protocol/domain/front-page";16import { Anonymous } from "@repo/protocol/principal";17import { Cause, Effect } from "effect";24import type { ProjectName } from "@repo/protocol/ids";25import type { Posture } from "@repo/protocol/posture";26import { Array as Arr, Cause, Context, DateTime, Effect, Option } from "effect";2728import { Projects } from "./projects.ts";2930/** A project's standing posture as it is kept between lists. */31export 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}4243/** Where a list keeps each project's standing posture between lists. */44export 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}5455/**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 */60export const StandingPostures = Context.Reference<StandingPosturesApi>(61 "project/StandingPostures",62 {63 defaultValue: () => ({64 get: () => Effect.succeed(new Map()),65 put: () => Effect.void,66 }),67 }68);6970/** How many projects a list reads at once (the platform handlers' `FAN_OUT`). */71const READS_AT_ONCE = 8;7273/** `effect`, or `fallback` with a warning if it fails: an interruption stays one. */74const 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 );8485/**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 */93export 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 }100101 const projects = yield* Projects;102 const store = yield* StandingPostures;103 const now = yield* DateTime.now;104 const names = Arr.dedupe(listed.map(({ project }) => project));10535 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 );111112 const fresh = new Map(113 [...kept].filter(114 ([, { until }]) =>115 until === undefined || DateTime.isLessThan(now, until)116 )117 );118119 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 );139140 const found = new Map<ProjectName, StandingEntry>(Arr.getSomes(read));141142 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 }149150 return listed.map((listing): ProjectListing => {151 const entry = found.get(listing.project) ?? fresh.get(listing.project);152153 return entry === undefined154 ? listing155 : { ...listing, posture: entry.posture };156 });157 });
modified:packages/project/src/visibility-port.ts+11 added
31 unmodified lines
32 RepoPath,33 SuiteRoot,34} from "@repo/protocol/ids";35import type { AskId, Handle, ProjectName, RequestId } from "@repo/protocol/ids";36import type { Posture } from "@repo/protocol/posture";37import type { Principal } from "@repo/protocol/principal";38import type { AttemptsExhausted, HeldBackFailed } from "@repo/protocol/refusal";39import { Context, Effect, Layer, Option, Schema } from "effect";40import type { DateTime } from "effect";
220 unmodified lines
261 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 lines
295 pinSuite: () => Option.none(),296 readableLayers: () => new Set(),297 recordRead: () => ({}),298 settle: () => Effect.succeed(true),299 standing: () => ({ posture: "open", until: Option.none() }),300};301302/**303 * How a host gives the project service typed visibility. The default is
30 unmodified lines
modified:packages/project/test/visibility/state.test.ts+34 added-1 removed
20 unmodified lines
21import { Anonymous } from "@repo/protocol/principal";22import { NotDecider } from "@repo/protocol/refusal";23import { advanceTo, at } from "@repo/testkit/clock";24import { areaRoots, suiteRoot } from "@repo/visibility/commitment";25import { Array, Effect, Option, Order } from "effect";25import { Array, DateTime, Effect, Option, Order } from "effect";2627import { drive } from "../../src/answer-runs/steps.ts";28import { ProjectStore } from "../../src/project-store.ts";29import { AdmissionRun, ProjectVisibility } from "../../src/visibility-port.ts";
178 unmodified lines
208 }).pipe(Effect.provide(visibilityWorld()))209 );210211 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));218219 /** 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);223224 return [posture, ledger.posture, until] as const;225 });226227 const waiting = yield* both;228229 yield* advanceTo("2026-10-08T12:00:00Z");230 yield* api.decide(okonkwo, { choice: "accept", decision: decision.id });231232 const accepted = yield* both;233234 yield* advanceTo("2026-10-14T12:00:00Z");235236 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 );243244 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 lines
modified:packages/project/test/code.test.ts+226 added-2 removed
8 unmodified lines
9import { describe, expect, it } from "@effect/vitest";10import { RepoHost } from "@repo/artifacts/repo-host";11import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12import { Brand } from "@repo/brand";13import { CommitDiff } from "@repo/protocol/domain/code";13import { CommitSha, RepoPath } from "@repo/protocol/ids";14import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";15import {16 UnknownCommit,17 UnknownPath,18 UnknownRevision,19} from "@repo/protocol/refusal";19import { DateTime, Effect, Exit, Fiber, Layer, Option, Ref } from "effect";20import {21 DateTime,22 Effect,23 Exit,24 Fiber,25 Layer,26 Option,27 Ref,28 Schema,29} from "effect";30import { TestClock } from "effect/testing";3132import { CodeStore } from "../src/code-store.ts";33import { CodeStoreMemory } from "../src/code-store/memory.ts";34import {35 commitOf,36 fileOf,37 logOf,
1 unmodified line
39 refsOf,40 treeOf,41} from "../src/code.ts";42import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";43import { commitKey, DIFF_TEXT } from "../src/code/commit.ts";44import { filesUnder } from "../src/code/paths.ts";45import { compareTags } from "../src/code/refs.ts";46import { READS_AT_ONCE } from "../src/code/tree.ts";47import {48 big,49 Content,50 datekit,51 fork,52 longHistory,53 project,54 overlappingTrees,55 wide,56 writer,57} from "./code-fixtures.ts";5859const revision = (name: string) => Option.some(name);60
499 unmodified lines
560 }).pipe(Effect.provide(RepoHostMemory))561 );562});563564/** 150 KiB of text: fourteen of them run past a diff's 2 MiB of text. */565const sizable = (name: string) => `${name.padEnd(1023, "y")}\n`.repeat(150);566567/**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 */572const twentyFiles = Effect.gen(function* () {573 const git = yield* writer;574 const name = RepoName.make("twentykit");575576 const paths = Array.from(577 { length: 20 },578 (_, at) => `f${String(at).padStart(2, "0")}.txt`579 );580581 const before = yield* git.commit(582 "Small",583 paths.map((at) => [at, Content.Text({ text: `${at}\n` })] as const),584 [],585 1586 );587588 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 );602603 yield* git.push(name, [["refs/heads/main", after]]);604605 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});617618describe("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);625626 const { diff, paths } = yield* Effect.gen(function* () {627 const made = yield* twentyFiles;628629 yield* Ref.set(reading, true);630631 return {632 diff: yield* commitOf(made.code, made.after),633 paths: made.paths,634 };635 }).pipe(Effect.provide(overlappingTrees(reading, peak, "blob")));636637 const most = yield* Ref.get(peak);638639 // 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});666667/** The memory store, with each blob `readBlob` is asked for counted in `reads`. */668const blobsCountedBy = (reads: Ref.Ref<number>) =>669 Layer.effect(670 RepoHost,671 Effect.gen(function* () {672 const host = yield* RepoHost;673674 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));683684/** What the store keeps under a key, as a diff, if it holds one that decodes. */685const 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 );692693describe("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[])[]>([]);700701 yield* Effect.gen(function* () {702 const { c4, code } = yield* datekit;703704 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 };711712 const first = yield* commitOf(counted, c4);713 const read = yield* Ref.get(blobs);714715 expect([first.commit.landing?.sha, read > 0]).toStrictEqual([716 c4,717 true,718 ]);719720 const kept = yield* keptUnder(commitKey(code.repo, c4));721722 // 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 }));732733 const second = yield* commitOf(counted, c4);734735 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 );745746 it.effect("is computed again when what is kept no longer decodes", () =>747 Effect.gen(function* () {748 const blobs = yield* Ref.make(0);749750 yield* Effect.gen(function* () {751 const { c2, code } = yield* datekit;752 const store = yield* CodeStore;753 const key = commitKey(code.repo, c2);754755 const fresh = yield* commitOf(code, c2).pipe(756 Effect.provideService(CodeStore, CodeStore.defaultValue())757 );758759 const read = yield* Ref.get(blobs);760761 yield* store.put(key, '{"files":"no longer a diff"}');762763 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});772773/** The memory store, with each tree id `readTree` is asked for counted in `reads`. */774const countedBy = (reads: Ref.Ref<readonly string[]>) =>775 Layer.effect(776 RepoHost,
89 unmodified lines
modified:packages/project/test/projection-d1.fixtures.ts+3 added
13 unmodified lines
1415/** The project list's and the credits' migration (`ProjectsCreditsDdl`). */16export const projectsMigration = "0004_projects_credits.sql";1718/** The kept standing postures' migration (`StandingPosturesDdl`). */19export const posturesMigration = "0005_standing_postures.sql";2021/** A migration of the platform's D1 database, as its file holds it. */22export const migration = (file: string) =>23 Effect.gen(function* () {24 const fs = yield* FileSystem.FileSystem;
27 unmodified lines
modified:packages/project/test/projection-d1.test.ts+190 added-2 removed
6 unmodified lines
7import { describe, expect, it } from "@effect/vitest";8import type { AskListing } from "@repo/protocol/domain/ask";9import { ProjectEvent } from "@repo/protocol/domain/event";10import type { FrontPageEntry } from "@repo/protocol/domain/front-page";11import { LedgerEntry } from "@repo/protocol/domain/visibility";12import {13 AskId,14 DecisionId,15 EnvKey,16 Handle,17 KindName,18 LandedSha,19 ProjectName,20} from "@repo/protocol/ids";18import { DateTime, Effect, Layer } from "effect";21import { DateTime, Effect, Layer, Logger } from "effect";22import { SqlClient } from "effect/sql/SqlClient";2324import { FrontPage } from "../src/front-page.ts";25import type { FrontPageFilter } from "../src/front-page.ts";26import { projectedRows } from "../src/outbox.ts";27import type { OutboxRow } from "../src/project-store/rows.ts";28import { FrontPageD1 } from "../src/projection-d1/front-page.ts";29import { StandingPosturesD1 } from "../src/projection-d1/postures.ts";30import { ProjectionD1 } from "../src/projection-d1/projection.ts";31import {32 FrontPageDdl,33 StandingPosturesDdl,27import { FrontPageDdl } from "../src/projection-d1/tables.ts";34} from "../src/projection-d1/tables.ts";35import { Projection, ProjectionFailed } from "../src/projection.ts";36import { StandingPostures } from "../src/standing-posture.ts";37import type { StandingEntry } from "../src/standing-posture.ts";38import {39 frontPageMigration,40 migrated,41 migration,42 posturesMigration,43 projectsMigration,44} from "./projection-d1.fixtures.ts";4546/**
376 unmodified lines
423 expect(yield* front.credits(Handle.make("bram"))).toStrictEqual([]);424 }).pipe(Effect.provide(world))425 );426});427428/** The projection and the kept postures over a database with every migration. */429const withPostures = Layer.mergeAll(ProjectionD1, StandingPosturesD1).pipe(430 Layer.provideMerge(431 migrated([frontPageMigration, projectsMigration, posturesMigration])432 )433);434435/** The same over a database the postures' migration has not reached yet. */436const beforePostures = Layer.mergeAll(ProjectionD1, StandingPosturesD1).pipe(437 Layer.provideMerge(migrated([frontPageMigration, projectsMigration]))438);439440const sealed: StandingEntry = {441 posture: "openWithSealedEvidence",442 seen: 1,443 until: DateTime.makeUnsafe("2026-10-14T12:00:00Z"),444};445446const open: StandingEntry = { posture: "open", seen: 1 };447448const keep = (kept: readonly (readonly [ProjectName, StandingEntry])[]) =>449 Effect.flatMap(Effect.service(StandingPostures), (store) =>450 store.put(new Map(kept))451 );452453const keptFor = (projects: readonly ProjectName[]) =>454 Effect.flatMap(Effect.service(StandingPostures), (store) =>455 store.get(projects)456 );457458const 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 });465466const 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 });477478describe("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 );484485 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 ]);491492 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 );503504 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]));515516 return [...(yield* keptFor([datekit, burrow])).keys()].toSorted();517 });518519 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 );536537 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 );544545 // Read when datekit had one event; the projection has applied two.546 yield* keep([[datekit, { ...open, seen: 1 }]]);547548 const stale = yield* keptFor([datekit]);549550 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 }]]);554555 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 );567568 it.effect(569 "before its migration, projects every event and keeps nothing, with a warning",570 () =>571 Effect.gen(function* () {572 const warnings: string[] = [];573574 const keeper = Logger.make(({ logLevel, message }) => {575 warnings.push(`${logLevel}: ${String(message)}`);576 });577578 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 }]]);587588 expect(yield* keptFor([datekit])).toStrictEqual(new Map());589590 const cursor = yield* Effect.flatMap(591 Effect.service(SqlClient),592 (sql) => sql<{ readonly seq: number }>`SELECT seq FROM cursor`593 );594595 expect(cursor.map(({ seq }) => seq)).toStrictEqual([3]);596 }).pipe(Effect.provide(Logger.layer([keeper])));597598 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 */10import { describe, expect, it } from "@effect/vitest";11import { ProjectEvent } from "@repo/protocol/domain/event";12import type { ProjectListing } from "@repo/protocol/domain/front-page";10import { ProjectName } from "@repo/protocol/ids";13import { LedgerEntry } from "@repo/protocol/domain/visibility";14import { DecisionId, Handle, LandedSha, ProjectName } from "@repo/protocol/ids";15import type { Posture } from "@repo/protocol/posture";12import { Principal } from "@repo/protocol/principal";16import { UnknownProject } from "@repo/protocol/refusal";17import { untouchable } from "@repo/testkit/untouchable";15import { Array, DateTime, Duration, Effect, Layer, Logger, Ref } from "effect";18import {19 Array,20 DateTime,21 Duration,22 Effect,23 Layer,24 Logger,25 Option,26 Ref,27} from "effect";28import { TestClock } from "effect/testing";2930import { projectedRows } from "../src/outbox.ts";31import type { ProjectApi } from "../src/project.ts";32import { StandingPosturesD1 } from "../src/projection-d1/postures.ts";33import { ProjectionD1 } from "../src/projection-d1/projection.ts";34import { Projection } from "../src/projection.ts";35import { Projects } from "../src/projects.ts";19import { withStandingPosture } from "../src/standing-posture.ts";36import {37 StandingPostures,38 withStandingPosture,39} from "../src/standing-posture.ts";40import { StandingPosturesMemory } from "../src/standing-posture/memory.ts";41import {42 frontPageMigration,43 migrated,44 posturesMigration,45 projectsMigration,46} from "./projection-d1.fixtures.ts";4748const datekit = ProjectName.make("datekit");4950const ghost = ProjectName.make("ghost");
4 unmodified lines
5556const landedAt = DateTime.makeUnsafe("2026-10-08T12:00:00Z");5758/**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 */62const 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 });7879/**80 * The platform's projects: datekit's ledger stands sealed, burrow's open,
15 unmodified lines
9697 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 lines
116 { openAsks: 0, posture: "sourceAvailable", project: broken },117 { landedAt, openAsks: 2, posture: "openOnSchedule", project: burrow },118];119120/** The projects as `listed` stands them, `datekit` sealed and `burrow` open. */121const 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[];132133/** One hour past the TestClock's start: when datekit's narrowing takes effect, below. */134const inAnHour = DateTime.makeUnsafe(Duration.toMillis(Duration.hours(1)));135136/**137 * `platform`, each project's `standing` read counted in `reads`; datekit's138 * moves by the clock at `datekitUntil`.139 */140const 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]);150151 switch (project) {152 case datekit: {153 return Effect.succeed(154 standingAt(datekit, "openWithSealedEvidence", read, datekitUntil)155 );156 }157158 case burrow: {159 return Effect.succeed(standingAt(burrow, "open", read));160 }161162 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 }170171 default: {172 return Effect.fail(new UnknownProject({ project }));173 }174 }175 },176 })177 );178179/** A store whose every read and write dies. */180const brokenStore = Layer.succeed(StandingPostures, {181 get: () => Effect.die("D1 is down"),182 put: () => Effect.die("D1 is down"),183});184185describe("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 lines
272 expect(yield* Ref.get(peak)).toBe(8);273 })274 );275});276277describe("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[]>([]);281282 const twice = yield* Effect.all([283 withStandingPosture(listed),284 withStandingPosture(listed),285 ]).pipe(286 Effect.provide(Layer.merge(counted(reads), StandingPosturesMemory))287 );288289 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 );300301 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[]>([]);306307 const kept = yield* Effect.gen(function* () {308 yield* withStandingPosture(listed);309310 const store = yield* StandingPostures;311312 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 );321322 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 );333334 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[]>([]);339340 yield* Effect.gen(function* () {341 yield* withStandingPosture(listed);342 yield* TestClock.adjust(Duration.minutes(59));343 yield* withStandingPosture(listed);344345 // 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]);349350 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 );361362 expect(363 (yield* Ref.get(reads)).filter((at) => at !== broken)364 ).toStrictEqual([datekit]);365 })366 );367368 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[]>([]);373374 const standing = yield* withStandingPosture(listed).pipe(375 Effect.provide(Layer.merge(counted(reads), brokenStore))376 );377378 expect(standing).toStrictEqual(standingListed);379 })380 );381});382383/** The kept postures and the projection over the platform's D1, in sqlite. */384const d1 = Layer.mergeAll(StandingPosturesD1, ProjectionD1).pipe(385 Layer.provideMerge(386 migrated([frontPageMigration, projectsMigration, posturesMigration])387 )388);389390/** One event of `project`'s, as the projection is handed it from the outbox. */391const projected = (project: ProjectName, event: ProjectEvent) =>392 Effect.flatMap(projectedRows(project, [event], landedAt), (rows) =>393 Projection.use((projection) => projection.apply(rows))394 );395396describe("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[]>([]);402403 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, []);407408 expect(yield* withStandingPosture(listed)).toStrictEqual(409 standingListed410 );411412 return (yield* Ref.get(reads))413 .filter((at) => at !== broken)414 .toSorted();415 });416417 const first = yield* list;418 const warm = yield* list;419420 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 );436437 const afterLanding = yield* list;438439 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 );453454 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});