llms.test.ts
This file
Path
apps/web/test/llms.test.ts
589 lines · 18.8 KiB · TypeScript
Last changed by
Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import type { CommandDoc } from "@repo/agent-kit/command-doc";3import { fullLlms } from "@repo/agent-kit/full-llms";4import { Brand } from "@repo/brand";5import { claimForkName, workingForkName } from "@repo/project/repo-names";6import { Contracts } from "@repo/protocol/contracts";7import type { AskListing } from "@repo/protocol/domain/ask";8import type { ProjectListing } from "@repo/protocol/domain/front-page";9import {10 addressOfRepo,11 AskId,12 Handle,13 KindName,14 ProjectName,15} from "@repo/protocol/ids";16import type { RepoName } from "@repo/protocol/ids";17import { Effect, Option } from "effect";1819import { commands as catalog } from "../src/features/agents/catalog.ts";20import {21 frontLlms,22 indexBanner,23 mcpCard,24 missingProjectLlms,25 projectLlms,26} from "../src/features/agents/llms.ts";27import {28 projectPageHead,29 projectPageHeaders,30} from "../src/routes/$owner/$project/index.tsx";31import { frontPageHead, frontPageHeaders } from "../src/routes/asks.tsx";32import { landingHead, landingHeaders } from "../src/routes/index.tsx";33import { llmsFullHandler } from "../src/routes/llms-full[.]txt.ts";34import { frontPageHandler, landingHandler } from "../src/server/front-page.ts";35import { projectPageHandler } from "../src/server/project-page.ts";36import { platformWith, unreachablePlatform } from "./platform.ts";3738const platformUrl = "https://platform-test.example.workers.dev";3940const webUrl = "https://web-test.example.workers.dev";4142const datekit = ProjectName.make("oscabriel/datekit");4344const burrow = ProjectName.make("oscabriel/burrow");4546const row = (47 path: readonly [string, ...string[]],48 summary: string,49 more: Partial<CommandDoc> = {}50): CommandDoc => ({51 flags: ["--json"],52 needsApproval: false,53 path,54 positional: [],55 readOnly: true,56 source: "contract",57 summary,58 ...more,59});6061const commands: readonly CommandDoc[] = [62 row(63 ["ask"],64 "Show one ask in full, with its brief in Markdown for an answerer to read first.",65 { flags: ["--project", "--json"], positional: ["ask"] }66 ),67 row(["asks"], "List a project's open asks.", {68 flags: ["--project", "--json"],69 }),70 row(["check"], "Run the gate's checks on your answer locally.", {71 flags: ["--ask", "--project", "--json"],72 source: "local",73 }),74 row(["claim"], "Claim an ask: an exclusive, expiring right to answer it.", {75 flags: ["--project", "--json", "--dry-run"],76 positional: ["ask"],77 readOnly: false,78 }),79 row(["env", "set"], "Set a sensitive env item's value from stdin.", {80 flags: ["--project", "--yes"],81 needsApproval: true,82 positional: ["key"],83 readOnly: false,84 source: "local",85 }),86 row(["front"], "List the open asks across every project."),87 row(["login"], "Sign in to a platform.", {88 flags: ["--url", "--json"],89 readOnly: false,90 source: "local",91 }),92 row(["mcp"], "Serve the platform's tools over MCP on stdio.", {93 flags: [],94 source: "local",95 }),96 row(["verdict"], "Show the verdict on an answer to an ask.", {97 flags: ["--ask", "--head", "--project", "--json"],98 }),99];100101const projects: readonly ProjectListing[] = [102 { openAsks: 3, posture: "open", project: datekit },103 { openAsks: 1, posture: "openWithSealedEvidence", project: burrow },104];105106const ask = (107 id: string,108 want: string,109 more: Partial<AskListing> = {}110): AskListing => ({111 ask: AskId.make(id),112 blockedBy: [],113 claimed: false,114 kind: KindName.make("fix"),115 territory: "src/parse.ts",116 want,117 ...more,118});119120const asks: readonly AskListing[] = [121 ask("parse-iso", "parse reads the year of an ISO date"),122 ask("parse-month", "parse reads the month of an ISO date", {123 claimed: true,124 }),125 ask("drop-legacy", "the legacy parser is gone", {126 blockedBy: [AskId.make("parse-iso"), AskId.make("parse-month")],127 reserve: "newcomers",128 }),129];130131const linesOf = (text: string) => text.split("\n");132133const { cli } = Brand;134135describe(frontLlms, () => {136 const text = frontLlms({ commands, platformUrl, projects, webUrl });137 const lines = linesOf(text);138139 it("opens with the platform's name and a one-line summary", () => {140 expect(lines[0]).toBe(`# ${Brand.name}`);141 expect(lines[1]).toBe("");142 expect(lines[2]).toMatch(143 new RegExp(`^> ${Brand.name} is a Git platform`, "u")144 );145 expect(text.endsWith("\n")).toBeTruthy();146 });147148 it("installs the CLI from the web host, then signs in to the platform", () => {149 expect(lines).toContain(`curl -fsSL ${webUrl}/install.sh | sh`);150 expect(lines).toContain(`${cli} login --url ${platformUrl}`);151 });152153 it("says where MCP is served, how it is signed in to, and where the skills are", () => {154 expect(lines).toContain(155 `- Endpoint: ${platformUrl}/mcp (streamable HTTP, MCP 2026-07-28), described at ${webUrl}/.well-known/mcp.json.`156 );157 expect(lines).toContain(158 `- Auth: a bearer token from the platform's own OAuth server, which an MCP client finds at ${platformUrl}/.well-known/oauth-protected-resource; you sign in with your account on ${Brand.name}.`159 );160 expect(lines).toContain(161 `- Without a client that signs in: \`${cli} mcp\` serves the same tools over stdio, with the token \`${cli} login\` stored.`162 );163 expect(lines).toContain(164 `- Skills: ${webUrl}/.well-known/agent-skills/index.json lists each project's contribute skill, with its digest.`165 );166 });167168 it("finds and takes an ask with the commands the catalog has", () => {169 expect(lines).toContain(170 `1. Find one: \`${cli} front\` lists the open asks across projects; \`${cli} asks --project <owner>/<name>\` lists one project's.`171 );172 expect(lines).toContain(173 `2. Read it: \`${cli} ask <ask> --project <owner>/<name>\`.`174 );175 expect(lines).toContain(176 `3. Claim it: \`${cli} claim <ask> --project <owner>/<name>\`. The claim prints your fork's remote; add it with \`git remote add ${Brand.slug} <remote>\`.`177 );178 expect(lines).toContain(179 `4. Change only the ask's territory, then run \`${cli} check\` and fix everything it reports.`180 );181 expect(lines).toContain(182 `5. Push to your fork with \`git push ${Brand.slug} HEAD:main\`, then read the verdict: \`${cli} verdict --ask <ask> --project <owner>/<name>\`. A refusal names the command to run next.`183 );184 });185186 it("lists every command on one line, with what it does", () => {187 expect(188 lines.filter((line) => line.startsWith(`- \`${cli} `))189 ).toStrictEqual([190 `- \`${cli} ask <ask>\`: Show one ask in full, with its brief in Markdown for an answerer to read first. Only reads.`,191 `- \`${cli} asks\`: List a project's open asks. Only reads.`,192 `- \`${cli} check\`: Run the gate's checks on your answer locally. Only reads.`,193 `- \`${cli} claim <ask>\`: Claim an ask: an exclusive, expiring right to answer it.`,194 `- \`${cli} env set <key>\`: Set a sensitive env item's value from stdin. Runs only with \`--yes\`.`,195 `- \`${cli} front\`: List the open asks across every project. Only reads.`,196 `- \`${cli} login\`: Sign in to a platform.`,197 `- \`${cli} mcp\`: Serve the platform's tools over MCP on stdio. Only reads.`,198 `- \`${cli} verdict\`: Show the verdict on an answer to an ask. Only reads.`,199 ]);200 });201202 it("lists each project on one line, with its posture and its open asks", () => {203 expect(lines).toContain(204 `- [oscabriel/datekit](${webUrl}/oscabriel/datekit/llms.txt): Open, 3 open asks.`205 );206 expect(lines).toContain(207 `- [oscabriel/burrow](${webUrl}/oscabriel/burrow/llms.txt): Open with sealed evidence, 1 open ask.`208 );209 });210211 it("says so when no project exists yet", () => {212 expect(213 linesOf(frontLlms({ commands, platformUrl, projects: [], webUrl }))214 ).toContain("No project is on the platform yet.");215 });216217 it("leaves out a step whose command the catalog lacks", () => {218 const withoutVerdict = frontLlms({219 commands: commands.filter(({ path }) => path.join(" ") !== "verdict"),220 platformUrl,221 projects,222 webUrl,223 });224225 expect(withoutVerdict).not.toContain(`${cli} verdict`);226 expect(linesOf(withoutVerdict)).toContain(227 `5. Push to your fork with \`git push ${Brand.slug} HEAD:main\`. A refusal names the command to run next.`228 );229 });230});231232describe(projectLlms, () => {233 const text = projectLlms({234 asks,235 commands,236 listing: {237 openAsks: 3,238 posture: "openWithSealedEvidence",239 project: datekit,240 },241 platformUrl,242 webUrl,243 });244245 const lines = linesOf(text);246247 it("opens with the project, its posture and how many asks are open, then the banner", () => {248 expect(lines.slice(0, 5)).toStrictEqual([249 "# oscabriel/datekit",250 "",251 `> A project on ${Brand.name}. Posture: Open with sealed evidence. 3 open asks.`,252 "",253 indexBanner({ project: datekit, webUrl }),254 ]);255 });256257 it("gives its page, its clone URL and the platform's llms.txt", () => {258 expect(lines).toContain(`- Page: ${webUrl}/oscabriel/datekit`);259 expect(lines).toContain(260 `- Clone: \`git clone ${platformUrl}/oscabriel/datekit.git\``261 );262 expect(lines).toContain(263 `- Everything else, and every command: ${webUrl}/llms.txt`264 );265 });266267 it("lists each open ask on one line, linking its Markdown", () => {268 expect(lines.filter((line) => line.startsWith("- ["))).toStrictEqual([269 `- [parse-iso](${webUrl}/oscabriel/datekit/asks/parse-iso.md): parse reads the year of an ISO date. Kind \`fix\`, territory \`src/parse.ts\`.`,270 `- [parse-month](${webUrl}/oscabriel/datekit/asks/parse-month.md): parse reads the month of an ISO date. Kind \`fix\`, territory \`src/parse.ts\`. Claimed.`,271 `- [drop-legacy](${webUrl}/oscabriel/datekit/asks/drop-legacy.md): the legacy parser is gone. Kind \`fix\`, territory \`src/parse.ts\`. Held for newcomers. Waits for \`parse-iso\`, \`parse-month\`.`,272 ]);273 });274275 it("names the project in the commands that take an ask", () => {276 expect(lines).toContain(277 `2. Read it: \`${cli} ask <ask> --project oscabriel/datekit\`.`278 );279 expect(lines).toContain(280 `3. Claim it: \`${cli} claim <ask> --project oscabriel/datekit\`. The claim prints your fork's remote; add it with \`git remote add ${Brand.slug} <remote>\`.`281 );282 });283284 it("says so when no ask is open", () => {285 expect(286 linesOf(287 projectLlms({288 asks: [],289 commands,290 listing: { openAsks: 0, posture: "open", project: datekit },291 platformUrl,292 webUrl,293 })294 )295 ).toContain("No ask is open.");296 });297});298299describe(missingProjectLlms, () => {300 it("names the project it did not find and where every project is", () => {301 expect(302 missingProjectLlms({303 project: Option.some(ProjectName.make("oscabriel/nowhere")),304 webUrl,305 })306 ).toBe(307 `# Not found\n\nNo project named \`oscabriel/nowhere\` is on ${Brand.name}. Every project is listed at ${webUrl}/llms.txt.\n`308 );309 });310311 it("repeats no name that could not be a project's", () => {312 expect(missingProjectLlms({ project: Option.none(), webUrl })).toBe(313 `# Not found\n\nNo such project is on ${Brand.name}. Every project is listed at ${webUrl}/llms.txt.\n`314 );315 });316});317318describe("the command catalog", () => {319 it("is every command the CLI has, and every row reaches llms.txt", () => {320 const text = frontLlms({321 commands: catalog,322 platformUrl,323 projects,324 webUrl,325 });326327 const words = catalog.map(({ path }) => path.join(" "));328329 expect(catalog.length).toBeGreaterThan(20);330 expect(words).toContain("asks");331 expect(words).toContain("env set");332 expect(words).toContain("login");333 expect(334 catalog.filter(335 ({ path }) => !text.includes(`- \`${cli} ${path.join(" ")}`)336 )337 ).toStrictEqual([]);338 });339});340341const listing = (listed: readonly ProjectListing[]) => () =>342 platformWith(343 Contracts.toLayerHandler("listProjects", () =>344 Effect.succeed({ projects: listed })345 )346 );347348const unreachable = () => unreachablePlatform;349350const getFull = () => new Request(`${webUrl}/llms-full.txt`);351352const addressed = (repo: RepoName) =>353 Option.getOrElse(addressOfRepo(repo), () => repo);354355const read = (response: Response) =>356 Effect.map(357 Effect.promise(() => response.text()),358 (body) => ({359 body,360 contentType: response.headers.get("content-type"),361 status: response.status,362 })363 );364365describe("/llms-full.txt", () => {366 it.effect("is fullLlms over the projects the platform lists", () =>367 Effect.gen(function* () {368 const response = yield* Effect.promise(() =>369 llmsFullHandler(listing(projects), platformUrl)({ request: getFull() })370 );371372 expect(yield* read(response)).toStrictEqual({373 body: fullLlms({ commands: catalog, platformUrl, projects, webUrl }),374 contentType: "text/markdown; charset=utf-8",375 status: 200,376 });377 })378 );379380 it.effect("is unavailable when the platform does not answer", () =>381 Effect.gen(function* () {382 const response = yield* Effect.promise(() =>383 llmsFullHandler(unreachable, platformUrl)({ request: getFull() })384 );385386 const seen = yield* read(response);387388 expect(seen.status).toBe(503);389 expect(seen.body).toContain("# Unavailable");390 })391 );392393 describe("its fork names", () => {394 const text = fullLlms({ commands: catalog, platformUrl, projects, webUrl });395 const parseIso = AskId.make("parse-iso");396 const ada = Handle.make("Ada");397398 const filled = (pattern: string) =>399 pattern400 .replaceAll("<owner>/<name>", datekit)401 .replaceAll("<ask>", parseIso)402 .replaceAll("<handle>", ada.toLowerCase());403404 const patterns = [405 ...text.matchAll(/`(?<name><owner>\/<name>--[^`]+)`/gu),406 ].map((match) => match.groups?.name ?? "");407408 it("spell a claim's fork as the gateway addresses it", () => {409 expect(patterns.map(filled)).toContain(410 addressed(claimForkName(datekit, parseIso, ada))411 );412 });413414 it("spell a working fork as the gateway addresses it", () => {415 expect(patterns.map(filled)).toContain(416 addressed(workingForkName(datekit, ada))417 );418 });419 });420});421422describe(mcpCard, () => {423 it("describes the platform's MCP endpoint and where its auth is found", () => {424 expect(mcpCard({ platformUrl })).toStrictEqual({425 authentication: {426 required: true,427 resource_metadata: `${platformUrl}/.well-known/oauth-protected-resource`,428 schemes: ["bearer"],429 },430 capabilities: { prompts: {}, resources: {}, tools: {} },431 description: `The contracts of ${Brand.name} as MCP tools, each ask's brief as a resource, and the contribute skill as a prompt.`,432 name: Brand.name,433 protocolVersion: "2026-07-28",434 transport: { endpoint: `${platformUrl}/mcp`, type: "streamable-http" },435 });436 });437});438439const listingWithAsks =440 (listed: readonly ProjectListing[], listedAsks: readonly AskListing[]) =>441 () =>442 platformWith(443 Contracts.toLayerHandler("listProjects", () =>444 Effect.succeed({ projects: listed })445 ),446 Contracts.toLayerHandler("listAsks", () =>447 Effect.succeed({ asks: listedAsks })448 )449 );450451const getAt = (path: string, accept: string) =>452 new Request(`${webUrl}${path}`, { headers: { accept } });453454const BROWSER =455 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";456457const answered = (result: Promise<Response> | "the page") =>458 result === "the page"459 ? Effect.void460 : Effect.flatMap(461 Effect.promise(() => result),462 (response) =>463 Effect.map(read(response), (seen) => ({464 ...seen,465 vary: response.headers.get("vary"),466 }))467 );468469const alternate = (href: string) => ({470 href,471 rel: "alternate",472 type: "text/markdown",473});474475describe("the list pages, asked for Markdown", () => {476 it.effect.each([477 ["/", landingHandler],478 ["/asks", frontPageHandler],479 ] as const)("answers %s with llms.txt, varied by Accept", ([path, handler]) =>480 Effect.gen(function* () {481 const seen = yield* answered(482 handler(483 listing(projects),484 platformUrl485 )({486 next: () => "the page" as const,487 request: getAt(path, "text/markdown"),488 })489 );490491 expect(seen).toStrictEqual({492 body: frontLlms({ commands: catalog, platformUrl, projects, webUrl }),493 contentType: "text/markdown; charset=utf-8",494 status: 200,495 vary: "Accept",496 });497 })498 );499500 it.effect(501 "answers /oscabriel/datekit with the project's llms.txt, varied by Accept",502 () =>503 Effect.gen(function* () {504 const seen = yield* answered(505 projectPageHandler(506 listingWithAsks(projects, asks),507 platformUrl508 )({509 next: () => "the page" as const,510 params: { project: "datekit" },511 request: getAt("/oscabriel/datekit", "text/markdown"),512 })513 );514515 expect(seen).toStrictEqual({516 body: projectLlms({517 asks,518 commands: catalog,519 listing: { openAsks: 3, posture: "open", project: datekit },520 platformUrl,521 webUrl,522 }),523 contentType: "text/markdown; charset=utf-8",524 status: 200,525 vary: "Accept",526 });527 })528 );529530 it("gives a browser the page", () => {531 expect(532 landingHandler(533 listing(projects),534 platformUrl535 )({536 next: () => "the page" as const,537 request: getAt("/", BROWSER),538 })539 ).toBe("the page");540 expect(541 frontPageHandler(542 listing(projects),543 platformUrl544 )({545 next: () => "the page" as const,546 request: getAt("/asks", BROWSER),547 })548 ).toBe("the page");549 expect(550 projectPageHandler(551 listing(projects),552 platformUrl553 )({554 next: () => "the page" as const,555 params: { project: "datekit" },556 request: getAt("/oscabriel/datekit", BROWSER),557 })558 ).toBe("the page");559 });560561 it("names each page's Markdown as an alternate, in its head and its Link header", () => {562 for (const [headers, head] of [563 [landingHeaders, landingHead],564 [frontPageHeaders, frontPageHead],565 ] as const) {566 expect(headers()).toMatchObject({567 link: '</llms.txt>; rel="alternate"; type="text/markdown"',568 vary: "Accept",569 });570 expect(head().links).toContainEqual(alternate("/llms.txt"));571 }572573 expect(574 projectPageHeaders({ params: { project: "datekit" } })575 ).toMatchObject({576 link: '</oscabriel/datekit/llms.txt>; rel="alternate"; type="text/markdown"',577 vary: "Accept",578 });579 expect(580 projectPageHead({ params: { project: "datekit" } }).links581 ).toContainEqual(alternate("/oscabriel/datekit/llms.txt"));582 });583584 it("names no Markdown for a path that can name no project", () => {585 expect(586 projectPageHeaders({ params: { project: "Not_A_Project" } })587 ).toStrictEqual({ vary: "Accept" });588 });589});