Skip to content
Myr

Merge build/1223-ask-and-answer

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

authored by oscabriel · committed by oscabriel · parents e817d6c, 613d347 · Browse files · 11 files+2844 added−777 removed
This commit

State

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

Diff stats

11 files+2844 added−777 removed

  • tests:+938 added−157 removed
  • other:+1906 added−620 removed

11 files+2844 added−777 removed

modified:apps/web/src/features/answer/answer-page.tsx+626 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 checking = false,181 lanes,182 project,183}: {184 readonly lanes: readonly LaneResult[];185 readonly project: Ask["project"];186 /** The gate is still at work on the answer: its lanes may yet run. */187 readonly checking?: boolean;188}) => {189 if (lanes.length === 0) {88 return <EmptyState title="No lane ran on this answer." />;190 return (191 <EmptyState192 title={193 checking ? "No lane has run yet." : "No lane ran on this answer."194 }195 />196 );197 }19891 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];199 const open = lanes.filter(({ result }) => result !== "passed");200 const passed = lanes.filter(({ result }) => result === "passed");201104 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>202 return (203 <div className="flex min-w-0 flex-col">204 {open.length === 0 ? null : (205 <ul206 aria-label="Lanes that did not pass"207 className="border-rule border-t"208 >209 {open.map((lane) => (210 <LaneRow key={lane.lane} lane={lane} project={project} />211 ))}212 </ul>213 )}214 {passed.length === 0 ? null : (215 <details216 className={`group border-rule border-b ${open.length === 0 ? "border-t" : ""}`}217 >218 <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">219 <StateMarkIcon mark="passed" />220 <span className="min-w-0 flex-1">{passedLine(passed)}</span>221 <ChevronDown222 aria-hidden="true"223 className="text-muted-foreground size-4 shrink-0 transition-transform duration-150 group-open:rotate-180"224 strokeWidth={1.75}225 />226 </summary>227 <ul aria-label="Lanes that passed" className="border-rule border-t">228 {passed.map((lane) => (229 <LaneRow key={lane.lane} lane={lane} project={project} />230 ))}231 </ul>232 </details>233 )}234 </div>235 );236};237238/** Held-back checks: one line per area, as the landing's trailer spells it, and nothing else. */
3 unmodified lines
242 readonly results: readonly HeldBackResult[];243}) => (244 <ul245 aria-label="Held-back checks by area"144 className="text-sealed flex flex-col gap-1 font-mono text-[0.8125rem] leading-6"246 className="text-sealed text-mono leading-terminal flex flex-col gap-1 font-mono"247 >248 {areas.map(({ area, passed, suite, total }) => (249 <li250 className="flex items-start gap-2 [overflow-wrap:anywhere]"251 data-area={area}252 key={area}253 >152 <LockKeyhole aria-hidden="true" className="mt-1 size-3.5 shrink-0" />254 <LockKeyhole255 aria-hidden="true"256 className="mt-1 size-3.5 shrink-0"257 strokeWidth={1.75}258 />259 <span className="min-w-0">260 {area} {passed}/{total} @ {suite}261 </span>262 </li>263 ))}264 </ul>265);266161const short = (sha: string) => sha.slice(0, 7);162267/** A git id, short as git prints it, whole on hover. */268const Sha = ({ sha }: { readonly sha: string }) => (165 <code className={CODE} title={sha}>166 {short(sha)}269 <code className="text-mono font-mono" title={sha}>270 {shortSha(sha)}271 </code>272);273170export const AnswerView = ({171 landing,274/** Content the inspector shows, left out of the facts drawn inline in main below the shell's width. */275export const InspectorOnly = ({276 children,277}: {278 readonly children: ReactNode;279}) => (280 <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">281 {children}282 </div>283);284285/** What the hero says before any answer was judged: who holds the ask, or how to take it. */286const NoAnswerYet = ({287 ask,288 now,289 states,290}: {291 readonly ask: Ask;292 readonly now: DateTime.Utc;293 readonly states: ReadonlyMap<AskId, AskProgress>;294}) => {295 const progress = states.get(ask.id);296297 const toAsk = (298 <AppLink299 className="decoration-rule underline hover:decoration-current"300 to={askPath(ask.project, ask.id)}301 >302 The ask303 </AppLink>304 );305306 const claimant = progress?.claimant;307 const pushed = progress?.lastPush;308309 if (claimant !== undefined || ask.state === "claimed") {310 const holder =311 claimant === undefined ? "Claimed" : `Claimed by ${claimant}`;312313 return (314 <EmptyState315 onward={toAsk}316 title={317 pushed === undefined318 ? `${holder}, no answer pushed yet.`319 : `${holder}; the answer pushed ${distanceInWords(pushed.at, now)} waits for the gate.`320 }321 />322 );323 }324325 // What it waits on must land before anyone can claim it.326 const waiting = ask.blockedBy.filter(327 (blocker) => states.get(blocker)?.landed === undefined328 ).length;329330 if (ask.state === "open" && waiting > 0) {331 return (332 <EmptyState333 onward={toAsk}334 title={`Nobody has answered this ask yet; it waits for ${waiting} ${335 waiting === 1 ? "ask" : "asks"336 } to land first.`}337 />338 );339 }340341 if (ask.state === "open") {342 return (343 <EmptyState344 command={`${Brand.cli} claim ${ask.id} --project ${ask.project}`}345 title="Nobody has answered this ask yet."346 />347 );348 }349350 return (351 <EmptyState352 onward={toAsk}353 title="No answer to this ask has been checked yet."354 />355 );356};357358/**359 * The outcome, a step up: settled in when it changes while the page is360 * open (never on the first paint), and stamped once on a live landing.361 */362const Hero = ({363 ask,364 now,365 stamp,366 states,367 verdict,368}: {175 readonly landing?: LandingView;369 readonly ask: Ask;370 readonly now: DateTime.Utc;371 readonly stamp: boolean;372 readonly states: ReadonlyMap<AskId, AskProgress>;373 readonly verdict: Verdict | undefined;374}) => {179 if (verdict === undefined) {180 return <EmptyState title="No answer to this ask has been checked yet." />;375 const tag = verdict?.outcome._tag ?? "none";376 // Only an outcome that replaced another while the page was open settles in.377 const [shown, setShown] = useState(tag);378 const [changed, setChanged] = useState(false);379380 if (shown !== tag) {381 setShown(tag);382 setChanged(true);383 }384385 const claimant = states.get(ask.id)?.claimant;386387 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>388 <section aria-label="Outcome" className="flex min-w-0 flex-col gap-3">389 <h2 className="sr-only">Outcome</h2>390 <div391 className={392 changed ? "animate-in fade-in-0 min-w-0 duration-150" : "min-w-0"393 }394 key={tag}395 >396 {verdict === undefined ? (397 <NoAnswerYet ask={ask} now={now} states={states} />398 ) : (399 <OutcomeView400 outcome={verdict.outcome}401 project={ask.project}402 size="title"403 stage={verdict.stage}404 stamp={stamp}405 {...(claimant === undefined ? {} : { claimant })}406 />407 )}408 </div>409 </section>410 );411};412219 <Region id="answer-gate" title="Gate">220 <StageStrip outcome={verdict.outcome} stage={verdict.stage} />221 <OutcomeView outcome={verdict.outcome} />413/** The answer's run: the gate, the lanes, the held-back checks, and the landing. */414const Run = ({415 holds,416 landing,417 now,418 verdict,419}: {420 readonly holds: ReturnType<typeof holdsOf>;421 readonly landing: LandingView | undefined;422 readonly now: DateTime.Utc;423 readonly verdict: Verdict;424}) => (425 <>426 <Region id="answer-gate" title="Gate">427 <StageStrip428 holds={holds}429 outcome={verdict.outcome}430 stage={verdict.stage}431 />432 <p className="text-ui text-muted-foreground">433 Checked on the tree it would land as: <Sha sha={verdict.head} /> merged434 onto main at{" "}435 <AppLink436 className="decoration-rule underline hover:decoration-current"437 to={commitHref(verdict.project, verdict.base)}438 >439 <Sha sha={verdict.base} />440 </AppLink>441 .442 </p>443 </Region>444445 <Region id="answer-lanes" title="Lanes">446 <Lanes447 checking={Outcome.isAnyOf(["Checking"])(verdict.outcome)}448 lanes={verdict.lanes}449 project={verdict.project}450 />451 </Region>452453 {verdict.heldBack.length === 0 ? null : (454 <Region id="answer-held-back" title="Held back">455 <p className="text-ui text-muted-foreground max-w-[70ch]">456 Checks the answer could not see: how many passed in each area, and the457 root of the suite the project committed to before the claim.458 </p>459 <HeldBackBits results={verdict.heldBack} />460 </Region>461 )}462224 <Region id="answer-lanes" title="Lanes">225 <LaneTable lanes={verdict.lanes} />463 {landing === undefined ? null : (464 <Region id="answer-landing" title="Landing">465 <CreditTrailers466 assisted={landing.assisted}467 credits={landing.credits}468 {...(landing.heldBackTrailer === undefined469 ? {}470 : { heldBack: landing.heldBackTrailer })}471 />472 <AppLink473 className="text-ui decoration-rule self-start font-medium underline hover:decoration-current"474 to={commitHref(landing.project, landing.sha)}475 >476 The landing commit477 </AppLink>478 <div className="flex min-w-0 flex-col gap-1.5">479 <span className="text-label text-muted-foreground">480 In a clone of {landing.project}481 </span>482 <CommandLine command={`git show ${landing.sha}`} />483 </div>484 </Region>485 )}486228 {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>487 {/* Below the shell's width the inspector's facts sit above the run, so488 the plumbing comes here, last. */}489 <div className="shell:hidden">490 <ProvenanceFacts entries={verdictProvenance(verdict, now)} />491 </div>492 </>493);494495export interface AnswerViewProps {496 /** The ask the answer is to: its want titles the page. */497 readonly ask: Ask;498 /** The verdict on the answer; none before one was judged. */499 readonly verdict: Verdict | undefined;500 /** The landing it made, once it landed. */501 readonly landing?: LandingView | undefined;502 readonly now: DateTime.Utc;503 /** Where each ask stands, from the project's events (`askStates`). */504 readonly states?: ReadonlyMap<AskId, AskProgress>;505 /** The family's parent, when the ask is a member of one. */506 readonly parent?: Ask | undefined;507 /** The head the address names, when it names an earlier answer. */508 readonly head?: CommitSha | undefined;509 /** It landed while the page was open: stamp the landing's mark, once. */510 readonly stamp?: boolean;511 /** Who is reading, to tell the claimant the claim is theirs. */512 readonly viewer?: Handle | undefined;513}514515const NONE: ReadonlyMap<AskId, AskProgress> = new Map();516517/** The answer's facts: its state, rounds, claim, family, territory and check, then what was judged. */518const AnswerFacts = ({519 ask,520 now,521 parent,522 progress,523 states,524 subject,525 verdict,526 viewer,527}: {528 readonly ask: Ask;529 readonly now: DateTime.Utc;530 readonly parent: Ask | undefined;531 readonly progress: AskProgress | undefined;532 readonly states: ReadonlyMap<AskId, AskProgress>;533 readonly subject: StatusSubject | undefined;534 readonly verdict: Verdict | undefined;535 readonly viewer: Handle | undefined;536}) => {537 const family = familyHead(ask, parent);538 const finale = family === undefined ? undefined : deleteChildOf(family);539540 const landed =541 verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome);542543 return (544 <>545 {subject === undefined ? null : (546 <InspectorOnly>547 <StateFacts subject={subject} />548 </InspectorOnly>549 )}550 <RoundsFacts551 ask={ask.id}552 now={now}553 project={ask.project}554 rounds={roundsAsTheyStand(progress, verdict)}555 {...(verdict === undefined ? {} : { current: verdict.head })}556 />557 {landed ? null : (558 <ClaimFacts559 now={now}560 {...(progress?.claimant === undefined561 ? {}562 : { claimant: progress.claimant })}563 {...(progress?.lastPush === undefined564 ? {}565 : { lastPush: progress.lastPush })}566 {...(viewer === undefined ? {} : { viewer })}567 />568 )}569 {family === undefined ? null : (570 <FamilyFacts571 current={ask.id}572 parent={family}573 project={ask.project}574 states={states}575 {...(finale === undefined ? {} : { finale })}576 />577 )}578 <TerritoryFacts ask={ask} />579 {verdict === undefined ? null : (580 <InspectorOnly>581 <ProvenanceFacts entries={verdictProvenance(verdict, now)} />582 </InspectorOnly>583 )}584 </>585 );586};587238 {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}`} />588/** The line under the hero's title: the ask, the round, when it was judged, and the way to the latest answer. */589const AnswerMeta = ({590 ask,591 head,592 now,593 rounds,594 verdict,595}: {596 readonly ask: Ask;597 readonly head: CommitSha | undefined;598 readonly now: DateTime.Utc;599 readonly rounds: AskProgress["rounds"];600 readonly verdict: Verdict | undefined;601}) => {602 const round =603 verdict === undefined ? undefined : roundOf(rounds, verdict.head);604605 return (606 <MetaLine607 parts={[608 <MetaCode key="ask">{ask.id}</MetaCode>,609 round === undefined610 ? undefined611 : `round ${round.number} of ${round.of}`,612 verdict === undefined ? undefined : (613 <span key="judged">614 judged <When at={verdict.at} now={now} />615 </span>616 ),617 head === undefined ? undefined : (618 <span key="earlier">619 an earlier answer;{" "}620 <AppLink621 className="decoration-rule underline hover:decoration-current"622 to={answerPath(ask.project, ask.id)}623 >624 the latest625 </AppLink>626 </span>627 ),628 ]}629 />630 );631};632633export const AnswerView = ({634 ask,635 head,636 landing,637 now,638 parent,639 stamp = false,640 states = NONE,641 verdict,642 viewer,643}: AnswerViewProps) => {644 const progress = states.get(ask.id);645646 const subject: StatusSubject | undefined =647 verdict === undefined648 ? undefined649 : {650 claimant: progress?.claimant,651 kind: "answer",652 outcome: verdict.outcome,653 project: ask.project,654 stage: verdict.stage,655 };656657 return (658 <Workspace659 crumbs={answerCrumbs(ask)}660 facts={661 <AnswerFacts662 ask={ask}663 now={now}664 parent={parent}665 progress={progress}666 states={states}667 subject={subject}668 verdict={verdict}669 viewer={viewer}670 />671 }672 factsHeading="This answer"673 state={674 <StatusLine675 compact676 subject={677 subject ?? {678 ask,679 claimant: progress?.claimant,680 kind: "ask",681 takeable: ask.state === "open",682 }683 }684 />685 }686 status={687 // The answer's head reads title, then which answer this is, then688 // the outcome: a refusal drawn whole would bury a line after it.689 <div className="flex min-w-0 flex-col gap-4">690 <div className="text-ui text-muted-foreground">691 <AnswerMeta692 ask={ask}693 head={head}694 now={now}695 rounds={progress?.rounds ?? []}696 verdict={verdict}697 />698 </div>259 </Region>699 <Hero700 ask={ask}701 now={now}702 stamp={703 stamp &&704 verdict !== undefined &&705 Outcome.isAnyOf(["Landed"])(verdict.outcome)706 }707 states={states}708 verdict={verdict}709 />710 </div>711 }712 title={ask.brief.want}713 >714 {verdict === undefined ? null : (715 <Run716 holds={holdsOf(verdict, landing, progress?.rounds ?? [])}717 landing={landing}718 now={now}719 verdict={verdict}720 />721 )}261 </>722 </Workspace>723 );724};
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+596 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>158 );159 }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 });267161 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;268 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 />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);323324/**325 * What a family's parent waits on, in the fan's terms: how many of its326 * children have yet to land, then the delete step; never a list of ids327 * (the fan draws each child).328 */329const FamilyWaits = ({330 finale,331 parent,332 project,333 states,334}: {335 readonly finale: AskId;336 readonly parent: Ask;337 readonly project: ProjectName;338 readonly states: ReadonlyMap<AskId, AskProgress>;339}) => {340 const children = parent.blockedBy.filter((child) => child !== finale);341342 const left = children.filter(343 (child) => states.get(child)?.landed === undefined344 ).length;345346 const deleteStep = (347 <AppLink className={LINK} to={askPath(project, finale)}>348 the delete step349 </AppLink>350 );351352 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>353 <p className="text-ui mt-2 flex items-start gap-2" data-state="waiting">354 <Hourglass355 aria-hidden="true"356 className="text-waiting mt-0.5 size-4 shrink-0"357 strokeWidth={1.75}358 />359 <span className="min-w-0">360 Waits for{" "}361 {left === 0 ? null : (362 <>363 {left} of {children.length}{" "}364 {children.length === 1 ? "child" : "children"} and{" "}365 </>366 )}367 {deleteStep} to land first; a claim waits until they do.368 </span>369 </p>370 );371};372187export const AskView = ({373export interface AskViewProps {374 readonly ask: Ask;375 /** The brief as the platform renders it for an agent, in Markdown. */376 readonly brief: string;377 readonly now: DateTime.Utc;378 /** Where the project is cloned from. */379 readonly platformUrl: string;380 /** Where each ask stands, from the project's events (`askStates`). */381 readonly states?: ReadonlyMap<AskId, AskProgress>;382 /** The family's parent, when the ask is a member of one. */383 readonly parent?: Ask | undefined;384 /** The verdict on its latest answer, to say at which stage a refusal came. */385 readonly verdict?: Verdict | undefined;386 /** The check's source, when it is a file the page could read. */387 readonly check?: CheckSource | undefined;388 /** The project's posture, once the list of projects has it. */389 readonly posture?: Posture | undefined;390 /** Who is reading, to tell the claimant the claim is theirs. */391 readonly viewer?: Handle | undefined;392}393394/** Where the ask stands, as its status line reads it. */395const subjectOf = (396 ask: Ask,397 states: ReadonlyMap<AskId, AskProgress>,398 verdict: Verdict | undefined,399 takeable: boolean400): StatusSubject => {401 const progress = states.get(ask.id);402 const claimant = progress?.claimant;403 const latest = progress?.latest;404405 if (progress?.landed !== undefined) {406 return {407 kind: "answer",408 outcome: Outcome.cases.Landed.make({ sha: progress.landed.sha }),409 project: ask.project,410 };411 }412413 // A refusal says at which stage it came, which only the verdict holds.414 const lastRound = progress?.rounds.at(-1);415416 if (417 latest !== undefined &&418 Outcome.isAnyOf(["Refused"])(latest) &&419 verdict !== undefined &&420 verdict.head === lastRound?.head421 ) {422 return {423 claimant,424 kind: "answer",425 outcome: latest,426 project: ask.project,427 stage: verdict.stage,428 };429 }430431 return {432 blockers:433 ask.parent !== undefined && ask.blockedBy.length > 0434 ? familyMarks(ask, states)435 : undefined,436 claimant,437 kind: "ask",438 latest,439 ask,440 takeable,441 };442};443444/** Where an ask stands for its page: what it still waits on, whether it can be taken, and its family. */445const standing = (446 ask: Ask,447 states: ReadonlyMap<AskId, AskProgress>,448 parent: Ask | undefined449) => {450 const progress = states.get(ask.id);451452 const remaining = ask.blockedBy.filter(453 (blocker) => states.get(blocker)?.landed === undefined454 );455456 const family = familyHead(ask, parent);457 const latest = progress?.latest;458459 return {460 family,461 finale: family === undefined ? undefined : deleteChildOf(family),462 held: progress?.claimant !== undefined || ask.state === "claimed",463 progress,464 remaining,465 takeable: ask.state === "open" && remaining.length === 0,466 // A family member says what it waits on in the family's terms, and a467 // wait the latest outcome already names needs no second line.468 waitsOn:469 ask.parent === undefined &&470 remaining.length > 0 &&471 !(latest !== undefined && Outcome.isAnyOf(["WaitingOnParent"])(latest)),472 };473};474475/** The ask's facts: its state, how to take it or who holds it, its territory and check, its family, its project's posture. */476const AskFacts = ({477 ask,189 brief,478 now,479 parent,480 platformUrl,481 posture,482 states,483 subject,484 viewer,485}: {486 readonly ask: Ask;194 readonly brief: string;487 readonly now: DateTime.Utc;488 readonly parent: Ask | undefined;489 readonly platformUrl: string;490 readonly posture: Posture | undefined;491 readonly states: ReadonlyMap<AskId, AskProgress>;492 readonly subject: StatusSubject;493 readonly viewer: Handle | undefined;494}) => {198 const { context, current, outOfScope, terms } = ask.brief;495 const { family, finale, held, progress, takeable } = standing(496 ask,497 states,498 parent499 );500501 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>502 <>503 <InspectorOnly>504 <StateFacts subject={subject} />505 </InspectorOnly>506 {takeable ? <TakeItFacts ask={ask} platformUrl={platformUrl} /> : null}507 {!takeable && held && ask.state !== "closed" ? (508 <ClaimFacts509 now={now}510 {...(progress?.claimant === undefined511 ? {}512 : { claimant: progress.claimant })}513 {...(progress?.lastPush === undefined514 ? {}515 : { lastPush: progress.lastPush })}516 {...(viewer === undefined ? {} : { viewer })}517 />518 ) : null}519 <TerritoryFacts ask={ask} />520 {family === undefined ? null : (521 <InspectorOnly>522 <FamilyFacts523 current={ask.id}524 parent={family}525 project={ask.project}526 states={states}527 {...(finale === undefined ? {} : { finale })}528 />529 </InspectorOnly>530 )}531 {posture === undefined ? null : (532 <PostureFacts533 label={postureLabel(posture)}534 posture={posture}535 project={ask.project}536 />537 )}538 </>539 );540};541542/** The line under the title: the kind, who asked (and mentors), and when it opened. */543const AskMeta = ({544 ask,545 now,546}: {547 readonly ask: Ask;548 readonly now: DateTime.Utc;549}) => (550 <MetaLine551 parts={[552 ask.kind,553 <span key="asked">554 asked by <HandleLink handle={ask.askedBy} />555 {ask.mentor === undefined ? null : (556 <>557 , mentored by <HandleLink handle={ask.mentor} />558 </>559 )}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>560 </span>,561 <span key="opened">562 opened <When at={ask.openedAt} now={now} />563 </span>,564 ]}565 />566);567253 {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>568/** The Markdown an agent reads, shown whole on demand, and its own address. */569const ForAgents = ({570 ask,571 brief,572}: {573 readonly ask: Ask;574 readonly brief: string;575}) => (576 <section aria-label="For agents" className="flex min-w-0 flex-col gap-3">577 <details className="group border-rule border-y">578 <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">579 <span className="min-w-0 flex-1">The brief, as an agent reads it</span>580 <ChevronDown581 aria-hidden="true"582 className="text-muted-foreground size-4 shrink-0 transition-transform duration-150 group-open:rotate-180"583 strokeWidth={1.75}584 />585 </summary>586 <pre className="border-rule bg-surface text-mono leading-terminal mb-3 overflow-x-auto border p-3 font-mono whitespace-pre-wrap">587 {brief}588 </pre>589 </details>590 <p className="text-ui text-muted-foreground">591 {/* A server route, not one of the router's pages. */}592 <a593 className={`text-foreground ${LINK}`}594 href={markdownPath(ask.project, ask.id)}595 type="text/markdown"596 >597 This ask as Markdown598 </a>599 , for an agent to fetch.600 </p>601 </section>602);603604export const AskView = ({605 ask,606 brief,607 check,608 now,609 parent,610 platformUrl,611 posture,612 states = NONE,613 verdict,614 viewer,615}: AskViewProps) => {616 const { family, finale, progress, remaining, takeable, waitsOn } = standing(617 ask,618 states,619 parent620 );621622 const subject = subjectOf(ask, states, verdict, takeable);623624 return (625 <Workspace626 crumbs={askCrumbs(ask)}627 facts={628 <AskFacts629 ask={ask}630 now={now}631 parent={parent}632 platformUrl={platformUrl}633 posture={posture}634 states={states}635 subject={subject}636 viewer={viewer}637 />638 }639 factsHeading="This ask"640 meta={<AskMeta ask={ask} now={now} />}641 state={<StatusLine compact subject={subject} />}642 status={643 <>644 <StatusLine subject={subject} />645 {waitsOn && family === ask && finale !== undefined ? (646 <FamilyWaits647 finale={finale}648 parent={ask}649 project={ask.project}650 states={states}651 />652 ) : null}653 {waitsOn && family !== ask ? (654 <WaitsOn asks={remaining} project={ask.project} />655 ) : null}656 {family === undefined ? null : (657 // Below the shell's width the family sits under the head, as a fan.658 <div className="shell:hidden mt-4">659 <FamilyStrip660 expanded={false}661 parent={family}662 project={ask.project}663 stamps={new Set()}664 states={states}665 {...(finale === undefined ? {} : { finale })}666 />667 </div>668 )}669 </>670 }671 title={ask.brief.want}672 {...(takeable ? { primaryCommand: claimCommand(ask) } : {})}673 >674 <Brief ask={ask} />675676 <Region id="ask-check" title="The check">677 <p className="text-ui max-w-[70ch]">678 <CheckSummary ask={ask} />679 </p>262 )}680 {check === undefined ? null : <CheckFile source={check} />}681 </Region>682264 <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>683 <Answers684 ask={ask}685 now={now}686 rounds={roundsAsTheyStand(progress, verdict)}687 />688298 <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>689 <ForAgents ask={ask} brief={brief} />690 </Workspace>691 );692};
modified:apps/web/src/features/ask/refused.tsx+64 added-14 removed
modified:apps/web/src/features/shared/outcome.tsx+8 added-3 removed
199 unmodified lines
200 data-stage={name}201 data-state={state}202 key={name}203 >204 <span className="text-label flex min-w-0 items-center gap-1.5">205 <StateMarkIcon mark={marks[state].mark} size="sm" />204 <span className="text-label flex min-w-0 items-start gap-1.5">205 <StateMarkIcon206 className="mt-px"207 mark={marks[state].mark}208 size="sm"209 />210 {/* Four cells a row on a phone: a long label wraps rather than losing its end. */}211 <span207 className={`truncate ${212 className={`min-w-0 break-words ${213 state === "pending" || state === "skipped"214 ? "text-muted-foreground"215 : "text-foreground"216 }`}
16 unmodified lines
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: "No such 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+384 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("keeps each passed lane's command and how long it ran inside the folded line", () => {241 const folded =242 /<details\b[^>]*>(?<inner>.*)<\/details>/su.exec(243 mainOf(markupOf(refusedPage))244 )?.groups?.inner ?? "";245246 expect(247 inOrder(plainText(folded), ["lint", "bun run lint", "passed", "1.2 s"])248 ).toBeTruthy();249 });250251 it("says no lane has run yet while the answer is checking, and that none ran once it was refused before them", () => {252 const checking = {253 ...verdictOf(Outcome.cases.Checking.make({ stage: "cheap" })),254 lanes: [],255 stage: "cheap" as const,256 };257258 const refusedEarly = { ...refused, lanes: [], stage: "shape" as const };259260 expect(textOf(page({ verdict: checking }))).toContain(261 "No lane has run yet."262 );263 expect(textOf(page({ verdict: checking }))).not.toContain("No lane ran");264 expect(textOf(page({ verdict: refusedEarly }))).toContain(265 "No lane ran on this answer."266 );267 });268269 it("names the ask and the round right under the title, before the outcome", () => {270 const states = askStates([271 claimedEvent(1, "okafor"),272 judgedEvent(2, refused.outcome),273 ]);274275 const markup = mainOf(markupOf(page({ states, verdict: refused })));276 const round = markup.indexOf("round 1 of 1");277278 expect(round).toBeGreaterThan(markup.indexOf("</h1>"));279 expect(round).toBeLessThan(markup.indexOf('aria-label="Outcome"'));280 });281282 it("gives no claim command for an ask that still waits on others to land", () => {283 const blocked = { ...ask, blockedBy: [AskId.make("split-format")] };284 const markup = mainOf(markupOf(page({ ask: blocked, verdict: undefined })));285286 expect(textIn(markup)).not.toContain(`${Brand.cli} claim`);287 expect(textIn(markup)).toContain("waits for 1 ask to land first");288 expect(markup).toContain(`href="/datekit/asks/${askId}"`);289 });290291 it("names a lane's log only as the command that reads it", () => {292 const passing = verdictOf(Outcome.cases.Checking.make({ stage: "checks" }));293 const text = textOf(page({ verdict: passing }));294295 const mentions = [296 ...text.matchAll(/logs\/datekit\/parse-iso-week\/unit/gu),297 ];298299 expect(mentions.length).toBeGreaterThan(0);300301 for (const { index } of mentions) {302 expect(text.slice(index - `${Brand.cli} evidence `.length, index)).toBe(303 `${Brand.cli} evidence `304 );305 }306 });307308 it("shows held-back checks only as an area's counts and its suite root", () => {309 const bits =310 /<ul aria-label="Held-back checks by area"[^>]*>(?<inner>.*?)<\/ul>/su.exec(118 markupOf(page)311 markupOf(refusedPage)312 )?.groups?.inner;313314 expect(plainText(bits ?? "").trim()).toBe(`export 6/7 @ ${suite}`);315 });316317 it("shows the refusals' explain lines in order, as git printed them", () => {318 expect(319 inOrder(127 textOf(page),320 textOf(refusedPage),321 explain([checksFailed, heldBackFailed]).map((line) => line.trim())322 )323 ).toBeTruthy();324 });325133 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" }));326 it("names the answer it judged, its round, and when", () => {327 const states = askStates([328 claimedEvent(1, "okafor"),329 judgedEvent(2, refused.outcome, CommitSha.make("e".repeat(40))),330 judgedEvent(3, refused.outcome),331 ]);332136 expect(textOf(<AnswerView now={now} verdict={passing} />)).not.toContain(137 "logs/datekit"333 const element = page({ states, verdict: refused });334 const text = textOf(element);335336 for (const shown of [337 "round 2 of 2",338 "bbbbbbb",339 "aaaaaaa",340 "redThenGreen@0.0.0+5e1d",341 "20 min ago",342 "okafor's move",343 ]) {344 expect(text).toContain(shown);345 }346 });347348 it("reads a wait on a decision as waiting, in the hero", () => {349 const waiting = verdictOf(350 Outcome.cases.AwaitingDecision.make({351 decision: DecisionId.make("dec-000001"),352 })353 );354355 const text = textOf(page({ verdict: waiting }));356357 expect(text).toContain("Waiting on decision dec-000001");358 });359141 it("names the answer it judged and when", () => {142 const text = textOf(page);360 it("gives an ask nobody answered the command that claims it", () => {361 const text = textOf(page({ verdict: undefined }));362144 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");363 expect(text).toContain("Nobody has answered this ask yet.");364 expect(text).toContain(`${Brand.cli} claim ${askId} --project datekit`);365 expect(markupOf(page({ verdict: undefined }))).not.toContain("data-stage");366 });367150 it("says plainly when no answer has been checked yet", () => {151 const text = textOf(<AnswerView now={now} verdict={undefined} />);368 it("names who holds a claimed ask with no answer pushed, and links back to the ask", () => {369 const states = askStates([claimedEvent(1, "bram")]);370 const element = page({ states, verdict: undefined });371 const main = mainOf(markupOf(element));372153 expect(text).toContain("No answer to this ask has been checked yet");154 expect(text).not.toContain("Parse");373 expect(textIn(main)).toContain("Claimed by bram, no answer pushed yet.");374 expect(main).toContain(`href="/datekit/asks/${askId}"`);375 });376377 it("shows a landed answer's credit trailers in trailer order, its held-back trailer, and its commit", () => {378 const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));159 const element = <AnswerView landing={landing} now={now} verdict={landed} />;160 const text = textOf(element);379 const text = textOf(page({ landing, verdict: landed }));380381 expect(text).toContain("Landed as 9b1c3e5");382 expect(383 inOrder(text, ["Asked-by: ines-v", "Signed-off-by: okafor"])
2 unmodified lines
386 expect(text).toContain("Assisted-by: claude-code:opus-5 (verified)");387 expect(text).toContain(`git show ${landedSha}`);388 });389171 it("links a landed answer's landing and its base to their commit pages, and keeps the git show command", () => {390 it("links a landed answer's landing (from the hero and the landing) and its base to their commit pages", () => {391 const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));392 const markup = markupOf(page({ landing, verdict: landed }));393174 const markup = markupOf(175 <AnswerView landing={landing} now={now} verdict={landed} />176 );177178 expect(commitLinksOf(markup)).toStrictEqual([394 expect(commitLinksOf(heroOf(markup))).toStrictEqual([395 [`/${project}/commit/${landedSha}`, "9b1c3e5"],396 ]);397 expect(commitLinksOf(runOf(markup))).toStrictEqual([398 [`/${project}/commit/${landed.base}`, landed.base.slice(0, 7)],399 [`/${project}/commit/${landedSha}`, "The landing commit"],400 ]);182 expect(markup).toContain(`git show ${landedSha}`);401 });402403 it("links neither the head nor the merged tree: they live in the claim's fork", () => {404 const landed = verdictOf(Outcome.cases.Landed.make({ sha: landedSha }));405 const markup = markupOf(page({ landing, verdict: landed }));406188 const markup = markupOf(189 <AnswerView landing={landing} now={now} verdict={landed} />190 );191407 expect(markup).not.toContain(`/commit/${landed.head}`);408 expect(markup).not.toContain(`/commit/${landed.tree}`);409 });410411 it("links the base and no landing when the answer has not landed", () => {197 expect(commitLinksOf(markupOf(page))).toStrictEqual([412 expect(commitLinksOf(heroOf(markupOf(refusedPage)))).toStrictEqual([]);413 expect(commitLinksOf(runOf(markupOf(refusedPage)))).toStrictEqual([414 [`/${project}/commit/${refused.base}`, refused.base.slice(0, 7)],415 ]);416 });201});417203describe(LaneTable, () => {204 it("gives each lane's command and how long it ran", () => {205 const { lanes } = refused;206 const text = textOf(<LaneTable lanes={lanes} />);418 it("stamps the landed mark only when the page is told the landing came while it was open", () => {419 const landed = landedAt("human", false);420208 expect(inOrder(text, ["lint", "bun run lint", "1.2 s"])).toBeTruthy();209 expect(inOrder(text, ["unit", "bun test", "8.3 s"])).toBeTruthy();421 expect(422 markupOf(page({ landing: plainLanding, stamp: true, verdict: landed }))423 ).toContain("animate-stamp");424 expect(425 markupOf(page({ landing: plainLanding, verdict: landed }))426 ).not.toContain("animate-stamp");427 });428212 it("says when no lane ran", () => {213 expect(textOf(<LaneTable lanes={[]} />)).toContain("No lane ran");429 it("draws a family member's family, the member marked", () => {430 const child = family.child(1);431432 const markup = markupOf(433 <AnswerView434 ask={child}435 now={now}436 parent={family.parent}437 verdict={refused}438 />439 );440441 expect(asideOf(markup)).toContain(`data-family="${family.parent.id}"`);442 expect(asideOf(markup)).toMatch(443 /aria-current="true"[^>]*title="retire-old-week-parse"|title="retire-old-week-parse"[^>]*aria-current="true"/u444 );445 });446});447448describe(HeldBackBits, () => {
8 unmodified lines
457 );458 });459});460461describe(durationText, () => {462 it("says how long a lane ran in the unit a person reads", () => {463 expect([640, 8312, 125_000].map(durationText)).toStrictEqual([464 "640 ms",465 "8.3 s",466 "2 min 5 s",467 ]);468 });469});470230/** What the stub platform was asked: verdicts and landings. */471/** What the stub platform was asked: verdicts, landings, asks and replays. */472interface Asked {473 readonly asks: number;474 readonly landings: number;475 readonly replays: number;476 readonly verdicts: number;477}478479/** Events in datekit: bram claimed the ask and pushed, and another ask was claimed too. */480const replay = [481 claimedEvent(1, "bram"),482 claimedEvent(2, "okafor", AskId.make("format-week")),483 judgedEvent(3, refused.outcome),484];485486const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>487 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));488489/**490 * A platform whose datekit ask's latest answer ended in `outcome`, as the491 * answer page's loader calls it; `landingKnown` says whether it still finds492 * the landing a landed verdict names.493 */494const platformAt = (495 asked: Ref.Ref<Asked>,496 outcome: Outcome,244 landingKnown = true497 landingKnown = true,498 shown: Ask = ask499) =>500 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(501 Layer.provide([502 Layer.mergeAll(503 unanswered,504 Contracts.toLayerHandler("verdict", (payload) =>505 Effect.gen(function* () {252 yield* Ref.update(asked, (seen) => ({253 ...seen,254 verdicts: seen.verdicts + 1,255 }));506 yield* count(asked, "verdicts");507508 if (payload.ask !== askId) {509 return yield* new UnknownAsk({ ask: payload.ask });510 }511512 return { verdict: verdictOf(outcome) };513 })514 ),515 Contracts.toLayerHandler("showAsk", (payload) =>516 Effect.gen(function* () {517 yield* count(asked, "asks");518519 if (payload.ask !== shown.id && payload.ask !== family.parent.id) {520 return yield* new UnknownAsk({ ask: payload.ask });521 }522523 return {524 ask: payload.ask === shown.id ? shown : family.parent,525 brief,526 };527 })528 ),529 Contracts.toLayerHandler("watch", () =>530 Stream.fromEffect(count(asked, "replays")).pipe(531 Stream.flatMap(() => Stream.fromIterable(replay))532 )533 ),534 Contracts.toLayerHandler("landing", (payload) =>535 Effect.gen(function* () {266 yield* Ref.update(asked, (seen) => ({267 ...seen,268 landings: seen.landings + 1,269 }));536 yield* count(asked, "landings");537538 if (!landingKnown || payload.sha !== landedSha) {539 return yield* new UnknownCommit({ sha: payload.sha });540 }
5 unmodified lines
546 asTester,547 ])548 );549283const nothingAsked: Asked = { landings: 0, verdicts: 0 };550const nothingAsked: Asked = { asks: 0, landings: 0, replays: 0, verdicts: 0 };551552describe(readAnswer, () => {286 it.effect("reads a landed answer's landing with its verdict", () =>553 it.effect(554 "reads a landed answer's landing with its verdict, its ask and the ask's events",555 () =>556 Effect.gen(function* () {557 const asked = yield* Ref.make(nothingAsked);558 const landed = Outcome.cases.Landed.make({ sha: landedSha });559560 const read = yield* readAnswer({ ask: askId, project }).pipe(561 Effect.provide(platformAt(asked, landed))562 );563564 expect({565 events: read.events.map(({ seq }) => seq),566 landing: read.landing?.sha,567 lastSeq: read.lastSeq,568 outcome: read.verdict?.outcome._tag,569 parent: read.parent,570 want: read.askRead.brief.want,571 }).toStrictEqual({572 events: [1, 3],573 landing: landedSha,574 lastSeq: 3,575 outcome: "Landed",576 parent: undefined,577 want: ask.brief.want,578 });579 expect(yield* Ref.get(asked)).toStrictEqual({580 asks: 1,581 landings: 1,582 replays: 1,583 verdicts: 1,584 });585 })586 );587588 it.effect("reads a family member's parent, for the family", () =>589 Effect.gen(function* () {590 const asked = yield* Ref.make(nothingAsked);289 const landed = Outcome.cases.Landed.make({ sha: landedSha });591592 const read = yield* readAnswer({ ask: askId, project }).pipe(292 Effect.provide(platformAt(asked, landed))593 Effect.provide(594 platformAt(asked, refused.outcome, true, {595 ...family.child(0),596 id: askId,597 })598 )599 );600295 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 });601 expect(read.parent?.id).toBe(family.parent.id);602 expect(yield* Ref.get(asked)).toStrictEqual({603 asks: 2,604 landings: 0,605 replays: 1,606 verdicts: 1,607 });608 })609 );610611 it.effect("asks for no landing when the answer did not land", () =>
5 unmodified lines
617 );618619 expect(read.verdict?.outcome._tag).toBe("Refused");620 expect(read.landing).toBeUndefined();311 expect(yield* Ref.get(asked)).toStrictEqual({ landings: 0, verdicts: 1 });621 expect((yield* Ref.get(asked)).landings).toBe(0);622 })623 );314624 it.effect(625 "shows the verdict alone when the platform no longer finds its landing",626 () =>627 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+453 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 ProjectName,18 RepoPath,19} from "@repo/protocol/ids";20import {21 OutOfScope,22 UnknownAsk,23 UnknownPath,24 UnknownProject,25} from "@repo/protocol/refusal";26import { explain } from "@repo/protocol/render";27import { asTester, unanswered } from "@repo/protocol/testing";28import { isNotFound } from "@tanstack/react-router";16import { Effect, Layer, Ref, Schema } from "effect";29import { Effect, Layer, Ref, Schema, Stream } from "effect";30import { RpcTest } from "effect/rpc";3132import { readAsk } from "../src/features/answer/reads.ts";33import { AskView } from "../src/features/ask/ask-page.tsx";34import { NoSuchAsk } from "../src/features/ask/refused.tsx";35import { askStates } from "../src/features/shared/ask-progress.ts";36import { Refusals } from "../src/features/shared/refusals.ts";22import { readAsk } from "../src/routes/$project/asks/$ask.tsx";37import {38 ask,39 askId,40 brief,41 claimedEvent,42 closedEvent,43 family,44 inOrder,45 judgedEvent,46 landedSha,47 markupOf,48 now,49 plainText,50 project,51 textOf,52 verdictOf,53} from "./ask-fixtures.ts";54import { textIn } from "./markup.ts";5556const platformUrl = "https://platform-test.example.workers.dev";5758/** The markup inside the first `<pre>`. */59const inPre = (markup: string) =>60 /<pre\b[^>]*>(?<inner>.*?)<\/pre>/su.exec(markup)?.groups?.inner;6140const page = (shown = ask) => (41 <AskView ask={shown} brief={brief} now={now} platformUrl={platformUrl} />62/** The page's main pane, without the inspector. */63const mainOf = (markup: string) =>64 /<main\b[^>]*>(?<inner>.*)<\/main>/su.exec(markup)?.groups?.inner ?? "";6566/** The inspector. */67const asideOf = (markup: string) =>68 /<aside\b[^>]*>(?<inner>.*)<\/aside>/su.exec(markup)?.groups?.inner ?? "";6970/** The context bar's trail. */71const trailOf = (markup: string) =>72 /<nav aria-label="Breadcrumb"[^>]*>(?<inner>.*?)<\/nav>/su.exec(markup)73 ?.groups?.inner ?? "";7475type AskProps = Parameters<typeof AskView>[0];7677const page = (shown = ask, more: Partial<AskProps> = {}) => (78 <AskView79 ask={shown}80 brief={brief}81 now={now}82 platformUrl={platformUrl}83 {...more}84 />85);8687/** The check's source, as the platform reads it. */88const checkSource = (lines: number) => ({89 path: RepoPath.make("test/parse-week.test.ts"),90 sha: "f".repeat(40),91 text: Array.from(92 { length: lines },93 (_, index) => `expect(parseWeek("2026-W41-${index}")).not.toBeNull();`94 ).join("\n"),95});9697describe(AskView, () => {98 it("titles the page with the want, then reads the brief's sections in order", () => {99 const markup = markupOf(page());100
13 unmodified lines
114 ])115 ).toBeTruthy();116 });117118 it("sets a want of 80 characters at the headline, and a longer one a step down, whole", () => {119 const want =120 "The linter reports a heading that skips a level, such as a level-two heading followed by a level-four one.";121122 const long = markupOf(page({ ...ask, brief: { ...ask.brief, want } }));123124 expect(125 /<h1\b[^>]*class="(?<classes>[^"]*)"/u.exec(long)?.groups?.classes126 ).toContain("text-title");127 expect(long).toContain(`>${want}</h1>`);128 expect(129 /<h1\b[^>]*class="(?<classes>[^"]*)"/u.exec(markupOf(page()))?.groups130 ?.classes131 ).toContain("text-headline");132 });133134 it("leaves out a section the brief does not have", () => {135 const text = textOf(136 page({ ...ask, brief: { want: "Parse ISO week dates like 2026-W41-3" } })137 );
2 unmodified lines
140 expect(text).not.toContain("Out of scope");141 expect(text).not.toContain("Terms");142 });14375 it("gives the ask's name, kind, state and check", () => {144 it("names the project, its asks and the ask in the context bar's trail", () => {145 const trail = trailOf(markupOf(page()));146147 expect(inOrder(plainText(trail), ["datekit", "Asks", askId])).toBeTruthy();148 expect(trail).toContain('href="/datekit"');149 });150151 it("says an open ask is open to take, who it is held for, and gives its kind, asker and age", () => {152 const held = {153 ...ask,154 mentor: Handle.make("okonkwo"),155 reserve: "newcomers" as const,156 };157158 const text = textOf(page(held));159160 expect(text).toContain("Open to take");161 expect(text).toContain("Held for newcomers, mentored by okonkwo");162 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 ])163 inOrder(text, ["fix", "asked by", "ines-v", "opened 2 d ago"])164 ).toBeTruthy();165 expect(markupOf(page(held))).toContain('href="/people/okonkwo"');166 expect(markupOf(page())).toContain('href="/people/ines-v"');167 });16890 it("gives the ask's territory, and who asked it when", () => {169 it("gives the ask's territory and its check", () => {170 const text = textOf(page());171172 expect(94 inOrder(text, ["Asked by", "ines-v", "opened 2 d ago"])173 inOrder(text, [174 "Territory and check",175 "@datekit/parse",176 "test/parse-week.test.ts",177 ])178 ).toBeTruthy();179 expect(markupOf(page())).toContain(180 'href="/datekit/blob/main/test/parse-week.test.ts"'181 );182 });183184 it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {185 expect(97 inOrder(text, ["Territory", "@datekit/parse", "packages/parse/**"])186 inOrder(textOf(page()), [187 `git clone ${platformUrl}/datekit.git`,188 `${Brand.cli} claim ${askId} --project datekit`,189 `${Brand.cli} check`,190 ])191 ).toBeTruthy();99 expect(markupOf(page())).toContain('href="/people/ines-v"');192 });193102 // 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 })194 it("names who holds a claimed ask and offers no way to take it", () => {195 const states = askStates([claimedEvent(1, "tamsin")]);196197 const text = textIn(198 markupOf(page({ ...ask, state: "claimed" }, { states }))199 );200115 const field = text.slice(116 text.indexOf("Territory"),117 text.indexOf("Check", text.indexOf("Territory"))201 expect(text).toContain("Claimed by tamsin, no answer pushed yet");202 expect(text).toContain("tamsin's move");203 expect(text).not.toContain("Take it");204 expect(text).not.toContain(`${Brand.cli} claim`);205 });206207 it("says where a refused answer was refused, whose move it is and what to run", () => {208 const refusal = new OutOfScope({ paths: [RepoPath.make("README.md")] });209 const outcome = Outcome.cases.Refused.make({ refusals: [refusal] });210211 const states = askStates([212 claimedEvent(1, "tamsin"),213 judgedEvent(2, outcome),214 ]);215216 const text = textOf(217 page(218 { ...ask, state: "claimed" },219 { states, verdict: { ...verdictOf(outcome), stage: "shape" } }220 )221 );222223 expect(121 inOrder(field, ["The paths", "src/parse.ts", "test/parse.test.ts"])224 inOrder(text, [225 "Refused",226 "at Shape",227 "OutOfScope",228 "tamsin's move",229 refusal.next,230 ])231 ).toBeTruthy();123 expect(field).not.toMatch(/\s\.\s|\s\.:/u);232 });233126 it("gives the lines that clone the project, claim the ask and check an answer, with the CLI's own name", () => {234 it("says a landed ask landed, with its commit", () => {235 const states = askStates([236 claimedEvent(1, "tamsin"),237 judgedEvent(2, Outcome.cases.Landed.make({ sha: landedSha })),238 closedEvent(3),239 ]);240241 const markup = markupOf(page({ ...ask, state: "closed" }, { states }));242243 expect(textOf(page({ ...ask, state: "closed" }, { states }))).toContain(244 "Landed as 9b1c3e5"245 );246 expect(markup).toContain(`href="/datekit/commit/${landedSha}"`);247 });248249 it("gives a round the word its landing or verdict has since said, not the one it was judged with", () => {250 const states = askStates([251 claimedEvent(1, "tamsin"),252 judgedEvent(2, Outcome.cases.Checking.make({ stage: "human" })),253 closedEvent(3),254 ]);255256 const answers = plainText(257 mainOf(markupOf(page({ ...ask, state: "closed" }, { states })))258 );259260 expect(inOrder(answers, ["Round 1", "bbbbbbb", "Landed"])).toBeTruthy();261 expect(answers).not.toContain("Checking");262 });263264 it("lists one answer row per judged round, each linking its answer", () => {265 const states = askStates([266 claimedEvent(1, "tamsin"),267 judgedEvent(268 2,269 Outcome.cases.Refused.make({270 refusals: [new OutOfScope({ paths: [RepoPath.make("README.md")] })],271 }),272 CommitSha.make("e".repeat(40))273 ),274 judgedEvent(3, Outcome.cases.Checking.make({ stage: "checks" })),275 ]);276277 const main = mainOf(278 markupOf(page({ ...ask, state: "claimed" }, { states }))279 );280281 const rows = [282 ...main.matchAll(283 /href="\/datekit\/answers\/parse-iso-week\?head=(?<head>[0-9a-f]+)"/gu284 ),285 ].map(({ groups }) => groups?.head);286287 expect(rows).toStrictEqual(["e".repeat(40), "b".repeat(40)]);288 expect(128 inOrder(textOf(page()), [129 `git clone ${platformUrl}/datekit.git`,130 `${Brand.cli} claim ${askId} --project datekit`,131 `${Brand.cli} check --ask ${askId}`,289 inOrder(plainText(main), [290 "Answers",291 "Round 1",292 "eeeeeee",293 "Refused",294 "Round 2",295 "bbbbbbb",296 "Checking",297 ])298 ).toBeTruthy();299 });300301 it("shows the check's source inline when it was read, its first 30 lines until asked for the whole", () => {302 const markup = mainOf(markupOf(page(ask, { check: checkSource(45) })));303 const text = plainText(markup);304305 expect(text).toContain('expect(parseWeek("2026-W41-29")).not.toBeNull();');306 expect(text).not.toContain(307 'expect(parseWeek("2026-W41-30")).not.toBeNull();'308 );309 expect(text).toContain("Show the whole check");310 expect(markup).toContain('data-code="plain"');311 });312313 it("shows only the check's path when its source could not be read", () => {314 const markup = mainOf(markupOf(page()));315316 expect(markup).not.toContain('data-code="plain"');317 expect(markup).toContain(318 'href="/datekit/blob/main/test/parse-week.test.ts"'319 );320 });321322 it("says a family's delete child waits for its siblings in the family's terms", () => {323 const { children, deleteChild, parent } = family;324 const states = askStates([closedEvent(1, children[0] ?? parent.id)]);325 const text = textOf(page(deleteChild, { parent, states }));326327 expect(text).toContain("Waiting for 2 of 3 children to land");328 expect(text).not.toContain("Waits on");329 });330331 it("says a delete child whose siblings all landed is open to take, and never that it waits", () => {332 const { children, deleteChild, parent } = family;333334 const states = askStates(335 children.map((child, index) => closedEvent(index + 1, child))336 );337338 const markup = markupOf(339 page({ ...deleteChild, state: "open" }, { parent, states })340 );341342 const text = textOf(343 page({ ...deleteChild, state: "open" }, { parent, states })344 );345346 expect(text).toContain("Open to take");347 expect(text).not.toContain("Waits on");348 expect(text).not.toContain("to land first");349 expect(asideOf(markup)).toContain(`data-family="${parent.id}"`);350 });351352 it("says a family's parent waits for its family in the family's terms, never as a list of ids", () => {353 const { children, deleteChild, parent } = family;354 const states = askStates([closedEvent(1, children[0] ?? parent.id)]);355 const markup = mainOf(markupOf(page(parent, { states })));356357 expect(plainText(markup)).toContain(358 "Waits for 2 of 3 children and the delete step to land first; a claim waits until they do."359 );360 expect(plainText(markup)).not.toContain("Waits on");361 expect(markup).toContain(`href="/datekit/asks/${deleteChild.id}"`);362 });363364 it("says a family's parent whose children all landed waits only for the delete step", () => {365 const { children, parent } = family;366367 const states = askStates(368 children.map((child, index) => closedEvent(index + 1, child))369 );370371 expect(plainText(mainOf(markupOf(page(parent, { states }))))).toContain(372 "Waits for the delete step to land first"373 );374 });375136 it("names the asks a blocked ask waits on, each linking to its page", () => {376 it("names the asks an ask outside a family waits on, each linking to its page", () => {377 const blocked = {378 ...ask,379 blockedBy: [AskId.make("split-format"), AskId.make("split-parse")],380 };
12 unmodified lines
393 expect(markup).toContain('href="/datekit/asks/split-format"');394 expect(markup).toContain('href="/datekit/asks/split-parse"');395 });396157 it("names nothing it waits on when nothing blocks it", () => {397 it("names nothing it waits on when nothing blocks it, or what blocked it landed", () => {398 expect(textOf(page())).not.toContain("Waits on");159 });399161 it("links a step of a migrate to its parent ask", () => {162 const child = { ...ask, parent: AskId.make("migrate-week-api") };400 const states = askStates([closedEvent(1, AskId.make("split-format"))]);401164 expect(markupOf(page(child))).toContain(165 'href="/datekit/asks/migrate-week-api"'166 );402 expect(403 textOf(404 page({ ...ask, blockedBy: [AskId.make("split-format")] }, { states })405 )406 ).not.toContain("Waits on");407 });408169 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 });181409 it("gives no claim line once the ask is closed", () => {410 const text = textOf(page({ ...ask, state: "closed" }));411412 expect(text).toContain("Closed");
9 unmodified lines
422423 it("shows the brief exactly as an agent reads it", () => {424 expect(inPre(markupOf(page()))).toBe(inPre(markupOf(<pre>{brief}</pre>)));425 });426427 it("gives the project's posture when the list of projects has it", () => {428 const text = textOf(page(ask, { posture: "openWithSealedEvidence" }));429430 expect(text).toContain("Open with sealed evidence");431 });432});433434describe(NoSuchAsk, () => {435 it("shows the refusal a loader's not-found carried from the server, as git printed it", () => {
14 unmodified lines
450 it("says nothing is at an address that names no ask at all", () => {451 expect(textOf(<NoSuchAsk />)).toContain("Nothing is at this address");452 });453454 it("offers the way onward: the project, and the open asks", () => {455 const markup = markupOf(<NoSuchAsk project="datekit" />);456457 expect(markup).toContain('href="/datekit"');458 expect(markup).toContain('href="/"');459 expect(textOf(<NoSuchAsk project="datekit" />)).toContain("Open asks");460 });461462 it("names the project and its asks in the trail, and no crumb for the ask that is not there", () => {463 const refusal = new UnknownAsk({ ask: AskId.make("no-such-ask") });464 const data = structuredClone(Schema.encodeSync(Refusals)([refusal]));465466 const trail = trailOf(467 markupOf(<NoSuchAsk data={data} project="datekit" />)468 );469470 expect(inOrder(plainText(trail), ["datekit", "Asks"])).toBeTruthy();471 expect(trail).toContain('href="/datekit"');472 expect(trail).not.toContain("no-such-ask");473 });474475 it("links no project the platform says it does not have", () => {476 const refusal = new UnknownProject({477 project: ProjectName.make("nowhere"),478 });479480 const data = structuredClone(Schema.encodeSync(Refusals)([refusal]));481 const markup = markupOf(<NoSuchAsk data={data} project="nowhere" />);482483 expect(markup).not.toContain('href="/nowhere"');484 expect(markup).toContain('href="/"');485 });486487 it("says what its route gives it when a not-found carries no refusal", () => {488 expect(489 textOf(<NoSuchAsk nothing="No answer is at this head." />)490 ).toContain("No answer is at this head.");491 });492});493228/** A platform that knows datekit's one ask, counting `showAsk` calls. */229const platformOf = (calls: Ref.Ref<number>) =>494/** What the stub platform was asked. */495interface Asked {496 readonly asks: number;497 readonly files: number;498 readonly replays: number;499 readonly verdicts: number;500}501502const nothingAsked: Asked = { asks: 0, files: 0, replays: 0, verdicts: 0 };503504const count = (asked: Ref.Ref<Asked>, key: keyof Asked) =>505 Ref.update(asked, (seen) => ({ ...seen, [key]: seen[key] + 1 }));506507/** Events in datekit: tamsin claimed the ask, and another ask was claimed too. */508const replay = [509 claimedEvent(1, "tamsin"),510 claimedEvent(2, "okafor", AskId.make("format-week")),511];512513/**514 * A platform that knows datekit's ask (`shown`, under its id) and the515 * family parent, its events, no verdict yet, and the check's file when516 * `readable`.517 */518const platformOf = (519 asked: Ref.Ref<Asked>,520 {521 readable = true,522 shown = ask,523 }: { readonly readable?: boolean; readonly shown?: Ask } = {}524) =>525 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(526 Layer.provide([527 Layer.mergeAll(528 unanswered,529 Contracts.toLayerHandler("showAsk", (payload) =>530 Effect.gen(function* () {236 yield* Ref.update(calls, (count) => count + 1);531 yield* count(asked, "asks");532533 if (payload.ask === family.parent.id) {534 return { ask: family.parent, brief };535 }536537 if (payload.ask !== askId) {538 return yield* new UnknownAsk({ ask: payload.ask });539 }540242 return { ask, brief };541 return { ask: shown, brief };542 })543 ),544 Contracts.toLayerHandler("verdict", () =>545 Effect.as(count(asked, "verdicts"), {})546 ),547 Contracts.toLayerHandler("watch", () =>548 Stream.fromEffect(count(asked, "replays")).pipe(549 Stream.flatMap(() => Stream.fromIterable(replay))550 )551 ),552 Contracts.toLayerHandler("readFile", (payload) =>553 Effect.gen(function* () {554 yield* count(asked, "files");555556 if (!readable) {557 return yield* new UnknownPath({558 commit: CommitSha.make("a".repeat(40)),559 path: payload.path,560 });561 }562563 return {564 at: CommitSha.make("a".repeat(40)),565 binary: false,566 path: payload.path,567 sha: BlobSha.make("f".repeat(40)),568 size: 42,569 text: 'test("parses", () => {});',570 truncated: false,571 };572 })573 )574 ),575 asTester,576 ])577 );578579describe(readAsk, () => {251 it.effect("reads the ask and its brief for the page", () =>252 Effect.gen(function* () {253 const calls = yield* Ref.make(0);580 it.effect(581 "reads the ask, its brief, its events and its check's source for the page",582 () =>583 Effect.gen(function* () {584 const asked = yield* Ref.make(nothingAsked);585255 const read = yield* readAsk({ ask: askId, project }).pipe(256 Effect.provide(platformOf(calls))257 );586 const read = yield* readAsk({ ask: askId, project }).pipe(587 Effect.provide(platformOf(asked))588 );589259 expect([read.ask.id, read.brief]).toStrictEqual([askId, brief]);260 expect(yield* Ref.get(calls)).toBe(1);261 })590 expect({591 ask: read.ask.id,592 brief: read.brief,593 check: read.check?.text,594 events: read.events.map(({ seq }) => seq),595 lastSeq: read.lastSeq,596 parent: read.parent,597 }).toStrictEqual({598 ask: askId,599 brief,600 check: 'test("parses", () => {});',601 events: [1],602 lastSeq: 2,603 parent: undefined,604 });605 expect(yield* Ref.get(asked)).toStrictEqual({606 asks: 1,607 files: 1,608 replays: 1,609 verdicts: 1,610 });611 })612 );613614 it.effect(615 "reads a family member's parent, and shows the ask without its check's source when the file cannot be read",616 () =>617 Effect.gen(function* () {618 const asked = yield* Ref.make(nothingAsked);619620 const read = yield* readAsk({ ask: askId, project }).pipe(621 Effect.provide(622 platformOf(asked, {623 readable: false,624 shown: { ...family.child(0), check: ask.check, id: askId },625 })626 )627 );628629 expect(read.parent?.id).toBe(family.parent.id);630 expect(read.check).toBeUndefined();631 expect((yield* Ref.get(asked)).asks).toBe(2);632 })633 );634635 it.effect(636 "is a not-found carrying the UnknownAsk refusal for an ask the project lacks",637 () =>638 Effect.gen(function* () {268 const calls = yield* Ref.make(0);639 const asked = yield* Ref.make(nothingAsked);640 const missing = AskId.make("no-such-ask");641642 const failed = yield* Effect.flip(643 readAsk({ ask: missing, project }).pipe(273 Effect.provide(platformOf(calls))644 Effect.provide(platformOf(asked))645 )646 );647648 expect(isNotFound(failed)).toBeTruthy();
11 unmodified lines
660 it.effect(661 "is a not-found with no refusal, and asks nothing, for a name no ask can have",662 () =>663 Effect.gen(function* () {293 const calls = yield* Ref.make(0);664 const asked = yield* Ref.make(nothingAsked);665666 const failed = yield* Effect.flip(667 readAsk({ ask: "Not_An-Ask", project }).pipe(297 Effect.provide(platformOf(calls))668 Effect.provide(platformOf(asked))669 )670 );671672 expect(isNotFound(failed)).toBeTruthy();673 expect(674 isNotFound(failed) ? failed.data : "not a not-found"675 ).toBeUndefined();305 expect(yield* Ref.get(calls)).toBe(0);676 expect(yield* Ref.get(asked)).toStrictEqual(nothingAsked);677 })678 );679});