Serve an ask as a page and as Markdown, and an answer's verdict stage by stage
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- /<project>/asks/<ask> renders the ask (want as title, kind, state, territory, check, who asked, parent, who it is held for, what it waits on, the brief's sections, and the clone, claim and check lines with Brand.cli). Its GET answers `Accept: text/markdown` with showAsk's brief untouched; the page carries `Link: <…/<ask>.md>; rel="alternate"; type="text/markdown"` and `Vary: Accept`. - /<project>/asks/<ask>.md always answers Markdown. The route file is `{$ask}[.]md.ts`, not `$ask[.]md.ts`: router-core reads `$ask.md` as one param named `ask.md`, while `{$ask}.md` is the param with a literal suffix (read in router-core's parseSegment, confirmed in vite dev). - Negotiation (`wantsMarkdown`) honours q-values: Markdown only when the request names `text/markdown` itself, above zero and at least text/html's quality; a wildcard alone or a browser gets the page. No user-agent lists. - Markdown answers: the brief 200 with `cache-control: public, max-age=60`, read from showAsk's `Visibility` annotation (a maintainers contract would be `private, no-store`); a refusal 404 whose body is its `explain` lines in a text block, then `Next: \`<next>\``; a path that can name no ask 404 without asking the platform; no answer from the platform 502. Only the brief is cacheable. - /<project>/answers/<ask> renders the verdict: the fields judged (head, base, merged tree, patch id, check version, when), the shared stage strip and outcome (a refusal as git printed it), each lane's result and time, held-back results only as `<area> <passed>/<total> @ <suite>`, and a landed answer's credit trailers with `git show <sha>`. `?head=` shows an earlier answer; a head that is not a commit id is a 404. - Pages read through loaders and server functions over `serverClient`, so they render on the server and an unknown project or ask is a real 404 (the refusal rides in the not-found's data, encoded, decoded on the page). The routes render from the client atoms (`askAtom`, `verdictAtom`, `landingAtom`), seeded through a page-scoped RegistryProvider with what the loader read, so nothing refetches until a key changes (510's live views). - TanStack infers route options in source order, so `loader` comes before `head` (and `validateSearch` before `loaderDeps`). - Tests: ask-markdown.test.ts (negotiation table, both URLs, refusals, the unreachable platform, the page's headers), ask.test.tsx (AskView and the not-found page), answer.test.tsx (AnswerView, LaneTable, HeldBackBits); web 85 tests. Checked in vite dev over a stub backend (not committed): the `.md` route wins over the page route, headers and statuses as above, no hydration errors, no sideways scroll at 360 px, light and dark. - bytes:check: web entry 717,829 of 1,665,000; JavaScript 2,100,499 of 2,500,000 (511 recorded 1,175,500): the unminified SSR chunks now carry Effect's RPC and HTTP clients and the atom runtime. - ASSUMPTION: an ask held for "people" means a person answers it, not an agent (GPR lens-asks-people.md: web claim, sign-off, mentor).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+2246 added−0 removed
- tests:+856 added−0 removed
- other:+1390 added−0 removed
Provenance
- Commit
b99c185- Tree
7a17404- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
eebd79b
14 files changed+2246 added−0 removed
added:apps/web/src/client/answer.ts+36 added
123456789101112131415161718192021222324252627282930313233343536/** * An answer's atoms (the data pattern in `src/surfaces.ts`): the verdict on * an ask's latest answer (or the one at `head`), and the landing a landed * answer made. A judged or landed answer changes its ask's keys, so both * refetch then. The answer page seeds them with the data its loader read * on the server. */import type { AskId, CommitSha, LandedSha, ProjectName,} from "@repo/protocol/ids";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";
/** The verdict on the ask's latest answer, or on the answer whose head is `head`. */export const verdictAtom = ( project: ProjectName, ask: AskId, head?: CommitSha) => ContractsClient.query( "verdict", head === undefined ? { ask, project } : { ask, head, project }, { reactivityKeys: keys.ask(project, ask) } );
/** The landing at `sha`, with its credit trailers. */export const landingAtom = (project: ProjectName, sha: LandedSha) => ContractsClient.query( "landing", { project, sha }, { reactivityKeys: keys.project(project) } );added:apps/web/src/client/ask.ts+18 added
123456789101112131415161718/** * An ask's atoms (the data pattern in `src/surfaces.ts`): `showAsk` over the * browser's `/rpc`, keyed so that a write that changes the ask (a claim, a * landing) refetches it. The ask page seeds this atom with the data its * loader read on the server, so it fetches only when its keys change. */import type { AskId, ProjectName } from "@repo/protocol/ids";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";
/** The ask and its brief. */export const askAtom = (project: ProjectName, ask: AskId) => ContractsClient.query( "showAsk", { ask, project }, { reactivityKeys: keys.ask(project, ask) } );added:apps/web/src/features/answer/answer-page.tsx+253 added
1+/**2+ * The verdict on an answer, as a report sheet: the fields that name what3+ * was judged (head, base, merged tree, patch id, check version, when), the4+ * gate's stages in a strip with the outcome under it (a refusal reads as5+ * `git push` printed it), each lane's result and time, the held-back checks6+ * as one line per area, and, once it landed, the landing's credit trailers7+ * and its commit.8+ *9+ * Held-back checks show only what `HeldBackResult` carries: an area, how10+ * many passed of how many, and the suite's root (spec D17). A lane's log is11+ * never shown here; a refusal that needs it names it, with the command12+ * that reads it.13+ */14+import type {15+ HeldBackResult,16+ LaneOutcome,17+ LaneResult,18+ Verdict,19+} from "@repo/protocol/domain/answer";20+import type { LandingView } from "@repo/protocol/domain/landing";21+import type { DateTime } from "effect";22+import {23+ Ban,24+ Check,25+ LockKeyhole,26+ RotateCcw,27+ TriangleAlert,28+ X,29+} from "lucide-react";30+import type { LucideIcon } from "lucide-react";31+32+import {33+ Table,34+ TableBody,35+ TableCell,36+ TableHead,37+ TableHeader,38+ TableRow,39+} from "../../components/ui/table.tsx";40+import { askPath } from "../ask/ask-page.tsx";41+import { CODE, Field, Fields, Region } from "../ask/fields.tsx";42+import { CommandLine } from "../shared/command.tsx";43+import { CreditTrailers } from "../shared/credits.tsx";44+import { EmptyState } from "../shared/empty.tsx";45+import { OutcomeView, StageStrip } from "../shared/outcome.tsx";46+import { When } from "../shared/time.tsx";47+48+/** How long a lane ran: "640 ms", "8.3 s", "2 min 5 s". */49+export const durationText = (millis: number) => {50+ if (millis < 1000) {51+ return `${millis} ms`;52+ }53+54+ if (millis < 60_000) {55+ return `${(millis / 1000).toFixed(1)} s`;56+ }57+58+ const seconds = Math.round(millis / 1000);59+60+ return `${Math.floor(seconds / 60)} min ${seconds % 60} s`;61+};62+63+/** Each lane result as a mark, a word and its role colour (DESIGN.md: the word first). */64+const results = {65+ blocked: { icon: Ban, tone: "text-waiting", word: "blocked" },66+ failed: { icon: X, tone: "text-refused", word: "failed" },67+ flaked: { icon: RotateCcw, tone: "text-waiting", word: "flaked" },68+ loadError: { icon: TriangleAlert, tone: "text-refused", word: "load error" },69+ passed: { icon: Check, tone: "text-landed", word: "passed" },70+} as const satisfies Record<71+ LaneOutcome,72+ { readonly icon: LucideIcon; readonly tone: string; readonly word: string }73+>;74+75+const HEAD = "text-muted-foreground h-8 px-0 text-xs font-medium";76+77+/** The lanes the platform ran on the merged tree: each one's command, result and time. */78+export const LaneTable = ({79+ lanes,80+}: {81+ readonly lanes: readonly LaneResult[];82+}) => {83+ if (lanes.length === 0) {84+ return <EmptyState title="No lane ran on this answer." />;85+ }86+87+ return (88+ <Table className="border-rule border-t text-sm">89+ <TableHeader>90+ <TableRow className="hover:bg-transparent">91+ <TableHead className={HEAD}>Lane and command</TableHead>92+ <TableHead className={`${HEAD} pl-4`}>Result</TableHead>93+ <TableHead className={`${HEAD} pl-4 text-right`}>Time</TableHead>94+ </TableRow>95+ </TableHeader>96+ <TableBody>97+ {lanes.map(({ command, durationMs, lane, result }) => {98+ const { icon: Icon, tone, word } = results[result];99+100+ return (101+ <TableRow102+ className="border-rule hover:bg-transparent"103+ data-lane={lane}104+ data-result={result}105+ key={lane}106+ >107+ <TableCell className="px-0 py-2 align-top whitespace-normal">108+ <span className="flex min-w-0 flex-col">109+ <span className={`${CODE} font-medium`}>{lane}</span>110+ <code className={`${CODE} text-muted-foreground`}>111+ {command}112+ </code>113+ </span>114+ </TableCell>115+ <TableCell className={`py-2 pl-4 align-top ${tone}`}>116+ <span className="inline-flex items-center gap-1.5">117+ <Icon aria-hidden="true" className="size-3.5 shrink-0" />118+ <span className="font-medium">{word}</span>119+ </span>120+ </TableCell>121+ <TableCell className="py-2 pr-0 pl-4 text-right align-top">122+ {durationText(durationMs)}123+ </TableCell>124+ </TableRow>125+ );126+ })}127+ </TableBody>128+ </Table>129+ );130+};131+132+/** Held-back checks: one line per area, as the landing's trailer spells it, and nothing else. */133+export const HeldBackBits = ({134+ results: areas,135+}: {136+ readonly results: readonly HeldBackResult[];137+}) => (138+ <ul139+ aria-label="Held-back checks by area"140+ className="text-sealed flex flex-col gap-1 font-mono text-[0.8125rem] leading-6"141+ >142+ {areas.map(({ area, passed, suite, total }) => (143+ <li144+ className="flex items-start gap-2 [overflow-wrap:anywhere]"145+ data-area={area}146+ key={area}147+ >148+ <LockKeyhole aria-hidden="true" className="mt-1 size-3.5 shrink-0" />149+ <span className="min-w-0">150+ {area} {passed}/{total} @ {suite}151+ </span>152+ </li>153+ ))}154+ </ul>155+);156+157+const short = (sha: string) => sha.slice(0, 7);158+159+/** A git id, short as git prints it, whole on hover. */160+const Sha = ({ sha }: { readonly sha: string }) => (161+ <code className={CODE} title={sha}>162+ {short(sha)}163+ </code>164+);165+166+const LINK = "decoration-rule underline hover:decoration-current";167+168+export const AnswerView = ({169+ landing,170+ now,171+ verdict,172+}: {173+ readonly landing?: LandingView;174+ readonly now: DateTime.Utc;175+ readonly verdict: Verdict | undefined;176+}) => {177+ if (verdict === undefined) {178+ return <EmptyState title="No answer to this ask has been checked yet." />;179+ }180+181+ return (182+ <>183+ <Fields label="What was judged">184+ <Field label="Ask">185+ <a186+ className={`${LINK} ${CODE}`}187+ href={askPath(verdict.project, verdict.ask)}188+ >189+ {verdict.ask}190+ </a>191+ </Field>192+ <Field label="Judged">193+ <When at={verdict.at} now={now} />{" "}194+ <span className="text-muted-foreground">195+ by the {verdict.verifier}196+ </span>197+ </Field>198+ <Field label="Head">199+ <Sha sha={verdict.head} />200+ </Field>201+ <Field label="Base">202+ <Sha sha={verdict.base} />203+ </Field>204+ <Field label="Merged tree">205+ <Sha sha={verdict.tree} />206+ </Field>207+ <Field label="Patch id">208+ <Sha sha={verdict.patchId} />209+ </Field>210+ <Field label="Check version">211+ <code className={CODE}>{verdict.checkVersion}</code>212+ </Field>213+ </Fields>214+215+ <Region id="answer-gate" title="Gate">216+ <StageStrip outcome={verdict.outcome} stage={verdict.stage} />217+ <OutcomeView outcome={verdict.outcome} />218+ </Region>219+220+ <Region id="answer-lanes" title="Lanes">221+ <LaneTable lanes={verdict.lanes} />222+ </Region>223+224+ {verdict.heldBack.length === 0 ? null : (225+ <Region id="answer-held-back" title="Held-back checks">226+ <p className="text-muted-foreground max-w-[70ch] text-sm">227+ Checks the answer could not see. Each area shows how many passed,228+ and the root of the suite the project committed to before the claim.229+ </p>230+ <HeldBackBits results={verdict.heldBack} />231+ </Region>232+ )}233+234+ {landing === undefined ? null : (235+ <Region id="answer-landing" title="Landing">236+ <CreditTrailers237+ assisted={landing.assisted}238+ credits={landing.credits}239+ {...(landing.heldBackTrailer === undefined240+ ? {}241+ : { heldBack: landing.heldBackTrailer })}242+ />243+ <div className="flex min-w-0 flex-col gap-1.5">244+ <span className="text-muted-foreground text-xs font-medium">245+ The landing commit, in a clone of {landing.project}246+ </span>247+ <CommandLine command={`git show ${landing.sha}`} />248+ </div>249+ </Region>250+ )}251+ </>252+ );253+};added:apps/web/src/features/ask/ask-page.tsx+328 added
1+/**2+ * An ask, as a person reads it: the want as the page's title, the fields3+ * (kind, state, territory, check, who asked, its parent, who it is held4+ * for), what it waits on, the brief's sections, and the lines that clone5+ * the project, claim the ask and check an answer. Agents read the same ask6+ * as Markdown (`markdown.ts`); the page links to it and shows the brief7+ * verbatim, so a person sees what their agent reads.8+ */9+import { Brand } from "@repo/brand";10+import type { Ask, AskState } from "@repo/protocol/domain/ask";11+import { CheckSpec } from "@repo/protocol/domain/check";12+import type { AskId, ProjectName } from "@repo/protocol/ids";13+import type { DateTime } from "effect";14+import { Circle, CircleDot, Hourglass, Minus } from "lucide-react";15+import type { LucideIcon } from "lucide-react";16+import type { ReactNode } from "react";17+18+import { CommandLine } from "../shared/command.tsx";19+import { HandleLink } from "../shared/handle.tsx";20+import { PageShell } from "../shared/layout.tsx";21+import { When } from "../shared/time.tsx";22+import { CODE, Field, Fields, Region } from "./fields.tsx";23+import { markdownPath } from "./markdown.ts";24+25+/** An ask's page. */26+export const askPath = (project: ProjectName, ask: AskId) =>27+ `/${project}/asks/${ask}`;28+29+/** The page of the verdict on an ask's latest answer. */30+export const answerPath = (project: ProjectName, ask: AskId) =>31+ `/${project}/answers/${ask}`;32+33+const LINK = "decoration-rule underline hover:decoration-current";34+35+/** Each state as a mark, a word and its role colour (none for open: nothing is happening yet). */36+const states = {37+ claimed: { icon: CircleDot, tone: "", word: "Claimed" },38+ closed: { icon: Minus, tone: "text-muted-foreground", word: "Closed" },39+ open: { icon: Circle, tone: "", word: "Open" },40+ waitingOnParent: {41+ icon: Hourglass,42+ tone: "text-waiting",43+ word: "Waiting on its parent",44+ },45+} as const satisfies Record<46+ AskState,47+ { readonly icon: LucideIcon; readonly tone: string; readonly word: string }48+>;49+50+const StateMark = ({ state }: { readonly state: AskState }) => {51+ const { icon: Icon, tone, word } = states[state];52+53+ return (54+ <span className={`font-medium ${tone}`}>55+ <Icon56+ aria-hidden="true"57+ className="mr-1.5 inline-block size-3.5 align-[-0.15em]"58+ />59+ {word}60+ </span>61+ );62+};63+64+const Code = ({ children }: { readonly children: ReactNode }) => (65+ <code className={CODE}>{children}</code>66+);67+68+/** What judges an answer: the check's kind in words, then what it names. */69+const checkOf = (check: CheckSpec) =>70+ CheckSpec.match(check, {71+ LintToZero: ({ rule, territory }) => (72+ <>73+ Lint to zero: <Code>{rule}</Code>74+ {territory === undefined ? null : (75+ <>76+ {" "}77+ in <Code>{territory}</Code>78+ </>79+ )}80+ </>81+ ),82+ Migrate: ({ from, to }) => (83+ <>84+ Migrate: <Code>{from}</Code>85+ {to === undefined ? null : (86+ <>87+ {" "}88+ to <Code>{to}</Code>89+ </>90+ )}91+ </>92+ ),93+ Ratchet: ({ ratchet }) => (94+ <>95+ Ratchet <Code>{ratchet}</Code> goes down96+ </>97+ ),98+ RedThenGreen: ({ path }) => (99+ <>100+ Red, then green: <Code>{path}</Code>101+ </>102+ ),103+ SymbolAbsent: ({ symbol }) => (104+ <>105+ Nothing uses <Code>{symbol}</Code>106+ </>107+ ),108+ });109+110+/** Asks, each linking to its page, separated by commas. */111+const AskLinks = ({112+ asks,113+ project,114+}: {115+ readonly asks: readonly AskId[];116+ readonly project: ProjectName;117+}) =>118+ asks.map((ask, index) => (119+ <span key={ask}>120+ {index === 0 ? null : ", "}121+ <a className={`${LINK} ${CODE}`} href={askPath(project, ask)}>122+ {ask}123+ </a>124+ </span>125+ ));126+127+const reserved = {128+ newcomers: "Held for newcomers",129+ people: "Held for a person to answer, not an agent",130+} as const;131+132+const BriefPart = ({133+ children,134+ title,135+}: {136+ readonly children: ReactNode;137+ readonly title: string;138+}) => (139+ <div className="flex flex-col gap-1.5">140+ <h3 className="text-sm font-semibold">{title}</h3>141+ {children}142+ </div>143+);144+145+const BriefList = ({ items }: { readonly items: readonly string[] }) => (146+ <ul className="flex list-[square] flex-col gap-1 pl-5 marker:text-[color:var(--rule-strong)]">147+ {items.map((item) => (148+ <li key={item}>{item}</li>149+ ))}150+ </ul>151+);152+153+/** The lines that start an answer: clone, claim (it prints the fork's remote), check before the push. */154+const TakeIt = ({155+ ask,156+ platformUrl,157+}: {158+ readonly ask: Ask;159+ readonly platformUrl: string;160+}) => {161+ if (ask.state === "closed") {162+ return (163+ <p className="text-muted-foreground text-sm">164+ This ask is closed, so it takes no claim.165+ </p>166+ );167+ }168+169+ const steps = [170+ ["Clone the project", `git clone ${platformUrl}/${ask.project}.git`],171+ [172+ "Claim the ask; the claim prints your fork's remote",173+ `${Brand.cli} claim ${ask.id} --project ${ask.project}`,174+ ],175+ [176+ "Check your answer before you push it",177+ `${Brand.cli} check --ask ${ask.id}`,178+ ],179+ ] as const;180+181+ return (182+ <ol className="flex flex-col gap-3">183+ {steps.map(([label, command]) => (184+ <li className="flex min-w-0 flex-col gap-1.5" key={command}>185+ <span className="text-muted-foreground text-xs font-medium">186+ {label}187+ </span>188+ <CommandLine command={command} />189+ </li>190+ ))}191+ </ol>192+ );193+};194+195+export const AskView = ({196+ ask,197+ brief,198+ now,199+ platformUrl,200+}: {201+ readonly ask: Ask;202+ readonly brief: string;203+ readonly now: DateTime.Utc;204+ readonly platformUrl: string;205+}) => {206+ const { context, current, outOfScope, terms } = ask.brief;207+208+ return (209+ <PageShell title={ask.brief.want}>210+ <Fields label="The ask">211+ <Field label="Ask">212+ <Code>{ask.id}</Code>213+ </Field>214+ <Field label="State">215+ <StateMark state={ask.state} />216+ </Field>217+ <Field label="Kind">218+ <Code>{ask.kind}</Code>219+ </Field>220+ <Field label="Asked by">221+ <HandleLink handle={ask.askedBy} />{" "}222+ <span className="text-muted-foreground">223+ · opened <When at={ask.openedAt} now={now} />224+ </span>225+ </Field>226+ <Field label="Territory">227+ <Code>{ask.territory.module}</Code>228+ <span className="text-muted-foreground">: </span>229+ {ask.territory.paths.map((path, index) => (230+ <span key={path}>231+ {index === 0 ? null : ", "}232+ <Code>{path}</Code>233+ </span>234+ ))}235+ </Field>236+ <Field label="Check">{checkOf(ask.check)}</Field>237+ {ask.parent === undefined ? null : (238+ <Field label="Step of">239+ <AskLinks asks={[ask.parent]} project={ask.project} />240+ </Field>241+ )}242+ {ask.reserve === undefined ? null : (243+ <Field label="Who may take it">244+ {reserved[ask.reserve]}245+ {ask.mentor === undefined ? null : (246+ <>247+ , mentored by <HandleLink handle={ask.mentor} />248+ </>249+ )}250+ </Field>251+ )}252+ </Fields>253+254+ {ask.blockedBy.length === 0 ? null : (255+ <p className="text-waiting flex items-start gap-2" data-state="waiting">256+ <Hourglass aria-hidden="true" className="mt-1 size-4 shrink-0" />257+ <span className="text-foreground min-w-0">258+ <strong className="text-waiting font-semibold">Waits on</strong>{" "}259+ <AskLinks asks={ask.blockedBy} project={ask.project} /> to land260+ first; a claim waits until they do.261+ </span>262+ </p>263+ )}264+265+ <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:gap-12">266+ <Region id="ask-brief" title="Brief">267+ <div className="flex max-w-[70ch] flex-col gap-5">268+ {current === undefined ? null : (269+ <BriefPart title="Current behaviour">270+ <p>{current}</p>271+ </BriefPart>272+ )}273+ {outOfScope === undefined ? null : (274+ <BriefPart title="Out of scope">275+ <BriefList items={outOfScope} />276+ </BriefPart>277+ )}278+ {terms === undefined || terms.length === 0 ? null : (279+ <BriefPart title="Terms">280+ <BriefList items={terms} />281+ </BriefPart>282+ )}283+ {context === undefined || context.length === 0 ? null : (284+ <BriefPart title="Context">285+ <BriefList items={context} />286+ </BriefPart>287+ )}288+ <details className="border-rule group border-t pt-3">289+ <summary className="text-muted-foreground hover:text-foreground cursor-pointer text-sm select-none">290+ The brief, as an agent reads it291+ </summary>292+ <pre className="border-rule bg-surface mt-3 overflow-x-auto border p-3 font-mono text-[0.8125rem] leading-6 whitespace-pre-wrap">293+ {brief}294+ </pre>295+ </details>296+ </div>297+ </Region>298+299+ <div className="flex min-w-0 flex-col gap-8">300+ <Region id="ask-take" title="Take it">301+ <TakeIt ask={ask} platformUrl={platformUrl} />302+ </Region>303+ <Region id="ask-more" title="See also">304+ <ul className="flex flex-col gap-1.5 text-sm">305+ <li>306+ <a className={LINK} href={answerPath(ask.project, ask.id)}>307+ Where the latest answer stands308+ </a>309+ </li>310+ <li>311+ <a312+ className={LINK}313+ href={markdownPath(ask.project, ask.id)}314+ type="text/markdown"315+ >316+ This ask as Markdown317+ </a>318+ <span className="text-muted-foreground">319+ , for an agent to fetch320+ </span>321+ </li>322+ </ul>323+ </Region>324+ </div>325+ </div>326+ </PageShell>327+ );328+};added:apps/web/src/features/ask/fields.tsx+56 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556/** * A report sheet's fields: a label, then its value, one ruled row each, as * the header of a test certificate reads (DESIGN.md). From `lg` two fields * share a row. Values that are code (ids, paths, SHAs) wrap anywhere, so a * phone never scrolls sideways. */import type { ReactNode } from "react";
/** Text that is code: an id, a path, a SHA, a command's name. */export const CODE = "font-mono text-[0.8125rem] [overflow-wrap:anywhere]";
export const Fields = ({ children, label,}: { readonly children: ReactNode; readonly label: string;}) => ( <dl aria-label={label} className="border-rule grid grid-cols-[minmax(6.5rem,max-content)_minmax(0,1fr)] gap-x-6 border-t text-sm lg:grid-cols-[minmax(6.5rem,max-content)_minmax(0,1fr)_minmax(6.5rem,max-content)_minmax(0,1fr)]" > {children} </dl>);
export const Field = ({ children, label,}: { readonly children: ReactNode; readonly label: string;}) => ( <div className="border-rule col-span-2 grid grid-cols-subgrid items-baseline border-b py-2"> <dt className="text-muted-foreground text-xs font-medium">{label}</dt> <dd className="min-w-0 [overflow-wrap:anywhere]">{children}</dd> </div>);
/** A titled region of a page: a heading over its content, 32 px from the next. */export const Region = ({ children, id, title,}: { readonly children: ReactNode; readonly id: string; readonly title: string;}) => ( <section aria-labelledby={id} className="flex min-w-0 flex-col gap-3"> <h2 className="text-lg font-semibold tracking-[-0.01em]" id={id}> {title} </h2> {children} </section>);added:apps/web/src/features/ask/markdown.ts+193 added
1+/**2+ * An ask as Markdown, for agents: a harness reads an ask with one plain3+ * fetch, either with `Accept: text/markdown` on the ask's own URL or at the4+ * same URL with `.md`. The request decides; no user-agent list does.5+ *6+ * The brief is the platform's: `showAsk` renders it once, and the web only7+ * serves it. A refusal is set the way `git push` printed it, from8+ * `@repo/protocol/render` (AGENTS.md principle 3), then its next command.9+ * Pure: a `Request` or an `Exit` in, a string or a `Response` out.10+ */11+import { Brand } from "@repo/brand";12+import { Refusal } from "@repo/protocol/refusal";13+import { explain } from "@repo/protocol/render";14+import { Array, Cause, Exit, Option, Schema } from "effect";15+16+const MARKDOWN = "text/markdown; charset=utf-8";17+18+/** Who may share the answer: a `public` contract's for a minute, a `maintainers` one's never. */19+export type ContractVisibility = "public" | "maintainers";20+21+/** One range of an `Accept` header: `text/markdown;q=0.8`. */22+interface MediaRange {23+ readonly quality: number;24+ readonly subtype: string;25+ readonly type: string;26+}27+28+/** A q-value as RFC 9110 writes it: 0 to 1, at most three decimals; anything else is no range. */29+const QUALITY = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;30+31+const rangesOf = (accept: string): readonly MediaRange[] =>32+ accept.split(",").flatMap((entry) => {33+ const [media = "", ...parameters] = entry34+ .split(";")35+ .map((part) => part.trim().toLowerCase());36+37+ const [type = "", subtype = ""] = media.split("/");38+ const q = parameters.find((parameter) => parameter.startsWith("q="));39+ const quality = q === undefined ? "1" : q.slice(2);40+41+ return type === "" || subtype === "" || !QUALITY.test(quality)42+ ? []43+ : [{ quality: Number(quality), subtype, type }];44+ });45+46+/** How closely `range` names `type/subtype`: 3 by name, 2 by `type/*`, 1 by `*\/*`, 0 not at all. */47+const closeness = (range: MediaRange, type: string, subtype: string) => {48+ if (range.type === type) {49+ if (range.subtype === subtype) {50+ return 3;51+ }52+53+ return range.subtype === "*" ? 2 : 0;54+ }55+56+ return range.type === "*" && range.subtype === "*" ? 1 : 0;57+};58+59+/** The quality the closest range gives `type/subtype` (RFC 9110 §12.5.1), and how close it was. */60+const preferenceFor = (61+ ranges: readonly MediaRange[],62+ type: string,63+ subtype: string64+) => {65+ let best = { close: 0, quality: 0 };66+67+ for (const range of ranges) {68+ const close = closeness(range, type, subtype);69+70+ if (close > best.close) {71+ best = { close, quality: range.quality };72+ }73+ }74+75+ return best;76+};77+78+/**79+ * Whether the request asks for the ask as Markdown: it names `text/markdown`80+ * itself, with a quality above zero and at least the quality it gives81+ * `text/html`. A wildcard alone (`*\/*`, `text/*`, or no `Accept` at all)82+ * gets the page, as a browser does.83+ */84+export const wantsMarkdown = (request: Request) => {85+ const ranges = rangesOf(request.headers.get("accept") ?? "");86+ const markdown = preferenceFor(ranges, "text", "markdown");87+ const html = preferenceFor(ranges, "text", "html");88+89+ return (90+ markdown.close === 3 &&91+ markdown.quality > 0 &&92+ markdown.quality >= html.quality93+ );94+};95+96+/** The longest run of backticks in `text`. */97+const longestTicks = (text: string) =>98+ Math.max(0, ...[...text.matchAll(/`+/gu)].map(([run]) => run.length));99+100+/** `text` as inline code, its delimiter longer than any backticks inside it. */101+const inlineCode = (text: string) => {102+ const ticks = longestTicks(text);103+ const fence = "`".repeat(ticks + 1);104+105+ return ticks === 0 ? `${fence}${text}${fence}` : `${fence} ${text} ${fence}`;106+};107+108+/**109+ * Refusals as an agent reads them in Markdown: every refusal's `explain`110+ * lines in one text block, verbatim (git's `remote:` lines, without the111+ * prefix), then each distinct `next` command once, as its own paragraph.112+ */113+export const refusalsMarkdown = (114+ refusals: Array.NonEmptyReadonlyArray<Refusal>115+) => {116+ const lines = explain(refusals);117+ const fence = "`".repeat(Math.max(3, longestTicks(lines.join("\n")) + 1));118+ const nexts = Array.dedupe(refusals.map((refusal) => refusal.next));119+120+ return [121+ `${fence}text`,122+ ...lines,123+ fence,124+ "",125+ nexts.map((next) => `Next: ${inlineCode(next)}`).join("\n\n"),126+ "",127+ ].join("\n");128+};129+130+const markdown = (body: string, status: number, cacheControl: string) =>131+ new Response(body, {132+ headers: {133+ "cache-control": cacheControl,134+ "content-type": MARKDOWN,135+ vary: "Accept",136+ },137+ status,138+ });139+140+/** What a Markdown answer may be cached for, by its contract's visibility (spec §3.1). */141+const cacheFor = (visibility: ContractVisibility) =>142+ visibility === "public" ? "public, max-age=60" : "private, no-store";143+144+const isRefusal = Schema.is(Refusal);145+146+/** What the web says when the platform gave neither the ask nor a refusal. */147+const UNANSWERED = [148+ "The platform did not answer, so the web cannot read this ask now. Ask again in a moment.",149+ "",150+].join("\n");151+152+/**153+ * How reading an ask ended, as the Markdown response: the brief (200,154+ * cacheable as its contract's visibility allows); a refusal (404, its155+ * Markdown); or no answer from the platform (502). Only a brief is cached.156+ */157+export const askMarkdownResponse = <E>(158+ result: Exit.Exit<{ readonly brief: string }, E>,159+ visibility: ContractVisibility160+): Response =>161+ Exit.match(result, {162+ onFailure: (cause) =>163+ Option.match(Option.filter(Cause.findErrorOption(cause), isRefusal), {164+ onNone: () => markdown(UNANSWERED, 502, "no-store"),165+ onSome: (refusal) =>166+ markdown(refusalsMarkdown([refusal]), 404, "no-store"),167+ }),168+ onSuccess: ({ brief }) => markdown(brief, 200, cacheFor(visibility)),169+ });170+171+/**172+ * The answer to a path that can name no ask: a project's and an ask's names173+ * are lowercase words joined by single dashes, so the platform is not asked.174+ */175+export const noAskAt = (path: string) =>176+ markdown(177+ [178+ `No ask is at ${inlineCode(path)}: a project's and an ask's names are lowercase words joined by single dashes.`,179+ "",180+ `Next: ${inlineCode(`${Brand.cli} asks`)}`,181+ "",182+ ].join("\n"),183+ 404,184+ "no-store"185+ );186+187+/** Where an ask's Markdown lives: its page's URL with `.md`. */188+export const markdownPath = (project: string, ask: string) =>189+ `/${project}/asks/${ask}.md`;190+191+/** The `Link` header that names an ask page's Markdown as an alternate of it. */192+export const markdownAlternate = (project: string, ask: string) =>193+ `<${markdownPath(project, ask)}>; rel="alternate"; type="text/markdown"`;added:apps/web/src/features/ask/refused.tsx+40 added
12345678910111213141516171819202122232425262728293031323334353637383940/** * The page for an address that names no ask, or no answer: a 404 whose body * is the refusal the platform gave (`UnknownProject`, `UnknownAsk`), as * `git push` printed it, so a person reads what an agent reads in Markdown. * The refusals travel from the server in a not-found's data, encoded as * `Refusals`; the route decodes them (AGENTS.md principle 2). */import { Refusal } from "@repo/protocol/refusal";import { notFound } from "@tanstack/react-router";import { Effect, Schema } from "effect";import type { Array } from "effect";
import { EmptyState } from "../shared/empty.tsx";import { PageShell } from "../shared/layout.tsx";import { RefusalView } from "../shared/refusal.tsx";
/** Refusals as a not-found carries them. */export const Refusals = Schema.NonEmptyArray(Refusal);
/** A loader's 404 for `refusal`: a not-found that carries it, encoded, to the page. */export const notFoundFor = (refusal: Refusal) => Effect.flatMap(Schema.encodeEffect(Refusals)([refusal]), (data) => Effect.fail(notFound({ data })) );
export const NotFoundView = ({ refusals, title,}: { readonly refusals: Array.NonEmptyReadonlyArray<Refusal> | undefined; readonly title: string;}) => ( <PageShell title={title}> {refusals === undefined ? ( <EmptyState title="Nothing is at this address: a project's and an ask's names are lowercase words joined by single dashes." /> ) : ( <RefusalView refusals={refusals} /> )} </PageShell>);added:apps/web/src/routes/$project/answers/$ask.tsx+224 added
1+import { RegistryProvider, useAtomValue } from "@effect/atom-react";2+import { Client } from "@repo/protocol/contracts";3+import { Verdict } from "@repo/protocol/domain/answer";4+import { LandingView } from "@repo/protocol/domain/landing";5+import { Outcome } from "@repo/protocol/domain/outcome";6+import { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";7+import type { LandedSha } from "@repo/protocol/ids";8+import { createFileRoute, notFound } from "@tanstack/react-router";9+import { createServerFn } from "@tanstack/react-start";10+import { env } from "cloudflare:workers";11+import { DateTime, Effect, Option, Predicate, Schema } from "effect";12+import { AsyncResult, Atom } from "effect/reactivity";13+14+import { landingAtom, verdictAtom } from "../../../client/answer.ts";15+import { AnswerView } from "../../../features/answer/answer-page.tsx";16+import { answerPath } from "../../../features/ask/ask-page.tsx";17+import { CODE } from "../../../features/ask/fields.tsx";18+import {19+ NotFoundView,20+ notFoundFor,21+ Refusals,22+} from "../../../features/ask/refused.tsx";23+import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";24+import { serverClient } from "../../../server/client.ts";25+26+// The answer page: the latest verdict on an answer to an ask, stage by27+// stage, or with `?head=<sha>` the verdict on an earlier answer. A landed28+// answer shows its landing's credit trailers.29+30+/** The page's address, not yet decoded: the path's names and `?head=`. */31+interface AnswerAddress {32+ readonly ask: string;33+ readonly head?: string | undefined;34+ readonly project: string;35+}36+37+/** The address, decoded: names the platform could hold, and a commit id. */38+const AnswerPath = Schema.Struct({39+ ask: AskId,40+ head: Schema.optionalKey(CommitSha),41+ project: ProjectName,42+});43+44+/** What the page's loader carries from the server, encoded: whose answer, its verdict and landing, and when it was read. */45+const AnswerPageData = Schema.Struct({46+ ...AnswerPath.fields,47+ landing: Schema.UndefinedOr(LandingView),48+ now: Schema.DateTimeUtcFromString,49+ verdict: Schema.UndefinedOr(Verdict),50+});51+52+type AnswerPageData = typeof AnswerPageData.Type;53+54+/** The landing a verdict's answer made, when it landed. */55+const landedBy = (verdict: Verdict | undefined): LandedSha | undefined =>56+ verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome)57+ ? verdict.outcome.sha58+ : undefined;59+60+/** The verdict for the page and, if its answer landed, the landing; or a not-found carrying the refusal (a 404). */61+const readAnswer = ({ ask, head, project }: AnswerAddress) =>62+ Effect.gen(function* () {63+ const path = yield* Schema.decodeEffect(AnswerPath)(64+ head === undefined ? { ask, project } : { ask, head, project }65+ ).pipe(Effect.mapError(() => notFound()));66+67+ const client = yield* Client;68+69+ const { verdict } = yield* client.verdict(path).pipe(70+ Effect.catchTags({71+ UnknownAsk: notFoundFor,72+ UnknownProject: notFoundFor,73+ })74+ );75+76+ const sha = landedBy(verdict);77+78+ const landing =79+ sha === undefined80+ ? Option.none()81+ : yield* client.landing({ project: path.project, sha }).pipe(82+ Effect.map((found) => Option.some(found.landing)),83+ // The verdict names a landing the platform no longer finds: show the verdict alone.84+ Effect.catchTag("UnknownCommit", () => Effect.succeedNone)85+ );86+87+ return yield* Schema.encodeEffect(AnswerPageData)({88+ ...path,89+ landing: Option.getOrUndefined(landing),90+ now: yield* DateTime.now,91+ verdict,92+ });93+ });94+95+const answerPage = createServerFn({ method: "GET" })96+ .validator((address: AnswerAddress) => address)97+ .handler(({ data }) =>98+ Effect.runPromise(readAnswer(data).pipe(Effect.provide(serverClient(env))))99+ );100+101+/** The verdict with its landing's trailers, from the landing's atom (seeded when the loader read it). */102+const LandedAnswer = ({103+ now,104+ project,105+ seeded,106+ sha,107+ verdict,108+}: {109+ readonly now: DateTime.Utc;110+ readonly project: ProjectName;111+ readonly seeded: LandingView | undefined;112+ readonly sha: LandedSha;113+ readonly verdict: Verdict;114+}) => {115+ const fresh = Option.map(116+ AsyncResult.value(useAtomValue(landingAtom(project, sha))),117+ (found) => found.landing118+ );119+120+ const landing = Option.getOrElse(fresh, () =>121+ seeded?.sha === sha ? seeded : undefined122+ );123+124+ return landing === undefined ? (125+ <AnswerView now={now} verdict={verdict} />126+ ) : (127+ <AnswerView landing={landing} now={now} verdict={verdict} />128+ );129+};130+131+/** The page over the verdict's atom, which starts from what the loader read and refetches when its keys change. */132+const FreshAnswer = ({133+ atom,134+ read,135+}: {136+ readonly atom: ReturnType<typeof verdictAtom>;137+ readonly read: AnswerPageData;138+}) => {139+ const { verdict } = Option.getOrElse(140+ AsyncResult.value(useAtomValue(atom)),141+ () => read142+ );143+144+ const sha = landedBy(verdict);145+146+ return verdict === undefined || sha === undefined ? (147+ <AnswerView now={read.now} verdict={verdict} />148+ ) : (149+ <LandedAnswer150+ now={read.now}151+ project={read.project}152+ seeded={read.landing}153+ sha={sha}154+ verdict={verdict}155+ />156+ );157+};158+159+const LINK = "decoration-rule underline hover:decoration-current";160+161+const AnswerPage = () => {162+ const read = Schema.decodeSync(AnswerPageData)(Route.useLoaderData());163+ const { ask, head, landing, project, verdict } = read;164+ const atom = verdictAtom(project, ask, head);165+166+ const seeds = [167+ Atom.initialValue(168+ atom,169+ AsyncResult.success(verdict === undefined ? {} : { verdict })170+ ),171+ ...(landing === undefined172+ ? []173+ : [174+ Atom.initialValue(175+ landingAtom(project, landing.sha),176+ AsyncResult.success({ landing })177+ ),178+ ]),179+ ];180+181+ return (182+ <PageShell title={`Answer to ${ask}`}>183+ {head === undefined ? null : (184+ <p className="text-sm">185+ An earlier answer, at <code className={CODE}>{head.slice(0, 7)}</code>186+ .{" "}187+ <a className={LINK} href={answerPath(project, ask)}>188+ The latest answer189+ </a>190+ </p>191+ )}192+ <RegistryProvider193+ initialValues={seeds}194+ key={`${project}/${ask}/${head ?? ""}`}195+ >196+ <FreshAnswer atom={atom} read={read} />197+ </RegistryProvider>198+ </PageShell>199+ );200+};201+202+/** A not-found's refusals, decoded where they arrive; none when it carries none. */203+const decodeRefusals = Schema.decodeUnknownOption(Refusals);204+205+const AnswerNotFound = ({ data }: { readonly data?: unknown }) => (206+ <NotFoundView207+ refusals={Option.getOrUndefined(decodeRefusals(data))}208+ title="No such ask"209+ />210+);211+212+export const Route = createFileRoute("/$project/answers/$ask")({213+ // TanStack infers each option from the ones before it, so the search comes214+ // before the loader that reads it.215+ validateSearch: ({ head }: { readonly head?: unknown }) =>216+ Predicate.isString(head) ? { head } : {},217+ loaderDeps: ({ search }) => ({ head: search.head }),218+ loader: ({ deps, params }) => answerPage({ data: { ...params, ...deps } }),219+ head: ({ params }) => ({220+ meta: [{ title: pageTitle(`Answer to ${params.ask}`) }],221+ }),222+ component: AnswerPage,223+ notFoundComponent: AnswerNotFound,224+});added:apps/web/src/routes/$project/asks/{$ask}[.]md.ts+68 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import { Client, ShowAsk, Visibility } from "@repo/protocol/contracts";import { AskId, ProjectName } from "@repo/protocol/ids";import { createFileRoute } from "@tanstack/react-router";import { env } from "cloudflare:workers";import { Context, Effect, Option, Schema } from "effect";import type { Layer } from "effect";
import { askMarkdownResponse, noAskAt,} from "../../../features/ask/markdown.ts";import { serverClient } from "../../../server/client.ts";
// An ask as Markdown, always: `/<project>/asks/<ask>.md` (a literal `.` is// `[.]` in a route file's name; `{$ask}` keeps the param apart from it). The// ask page's own URL answers the same with `Accept: text/markdown`// (`$ask.tsx`), so a harness reads an ask with one plain fetch.
/** The path params an ask's routes are handed, not yet decoded. */export interface AskParams { readonly ask: string; readonly project: string;}
/** An ask's path, decoded: names the platform could hold. */export const AskPath = Schema.Struct({ ask: AskId, project: ProjectName });
/** The protocol client a route calls the platform with, for the request it answers. */export type ClientFor = (request: Request) => Layer.Layer<Client>;
/** `showAsk` is public, so its Markdown may be cached; the annotation says so, not this file. */const visibility = Context.get(ShowAsk.annotations, Visibility);
/** * The `.md` route's handler as a function of its client, which its test * drives with a stub platform: the brief `showAsk` gives, a refusal as a * 404, or a 404 without asking when the path can name no ask. */export const askMarkdownHandler = (clientFor: ClientFor) => ({ params, request, }: { readonly params: AskParams; readonly request: Request; }): Promise<Response> => Effect.runPromise( Option.match(Schema.decodeOption(AskPath)(params), { onNone: () => Effect.succeed(noAskAt(new URL(request.url).pathname)), onSome: (path) => Effect.flatMap(Effect.service(Client), (client) => client.showAsk(path) ).pipe( Effect.exit, Effect.map((exit) => askMarkdownResponse(exit, visibility)), Effect.provide(clientFor(request)) ), }) );
export const Route = createFileRoute("/$project/asks/{$ask}.md")({ server: { handlers: { GET: askMarkdownHandler((request) => serverClient(env, request)), }, },});added:apps/web/src/routes/$project/asks/$ask.tsx+174 added
1+import { RegistryProvider, useAtomValue } from "@effect/atom-react";2+import { Client } from "@repo/protocol/contracts";3+import { Ask } from "@repo/protocol/domain/ask";4+import { createFileRoute, getRouteApi, notFound } from "@tanstack/react-router";5+import { createServerFn } from "@tanstack/react-start";6+import { env } from "cloudflare:workers";7+import { DateTime, Effect, Option, Schema } from "effect";8+import { AsyncResult, Atom } from "effect/reactivity";9+10+import { askAtom } from "../../../client/ask.ts";11+import { AskView } from "../../../features/ask/ask-page.tsx";12+import {13+ markdownAlternate,14+ wantsMarkdown,15+} from "../../../features/ask/markdown.ts";16+import {17+ NotFoundView,18+ notFoundFor,19+ Refusals,20+} from "../../../features/ask/refused.tsx";21+import { pageTitle } from "../../../features/shared/layout.tsx";22+import { serverClient } from "../../../server/client.ts";23+import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";24+import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";25+26+// The ask page: the brief, its fields and the lines that take it. The same27+// URL answers `Accept: text/markdown` with the brief as Markdown (the GET28+// handler below), and its `.md` twin always does (`{$ask}[.]md.ts`).29+30+/**31+ * The ask page's GET, as a function of its client: a request that asks for32+ * Markdown gets the ask's Markdown, as at its `.md` URL; any other falls33+ * through to the page.34+ */35+export const askPageHandler =36+ (clientFor: ClientFor) =>37+ <Next,>({38+ next,39+ params,40+ request,41+ }: {42+ readonly next: () => Next;43+ readonly params: AskParams;44+ readonly request: Request;45+ }): Promise<Response> | Next =>46+ wantsMarkdown(request)47+ ? askMarkdownHandler(clientFor)({ params, request })48+ : next();49+50+/** The page's headers: its Markdown as an alternate, and that the URL answers by `Accept`. */51+export const askPageHeaders = ({ params }: { readonly params: AskParams }) => ({52+ link: markdownAlternate(params.project, params.ask),53+ vary: "Accept",54+});55+56+/** What the page's loader carries from the server, encoded: the ask, its brief, and when it was read. */57+const AskPageData = Schema.Struct({58+ ask: Ask,59+ brief: Schema.NonEmptyString,60+ now: Schema.DateTimeUtcFromString,61+});62+63+/** The ask for its page, or a not-found carrying the platform's refusal (a 404). */64+const readAsk = (params: AskParams) =>65+ Effect.gen(function* () {66+ const path = yield* Schema.decodeEffect(AskPath)(params).pipe(67+ Effect.mapError(() => notFound())68+ );69+70+ const client = yield* Client;71+72+ const read = yield* client.showAsk(path).pipe(73+ Effect.catchTags({74+ UnknownAsk: notFoundFor,75+ UnknownProject: notFoundFor,76+ })77+ );78+79+ return yield* Schema.encodeEffect(AskPageData)({80+ ...read,81+ now: yield* DateTime.now,82+ });83+ });84+85+const askPage = createServerFn({ method: "GET" })86+ .validator((params: AskParams) => params)87+ .handler(({ data }) =>88+ Effect.runPromise(readAsk(data).pipe(Effect.provide(serverClient(env))))89+ );90+91+const root = getRouteApi("__root__");92+93+type AskRead = Pick<typeof AskPageData.Type, "ask" | "brief">;94+95+/** The page over the ask's atom, which starts from what the loader read and refetches when its keys change. */96+const FreshAsk = ({97+ atom,98+ now,99+ platformUrl,100+ read,101+}: {102+ readonly atom: ReturnType<typeof askAtom>;103+ readonly now: DateTime.Utc;104+ readonly platformUrl: string;105+ readonly read: AskRead;106+}) => {107+ const { ask, brief } = Option.getOrElse(108+ AsyncResult.value(useAtomValue(atom)),109+ () => read110+ );111+112+ return (113+ <AskView ask={ask} brief={brief} now={now} platformUrl={platformUrl} />114+ );115+};116+117+const AskPage = () => {118+ const { platformUrl } = root.useLoaderData();119+120+ const { ask, brief, now } = Schema.decodeSync(AskPageData)(121+ Route.useLoaderData()122+ );123+124+ const atom = askAtom(ask.project, ask.id);125+126+ return (127+ <RegistryProvider128+ initialValues={[129+ Atom.initialValue(atom, AsyncResult.success({ ask, brief })),130+ ]}131+ key={`${ask.project}/${ask.id}`}132+ >133+ <FreshAsk134+ atom={atom}135+ now={now}136+ platformUrl={platformUrl}137+ read={{ ask, brief }}138+ />139+ </RegistryProvider>140+ );141+};142+143+/** A not-found's refusals, decoded where they arrive; none when it carries none. */144+const decodeRefusals = Schema.decodeUnknownOption(Refusals);145+146+const AskNotFound = ({ data }: { readonly data?: unknown }) => (147+ <NotFoundView148+ refusals={Option.getOrUndefined(decodeRefusals(data))}149+ title="No such ask"150+ />151+);152+153+export const Route = createFileRoute("/$project/asks/$ask")({154+ // TanStack infers each option from the ones before it: the loader comes155+ // first, so `head` reads its data.156+ loader: ({ params }) => askPage({ data: params }),157+ head: ({ loaderData }) => ({158+ meta: [159+ {160+ title: pageTitle(161+ loaderData === undefined ? "No such ask" : loaderData.ask.brief.want162+ ),163+ },164+ ],165+ }),166+ headers: askPageHeaders,167+ component: AskPage,168+ notFoundComponent: AskNotFound,169+ server: {170+ handlers: {171+ GET: askPageHandler((request) => serverClient(env, request)),172+ },173+ },174+});added:apps/web/test/answer.test.tsx+163 added
1+/**2+ * The answer page: the latest verdict on an ask's answer, stage by stage.3+ * The gate's stages in a strip, each lane's result and time, held-back4+ * checks only as one line per area (its counts and suite root, nothing5+ * more), the outcome, and a refusal as `git push` printed it. A landed6+ * answer shows its landing's credit trailers and the commit.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { Brand } from "@repo/brand";10+import { Outcome } from "@repo/protocol/domain/outcome";11+import { AreaName } from "@repo/protocol/ids";12+import { ChecksFailed, HeldBackFailed } from "@repo/protocol/refusal";13+import { explain } from "@repo/protocol/render";14+15+import {16+ AnswerView,17+ HeldBackBits,18+ LaneTable,19+} from "../src/features/answer/answer-page.tsx";20+import {21+ inOrder,22+ landedSha,23+ landing,24+ markupOf,25+ now,26+ suite,27+ textOf,28+ verdictOf,29+} from "./ask-fixtures.ts";30+31+const checksFailed = new ChecksFailed({32+ lane: "unit",33+ logRef: "logs/datekit/parse-iso-week/unit",34+ next: `${Brand.cli} evidence logs/datekit/parse-iso-week/unit`,35+});36+37+const heldBackFailed = new HeldBackFailed({ area: "export", suite });38+39+const refused = verdictOf(40+ Outcome.cases.Refused.make({ refusals: [checksFailed, heldBackFailed] })41+);42+43+/** Each element that names a stage, as `[stage, state]`. */44+const stagesOf = (markup: string) =>45+ [...markup.matchAll(/<li\b[^>]*>/gu)].flatMap(([tag]) => {46+ const stage = /data-stage="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;47+ const state = /data-state="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;48+49+ return stage === undefined || state === undefined ? [] : [[stage, state]];50+ });51+52+/** Each lane row, as `[lane, result]`. */53+const lanesOf = (markup: string) =>54+ [...markup.matchAll(/<tr\b[^>]*>/gu)].flatMap(([tag]) => {55+ const lane = /data-lane="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;56+ const result = /data-result="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;57+58+ return lane === undefined || result === undefined ? [] : [[lane, result]];59+ });60+61+describe(AnswerView, () => {62+ const page = <AnswerView now={now} verdict={refused} />;63+64+ it("shows the stages the answer passed, the one that refused it, and the ones it never reached", () => {65+ expect(stagesOf(markupOf(page))).toStrictEqual([66+ ["parse", "passed"],67+ ["shape", "passed"],68+ ["merge", "passed"],69+ ["cheap", "passed"],70+ ["checks", "refused"],71+ ["heldBack", "pending"],72+ ["human", "pending"],73+ ]);74+ });75+76+ it("shows each lane with its result", () => {77+ expect(lanesOf(markupOf(page))).toStrictEqual([78+ ["lint", "passed"],79+ ["unit", "failed"],80+ ]);81+ expect(82+ inOrder(textOf(page), ["lint", "passed", "unit", "failed"])83+ ).toBeTruthy();84+ });85+86+ it("shows held-back checks only as an area's counts and its suite root", () => {87+ expect(textOf(page)).toContain(`export 6/7 @ ${suite}`);88+ });89+90+ it("shows the refusals' explain lines in order, as git printed them", () => {91+ expect(92+ inOrder(93+ textOf(page),94+ explain([checksFailed, heldBackFailed]).map((line) => line.trim())95+ )96+ ).toBeTruthy();97+ });98+99+ it("never shows where a lane's log is kept outside the refusal that names it", () => {100+ const passing = verdictOf(Outcome.cases.Checking.make({ stage: "checks" }));101+102+ expect(textOf(<AnswerView now={now} verdict={passing} />)).not.toContain(103+ "logs/datekit"104+ );105+ });106+107+ it("names the answer it judged and when", () => {108+ const text = textOf(page);109+110+ expect(text).toContain("bbbbbbb");111+ expect(text).toContain("aaaaaaa");112+ expect(text).toContain("redThenGreen@0.0.0+5e1d");113+ expect(text).toContain("20 min ago");114+ });115+116+ it("says plainly when no answer has been checked yet", () => {117+ const text = textOf(<AnswerView now={now} verdict={undefined} />);118+119+ expect(text).toContain("No answer to this ask has been checked yet");120+ expect(text).not.toContain("Parse");121+ });122+123+ it("shows a landed answer's credit trailers in trailer order, its held-back trailer, and its commit", () => {124+ const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));125+ const element = <AnswerView landing={landing} now={now} verdict={landed} />;126+ const text = textOf(element);127+128+ expect(text).toContain("Landed as 9b1c3e5");129+ expect(130+ inOrder(text, ["Asked-by: ines-v", "Signed-off-by: okafor"])131+ ).toBeTruthy();132+ expect(text).toContain(`Held-back: export 7/7 @ ${suite}`);133+ expect(text).toContain("Assisted-by: claude-code:opus-5 (verified)");134+ expect(text).toContain(`git show ${landedSha}`);135+ });136+});137+138+describe(LaneTable, () => {139+ it("gives each lane's command and how long it ran", () => {140+ const { lanes } = refused;141+ const text = textOf(<LaneTable lanes={lanes} />);142+143+ expect(inOrder(text, ["lint", "bun run lint", "1.2 s"])).toBeTruthy();144+ expect(inOrder(text, ["unit", "bun test", "8.3 s"])).toBeTruthy();145+ });146+147+ it("says when no lane ran", () => {148+ expect(textOf(<LaneTable lanes={[]} />)).toContain("No lane ran");149+ });150+});151+152+describe(HeldBackBits, () => {153+ it("shows one line per area, and nothing else about the held-back checks", () => {154+ const results = [155+ { area: AreaName.make("export"), passed: 6, suite, total: 7 },156+ { area: AreaName.make("parse"), passed: 3, suite, total: 3 },157+ ];158+159+ expect(textOf(<HeldBackBits results={results} />).trim()).toBe(160+ `export 6/7 @ ${suite} parse 3/3 @ ${suite}`161+ );162+ });163+});added:apps/web/test/ask-fixtures.ts+173 added
1+/**2+ * datekit's `parse-iso-week` (a fictional ask in a fictional project), and3+ * the answers to it, as the platform's contracts return them: the ask and4+ * its brief (`showAsk`), a verdict (`verdict`) and a landing (`landing`).5+ * Also how the view tests read rendered markup.6+ */7+import { Brand } from "@repo/brand";8+import type { Verdict } from "@repo/protocol/domain/answer";9+import type { Ask } from "@repo/protocol/domain/ask";10+import { CheckSpec } from "@repo/protocol/domain/check";11+import { Glob } from "@repo/protocol/domain/common";12+import type { LandingView } from "@repo/protocol/domain/landing";13+import type { Outcome } from "@repo/protocol/domain/outcome";14+import {15+ AreaName,16+ AskId,17+ CheckVersion,18+ CommitSha,19+ Handle,20+ KindName,21+ LandedSha,22+ LaneName,23+ PatchId,24+ ProjectName,25+ RepoPath,26+ SuiteRoot,27+ TreeSha,28+} from "@repo/protocol/ids";29+import { DateTime } from "effect";30+import type { ReactElement } from "react";31+import { renderToStaticMarkup } from "react-dom/server";32+33+export const project = ProjectName.make("datekit");34+35+export const askId = AskId.make("parse-iso-week");36+37+/** The moment every view test renders at. */38+export const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");39+40+export const ask: Ask = {41+ askedBy: Handle.make("ines-v"),42+ blockedBy: [],43+ brief: {44+ context: [45+ "ISO 8601 numbers weeks from the Monday of the week holding 4 January.",46+ ],47+ current: "parseWeek returns null for 2026-W41-3.",48+ outOfScope: ["Formatting week dates back to strings."],49+ terms: ["Week date: a date written as year, week and weekday."],50+ want: "Parse ISO week dates like 2026-W41-3",51+ },52+ check: CheckSpec.cases.RedThenGreen.make({53+ path: RepoPath.make("test/parse-week.test.ts"),54+ }),55+ file: RepoPath.make(`${Brand.configDir}/asks/parse-iso-week.ask.ts`),56+ id: askId,57+ kind: KindName.make("fix"),58+ openedAt: DateTime.makeUnsafe("2026-10-05T12:00:00Z"),59+ openedIn: LandedSha.make("1f3a5b7c9d1e3f5a7b9c1d3e5f7a9b1c3d5e7f9a"),60+ project,61+ state: "open",62+ territory: {63+ module: "@datekit/parse",64+ paths: [Glob.make("packages/parse/**")],65+ },66+};67+68+/** The brief as the platform renders it for `showAsk`; the web serves it untouched. */69+export const brief = `# Parse ISO week dates like 2026-W41-370+71+Ask \`parse-iso-week\` in datekit, a \`fix\` ask from ines-v.72+73+## Territory74+75+The module \`@datekit/parse\`: \`packages/parse/**\`.76+77+## Current78+79+parseWeek returns null for 2026-W41-3.80+`;81+82+const sha = (digit: string) => digit.repeat(40);83+84+export const suite = SuiteRoot.make(`sha256:${"4f2a".repeat(16)}`);85+86+export const landedSha = LandedSha.make(87+ "9b1c3e5d7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c"88+);89+90+/** A verdict on the ask's latest answer: lint passed, unit failed, one held-back area 6 of 7. */91+export const verdictOf = (outcome: Outcome): Verdict => ({92+ ask: askId,93+ at: DateTime.makeUnsafe("2026-10-07T11:40:00Z"),94+ base: CommitSha.make(sha("a")),95+ checkVersion: CheckVersion.make("redThenGreen@0.0.0+5e1d"),96+ head: CommitSha.make(sha("b")),97+ heldBack: [{ area: AreaName.make("export"), passed: 6, suite, total: 7 }],98+ lanes: [99+ {100+ command: "bun run lint",101+ durationMs: 1240,102+ lane: LaneName.make("lint"),103+ result: "passed",104+ },105+ {106+ command: "bun test",107+ durationMs: 8312,108+ lane: LaneName.make("unit"),109+ logRef: "logs/datekit/parse-iso-week/unit",110+ result: "failed",111+ },112+ ],113+ outcome,114+ patchId: PatchId.make("c".repeat(64)),115+ project,116+ stage: "checks",117+ tree: TreeSha.make(sha("d")),118+ verifier: "platform",119+});120+121+export const landing: LandingView = {122+ ask: askId,123+ assisted: [{ harness: "claude-code", model: "opus-5", verified: true }],124+ author: Handle.make("okafor"),125+ credits: [126+ { handle: Handle.make("okafor"), role: "Signed-off-by" },127+ { handle: Handle.make("ines-v"), role: "Asked-by" },128+ ],129+ heldBackTrailer: `export 7/7 @ ${suite}`,130+ landedAt: DateTime.makeUnsafe("2026-10-07T11:45:00Z"),131+ parent: LandedSha.make(sha("a")),132+ project,133+ sha: landedSha,134+};135+136+/** The entities React writes for text, and what each reads as. */137+const ENTITIES: ReadonlyMap<string, string> = new Map([138+ ["'", "'"],139+ ["&", "&"],140+ [">", ">"],141+ ["<", "<"],142+ [""", '"'],143+]);144+145+export const markupOf = (element: ReactElement) =>146+ renderToStaticMarkup(element);147+148+/** What a reader sees: the markup without its tags, entities decoded. */149+export const textOf = (element: ReactElement) =>150+ markupOf(element)151+ .replaceAll(/<[^>]+>/gu, " ")152+ .replaceAll(153+ /&(?:#x27|amp|gt|lt|quot);/gu,154+ (entity) => ENTITIES.get(entity) ?? entity155+ )156+ .replaceAll(/\s+/gu, " ");157+158+/** Whether each of `parts` appears in `text`, each after the one before. */159+export const inOrder = (text: string, parts: readonly string[]) => {160+ let from = 0;161+162+ for (const part of parts) {163+ const at = text.indexOf(part, from);164+165+ if (at === -1) {166+ return false;167+ }168+169+ from = at + part.length;170+ }171+172+ return true;173+};added:apps/web/test/ask-markdown.test.ts+324 added
1+/**2+ * An ask answers as Markdown, so a harness reads it with one plain fetch:3+ * the ask's URL with `Accept: text/markdown`, or the same URL with `.md`.4+ * The body is the brief the platform rendered (`showAsk`), untouched; an5+ * unknown ask is a 404 whose body is the refusal, as git would print it.6+ * A browser asking for HTML gets the page.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { Brand } from "@repo/brand";10+import { Client, Contracts } from "@repo/protocol/contracts";11+import { AskId, ProjectName } from "@repo/protocol/ids";12+import { UnknownAsk, UnknownProject } from "@repo/protocol/refusal";13+import { explain } from "@repo/protocol/render";14+import { asTester, unanswered } from "@repo/protocol/testing";15+import { Effect, Layer, Ref } from "effect";16+import { RpcTest } from "effect/rpc";17+18+import {19+ refusalsMarkdown,20+ wantsMarkdown,21+} from "../src/features/ask/markdown.ts";22+import {23+ askPageHandler,24+ askPageHeaders,25+} from "../src/routes/$project/asks/$ask.tsx";26+import { askMarkdownHandler } from "../src/routes/$project/asks/{$ask}[.]md.ts";27+import { ask, askId, brief, project } from "./ask-fixtures.ts";28+29+const WEB = "https://web-test.example.workers.dev";30+31+const MARKDOWN = "text/markdown; charset=utf-8";32+33+const BROWSER =34+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";35+36+/**37+ * A platform that knows datekit and its one ask, counting `showAsk` calls,38+ * as a route's client.39+ */40+const platformOf = (calls: Ref.Ref<number>) => () =>41+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(42+ Layer.provide([43+ Layer.mergeAll(44+ unanswered,45+ Contracts.toLayerHandler("showAsk", (payload) =>46+ Effect.gen(function* () {47+ yield* Ref.update(calls, (count) => count + 1);48+49+ if (payload.project !== project) {50+ return yield* new UnknownProject({ project: payload.project });51+ }52+53+ if (payload.ask !== askId) {54+ return yield* new UnknownAsk({ ask: payload.ask });55+ }56+57+ return { ask, brief };58+ })59+ )60+ ),61+ asTester,62+ ])63+ );64+65+/** A platform that cannot be reached: every call dies on the way. */66+const unreachable = () =>67+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(68+ Layer.provide([unanswered, asTester])69+ );70+71+const get = (path: string, accept?: string) =>72+ new Request(`${WEB}${path}`, {73+ headers: accept === undefined ? {} : { accept },74+ });75+76+const params = (askName: string, projectName: string = project) => ({77+ ask: askName,78+ project: projectName,79+});80+81+/** What a response says, read whole. */82+const read = (response: Response) =>83+ Effect.map(84+ Effect.promise(() => response.text()),85+ (body) => ({86+ body,87+ cacheControl: response.headers.get("cache-control"),88+ contentType: response.headers.get("content-type"),89+ status: response.status,90+ vary: response.headers.get("vary"),91+ })92+ );93+94+/** The page's own render, which a Markdown request must never reach. */95+const PAGE = new Response("<!doctype html><title>the page</title>");96+97+describe("an ask's URL with Accept: text/markdown", () => {98+ it.effect(99+ "answers with the brief showAsk gives, as Markdown that public caches may keep a minute",100+ () =>101+ Effect.gen(function* () {102+ const calls = yield* Ref.make(0);103+104+ const response = yield* Effect.promise(() =>105+ Promise.resolve(106+ askPageHandler(platformOf(calls))({107+ next: () => PAGE,108+ params: params(askId),109+ request: get(`/datekit/asks/${askId}`, "text/markdown"),110+ })111+ )112+ );113+114+ expect(yield* read(response)).toStrictEqual({115+ body: brief,116+ cacheControl: "public, max-age=60",117+ contentType: MARKDOWN,118+ status: 200,119+ vary: "Accept",120+ });121+ expect(yield* Ref.get(calls)).toBe(1);122+ })123+ );124+125+ it.effect(126+ "falls through to the page when the reader asks for HTML, and reads no ask",127+ () =>128+ Effect.gen(function* () {129+ const calls = yield* Ref.make(0);130+131+ const answered = askPageHandler(platformOf(calls))({132+ next: () => PAGE,133+ params: params(askId),134+ request: get(`/datekit/asks/${askId}`, BROWSER),135+ });136+137+ expect(answered).toBe(PAGE);138+ expect(yield* Ref.get(calls)).toBe(0);139+ })140+ );141+});142+143+describe("an ask's .md URL", () => {144+ it.effect(145+ "answers with the same Markdown, whatever the request accepts",146+ () =>147+ Effect.gen(function* () {148+ const calls = yield* Ref.make(0);149+150+ const response = yield* Effect.promise(() =>151+ askMarkdownHandler(platformOf(calls))({152+ params: params(askId),153+ request: get(`/datekit/asks/${askId}.md`, BROWSER),154+ })155+ );156+157+ expect(yield* read(response)).toStrictEqual({158+ body: brief,159+ cacheControl: "public, max-age=60",160+ contentType: MARKDOWN,161+ status: 200,162+ vary: "Accept",163+ });164+ })165+ );166+167+ it.effect(168+ "answers an unknown ask with 404 and the UnknownAsk refusal, as git prints it, then its next command",169+ () =>170+ Effect.gen(function* () {171+ const calls = yield* Ref.make(0);172+ const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });173+174+ const response = yield* Effect.promise(() =>175+ askMarkdownHandler(platformOf(calls))({176+ params: params("no-such-ask"),177+ request: get("/datekit/asks/no-such-ask.md"),178+ })179+ );180+181+ const seen = yield* read(response);182+183+ expect(seen.status).toBe(404);184+ expect(seen.contentType).toBe(MARKDOWN);185+ expect(seen.body).toBe(186+ [187+ "```text",188+ ...explain([refusal]),189+ "```",190+ "",191+ `Next: \`${Brand.cli} asks\``,192+ "",193+ ].join("\n")194+ );195+ expect(seen.cacheControl).toBe("no-store");196+ })197+ );198+199+ it.effect(200+ "answers an unknown project with 404 and the UnknownProject refusal",201+ () =>202+ Effect.gen(function* () {203+ const calls = yield* Ref.make(0);204+205+ const response = yield* Effect.promise(() =>206+ askMarkdownHandler(platformOf(calls))({207+ params: params(askId, "nowhere"),208+ request: get(`/nowhere/asks/${askId}.md`),209+ })210+ );211+212+ const seen = yield* read(response);213+214+ expect(seen.status).toBe(404);215+ expect(seen.body).toBe(216+ refusalsMarkdown([217+ new UnknownProject({ project: ProjectName.make("nowhere") }),218+ ])219+ );220+ expect(seen.body).toContain(221+ "UnknownProject: no project is named nowhere"222+ );223+ })224+ );225+226+ it.effect(227+ "answers a path that can name no ask with 404, and asks the platform nothing",228+ () =>229+ Effect.gen(function* () {230+ const calls = yield* Ref.make(0);231+232+ const response = yield* Effect.promise(() =>233+ askMarkdownHandler(platformOf(calls))({234+ params: params("Not_An-Ask"),235+ request: get("/datekit/asks/Not_An-Ask.md"),236+ })237+ );238+239+ const seen = yield* read(response);240+241+ expect(seen.status).toBe(404);242+ expect(seen.contentType).toBe(MARKDOWN);243+ expect(seen.body).toContain("Not_An-Ask");244+ expect(yield* Ref.get(calls)).toBe(0);245+ })246+ );247+248+ it.effect(249+ "answers 502 when the platform does not answer, and keeps it out of caches",250+ () =>251+ Effect.gen(function* () {252+ const response = yield* Effect.promise(() =>253+ askMarkdownHandler(unreachable)({254+ params: params(askId),255+ request: get(`/datekit/asks/${askId}.md`),256+ })257+ );258+259+ const seen = yield* read(response);260+261+ expect(seen.status).toBe(502);262+ expect(seen.contentType).toBe(MARKDOWN);263+ expect(seen.cacheControl).toBe("no-store");264+ })265+ );266+});267+268+describe("the ask page", () => {269+ it("names its Markdown as an alternate, and says it varies by Accept", () => {270+ expect(askPageHeaders({ params: params(askId) })).toStrictEqual({271+ link: `</datekit/asks/${askId}.md>; rel="alternate"; type="text/markdown"`,272+ vary: "Accept",273+ });274+ });275+});276+277+describe(refusalsMarkdown, () => {278+ it("sets every refusal's explain lines in one text block, then each distinct next command once", () => {279+ const refusals = [280+ new UnknownProject({ project: ProjectName.make("nowhere") }),281+ new UnknownAsk({ ask: askId }),282+ ] as const;283+284+ expect(refusalsMarkdown(refusals)).toBe(285+ [286+ "```text",287+ ...explain(refusals),288+ "```",289+ "",290+ `Next: \`${Brand.cli} asks\``,291+ "",292+ ].join("\n")293+ );294+ });295+});296+297+const accepting = (accept: string | undefined) =>298+ wantsMarkdown(get("/datekit/asks/parse-iso-week", accept));299+300+describe(wantsMarkdown, () => {301+ it.each([302+ ["text/markdown"],303+ ["text/markdown, text/html"],304+ ["text/html;q=0.9, text/markdown"],305+ ["text/markdown;q=0.8, */*;q=0.1"],306+ ["Text/Markdown; charset=utf-8"],307+ ])("serves Markdown to %o", (accept) => {308+ expect(accepting(accept)).toBeTruthy();309+ });310+311+ it.each([312+ [undefined],313+ ["*/*"],314+ ["text/*"],315+ ["text/html"],316+ [BROWSER],317+ ["text/markdown;q=0.5, text/html"],318+ ["text/markdown;q=0, text/html;q=0.1"],319+ ["text/markdown;q=0"],320+ ["application/json"],321+ ])("serves the page to %o", (accept) => {322+ expect(accepting(accept)).toBeFalsy();323+ });324+});added:apps/web/test/ask.test.tsx+196 added
1+/**2+ * The ask page, as a person reads it: the brief (want, current behaviour,3+ * out of scope, terms, context), its kind, territory, check and state, who4+ * asked, its parent and blockers, and the exact lines that clone, claim and5+ * check it. Rendered to HTML with `react-dom/server`.6+ */7+import { describe, expect, it } from "@effect/vitest";8+import { Brand } from "@repo/brand";9+import { AskId, Handle } from "@repo/protocol/ids";10+import { UnknownAsk } from "@repo/protocol/refusal";11+import { explain } from "@repo/protocol/render";12+import { Schema } from "effect";13+14+import { AskView } from "../src/features/ask/ask-page.tsx";15+import { NotFoundView, Refusals } from "../src/features/ask/refused.tsx";16+import {17+ ask,18+ askId,19+ brief,20+ inOrder,21+ markupOf,22+ now,23+ textOf,24+} from "./ask-fixtures.ts";25+26+const platformUrl = "https://platform-test.example.workers.dev";27+28+const page = (shown = ask) => (29+ <AskView ask={shown} brief={brief} now={now} platformUrl={platformUrl} />30+);31+32+describe(AskView, () => {33+ it("titles the page with the want, then reads the brief's sections in order", () => {34+ const markup = markupOf(page());35+36+ expect(markup).toMatch(37+ /<h1\b[^>]*>Parse ISO week dates like 2026-W41-3<\/h1>/u38+ );39+ expect(40+ inOrder(textOf(page()), [41+ "Current behaviour",42+ "parseWeek returns null for 2026-W41-3.",43+ "Out of scope",44+ "Formatting week dates back to strings.",45+ "Terms",46+ "Week date: a date written as year, week and weekday.",47+ "Context",48+ "ISO 8601 numbers weeks from the Monday of the week holding 4 January.",49+ ])50+ ).toBeTruthy();51+ });52+53+ it("leaves out a section the brief does not have", () => {54+ const text = textOf(55+ page({ ...ask, brief: { want: "Parse ISO week dates like 2026-W41-3" } })56+ );57+58+ expect(text).not.toContain("Current behaviour");59+ expect(text).not.toContain("Out of scope");60+ expect(text).not.toContain("Terms");61+ });62+63+ it("gives the ask's name, kind, state and check", () => {64+ expect(65+ inOrder(textOf(page()), [66+ "Ask",67+ askId,68+ "State",69+ "Open",70+ "Kind",71+ "fix",72+ "Check",73+ "test/parse-week.test.ts",74+ ])75+ ).toBeTruthy();76+ });77+78+ it("gives the ask's territory, and who asked it when", () => {79+ const text = textOf(page());80+81+ expect(82+ inOrder(text, ["Asked by", "ines-v", "opened 2 d ago"])83+ ).toBeTruthy();84+ expect(85+ inOrder(text, ["Territory", "@datekit/parse", "packages/parse/**"])86+ ).toBeTruthy();87+ expect(markupOf(page())).toContain('href="/people/ines-v"');88+ });89+90+ it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {91+ expect(92+ inOrder(textOf(page()), [93+ `git clone ${platformUrl}/datekit.git`,94+ `${Brand.cli} claim ${askId} --project datekit`,95+ `${Brand.cli} check --ask ${askId}`,96+ ])97+ ).toBeTruthy();98+ });99+100+ it("names the asks a blocked ask waits on, each linking to its page", () => {101+ const blocked = {102+ ...ask,103+ blockedBy: [AskId.make("split-format"), AskId.make("split-parse")],104+ };105+106+ const text = textOf(page(blocked));107+ const markup = markupOf(page(blocked));108+109+ expect(110+ inOrder(text, [111+ "Waits on",112+ "split-format",113+ "split-parse",114+ "to land first",115+ ])116+ ).toBeTruthy();117+ expect(markup).toContain('href="/datekit/asks/split-format"');118+ expect(markup).toContain('href="/datekit/asks/split-parse"');119+ });120+121+ it("names nothing it waits on when nothing blocks it", () => {122+ expect(textOf(page())).not.toContain("Waits on");123+ });124+125+ it("links a step of a migrate to its parent ask", () => {126+ const child = { ...ask, parent: AskId.make("migrate-week-api") };127+128+ expect(markupOf(page(child))).toContain(129+ 'href="/datekit/asks/migrate-week-api"'130+ );131+ });132+133+ it("says when an ask is held for newcomers, and who mentors them", () => {134+ const held = {135+ ...ask,136+ mentor: Handle.make("okonkwo"),137+ reserve: "newcomers" as const,138+ };139+140+ const text = textOf(page(held));141+142+ expect(text).toContain("Held for newcomers");143+ expect(markupOf(page(held))).toContain('href="/people/okonkwo"');144+ });145+146+ it("gives no claim line once the ask is closed", () => {147+ const text = textOf(page({ ...ask, state: "closed" }));148+149+ expect(text).toContain("Closed");150+ expect(text).not.toContain(`${Brand.cli} claim`);151+ });152+153+ it("links to the ask's Markdown and to the verdict on its latest answer", () => {154+ const markup = markupOf(page());155+156+ expect(markup).toContain(`href="/datekit/asks/${askId}.md"`);157+ expect(markup).toContain(`href="/datekit/answers/${askId}"`);158+ });159+160+ it("shows the brief exactly as an agent reads it", () => {161+ expect(textOf(page())).toContain(162+ textOf(<pre>{brief}</pre>)163+ .trim()164+ .slice(0, 60)165+ );166+ });167+});168+169+describe(NotFoundView, () => {170+ it("shows the refusal a not-found carried from the server, as git printed it", () => {171+ const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });172+173+ // The refusal crosses from the server encoded, as a loader's not-found carries it.174+ const carried = Schema.decodeUnknownSync(Refusals)(175+ structuredClone(Schema.encodeSync(Refusals)([refusal]))176+ );177+178+ const text = textOf(179+ <NotFoundView refusals={carried} title="No such ask" />180+ );181+182+ expect(183+ inOrder(text, [184+ "No such ask",185+ ...explain([refusal]).map((line) => line.trim()),186+ `${Brand.cli} asks`,187+ ])188+ ).toBeTruthy();189+ });190+191+ it("says nothing is at an address that names no ask at all", () => {192+ expect(193+ textOf(<NotFoundView refusals={undefined} title="No such ask" />)194+ ).toContain("Nothing is at this address");195+ });196+});