Skip to content
Myr

Serve an ask as a page and as Markdown, and an answer's verdict stage by stage

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- /<project>/asks/<ask> renders the ask (want as title, kind, state, territory, check, who asked, parent, who it is held for, what it waits on, the brief's sections, and the clone, claim and check lines with Brand.cli). Its GET answers `Accept: text/markdown` with showAsk's brief untouched; the page carries `Link: <…/<ask>.md>; rel="alternate"; type="text/markdown"` and `Vary: Accept`. - /<project>/asks/<ask>.md always answers Markdown. The route file is `{$ask}[.]md.ts`, not `$ask[.]md.ts`: router-core reads `$ask.md` as one param named `ask.md`, while `{$ask}.md` is the param with a literal suffix (read in router-core's parseSegment, confirmed in vite dev). - Negotiation (`wantsMarkdown`) honours q-values: Markdown only when the request names `text/markdown` itself, above zero and at least text/html's quality; a wildcard alone or a browser gets the page. No user-agent lists. - Markdown answers: the brief 200 with `cache-control: public, max-age=60`, read from showAsk's `Visibility` annotation (a maintainers contract would be `private, no-store`); a refusal 404 whose body is its `explain` lines in a text block, then `Next: \`<next>\``; a path that can name no ask 404 without asking the platform; no answer from the platform 502. Only the brief is cacheable. - /<project>/answers/<ask> renders the verdict: the fields judged (head, base, merged tree, patch id, check version, when), the shared stage strip and outcome (a refusal as git printed it), each lane's result and time, held-back results only as `<area> <passed>/<total> @ <suite>`, and a landed answer's credit trailers with `git show <sha>`. `?head=` shows an earlier answer; a head that is not a commit id is a 404. - Pages read through loaders and server functions over `serverClient`, so they render on the server and an unknown project or ask is a real 404 (the refusal rides in the not-found's data, encoded, decoded on the page). The routes render from the client atoms (`askAtom`, `verdictAtom`, `landingAtom`), seeded through a page-scoped RegistryProvider with what the loader read, so nothing refetches until a key changes (510's live views). - TanStack infers route options in source order, so `loader` comes before `head` (and `validateSearch` before `loaderDeps`). - Tests: ask-markdown.test.ts (negotiation table, both URLs, refusals, the unreachable platform, the page's headers), ask.test.tsx (AskView and the not-found page), answer.test.tsx (AnswerView, LaneTable, HeldBackBits); web 85 tests. Checked in vite dev over a stub backend (not committed): the `.md` route wins over the page route, headers and statuses as above, no hydration errors, no sideways scroll at 360 px, light and dark. - bytes:check: web entry 717,829 of 1,665,000; JavaScript 2,100,499 of 2,500,000 (511 recorded 1,175,500): the unminified SSR chunks now carry Effect's RPC and HTTP clients and the atom runtime. - ASSUMPTION: an ask held for "people" means a person answers it, not an agent (GPR lens-asks-people.md: web claim, sign-off, mentor).

authored by oscabriel · committed by oscabriel · parent eebd79b · Browse files · 14 files+2246 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+2246 added−0 removed

  • tests:+856 added−0 removed
  • other:+1390 added−0 removed

14 files+2246 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+253 added
1/**2 * The verdict on an answer, as a report sheet: the fields that name what3 * was judged (head, base, merged tree, patch id, check version, when), the4 * gate's stages in a strip with the outcome under it (a refusal reads as5 * `git push` printed it), each lane's result and time, the held-back checks6 * as one line per area, and, once it landed, the landing's credit trailers7 * and its commit.8 *9 * Held-back checks show only what `HeldBackResult` carries: an area, how10 * many passed of how many, and the suite's root (spec D17). A lane's log is11 * never shown here; a refusal that needs it names it, with the command12 * that reads it.13 */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, 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);165166const LINK = "decoration-rule underline hover:decoration-current";167168export const AnswerView = ({169 landing,170 now,171 verdict,172}: {173 readonly landing?: LandingView;174 readonly now: DateTime.Utc;175 readonly verdict: Verdict | undefined;176}) => {177 if (verdict === undefined) {178 return <EmptyState title="No answer to this ask has been checked yet." />;179 }180181 return (182 <>183 <Fields label="What was judged">184 <Field label="Ask">185 <a186 className={`${LINK} ${CODE}`}187 href={askPath(verdict.project, verdict.ask)}188 >189 {verdict.ask}190 </a>191 </Field>192 <Field label="Judged">193 <When at={verdict.at} now={now} />{" "}194 <span className="text-muted-foreground">195 by the {verdict.verifier}196 </span>197 </Field>198 <Field label="Head">199 <Sha sha={verdict.head} />200 </Field>201 <Field label="Base">202 <Sha sha={verdict.base} />203 </Field>204 <Field label="Merged tree">205 <Sha sha={verdict.tree} />206 </Field>207 <Field label="Patch id">208 <Sha sha={verdict.patchId} />209 </Field>210 <Field label="Check version">211 <code className={CODE}>{verdict.checkVersion}</code>212 </Field>213 </Fields>214215 <Region id="answer-gate" title="Gate">216 <StageStrip outcome={verdict.outcome} stage={verdict.stage} />217 <OutcomeView outcome={verdict.outcome} />218 </Region>219220 <Region id="answer-lanes" title="Lanes">221 <LaneTable lanes={verdict.lanes} />222 </Region>223224 {verdict.heldBack.length === 0 ? null : (225 <Region id="answer-held-back" title="Held-back checks">226 <p className="text-muted-foreground max-w-[70ch] text-sm">227 Checks the answer could not see. Each area shows how many passed,228 and the root of the suite the project committed to before the claim.229 </p>230 <HeldBackBits results={verdict.heldBack} />231 </Region>232 )}233234 {landing === undefined ? null : (235 <Region id="answer-landing" title="Landing">236 <CreditTrailers237 assisted={landing.assisted}238 credits={landing.credits}239 {...(landing.heldBackTrailer === undefined240 ? {}241 : { heldBack: landing.heldBackTrailer })}242 />243 <div className="flex min-w-0 flex-col gap-1.5">244 <span className="text-muted-foreground text-xs font-medium">245 The landing commit, in a clone of {landing.project}246 </span>247 <CommandLine command={`git show ${landing.sha}`} />248 </div>249 </Region>250 )}251 </>252 );253};
added:apps/web/src/features/ask/ask-page.tsx+328 added
1/**2 * An ask, as a person reads it: the want as the page's title, the fields3 * (kind, state, territory, check, who asked, its parent, who it is held4 * for), what it waits on, the brief's sections, and the lines that clone5 * the project, claim the ask and check an answer. Agents read the same ask6 * as Markdown (`markdown.ts`); the page links to it and shows the brief7 * verbatim, so a person sees what their agent reads.8 */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, 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}`;3233const LINK = "decoration-rule underline hover:decoration-current";3435/** Each state as a mark, a word and its role colour (none for open: nothing is happening yet). */36const states = {37 claimed: { icon: CircleDot, tone: "", word: "Claimed" },38 closed: { icon: Minus, tone: "text-muted-foreground", word: "Closed" },39 open: { icon: Circle, tone: "", word: "Open" },40 waitingOnParent: {41 icon: Hourglass,42 tone: "text-waiting",43 word: "Waiting on its parent",44 },45} as const satisfies Record<46 AskState,47 { readonly icon: LucideIcon; readonly tone: string; readonly word: string }48>;4950const StateMark = ({ state }: { readonly state: AskState }) => {51 const { icon: Icon, tone, word } = states[state];5253 return (54 <span className={`font-medium ${tone}`}>55 <Icon56 aria-hidden="true"57 className="mr-1.5 inline-block size-3.5 align-[-0.15em]"58 />59 {word}60 </span>61 );62};6364const Code = ({ children }: { readonly children: ReactNode }) => (65 <code className={CODE}>{children}</code>66);6768/** What judges an answer: the check's kind in words, then what it names. */69const checkOf = (check: CheckSpec) =>70 CheckSpec.match(check, {71 LintToZero: ({ rule, territory }) => (72 <>73 Lint to zero: <Code>{rule}</Code>74 {territory === undefined ? null : (75 <>76 {" "}77 in <Code>{territory}</Code>78 </>79 )}80 </>81 ),82 Migrate: ({ from, to }) => (83 <>84 Migrate: <Code>{from}</Code>85 {to === undefined ? null : (86 <>87 {" "}88 to <Code>{to}</Code>89 </>90 )}91 </>92 ),93 Ratchet: ({ ratchet }) => (94 <>95 Ratchet <Code>{ratchet}</Code> goes down96 </>97 ),98 RedThenGreen: ({ path }) => (99 <>100 Red, then green: <Code>{path}</Code>101 </>102 ),103 SymbolAbsent: ({ symbol }) => (104 <>105 Nothing uses <Code>{symbol}</Code>106 </>107 ),108 });109110/** Asks, each linking to its page, separated by commas. */111const AskLinks = ({112 asks,113 project,114}: {115 readonly asks: readonly AskId[];116 readonly project: ProjectName;117}) =>118 asks.map((ask, index) => (119 <span key={ask}>120 {index === 0 ? null : ", "}121 <a className={`${LINK} ${CODE}`} href={askPath(project, ask)}>122 {ask}123 </a>124 </span>125 ));126127const reserved = {128 newcomers: "Held for newcomers",129 people: "Held for a person to answer, not an agent",130} as const;131132const BriefPart = ({133 children,134 title,135}: {136 readonly children: ReactNode;137 readonly title: string;138}) => (139 <div className="flex flex-col gap-1.5">140 <h3 className="text-sm font-semibold">{title}</h3>141 {children}142 </div>143);144145const BriefList = ({ items }: { readonly items: readonly string[] }) => (146 <ul className="flex list-[square] flex-col gap-1 pl-5 marker:text-[color:var(--rule-strong)]">147 {items.map((item) => (148 <li key={item}>{item}</li>149 ))}150 </ul>151);152153/** The lines that start an answer: clone, claim (it prints the fork's remote), check before the push. */154const TakeIt = ({155 ask,156 platformUrl,157}: {158 readonly ask: Ask;159 readonly platformUrl: string;160}) => {161 if (ask.state === "closed") {162 return (163 <p className="text-muted-foreground text-sm">164 This ask is closed, so it takes no claim.165 </p>166 );167 }168169 const steps = [170 ["Clone the project", `git clone ${platformUrl}/${ask.project}.git`],171 [172 "Claim the ask; the claim prints your fork's remote",173 `${Brand.cli} claim ${ask.id} --project ${ask.project}`,174 ],175 [176 "Check your answer before you push it",177 `${Brand.cli} check --ask ${ask.id}`,178 ],179 ] as const;180181 return (182 <ol className="flex flex-col gap-3">183 {steps.map(([label, command]) => (184 <li className="flex min-w-0 flex-col gap-1.5" key={command}>185 <span className="text-muted-foreground text-xs font-medium">186 {label}187 </span>188 <CommandLine command={command} />189 </li>190 ))}191 </ol>192 );193};194195export const AskView = ({196 ask,197 brief,198 now,199 platformUrl,200}: {201 readonly ask: Ask;202 readonly brief: string;203 readonly now: DateTime.Utc;204 readonly platformUrl: string;205}) => {206 const { context, current, outOfScope, terms } = ask.brief;207208 return (209 <PageShell title={ask.brief.want}>210 <Fields label="The ask">211 <Field label="Ask">212 <Code>{ask.id}</Code>213 </Field>214 <Field label="State">215 <StateMark state={ask.state} />216 </Field>217 <Field label="Kind">218 <Code>{ask.kind}</Code>219 </Field>220 <Field label="Asked by">221 <HandleLink handle={ask.askedBy} />{" "}222 <span className="text-muted-foreground">223 · opened <When at={ask.openedAt} now={now} />224 </span>225 </Field>226 <Field label="Territory">227 <Code>{ask.territory.module}</Code>228 <span className="text-muted-foreground">: </span>229 {ask.territory.paths.map((path, index) => (230 <span key={path}>231 {index === 0 ? null : ", "}232 <Code>{path}</Code>233 </span>234 ))}235 </Field>236 <Field label="Check">{checkOf(ask.check)}</Field>237 {ask.parent === undefined ? null : (238 <Field label="Step of">239 <AskLinks asks={[ask.parent]} project={ask.project} />240 </Field>241 )}242 {ask.reserve === undefined ? null : (243 <Field label="Who may take it">244 {reserved[ask.reserve]}245 {ask.mentor === undefined ? null : (246 <>247 , mentored by <HandleLink handle={ask.mentor} />248 </>249 )}250 </Field>251 )}252 </Fields>253254 {ask.blockedBy.length === 0 ? null : (255 <p className="text-waiting flex items-start gap-2" data-state="waiting">256 <Hourglass aria-hidden="true" className="mt-1 size-4 shrink-0" />257 <span className="text-foreground min-w-0">258 <strong className="text-waiting font-semibold">Waits on</strong>{" "}259 <AskLinks asks={ask.blockedBy} project={ask.project} /> to land260 first; a claim waits until they do.261 </span>262 </p>263 )}264265 <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:gap-12">266 <Region id="ask-brief" title="Brief">267 <div className="flex max-w-[70ch] flex-col gap-5">268 {current === undefined ? null : (269 <BriefPart title="Current behaviour">270 <p>{current}</p>271 </BriefPart>272 )}273 {outOfScope === undefined ? null : (274 <BriefPart title="Out of scope">275 <BriefList items={outOfScope} />276 </BriefPart>277 )}278 {terms === undefined || terms.length === 0 ? null : (279 <BriefPart title="Terms">280 <BriefList items={terms} />281 </BriefPart>282 )}283 {context === undefined || context.length === 0 ? null : (284 <BriefPart title="Context">285 <BriefList items={context} />286 </BriefPart>287 )}288 <details className="border-rule group border-t pt-3">289 <summary className="text-muted-foreground hover:text-foreground cursor-pointer text-sm select-none">290 The brief, as an agent reads it291 </summary>292 <pre className="border-rule bg-surface mt-3 overflow-x-auto border p-3 font-mono text-[0.8125rem] leading-6 whitespace-pre-wrap">293 {brief}294 </pre>295 </details>296 </div>297 </Region>298299 <div className="flex min-w-0 flex-col gap-8">300 <Region id="ask-take" title="Take it">301 <TakeIt ask={ask} platformUrl={platformUrl} />302 </Region>303 <Region id="ask-more" title="See also">304 <ul className="flex flex-col gap-1.5 text-sm">305 <li>306 <a className={LINK} href={answerPath(ask.project, ask.id)}>307 Where the latest answer stands308 </a>309 </li>310 <li>311 <a312 className={LINK}313 href={markdownPath(ask.project, ask.id)}314 type="text/markdown"315 >316 This ask as Markdown317 </a>318 <span className="text-muted-foreground">319 , for an agent to fetch320 </span>321 </li>322 </ul>323 </Region>324 </div>325 </div>326 </PageShell>327 );328};
added:apps/web/src/features/ask/fields.tsx+56 added
added:apps/web/src/features/ask/markdown.ts+193 added
1/**2 * An ask as Markdown, for agents: a harness reads an ask with one plain3 * fetch, either with `Accept: text/markdown` on the ask's own URL or at the4 * same URL with `.md`. The request decides; no user-agent list does.5 *6 * The brief is the platform's: `showAsk` renders it once, and the web only7 * serves it. A refusal is set the way `git push` printed it, from8 * `@repo/protocol/render` (AGENTS.md principle 3), then its next command.9 * Pure: a `Request` or an `Exit` in, a string or a `Response` out.10 */11import { Brand } from "@repo/brand";12import { Refusal } from "@repo/protocol/refusal";13import { explain } from "@repo/protocol/render";14import { Array, Cause, Exit, Option, Schema } from "effect";1516const MARKDOWN = "text/markdown; charset=utf-8";1718/** Who may share the answer: a `public` contract's for a minute, a `maintainers` one's never. */19export type ContractVisibility = "public" | "maintainers";2021/** One range of an `Accept` header: `text/markdown;q=0.8`. */22interface MediaRange {23 readonly quality: number;24 readonly subtype: string;25 readonly type: string;26}2728/** A q-value as RFC 9110 writes it: 0 to 1, at most three decimals; anything else is no range. */29const QUALITY = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;3031const rangesOf = (accept: string): readonly MediaRange[] =>32 accept.split(",").flatMap((entry) => {33 const [media = "", ...parameters] = entry34 .split(";")35 .map((part) => part.trim().toLowerCase());3637 const [type = "", subtype = ""] = media.split("/");38 const q = parameters.find((parameter) => parameter.startsWith("q="));39 const quality = q === undefined ? "1" : q.slice(2);4041 return type === "" || subtype === "" || !QUALITY.test(quality)42 ? []43 : [{ quality: Number(quality), subtype, type }];44 });4546/** How closely `range` names `type/subtype`: 3 by name, 2 by `type/*`, 1 by `*\/*`, 0 not at all. */47const closeness = (range: MediaRange, type: string, subtype: string) => {48 if (range.type === type) {49 if (range.subtype === subtype) {50 return 3;51 }5253 return range.subtype === "*" ? 2 : 0;54 }5556 return range.type === "*" && range.subtype === "*" ? 1 : 0;57};5859/** The quality the closest range gives `type/subtype` (RFC 9110 §12.5.1), and how close it was. */60const preferenceFor = (61 ranges: readonly MediaRange[],62 type: string,63 subtype: string64) => {65 let best = { close: 0, quality: 0 };6667 for (const range of ranges) {68 const close = closeness(range, type, subtype);6970 if (close > best.close) {71 best = { close, quality: range.quality };72 }73 }7475 return best;76};7778/**79 * Whether the request asks for the ask as Markdown: it names `text/markdown`80 * itself, with a quality above zero and at least the quality it gives81 * `text/html`. A wildcard alone (`*\/*`, `text/*`, or no `Accept` at all)82 * gets the page, as a browser does.83 */84export const wantsMarkdown = (request: Request) => {85 const ranges = rangesOf(request.headers.get("accept") ?? "");86 const markdown = preferenceFor(ranges, "text", "markdown");87 const html = preferenceFor(ranges, "text", "html");8889 return (90 markdown.close === 3 &&91 markdown.quality > 0 &&92 markdown.quality >= html.quality93 );94};9596/** The longest run of backticks in `text`. */97const longestTicks = (text: string) =>98 Math.max(0, ...[...text.matchAll(/`+/gu)].map(([run]) => run.length));99100/** `text` as inline code, its delimiter longer than any backticks inside it. */101const inlineCode = (text: string) => {102 const ticks = longestTicks(text);103 const fence = "`".repeat(ticks + 1);104105 return ticks === 0 ? `${fence}${text}${fence}` : `${fence} ${text} ${fence}`;106};107108/**109 * Refusals as an agent reads them in Markdown: every refusal's `explain`110 * lines in one text block, verbatim (git's `remote:` lines, without the111 * prefix), then each distinct `next` command once, as its own paragraph.112 */113export const refusalsMarkdown = (114 refusals: Array.NonEmptyReadonlyArray<Refusal>115) => {116 const lines = explain(refusals);117 const fence = "`".repeat(Math.max(3, longestTicks(lines.join("\n")) + 1));118 const nexts = Array.dedupe(refusals.map((refusal) => refusal.next));119120 return [121 `${fence}text`,122 ...lines,123 fence,124 "",125 nexts.map((next) => `Next: ${inlineCode(next)}`).join("\n\n"),126 "",127 ].join("\n");128};129130const markdown = (body: string, status: number, cacheControl: string) =>131 new Response(body, {132 headers: {133 "cache-control": cacheControl,134 "content-type": MARKDOWN,135 vary: "Accept",136 },137 status,138 });139140/** What a Markdown answer may be cached for, by its contract's visibility (spec §3.1). */141const cacheFor = (visibility: ContractVisibility) =>142 visibility === "public" ? "public, max-age=60" : "private, no-store";143144const isRefusal = Schema.is(Refusal);145146/** What the web says when the platform gave neither the ask nor a refusal. */147const UNANSWERED = [148 "The platform did not answer, so the web cannot read this ask now. Ask again in a moment.",149 "",150].join("\n");151152/**153 * How reading an ask ended, as the Markdown response: the brief (200,154 * cacheable as its contract's visibility allows); a refusal (404, its155 * Markdown); or no answer from the platform (502). Only a brief is cached.156 */157export const askMarkdownResponse = <E>(158 result: Exit.Exit<{ readonly brief: string }, E>,159 visibility: ContractVisibility160): Response =>161 Exit.match(result, {162 onFailure: (cause) =>163 Option.match(Option.filter(Cause.findErrorOption(cause), isRefusal), {164 onNone: () => markdown(UNANSWERED, 502, "no-store"),165 onSome: (refusal) =>166 markdown(refusalsMarkdown([refusal]), 404, "no-store"),167 }),168 onSuccess: ({ brief }) => markdown(brief, 200, cacheFor(visibility)),169 });170171/**172 * The answer to a path that can name no ask: a project's and an ask's names173 * are lowercase words joined by single dashes, so the platform is not asked.174 */175export const noAskAt = (path: string) =>176 markdown(177 [178 `No ask is at ${inlineCode(path)}: a project's and an ask's names are lowercase words joined by single dashes.`,179 "",180 `Next: ${inlineCode(`${Brand.cli} asks`)}`,181 "",182 ].join("\n"),183 404,184 "no-store"185 );186187/** Where an ask's Markdown lives: its page's URL with `.md`. */188export const markdownPath = (project: string, ask: string) =>189 `/${project}/asks/${ask}.md`;190191/** The `Link` header that names an ask page's Markdown as an alternate of it. */192export const markdownAlternate = (project: string, ask: string) =>193 `<${markdownPath(project, ask)}>; rel="alternate"; type="text/markdown"`;
added:apps/web/src/features/ask/refused.tsx+40 added
added:apps/web/src/routes/$project/answers/$ask.tsx+224 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 } from "../../../features/ask/fields.tsx";18import {19 NotFoundView,20 notFoundFor,21 Refusals,22} from "../../../features/ask/refused.tsx";23import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";24import { serverClient } from "../../../server/client.ts";2526// The answer page: the latest verdict on an answer to an ask, stage by27// stage, or with `?head=<sha>` the verdict on an earlier answer. A landed28// answer shows its landing's credit trailers.2930/** The page's address, not yet decoded: the path's names and `?head=`. */31interface AnswerAddress {32 readonly ask: string;33 readonly head?: string | undefined;34 readonly project: string;35}3637/** The address, decoded: names the platform could hold, and a commit id. */38const AnswerPath = Schema.Struct({39 ask: AskId,40 head: Schema.optionalKey(CommitSha),41 project: ProjectName,42});4344/** What the page's loader carries from the server, encoded: whose answer, its verdict and landing, and when it was read. */45const AnswerPageData = Schema.Struct({46 ...AnswerPath.fields,47 landing: Schema.UndefinedOr(LandingView),48 now: Schema.DateTimeUtcFromString,49 verdict: Schema.UndefinedOr(Verdict),50});5152type AnswerPageData = typeof AnswerPageData.Type;5354/** The landing a verdict's answer made, when it landed. */55const landedBy = (verdict: Verdict | undefined): LandedSha | undefined =>56 verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome)57 ? verdict.outcome.sha58 : undefined;5960/** The verdict for the page and, if its answer landed, the landing; or a not-found carrying the refusal (a 404). */61const readAnswer = ({ ask, head, project }: AnswerAddress) =>62 Effect.gen(function* () {63 const path = yield* Schema.decodeEffect(AnswerPath)(64 head === undefined ? { ask, project } : { ask, head, project }65 ).pipe(Effect.mapError(() => notFound()));6667 const client = yield* Client;6869 const { verdict } = yield* client.verdict(path).pipe(70 Effect.catchTags({71 UnknownAsk: notFoundFor,72 UnknownProject: notFoundFor,73 })74 );7576 const sha = landedBy(verdict);7778 const landing =79 sha === undefined80 ? Option.none()81 : yield* client.landing({ project: path.project, sha }).pipe(82 Effect.map((found) => Option.some(found.landing)),83 // The verdict names a landing the platform no longer finds: show the verdict alone.84 Effect.catchTag("UnknownCommit", () => Effect.succeedNone)85 );8687 return yield* Schema.encodeEffect(AnswerPageData)({88 ...path,89 landing: Option.getOrUndefined(landing),90 now: yield* DateTime.now,91 verdict,92 });93 });9495const answerPage = createServerFn({ method: "GET" })96 .validator((address: AnswerAddress) => address)97 .handler(({ data }) =>98 Effect.runPromise(readAnswer(data).pipe(Effect.provide(serverClient(env))))99 );100101/** The verdict with its landing's trailers, from the landing's atom (seeded when the loader read it). */102const LandedAnswer = ({103 now,104 project,105 seeded,106 sha,107 verdict,108}: {109 readonly now: DateTime.Utc;110 readonly project: ProjectName;111 readonly seeded: LandingView | undefined;112 readonly sha: LandedSha;113 readonly verdict: Verdict;114}) => {115 const fresh = Option.map(116 AsyncResult.value(useAtomValue(landingAtom(project, sha))),117 (found) => found.landing118 );119120 const landing = Option.getOrElse(fresh, () =>121 seeded?.sha === sha ? seeded : undefined122 );123124 return landing === undefined ? (125 <AnswerView now={now} verdict={verdict} />126 ) : (127 <AnswerView landing={landing} now={now} verdict={verdict} />128 );129};130131/** The page over the verdict's atom, which starts from what the loader read and refetches when its keys change. */132const FreshAnswer = ({133 atom,134 read,135}: {136 readonly atom: ReturnType<typeof verdictAtom>;137 readonly read: AnswerPageData;138}) => {139 const { verdict } = Option.getOrElse(140 AsyncResult.value(useAtomValue(atom)),141 () => read142 );143144 const sha = landedBy(verdict);145146 return verdict === undefined || sha === undefined ? (147 <AnswerView now={read.now} verdict={verdict} />148 ) : (149 <LandedAnswer150 now={read.now}151 project={read.project}152 seeded={read.landing}153 sha={sha}154 verdict={verdict}155 />156 );157};158159const LINK = "decoration-rule underline hover:decoration-current";160161const AnswerPage = () => {162 const read = Schema.decodeSync(AnswerPageData)(Route.useLoaderData());163 const { ask, head, landing, project, verdict } = read;164 const atom = verdictAtom(project, ask, head);165166 const seeds = [167 Atom.initialValue(168 atom,169 AsyncResult.success(verdict === undefined ? {} : { verdict })170 ),171 ...(landing === undefined172 ? []173 : [174 Atom.initialValue(175 landingAtom(project, landing.sha),176 AsyncResult.success({ landing })177 ),178 ]),179 ];180181 return (182 <PageShell title={`Answer to ${ask}`}>183 {head === undefined ? null : (184 <p className="text-sm">185 An earlier answer, at <code className={CODE}>{head.slice(0, 7)}</code>186 .{" "}187 <a className={LINK} href={answerPath(project, ask)}>188 The latest answer189 </a>190 </p>191 )}192 <RegistryProvider193 initialValues={seeds}194 key={`${project}/${ask}/${head ?? ""}`}195 >196 <FreshAnswer atom={atom} read={read} />197 </RegistryProvider>198 </PageShell>199 );200};201202/** A not-found's refusals, decoded where they arrive; none when it carries none. */203const decodeRefusals = Schema.decodeUnknownOption(Refusals);204205const AnswerNotFound = ({ data }: { readonly data?: unknown }) => (206 <NotFoundView207 refusals={Option.getOrUndefined(decodeRefusals(data))}208 title="No such ask"209 />210);211212export const Route = createFileRoute("/$project/answers/$ask")({213 // TanStack infers each option from the ones before it, so the search comes214 // before the loader that reads it.215 validateSearch: ({ head }: { readonly head?: unknown }) =>216 Predicate.isString(head) ? { head } : {},217 loaderDeps: ({ search }) => ({ head: search.head }),218 loader: ({ deps, params }) => answerPage({ data: { ...params, ...deps } }),219 head: ({ params }) => ({220 meta: [{ title: pageTitle(`Answer to ${params.ask}`) }],221 }),222 component: AnswerPage,223 notFoundComponent: AnswerNotFound,224});
added:apps/web/src/routes/$project/asks/{$ask}[.]md.ts+68 added
added:apps/web/src/routes/$project/asks/$ask.tsx+174 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 {17 NotFoundView,18 notFoundFor,19 Refusals,20} from "../../../features/ask/refused.tsx";21import { pageTitle } from "../../../features/shared/layout.tsx";22import { serverClient } from "../../../server/client.ts";23import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";24import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";2526// The ask page: the brief, its fields and the lines that take it. The same27// URL answers `Accept: text/markdown` with the brief as Markdown (the GET28// handler below), and its `.md` twin always does (`{$ask}[.]md.ts`).2930/**31 * The ask page's GET, as a function of its client: a request that asks for32 * Markdown gets the ask's Markdown, as at its `.md` URL; any other falls33 * through to the page.34 */35export const askPageHandler =36 (clientFor: ClientFor) =>37 <Next,>({38 next,39 params,40 request,41 }: {42 readonly next: () => Next;43 readonly params: AskParams;44 readonly request: Request;45 }): Promise<Response> | Next =>46 wantsMarkdown(request)47 ? askMarkdownHandler(clientFor)({ params, request })48 : next();4950/** The page's headers: its Markdown as an alternate, and that the URL answers by `Accept`. */51export const askPageHeaders = ({ params }: { readonly params: AskParams }) => ({52 link: markdownAlternate(params.project, params.ask),53 vary: "Accept",54});5556/** What the page's loader carries from the server, encoded: the ask, its brief, and when it was read. */57const AskPageData = Schema.Struct({58 ask: Ask,59 brief: Schema.NonEmptyString,60 now: Schema.DateTimeUtcFromString,61});6263/** The ask for its page, or a not-found carrying the platform's refusal (a 404). */64const readAsk = (params: AskParams) =>65 Effect.gen(function* () {66 const path = yield* Schema.decodeEffect(AskPath)(params).pipe(67 Effect.mapError(() => notFound())68 );6970 const client = yield* Client;7172 const read = yield* client.showAsk(path).pipe(73 Effect.catchTags({74 UnknownAsk: notFoundFor,75 UnknownProject: notFoundFor,76 })77 );7879 return yield* Schema.encodeEffect(AskPageData)({80 ...read,81 now: yield* DateTime.now,82 });83 });8485const askPage = createServerFn({ method: "GET" })86 .validator((params: AskParams) => params)87 .handler(({ data }) =>88 Effect.runPromise(readAsk(data).pipe(Effect.provide(serverClient(env))))89 );9091const root = getRouteApi("__root__");9293type AskRead = Pick<typeof AskPageData.Type, "ask" | "brief">;9495/** The page over the ask's atom, which starts from what the loader read and refetches when its keys change. */96const FreshAsk = ({97 atom,98 now,99 platformUrl,100 read,101}: {102 readonly atom: ReturnType<typeof askAtom>;103 readonly now: DateTime.Utc;104 readonly platformUrl: string;105 readonly read: AskRead;106}) => {107 const { ask, brief } = Option.getOrElse(108 AsyncResult.value(useAtomValue(atom)),109 () => read110 );111112 return (113 <AskView ask={ask} brief={brief} now={now} platformUrl={platformUrl} />114 );115};116117const AskPage = () => {118 const { platformUrl } = root.useLoaderData();119120 const { ask, brief, now } = Schema.decodeSync(AskPageData)(121 Route.useLoaderData()122 );123124 const atom = askAtom(ask.project, ask.id);125126 return (127 <RegistryProvider128 initialValues={[129 Atom.initialValue(atom, AsyncResult.success({ ask, brief })),130 ]}131 key={`${ask.project}/${ask.id}`}132 >133 <FreshAsk134 atom={atom}135 now={now}136 platformUrl={platformUrl}137 read={{ ask, brief }}138 />139 </RegistryProvider>140 );141};142143/** A not-found's refusals, decoded where they arrive; none when it carries none. */144const decodeRefusals = Schema.decodeUnknownOption(Refusals);145146const AskNotFound = ({ data }: { readonly data?: unknown }) => (147 <NotFoundView148 refusals={Option.getOrUndefined(decodeRefusals(data))}149 title="No such ask"150 />151);152153export const Route = createFileRoute("/$project/asks/$ask")({154 // TanStack infers each option from the ones before it: the loader comes155 // first, so `head` reads its data.156 loader: ({ params }) => askPage({ data: params }),157 head: ({ loaderData }) => ({158 meta: [159 {160 title: pageTitle(161 loaderData === undefined ? "No such ask" : loaderData.ask.brief.want162 ),163 },164 ],165 }),166 headers: askPageHeaders,167 component: AskPage,168 notFoundComponent: AskNotFound,169 server: {170 handlers: {171 GET: askPageHandler((request) => serverClient(env, request)),172 },173 },174});
added:apps/web/test/answer.test.tsx+163 added
1/**2 * The answer page: the latest verdict on an ask's answer, stage by stage.3 * The gate's stages in a strip, each lane's result and time, held-back4 * checks only as one line per area (its counts and suite root, nothing5 * more), the outcome, and a refusal as `git push` printed it. A landed6 * answer shows its landing's credit trailers and the commit.7 */8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import { Outcome } from "@repo/protocol/domain/outcome";11import { AreaName } from "@repo/protocol/ids";12import { ChecksFailed, HeldBackFailed } from "@repo/protocol/refusal";13import { explain } from "@repo/protocol/render";1415import {16 AnswerView,17 HeldBackBits,18 LaneTable,19} from "../src/features/answer/answer-page.tsx";20import {21 inOrder,22 landedSha,23 landing,24 markupOf,25 now,26 suite,27 textOf,28 verdictOf,29} from "./ask-fixtures.ts";3031const checksFailed = new ChecksFailed({32 lane: "unit",33 logRef: "logs/datekit/parse-iso-week/unit",34 next: `${Brand.cli} evidence logs/datekit/parse-iso-week/unit`,35});3637const heldBackFailed = new HeldBackFailed({ area: "export", suite });3839const refused = verdictOf(40 Outcome.cases.Refused.make({ refusals: [checksFailed, heldBackFailed] })41);4243/** Each element that names a stage, as `[stage, state]`. */44const stagesOf = (markup: string) =>45 [...markup.matchAll(/<li\b[^>]*>/gu)].flatMap(([tag]) => {46 const stage = /data-stage="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;47 const state = /data-state="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;4849 return stage === undefined || state === undefined ? [] : [[stage, state]];50 });5152/** Each lane row, as `[lane, result]`. */53const lanesOf = (markup: string) =>54 [...markup.matchAll(/<tr\b[^>]*>/gu)].flatMap(([tag]) => {55 const lane = /data-lane="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;56 const result = /data-result="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;5758 return lane === undefined || result === undefined ? [] : [[lane, result]];59 });6061describe(AnswerView, () => {62 const page = <AnswerView now={now} verdict={refused} />;6364 it("shows the stages the answer passed, the one that refused it, and the ones it never reached", () => {65 expect(stagesOf(markupOf(page))).toStrictEqual([66 ["parse", "passed"],67 ["shape", "passed"],68 ["merge", "passed"],69 ["cheap", "passed"],70 ["checks", "refused"],71 ["heldBack", "pending"],72 ["human", "pending"],73 ]);74 });7576 it("shows each lane with its result", () => {77 expect(lanesOf(markupOf(page))).toStrictEqual([78 ["lint", "passed"],79 ["unit", "failed"],80 ]);81 expect(82 inOrder(textOf(page), ["lint", "passed", "unit", "failed"])83 ).toBeTruthy();84 });8586 it("shows held-back checks only as an area's counts and its suite root", () => {87 expect(textOf(page)).toContain(`export 6/7 @ ${suite}`);88 });8990 it("shows the refusals' explain lines in order, as git printed them", () => {91 expect(92 inOrder(93 textOf(page),94 explain([checksFailed, heldBackFailed]).map((line) => line.trim())95 )96 ).toBeTruthy();97 });9899 it("never shows where a lane's log is kept outside the refusal that names it", () => {100 const passing = verdictOf(Outcome.cases.Checking.make({ stage: "checks" }));101102 expect(textOf(<AnswerView now={now} verdict={passing} />)).not.toContain(103 "logs/datekit"104 );105 });106107 it("names the answer it judged and when", () => {108 const text = textOf(page);109110 expect(text).toContain("bbbbbbb");111 expect(text).toContain("aaaaaaa");112 expect(text).toContain("redThenGreen@0.0.0+5e1d");113 expect(text).toContain("20 min ago");114 });115116 it("says plainly when no answer has been checked yet", () => {117 const text = textOf(<AnswerView now={now} verdict={undefined} />);118119 expect(text).toContain("No answer to this ask has been checked yet");120 expect(text).not.toContain("Parse");121 });122123 it("shows a landed answer's credit trailers in trailer order, its held-back trailer, and its commit", () => {124 const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));125 const element = <AnswerView landing={landing} now={now} verdict={landed} />;126 const text = textOf(element);127128 expect(text).toContain("Landed as 9b1c3e5");129 expect(130 inOrder(text, ["Asked-by: ines-v", "Signed-off-by: okafor"])131 ).toBeTruthy();132 expect(text).toContain(`Held-back: export 7/7 @ ${suite}`);133 expect(text).toContain("Assisted-by: claude-code:opus-5 (verified)");134 expect(text).toContain(`git show ${landedSha}`);135 });136});137138describe(LaneTable, () => {139 it("gives each lane's command and how long it ran", () => {140 const { lanes } = refused;141 const text = textOf(<LaneTable lanes={lanes} />);142143 expect(inOrder(text, ["lint", "bun run lint", "1.2 s"])).toBeTruthy();144 expect(inOrder(text, ["unit", "bun test", "8.3 s"])).toBeTruthy();145 });146147 it("says when no lane ran", () => {148 expect(textOf(<LaneTable lanes={[]} />)).toContain("No lane ran");149 });150});151152describe(HeldBackBits, () => {153 it("shows one line per area, and nothing else about the held-back checks", () => {154 const results = [155 { area: AreaName.make("export"), passed: 6, suite, total: 7 },156 { area: AreaName.make("parse"), passed: 3, suite, total: 3 },157 ];158159 expect(textOf(<HeldBackBits results={results} />).trim()).toBe(160 `export 6/7 @ ${suite} parse 3/3 @ ${suite}`161 );162 });163});
added:apps/web/test/ask-fixtures.ts+173 added
1/**2 * datekit's `parse-iso-week` (a fictional ask in a fictional project), and3 * the answers to it, as the platform's contracts return them: the ask and4 * its brief (`showAsk`), a verdict (`verdict`) and a landing (`landing`).5 * Also how the view tests read rendered markup.6 */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: the markup without its tags, entities decoded. */149export const textOf = (element: ReactElement) =>150 markupOf(element)151 .replaceAll(/<[^>]+>/gu, " ")152 .replaceAll(153 /&(?:#x27|amp|gt|lt|quot);/gu,154 (entity) => ENTITIES.get(entity) ?? entity155 )156 .replaceAll(/\s+/gu, " ");157158/** Whether each of `parts` appears in `text`, each after the one before. */159export const inOrder = (text: string, parts: readonly string[]) => {160 let from = 0;161162 for (const part of parts) {163 const at = text.indexOf(part, from);164165 if (at === -1) {166 return false;167 }168169 from = at + part.length;170 }171172 return true;173};
added:apps/web/test/ask-markdown.test.ts+324 added
1/**2 * An ask answers as Markdown, so a harness reads it with one plain fetch:3 * the ask's URL with `Accept: text/markdown`, or the same URL with `.md`.4 * The body is the brief the platform rendered (`showAsk`), untouched; an5 * unknown ask is a 404 whose body is the refusal, as git would print it.6 * A browser asking for HTML gets the page.7 */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, Layer, Ref } from "effect";16import { RpcTest } from "effect/rpc";1718import {19 refusalsMarkdown,20 wantsMarkdown,21} from "../src/features/ask/markdown.ts";22import {23 askPageHandler,24 askPageHeaders,25} from "../src/routes/$project/asks/$ask.tsx";26import { askMarkdownHandler } from "../src/routes/$project/asks/{$ask}[.]md.ts";27import { ask, askId, brief, project } from "./ask-fixtures.ts";2829const WEB = "https://web-test.example.workers.dev";3031const MARKDOWN = "text/markdown; charset=utf-8";3233const BROWSER =34 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";3536/**37 * A platform that knows datekit and its one ask, counting `showAsk` calls,38 * as a route's client.39 */40const platformOf = (calls: Ref.Ref<number>) => () =>41 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(42 Layer.provide([43 Layer.mergeAll(44 unanswered,45 Contracts.toLayerHandler("showAsk", (payload) =>46 Effect.gen(function* () {47 yield* Ref.update(calls, (count) => count + 1);4849 if (payload.project !== project) {50 return yield* new UnknownProject({ project: payload.project });51 }5253 if (payload.ask !== askId) {54 return yield* new UnknownAsk({ ask: payload.ask });55 }5657 return { ask, brief };58 })59 )60 ),61 asTester,62 ])63 );6465/** A platform that cannot be reached: every call dies on the way. */66const unreachable = () =>67 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(68 Layer.provide([unanswered, asTester])69 );7071const get = (path: string, accept?: string) =>72 new Request(`${WEB}${path}`, {73 headers: accept === undefined ? {} : { accept },74 });7576const params = (askName: string, projectName: string = project) => ({77 ask: askName,78 project: projectName,79});8081/** What a response says, read whole. */82const read = (response: Response) =>83 Effect.map(84 Effect.promise(() => response.text()),85 (body) => ({86 body,87 cacheControl: response.headers.get("cache-control"),88 contentType: response.headers.get("content-type"),89 status: response.status,90 vary: response.headers.get("vary"),91 })92 );9394/** The page's own render, which a Markdown request must never reach. */95const PAGE = new Response("<!doctype html><title>the page</title>");9697describe("an ask's URL with Accept: text/markdown", () => {98 it.effect(99 "answers with the brief showAsk gives, as Markdown that public caches may keep a minute",100 () =>101 Effect.gen(function* () {102 const calls = yield* Ref.make(0);103104 const response = yield* Effect.promise(() =>105 Promise.resolve(106 askPageHandler(platformOf(calls))({107 next: () => PAGE,108 params: params(askId),109 request: get(`/datekit/asks/${askId}`, "text/markdown"),110 })111 )112 );113114 expect(yield* read(response)).toStrictEqual({115 body: brief,116 cacheControl: "public, max-age=60",117 contentType: MARKDOWN,118 status: 200,119 vary: "Accept",120 });121 expect(yield* Ref.get(calls)).toBe(1);122 })123 );124125 it.effect(126 "falls through to the page when the reader asks for HTML, and reads no ask",127 () =>128 Effect.gen(function* () {129 const calls = yield* Ref.make(0);130131 const answered = askPageHandler(platformOf(calls))({132 next: () => PAGE,133 params: params(askId),134 request: get(`/datekit/asks/${askId}`, BROWSER),135 });136137 expect(answered).toBe(PAGE);138 expect(yield* Ref.get(calls)).toBe(0);139 })140 );141});142143describe("an ask's .md URL", () => {144 it.effect(145 "answers with the same Markdown, whatever the request accepts",146 () =>147 Effect.gen(function* () {148 const calls = yield* Ref.make(0);149150 const response = yield* Effect.promise(() =>151 askMarkdownHandler(platformOf(calls))({152 params: params(askId),153 request: get(`/datekit/asks/${askId}.md`, BROWSER),154 })155 );156157 expect(yield* read(response)).toStrictEqual({158 body: brief,159 cacheControl: "public, max-age=60",160 contentType: MARKDOWN,161 status: 200,162 vary: "Accept",163 });164 })165 );166167 it.effect(168 "answers an unknown ask with 404 and the UnknownAsk refusal, as git prints it, then its next command",169 () =>170 Effect.gen(function* () {171 const calls = yield* Ref.make(0);172 const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });173174 const response = yield* Effect.promise(() =>175 askMarkdownHandler(platformOf(calls))({176 params: params("no-such-ask"),177 request: get("/datekit/asks/no-such-ask.md"),178 })179 );180181 const seen = yield* read(response);182183 expect(seen.status).toBe(404);184 expect(seen.contentType).toBe(MARKDOWN);185 expect(seen.body).toBe(186 [187 "```text",188 ...explain([refusal]),189 "```",190 "",191 `Next: \`${Brand.cli} asks\``,192 "",193 ].join("\n")194 );195 expect(seen.cacheControl).toBe("no-store");196 })197 );198199 it.effect(200 "answers an unknown project with 404 and the UnknownProject refusal",201 () =>202 Effect.gen(function* () {203 const calls = yield* Ref.make(0);204205 const response = yield* Effect.promise(() =>206 askMarkdownHandler(platformOf(calls))({207 params: params(askId, "nowhere"),208 request: get(`/nowhere/asks/${askId}.md`),209 })210 );211212 const seen = yield* read(response);213214 expect(seen.status).toBe(404);215 expect(seen.body).toBe(216 refusalsMarkdown([217 new UnknownProject({ project: ProjectName.make("nowhere") }),218 ])219 );220 expect(seen.body).toContain(221 "UnknownProject: no project is named nowhere"222 );223 })224 );225226 it.effect(227 "answers a path that can name no ask with 404, and asks the platform nothing",228 () =>229 Effect.gen(function* () {230 const calls = yield* Ref.make(0);231232 const response = yield* Effect.promise(() =>233 askMarkdownHandler(platformOf(calls))({234 params: params("Not_An-Ask"),235 request: get("/datekit/asks/Not_An-Ask.md"),236 })237 );238239 const seen = yield* read(response);240241 expect(seen.status).toBe(404);242 expect(seen.contentType).toBe(MARKDOWN);243 expect(seen.body).toContain("Not_An-Ask");244 expect(yield* Ref.get(calls)).toBe(0);245 })246 );247248 it.effect(249 "answers 502 when the platform does not answer, and keeps it out of caches",250 () =>251 Effect.gen(function* () {252 const response = yield* Effect.promise(() =>253 askMarkdownHandler(unreachable)({254 params: params(askId),255 request: get(`/datekit/asks/${askId}.md`),256 })257 );258259 const seen = yield* read(response);260261 expect(seen.status).toBe(502);262 expect(seen.contentType).toBe(MARKDOWN);263 expect(seen.cacheControl).toBe("no-store");264 })265 );266});267268describe("the ask page", () => {269 it("names its Markdown as an alternate, and says it varies by Accept", () => {270 expect(askPageHeaders({ params: params(askId) })).toStrictEqual({271 link: `</datekit/asks/${askId}.md>; rel="alternate"; type="text/markdown"`,272 vary: "Accept",273 });274 });275});276277describe(refusalsMarkdown, () => {278 it("sets every refusal's explain lines in one text block, then each distinct next command once", () => {279 const refusals = [280 new UnknownProject({ project: ProjectName.make("nowhere") }),281 new UnknownAsk({ ask: askId }),282 ] as const;283284 expect(refusalsMarkdown(refusals)).toBe(285 [286 "```text",287 ...explain(refusals),288 "```",289 "",290 `Next: \`${Brand.cli} asks\``,291 "",292 ].join("\n")293 );294 });295});296297const accepting = (accept: string | undefined) =>298 wantsMarkdown(get("/datekit/asks/parse-iso-week", accept));299300describe(wantsMarkdown, () => {301 it.each([302 ["text/markdown"],303 ["text/markdown, text/html"],304 ["text/html;q=0.9, text/markdown"],305 ["text/markdown;q=0.8, */*;q=0.1"],306 ["Text/Markdown; charset=utf-8"],307 ])("serves Markdown to %o", (accept) => {308 expect(accepting(accept)).toBeTruthy();309 });310311 it.each([312 [undefined],313 ["*/*"],314 ["text/*"],315 ["text/html"],316 [BROWSER],317 ["text/markdown;q=0.5, text/html"],318 ["text/markdown;q=0, text/html;q=0.1"],319 ["text/markdown;q=0"],320 ["application/json"],321 ])("serves the page to %o", (accept) => {322 expect(accepting(accept)).toBeFalsy();323 });324});
added:apps/web/test/ask.test.tsx+196 added
1/**2 * The ask page, as a person reads it: the brief (want, current behaviour,3 * out of scope, terms, context), its kind, territory, check and state, who4 * asked, its parent and blockers, and the exact lines that clone, claim and5 * check it. Rendered to HTML with `react-dom/server`.6 */7import { describe, expect, it } from "@effect/vitest";8import { Brand } from "@repo/brand";9import { AskId, Handle } from "@repo/protocol/ids";10import { UnknownAsk } from "@repo/protocol/refusal";11import { explain } from "@repo/protocol/render";12import { Schema } from "effect";1314import { AskView } from "../src/features/ask/ask-page.tsx";15import { NotFoundView, Refusals } from "../src/features/ask/refused.tsx";16import {17 ask,18 askId,19 brief,20 inOrder,21 markupOf,22 now,23 textOf,24} from "./ask-fixtures.ts";2526const platformUrl = "https://platform-test.example.workers.dev";2728const page = (shown = ask) => (29 <AskView ask={shown} brief={brief} now={now} platformUrl={platformUrl} />30);3132describe(AskView, () => {33 it("titles the page with the want, then reads the brief's sections in order", () => {34 const markup = markupOf(page());3536 expect(markup).toMatch(37 /<h1\b[^>]*>Parse ISO week dates like 2026-W41-3<\/h1>/u38 );39 expect(40 inOrder(textOf(page()), [41 "Current behaviour",42 "parseWeek returns null for 2026-W41-3.",43 "Out of scope",44 "Formatting week dates back to strings.",45 "Terms",46 "Week date: a date written as year, week and weekday.",47 "Context",48 "ISO 8601 numbers weeks from the Monday of the week holding 4 January.",49 ])50 ).toBeTruthy();51 });5253 it("leaves out a section the brief does not have", () => {54 const text = textOf(55 page({ ...ask, brief: { want: "Parse ISO week dates like 2026-W41-3" } })56 );5758 expect(text).not.toContain("Current behaviour");59 expect(text).not.toContain("Out of scope");60 expect(text).not.toContain("Terms");61 });6263 it("gives the ask's name, kind, state and check", () => {64 expect(65 inOrder(textOf(page()), [66 "Ask",67 askId,68 "State",69 "Open",70 "Kind",71 "fix",72 "Check",73 "test/parse-week.test.ts",74 ])75 ).toBeTruthy();76 });7778 it("gives the ask's territory, and who asked it when", () => {79 const text = textOf(page());8081 expect(82 inOrder(text, ["Asked by", "ines-v", "opened 2 d ago"])83 ).toBeTruthy();84 expect(85 inOrder(text, ["Territory", "@datekit/parse", "packages/parse/**"])86 ).toBeTruthy();87 expect(markupOf(page())).toContain('href="/people/ines-v"');88 });8990 it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {91 expect(92 inOrder(textOf(page()), [93 `git clone ${platformUrl}/datekit.git`,94 `${Brand.cli} claim ${askId} --project datekit`,95 `${Brand.cli} check --ask ${askId}`,96 ])97 ).toBeTruthy();98 });99100 it("names the asks a blocked ask waits on, each linking to its page", () => {101 const blocked = {102 ...ask,103 blockedBy: [AskId.make("split-format"), AskId.make("split-parse")],104 };105106 const text = textOf(page(blocked));107 const markup = markupOf(page(blocked));108109 expect(110 inOrder(text, [111 "Waits on",112 "split-format",113 "split-parse",114 "to land first",115 ])116 ).toBeTruthy();117 expect(markup).toContain('href="/datekit/asks/split-format"');118 expect(markup).toContain('href="/datekit/asks/split-parse"');119 });120121 it("names nothing it waits on when nothing blocks it", () => {122 expect(textOf(page())).not.toContain("Waits on");123 });124125 it("links a step of a migrate to its parent ask", () => {126 const child = { ...ask, parent: AskId.make("migrate-week-api") };127128 expect(markupOf(page(child))).toContain(129 'href="/datekit/asks/migrate-week-api"'130 );131 });132133 it("says when an ask is held for newcomers, and who mentors them", () => {134 const held = {135 ...ask,136 mentor: Handle.make("okonkwo"),137 reserve: "newcomers" as const,138 };139140 const text = textOf(page(held));141142 expect(text).toContain("Held for newcomers");143 expect(markupOf(page(held))).toContain('href="/people/okonkwo"');144 });145146 it("gives no claim line once the ask is closed", () => {147 const text = textOf(page({ ...ask, state: "closed" }));148149 expect(text).toContain("Closed");150 expect(text).not.toContain(`${Brand.cli} claim`);151 });152153 it("links to the ask's Markdown and to the verdict on its latest answer", () => {154 const markup = markupOf(page());155156 expect(markup).toContain(`href="/datekit/asks/${askId}.md"`);157 expect(markup).toContain(`href="/datekit/answers/${askId}"`);158 });159160 it("shows the brief exactly as an agent reads it", () => {161 expect(textOf(page())).toContain(162 textOf(<pre>{brief}</pre>)163 .trim()164 .slice(0, 60)165 );166 });167});168169describe(NotFoundView, () => {170 it("shows the refusal a not-found carried from the server, as git printed it", () => {171 const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });172173 // The refusal crosses from the server encoded, as a loader's not-found carries it.174 const carried = Schema.decodeUnknownSync(Refusals)(175 structuredClone(Schema.encodeSync(Refusals)([refusal]))176 );177178 const text = textOf(179 <NotFoundView refusals={carried} title="No such ask" />180 );181182 expect(183 inOrder(text, [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(193 textOf(<NotFoundView refusals={undefined} title="No such ask" />)194 ).toContain("Nothing is at this address");195 });196});