Serve a project's refs, trees, paths, files, log and commits over /rpc, and its raw bytes under a sandbox
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- @repo/project/code: one module per read (refs, tree, paths, file, log, commit, revision, raw, cache); the façade delegates, `whyOf` stays 912's stub. Canonical repo only; no payload names a repo. - Revisions (W9-D3): absent/`main` is the record's head; 40 hex is a commit `readCommit` finds; anything else matches a `RepoHost.tags` name exactly, never joined into a ref path, so `../heads/master` and the landed mirror are UnknownRevision. - listRefs reads only tags (peeled), sorted by digit runs, newest first, a release before its own pre-release; forks from the record. Nothing under the platform's refs, notes or a stale master shows. - readTree: folders first then by name; gitlink -> submodule, 120000 -> symlink; README by GitLab's precedence, any case. listPaths walks 8 trees at a time, caps at 50,000, kept by root tree id. - readFile: blob via the tree walk; binary = NUL in the first 8 KiB; text <= 1 MiB else truncated; Artifacts' MEMORY_LIMIT defect (decoded by its code) reads as truncated. - log: first parents from `at`, limit <= 100, `next` when more; with a path, scans <= 200 commits a call comparing the path's entry (mode + id) with the first parent's, `next` resumes the scan; trailers by parseTrailers, `landing` from one `landings` batch. - showCommit: treeDiff (used as is, its readTree routed through the cache) or every file added for a root; submodule sides get no text; > 300 files or past 2 MiB of text -> paths only, truncated. - CodeCache: CodeCacheLive(capacity) over effect's Cache, keyed <repo>:<kind>:<id>; failures, misses and texts over 256 KiB are never kept (an optional `keep` on `through`); one SAFETY'd value assertion, since one cache holds every kind. Provided once in ports.ts (2,000 entries). - Raw (W9-D6): shared pure module (rawHeaders, rawOf, rawRequestOf, rawFor) behind apps/platform/src/raw.ts and a new GET /:project/raw/* route in the web's dev server. nosniff + sandbox CSP on every answer; images as themselves (SVG too), html/xml/text as text/plain, other binary as octet-stream; immutable + etag for a SHA, max-age=60 otherwise; any `..`, `.` or empty segment (before or after decoding), unknown revision, project or path is a bare 404. - Outside the territory, needed by the check: RefName now allows `@` and `+`, so scoped tags (`@changesets/cli@2.27.1`) no longer throw in the memory/local stores or vanish from smart-HTTP listings; 901's façade and W9 contract tests now expect only `why` unbuilt; CodeProject gains `project`. - Tests: packages/project/test/code.test.ts (20), code-raw.test.ts (5) over code-fixtures.ts (repos written object by object: binary, 1.5 MiB, symlink, submodule, annotated and scoped tags, the platform's refs); apps/platform/test/code-reads.test.ts (anonymous /rpc, an extra `repo` key still reads canonical, no code-read payload field is RepoName or `repo`), raw.test.ts (headers with a stale bearer, climbing paths 404, git paths still git). The 250-commit tests carry a 30 s timeout: well under 1 s alone, ~5 s beside every package's tests. - ASSUMPTION: a MEMORY_LIMIT blob's size is unknown, so readFile reports size 0 there.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+2972 added−103 removed
- tests:+1461 added−53 removed
- other:+1511 added−50 removed
Provenance
- Commit
862c756- Tree
df4e215- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
254268a
21 files changed+2972 added−103 removed
modified:apps/platform/src/ports.ts+12 added-1 removed
26 unmodified lines27282930313233343517 unmodified lines53545556575859606162636465666766 unmodified lines1341351361371301381391401411421431441454 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 (trees, commits, file texts, a commit's changes) an * isolate keeps by object id, the least recently used dropped first. Each * Artifacts read is billed; what an object id names never changes. */const CODE_READS_KEPT = 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) ).pipe( Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)), Layer.provideMerge(WorkerFetch) );4 unmodified linesmodified:apps/platform/src/raw.ts+8 added-7 removed
123454567891011101213141514151617161718/** * 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. `rest` is everything after `raw/`, * undecoded: the revision and the path, each decoded there once. */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): Effect.Effect<Response, never, RepoHost | Projects> => Effect.succeed(new Response("not built: 903", { status: 501 })); project: ProjectName, rest: string): Effect.Effect<Response, never, RepoHost | Projects> => rawFor(project, rest);added: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+167 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 { Projects } from "@repo/project/projects";11+import { RepoName } from "@repo/protocol/ids";12+import { Person } from "@repo/protocol/principal";13+import { advanceTo } from "@repo/testkit/clock";14+import { gitClient } from "@repo/testkit/git-client";15+import { aProject } from "@repo/testkit/scenarios";16+import { Effect, Layer, Option } from "effect";17+18+import { Handlers } from "../src/handlers.ts";19+import { MemorySessions } from "../src/sessions/memory.ts";20+import { worldOf } from "./handlers.fixtures.ts";21+import { origin, served } from "./harness.ts";22+23+const datekit = aProject({ people: [] });24+25+const { project } = datekit;26+27+const readme = "# datekit\n\nDates, parsed.\n";28+29+/**30+ * The platform over a world where datekit was made and its first commit,31+ * a README and a manifest, pushed to main; and that commit's id.32+ */33+const platform = Effect.gen(function* () {34+ yield* advanceTo("2026-10-07T12:00:00Z");35+36+ const world = yield* Layer.build(worldOf([datekit]));37+38+ const first = yield* Effect.gen(function* () {39+ const host = yield* RepoHost;40+ const api = yield* (yield* Projects).create(project);41+ const initializer = Person.make({ handle: datekit.initializer });42+ const client = yield* gitClient(memoryFs());43+44+ yield* api.initProject(initializer, {});45+46+ const sha = yield* client.commit("Start", [47+ ["README.md", readme],48+ ["package.json", '{ "name": "datekit" }\n'],49+ ]);50+51+ yield* host.push(RepoName.make(project), client.source, [52+ { from: Option.none(), ref: RefName.make("refs/heads/main"), to: sha },53+ ]);54+ yield* api.recordFirstPush(initializer, sha);55+56+ return sha;57+ }).pipe(Effect.orDie, Effect.provide(world));58+59+ const ports = Layer.succeedContext(world);60+61+ const { fetch } = yield* served(62+ Layer.mergeAll(63+ Handlers.pipe(Layer.provide(ports)),64+ ports,65+ MemorySessions.layer({})66+ )67+ );68+69+ return { fetch, first };70+});71+72+const get = (73+ fetch: (request: Request) => Effect.Effect<Response>,74+ path: string,75+ headers: Record<string, string> = {}76+) =>77+ Effect.flatMap(78+ fetch(new Request(`${origin}${path}`, { headers })),79+ (response) =>80+ Effect.map(81+ Effect.promise(() => response.text()),82+ (text) => ({ headers: response.headers, status: response.status, text })83+ )84+ );85+86+describe("a project's raw files", () => {87+ it.effect(88+ "answer anyone with the bytes and their headers, a stale bearer or not",89+ () =>90+ Effect.gen(function* () {91+ const { fetch, first } = yield* platform;92+ const path = `/${project}/raw/${first}/README.md`;93+94+ const answers = yield* Effect.forEach(95+ [{}, { authorization: "Bearer not-a-token-the-platform-knows" }],96+ (headers) =>97+ Effect.map(get(fetch, path, headers), (answer) => ({98+ cache: answer.headers.get("cache-control"),99+ etag: /^"[0-9a-f]{40}"$/u.test(answer.headers.get("etag") ?? ""),100+ nosniff: answer.headers.get("x-content-type-options"),101+ sandboxed: (102+ answer.headers.get("content-security-policy") ?? ""103+ ).includes("sandbox"),104+ status: answer.status,105+ text: answer.text,106+ type: answer.headers.get("content-type"),107+ }))108+ );109+110+ expect(answers).toStrictEqual(111+ answers.map(() => ({112+ cache: "public, max-age=31536000, immutable",113+ etag: true,114+ nosniff: "nosniff",115+ sandboxed: true,116+ status: 200,117+ text: readme,118+ type: "text/plain; charset=utf-8",119+ }))120+ );121+ expect(answers).toHaveLength(2);122+123+ const main = yield* get(fetch, `/${project}/raw/main/README.md`);124+125+ expect([main.status, main.headers.get("cache-control")]).toStrictEqual([126+ 200,127+ "public, max-age=60",128+ ]);129+ })130+ );131+132+ it.effect(133+ "is a 404 with no body for a path that climbs out, a missing file or project",134+ () =>135+ Effect.gen(function* () {136+ const { fetch, first } = yield* platform;137+138+ const answers = yield* Effect.forEach(139+ [140+ `/${project}/raw/${first}/../../x`,141+ `/${project}/raw/${first}/..%2F..%2Fx`,142+ `/${project}/raw/${first}/nope.md`,143+ `/${project}/raw/v9/README.md`,144+ `/nobody/raw/main/README.md`,145+ ],146+ (path) =>147+ Effect.map(get(fetch, path), ({ status, text }) => [status, text])148+ );149+150+ expect(answers).toStrictEqual(answers.map(() => [404, ""]));151+ })152+ );153+154+ it.effect("leave git's own paths to git", () =>155+ Effect.gen(function* () {156+ const { fetch } = yield* platform;157+158+ const answer = yield* get(159+ fetch,160+ `/${project}/info/refs?service=git-upload-pack`161+ );162+163+ expect(answer.status).not.toBe(404);164+ expect(answer.headers.get("content-security-policy")).toBeNull();165+ })166+ );167+});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+50 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, 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+44+ return yield* Option.match(decodeProject(params.project), {45+ onNone: () =>46+ Effect.succeed(HttpServerResponse.empty({ status: 404 })),47+ onSome: (project) =>48+ rawFor(project, params["*"] ?? "").pipe(49+ Effect.provide(services),50+ Effect.map(HttpServerResponse.fromWeb)51+ ),52+ });53+ })54+ );55+ })56+);57+58 /**24- * The contracts at `/rpc` over a fresh, seeded world. `toWebHandler` builds59+ * The contracts at `/rpc` and the raw files over a fresh, seeded world. `toWebHandler` builds60 * its layer as soon as it is called, so the world is made and seeded from61 * that moment, and a request that arrives before the seed is done waits for62 * it. `dispose` ends the world.63 */64 export const devServer = () =>65 HttpRouter.toWebHandler(66+ 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- ),67+ RpcServer.layerHttp({68+ group: Contracts,69+ path: "/rpc",70+ protocol: "http",71+ }).pipe(72+ Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson])73+ ),74+ raw75+ ).pipe(Layer.provide(seededWorld)),76 { disableLogger: true }77 );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+114 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 */10-import { Context } from "effect";11-import type { Effect } from "effect";11+import {12+ Cache,13+ Context,14+ Duration,15+ Effect,16+ Equal,17+ Exit,18+ Hash,19+ Layer,20+ Option,21+ Ref,22+} from "effect";23 24 /** The code reads, each kept by its key once read. */25 export interface CodeReads {15- /** `read`, or what it gave before for `key`. */26+ /**27+ * `read`, or what it gave before for `key`. A failure is never kept,28+ * and neither is a value `keep` turns down (a large file's text).29+ */30 readonly through: <A, E, R>(31 key: string,18- read: Effect.Effect<A, E, R>32+ read: Effect.Effect<A, E, R>,33+ keep?: (value: A) => boolean34 ) => Effect.Effect<A, E, R>;35 }36 37 export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {38 defaultValue: () => ({ through: (_key, read) => read }),39 });40+41+/** What one read gave, when it succeeded, and whether it may be kept. */42+interface Entry {43+ readonly value: Option.Option<unknown>;44+ readonly kept: boolean;45+}46+47+/**48+ * One read and the key it is kept by: two are the same entry when their49+ * keys are, whatever their reads (each a closure of its own).50+ */51+class Keyed implements Equal.Equal {52+ readonly key: string;53+ readonly read: Effect.Effect<Entry>;54+55+ constructor(key: string, read: Effect.Effect<Entry>) {56+ this.key = key;57+ this.read = read;58+ }59+60+ [Equal.symbol](that: Equal.Equal): boolean {61+ return that instanceof Keyed && that.key === this.key;62+ }63+64+ [Hash.symbol](): number {65+ return Hash.string(this.key);66+ }67+}68+69+const always = () => true;70+71+/** How long an entry is kept: for good when its read succeeded and may be kept, else not at all. */72+const lifeOf = (exit: Exit.Exit<Entry>) =>73+ Exit.isSuccess(exit) && exit.value.kept ? Duration.infinity : Duration.zero;74+75+/**76+ * A cache of at most `capacity` reads, the least recently used dropped77+ * first. Two calls with one key while the first is under way share its78+ * read; a caller whose own read ran gets its exit as it was, and one that79+ * waited on a read that failed reads for itself.80+ */81+export const CodeCacheLive = (capacity: number) =>82+ Layer.effect(83+ CodeCache,84+ Effect.map(85+ Cache.makeWith((key: Keyed) => key.read, {86+ capacity,87+ timeToLive: lifeOf,88+ }),89+ (cache): CodeReads => ({90+ through: <A, E, R>(91+ key: string,92+ read: Effect.Effect<A, E, R>,93+ keep: (value: A) => boolean = always94+ ) =>95+ Effect.gen(function* () {96+ const context = yield* Effect.context<R>();97+ const own = yield* Ref.make(Option.none<Exit.Exit<A, E>>());98+99+ const entry = yield* Cache.get(100+ cache,101+ new Keyed(102+ key,103+ Effect.exit(Effect.provideContext(read, context)).pipe(104+ Effect.tap((exit) => Ref.set(own, Option.some(exit))),105+ Effect.map((exit): Entry => ({106+ kept: Exit.isSuccess(exit) && keep(exit.value),107+ value: Exit.isSuccess(exit)108+ ? Option.some(exit.value)109+ : Option.none(),110+ }))111+ )112+ )113+ );114+115+ const ran = yield* Ref.get(own);116+117+ if (Option.isSome(ran)) {118+ return yield* ran.value;119+ }120+121+ if (Option.isNone(entry.value)) {122+ return yield* read;123+ }124+125+ // SAFETY: every key names one kind of read (`<repo>:<kind>:<id>`), so the126+ // value kept under it is what a read typed as this one gave.127+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one cache holds every kind of read, so its values are typed `unknown`; see SAFETY.128+ return entry.value.value as A;129+ }),130+ })131+ )132+ );added:packages/project/src/code/commit.ts+231 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+/** A change, and whether each side is a submodule (whose id names no blob here). */36+interface Changed extends Change {37+ readonly links: { readonly before: boolean; readonly after: boolean };38+}39+40+const isLink = (entry: Option.Option<TreeEntry>) =>41+ Option.exists(entry, ({ type }) => type === "commit");42+43+/** Every file under a root commit's tree, each added. */44+const rootChanges = (repo: RepoName, tree: string) =>45+ Effect.map(filesUnder(repo, tree, PATHS_CAP), ({ files }) =>46+ files.map(({ entry, path }): Changed => ({47+ after: BlobSha.make(entry.sha),48+ links: { after: entry.type === "commit", before: false },49+ path,50+ status: "added",51+ }))52+ );53+54+/**55+ * What changed from `base` to `head`, by `treeDiff` over this repo's trees56+ * read through the cache (so the side lookups that follow read none again).57+ */58+const changesBetween = (repo: RepoName, base: string, head: string) =>59+ Effect.gen(function* () {60+ const host = yield* RepoHost;61+62+ const changes = yield* treeDiff(63+ repo,64+ TreeSha.make(base),65+ TreeSha.make(head)66+ ).pipe(67+ Effect.provideService(68+ RepoHost,69+ RepoHost.of({70+ ...host,71+ readTree: (name, id) =>72+ name === repo73+ ? Effect.asSome(74+ Effect.provideService(entriesOf(repo, id), RepoHost, host)75+ )76+ : host.readTree(name, id),77+ })78+ )79+ );80+81+ return yield* Effect.forEach(82+ changes,83+ (change): Effect.Effect<Changed, RepoNotFound, RepoHost> =>84+ Effect.map(85+ Effect.all([86+ entryAt(repo, base, change.path),87+ entryAt(repo, head, change.path),88+ ]),89+ ([before, after]) => ({90+ ...change,91+ links: { after: isLink(after), before: isLink(before) },92+ })93+ ),94+ { concurrency: 8 }95+ );96+ });97+98+const byPath = Order.mapInput(Order.String, (change: Changed) => change.path);99+100+/** A side's contents, unless it is a submodule or absent. */101+const sideOf = (102+ repo: RepoName,103+ blob: BlobSha | undefined,104+ link: boolean105+): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>106+ blob === undefined || link ? Effect.succeedNone : contentsOf(repo, blob);107+108+/** A change as a path, its status and its blob ids, with no text. */109+const pathOnly = ({ after, before, path, status }: Changed): ChangedFile => {110+ const file = { binary: false, path, status };111+112+ if (before !== undefined && after !== undefined) {113+ return { ...file, after, before };114+ }115+116+ if (before !== undefined) {117+ return { ...file, before };118+ }119+120+ return after === undefined ? file : { ...file, after };121+};122+123+/** Each change with its text while the budget lasts, and whether any went without. */124+const withText = (repo: RepoName, changes: readonly Changed[]) =>125+ Effect.gen(function* () {126+ if (changes.length > DIFF_FILES) {127+ return { files: changes.map(pathOnly), truncated: true };128+ }129+130+ const files: ChangedFile[] = [];131+ let budget = DIFF_TEXT;132+ let truncated = false;133+134+ for (const change of changes) {135+ if (truncated) {136+ files.push(pathOnly(change));137+ continue;138+ }139+140+ const before = yield* sideOf(repo, change.before, change.links.before);141+ const after = yield* sideOf(repo, change.after, change.links.after);142+ const oldText = Option.flatMap(before, ({ text }) => text);143+ const newText = Option.flatMap(after, ({ text }) => text);144+145+ const size =146+ Option.getOrElse(147+ Option.map(oldText, (text) => text.length),148+ () => 0149+ ) +150+ Option.getOrElse(151+ Option.map(newText, (text) => text.length),152+ () => 0153+ );154+155+ if (size > budget) {156+ truncated = true;157+ files.push(pathOnly(change));158+ continue;159+ }160+161+ budget -= size;162+163+ files.push({164+ ...pathOnly(change),165+ binary:166+ Option.exists(before, ({ binary }) => binary) ||167+ Option.exists(after, ({ binary }) => binary),168+ ...Option.match(oldText, {169+ onNone: () => ({}),170+ onSome: (text) => ({ oldText: text }),171+ }),172+ ...Option.match(newText, {173+ onNone: () => ({}),174+ onSome: (text) => ({ newText: text }),175+ }),176+ });177+ }178+179+ return { files, truncated };180+ });181+182+/** One commit and the files it changed against its first parent. */183+export const commitDiff = (184+ project: CodeProject,185+ sha: CommitSha186+): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>187+ Effect.gen(function* () {188+ const { repo } = project;189+ const cache = yield* CodeCache;190+191+ const commit = yield* commitAt(repo, sha).pipe(192+ Effect.orDie,193+ Effect.flatMap(194+ Option.match({195+ onNone: () => Effect.fail(new UnknownCommit({ sha })),196+ onSome: Effect.succeed,197+ })198+ )199+ );200+201+ const parent = yield* Option.match(202+ Option.fromUndefinedOr(commit.parents[0]),203+ {204+ onNone: () => Effect.succeedNone,205+ onSome: (first) => commitAt(repo, first),206+ }207+ ).pipe(Effect.orDie);208+209+ const changes = yield* cache210+ .through(211+ `${repo}:changes:${sha}`,212+ Option.match(parent, {213+ onNone: () => rootChanges(repo, commit.tree),214+ onSome: ({ tree }) => changesBetween(repo, tree, commit.tree),215+ })216+ )217+ .pipe(Effect.orDie);218+219+ const { files, truncated } = yield* withText(220+ repo,221+ Array.sort(changes, byPath)222+ ).pipe(Effect.orDie);223+224+ const [view] = yield* commitViews(project, [commit]);225+226+ if (view === undefined) {227+ return yield* Effect.die(`no view of ${sha}`);228+ }229+230+ return { commit: view, files, truncated };231+ });added:packages/project/src/code/file.ts+153 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+ (contents) =>102+ Option.match(contents, {103+ onNone: () => false,104+ onSome: ({ text }) =>105+ Option.match(text, {106+ onNone: () => true,107+ onSome: (read) => read.length <= KEPT_TEXT,108+ }),109+ })110+ );111+ });112+113+/** One file at `at`: its text, or that it is binary or too large. */114+export const fileView = (115+ project: CodeProject,116+ at: Option.Option<Rev>,117+ path: RepoPath118+): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>119+ Effect.gen(function* () {120+ const commit = yield* resolveRev(project, at);121+122+ const { tree } = yield* commitAt(project.repo, commit).pipe(123+ Effect.flatMap(Effect.fromOption),124+ Effect.orDie125+ );126+127+ const entry = yield* entryAt(project.repo, tree, path).pipe(Effect.orDie);128+129+ if (Option.isNone(entry) || entry.value.type !== "blob") {130+ return yield* new UnknownPath({ commit, path });131+ }132+133+ const sha = BlobSha.make(entry.value.sha);134+135+ const contents = yield* contentsOf(project.repo, sha).pipe(136+ Effect.orDie,137+ Effect.flatMap(Effect.fromOption),138+ Effect.orDie139+ );140+141+ return {142+ at: commit,143+ binary: contents.binary,144+ path,145+ sha,146+ size: contents.size,147+ truncated: contents.truncated,148+ ...Option.match(contents.text, {149+ onNone: () => ({}),150+ onSome: (text) => ({ text }),151+ }),152+ };153+ });added:packages/project/src/code/log.ts+211 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+ );107+ });108+109+/** What sits at `path` in `tree`: its id and mode, or nothing. */110+const idAt = (repo: RepoName, tree: string, path: RepoPath) =>111+ Effect.map(112+ entryAt(repo, tree, path),113+ Option.map(({ mode, sha }: TreeEntry) => `${mode} ${sha}`)114+ );115+116+/** A page of the log, and where the next starts when there is more. */117+export interface LogPage {118+ readonly commits: readonly CommitView[];119+ readonly next?: number;120+}121+122+const pageWith = (123+ commits: readonly CommitView[],124+ next: Option.Option<number>125+): LogPage =>126+ Option.match(next, {127+ onNone: () => ({ commits }),128+ onSome: (at) => ({ commits, next: at }),129+ });130+131+/** A page of first-parent commits from `at`, each landing with its record. */132+export const logPage = (133+ project: CodeProject,134+ input: {135+ readonly at: Option.Option<Rev>;136+ readonly path: Option.Option<RepoPath>;137+ readonly from: number;138+ readonly limit: number;139+ }140+): Effect.Effect<LogPage, UnknownRevision, RepoHost> =>141+ Effect.gen(function* () {142+ const sha = yield* resolveRev(project, input.at);143+ const from = Math.max(0, Math.floor(input.from));144+ const limit = Math.min(LOG_LIMIT, Math.max(1, Math.floor(input.limit)));145+ const { repo } = project;146+147+ if (Option.isNone(input.path)) {148+ const read = yield* pageOf(repo, sha, from, limit + 1).pipe(Effect.orDie);149+ const commits = yield* commitViews(project, read.slice(0, limit));150+151+ return pageWith(152+ commits,153+ read.length > limit ? Option.some(from + limit) : Option.none()154+ );155+ }156+157+ const path = input.path.value;158+159+ // One past the scan, so the last scanned commit's parent is at hand160+ // and whether history goes on is known.161+ const scan = yield* pageOf(repo, sha, from, PATH_SCAN + 1).pipe(162+ Effect.orDie163+ );164+165+ const scanned = scan.slice(0, PATH_SCAN);166+ const touched: Commit[] = [];167+168+ for (const [at, commit] of scanned.entries()) {169+ const parent = Option.fromUndefinedOr(commit.parents[0]);170+ const after = Option.fromUndefinedOr(scan[at + 1]);171+172+ // The log is first parents, so the next commit in it is this one's173+ // parent; only past the scan is the parent read on its own.174+ const parentCommit = yield* Option.match(parent, {175+ onNone: () => Effect.succeedNone,176+ onSome: (first) =>177+ Option.exists(after, ({ sha: next }) => next === first)178+ ? Effect.succeed(after)179+ : commitAt(repo, first),180+ }).pipe(Effect.orDie);181+182+ const parentTree = Option.map(parentCommit, ({ tree }) => tree);183+184+ const now = yield* idAt(repo, commit.tree, path).pipe(Effect.orDie);185+186+ const before = yield* Option.match(parentTree, {187+ onNone: () => Effect.succeedNone,188+ onSome: (tree) => idAt(repo, tree, path),189+ }).pipe(Effect.orDie);190+191+ if (!Equal.equals(now, before)) {192+ touched.push(commit);193+ }194+195+ if (touched.length === limit) {196+ const commits = yield* commitViews(project, touched);197+198+ return pageWith(199+ commits,200+ at + 1 < scan.length ? Option.some(from + at + 1) : Option.none()201+ );202+ }203+ }204+205+ const commits = yield* commitViews(project, touched);206+207+ return pageWith(208+ commits,209+ scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()210+ );211+ });added:packages/project/src/code/paths.ts+118 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 and stops descending once5+ * 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, Ref, Semaphore } 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+// Store calls under way at once, however wide or deep the tree.28+const STORE_CALLS = 8;29+30+/** One file under a root tree, with the entry that names it. */31+export interface FileAt {32+ readonly path: RepoPath;33+ readonly entry: TreeEntry;34+}35+36+/**37+ * Every file under the tree `root`, in path order; past `cap`, the walk38+ * stops and says so.39+ */40+export const filesUnder = (41+ repo: RepoName,42+ root: string,43+ cap: number44+): Effect.Effect<45+ { readonly files: readonly FileAt[]; readonly truncated: boolean },46+ RepoNotFound,47+ RepoHost48+> =>49+ Effect.gen(function* () {50+ const calls = yield* Semaphore.make(STORE_CALLS);51+ const seen = yield* Ref.make(0);52+53+ const walk = (54+ prefix: string,55+ tree: string56+ ): Effect.Effect<readonly FileAt[], RepoNotFound, RepoHost> =>57+ Effect.gen(function* () {58+ if ((yield* Ref.get(seen)) > cap) {59+ return [];60+ }61+62+ const entries = yield* Semaphore.withPermit(63+ calls,64+ entriesOf(repo, tree)65+ );66+67+ const files = entries68+ .filter(({ type }) => type !== "tree")69+ .map((entry) => ({70+ entry,71+ path: RepoPath.make(`${prefix}${entry.name}`),72+ }));73+74+ yield* Ref.update(seen, (count) => count + files.length);75+76+ const nested = yield* Effect.forEach(77+ entries.filter(({ type }) => type === "tree"),78+ (entry) => walk(`${prefix}${entry.name}/`, entry.sha),79+ { concurrency: "unbounded" }80+ );81+82+ return [...files, ...nested.flat()];83+ });84+85+ const all = Array.sort(86+ yield* walk("", root),87+ Order.mapInput(Order.String, (file: FileAt) => file.path)88+ );89+90+ return {91+ files: all.slice(0, cap),92+ truncated: all.length > cap || (yield* Ref.get(seen)) > cap,93+ };94+ });95+96+/** Every file path at `at`, up to the cap. */97+export const pathList = (98+ project: CodeProject,99+ at: Option.Option<Rev>100+): Effect.Effect<PathList, UnknownRevision, RepoHost> =>101+ Effect.gen(function* () {102+ const commit = yield* resolveRev(project, at);103+ const cache = yield* CodeCache;104+105+ const { tree } = yield* commitAt(project.repo, commit).pipe(106+ Effect.flatMap(Effect.fromOption),107+ Effect.orDie108+ );109+110+ const { files, truncated } = yield* cache111+ .through(112+ `${project.repo}:paths:${tree}`,113+ filesUnder(project.repo, tree, PATHS_CAP)114+ )115+ .pipe(Effect.orDie);116+117+ return { at: commit, paths: files.map(({ path }) => path), truncated };118+ });added:packages/project/src/code/raw.ts+176 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+/** `path`'s extension, lowercased; none without one. */44+const extensionOf = (path: string) => {45+ const name = path.slice(path.lastIndexOf("/") + 1);46+ const dot = name.lastIndexOf(".");47+48+ return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();49+};50+51+/**52+ * The headers a raw answer for the blob `blob` at `path` carries: its type53+ * by extension (an image as itself, anything else as plain text, or as54+ * bytes when `binary`), `nosniff` and the sandbox, and a cache for good55+ * when `rev` is a commit's id, for a minute when it is a name.56+ */57+export const rawHeaders = (58+ path: RepoPath,59+ rev: "sha" | "ref",60+ blob: BlobSha,61+ binary = false62+): Headers => {63+ const headers = new Headers({64+ "content-security-policy": SANDBOX,65+ "content-type":66+ IMAGES.get(extensionOf(path)) ??67+ (binary ? "application/octet-stream" : TEXT),68+ "x-content-type-options": "nosniff",69+ });70+71+ if (rev === "sha") {72+ headers.set("cache-control", "public, max-age=31536000, immutable");73+ headers.set("etag", `"${blob}"`);74+ } else {75+ headers.set("cache-control", "public, max-age=60");76+ }77+78+ return headers;79+};80+81+/** A 404 that says nothing of the repo. */82+const notFound = () => new Response(null, { status: 404 });83+84+/** The file `path` at `rev` of the project's canonical repo, as raw bytes. */85+export const rawOf = (86+ project: CodeProject,87+ rev: Rev,88+ path: RepoPath89+): Effect.Effect<Response, never, RepoHost> =>90+ Effect.gen(function* () {91+ const commit = yield* resolveRev(project, Option.some(rev));92+93+ const { tree } = yield* commitAt(project.repo, commit).pipe(94+ Effect.flatMap(Effect.fromOption)95+ );96+97+ const entry = yield* entryAt(project.repo, tree, path);98+99+ if (Option.isNone(entry) || entry.value.type !== "blob") {100+ return notFound();101+ }102+103+ const blob = BlobSha.make(entry.value.sha);104+105+ const bytes = yield* RepoHost.use((host) =>106+ host.readBlob(project.repo, ObjectId.make(blob))107+ );108+109+ return Option.match(bytes, {110+ onNone: notFound,111+ onSome: (read) =>112+ new Response(new Uint8Array(read), {113+ headers: rawHeaders(114+ path,115+ isFullSha(rev) ? "sha" : "ref",116+ blob,117+ isBinary(read)118+ ),119+ status: 200,120+ }),121+ });122+ }).pipe(123+ (read) => unlessTooLarge(read, () => new Response(null, { status: 413 })),124+ Effect.catchTags({125+ NoSuchElementError: () => Effect.succeed(notFound()),126+ RepoNotFound: () => Effect.succeed(notFound()),127+ UnknownRevision: () => Effect.succeed(notFound()),128+ })129+ );130+131+const decodeRev = Schema.decodeUnknownOption(Rev);132+133+const decodePath = Schema.decodeUnknownOption(RepoPath);134+135+const decoded = Option.liftThrowable(decodeURIComponent);136+137+/**138+ * A raw request's revision and path from everything after `raw/`, as the139+ * URL carries it: the first segment is the revision (a tag's `/` arrives140+ * as `%2F`), the rest the file's path, each decoded once. A path with an141+ * empty, `.` or `..` segment, before or after decoding, is none.142+ */143+export const rawRequestOf = (144+ rest: string145+): Option.Option<{ readonly rev: Rev; readonly path: RepoPath }> => {146+ const slash = rest.indexOf("/");147+148+ if (slash === -1) {149+ return Option.none();150+ }151+152+ return Option.all({153+ path: decoded(rest.slice(slash + 1)).pipe(154+ Option.filter((path) => Option.isSome(segmentsOf(path))),155+ Option.flatMap(decodePath)156+ ),157+ rev: Option.flatMap(decoded(rest.slice(0, slash)), decodeRev),158+ });159+};160+161+/**162+ * The answer to `GET /<project>/raw/<rest>`: the project found by its163+ * name, then its file. A project never made is a 404 too.164+ */165+export const rawFor = (166+ project: ProjectName,167+ rest: string168+): Effect.Effect<Response, never, RepoHost | Projects> =>169+ Option.match(rawRequestOf(rest), {170+ onNone: () => Effect.succeed(notFound()),171+ onSome: ({ path, rev }) =>172+ Projects.use((projects) => projects.get(project)).pipe(173+ Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),174+ Effect.catchTag("UnknownProject", () => Effect.succeed(notFound()))175+ ),176+ });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+188 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+/** A file a reader may open: a blob or a symlink, never a folder or a submodule. */93+export const isFile = (entry: TreeEntry) => entry.type === "blob";94+95+/** Folders first, then by name. */96+const byKindThenName = Order.combine(97+ Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),98+ Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)99+);100+101+/** GitLab's README precedence, lowercased. */102+const README = [103+ "readme.md",104+ "readme.markdown",105+ "readme.mdown",106+ "readme",107+ "readme.txt",108+ "readme.rst",109+];110+111+const readmeOf = (entries: readonly CodeEntry[]) =>112+ Array.findFirst(README, (name) =>113+ Array.findFirst(114+ entries,115+ (entry) => entry.type === "blob" && entry.name.toLowerCase() === name116+ )117+ ).pipe(Option.map(({ path, sha }) => ({ path, sha: BlobSha.make(sha) })));118+119+/** The tree `path` names at `commit`, or `UnknownPath`. */120+export const folderAt = (121+ repo: RepoName,122+ commit: CommitSha,123+ path: Option.Option<RepoPath>124+): Effect.Effect<string, UnknownPath, RepoHost> =>125+ Effect.gen(function* () {126+ const found = yield* commitAt(repo, commit).pipe(127+ Effect.flatMap(Effect.fromOption)128+ );129+130+ if (Option.isNone(path)) {131+ return found.tree;132+ }133+134+ const entry = yield* entryAt(repo, found.tree, path.value);135+136+ if (Option.isNone(entry) || entry.value.type !== "tree") {137+ return yield* new UnknownPath({ commit, path: path.value });138+ }139+140+ return entry.value.sha;141+ }).pipe(142+ Effect.catchTags({143+ NoSuchElementError: Effect.die,144+ RepoNotFound: Effect.die,145+ })146+ );147+148+/** One folder at `at`, folders first, with its README. */149+export const listing = (150+ project: CodeProject,151+ at: Option.Option<Rev>,152+ path: Option.Option<RepoPath>153+): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>154+ Effect.gen(function* () {155+ const commit = yield* resolveRev(project, at);156+ const tree = yield* folderAt(project.repo, commit, path);157+158+ const prefix = Option.match(path, {159+ onNone: () => "",160+ onSome: (folder) => `${folder}/`,161+ });162+163+ const read = yield* entriesOf(project.repo, tree).pipe(Effect.orDie);164+165+ const entries = Array.sort(166+ read.map((entry): CodeEntry => ({167+ mode: entry.mode,168+ name: entry.name,169+ path: RepoPath.make(`${prefix}${entry.name}`),170+ sha: entry.sha,171+ type: kindOf(entry),172+ })),173+ byKindThenName174+ );175+176+ return {177+ at: commit,178+ entries,179+ ...Option.match(path, {180+ onNone: () => ({}),181+ onSome: (folder) => ({ path: folder }),182+ }),183+ ...Option.match(readmeOf(entries), {184+ onNone: () => ({}),185+ onSome: (readme) => ({ readme }),186+ }),187+ };188+ });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+171 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 } 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, status }) => [status, body.length])132+ ).toStrictEqual([133+ [404, 0],134+ [404, 0],135+ [404, 0],136+ [404, 0],137+ [404, 0],138+ ]);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+});added:packages/project/test/code.test.ts+529 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 { CodeCacheLive } from "../src/code/cache.ts";30+import { compareTags } from "../src/code/refs.ts";31+import {32+ big,33+ datekit,34+ fork,35+ longHistory,36+ project,37+ wide,38+} from "./code-fixtures.ts";39+40+const revision = (name: string) => Option.some(name);41+42+const main = Option.none();43+44+const path = (text: string) => Option.some(RepoPath.make(text));45+46+const page = { at: main, from: 0, limit: 30, path: Option.none() };47+48+/**49+ * A history of hundreds of commits, written and pushed in memory: well50+ * under a second alone, many times that beside every other package's tests.51+ */52+const long = { timeout: 30_000 };53+54+describe("a project's refs", () => {55+ it.effect(56+ "are main's landed commit, its tags newest first and its forks, and nothing of the platform's own",57+ () =>58+ Effect.gen(function* () {59+ const { c1, c2, c3, c4, code } = yield* datekit;60+61+ expect(yield* refsOf(code)).toStrictEqual({62+ forks: [fork],63+ landed: c4,64+ project,65+ tags: [66+ { name: "v1.10.0", sha: c2 },67+ { name: "v1.9.0", sha: c1 },68+ { name: "@datekit/core@2.0.0", sha: c3 },69+ ],70+ });71+ }).pipe(Effect.provide(RepoHostMemory))72+ );73+74+ it("sort by version, newest first, each package's together", () => {75+ expect(76+ [77+ "v1.9.0",78+ "v1.10.0",79+ "v1.10.0-beta.1",80+ "v2.0.0",81+ "@changesets/cli@2.27.1",82+ "@changesets/cli@2.3.0",83+ "@changesets/apply@1.0.0",84+ ].toSorted(compareTags)85+ ).toStrictEqual([86+ "v2.0.0",87+ "v1.10.0",88+ "v1.10.0-beta.1",89+ "v1.9.0",90+ "@changesets/cli@2.27.1",91+ "@changesets/cli@2.3.0",92+ "@changesets/apply@1.0.0",93+ ]);94+ });95+});96+97+describe("a folder", () => {98+ it.effect(99+ "lists folders first, then files by name, each by its kind, with its README",100+ () =>101+ Effect.gen(function* () {102+ const { c4, code } = yield* datekit;103+ const listing = yield* treeOf(code, main, Option.none());104+105+ expect(listing.at).toBe(c4);106+ expect(listing.path).toBeUndefined();107+ expect(108+ listing.entries.map(({ name, path: at, type }) => [name, at, type])109+ ).toStrictEqual([110+ ["lib", "lib", "tree"],111+ ["src", "src", "tree"],112+ ["README.md", "README.md", "blob"],113+ ["big.txt", "big.txt", "blob"],114+ ["feed.xml", "feed.xml", "blob"],115+ ["latest", "latest", "symlink"],116+ ["logo.png", "logo.png", "blob"],117+ ["logo.svg", "logo.svg", "blob"],118+ ["new.txt", "new.txt", "blob"],119+ ["page.html", "page.html", "blob"],120+ ["vendor", "vendor", "submodule"],121+ ]);122+ expect({123+ readme: listing.readme,124+ vendor: listing.entries.find(({ name }) => name === "vendor"),125+ }).toMatchObject({126+ readme: {127+ path: "README.md",128+ sha: listing.entries.find(({ name }) => name === "README.md")?.sha,129+ },130+ vendor: { mode: "160000", sha: "a".repeat(40) },131+ });132+ }).pipe(Effect.provide(RepoHostMemory))133+ );134+135+ it.effect("finds a lowercase readme.md before a README.txt", () =>136+ Effect.gen(function* () {137+ const { code } = yield* datekit;138+ const listing = yield* treeOf(code, main, path("lib"));139+140+ expect(listing.path).toBe("lib");141+ expect(listing.entries.map(({ path: at }) => at)).toStrictEqual([142+ "lib/README.txt",143+ "lib/readme.md",144+ ]);145+ expect(listing.readme?.path).toBe("lib/readme.md");146+ }).pipe(Effect.provide(RepoHostMemory))147+ );148+149+ it.effect("is UnknownPath when missing, or a file", () =>150+ Effect.gen(function* () {151+ const { c4, code } = yield* datekit;152+153+ expect(154+ yield* Effect.exit(treeOf(code, main, path("nope")))155+ ).toStrictEqual(156+ Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("nope") }))157+ );158+ expect(159+ yield* Effect.exit(treeOf(code, main, path("src/a.ts/x")))160+ ).toStrictEqual(161+ Exit.fail(162+ new UnknownPath({ commit: c4, path: RepoPath.make("src/a.ts/x") })163+ )164+ );165+ expect(166+ yield* Effect.exit(treeOf(code, main, path("README.md")))167+ ).toStrictEqual(168+ Exit.fail(169+ new UnknownPath({ commit: c4, path: RepoPath.make("README.md") })170+ )171+ );172+ }).pipe(Effect.provide(RepoHostMemory))173+ );174+});175+176+describe("a revision", () => {177+ it.effect(178+ "is main, a commit the repo holds, or a tag by its exact name, peeled",179+ () =>180+ Effect.gen(function* () {181+ const { c1, c2, c3, c4, code } = yield* datekit;182+183+ const resolved = (rev: string) =>184+ Effect.map(185+ treeOf(code, revision(rev), Option.none()),186+ ({ at: sha }) => sha187+ );188+189+ expect(190+ yield* Effect.all([191+ resolved("main"),192+ resolved(c1),193+ resolved("v1.9.0"),194+ resolved("v1.10.0"),195+ resolved("@datekit/core@2.0.0"),196+ ])197+ ).toStrictEqual([c4, c1, c1, c2, c3]);198+ }).pipe(Effect.provide(RepoHostMemory))199+ );200+201+ it.effect(202+ "is UnknownRevision for anything else, a ref path or another branch included",203+ () =>204+ Effect.gen(function* () {205+ const { code } = yield* datekit;206+207+ const refused = [208+ "v9",209+ "master",210+ "../heads/master",211+ "refs/heads/master",212+ "refs/tags/v1.9.0",213+ `${Brand.refsPrefix}landed`,214+ "f".repeat(40),215+ "HEAD",216+ ];217+218+ expect(219+ yield* Effect.forEach(refused, (rev) =>220+ Effect.exit(treeOf(code, revision(rev), Option.none()))221+ )222+ ).toStrictEqual(223+ refused.map((rev) => Exit.fail(new UnknownRevision({ rev })))224+ );225+ }).pipe(Effect.provide(RepoHostMemory))226+ );227+});228+229+describe("a file", () => {230+ it.effect("is its text, with its blob id and size", () =>231+ Effect.gen(function* () {232+ const { c4, code } = yield* datekit;233+ const listing = yield* treeOf(code, main, Option.none());234+235+ expect(236+ yield* fileOf(code, main, RepoPath.make("README.md"))237+ ).toStrictEqual({238+ at: c4,239+ binary: false,240+ path: "README.md",241+ sha: listing.readme?.sha,242+ size: 18,243+ text: "# datekit, landed\n",244+ truncated: false,245+ });246+ }).pipe(Effect.provide(RepoHostMemory))247+ );248+249+ it.effect("past 1 MiB is truncated, with no text", () =>250+ Effect.gen(function* () {251+ const { code } = yield* datekit;252+ const file = yield* fileOf(code, main, RepoPath.make("big.txt"));253+254+ expect(file).toMatchObject({255+ binary: false,256+ size: big.length,257+ truncated: true,258+ });259+ expect(file.text).toBeUndefined();260+ }).pipe(Effect.provide(RepoHostMemory))261+ );262+263+ it.effect("with a NUL among its first bytes is binary, with no text", () =>264+ Effect.gen(function* () {265+ const { code } = yield* datekit;266+ const file = yield* fileOf(code, main, RepoPath.make("logo.png"));267+268+ expect(file).toMatchObject({ binary: true, size: 12, truncated: false });269+ expect(file.text).toBeUndefined();270+ }).pipe(Effect.provide(RepoHostMemory))271+ );272+273+ it.effect("is UnknownPath for a folder or a missing path", () =>274+ Effect.gen(function* () {275+ const { c4, code } = yield* datekit;276+277+ expect(278+ yield* Effect.exit(fileOf(code, main, RepoPath.make("src")))279+ ).toStrictEqual(280+ Exit.fail(new UnknownPath({ commit: c4, path: RepoPath.make("src") }))281+ );282+ expect(283+ yield* Effect.exit(fileOf(code, main, RepoPath.make("src/b.ts")))284+ ).toStrictEqual(285+ Exit.fail(286+ new UnknownPath({ commit: c4, path: RepoPath.make("src/b.ts") })287+ )288+ );289+ }).pipe(Effect.provide(RepoHostMemory))290+ );291+});292+293+describe("every path", () => {294+ it.effect("lists each file, symlink and submodule at the revision", () =>295+ Effect.gen(function* () {296+ const { c1, code } = yield* datekit;297+298+ expect(yield* pathsOf(code, revision(c1))).toStrictEqual({299+ at: c1,300+ paths: [301+ "README.md",302+ "big.txt",303+ "feed.xml",304+ "latest",305+ "lib/README.txt",306+ "lib/readme.md",307+ "logo.png",308+ "logo.svg",309+ "old.txt",310+ "page.html",311+ "src/a.ts",312+ "vendor",313+ ],314+ truncated: false,315+ });316+ }).pipe(Effect.provide(RepoHostMemory))317+ );318+});319+320+describe("the log", () => {321+ it.effect(322+ "is first parents from the revision, each landing with the platform's record and no other",323+ () =>324+ Effect.gen(function* () {325+ const { c1, c2, c3, c4, code } = yield* datekit;326+ const { commits, next } = yield* logOf(code, page);327+328+ expect(next).toBeUndefined();329+ expect(commits.map(({ sha }) => sha)).toStrictEqual([c4, c3, c2, c1]);330+331+ const [landed, imported] = commits;332+333+ expect(landed?.landing).toMatchObject({ ask: "parse-iso", sha: c4 });334+ expect(imported?.landing).toBeUndefined();335+ expect(336+ Option.map(Option.fromUndefinedOr(imported), (commit) => ({337+ at: DateTime.formatIso(commit.author.at),338+ email: commit.author.email,339+ name: commit.author.name,340+ parents: commit.parents,341+ subject: commit.subject,342+ trailers: commit.trailers,343+ }))344+ ).toStrictEqual(345+ Option.some({346+ at: "2026-10-01T00:00:03.000Z",347+ email: "writer@example.com",348+ name: "Writer",349+ parents: [c2],350+ subject: "Tidy the readme",351+ trailers: [352+ { key: "Asked-by", value: "mallory <mallory@example.com>" },353+ ],354+ })355+ );356+ }).pipe(Effect.provide(RepoHostMemory))357+ );358+359+ it.effect(360+ "pages 30 at a time, naming where the next page starts",361+ () =>362+ Effect.gen(function* () {363+ const { code, shas } = yield* longHistory(250);364+ const first = yield* logOf(code, page);365+366+ expect(first.commits).toHaveLength(30);367+ expect(first.commits[0]?.sha).toBe(shas[249]);368+ expect(first.next).toBe(30);369+370+ const last = yield* logOf(code, { ...page, from: 240 });371+372+ expect(last.commits.map(({ sha }) => sha)).toStrictEqual(373+ shas.slice(0, 10).toReversed()374+ );375+ expect(last.next).toBeUndefined();376+ }).pipe(Effect.provide(RepoHostMemory)),377+ long378+ );379+380+ it.effect(381+ "for a path, keeps only the commits that changed it, scanning at most 200 a call",382+ () =>383+ Effect.gen(function* () {384+ const { code, shas } = yield* longHistory(250);385+ const once = { ...page, path: path("once.txt") };386+ const scanned = yield* logOf(code, once);387+388+ expect(scanned).toStrictEqual({ commits: [], next: 200 });389+390+ const older = yield* logOf(code, { ...once, from: 200 });391+392+ expect(older.commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);393+ expect(older.next).toBeUndefined();394+395+ const counted = yield* logOf(code, {396+ ...page,397+ limit: 3,398+ path: path("count.txt"),399+ });400+401+ expect(counted.commits.map(({ sha }) => sha)).toStrictEqual(402+ shas.slice(247).toReversed()403+ );404+ expect(counted.next).toBe(3);405+ }).pipe(Effect.provide(RepoHostMemory)),406+ long407+ );408+});409+410+describe("a commit", () => {411+ it.effect("at the root adds every file", () =>412+ Effect.gen(function* () {413+ const { c1, code } = yield* datekit;414+ const diff = yield* commitOf(code, c1);415+416+ expect([diff.commit.sha, diff.truncated]).toStrictEqual([c1, false]);417+ expect(418+ diff.files.map(({ path: at, status }) => [at, status])419+ ).toStrictEqual(420+ (yield* pathsOf(code, revision(c1))).paths.map((at) => [at, "added"])421+ );422+ expect(423+ diff.files.find(({ path: at }) => at === "src/a.ts")424+ ).toMatchObject({ binary: false, newText: "export const a = 1;\n" });425+426+ const logo = diff.files.find(({ path: at }) => at === "logo.png");427+428+ expect([logo?.binary, logo?.newText]).toStrictEqual([true, undefined]);429+ }).pipe(Effect.provide(RepoHostMemory))430+ );431+432+ it.effect(433+ "after it shows each change against the first parent, with both blob ids",434+ () =>435+ Effect.gen(function* () {436+ const { c2, code } = yield* datekit;437+ const diff = yield* commitOf(code, c2);438+439+ expect(440+ diff.files.map(({ before, after, path: at, status }) => [441+ at,442+ status,443+ before !== undefined,444+ after !== undefined,445+ ])446+ ).toStrictEqual([447+ ["new.txt", "added", false, true],448+ ["old.txt", "deleted", true, false],449+ ["src/a.ts", "modified", true, true],450+ ]);451+ expect(452+ diff.files.find(({ path: at }) => at === "src/a.ts")453+ ).toMatchObject({454+ newText: "export const a = 2;\n",455+ oldText: "export const a = 1;\n",456+ });457+ expect(diff.commit.landing).toBeUndefined();458+ }).pipe(Effect.provide(RepoHostMemory))459+ );460+461+ it.effect(462+ "past 300 files lists paths only, truncated",463+ () =>464+ Effect.gen(function* () {465+ const { code, sha } = yield* wide(301);466+ const diff = yield* commitOf(code, sha);467+468+ expect([diff.truncated, diff.files.length]).toStrictEqual([true, 301]);469+ expect(470+ diff.files.filter(471+ ({ newText, oldText }) =>472+ newText !== undefined || oldText !== undefined473+ )474+ ).toStrictEqual([]);475+ }).pipe(Effect.provide(RepoHostMemory)),476+ long477+ );478+479+ it.effect("the repo does not hold is UnknownCommit", () =>480+ Effect.gen(function* () {481+ const { code } = yield* datekit;482+ const missing = CommitSha.make("f".repeat(40));483+484+ expect(yield* Effect.exit(commitOf(code, missing))).toStrictEqual(485+ Exit.fail(new UnknownCommit({ sha: missing }))486+ );487+ }).pipe(Effect.provide(RepoHostMemory))488+ );489+});490+491+/** The memory store, with each tree id `readTree` is asked for counted in `reads`. */492+const countedBy = (reads: Ref.Ref<readonly string[]>) =>493+ Layer.effect(494+ RepoHost,495+ Effect.gen(function* () {496+ const host = yield* RepoHost;497+498+ return RepoHost.of({499+ ...host,500+ readTree: (name, tree) =>501+ Ref.update(reads, (all) => [...all, tree]).pipe(502+ Effect.andThen(host.readTree(name, tree))503+ ),504+ });505+ })506+ ).pipe(Layer.provide(RepoHostMemory));507+508+describe("reads by object id", () => {509+ it.effect("are kept once read, while main resolves every time", () =>510+ Effect.gen(function* () {511+ const reads = yield* Ref.make<readonly string[]>([]);512+513+ yield* Effect.gen(function* () {514+ const { code } = yield* datekit;515+ const first = yield* treeOf(code, main, Option.none());516+ const counted = (yield* Ref.get(reads)).length;517+518+ expect(counted).toBeGreaterThan(0);519+520+ const again = yield* treeOf(code, main, Option.none());521+522+ expect(again).toStrictEqual(first);523+ expect(yield* Ref.get(reads)).toHaveLength(counted);524+ }).pipe(525+ Effect.provide(Layer.merge(countedBy(reads), CodeCacheLive(100)))526+ );527+ })528+ );529+});