Skip to content
Myr

project.test.tsx

This file

Path

apps/web/test/project.test.tsx

1,494 lines · 45.0 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { commandDocs } from "@repo/agent-kit/command-doc";3import { Brand } from "@repo/brand";4import { Client, Contracts } from "@repo/protocol/contracts";5import { AskListing } from "@repo/protocol/domain/ask";6import type { Ask } from "@repo/protocol/domain/ask";7import { FileView, TagName, TreeListing } from "@repo/protocol/domain/code";8import { Glob } from "@repo/protocol/domain/common";9import type { ProjectEvent } from "@repo/protocol/domain/event";10import { ProjectListing } from "@repo/protocol/domain/front-page";11import { LandingView } from "@repo/protocol/domain/landing";12import { LedgerEntry } from "@repo/protocol/domain/visibility";13import type { Ledger } from "@repo/protocol/domain/visibility";14import {15  AreaName,16  AskId,17  Handle,18  KindName,19  LayerName,20  ProjectName,21} from "@repo/protocol/ids";22import { UnknownRevision } from "@repo/protocol/refusal";23import { asTester, unanswered } from "@repo/protocol/testing";24import { isNotFound } from "@tanstack/react-router";25import {26  DateTime,27  Deferred,28  Duration,29  Effect,30  Layer,31  Option,32  Ref,33  Schema,34  Stream,35} from "effect";36import { FetchHttpClient } from "effect/http";37import { RpcClient, RpcSerialization, RpcTest } from "effect/rpc";38import type { ReactNode } from "react";3940import { recentLandings } from "../src/client/events.ts";41import type { DevWorldOptions } from "../src/dev/server.ts";42import { devServer } from "../src/dev/server.ts";43import { ledeOf } from "../src/features/front/head.ts";44import { stampStep } from "../src/features/front/stamps.ts";45import { ImportOffer, offerFor } from "../src/features/import/import-offer.tsx";46import { recentShown } from "../src/features/project/landings.tsx";47import { postureWord } from "../src/features/project/posture-label.ts";48import { ProjectFrame } from "../src/features/project/project-frame.tsx";49import {50  CloneSteps,51  ProjectHeader,52  WatchSteps,53} from "../src/features/project/project-header.tsx";54import {55  ProjectView,56  heldBackOf,57  homeListing,58} from "../src/features/project/project-page.tsx";59import type { ProjectViewProps } from "../src/features/project/project-page.tsx";60import { UnknownProjectView } from "../src/features/project/unknown-project.tsx";61import { askStates } from "../src/features/shared/ask-progress.ts";62import {63  inProjectFrame,64  projectSections,65  projectTabOf,66} from "../src/features/shared/shell/sections.ts";67import { getRouter } from "../src/router.tsx";68import {69  headerLoader,70  headerOrNone,71  Route as ProjectLayout,72} from "../src/routes/$owner/$project/route.tsx";73import {74  ProjectHeaderData,75  ProjectPageData,76  readProjectHeader,77  readProjectPage,78} from "../src/server/project-page.ts";79import { ask as parseIsoWeek } from "./ask-fixtures.ts";80import { allInOrder, markupOf, textIn, textOf } from "./markup.ts";81import { elementWith } from "./records.ts";82import { renderAt } from "./render.tsx";83import { reachingTransport } from "./transport.ts";8485const rowOf = (markup: string, ask: string) => {86  const start = markup.indexOf(`data-ask="${ask}"`);8788  const ends = ['data-ask="', "</ul></section>", "</main>"].flatMap((end) => {89    const at = markup.indexOf(end, start + 1);9091    return at === -1 ? [] : [at];92  });9394  return start === -1 ? "" : markup.slice(start, Math.min(...ends));95};9697const missingFrom = (text: string, parts: readonly string[]) =>98  parts.filter((part) => !text.includes(part));99100const foundIn = (text: string, parts: readonly string[]) =>101  parts.filter((part) => text.includes(part));102103const mainOf = (markup: string) =>104  markup.slice(markup.indexOf("<main"), markup.indexOf("</main>"));105106const aboutOf = (markup: string) => elementWith(markup, 'data-column="about"');107108/** The main region without its about column. */109const mainColumnOf = (markup: string) =>110  mainOf(markup).replace(aboutOf(markup), "");111112const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");113114const platformUrl = "https://platform-test.example.workers.dev";115116/** The gate's seven stages in cost order, as DESIGN.md's stage strip names them. */117const STAGES = [118  "Parse",119  "Shape",120  "Merge",121  "Cheap",122  "Checks",123  "Held-back",124  "Maintainer",125];126127const TABS = [128  "Overview",129  "Code",130  "Asks",131  "Landings",132  "Proposals",133  "People",134  "Policy",135  "Visibility",136];137138const listing = Schema.decodeSync(ProjectListing)({139  landedAt: "2026-10-06T09:00:00.000Z",140  openAsks: 2,141  posture: "openWithSealedEvidence",142  project: "datekit",143});144145const asks = Schema.decodeSync(Schema.Array(AskListing))([146  {147    ask: "fix-week-start",148    blockedBy: [],149    claimed: false,150    kind: "bug",151    territory: "core",152    want: "A week starts on the locale's first day, not always on Sunday.",153  },154  {155    ask: "drop-legacy-parse",156    blockedBy: [157      "drop-legacy-parse-core",158      "drop-legacy-parse-format",159      "drop-legacy-parse-delete",160    ],161    claimed: false,162    kind: "migrate",163    territory: ".",164    want: "Nothing calls the legacy parser any more.",165  },166  {167    ask: "drop-legacy-parse-core",168    blockedBy: [],169    claimed: false,170    kind: "migrate",171    territory: "core",172    want: "core: 2 callers of legacyParse → parse",173  },174  {175    ask: "drop-legacy-parse-format",176    blockedBy: [],177    claimed: true,178    kind: "migrate",179    territory: "format",180    want: "format: 1 caller of legacyParse → parse",181  },182  {183    ask: "drop-legacy-parse-delete",184    blockedBy: ["drop-legacy-parse-core", "drop-legacy-parse-format"],185    claimed: false,186    kind: "migrate",187    territory: ".",188    want: "Delete legacyParse: nothing calls it any more",189  },190  {191    ask: "trim-week-names",192    blockedBy: ["fix-week-start"],193    claimed: false,194    kind: "bug",195    reserve: "newcomers",196    territory: "core",197    want: "Week names are trimmed.",198  },199]);200201const parent: Ask = {202  ...parseIsoWeek,203  blockedBy: [204    AskId.make("drop-legacy-parse-core"),205    AskId.make("drop-legacy-parse-format"),206    AskId.make("drop-legacy-parse-delete"),207  ],208  brief: { want: "Nothing calls the legacy parser any more." },209  id: AskId.make("drop-legacy-parse"),210  kind: KindName.make("migrate"),211};212213const landingOf = (214  sha: string,215  more: { readonly ask?: string; readonly opened?: string },216  answerer?: string217) =>218  Schema.decodeSync(LandingView)({219    ...more,220    assisted: [],221    author: answerer ?? "ines-v",222    credits: [223      { handle: "ines-v", role: "Asked-by" },224      ...(answerer === undefined225        ? []226        : [{ handle: answerer, role: "Signed-off-by" as const }]),227    ],228    landedAt: "2026-10-06T09:00:00.000Z",229    parent: "2".repeat(40),230    project: "datekit",231    sha: sha.repeat(40),232  });233234const landings = [235  landingOf("a", { ask: "parse-iso-week" }, "bram"),236  landingOf("b", { opened: "format-ordinal" }),237  landingOf("c", { ask: "format-era" }, "okonkwo"),238  landingOf("d", { opened: "add-months-clamp" }),239];240241const AT = "a".repeat(40);242243const root = Schema.decodeSync(TreeListing)({244  at: AT,245  entries: [246    {247      mode: "040000",248      name: "src",249      path: "src",250      sha: "b".repeat(40),251      type: "tree",252    },253    {254      mode: "100644",255      name: "README.md",256      path: "README.md",257      sha: "c".repeat(40),258      type: "blob",259    },260  ],261  readme: { path: "README.md", sha: "c".repeat(40) },262});263264const readme = Schema.decodeSync(FileView)({265  at: AT,266  binary: false,267  path: "README.md",268  sha: "c".repeat(40),269  size: 26,270  text: "# datekit\n\nDates, kept.\n",271  truncated: false,272});273274const vellumLedger: Ledger = {275  entries: [276    LedgerEntry.cases.CountChanged.make({277      area: AreaName.make("export"),278      at: now,279      count: 7,280      layer: LayerName.make("maintainers"),281      seq: 1,282    }),283  ],284  layers: [],285  posture: "openWithSealedEvidence",286  postureLabel: "Open with sealed evidence",287  project: ProjectName.make("oscabriel/vellum"),288};289290const props = (more: Partial<ProjectViewProps> = {}): ProjectViewProps => ({291  asks,292  landings,293  listing,294  now,295  parents: [parent],296  platformUrl,297  ...more,298});299300const page = (more: Partial<ProjectViewProps> = {}) =>301  renderAt("/oscabriel/datekit", <ProjectView {...props(more)} />);302303describe(ProjectView, () => {304  it.effect(305    "lists every open ask with its want as the link, then its kind, territory and id",306    () =>307      Effect.gen(function* () {308        const row = rowOf(yield* page(), "fix-week-start");309310        expect(row).toMatch(311          /<a\b[^>]*href="\/oscabriel\/datekit\/asks\/fix-week-start"[^>]*>A week starts on the locale&#x27;s first day, not always on Sunday\.<\/a>/u312        );313        expect(textIn(row)).toContain("bug · core · fix-week-start");314        expect(textIn(row)).toContain("Open to take");315        expect(textIn(row)).toContain(316          `${Brand.cli} claim fix-week-start --project oscabriel/datekit`317        );318      })319  );320321  it.effect(322    "reads an ask whose blockers have all landed (left the list) as open to take, and counts it",323    () =>324      Effect.gen(function* () {325        const markup = yield* page({326          asks: asks.map((each) =>327            each.ask === "fix-week-start"328              ? { ...each, blockedBy: [AskId.make("landed-before")] }329              : each330          ),331        });332333        expect(textIn(rowOf(markup, "fix-week-start"))).toContain(334          "Open to take"335        );336        expect(textIn(markup)).toContain("5 open asks, 2 open to take");337      })338  );339340  it.effect(341    "draws a family as its parent's row with the fan, its children listed under it",342    () =>343      Effect.gen(function* () {344        const markup = yield* page();345        const family = rowOf(markup, "drop-legacy-parse");346347        expect(family).toContain('data-family="drop-legacy-parse"');348        expect(349          missingFrom(textIn(family), [350            "0 of 2 landed",351            "Hide 2 children",352            "core: 2 callers of legacyParse → parse",353            "delete waits for 2",354          ])355        ).toStrictEqual([]);356        expect(family.match(/data-family-child="/gu)).toHaveLength(2);357        // Its members are drawn in the fan, not again as rows of their own.358        expect(359          foundIn(markup, [360            'data-ask="drop-legacy-parse-core"',361            'data-ask="drop-legacy-parse-delete"',362          ])363        ).toStrictEqual([]);364      })365  );366367  it.effect(368    "reads an ask that waits on another as waiting, with the one it waits on listed",369    () =>370      Effect.gen(function* () {371        const markup = yield* page();372        const row = rowOf(markup, "trim-week-names");373374        expect(textIn(row)).toContain("Waiting");375        expect(row).not.toContain(`${Brand.cli} claim trim-week-names`);376        expect(markup).toContain('data-ask="fix-week-start"');377      })378  );379380  it.effect(381    "says in the about column how a change lands here: the seven stages, who decides, what is held back",382    () =>383      Effect.gen(function* () {384        const about = aboutOf(385          yield* page({386            deciders: [387              {388                handles: [Handle.make("ines-v"), Handle.make("okonkwo")],389                paths: Glob.make("src/**"),390              },391            ],392            heldBack: heldBackOf(vellumLedger),393          })394        );395396        const text = textIn(about);397398        expect(399          missingFrom(text, [400            "How a change lands here",401            "export: 7 sealed checks",402          ])403        ).toStrictEqual([]);404        expect(allInOrder(text, STAGES)).toBeTruthy();405        expect(text).toMatch(/src\/\*\*\s*·\s*ines-v, okonkwo/u);406        expect(407          missingFrom(about, [408            'href="/oscabriel/datekit/people"',409            'href="/oscabriel/datekit/visibility#ledger"',410            'href="/oscabriel/datekit/llms.txt"',411          ])412        ).toStrictEqual([]);413        // The posture is the header's to say, once.414        expect(about).not.toContain("data-posture=");415      })416  );417418  it.effect(419    "names where an imported project came from, with its branch, as a copy read-only here; and nothing for one that started empty",420    () =>421      Effect.gen(function* () {422        const facts = aboutOf(423          yield* page({424            importedFrom: {425              branch: "master",426              url: "https://github.com/dtolnay/anyhow",427            },428          })429        );430431        const text = textIn(facts);432433        expect(434          missingFrom(text, [435            "Imported from",436            "https://github.com/dtolnay/anyhow",437            "branch master",438            "This project is a copy of a public repo, read-only here and not run by its upstream maintainers.",439          ])440        ).toStrictEqual([]);441        expect(facts).toMatch(442          /<a[^>]*href="https:\/\/github\.com\/dtolnay\/anyhow"[^>]*rel="noreferrer"/u443        );444        expect(textIn(aboutOf(yield* page()))).not.toContain("Imported from");445      })446  );447448  it.effect(449    "gives the clone command and the claim command in the about column, and the last three landings as one-line credits in the main one",450    () =>451      Effect.gen(function* () {452        const markup = yield* page();453        const about = textIn(aboutOf(markup));454        const landed = mainColumnOf(markup);455456        expect(457          allInOrder(about, [458            `git clone ${platformUrl}/oscabriel/datekit.git`,459            `${Brand.cli} claim <ask> --project oscabriel/datekit`,460          ])461        ).toBeTruthy();462        expect(landed.match(/data-landing="/gu)).toHaveLength(3);463        expect(464          missingFrom(textIn(landed), [465            "Answer parse-iso-week",466            "Asked by ines-v · answered by bram",467          ])468        ).toStrictEqual([]);469        expect(textIn(landed)).not.toContain("Asked-by: ines-v");470      })471  );472473  it.effect(474    "has no code table, and its clone command only in the about column: the Code tab has the rest",475    () =>476      Effect.gen(function* () {477        const markup = yield* page({ code: { readme, root } });478        const main = mainColumnOf(markup);479480        expect(main).not.toContain('href="/oscabriel/datekit/tree/main/src"');481        expect(main).not.toContain("git clone");482        expect(main).toContain('data-readme="README.md"');483        expect(textIn(main)).toContain("Dates, kept.");484        // The README comes after the asks and the landings.485        expect(486          allInOrder(main, [487            'id="open-asks"',488            'id="recent-landings"',489            "data-readme",490          ])491        ).toBeTruthy();492      })493  );494495  it.effect(496    "says an empty project is empty, with the commands that would fill it",497    () =>498      Effect.gen(function* () {499        const { landedAt: _landed, ...unlanded } = listing;500501        const text = textIn(502          yield* page({503            asks: [],504            landings: [],505            listing: { ...unlanded, openAsks: 0 },506          })507        );508509        expect(text).toContain("No open asks");510        expect(text).toContain(`${Brand.cli} ask open`);511        expect(text).toContain("Nothing has landed");512        // The project exists, so `init` would refuse it: its first push lands main.513        expect(text).toContain(514          `git push ${platformUrl}/oscabriel/datekit.git HEAD:main`515        );516        expect(text).not.toContain(`${Brand.cli} init`);517      })518  );519520  it.effect(521    "never says nothing has landed on a project whose main has landed",522    () =>523      Effect.gen(function* () {524        const text = textIn(yield* page({ landings: [] }));525526        expect(text).toContain("No landings among the recent events");527        expect(text).not.toContain("Nothing has landed");528        expect(text).not.toContain("git push");529      })530  );531532  it("draws the same page with no router around it, nothing selected", () => {533    const text = textOf(<ProjectView {...props()} />);534535    expect(text).toContain("How a change lands here");536    expect(text).toContain("fix-week-start");537  });538});539540describe(recentShown, () => {541  it("shows the last three answers once three have landed, the setup's landings dropped", () => {542    const answers = [543      landingOf("1", { ask: "one" }, "bram"),544      landingOf("2", { opened: "two" }),545      landingOf("3", { ask: "three" }, "bram"),546      landingOf("4", { ask: "four" }, "bram"),547      landingOf("5", {}),548    ];549550    expect(recentShown(answers).map(({ ask }) => ask)).toStrictEqual([551      "one",552      "three",553      "four",554    ]);555  });556557  it("shows the last three of any kind before three answers have landed", () => {558    expect(recentShown(landings).map(({ sha }) => sha[0])).toStrictEqual([559      "a",560      "b",561      "c",562    ]);563  });564});565566describe(ledeOf, () => {567  it("is a README's first sentence, past its title, as plain words", () => {568    expect(569      ledeOf(570        "# datekit\n\nSmall, dependency-free date helpers for `TypeScript`. datekit reads ISO 8601 text.\n"571      )572    ).toBe("Small, dependency-free date helpers for TypeScript.");573    expect(574      ledeOf(575        "# burrow\n\nThe services behind [burrow's](https://x.test) shop: six packages.\n"576      )577    ).toBe("The services behind burrow's shop: six packages.");578  });579580  it("is none when the README opens with no prose", () => {581    expect(ledeOf("# title\n\n| a | b |\n| - | - |\n")).toBeUndefined();582  });583});584585const clientOver = (answer: (request: Request) => Promise<Response>) =>586  Layer.effect(Client)(RpcClient.make(Contracts)).pipe(587    Layer.provide(RpcClient.layerProtocolHttp({ url: "http://localhost/rpc" })),588    Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),589    Layer.provide(590      Layer.succeed(FetchHttpClient.Fetch, (input, init) =>591        answer(new Request(input, init))592      )593    )594  );595596const failingProjects =597  (598    handler: (request: Request) => Promise<Response>,599    listed: Ref.Ref<number> | undefined600  ) =>601  (request: Request) =>602    Effect.runPromise(603      Effect.gen(function* () {604        const body = yield* Effect.promise(() => request.clone().text());605606        if (listed !== undefined && body.includes('"listProjects"')) {607          yield* Ref.update(listed, (count) => count + 1);608609          return new Response("", { status: 503 });610        }611612        return yield* Effect.promise(() => handler(request));613      })614    );615616const devWorldWith = (options: DevWorldOptions, listed?: Ref.Ref<number>) =>617  Layer.unwrap(618    Effect.gen(function* () {619      const { dispose, handler } = devServer(options);620621      yield* Effect.addFinalizer(() => Effect.promise(dispose));622623      return clientOver(failingProjects(handler, listed));624    })625  );626627const devWorld = devWorldWith({});628629const unanswering = clientOver(() =>630  Promise.resolve(new Response("", { status: 503 }))631);632633const nothingLanded = Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(634  Layer.provide([635    Layer.mergeAll(636      unanswered,637      Contracts.toLayerHandler("readTree", ({ at }) =>638        Effect.fail(new UnknownRevision({ rev: at ?? "main" }))639      ),640      Contracts.toLayerHandler("listAsks", () => Effect.succeed({ asks: [] }))641    ),642    asTester,643  ])644);645646const decodePage = Schema.decodeEffect(ProjectPageData);647648const inputNamed = (markup: string, name: string) =>649  new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";650651/** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */652const seededWorld = { timeout: 30_000 };653654const propsFrom = (data: ProjectPageData): ProjectViewProps => {655  const events = data.events ?? [];656  const [latest] = recentLandings(events);657658  return {659    asks: data.asks,660    code: data.code,661    deciders: data.policy?.policy?.deciders,662    heldBack: data.ledger === undefined ? undefined : heldBackOf(data.ledger),663    importedFrom: data.policy?.importedFrom,664    landings: recentLandings(events),665    lastLanded: latest?.landedAt,666    listing: homeListing({667      asks: data.asks,668      ledger: data.ledger,669      project: data.project,670    }),671    now: data.now,672    parents: data.parents,673    platformUrl,674    states: askStates(events),675  };676};677678const sentFrom = (679  data: ProjectPageData,680  more: Partial<ProjectViewProps> = {}681) =>682  renderAt(`/${data.project}`, <ProjectView {...propsFrom(data)} {...more} />);683684const readFrom = (name: string, world: Layer.Layer<Client>) =>685  readProjectPage(name).pipe(Effect.flatMap(decodePage), Effect.provide(world));686687const decodeHeader = Schema.decodeEffect(ProjectHeaderData);688689const headerFrom = (name: string, world: Layer.Layer<Client>) =>690  readProjectHeader(name).pipe(691    Effect.flatMap(decodeHeader),692    Effect.provide(world)693  );694695/** A project page as its route draws it: the project's frame, its header (its tab from the path alone), then the page. */696const framed = (url: string, header: ProjectHeaderData, body: ReactNode) =>697  renderAt(698    url,699    <ProjectFrame700      header={701        <ProjectHeader702          current={projectTabOf(new URL(url, platformUrl).pathname)}703          header={header}704          platformUrl={platformUrl}705        />706      }707    >708      {body}709    </ProjectFrame>710  );711712const tabsOf = (markup: string) =>713  [714    ...elementWith(markup, 'data-project-tabs=""').matchAll(715      /<a\b(?<attributes>[^>]*)>(?<text>[\s\S]*?)<\/a>/gu716    ),717  ].map(({ groups }) => ({718    current: /aria-current="page"/u.test(groups?.attributes ?? ""),719    label: textIn(groups?.text ?? "")720      .replaceAll(/\d+/gu, "")721      .trim(),722  }));723724describe("the project's home as the server sends it", () => {725  it.effect(726    "carries datekit's asks, landings and README, with no code table, and the clone command only beside them",727    () =>728      Effect.gen(function* () {729        const data = yield* readFrom("datekit", devWorld);730        const markup = yield* sentFrom(data);731        const main = mainOf(markup);732733        expect(main).toMatch(734          /<a\b[^>]*href="\/oscabriel\/datekit\/asks\/add-months-clamp"[^>]*>[^<]+<\/a>/u735        );736        expect(737          missingFrom(main, [738            "Small, dependency-free date helpers",739            'data-readme="README.md"',740          ])741        ).toStrictEqual([]);742        expect(743          foundIn(mainColumnOf(markup), [744            'href="/oscabriel/datekit/tree/main/src"',745            "git clone",746            "Reading from the platform",747          ])748        ).toStrictEqual([]);749        expect(textIn(aboutOf(markup))).toContain("How a change lands here");750        expect(751          (main.match(/data-landing="/gu) ?? []).length752        ).toBeLessThanOrEqual(3);753      }),754    seededWorld755  );756757  it.effect(758    "draws burrow's family expanded, its six children listed",759    () =>760      Effect.gen(function* () {761        const data = yield* readFrom("burrow", devWorld);762763        const family = rowOf(764          mainOf(yield* sentFrom(data)),765          "drop-legacy-fetch"766        );767768        expect(family.match(/data-family-child="/gu)).toHaveLength(6);769        expect(textIn(family)).toContain("0 of 6 landed");770        expect(textIn(family)).toContain("Hide 6 children");771      }),772    seededWorld773  );774775  it.effect(776    "is sent without its asks and code, not as a not-found, when the platform does not answer",777    () =>778      Effect.gen(function* () {779        const { asks: read, code } = yield* readFrom("datekit", unanswering);780781        expect(read).toBeUndefined();782        expect(code).toBeUndefined();783      })784  );785786  it.effect(787    "shows a project whose main has not landed with no code, and no error",788    () =>789      Effect.gen(function* () {790        const data = yield* readFrom("datekit", nothingLanded);791792        expect(data.code).toBeUndefined();793        expect(mainOf(yield* sentFrom(data))).not.toContain("data-readme");794      })795  );796797  it.effect.each(["no-such-project", "Not_A_Project"])(798    "is a not-found for %s, which the platform does not know",799    (name) =>800      Effect.gen(function* () {801        const failed = yield* Effect.flip(802          readProjectPage(name).pipe(Effect.provide(devWorld))803        );804805        expect(isNotFound(failed)).toBeTruthy();806      }),807    seededWorld808  );809});810811const headerFacts = {812  deciders: [Handle.make("ines-v"), Handle.make("okonkwo")],813  landedAt: DateTime.makeUnsafe("2026-10-06T09:00:00Z"),814  latestTag: TagName.make("v0.3.0"),815  lede: "Dates, kept.",816  now,817  open: { asks: 5, takeable: 2 },818  posture: {819    label: "Open with sealed evidence · sealed checks in export",820    posture: "openWithSealedEvidence",821  },822  project: ProjectName.make("oscabriel/datekit"),823} satisfies ProjectHeaderData;824825const headerOf = (markup: string) =>826  elementWith(markup, 'data-project-header=""');827828/** The header as a page draws it, its current tab's marks (its own and the router's) and its name's element taken out. */829const sameHeader = (markup: string) =>830  headerOf(markup)831    .replaceAll(' aria-current="page"', "")832    .replaceAll(' data-current=""', "")833    .replaceAll(' data-status="active"', "")834    .replaceAll(' active"', '"')835    .replace('<h1 class="text-headline', '<p class="text-headline')836    .replace("</h1>", "</p>");837838const HEADER_READS = [839  "ledger",840  "listAsks",841  "listRefs",842  "log",843  "projectPolicy",844  "readFile",845  "readTree",846] as const;847848/** Each read waits until every one has started, so a read made after another never ends. */849const answeringAtOnce = Layer.unwrap(850  Effect.gen(function* () {851    const started = yield* Ref.make(0);852    const all = yield* Deferred.make<boolean>();853854    const held = Effect.gen(function* () {855      const count = yield* Ref.updateAndGet(started, (seen) => seen + 1);856857      if (count === HEADER_READS.length) {858        yield* Deferred.succeed(all, true);859      }860861      yield* Deferred.await(all);862863      return yield* Effect.die("Read at once, answered with nothing.");864    });865866    return Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(867      Layer.provide([868        Layer.mergeAll(869          unanswered,870          ...HEADER_READS.map((read) =>871            Contracts.toLayerHandler(read, () => held)872          )873        ),874        asTester,875      ])876    );877  })878);879880/** Each read asked of `handler`, written down by its contract's name. */881const counting =882  (883    handler: (request: Request) => Promise<Response>,884    seen: Ref.Ref<readonly string[]>885  ) =>886  (request: Request) =>887    Effect.runPromise(888      Effect.gen(function* () {889        const body = yield* Effect.promise(() => request.clone().text());890891        const tags = [...body.matchAll(/"tag":"(?<tag>\w+)"/gu)].map(892          ({ groups }) => groups?.tag ?? ""893        );894895        yield* Ref.update(seen, (before) => [...before, ...tags]);896897        return yield* Effect.promise(() => handler(request));898      })899    );900901/** The dev world, each read it is asked for written down. */902const countingWorld = (seen: Ref.Ref<readonly string[]>) =>903  Layer.unwrap(904    Effect.gen(function* () {905      const { dispose, handler } = devServer({});906907      yield* Effect.addFinalizer(() => Effect.promise(dispose));908909      return clientOver(counting(handler, seen));910    })911  );912913describe("a project's page in its frame", () => {914  it.effect(915    "opens burrow on Overview: eight tabs, the clone command and the seven stages in the about column, and no inspector",916    () =>917      Effect.gen(function* () {918        const data = yield* readFrom("oscabriel/burrow", devWorld);919920        const markup = yield* framed(921          "/oscabriel/burrow",922          data.header,923          <ProjectView {...propsFrom(data)} />924        );925926        const about = textIn(elementWith(markup, 'data-column="about"'));927928        expect(tabsOf(markup)).toStrictEqual(929          TABS.map((label) => ({ current: label === "Overview", label }))930        );931        expect(about).toContain(932          `git clone ${platformUrl}/oscabriel/burrow.git`933        );934        expect(allInOrder(about, STAGES)).toBeTruthy();935        expect(markup).not.toMatch(/data-facts="(?:inline|inspector)"/u);936      }),937    seededWorld938  );939940  it.effect(941    "draws the same header on Overview, a tree page and an ask page, only the current tab moving",942    () =>943      Effect.gen(function* () {944        const pages = [945          "/oscabriel/datekit",946          "/oscabriel/datekit/tree/main/src",947          "/oscabriel/datekit/asks/fix-week-start",948        ];949950        const markups = yield* Effect.forEach(pages, (url) =>951          framed(url, headerFacts, <main id="main" />)952        );953954        expect(955          markups.map((markup) =>956            tabsOf(markup)957              .filter(({ current }) => current)958              .map(({ label }) => label)959          )960        ).toStrictEqual([["Overview"], ["Code"], ["Asks"]]);961        // Overview's title is the project; the others title their own subject.962        expect(new Set(markups.map(sameHeader)).size).toBe(1);963        expect(964          markups.map(headerOf).every((header) => header !== "")965        ).toBeTruthy();966      })967  );968969  it.effect(970    "says the posture once on the page, in its short form, the platform's words in its title",971    () =>972      Effect.gen(function* () {973        const markup = yield* framed(974          "/oscabriel/datekit",975          headerFacts,976          <ProjectView {...props({ heldBack: heldBackOf(vellumLedger) })} />977        );978979        const header = headerOf(markup);980981        expect(markup.match(/data-posture="/gu)).toHaveLength(1);982        expect(header).toContain('data-posture="openWithSealedEvidence"');983        expect(textIn(header)).toContain(postureWord("openWithSealedEvidence"));984        expect(header).toContain(985          'title="Open with sealed evidence · sealed checks in export"'986        );987      })988  );989990  it.effect(991    "gives the project's facts in one row: open asks, last landing, newest tag and who decides",992    () =>993      Effect.gen(function* () {994        const markup = yield* framed("/oscabriel/datekit", headerFacts, null);995        const facts = elementWith(markup, 'data-project-facts=""');996997        expect(998          allInOrder(textIn(facts), [999            "5 open asks",1000            "Landed 1 d ago",1001            "v0.3.0",1002            "Decided by ines-v, okonkwo",1003          ])1004        ).toBeTruthy();1005        expect(facts).toContain('href="/people/ines-v"');1006        expect(textIn(headerOf(markup))).toContain("Dates, kept.");1007      })1008  );10091010  it.effect(1011    "offers Watch, Clone and Contribute, and counts the open asks on the Asks tab",1012    () =>1013      Effect.gen(function* () {1014        const markup = yield* framed("/oscabriel/datekit", headerFacts, null);10151016        expect(1017          [...headerOf(markup).matchAll(/data-action="(?<action>\w+)"/gu)].map(1018            ({ groups }) => groups?.action1019          )1020        ).toStrictEqual(["watch", "clone", "contribute"]);1021        expect(textIn(elementWith(markup, 'data-project-tabs=""'))).toContain(1022          "Asks5"1023        );1024      })1025  );10261027  it.effect(1028    "opens each tab that stands for a region of Overview on that region, inside the frame",1029    () =>1030      Effect.gen(function* () {1031        const markup = yield* framed(1032          "/oscabriel/datekit",1033          headerFacts,1034          <ProjectView {...props()} />1035        );10361037        const hashes = projectSections("oscabriel/datekit").flatMap(1038          ({ hash }) => (hash === undefined ? [] : [hash])1039        );10401041        expect(hashes).toStrictEqual([1042          "open-asks",1043          "recent-landings",1044          "proposals",1045          "who-decides",1046        ]);1047        expect(1048          hashes.filter((hash) => !markup.includes(`id="${hash}"`))1049        ).toStrictEqual([]);1050      })1051  );10521053  it.effect(1054    "titles Overview with the project whichever region its tabs have opened",1055    () =>1056      Effect.gen(function* () {1057        const markup = yield* framed(1058          "/oscabriel/datekit#proposals",1059          headerFacts,1060          null1061        );10621063        expect(headerOf(markup)).toMatch(/<h1 class="text-headline/u);1064        expect(1065          tabsOf(markup)1066            .filter(({ current }) => current)1067            .map(({ label }) => label)1068        ).toStrictEqual(["Overview"]);1069      })1070  );10711072  it.effect(1073    "sticks the header and its tabs under the top bar together, and moves what sticks below by their height",1074    () =>1075      Effect.gen(function* () {1076        const markup = yield* framed(1077          "/oscabriel/datekit/tree/main",1078          headerFacts,1079          null1080        );10811082        const head = elementWith(markup, 'data-project-head=""');10831084        expect(head).toMatch(1085          /^<div\b[^>]*class="[^"]*sticky top-\(--top-bar\)/u1086        );1087        expect(1088          missingFrom(head, ['data-project-header=""', 'data-project-tabs=""'])1089        ).toStrictEqual([]);1090        expect(elementWith(head, 'data-project-tabs=""')).not.toContain(1091          "sticky"1092        );1093        expect(markup).toContain(1094          "[--stick-toolbar:calc(var(--top-bar)_+_var(--project-head,11.25rem)_+_var(--toolbar)_-_1px)]"1095        );1096      })1097  );10981099  it("says the commands its popovers give whole, each a real CLI command with its project", () => {1100    const steps = textOf(1101      <>1102        <CloneSteps platformUrl={platformUrl} project={headerFacts.project} />1103        <WatchSteps project={headerFacts.project} />1104      </>1105    );11061107    expect(1108      allInOrder(steps, [1109        `git clone ${platformUrl}/oscabriel/datekit.git`,1110        `${Brand.cli} claim <ask> --project oscabriel/datekit`,1111        `${Brand.cli} status --project oscabriel/datekit`,1112      ])1113    ).toBeTruthy();1114    expect(1115      commandDocs(Contracts)1116        .filter(({ path }) => ["claim", "status"].includes(path.join(" ")))1117        .map(({ flags, path }) => [path.join(" "), flags.includes("--project")])1118    ).toStrictEqual([1119      ["claim", true],1120      ["status", true],1121    ]);1122  });1123});11241125describe("the project's header as the server sends it", () => {1126  it.effect(1127    "takes its posture from the project's own ledger, never the list of projects",1128    () =>1129      Effect.gen(function* () {1130        const listed = yield* Ref.make(0);11311132        const header = yield* headerFrom(1133          "oscabriel/vellum",1134          devWorldWith({ fixtures: "on" }, listed)1135        );11361137        const head = headerOf(yield* framed("/oscabriel/vellum", header, null));11381139        expect(yield* Ref.get(listed)).toBe(0);1140        expect(head).toContain('data-posture="openWithSealedEvidence"');1141        expect(head).toContain('title="Open with sealed evidence');1142      }),1143    seededWorld1144  );11451146  it.effect(1147    "says no posture while its own ledger is unread, never one it was not told",1148    () =>1149      Effect.gen(function* () {1150        const { posture: _unread, ...header } = yield* headerFrom(1151          "oscabriel/vellum",1152          devWorldWith({ fixtures: "on" })1153        );11541155        const markup = yield* framed("/oscabriel/vellum", header, null);11561157        expect(markup.match(/data-posture="/gu)?.length ?? 0).toBe(0);1158      }),1159    seededWorld1160  );11611162  it.effect(1163    "comes with Overview's own read on Overview, each of its reads made once",1164    () =>1165      Effect.gen(function* () {1166        const seen = yield* Ref.make<readonly string[]>([]);11671168        const { alone, data, tags } = yield* Effect.gen(function* () {1169          const overview = yield* readProjectPage("oscabriel/datekit").pipe(1170            Effect.flatMap(decodePage)1171          );11721173          const made = yield* Ref.get(seen);11741175          const header = yield* readProjectHeader("oscabriel/datekit").pipe(1176            Effect.flatMap(decodeHeader)1177          );11781179          return { alone: header, data: overview, tags: made };1180        }).pipe(Effect.provide(countingWorld(seen)));11811182        expect(1183          HEADER_READS.map((read) => tags.filter((tag) => tag === read).length)1184        ).toStrictEqual(HEADER_READS.map(() => 1));1185        expect(data.header).toStrictEqual(alone);1186      }),1187    seededWorld1188  );11891190  it.live("makes every read at once, none waiting on another", () =>1191    Effect.gen(function* () {1192      const header = yield* readProjectHeader("oscabriel/datekit").pipe(1193        Effect.flatMap(decodeHeader),1194        Effect.provide(answeringAtOnce),1195        Effect.timeout(Duration.seconds(3))1196      );11971198      expect(Object.keys(header).toSorted()).toStrictEqual(["now", "project"]);1199    })1200  );12011202  it.effect.each(["oscabriel/no-such-project", "Not_A_Project"])(1203    "is a not-found for %s, so the page under it says why",1204    (name) =>1205      Effect.gen(function* () {1206        const failed = yield* Effect.flip(1207          readProjectHeader(name).pipe(Effect.provide(devWorld))1208        );12091210        expect(isNotFound(failed)).toBeTruthy();1211      }),1212    seededWorld1213  );1214});12151216const datekitAt = (rest: string) => `/oscabriel/datekit${rest}`;12171218/** What the project's layout loads at `pathname`, its header read through the world it runs in. */1219const layoutLoadAt = (pathname: string) =>1220  Effect.gen(function* () {1221    const services = yield* Effect.context<Client>();12221223    const load = headerLoader((project) =>1224      Effect.runPromiseWith(services)(headerOrNone(project))1225    );12261227    const loaded = load({1228      location: { pathname },1229      params: { project: "oscabriel/datekit" },1230    });12311232    return yield* Effect.promise(() => Promise.resolve(loaded));1233  });12341235const decodeLoaded = Schema.decodeUnknownEffect(ProjectHeaderData);12361237const routeSources: Readonly<Record<string, string>> = import.meta.glob(1238  "../src/routes/$owner/$project/**/*.{ts,tsx}",1239  { eager: true, import: "default", query: "?raw" }1240);12411242const LAYOUT_DIR = "../src/routes/$owner/$project";12431244/** A route file's address, each param filled in, as the router's file naming spells it. */1245const addressOfFile = (file: string) =>1246  file1247    .replace(LAYOUT_DIR, "/oscabriel/datekit")1248    .replace(/\.tsx?$/u, "")1249    .replace(/\/(?:index|route)$/u, "")1250    .replaceAll("[.]", ".")1251    .replaceAll(/\{?\$\w*\}?/gu, "x");12521253/** Every page under a project's layout at a concrete address, with the shell its route names. */1254const pagesUnderLayout = () =>1255  Object.entries(routeSources)1256    .filter(([file]) => !file.split("/").some((part) => part.startsWith("-")))1257    .map(([file, source]) => ({1258      path: addressOfFile(file),1259      shell:1260        /shell:\s*"(?<shell>\w+)"/u.exec(source)?.groups?.shell ?? "project",1261    }));12621263describe("the project's layout route", () => {1264  it.effect(1265    "reads the header for a tree page, and nothing on Overview, which reads its own, or on a new proposal, which draws none",1266    () =>1267      Effect.gen(function* () {1268        const seen = yield* Ref.make<readonly string[]>([]);12691270        const { made, quiet, tree } = yield* Effect.gen(function* () {1271          const skipped = yield* Effect.forEach(1272            [datekitAt(""), datekitAt("/proposals/new")],1273            layoutLoadAt1274          );12751276          const before = yield* Ref.get(seen);12771278          const read = yield* layoutLoadAt(datekitAt("/tree/main")).pipe(1279            Effect.flatMap(decodeLoaded)1280          );12811282          return { made: before, quiet: skipped, tree: read };1283        }).pipe(Effect.provide(countingWorld(seen)));12841285        expect(quiet).toStrictEqual([undefined, undefined]);1286        expect(made).toStrictEqual([]);1287        expect(tree.project).toBe("oscabriel/datekit");1288        expect(tree.open?.asks).toBeGreaterThan(0);1289      }),1290    seededWorld1291  );12921293  it("is matched for every page of a project, and leaves out of its frame exactly the pages that name another shell", () => {1294    const pages = pagesUnderLayout();12951296    expect(1297      pages.filter(1298        ({ path }) =>1299          !getRouter().getMatchedRoutes(path)[0].includes(ProjectLayout)1300      )1301    ).toStrictEqual([]);1302    expect(1303      pages.filter(({ path }) => !inProjectFrame(path)).map(({ path }) => path)1304    ).toStrictEqual(1305      pages.filter(({ shell }) => shell !== "project").map(({ path }) => path)1306    );1307    expect(pages.map(({ path }) => path)).toContain(1308      datekitAt("/proposals/new")1309    );1310  });1311});13121313const vellum = ProjectName.make("oscabriel/vellum");13141315describe("a family child landing while the page is open", () => {1316  it.live(1317    "stamps nothing the first read holds, then stamps the child that landed, once, and moves the count",1318    () =>1319      Effect.gen(function* () {1320        const world = devWorldWith({1321          fixtures: "live",1322          liveAfter: Duration.zero,1323        });13241325        const [data, later] = yield* Effect.gen(function* () {1326          const first = yield* readProjectPage("oscabriel/vellum").pipe(1327            Effect.flatMap(decodePage)1328          );13291330          const client = yield* Client;13311332          const second: readonly ProjectEvent[] = yield* Stream.runCollect(1333            client.watch({ project: vellum, since: 0 })1334          );13351336          return [first, second] as const;1337        }).pipe(Effect.provide(world));13381339        const mounted = stampStep(undefined, data.events ?? []);1340        const read = stampStep(mounted, later);1341        const again = stampStep(read, later);13421343        expect([...mounted.stamped]).toStrictEqual([]);1344        expect([...read.stamped]).toStrictEqual([1345          "retire-old-tokenizer-vellum-lint",1346        ]);1347        expect(again.stamped).toBe(read.stamped);13481349        const before = rowOf(1350          mainOf(yield* sentFrom(data, { stamps: mounted.stamped })),1351          "retire-old-tokenizer"1352        );13531354        const after = rowOf(1355          mainOf(1356            yield* sentFrom(1357              { ...data, events: later },1358              { stamps: read.stamped }1359            )1360          ),1361          "retire-old-tokenizer"1362        );13631364        expect({1365          after: textIn(after).includes("3 of 6 landed"),1366          before: textIn(before).includes("2 of 6 landed"),1367          stampedAfter: after.match(/animate-stamp/gu)?.length,1368          stampedBefore: before.includes("animate-stamp"),1369        }).toStrictEqual({1370          after: true,1371          before: true,1372          // The child's node in the fan, and its row in the list under it.1373          stampedAfter: 2,1374          stampedBefore: false,1375        });1376      }),1377    seededWorld1378  );1379});13801381describe(UnknownProjectView, () => {1382  it.effect(1383    "shows the platform's UnknownProject refusal for a name that could be a project, and the way onward",1384    () =>1385      Effect.gen(function* () {1386        const markup = yield* renderAt(1387          "/oscabriel/no-such-project",1388          <UnknownProjectView name="oscabriel/no-such-project" />1389        );13901391        expect(markup).toContain('data-refusal="UnknownProject"');1392        expect(markup).toContain("oscabriel/no-such-project");1393        expect(markup).toMatch(/<a\b[^>]*href="\/asks"[^>]*>Open asks<\/a>/u);1394      })1395  );13961397  it.effect(1398    "keeps the one-sentence not-found, and no offer, for a person's address",1399    () =>1400      Effect.gen(function* () {1401        const markup = yield* renderAt(1402          "/oscabriel/no-such",1403          <UnknownProjectView name="oscabriel/no-such" />1404        );14051406        expect(markup).toContain('data-refusal="UnknownProject"');1407        expect(markup).not.toContain("<form");1408        expect(offerFor("oscabriel/no-such")).toStrictEqual(Option.none());1409      })1410  );14111412  it("says in a sentence that an address naming no possible project names none", () => {1413    const markup = markupOf(<UnknownProjectView name="Not_A_Project" />);14141415    expect(markup).not.toContain("data-refusal");1416    expect(textOf(<UnknownProjectView name="Not_A_Project" />)).toContain(1417      "No such project"1418    );1419  });1420});14211422describe(ImportOffer, () => {1423  const click = ProjectName.make("github.com/pallets/click");14241425  const offered = (handle: Option.Option<Handle>) =>1426    renderAt(1427      "/github.com/pallets/click",1428      <ImportOffer importer={{ handle }} project={click} />1429    );14301431  it("is what a source namespace's address offers, and no other", () => {1432    expect(offerFor("github.com/pallets/click")).toStrictEqual(1433      Option.some(click)1434    );1435    expect(offerFor("oscabriel/no-such")).toStrictEqual(Option.none());1436    expect(offerFor("Not_A_Project")).toStrictEqual(Option.none());1437  });14381439  it.effect(1440    "draws the form prefilled from the address, the owner fixed and no refusal",1441    () =>1442      Effect.gen(function* () {1443        const markup = yield* offered(Option.some(Handle.make("oscabriel")));14441445        expect(inputNamed(markup, "url")).toContain(1446          'value="https://github.com/pallets/click"'1447        );1448        expect(inputNamed(markup, "owner")).toMatch(1449          /type="hidden"[^>]*value="github\.com\/pallets"|value="github\.com\/pallets"[^>]*type="hidden"/u1450        );1451        expect(inputNamed(markup, "name")).toContain('value="click"');1452        expect(markup).not.toContain('data-slot="select-trigger"');1453        expect(markup).not.toContain("data-refusal");1454      })1455  );14561457  it.effect(1458    "keeps the URL the address rebuilds read-only, and the branch and the name editable",1459    () =>1460      Effect.gen(function* () {1461        const markup = yield* offered(Option.some(Handle.make("oscabriel")));14621463        expect(inputNamed(markup, "url")).toContain('readOnly=""');1464        expect(inputNamed(markup, "branch")).not.toContain("readOnly");1465        expect(inputNamed(markup, "name")).not.toContain("readOnly");1466      })1467  );14681469  it.effect(1470    "signed out, says what would be imported, with the sign-in link back to the address",1471    () =>1472      Effect.gen(function* () {1473        const markup = yield* offered(Option.none());14741475        expect(markup).not.toContain("<form");1476        expect(markup).toContain(1477          `href="/auth/signin?return=${encodeURIComponent("/github.com/pallets/click")}"`1478        );1479        expect(textIn(markup)).toContain("https://github.com/pallets/click");1480      })1481  );1482});14831484describe("the project's views", () => {1485  const sources: Readonly<Record<string, string>> = import.meta.glob(1486    "../src/features/project/**/*.{ts,tsx}",1487    { eager: true, import: "default", query: "?raw" }1488  );14891490  it("import no transport", () => {1491    expect(Object.keys(sources).length).toBeGreaterThanOrEqual(3);1492    expect(reachingTransport(sources)).toStrictEqual([]);1493  });1494});