Skip to content
Myr

Rebuild the ask and answer pages: state, whose move and what runs next, and an answer read like a run of the gate

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

- Answer page: the outcome is the hero under the ask's want (a step up, whose move, a refusal drawn whole by RefusalView), then the gate's strip, failed lanes open with `myr evidence <logRef> --project <p>`, passed lanes folded into one line ("4 lanes passed in 16.8 s"; lanes run one after another, so their times add up), held-back lines, and the landing's credit. What was judged moved to the inspector (and to the end of main below the shell's width), with State, Rounds, Claim, Family and Territory and check. - The strip reads "not needed" for the decider and held-back stages an answer never needed: the page passes `stageStates` what the verdict holds (a `Decided-by` on the landing, or a round of that head that waited on a person; held-back results on the verdict). - No answer yet is never a dead end: unclaimed gives the claim command, claimed says who holds it and links the ask. - Live: the page keeps one tree position as the answer lands, so the hero's word and mark settle in (150 ms, only after the first paint) and the landing stamps once; a landing the server's read already held never stamps. - Ask page: the want as the title (a step down past 80 characters), a status line per state (open to take and who it is held for; claimed by the claimant from the event fold; refused at the stage the verdict names; landed as), the brief, the check with its source inline (first 30 lines until asked for the whole; its path alone when it cannot be read), every judged round as a row, and the Markdown the agent reads. Inspector: State, Take it or Claim, Territory and check, Family, Posture. - A family's delete child says what it waits on in the family's terms and reads "Open to take" once every sibling landed; "Waits on … to land first" stays only for an ask outside a family whose blockers have not landed. - A round shows the last word on it (its verdict, or the landing that closed the ask), not the "checking" it was judged with. - Not found: "No such ask", the refusal verbatim, then the project and the open asks as the way onward. - The pages' server reads (`readAsk`, `readAnswer`) and their reads beside the subject (events kept to the asks drawn, the family's parent, the check's file) live in `features/answer/{reads,subject}.ts`, called only from the server functions: exported from a route file they sat in the root chunk and pushed its preloads over their ceiling. Both routes send `branchPage`'s Cache-Control; the ask's `vary` and `link` are unchanged. - Tests: the answer and ask view and loader cases rewritten for the new markup and extended (hero first, provenance in the inspector, failed lanes first, not needed vs passed, empty states, round words, family member and delete child states, long wants, inline check source, onward links). - ASSUMPTION: a family's delete child is the stored child named `<parent>-delete`, as the platform names it when it splits a migrate ask.

authored by oscabriel · committed by oscabriel · parent e817d6c · Browse files · 10 files+2607 added−764 removed
This commit

State

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

Diff stats

10 files+2607 added−764 removed

  • tests:+832 added−157 removed
  • other:+1775 added−607 removed

10 files+2607 added−764 removed

modified:apps/web/src/features/answer/answer-page.tsx+591 added-165 removed
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. The base and the landing link their commit pages; the8 * head and the merged tree stay plain, since they live in the claim's fork,9 * which the code browser never reads (ADR 0019).2 * An answer, read like a run of the gate: where it stands first, then the3 * stages it passed, the lanes (failed ones open, passed ones folded into a4 * line), the held-back checks as one line per area, and, once it landed,5 * the landing's credit and its commit. What was judged (head, base, merged6 * tree, patch id) is plumbing, so it sits last, in the inspector.7 *8 * - The outcome is the hero: the status line a step up, whose move it is,9 * and a refusal drawn whole by `RefusalView`, as `git push` printed it.10 * When the outcome changes while the page is open its word and mark11 * settle in, and a landing that happened then is stamped once.12 * - A stage the answer never needed (no decider took part, no held-back13 * checks judged it) reads not needed, never passed.14 * - With no answer judged yet, the page says who holds the ask, or gives15 * the command that claims it: never a dead end.16 *17 * Held-back checks show only what `HeldBackResult` carries: an area, how12 * many passed of how many, and the suite's root. A lane's log is13 * never shown here; a refusal that needs it names it, with the command14 * that reads it.18 * many passed of how many, and the suite's root. A lane's log is named19 * only by the command that reads it. The head and the merged tree live in20 * the claim's fork, which the code browser never reads, so only the base21 * and the landing link their commit pages.22 */23import { Brand } from "@repo/brand";24import type {25 HeldBackResult,26 LaneOutcome,27 LaneResult,28 Verdict,29} from "@repo/protocol/domain/answer";30import type { Ask } from "@repo/protocol/domain/ask";31import type { LandingView } from "@repo/protocol/domain/landing";32import { Outcome } from "@repo/protocol/domain/outcome";33import type { AskId, CommitSha, Handle } from "@repo/protocol/ids";34import { ChecksFailed } from "@repo/protocol/refusal";35import type { DateTime } from "effect";24import {25 Ban,26 Check,27 LockKeyhole,28 RotateCcw,29 TriangleAlert,30 X,31} from "lucide-react";32import type { LucideIcon } from "lucide-react";36import { ChevronDown, LockKeyhole } from "lucide-react";37import { useState } from "react";38import type { ReactNode } from "react";3934import {35 Table,36 TableBody,37 TableCell,38 TableHead,39 TableHeader,40 TableRow,41} from "../../components/ui/table.tsx";42import { Field, Fields, Region } from "../ask/fields.tsx";43import { commitHref } from "../code/paths.ts";44import { CODE, LINK } from "../shared/classes.ts";40import { Region } from "../ask/fields.tsx";41import { commitHref, shortSha } from "../code/paths.ts";42import type { AskProgress } from "../shared/ask-progress.ts";43import { CommandLine } from "../shared/command.tsx";44import { CreditTrailers } from "../shared/credits.tsx";45import { EmptyState } from "../shared/empty.tsx";46import {47 ClaimFacts,48 FamilyFacts,49 ProvenanceFacts,50 RoundsFacts,51 StateFacts,52 TerritoryFacts,53 verdictProvenance,54} from "../shared/facts.tsx";55import { AppLink } from "../shared/link.tsx";56import { StateMarkIcon } from "../shared/marks.tsx";57import type { StateMark } from "../shared/marks.tsx";58import { OutcomeView, StageStrip } from "../shared/outcome.tsx";49import { askPath } from "../shared/paths.ts";50import { When } from "../shared/time.tsx";59import { answerPath, askPath } from "../shared/paths.ts";60import { MetaCode, MetaLine } from "../shared/row.tsx";61import type { Crumb } from "../shared/shell/sections.ts";62import { Workspace } from "../shared/shell/workspace.tsx";63import { StatusLine } from "../shared/status-line.tsx";64import type { StatusSubject } from "../shared/status-line.tsx";65import { distanceInWords, When } from "../shared/time.tsx";66import {67 deleteChildOf,68 familyHead,69 holdsOf,70 roundOf,71 roundsAsTheyStand,72} from "./subject.ts";7374/** How long a lane ran: "640 ms", "8.3 s", "2 min 5 s". */75export const durationText = (millis: number) => {76 if (millis < 1000) {
8 unmodified lines
8586 return `${Math.floor(seconds / 60)} min ${seconds % 60} s`;87};8867/** Each lane result as a mark, a word and its role colour (DESIGN.md: the word first). */89/** Each lane result as a mark, a word and its role colour: the word first. */90const results = {69 blocked: { icon: Ban, tone: "text-waiting", word: "blocked" },70 failed: { icon: X, tone: "text-refused", word: "failed" },71 flaked: { icon: RotateCcw, tone: "text-waiting", word: "flaked" },72 loadError: { icon: TriangleAlert, tone: "text-refused", word: "load error" },73 passed: { icon: Check, tone: "text-landed", word: "passed" },91 blocked: { mark: "waiting", tone: "text-waiting", word: "blocked" },92 failed: { mark: "refused", tone: "text-refused", word: "failed" },93 flaked: { mark: "retry", tone: "text-waiting", word: "flaked" },94 loadError: { mark: "refused", tone: "text-refused", word: "load error" },95 passed: { mark: "passed", tone: "text-landed", word: "passed" },96} as const satisfies Record<97 LaneOutcome,76 { readonly icon: LucideIcon; readonly tone: string; readonly word: string }98 { readonly mark: StateMark; readonly tone: string; readonly word: string }99>;10079const HEAD = "text-muted-foreground h-8 px-0 text-xs font-medium";101/** The page's trail: the project, its asks, the ask, then this answer. */102export const answerCrumbs = (ask: Ask): readonly Crumb[] => [103 { label: ask.project, to: `/${ask.project}` },104 { label: "Asks", to: `/${ask.project}` },105 { label: ask.id, mono: true, to: askPath(ask.project, ask.id) },106 { label: "Answer" },107];108109/** What reads a lane's log, when the platform kept one. */110const LaneLog = ({111 lane,112 project,113}: {114 readonly lane: LaneResult;115 readonly project: Ask["project"];116}) => {117 if (lane.logRef === undefined) {118 return null;119 }120121 return lane.logRef === ChecksFailed.withheld ? (122 <p className="text-ui text-muted-foreground">123 Its log was not kept: it held a write-only value.124 </p>125 ) : (126 <CommandLine127 command={`${Brand.cli} evidence ${lane.logRef} --project ${project}`}128 />129 );130};131132/** One lane: its mark, name and command, its result in a word, and how long it ran. */133const LaneRow = ({134 lane,135 project,136}: {137 readonly lane: LaneResult;138 readonly project: Ask["project"];139}) => {140 const { mark, tone, word } = results[lane.result];141142 return (143 <li144 className="border-rule flex min-w-0 flex-col gap-2 border-b py-2.5"145 data-lane={lane.lane}146 data-result={lane.result}147 >148 <div className="text-ui flex min-w-0 items-baseline gap-3">149 <StateMarkIcon className="translate-y-[3px]" mark={mark} />150 <span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-0.5">151 <span className="text-mono text-foreground font-mono font-medium">152 {lane.lane}153 </span>154 <code className="text-mono text-muted-foreground min-w-0 font-mono [overflow-wrap:anywhere]">155 {lane.command}156 </code>157 </span>158 <span className={`shrink-0 font-medium ${tone}`}>{word}</span>159 <span className="text-label text-muted-foreground w-16 shrink-0 text-right tabular-nums">160 {durationText(lane.durationMs)}161 </span>162 </div>163 {lane.result === "passed" ? null : (164 <div className="pl-7">165 <LaneLog lane={lane} project={project} />166 </div>167 )}168 </li>169 );170};171172/** "6 lanes passed in 41 s": the lanes run one after another, so their times add up. */173const passedLine = (lanes: readonly LaneResult[]) =>174 `${lanes.length} ${lanes.length === 1 ? "lane" : "lanes"} passed in ${durationText(175 lanes.reduce((total, { durationMs }) => total + durationMs, 0)176 )}`;17781/** The lanes the platform ran on the merged tree: each one's command, result and time. */82export const LaneTable = ({178/** The lanes the platform ran on the merged tree: what failed, open and first; what passed, in one line. */179export const Lanes = ({180 lanes,181 project,182}: {183 readonly lanes: readonly LaneResult[];184 readonly project: Ask["project"];185}) => {186 if (lanes.length === 0) {187 return <EmptyState title="No lane ran on this answer." />;188 }18991 return (92 <Table className="border-rule border-t text-sm">93 <TableHeader>94 <TableRow className="hover:bg-transparent">95 <TableHead className={HEAD}>Lane and command</TableHead>96 <TableHead className={`${HEAD} pl-4`}>Result</TableHead>97 <TableHead className={`${HEAD} pl-4 text-right`}>Time</TableHead>98 </TableRow>99 </TableHeader>100 <TableBody>101 {lanes.map(({ command, durationMs, lane, result }) => {102 const { icon: Icon, tone, word } = results[result];190 const open = lanes.filter(({ result }) => result !== "passed");191 const passed = lanes.filter(({ result }) => result === "passed");192104 return (105 <TableRow106 className="border-rule hover:bg-transparent"107 data-lane={lane}108 data-result={result}109 key={lane}110 >111 <TableCell className="px-0 py-2 align-top whitespace-normal">112 <span className="flex min-w-0 flex-col">113 <span className={`${CODE} font-medium`}>{lane}</span>114 <code className={`${CODE} text-muted-foreground`}>115 {command}116 </code>117 </span>118 </TableCell>119 <TableCell className={`py-2 pl-4 align-top ${tone}`}>120 <span className="inline-flex items-center gap-1.5">121 <Icon aria-hidden="true" className="size-3.5 shrink-0" />122 <span className="font-medium">{word}</span>123 </span>124 </TableCell>125 <TableCell className="py-2 pr-0 pl-4 text-right align-top">126 {durationText(durationMs)}127 </TableCell>128 </TableRow>129 );130 })}131 </TableBody>132 </Table>193 return (194 <div className="flex min-w-0 flex-col">195 {open.length === 0 ? null : (196 <ul197 aria-label="Lanes that did not pass"198 className="border-rule border-t"199 >200 {open.map((lane) => (201 <LaneRow key={lane.lane} lane={lane} project={project} />202 ))}203 </ul>204 )}205 {passed.length === 0 ? null : (206 <details207 className={`group border-rule border-b ${open.length === 0 ? "border-t" : ""}`}208 >209 <summary className="text-ui hover:bg-surface/50 flex min-h-10 cursor-pointer list-none items-center gap-3 transition-colors duration-[120ms] [&::-webkit-details-marker]:hidden">210 <StateMarkIcon mark="passed" />211 <span className="min-w-0 flex-1">{passedLine(passed)}</span>212 <ChevronDown213 aria-hidden="true"214 className="text-muted-foreground size-4 shrink-0 transition-transform duration-150 group-open:rotate-180"215 strokeWidth={1.75}216 />217 </summary>218 <ul aria-label="Lanes that passed" className="border-rule border-t">219 {passed.map((lane) => (220 <LaneRow key={lane.lane} lane={lane} project={project} />221 ))}222 </ul>223 </details>224 )}225 </div>226 );227};228229/** Held-back checks: one line per area, as the landing's trailer spells it, and nothing else. */
3 unmodified lines
233 readonly results: readonly HeldBackResult[];234}) => (235 <ul236 aria-label="Held-back checks by area"144 className="text-sealed flex flex-col gap-1 font-mono text-[0.8125rem] leading-6"237 className="text-sealed text-mono leading-terminal flex flex-col gap-1 font-mono"238 >239 {areas.map(({ area, passed, suite, total }) => (240 <li241 className="flex items-start gap-2 [overflow-wrap:anywhere]"242 data-area={area}243 key={area}244 >152 <LockKeyhole aria-hidden="true" className="mt-1 size-3.5 shrink-0" />245 <LockKeyhole246 aria-hidden="true"247 className="mt-1 size-3.5 shrink-0"248 strokeWidth={1.75}249 />250 <span className="min-w-0">251 {area} {passed}/{total} @ {suite}252 </span>253 </li>254 ))}255 </ul>256);257161const short = (sha: string) => sha.slice(0, 7);162258/** A git id, short as git prints it, whole on hover. */259const Sha = ({ sha }: { readonly sha: string }) => (165 <code className={CODE} title={sha}>166 {short(sha)}260 <code className="text-mono font-mono" title={sha}>261 {shortSha(sha)}262 </code>263);264170export const AnswerView = ({171 landing,265/** Content the inspector shows, left out of the facts drawn inline in main below the shell's width. */266export const InspectorOnly = ({267 children,268}: {269 readonly children: ReactNode;270}) => (271 <div className="border-rule flex min-w-0 flex-col border-t pt-3 first:border-t-0 first:pt-0 [[data-facts=inline]_&]:hidden">272 {children}273 </div>274);275276/** What the hero says before any answer was judged: who holds the ask, or how to take it. */277const NoAnswerYet = ({278 ask,279 now,280 progress,281}: {282 readonly ask: Ask;283 readonly now: DateTime.Utc;284 readonly progress: AskProgress | undefined;285}) => {286 const toAsk = (287 <AppLink288 className="decoration-rule underline hover:decoration-current"289 to={askPath(ask.project, ask.id)}290 >291 The ask292 </AppLink>293 );294295 const claimant = progress?.claimant;296 const pushed = progress?.lastPush;297298 if (claimant !== undefined || ask.state === "claimed") {299 const holder =300 claimant === undefined ? "Claimed" : `Claimed by ${claimant}`;301302 return (303 <EmptyState304 onward={toAsk}305 title={306 pushed === undefined307 ? `${holder}, no answer pushed yet.`308 : `${holder}; the answer pushed ${distanceInWords(pushed.at, now)} waits for the gate.`309 }310 />311 );312 }313314 if (ask.state === "open") {315 return (316 <EmptyState317 command={`${Brand.cli} claim ${ask.id} --project ${ask.project}`}318 title="Nobody has answered this ask yet."319 />320 );321 }322323 return (324 <EmptyState325 onward={toAsk}326 title="No answer to this ask has been checked yet."327 />328 );329};330331/**332 * The outcome, a step up: settled in when it changes while the page is333 * open (never on the first paint), and stamped once on a live landing.334 */335const Hero = ({336 ask,337 now,338 progress,339 stamp,340 verdict,341}: {175 readonly landing?: LandingView;342 readonly ask: Ask;343 readonly now: DateTime.Utc;344 readonly progress: AskProgress | undefined;345 readonly stamp: boolean;346 readonly verdict: Verdict | undefined;347}) => {179 if (verdict === undefined) {180 return <EmptyState title="No answer to this ask has been checked yet." />;348 const tag = verdict?.outcome._tag ?? "none";349 // Only an outcome that replaced another while the page was open settles in.350 const [shown, setShown] = useState(tag);351 const [changed, setChanged] = useState(false);352353 if (shown !== tag) {354 setShown(tag);355 setChanged(true);356 }357358 const claimant = progress?.claimant;359360 return (184 <>185 <Fields label="What was judged">186 <Field label="Ask">187 <a188 className={`${LINK} ${CODE}`}189 href={askPath(verdict.project, verdict.ask)}190 >191 {verdict.ask}192 </a>193 </Field>194 <Field label="Judged">195 <When at={verdict.at} now={now} />{" "}196 <span className="text-muted-foreground">197 by the {verdict.verifier}198 </span>199 </Field>200 <Field label="Head">201 <Sha sha={verdict.head} />202 </Field>203 <Field label="Base">204 <a className={LINK} href={commitHref(verdict.project, verdict.base)}>205 <Sha sha={verdict.base} />206 </a>207 </Field>208 <Field label="Merged tree">209 <Sha sha={verdict.tree} />210 </Field>211 <Field label="Patch id">212 <Sha sha={verdict.patchId} />213 </Field>214 <Field label="Check version">215 <code className={CODE}>{verdict.checkVersion}</code>216 </Field>217 </Fields>361 <section aria-label="Outcome" className="flex min-w-0 flex-col gap-3">362 <h2 className="sr-only">Outcome</h2>363 <div364 className={365 changed ? "animate-in fade-in-0 min-w-0 duration-150" : "min-w-0"366 }367 key={tag}368 >369 {verdict === undefined ? (370 <NoAnswerYet ask={ask} now={now} progress={progress} />371 ) : (372 <OutcomeView373 outcome={verdict.outcome}374 project={ask.project}375 size="title"376 stage={verdict.stage}377 stamp={stamp}378 {...(claimant === undefined ? {} : { claimant })}379 />380 )}381 </div>382 </section>383 );384};385219 <Region id="answer-gate" title="Gate">220 <StageStrip outcome={verdict.outcome} stage={verdict.stage} />221 <OutcomeView outcome={verdict.outcome} />386/** The answer's run: the gate, the lanes, the held-back checks, and the landing. */387const Run = ({388 holds,389 landing,390 now,391 verdict,392}: {393 readonly holds: ReturnType<typeof holdsOf>;394 readonly landing: LandingView | undefined;395 readonly now: DateTime.Utc;396 readonly verdict: Verdict;397}) => (398 <>399 <Region id="answer-gate" title="Gate">400 <StageStrip401 holds={holds}402 outcome={verdict.outcome}403 stage={verdict.stage}404 />405 <p className="text-ui text-muted-foreground">406 Checked on the tree it would land as: <Sha sha={verdict.head} /> merged407 onto main at{" "}408 <AppLink409 className="decoration-rule underline hover:decoration-current"410 to={commitHref(verdict.project, verdict.base)}411 >412 <Sha sha={verdict.base} />413 </AppLink>414 .415 </p>416 </Region>417418 <Region id="answer-lanes" title="Lanes">419 <Lanes lanes={verdict.lanes} project={verdict.project} />420 </Region>421422 {verdict.heldBack.length === 0 ? null : (423 <Region id="answer-held-back" title="Held back">424 <p className="text-ui text-muted-foreground max-w-[70ch]">425 Checks the answer could not see: how many passed in each area, and the426 root of the suite the project committed to before the claim.427 </p>428 <HeldBackBits results={verdict.heldBack} />429 </Region>430 )}431224 <Region id="answer-lanes" title="Lanes">225 <LaneTable lanes={verdict.lanes} />432 {landing === undefined ? null : (433 <Region id="answer-landing" title="Landing">434 <CreditTrailers435 assisted={landing.assisted}436 credits={landing.credits}437 {...(landing.heldBackTrailer === undefined438 ? {}439 : { heldBack: landing.heldBackTrailer })}440 />441 <AppLink442 className="text-ui decoration-rule self-start font-medium underline hover:decoration-current"443 to={commitHref(landing.project, landing.sha)}444 >445 The landing commit446 </AppLink>447 <div className="flex min-w-0 flex-col gap-1.5">448 <span className="text-label text-muted-foreground">449 In a clone of {landing.project}450 </span>451 <CommandLine command={`git show ${landing.sha}`} />452 </div>453 </Region>454 )}455228 {verdict.heldBack.length === 0 ? null : (229 <Region id="answer-held-back" title="Held-back checks">230 <p className="text-muted-foreground max-w-[70ch] text-sm">231 Checks the answer could not see. Each area shows how many passed,232 and the root of the suite the project committed to before the claim.233 </p>234 <HeldBackBits results={verdict.heldBack} />235 </Region>236 )}456 {/* Below the shell's width the inspector's facts sit above the run, so457 the plumbing comes here, last. */}458 <div className="shell:hidden">459 <ProvenanceFacts entries={verdictProvenance(verdict, now)} />460 </div>461 </>462);463238 {landing === undefined ? null : (239 <Region id="answer-landing" title="Landing">240 <CreditTrailers241 assisted={landing.assisted}242 credits={landing.credits}243 {...(landing.heldBackTrailer === undefined244 ? {}245 : { heldBack: landing.heldBackTrailer })}246 />247 <a248 className={`${LINK} self-start text-sm font-medium`}249 href={commitHref(landing.project, landing.sha)}250 >251 The landing commit252 </a>253 <div className="flex min-w-0 flex-col gap-1.5">254 <span className="text-muted-foreground text-xs font-medium">255 In a clone of {landing.project}256 </span>257 <CommandLine command={`git show ${landing.sha}`} />258 </div>259 </Region>464export interface AnswerViewProps {465 /** The ask the answer is to: its want titles the page. */466 readonly ask: Ask;467 /** The verdict on the answer; none before one was judged. */468 readonly verdict: Verdict | undefined;469 /** The landing it made, once it landed. */470 readonly landing?: LandingView | undefined;471 readonly now: DateTime.Utc;472 /** Where each ask stands, from the project's events (`askStates`). */473 readonly states?: ReadonlyMap<AskId, AskProgress>;474 /** The family's parent, when the ask is a member of one. */475 readonly parent?: Ask | undefined;476 /** The head the address names, when it names an earlier answer. */477 readonly head?: CommitSha | undefined;478 /** It landed while the page was open: stamp the landing's mark, once. */479 readonly stamp?: boolean;480 /** Who is reading, to tell the claimant the claim is theirs. */481 readonly viewer?: Handle | undefined;482}483484const NONE: ReadonlyMap<AskId, AskProgress> = new Map();485486/** The answer's facts: its state, rounds, claim, family, territory and check, then what was judged. */487const AnswerFacts = ({488 ask,489 now,490 parent,491 progress,492 states,493 subject,494 verdict,495 viewer,496}: {497 readonly ask: Ask;498 readonly now: DateTime.Utc;499 readonly parent: Ask | undefined;500 readonly progress: AskProgress | undefined;501 readonly states: ReadonlyMap<AskId, AskProgress>;502 readonly subject: StatusSubject | undefined;503 readonly verdict: Verdict | undefined;504 readonly viewer: Handle | undefined;505}) => {506 const family = familyHead(ask, parent);507 const finale = family === undefined ? undefined : deleteChildOf(family);508509 const landed =510 verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome);511512 return (513 <>514 {subject === undefined ? null : (515 <InspectorOnly>516 <StateFacts subject={subject} />517 </InspectorOnly>518 )}519 <RoundsFacts520 ask={ask.id}521 now={now}522 project={ask.project}523 rounds={roundsAsTheyStand(progress, verdict)}524 {...(verdict === undefined ? {} : { current: verdict.head })}525 />526 {landed ? null : (527 <ClaimFacts528 now={now}529 {...(progress?.claimant === undefined530 ? {}531 : { claimant: progress.claimant })}532 {...(progress?.lastPush === undefined533 ? {}534 : { lastPush: progress.lastPush })}535 {...(viewer === undefined ? {} : { viewer })}536 />537 )}538 {family === undefined ? null : (539 <FamilyFacts540 current={ask.id}541 parent={family}542 project={ask.project}543 states={states}544 {...(finale === undefined ? {} : { finale })}545 />546 )}547 <TerritoryFacts ask={ask} />548 {verdict === undefined ? null : (549 <InspectorOnly>550 <ProvenanceFacts entries={verdictProvenance(verdict, now)} />551 </InspectorOnly>552 )}553 </>554 );555};556557/** The line under the hero's title: the ask, the round, when it was judged, and the way to the latest answer. */558const AnswerMeta = ({559 ask,560 head,561 now,562 rounds,563 verdict,564}: {565 readonly ask: Ask;566 readonly head: CommitSha | undefined;567 readonly now: DateTime.Utc;568 readonly rounds: AskProgress["rounds"];569 readonly verdict: Verdict | undefined;570}) => {571 const round =572 verdict === undefined ? undefined : roundOf(rounds, verdict.head);573574 return (575 <MetaLine576 parts={[577 <MetaCode key="ask">{ask.id}</MetaCode>,578 round === undefined579 ? undefined580 : `round ${round.number} of ${round.of}`,581 verdict === undefined ? undefined : (582 <span key="judged">583 judged <When at={verdict.at} now={now} />584 </span>585 ),586 head === undefined ? undefined : (587 <span key="earlier">588 an earlier answer;{" "}589 <AppLink590 className="decoration-rule underline hover:decoration-current"591 to={answerPath(ask.project, ask.id)}592 >593 the latest594 </AppLink>595 </span>596 ),597 ]}598 />599 );600};601602export const AnswerView = ({603 ask,604 head,605 landing,606 now,607 parent,608 stamp = false,609 states = NONE,610 verdict,611 viewer,612}: AnswerViewProps) => {613 const progress = states.get(ask.id);614615 const subject: StatusSubject | undefined =616 verdict === undefined617 ? undefined618 : {619 claimant: progress?.claimant,620 kind: "answer",621 outcome: verdict.outcome,622 project: ask.project,623 stage: verdict.stage,624 };625626 return (627 <Workspace628 crumbs={answerCrumbs(ask)}629 facts={630 <AnswerFacts631 ask={ask}632 now={now}633 parent={parent}634 progress={progress}635 states={states}636 subject={subject}637 verdict={verdict}638 viewer={viewer}639 />640 }641 factsHeading="This answer"642 meta={643 <AnswerMeta644 ask={ask}645 head={head}646 now={now}647 rounds={progress?.rounds ?? []}648 verdict={verdict}649 />650 }651 state={652 <StatusLine653 compact654 subject={655 subject ?? {656 ask,657 claimant: progress?.claimant,658 kind: "ask",659 takeable: ask.state === "open",660 }661 }662 />663 }664 status={665 <Hero666 ask={ask}667 now={now}668 progress={progress}669 stamp={670 stamp &&671 verdict !== undefined &&672 Outcome.isAnyOf(["Landed"])(verdict.outcome)673 }674 verdict={verdict}675 />676 }677 title={ask.brief.want}678 >679 {verdict === undefined ? null : (680 <Run681 holds={holdsOf(verdict, landing, progress?.rounds ?? [])}682 landing={landing}683 now={now}684 verdict={verdict}685 />686 )}687 </Workspace>688 );689};
added:apps/web/src/features/answer/reads.ts+231 added
1/**2 * What the ask page and the answer page read on the server, before either3 * draws: the subject, then what is read beside it (the project's events,4 * the family's parent, the check's source, the landing). A read beside the5 * subject that fails leaves its part out; the subject's own refusal is the6 * page's 404 (`notFoundFor`). The routes call these from their server7 * functions only, so none of it reaches the browser's first load.8 */9import { Client } from "@repo/protocol/contracts";10import { Verdict } from "@repo/protocol/domain/answer";11import { Ask } from "@repo/protocol/domain/ask";12import { CheckSpec } from "@repo/protocol/domain/check";13import { ProjectEvent } from "@repo/protocol/domain/event";14import { LandingView } from "@repo/protocol/domain/landing";15import { Outcome } from "@repo/protocol/domain/outcome";16import {17 AskId,18 BlobSha,19 CommitSha,20 ProjectName,21 RepoPath,22} from "@repo/protocol/ids";23import type { LandedSha } from "@repo/protocol/ids";24import { notFound } from "@tanstack/react-router";25import { DateTime, Effect, Option, Schema } from "effect";2627import { notFoundFor } from "../shared/refusals.ts";28import { keptEvents, readEvents, readParent } from "./subject.ts";2930/** An ask's address, not yet decoded. */31export interface AskAddress {32 readonly ask: string;33 readonly project: string;34}3536/** The address, decoded: names the platform could hold. */37const AskPath = Schema.Struct({ ask: AskId, project: ProjectName });3839/** The check's file, as the page carries it. */40const CheckRead = Schema.Struct({41 path: RepoPath,42 sha: BlobSha,43 text: Schema.String,44});4546/**47 * What the page's loader carries from the server, encoded: the ask and its48 * brief, the family's parent, the verdict on its latest answer, the49 * check's source, the events about them (and the last number of all the50 * project's), and when it was read.51 */52export const AskPageData = Schema.Struct({53 ask: Ask,54 brief: Schema.NonEmptyString,55 check: Schema.UndefinedOr(CheckRead),56 events: Schema.Array(ProjectEvent),57 lastSeq: Schema.Int,58 now: Schema.DateTimeUtcFromString,59 parent: Schema.UndefinedOr(Ask),60 verdict: Schema.UndefinedOr(Verdict),61});6263export type AskPageData = typeof AskPageData.Type;6465/** The check's source on main, when the check is a file that reads as text; none when it cannot be read. */66const readCheck = (ask: Ask) =>67 Effect.gen(function* () {68 if (!CheckSpec.guards.RedThenGreen(ask.check)) {69 return Option.none<typeof CheckRead.Type>();70 }7172 const client = yield* Client;7374 return yield* client75 .readFile({ path: ask.check.path, project: ask.project })76 .pipe(77 Effect.map(({ binary, path, sha, text }) =>78 binary || text === undefined79 ? Option.none()80 : Option.some({ path, sha, text })81 ),82 Effect.orElseSucceed(() => Option.none<typeof CheckRead.Type>())83 );84 });8586/**87 * The page's reads: the ask, the project's events and the latest verdict88 * at once, then the family's parent (if it is in one) and the check's89 * source; or a not-found carrying the platform's refusal (a 404).90 */91export const readAsk = (params: AskAddress) =>92 Effect.gen(function* () {93 const path = yield* Schema.decodeEffect(AskPath)(params).pipe(94 Effect.mapError(() => notFound())95 );9697 const client = yield* Client;9899 const [read, events, verdict] = yield* Effect.all(100 [101 client.showAsk(path),102 readEvents(path.project),103 Effect.option(client.verdict(path)),104 ],105 { concurrency: "unbounded" }106 ).pipe(107 Effect.catchTags({108 UnknownAsk: notFoundFor,109 UnknownProject: notFoundFor,110 })111 );112113 const [parent, check] = yield* Effect.all(114 [readParent(read.ask), readCheck(read.ask)],115 { concurrency: "unbounded" }116 );117118 return yield* Schema.encodeEffect(AskPageData)({119 ...read,120 ...keptEvents(events, read.ask, Option.getOrUndefined(parent)),121 check: Option.getOrUndefined(check),122 now: yield* DateTime.now,123 parent: Option.getOrUndefined(parent),124 verdict: Option.getOrUndefined(125 Option.flatMap(verdict, (found) =>126 Option.fromUndefinedOr(found.verdict)127 )128 ),129 });130 });131132/** The page's address, not yet decoded: the path's names and `?head=`. */133export interface AnswerAddress {134 readonly ask: string;135 readonly head?: string | undefined;136 readonly project: string;137}138139/** The address, decoded: names the platform could hold, and a commit id. */140const AnswerPath = Schema.Struct({141 ask: AskId,142 head: Schema.optionalKey(CommitSha),143 project: ProjectName,144});145146/**147 * What the page's loader carries from the server, encoded: the ask, the148 * verdict and its landing, the family's parent, the events about them (and149 * the last number of all the project's), and when it was read.150 */151export const AnswerPageData = Schema.Struct({152 ...AnswerPath.fields,153 askRead: Ask,154 brief: Schema.NonEmptyString,155 events: Schema.Array(ProjectEvent),156 landing: Schema.UndefinedOr(LandingView),157 lastSeq: Schema.Int,158 now: Schema.DateTimeUtcFromString,159 parent: Schema.UndefinedOr(Ask),160 verdict: Schema.UndefinedOr(Verdict),161});162163export type AnswerPageData = typeof AnswerPageData.Type;164165/** The landing a verdict's answer made, when it landed. */166export const landedBy = (167 verdict: Verdict | undefined168): LandedSha | undefined =>169 verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome)170 ? verdict.outcome.sha171 : undefined;172173/** The landing at `sha`; none for no landing, or one the platform no longer finds. */174const readLanding = (project: ProjectName, sha: LandedSha | undefined) =>175 Effect.gen(function* () {176 if (sha === undefined) {177 return Option.none<LandingView>();178 }179180 const client = yield* Client;181182 return yield* client.landing({ project, sha }).pipe(183 Effect.map((found) => Option.some(found.landing)),184 // The verdict names a landing the platform no longer finds: show the verdict alone.185 Effect.catchTag("UnknownCommit", () => Effect.succeedNone)186 );187 });188189/**190 * The page's reads: the verdict, the ask and the project's events at191 * once, then the landing (if it landed) and the family's parent (if it is192 * in one); or a not-found carrying the refusal (a 404).193 */194export const readAnswer = ({ ask, head, project }: AnswerAddress) =>195 Effect.gen(function* () {196 const path = yield* Schema.decodeEffect(AnswerPath)(197 head === undefined ? { ask, project } : { ask, head, project }198 ).pipe(Effect.mapError(() => notFound()));199200 const client = yield* Client;201202 const [{ verdict }, shown, events] = yield* Effect.all(203 [204 client.verdict(path),205 client.showAsk({ ask: path.ask, project: path.project }),206 readEvents(path.project),207 ],208 { concurrency: "unbounded" }209 ).pipe(210 Effect.catchTags({211 UnknownAsk: notFoundFor,212 UnknownProject: notFoundFor,213 })214 );215216 const [landing, parent] = yield* Effect.all(217 [readLanding(path.project, landedBy(verdict)), readParent(shown.ask)],218 { concurrency: "unbounded" }219 );220221 return yield* Schema.encodeEffect(AnswerPageData)({222 ...path,223 askRead: shown.ask,224 brief: shown.brief,225 ...keptEvents(events, shown.ask, Option.getOrUndefined(parent)),226 landing: Option.getOrUndefined(landing),227 now: yield* DateTime.now,228 parent: Option.getOrUndefined(parent),229 verdict,230 });231 });
added:apps/web/src/features/answer/subject.ts+177 added
1/**2 * What an ask's page and its answer's page read beside their subject, and3 * the plain readings over it:4 *5 * - the project's events (`watch`, replayed from the first), kept to the6 * ones about the asks the page draws: the ask, what it waits on, and its7 * family. The fold over them (`askStates`) says who holds each ask, its8 * rounds and whether it landed, with no contract of its own;9 * - a family member's parent (`showAsk`), whose stored children count the10 * family, since a listing drops the ones that landed;11 * - what a verdict holds, so the gate's strip draws a stage the answer12 * never needed as not needed.13 *14 * A read beside the subject that fails leaves its part out; it never fails15 * the page.16 */17import { Client } from "@repo/protocol/contracts";18import type { Verdict } from "@repo/protocol/domain/answer";19import type { Ask } from "@repo/protocol/domain/ask";20import { ProjectEvent } from "@repo/protocol/domain/event";21import type { LandingView } from "@repo/protocol/domain/landing";22import { Outcome } from "@repo/protocol/domain/outcome";23import type { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";24import { Effect, Option, Stream } from "effect";2526import { lastSeq } from "../shared/ask-progress.ts";27import type { AskProgress, Round } from "../shared/ask-progress.ts";28import type { StageHolds } from "../shared/outcome.tsx";2930/** The ask an event is about: one, or none. */31const askOf = (event: ProjectEvent): readonly AskId[] =>32 ProjectEvent.match(event, {33 AskClosed: ({ ask }) => [ask],34 AskOpened: ({ ask }) => [ask.ask],35 Claimed: ({ ask }) => [ask],36 Decided: () => [],37 Judged: ({ ask }) => [ask],38 Landed: () => [],39 Lapsed: ({ ask }) => [ask],40 LedgerAppended: () => [],41 ProposalDrafted: () => [],42 ProposalOpened: () => [],43 Pushed: ({ ask }) => [ask],44 Released: ({ ask }) => [ask],45 Warned: ({ ask }) => [ask],46 });4748/** The events about `asks`, in the order given. */49export const eventsAbout = (50 events: readonly ProjectEvent[],51 asks: ReadonlySet<AskId>52): readonly ProjectEvent[] =>53 events.filter((event) => askOf(event).some((about) => asks.has(about)));5455/**56 * The delete child among a family parent's stored children: the one named57 * for the parent, as the platform names it when it splits a migrate ask.58 */59export const deleteChildOf = (parent: Ask): AskId | undefined =>60 parent.blockedBy.find((child) => child === `${parent.id}-delete`);6162/** The parent of the family `ask` is in: the one read for it, or the ask itself when it heads one. */63export const familyHead = (ask: Ask, parent: Ask | undefined) =>64 parent ?? (deleteChildOf(ask) === undefined ? undefined : ask);6566/** Every ask whose events the page needs: the ask, what it waits on, and its family. */67export const asksAround = (68 ask: Ask,69 parent: Ask | undefined70): ReadonlySet<AskId> =>71 new Set([72 ask.id,73 ...ask.blockedBy,74 ...(parent === undefined ? [] : [parent.id, ...parent.blockedBy]),75 ]);7677/** The project's events from the first; none when they cannot be read. */78export const readEvents = (project: ProjectName) =>79 Effect.gen(function* () {80 const client = yield* Client;8182 const events: readonly ProjectEvent[] = yield* Stream.runCollect(83 client.watch({ project, since: 0 })84 ).pipe(Effect.orElseSucceed((): readonly ProjectEvent[] => []));8586 return events;87 });8889/** The parent ask of a family member; none for an ask in no family, or one the platform no longer finds. */90export const readParent = (ask: Ask) =>91 Effect.gen(function* () {92 if (ask.parent === undefined) {93 return Option.none<Ask>();94 }9596 const client = yield* Client;9798 return yield* client99 .showAsk({ ask: ask.parent, project: ask.project })100 .pipe(101 Effect.map(({ ask: parent }) => Option.some(parent)),102 Effect.orElseSucceed(() => Option.none<Ask>())103 );104 });105106/** What a page carries of the events: those about its asks, and the last number of all of them. */107export const keptEvents = (108 events: readonly ProjectEvent[],109 ask: Ask,110 parent: Ask | undefined111) => ({112 events: eventsAbout(events, asksAround(ask, parent)),113 lastSeq: lastSeq(events),114});115116/** Whether an outcome waited on a person: a decision, or a decider's finish. */117const waitedOnPerson = Outcome.isAnyOf(["AwaitingDecision", "AwaitingFinish"]);118119/**120 * What a verdict holds beyond its stage: whether a decider took part (the121 * landing's `Decided-by`, or a round of the same answer that waited on one)122 * and whether held-back checks judged it.123 */124export const holdsOf = (125 verdict: Verdict,126 landing: LandingView | undefined,127 rounds: readonly Round[]128): StageHolds => ({129 decided:130 (landing?.credits.some(({ role }) => role === "Decided-by") ?? false) ||131 rounds.some(132 ({ head, outcome }) => head === verdict.head && waitedOnPerson(outcome)133 ),134 heldBack: verdict.heldBack.length > 0,135});136137/** Which round the answer at `head` is, of how many: the last round judged at that head. */138export const roundOf = (139 rounds: readonly Round[],140 head: CommitSha141): { readonly number: number; readonly of: number } | undefined => {142 const index = rounds.findLastIndex((round) => round.head === head);143144 return index === -1 ? undefined : { number: index + 1, of: rounds.length };145};146147/**148 * Each round with the last word on it: a round's own event says what the149 * gate said when it judged the push (often that it was still checking),150 * so the verdict on that head, and the landing that closed the ask, speak151 * for it once they came.152 */153export const roundsAsTheyStand = (154 progress: AskProgress | undefined,155 verdict: Verdict | undefined156): readonly Round[] => {157 const rounds = progress?.rounds ?? [];158 const landed = progress?.landed;159 const last = rounds.length - 1;160161 const latestAt =162 verdict === undefined163 ? -1164 : rounds.findLastIndex(({ head }) => head === verdict.head);165166 return rounds.map((round, index) => {167 if (index === latestAt && verdict !== undefined) {168 return { ...round, outcome: verdict.outcome };169 }170171 return index === last &&172 landed !== undefined &&173 !Outcome.isAnyOf(["Refused"])(round.outcome)174 ? { ...round, outcome: Outcome.cases.Landed.make({ sha: landed.sha }) }175 : round;176 });177};
modified:apps/web/src/features/ask/ask-page.tsx+537 added-231 removed
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.2 * An ask, as a person reads it: the want as the title, then where it3 * stands in one line (open to take, claimed by someone, refused at a4 * stage, landed), whose move that is and what runs next. Below, the brief,5 * the check (the spec: its source inline), and every answer judged so far,6 * one row each. The inspector holds the typed facts: its state, how to7 * take it or who holds it, its territory and check, its family, and its8 * project's posture.9 *10 * A family member says what it waits on in the family's terms ("waiting11 * for 4 of 6 children to land") and draws the family as a fan; once every12 * sibling has landed, the delete child reads open to take. Who holds an13 * ask and its rounds come from the project's events (`askStates`), with14 * no contract of their own.15 *16 * Agents read the same ask as Markdown (`markdown.ts`); the page shows the17 * brief exactly as they read it, and links the Markdown.18 */19import { Brand } from "@repo/brand";20import type { Verdict } from "@repo/protocol/domain/answer";10import type { Ask, AskState } from "@repo/protocol/domain/ask";21import type { Ask } from "@repo/protocol/domain/ask";22import { CheckSpec } from "@repo/protocol/domain/check";23import { Outcome } from "@repo/protocol/domain/outcome";12import type { AskId, ProjectName } from "@repo/protocol/ids";24import type { AskId, Handle, ProjectName } from "@repo/protocol/ids";25import type { Posture } from "@repo/protocol/posture";26import type { DateTime } from "effect";14import { Circle, CircleDot, Hourglass, Minus } from "lucide-react";15import type { LucideIcon } from "lucide-react";27import { ChevronDown, Hourglass } from "lucide-react";28import { useState } from "react";29import type { ReactNode } from "react";3018import { CODE, LINK } from "../shared/classes.ts";19import { CommandLine } from "../shared/command.tsx";31import { InspectorOnly } from "../answer/answer-page.tsx";32import {33 deleteChildOf,34 familyHead,35 roundsAsTheyStand,36} from "../answer/subject.ts";37import { ClientFile } from "../code/client-code.tsx";38import { linesOf } from "../code/file-header.tsx";39import { NumberedLines } from "../code/numbered-lines.tsx";40import { blobHref, shortSha } from "../code/paths.ts";41import { postureLabel } from "../project/posture-label.ts";42import { familyMarks } from "../shared/ask-progress.ts";43import type { AskProgress } from "../shared/ask-progress.ts";44import {45 ClaimFacts,46 FamilyFacts,47 PostureFacts,48 StateFacts,49 TakeItFacts,50 TerritoryFacts,51} from "../shared/facts.tsx";52import { FamilyStrip } from "../shared/family.tsx";53import { HandleLink } from "../shared/handle.tsx";21import { PageShell } from "../shared/layout.tsx";54import { AppLink } from "../shared/link.tsx";55import { answerPath, askPath } from "../shared/paths.ts";56import { MetaCode, MetaLine, Row } from "../shared/row.tsx";57import type { Crumb } from "../shared/shell/sections.ts";58import { Workspace } from "../shared/shell/workspace.tsx";59import { StatusLine, readStatus } from "../shared/status-line.tsx";60import type { StatusSubject } from "../shared/status-line.tsx";61import { When } from "../shared/time.tsx";24import { Field, Fields, Region } from "./fields.tsx";62import { Region } from "./fields.tsx";63import { markdownPath } from "./markdown.ts";6427/** Each state as a mark, a word and its role colour (none for open: nothing is happening yet). */28const states = {29 claimed: { icon: CircleDot, tone: "", word: "Claimed" },30 closed: { icon: Minus, tone: "text-muted-foreground", word: "Closed" },31 open: { icon: Circle, tone: "", word: "Open" },32 waitingOnParent: {33 icon: Hourglass,34 tone: "text-waiting",35 word: "Waiting on its parent",36 },37} as const satisfies Record<38 AskState,39 { readonly icon: LucideIcon; readonly tone: string; readonly word: string }40>;65/** The check's file, as the page read it: enough to draw its source. */66export interface CheckSource {67 readonly path: string;68 /** The blob's id: the drawing's cache key. */69 readonly sha: string;70 readonly text: string;71}7242const StateMark = ({ state }: { readonly state: AskState }) => {43 const { icon: Icon, tone, word } = states[state];73const LINK = "decoration-rule underline hover:decoration-current";7445 return (46 <span className={`font-medium ${tone}`}>47 <Icon48 aria-hidden="true"49 className="mr-1.5 inline-block size-3.5 align-[-0.15em]"50 />51 {word}52 </span>53 );54};75const NONE: ReadonlyMap<AskId, AskProgress> = new Map();7656const Code = ({ children }: { readonly children: ReactNode }) => (57 <code className={CODE}>{children}</code>58);77/** How many lines of the check show before the reader asks for the whole. */78const CHECK_LINES = 30;7960/** What judges an answer: the check's kind in words, then what it names. */61const checkOf = (check: CheckSpec) =>62 CheckSpec.match(check, {80/** The page's trail: the project, its asks, then the ask. */81export const askCrumbs = (ask: Ask): readonly Crumb[] => [82 { label: ask.project, to: `/${ask.project}` },83 { label: "Asks", to: `/${ask.project}` },84 { label: ask.id, mono: true },85];8687/** The command that claims an ask, run in a clone of its project. */88export const claimCommand = (ask: Ask) =>89 `${Brand.cli} claim ${ask.id} --project ${ask.project}`;9091/** What judges an answer, by the check's kind, in words; its file linked when it has one. */92const CheckSummary = ({ ask }: { readonly ask: Ask }) =>93 CheckSpec.match(ask.check, {94 LintToZero: ({ rule, territory }) => (95 <>65 Lint to zero: <Code>{rule}</Code>96 Lint to zero: <MetaCode>{rule}</MetaCode>97 {territory === undefined ? null : (98 <>99 {" "}69 in <Code>{territory}</Code>100 in <MetaCode>{territory}</MetaCode>101 </>102 )}103 </>104 ),105 Migrate: ({ from, to }) => (106 <>76 Migrate: <Code>{from}</Code>107 Migrate: no caller of <MetaCode>{from}</MetaCode> is left108 {to === undefined ? null : (109 <>79 {" "}80 to <Code>{to}</Code>110 ; each moves to <MetaCode>{to}</MetaCode>111 </>112 )}113 </>114 ),115 Ratchet: ({ ratchet }) => (116 <>87 Ratchet <Code>{ratchet}</Code> goes down117 The ratchet <MetaCode>{ratchet}</MetaCode> goes down118 </>119 ),120 RedThenGreen: ({ path }) => (121 <>92 Red, then green: <Code>{path}</Code>122 Red, then green:{" "}123 <AppLink124 className={`text-mono font-mono [overflow-wrap:anywhere] ${LINK}`}125 to={blobHref(ask.project, "main", path)}126 >127 {path}128 </AppLink>{" "}129 fails on main, and passes once the ask is answered.130 </>131 ),132 SymbolAbsent: ({ symbol }) => (133 <>97 Nothing uses <Code>{symbol}</Code>134 Nothing uses <MetaCode>{symbol}</MetaCode> any more135 </>136 ),137 });138102/** Asks, each linking to its page, separated by commas. */103const AskLinks = ({104 asks,105 project,106}: {107 readonly asks: readonly AskId[];108 readonly project: ProjectName;109}) =>110 asks.map((ask, index) => (111 <span key={ask}>112 {index === 0 ? null : ", "}113 <a className={`${LINK} ${CODE}`} href={askPath(project, ask)}>114 {ask}115 </a>116 </span>117 ));139/**140 * The check's source, drawn as the code browser draws a file: its first141 * thirty lines until the reader asks for the whole, the server's plain142 * lines first and the highlighted drawing in place of them.143 */144const CheckFile = ({ source }: { readonly source: CheckSource }) => {145 const [whole, setWhole] = useState(false);146 const lines = linesOf(source.text);147 const long = lines.length > CHECK_LINES;148119const reserved = {120 newcomers: "Held for newcomers",121 people: "Held for a person to answer, not an agent",122} as const;149 const shown =150 whole || !long ? source.text : lines.slice(0, CHECK_LINES).join("\n");151152 return (153 <figure className="border-rule flex min-w-0 flex-col border">154 <figcaption className="border-rule text-label text-muted-foreground flex h-9 min-w-0 items-center gap-3 border-b px-3">155 <span className="text-mono min-w-0 flex-1 truncate font-mono">156 {source.path}157 </span>158 <span className="shrink-0 tabular-nums">159 {lines.length} {lines.length === 1 ? "line" : "lines"}160 </span>161 </figcaption>162 <ClientFile163 // Each cut of the file is its own drawing.164 fallback={<NumberedLines text={shown} />}165 key={whole ? "whole" : "head"}166 path={source.path}167 sha={whole || !long ? source.sha : `${source.sha}:${CHECK_LINES}`}168 text={shown}169 />170 {long ? (171 <button172 aria-expanded={whole}173 className="border-rule text-ui hover:bg-surface flex min-h-10 items-center gap-2 border-t px-3 text-left transition-colors duration-[120ms]"174 onClick={() => {175 setWhole((now) => !now);176 }}177 type="button"178 >179 <ChevronDown180 aria-hidden="true"181 className={`text-muted-foreground size-4 shrink-0 transition-transform duration-150 ${whole ? "rotate-180" : ""}`}182 strokeWidth={1.75}183 />184 {whole185 ? `Show the first ${CHECK_LINES} lines`186 : `Show the whole check, ${lines.length} lines`}187 </button>188 ) : null}189 </figure>190 );191};192193const BriefPart = ({194 children,195 title,196}: {197 readonly children: ReactNode;198 readonly title: string;199}) => (200 <div className="flex flex-col gap-1.5">132 <h3 className="text-sm font-semibold">{title}</h3>201 <h3 className="text-ui font-semibold">{title}</h3>202 {children}203 </div>204);205
4 unmodified lines
210 ))}211 </ul>212);213145/** The lines that start an answer: clone, claim (it prints the fork's remote), check before the push. */146const TakeIt = ({214/** The brief's sections, as prose; the want is the page's title. */215const Brief = ({ ask }: { readonly ask: Ask }) => {216 const { context, current, outOfScope, terms } = ask.brief;217218 const parts = [219 current === undefined ? null : (220 <BriefPart key="current" title="Current behaviour">221 <p>{current}</p>222 </BriefPart>223 ),224 outOfScope === undefined ? null : (225 <BriefPart key="out" title="Out of scope">226 <BriefList items={outOfScope} />227 </BriefPart>228 ),229 terms === undefined || terms.length === 0 ? null : (230 <BriefPart key="terms" title="Terms">231 <BriefList items={terms} />232 </BriefPart>233 ),234 context === undefined || context.length === 0 ? null : (235 <BriefPart key="context" title="Context">236 <BriefList items={context} />237 </BriefPart>238 ),239 ].filter((part) => part !== null);240241 return parts.length === 0 ? null : (242 <Region id="ask-brief" title="Brief">243 <div className="text-body flex max-w-[70ch] flex-col gap-5">{parts}</div>244 </Region>245 );246};247248/** Every answer judged, one row each, oldest first, each linking its verdict. */249const Answers = ({250 ask,148 platformUrl,251 now,252 rounds,253}: {254 readonly ask: Ask;151 readonly platformUrl: string;152}) => {153 if (ask.state === "closed") {154 return (155 <p className="text-muted-foreground text-sm">156 This ask is closed, so it takes no claim.255 readonly now: DateTime.Utc;256 readonly rounds: AskProgress["rounds"];257}) => (258 <Region id="ask-answers" title="Answers">259 {rounds.length === 0 ? (260 <p className="text-ui text-muted-foreground">261 No answer has been judged yet.262 </p>263 ) : (264 <ul aria-label="Answers, oldest first" className="border-rule border-t">265 {rounds.map(({ at, head, outcome, seq }, index) => {266 const { lead, mark } = readStatus({ kind: "answer", outcome });267268 return (269 <Row270 href={answerPath(ask.project, ask.id)}271 id={`${head}:${seq}`}272 key={seq}273 meta={<MetaCode>{shortSha(head)}</MetaCode>}274 search={{ head }}275 size="one-line"276 state={{ mark, time: <When at={at} now={now} />, word: lead }}277 title={`Round ${index + 1}`}278 />158 );279 );280 })}281 </ul>282 )}283 <AppLink284 className={`text-ui self-start ${LINK}`}285 to={answerPath(ask.project, ask.id)}286 >287 Where the latest answer stands288 </AppLink>289 </Region>290);291292/** The asks an ask outside a family still waits on, each linked. */293const WaitsOn = ({294 asks,295 project,296}: {297 readonly asks: readonly AskId[];298 readonly project: ProjectName;299}) => (300 <p className="text-ui mt-2 flex items-start gap-2" data-state="waiting">301 <Hourglass302 aria-hidden="true"303 className="text-waiting mt-0.5 size-4 shrink-0"304 strokeWidth={1.75}305 />306 <span className="min-w-0">307 Waits on{" "}308 {asks.map((ask, index) => (309 <span key={ask}>310 {index === 0 ? null : ", "}311 <AppLink312 className={`text-mono font-mono ${LINK}`}313 to={askPath(project, ask)}314 >315 {ask}316 </AppLink>317 </span>318 ))}{" "}319 to land first; a claim waits until they do.320 </span>321 </p>322);323324export interface AskViewProps {325 readonly ask: Ask;326 /** The brief as the platform renders it for an agent, in Markdown. */327 readonly brief: string;328 readonly now: DateTime.Utc;329 /** Where the project is cloned from. */330 readonly platformUrl: string;331 /** Where each ask stands, from the project's events (`askStates`). */332 readonly states?: ReadonlyMap<AskId, AskProgress>;333 /** The family's parent, when the ask is a member of one. */334 readonly parent?: Ask | undefined;335 /** The verdict on its latest answer, to say at which stage a refusal came. */336 readonly verdict?: Verdict | undefined;337 /** The check's source, when it is a file the page could read. */338 readonly check?: CheckSource | undefined;339 /** The project's posture, once the list of projects has it. */340 readonly posture?: Posture | undefined;341 /** Who is reading, to tell the claimant the claim is theirs. */342 readonly viewer?: Handle | undefined;343}344345/** Where the ask stands, as its status line reads it. */346const subjectOf = (347 ask: Ask,348 states: ReadonlyMap<AskId, AskProgress>,349 verdict: Verdict | undefined,350 takeable: boolean351): StatusSubject => {352 const progress = states.get(ask.id);353 const claimant = progress?.claimant;354 const latest = progress?.latest;355356 if (progress?.landed !== undefined) {357 return {358 kind: "answer",359 outcome: Outcome.cases.Landed.make({ sha: progress.landed.sha }),360 project: ask.project,361 };362 }363161 const steps = [162 ["Clone the project", `git clone ${platformUrl}/${ask.project}.git`],163 [164 "Claim the ask; the claim prints your fork's remote",165 `${Brand.cli} claim ${ask.id} --project ${ask.project}`,166 ],167 [168 "Check your answer before you push it",169 `${Brand.cli} check --ask ${ask.id}`,170 ],171 ] as const;364 // A refusal says at which stage it came, which only the verdict holds.365 const lastRound = progress?.rounds.at(-1);366173 return (174 <ol className="flex flex-col gap-3">175 {steps.map(([label, command]) => (176 <li className="flex min-w-0 flex-col gap-1.5" key={command}>177 <span className="text-muted-foreground text-xs font-medium">178 {label}179 </span>180 <CommandLine command={command} />181 </li>182 ))}183 </ol>367 if (368 latest !== undefined &&369 Outcome.isAnyOf(["Refused"])(latest) &&370 verdict !== undefined &&371 verdict.head === lastRound?.head372 ) {373 return {374 claimant,375 kind: "answer",376 outcome: latest,377 project: ask.project,378 stage: verdict.stage,379 };380 }381382 return {383 blockers:384 ask.parent !== undefined && ask.blockedBy.length > 0385 ? familyMarks(ask, states)386 : undefined,387 claimant,388 kind: "ask",389 latest,390 ask,391 takeable,392 };393};394395/** Where an ask stands for its page: what it still waits on, whether it can be taken, and its family. */396const standing = (397 ask: Ask,398 states: ReadonlyMap<AskId, AskProgress>,399 parent: Ask | undefined400) => {401 const progress = states.get(ask.id);402403 const remaining = ask.blockedBy.filter(404 (blocker) => states.get(blocker)?.landed === undefined405 );406407 const family = familyHead(ask, parent);408 const latest = progress?.latest;409410 return {411 family,412 finale: family === undefined ? undefined : deleteChildOf(family),413 held: progress?.claimant !== undefined || ask.state === "claimed",414 progress,415 remaining,416 takeable: ask.state === "open" && remaining.length === 0,417 // A family member says what it waits on in the family's terms, and a418 // wait the latest outcome already names needs no second line.419 waitsOn:420 ask.parent === undefined &&421 remaining.length > 0 &&422 !(latest !== undefined && Outcome.isAnyOf(["WaitingOnParent"])(latest)),423 };424};425187export const AskView = ({426/** The ask's facts: its state, how to take it or who holds it, its territory and check, its family, its project's posture. */427const AskFacts = ({428 ask,189 brief,429 now,430 parent,431 platformUrl,432 posture,433 states,434 subject,435 viewer,436}: {437 readonly ask: Ask;194 readonly brief: string;438 readonly now: DateTime.Utc;439 readonly parent: Ask | undefined;440 readonly platformUrl: string;441 readonly posture: Posture | undefined;442 readonly states: ReadonlyMap<AskId, AskProgress>;443 readonly subject: StatusSubject;444 readonly viewer: Handle | undefined;445}) => {198 const { context, current, outOfScope, terms } = ask.brief;446 const { family, finale, held, progress, takeable } = standing(447 ask,448 states,449 parent450 );451452 return (201 <PageShell title={ask.brief.want}>202 <Fields label="The ask">203 <Field label="Ask">204 <Code>{ask.id}</Code>205 </Field>206 <Field label="State">207 <StateMark state={ask.state} />208 </Field>209 <Field label="Kind">210 <Code>{ask.kind}</Code>211 </Field>212 <Field label="Asked by">213 <HandleLink handle={ask.askedBy} />{" "}214 <span className="text-muted-foreground">215 · opened <When at={ask.openedAt} now={now} />216 </span>217 </Field>218 <Field label="Territory">219 {/* A paths territory (module `.`) reads as its paths alone. */}220 {ask.territory.module === "." ? (221 <span className="text-muted-foreground">The paths </span>222 ) : (223 <>224 <Code>{ask.territory.module}</Code>225 <span className="text-muted-foreground">: </span>226 </>227 )}228 {ask.territory.paths.map((path, index) => (229 <span key={path}>230 {index === 0 ? null : ", "}231 <Code>{path}</Code>232 </span>233 ))}234 </Field>235 <Field label="Check">{checkOf(ask.check)}</Field>236 {ask.parent === undefined ? null : (237 <Field label="Step of">238 <AskLinks asks={[ask.parent]} project={ask.project} />239 </Field>453 <>454 <InspectorOnly>455 <StateFacts subject={subject} />456 </InspectorOnly>457 {takeable ? <TakeItFacts ask={ask} platformUrl={platformUrl} /> : null}458 {!takeable && held && ask.state !== "closed" ? (459 <ClaimFacts460 now={now}461 {...(progress?.claimant === undefined462 ? {}463 : { claimant: progress.claimant })}464 {...(progress?.lastPush === undefined465 ? {}466 : { lastPush: progress.lastPush })}467 {...(viewer === undefined ? {} : { viewer })}468 />469 ) : null}470 <TerritoryFacts ask={ask} />471 {family === undefined ? null : (472 <InspectorOnly>473 <FamilyFacts474 current={ask.id}475 parent={family}476 project={ask.project}477 states={states}478 {...(finale === undefined ? {} : { finale })}479 />480 </InspectorOnly>481 )}482 {posture === undefined ? null : (483 <PostureFacts484 label={postureLabel(posture)}485 posture={posture}486 project={ask.project}487 />488 )}489 </>490 );491};492493/** The line under the title: the kind, who asked (and mentors), and when it opened. */494const AskMeta = ({495 ask,496 now,497}: {498 readonly ask: Ask;499 readonly now: DateTime.Utc;500}) => (501 <MetaLine502 parts={[503 ask.kind,504 <span key="asked">505 asked by <HandleLink handle={ask.askedBy} />506 {ask.mentor === undefined ? null : (507 <>508 , mentored by <HandleLink handle={ask.mentor} />509 </>510 )}241 {ask.reserve === undefined ? null : (242 <Field label="Who may take it">243 {reserved[ask.reserve]}244 {ask.mentor === undefined ? null : (245 <>246 , mentored by <HandleLink handle={ask.mentor} />247 </>248 )}249 </Field>250 )}251 </Fields>511 </span>,512 <span key="opened">513 opened <When at={ask.openedAt} now={now} />514 </span>,515 ]}516 />517);518253 {ask.blockedBy.length === 0 ? null : (254 <p className="text-waiting flex items-start gap-2" data-state="waiting">255 <Hourglass aria-hidden="true" className="mt-1 size-4 shrink-0" />256 <span className="text-foreground min-w-0">257 <strong className="text-waiting font-semibold">Waits on</strong>{" "}258 <AskLinks asks={ask.blockedBy} project={ask.project} /> to land259 first; a claim waits until they do.260 </span>519/** The Markdown an agent reads, shown whole on demand, and its own address. */520const ForAgents = ({521 ask,522 brief,523}: {524 readonly ask: Ask;525 readonly brief: string;526}) => (527 <section aria-label="For agents" className="flex min-w-0 flex-col gap-3">528 <details className="group border-rule border-y">529 <summary className="text-ui hover:bg-surface/50 flex min-h-10 cursor-pointer list-none items-center gap-3 transition-colors duration-[120ms] [&::-webkit-details-marker]:hidden">530 <span className="min-w-0 flex-1">The brief, as an agent reads it</span>531 <ChevronDown532 aria-hidden="true"533 className="text-muted-foreground size-4 shrink-0 transition-transform duration-150 group-open:rotate-180"534 strokeWidth={1.75}535 />536 </summary>537 <pre className="border-rule bg-surface text-mono leading-terminal mb-3 overflow-x-auto border p-3 font-mono whitespace-pre-wrap">538 {brief}539 </pre>540 </details>541 <p className="text-ui text-muted-foreground">542 {/* A server route, not one of the router's pages. */}543 <a544 className={`text-foreground ${LINK}`}545 href={markdownPath(ask.project, ask.id)}546 type="text/markdown"547 >548 This ask as Markdown549 </a>550 , for an agent to fetch.551 </p>552 </section>553);554555export const AskView = ({556 ask,557 brief,558 check,559 now,560 parent,561 platformUrl,562 posture,563 states = NONE,564 verdict,565 viewer,566}: AskViewProps) => {567 const { family, finale, progress, remaining, takeable, waitsOn } = standing(568 ask,569 states,570 parent571 );572573 const subject = subjectOf(ask, states, verdict, takeable);574575 return (576 <Workspace577 crumbs={askCrumbs(ask)}578 facts={579 <AskFacts580 ask={ask}581 now={now}582 parent={parent}583 platformUrl={platformUrl}584 posture={posture}585 states={states}586 subject={subject}587 viewer={viewer}588 />589 }590 factsHeading="This ask"591 meta={<AskMeta ask={ask} now={now} />}592 state={<StatusLine compact subject={subject} />}593 status={594 <>595 <StatusLine subject={subject} />596 {waitsOn ? <WaitsOn asks={remaining} project={ask.project} /> : null}597 {family === undefined ? null : (598 // Below the shell's width the family sits under the head, as a fan.599 <div className="shell:hidden mt-4">600 <FamilyStrip601 expanded={false}602 parent={family}603 project={ask.project}604 stamps={new Set()}605 states={states}606 {...(finale === undefined ? {} : { finale })}607 />608 </div>609 )}610 </>611 }612 title={ask.brief.want}613 {...(takeable ? { primaryCommand: claimCommand(ask) } : {})}614 >615 <Brief ask={ask} />616617 <Region id="ask-check" title="The check">618 <p className="text-ui max-w-[70ch]">619 <CheckSummary ask={ask} />620 </p>262 )}621 {check === undefined ? null : <CheckFile source={check} />}622 </Region>623264 <div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] lg:gap-12">265 <Region id="ask-brief" title="Brief">266 <div className="flex max-w-[70ch] flex-col gap-5">267 {current === undefined ? null : (268 <BriefPart title="Current behaviour">269 <p>{current}</p>270 </BriefPart>271 )}272 {outOfScope === undefined ? null : (273 <BriefPart title="Out of scope">274 <BriefList items={outOfScope} />275 </BriefPart>276 )}277 {terms === undefined || terms.length === 0 ? null : (278 <BriefPart title="Terms">279 <BriefList items={terms} />280 </BriefPart>281 )}282 {context === undefined || context.length === 0 ? null : (283 <BriefPart title="Context">284 <BriefList items={context} />285 </BriefPart>286 )}287 <details className="border-rule group border-t pt-3">288 <summary className="text-muted-foreground hover:text-foreground cursor-pointer text-sm select-none">289 The brief, as an agent reads it290 </summary>291 <pre className="border-rule bg-surface mt-3 overflow-x-auto border p-3 font-mono text-[0.8125rem] leading-6 whitespace-pre-wrap">292 {brief}293 </pre>294 </details>295 </div>296 </Region>624 <Answers625 ask={ask}626 now={now}627 rounds={roundsAsTheyStand(progress, verdict)}628 />629298 <div className="flex min-w-0 flex-col gap-8">299 <Region id="ask-take" title="Take it">300 <TakeIt ask={ask} platformUrl={platformUrl} />301 </Region>302 <Region id="ask-more" title="See also">303 <ul className="flex flex-col gap-1.5 text-sm">304 <li>305 <a className={LINK} href={answerPath(ask.project, ask.id)}>306 Where the latest answer stands307 </a>308 </li>309 <li>310 <a311 className={LINK}312 href={markdownPath(ask.project, ask.id)}313 type="text/markdown"314 >315 This ask as Markdown316 </a>317 <span className="text-muted-foreground">318 , for an agent to fetch319 </span>320 </li>321 </ul>322 </Region>323 </div>324 </div>325 </PageShell>630 <ForAgents ask={ask} brief={brief} />631 </Workspace>632 );633};
modified:apps/web/src/features/ask/refused.tsx+35 added-4 removed
modified:apps/web/src/routes/$project/answers/$ask.tsx+109 added-139 removed
1import { useAtomMount, 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";2import type { LandingView } from "@repo/protocol/domain/landing";3import type { Handle, LandedSha } from "@repo/protocol/ids";4import { createFileRoute, useParams } from "@tanstack/react-router";5import { createServerFn } from "@tanstack/react-start";6import { env } from "cloudflare:workers";11import { DateTime, Effect, Option, Predicate, Schema } from "effect";12import { AsyncResult } from "effect/reactivity";7import { Effect, Option, Predicate, Schema } from "effect";8import { AsyncResult, Atom } from "effect/reactivity";9import { useMemo } from "react";1011import { landingAtom, verdictAtom } from "../../../client/answer.ts";12import { askAtom } from "../../../client/ask.ts";13import { askStates, projectEventsAtom } from "../../../client/events.ts";14import { SeededAtoms, seedSuccess } from "../../../client/seeded.ts";15import { watchAtom } from "../../../client/watch.ts";16import { AnswerView } from "../../../features/answer/answer-page.tsx";17import {18 AnswerPageData,19 landedBy,20 readAnswer,21} from "../../../features/answer/reads.ts";22import type { AnswerAddress } from "../../../features/answer/reads.ts";23import { NoSuchAsk } from "../../../features/ask/refused.tsx";19import { CODE, LINK } from "../../../features/shared/classes.ts";24import { whoAtom } from "../../../features/auth/who.ts";25import { pageHead } from "../../../features/shared/head.ts";21import { PageShell } from "../../../features/shared/layout.tsx";22import { answerPath } from "../../../features/shared/paths.ts";23import { notFoundFor } from "../../../features/shared/refusals.ts";26import { branchPage } from "../../../server/cache-headers.ts";27import { serverClient } from "../../../server/client.ts";2826// The answer page: the latest verdict on an answer to an ask, stage by27// stage, or with `?head=<sha>` the verdict on an earlier answer. A landed28// answer shows its landing's credit trailers.29// The answer page: where the latest answer to an ask stands, stage by30// stage, or with `?head=<sha>` an earlier answer. It updates live while31// open, from the project's events.3230/** 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). */61export const readAnswer = ({ ask, head, project }: AnswerAddress) =>62 Effect.gen(function* () {63 const path = yield* Schema.decodeEffect(AnswerPath)(64 head === undefined ? { ask, project } : { ask, head, project }65 ).pipe(Effect.mapError(() => notFound()));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 });9433const answerPage = createServerFn({ method: "GET" })34 .validator((address: AnswerAddress) => address)35 .handler(({ data }) =>36 Effect.runPromise(readAnswer(data).pipe(Effect.provide(serverClient(env))))37 );38101/** 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 );39/** No landing to read: what the page reads while the answer has not landed. */40const noLanding = Atom.make(Option.none<LandingView>());41120 const landing = Option.getOrElse(fresh, () =>121 seeded?.sha === sha ? seeded : undefined42/**43 * The landing at `sha`, from its atom (seeded when the loader read it), or44 * as the loader read it. One hook whether or not the answer landed, so the45 * page keeps its place in the tree when the answer lands while it is open46 * (its outcome settles in rather than the page drawing anew).47 */48const useLanding = (49 read: AnswerPageData,50 sha: LandedSha | undefined51): LandingView | undefined => {52 const atom = useMemo(53 () =>54 sha === undefined55 ? noLanding56 : Atom.map(landingAtom(read.project, sha), (result) =>57 Option.map(AsyncResult.value(result), (found) => found.landing)58 ),59 [read.project, sha]60 );61124 return landing === undefined ? (125 <AnswerView now={now} verdict={verdict} />126 ) : (127 <AnswerView landing={landing} now={now} verdict={verdict} />62 return Option.getOrElse(useAtomValue(atom), () =>63 sha !== undefined && read.landing?.sha === sha ? read.landing : undefined64 );65};66131/** The page over the verdict's atom, which starts from what the loader read and refetches when its keys change. */67/**68 * The page over its atoms, which start from what the loader read and read69 * again as the project's events arrive: the verdict, the ask, its landing,70 * and the events the fold reads.71 */72const FreshAnswer = ({133 atom,73 read,74 viewer,75}: {136 readonly atom: ReturnType<typeof verdictAtom>;76 readonly read: AnswerPageData;77 readonly viewer: Handle | undefined;78}) => {139 // Live: a push, a verdict or a landing on the ask makes the verdict fetch again.79 // Live: each event the project hears reads again what it changed.80 useAtomMount(watchAtom(read.project));8182 const { verdict } = Option.getOrElse(143 AsyncResult.value(useAtomValue(atom)),83 AsyncResult.value(84 useAtomValue(verdictAtom(read.project, read.ask, read.head))85 ),86 () => read87 );88147 const sha = landedBy(verdict);89 const { ask } = Option.getOrElse(90 AsyncResult.value(useAtomValue(askAtom(read.project, read.ask))),91 () => ({ ask: read.askRead })92 );93149 return verdict === undefined || sha === undefined ? (150 <AnswerView now={read.now} verdict={verdict} />151 ) : (152 <LandedAnswer94 // The replay as the browser reads it, once it has; until then the95 // server's, which holds the same events about these asks.96 const events = Option.getOrElse(97 AsyncResult.value(useAtomValue(projectEventsAtom(read.project))),98 () => read.events99 );100101 const states = askStates(events);102 const landed = states.get(read.ask)?.landed;103104 const landing = useLanding(read, landedBy(verdict));105106 return (107 <AnswerView108 ask={ask}109 head={read.head}110 landing={landing}111 now={read.now}154 project={read.project}155 seeded={read.landing}156 sha={sha}112 parent={read.parent}113 // A landing the server's read already held never stamps.114 stamp={landed !== undefined && landed.seq > read.lastSeq}115 states={states}116 verdict={verdict}117 viewer={viewer}118 />119 );120};121122const AnswerPage = () => {123 const read = Schema.decodeSync(AnswerPageData)(Route.useLoaderData());164 const { ask, head, landing, project, verdict } = read;165 const atom = verdictAtom(project, ask, head);124 const who = useAtomValue(whoAtom);125 const { ask, askRead, brief, head, landing, project, verdict } = read;126127 const seeds = [168 seedSuccess(atom, verdict === undefined ? {} : { verdict }),128 seedSuccess(129 verdictAtom(project, ask, head),130 verdict === undefined ? {} : { verdict }131 ),132 seedSuccess(askAtom(project, ask), { ask: askRead, brief }),133 ...(landing === undefined134 ? []135 : [seedSuccess(landingAtom(project, landing.sha), { landing })]),136 ];137138 return (175 <PageShell title={`Answer to ${ask}`}>176 {head === undefined ? null : (177 <p className="text-sm">178 An earlier answer, at <code className={CODE}>{head.slice(0, 7)}</code>179 .{" "}180 <a className={LINK} href={answerPath(project, ask)}>181 The latest answer182 </a>183 </p>184 )}185 <SeededAtoms id={`${project}/${ask}/${head ?? ""}`} seeds={seeds}>186 <FreshAnswer atom={atom} read={read} />187 </SeededAtoms>188 </PageShell>139 <SeededAtoms id={`${project}/${ask}/${head ?? ""}`} seeds={seeds}>140 <FreshAnswer141 read={read}142 viewer={143 AsyncResult.isSuccess(who)144 ? Option.getOrUndefined(who.value)145 : undefined146 }147 />148 </SeededAtoms>149 );150};151152/** An address with no refusal behind it: a name that can name nothing, or a `?head=` that is no commit id. */153const NOTHING =154 "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.";155196const AnswerNotFound = ({ data }: { readonly data?: unknown }) => (197 <NoSuchAsk data={data} nothing={NOTHING} />198);156const AnswerNotFound = ({ data }: { readonly data?: unknown }) => {157 const { project } = useParams({ strict: false });158159 return <NoSuchAsk data={data} nothing={NOTHING} project={project} />;160};161162export const Route = createFileRoute("/$project/answers/$ask")({163 // TanStack infers each option from the ones before it, so the search comes164 // before the loader that reads it.165 validateSearch: ({ head }: { readonly head?: unknown }) =>166 Predicate.isString(head) ? { head } : {},167 loaderDeps: ({ search }) => ({ head: search.head }),168 loader: ({ deps, params }) => answerPage({ data: { ...params, ...deps } }),207 head: ({ params }) => pageHead({ title: `Answer to ${params.ask}` }),169 head: ({ loaderData, params }) =>170 loaderData === undefined171 ? pageHead({ title: `Answer to ${params.ask}` })172 : pageHead({173 description: loaderData.askRead.brief.want,174 title: `Answer to ${params.ask} · ${params.project}`,175 }),176 // An answer moves with each push and verdict: kept briefly, asked again.177 headers: () => branchPage,178 component: AnswerPage,179 notFoundComponent: AnswerNotFound,180});
modified:apps/web/src/routes/$project/asks/$ask.tsx+95 added-68 removed
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";1import { useAtomMount, useAtomValue } from "@effect/atom-react";2import type { Handle } from "@repo/protocol/ids";3import {4 createFileRoute,5 getRouteApi,6 useParams,7} from "@tanstack/react-router";8import { createServerFn } from "@tanstack/react-start";9import { env } from "cloudflare:workers";7import { DateTime, Effect, Option, Schema } from "effect";8import { AsyncResult, Atom } from "effect/reactivity";10import { Effect, Option, Schema } from "effect";11import { AsyncResult } from "effect/reactivity";1213import { verdictAtom } from "../../../client/answer.ts";14import { askAtom } from "../../../client/ask.ts";15import { askStates, projectEventsAtom } from "../../../client/events.ts";16import { SeededAtoms, seedSuccess } from "../../../client/seeded.ts";17import { watchAtom } from "../../../client/watch.ts";18import { AskPageData, readAsk } from "../../../features/answer/reads.ts";19import { AskView } from "../../../features/ask/ask-page.tsx";20import {21 markdownAlternate,22 wantsMarkdown,23} from "../../../features/ask/markdown.ts";24import { NoSuchAsk } from "../../../features/ask/refused.tsx";25import { whoAtom } from "../../../features/auth/who.ts";26import { pageHead } from "../../../features/shared/head.ts";18import { notFoundFor } from "../../../features/shared/refusals.ts";27import { useProjectList } from "../../../features/shared/shell/context.ts";28import { branchPage } from "../../../server/cache-headers.ts";29import { serverClient } from "../../../server/client.ts";30import { AskPath, askMarkdownHandler } from "./{$ask}[.]md.ts";31import type { AskParams, ClientFor } from "./{$ask}[.]md.ts";3223// The ask page: the brief, its fields and the lines that take it. The same33// The ask page: where the ask stands, its brief, its check and its answers,34// and the lines that take it; live while open. The same35// URL answers `Accept: text/markdown` with the brief as Markdown (the GET36// handler below), and its `.md` twin always does (`{$ask}[.]md.ts`).3738/**
33 unmodified lines
72 vary: "Accept",73 }),74 });7565/** What the page's loader carries from the server, encoded: the ask, its brief, and when it was read. */66const AskPageData = Schema.Struct({67 ask: Ask,68 brief: Schema.NonEmptyString,69 now: Schema.DateTimeUtcFromString,70});7172/** The ask for its page, or a not-found carrying the platform's refusal (a 404). */73export const readAsk = (params: AskParams) =>74 Effect.gen(function* () {75 const path = yield* Schema.decodeEffect(AskPath)(params).pipe(76 Effect.mapError(() => notFound())77 );7879 const client = yield* Client;8081 const read = yield* client.showAsk(path).pipe(82 Effect.catchTags({83 UnknownAsk: notFoundFor,84 UnknownProject: notFoundFor,85 })86 );8788 return yield* Schema.encodeEffect(AskPageData)({89 ...read,90 now: yield* DateTime.now,91 });92 });9376const askPage = createServerFn({ method: "GET" })77 .validator((params: AskParams) => params)78 .handler(({ data }) =>79 Effect.runPromise(readAsk(data).pipe(Effect.provide(serverClient(env))))80 );8182const root = getRouteApi("__root__");83102type AskRead = Pick<typeof AskPageData.Type, "ask" | "brief">;103104/** The page over the ask's atom, which starts from what the loader read and refetches when its keys change. */84/**85 * The page over its atoms, which start from what the loader read and read86 * again as the project's events arrive: the ask, its latest verdict, and87 * the events the fold reads.88 */89const FreshAsk = ({106 atom,107 now,90 platformUrl,91 read,92 viewer,93}: {111 readonly atom: ReturnType<typeof askAtom>;112 readonly now: DateTime.Utc;94 readonly platformUrl: string;114 readonly read: AskRead;95 readonly read: AskPageData;96 readonly viewer: Handle | undefined;97}) => {98 const { project } = read.ask;99100 // Live: each event the project hears reads again what it changed.101 useAtomMount(watchAtom(project));102103 const { ask, brief } = Option.getOrElse(117 AsyncResult.value(useAtomValue(atom)),104 AsyncResult.value(useAtomValue(askAtom(project, read.ask.id))),105 () => read106 );107108 const { verdict } = Option.getOrElse(109 AsyncResult.value(useAtomValue(verdictAtom(project, read.ask.id))),110 () => read111 );112113 // The replay as the browser reads it, once it has; until then the114 // server's, which holds the same events about these asks.115 const events = Option.getOrElse(116 AsyncResult.value(useAtomValue(projectEventsAtom(project))),117 () => read.events118 );119120 const posture = useProjectList()?.find(121 (listing) => listing.project === project122 )?.posture;123124 return (122 <AskView ask={ask} brief={brief} now={now} platformUrl={platformUrl} />125 <AskView126 ask={ask}127 brief={brief}128 check={read.check}129 now={read.now}130 parent={read.parent}131 platformUrl={platformUrl}132 posture={posture}133 states={askStates(events)}134 verdict={verdict}135 viewer={viewer}136 />137 );138};139140const AskPage = () => {141 const { platformUrl } = root.useLoaderData();142 const read = Schema.decodeSync(AskPageData)(Route.useLoaderData());143 const who = useAtomValue(whoAtom);144 const { ask, brief, verdict } = read;145129 const { ask, brief, now } = Schema.decodeSync(AskPageData)(130 Route.useLoaderData()131 );132133 const atom = askAtom(ask.project, ask.id);134146 return (136 <RegistryProvider137 initialValues={[138 Atom.initialValue(atom, AsyncResult.success({ ask, brief })),147 <SeededAtoms148 id={`${ask.project}/${ask.id}`}149 seeds={[150 seedSuccess(askAtom(ask.project, ask.id), { ask, brief }),151 seedSuccess(152 verdictAtom(ask.project, ask.id),153 verdict === undefined ? {} : { verdict }154 ),155 ]}140 key={`${ask.project}/${ask.id}`}156 >157 <FreshAsk143 atom={atom}144 now={now}158 platformUrl={platformUrl}146 read={{ ask, brief }}159 read={read}160 viewer={161 AsyncResult.isSuccess(who)162 ? Option.getOrUndefined(who.value)163 : undefined164 }165 />148 </RegistryProvider>166 </SeededAtoms>167 );168};169170const AskNotFound = ({ data }: { readonly data?: unknown }) => {171 const { project } = useParams({ strict: false });172173 return <NoSuchAsk data={data} project={project} />;174};175176export const Route = createFileRoute("/$project/asks/$ask")({177 // TanStack infers each option from the ones before it: the loader comes178 // first, so `head` reads its data.179 loader: ({ params }) => askPage({ data: params }),156 head: ({ loaderData }) =>157 pageHead({158 title:159 loaderData === undefined ? "No such ask" : loaderData.ask.brief.want,160 }),161 headers: askPageHeaders,180 head: ({ loaderData, params }) =>181 loaderData === undefined182 ? pageHead({ title: "No such ask" })183 : pageHead({184 description: loaderData.ask.brief.want,185 title: `${params.ask} · ${params.project}`,186 }),187 // An ask moves with each claim and landing: kept briefly, asked again.188 headers: (context) => ({ ...branchPage, ...askPageHeaders(context) }),189 component: AskPage,163 notFoundComponent: NoSuchAsk,190 notFoundComponent: AskNotFound,191 server: {192 handlers: {193 GET: askPageHandler((request) => serverClient(env, request)),194 },
2 unmodified lines
modified:apps/web/test/answer.test.tsx+333 added-75 removed
8 unmodified lines
9 */10import { describe, expect, it } from "@effect/vitest";11import { Brand } from "@repo/brand";12import { Client, Contracts } from "@repo/protocol/contracts";13import type { Verdict } from "@repo/protocol/domain/answer";14import type { Ask } from "@repo/protocol/domain/ask";15import { Outcome } from "@repo/protocol/domain/outcome";16import type { StageName } from "@repo/protocol/domain/outcome";14import { AreaName, AskId } from "@repo/protocol/ids";17import { AreaName, AskId, CommitSha, DecisionId } from "@repo/protocol/ids";18import {19 ChecksFailed,20 HeldBackFailed,21 UnknownAsk,
1 unmodified line
23} from "@repo/protocol/refusal";24import { explain } from "@repo/protocol/render";25import { asTester, unanswered } from "@repo/protocol/testing";26import { isNotFound } from "@tanstack/react-router";24import { Effect, Layer, Ref, Schema } from "effect";27import { Effect, Layer, Ref, Schema, Stream } from "effect";28import { RpcTest } from "effect/rpc";2930import {31 AnswerView,32 durationText,33 HeldBackBits,30 LaneTable,34} from "../src/features/answer/answer-page.tsx";35import { readAnswer } from "../src/features/answer/reads.ts";36import { askStates } from "../src/features/shared/ask-progress.ts";37import { Refusals } from "../src/features/shared/refusals.ts";33import { readAnswer } from "../src/routes/$project/answers/$ask.tsx";38import {39 ask,40 askId,41 brief,42 claimedEvent,43 decidedLanding,44 family,45 inOrder,46 judgedEvent,47 landedSha,48 landing,49 markupOf,50 now,51 plainLanding,52 plainText,53 project,54 suite,55 textOf,56 verdictOf,57} from "./ask-fixtures.ts";58import { textIn } from "./markup.ts";5960const checksFailed = new ChecksFailed({61 lane: "unit",62 logRef: "logs/datekit/parse-iso-week/unit",
14 unmodified lines
7778 return stage === undefined || state === undefined ? [] : [[stage, state]];79 });8069/** Each lane row, as `[lane, result]`. */81/** Each lane, in page order, as `[lane, result]`. */82const lanesOf = (markup: string) =>71 [...markup.matchAll(/<tr\b[^>]*>/gu)].flatMap(([tag]) => {72 const lane = /data-lane="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;73 const result = /data-result="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;83 [...markup.matchAll(/<[a-z]+\b[^>]*data-lane="[^"]*"[^>]*>/gu)].flatMap(84 ([tag]) => {85 const lane = /data-lane="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;86 const result = /data-result="(?<value>[^"]+)"/u.exec(tag)?.groups?.value;8775 return lane === undefined || result === undefined ? [] : [[lane, result]];76 });88 return lane === undefined || result === undefined ? [] : [[lane, result]];89 }90 );9192/** Each link to a commit page, in page order, as `[href, text]`. */93const commitLinksOf = (markup: string) =>94 [
5 unmodified lines
100 ? []101 : [[groups.href, plainText(groups.inner).trim()]]102 );10390describe(AnswerView, () => {91 const page = <AnswerView now={now} verdict={refused} />;104/** The hero, and the run after it. */105const heroOf = (markup: string) =>106 /<section aria-label="Outcome"[^>]*>(?<inner>.*?)<\/section>/su.exec(markup)107 ?.groups?.inner ?? "";108109const runOf = (markup: string) =>110 markup.slice(markup.indexOf('id="answer-gate"'), markup.indexOf("</main>"));111112/** The page's main pane, without the inspector. */113const mainOf = (markup: string) =>114 /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";115116/** The inspector. */117const asideOf = (markup: string) =>118 /<aside\b[^>]*>(?<inner>.*)<\/aside>/su.exec(markup)?.groups?.inner ?? "";119120const page = (121 props: Partial<Parameters<typeof AnswerView>[0]> & {122 readonly verdict: Verdict | undefined;123 }124) => <AnswerView ask={ask} now={now} {...props} />;125126const landedAt = (stage: StageName, heldBack: boolean) => ({127 ...verdictOf(Outcome.cases.Landed.make({ sha: landedSha })),128 heldBack: heldBack129 ? verdictOf(Outcome.cases.Landed.make({ sha: landedSha })).heldBack130 : [],131 stage,132});133134describe("the answer page", () => {135 const refusedPage = page({ verdict: refused });136137 it("titles the page with the ask's want, and names the project, the ask and the answer in its trail", () => {138 const markup = markupOf(refusedPage);139140 expect(markup).toMatch(141 /<h1\b[^>]*>Parse ISO week dates like 2026-W41-3<\/h1>/u142 );143 expect(144 inOrder(textOf(refusedPage), ["datekit", "Asks", askId, "Answer"])145 ).toBeTruthy();146 expect(markup).toContain('href="/datekit"');147 expect(markup).toContain(`href="/datekit/asks/${askId}"`);148 });149150 it("leads with the outcome: the first heading after the title is the hero, and a landing links its commit", () => {151 const landed = landedAt("human", true);152 const markup = markupOf(page({ landing: decidedLanding, verdict: landed }));153 const afterTitle = markup.slice(markup.indexOf("</h1>"));154155 const hero =156 /<section aria-label="Outcome"[^>]*>(?<inner>.*?)<\/section>/su.exec(157 afterTitle158 );159160 expect(hero).not.toBeNull();161 expect(afterTitle.indexOf('<section aria-label="Outcome"')).toBeLessThan(162 afterTitle.indexOf("<h2")163 );164 expect(plainText(hero?.groups?.inner ?? "")).toContain("Landed as 9b1c3e5");165 expect(hero?.groups?.inner).toContain(166 `href="/datekit/commit/${landedSha}"`167 );168 });169170 it("puts what was judged in the inspector, after the outcome and the gate", () => {171 const markup = markupOf(refusedPage);172 const strip = markup.indexOf('data-stage="human"');173174 expect(strip).toBeGreaterThan(markup.indexOf('aria-label="Outcome"'));175 expect(asideOf(markup)).toContain("Patch id");176 expect(asideOf(markup)).toContain("Merged tree");177178 expect(markup.indexOf("<aside")).toBeGreaterThan(strip);179 // Below the shell's width, where the facts sit above the run, it comes last in main.180 expect(mainOf(markup).lastIndexOf("Patch id")).toBeGreaterThan(181 mainOf(markup).indexOf('data-stage="human"')182 );183 });184185 it("shows the stages the answer passed, the one that refused it, and the ones it never reached", () => {94 expect(stagesOf(markupOf(page))).toStrictEqual([186 expect(stagesOf(mainOf(markupOf(refusedPage)))).toStrictEqual([187 ["parse", "passed"],188 ["shape", "passed"],189 ["merge", "passed"],190 ["cheap", "passed"],
2 unmodified lines
193 ["human", "pending"],194 ]);195 });196105 it("shows each lane with its result", () => {106 expect(lanesOf(markupOf(page))).toStrictEqual([107 ["lint", "passed"],197 it("reads the decider and held-back stages as not needed for a landing that needed neither", () => {198 const markup = markupOf(199 page({ landing: plainLanding, verdict: landedAt("human", false) })200 );201202 expect(stagesOf(mainOf(markup)).slice(5)).toStrictEqual([203 ["heldBack", "skipped"],204 ["human", "skipped"],205 ]);206 expect(207 textOf(page({ landing: plainLanding, verdict: landedAt("human", false) }))208 ).toContain("not needed");209 });210211 it("reads them passed for a landing a decider finished and held-back checks judged", () => {212 const markup = markupOf(213 page({ landing: decidedLanding, verdict: landedAt("human", true) })214 );215216 expect(stagesOf(mainOf(markup)).slice(5)).toStrictEqual([217 ["heldBack", "passed"],218 ["human", "passed"],219 ]);220 });221222 it("opens failed lanes first, each with the command that reads its log, and folds the passed ones into a line", () => {223 const markup = markupOf(refusedPage);224 const text = textOf(refusedPage);225226 expect(lanesOf(mainOf(markup))).toStrictEqual([227 ["unit", "failed"],228 ["lint", "passed"],229 ]);230 expect(text).toContain(231 `${Brand.cli} evidence logs/datekit/parse-iso-week/unit --project datekit`232 );233 expect(text).toContain("1 lane passed in 1.2 s");234 expect(111 inOrder(textOf(page), ["lint", "passed", "unit", "failed"])235 /<details\b[^>]*>.*data-lane="lint".*<\/details>/su.test(mainOf(markup))236 ).toBeTruthy();237 expect(inOrder(text, ["unit", "bun test", "failed", "8.3 s"])).toBeTruthy();238 });239240 it("names a lane's log only as the command that reads it", () => {241 const passing = verdictOf(Outcome.cases.Checking.make({ stage: "checks" }));242 const text = textOf(page({ verdict: passing }));243244 const mentions = [245 ...text.matchAll(/logs\/datekit\/parse-iso-week\/unit/gu),246 ];247248 expect(mentions.length).toBeGreaterThan(0);249250 for (const { index } of mentions) {251 expect(text.slice(index - `${Brand.cli} evidence `.length, index)).toBe(252 `${Brand.cli} evidence `253 );254 }255 });256257 it("shows held-back checks only as an area's counts and its suite root", () => {258 const bits =259 /<ul aria-label="Held-back checks by area"[^>]*>(?<inner>.*?)<\/ul>/su.exec(118 markupOf(page)260 markupOf(refusedPage)261 )?.groups?.inner;262263 expect(plainText(bits ?? "").trim()).toBe(`export 6/7 @ ${suite}`);264 });265266 it("shows the refusals' explain lines in order, as git printed them", () => {267 expect(268 inOrder(127 textOf(page),269 textOf(refusedPage),270 explain([checksFailed, heldBackFailed]).map((line) => line.trim())271 )272 ).toBeTruthy();273 });274133 it("never shows where a lane's log is kept outside the refusal that names it", () => {134 const passing = verdictOf(Outcome.cases.Checking.make({ stage: "checks" }));275 it("names the answer it judged, its round, and when", () => {276 const states = askStates([277 claimedEvent(1, "okafor"),278 judgedEvent(2, refused.outcome, CommitSha.make("e".repeat(40))),279 judgedEvent(3, refused.outcome),280 ]);281136 expect(textOf(<AnswerView now={now} verdict={passing} />)).not.toContain(137 "logs/datekit"282 const element = page({ states, verdict: refused });283 const text = textOf(element);284285 for (const shown of [286 "round 2 of 2",287 "bbbbbbb",288 "aaaaaaa",289 "redThenGreen@0.0.0+5e1d",290 "20 min ago",291 "okafor's move",292 ]) {293 expect(text).toContain(shown);294 }295 });296297 it("reads a wait on a decision as waiting, in the hero", () => {298 const waiting = verdictOf(299 Outcome.cases.AwaitingDecision.make({300 decision: DecisionId.make("dec-000001"),301 })302 );303304 const text = textOf(page({ verdict: waiting }));305306 expect(text).toContain("Waiting on decision dec-000001");307 });308141 it("names the answer it judged and when", () => {142 const text = textOf(page);309 it("gives an ask nobody answered the command that claims it", () => {310 const text = textOf(page({ verdict: undefined }));311144 expect(text).toContain("bbbbbbb");145 expect(text).toContain("aaaaaaa");146 expect(text).toContain("redThenGreen@0.0.0+5e1d");147 expect(text).toContain("20 min ago");312 expect(text).toContain("Nobody has answered this ask yet.");313 expect(text).toContain(`${Brand.cli} claim ${askId} --project datekit`);314 expect(markupOf(page({ verdict: undefined }))).not.toContain("data-stage");315 });316150 it("says plainly when no answer has been checked yet", () => {151 const text = textOf(<AnswerView now={now} verdict={undefined} />);317 it("names who holds a claimed ask with no answer pushed, and links back to the ask", () => {318 const states = askStates([claimedEvent(1, "bram")]);319 const element = page({ states, verdict: undefined });320 const main = mainOf(markupOf(element));321153 expect(text).toContain("No answer to this ask has been checked yet");154 expect(text).not.toContain("Parse");322 expect(textIn(main)).toContain("Claimed by bram, no answer pushed yet.");323 expect(main).toContain(`href="/datekit/asks/${askId}"`);324 });325326 it("shows a landed answer's credit trailers in trailer order, its held-back trailer, and its commit", () => {327 const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));159 const element = <AnswerView landing={landing} now={now} verdict={landed} />;160 const text = textOf(element);328 const text = textOf(page({ landing, verdict: landed }));329330 expect(text).toContain("Landed as 9b1c3e5");331 expect(332 inOrder(text, ["Asked-by: ines-v", "Signed-off-by: okafor"])
2 unmodified lines
335 expect(text).toContain("Assisted-by: claude-code:opus-5 (verified)");336 expect(text).toContain(`git show ${landedSha}`);337 });338171 it("links a landed answer's landing and its base to their commit pages, and keeps the git show command", () => {339 it("links a landed answer's landing (from the hero and the landing) and its base to their commit pages", () => {340 const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));341 const markup = markupOf(page({ landing, verdict: landed }));342174 const markup = markupOf(175 <AnswerView landing={landing} now={now} verdict={landed} />176 );177178 expect(commitLinksOf(markup)).toStrictEqual([343 expect(commitLinksOf(heroOf(markup))).toStrictEqual([344 [`/${project}/commit/${landedSha}`, "9b1c3e5"],345 ]);346 expect(commitLinksOf(runOf(markup))).toStrictEqual([347 [`/${project}/commit/${landed.base}`, landed.base.slice(0, 7)],348 [`/${project}/commit/${landedSha}`, "The landing commit"],349 ]);182 expect(markup).toContain(`git show ${landedSha}`);350 });351352 it("links neither the head nor the merged tree: they live in the claim's fork", () => {353 const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));354 const markup = markupOf(page({ landing, verdict: landed }));355188 const markup = markupOf(189 <AnswerView landing={landing} now={now} verdict={landed} />190 );191356 expect(markup).not.toContain(`/commit/${landed.head}`);357 expect(markup).not.toContain(`/commit/${landed.tree}`);358 });359360 it("links the base and no landing when the answer has not landed", () => {197 expect(commitLinksOf(markupOf(page))).toStrictEqual([361 expect(commitLinksOf(heroOf(markupOf(refusedPage)))).toStrictEqual([]);362 expect(commitLinksOf(runOf(markupOf(refusedPage)))).toStrictEqual([363 [`/${project}/commit/${refused.base}`, refused.base.slice(0, 7)],364 ]);365 });201});366203describe(LaneTable, () => {204 it("gives each lane's command and how long it ran", () => {205 const { lanes } = refused;206 const text = textOf(<LaneTable lanes={lanes} />);367 it("stamps the landed mark only when the page is told the landing came while it was open", () => {368 const landed = landedAt("human", false);369208 expect(inOrder(text, ["lint", "bun run lint", "1.2 s"])).toBeTruthy();209 expect(inOrder(text, ["unit", "bun test", "8.3 s"])).toBeTruthy();370 expect(371 markupOf(page({ landing: plainLanding, stamp: true, verdict: landed }))372 ).toContain("animate-stamp");373 expect(374 markupOf(page({ landing: plainLanding, verdict: landed }))375 ).not.toContain("animate-stamp");376 });377212 it("says when no lane ran", () => {213 expect(textOf(<LaneTable lanes={[]} />)).toContain("No lane ran");378 it("draws a family member's family, the member marked", () => {379 const child = family.child(1);380381 const markup = markupOf(382 <AnswerView383 ask={child}384 now={now}385 parent={family.parent}386 verdict={refused}387 />388 );389390 expect(asideOf(markup)).toContain(`data-family="${family.parent.id}"`);391 expect(asideOf(markup)).toMatch(392 /aria-current="true"[^>]*title="retire-old-week-parse"|title="retire-old-week-parse"[^>]*aria-current="true"/u393 );394 });395});396397describe(HeldBackBits, () => {
8 unmodified lines
406 );407 });408});409410describe(durationText, () => {411 it("says how long a lane ran in the unit a person reads", () => {412 expect([640, 8312, 125_000].map(durationText)).toStrictEqual([413 "640 ms",414 "8.3 s",415 "2 min 5 s",416 ]);417 });418});419230/** What the stub platform was asked: verdicts and landings. */420/** What the stub platform was asked: verdicts, landings, asks and replays. */421interface Asked {422 readonly asks: number;423 readonly landings: number;424 readonly replays: number;425 readonly verdicts: number;426}427428/** Events in datekit: bram claimed the ask and pushed, and another ask was claimed too. */429const replay = [430 claimedEvent(1, "bram"),431 claimedEvent(2, "okafor", AskId.make("format-week")),432 judgedEvent(3, refused.outcome),433];434435const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>436 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));437438/**439 * A platform whose datekit ask's latest answer ended in `outcome`, as the440 * answer page's loader calls it; `landingKnown` says whether it still finds441 * the landing a landed verdict names.442 */443const platformAt = (444 asked: Ref.Ref<Asked>,445 outcome: Outcome,244 landingKnown = true446 landingKnown = true,447 shown: Ask = ask448) =>449 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(450 Layer.provide([451 Layer.mergeAll(452 unanswered,453 Contracts.toLayerHandler("verdict", (payload) =>454 Effect.gen(function* () {252 yield* Ref.update(asked, (seen) => ({253 ...seen,254 verdicts: seen.verdicts + 1,255 }));455 yield* count(asked, "verdicts");456457 if (payload.ask !== askId) {458 return yield* new UnknownAsk({ ask: payload.ask });459 }460461 return { verdict: verdictOf(outcome) };462 })463 ),464 Contracts.toLayerHandler("showAsk", (payload) =>465 Effect.gen(function* () {466 yield* count(asked, "asks");467468 if (payload.ask !== shown.id && payload.ask !== family.parent.id) {469 return yield* new UnknownAsk({ ask: payload.ask });470 }471472 return {473 ask: payload.ask === shown.id ? shown : family.parent,474 brief,475 };476 })477 ),478 Contracts.toLayerHandler("watch", () =>479 Stream.fromEffect(count(asked, "replays")).pipe(480 Stream.flatMap(() => Stream.fromIterable(replay))481 )482 ),483 Contracts.toLayerHandler("landing", (payload) =>484 Effect.gen(function* () {266 yield* Ref.update(asked, (seen) => ({267 ...seen,268 landings: seen.landings + 1,269 }));485 yield* count(asked, "landings");486487 if (!landingKnown || payload.sha !== landedSha) {488 return yield* new UnknownCommit({ sha: payload.sha });489 }
5 unmodified lines
495 asTester,496 ])497 );498283const nothingAsked: Asked = { landings: 0, verdicts: 0 };499const nothingAsked: Asked = { asks: 0, landings: 0, replays: 0, verdicts: 0 };500501describe(readAnswer, () => {286 it.effect("reads a landed answer's landing with its verdict", () =>502 it.effect(503 "reads a landed answer's landing with its verdict, its ask and the ask's events",504 () =>505 Effect.gen(function* () {506 const asked = yield* Ref.make(nothingAsked);507 const landed = Outcome.cases.Landed.make({ sha: landedSha });508509 const read = yield* readAnswer({ ask: askId, project }).pipe(510 Effect.provide(platformAt(asked, landed))511 );512513 expect({514 events: read.events.map(({ seq }) => seq),515 landing: read.landing?.sha,516 lastSeq: read.lastSeq,517 outcome: read.verdict?.outcome._tag,518 parent: read.parent,519 want: read.askRead.brief.want,520 }).toStrictEqual({521 events: [1, 3],522 landing: landedSha,523 lastSeq: 3,524 outcome: "Landed",525 parent: undefined,526 want: ask.brief.want,527 });528 expect(yield* Ref.get(asked)).toStrictEqual({529 asks: 1,530 landings: 1,531 replays: 1,532 verdicts: 1,533 });534 })535 );536537 it.effect("reads a family member's parent, for the family", () =>538 Effect.gen(function* () {539 const asked = yield* Ref.make(nothingAsked);289 const landed = Outcome.cases.Landed.make({ sha: landedSha });540541 const read = yield* readAnswer({ ask: askId, project }).pipe(292 Effect.provide(platformAt(asked, landed))542 Effect.provide(543 platformAt(asked, refused.outcome, true, {544 ...family.child(0),545 id: askId,546 })547 )548 );549295 expect(read.verdict?.outcome._tag).toBe("Landed");296 expect(read.landing?.sha).toBe(landedSha);297 expect(yield* Ref.get(asked)).toStrictEqual({ landings: 1, verdicts: 1 });550 expect(read.parent?.id).toBe(family.parent.id);551 expect(yield* Ref.get(asked)).toStrictEqual({552 asks: 2,553 landings: 0,554 replays: 1,555 verdicts: 1,556 });557 })558 );559560 it.effect("asks for no landing when the answer did not land", () =>
5 unmodified lines
566 );567568 expect(read.verdict?.outcome._tag).toBe("Refused");569 expect(read.landing).toBeUndefined();311 expect(yield* Ref.get(asked)).toStrictEqual({ landings: 0, verdicts: 1 });570 expect((yield* Ref.get(asked)).landings).toBe(0);571 })572 );314573 it.effect(574 "shows the verdict alone when the platform no longer finds its landing",575 () =>576 Effect.gen(function* () {
62 unmodified lines
modified:apps/web/test/ask-fixtures.ts+101 added
7 unmodified lines
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 { ProjectEvent } from "@repo/protocol/domain/event";13import type { LandingView } from "@repo/protocol/domain/landing";14import type { Outcome } from "@repo/protocol/domain/outcome";15import {16 AreaName,
116 unmodified lines
133 project,134 sha: landedSha,135};136137/** The landing as a decider's finish made it: decided, and judged by held-back checks. */138export const decidedLanding: LandingView = {139 ...landing,140 credits: [141 ...landing.credits,142 { handle: Handle.make("ines-v"), role: "Decided-by" },143 ],144};145146/** The landing as one that needed neither a decider nor held-back checks makes it. */147export const plainLanding: LandingView = {148 ask: askId,149 assisted: [],150 author: Handle.make("bram"),151 credits: [152 { handle: Handle.make("bram"), role: "Signed-off-by" },153 { handle: Handle.make("ines-v"), role: "Asked-by" },154 ],155 landedAt: DateTime.makeUnsafe("2026-10-07T11:45:00Z"),156 parent: LandedSha.make(sha("a")),157 project,158 sha: landedSha,159};160161/** When the events below happened. */162const eventAt = DateTime.makeUnsafe("2026-10-07T11:30:00Z");163164/** `claimant` claimed `on`, as event `seq`. */165export const claimedEvent = (seq: number, claimant: string, on = askId) =>166 ProjectEvent.cases.Claimed.make({167 ask: on,168 at: eventAt,169 claimant: Handle.make(claimant),170 seq,171 });172173/** An answer at `head` to `on` was judged `outcome`, as event `seq`. */174export const judgedEvent = (175 seq: number,176 outcome: Outcome,177 head = CommitSha.make(sha("b")),178 on = askId179) =>180 ProjectEvent.cases.Judged.make({ ask: on, at: eventAt, head, outcome, seq });181182/** An answer to `on` was pushed at `head`, as event `seq`. */183export const pushedEvent = (184 seq: number,185 head = CommitSha.make(sha("b")),186 on = askId187) => ProjectEvent.cases.Pushed.make({ ask: on, at: eventAt, head, seq });188189/** `on` closed by a landing, as event `seq`. */190export const closedEvent = (seq: number, on = askId) =>191 ProjectEvent.cases.AskClosed.make({192 ask: on,193 at: eventAt,194 landing: landedSha,195 seq,196 });197198const familyParent = AskId.make("retire-old-week");199200const familyChildren = ["format", "parse", "zones"].map((module) =>201 AskId.make(`retire-old-week-${module}`)202);203204const familyDelete = AskId.make("retire-old-week-delete");205206/** One member of the family below: blocked by `blockedBy`, its parent named. */207const member = (id: AskId, blockedBy: readonly AskId[]): Ask => ({208 ...ask,209 blockedBy,210 brief: { want: `Step ${id} of retiring oldWeek` },211 id,212 kind: KindName.make("migrate"),213 parent: familyParent,214});215216/** A migrate family in datekit: a parent, three children, and the delete child that waits on them. */217export const family = {218 /** The child at `index`, which waits on nothing. */219 child: (index: number) =>220 member(familyChildren[index] ?? AskId.make("retire-old-week-format"), []),221 children: familyChildren,222 deleteChild: {223 ...member(familyDelete, familyChildren),224 state: "waitingOnParent",225 } satisfies Ask,226 parent: {227 ...ask,228 blockedBy: [...familyChildren, familyDelete],229 brief: {230 want: "Replace every call to oldWeek with week, then delete oldWeek.",231 },232 id: familyParent,233 kind: KindName.make("migrate"),234 } satisfies Ask,235};236237/** The entities React writes for text, and what each reads as. */238const ENTITIES: ReadonlyMap<string, string> = new Map([239 ["&#x27;", "'"],240 ["&amp;", "&"],
37 unmodified lines
modified:apps/web/test/ask.test.tsx+398 added-82 removed
5 unmodified lines
6 */7import { describe, expect, it } from "@effect/vitest";8import { Brand } from "@repo/brand";9import { Client, Contracts } from "@repo/protocol/contracts";10import { Glob } from "@repo/protocol/domain/common";11import { AskId, Handle } from "@repo/protocol/ids";12import { UnknownAsk } from "@repo/protocol/refusal";10import type { Ask } from "@repo/protocol/domain/ask";11import { Outcome } from "@repo/protocol/domain/outcome";12import {13 AskId,14 BlobSha,15 CommitSha,16 Handle,17 RepoPath,18} from "@repo/protocol/ids";19import { OutOfScope, UnknownAsk, UnknownPath } from "@repo/protocol/refusal";20import { explain } from "@repo/protocol/render";21import { asTester, unanswered } from "@repo/protocol/testing";22import { isNotFound } from "@tanstack/react-router";16import { Effect, Layer, Ref, Schema } from "effect";23import { Effect, Layer, Ref, Schema, Stream } from "effect";24import { RpcTest } from "effect/rpc";2526import { readAsk } from "../src/features/answer/reads.ts";27import { AskView } from "../src/features/ask/ask-page.tsx";28import { NoSuchAsk } from "../src/features/ask/refused.tsx";29import { askStates } from "../src/features/shared/ask-progress.ts";30import { Refusals } from "../src/features/shared/refusals.ts";22import { readAsk } from "../src/routes/$project/asks/$ask.tsx";31import {32 ask,33 askId,34 brief,35 claimedEvent,36 closedEvent,37 family,38 inOrder,39 judgedEvent,40 landedSha,41 markupOf,42 now,43 plainText,44 project,45 textOf,46 verdictOf,47} from "./ask-fixtures.ts";48import { textIn } from "./markup.ts";4950const platformUrl = "https://platform-test.example.workers.dev";5152/** The markup inside the first `<pre>`. */53const inPre = (markup: string) =>54 /<pre\b[^>]*>(?<inner>.*?)<\/pre>/su.exec(markup)?.groups?.inner;5540const page = (shown = ask) => (41 <AskView ask={shown} brief={brief} now={now} platformUrl={platformUrl} />56/** The page's main pane, without the inspector. */57const mainOf = (markup: string) =>58 /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";5960/** The inspector. */61const asideOf = (markup: string) =>62 /<aside\b[^>]*>(?<inner>.*)<\/aside>/su.exec(markup)?.groups?.inner ?? "";6364/** The context bar's trail. */65const trailOf = (markup: string) =>66 /<nav aria-label="Breadcrumb"[^>]*>(?<inner>.*?)<\/nav>/su.exec(markup)67 ?.groups?.inner ?? "";6869type AskProps = Parameters<typeof AskView>[0];7071const page = (shown = ask, more: Partial<AskProps> = {}) => (72 <AskView73 ask={shown}74 brief={brief}75 now={now}76 platformUrl={platformUrl}77 {...more}78 />79);8081/** The check's source, as the platform reads it. */82const checkSource = (lines: number) => ({83 path: RepoPath.make("test/parse-week.test.ts"),84 sha: "f".repeat(40),85 text: Array.from(86 { length: lines },87 (_, index) => `expect(parseWeek("2026-W41-${index}")).not.toBeNull();`88 ).join("\n"),89});9091describe(AskView, () => {92 it("titles the page with the want, then reads the brief's sections in order", () => {93 const markup = markupOf(page());94
13 unmodified lines
108 ])109 ).toBeTruthy();110 });111112 it("sets a want of 80 characters at the headline, and a longer one a step down, whole", () => {113 const want =114 "The linter reports a heading that skips a level, such as a level-two heading followed by a level-four one.";115116 const long = markupOf(page({ ...ask, brief: { ...ask.brief, want } }));117118 expect(119 /<h1\b[^>]*class="(?<classes>[^"]*)"/u.exec(long)?.groups?.classes120 ).toContain("text-title");121 expect(long).toContain(`>${want}</h1>`);122 expect(123 /<h1\b[^>]*class="(?<classes>[^"]*)"/u.exec(markupOf(page()))?.groups124 ?.classes125 ).toContain("text-headline");126 });127128 it("leaves out a section the brief does not have", () => {129 const text = textOf(130 page({ ...ask, brief: { want: "Parse ISO week dates like 2026-W41-3" } })131 );
2 unmodified lines
134 expect(text).not.toContain("Out of scope");135 expect(text).not.toContain("Terms");136 });13775 it("gives the ask's name, kind, state and check", () => {138 it("names the project, its asks and the ask in the context bar's trail", () => {139 const trail = trailOf(markupOf(page()));140141 expect(inOrder(plainText(trail), ["datekit", "Asks", askId])).toBeTruthy();142 expect(trail).toContain('href="/datekit"');143 });144145 it("says an open ask is open to take, who it is held for, and gives its kind, asker and age", () => {146 const held = {147 ...ask,148 mentor: Handle.make("okonkwo"),149 reserve: "newcomers" as const,150 };151152 const text = textOf(page(held));153154 expect(text).toContain("Open to take");155 expect(text).toContain("Held for newcomers, mentored by okonkwo");156 expect(77 inOrder(textOf(page()), [78 "Ask",79 askId,80 "State",81 "Open",82 "Kind",83 "fix",84 "Check",85 "test/parse-week.test.ts",86 ])157 inOrder(text, ["fix", "asked by", "ines-v", "opened 2 d ago"])158 ).toBeTruthy();159 expect(markupOf(page(held))).toContain('href="/people/okonkwo"');160 expect(markupOf(page())).toContain('href="/people/ines-v"');161 });16290 it("gives the ask's territory, and who asked it when", () => {163 it("gives the ask's territory and its check", () => {164 const text = textOf(page());165166 expect(94 inOrder(text, ["Asked by", "ines-v", "opened 2 d ago"])167 inOrder(text, [168 "Territory and check",169 "@datekit/parse",170 "test/parse-week.test.ts",171 ])172 ).toBeTruthy();173 expect(markupOf(page())).toContain(174 'href="/datekit/blob/main/test/parse-week.test.ts"'175 );176 });177178 it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {179 expect(97 inOrder(text, ["Territory", "@datekit/parse", "packages/parse/**"])180 inOrder(textOf(page()), [181 `git clone ${platformUrl}/datekit.git`,182 `${Brand.cli} claim ${askId} --project datekit`,183 `${Brand.cli} check`,184 ])185 ).toBeTruthy();99 expect(markupOf(page())).toContain('href="/people/ines-v"');186 });187102 // A paths territory (`territory.paths(...)`) has module `.`, which names103 // nothing a reader knows: the field gives its paths alone.104 it("gives a paths territory as its paths, with no module `.`", () => {105 const text = textOf(106 page({107 ...ask,108 territory: {109 module: ".",110 paths: [Glob.make("src/parse.ts"), Glob.make("test/parse.test.ts")],111 },112 })188 it("names who holds a claimed ask and offers no way to take it", () => {189 const states = askStates([claimedEvent(1, "tamsin")]);190191 const text = textIn(192 markupOf(page({ ...ask, state: "claimed" }, { states }))193 );194115 const field = text.slice(116 text.indexOf("Territory"),117 text.indexOf("Check", text.indexOf("Territory"))195 expect(text).toContain("Claimed by tamsin, no answer pushed yet");196 expect(text).toContain("tamsin's move");197 expect(text).not.toContain("Take it");198 expect(text).not.toContain(`${Brand.cli} claim`);199 });200201 it("says where a refused answer was refused, whose move it is and what to run", () => {202 const refusal = new OutOfScope({ paths: [RepoPath.make("README.md")] });203 const outcome = Outcome.cases.Refused.make({ refusals: [refusal] });204205 const states = askStates([206 claimedEvent(1, "tamsin"),207 judgedEvent(2, outcome),208 ]);209210 const text = textOf(211 page(212 { ...ask, state: "claimed" },213 { states, verdict: { ...verdictOf(outcome), stage: "shape" } }214 )215 );216217 expect(121 inOrder(field, ["The paths", "src/parse.ts", "test/parse.test.ts"])218 inOrder(text, [219 "Refused",220 "at Shape",221 "OutOfScope",222 "tamsin's move",223 refusal.next,224 ])225 ).toBeTruthy();123 expect(field).not.toMatch(/\s\.\s|\s\.:/u);226 });227126 it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {228 it("says a landed ask landed, with its commit", () => {229 const states = askStates([230 claimedEvent(1, "tamsin"),231 judgedEvent(2, Outcome.cases.Landed.make({ sha: landedSha })),232 closedEvent(3),233 ]);234235 const markup = markupOf(page({ ...ask, state: "closed" }, { states }));236237 expect(textOf(page({ ...ask, state: "closed" }, { states }))).toContain(238 "Landed as 9b1c3e5"239 );240 expect(markup).toContain(`href="/datekit/commit/${landedSha}"`);241 });242243 it("gives a round the word its landing or verdict has since said, not the one it was judged with", () => {244 const states = askStates([245 claimedEvent(1, "tamsin"),246 judgedEvent(2, Outcome.cases.Checking.make({ stage: "human" })),247 closedEvent(3),248 ]);249250 const answers = plainText(251 mainOf(markupOf(page({ ...ask, state: "closed" }, { states })))252 );253254 expect(inOrder(answers, ["Round 1", "bbbbbbb", "Landed"])).toBeTruthy();255 expect(answers).not.toContain("Checking");256 });257258 it("lists one answer row per judged round, each linking its answer", () => {259 const states = askStates([260 claimedEvent(1, "tamsin"),261 judgedEvent(262 2,263 Outcome.cases.Refused.make({264 refusals: [new OutOfScope({ paths: [RepoPath.make("README.md")] })],265 }),266 CommitSha.make("e".repeat(40))267 ),268 judgedEvent(3, Outcome.cases.Checking.make({ stage: "checks" })),269 ]);270271 const main = mainOf(272 markupOf(page({ ...ask, state: "claimed" }, { states }))273 );274275 const rows = [276 ...main.matchAll(277 /href="\/datekit\/answers\/parse-iso-week\?head=(?<head>[0-9a-f]+)"/gu278 ),279 ].map(({ groups }) => groups?.head);280281 expect(rows).toStrictEqual(["e".repeat(40), "b".repeat(40)]);282 expect(128 inOrder(textOf(page()), [129 `git clone ${platformUrl}/datekit.git`,130 `${Brand.cli} claim ${askId} --project datekit`,131 `${Brand.cli} check --ask ${askId}`,283 inOrder(plainText(main), [284 "Answers",285 "Round 1",286 "eeeeeee",287 "Refused",288 "Round 2",289 "bbbbbbb",290 "Checking",291 ])292 ).toBeTruthy();293 });294295 it("shows the check's source inline when it was read, its first 30 lines until asked for the whole", () => {296 const markup = mainOf(markupOf(page(ask, { check: checkSource(45) })));297 const text = plainText(markup);298299 expect(text).toContain('expect(parseWeek("2026-W41-29")).not.toBeNull();');300 expect(text).not.toContain(301 'expect(parseWeek("2026-W41-30")).not.toBeNull();'302 );303 expect(text).toContain("Show the whole check");304 expect(markup).toContain('data-code="plain"');305 });306307 it("shows only the check's path when its source could not be read", () => {308 const markup = mainOf(markupOf(page()));309310 expect(markup).not.toContain('data-code="plain"');311 expect(markup).toContain(312 'href="/datekit/blob/main/test/parse-week.test.ts"'313 );314 });315316 it("says a family's delete child waits for its siblings in the family's terms", () => {317 const { children, deleteChild, parent } = family;318 const states = askStates([closedEvent(1, children[0] ?? parent.id)]);319 const text = textOf(page(deleteChild, { parent, states }));320321 expect(text).toContain("Waiting for 2 of 3 children to land");322 expect(text).not.toContain("Waits on");323 });324325 it("says a delete child whose siblings all landed is open to take, and never that it waits", () => {326 const { children, deleteChild, parent } = family;327328 const states = askStates(329 children.map((child, index) => closedEvent(index + 1, child))330 );331332 const markup = markupOf(333 page({ ...deleteChild, state: "open" }, { parent, states })334 );335336 const text = textOf(337 page({ ...deleteChild, state: "open" }, { parent, states })338 );339340 expect(text).toContain("Open to take");341 expect(text).not.toContain("Waits on");342 expect(text).not.toContain("to land first");343 expect(asideOf(markup)).toContain(`data-family="${parent.id}"`);344 });345136 it("names the asks a blocked ask waits on, each linking to its page", () => {346 it("names the asks an ask outside a family waits on, each linking to its page", () => {347 const blocked = {348 ...ask,349 blockedBy: [AskId.make("split-format"), AskId.make("split-parse")],350 };
12 unmodified lines
363 expect(markup).toContain('href="/datekit/asks/split-format"');364 expect(markup).toContain('href="/datekit/asks/split-parse"');365 });366157 it("names nothing it waits on when nothing blocks it", () => {367 it("names nothing it waits on when nothing blocks it, or what blocked it landed", () => {368 expect(textOf(page())).not.toContain("Waits on");159 });369161 it("links a step of a migrate to its parent ask", () => {162 const child = { ...ask, parent: AskId.make("migrate-week-api") };370 const states = askStates([closedEvent(1, AskId.make("split-format"))]);371164 expect(markupOf(page(child))).toContain(165 'href="/datekit/asks/migrate-week-api"'166 );372 expect(373 textOf(374 page({ ...ask, blockedBy: [AskId.make("split-format")] }, { states })375 )376 ).not.toContain("Waits on");377 });378169 it("says when an ask is held for newcomers, and who mentors them", () => {170 const held = {171 ...ask,172 mentor: Handle.make("okonkwo"),173 reserve: "newcomers" as const,174 };175176 const text = textOf(page(held));177178 expect(text).toContain("Held for newcomers");179 expect(markupOf(page(held))).toContain('href="/people/okonkwo"');180 });181379 it("gives no claim line once the ask is closed", () => {380 const text = textOf(page({ ...ask, state: "closed" }));381382 expect(text).toContain("Closed");
9 unmodified lines
392393 it("shows the brief exactly as an agent reads it", () => {394 expect(inPre(markupOf(page()))).toBe(inPre(markupOf(<pre>{brief}</pre>)));395 });396397 it("gives the project's posture when the list of projects has it", () => {398 const text = textOf(page(ask, { posture: "openWithSealedEvidence" }));399400 expect(text).toContain("Open with sealed evidence");401 });402});403404describe(NoSuchAsk, () => {405 it("shows the refusal a loader's not-found carried from the server, as git printed it", () => {
14 unmodified lines
420 it("says nothing is at an address that names no ask at all", () => {421 expect(textOf(<NoSuchAsk />)).toContain("Nothing is at this address");422 });423424 it("offers the way onward: the project, and the open asks", () => {425 const markup = markupOf(<NoSuchAsk project="datekit" />);426427 expect(markup).toContain('href="/datekit"');428 expect(markup).toContain('href="/"');429 expect(textOf(<NoSuchAsk project="datekit" />)).toContain("Open asks");430 });431432 it("says what its route gives it when a not-found carries no refusal", () => {433 expect(434 textOf(<NoSuchAsk nothing="No answer is at this head." />)435 ).toContain("No answer is at this head.");436 });437});438228/** A platform that knows datekit's one ask, counting `showAsk` calls. */229const platformOf = (calls: Ref.Ref<number>) =>439/** What the stub platform was asked. */440interface Asked {441 readonly asks: number;442 readonly files: number;443 readonly replays: number;444 readonly verdicts: number;445}446447const nothingAsked: Asked = { asks: 0, files: 0, replays: 0, verdicts: 0 };448449const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>450 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));451452/** Events in datekit: tamsin claimed the ask, and another ask was claimed too. */453const replay = [454 claimedEvent(1, "tamsin"),455 claimedEvent(2, "okafor", AskId.make("format-week")),456];457458/**459 * A platform that knows datekit's ask (`shown`, under its id) and the460 * family parent, its events, no verdict yet, and the check's file when461 * `readable`.462 */463const platformOf = (464 asked: Ref.Ref<Asked>,465 {466 readable = true,467 shown = ask,468 }: { readonly readable?: boolean; readonly shown?: Ask } = {}469) =>470 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(471 Layer.provide([472 Layer.mergeAll(473 unanswered,474 Contracts.toLayerHandler("showAsk", (payload) =>475 Effect.gen(function* () {236 yield* Ref.update(calls, (count) => count + 1);476 yield* count(asked, "asks");477478 if (payload.ask === family.parent.id) {479 return { ask: family.parent, brief };480 }481482 if (payload.ask !== askId) {483 return yield* new UnknownAsk({ ask: payload.ask });484 }485242 return { ask, brief };486 return { ask: shown, brief };487 })488 ),489 Contracts.toLayerHandler("verdict", () =>490 Effect.as(count(asked, "verdicts"), {})491 ),492 Contracts.toLayerHandler("watch", () =>493 Stream.fromEffect(count(asked, "replays")).pipe(494 Stream.flatMap(() => Stream.fromIterable(replay))495 )496 ),497 Contracts.toLayerHandler("readFile", (payload) =>498 Effect.gen(function* () {499 yield* count(asked, "files");500501 if (!readable) {502 return yield* new UnknownPath({503 commit: CommitSha.make("a".repeat(40)),504 path: payload.path,505 });506 }507508 return {509 at: CommitSha.make("a".repeat(40)),510 binary: false,511 path: payload.path,512 sha: BlobSha.make("f".repeat(40)),513 size: 42,514 text: 'test("parses", () => {});',515 truncated: false,516 };517 })518 )519 ),520 asTester,521 ])522 );523524describe(readAsk, () => {251 it.effect("reads the ask and its brief for the page", () =>252 Effect.gen(function* () {253 const calls = yield* Ref.make(0);525 it.effect(526 "reads the ask, its brief, its events and its check's source for the page",527 () =>528 Effect.gen(function* () {529 const asked = yield* Ref.make(nothingAsked);530255 const read = yield* readAsk({ ask: askId, project }).pipe(256 Effect.provide(platformOf(calls))257 );531 const read = yield* readAsk({ ask: askId, project }).pipe(532 Effect.provide(platformOf(asked))533 );534259 expect([read.ask.id, read.brief]).toStrictEqual([askId, brief]);260 expect(yield* Ref.get(calls)).toBe(1);261 })535 expect({536 ask: read.ask.id,537 brief: read.brief,538 check: read.check?.text,539 events: read.events.map(({ seq }) => seq),540 lastSeq: read.lastSeq,541 parent: read.parent,542 }).toStrictEqual({543 ask: askId,544 brief,545 check: 'test("parses", () => {});',546 events: [1],547 lastSeq: 2,548 parent: undefined,549 });550 expect(yield* Ref.get(asked)).toStrictEqual({551 asks: 1,552 files: 1,553 replays: 1,554 verdicts: 1,555 });556 })557 );558559 it.effect(560 "reads a family member's parent, and shows the ask without its check's source when the file cannot be read",561 () =>562 Effect.gen(function* () {563 const asked = yield* Ref.make(nothingAsked);564565 const read = yield* readAsk({ ask: askId, project }).pipe(566 Effect.provide(567 platformOf(asked, {568 readable: false,569 shown: { ...family.child(0), check: ask.check, id: askId },570 })571 )572 );573574 expect(read.parent?.id).toBe(family.parent.id);575 expect(read.check).toBeUndefined();576 expect((yield* Ref.get(asked)).asks).toBe(2);577 })578 );579580 it.effect(581 "is a not-found carrying the UnknownAsk refusal for an ask the project lacks",582 () =>583 Effect.gen(function* () {268 const calls = yield* Ref.make(0);584 const asked = yield* Ref.make(nothingAsked);585 const missing = AskId.make("no-such-ask");586587 const failed = yield* Effect.flip(588 readAsk({ ask: missing, project }).pipe(273 Effect.provide(platformOf(calls))589 Effect.provide(platformOf(asked))590 )591 );592593 expect(isNotFound(failed)).toBeTruthy();
11 unmodified lines
605 it.effect(606 "is a not-found with no refusal, and asks nothing, for a name no ask can have",607 () =>608 Effect.gen(function* () {293 const calls = yield* Ref.make(0);609 const asked = yield* Ref.make(nothingAsked);610611 const failed = yield* Effect.flip(612 readAsk({ ask: "Not_An-Ask", project }).pipe(297 Effect.provide(platformOf(calls))613 Effect.provide(platformOf(asked))614 )615 );616617 expect(isNotFound(failed)).toBeTruthy();618 expect(619 isNotFound(failed) ? failed.data : "not a not-found"620 ).toBeUndefined();305 expect(yield* Ref.get(calls)).toBe(0);621 expect(yield* Ref.get(asked)).toStrictEqual(nothingAsked);622 })623 );624});