Merge branch 'build/903-code-reads'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 254268a, 623b096 · Browse files · 23 files·+3243 added−108 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
23 files+3243 added−108 removed
- tests:+1650 added−53 removed
- other:+1593 added−55 removed
Provenance
- Commit
7608aca- Tree
77d69d7- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
254268a- Parent 2
623b096
23 files changed+3243 added−108 removed
modified:apps/platform/src/ports.ts+15 added-1 removed
26 unmodified lines27282930313233343517 unmodified lines53545556575859606162636465666768697066 unmodified lines1371381391401301411421431441451461471484 unmodified lines26 unmodified linesimport type { EvidenceStore } from "@repo/checks/evidence-store";import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";import type { Upstream } from "@repo/git/upstream";import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";import { CodeCacheLive } from "@repo/project/code/cache";import type { FrontPage } from "@repo/project/front-page";import { FrontPageMemory } from "@repo/project/front-page/memory";import type { Lander } from "@repo/project/lander";import { LanderIsogit } from "@repo/project/lander/isogit";17 unmodified linesimport type { PlatformConfig } from "./platform.ts";import type { RateLimits } from "./rate-limits.ts";import { ProjectSockets } from "./watch.ts";
/** * How many code reads an isolate keeps by object id, the least recently * used dropped first: light ones (trees, commits; a few KiB each) and * heavy ones (a file's text up to 256 KiB, a path list, a commit's * changes, a page of the log; up to about 1 MB each), so the cache stays * well inside the isolate's 128 MB. Each Artifacts read is billed; what an * object id names never changes. */const CODE_READS_KEPT = { heavy: 40, light: 2000 };
/** What the Worker's code runs on, besides sessions and the contracts' handlers. */export type WorkerPorts = | CheckRunner | EvidenceStore66 unmodified lines claim: config.CLAIM_LIMIT, draft: config.DRAFT_LIMIT, proposal: config.PROPOSAL_LIMIT, }), EvidenceStoreR2(config.EVIDENCE) EvidenceStoreR2(config.EVIDENCE), // The code reads' cache, one per isolate: a `Context.Reference`, so // without this entry every read goes to Artifacts. CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy) ).pipe( Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)), Layer.provideMerge(WorkerFetch) );4 unmodified linesmodified:apps/platform/src/raw.ts+10 added-7 removed
1234545678910111213101415161314151718191720/** * A project's raw bytes: `GET /<project>/raw/<rev>/<path…>`, from its * canonical repo only, under a sandboxing CSP and `nosniff` so no file runs * as script on this origin. A stub until 903 lands: it answers 501. * `rest` is everything after `raw/`, undecoded: the revision and the path. * as script on this origin. The answer is `@repo/project/code/raw`'s, the * one the web's dev world serves too. The revision and the path are read * from the request's own URL, still encoded, and decoded there once: the * router's parameter has `%2F` decoded already, which would cut a tag's * name in two. */import type { RepoHost } from "@repo/artifacts/repo-host";import { rawFor } from "@repo/project/code/raw";import type { Projects } from "@repo/project/projects";import type { ProjectName } from "@repo/protocol/ids";import { Effect } from "effect";import type { Effect } from "effect";
export const rawResponse = ( _request: Request, _project: ProjectName, _rest: string request: Request, project: ProjectName): Effect.Effect<Response, never, RepoHost | Projects> => Effect.succeed(new Response("not built: 903", { status: 501 })); rawFor(project, request.url);modified:apps/platform/src/surfaces.ts+6 added-5 removed
1 unmodified line2 import { platformSkill } from "@repo/agent-kit/platform";3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { Brand } from "@repo/brand";5 import { Upstream } from "@repo/git/upstream";6+import { CodeCache } from "@repo/project/code/cache";7 import { FrontPage } from "@repo/project/front-page";8 import { Projects } from "@repo/project/projects";9 import { authenticated, bearerToken } from "@repo/protocol/authenticate";10 import { Client, Contracts, surfaced } from "@repo/protocol/contracts";375 unmodified lines386 387 /** `/<project>/raw/<rev>/<path…>`: a project's raw files (`raw.ts`). */388 const raw = HttpRouter.use((router) =>389 Effect.gen(function* () {390+ // The isolate's code cache, as the `/rpc` code reads have it: a391+ // `Context.Reference`, so without it every raw read goes to Artifacts.392 const services = Context.make(RepoHost, yield* RepoHost).pipe(390- Context.add(Projects, yield* Projects)393+ Context.add(Projects, yield* Projects),394+ Context.add(CodeCache, yield* CodeCache)395 );396 397 yield* router.add("GET", "/:project/raw/*", (request) =>398 Effect.gen(function* () {3 unmodified lines402 onNone: () =>403 Effect.succeed(HttpServerResponse.empty({ status: 404 })),404 onSome: (project) =>405 fromWeb((web) =>402- Effect.provide(403- rawResponse(web, project, params["*"] ?? ""),404- services405- )406+ Effect.provide(rawResponse(web, project), services)407 )(request),408 });409 })410 );75 unmodified linesadded:apps/platform/test/code-reads.test.ts+177 added
1+/**2+ * The code reads over `/rpc`, as anyone not signed in calls them: datekit's3+ * refs, a folder, a file, the log and a commit's changes, read from its4+ * canonical repo only. No code read's payload names a repo, so a caller5+ * cannot point one at a fork: an extra `repo` key is dropped or refused,6+ * and the canonical repo is read either way.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { Contracts } from "@repo/protocol/contracts";10+import { RepoName, RepoPath } from "@repo/protocol/ids";11+import { advanceTo } from "@repo/testkit/clock";12+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";13+import { Effect, Layer, SchemaAST } from "effect";14+15+import { Handlers } from "../src/handlers.ts";16+import { MemorySessions } from "../src/sessions/memory.ts";17+import { seeded, worldOf } from "./handlers.fixtures.ts";18+import { origin, rpcClient, served } from "./harness.ts";19+20+const datekit = aProject({ people: ["bob"] }).pipe(21+ withVouches(["bob"]),22+ withAsk({ id: "parse-iso", territory: "packages/parser" })23+);24+25+const { project } = datekit;26+27+/** The platform over datekit's world, seeded: made, pushed to, its ask open. */28+const platform = Effect.gen(function* () {29+ yield* advanceTo("2026-10-07T12:00:00Z");30+31+ const world = yield* Layer.build(worldOf([datekit]));32+33+ yield* seeded(datekit).pipe(Effect.provide(world));34+35+ const ports = Layer.succeedContext(world);36+37+ return yield* served(38+ Layer.mergeAll(39+ Handlers.pipe(Layer.provide(ports)),40+ ports,41+ MemorySessions.layer({})42+ )43+ );44+});45+46+/** The contracts that read a project's code. */47+const codeReads = [48+ "listRefs",49+ "readTree",50+ "listPaths",51+ "readFile",52+ "log",53+ "showCommit",54+ "why",55+];56+57+/** Every field of a payload, nested ones included: its name and its type's AST. */58+const fieldsIn = (59+ ast: SchemaAST.AST60+): readonly (readonly [string, SchemaAST.AST])[] => {61+ if (SchemaAST.isObjects(ast)) {62+ return ast.propertySignatures.flatMap(({ name, type }) => [63+ [String(name), type] as const,64+ ...fieldsIn(type),65+ ]);66+ }67+68+ return SchemaAST.isUnion(ast) ? ast.types.flatMap(fieldsIn) : [];69+};70+71+describe("the code reads over /rpc", () => {72+ it.effect(73+ "answer anyone with datekit's refs, its root folder and a file",74+ () =>75+ Effect.gen(function* () {76+ const { handler } = yield* platform;77+ const anyone = yield* rpcClient(handler);78+ const refs = yield* anyone.listRefs({ project });79+ const root = yield* anyone.readTree({ project });80+81+ const file = yield* anyone.readFile({82+ path: RepoPath.make("package.json"),83+ project,84+ });85+86+ expect([refs.project, refs.tags]).toStrictEqual([project, []]);87+ expect(root.at).toBe(refs.landed);88+ expect(root.entries.map(({ name }) => name)).toStrictEqual(89+ expect.arrayContaining(["packages", "package.json"])90+ );91+ expect(file.text).toContain('"name": "datekit"');92+ })93+ );94+95+ it.effect("answer anyone with datekit's paths, log and first commit", () =>96+ Effect.gen(function* () {97+ const { handler } = yield* platform;98+ const anyone = yield* rpcClient(handler);99+ const { landed } = yield* anyone.listRefs({ project });100+ const { commits } = yield* anyone.log({ project });101+ const first = commits.at(-1)?.sha ?? "main";102+ const paths = yield* anyone.listPaths({ at: first, project });103+104+ expect([commits[0]?.sha, commits.at(-1)?.subject]).toStrictEqual([105+ landed,106+ "Start",107+ ]);108+ expect(paths.paths).toContain("packages/parser/src/parse.ts");109+110+ const diff = yield* anyone.showCommit({ project, sha: paths.at });111+112+ expect(113+ diff.files.map(({ path, status }) => [path, status])114+ ).toStrictEqual(paths.paths.map((path) => [path, "added"]));115+ })116+ );117+118+ it.effect(119+ "read the canonical repo whatever extra key a payload carries",120+ () =>121+ Effect.gen(function* () {122+ const { handler } = yield* platform;123+124+ // The wire's request, written as a client would send it, with a125+ // `repo` beside the project that no contract has.126+ const payload = JSON.stringify({ project, repo: "datekit--me--alice" });127+128+ const response = yield* Effect.promise(() =>129+ handler(130+ new Request(`${origin}/rpc`, {131+ body: `{"_tag":"Request","id":"1","tag":"readTree","payload":${payload},"headers":[]}`,132+ headers: { "content-type": "application/json" },133+ method: "POST",134+ })135+ )136+ );137+138+ const text = yield* Effect.promise(() => response.text());139+ const anyone = yield* rpcClient(handler);140+ const canonical = yield* anyone.readTree({ project });141+142+ expect(response.status).toBe(200);143+ expect(text).not.toContain("datekit--me--alice");144+ expect(text).toContain(canonical.at);145+ })146+ );147+148+ it("name no repo in any code read's payload", () => {149+ const rpcs = codeReads.map(150+ (tag) => [tag, Contracts.requests.get(tag)] as const151+ );152+153+ const fields = rpcs.flatMap(([tag, rpc]) =>154+ rpc === undefined155+ ? []156+ : fieldsIn(rpc.payloadSchema.ast).map(157+ ([name, type]) => [tag, name, type] as const158+ )159+ );160+161+ expect(162+ rpcs.flatMap(([tag, rpc]) => (rpc === undefined ? [tag] : []))163+ ).toStrictEqual([]);164+ // The check sees a branded field: `readFile`'s path is a `RepoPath`.165+ expect(166+ fields.some(167+ ([tag, name, type]) =>168+ tag === "readFile" && name === "path" && type === RepoPath.ast169+ )170+ ).toBeTruthy();171+ expect(172+ fields.flatMap(([tag, name, type]) =>173+ type === RepoName.ast || name === "repo" ? [`${tag}.${name}`] : []174+ )175+ ).toStrictEqual([]);176+ });177+});added:apps/platform/test/raw.test.ts+239 added
1+/**2+ * A project's raw files through the platform's fetch handler:3+ * `GET /<project>/raw/<rev>/<path…>` answers the bytes with their headers4+ * to anyone, a stale bearer token or not; a path that climbs out is a5+ * 404; and git's own paths beside it still reach git.6+ */7+import { describe, expect, it } from "@effect/vitest";8+import { RefName, RepoHost } from "@repo/artifacts/repo-host";9+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";10+import { CodeCacheLive } from "@repo/project/code/cache";11+import { Projects } from "@repo/project/projects";12+import { RepoName } from "@repo/protocol/ids";13+import { Person } from "@repo/protocol/principal";14+import { advanceTo } from "@repo/testkit/clock";15+import { gitClient } from "@repo/testkit/git-client";16+import { aProject } from "@repo/testkit/scenarios";17+import { Context, Effect, Layer, Option, Ref } from "effect";18+19+import { Handlers } from "../src/handlers.ts";20+import { MemorySessions } from "../src/sessions/memory.ts";21+import { worldOf } from "./handlers.fixtures.ts";22+import { origin, served } from "./harness.ts";23+24+const datekit = aProject({ people: [] });25+26+const { project } = datekit;27+28+const readme = "# datekit\n\nDates, parsed.\n";29+30+/**31+ * The platform over a world where datekit was made and its first commit,32+ * a README and a manifest, pushed to main; and that commit's id. With33+ * `reads`, the platform has the isolate's code cache, as `ports.ts` gives34+ * it, and each tree its repo host is asked for is counted there.35+ */36+const platformWith = (reads: Option.Option<Ref.Ref<number>>) =>37+ Effect.gen(function* () {38+ yield* advanceTo("2026-10-07T12:00:00Z");39+40+ const world = yield* Layer.build(worldOf([datekit]));41+42+ const first = yield* Effect.gen(function* () {43+ const host = yield* RepoHost;44+ const api = yield* (yield* Projects).create(project);45+ const initializer = Person.make({ handle: datekit.initializer });46+ const client = yield* gitClient(memoryFs());47+48+ yield* api.initProject(initializer, {});49+50+ const sha = yield* client.commit("Start", [51+ ["README.md", readme],52+ ["package.json", '{ "name": "datekit" }\n'],53+ ]);54+55+ yield* host.push(RepoName.make(project), client.source, [56+ { from: Option.none(), ref: RefName.make("refs/heads/main"), to: sha },57+ {58+ from: Option.none(),59+ ref: RefName.make("refs/tags/@datekit/core@1.0.0"),60+ to: sha,61+ },62+ ]);63+ yield* api.recordFirstPush(initializer, sha);64+65+ return sha;66+ }).pipe(Effect.orDie, Effect.provide(world));67+68+ const cached = yield* Option.match(reads, {69+ onNone: () => Effect.succeed(world),70+ onSome: (count) =>71+ Effect.map(Layer.build(CodeCacheLive(100)), (cache) => {72+ const host = Context.get(world, RepoHost);73+74+ return Context.merge(world, cache).pipe(75+ Context.add(76+ RepoHost,77+ RepoHost.of({78+ ...host,79+ readTree: (name, tree) =>80+ Effect.andThen(81+ Ref.update(count, (n) => n + 1),82+ host.readTree(name, tree)83+ ),84+ })85+ )86+ );87+ }),88+ });89+90+ const ports = Layer.succeedContext(cached);91+92+ const { fetch } = yield* served(93+ Layer.mergeAll(94+ Handlers.pipe(Layer.provide(ports)),95+ ports,96+ MemorySessions.layer({})97+ )98+ );99+100+ return { fetch, first };101+ });102+103+const platform = platformWith(Option.none());104+105+const get = (106+ fetch: (request: Request) => Effect.Effect<Response>,107+ path: string,108+ headers: Record<string, string> = {}109+) =>110+ Effect.flatMap(111+ fetch(new Request(`${origin}${path}`, { headers })),112+ (response) =>113+ Effect.map(114+ Effect.promise(() => response.text()),115+ (text) => ({ headers: response.headers, status: response.status, text })116+ )117+ );118+119+describe("a project's raw files", () => {120+ it.effect(121+ "answer anyone with the bytes and their headers, a stale bearer or not",122+ () =>123+ Effect.gen(function* () {124+ const { fetch, first } = yield* platform;125+ const path = `/${project}/raw/${first}/README.md`;126+127+ const answers = yield* Effect.forEach(128+ [{}, { authorization: "Bearer not-a-token-the-platform-knows" }],129+ (headers) =>130+ Effect.map(get(fetch, path, headers), (answer) => ({131+ cache: answer.headers.get("cache-control"),132+ etag: /^"[0-9a-f]{40}"$/u.test(answer.headers.get("etag") ?? ""),133+ nosniff: answer.headers.get("x-content-type-options"),134+ sandboxed: (135+ answer.headers.get("content-security-policy") ?? ""136+ ).includes("sandbox"),137+ status: answer.status,138+ text: answer.text,139+ type: answer.headers.get("content-type"),140+ }))141+ );142+143+ expect(answers).toStrictEqual(144+ answers.map(() => ({145+ cache: "public, max-age=31536000, immutable",146+ etag: true,147+ nosniff: "nosniff",148+ sandboxed: true,149+ status: 200,150+ text: readme,151+ type: "text/plain; charset=utf-8",152+ }))153+ );154+ expect(answers).toHaveLength(2);155+156+ const main = yield* get(fetch, `/${project}/raw/main/README.md`);157+158+ expect([main.status, main.headers.get("cache-control")]).toStrictEqual([159+ 200,160+ "public, max-age=60",161+ ]);162+ })163+ );164+165+ it.effect(166+ "find a tag by its name, URL-encoded in one segment, slash and all",167+ () =>168+ Effect.gen(function* () {169+ const { fetch } = yield* platform;170+171+ const answer = yield* get(172+ fetch,173+ `/${project}/raw/${encodeURIComponent("@datekit/core@1.0.0")}/README.md`174+ );175+176+ expect([177+ answer.status,178+ answer.text,179+ answer.headers.get("cache-control"),180+ ]).toStrictEqual([200, readme, "public, max-age=60"]);181+ })182+ );183+184+ it.effect(185+ "is a 404 with no body for a path that climbs out, a missing file or project",186+ () =>187+ Effect.gen(function* () {188+ const { fetch, first } = yield* platform;189+190+ const answers = yield* Effect.forEach(191+ [192+ `/${project}/raw/${first}/../../x`,193+ `/${project}/raw/${first}/..%2F..%2Fx`,194+ `/${project}/raw/${first}/nope.md`,195+ `/${project}/raw/v9/README.md`,196+ `/nobody/raw/main/README.md`,197+ ],198+ (path) =>199+ Effect.map(get(fetch, path), ({ status, text }) => [status, text])200+ );201+202+ expect(answers).toStrictEqual(answers.map(() => [404, ""]));203+ })204+ );205+206+ it.effect("read a tree once per isolate, by its id", () =>207+ Effect.gen(function* () {208+ const reads = yield* Ref.make(0);209+ const { fetch, first } = yield* platformWith(Option.some(reads));210+ const path = `/${project}/raw/${first}/README.md`;211+212+ const once = yield* get(fetch, path);213+ const counted = yield* Ref.get(reads);214+ const again = yield* get(fetch, path);215+216+ expect([once.status, again.status, again.text]).toStrictEqual([217+ 200,218+ 200,219+ readme,220+ ]);221+ expect(counted).toBeGreaterThan(0);222+ expect(yield* Ref.get(reads)).toBe(counted);223+ })224+ );225+226+ it.effect("leave git's own paths to git", () =>227+ Effect.gen(function* () {228+ const { fetch } = yield* platform;229+230+ const answer = yield* get(231+ fetch,232+ `/${project}/info/refs?service=git-upload-pack`233+ );234+235+ expect(answer.status).not.toBe(404);236+ expect(answer.headers.get("content-security-policy")).toBeNull();237+ })238+ );239+});modified:apps/platform/test/w9-contracts.test.ts+15 added-17 removed
1 /**2 * The code browser's, the people page's and drafting's contracts and3 * routes, wired end to end through the platform's fetch4- * handler before their bodies exist: the policy read answers, each code5- * read reaches the façade (which names the issue that builds it), a draft6- * needs a person, and `/` and a project's raw files have their slots, open7- * to a stale credential as every public path is.4+ * handler: the policy read answers, the code reads reach the façade5+ * (`why` names the issue that builds it; the others are6+ * `code-reads.test.ts`'), a draft needs a person, and `/` and a project's7+ * raw files have their routes, open to a stale credential as every public8+ * path is (a raw file at no revision is a 404).9 */10 import { describe, expect, it } from "@effect/vitest";10-import { ProposalId } from "@repo/protocol/ids";11+import { ProposalId, RepoPath } from "@repo/protocol/ids";12 import { Unauthenticated } from "@repo/protocol/principal";13 import { advanceTo } from "@repo/testkit/clock";14 import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";15 import { Cause, Effect, Exit, Layer, Option } from "effect";54 unmodified lines70 Effect.gen(function* () {71 const { handler } = yield* platform;72 const anyone = yield* rpcClient(handler);73 73- expect(yield* diedWith(anyone.listRefs({ project }))).toStrictEqual(74- Option.some("not built: 903")75- );76- expect(yield* diedWith(anyone.readTree({ project }))).toStrictEqual(77- Option.some("not built: 903")78- );74+ expect(75+ yield* diedWith(76+ anyone.why({ path: RepoPath.make("package.json"), project })77+ )78+ ).toStrictEqual(Option.some("not built: 912"));79 })80 );81 82 it.effect("refuse a draft to anyone not signed in", () =>49 unmodified lines132 homeStale: {133 status: 501,134 text: "not built: 906 (draft model test-model)",135 },136- raw: { status: 501, text: "not built: 903" },137- rawStale: { status: 501, text: "not built: 903" },136+ raw: { status: 404, text: "" },137+ rawStale: { status: 404, text: "" },138 });139 })140 );141 4 unmodified lines146 const response = yield* fetch(147 new Request(`${origin}/${project}/raw/info/refs`)148 );149 150- expect(response.status).toBe(501);151- expect(yield* Effect.promise(() => response.text())).toBe(152- "not built: 903"153- );150+ expect(response.status).toBe(404);151+ expect(yield* Effect.promise(() => response.text())).toBe("");152 })153 );154 });modified:apps/web/src/dev/server.ts+51 added-13 removed
1 /**2 * The dev world as a fetch handler: `POST /rpc` is an `RpcServer` over3 * `Contracts` with the dev handlers, protocol's `Authenticated` server side4 * over dev tokens (`sessions.ts`) and JSON, as the platform's `/rpc` serves5- * it, over a fresh world the seed has brought to its state. `backend.ts`6- * makes the one an isolate serves; a test makes its own.5+ * it, over a fresh world the seed has brought to its state; and6+ * `GET /<project>/raw/<rev>/<path…>` answers a project's raw files with7+ * the response the platform's `raw.ts` gives (`@repo/project/code/raw`).8+ * `backend.ts` makes the one an isolate serves; a test makes its own.9 */10+import { RepoHost } from "@repo/artifacts/repo-host";11+import { rawFor } from "@repo/project/code/raw";12+import { Projects } from "@repo/project/projects";13 import { Contracts } from "@repo/protocol/contracts";9-import { Layer } from "effect";10-import { HttpRouter } from "effect/http";14+import { ProjectName } from "@repo/protocol/ids";15+import { Context, Effect, Layer, Option, Schema } from "effect";16+import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";17 import { RpcSerialization, RpcServer } from "effect/rpc";18 19 import { devHandlers } from "./handlers.ts";20 import { seedDev } from "./seed.ts";4 unmodified lines25 const seededWorld = Layer.effectDiscard(seedDev).pipe(26 Layer.provideMerge(devWorld)27 );28 29+const decodeProject = Schema.decodeUnknownOption(ProjectName);30+31+/** `/<project>/raw/<rev>/<path…>`: a project's raw files, as the platform serves them. */32+const raw = Layer.unwrap(33+ Effect.gen(function* () {34+ const services = Context.make(RepoHost, yield* RepoHost).pipe(35+ Context.add(Projects, yield* Projects)36+ );37+38+ return HttpRouter.add(39+ "GET",40+ "/:project/raw/*",41+ Effect.gen(function* () {42+ const params = yield* HttpRouter.params;43+ const request = yield* HttpServerRequest.HttpServerRequest;44+45+ return yield* Option.match(decodeProject(params.project), {46+ onNone: () =>47+ Effect.succeed(HttpServerResponse.empty({ status: 404 })),48+ onSome: (project) =>49+ rawFor(project, request.url).pipe(50+ Effect.provide(services),51+ Effect.map(HttpServerResponse.fromWeb)52+ ),53+ });54+ })55+ );56+ })57+);58+59 /**24- * The contracts at `/rpc` over a fresh, seeded world. `toWebHandler` builds60+ * The contracts at `/rpc` and the raw files over a fresh, seeded world. `toWebHandler` builds61 * its layer as soon as it is called, so the world is made and seeded from62 * that moment, and a request that arrives before the seed is done waits for63 * it. `dispose` ends the world.64 */65 export const devServer = () =>66 HttpRouter.toWebHandler(67+ Layer.merge(31- RpcServer.layerHttp({32- group: Contracts,33- path: "/rpc",34- protocol: "http",35- }).pipe(36- Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson]),37- Layer.provide(seededWorld)38- ),68+ RpcServer.layerHttp({69+ group: Contracts,70+ path: "/rpc",71+ protocol: "http",72+ }).pipe(73+ Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson])74+ ),75+ raw76+ ).pipe(Layer.provide(seededWorld)),77 { disableLogger: true }78 );modified:apps/web/test/dev-backend.test.ts+48 added
234 unmodified lines235 );236 })237 );238 });239+240+/** Each of `paths` on a fresh world's own handler: its status, headers and body. */241+const fetched = (paths: readonly string[]) =>242+ Effect.scoped(243+ Effect.gen(function* () {244+ const { dispose, handler } = devServer();245+246+ yield* Effect.addFinalizer(() => Effect.promise(dispose));247+248+ return yield* Effect.forEach(paths, (path) =>249+ Effect.gen(function* () {250+ const response = yield* Effect.promise(() =>251+ handler(new Request(`http://localhost${path}`))252+ );253+254+ return {255+ cache: response.headers.get("cache-control"),256+ csp: response.headers.get("content-security-policy") ?? "",257+ nosniff: response.headers.get("x-content-type-options"),258+ status: response.status,259+ text: yield* Effect.promise(() => response.text()),260+ };261+ })262+ );263+ })264+ );265+266+describe("the dev world's raw files", seededWorlds, () => {267+ it.live(268+ "answer a project's file as the platform does, and a path that climbs out with a 404",269+ () =>270+ Effect.gen(function* () {271+ const [manifest, climbed] = yield* fetched([272+ "/datekit/raw/main/package.json",273+ "/datekit/raw/main/..%2F..%2Fpackage.json",274+ ]);275+276+ expect(manifest).toMatchObject({277+ cache: "public, max-age=60",278+ nosniff: "nosniff",279+ status: 200,280+ });281+ expect(manifest?.csp).toContain("sandbox");282+ expect(manifest?.text).toContain('"name": "datekit"');283+ expect([climbed?.status, climbed?.text]).toStrictEqual([404, ""]);284+ })285+ );286+});modified:packages/artifacts/src/repo-host.ts+8 added-2 removed
24 unmodified lines25 );26 27 export type BranchName = typeof BranchName.Type;28 29-/** A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`. */29+/**30+ * A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`,31+ * `refs/tags/@changesets/cli@2.27.1` (a scoped package's tag; `@` and `+`32+ * are git's as well).33+ */34 export const RefName = Schema.String.pipe(35 Schema.check(32- Schema.isPattern(/^refs\/(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+$/u)36+ Schema.isPattern(37+ /^refs\/(?!.*\.\.)[A-Za-z0-9._@+-]+(?:\/[A-Za-z0-9._@+-]+)+$/u38+ )39 ),40 Schema.brand("RefName")41 );42 198 unmodified linesmodified:packages/project/src/code/cache.ts+153 added-6 removed
1 unmodified line2 * The code reads' cache: what an object id names never changes, so a read3 * keyed by `<repo>:<kind>:<object id>` (a tree, a blob, a commit, a commit's4 * diff, a blame at a commit) is read once. A `Context.Reference` whose5 * default caches nothing, so every host composes before one is given; the6- * platform gives one held in a layer (no module-level state, principle 6).7- * `main` is never a key: it resolves through the project's record on every6+ * platform gives one held in a layer (no module-level state, principle 6),7+ * so it lives as long as the isolate. `main` and a tag are never a key:8+ * each resolves through the project's record or the repo's tags on every9 * call.10+ *11+ * Entries come in two weights, each in a cache of its own, so a count of12+ * entries bounds the memory they take: trees and commits are light (a few13+ * KiB), while a file's text, a commit's path list or changes and a page of14+ * the log are heavy (up to hundreds of KiB), and an isolate holds 128 MB.15 */10-import { Context } from "effect";11-import type { Effect } from "effect";16+import {17+ Cache,18+ Context,19+ Duration,20+ Effect,21+ Equal,22+ Exit,23+ Hash,24+ Layer,25+ Option,26+ Ref,27+} from "effect";28 29+/** How a read's value is kept. */30+export interface Keeping<A> {31+ /** Whether the value may weigh up to hundreds of KiB (a text, a list). */32+ readonly heavy?: boolean;33+ /** Whether this value may be kept at all; a larger one is read again. */34+ readonly keep?: (value: A) => boolean;35+}36+37 /** The code reads, each kept by its key once read. */38 export interface CodeReads {15- /** `read`, or what it gave before for `key`. */39+ /**40+ * `read`, or what it gave before for `key`. A failure is never kept,41+ * and neither is a value `keeping.keep` turns down (a large file's text).42+ */43 readonly through: <A, E, R>(44 key: string,18- read: Effect.Effect<A, E, R>45+ read: Effect.Effect<A, E, R>,46+ keeping?: Keeping<A>47 ) => Effect.Effect<A, E, R>;48 }49 50 export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {51 defaultValue: () => ({ through: (_key, read) => read }),52 });53+54+/** What one read gave, when it succeeded, and whether it may be kept. */55+interface Entry {56+ readonly value: Option.Option<unknown>;57+ readonly kept: boolean;58+}59+60+/**61+ * One read and the key it is kept by: two are the same entry when their62+ * keys are, whatever their reads (each a closure of its own).63+ */64+class Keyed implements Equal.Equal {65+ readonly key: string;66+ readonly read: Effect.Effect<Entry>;67+68+ constructor(key: string, read: Effect.Effect<Entry>) {69+ this.key = key;70+ this.read = read;71+ }72+73+ [Equal.symbol](that: Equal.Equal): boolean {74+ return that instanceof Keyed && that.key === this.key;75+ }76+77+ [Hash.symbol](): number {78+ return Hash.string(this.key);79+ }80+}81+82+const always = () => true;83+84+/** How long an entry is kept: for good when its read succeeded and may be kept, else not at all. */85+const lifeOf = (exit: Exit.Exit<Entry>) =>86+ Exit.isSuccess(exit) && exit.value.kept ? Duration.infinity : Duration.zero;87+88+/** One cache of at most `capacity` reads. */89+const cacheOf = (capacity: number) =>90+ Cache.makeWith((key: Keyed) => key.read, {91+ capacity,92+ timeToLive: lifeOf,93+ });94+95+/** `read` through `cache`, kept by `key` when `keep` allows. */96+const throughCache =97+ (cache: Cache.Cache<Keyed, Entry>) =>98+ <A, E, R>(99+ key: string,100+ read: Effect.Effect<A, E, R>,101+ keep: (value: A) => boolean102+ ) =>103+ Effect.gen(function* () {104+ const context = yield* Effect.context<R>();105+ const own = yield* Ref.make(Option.none<Exit.Exit<A, E>>());106+107+ const entry = yield* Cache.get(108+ cache,109+ new Keyed(110+ key,111+ Effect.exit(Effect.provideContext(read, context)).pipe(112+ Effect.tap((exit) => Ref.set(own, Option.some(exit))),113+ Effect.map((exit): Entry => ({114+ kept: Exit.isSuccess(exit) && keep(exit.value),115+ value: Exit.isSuccess(exit)116+ ? Option.some(exit.value)117+ : Option.none(),118+ }))119+ )120+ )121+ );122+123+ const ran = yield* Ref.get(own);124+125+ if (Option.isSome(ran)) {126+ return yield* ran.value;127+ }128+129+ if (Option.isNone(entry.value)) {130+ return yield* read;131+ }132+133+ // SAFETY: every key names one kind of read (`<repo>:<kind>:<id>`), so the134+ // value kept under it is what a read typed as this one gave.135+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one cache holds every kind of read, so its values are typed `unknown`; see SAFETY.136+ return entry.value.value as A;137+ });138+139+/**140+ * At most `capacity` light reads and `heavy` heavy ones, the least141+ * recently used of each dropped first. Two calls with one key while the142+ * first is under way share its read; a caller whose own read ran gets its143+ * exit as it was, and one that waited on a read that failed reads for144+ * itself.145+ */146+export const CodeCacheLive = (147+ capacity: number,148+ heavy = Math.max(1, Math.ceil(capacity / 50))149+) =>150+ Layer.effect(151+ CodeCache,152+ Effect.gen(function* () {153+ const light = throughCache(yield* cacheOf(capacity));154+ const weighty = throughCache(yield* cacheOf(heavy));155+156+ const reads: CodeReads = {157+ through: <A, E, R>(158+ key: string,159+ read: Effect.Effect<A, E, R>,160+ keeping: Keeping<A> = {}161+ ) =>162+ (keeping.heavy === true ? weighty : light)(163+ key,164+ read,165+ keeping.keep ?? always166+ ),167+ };168+169+ return reads;170+ })171+ );added:packages/project/src/code/commit.ts+236 added
1+/**2+ * One commit and what it changed against its first parent (a root commit3+ * 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.9+ */10+import { RepoHost } from "@repo/artifacts/repo-host";11+import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";12+import { treeDiff } from "@repo/git/tree-diff";13+import type { Change } from "@repo/git/tree-diff";14+import type { ChangedFile, CommitDiff } from "@repo/protocol/domain/code";15+import { BlobSha, TreeSha } from "@repo/protocol/ids";16+import type { CommitSha, RepoName } from "@repo/protocol/ids";17+import { UnknownCommit } from "@repo/protocol/refusal";18+import { Array, Effect, Option, Order } from "effect";19+20+import type { CodeProject } from "../code.ts";21+import { CodeCache } from "./cache.ts";22+import { contentsOf } from "./file.ts";23+import type { Contents } from "./file.ts";24+import { commitViews } from "./log.ts";25+import { filesUnder, PATHS_CAP } from "./paths.ts";26+import { commitAt } from "./revision.ts";27+import { entriesOf, entryAt } from "./tree.ts";28+29+/** The most files a commit's diff carries text for. */30+export const DIFF_FILES = 300;31+32+/** The most text a commit's diff carries in all: 2 MiB. */33+export const DIFF_TEXT = 2 * 1024 * 1024;34+35+/** The longest list of changes the cache keeps. */36+const KEPT_CHANGES = 1000;37+38+/** A change, and whether each side is a submodule (whose id names no blob here). */39+interface Changed extends Change {40+ readonly links: { readonly before: boolean; readonly after: boolean };41+}42+43+const isLink = (entry: Option.Option<TreeEntry>) =>44+ Option.exists(entry, ({ type }) => type === "commit");45+46+/** Every file under a root commit's tree, each added. */47+const rootChanges = (repo: RepoName, tree: string) =>48+ Effect.map(filesUnder(repo, tree, PATHS_CAP), ({ files }) =>49+ files.map(({ entry, path }): Changed => ({50+ after: BlobSha.make(entry.sha),51+ links: { after: entry.type === "commit", before: false },52+ path,53+ status: "added",54+ }))55+ );56+57+/**58+ * What changed from `base` to `head`, by `treeDiff` over this repo's trees59+ * read through the cache (so the side lookups that follow read none again).60+ */61+const changesBetween = (repo: RepoName, base: string, head: string) =>62+ Effect.gen(function* () {63+ const host = yield* RepoHost;64+65+ const changes = yield* treeDiff(66+ repo,67+ TreeSha.make(base),68+ TreeSha.make(head)69+ ).pipe(70+ Effect.provideService(71+ RepoHost,72+ RepoHost.of({73+ ...host,74+ readTree: (name, id) =>75+ name === repo76+ ? Effect.asSome(77+ Effect.provideService(entriesOf(repo, id), RepoHost, host)78+ )79+ : host.readTree(name, id),80+ })81+ )82+ );83+84+ return yield* Effect.forEach(85+ changes,86+ (change): Effect.Effect<Changed, RepoNotFound, RepoHost> =>87+ Effect.map(88+ Effect.all([89+ entryAt(repo, base, change.path),90+ entryAt(repo, head, change.path),91+ ]),92+ ([before, after]) => ({93+ ...change,94+ links: { after: isLink(after), before: isLink(before) },95+ })96+ ),97+ { concurrency: 8 }98+ );99+ });100+101+const byPath = Order.mapInput(Order.String, (change: Changed) => change.path);102+103+/** A side's contents, unless it is a submodule or absent. */104+const sideOf = (105+ repo: RepoName,106+ blob: BlobSha | undefined,107+ link: boolean108+): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>109+ blob === undefined || link ? Effect.succeedNone : contentsOf(repo, blob);110+111+/** A change as a path, its status and its blob ids, with no text. */112+const pathOnly = ({ after, before, path, status }: Changed): ChangedFile => {113+ const file = { binary: false, path, status };114+115+ if (before !== undefined && after !== undefined) {116+ return { ...file, after, before };117+ }118+119+ if (before !== undefined) {120+ return { ...file, before };121+ }122+123+ return after === undefined ? file : { ...file, after };124+};125+126+/** Each change with its text while the budget lasts, and whether any went without. */127+const withText = (repo: RepoName, changes: readonly Changed[]) =>128+ Effect.gen(function* () {129+ if (changes.length > DIFF_FILES) {130+ return { files: changes.map(pathOnly), truncated: true };131+ }132+133+ const files: ChangedFile[] = [];134+ let budget = DIFF_TEXT;135+ let truncated = false;136+137+ for (const change of changes) {138+ if (truncated) {139+ files.push(pathOnly(change));140+ continue;141+ }142+143+ const before = yield* sideOf(repo, change.before, change.links.before);144+ const after = yield* sideOf(repo, change.after, change.links.after);145+ const oldText = Option.flatMap(before, ({ text }) => text);146+ const newText = Option.flatMap(after, ({ text }) => text);147+148+ const size =149+ Option.getOrElse(150+ Option.map(oldText, (text) => text.length),151+ () => 0152+ ) +153+ Option.getOrElse(154+ Option.map(newText, (text) => text.length),155+ () => 0156+ );157+158+ if (size > budget) {159+ truncated = true;160+ files.push(pathOnly(change));161+ continue;162+ }163+164+ budget -= size;165+166+ files.push({167+ ...pathOnly(change),168+ binary:169+ Option.exists(before, ({ binary }) => binary) ||170+ Option.exists(after, ({ binary }) => binary),171+ ...Option.match(oldText, {172+ onNone: () => ({}),173+ onSome: (text) => ({ oldText: text }),174+ }),175+ ...Option.match(newText, {176+ onNone: () => ({}),177+ onSome: (text) => ({ newText: text }),178+ }),179+ });180+ }181+182+ return { files, truncated };183+ });184+185+/** One commit and the files it changed against its first parent. */186+export const commitDiff = (187+ project: CodeProject,188+ sha: CommitSha189+): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>190+ Effect.gen(function* () {191+ const { repo } = project;192+ const cache = yield* CodeCache;193+194+ const commit = yield* commitAt(repo, sha).pipe(195+ Effect.orDie,196+ Effect.flatMap(197+ Option.match({198+ onNone: () => Effect.fail(new UnknownCommit({ sha })),199+ onSome: Effect.succeed,200+ })201+ )202+ );203+204+ const parent = yield* Option.match(205+ Option.fromUndefinedOr(commit.parents[0]),206+ {207+ onNone: () => Effect.succeedNone,208+ onSome: (first) => commitAt(repo, first),209+ }210+ ).pipe(Effect.orDie);211+212+ const changes = yield* cache213+ .through(214+ `${repo}:changes:${sha}`,215+ Option.match(parent, {216+ onNone: () => rootChanges(repo, commit.tree),217+ onSome: ({ tree }) => changesBetween(repo, tree, commit.tree),218+ }),219+ // A longer list is listed again, over trees the cache keeps.220+ { heavy: true, keep: (all) => all.length <= KEPT_CHANGES }221+ )222+ .pipe(Effect.orDie);223+224+ const { files, truncated } = yield* withText(225+ repo,226+ Array.sort(changes, byPath)227+ ).pipe(Effect.orDie);228+229+ const [view] = yield* commitViews(project, [commit]);230+231+ if (view === undefined) {232+ return yield* Effect.die(`no view of ${sha}`);233+ }234+235+ return { commit: view, files, truncated };236+ });added:packages/project/src/code/file.ts+156 added
1+/**2+ * One file's contents as a reader sees them: its size, whether it is3+ * binary (a NUL in its first 8 KiB, git's own test and `tree-diff.ts`'s),4+ * and its text up to 1 MiB; past that, or when Artifacts answers that the5+ * blob is too large to hold (`MEMORY_LIMIT`), it is truncated with no text.6+ * Kept by the blob's id, unless its text is large.7+ */8+import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";9+import type { RepoNotFound } from "@repo/artifacts/repo-host";10+import type { FileView, Rev } from "@repo/protocol/domain/code";11+import { BlobSha } from "@repo/protocol/ids";12+import type { RepoName, RepoPath } from "@repo/protocol/ids";13+import { UnknownPath } from "@repo/protocol/refusal";14+import type { UnknownRevision } from "@repo/protocol/refusal";15+import { Effect, Option, Schema } from "effect";16+17+import type { CodeProject } from "../code.ts";18+import { CodeCache } from "./cache.ts";19+import { commitAt, resolveRev } from "./revision.ts";20+import { entryAt } from "./tree.ts";21+22+/** The most text a file's view carries: 1 MiB. */23+export const TEXT_CAP = 1024 * 1024;24+25+// git's own test: a NUL among the first bytes means the blob is not text.26+const SNIFF = 8192;27+28+/** The largest text a cache entry keeps; a larger one is read again. */29+const KEPT_TEXT = 256 * 1024;30+31+/** Whether `bytes` read as binary: a NUL among the first 8 KiB. */32+export const isBinary = (bytes: Uint8Array) =>33+ bytes.subarray(0, SNIFF).includes(0);34+35+/** A file's contents: its text only when it is text and within the cap. */36+export interface Contents {37+ readonly size: number;38+ readonly binary: boolean;39+ readonly truncated: boolean;40+ readonly text: Option.Option<string>;41+}42+43+/** What Artifacts throws when a blob is too large for the Worker to hold. */44+const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });45+46+const isMemoryLimit = Schema.is(MemoryLimit);47+48+/**49+ * `read`, or `tooLarge` when Artifacts said the blob was too large to hold:50+ * its binding throws that as a defect, which here is an answer.51+ */52+export const unlessTooLarge = <A, E, R>(53+ read: Effect.Effect<A, E, R>,54+ tooLarge: () => A55+): Effect.Effect<A, E, R> =>56+ Effect.catchDefect(read, (defect) =>57+ isMemoryLimit(defect) ? Effect.succeed(tooLarge()) : Effect.die(defect)58+ );59+60+/** `bytes` as a reader sees them. */61+export const contentsOfBytes = (bytes: Uint8Array): Contents => {62+ const binary = isBinary(bytes);63+ const truncated = !binary && bytes.length > TEXT_CAP;64+65+ return {66+ binary,67+ size: bytes.length,68+ text:69+ binary || truncated70+ ? Option.none()71+ : Option.some(new TextDecoder().decode(bytes)),72+ truncated,73+ };74+};75+76+/**77+ * The blob `blob`'s contents, kept by its id; none when the repo has no78+ * blob by it (a submodule's commit).79+ */80+export const contentsOf = (81+ repo: RepoName,82+ blob: BlobSha83+): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>84+ Effect.gen(function* () {85+ const cache = yield* CodeCache;86+87+ return yield* cache.through(88+ `${repo}:text:${blob}`,89+ unlessTooLarge(90+ RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(91+ Effect.map(Option.map(contentsOfBytes))92+ ),93+ () =>94+ Option.some({95+ binary: false,96+ size: 0,97+ text: Option.none(),98+ truncated: true,99+ })100+ ),101+ {102+ heavy: true,103+ keep: (contents) =>104+ Option.match(contents, {105+ onNone: () => false,106+ onSome: ({ text }) =>107+ Option.match(text, {108+ onNone: () => true,109+ onSome: (read) => read.length <= KEPT_TEXT,110+ }),111+ }),112+ }113+ );114+ });115+116+/** One file at `at`: its text, or that it is binary or too large. */117+export const fileView = (118+ project: CodeProject,119+ at: Option.Option<Rev>,120+ path: RepoPath121+): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>122+ Effect.gen(function* () {123+ const commit = yield* resolveRev(project, at);124+125+ const { tree } = yield* commitAt(project.repo, commit).pipe(126+ Effect.flatMap(Effect.fromOption),127+ Effect.orDie128+ );129+130+ const entry = yield* entryAt(project.repo, tree, path).pipe(Effect.orDie);131+132+ if (Option.isNone(entry) || entry.value.type !== "blob") {133+ return yield* new UnknownPath({ commit, path });134+ }135+136+ const sha = BlobSha.make(entry.value.sha);137+138+ const contents = yield* contentsOf(project.repo, sha).pipe(139+ Effect.orDie,140+ Effect.flatMap(Effect.fromOption),141+ Effect.orDie142+ );143+144+ return {145+ at: commit,146+ binary: contents.binary,147+ path,148+ sha,149+ size: contents.size,150+ truncated: contents.truncated,151+ ...Option.match(contents.text, {152+ onNone: () => ({}),153+ onSome: (text) => ({ text }),154+ }),155+ };156+ });added:packages/project/src/code/log.ts+212 added
1+/**2+ * The first-parent log from a revision, a page at a time: each commit as a3+ * reader sees it (subject, body, trailers, who and when), and `landing`4+ * only where the project's record has one, so a trailer in an imported5+ * commit never reads as a landing. With a path, only the commits whose6+ * first-parent change touched it, scanning at most 200 commits a call;7+ * `next` is where the scan stopped, so the next page resumes it.8+ */9+import { Revision, RepoHost } from "@repo/artifacts/repo-host";10+import type {11+ Commit,12+ RepoNotFound,13+ TreeEntry,14+} from "@repo/artifacts/repo-host";15+import { parseTrailers } from "@repo/git/trailers";16+import type { CommitView, Rev } from "@repo/protocol/domain/code";17+import type { LandingView } from "@repo/protocol/domain/landing";18+import { TreeSha } from "@repo/protocol/ids";19+import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";20+import type { UnknownRevision } from "@repo/protocol/refusal";21+import { DateTime, Effect, Equal, Option } from "effect";22+23+import type { CodeProject } from "../code.ts";24+import { CodeCache } from "./cache.ts";25+import { commitAt, resolveRev } from "./revision.ts";26+import { entryAt } from "./tree.ts";27+28+/** The most commits one page holds. */29+export const LOG_LIMIT = 100;30+31+/** The most first-parent commits a path's log scans in one call. */32+export const PATH_SCAN = 200;33+34+/** A commit as a reader sees it, with its landing when it is one. */35+export const commitView = (36+ commit: Commit,37+ landing: Option.Option<LandingView>38+): CommitView => {39+ const [subject = "", ...rest] = commit.message.split("\n");40+41+ return {42+ author: {43+ at: DateTime.fromEpochSeconds(commit.authoredAt),44+ email: commit.author.email,45+ name: commit.author.name,46+ },47+ body: rest.join("\n").replace(/^\n+/u, ""),48+ committer: {49+ at: DateTime.fromEpochSeconds(commit.committedAt),50+ email: commit.committer.email,51+ name: commit.committer.name,52+ },53+ parents: commit.parents,54+ sha: commit.sha,55+ subject,56+ trailers: parseTrailers(commit.message).map(({ key, value }) => ({57+ key,58+ value,59+ })),60+ tree: TreeSha.make(commit.tree),61+ ...Option.match(landing, {62+ onNone: () => ({}),63+ onSome: (found) => ({ landing: found }),64+ }),65+ };66+};67+68+/** `commits` as a reader sees them, each landing from one batch of the project's record. */69+export const commitViews = (70+ project: CodeProject,71+ commits: readonly Commit[]72+): Effect.Effect<readonly CommitView[]> =>73+ Effect.map(74+ commits.length === 075+ ? Effect.succeed([])76+ : project.landings(commits.map(({ sha }) => sha)),77+ (landings) => {78+ const bySha = new Map<string, LandingView>(79+ landings.map((landing) => [landing.sha, landing])80+ );81+82+ return commits.map((commit) =>83+ commitView(commit, Option.fromUndefinedOr(bySha.get(commit.sha)))84+ );85+ }86+ );87+88+/**89+ * `count` first-parent commits from `sha`, the first `from` skipped: a90+ * commit's history never changes, so the page is kept by its start.91+ */92+const pageOf = (93+ repo: RepoName,94+ sha: CommitSha,95+ from: number,96+ count: number97+): Effect.Effect<readonly Commit[], RepoNotFound, RepoHost> =>98+ Effect.gen(function* () {99+ const cache = yield* CodeCache;100+101+ return yield* cache.through(102+ `${repo}:log:${sha}:${from}:${count}`,103+ RepoHost.use((host) =>104+ host.log(repo, Revision.Commit({ sha }), count, from)105+ ),106+ { heavy: true }107+ );108+ });109+110+/** What sits at `path` in `tree`: its id and mode, or nothing. */111+const idAt = (repo: RepoName, tree: string, path: RepoPath) =>112+ Effect.map(113+ entryAt(repo, tree, path),114+ Option.map(({ mode, sha }: TreeEntry) => `${mode} ${sha}`)115+ );116+117+/** A page of the log, and where the next starts when there is more. */118+export interface LogPage {119+ readonly commits: readonly CommitView[];120+ readonly next?: number;121+}122+123+const pageWith = (124+ commits: readonly CommitView[],125+ next: Option.Option<number>126+): LogPage =>127+ Option.match(next, {128+ onNone: () => ({ commits }),129+ onSome: (at) => ({ commits, next: at }),130+ });131+132+/** A page of first-parent commits from `at`, each landing with its record. */133+export const logPage = (134+ project: CodeProject,135+ input: {136+ readonly at: Option.Option<Rev>;137+ readonly path: Option.Option<RepoPath>;138+ readonly from: number;139+ readonly limit: number;140+ }141+): Effect.Effect<LogPage, UnknownRevision, RepoHost> =>142+ Effect.gen(function* () {143+ const sha = yield* resolveRev(project, input.at);144+ const from = Math.max(0, Math.floor(input.from));145+ const limit = Math.min(LOG_LIMIT, Math.max(1, Math.floor(input.limit)));146+ const { repo } = project;147+148+ if (Option.isNone(input.path)) {149+ const read = yield* pageOf(repo, sha, from, limit + 1).pipe(Effect.orDie);150+ const commits = yield* commitViews(project, read.slice(0, limit));151+152+ return pageWith(153+ commits,154+ read.length > limit ? Option.some(from + limit) : Option.none()155+ );156+ }157+158+ const path = input.path.value;159+160+ // One past the scan, so the last scanned commit's parent is at hand161+ // and whether history goes on is known.162+ const scan = yield* pageOf(repo, sha, from, PATH_SCAN + 1).pipe(163+ Effect.orDie164+ );165+166+ const scanned = scan.slice(0, PATH_SCAN);167+ const touched: Commit[] = [];168+169+ for (const [at, commit] of scanned.entries()) {170+ const parent = Option.fromUndefinedOr(commit.parents[0]);171+ const after = Option.fromUndefinedOr(scan[at + 1]);172+173+ // The log is first parents, so the next commit in it is this one's174+ // parent; only past the scan is the parent read on its own.175+ const parentCommit = yield* Option.match(parent, {176+ onNone: () => Effect.succeedNone,177+ onSome: (first) =>178+ Option.exists(after, ({ sha: next }) => next === first)179+ ? Effect.succeed(after)180+ : commitAt(repo, first),181+ }).pipe(Effect.orDie);182+183+ const parentTree = Option.map(parentCommit, ({ tree }) => tree);184+185+ const now = yield* idAt(repo, commit.tree, path).pipe(Effect.orDie);186+187+ const before = yield* Option.match(parentTree, {188+ onNone: () => Effect.succeedNone,189+ onSome: (tree) => idAt(repo, tree, path),190+ }).pipe(Effect.orDie);191+192+ if (!Equal.equals(now, before)) {193+ touched.push(commit);194+ }195+196+ if (touched.length === limit) {197+ const commits = yield* commitViews(project, touched);198+199+ return pageWith(200+ commits,201+ at + 1 < scan.length ? Option.some(from + at + 1) : Option.none()202+ );203+ }204+ }205+206+ const commits = yield* commitViews(project, touched);207+208+ return pageWith(209+ commits,210+ scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()211+ );212+ });added:packages/project/src/code/paths.ts+125 added
1+/**2+ * Every file of a commit: each blob, symlink and submodule path under its3+ * root tree, up to 50,000 (a file tree's sidebar), kept by the root tree's4+ * id. The walk reads at most eight trees at once, one depth at a time, and5+ * stops descending once the cap is passed.6+ */7+import type {8+ RepoHost,9+ RepoNotFound,10+ TreeEntry,11+} from "@repo/artifacts/repo-host";12+import type { PathList, Rev } from "@repo/protocol/domain/code";13+import { RepoPath } from "@repo/protocol/ids";14+import type { RepoName } from "@repo/protocol/ids";15+import type { UnknownRevision } from "@repo/protocol/refusal";16+import type { Option } from "effect";17+import { Array, Effect, Order } from "effect";18+19+import type { CodeProject } from "../code.ts";20+import { CodeCache } from "./cache.ts";21+import { commitAt, resolveRev } from "./revision.ts";22+import { entriesOf } from "./tree.ts";23+24+/** The most paths a commit's list holds. */25+export const PATHS_CAP = 50_000;26+27+/** The longest path list the cache keeps: about 1 MB of paths. */28+const KEPT_PATHS = 10_000;29+30+// Store calls under way at once, however wide or deep the tree.31+const STORE_CALLS = 8;32+33+/** One file under a root tree, with the entry that names it. */34+export interface FileAt {35+ readonly path: RepoPath;36+ readonly entry: TreeEntry;37+}38+39+/** A folder still to read: its path's prefix and its tree's id. */40+interface Folder {41+ readonly prefix: string;42+ readonly tree: string;43+}44+45+/**46+ * Every file under the tree `root`, in path order; past `cap`, the walk47+ * stops and says so. It reads one depth at a time, so which folders it48+ * reaches before it stops depends on the tree alone, never on which read49+ * came back first: the same tree gives the same list (principle 8).50+ */51+export const filesUnder = (52+ repo: RepoName,53+ root: string,54+ cap: number55+): Effect.Effect<56+ { readonly files: readonly FileAt[]; readonly truncated: boolean },57+ RepoNotFound,58+ RepoHost59+> =>60+ Effect.gen(function* () {61+ const found: FileAt[] = [];62+ let depth: readonly Folder[] = [{ prefix: "", tree: root }];63+64+ while (depth.length > 0 && found.length <= cap) {65+ const read = yield* Effect.forEach(66+ depth,67+ ({ prefix, tree }) =>68+ Effect.map(entriesOf(repo, tree), (entries) => ({ entries, prefix })),69+ { concurrency: STORE_CALLS }70+ );71+72+ const deeper: Folder[] = [];73+74+ for (const { entries, prefix } of read) {75+ for (const entry of entries) {76+ if (entry.type === "tree") {77+ deeper.push({ prefix: `${prefix}${entry.name}/`, tree: entry.sha });78+ } else {79+ found.push({80+ entry,81+ path: RepoPath.make(`${prefix}${entry.name}`),82+ });83+ }84+ }85+ }86+87+ depth = deeper;88+ }89+90+ const all = Array.sort(91+ found,92+ Order.mapInput(Order.String, (file: FileAt) => file.path)93+ );94+95+ return {96+ files: all.slice(0, cap),97+ truncated: all.length > cap || depth.length > 0,98+ };99+ });100+101+/** Every file path at `at`, up to the cap. */102+export const pathList = (103+ project: CodeProject,104+ at: Option.Option<Rev>105+): Effect.Effect<PathList, UnknownRevision, RepoHost> =>106+ Effect.gen(function* () {107+ const commit = yield* resolveRev(project, at);108+ const cache = yield* CodeCache;109+110+ const { tree } = yield* commitAt(project.repo, commit).pipe(111+ Effect.flatMap(Effect.fromOption),112+ Effect.orDie113+ );114+115+ const { files, truncated } = yield* cache116+ .through(117+ `${project.repo}:paths:${tree}`,118+ filesUnder(project.repo, tree, PATHS_CAP),119+ // A longer list is walked again, over trees the cache keeps.120+ { heavy: true, keep: (list) => list.files.length <= KEPT_PATHS }121+ )122+ .pipe(Effect.orDie);123+124+ return { at: commit, paths: files.map(({ path }) => path), truncated };125+ });added:packages/project/src/code/raw.ts+194 added
1+/**2+ * A project's raw bytes, `GET /<project>/raw/<rev>/<path…>` (spec W9-D6),3+ * as one pure response both the platform (`apps/platform/src/raw.ts`) and4+ * the web's dev world serve. Both origins hold a session cookie, so no file5+ * may run as script there: every answer carries `nosniff` and a sandboxing6+ * CSP, images come back as themselves (an SVG too: an `<img>` never runs7+ * its script, and opened on its own the sandbox gives it no script and an8+ * opaque origin), markup and every other text as plain text, and anything9+ * else binary as bytes to save. A file at a commit's id never changes, so10+ * it is cached for good; at a name that moves, for a minute. Anything that11+ * is not a file at a revision is a 404 that says nothing of the repo.12+ */13+import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";14+import { Rev } from "@repo/protocol/domain/code";15+import { BlobSha, RepoPath } from "@repo/protocol/ids";16+import type { ProjectName } from "@repo/protocol/ids";17+import { Effect, Option, Schema } from "effect";18+19+import { codeProjectOf } from "../code.ts";20+import type { CodeProject } from "../code.ts";21+import { Projects } from "../projects.ts";22+import { isBinary, unlessTooLarge } from "./file.ts";23+import { commitAt, isFullSha, resolveRev } from "./revision.ts";24+import { entryAt, segmentsOf } from "./tree.ts";25+26+/** What a raw answer may load and do: nothing but its own images and inline styles, sandboxed. */27+const SANDBOX =28+ "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";29+30+const IMAGES = new Map([31+ ["avif", "image/avif"],32+ ["gif", "image/gif"],33+ ["ico", "image/x-icon"],34+ ["jpeg", "image/jpeg"],35+ ["jpg", "image/jpeg"],36+ ["png", "image/png"],37+ ["svg", "image/svg+xml"],38+ ["webp", "image/webp"],39+]);40+41+const TEXT = "text/plain; charset=utf-8";42+43+/** What every raw answer carries, a refusal too (spec W9-D6). */44+const SAFE = {45+ "content-security-policy": SANDBOX,46+ "x-content-type-options": "nosniff",47+} as const;48+49+/** `path`'s extension, lowercased; none without one. */50+const extensionOf = (path: string) => {51+ const name = path.slice(path.lastIndexOf("/") + 1);52+ const dot = name.lastIndexOf(".");53+54+ return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();55+};56+57+/**58+ * The headers a raw answer for the blob `blob` at `path` carries: its type59+ * by extension (an image as itself, anything else as plain text, or as60+ * bytes when `binary`), `nosniff` and the sandbox, and a cache for good61+ * when `rev` is a commit's id, for a minute when it is a name.62+ */63+export const rawHeaders = (64+ path: RepoPath,65+ rev: "sha" | "ref",66+ blob: BlobSha,67+ binary = false68+): Headers => {69+ const headers = new Headers({70+ ...SAFE,71+ "content-type":72+ IMAGES.get(extensionOf(path)) ??73+ (binary ? "application/octet-stream" : TEXT),74+ });75+76+ if (rev === "sha") {77+ headers.set("cache-control", "public, max-age=31536000, immutable");78+ headers.set("etag", `"${blob}"`);79+ } else {80+ headers.set("cache-control", "public, max-age=60");81+ }82+83+ return headers;84+};85+86+/** A 404 that says nothing of the repo. */87+const notFound = () => new Response(null, { headers: SAFE, status: 404 });88+89+/** A 413: Artifacts said the blob is too large to hold. */90+const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });91+92+/** The file `path` at `rev` of the project's canonical repo, as raw bytes. */93+export const rawOf = (94+ project: CodeProject,95+ rev: Rev,96+ path: RepoPath97+): Effect.Effect<Response, never, RepoHost> =>98+ Effect.gen(function* () {99+ const commit = yield* resolveRev(project, Option.some(rev));100+101+ const { tree } = yield* commitAt(project.repo, commit).pipe(102+ Effect.flatMap(Effect.fromOption)103+ );104+105+ const entry = yield* entryAt(project.repo, tree, path);106+107+ if (Option.isNone(entry) || entry.value.type !== "blob") {108+ return notFound();109+ }110+111+ const blob = BlobSha.make(entry.value.sha);112+113+ const bytes = yield* RepoHost.use((host) =>114+ host.readBlob(project.repo, ObjectId.make(blob))115+ );116+117+ return Option.match(bytes, {118+ onNone: notFound,119+ onSome: (read) =>120+ new Response(new Uint8Array(read), {121+ headers: rawHeaders(122+ path,123+ isFullSha(rev) ? "sha" : "ref",124+ blob,125+ isBinary(read)126+ ),127+ status: 200,128+ }),129+ });130+ }).pipe(131+ (read) => unlessTooLarge(read, tooLarge),132+ Effect.catchTags({133+ NoSuchElementError: () => Effect.succeed(notFound()),134+ RepoNotFound: () => Effect.succeed(notFound()),135+ UnknownRevision: () => Effect.succeed(notFound()),136+ })137+ );138+139+const decodeRev = Schema.decodeUnknownOption(Rev);140+141+const decodePath = Schema.decodeUnknownOption(RepoPath);142+143+const decoded = Option.liftThrowable(decodeURIComponent);144+145+/**146+ * A raw request's revision and path from everything after `raw/`, as the147+ * URL carries it: the first segment is the revision (a tag's `/` arrives148+ * as `%2F`), the rest the file's path, each decoded once. A path with an149+ * empty, `.` or `..` segment, before or after decoding, is none.150+ */151+export const rawRequestOf = (152+ rest: string153+): Option.Option<{ readonly rev: Rev; readonly path: RepoPath }> => {154+ const slash = rest.indexOf("/");155+156+ if (slash === -1) {157+ return Option.none();158+ }159+160+ return Option.all({161+ path: decoded(rest.slice(slash + 1)).pipe(162+ Option.filter((path) => Option.isSome(segmentsOf(path))),163+ Option.flatMap(decodePath)164+ ),165+ rev: Option.flatMap(decoded(rest.slice(0, slash)), decodeRev),166+ });167+};168+169+/**170+ * Everything after `/<project>/raw/` in a request's URL (whole, or its path171+ * and query), still encoded. Read from the URL itself, not a router's172+ * parameter: a router decodes `%2F`, which would cut a tag's name173+ * (`%40datekit%2Fcore%402.0.0`) in two.174+ */175+export const rawRestOf = (url: string): string =>176+ new URL(url, "http://raw.invalid").pathname.split("/").slice(3).join("/");177+178+/**179+ * The answer to `GET /<project>/raw/<rest>` at `url` (whole, or its path180+ * and query): the project found by its name, then its file. A project181+ * never made is a 404 too.182+ */183+export const rawFor = (184+ project: ProjectName,185+ url: string186+): Effect.Effect<Response, never, RepoHost | Projects> =>187+ Option.match(rawRequestOf(rawRestOf(url)), {188+ onNone: () => Effect.succeed(notFound()),189+ onSome: ({ path, rev }) =>190+ Projects.use((projects) => projects.get(project)).pipe(191+ Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),192+ Effect.catchTag("UnknownProject", () => Effect.succeed(notFound()))193+ ),194+ });added:packages/project/src/code/refs.ts+112 added
1+/**2+ * A project's refs as readers see them: main's landed commit (the3+ * project's record, never a ref), its tags peeled to their commits (the4+ * repo's `tags`) and sorted by version, newest first, and its forks. Only5+ * `refs/tags/*` is read: nothing of the platform's own (its landed mirror,6+ * compose refs, notes) and no branch but main ever shows.7+ */8+import { RepoHost } from "@repo/artifacts/repo-host";9+import { TagName } from "@repo/protocol/domain/code";10+import type { RefsView, TagRef } from "@repo/protocol/domain/code";11+import { Array, Effect, Option, Schema } from "effect";12+13+import type { CodeProject } from "../code.ts";14+import { tagNameOf } from "./revision.ts";15+16+/** A name cut into runs of digits and runs of anything else. */17+const runsOf = (name: string) => name.match(/\d+|\D+/gu) ?? [];18+19+const isDigits = (run: string) => /^\d/u.test(run);20+21+/** Two strings as written, code point by code point. */22+const compareText = (one: string, other: string) => {23+ if (one === other) {24+ return 0;25+ }26+27+ return one < other ? -1 : 1;28+};29+30+/** Two runs of digits by their value, however long. */31+const compareNumbers = (one: string, other: string) => {32+ const left = one.replace(/^0+(?=\d)/u, "");33+ const right = other.replace(/^0+(?=\d)/u, "");34+35+ if (left.length !== right.length) {36+ return left.length < right.length ? -1 : 1;37+ }38+39+ return compareText(left, right);40+};41+42+/**43+ * Tags newest first, by version: runs of digits compare by value, so44+ * `v1.10.0` comes before `v1.9.0`, and a release before its own45+ * pre-releases (`v1.10.0` before `v1.10.0-beta.1`). Names are otherwise46+ * compared as written, so a scoped package's tags stay together.47+ */48+export const compareTags = (one: string, other: string): number => {49+ const left = runsOf(one);50+ const right = runsOf(other);51+52+ for (let at = 0; at < Math.min(left.length, right.length); at += 1) {53+ const mine = left[at] ?? "";54+ const theirs = right[at] ?? "";55+56+ const order =57+ isDigits(mine) && isDigits(theirs)58+ ? compareNumbers(mine, theirs)59+ : compareText(mine, theirs);60+61+ if (order !== 0) {62+ return -order;63+ }64+ }65+66+ if (left.length === right.length) {67+ return 0;68+ }69+70+ // One name runs on past the other: a pre-release (`-beta.1`) is older71+ // than its release, anything else newer.72+ const longer = left.length > right.length ? left : right;73+ const rest = longer[Math.min(left.length, right.length)] ?? "";74+ const longerIsNewer = !rest.startsWith("-");75+ const leftIsLonger = left.length > right.length;76+77+ return leftIsLonger === longerIsNewer ? -1 : 1;78+};79+80+const decodeTag = Schema.decodeUnknownOption(TagName);81+82+/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */83+export const refsView = (84+ project: CodeProject85+): Effect.Effect<RefsView, never, RepoHost> =>86+ Effect.gen(function* () {87+ const landed = yield* project.head;88+ const forks = yield* project.forks;89+90+ const tags = yield* RepoHost.use((host) => host.tags(project.repo)).pipe(91+ Effect.catchTag("RepoNotFound", () => Effect.succeed([]))92+ );93+94+ const named = Array.getSomes(95+ tags.map(({ name, sha }) =>96+ Option.map(97+ Option.flatMap(tagNameOf(name), decodeTag),98+ (tag): TagRef => ({ name: tag, sha })99+ )100+ )101+ );102+103+ return {104+ forks,105+ project: project.project,106+ tags: named.toSorted((one, other) => compareTags(one.name, other.name)),107+ ...Option.match(landed, {108+ onNone: () => ({}),109+ onSome: (sha) => ({ landed: sha }),110+ }),111+ };112+ });added:packages/project/src/code/revision.ts+99 added
1+/**2+ * A revision as a reader names it, resolved to the commit it means in the3+ * project's canonical repo (spec W9-D3): absent or `main` is main's landed4+ * commit, from the project's record and never from a ref; 40 hex digits are5+ * that commit, if the repo holds it; anything else is a tag's exact name,6+ * found among the repo's tags and never joined into a ref path, so7+ * `../heads/x` or a ref of the platform's own names nothing.8+ */9+import { RepoHost } from "@repo/artifacts/repo-host";10+import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";11+import type { Rev } from "@repo/protocol/domain/code";12+import { CommitSha } from "@repo/protocol/ids";13+import type { RepoName } from "@repo/protocol/ids";14+import { UnknownRevision } from "@repo/protocol/refusal";15+import { Array, Effect, Option } from "effect";16+17+import type { CodeProject } from "../code.ts";18+import { CodeCache } from "./cache.ts";19+20+/** A full commit id: 40 lowercase hex digits. Short ids are not resolved. */21+const FULL_SHA = /^[0-9a-f]{40}$/u;22+23+/** Whether `rev` names a commit by its full id (and so never moves). */24+export const isFullSha = (rev: string) => FULL_SHA.test(rev);25+26+/** Where every tag's name starts. */27+const TAGS = "refs/tags/";28+29+/** A ref name's tag name, when it is a tag's. */30+export const tagNameOf = (ref: string): Option.Option<string> =>31+ ref.startsWith(TAGS) ? Option.some(ref.slice(TAGS.length)) : Option.none();32+33+/**34+ * The commit `sha` in `repo`, kept once found. A miss is not kept: the35+ * commit may yet be pushed.36+ */37+export const commitAt = (38+ repo: RepoName,39+ sha: CommitSha40+): Effect.Effect<Option.Option<Commit>, RepoNotFound, RepoHost> =>41+ Effect.gen(function* () {42+ const cache = yield* CodeCache;43+44+ return yield* cache45+ .through(46+ `${repo}:commit:${sha}`,47+ RepoHost.use((host) => host.readCommit(repo, sha)).pipe(48+ Effect.flatMap(Effect.fromOption)49+ )50+ )51+ .pipe(52+ Effect.asSome,53+ Effect.catchTag("NoSuchElementError", () => Effect.succeedNone)54+ );55+ });56+57+/** The commit `at` names in the project's canonical repo. */58+export const resolveRev = (59+ project: CodeProject,60+ at: Option.Option<Rev>61+): Effect.Effect<CommitSha, UnknownRevision, RepoHost> => {62+ const rev = Option.getOrElse(at, () => "main");63+ const unknown = new UnknownRevision({ rev });64+65+ if (rev === "main") {66+ return Effect.flatMap(project.head, (landed) =>67+ Option.match(landed, {68+ onNone: () => Effect.fail(unknown),69+ onSome: (sha) => Effect.succeed<CommitSha>(sha),70+ })71+ );72+ }73+74+ if (isFullSha(rev)) {75+ const sha = CommitSha.make(rev);76+77+ return commitAt(project.repo, sha).pipe(78+ Effect.catchTag("RepoNotFound", () => Effect.succeedNone),79+ Effect.flatMap((found) =>80+ Option.isSome(found) ? Effect.succeed(sha) : Effect.fail(unknown)81+ )82+ );83+ }84+85+ return RepoHost.use((host) => host.tags(project.repo)).pipe(86+ Effect.catchTag("RepoNotFound", () => Effect.succeed([])),87+ Effect.flatMap((tags) =>88+ Option.match(89+ Array.findFirst(tags, ({ name }) =>90+ Option.contains(tagNameOf(name), rev)91+ ),92+ {93+ onNone: () => Effect.fail(unknown),94+ onSome: ({ sha }) => Effect.succeed(sha),95+ }96+ )97+ )98+ );99+};added:packages/project/src/code/tree.ts+185 added
1+/**2+ * Folders of a commit: a tree's entries by its id (kept once read), the3+ * entry at a path, walked one segment at a time, and one folder as a4+ * reader lists it: folders first, then by name, each entry by its kind,5+ * with its README by GitLab's precedence, any case.6+ */7+import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";8+import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";9+import type { CodeEntry, Rev, TreeListing } from "@repo/protocol/domain/code";10+import { BlobSha, RepoPath } from "@repo/protocol/ids";11+import type { CommitSha, RepoName } from "@repo/protocol/ids";12+import { UnknownPath } from "@repo/protocol/refusal";13+import type { UnknownRevision } from "@repo/protocol/refusal";14+import { Array, Effect, Match, Option, Order } from "effect";15+16+import type { CodeProject } from "../code.ts";17+import { CodeCache } from "./cache.ts";18+import { commitAt, resolveRev } from "./revision.ts";19+20+/** The entries of the tree `id`; a tree a commit or a tree names is always there. */21+export const entriesOf = (22+ repo: RepoName,23+ id: string24+): Effect.Effect<readonly TreeEntry[], RepoNotFound, RepoHost> =>25+ Effect.gen(function* () {26+ const cache = yield* CodeCache;27+28+ return yield* cache.through(29+ `${repo}:tree:${id}`,30+ RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(31+ Effect.flatMap(32+ Option.match({33+ onNone: () => Effect.die(`${repo} has no tree ${id}`),34+ onSome: Effect.succeed,35+ })36+ )37+ )38+ );39+ });40+41+/** The segments of `path`; none when one is empty, `.` or `..`. */42+export const segmentsOf = (path: string): Option.Option<readonly string[]> => {43+ const segments = path.split("/");44+45+ return segments.every(46+ (segment) => segment !== "" && segment !== "." && segment !== ".."47+ )48+ ? Option.some(segments)49+ : Option.none();50+};51+52+/** The entry at `path` under the tree `root`, walked one segment at a time. */53+export const entryAt = (54+ repo: RepoName,55+ root: string,56+ path: string57+): Effect.Effect<Option.Option<TreeEntry>, RepoNotFound, RepoHost> =>58+ Option.match(segmentsOf(path), {59+ onNone: () => Effect.succeedNone,60+ onSome: (segments) =>61+ Effect.gen(function* () {62+ let tree = root;63+ let found: Option.Option<TreeEntry> = Option.none();64+65+ for (const [at, segment] of segments.entries()) {66+ if (at > 0) {67+ if (Option.isNone(found) || found.value.type !== "tree") {68+ return Option.none();69+ }70+71+ tree = found.value.sha;72+ }73+74+ const entries = yield* entriesOf(repo, tree);75+76+ found = Array.findFirst(entries, ({ name }) => name === segment);77+ }78+79+ return found;80+ }),81+ });82+83+/** What a reader sees an entry as: a gitlink is a submodule, mode 120000 a symlink. */84+export const kindOf = (entry: TreeEntry): CodeEntry["type"] =>85+ Match.value(entry).pipe(86+ Match.when({ type: "tree" }, () => "tree" as const),87+ Match.when({ type: "commit" }, () => "submodule" as const),88+ Match.when({ mode: "120000" }, () => "symlink" as const),89+ Match.orElse(() => "blob" as const)90+ );91+92+/** Folders first, then by name. */93+const byKindThenName = Order.combine(94+ Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),95+ Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)96+);97+98+/** GitLab's README precedence, lowercased. */99+const README = [100+ "readme.md",101+ "readme.markdown",102+ "readme.mdown",103+ "readme",104+ "readme.txt",105+ "readme.rst",106+];107+108+const readmeOf = (entries: readonly CodeEntry[]) =>109+ Array.findFirst(README, (name) =>110+ Array.findFirst(111+ entries,112+ (entry) => entry.type === "blob" && entry.name.toLowerCase() === name113+ )114+ ).pipe(Option.map(({ path, sha }) => ({ path, sha: BlobSha.make(sha) })));115+116+/** The tree `path` names at `commit`, or `UnknownPath`. */117+export const folderAt = (118+ repo: RepoName,119+ commit: CommitSha,120+ path: Option.Option<RepoPath>121+): Effect.Effect<string, UnknownPath, RepoHost> =>122+ Effect.gen(function* () {123+ const found = yield* commitAt(repo, commit).pipe(124+ Effect.flatMap(Effect.fromOption)125+ );126+127+ if (Option.isNone(path)) {128+ return found.tree;129+ }130+131+ const entry = yield* entryAt(repo, found.tree, path.value);132+133+ if (Option.isNone(entry) || entry.value.type !== "tree") {134+ return yield* new UnknownPath({ commit, path: path.value });135+ }136+137+ return entry.value.sha;138+ }).pipe(139+ Effect.catchTags({140+ NoSuchElementError: Effect.die,141+ RepoNotFound: Effect.die,142+ })143+ );144+145+/** One folder at `at`, folders first, with its README. */146+export const listing = (147+ project: CodeProject,148+ at: Option.Option<Rev>,149+ path: Option.Option<RepoPath>150+): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>151+ Effect.gen(function* () {152+ const commit = yield* resolveRev(project, at);153+ const tree = yield* folderAt(project.repo, commit, path);154+155+ const prefix = Option.match(path, {156+ onNone: () => "",157+ onSome: (folder) => `${folder}/`,158+ });159+160+ const read = yield* entriesOf(project.repo, tree).pipe(Effect.orDie);161+162+ const entries = Array.sort(163+ read.map((entry): CodeEntry => ({164+ mode: entry.mode,165+ name: entry.name,166+ path: RepoPath.make(`${prefix}${entry.name}`),167+ sha: entry.sha,168+ type: kindOf(entry),169+ })),170+ byKindThenName171+ );172+173+ return {174+ at: commit,175+ entries,176+ ...Option.match(path, {177+ onNone: () => ({}),178+ onSome: (folder) => ({ path: folder }),179+ }),180+ ...Option.match(readmeOf(entries), {181+ onNone: () => ({}),182+ onSome: (readme) => ({ readme }),183+ }),184+ };185+ });modified:packages/project/src/code.ts+31 added-21 removed
5 unmodified lines6 * the web's dev world call these with the `RepoHost` they run on, and7 * consult the project's record only for main's landed commit, its landings8 * and its forks (`CodeProject`). Reads by object id go through `CodeCache`.9 *10- * Stubs until 903 (every read but `whyOf`) and 912 (`whyOf`) land; the11- * signatures are final.10+ * Each read lives in its own module under `code/`; `whyOf` is a stub until11+ * 912 lands.12 */13 import type { RepoHost } from "@repo/artifacts/repo-host";14 import type {15 CommitDiff,20 unmodified lines36 UnknownRevision,37 } from "@repo/protocol/refusal";38 import { Effect, Option } from "effect";39 40+import { commitDiff } from "./code/commit.ts";41+import { fileView } from "./code/file.ts";42+import { logPage } from "./code/log.ts";43+import { pathList } from "./code/paths.ts";44+import { refsView } from "./code/refs.ts";45+import { listing } from "./code/tree.ts";46 import type { ProjectApi } from "./project.ts";47 48 /** What the code reads take from a project's record, beside its canonical repo. */49 export interface CodeProject {50+ /** The project, as its refs name it. */51+ readonly project: ProjectName;52 /** The project's canonical repo: never a fork's or a layer's. */53 readonly repo: RepoName;54 /** Main's landed commit; none before the first push. */55 readonly head: Effect.Effect<Option.Option<LandedSha>>;11 unmodified lines67 ): CodeProject => ({68 forks: api.forks(),69 head: Effect.map(api.head(), ({ landed }) => Option.fromUndefinedOr(landed)),70 landings: api.landings,71+ project,72 repo: RepoName.make(project),73 });74 75 const notBuilt = (issue: string) => Effect.die(`not built: ${issue}`);76 77 /** Main's landed commit, its tags peeled and sorted newest first, and its forks. */78 export const refsOf = (70- _project: CodeProject71-): Effect.Effect<RefsView, never, RepoHost> => notBuilt("903");79+ project: CodeProject80+): Effect.Effect<RefsView, never, RepoHost> => refsView(project);81 82 /** One folder at `at` (main when none), folders first, with its README. */83 export const treeOf = (75- _project: CodeProject,76- _at: Option.Option<Rev>,77- _path: Option.Option<RepoPath>84+ project: CodeProject,85+ at: Option.Option<Rev>,86+ path: Option.Option<RepoPath>87 ): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>79- notBuilt("903");88+ listing(project, at, path);89 90 /** Every file path at `at`, up to the cap. */91 export const pathsOf = (83- _project: CodeProject,84- _at: Option.Option<Rev>85-): Effect.Effect<PathList, UnknownRevision, RepoHost> => notBuilt("903");92+ project: CodeProject,93+ at: Option.Option<Rev>94+): Effect.Effect<PathList, UnknownRevision, RepoHost> => pathList(project, at);95 96 /** One file at `at`: its text, or that it is binary or too large. */97 export const fileOf = (89- _project: CodeProject,90- _at: Option.Option<Rev>,91- _path: RepoPath98+ project: CodeProject,99+ at: Option.Option<Rev>,100+ path: RepoPath101 ): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>93- notBuilt("903");102+ fileView(project, at, path);103 104 /** A page of first-parent commits from `at`, each landing with its record. */105 export const logOf = (97- _project: CodeProject,98- _input: {106+ project: CodeProject,107+ input: {108 readonly at: Option.Option<Rev>;109 readonly path: Option.Option<RepoPath>;110 readonly from: number;111 readonly limit: number;1 unmodified line113 ): Effect.Effect<114 { readonly commits: readonly CommitView[]; readonly next?: number },115 UnknownRevision,116 RepoHost108-> => notBuilt("903");117+> => logPage(project, input);118 119 /** One commit and the files it changed against its first parent. */120 export const commitOf = (112- _project: CodeProject,113- _sha: CommitSha114-): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> => notBuilt("903");121+ project: CodeProject,122+ sha: CommitSha123+): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>124+ commitDiff(project, sha);125 126 /** Why each line of a file at `at` is there. */127 export const whyOf = (128 _project: CodeProject,4 unmodified linesmodified:packages/project/test/code-facade.test.ts+7 added-36 removed
1 /**2 * The code façade both handler files call: a project's code read from its3 * canonical repo alone, with main resolved through the project's record.4- * Until 903 and 912 land, each read names the issue that builds it.4+ * Until 912 lands, why each line is there names the issue that builds it.5 */6 import { describe, expect, it } from "@effect/vitest";7 import { RepoHost } from "@repo/artifacts/repo-host";8 import type { ProjectApi } from "@repo/project/project";9-import {10- CommitSha,11- LandedSha,12- ProjectName,13- RepoPath,14-} from "@repo/protocol/ids";9+import { LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";10 import { untouchable } from "@repo/testkit/untouchable";11 import { Cause, Effect, Exit, Option } from "effect";12 18-import {19- codeProjectOf,20- commitOf,21- fileOf,22- logOf,23- pathsOf,24- refsOf,25- treeOf,26- whyOf,27-} from "../src/code.ts";13+import { codeProjectOf, whyOf } from "../src/code.ts";14 import { CodeCache } from "../src/code/cache.ts";15 16 const project = ProjectName.make("datekit");17 18 const landed = LandedSha.make("4".repeat(40));19 34-const sha = CommitSha.make("4".repeat(40));35-20 const path = RepoPath.make("README.md");21 22 /** A project's record, as the façade reads it: only these three. */23 const api = untouchable<ProjectApi>("ProjectApi", {46 unmodified lines70 expect(yield* cache.through("datekit:tree:x", read)).toBe(2);71 })72 );73 90- it.effect("names the issue that builds each read", () =>74+ it.effect("names the issue that builds why each line is there", () =>75 Effect.gen(function* () {92- const none = Option.none();93-94- expect(95- yield* Effect.all([96- diedWith(refsOf(code)),97- diedWith(treeOf(code, none, none)),98- diedWith(pathsOf(code, none)),99- diedWith(fileOf(code, none, path)),100- diedWith(logOf(code, { at: none, from: 0, limit: 30, path: none })),101- diedWith(commitOf(code, sha)),102- diedWith(whyOf(code, none, path)),103- ])104- ).toStrictEqual([105- ...Array.from({ length: 6 }, () => Option.some("not built: 903")),106- Option.some("not built: 912"),107- ]);76+ expect(yield* diedWith(whyOf(code, Option.none(), path))).toStrictEqual(77+ Option.some("not built: 912")78+ );79 })80 );81 });added:packages/project/test/code-fixtures.ts+395 added
1+/**2+ * Repos the code reads are tested over, written object by object with3+ * isomorphic-git and pushed to the memory repo host: files of every kind4+ * (text, binary, too large, a symlink, a submodule), the refs a canonical5+ * repo really carries beside main (the landed mirror, a compose ref, the6+ * notes, an import's stale `master`), and tags both lightweight and7+ * annotated. Each `CodeProject` is fixed: its head, its one landing and its8+ * one fork never come from the repo.9+ */10+import { RefName, RepoHost } from "@repo/artifacts/repo-host";11+import type { RefUpdate } from "@repo/artifacts/repo-host";12+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";13+import { Brand } from "@repo/brand";14+import type { ForkRef } from "@repo/protocol/domain/code";15+import type { LandingView } from "@repo/protocol/domain/landing";16+import {17+ AskId,18+ CommitSha,19+ Handle,20+ LandedSha,21+ ProjectName,22+ RepoName,23+} from "@repo/protocol/ids";24+import { Array, Data, DateTime, Effect, Option } from "effect";25+import {26+ init,27+ writeBlob,28+ writeCommit,29+ writeTag,30+ writeTree,31+} from "isomorphic-git";32+import type { FsClient, TreeEntry } from "isomorphic-git";33+34+import type { CodeProject } from "../src/code.ts";35+36+/** A file's content: text, bytes, a symlink's target, or a submodule's commit. */37+export type Content = Data.TaggedEnum<{38+ Bytes: { readonly bytes: Uint8Array };39+ Gitlink: { readonly commit: string };40+ Link: { readonly target: string };41+ Text: { readonly text: string };42+}>;43+44+export const Content = Data.taggedEnum<Content>();45+46+/** Paths and what each holds. */47+export type Tree = readonly (readonly [path: string, content: Content])[];48+49+interface Source {50+ readonly fs: FsClient;51+ readonly gitdir: string;52+}53+54+const blobOf = (55+ source: Source,56+ name: string,57+ mode: string,58+ bytes: Uint8Array59+) =>60+ Effect.map(61+ Effect.promise(() => writeBlob({ ...source, blob: bytes })),62+ (oid): TreeEntry => ({ mode, oid, path: name, type: "blob" })63+ );64+65+const entryOf = (source: Source, name: string, content: Content) =>66+ Content.$match(content, {67+ Bytes: ({ bytes }) => blobOf(source, name, "100644", bytes),68+ Gitlink: ({ commit }) =>69+ Effect.succeed<TreeEntry>({70+ mode: "160000",71+ oid: commit,72+ path: name,73+ type: "commit",74+ }),75+ Link: ({ target }) =>76+ blobOf(source, name, "120000", new TextEncoder().encode(target)),77+ Text: ({ text }) =>78+ blobOf(source, name, "100644", new TextEncoder().encode(text)),79+ });80+81+const treeOf = (source: Source, files: Tree): Effect.Effect<string> =>82+ Effect.gen(function* () {83+ const entries: TreeEntry[] = [];84+ const nested = new Map<string, [string, Content][]>();85+86+ for (const [path, content] of files) {87+ const [head = path, ...rest] = path.split("/");88+89+ if (rest.length === 0) {90+ entries.push(yield* entryOf(source, head, content));91+ } else {92+ nested.set(head, [93+ ...(nested.get(head) ?? []),94+ [rest.join("/"), content],95+ ]);96+ }97+ }98+99+ for (const [path, inner] of nested) {100+ const oid = yield* treeOf(source, inner);101+102+ entries.push({ mode: "040000", oid, path, type: "tree" });103+ }104+105+ return yield* Effect.promise(() => writeTree({ ...source, tree: entries }));106+ });107+108+/**109+ * A bare repo in memory that commits are written to and pushed from, each110+ * commit's time `at` seconds after 2026-10-01.111+ */112+export const writer = Effect.gen(function* () {113+ const source = { fs: memoryFs(), gitdir: "/source.git" };114+115+ yield* Effect.promise(() =>116+ init({ ...source, bare: true, defaultBranch: "main" })117+ );118+119+ const commit = (120+ message: string,121+ files: Tree,122+ parents: readonly CommitSha[],123+ at: number124+ ) =>125+ Effect.gen(function* () {126+ const tree = yield* treeOf(source, files);127+128+ const signature = {129+ email: "writer@example.com",130+ name: "Writer",131+ timestamp: 1_790_812_800 + at,132+ timezoneOffset: 0,133+ };134+135+ const oid = yield* Effect.promise(() =>136+ writeCommit({137+ ...source,138+ commit: {139+ author: signature,140+ committer: signature,141+ message: `${message}\n`,142+ parent: [...parents],143+ tree,144+ },145+ })146+ );147+148+ return CommitSha.make(oid);149+ });150+151+ /** An annotated tag object naming `commit`; its id, as a push sends it. */152+ const annotated = (name: string, target: CommitSha) =>153+ Effect.map(154+ Effect.promise(() =>155+ writeTag({156+ ...source,157+ tag: {158+ message: `${name}\n`,159+ object: target,160+ tag: name,161+ tagger: {162+ email: "tagger@example.com",163+ name: "Tagger",164+ timestamp: 1_790_812_800,165+ timezoneOffset: 0,166+ },167+ type: "commit",168+ },169+ })170+ ),171+ // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.172+ (oid) => CommitSha.make(oid)173+ );174+175+ /** `repo` made in the host, holding `refs`, each set to its commit. */176+ const push = (177+ repo: RepoName,178+ refs: readonly (readonly [ref: string, to: CommitSha])[]179+ ) =>180+ Effect.gen(function* () {181+ const host = yield* RepoHost;182+183+ yield* host.create(repo);184+185+ const updates = refs.map(([ref, to]): RefUpdate => ({186+ from: Option.none(),187+ ref: RefName.make(ref),188+ to,189+ }));190+191+ if (Array.isReadonlyArrayNonEmpty(updates)) {192+ yield* host.push(repo, source, updates);193+ }194+ }).pipe(Effect.orDie);195+196+ return { annotated, commit, push };197+});198+199+/** A PNG's signature and the start of its header: a NUL in the first bytes. */200+export const png = Uint8Array.of(201+ 0x89,202+ 0x50,203+ 0x4e,204+ 0x47,205+ 0x0d,206+ 0x0a,207+ 0x1a,208+ 0x0a,209+ 0,210+ 0,211+ 0,212+ 0x0d213+);214+215+/** 1.5 MiB of text: past the 1 MiB a file's text may be. */216+export const big = `${"x".repeat(1023)}\n`.repeat(1536);217+218+export const svg =219+ '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>\n';220+221+export const project = ProjectName.make("datekit");222+223+const repo = RepoName.make(project);224+225+const text = (value: string) => Content.Text({ text: value });226+227+const first: Tree = [228+ ["README.md", text("# datekit\n")],229+ ["big.txt", text(big)],230+ ["feed.xml", text("<feed/>\n")],231+ ["latest", Content.Link({ target: "README.md" })],232+ ["lib/README.txt", text("upper\n")],233+ ["lib/readme.md", text("lower\n")],234+ ["logo.png", Content.Bytes({ bytes: png })],235+ ["logo.svg", text(svg)],236+ ["old.txt", text("old\n")],237+ ["page.html", text("<script>alert(1)</script>\n")],238+ ["src/a.ts", text("export const a = 1;\n")],239+ ["vendor", Content.Gitlink({ commit: "a".repeat(40) })],240+];241+242+const without = (tree: Tree, path: string) =>243+ tree.filter(([at]) => at !== path);244+245+const second: Tree = [246+ ...without(without(first, "src/a.ts"), "old.txt"),247+ ["new.txt", text("new\n")],248+ ["src/a.ts", text("export const a = 2;\n")],249+];250+251+const third: Tree = [252+ ...without(second, "README.md"),253+ ["README.md", text("# datekit, tidied\n")],254+];255+256+const fourth: Tree = [257+ ...without(third, "README.md"),258+ ["README.md", text("# datekit, landed\n")],259+];260+261+/** The claim fork the project's record lists. */262+export const fork: ForkRef = {263+ ask: AskId.make("parse-iso"),264+ handle: Handle.make("bob"),265+ kind: "claim",266+ repo: RepoName.make("datekit--parse-iso--bob"),267+};268+269+/** The project's one landing, on `sha`. */270+const landingOf = (sha: CommitSha, parent: CommitSha): LandingView => ({271+ ask: AskId.make("parse-iso"),272+ assisted: [],273+ author: Handle.make("bob"),274+ credits: [],275+ landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),276+ parent: LandedSha.make(parent),277+ project,278+ sha: LandedSha.make(sha),279+});280+281+/** A project's record, fixed: main at `head`, `landed` its only landing. */282+const recordOf = (283+ name: RepoName,284+ head: CommitSha,285+ landed: readonly LandingView[]286+): CodeProject => ({287+ forks: Effect.succeed([fork]),288+ head: Effect.succeedSome(LandedSha.make(head)),289+ landings: (shas) =>290+ Effect.succeed(landed.filter(({ sha }) => shas.includes(sha))),291+ project: ProjectName.make(name),292+ repo: name,293+});294+295+/**296+ * datekit, four commits on main: the root; one that modifies `src/a.ts`,297+ * deletes `old.txt` and adds `new.txt`; an imported commit whose trailer298+ * forges an ask; and the platform's landing. Beside main: `master` at the299+ * root (an import's stale branch), the landed mirror, a compose ref, the300+ * notes, and three tags (`v1.9.0` light on the root, `v1.10.0` annotated301+ * on the second, `@datekit/core@2.0.0` light on the third).302+ */303+export const datekit = Effect.gen(function* () {304+ const git = yield* writer;305+ const c1 = yield* git.commit("Start", first, [], 1);306+ const c2 = yield* git.commit("Rework a", second, [c1], 2);307+308+ const c3 = yield* git.commit(309+ "Tidy the readme\n\nAsked-by: mallory <mallory@example.com>",310+ third,311+ [c2],312+ 3313+ );314+315+ const c4 = yield* git.commit(316+ "Land parse-iso\n\nAsked-by: bob <bob@example.com>",317+ fourth,318+ [c3],319+ 4320+ );321+322+ const tag = yield* git.annotated("v1.10.0", c2);323+324+ yield* git.push(repo, [325+ ["refs/heads/main", c4],326+ ["refs/heads/master", c1],327+ [`${Brand.refsPrefix}landed`, c4],328+ [`${Brand.refsPrefix}compose/${"b".repeat(40)}`, c3],329+ [`refs/notes/${Brand.slug}`, c2],330+ ["refs/tags/v1.9.0", c1],331+ ["refs/tags/v1.10.0", tag],332+ ["refs/tags/@datekit/core@2.0.0", c3],333+ ]);334+335+ return {336+ c1,337+ c2,338+ c3,339+ c4,340+ code: recordOf(repo, c4, [landingOf(c4, c3)]),341+ };342+});343+344+/**345+ * A history of `count` commits: the first adds `once.txt`, and every one346+ * after changes only `count.txt`.347+ */348+export const longHistory = (count: number) =>349+ Effect.gen(function* () {350+ const git = yield* writer;351+ const name = RepoName.make("longkit");352+ const shas: CommitSha[] = [];353+354+ for (let at = 1; at <= count; at += 1) {355+ const sha = yield* git.commit(356+ `Commit ${at}`,357+ [358+ ["count.txt", text(`${at}\n`)],359+ ["once.txt", text("once\n")],360+ ],361+ shas.slice(-1),362+ at363+ );364+365+ shas.push(sha);366+ }367+368+ const head = shas.at(-1) ?? shas[0];369+370+ if (head === undefined) {371+ return yield* Effect.die("no commits");372+ }373+374+ yield* git.push(name, [["refs/heads/main", head]]);375+376+ return { code: recordOf(name, head, []), shas };377+ });378+379+/** One root commit of `count` files. */380+export const wide = (count: number) =>381+ Effect.gen(function* () {382+ const git = yield* writer;383+ const name = RepoName.make("widekit");384+385+ const sha = yield* git.commit(386+ "Many files",387+ Array.makeBy(count, (at) => [`f${at}.txt`, text(`${at}\n`)] as const),388+ [],389+ 1390+ );391+392+ yield* git.push(name, [["refs/heads/main", sha]]);393+394+ return { code: recordOf(name, sha, []), sha };395+ });added:packages/project/test/code-raw.test.ts+187 added
1+/**2+ * A project's raw bytes as the platform and the dev world serve them: each3+ * file under a sandboxing CSP and `nosniff`, typed by its extension so4+ * that only images render as themselves (an SVG under the sandbox), markup5+ * comes back as plain text, an immutable cache for a commit's id and a6+ * minute for a name that moves, and a 404 with nothing from the repo for7+ * anything else.8+ */9+import { describe, expect, it } from "@effect/vitest";10+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";11+import { RepoPath } from "@repo/protocol/ids";12+import { Effect, Option } from "effect";13+14+import { treeOf } from "../src/code.ts";15+import { rawOf, rawRequestOf, rawRestOf } from "../src/code/raw.ts";16+import { datekit, png, svg } from "./code-fixtures.ts";17+18+const read = (response: Response) =>19+ Effect.map(20+ Effect.promise(() => response.arrayBuffer()),21+ (body) => ({22+ body: new Uint8Array(body),23+ headers: Object.fromEntries(response.headers.entries()),24+ status: response.status,25+ })26+ );27+28+describe("a raw file", () => {29+ it.effect(30+ "at a commit's id is its bytes, sandboxed, unsniffed and cached for good",31+ () =>32+ Effect.gen(function* () {33+ const { c4, code } = yield* datekit;34+ const listing = yield* treeOf(code, Option.none(), Option.none());35+36+ const blob = listing.entries.find(37+ ({ name }) => name === "logo.svg"38+ )?.sha;39+40+ const { body, headers, status } = yield* read(41+ yield* rawOf(code, c4, RepoPath.make("logo.svg"))42+ );43+44+ expect([status, new TextDecoder().decode(body)]).toStrictEqual([45+ 200,46+ svg,47+ ]);48+ expect(headers).toMatchObject({49+ "cache-control": "public, max-age=31536000, immutable",50+ "content-type": "image/svg+xml",51+ etag: `"${blob}"`,52+ "x-content-type-options": "nosniff",53+ });54+ expect(headers["content-security-policy"]).toContain("sandbox");55+ expect(headers["content-security-policy"]).toContain(56+ "default-src 'none'"57+ );58+ }).pipe(Effect.provide(RepoHostMemory))59+ );60+61+ it.effect("at main or a tag is cached for a minute", () =>62+ Effect.gen(function* () {63+ const { code } = yield* datekit;64+65+ const cached = (rev: string) =>66+ Effect.map(rawOf(code, rev, RepoPath.make("README.md")), (response) => [67+ response.status,68+ response.headers.get("cache-control"),69+ ]);70+71+ expect(72+ yield* Effect.all([cached("main"), cached("v1.9.0")])73+ ).toStrictEqual([74+ [200, "public, max-age=60"],75+ [200, "public, max-age=60"],76+ ]);77+ }).pipe(Effect.provide(RepoHostMemory))78+ );79+80+ it.effect(81+ "is typed by its extension: images as themselves, markup and the rest as text, binary as bytes",82+ () =>83+ Effect.gen(function* () {84+ const { code } = yield* datekit;85+86+ const typed = (path: string) =>87+ Effect.map(rawOf(code, "main", RepoPath.make(path)), (response) =>88+ response.headers.get("content-type")89+ );90+91+ expect(92+ yield* Effect.all([93+ typed("logo.png"),94+ typed("page.html"),95+ typed("feed.xml"),96+ typed("README.md"),97+ ])98+ ).toStrictEqual([99+ "image/png",100+ "text/plain; charset=utf-8",101+ "text/plain; charset=utf-8",102+ "text/plain; charset=utf-8",103+ ]);104+105+ const image = yield* read(106+ yield* rawOf(code, "main", RepoPath.make("logo.png"))107+ );108+109+ expect(image.body).toStrictEqual(png);110+ }).pipe(Effect.provide(RepoHostMemory))111+ );112+113+ it.effect(114+ "that is missing, a folder, a submodule or at no revision is a 404 with no body",115+ () =>116+ Effect.gen(function* () {117+ const { code } = yield* datekit;118+119+ const missing = (rev: string, path: string) =>120+ Effect.flatMap(rawOf(code, rev, RepoPath.make(path)), read);121+122+ const answers = yield* Effect.all([123+ missing("main", "nope.txt"),124+ missing("main", "src"),125+ missing("main", "vendor"),126+ missing("v9", "README.md"),127+ missing("main", "src/../README.md"),128+ ]);129+130+ expect(131+ answers.map(({ body, headers, status }) => [132+ status,133+ body.length,134+ headers["x-content-type-options"],135+ headers["content-security-policy"]?.endsWith("; sandbox"),136+ ])137+ ).toStrictEqual(answers.map(() => [404, 0, "nosniff", true]));138+ expect(answers).toHaveLength(5);139+ }).pipe(Effect.provide(RepoHostMemory))140+ );141+});142+143+describe("a raw request's path", () => {144+ it("is a revision, then a file's path, each decoded once", () => {145+ expect(146+ [147+ "main/README.md",148+ "%40datekit%2Fcore%402.0.0/docs/a%20b.md",149+ `${"a".repeat(40)}/src/a.ts`,150+ "main",151+ "main/",152+ "main/src//a.ts",153+ "main/../x",154+ "main/src/%2E%2E/x",155+ "main/..%2Fx",156+ "main/%E0%A4%A",157+ ].map(rawRequestOf)158+ ).toStrictEqual([159+ Option.some({ path: "README.md", rev: "main" }),160+ Option.some({ path: "docs/a b.md", rev: "@datekit/core@2.0.0" }),161+ Option.some({ path: "src/a.ts", rev: "a".repeat(40) }),162+ Option.none(),163+ Option.none(),164+ Option.none(),165+ Option.none(),166+ Option.none(),167+ Option.none(),168+ Option.none(),169+ ]);170+ });171+});172+173+describe("a raw request's URL", () => {174+ it("gives everything after the project's raw/, still encoded", () => {175+ expect(176+ [177+ "https://host.example/datekit/raw/%40datekit%2Fcore%402.0.0/README.md",178+ "/datekit/raw/main/docs/a%20b.md?plain=1#L2",179+ "/datekit/raw/main",180+ ].map(rawRestOf)181+ ).toStrictEqual([182+ "%40datekit%2Fcore%402.0.0/README.md",183+ "main/docs/a%20b.md",184+ "main",185+ ]);186+ });187+});added:packages/project/test/code.test.ts+582 added
1+/**2+ * A project's code as readers browse it, read from its canonical repo over3+ * the memory repo host, with main, the landings and the forks taken from a4+ * fixed project record: refs without the platform's internals, folders and5+ * their READMEs, revisions that resolve only to main, a commit or a tag,6+ * files within their caps, the first-parent log with its landings, a7+ * commit's changes, and reads by object id kept once read.8+ */9+import { describe, expect, it } from "@effect/vitest";10+import { RepoHost } from "@repo/artifacts/repo-host";11+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12+import { Brand } from "@repo/brand";13+import { CommitSha, RepoPath } from "@repo/protocol/ids";14+import {15+ UnknownCommit,16+ UnknownPath,17+ UnknownRevision,18+} from "@repo/protocol/refusal";19+import { DateTime, Effect, Exit, Layer, Option, Ref } from "effect";20+21+import {22+ commitOf,23+ fileOf,24+ logOf,25+ pathsOf,26+ refsOf,27+ treeOf,28+} from "../src/code.ts";29+import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";30+import { filesUnder } from "../src/code/paths.ts";31+import { compareTags } from "../src/code/refs.ts";32+import {33+ big,34+ datekit,35+ fork,36+ longHistory,37+ project,38+ wide,39+} from "./code-fixtures.ts";40+41+const revision = (name: string) => Option.some(name);42+43+const main = Option.none();44+45+const path = (text: string) => Option.some(RepoPath.make(text));46+47+const page = { at: main, from: 0, limit: 30, path: Option.none() };48+49+/**50+ * A history of hundreds of commits, written and pushed in memory: well51+ * under a second alone, many times that beside every other package's tests.52+ */53+const long = { timeout: 30_000 };54+55+describe("a project's refs", () => {56+ it.effect(57+ "are main's landed commit, its tags newest first and its forks, and nothing of the platform's own",58+ () =>59+ Effect.gen(function* () {60+ const { c1, c2, c3, c4, code } = yield* datekit;61+62+ expect(yield* refsOf(code)).toStrictEqual({63+ forks: [fork],64+ landed: c4,65+ project,66+ tags: [67+ { name: "v1.10.0", sha: c2 },68+ { name: "v1.9.0", sha: c1 },69+ { name: "@datekit/core@2.0.0", sha: c3 },70+ ],71+ });72+ }).pipe(Effect.provide(RepoHostMemory))73+ );74+75+ it("sort by version, newest first, each package's together", () => {76+ expect(77+ [78+ "v1.9.0",79+ "v1.10.0",80+ "v1.10.0-beta.1",81+ "v2.0.0",82+ "@changesets/cli@2.27.1",83+ "@changesets/cli@2.3.0",84+ "@changesets/apply@1.0.0",85+ ].toSorted(compareTags)86+ ).toStrictEqual([87+ "v2.0.0",88+ "v1.10.0",89+ "v1.10.0-beta.1",90+ "v1.9.0",91+ "@changesets/cli@2.27.1",92+ "@changesets/cli@2.3.0",93+ "@changesets/apply@1.0.0",94+ ]);95+ });96+});97+98+describe("a folder", () => {99+ it.effect(100+ "lists folders first, then files by name, each by its kind, with its README",101+ () =>102+ Effect.gen(function* () {103+ const { c4, code } = yield* datekit;104+ const listing = yield* treeOf(code, main, Option.none());105+106+ expect(listing.at).toBe(c4);107+ expect(listing.path).toBeUndefined();108+ expect(109+ listing.entries.map(({ name, path: at, type }) => [name, at, type])110+ ).toStrictEqual([111+ ["lib", "lib", "tree"],112+ ["src", "src", "tree"],113+ ["README.md", "README.md", "blob"],114+ ["big.txt", "big.txt", "blob"],115+ ["feed.xml", "feed.xml", "blob"],116+ ["latest", "latest", "symlink"],117+ ["logo.png", "logo.png", "blob"],118+ ["logo.svg", "logo.svg", "blob"],119+ ["new.txt", "new.txt", "blob"],120+ ["page.html", "page.html", "blob"],121+ ["vendor", "vendor", "submodule"],122+ ]);123+ expect({124+ readme: listing.readme,125+ vendor: listing.entries.find(({ name }) => name === "vendor"),126+ }).toMatchObject({127+ readme: {128+ path: "README.md",129+ sha: listing.entries.find(({ name }) => name === "README.md")?.sha,130+ },131+ vendor: { mode: "160000", sha: "a".repeat(40) },132+ });133+ }).pipe(Effect.provide(RepoHostMemory))134+ );135+136+ it.effect("finds a lowercase readme.md before a README.txt", () =>137+ Effect.gen(function* () {138+ const { code } = yield* datekit;139+ const listing = yield* treeOf(code, main, path("lib"));140+141+ expect(listing.path).toBe("lib");142+ expect(listing.entries.map(({ path: at }) => at)).toStrictEqual([143+ "lib/README.txt",144+ "lib/readme.md",145+ ]);146+ expect(listing.readme?.path).toBe("lib/readme.md");147+ }).pipe(Effect.provide(RepoHostMemory))148+ );149+150+ it.effect("is UnknownPath when missing, or a file", () =>151+ Effect.gen(function* () {152+ const { c4, code } = yield* datekit;153+154+ expect(155+ yield* Effect.exit(treeOf(code, main, path("nope")))156+ ).toStrictEqual(157+ Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("nope") }))158+ );159+ expect(160+ yield* Effect.exit(treeOf(code, main, path("src/a.ts/x")))161+ ).toStrictEqual(162+ Exit.fail(163+ new UnknownPath({ commit: c4, path: RepoPath.make("src/a.ts/x") })164+ )165+ );166+ expect(167+ yield* Effect.exit(treeOf(code, main, path("README.md")))168+ ).toStrictEqual(169+ Exit.fail(170+ new UnknownPath({ commit: c4, path: RepoPath.make("README.md") })171+ )172+ );173+ }).pipe(Effect.provide(RepoHostMemory))174+ );175+});176+177+describe("a revision", () => {178+ it.effect(179+ "is main, a commit the repo holds, or a tag by its exact name, peeled",180+ () =>181+ Effect.gen(function* () {182+ const { c1, c2, c3, c4, code } = yield* datekit;183+184+ const resolved = (rev: string) =>185+ Effect.map(186+ treeOf(code, revision(rev), Option.none()),187+ ({ at: sha }) => sha188+ );189+190+ expect(191+ yield* Effect.all([192+ resolved("main"),193+ resolved(c1),194+ resolved("v1.9.0"),195+ resolved("v1.10.0"),196+ resolved("@datekit/core@2.0.0"),197+ ])198+ ).toStrictEqual([c4, c1, c1, c2, c3]);199+ }).pipe(Effect.provide(RepoHostMemory))200+ );201+202+ it.effect(203+ "is UnknownRevision for anything else, a ref path or another branch included",204+ () =>205+ Effect.gen(function* () {206+ const { code } = yield* datekit;207+208+ const refused = [209+ "v9",210+ "master",211+ "../heads/master",212+ "refs/heads/master",213+ "refs/tags/v1.9.0",214+ `${Brand.refsPrefix}landed`,215+ "f".repeat(40),216+ "HEAD",217+ ];218+219+ expect(220+ yield* Effect.forEach(refused, (rev) =>221+ Effect.exit(treeOf(code, revision(rev), Option.none()))222+ )223+ ).toStrictEqual(224+ refused.map((rev) => Exit.fail(new UnknownRevision({ rev })))225+ );226+ }).pipe(Effect.provide(RepoHostMemory))227+ );228+});229+230+describe("a file", () => {231+ it.effect("is its text, with its blob id and size", () =>232+ Effect.gen(function* () {233+ const { c4, code } = yield* datekit;234+ const listing = yield* treeOf(code, main, Option.none());235+236+ expect(237+ yield* fileOf(code, main, RepoPath.make("README.md"))238+ ).toStrictEqual({239+ at: c4,240+ binary: false,241+ path: "README.md",242+ sha: listing.readme?.sha,243+ size: 18,244+ text: "# datekit, landed\n",245+ truncated: false,246+ });247+ }).pipe(Effect.provide(RepoHostMemory))248+ );249+250+ it.effect("past 1 MiB is truncated, with no text", () =>251+ Effect.gen(function* () {252+ const { code } = yield* datekit;253+ const file = yield* fileOf(code, main, RepoPath.make("big.txt"));254+255+ expect(file).toMatchObject({256+ binary: false,257+ size: big.length,258+ truncated: true,259+ });260+ expect(file.text).toBeUndefined();261+ }).pipe(Effect.provide(RepoHostMemory))262+ );263+264+ it.effect("with a NUL among its first bytes is binary, with no text", () =>265+ Effect.gen(function* () {266+ const { code } = yield* datekit;267+ const file = yield* fileOf(code, main, RepoPath.make("logo.png"));268+269+ expect(file).toMatchObject({ binary: true, size: 12, truncated: false });270+ expect(file.text).toBeUndefined();271+ }).pipe(Effect.provide(RepoHostMemory))272+ );273+274+ it.effect("is UnknownPath for a folder or a missing path", () =>275+ Effect.gen(function* () {276+ const { c4, code } = yield* datekit;277+278+ expect(279+ yield* Effect.exit(fileOf(code, main, RepoPath.make("src")))280+ ).toStrictEqual(281+ Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("src") }))282+ );283+ expect(284+ yield* Effect.exit(fileOf(code, main, RepoPath.make("src/b.ts")))285+ ).toStrictEqual(286+ Exit.fail(287+ new UnknownPath({ commit: c4, path: RepoPath.make("src/b.ts") })288+ )289+ );290+ }).pipe(Effect.provide(RepoHostMemory))291+ );292+});293+294+describe("every path", () => {295+ it.effect("lists each file, symlink and submodule at the revision", () =>296+ Effect.gen(function* () {297+ const { c1, code } = yield* datekit;298+299+ expect(yield* pathsOf(code, revision(c1))).toStrictEqual({300+ at: c1,301+ paths: [302+ "README.md",303+ "big.txt",304+ "feed.xml",305+ "latest",306+ "lib/README.txt",307+ "lib/readme.md",308+ "logo.png",309+ "logo.svg",310+ "old.txt",311+ "page.html",312+ "src/a.ts",313+ "vendor",314+ ],315+ truncated: false,316+ });317+ }).pipe(Effect.provide(RepoHostMemory))318+ );319+});320+321+describe("every path past the cap", () => {322+ it.effect(323+ "is the first by path among the folders read before the cap, truncated",324+ () =>325+ Effect.gen(function* () {326+ const { c1, code } = yield* datekit;327+ const host = yield* RepoHost;328+ const commit = yield* host.readCommit(code.repo, c1);329+ const { tree } = Option.getOrThrow(commit);330+ const capped = yield* filesUnder(code.repo, tree, 3);331+332+ // The root alone holds nine files, so no folder below it is read.333+ expect({334+ paths: capped.files.map(({ path: at }) => at),335+ truncated: capped.truncated,336+ }).toStrictEqual({337+ paths: ["README.md", "big.txt", "feed.xml"],338+ truncated: true,339+ });340+ expect((yield* filesUnder(code.repo, tree, 12)).truncated).toBeFalsy();341+ }).pipe(Effect.provide(RepoHostMemory))342+ );343+});344+345+describe("the log", () => {346+ it.effect(347+ "is first parents from the revision, each landing with the platform's record and no other",348+ () =>349+ Effect.gen(function* () {350+ const { c1, c2, c3, c4, code } = yield* datekit;351+ const { commits, next } = yield* logOf(code, page);352+353+ expect(next).toBeUndefined();354+ expect(commits.map(({ sha }) => sha)).toStrictEqual([c4, c3, c2, c1]);355+356+ const [landed, imported] = commits;357+358+ expect(landed?.landing).toMatchObject({ ask: "parse-iso", sha: c4 });359+ expect(imported?.landing).toBeUndefined();360+ expect(361+ Option.map(Option.fromUndefinedOr(imported), (commit) => ({362+ at: DateTime.formatIso(commit.author.at),363+ email: commit.author.email,364+ name: commit.author.name,365+ parents: commit.parents,366+ subject: commit.subject,367+ trailers: commit.trailers,368+ }))369+ ).toStrictEqual(370+ Option.some({371+ at: "2026-10-01T00:00:03.000Z",372+ email: "writer@example.com",373+ name: "Writer",374+ parents: [c2],375+ subject: "Tidy the readme",376+ trailers: [377+ { key: "Asked-by", value: "mallory <mallory@example.com>" },378+ ],379+ })380+ );381+ }).pipe(Effect.provide(RepoHostMemory))382+ );383+384+ it.effect(385+ "pages 30 at a time, naming where the next page starts",386+ () =>387+ Effect.gen(function* () {388+ const { code, shas } = yield* longHistory(250);389+ const first = yield* logOf(code, page);390+391+ expect(first.commits).toHaveLength(30);392+ expect(first.commits[0]?.sha).toBe(shas[249]);393+ expect(first.next).toBe(30);394+395+ const last = yield* logOf(code, { ...page, from: 240 });396+397+ expect(last.commits.map(({ sha }) => sha)).toStrictEqual(398+ shas.slice(0, 10).toReversed()399+ );400+ expect(last.next).toBeUndefined();401+ }).pipe(Effect.provide(RepoHostMemory)),402+ long403+ );404+405+ it.effect(406+ "for a path, keeps only the commits that changed it, scanning at most 200 a call",407+ () =>408+ Effect.gen(function* () {409+ const { code, shas } = yield* longHistory(250);410+ const once = { ...page, path: path("once.txt") };411+ const scanned = yield* logOf(code, once);412+413+ expect(scanned).toStrictEqual({ commits: [], next: 200 });414+415+ const older = yield* logOf(code, { ...once, from: 200 });416+417+ expect(older.commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);418+ expect(older.next).toBeUndefined();419+420+ const counted = yield* logOf(code, {421+ ...page,422+ limit: 3,423+ path: path("count.txt"),424+ });425+426+ expect(counted.commits.map(({ sha }) => sha)).toStrictEqual(427+ shas.slice(247).toReversed()428+ );429+ expect(counted.next).toBe(3);430+ }).pipe(Effect.provide(RepoHostMemory)),431+ long432+ );433+});434+435+describe("a commit", () => {436+ it.effect("at the root adds every file", () =>437+ Effect.gen(function* () {438+ const { c1, code } = yield* datekit;439+ const diff = yield* commitOf(code, c1);440+441+ expect([diff.commit.sha, diff.truncated]).toStrictEqual([c1, false]);442+ expect(443+ diff.files.map(({ path: at, status }) => [at, status])444+ ).toStrictEqual(445+ (yield* pathsOf(code, revision(c1))).paths.map((at) => [at, "added"])446+ );447+ expect(448+ diff.files.find(({ path: at }) => at === "src/a.ts")449+ ).toMatchObject({ binary: false, newText: "export const a = 1;\n" });450+451+ const logo = diff.files.find(({ path: at }) => at === "logo.png");452+453+ expect([logo?.binary, logo?.newText]).toStrictEqual([true, undefined]);454+ }).pipe(Effect.provide(RepoHostMemory))455+ );456+457+ it.effect(458+ "after it shows each change against the first parent, with both blob ids",459+ () =>460+ Effect.gen(function* () {461+ const { c2, code } = yield* datekit;462+ const diff = yield* commitOf(code, c2);463+464+ expect(465+ diff.files.map(({ before, after, path: at, status }) => [466+ at,467+ status,468+ before !== undefined,469+ after !== undefined,470+ ])471+ ).toStrictEqual([472+ ["new.txt", "added", false, true],473+ ["old.txt", "deleted", true, false],474+ ["src/a.ts", "modified", true, true],475+ ]);476+ expect(477+ diff.files.find(({ path: at }) => at === "src/a.ts")478+ ).toMatchObject({479+ newText: "export const a = 2;\n",480+ oldText: "export const a = 1;\n",481+ });482+ expect(diff.commit.landing).toBeUndefined();483+ }).pipe(Effect.provide(RepoHostMemory))484+ );485+486+ it.effect(487+ "past 300 files lists paths only, truncated",488+ () =>489+ Effect.gen(function* () {490+ const { code, sha } = yield* wide(301);491+ const diff = yield* commitOf(code, sha);492+493+ expect([diff.truncated, diff.files.length]).toStrictEqual([true, 301]);494+ expect(495+ diff.files.filter(496+ ({ newText, oldText }) =>497+ newText !== undefined || oldText !== undefined498+ )499+ ).toStrictEqual([]);500+ }).pipe(Effect.provide(RepoHostMemory)),501+ long502+ );503+504+ it.effect("the repo does not hold is UnknownCommit", () =>505+ Effect.gen(function* () {506+ const { code } = yield* datekit;507+ const missing = CommitSha.make("f".repeat(40));508+509+ expect(yield* Effect.exit(commitOf(code, missing))).toStrictEqual(510+ Exit.fail(new UnknownCommit({ sha: missing }))511+ );512+ }).pipe(Effect.provide(RepoHostMemory))513+ );514+});515+516+/** The memory store, with each tree id `readTree` is asked for counted in `reads`. */517+const countedBy = (reads: Ref.Ref<readonly string[]>) =>518+ Layer.effect(519+ RepoHost,520+ Effect.gen(function* () {521+ const host = yield* RepoHost;522+523+ return RepoHost.of({524+ ...host,525+ readTree: (name, tree) =>526+ Ref.update(reads, (all) => [...all, tree]).pipe(527+ Effect.andThen(host.readTree(name, tree))528+ ),529+ });530+ })531+ ).pipe(Layer.provide(RepoHostMemory));532+533+describe("reads by object id", () => {534+ it.effect("are kept once read, while main resolves every time", () =>535+ Effect.gen(function* () {536+ const reads = yield* Ref.make<readonly string[]>([]);537+538+ yield* Effect.gen(function* () {539+ const { code } = yield* datekit;540+ const first = yield* treeOf(code, main, Option.none());541+ const counted = (yield* Ref.get(reads)).length;542+543+ expect(counted).toBeGreaterThan(0);544+545+ const again = yield* treeOf(code, main, Option.none());546+547+ expect(again).toStrictEqual(first);548+ expect(yield* Ref.get(reads)).toHaveLength(counted);549+ }).pipe(550+ Effect.provide(Layer.merge(countedBy(reads), CodeCacheLive(100)))551+ );552+ })553+ );554+555+ it.effect("keep heavy reads apart, so many texts never push out a tree", () =>556+ Effect.gen(function* () {557+ const cache = yield* CodeCache;558+ const reads = yield* Ref.make<readonly string[]>([]);559+560+ const read = (key: string, heavy: boolean) =>561+ cache.through(562+ key,563+ Ref.update(reads, (all) => [...all, key]),564+ { heavy }565+ );566+567+ yield* read("datekit:tree:t", false);568+ yield* read("datekit:text:1", true);569+ yield* read("datekit:text:2", true);570+ yield* read("datekit:tree:t", false);571+ yield* read("datekit:text:2", true);572+ yield* read("datekit:text:1", true);573+574+ expect(yield* Ref.get(reads)).toStrictEqual([575+ "datekit:tree:t",576+ "datekit:text:1",577+ "datekit:text:2",578+ "datekit:text:1",579+ ]);580+ }).pipe(Effect.provide(CodeCacheLive(2, 1)))581+ );582+});