Skip to content
Myr

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

14 files+2549 added−0 removed

added:apps/web/src/client/answer.ts+36 added
added:apps/web/src/client/ask.ts+18 added
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 */14import type {15 HeldBackResult,16 LaneOutcome,17 LaneResult,18 Verdict,19} from "@repo/protocol/domain/answer";20import type { LandingView } from "@repo/protocol/domain/landing";21import type { DateTime } from "effect";22import {23 Ban,24 Check,25 LockKeyhole,26 RotateCcw,27 TriangleAlert,28 X,29} from "lucide-react";30import type { LucideIcon } from "lucide-react";3132import {33 Table,34 TableBody,35 TableCell,36 TableHead,37 TableHeader,38 TableRow,39} from "../../components/ui/table.tsx";40import { askPath } from "../ask/ask-page.tsx";41import { CODE, Field, Fields, LINK, Region } from "../ask/fields.tsx";42import { CommandLine } from "../shared/command.tsx";43import { CreditTrailers } from "../shared/credits.tsx";44import { EmptyState } from "../shared/empty.tsx";45import { OutcomeView, StageStrip } from "../shared/outcome.tsx";46import { When } from "../shared/time.tsx";4748/** How long a lane ran: "640 ms", "8.3 s", "2 min 5 s". */49export const durationText = (millis: number) => {50 if (millis < 1000) {51 return `${millis} ms`;52 }5354 if (millis < 60_000) {55 return `${(millis / 1000).toFixed(1)} s`;56 }5758 const seconds = Math.round(millis / 1000);5960 return `${Math.floor(seconds / 60)} min ${seconds % 60} s`;61};6263/** Each lane result as a mark, a word and its role colour (DESIGN.md: the word first). */64const 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>;7475const HEAD = "text-muted-foreground h-8 px-0 text-xs font-medium";7677/** The lanes the platform ran on the merged tree: each one's command, result and time. */78export 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 }8687 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];99100 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};131132/** Held-back checks: one line per area, as the landing's trailer spells it, and nothing else. */133export 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);156157const short = (sha: string) => sha.slice(0, 7);158159/** A git id, short as git prints it, whole on hover. */160const Sha = ({ sha }: { readonly sha: string }) => (161 <code className={CODE} title={sha}>162 {short(sha)}163 </code>164);165166export 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 }178179 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>212213 <Region id="answer-gate" title="Gate">214 <StageStrip outcome={verdict.outcome} stage={verdict.stage} />215 <OutcomeView outcome={verdict.outcome} />216 </Region>217218 <Region id="answer-lanes" title="Lanes">219 <LaneTable lanes={verdict.lanes} />220 </Region>221222 {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 )}231232 {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 */9import { Brand } from "@repo/brand";10import type { Ask, AskState } from "@repo/protocol/domain/ask";11import { CheckSpec } from "@repo/protocol/domain/check";12import type { AskId, ProjectName } from "@repo/protocol/ids";13import type { DateTime } from "effect";14import { Circle, CircleDot, Hourglass, Minus } from "lucide-react";15import type { LucideIcon } from "lucide-react";16import type { ReactNode } from "react";1718import { CommandLine } from "../shared/command.tsx";19import { HandleLink } from "../shared/handle.tsx";20import { PageShell } from "../shared/layout.tsx";21import { When } from "../shared/time.tsx";22import { CODE, Field, Fields, LINK, Region } from "./fields.tsx";23import { markdownPath } from "./markdown.ts";2425/** An ask's page. */26export const askPath = (project: ProjectName, ask: AskId) =>27 `/${project}/asks/${ask}`;2829/** The page of the verdict on an ask's latest answer. */30export const answerPath = (project: ProjectName, ask: AskId) =>31 `/${project}/answers/${ask}`;3233/** Each state as a mark, a word and its role colour (none for open: nothing is happening yet). */34const 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>;4748const StateMark = ({ state }: { readonly state: AskState }) => {49 const { icon: Icon, tone, word } = states[state];5051 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};6162const Code = ({ children }: { readonly children: ReactNode }) => (63 <code className={CODE}>{children}</code>64);6566/** What judges an answer: the check's kind in words, then what it names. */67const 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 });107108/** Asks, each linking to its page, separated by commas. */109const 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 ));124125const reserved = {126 newcomers: "Held for newcomers",127 people: "Held for a person to answer, not an agent",128} as const;129130const 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);142143const 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);150151/** The lines that start an answer: clone, claim (it prints the fork's remote), check before the push. */152const 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 }166167 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;178179 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};192193export 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;205206 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>251252 {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 )}262263 <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>296297 <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
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 */11import { Brand } from "@repo/brand";12import type { Visibility } from "@repo/protocol/annotations";13import { Refusal } from "@repo/protocol/refusal";14import { explain } from "@repo/protocol/render";15import { Array, Cause, Exit, Option, Schema } from "effect";1617const MARKDOWN = "text/markdown; charset=utf-8";1819/** A contract's `Visibility` (spec §3.1): a `public` one's answer may be cached for a minute, a `maintainers` one's never. */20export type ContractVisibility = ReturnType<typeof Visibility.defaultValue>;2122/** One range of an `Accept` header: `text/markdown;q=0.8`. */23interface MediaRange {24 readonly quality: number;25 readonly subtype: string;26 readonly type: string;27}2829/** A q-value as RFC 9110 writes it: 0 to 1, at most three decimals; anything else is no range. */30const QUALITY = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;3132const rangesOf = (accept: string): readonly MediaRange[] =>33 accept.split(",").flatMap((entry) => {34 const [media = "", ...parameters] = entry35 .split(";")36 .map((part) => part.trim().toLowerCase());3738 const [type = "", subtype = ""] = media.split("/");39 const q = parameters.find((parameter) => parameter.startsWith("q="));40 const quality = q === undefined ? "1" : q.slice(2);4142 return type === "" || subtype === "" || !QUALITY.test(quality)43 ? []44 : [{ quality: Number(quality), subtype, type }];45 });4647/** How closely `range` names `type/subtype`: 3 by name, 2 by `type/*`, 1 by `*\/*`, 0 not at all. */48const closeness = (range: MediaRange, type: string, subtype: string) => {49 if (range.type === type) {50 if (range.subtype === subtype) {51 return 3;52 }5354 return range.subtype === "*" ? 2 : 0;55 }5657 return range.type === "*" && range.subtype === "*" ? 1 : 0;58};5960/** The quality the closest range gives `type/subtype` (RFC 9110 §12.5.1), and how close it was. */61const preferenceFor = (62 ranges: readonly MediaRange[],63 type: string,64 subtype: string65) => {66 let best = { close: 0, quality: 0 };6768 for (const range of ranges) {69 const close = closeness(range, type, subtype);7071 if (close > best.close) {72 best = { close, quality: range.quality };73 }74 }7576 return best;77};7879/**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 */85export 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");8990 return (91 markdown.close === 3 &&92 markdown.quality > 0 &&93 markdown.quality >= html.quality94 );95};9697/** The longest run of backticks in `text`. */98const longestTicks = (text: string) =>99 Math.max(0, ...[...text.matchAll(/`+/gu)].map(([run]) => run.length));100101/** `text` as inline code, its delimiter longer than any backticks inside it. */102const inlineCode = (text: string) => {103 const ticks = longestTicks(text);104 const fence = "`".repeat(ticks + 1);105106 return ticks === 0 ? `${fence}${text}${fence}` : `${fence} ${text} ${fence}`;107};108109/**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 */114export 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));120121 return [122 `${fence}text`,123 ...lines,124 fence,125 "",126 nexts.map((next) => `Next: ${inlineCode(next)}`).join("\n\n"),127 "",128 ].join("\n");129};130131const 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 });140141/** What a Markdown answer may be cached for, by its contract's visibility (spec §3.1). */142const cacheFor = (visibility: ContractVisibility) =>143 visibility === "public" ? "public, max-age=60" : "private, no-store";144145const isRefusal = Schema.is(Refusal);146147/** What the web says when the platform gave neither the ask nor a refusal. */148const UNANSWERED = [149 "The platform did not answer, so the web cannot read this ask now. Ask again in a moment.",150 "",151].join("\n");152153/**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 */158export 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 });171172/**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 */176export 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 );187188/** Where an ask's Markdown lives: its page's URL with `.md`. */189export const markdownPath = (project: string, ask: string) =>190 `/${project}/asks/${ask}.md`;191192/** The `Link` header that names an ask page's Markdown as an alternate of it. */193export 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
added:apps/web/src/routes/$project/answers/$ask.tsx+216 added
1import { RegistryProvider, useAtomValue } from "@effect/atom-react";2import { Client } from "@repo/protocol/contracts";3import { Verdict } from "@repo/protocol/domain/answer";4import { LandingView } from "@repo/protocol/domain/landing";5import { Outcome } from "@repo/protocol/domain/outcome";6import { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";7import type { LandedSha } from "@repo/protocol/ids";8import { createFileRoute, notFound } from "@tanstack/react-router";9import { createServerFn } from "@tanstack/react-start";10import { env } from "cloudflare:workers";11import { DateTime, Effect, Option, Predicate, Schema } from "effect";12import { AsyncResult, Atom } from "effect/reactivity";1314import { landingAtom, verdictAtom } from "../../../client/answer.ts";15import { AnswerView } from "../../../features/answer/answer-page.tsx";16import { answerPath } from "../../../features/ask/ask-page.tsx";17import { CODE, LINK } from "../../../features/ask/fields.tsx";18import { NoSuchAsk, notFoundFor } from "../../../features/ask/refused.tsx";19import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";20import { serverClient } from "../../../server/client.ts";2122// 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.2526/** The page's address, not yet decoded: the path's names and `?head=`. */27interface AnswerAddress {28 readonly ask: string;29 readonly head?: string | undefined;30 readonly project: string;31}3233/** The address, decoded: names the platform could hold, and a commit id. */34const AnswerPath = Schema.Struct({35 ask: AskId,36 head: Schema.optionalKey(CommitSha),37 project: ProjectName,38});3940/** What the page's loader carries from the server, encoded: whose answer, its verdict and landing, and when it was read. */41const AnswerPageData = Schema.Struct({42 ...AnswerPath.fields,43 landing: Schema.UndefinedOr(LandingView),44 now: Schema.DateTimeUtcFromString,45 verdict: Schema.UndefinedOr(Verdict),46});4748type AnswerPageData = typeof AnswerPageData.Type;4950/** The landing a verdict's answer made, when it landed. */51const landedBy = (verdict: Verdict | undefined): LandedSha | undefined =>52 verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome)53 ? verdict.outcome.sha54 : undefined;5556/** The verdict for the page and, if its answer landed, the landing; or a not-found carrying the refusal (a 404). */57export 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()));6263 const client = yield* Client;6465 const { verdict } = yield* client.verdict(path).pipe(66 Effect.catchTags({67 UnknownAsk: notFoundFor,68 UnknownProject: notFoundFor,69 })70 );7172 const sha = landedBy(verdict);7374 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 );8283 return yield* Schema.encodeEffect(AnswerPageData)({84 ...path,85 landing: Option.getOrUndefined(landing),86 now: yield* DateTime.now,87 verdict,88 });89 });9091const answerPage = createServerFn({ method: "GET" })92 .validator((address: AnswerAddress) => address)93 .handler(({ data }) =>94 Effect.runPromise(readAnswer(data).pipe(Effect.provide(serverClient(env))))95 );9697/** The verdict with its landing's trailers, from the landing's atom (seeded when the loader read it). */98const 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 );115116 const landing = Option.getOrElse(fresh, () =>117 seeded?.sha === sha ? seeded : undefined118 );119120 return landing === undefined ? (121 <AnswerView now={now} verdict={verdict} />122 ) : (123 <AnswerView landing={landing} now={now} verdict={verdict} />124 );125};126127/** The page over the verdict's atom, which starts from what the loader read and refetches when its keys change. */128const 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 );139140 const sha = landedBy(verdict);141142 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};154155const AnswerPage = () => {156 const read = Schema.decodeSync(AnswerPageData)(Route.useLoaderData());157 const { ask, head, landing, project, verdict } = read;158 const atom = verdictAtom(project, ask, head);159160 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 ];174175 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};195196/** An address with no refusal behind it: a name that can name nothing, or a `?head=` that is no commit id. */197const 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.";199200const AnswerNotFound = ({ data }: { readonly data?: unknown }) => (201 <NoSuchAsk data={data} nothing={NOTHING} />202);203204export 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
added:apps/web/src/routes/$project/asks/$ask.tsx+172 added
1import { RegistryProvider, useAtomValue } from "@effect/atom-react";2import { Client } from "@repo/protocol/contracts";3import { Ask } from "@repo/protocol/domain/ask";4import { createFileRoute, getRouteApi, notFound } from "@tanstack/react-router";5import { createServerFn } from "@tanstack/react-start";6import { env } from "cloudflare:workers";7import { DateTime, Effect, Option, Schema } from "effect";8import { AsyncResult, Atom } from "effect/reactivity";910import { askAtom } from "../../../client/ask.ts";11import { AskView } from "../../../features/ask/ask-page.tsx";12import {13 markdownAlternate,14 wantsMarkdown,15} from "../../../features/ask/markdown.ts";16import { NoSuchAsk, notFoundFor } from "../../../features/ask/refused.tsx";17import { pageTitle } from "../../../features/shared/layout.tsx";18import { serverClient } from "../../../server/client.ts";19import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";20import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";2122// 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`).2526/**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 */31export 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();4546/**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 */51export 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 });6364/** What the page's loader carries from the server, encoded: the ask, its brief, and when it was read. */65const AskPageData = Schema.Struct({66 ask: Ask,67 brief: Schema.NonEmptyString,68 now: Schema.DateTimeUtcFromString,69});7071/** The ask for its page, or a not-found carrying the platform's refusal (a 404). */72export const readAsk = (params: AskParams) =>73 Effect.gen(function* () {74 const path = yield* Schema.decodeEffect(AskPath)(params).pipe(75 Effect.mapError(() => notFound())76 );7778 const client = yield* Client;7980 const read = yield* client.showAsk(path).pipe(81 Effect.catchTags({82 UnknownAsk: notFoundFor,83 UnknownProject: notFoundFor,84 })85 );8687 return yield* Schema.encodeEffect(AskPageData)({88 ...read,89 now: yield* DateTime.now,90 });91 });9293const askPage = createServerFn({ method: "GET" })94 .validator((params: AskParams) => params)95 .handler(({ data }) =>96 Effect.runPromise(readAsk(data).pipe(Effect.provide(serverClient(env))))97 );9899const root = getRouteApi("__root__");100101type AskRead = Pick<typeof AskPageData.Type, "ask" | "brief">;102103/** The page over the ask's atom, which starts from what the loader read and refetches when its keys change. */104const 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 );119120 return (121 <AskView ask={ask} brief={brief} now={now} platformUrl={platformUrl} />122 );123};124125const AskPage = () => {126 const { platformUrl } = root.useLoaderData();127128 const { ask, brief, now } = Schema.decodeSync(AskPageData)(129 Route.useLoaderData()130 );131132 const atom = askAtom(ask.project, ask.id);133134 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};150151export 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 */8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import { Client, Contracts } from "@repo/protocol/contracts";11import { Outcome } from "@repo/protocol/domain/outcome";12import { AreaName, AskId } from "@repo/protocol/ids";13import {14 ChecksFailed,15 HeldBackFailed,16 UnknownAsk,17 UnknownCommit,18} from "@repo/protocol/refusal";19import { explain } from "@repo/protocol/render";20import { asTester, unanswered } from "@repo/protocol/testing";21import { isNotFound } from "@tanstack/react-router";22import { Effect, Layer, Ref, Schema } from "effect";23import { RpcTest } from "effect/rpc";2425import {26 AnswerView,27 HeldBackBits,28 LaneTable,29} from "../src/features/answer/answer-page.tsx";30import { Refusals } from "../src/features/ask/refused.tsx";31import { readAnswer } from "../src/routes/$project/answers/$ask.tsx";32import {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";4546const 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});5152const heldBackFailed = new HeldBackFailed({ area: "export", suite });5354const refused = verdictOf(55 Outcome.cases.Refused.make({ refusals: [checksFailed, heldBackFailed] })56);5758/** Each element that names a stage, as `[stage, state]`. */59const 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;6364 return stage === undefined || state === undefined ? [] : [[stage, state]];65 });6667/** Each lane row, as `[lane, result]`. */68const 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;7273 return lane === undefined || result === undefined ? [] : [[lane, result]];74 });7576describe(AnswerView, () => {77 const page = <AnswerView now={now} verdict={refused} />;7879 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 });9091 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 });100101 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;106107 expect(plainText(bits ?? "").trim()).toBe(`export 6/7 @ ${suite}`);108 });109110 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 });118119 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" }));121122 expect(textOf(<AnswerView now={now} verdict={passing} />)).not.toContain(123 "logs/datekit"124 );125 });126127 it("names the answer it judged and when", () => {128 const text = textOf(page);129130 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 });135136 it("says plainly when no answer has been checked yet", () => {137 const text = textOf(<AnswerView now={now} verdict={undefined} />);138139 expect(text).toContain("No answer to this ask has been checked yet");140 expect(text).not.toContain("Parse");141 });142143 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);147148 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});157158describe(LaneTable, () => {159 it("gives each lane's command and how long it ran", () => {160 const { lanes } = refused;161 const text = textOf(<LaneTable lanes={lanes} />);162163 expect(inOrder(text, ["lint", "bun run lint", "1.2 s"])).toBeTruthy();164 expect(inOrder(text, ["unit", "bun test", "8.3 s"])).toBeTruthy();165 });166167 it("says when no lane ran", () => {168 expect(textOf(<LaneTable lanes={[]} />)).toContain("No lane ran");169 });170});171172describe(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 ];178179 expect(textOf(<HeldBackBits results={results} />).trim()).toBe(180 `export 6/7 @ ${suite} parse 3/3 @ ${suite}`181 );182 });183});184185/** What the stub platform was asked: verdicts and landings. */186interface Asked {187 readonly landings: number;188 readonly verdicts: number;189}190191/**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 */196const 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 }));211212 if (payload.ask !== askId) {213 return yield* new UnknownAsk({ ask: payload.ask });214 }215216 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 }));225226 if (!landingKnown || payload.sha !== landedSha) {227 return yield* new UnknownCommit({ sha: payload.sha });228 }229230 return { landing };231 })232 )233 ),234 asTester,235 ])236 );237238const nothingAsked: Asked = { landings: 0, verdicts: 0 };239240describe(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 });245246 const read = yield* readAnswer({ ask: askId, project }).pipe(247 Effect.provide(platformAt(asked, landed))248 );249250 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 );255256 it.effect("asks for no landing when the answer did not land", () =>257 Effect.gen(function* () {258 const asked = yield* Ref.make(nothingAsked);259260 const read = yield* readAnswer({ ask: askId, project }).pipe(261 Effect.provide(platformAt(asked, refused.outcome))262 );263264 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 );269270 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 });276277 const read = yield* readAnswer({ ask: askId, project }).pipe(278 Effect.provide(platformAt(asked, landed, false))279 );280281 expect(read.verdict?.outcome._tag).toBe("Landed");282 expect(read.landing).toBeUndefined();283 })284 );285286 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");292293 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 );303304 expect(isNotFound(failed)).toBeTruthy();305306 const carried = yield* Schema.decodeUnknownEffect(Refusals)(307 isNotFound(failed) ? failed.data : undefined308 );309310 expect(explain(carried)).toStrictEqual(311 explain([new UnknownAsk({ ask: missing })])312 );313 })314 );315316 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);321322 const failed = yield* Effect.flip(323 readAnswer({ ask: askId, head: "9b1c3e5", project }).pipe(324 Effect.provide(platformAt(asked, refused.outcome))325 )326 );327328 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 */7import { Brand } from "@repo/brand";8import type { Verdict } from "@repo/protocol/domain/answer";9import type { Ask } from "@repo/protocol/domain/ask";10import { CheckSpec } from "@repo/protocol/domain/check";11import { Glob } from "@repo/protocol/domain/common";12import type { LandingView } from "@repo/protocol/domain/landing";13import type { Outcome } from "@repo/protocol/domain/outcome";14import {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";29import { DateTime } from "effect";30import type { ReactElement } from "react";31import { renderToStaticMarkup } from "react-dom/server";3233export const project = ProjectName.make("datekit");3435export const askId = AskId.make("parse-iso-week");3637/** The moment every view test renders at. */38export const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");3940export 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};6768/** The brief as the platform renders it for `showAsk`; the web serves it untouched. */69export const brief = `# Parse ISO week dates like 2026-W41-37071Ask \`parse-iso-week\` in datekit, a \`fix\` ask from ines-v.7273## Territory7475The module \`@datekit/parse\`: \`packages/parse/**\`.7677## Current7879parseWeek returns null for 2026-W41-3.80`;8182const sha = (digit: string) => digit.repeat(40);8384export const suite = SuiteRoot.make(`sha256:${"4f2a".repeat(16)}`);8586export const landedSha = LandedSha.make(87 "9b1c3e5d7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c"88);8990/** A verdict on the ask's latest answer: lint passed, unit failed, one held-back area 6 of 7. */91export 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});120121export 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};135136/** The entities React writes for text, and what each reads as. */137const ENTITIES: ReadonlyMap<string, string> = new Map([138 ["&#x27;", "'"],139 ["&amp;", "&"],140 ["&gt;", ">"],141 ["&lt;", "<"],142 ["&quot;", '"'],143]);144145export const markupOf = (element: ReactElement) =>146 renderToStaticMarkup(element);147148/** What a reader sees of `markup`: the text without its tags, entities decoded. */149export 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, " ");157158/** What a reader sees of `element`, rendered. */159export const textOf = (element: ReactElement) => plainText(markupOf(element));160161/** Whether each of `parts` appears in `text`, each after the one before. */162export const inOrder = (text: string, parts: readonly string[]) => {163 let from = 0;164165 for (const part of parts) {166 const at = text.indexOf(part, from);167168 if (at === -1) {169 return false;170 }171172 from = at + part.length;173 }174175 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 */8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import { Client, Contracts } from "@repo/protocol/contracts";11import { AskId, ProjectName } from "@repo/protocol/ids";12import { UnknownAsk, UnknownProject } from "@repo/protocol/refusal";13import { explain } from "@repo/protocol/render";14import { asTester, unanswered } from "@repo/protocol/testing";15import { Effect, Exit, Layer, Ref } from "effect";16import { RpcTest } from "effect/rpc";1718import {19 askMarkdownResponse,20 refusalsMarkdown,21 wantsMarkdown,22} from "../src/features/ask/markdown.ts";23import {24 askPageHandler,25 askPageHeaders,26} from "../src/routes/$project/asks/$ask.tsx";27import { askMarkdownHandler } from "../src/routes/$project/asks/{$ask}[.]md.ts";28import { ask, askId, brief, project } from "./ask-fixtures.ts";2930const WEB = "https://web-test.example.workers.dev";3132const MARKDOWN = "text/markdown; charset=utf-8";3334const BROWSER =35 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";3637/**38 * A platform that knows datekit and its one ask, counting `showAsk` calls,39 * as a route's client.40 */41const 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);4950 if (payload.project !== project) {51 return yield* new UnknownProject({ project: payload.project });52 }5354 if (payload.ask !== askId) {55 return yield* new UnknownAsk({ ask: payload.ask });56 }5758 return { ask, brief };59 })60 )61 ),62 asTester,63 ])64 );6566/** A platform that cannot be reached: every call dies on the way. */67const unreachable = () =>68 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(69 Layer.provide([unanswered, asTester])70 );7172const get = (path: string, accept?: string) =>73 new Request(`${WEB}${path}`, {74 headers: accept === undefined ? {} : { accept },75 });7677const params = (askName: string, projectName: string = project) => ({78 ask: askName,79 project: projectName,80});8182/** What a response says, read whole. */83const 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 );9495/** The page's own render, which a Markdown request must never reach. */96const PAGE = new Response("<!doctype html><title>the page</title>");9798describe("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);104105 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 );114115 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 );125126 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);131132 const answered = askPageHandler(platformOf(calls))({133 next: () => PAGE,134 params: params(askId),135 request: get(`/datekit/asks/${askId}`, BROWSER),136 });137138 expect(answered).toBe(PAGE);139 expect(yield* Ref.get(calls)).toBe(0);140 })141 );142});143144describe("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);150151 const response = yield* Effect.promise(() =>152 askMarkdownHandler(platformOf(calls))({153 params: params(askId),154 request: get(`/datekit/asks/${askId}.md`, BROWSER),155 })156 );157158 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 );167168 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") });174175 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 );181182 const seen = yield* read(response);183184 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 );199200 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);205206 const response = yield* Effect.promise(() =>207 askMarkdownHandler(platformOf(calls))({208 params: params(askId, "nowhere"),209 request: get(`/nowhere/asks/${askId}.md`),210 })211 );212213 const seen = yield* read(response);214215 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 );226227 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);232233 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 );239240 const seen = yield* read(response);241242 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 );248249 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 );259260 const seen = yield* read(response);261262 expect(seen.status).toBe(502);263 expect(seen.contentType).toBe(MARKDOWN);264 expect(seen.cacheControl).toBe("no-store");265 })266 );267});268269describe("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 });276277 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});283284describe(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 );292293 expect([seen.status, seen.cacheControl, seen.body]).toStrictEqual([294 200,295 "private, no-store",296 brief,297 ]);298 })299 );300});301302describe(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;308309 expect(refusalsMarkdown(refusals)).toBe(310 [311 "```text",312 ...explain(refusals),313 "```",314 "",315 `Next: \`${Brand.cli} asks\``,316 "",317 ].join("\n")318 );319 });320});321322const accepting = (accept: string | undefined) =>323 wantsMarkdown(get("/datekit/asks/parse-iso-week", accept));324325describe(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 });335336 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 */7import { describe, expect, it } from "@effect/vitest";8import { Brand } from "@repo/brand";9import { Client, Contracts } from "@repo/protocol/contracts";10import { AskId, Handle } from "@repo/protocol/ids";11import { UnknownAsk } from "@repo/protocol/refusal";12import { explain } from "@repo/protocol/render";13import { asTester, unanswered } from "@repo/protocol/testing";14import { isNotFound } from "@tanstack/react-router";15import { Effect, Layer, Ref, Schema } from "effect";16import { RpcTest } from "effect/rpc";1718import { AskView } from "../src/features/ask/ask-page.tsx";19import { NoSuchAsk, Refusals } from "../src/features/ask/refused.tsx";20import { readAsk } from "../src/routes/$project/asks/$ask.tsx";21import {22 ask,23 askId,24 brief,25 inOrder,26 markupOf,27 now,28 project,29 textOf,30} from "./ask-fixtures.ts";3132const platformUrl = "https://platform-test.example.workers.dev";3334/** The markup inside the first `<pre>`. */35const inPre = (markup: string) =>36 /<pre\b[^>]*>(?<inner>.*?)<\/pre>/su.exec(markup)?.groups?.inner;3738const page = (shown = ask) => (39 <AskView ask={shown} brief={brief} now={now} platformUrl={platformUrl} />40);4142describe(AskView, () => {43 it("titles the page with the want, then reads the brief's sections in order", () => {44 const markup = markupOf(page());4546 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 });6263 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 );6768 expect(text).not.toContain("Current behaviour");69 expect(text).not.toContain("Out of scope");70 expect(text).not.toContain("Terms");71 });7273 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 });8788 it("gives the ask's territory, and who asked it when", () => {89 const text = textOf(page());9091 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 });99100 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 });109110 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 };115116 const text = textOf(page(blocked));117 const markup = markupOf(page(blocked));118119 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 });130131 it("names nothing it waits on when nothing blocks it", () => {132 expect(textOf(page())).not.toContain("Waits on");133 });134135 it("links a step of a migrate to its parent ask", () => {136 const child = { ...ask, parent: AskId.make("migrate-week-api") };137138 expect(markupOf(page(child))).toContain(139 'href="/datekit/asks/migrate-week-api"'140 );141 });142143 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 };149150 const text = textOf(page(held));151152 expect(text).toContain("Held for newcomers");153 expect(markupOf(page(held))).toContain('href="/people/okonkwo"');154 });155156 it("gives no claim line once the ask is closed", () => {157 const text = textOf(page({ ...ask, state: "closed" }));158159 expect(text).toContain("Closed");160 expect(text).not.toContain(`${Brand.cli} claim`);161 });162163 it("links to the ask's Markdown and to the verdict on its latest answer", () => {164 const markup = markupOf(page());165166 expect(markup).toContain(`href="/datekit/asks/${askId}.md"`);167 expect(markup).toContain(`href="/datekit/answers/${askId}"`);168 });169170 it("shows the brief exactly as an agent reads it", () => {171 expect(inPre(markupOf(page()))).toBe(inPre(markupOf(<pre>{brief}</pre>)));172 });173});174175describe(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") });178179 // The not-found's data, as it crosses from the server: encoded, then cloned.180 const data = structuredClone(Schema.encodeSync(Refusals)([refusal]));181182 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 });190191 it("says nothing is at an address that names no ask at all", () => {192 expect(textOf(<NoSuchAsk />)).toContain("Nothing is at this address");193 });194195 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});201202/** A platform that knows datekit's one ask, counting `showAsk` calls. */203const 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);211212 if (payload.ask !== askId) {213 return yield* new UnknownAsk({ ask: payload.ask });214 }215216 return { ask, brief };217 })218 )219 ),220 asTester,221 ])222 );223224describe(readAsk, () => {225 it.effect("reads the ask and its brief for the page", () =>226 Effect.gen(function* () {227 const calls = yield* Ref.make(0);228229 const read = yield* readAsk({ ask: askId, project }).pipe(230 Effect.provide(platformOf(calls))231 );232233 expect([read.ask.id, read.brief]).toStrictEqual([askId, brief]);234 expect(yield* Ref.get(calls)).toBe(1);235 })236 );237238 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");244245 const failed = yield* Effect.flip(246 readAsk({ ask: missing, project }).pipe(247 Effect.provide(platformOf(calls))248 )249 );250251 expect(isNotFound(failed)).toBeTruthy();252253 const carried = yield* Schema.decodeUnknownEffect(Refusals)(254 isNotFound(failed) ? failed.data : undefined255 );256257 expect(explain(carried)).toStrictEqual(258 explain([new UnknownAsk({ ask: missing })])259 );260 })261 );262263 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);268269 const failed = yield* Effect.flip(270 readAsk({ ask: "Not_An-Ask", project }).pipe(271 Effect.provide(platformOf(calls))272 )273 );274275 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});