Merge build/512-web-ask-answer-markdown
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 61e69c9, 88a09d9 · Browse files · 14 files·+2549 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+2549 added−0 removed
- tests:+1142 added−0 removed
- other:+1407 added−0 removed
Provenance
- Commit
f55adf5- Tree
fd6f26a- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
61e69c9- Parent 2
88a09d9
14 files changed+2549 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+251 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, LINK, 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+export const AnswerView = ({167+ landing,168+ now,169+ verdict,170+}: {171+ readonly landing?: LandingView;172+ readonly now: DateTime.Utc;173+ readonly verdict: Verdict | undefined;174+}) => {175+ if (verdict === undefined) {176+ return <EmptyState title="No answer to this ask has been checked yet." />;177+ }178+179+ return (180+ <>181+ <Fields label="What was judged">182+ <Field label="Ask">183+ <a184+ className={`${LINK} ${CODE}`}185+ href={askPath(verdict.project, verdict.ask)}186+ >187+ {verdict.ask}188+ </a>189+ </Field>190+ <Field label="Judged">191+ <When at={verdict.at} now={now} />{" "}192+ <span className="text-muted-foreground">193+ by the {verdict.verifier}194+ </span>195+ </Field>196+ <Field label="Head">197+ <Sha sha={verdict.head} />198+ </Field>199+ <Field label="Base">200+ <Sha sha={verdict.base} />201+ </Field>202+ <Field label="Merged tree">203+ <Sha sha={verdict.tree} />204+ </Field>205+ <Field label="Patch id">206+ <Sha sha={verdict.patchId} />207+ </Field>208+ <Field label="Check version">209+ <code className={CODE}>{verdict.checkVersion}</code>210+ </Field>211+ </Fields>212+213+ <Region id="answer-gate" title="Gate">214+ <StageStrip outcome={verdict.outcome} stage={verdict.stage} />215+ <OutcomeView outcome={verdict.outcome} />216+ </Region>217+218+ <Region id="answer-lanes" title="Lanes">219+ <LaneTable lanes={verdict.lanes} />220+ </Region>221+222+ {verdict.heldBack.length === 0 ? null : (223+ <Region id="answer-held-back" title="Held-back checks">224+ <p className="text-muted-foreground max-w-[70ch] text-sm">225+ Checks the answer could not see. Each area shows how many passed,226+ and the root of the suite the project committed to before the claim.227+ </p>228+ <HeldBackBits results={verdict.heldBack} />229+ </Region>230+ )}231+232+ {landing === undefined ? null : (233+ <Region id="answer-landing" title="Landing">234+ <CreditTrailers235+ assisted={landing.assisted}236+ credits={landing.credits}237+ {...(landing.heldBackTrailer === undefined238+ ? {}239+ : { heldBack: landing.heldBackTrailer })}240+ />241+ <div className="flex min-w-0 flex-col gap-1.5">242+ <span className="text-muted-foreground text-xs font-medium">243+ The landing commit, in a clone of {landing.project}244+ </span>245+ <CommandLine command={`git show ${landing.sha}`} />246+ </div>247+ </Region>248+ )}249+ </>250+ );251+};added:apps/web/src/features/ask/ask-page.tsx+326 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, LINK, 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+/** Each state as a mark, a word and its role colour (none for open: nothing is happening yet). */34+const states = {35+ claimed: { icon: CircleDot, tone: "", word: "Claimed" },36+ closed: { icon: Minus, tone: "text-muted-foreground", word: "Closed" },37+ open: { icon: Circle, tone: "", word: "Open" },38+ waitingOnParent: {39+ icon: Hourglass,40+ tone: "text-waiting",41+ word: "Waiting on its parent",42+ },43+} as const satisfies Record<44+ AskState,45+ { readonly icon: LucideIcon; readonly tone: string; readonly word: string }46+>;47+48+const StateMark = ({ state }: { readonly state: AskState }) => {49+ const { icon: Icon, tone, word } = states[state];50+51+ return (52+ <span className={`font-medium ${tone}`}>53+ <Icon54+ aria-hidden="true"55+ className="mr-1.5 inline-block size-3.5 align-[-0.15em]"56+ />57+ {word}58+ </span>59+ );60+};61+62+const Code = ({ children }: { readonly children: ReactNode }) => (63+ <code className={CODE}>{children}</code>64+);65+66+/** What judges an answer: the check's kind in words, then what it names. */67+const checkOf = (check: CheckSpec) =>68+ CheckSpec.match(check, {69+ LintToZero: ({ rule, territory }) => (70+ <>71+ Lint to zero: <Code>{rule}</Code>72+ {territory === undefined ? null : (73+ <>74+ {" "}75+ in <Code>{territory}</Code>76+ </>77+ )}78+ </>79+ ),80+ Migrate: ({ from, to }) => (81+ <>82+ Migrate: <Code>{from}</Code>83+ {to === undefined ? null : (84+ <>85+ {" "}86+ to <Code>{to}</Code>87+ </>88+ )}89+ </>90+ ),91+ Ratchet: ({ ratchet }) => (92+ <>93+ Ratchet <Code>{ratchet}</Code> goes down94+ </>95+ ),96+ RedThenGreen: ({ path }) => (97+ <>98+ Red, then green: <Code>{path}</Code>99+ </>100+ ),101+ SymbolAbsent: ({ symbol }) => (102+ <>103+ Nothing uses <Code>{symbol}</Code>104+ </>105+ ),106+ });107+108+/** Asks, each linking to its page, separated by commas. */109+const AskLinks = ({110+ asks,111+ project,112+}: {113+ readonly asks: readonly AskId[];114+ readonly project: ProjectName;115+}) =>116+ asks.map((ask, index) => (117+ <span key={ask}>118+ {index === 0 ? null : ", "}119+ <a className={`${LINK} ${CODE}`} href={askPath(project, ask)}>120+ {ask}121+ </a>122+ </span>123+ ));124+125+const reserved = {126+ newcomers: "Held for newcomers",127+ people: "Held for a person to answer, not an agent",128+} as const;129+130+const BriefPart = ({131+ children,132+ title,133+}: {134+ readonly children: ReactNode;135+ readonly title: string;136+}) => (137+ <div className="flex flex-col gap-1.5">138+ <h3 className="text-sm font-semibold">{title}</h3>139+ {children}140+ </div>141+);142+143+const BriefList = ({ items }: { readonly items: readonly string[] }) => (144+ <ul className="flex list-[square] flex-col gap-1 pl-5 marker:text-[color:var(--rule-strong)]">145+ {items.map((item) => (146+ <li key={item}>{item}</li>147+ ))}148+ </ul>149+);150+151+/** The lines that start an answer: clone, claim (it prints the fork's remote), check before the push. */152+const TakeIt = ({153+ ask,154+ platformUrl,155+}: {156+ readonly ask: Ask;157+ readonly platformUrl: string;158+}) => {159+ if (ask.state === "closed") {160+ return (161+ <p className="text-muted-foreground text-sm">162+ This ask is closed, so it takes no claim.163+ </p>164+ );165+ }166+167+ const steps = [168+ ["Clone the project", `git clone ${platformUrl}/${ask.project}.git`],169+ [170+ "Claim the ask; the claim prints your fork's remote",171+ `${Brand.cli} claim ${ask.id} --project ${ask.project}`,172+ ],173+ [174+ "Check your answer before you push it",175+ `${Brand.cli} check --ask ${ask.id}`,176+ ],177+ ] as const;178+179+ return (180+ <ol className="flex flex-col gap-3">181+ {steps.map(([label, command]) => (182+ <li className="flex min-w-0 flex-col gap-1.5" key={command}>183+ <span className="text-muted-foreground text-xs font-medium">184+ {label}185+ </span>186+ <CommandLine command={command} />187+ </li>188+ ))}189+ </ol>190+ );191+};192+193+export const AskView = ({194+ ask,195+ brief,196+ now,197+ platformUrl,198+}: {199+ readonly ask: Ask;200+ readonly brief: string;201+ readonly now: DateTime.Utc;202+ readonly platformUrl: string;203+}) => {204+ const { context, current, outOfScope, terms } = ask.brief;205+206+ return (207+ <PageShell title={ask.brief.want}>208+ <Fields label="The ask">209+ <Field label="Ask">210+ <Code>{ask.id}</Code>211+ </Field>212+ <Field label="State">213+ <StateMark state={ask.state} />214+ </Field>215+ <Field label="Kind">216+ <Code>{ask.kind}</Code>217+ </Field>218+ <Field label="Asked by">219+ <HandleLink handle={ask.askedBy} />{" "}220+ <span className="text-muted-foreground">221+ · opened <When at={ask.openedAt} now={now} />222+ </span>223+ </Field>224+ <Field label="Territory">225+ <Code>{ask.territory.module}</Code>226+ <span className="text-muted-foreground">: </span>227+ {ask.territory.paths.map((path, index) => (228+ <span key={path}>229+ {index === 0 ? null : ", "}230+ <Code>{path}</Code>231+ </span>232+ ))}233+ </Field>234+ <Field label="Check">{checkOf(ask.check)}</Field>235+ {ask.parent === undefined ? null : (236+ <Field label="Step of">237+ <AskLinks asks={[ask.parent]} project={ask.project} />238+ </Field>239+ )}240+ {ask.reserve === undefined ? null : (241+ <Field label="Who may take it">242+ {reserved[ask.reserve]}243+ {ask.mentor === undefined ? null : (244+ <>245+ , mentored by <HandleLink handle={ask.mentor} />246+ </>247+ )}248+ </Field>249+ )}250+ </Fields>251+252+ {ask.blockedBy.length === 0 ? null : (253+ <p className="text-waiting flex items-start gap-2" data-state="waiting">254+ <Hourglass aria-hidden="true" className="mt-1 size-4 shrink-0" />255+ <span className="text-foreground min-w-0">256+ <strong className="text-waiting font-semibold">Waits on</strong>{" "}257+ <AskLinks asks={ask.blockedBy} project={ask.project} /> to land258+ first; a claim waits until they do.259+ </span>260+ </p>261+ )}262+263+ <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:gap-12">264+ <Region id="ask-brief" title="Brief">265+ <div className="flex max-w-[70ch] flex-col gap-5">266+ {current === undefined ? null : (267+ <BriefPart title="Current behaviour">268+ <p>{current}</p>269+ </BriefPart>270+ )}271+ {outOfScope === undefined ? null : (272+ <BriefPart title="Out of scope">273+ <BriefList items={outOfScope} />274+ </BriefPart>275+ )}276+ {terms === undefined || terms.length === 0 ? null : (277+ <BriefPart title="Terms">278+ <BriefList items={terms} />279+ </BriefPart>280+ )}281+ {context === undefined || context.length === 0 ? null : (282+ <BriefPart title="Context">283+ <BriefList items={context} />284+ </BriefPart>285+ )}286+ <details className="border-rule group border-t pt-3">287+ <summary className="text-muted-foreground hover:text-foreground cursor-pointer text-sm select-none">288+ The brief, as an agent reads it289+ </summary>290+ <pre className="border-rule bg-surface mt-3 overflow-x-auto border p-3 font-mono text-[0.8125rem] leading-6 whitespace-pre-wrap">291+ {brief}292+ </pre>293+ </details>294+ </div>295+ </Region>296+297+ <div className="flex min-w-0 flex-col gap-8">298+ <Region id="ask-take" title="Take it">299+ <TakeIt ask={ask} platformUrl={platformUrl} />300+ </Region>301+ <Region id="ask-more" title="See also">302+ <ul className="flex flex-col gap-1.5 text-sm">303+ <li>304+ <a className={LINK} href={answerPath(ask.project, ask.id)}>305+ Where the latest answer stands306+ </a>307+ </li>308+ <li>309+ <a310+ className={LINK}311+ href={markdownPath(ask.project, ask.id)}312+ type="text/markdown"313+ >314+ This ask as Markdown315+ </a>316+ <span className="text-muted-foreground">317+ , for an agent to fetch318+ </span>319+ </li>320+ </ul>321+ </Region>322+ </div>323+ </div>324+ </PageShell>325+ );326+};added:apps/web/src/features/ask/fields.tsx+59 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859/** * 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]";
/** A link in running text: underlined in the rule colour, darker on hover. */export const LINK = "decoration-rule underline hover:decoration-current";
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+194 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 type { Visibility } from "@repo/protocol/annotations";13+import { Refusal } from "@repo/protocol/refusal";14+import { explain } from "@repo/protocol/render";15+import { Array, Cause, Exit, Option, Schema } from "effect";16+17+const MARKDOWN = "text/markdown; charset=utf-8";18+19+/** A contract's `Visibility` (spec §3.1): a `public` one's answer may be cached for a minute, a `maintainers` one's never. */20+export type ContractVisibility = ReturnType<typeof Visibility.defaultValue>;21+22+/** One range of an `Accept` header: `text/markdown;q=0.8`. */23+interface MediaRange {24+ readonly quality: number;25+ readonly subtype: string;26+ readonly type: string;27+}28+29+/** A q-value as RFC 9110 writes it: 0 to 1, at most three decimals; anything else is no range. */30+const QUALITY = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;31+32+const rangesOf = (accept: string): readonly MediaRange[] =>33+ accept.split(",").flatMap((entry) => {34+ const [media = "", ...parameters] = entry35+ .split(";")36+ .map((part) => part.trim().toLowerCase());37+38+ const [type = "", subtype = ""] = media.split("/");39+ const q = parameters.find((parameter) => parameter.startsWith("q="));40+ const quality = q === undefined ? "1" : q.slice(2);41+42+ return type === "" || subtype === "" || !QUALITY.test(quality)43+ ? []44+ : [{ quality: Number(quality), subtype, type }];45+ });46+47+/** How closely `range` names `type/subtype`: 3 by name, 2 by `type/*`, 1 by `*\/*`, 0 not at all. */48+const closeness = (range: MediaRange, type: string, subtype: string) => {49+ if (range.type === type) {50+ if (range.subtype === subtype) {51+ return 3;52+ }53+54+ return range.subtype === "*" ? 2 : 0;55+ }56+57+ return range.type === "*" && range.subtype === "*" ? 1 : 0;58+};59+60+/** The quality the closest range gives `type/subtype` (RFC 9110 §12.5.1), and how close it was. */61+const preferenceFor = (62+ ranges: readonly MediaRange[],63+ type: string,64+ subtype: string65+) => {66+ let best = { close: 0, quality: 0 };67+68+ for (const range of ranges) {69+ const close = closeness(range, type, subtype);70+71+ if (close > best.close) {72+ best = { close, quality: range.quality };73+ }74+ }75+76+ return best;77+};78+79+/**80+ * Whether the request asks for the ask as Markdown: it names `text/markdown`81+ * itself, with a quality above zero and at least the quality it gives82+ * `text/html`. A wildcard alone (`*\/*`, `text/*`, or no `Accept` at all)83+ * gets the page, as a browser does.84+ */85+export const wantsMarkdown = (request: Request) => {86+ const ranges = rangesOf(request.headers.get("accept") ?? "");87+ const markdown = preferenceFor(ranges, "text", "markdown");88+ const html = preferenceFor(ranges, "text", "html");89+90+ return (91+ markdown.close === 3 &&92+ markdown.quality > 0 &&93+ markdown.quality >= html.quality94+ );95+};96+97+/** The longest run of backticks in `text`. */98+const longestTicks = (text: string) =>99+ Math.max(0, ...[...text.matchAll(/`+/gu)].map(([run]) => run.length));100+101+/** `text` as inline code, its delimiter longer than any backticks inside it. */102+const inlineCode = (text: string) => {103+ const ticks = longestTicks(text);104+ const fence = "`".repeat(ticks + 1);105+106+ return ticks === 0 ? `${fence}${text}${fence}` : `${fence} ${text} ${fence}`;107+};108+109+/**110+ * Refusals as an agent reads them in Markdown: every refusal's `explain`111+ * lines in one text block, verbatim (git's `remote:` lines, without the112+ * prefix), then each distinct `next` command once, as its own paragraph.113+ */114+export const refusalsMarkdown = (115+ refusals: Array.NonEmptyReadonlyArray<Refusal>116+) => {117+ const lines = explain(refusals);118+ const fence = "`".repeat(Math.max(3, longestTicks(lines.join("\n")) + 1));119+ const nexts = Array.dedupe(refusals.map((refusal) => refusal.next));120+121+ return [122+ `${fence}text`,123+ ...lines,124+ fence,125+ "",126+ nexts.map((next) => `Next: ${inlineCode(next)}`).join("\n\n"),127+ "",128+ ].join("\n");129+};130+131+const markdown = (body: string, status: number, cacheControl: string) =>132+ new Response(body, {133+ headers: {134+ "cache-control": cacheControl,135+ "content-type": MARKDOWN,136+ vary: "Accept",137+ },138+ status,139+ });140+141+/** What a Markdown answer may be cached for, by its contract's visibility (spec §3.1). */142+const cacheFor = (visibility: ContractVisibility) =>143+ visibility === "public" ? "public, max-age=60" : "private, no-store";144+145+const isRefusal = Schema.is(Refusal);146+147+/** What the web says when the platform gave neither the ask nor a refusal. */148+const UNANSWERED = [149+ "The platform did not answer, so the web cannot read this ask now. Ask again in a moment.",150+ "",151+].join("\n");152+153+/**154+ * How reading an ask ended, as the Markdown response: the brief (200,155+ * cacheable as its contract's visibility allows); a refusal (404, its156+ * Markdown); or no answer from the platform (502). Only a brief is cached.157+ */158+export const askMarkdownResponse = <E>(159+ result: Exit.Exit<{ readonly brief: string }, E>,160+ visibility: ContractVisibility161+): Response =>162+ Exit.match(result, {163+ onFailure: (cause) =>164+ Option.match(Option.filter(Cause.findErrorOption(cause), isRefusal), {165+ onNone: () => markdown(UNANSWERED, 502, "no-store"),166+ onSome: (refusal) =>167+ markdown(refusalsMarkdown([refusal]), 404, "no-store"),168+ }),169+ onSuccess: ({ brief }) => markdown(brief, 200, cacheFor(visibility)),170+ });171+172+/**173+ * The answer to a path that can name no ask: a project's and an ask's names174+ * are lowercase words joined by single dashes, so the platform is not asked.175+ */176+export const noAskAt = (path: string) =>177+ markdown(178+ [179+ `No ask is at ${inlineCode(path)}: a project's and an ask's names are lowercase words joined by single dashes.`,180+ "",181+ `Next: ${inlineCode(`${Brand.cli} asks`)}`,182+ "",183+ ].join("\n"),184+ 404,185+ "no-store"186+ );187+188+/** Where an ask's Markdown lives: its page's URL with `.md`. */189+export const markdownPath = (project: string, ask: string) =>190+ `/${project}/asks/${ask}.md`;191+192+/** The `Link` header that names an ask page's Markdown as an alternate of it. */193+export const markdownAlternate = (project: string, ask: string) =>194+ `<${markdownPath(project, ask)}>; rel="alternate"; type="text/markdown"`;added:apps/web/src/features/ask/refused.tsx+67 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667/** * 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`; `NoSuchAsk` decodes them where they arrive (AGENTS.md * principle 2). */import { Refusal } from "@repo/protocol/refusal";import { notFound } from "@tanstack/react-router";import { Effect, Option, 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 })) );
/** What a 404 says when the address could name no ask, so no refusal came back. */export const NAMES_ONLY = "Nothing is at this address: a project's and an ask's names are lowercase words joined by single dashes.";
export const NotFoundView = ({ nothing = NAMES_ONLY, refusals, title,}: { readonly nothing?: string; readonly refusals: Array.NonEmptyReadonlyArray<Refusal> | undefined; readonly title: string;}) => ( <PageShell title={title}> {refusals === undefined ? ( <EmptyState title={nothing} /> ) : ( <RefusalView refusals={refusals} /> )} </PageShell>);
const decodeRefusals = Schema.decodeUnknownOption(Refusals);
/** * A route's not-found page: the refusals its loader's not-found carried, * decoded; `nothing` when it carried none (the address could name no ask). */export const NoSuchAsk = ({ data, nothing = NAMES_ONLY,}: { readonly data?: unknown; readonly nothing?: string;}) => ( <NotFoundView nothing={nothing} refusals={Option.getOrUndefined(decodeRefusals(data))} title="No such ask" />);added:apps/web/src/routes/$project/answers/$ask.tsx+216 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, LINK } from "../../../features/ask/fields.tsx";18+import { NoSuchAsk, notFoundFor } from "../../../features/ask/refused.tsx";19+import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";20+import { serverClient } from "../../../server/client.ts";21+22+// The answer page: the latest verdict on an answer to an ask, stage by23+// stage, or with `?head=<sha>` the verdict on an earlier answer. A landed24+// answer shows its landing's credit trailers.25+26+/** The page's address, not yet decoded: the path's names and `?head=`. */27+interface AnswerAddress {28+ readonly ask: string;29+ readonly head?: string | undefined;30+ readonly project: string;31+}32+33+/** The address, decoded: names the platform could hold, and a commit id. */34+const AnswerPath = Schema.Struct({35+ ask: AskId,36+ head: Schema.optionalKey(CommitSha),37+ project: ProjectName,38+});39+40+/** What the page's loader carries from the server, encoded: whose answer, its verdict and landing, and when it was read. */41+const AnswerPageData = Schema.Struct({42+ ...AnswerPath.fields,43+ landing: Schema.UndefinedOr(LandingView),44+ now: Schema.DateTimeUtcFromString,45+ verdict: Schema.UndefinedOr(Verdict),46+});47+48+type AnswerPageData = typeof AnswerPageData.Type;49+50+/** The landing a verdict's answer made, when it landed. */51+const landedBy = (verdict: Verdict | undefined): LandedSha | undefined =>52+ verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome)53+ ? verdict.outcome.sha54+ : undefined;55+56+/** The verdict for the page and, if its answer landed, the landing; or a not-found carrying the refusal (a 404). */57+export const readAnswer = ({ ask, head, project }: AnswerAddress) =>58+ Effect.gen(function* () {59+ const path = yield* Schema.decodeEffect(AnswerPath)(60+ head === undefined ? { ask, project } : { ask, head, project }61+ ).pipe(Effect.mapError(() => notFound()));62+63+ const client = yield* Client;64+65+ const { verdict } = yield* client.verdict(path).pipe(66+ Effect.catchTags({67+ UnknownAsk: notFoundFor,68+ UnknownProject: notFoundFor,69+ })70+ );71+72+ const sha = landedBy(verdict);73+74+ const landing =75+ sha === undefined76+ ? Option.none()77+ : yield* client.landing({ project: path.project, sha }).pipe(78+ Effect.map((found) => Option.some(found.landing)),79+ // The verdict names a landing the platform no longer finds: show the verdict alone.80+ Effect.catchTag("UnknownCommit", () => Effect.succeedNone)81+ );82+83+ return yield* Schema.encodeEffect(AnswerPageData)({84+ ...path,85+ landing: Option.getOrUndefined(landing),86+ now: yield* DateTime.now,87+ verdict,88+ });89+ });90+91+const answerPage = createServerFn({ method: "GET" })92+ .validator((address: AnswerAddress) => address)93+ .handler(({ data }) =>94+ Effect.runPromise(readAnswer(data).pipe(Effect.provide(serverClient(env))))95+ );96+97+/** The verdict with its landing's trailers, from the landing's atom (seeded when the loader read it). */98+const LandedAnswer = ({99+ now,100+ project,101+ seeded,102+ sha,103+ verdict,104+}: {105+ readonly now: DateTime.Utc;106+ readonly project: ProjectName;107+ readonly seeded: LandingView | undefined;108+ readonly sha: LandedSha;109+ readonly verdict: Verdict;110+}) => {111+ const fresh = Option.map(112+ AsyncResult.value(useAtomValue(landingAtom(project, sha))),113+ (found) => found.landing114+ );115+116+ const landing = Option.getOrElse(fresh, () =>117+ seeded?.sha === sha ? seeded : undefined118+ );119+120+ return landing === undefined ? (121+ <AnswerView now={now} verdict={verdict} />122+ ) : (123+ <AnswerView landing={landing} now={now} verdict={verdict} />124+ );125+};126+127+/** The page over the verdict's atom, which starts from what the loader read and refetches when its keys change. */128+const FreshAnswer = ({129+ atom,130+ read,131+}: {132+ readonly atom: ReturnType<typeof verdictAtom>;133+ readonly read: AnswerPageData;134+}) => {135+ const { verdict } = Option.getOrElse(136+ AsyncResult.value(useAtomValue(atom)),137+ () => read138+ );139+140+ const sha = landedBy(verdict);141+142+ return verdict === undefined || sha === undefined ? (143+ <AnswerView now={read.now} verdict={verdict} />144+ ) : (145+ <LandedAnswer146+ now={read.now}147+ project={read.project}148+ seeded={read.landing}149+ sha={sha}150+ verdict={verdict}151+ />152+ );153+};154+155+const AnswerPage = () => {156+ const read = Schema.decodeSync(AnswerPageData)(Route.useLoaderData());157+ const { ask, head, landing, project, verdict } = read;158+ const atom = verdictAtom(project, ask, head);159+160+ const seeds = [161+ Atom.initialValue(162+ atom,163+ AsyncResult.success(verdict === undefined ? {} : { verdict })164+ ),165+ ...(landing === undefined166+ ? []167+ : [168+ Atom.initialValue(169+ landingAtom(project, landing.sha),170+ AsyncResult.success({ landing })171+ ),172+ ]),173+ ];174+175+ return (176+ <PageShell title={`Answer to ${ask}`}>177+ {head === undefined ? null : (178+ <p className="text-sm">179+ An earlier answer, at <code className={CODE}>{head.slice(0, 7)}</code>180+ .{" "}181+ <a className={LINK} href={answerPath(project, ask)}>182+ The latest answer183+ </a>184+ </p>185+ )}186+ <RegistryProvider187+ initialValues={seeds}188+ key={`${project}/${ask}/${head ?? ""}`}189+ >190+ <FreshAnswer atom={atom} read={read} />191+ </RegistryProvider>192+ </PageShell>193+ );194+};195+196+/** An address with no refusal behind it: a name that can name nothing, or a `?head=` that is no commit id. */197+const NOTHING =198+ "Nothing is at this address: a project's and an ask's names are lowercase words joined by single dashes, and ?head= takes an answer's whole commit id, 40 hex digits.";199+200+const AnswerNotFound = ({ data }: { readonly data?: unknown }) => (201+ <NoSuchAsk data={data} nothing={NOTHING} />202+);203+204+export const Route = createFileRoute("/$project/answers/$ask")({205+ // TanStack infers each option from the ones before it, so the search comes206+ // before the loader that reads it.207+ validateSearch: ({ head }: { readonly head?: unknown }) =>208+ Predicate.isString(head) ? { head } : {},209+ loaderDeps: ({ search }) => ({ head: search.head }),210+ loader: ({ deps, params }) => answerPage({ data: { ...params, ...deps } }),211+ head: ({ params }) => ({212+ meta: [{ title: pageTitle(`Answer to ${params.ask}`) }],213+ }),214+ component: AnswerPage,215+ notFoundComponent: AnswerNotFound,216+});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+172 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 { NoSuchAsk, notFoundFor } from "../../../features/ask/refused.tsx";17+import { pageTitle } from "../../../features/shared/layout.tsx";18+import { serverClient } from "../../../server/client.ts";19+import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";20+import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";21+22+// The ask page: the brief, its fields and the lines that take it. The same23+// URL answers `Accept: text/markdown` with the brief as Markdown (the GET24+// handler below), and its `.md` twin always does (`{$ask}[.]md.ts`).25+26+/**27+ * The ask page's GET, as a function of its client: a request that asks for28+ * Markdown gets the ask's Markdown, as at its `.md` URL; any other falls29+ * through to the page.30+ */31+export const askPageHandler =32+ (clientFor: ClientFor) =>33+ <Next,>({34+ next,35+ params,36+ request,37+ }: {38+ readonly next: () => Next;39+ readonly params: AskParams;40+ readonly request: Request;41+ }): Promise<Response> | Next =>42+ wantsMarkdown(request)43+ ? askMarkdownHandler(clientFor)({ params, request })44+ : next();45+46+/**47+ * The page's headers: that the URL answers by `Accept`, and, for a path that48+ * can name an ask, its Markdown as an alternate. A path that cannot (a 404)49+ * names none, so no raw path text reaches a header.50+ */51+export const askPageHeaders = ({52+ params,53+}: {54+ readonly params: AskParams;55+}): Readonly<Record<string, string>> =>56+ Option.match(Schema.decodeOption(AskPath)(params), {57+ onNone: () => ({ vary: "Accept" }),58+ onSome: ({ ask, project }) => ({59+ link: markdownAlternate(project, ask),60+ vary: "Accept",61+ }),62+ });63+64+/** What the page's loader carries from the server, encoded: the ask, its brief, and when it was read. */65+const AskPageData = Schema.Struct({66+ ask: Ask,67+ brief: Schema.NonEmptyString,68+ now: Schema.DateTimeUtcFromString,69+});70+71+/** The ask for its page, or a not-found carrying the platform's refusal (a 404). */72+export const readAsk = (params: AskParams) =>73+ Effect.gen(function* () {74+ const path = yield* Schema.decodeEffect(AskPath)(params).pipe(75+ Effect.mapError(() => notFound())76+ );77+78+ const client = yield* Client;79+80+ const read = yield* client.showAsk(path).pipe(81+ Effect.catchTags({82+ UnknownAsk: notFoundFor,83+ UnknownProject: notFoundFor,84+ })85+ );86+87+ return yield* Schema.encodeEffect(AskPageData)({88+ ...read,89+ now: yield* DateTime.now,90+ });91+ });92+93+const askPage = createServerFn({ method: "GET" })94+ .validator((params: AskParams) => params)95+ .handler(({ data }) =>96+ Effect.runPromise(readAsk(data).pipe(Effect.provide(serverClient(env))))97+ );98+99+const root = getRouteApi("__root__");100+101+type AskRead = Pick<typeof AskPageData.Type, "ask" | "brief">;102+103+/** The page over the ask's atom, which starts from what the loader read and refetches when its keys change. */104+const FreshAsk = ({105+ atom,106+ now,107+ platformUrl,108+ read,109+}: {110+ readonly atom: ReturnType<typeof askAtom>;111+ readonly now: DateTime.Utc;112+ readonly platformUrl: string;113+ readonly read: AskRead;114+}) => {115+ const { ask, brief } = Option.getOrElse(116+ AsyncResult.value(useAtomValue(atom)),117+ () => read118+ );119+120+ return (121+ <AskView ask={ask} brief={brief} now={now} platformUrl={platformUrl} />122+ );123+};124+125+const AskPage = () => {126+ const { platformUrl } = root.useLoaderData();127+128+ const { ask, brief, now } = Schema.decodeSync(AskPageData)(129+ Route.useLoaderData()130+ );131+132+ const atom = askAtom(ask.project, ask.id);133+134+ return (135+ <RegistryProvider136+ initialValues={[137+ Atom.initialValue(atom, AsyncResult.success({ ask, brief })),138+ ]}139+ key={`${ask.project}/${ask.id}`}140+ >141+ <FreshAsk142+ atom={atom}143+ now={now}144+ platformUrl={platformUrl}145+ read={{ ask, brief }}146+ />147+ </RegistryProvider>148+ );149+};150+151+export const Route = createFileRoute("/$project/asks/$ask")({152+ // TanStack infers each option from the ones before it: the loader comes153+ // first, so `head` reads its data.154+ loader: ({ params }) => askPage({ data: params }),155+ head: ({ loaderData }) => ({156+ meta: [157+ {158+ title: pageTitle(159+ loaderData === undefined ? "No such ask" : loaderData.ask.brief.want160+ ),161+ },162+ ],163+ }),164+ headers: askPageHeaders,165+ component: AskPage,166+ notFoundComponent: NoSuchAsk,167+ server: {168+ handlers: {169+ GET: askPageHandler((request) => serverClient(env, request)),170+ },171+ },172+});added:apps/web/test/answer.test.tsx+335 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 { Client, Contracts } from "@repo/protocol/contracts";11+import { Outcome } from "@repo/protocol/domain/outcome";12+import { AreaName, AskId } from "@repo/protocol/ids";13+import {14+ ChecksFailed,15+ HeldBackFailed,16+ UnknownAsk,17+ UnknownCommit,18+} from "@repo/protocol/refusal";19+import { explain } from "@repo/protocol/render";20+import { asTester, unanswered } from "@repo/protocol/testing";21+import { isNotFound } from "@tanstack/react-router";22+import { Effect, Layer, Ref, Schema } from "effect";23+import { RpcTest } from "effect/rpc";24+25+import {26+ AnswerView,27+ HeldBackBits,28+ LaneTable,29+} from "../src/features/answer/answer-page.tsx";30+import { Refusals } from "../src/features/ask/refused.tsx";31+import { readAnswer } from "../src/routes/$project/answers/$ask.tsx";32+import {33+ askId,34+ inOrder,35+ landedSha,36+ landing,37+ markupOf,38+ now,39+ plainText,40+ project,41+ suite,42+ textOf,43+ verdictOf,44+} from "./ask-fixtures.ts";45+46+const checksFailed = new ChecksFailed({47+ lane: "unit",48+ logRef: "logs/datekit/parse-iso-week/unit",49+ next: `${Brand.cli} evidence logs/datekit/parse-iso-week/unit`,50+});51+52+const heldBackFailed = new HeldBackFailed({ area: "export", suite });53+54+const refused = verdictOf(55+ Outcome.cases.Refused.make({ refusals: [checksFailed, heldBackFailed] })56+);57+58+/** Each element that names a stage, as `[stage, state]`. */59+const stagesOf = (markup: string) =>60+ [...markup.matchAll(/<li\b[^>]*>/gu)].flatMap(([tag]) => {61+ const stage = /data-stage="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;62+ const state = /data-state="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;63+64+ return stage === undefined || state === undefined ? [] : [[stage, state]];65+ });66+67+/** Each lane row, as `[lane, result]`. */68+const lanesOf = (markup: string) =>69+ [...markup.matchAll(/<tr\b[^>]*>/gu)].flatMap(([tag]) => {70+ const lane = /data-lane="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;71+ const result = /data-result="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;72+73+ return lane === undefined || result === undefined ? [] : [[lane, result]];74+ });75+76+describe(AnswerView, () => {77+ const page = <AnswerView now={now} verdict={refused} />;78+79+ it("shows the stages the answer passed, the one that refused it, and the ones it never reached", () => {80+ expect(stagesOf(markupOf(page))).toStrictEqual([81+ ["parse", "passed"],82+ ["shape", "passed"],83+ ["merge", "passed"],84+ ["cheap", "passed"],85+ ["checks", "refused"],86+ ["heldBack", "pending"],87+ ["human", "pending"],88+ ]);89+ });90+91+ it("shows each lane with its result", () => {92+ expect(lanesOf(markupOf(page))).toStrictEqual([93+ ["lint", "passed"],94+ ["unit", "failed"],95+ ]);96+ expect(97+ inOrder(textOf(page), ["lint", "passed", "unit", "failed"])98+ ).toBeTruthy();99+ });100+101+ it("shows held-back checks only as an area's counts and its suite root", () => {102+ const bits =103+ /<ul aria-label="Held-back checks by area"[^>]*>(?<inner>.*?)<\/ul>/su.exec(104+ markupOf(page)105+ )?.groups?.inner;106+107+ expect(plainText(bits ?? "").trim()).toBe(`export 6/7 @ ${suite}`);108+ });109+110+ it("shows the refusals' explain lines in order, as git printed them", () => {111+ expect(112+ inOrder(113+ textOf(page),114+ explain([checksFailed, heldBackFailed]).map((line) => line.trim())115+ )116+ ).toBeTruthy();117+ });118+119+ it("never shows where a lane's log is kept outside the refusal that names it", () => {120+ const passing = verdictOf(Outcome.cases.Checking.make({ stage: "checks" }));121+122+ expect(textOf(<AnswerView now={now} verdict={passing} />)).not.toContain(123+ "logs/datekit"124+ );125+ });126+127+ it("names the answer it judged and when", () => {128+ const text = textOf(page);129+130+ expect(text).toContain("bbbbbbb");131+ expect(text).toContain("aaaaaaa");132+ expect(text).toContain("redThenGreen@0.0.0+5e1d");133+ expect(text).toContain("20 min ago");134+ });135+136+ it("says plainly when no answer has been checked yet", () => {137+ const text = textOf(<AnswerView now={now} verdict={undefined} />);138+139+ expect(text).toContain("No answer to this ask has been checked yet");140+ expect(text).not.toContain("Parse");141+ });142+143+ it("shows a landed answer's credit trailers in trailer order, its held-back trailer, and its commit", () => {144+ const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));145+ const element = <AnswerView landing={landing} now={now} verdict={landed} />;146+ const text = textOf(element);147+148+ expect(text).toContain("Landed as 9b1c3e5");149+ expect(150+ inOrder(text, ["Asked-by: ines-v", "Signed-off-by: okafor"])151+ ).toBeTruthy();152+ expect(text).toContain(`Held-back: export 7/7 @ ${suite}`);153+ expect(text).toContain("Assisted-by: claude-code:opus-5 (verified)");154+ expect(text).toContain(`git show ${landedSha}`);155+ });156+});157+158+describe(LaneTable, () => {159+ it("gives each lane's command and how long it ran", () => {160+ const { lanes } = refused;161+ const text = textOf(<LaneTable lanes={lanes} />);162+163+ expect(inOrder(text, ["lint", "bun run lint", "1.2 s"])).toBeTruthy();164+ expect(inOrder(text, ["unit", "bun test", "8.3 s"])).toBeTruthy();165+ });166+167+ it("says when no lane ran", () => {168+ expect(textOf(<LaneTable lanes={[]} />)).toContain("No lane ran");169+ });170+});171+172+describe(HeldBackBits, () => {173+ it("shows one line per area, and nothing else about the held-back checks", () => {174+ const results = [175+ { area: AreaName.make("export"), passed: 6, suite, total: 7 },176+ { area: AreaName.make("parse"), passed: 3, suite, total: 3 },177+ ];178+179+ expect(textOf(<HeldBackBits results={results} />).trim()).toBe(180+ `export 6/7 @ ${suite} parse 3/3 @ ${suite}`181+ );182+ });183+});184+185+/** What the stub platform was asked: verdicts and landings. */186+interface Asked {187+ readonly landings: number;188+ readonly verdicts: number;189+}190+191+/**192+ * A platform whose datekit ask's latest answer ended in `outcome`, as the193+ * answer page's loader calls it; `landingKnown` says whether it still finds194+ * the landing a landed verdict names.195+ */196+const platformAt = (197+ asked: Ref.Ref<Asked>,198+ outcome: Outcome,199+ landingKnown = true200+) =>201+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(202+ Layer.provide([203+ Layer.mergeAll(204+ unanswered,205+ Contracts.toLayerHandler("verdict", (payload) =>206+ Effect.gen(function* () {207+ yield* Ref.update(asked, (seen) => ({208+ ...seen,209+ verdicts: seen.verdicts + 1,210+ }));211+212+ if (payload.ask !== askId) {213+ return yield* new UnknownAsk({ ask: payload.ask });214+ }215+216+ return { verdict: verdictOf(outcome) };217+ })218+ ),219+ Contracts.toLayerHandler("landing", (payload) =>220+ Effect.gen(function* () {221+ yield* Ref.update(asked, (seen) => ({222+ ...seen,223+ landings: seen.landings + 1,224+ }));225+226+ if (!landingKnown || payload.sha !== landedSha) {227+ return yield* new UnknownCommit({ sha: payload.sha });228+ }229+230+ return { landing };231+ })232+ )233+ ),234+ asTester,235+ ])236+ );237+238+const nothingAsked: Asked = { landings: 0, verdicts: 0 };239+240+describe(readAnswer, () => {241+ it.effect("reads a landed answer's landing with its verdict", () =>242+ Effect.gen(function* () {243+ const asked = yield* Ref.make(nothingAsked);244+ const landed = Outcome.cases.Landed.make({ sha: landedSha });245+246+ const read = yield* readAnswer({ ask: askId, project }).pipe(247+ Effect.provide(platformAt(asked, landed))248+ );249+250+ expect(read.verdict?.outcome._tag).toBe("Landed");251+ expect(read.landing?.sha).toBe(landedSha);252+ expect(yield* Ref.get(asked)).toStrictEqual({ landings: 1, verdicts: 1 });253+ })254+ );255+256+ it.effect("asks for no landing when the answer did not land", () =>257+ Effect.gen(function* () {258+ const asked = yield* Ref.make(nothingAsked);259+260+ const read = yield* readAnswer({ ask: askId, project }).pipe(261+ Effect.provide(platformAt(asked, refused.outcome))262+ );263+264+ expect(read.verdict?.outcome._tag).toBe("Refused");265+ expect(read.landing).toBeUndefined();266+ expect(yield* Ref.get(asked)).toStrictEqual({ landings: 0, verdicts: 1 });267+ })268+ );269+270+ it.effect(271+ "shows the verdict alone when the platform no longer finds its landing",272+ () =>273+ Effect.gen(function* () {274+ const asked = yield* Ref.make(nothingAsked);275+ const landed = Outcome.cases.Landed.make({ sha: landedSha });276+277+ const read = yield* readAnswer({ ask: askId, project }).pipe(278+ Effect.provide(platformAt(asked, landed, false))279+ );280+281+ expect(read.verdict?.outcome._tag).toBe("Landed");282+ expect(read.landing).toBeUndefined();283+ })284+ );285+286+ it.effect(287+ "is a not-found carrying the UnknownAsk refusal for an ask the project lacks",288+ () =>289+ Effect.gen(function* () {290+ const asked = yield* Ref.make(nothingAsked);291+ const missing = AskId.make("no-such-ask");292+293+ const failed = yield* Effect.flip(294+ readAnswer({ ask: missing, project }).pipe(295+ Effect.provide(296+ platformAt(297+ asked,298+ Outcome.cases.Checking.make({ stage: "checks" })299+ )300+ )301+ )302+ );303+304+ expect(isNotFound(failed)).toBeTruthy();305+306+ const carried = yield* Schema.decodeUnknownEffect(Refusals)(307+ isNotFound(failed) ? failed.data : undefined308+ );309+310+ expect(explain(carried)).toStrictEqual(311+ explain([new UnknownAsk({ ask: missing })])312+ );313+ })314+ );315+316+ it.effect(317+ "is a not-found with no refusal, and asks nothing, when ?head= is not a whole commit id",318+ () =>319+ Effect.gen(function* () {320+ const asked = yield* Ref.make(nothingAsked);321+322+ const failed = yield* Effect.flip(323+ readAnswer({ ask: askId, head: "9b1c3e5", project }).pipe(324+ Effect.provide(platformAt(asked, refused.outcome))325+ )326+ );327+328+ expect(isNotFound(failed)).toBeTruthy();329+ expect(330+ isNotFound(failed) ? failed.data : "not a not-found"331+ ).toBeUndefined();332+ expect(yield* Ref.get(asked)).toStrictEqual(nothingAsked);333+ })334+ );335+});added:apps/web/test/ask-fixtures.ts+176 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 of `markup`: the text without its tags, entities decoded. */149+export const plainText = (markup: string) =>150+ markup151+ .replaceAll(/<[^>]+>/gu, " ")152+ .replaceAll(153+ /&(?:#x27|amp|gt|lt|quot);/gu,154+ (entity) => ENTITIES.get(entity) ?? entity155+ )156+ .replaceAll(/\s+/gu, " ");157+158+/** What a reader sees of `element`, rendered. */159+export const textOf = (element: ReactElement) => plainText(markupOf(element));160+161+/** Whether each of `parts` appears in `text`, each after the one before. */162+export const inOrder = (text: string, parts: readonly string[]) => {163+ let from = 0;164+165+ for (const part of parts) {166+ const at = text.indexOf(part, from);167+168+ if (at === -1) {169+ return false;170+ }171+172+ from = at + part.length;173+ }174+175+ return true;176+};added:apps/web/test/ask-markdown.test.ts+349 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, Exit, Layer, Ref } from "effect";16+import { RpcTest } from "effect/rpc";17+18+import {19+ askMarkdownResponse,20+ refusalsMarkdown,21+ wantsMarkdown,22+} from "../src/features/ask/markdown.ts";23+import {24+ askPageHandler,25+ askPageHeaders,26+} from "../src/routes/$project/asks/$ask.tsx";27+import { askMarkdownHandler } from "../src/routes/$project/asks/{$ask}[.]md.ts";28+import { ask, askId, brief, project } from "./ask-fixtures.ts";29+30+const WEB = "https://web-test.example.workers.dev";31+32+const MARKDOWN = "text/markdown; charset=utf-8";33+34+const BROWSER =35+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";36+37+/**38+ * A platform that knows datekit and its one ask, counting `showAsk` calls,39+ * as a route's client.40+ */41+const platformOf = (calls: Ref.Ref<number>) => () =>42+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(43+ Layer.provide([44+ Layer.mergeAll(45+ unanswered,46+ Contracts.toLayerHandler("showAsk", (payload) =>47+ Effect.gen(function* () {48+ yield* Ref.update(calls, (count) => count + 1);49+50+ if (payload.project !== project) {51+ return yield* new UnknownProject({ project: payload.project });52+ }53+54+ if (payload.ask !== askId) {55+ return yield* new UnknownAsk({ ask: payload.ask });56+ }57+58+ return { ask, brief };59+ })60+ )61+ ),62+ asTester,63+ ])64+ );65+66+/** A platform that cannot be reached: every call dies on the way. */67+const unreachable = () =>68+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(69+ Layer.provide([unanswered, asTester])70+ );71+72+const get = (path: string, accept?: string) =>73+ new Request(`${WEB}${path}`, {74+ headers: accept === undefined ? {} : { accept },75+ });76+77+const params = (askName: string, projectName: string = project) => ({78+ ask: askName,79+ project: projectName,80+});81+82+/** What a response says, read whole. */83+const read = (response: Response) =>84+ Effect.map(85+ Effect.promise(() => response.text()),86+ (body) => ({87+ body,88+ cacheControl: response.headers.get("cache-control"),89+ contentType: response.headers.get("content-type"),90+ status: response.status,91+ vary: response.headers.get("vary"),92+ })93+ );94+95+/** The page's own render, which a Markdown request must never reach. */96+const PAGE = new Response("<!doctype html><title>the page</title>");97+98+describe("an ask's URL with Accept: text/markdown", () => {99+ it.effect(100+ "answers with the brief showAsk gives, as Markdown that public caches may keep a minute",101+ () =>102+ Effect.gen(function* () {103+ const calls = yield* Ref.make(0);104+105+ const response = yield* Effect.promise(() =>106+ Promise.resolve(107+ askPageHandler(platformOf(calls))({108+ next: () => PAGE,109+ params: params(askId),110+ request: get(`/datekit/asks/${askId}`, "text/markdown"),111+ })112+ )113+ );114+115+ expect(yield* read(response)).toStrictEqual({116+ body: brief,117+ cacheControl: "public, max-age=60",118+ contentType: MARKDOWN,119+ status: 200,120+ vary: "Accept",121+ });122+ expect(yield* Ref.get(calls)).toBe(1);123+ })124+ );125+126+ it.effect(127+ "falls through to the page when the reader asks for HTML, and reads no ask",128+ () =>129+ Effect.gen(function* () {130+ const calls = yield* Ref.make(0);131+132+ const answered = askPageHandler(platformOf(calls))({133+ next: () => PAGE,134+ params: params(askId),135+ request: get(`/datekit/asks/${askId}`, BROWSER),136+ });137+138+ expect(answered).toBe(PAGE);139+ expect(yield* Ref.get(calls)).toBe(0);140+ })141+ );142+});143+144+describe("an ask's .md URL", () => {145+ it.effect(146+ "answers with the same Markdown, whatever the request accepts",147+ () =>148+ Effect.gen(function* () {149+ const calls = yield* Ref.make(0);150+151+ const response = yield* Effect.promise(() =>152+ askMarkdownHandler(platformOf(calls))({153+ params: params(askId),154+ request: get(`/datekit/asks/${askId}.md`, BROWSER),155+ })156+ );157+158+ expect(yield* read(response)).toStrictEqual({159+ body: brief,160+ cacheControl: "public, max-age=60",161+ contentType: MARKDOWN,162+ status: 200,163+ vary: "Accept",164+ });165+ })166+ );167+168+ it.effect(169+ "answers an unknown ask with 404 and the UnknownAsk refusal, as git prints it, then its next command",170+ () =>171+ Effect.gen(function* () {172+ const calls = yield* Ref.make(0);173+ const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });174+175+ const response = yield* Effect.promise(() =>176+ askMarkdownHandler(platformOf(calls))({177+ params: params("no-such-ask"),178+ request: get("/datekit/asks/no-such-ask.md"),179+ })180+ );181+182+ const seen = yield* read(response);183+184+ expect(seen.status).toBe(404);185+ expect(seen.contentType).toBe(MARKDOWN);186+ expect(seen.body).toBe(187+ [188+ "```text",189+ ...explain([refusal]),190+ "```",191+ "",192+ `Next: \`${Brand.cli} asks\``,193+ "",194+ ].join("\n")195+ );196+ expect(seen.cacheControl).toBe("no-store");197+ })198+ );199+200+ it.effect(201+ "answers an unknown project with 404 and the UnknownProject refusal",202+ () =>203+ Effect.gen(function* () {204+ const calls = yield* Ref.make(0);205+206+ const response = yield* Effect.promise(() =>207+ askMarkdownHandler(platformOf(calls))({208+ params: params(askId, "nowhere"),209+ request: get(`/nowhere/asks/${askId}.md`),210+ })211+ );212+213+ const seen = yield* read(response);214+215+ expect(seen.status).toBe(404);216+ expect(seen.body).toBe(217+ refusalsMarkdown([218+ new UnknownProject({ project: ProjectName.make("nowhere") }),219+ ])220+ );221+ expect(seen.body).toContain(222+ "UnknownProject: no project is named nowhere"223+ );224+ })225+ );226+227+ it.effect(228+ "answers a path that can name no ask with 404, and asks the platform nothing",229+ () =>230+ Effect.gen(function* () {231+ const calls = yield* Ref.make(0);232+233+ const response = yield* Effect.promise(() =>234+ askMarkdownHandler(platformOf(calls))({235+ params: params("Not_An-Ask"),236+ request: get("/datekit/asks/Not_An-Ask.md"),237+ })238+ );239+240+ const seen = yield* read(response);241+242+ expect(seen.status).toBe(404);243+ expect(seen.contentType).toBe(MARKDOWN);244+ expect(seen.body).toContain("Not_An-Ask");245+ expect(yield* Ref.get(calls)).toBe(0);246+ })247+ );248+249+ it.effect(250+ "answers 502 when the platform does not answer, and keeps it out of caches",251+ () =>252+ Effect.gen(function* () {253+ const response = yield* Effect.promise(() =>254+ askMarkdownHandler(unreachable)({255+ params: params(askId),256+ request: get(`/datekit/asks/${askId}.md`),257+ })258+ );259+260+ const seen = yield* read(response);261+262+ expect(seen.status).toBe(502);263+ expect(seen.contentType).toBe(MARKDOWN);264+ expect(seen.cacheControl).toBe("no-store");265+ })266+ );267+});268+269+describe("the ask page", () => {270+ it("names its Markdown as an alternate, and says it varies by Accept", () => {271+ expect(askPageHeaders({ params: params(askId) })).toStrictEqual({272+ link: `</datekit/asks/${askId}.md>; rel="alternate"; type="text/markdown"`,273+ vary: "Accept",274+ });275+ });276+277+ it("names no alternate for a path that can name no ask, so no raw path text reaches a header", () => {278+ expect(279+ askPageHeaders({ params: params('x>; rel="next"\nset-cookie: a=b') })280+ ).toStrictEqual({ vary: "Accept" });281+ });282+});283+284+describe(askMarkdownResponse, () => {285+ it.effect(286+ "never lets a cache keep the answer of a contract only maintainers may see",287+ () =>288+ Effect.gen(function* () {289+ const seen = yield* read(290+ askMarkdownResponse(Exit.succeed({ brief }), "maintainers")291+ );292+293+ expect([seen.status, seen.cacheControl, seen.body]).toStrictEqual([294+ 200,295+ "private, no-store",296+ brief,297+ ]);298+ })299+ );300+});301+302+describe(refusalsMarkdown, () => {303+ it("sets every refusal's explain lines in one text block, then each distinct next command once", () => {304+ const refusals = [305+ new UnknownProject({ project: ProjectName.make("nowhere") }),306+ new UnknownAsk({ ask: askId }),307+ ] as const;308+309+ expect(refusalsMarkdown(refusals)).toBe(310+ [311+ "```text",312+ ...explain(refusals),313+ "```",314+ "",315+ `Next: \`${Brand.cli} asks\``,316+ "",317+ ].join("\n")318+ );319+ });320+});321+322+const accepting = (accept: string | undefined) =>323+ wantsMarkdown(get("/datekit/asks/parse-iso-week", accept));324+325+describe(wantsMarkdown, () => {326+ it.each([327+ ["text/markdown"],328+ ["text/markdown, text/html"],329+ ["text/html;q=0.9, text/markdown"],330+ ["text/markdown;q=0.8, */*;q=0.1"],331+ ["Text/Markdown; charset=utf-8"],332+ ])("serves Markdown to %o", (accept) => {333+ expect(accepting(accept)).toBeTruthy();334+ });335+336+ it.each([337+ [undefined],338+ ["*/*"],339+ ["text/*"],340+ ["text/html"],341+ [BROWSER],342+ ["text/markdown;q=0.5, text/html"],343+ ["text/markdown;q=0, text/html;q=0.1"],344+ ["text/markdown;q=0"],345+ ["application/json"],346+ ])("serves the page to %o", (accept) => {347+ expect(accepting(accept)).toBeFalsy();348+ });349+});added:apps/web/test/ask.test.tsx+282 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 { Client, Contracts } from "@repo/protocol/contracts";10+import { AskId, Handle } from "@repo/protocol/ids";11+import { UnknownAsk } from "@repo/protocol/refusal";12+import { explain } from "@repo/protocol/render";13+import { asTester, unanswered } from "@repo/protocol/testing";14+import { isNotFound } from "@tanstack/react-router";15+import { Effect, Layer, Ref, Schema } from "effect";16+import { RpcTest } from "effect/rpc";17+18+import { AskView } from "../src/features/ask/ask-page.tsx";19+import { NoSuchAsk, Refusals } from "../src/features/ask/refused.tsx";20+import { readAsk } from "../src/routes/$project/asks/$ask.tsx";21+import {22+ ask,23+ askId,24+ brief,25+ inOrder,26+ markupOf,27+ now,28+ project,29+ textOf,30+} from "./ask-fixtures.ts";31+32+const platformUrl = "https://platform-test.example.workers.dev";33+34+/** The markup inside the first `<pre>`. */35+const inPre = (markup: string) =>36+ /<pre\b[^>]*>(?<inner>.*?)<\/pre>/su.exec(markup)?.groups?.inner;37+38+const page = (shown = ask) => (39+ <AskView ask={shown} brief={brief} now={now} platformUrl={platformUrl} />40+);41+42+describe(AskView, () => {43+ it("titles the page with the want, then reads the brief's sections in order", () => {44+ const markup = markupOf(page());45+46+ expect(markup).toMatch(47+ /<h1\b[^>]*>Parse ISO week dates like 2026-W41-3<\/h1>/u48+ );49+ expect(50+ inOrder(textOf(page()), [51+ "Current behaviour",52+ "parseWeek returns null for 2026-W41-3.",53+ "Out of scope",54+ "Formatting week dates back to strings.",55+ "Terms",56+ "Week date: a date written as year, week and weekday.",57+ "Context",58+ "ISO 8601 numbers weeks from the Monday of the week holding 4 January.",59+ ])60+ ).toBeTruthy();61+ });62+63+ it("leaves out a section the brief does not have", () => {64+ const text = textOf(65+ page({ ...ask, brief: { want: "Parse ISO week dates like 2026-W41-3" } })66+ );67+68+ expect(text).not.toContain("Current behaviour");69+ expect(text).not.toContain("Out of scope");70+ expect(text).not.toContain("Terms");71+ });72+73+ it("gives the ask's name, kind, state and check", () => {74+ expect(75+ inOrder(textOf(page()), [76+ "Ask",77+ askId,78+ "State",79+ "Open",80+ "Kind",81+ "fix",82+ "Check",83+ "test/parse-week.test.ts",84+ ])85+ ).toBeTruthy();86+ });87+88+ it("gives the ask's territory, and who asked it when", () => {89+ const text = textOf(page());90+91+ expect(92+ inOrder(text, ["Asked by", "ines-v", "opened 2 d ago"])93+ ).toBeTruthy();94+ expect(95+ inOrder(text, ["Territory", "@datekit/parse", "packages/parse/**"])96+ ).toBeTruthy();97+ expect(markupOf(page())).toContain('href="/people/ines-v"');98+ });99+100+ it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {101+ expect(102+ inOrder(textOf(page()), [103+ `git clone ${platformUrl}/datekit.git`,104+ `${Brand.cli} claim ${askId} --project datekit`,105+ `${Brand.cli} check --ask ${askId}`,106+ ])107+ ).toBeTruthy();108+ });109+110+ it("names the asks a blocked ask waits on, each linking to its page", () => {111+ const blocked = {112+ ...ask,113+ blockedBy: [AskId.make("split-format"), AskId.make("split-parse")],114+ };115+116+ const text = textOf(page(blocked));117+ const markup = markupOf(page(blocked));118+119+ expect(120+ inOrder(text, [121+ "Waits on",122+ "split-format",123+ "split-parse",124+ "to land first",125+ ])126+ ).toBeTruthy();127+ expect(markup).toContain('href="/datekit/asks/split-format"');128+ expect(markup).toContain('href="/datekit/asks/split-parse"');129+ });130+131+ it("names nothing it waits on when nothing blocks it", () => {132+ expect(textOf(page())).not.toContain("Waits on");133+ });134+135+ it("links a step of a migrate to its parent ask", () => {136+ const child = { ...ask, parent: AskId.make("migrate-week-api") };137+138+ expect(markupOf(page(child))).toContain(139+ 'href="/datekit/asks/migrate-week-api"'140+ );141+ });142+143+ it("says when an ask is held for newcomers, and who mentors them", () => {144+ const held = {145+ ...ask,146+ mentor: Handle.make("okonkwo"),147+ reserve: "newcomers" as const,148+ };149+150+ const text = textOf(page(held));151+152+ expect(text).toContain("Held for newcomers");153+ expect(markupOf(page(held))).toContain('href="/people/okonkwo"');154+ });155+156+ it("gives no claim line once the ask is closed", () => {157+ const text = textOf(page({ ...ask, state: "closed" }));158+159+ expect(text).toContain("Closed");160+ expect(text).not.toContain(`${Brand.cli} claim`);161+ });162+163+ it("links to the ask's Markdown and to the verdict on its latest answer", () => {164+ const markup = markupOf(page());165+166+ expect(markup).toContain(`href="/datekit/asks/${askId}.md"`);167+ expect(markup).toContain(`href="/datekit/answers/${askId}"`);168+ });169+170+ it("shows the brief exactly as an agent reads it", () => {171+ expect(inPre(markupOf(page()))).toBe(inPre(markupOf(<pre>{brief}</pre>)));172+ });173+});174+175+describe(NoSuchAsk, () => {176+ it("shows the refusal a loader's not-found carried from the server, as git printed it", () => {177+ const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });178+179+ // The not-found's data, as it crosses from the server: encoded, then cloned.180+ const data = structuredClone(Schema.encodeSync(Refusals)([refusal]));181+182+ expect(183+ inOrder(textOf(<NoSuchAsk data={data} />), [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(textOf(<NoSuchAsk />)).toContain("Nothing is at this address");193+ });194+195+ it("says what its route gives it when a not-found carries no refusal", () => {196+ expect(197+ textOf(<NoSuchAsk nothing="No answer is at this head." />)198+ ).toContain("No answer is at this head.");199+ });200+});201+202+/** A platform that knows datekit's one ask, counting `showAsk` calls. */203+const platformOf = (calls: Ref.Ref<number>) =>204+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(205+ Layer.provide([206+ Layer.mergeAll(207+ unanswered,208+ Contracts.toLayerHandler("showAsk", (payload) =>209+ Effect.gen(function* () {210+ yield* Ref.update(calls, (count) => count + 1);211+212+ if (payload.ask !== askId) {213+ return yield* new UnknownAsk({ ask: payload.ask });214+ }215+216+ return { ask, brief };217+ })218+ )219+ ),220+ asTester,221+ ])222+ );223+224+describe(readAsk, () => {225+ it.effect("reads the ask and its brief for the page", () =>226+ Effect.gen(function* () {227+ const calls = yield* Ref.make(0);228+229+ const read = yield* readAsk({ ask: askId, project }).pipe(230+ Effect.provide(platformOf(calls))231+ );232+233+ expect([read.ask.id, read.brief]).toStrictEqual([askId, brief]);234+ expect(yield* Ref.get(calls)).toBe(1);235+ })236+ );237+238+ it.effect(239+ "is a not-found carrying the UnknownAsk refusal for an ask the project lacks",240+ () =>241+ Effect.gen(function* () {242+ const calls = yield* Ref.make(0);243+ const missing = AskId.make("no-such-ask");244+245+ const failed = yield* Effect.flip(246+ readAsk({ ask: missing, project }).pipe(247+ Effect.provide(platformOf(calls))248+ )249+ );250+251+ expect(isNotFound(failed)).toBeTruthy();252+253+ const carried = yield* Schema.decodeUnknownEffect(Refusals)(254+ isNotFound(failed) ? failed.data : undefined255+ );256+257+ expect(explain(carried)).toStrictEqual(258+ explain([new UnknownAsk({ ask: missing })])259+ );260+ })261+ );262+263+ it.effect(264+ "is a not-found with no refusal, and asks nothing, for a name no ask can have",265+ () =>266+ Effect.gen(function* () {267+ const calls = yield* Ref.make(0);268+269+ const failed = yield* Effect.flip(270+ readAsk({ ask: "Not_An-Ask", project }).pipe(271+ Effect.provide(platformOf(calls))272+ )273+ );274+275+ expect(isNotFound(failed)).toBeTruthy();276+ expect(277+ isNotFound(failed) ? failed.data : "not a not-found"278+ ).toBeUndefined();279+ expect(yield* Ref.get(calls)).toBe(0);280+ })281+ );282+});